CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-highlightjs--cdn-assets

Pre-compiled CDN assets for highlight.js syntax highlighting with language autodetection and theme support.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

utilities.mddocs/

Utilities

Utility functions, regex helpers, built-in mode constants, and development tools for advanced usage and language definition creation.

Capabilities

Core Utilities

inherit()

Creates deep copies of objects with inheritance for merging configurations.

/**
 * Creates deep copy with inheritance, merging multiple objects
 * @param original - Base object to inherit from
 * @param args - Additional objects to merge in
 * @returns New object with merged properties
 */
function inherit<T>(original: T, ...args: Record<string, any>[]): T;

Usage Examples:

import hljs from '@highlightjs/cdn-assets/es/highlight.js';

// Inherit from base mode
const baseStringMode = hljs.QUOTE_STRING_MODE;
const customStringMode = hljs.inherit(baseStringMode, {
  className: 'custom-string',
  contains: [hljs.BACKSLASH_ESCAPE]
});

// Merge language definitions
const baseLanguage = {
  keywords: 'if else while',
  contains: [hljs.C_LINE_COMMENT_MODE]
};

const extendedLanguage = hljs.inherit(baseLanguage, {
  keywords: 'if else while for function class',
  contains: [hljs.C_LINE_COMMENT_MODE, hljs.QUOTE_STRING_MODE]
});

// Configuration inheritance
const baseConfig = { classPrefix: 'hljs-', cssSelector: 'pre code' };
const customConfig = hljs.inherit(baseConfig, { classPrefix: 'syntax-' });

newInstance()

Creates a new isolated highlighter instance with independent configuration.

/**
 * Creates new isolated highlighter instance
 * @returns New HLJSApi instance with independent state
 */
function newInstance(): HLJSApi;

Usage Examples:

// Create isolated instance
const customHljs = hljs.newInstance();

// Configure independently
customHljs.configure({ classPrefix: 'code-' });
hljs.configure({ classPrefix: 'syntax-' });

// Register different languages
customHljs.registerLanguage('mylang', myLanguageDefinition);
// hljs doesn't have 'mylang' registered

// Use independently
const result1 = hljs.highlight('code', { language: 'javascript' });
const result2 = customHljs.highlight('code', { language: 'javascript' });
// Different CSS classes due to different classPrefix

Debug and Safety Functions

debugMode()

Enables debug mode, disabling safety checks for development.

/**
 * Enables debug mode (disables safe mode)
 * Allows more detailed error reporting and debugging
 */
function debugMode(): void;

Usage Examples:

// Enable debug mode for development
if (process.env.NODE_ENV === 'development') {
  hljs.debugMode();
}

// Debug mode provides more detailed errors
hljs.debugMode();
try {
  hljs.highlight('bad code', { language: 'nonexistent' });
} catch (error) {
  console.error('Detailed error:', error); // More verbose in debug mode
}

safeMode()

Enables safe mode with error protection (default behavior).

/**
 * Enables safe mode (default)
 * Provides error protection and graceful degradation
 */
function safeMode(): void;

Usage Examples:

// Re-enable safe mode after debugging
hljs.safeMode();

// Safe mode handles errors gracefully
const result = hljs.highlight('problematic code', { language: 'unknown' });
// Returns graceful fallback instead of throwing

Version Information

versionString

String constant containing the current highlight.js version.

/**
 * Current version string of highlight.js
 */
const versionString: string;

Usage Examples:

console.log('Using highlight.js version:', hljs.versionString); // "11.11.1"

// Version-dependent features
const [major, minor, patch] = hljs.versionString.split('.').map(Number);
if (major >= 11) {
  // Use modern API
  const result = hljs.highlight(code, { language: 'javascript' });
} else {
  // Use legacy API
  const result = hljs.highlight('javascript', code);
}

// Version reporting
function getHighlightJSInfo() {
  return {
    version: hljs.versionString,
    languages: hljs.listLanguages().length,
    instance: 'cdn-assets'
  };
}

Regex Utilities

Advanced regex pattern construction utilities for language definition creation.

concat()

Concatenates regex patterns into a single pattern string.

/**
 * Concatenates regex patterns or strings
 * @param args - Regex patterns or strings to concatenate
 * @returns Combined regex pattern string
 */
function concat(...args: (RegExp | string)[]): string;

Usage Examples:

// Simple concatenation
const pattern = hljs.regex.concat('function', /\s+/, /[a-zA-Z_][a-zA-Z0-9_]*/);
// Result: "function\\s+[a-zA-Z_][a-zA-Z0-9_]*"

// Building complex patterns
const functionPattern = hljs.regex.concat(
  /\b(function|async\s+function)\s+/,
  /[a-zA-Z_$][a-zA-Z0-9_$]*/,
  /\s*\(/
);

lookahead()

Creates a positive lookahead regex pattern.

/**
 * Creates positive lookahead pattern
 * @param re - Pattern to look ahead for
 * @returns Lookahead regex pattern string
 */
function lookahead(re: RegExp | string): string;

Usage Examples:

// Look ahead for specific pattern
const ifKeyword = hljs.regex.lookahead(/\bif\b/);
// Result: "(?=\\bif\\b)"

// Complex lookahead
const functionLookahead = hljs.regex.lookahead(
  hljs.regex.concat(/function/, /\s+/, /[a-zA-Z_]/)
);

either()

Creates an alternation (OR) pattern from multiple options.

/**
 * Creates alternation pattern (a|b|c)
 * @param args - Patterns to alternate between, optional options object
 * @returns Alternation regex pattern string
 */
function either(...args: (RegExp | string)[] | [...(RegExp | string)[], RegexEitherOptions]): string;

interface RegexEitherOptions {
  /** Whether to capture the alternation group */
  capture?: boolean;
}

Usage Examples:

// Simple alternation
const keywords = hljs.regex.either('if', 'else', 'while', 'for');
// Result: "if|else|while|for"

// Complex patterns
const types = hljs.regex.either(/\bint\b/, /\bstring\b/, /\bbool\b/);

// With capture group
const capturedKeywords = hljs.regex.either('function', 'class', 'interface', {
  capture: true
});
// Result: "(function|class|interface)"

optional()

Makes a regex pattern optional.

/**
 * Makes a regex pattern optional
 * @param re - Pattern to make optional
 * @returns Optional regex pattern string
 */
function optional(re: RegExp | string): string;

Usage Examples:

// Optional whitespace
const optionalSpace = hljs.regex.optional(/\s+/);
// Result: "(?:\\s+)?"

// Optional modifiers
const functionDecl = hljs.regex.concat(
  hljs.regex.optional('async '),
  'function',
  hljs.regex.optional(' ')
);

anyNumberOfTimes()

Creates a pattern that matches any number of repetitions.

/**
 * Allows pattern to repeat any number of times
 * @param re - Pattern to repeat
 * @returns Repeating regex pattern string
 */
function anyNumberOfTimes(re: RegExp | string): string;

Usage Examples:

// Repeat digits
const digits = hljs.regex.anyNumberOfTimes(/[0-9]/);
// Result: "(?:[0-9])*"

// Repeat word characters
const identifier = hljs.regex.concat(
  /[a-zA-Z_]/,
  hljs.regex.anyNumberOfTimes(/[a-zA-Z0-9_]/)
);

Built-in Mode Constants

Pre-defined syntax highlighting modes for common language constructs.

String Modes

/** Double-quoted string mode */
const QUOTE_STRING_MODE: Mode;

/** Single-quoted string mode */
const APOS_STRING_MODE: Mode;

/** Backslash escape sequences */
const BACKSLASH_ESCAPE: Mode;

/** Multi-word phrases mode */
const PHRASAL_WORDS_MODE: Mode;

Comment Modes

/** C-style line comments (//) */
const C_LINE_COMMENT_MODE: Mode;

/** C-style block comments (/* */) */
const C_BLOCK_COMMENT_MODE: Mode;

/** Hash-style comments (#) */
const HASH_COMMENT_MODE: Mode;

/**
 * Generic comment mode factory
 * @param begin - Comment start pattern
 * @param end - Comment end pattern  
 * @param modeOpts - Additional mode options
 * @returns Comment mode definition
 */
function COMMENT(begin: string | RegExp, end: string | RegExp, modeOpts?: Mode | {}): Mode;

Number Modes

/** Generic number mode */
const NUMBER_MODE: Mode;

/** C-style number mode */
const C_NUMBER_MODE: Mode;

/** Binary number mode */
const BINARY_NUMBER_MODE: Mode;

Other Built-in Modes

/** Regular expression mode */
const REGEXP_MODE: Mode;

/** Title/function name mode */
const TITLE_MODE: Mode;

/** Underscore-style title mode */
const UNDERSCORE_TITLE_MODE: Mode;

/** Method call guard */
const METHOD_GUARD: Mode;

/**
 * Shebang line mode
 * @param mode - Optional mode configuration with binary pattern
 * @returns Shebang mode definition
 */
function SHEBANG(mode?: Partial<Mode> & {binary?: string | RegExp}): Mode;

/**
 * End-same-as-begin mode factory
 * @param mode - Mode where end pattern matches begin pattern
 * @returns Mode with matching begin/end
 */
function END_SAME_AS_BEGIN(mode: Mode): Mode;

Regular Expression Constants

/** Identifier pattern string */
const IDENT_RE: string; // "[A-Za-z$_][0-9A-Za-z$_]*"

/** Underscore identifier pattern */  
const UNDERSCORE_IDENT_RE: string; // "[A-Za-z_$][0-9A-Za-z_$]*"

/** Pattern that never matches */
const MATCH_NOTHING_RE: string; // "\\b\\B"

/** Generic number pattern */
const NUMBER_RE: string; // "\\b\\d+(\\.\\d+)?"

/** C-style number pattern */
const C_NUMBER_RE: string; // "(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)"

/** Binary number pattern */
const BINARY_NUMBER_RE: string; // "\\b(0b[01]+)"

/** Regex delimiter starters */
const RE_STARTERS_RE: string; // "!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~"

Usage Examples

Creating Custom Language Definition

hljs.registerLanguage('custom', function(hljs) {
  return {
    name: 'Custom Language',
    aliases: ['cust'],
    keywords: {
      keyword: 'if else while for function class',
      literal: 'true false null',
      built_in: 'print input len'
    },
    contains: [
      // Use built-in modes
      hljs.HASH_COMMENT_MODE,
      hljs.QUOTE_STRING_MODE,
      hljs.C_NUMBER_MODE,
      
      // Custom function definition
      {
        className: 'function',
        beginKeywords: 'function',
        end: hljs.regex.lookahead(/\s*\{/),
        contains: [{
          className: 'title',
          begin: hljs.IDENT_RE
        }]
      },
      
      // Custom string with interpolation
      hljs.inherit(hljs.QUOTE_STRING_MODE, {
        contains: [{
          begin: /\$\{/, end: /\}/,
          contains: ['self']
        }]
      })
    ]
  };
});

Advanced Regex Pattern Building

// Complex identifier pattern
const advancedIdentifier = hljs.regex.concat(
  hljs.regex.either('_', /[a-zA-Z]/),
  hljs.regex.anyNumberOfTimes(
    hljs.regex.either('_', /[a-zA-Z0-9]/)
  )
);

// Function signature pattern
const functionSignature = hljs.regex.concat(
  hljs.regex.optional(hljs.regex.either('async', 'static')),
  hljs.regex.optional(/\s+/),
  'function',
  /\s+/,
  advancedIdentifier,
  /\s*\(/
);

docs

configuration.md

core-highlighting.md

index.md

language-assets.md

language-management.md

plugins.md

utilities.md

tile.json