# Source maps How typestrip keeps positions right, when it needs a source map, and how it makes one. Most of what typestrip does needs no map at all. Erase mode keeps every offset. Downlevel mode keeps every line, and shifts columns only inside the constructs it rewrites. A map exists to repair those columns, and nothing else. The design follows from that: map every line to itself, and add a column mapping wherever a rewrite moved text. ## Erasable syntax needs no map Erase mode is the common case. It replaces each erased character with a space and keeps every line terminator, so the output has the same UTF-16 length as the input and every kept character sits at its original offset. [modes.md](modes.md#erase-mode) states the guarantee in full. ```ts let x: number = 1; ``` ```js let x = 1; ``` A stack trace, a breakpoint, or a DevTools cursor in the output points at the same line and column in the source. There is nothing to map. ts-blank-space and Node's type stripping make the same choice for the same reason. The erase engine has no mapping code, and the `sourceMap` option is a no-op in erase mode: there is no map to make, and the output would map every position to itself. The same holds for `jsx: true` in erase mode, and for `runtime: "preserve"` in downlevel mode. JSX that is kept is kept at its offsets. ## Downlevel and JSX keep the lines Downlevel mode rewrites `enum`, instantiated `namespace`, parameter properties, `import x = require()`, `export =`, and, with `jsx` on, JSX elements. Each rewrite is designed under one rule: **every line of the input is a line of the output, and inserted text never contains a line break.** A construct that spans lines is rewritten line by line, so each line gets only its own inserts. [modes.md](modes.md#downlevel-mode) shows the output shapes. The rule is what makes a map cheap, and what makes the output usable without one. Line numbers in stack traces are right with no map at all. Columns are right on every line that holds no rewrite. Only columns on a rewritten line are wrong, and only from the first inserted character onward. So the map has one job: on each rewritten line, say where the source columns went. Every line maps to the line with the same number. That is the design center, and each part of the implementation below exists to keep it true or to express the few places where it isn't. ### The exceptions, and what happens to them Three places in the automatic JSX runtime's output broke "every line maps to itself" when it was first written: - **The `key` argument.** `
  • …
  • ` becomes `_jsx("li", {…}, (id))`. The key moves from attribute position to the third argument, which is at the element's close. If the element spans lines, the key's text is written on a later line than its source. This is a real move, and the map expresses it: the key's record carries its own source line, and the segment for it has a non-zero line delta. Every other segment's line delta is zero. - **A namespaced name split across lines.** `svg:\nrect` is written as one string, `"svg:rect"`, on the first line. The map expresses it the same way, with the record's source line. - **The runtime import after a trailing line comment.** The automatic runtime's import is written at the end of the file. When the file ends in a `//` comment, the import needed a new line. The cleanup work moves the import before the file's trailing trivia instead, so no line is ever added. Two other mechanics in the engine write into output that was already emitted, which would shift the generated columns of records logged before them: the parameter-property field list at the class body's `{`, and the JSX callee (`_jsx(`, `_jsxs(`, or `_createElement(`), which is chosen only when the element closes. The callee now gets a fixed-width slot at the element's open (`_jsx (` and `_jsxs(` are both six characters) that is filled in place at the close. `_createElement(` is longer and rare, and keeps the insert-and-adjust path. So does the field list: moving it after the constructor would change the order of the object's own keys, which the downlevel corpus pins, so the records logged before it are adjusted instead. ### What the map leaves out **`names`.** The `names` array lets a consumer show an original identifier where the generated code has a different one. typestrip renames nothing. `E` in `var E;(function(E){…}).call(E||(E={}),E)` is the same `E`. `_jsx` has no source identifier at all. So `names` is always empty. **Scopes.** The [Scopes proposal](https://github.com/tc39/ecma426/blob/main/proposals/scopes.md) to ECMA-426 adds `scopes` and `ranges` fields that describe the source's scope tree and its bindings in the generated code, so a debugger can show original variables through renaming and inlining. typestrip does neither. The one thing it would buy is hiding the synthetic function frame of an enum or namespace when stepping into one. That is cosmetic, the proposal is still moving, and only Chrome reads it. typestrip does not emit it. **Debug IDs.** The [Debug ID proposal](https://github.com/tc39/ecma426/blob/main/proposals/debug-id.md) adds a `debugId` UUID to the map and a matching `//# debugId=` comment to the generated file, so an error-reporting service can pair them without relying on file names. It is a property of a build, not of a transform. A caller that wants one adds the field to the map object typestrip returns. ## The rule consumers impose A `mappings` string is a list of segments, one list per generated line. Each segment names a generated column and the source position it starts at, and it stays in force until the next segment. Nothing in the format says a line has to have a segment. But the consumers that matter all behave the same way when a line has none: - **Chrome DevTools** keeps every segment in one array sorted by generated line and column. `findEntry` finds the last entry at or before the queried position, with no check that it is on the same line. A line with no segment resolves to the last segment of some earlier line. - **Node** (`--enable-source-maps`, `module.findSourceMap`) does the same binary search over the same flat layout, and returns nothing only for a position before the first segment of the whole map. - **Mozilla's `source-map` library**, which Firefox's debugger and several editors have used, requires the line to match and returns `null` for a line with no segment. The position is then shown as generated, or a breakpoint fails to bind. So a map with segments only on rewritten lines is wrong in Chrome and Node and lossy in Firefox. esbuild adds a segment at column 0 of every generated line, citing the `source-map` behavior, and sucrase does the same. typestrip does too. **The rule:** every generated line gets an **identity segment** at column 0 that maps to column 0 of the source line with the same number. A rewritten line gets more segments after it, one at each point where the source column stops tracking the generated column. ### A worked example ```ts enum E { A } foo(1); ``` ```js var E;(function(E) { A=0;var A;this.A=A;this[A]="A"; }).call(E||(E={}),E); foo(1); ``` A consumer maps every position in a segment to the segment's one source position. It does not add the distance from the segment's start. So once a line's columns have moved, each copied token needs a segment of its own to land on itself, and each inserted span needs one that names the source point it stands for. Before the first rewrite on a line, the identity segment covers everything. | Generated column | Text | Source column | Why | |---|---|---|---| | 0 | `var` | 0 | Identity segment | | 3 | ` ` | 3 | `enum` became `var` and a blank; the first copied range after a rewrite | | 6 | `;(function(E)` | 6 | Inserted; stands for the input after `E` | | 19 | ` ` | 6 | Copy resumes | | 20, 21, 22 | `{`, ` `, `A` | 7, 8, 9 | One segment per copied range | | 23 | `=0;var A;this.A=A;this[A]="A";` | 10 | Inserted | | 53, 54 | ` `, `}` | 10, 11 | Copy resumes | | 55 | `).call(E\|\|(E={}),E);` | 12 | Inserted | | 75 … 82 | ` `, `foo`, `(`, `1`, `)`, `;` | 12 … 19 | Copy resumes, one segment per range | Each segment is four fields: the generated column, the source index, the source line, and the source column. Each is a delta from the previous segment, except the generated column, which restarts at each line. The source index is always 0, since there is one source. The line delta is 0 on every segment of a line, and 1 on the first segment of the next line. The input ends in a newline, so there is a second, empty generated line, whose identity segment is generated column 0, source 0, line +1, and source column 0 − 20 = −20: ``` AAAA,GAAG,GAAG,aAAA,CAAC,CAAC,CAAC,CAAC,8BAAA,CAAC,CAAC,oBAAA,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AACpB ``` `CAAC` is a one-column step on both sides. `aAAA` is a 13-column step in the output with no step in the source: the copy resuming after inserted text. That last segment, `AACpB`, shows why the identity segment is not a constant string. The source column field is relative to the previous segment's source column, so it is `A` only when that column was 0. Across a run of unchanged lines it is `AACA` every time, which gzip reduces to almost nothing. A thousand-line file with no rewrites produces about 5 kB of `mappings` before compression. Each rewritten line adds a few bytes per segment. ## How it is built ### Lines and columns in the engine The engine works in UTF-8 byte offsets, and before this work it tracked no lines or columns at all. Errors crossed the ABI as UTF-16 offset pairs, converted by a forward-only cursor. Positions in a source map are UTF-16 columns within a line, so the engine needs both. The lexer already sees every byte, and already notes when a line terminator precedes a token. It now also counts terminators, and at each one records the UTF-16 cursor's count, which is the line's start. The spans the lexer skips with SIMD, block comments, strings, and templates, count the terminators their match masks find. A source column is the cursor's count at an offset minus the current line's start. A generated column is a source column plus the shift accumulated on the current generated line. The engine knows the shift at every point: each insert adds its length, each dropped span subtracts its length, and the shift resets at each emitted line terminator. No scan of the output is needed. ### Records Each **edit boundary**, where inserted text starts or where copying resumes after inserted or dropped input, logs one **record**, and so does each copied range on a line whose columns have already moved: generated line, generated column, source line, source column, plus the output offset and a kind the engine uses to adjust records under an anchor. The three output primitives write them, so no emitter knows about the map. Records go into a MAP memory region with `mapCount` and `mapPtr` exports, read incrementally by the wrapper after each `push`, the same way it reads the error region. `mapLine` and `mapSrcLine` give the final line counts, so the wrapper knows how many identity segments to fill. Erase mode's engine has no record region and no exports for it, so `build/erase.wasm` pays nothing. Output under an open anchor may still be rewritten, truncated, or inserted into before it is flushed. Records logged under an anchor are held with it. A rewrite in place changes no column and touches no record. A truncation drops the records past the truncation point; the automatic runtime's `key` saves its value's source position when it saves the value, and logs a record with it where the value is written again. An insert into earlier output adds its length to the generated column of every held record on that line after the insertion point. Only `_createElement(` and the parameter-property field list take that path. ### Encoding in the wrapper The wrapper serializes the map after the last chunk. It walks the lines in order. A line with no records gets its identity segment. A line with records gets its identity segment and then one segment per record. Each segment is four fields of VLQ: ```js const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function vlq(n) { let v = n < 0 ? (-n << 1) | 1 : n << 1, s = ""; do { let d = v & 31; v >>>= 5; if (v) d |= 32; s += B64[d]; } while (v); return s; } ``` VLQ is base64 with a continuation bit. The number is shifted left once and its sign goes in bit 0. Then it is written five bits at a time, lowest bits first, one base64 character per group, with bit 5 set on every character but the last. Most fields are one character. A generated column past 15 takes two, past 511 takes three. That function is the whole encoder. The libraries that do this are larger because they also decode, deduplicate sources and names, sort segments, and look positions up. typestrip emits one source, no names, and segments already in order, so none of that is needed. ### Streaming `mappings` is append-only. Each generated line's segments depend only on the previous segment's fields, so the wrapper carries four integers between chunks and never revisits a line. The map object itself is complete only after the last chunk, because `mappings` is a single string. `sources`, `sourcesContent`, and `file` are the caller's. typestrip does not know the file's name, and holding the whole input to fill `sourcesContent` would break the flat memory profile of streaming. The map typestrip returns has `version: 3`, `sources: [""]`, `names: []`, and `mappings`. A caller sets `sources[0]`, and `sourcesContent` or `file` if it wants them. ## The API ```js const { code, map } = await transform(src, { mode: "downlevel", sourceMap: true }); ``` With `sourceMap: true` and a string input, `transform` and `transformSync` return `{ code, map }` instead of a string. `map` is the source map object, not JSON. In erase mode `map` is `null`, since no position changed. With a stream of chunks, the generator still yields output strings. The map is available from the generator's return value when it finishes: ```js const gen = transform(chunks, { mode: "downlevel", sourceMap: true }); let out = "", next; while (!(next = await gen.next()).done) out += next.value; const map = next.value; ``` [api.md](api.md) has the option's full shape, including `source`, `file`, and `includeContent`. ## Testing - **Round trip.** `test/sourcemap.mjs` decodes each map with `@jridgewell/trace-mapping`, a devDependency, for every case in `corpus/downlevel.jsonl` and `corpus/jsx.jsonl`. Every line must have a segment at column 0, segments must be in order and within their lines, every segment must map to the line with the same number except where JSX moves a `key`, and every identifier that appears once in a source line and once in its output line must map back onto itself. A key's value is written from a saved copy, so everything inside it maps to the value's start. - **Streaming.** The same file, chunked at random and at every five bytes, must produce a byte-identical map. - **Line count.** The downlevel and JSX judges already require the output to have the input's line count. - **By eye.** Drop an output and its map into [source-map-visualization](https://evanw.github.io/source-map-visualization/) to inspect a case.