@remotex-labs/xmap
Version:
A library with a sourcemap parser and TypeScript code formatter for the CLI
1,582 lines (1,581 loc) • 68.3 kB
TypeScript
/**
* This file was automatically generated by xBuild.
* DO NOT EDIT MANUALLY.
*/
/**
* Formats a stack frame into a single display line.
*
* @param frame - Stack frame to format.
* @returns Formatted stack trace line.
*
* @remarks
* When `frame.fileName` is a URL, `#L<line>` is appended to improve linkability.
* When both `line` and `column` are available, they are rendered as a `[line:column]` suffix.
*
* @since 5.0.0
*/
declare function formatStackLine(frame: StackFrameInterface): string;
/**
* Creates a formatted stack entry enriched with source context and highlighted code.
*
* @param position - Resolved position and extracted code context for the frame.
* @param frame - Stack frame to enrich.
* @returns Formatted stack frame entry containing `format`, optional `code`, and the source snippet start line.
*
* @remarks
* This function mutates `frame` with resolved `line`, `column`, `fileName`, and optionally `functionName`.
* When `position.sourceRoot` is present and the source is not an HTTP URL, `frame.fileName` is prefixed with it.
* It formats the stack line with {@link formatStackLine} and preserves the extracted code context for rendering.
*
* @see StackFrameInterface
* @see PositionWithCodeInterface
*
* @since 5.0.0
*/
declare function stackSourceEntry(position: PositionWithCodeInterface, frame: StackFrameInterface): FormatStackFrameInterface;
/**
* Converts a stack frame into a formatted entry, optionally enriched with source code context.
*
* @param frame - Stack frame to convert.
* @param options - Resolver options controlling filtering and source lookups.
* @returns Formatted stack frame entry, or `undefined` when filtered out.
*
* @remarks
* Frames marked as native (`frame.native === true`) are excluded unless `options.withNativeFrames` is true.
* If a source is available via `options.getSource`, the frame is enriched with a highlighted code snippet.
*
* @see ResolveOptionsInterface
* @see FormatStackFrameInterface
*
* @since 5.0.0
*/
declare function stackEntry(frame: StackFrameInterface, options?: ResolveOptionsInterface): FormatStackFrameInterface | undefined;
/**
* Resolves a parsed stack trace into structured metadata with formatted stack entries.
*
* @param error - Parsed stack trace to resolve.
* @param options - Resolver options controlling filtering and source lookups.
* @returns Resolved metadata containing `name`, `message`, and formatted `stack`.
*
* @remarks
* Stack entries that are filtered out or cannot be enriched are omitted from the returned `stack`.
*
* @since 5.0.0
*/
declare function resolveError(error: ParsedStackTraceInterface, options?: ResolveOptionsInterface): ResolveMetadataInterface;
/**
* Describes the origin of evaluated code referenced by a stack frame.
*
* @since 3.0.0
*/
interface EvalOriginInterface {
/**
* 1-based line number within the evaluated source, when available.
* @since 3.0.0
*/
line?: number;
/**
* 1-based column number within the evaluated source line, when available.
* @since 3.0.0
*/
column?: number;
/**
* File name associated with the evaluated source, when available.
* @since 3.0.0
*/
fileName?: string;
/**
* Function name associated with the evaluated source, when available.
* @since 3.0.0
*/
functionName?: string;
}
/**
* Represents a stack frame in a stack trace.
*
* @remarks
* This structure provides location and classification details about a single call site,
* primarily used for diagnostics, stack analysis, and rendering stack traces in a structured form.
*
* @since 3.0.0
*/
interface StackFrameInterface {
/**
* The original frame text as provided by the runtime or parser.
* @since 3.0.0
*/
source: string;
/**
* 1-based line number within the source file, when available.
* @since 3.0.0
*/
line?: number;
/**
* 1-based column number within the source line, when available.
* @since 3.0.0
*/
column?: number;
/**
* File name for the call site, when available.
* @since 3.0.0
*/
fileName?: string;
/**
* Function name for the call site, when available.
* @since 3.0.0
*/
functionName?: string;
/**
* True when the frame originates from evaluated code (for example, `eval()`).
* @since 3.0.0
*/
eval: boolean;
/**
* True when the frame is part of an asynchronous call chain, when detectable.
* @since 3.0.0
*/
async: boolean;
/**
* True when the frame originates from native code execution.
* @since 3.0.0
*/
native: boolean;
/**
* True when the frame represents a constructor invocation.
* @since 3.0.0
*/
constructor: boolean;
/**
* Information about the evaluated code origin, when `eval` is true and the runtime provides it.
* @see EvalOriginInterface
* @since 3.0.0
*/
evalOrigin?: EvalOriginInterface;
}
/**
* Represents a fully parsed error stack trace with structured information.
*
* @remarks
* `rawStack` preserves the original stack string for debugging and fallback rendering.
*
* @see StackFrameInterface
* @since 2.1.0
*/
interface ParsedStackTraceInterface {
/**
* Error name (for example, `TypeError`).
* @since 2.1.0
*/
name: string;
/**
* Error message.
* @since 2.1.0
*/
message: string;
/**
* Parsed frames in call order.
* @see StackFrameInterface
* @since 2.1.0
*/
stack: Array<StackFrameInterface>;
/**
* The raw stack string as received from the runtime.
* @since 2.1.0
*/
rawStack: string;
}
/**
* Represents a source map structure used for mapping code within a file to its original source
* @since 1.0.0
*/
interface SourceMapInterface {
/**
* The generated file's name that the source map is associated with
* @since 1.0.0
*/
file?: string | null;
/**
* An array of variable/function names present in the original source
* @since 1.0.0
*/
names?: Array<string>;
/**
* The version of the source map specification (standard is 3)
* @since 1.0.0
*/
version: number;
/**
* An array of URLs or paths to the original source files
* @since 1.0.0
*/
sources: Array<string>;
/**
* VLQ encoded string that maps generated code back to original source code
* @since 1.0.0
*/
mappings: string;
/**
* Root URL for resolving the sources
* @since 1.0.0
*/
sourceRoot?: string | null;
/**
* Array containing the content of the original source files
* @since 1.0.0
*/
sourcesContent?: Array<string>;
}
/**
* Represents a position in source code with mapping information
* @since 1.0.0
*/
interface PositionInterface {
/**
* Name of the identifier at this position
* @since 1.0.0
*/
name: string | null;
/**
* Line number in the original source
* @since 1.0.0
*/
line: number;
/**
* Column number in the original source
* @since 1.0.0
*/
column: number;
/**
* Path or URL to the original source file
* @since 1.0.0
*/
source: string;
/**
* Root URL for resolving the source
* @since 1.0.0
*/
sourceRoot: string | null;
/**
* Index of the source in the sources array
* @since 1.0.0
*/
sourceIndex: number;
/**
* Line number in the generated code
* @since 1.0.0
*/
generatedLine: number;
/**
* Column number in the generated code
* @since 1.0.0
*/
generatedColumn: number;
}
/**
* Position in source code including the original source content
*
* @see PositionInterface
* @since 1.0.0
*/
interface PositionWithContentInterface extends PositionInterface {
/**
* Content of the original source file
* @since 1.0.0
*/
sourcesContent: string;
}
/**
* Position in source code including code fragment information
*
* @see PositionInterface
* @since 1.0.0
*/
interface PositionWithCodeInterface extends PositionInterface {
/**
* Code fragment from the original source
* @since 1.0.0
*/
code: string;
/**
* Ending line number of the code fragment
* @since 1.0.0
*/
endLine: number;
/**
* Starting line number of the code fragment
* @since 1.0.0
*/
startLine: number;
}
/**
* Options for retrieving source code context
* @since 1.0.0
*/
interface SourceOptionsInterface {
/**
* Number of lines to include after the target line
* @since 1.0.0
*/
linesAfter?: number;
/**
* Number of lines to include before the target line
* @since 1.0.0
*/
linesBefore?: number;
}
/**
* Options controlling stack trace resolution and source context extraction.
*
* @remarks
* These options are consumed by the resolver to decide how to interpret positions,
* how much code context to include, and whether to filter native frames.
*
* @since 5.0.0
*/
interface ResolveOptionsInterface {
/**
* Bias used when mapping line/column pairs to a source position.
*
* @remarks
* Passed through to the underlying source resolver when extracting code context.
*
* @since 5.0.0
*/
bias?: Bias;
/**
* Number of lines of source code to include after the error line.
*
* @defaultValue 3
*
* @remarks
* Defaults to 3 if not specified. Used when extracting code context
* from source files or snapshots.
*
* @since 5.0.0
*/
linesAfter?: number;
/**
* Number of lines of source code to include before the error line.
*
* @defaultValue 3
*
* @remarks
* Defaults to 3 if not specified. Used when extracting code context
* from source files or snapshots.
*
* @since 5.0.0
*/
linesBefore?: number;
/**
* Line offset applied to resolved source positions.
*
* @remarks
* This value is added to resolved line numbers before formatted stack entries are created.
* It is useful when the source context comes from a shifted or combined source, where the
* displayed line numbers need to be adjusted to match the original file.
*
* @since 5.1.0
*/
lineOffset?: number;
/**
* Whether to include native (built-in) stack frames in the output.
*
* @defaultValue Based on `ConfigurationService.verbose` setting
*
* @remarks
* Native frames are those marked with `frame.native === true`, typically
* representing Node.js internal functions. When false, these frames are
* filtered out during processing. Automatically set based on the `verbose`
* configuration setting if not explicitly provided.
*
* @since 5.0.0
*/
withNativeFrames?: boolean;
/**
* Resolves a {@link SourceService} for the provided path.
*
* @param path - File path or URL to resolve.
* @returns The source service when available, otherwise `null`/`undefined`.
*
* @remarks
* When provided, the resolver uses this callback to enrich frames with highlighted code context.
*
* @since 5.0.0
*/
getSource?(path: string): SourceService | null | undefined;
}
/**
* Structured metadata produced by resolving a parsed stack trace.
*
* @since 5.0.0
*/
interface ResolveMetadataInterface {
/**
* Error name (for example, `TypeError`).
* @since 5.0.0
*/
name: string;
/**
* Error message.
* @since 5.0.0
*/
message: string;
/**
* Formatted stack frames.
* @see FormatStackFrameInterface
* @since 5.0.0
*/
stack: Array<FormatStackFrameInterface>;
}
/**
* A stack frame enriched with display formatting and optional source code context.
*
* @see StackFrameInterface
* @since 5.0.0
*/
interface FormatStackFrameInterface extends StackFrameInterface {
/**
* Highlighted code context, when available.
* @since 5.0.0
*/
code?: string;
/**
* Formatted stack line representation.
* @since 5.0.0
*/
format: string;
/**
* Starting line number of the highlighted code fragment.
*
* @remarks
* Used together with {@link code} to indicate the first line displayed
* in the extracted source context.
*
* @since 5.0.1
*/
stratLine?: number;
/**
* Root URL for resolving the source
* @since 5.1.0
*/
sourceRoot?: string | null;
}
/**
* Service for loading, merging, and querying Source Map v3 data.
*
* @remarks
* This service wraps a {@link MappingService} and enriches segment lookups with
* source file paths, names, and optional source content/code context.
*
* @example
* ```ts
* const sourceMapJSON = '{"version": 3, "file": "bundle.js", "sources": ["foo.ts"], "names": [], "mappings": "AAAA"}';
* const sourceService = new SourceService(sourceMapJSON);
* console.log(sourceService.file); // 'bundle.js'
* ```
*
* @since 5.0.0
*/
declare class SourceService {
/**
* Normalized generated file path associated with this source map.
* @since 5.0.0
*/
readonly file: string;
/**
* Identifier names referenced by mapped segments.
* @since 5.0.0
*/
readonly names: Array<string>;
/**
* Resolved source file paths used by the map.
* @since 5.0.0
*/
readonly sources: Array<string>;
/**
* Optional source root from the source map payload.
* @since 5.0.0
*/
readonly sourceRoot: string;
/**
* Inline source contents aligned with {@link sources} by index.
* @since 5.0.0
*/
readonly sourcesContent: Array<string>;
/**
* Internal mappings handler for encode/decode and lookups.
* @since 5.0.0
*/
readonly mappings: MappingService;
/**
* Creates an empty source service instance.
*
* @remarks
* Useful when building mappings incrementally or as an accumulator target
* for {@link assign}.
*
* @example
* ```ts
* const source = new SourceService();
* ```
*
* @since 5.0.0
*/
constructor();
/**
* Creates a source service with a generated line offset.
*
* @param source - Source map payload as object or JSON string
* @param offset - Generated line offset applied during mapping decode
*
* @remarks
* Use this overload when the source map file path is already embedded in
* the source map payload and only line shifting is required.
*
* @example
* ```ts
* const source = new SourceService(rawMap, 20);
* ```
*
* @since 5.0.0
*/
constructor(source: SourceMapInterface | string, offset?: number);
/**
* Creates a source service with explicit file path and optional line offset.
*
* @param source - Source map payload as object or JSON string
* @param file - Generated file path override
* @param offset - Generated line offset applied during mapping decode
*
* @remarks
* Prefer this overload when the source map payload omits `file` or when a
* normalized file path override is required.
*
* @example
* ```ts
* const source = new SourceService(rawMap, 'dist/app.js', 5);
* ```
*
* @since 5.0.0
*/
constructor(source: SourceMapInterface | string, file?: string, offset?: number);
/**
* Concatenates multiple source maps into one service instance.
*
* @param sources - Source services to merge in order
*
* @returns A new service containing merged mappings, names, sources, and contents
*
* @throws Error - If no source services are provided
*
* @remarks
* Name and source indices are offset during decode to preserve index
* correctness across all merged source maps.
*
* @example
* ```ts
* const merged = SourceService.assign(sourceA, sourceB, ...);
* ```
*
* @since 5.0.0
*/
static assign(...sources: Array<SourceService>): SourceService;
/**
* Serializes current data to a Source Map v3 object.
*
* @returns A source map object with encoded mappings
*
* @remarks
* Includes optional `file` and `sourceRoot` only when they are set.
*
* @example
* ```ts
* const map = source.getSourceObject();
* ```
*
* @since 5.0.0
*/
getSourceObject(): SourceMapInterface;
/**
* Resolves an original position from a generated position.
*
* @param line - 1-based generated line number
* @param column - 1-based generated column number
* @param bias - Search behavior when no exact match exists (default: {@link BOUND})
*
* @returns Position details, or `null` when no segment matches
*
* @remarks
* The returned `name` can be `null` when the mapped segment has no
* associated name index.
*
* @example
* ```ts
* const pos = source.getPosition(12, 8);
* ```
*
* @since 5.0.0
*/
getPosition(line: number, column: number, bias?: Bias): PositionInterface | null;
/**
* Resolves an original position and includes full source content for that file.
*
* @param line - 1-based generated line number
* @param column - 1-based generated column number
* @param bias - Search behavior when no exact match exists (default: {@link BOUND})
*
* @returns Position details with source content, or `null` when unavailable
*
* @remarks
* Returns `null` if no mapped segment is found for the generated position.
*
* @example
* ```ts
* const pos = source.getPositionWithContent(12, 8);
* ```
*
* @since 5.0.0
*/
getPositionWithContent(line: number, column: number, bias?: Bias): PositionWithContentInterface | null;
/**
* Resolves an original position and includes surrounding code context.
*
* @param line - 1-based generated line number
* @param column - 1-based generated column number
* @param bias - Search behavior when no exact match exists (default: {@link BOUND})
* @param options - Optional line window configuration
*
* @returns Position details with extracted code context, or `null` when unavailable
*
* @remarks
* Default window uses `3` lines before and `4` lines after the target line.
*
* @example
* ```ts
* const pos = source.getPositionWithCode(12, 8, BOUND, {
* linesBefore: 2,
* linesAfter: 2
* });
* ```
*
* @since 5.0.0
*/
getPositionWithCode(line: number, column: number, bias?: Bias, options?: SourceOptionsInterface): PositionWithCodeInterface | null;
/**
* Resolves a generated position from an original source position.
*
* @param line - 1-based original source line number
* @param column - 1-based original source column number
* @param sourceIndex - Source index or a partial source path to locate the index
* @param bias - Search behavior when no exact match exists (default: {@link BOUND})
*
* @returns Position details, or `null` when no segment/source matches
*
* @remarks
* String `sourceIndex` is matched using substring search against resolved
* source paths in {@link sources}.
*
* @example
* ```ts
* const pos = source.getPositionByOriginal(40, 3, 'src/main.ts');
* ```
*
* @since 5.0.0
*/
getPositionByOriginal(line: number, column: number, sourceIndex: number | string, bias?: Bias): PositionInterface | null;
/**
* Serializes the current source map object as JSON.
*
* @returns JSON string representation of {@link getSourceObject}
*
* @remarks
* Output is suitable for writing a `.map` file or transport over APIs.
*
* @example
* ```ts
* const json = source.toString();
* ```
*
* @since 5.0.0
*/
toString(): string;
/**
* Parses and validates Source Map v3 input.
*
* @param input - Source map object or JSON string
*
* @returns Parsed and validated source map object
*
* @throws Error - If source map version is not `3`
* @throws Error - If required keys are missing
*
* @remarks
* Accepts JSON input for convenience and validates required structural keys
* before decode operations are attempted.
*
* @example
* ```ts
* const map = SourceService['parseSourceMap'](raw);
* ```
*
* @since 5.0.0
*/
private static parseSourceMap;
/**
* Checks whether a source path is an HTTP(S) URL.
*
* @param path - Path or URL candidate to evaluate
*
* @returns `true` when the value starts with `http` or `https`, otherwise `false`
*
* @remarks
* This helper is used to preserve absolute URL sources and avoid filesystem
* path normalization for remote resources.
*
* @example
* ```ts
* SourceService['isURL']('https://cdn.example.com/app.ts'); // true
* SourceService['isURL']('src/app.ts'); // false
* ```
*
* @since 5.0.0
*/
private static isURL;
/**
* Resolves source paths relative to the current working directory.
*
* @param sources - Raw source entries from source map payload
*
* @returns Normalized relative source file paths
*
* @remarks
* Each path is resolved from the generated file location, then converted to
* a path relative to `process.cwd()`.
*
* @example
* ```ts
* // internal utility used during construction
* ```
*
* @since 5.0.0
*/
private resolveSources;
}
/**
* Service for encoding, decoding, and querying Source Map v3 mappings.
*
* @remarks
* This service manages the full lifecycle of source map operations:
* - Decoding from VLQ-encoded strings or structured arrays
* - Encoding to VLQ-encoded mapping strings
* - Querying segments by generated or original positions
* - Building position indices for efficient lookups
*
* The service maintains an internal offset state to support merging multiple
* source maps and handles both 0-based VLQ wire format and 1-based public API.
*
* All line and column positions in the public API are 1-based, consistent
* with how most editors and tools display positions.
*
* @example Basic decoding and encoding
* ```ts
* const service = new MappingService();
* service.decode('AAAA;AACA,AADA;AAGA;');
* const encoded = service.encode();
* ```
*
* @example Querying segments
* ```ts
* const service = new MappingService();
* service.decode(mappingArray);
* const segment = service.getSegment(1, 5);
* ```
*
* @since 5.0.0
*/
declare class MappingService {
/**
* The generated file this source map is associated with.
*
* @remarks
* Optional field specifying the filename of the generated code that this
* source map describes. This is typically a relative path.
*
* Can be `null` or omitted if the filename is not relevant or is provided
* through other means (e.g., HTTP headers, file naming conventions).
*
* @example
* ```ts
* file: 'bundle.min.js'
* ```
*
* @since 5.0.0
*/
private lines;
/**
* List of identifier names referenced in the mappings.
*
* @remarks
* Optional array containing all identifier names (variables, functions, etc.)
* that are referenced by segments with a `nameIndex`. These names correspond
* to their positions in the original source code.
*
* Segments can reference these names by index to indicate which identifier
* in the original code corresponds to a position in the generated code.
*
* Omit this field if no names need to be tracked, or provide an empty array.
*
* @example
* ```ts
* names: ['myFunction', 'result', 'value']
* ```
*
* @since 5.0.0
*/
private readonly offsets;
/**
* Gets the current line offset used for coordinate adjustments.
*
* @returns The line offset value
*
* @remarks
* This offset is applied when decoding mappings to shift generated line numbers.
* Useful when merging multiple source maps where line numbers need adjustment.
*
* @since 5.0.0
*/
get lineOffset(): number;
/**
* Gets the current name index offset used for coordinate adjustments.
*
* @returns The name index offset value
*
* @remarks
* This offset is applied when decoding mappings to shift name indices.
* Necessary when concatenating source maps with different name arrays.
*
* @since 5.0.0
*/
get namesOffset(): number;
/**
* Gets the current source file index offset used for coordinate adjustments.
*
* @returns The source index offset value
*
* @remarks
* This offset is applied when decoding mappings to shift source file indices.
* Required when merging source maps with different source file arrays.
*
* @since 5.0.0
*/
get sourcesOffset(): number;
/**
* Encodes all stored mappings to a Source Map v3 VLQ string.
*
* @returns A Base64 VLQ-encoded mappings string
*
* @remarks
* Converts the internal 1-based segment representation to 0-based VLQ deltas
* and encodes them as a semicolon-separated string where:
* - Semicolons (`;`) separate lines
* - Commas (`,`) separate segments within a line
* - Empty frames are represented as empty strings between semicolons
*
* The encoding process:
* 1. Resets column offset at each line boundary
* 2. Computes deltas relative to a previous segment
* 3. Encodes deltas using Base64 VLQ
*
* @example Encoding mappings
* ```ts
* const service = new MappingService();
* service.decode(mappingArray);
* const vlqString = service.encode();
* // Returns: "AAAA;AACA,AADA;AAGA;"
* ```
*
* @since 5.0.0
*/
encode(): string;
/**
* Decodes and stores source map data from various input formats.
*
* @param mapping - Source map data (VLQ string, array, or MappingService instance)
* @param namesOffset - Offset to apply to name indices (default: 0)
* @param sourcesOffset - Offset to apply to source file indices (default: 0)
* @param lineOffset - Offset to apply to generated line numbers (default: 0)
*
* @throws Error - If the mapping format is invalid or contains malformed data
*
* @remarks
* Accepts three input formats:
* - **VLQ string**: Standard Source Map v3 encoded mappings
* - **Array**: Structured {@link SourceMappingType} with segments
* - **MappingService**: Another service instance (copies its lines)
*
* Offsets are useful when merging multiple source maps, allowing index
* adjustment to prevent conflicts in name and source arrays.
*
* The method appends to existing mappings, so calling it multiple times
* will accumulate all decoded segments.
*
* @example Decoding from string
* ```ts
* const service = new MappingService();
* service.decode('AAAA;AACA;AADA;');
* ```
*
* @example Decoding with offsets
* ```ts
* const service = new MappingService();
* service.decode(mappingArray, 5, 3, 10);
* // All name indices += 5, source indices += 3, generated lines += 10
* ```
*
* @example Decoding from another service
* ```ts
* const source = new MappingService();
* source.decode('AAAA;');
* const target = new MappingService();
* target.decode(source);
* ```
*
* @since 5.0.0
*/
decode(mapping: MappingService | SourceMappingType | string, namesOffset?: number, sourcesOffset?: number, lineOffset?: number): void;
/**
* Finds a segment at the specified generated position using binary search.
*
* @param generatedLine - 1-based generated line number
* @param generatedColumn - 1-based generated column number
* @param bias - Search behavior when no exact match exists (default: {@link BOUND})
*
* @returns The matching segment, or `null` if no suitable segment exists
*
* @remarks
* Uses binary search for O(log n) performance on sorted segment arrays.
*
* Bias behavior:
* - **`BOUND`**: Returns exact matches only
* - **`LOWER_BOUND`**: Returns the largest segment ≤ target column
* - **`UPPER_BOUND`**: Returns the smallest segment ≥ target column
*
* The line index is adjusted by the current {@link lineOffset} to support
* merged source maps with shifted line numbers.
*
* @example Finding exact segment
* ```ts
* const service = new MappingService();
* service.decode(mappings);
* const segment = service.getSegment(1, 5);
* // Returns a segment at line 1, column 5, or null
* ```
*
* @example Finding nearest lower bound
* ```ts
* const segment = service.getSegment(1, 7, LOWER_BOUND);
* // Returns the closest segment at or before column 7
* ```
*
* @see {@link Bias} for bias options
* @see {@link getOriginalSegment} for reverse lookups
*
* @since 5.0.0
*/
getSegment(generatedLine: number, generatedColumn: number, bias?: Bias): SegmentInterface | null;
/**
* Finds a segment at the specified original source position using linear search.
*
* @param sourceLine - 1-based original source line number
* @param sourceColumn - 1-based original source column number
* @param sourceIndex - Source file index
* @param bias - Search behavior when no exact match exists (default: {@link BOUND})
*
* @returns The matching segment, or `null` if no suitable segment exists
*
* @remarks
* Performs exhaustive linear search across all segments to find matches
* by original position. For frequent lookups, consider building an index
* first using {@link buildOriginalPositionIndex}.
*
* Returns immediately on the exact column match. For bias modes, tracks the
* closest segment by computing column distance.
*
* Bias behavior:
* - **`BOUND`**: Returns exact matches only
* - **`LOWER_BOUND`**: Returns the closest segment with column ≤ target
* - **`UPPER_BOUND`**: Returns the closest segment with column ≥ target
*
* @example Finding original segment
* ```ts
* const service = new MappingService();
* service.decode(mappings);
* const segment = service.getOriginalSegment(10, 25, 0);
* // Returns segment mapping to source file 0, line 10, column 25
* ```
*
* @example Finding the nearest original position
* ```ts
* const segment = service.getOriginalSegment(10, 25, 0, LOWER_BOUND);
* // Returns the closest segment at or before column 25
* ```
*
* @see {@link Bias} for bias options
* @see {@link getSegment} for generated position lookups
* @see {@link buildOriginalPositionIndex} for optimized repeated lookups
*
* @since 5.0.0
*/
getOriginalSegment(sourceLine: number, sourceColumn: number, sourceIndex: number, bias?: Bias): SegmentInterface | null;
/**
* Builds an indexed map of segments grouped by original source position.
*
* @returns A map keyed by `"sourceIndex:line"` with sorted segment arrays
*
* @remarks
* Creates a lookup structure for efficient reverse mapping from original
* to generated positions. Each bucket contains all segments that map to
* the same source file and line, sorted by column in ascending order.
*
* The index structure:
* - **Keys**: Formatted as `"sourceIndex:line"` (e.g., `"0:1"`, `"2:15"`)
* - **Values**: Arrays of {@link SegmentInterface} sorted by `column`
*
* This is useful when performing many original position lookups, as it
* avoids the O(n) linear search of {@link getOriginalSegment}.
*
* Null/empty lines are safely skipped during index construction.
*
* @example Building and using index
* ```ts
* const service = new MappingService();
* service.decode(mappings);
* const index = service.buildOriginalPositionIndex();
*
* const segments = index.get('0:10');
* // Returns all segments mapping to source file 0, line 10
* ```
*
* @example Binary search on indexed bucket
* ```ts
* const index = service.buildOriginalPositionIndex();
* const bucket = index.get('0:10') || [];
* // Perform binary search on bucket for specific column
* ```
*
* @see {@link getOriginalSegment} for single lookups
*
* @since 5.0.0
*/
buildOriginalPositionIndex(): Map<string, Array<SegmentInterface>>;
/**
* Encodes a structured source mapping array to a VLQ string.
*
* @param sourceMapping - Array of segment lines to encode
*
* @returns A Base64 VLQ-encoded mappings string
*
* @remarks
* Converts 1-based segment positions to 0-based VLQ deltas and encodes
* them according to Source Map v3 specification.
*
* The encoding process:
* 1. Pre-allocates arrays for optimal performance
* 2. Resets `generatedColumn` offset to 0 at each line boundary
* 3. Encodes each segment as deltas from the previous segment
* 4. Joins segments with commas (`,`) and lines with semicolons (`;`)
*
* Null lines are encoded as empty strings (represented by consecutive
* semicolons in the output).
*
* This method never reads the `generatedLine` field from segments, as
* line boundaries are encoded structurally via semicolons.
*
* @example Internal encoding
* ```ts
* const encoded = this.encodeSourceMapping([
* [{ generatedColumn: 1, sourceIndex: 0, line: 1, column: 1, nameIndex: null, generatedLine: 1 }],
* null,
* [{ generatedColumn: 5, sourceIndex: 0, line: 2, column: 5, nameIndex: null, generatedLine: 3 }]
* ]);
* // Returns: "AAAA;;IAIA"
* ```
*
* @see {@link encode} for public API
* @see {@link encodeSegment} for single segment encoding
*
* @since 5.0.0
*/
private encodeSourceMapping;
/**
* Validates that a string contains only valid VLQ characters.
*
* @param raw - String to validate
*
* @returns `true` if the string is valid, `false` otherwise
*
* @remarks
* Checks that the input contains only characters from the Source Map v3
* VLQ alphabet plus structural separators:
* - Base64 VLQ characters: `A-Z`, `a-z`, `0-9`, `+`, `/`
* - Separators: `,` (segments), `;` (lines)
*
* Empty strings are considered invalid.
*
* @example Valid mapping string
* ```ts
* this.validateSourceMappingString('AAAA;AACA,AADA;')
* // Returns: true
* ```
*
* @example Invalid mapping string
* ```ts
* this.validateSourceMappingString('AAAA;A#A;')
* // Returns: false (contains '#')
* ```
*
* @since 5.0.0
*/
private validateSourceMappingString;
/**
* Decodes a structured source mapping array and appends segments to internal state.
*
* @param sourceMapping - Array of segment lines or null
*
* @throws Error - If the array structure is invalid or segments fail validation
*
* @remarks
* Processes a pre-parsed {@link SourceMappingType} array, applying configured
* offsets to all indices and positions.
*
* The decoding process:
* 1. Validates that input is an array
* 2. Pre-computes combined line shift for performance
* 3. Validates each segment using {@link validateSegment}
* 4. Applies name, source, and line offsets to all coordinates
* 5. Appends decoded segments to an internal lines array
*
* Null lines are preserved as-is. Each segment is validated before the offset
* application to ensure data integrity.
*
* Error messages include 1-based line numbers for easier debugging.
*
* @example Internal array decoding
* ```ts
* this.decodeSourceMappingArray([
* [{ line: 1, column: 1, nameIndex: null, sourceIndex: 0, generatedLine: 1, generatedColumn: 1 }],
* null,
* [{ line: 2, column: 5, nameIndex: 0, sourceIndex: 0, generatedLine: 3, generatedColumn: 3 }]
* ]);
* ```
*
* @see {@link decode} for public API
* @see {@link validateSegment} for validation rules
*
* @since 5.0.0
*/
private decodeSourceMappingArray;
/**
* Decodes a VLQ-encoded mapping string and appends segments to internal state.
*
* @param encodedMapping - Base64 VLQ-encoded mappings string
*
* @throws Error - If the string format is invalid or decoding fails
*
* @remarks
* Parses a Source Map v3 VLQ string into structured segments with 1-based
* positions, applying configured offsets.
*
* The decoding process:
* 1. Validates a character set using {@link validateSourceMappingString}
* 2. Splits string by semicolons (`;`) to separate lines
* 3. Pre-computes offset flags to minimize branching in hot loop
* 4. For each line:
* - Resets `generatedColumn` offset to 0
* - Splits by commas (`,`) to separate segments
* - Decodes VLQ deltas using {@link decodeVLQ}
* - Applies offsets (only allocating new objects when needed)
* 5. Appends decoded segments to an internal lines array
*
* Empty lines (consecutive semicolons) are stored as `null`.
*
* Line offset is only applied when non-zero, avoiding unnecessary object
* allocations for the common case.
*
* Error messages include 1-based line numbers for debugging.
*
* @example Internal string decoding
* ```ts
* this.decodeSourceMappingString('AAAA;AACA,AADA;AAGA;');
* ```
*
* @see {@link decode} for public API
* @see {@link decodeVLQ} for VLQ decoding
* @see {@link decodeSegment} for delta application
*
* @since 5.0.0
*/
private decodeSourceMappingString;
}
/**
* Bias options for binary search operations on segment arrays.
*
* @remarks
* Controls how the search behaves when an exact match is not found:
* - `BOUND`: Returns the closest match
* - `LOWER_BOUND`: Returns the largest element less than or equal to the target
* - `UPPER_BOUND`: Returns the smallest element greater than or equal to the target
*
* @since 5.0.0
*/
declare const enum Bias {
BOUND = 0,
LOWER_BOUND = 1,
UPPER_BOUND = 2
}
/**
* Creates a new VLQ offset state initialized to zero-based positions.
*
* @param namesOffset - Initial name index offset
* @param sourceOffset - Initial source file index offset
*
* @returns A new {@link VLQOffsetInterface} with all positional fields set to zero
*
* @remarks
* This function initializes the mutable running state used by VLQ encoding/decoding
* operations. The offset tracks cumulative deltas as segments are processed sequentially.
*
* All positional fields (line, column, generatedLine, generatedColumn) start at 0
* because the Source Map v3 spec uses 0-based coordinates internally.
*
* @example Creating default offset
* ```ts
* const offset = createOffset();
* // { line: 0, column: 0, generatedLine: 0, generatedColumn: 0, sourceIndex: 0, nameIndex: 0 }
* ```
*
* @example Creating offset with initial indices
* ```ts
* const offset = createOffset(5, 2);
* // { line: 0, column: 0, generatedLine: 0, generatedColumn: 0, sourceIndex: 2, nameIndex: 5 }
* ```
*
* @since 5.0.0
*/
declare function createOffset(namesOffset?: number, sourceOffset?: number): VLQOffsetInterface;
/**
* Apply a single array of decoded VLQ deltas to the running offset and return
* a fully resolved, **1-based** {@link SegmentInterface}.
*
* @param offset - Mutable VLQ running state; **updated in-place**.
* @param deltas - Raw integers from `decodeVLQ`: `[genCol, srcIdx, srcLine, srcCol, nameIdx?]`
*
* @returns A 1-based segment with all positions resolved
*
* @remarks
* The Source Map v3 spec stores values as 0-based deltas from the previous segment.
* This function advances the offset in-place and converts to 1-based output, so
* callers never have to reason about the wire format.
*
* Delta array structure:
* - `[0]`: Generated column delta (always present)
* - `[1]`: Source file index delta (optional)
* - `[2]`: Source line delta (optional)
* - `[3]`: Source column delta (optional)
* - `[4]`: Name index delta (optional, only when a segment references a name)
*
* The offset parameter is mutated to reflect the new accumulated state.
*
* @example Decoding segment with name
* ```ts
* const offset = createOffset();
* const segment = decodeSegment(offset, [4, 0, 0, 5, 0]);
* // { generatedLine: 1, generatedColumn: 5, line: 1, column: 6, sourceIndex: 0, nameIndex: 0 }
* ```
*
* @example Decoding segment without name
* ```ts
* const offset = createOffset();
* const segment = decodeSegment(offset, [10, 1, 2, 3]);
* // { generatedLine: 1, generatedColumn: 11, line: 3, column: 4, sourceIndex: 1, nameIndex: null }
* ```
*
* @see {@link SegmentInterface} for the resolved segment output
* @see {@link VLQOffsetInterface} for more details on the running state
*
* @since 5.0.0
*/
declare function decodeSegment(offset: VLQOffsetInterface, deltas: Array<number>): SegmentInterface;
/**
* Decode a single raw VLQ segment string into a resolved, **1-based** {@link SegmentInterface}.
*
* @param offset - Mutable VLQ running state; **updated in-place**.
* @param raw - A single VLQ-encoded segment string (e.g. `"AAAA"` or `"kBgB"`)
*
* @returns A 1-based segment with all positions resolved
*
* @remarks
* Convenience wrapper around {@link decodeSegment} + {@link decodeVLQ}.
* This function first decodes the Base64 VLQ string into an array of integers,
* then processes those deltas to produce the final segment.
*
* The offset parameter is advanced to reflect the cumulative state.
*
* @example Decoding a raw segment
* ```ts
* const offset = createOffset();
* const segment = decodeSegmentRaw(offset, "AAAA");
* // Decodes and applies the VLQ-encoded deltas
* ```
*
* @see {@link decodeVLQ} for Base64 VLQ decoding
* @see {@link decodeSegment} for delta processing
*
* @since 5.0.0
*/
declare function decodeSegmentRaw(offset: VLQOffsetInterface, raw: string): SegmentInterface;
/**
* Encode a **1-based** {@link SegmentInterface} into a VLQ delta string.
*
* @param offset - Mutable VLQ running state; **updated in-place**.
* @param seg - The 1-based segment to encode
*
* @returns A Base64 VLQ-encoded string representing the deltas
*
* @remarks
* The 1-based public values are converted back to 0-based VLQ deltas so the
* wire format stays spec-compliant with Source Map v3.
*
* This function:
* 1. Converts 1-based positions to 0-based coordinates
* 2. Computes deltas from the running offset
* 3. Encodes deltas as Base64 VLQ
* 4. Updates the offset to reflect the new state
*
* The encoded string contains 4 or 5 values:
* - Generated column delta (always present)
* - Source file index delta
* - Source line delta
* - Source column delta
* - Name index delta (only if segment has a name)
*
* @example Encoding a segment
* ```ts
* const offset = createOffset();
* const encoded = encodeSegment(offset, {
* generatedLine: 1, generatedColumn: 5,
* line: 1, column: 6,
* sourceIndex: 0, nameIndex: 0
* });
* // Returns Base64 VLQ string like "IAAMA"
* ```
*
* @see {@link encodeArrayVLQ} for Base64 VLQ encoding
*
* @since 5.0.0
*/
declare function encodeSegment(offset: VLQOffsetInterface, seg: SegmentInterface): string;
/**
* Validate all fields of a {@link SegmentInterface}.
*
* @param segment - The segment to validate
*
* @throws Error - on the first field that fails validation
*
* @remarks
* Ensures all positional values are finite numbers and that every 1-based
* position is ≥ 1. Throws on the first invalid field with a descriptive message.
*
* Validation rules:
* - `line`, `column`, `generatedLine`, `generatedColumn`: Must be finite and ≥ 1
* - `sourceIndex`: Must be a finite number (can be 0)
* - `nameIndex`: Must be a finite number or `null`
*
* @example Valid segment
* ```ts
* validateSegment({
* line: 1, column: 5,
* generatedLine: 1, generatedColumn: 10,
* sourceIndex: 0, nameIndex: null
* });
* // No error thrown
* ```
*
* @example Invalid segment (throws)
* ```ts
* validateSegment({
* line: 0, column: 5,
* generatedLine: 1, generatedColumn: 10,
* sourceIndex: 0, nameIndex: null
* });
* // Error: Invalid segment: 'line' must be a finite number ≥ 1, received 0
* ```
*
* @see SegmentInterface
*
* @since 5.0.0
*/
declare function validateSegment(segment: SegmentInterface): void;
/**
* A single decoded segment in a source map.
*
* @remarks
* All line and column values are **1-based** for the public API.
* This represents a mapping between a position in the generated (output) file
* and the corresponding position in the original source file.
*
* Each segment can optionally reference a name from the source map's `names` array,
* typically used for identifier mappings (e.g., minified variable names).
*
* @example Basic segment
* ```ts
* const segment: SegmentInterface = {
* generatedLine: 1,
* generatedColumn: 5,
* line: 10,
* column: 15,
* sourceIndex: 0,
* nameIndex: null
* };
* ```
*
* @example Segment with name reference
* ```ts
* const segment: SegmentInterface = {
* generatedLine: 1,
* generatedColumn: 10,
* line: 5,
* column: 20,
* sourceIndex: 0,
* nameIndex: 3 // References names[3] in the source map
* };
* ```
*
* @see {@link VLQOffsetInterface}
*
* @since 5.0.0
*/
interface SegmentInterface {
/**
* 1-based line in the original source file.
*
* @remarks
* Corresponds to the original source position before transformation.
* Always ≥ 1 for valid segments.
*
* @since 5.0.0
*/
line: number;
/**
* 1-based column in the original source file.
*
* @remarks
* Corresponds to the original source position before transformation.
* Always ≥ 1 for valid segments.
*
* @since 5.0.0
*/
column: number;
/**
* 1-based line in the generated (output) file.
*
* @remarks
* Corresponds to the position in the transformed/compiled output.
* Always ≥ 1 for valid segments.
*
* @since 5.0.0
*/
generatedLine: number;
/**
* 1-based column in the generated (output) file.
*
* @remarks
* Corresponds to the position in the transformed/compiled output.
* Always ≥ 1 for valid segments.
*
* @since 5.0.0
*/
generatedColumn: number;
/**
* Index into the source map's `sources` array.
*
* @remarks
* This is 0-based and references which source file this segment maps to.
* Must be a finite number ≥ 0.
*
* @since 5.0.0
*/
sourceIndex: number;
/**
* Index into the source map's `names` array, or null when absent.
*
* @remarks
* This is 0-based and references an identifier name (e.g., variable or function name)
* in the source map. When `null`, this segment does not reference a name.
*
* Typically used for preserving original identifier names after minification.
*
* @since 5.0.0
*/
nameIndex: number | null;
}
/**
* Internal VLQ running-state used while incrementally encoding or decoding deltas.
*
* @remarks
* All fields are **0-based** — the Source Map v3 wire format is 0-based throughout.
* This type is an implementation detail; callers work with {@link SegmentInterface} instead.
*
* The offset is mutated in-place as segments are processed sequentially, accumulating
* deltas from the VLQ-encoded mappings string. This avoids repeated conversions between
* 0-based and 1-based coordinates.
*
* @example Creating initial offset
* ```ts
* const offset: VLQOffsetInterface = {
* line: 0,
* column: 0,
* generatedLine: 0,
* generatedColumn: 0,
* sourceIndex: 0,
* nameIndex: 0
* };
* ```
*
* @see {@link SegmentInterface}
*
* @since 5.0.0
*/
interface VLQOffsetInterface {
/**
* 0-based running source line.
*
* @remarks
* Accumulates line deltas from decoded VLQ segments.
* Internal representation only; converted to 1-based for public API.
*
* @since 5.0.0
*/
line: number;
/**
* 0-based running source column.
*
* @remarks
* Accumulates column deltas from decoded VLQ segments.
* Internal representation only; converted to 1-based for public API.
*
* @since 5.0.0
*/
column: number;
/**
* 0-based running generated line (frame index).
*
* @remarks
* Tracks the current line in the generated output file.
* Internal representation only; converted to 1-based for public API.
*
* @since 5.0.0
*/
generatedLine: number;
/**
* 0-based running generated column — resets to 0 at the start