Skip to content

Change sourcesContent type to allow null values - #75

Closed
lahmatiy wants to merge 70 commits into
7rulnik:mainfrom
lahmatiy:patch-1
Closed

lahmatiy wants to merge 70 commits into
7rulnik:mainfrom
lahmatiy:patch-1

Conversation

@lahmatiy

@lahmatiy lahmatiy commented Jun 3, 2026 •

Copy link
Copy Markdown

sourcesContent entries can be null

7rulnik and others added 30 commits February 1, 2026 17:56
scripts/bench-diff.sh runs `yarn bench:jridgewell:{trace,generate}` once on
the working tree and once with the lib files of a baseline ref overlaid
into the working tree. Each side runs in its own process; the candidate
build's source-map.js / lib are restored on exit (incl. Ctrl-C / failure).

scripts/bench-delta.js parses both bench logs, extracts the
"source-map-js current" rows by fixture and suite, and prints a delta
table plus a one-line summary (mean / best / worst).

Two-process is required because in-process DIFF=1 mode has a structural
~20-50% gap on init benches even when both columns are byte-identical:
V8 specializes physically distinct module instances asymmetrically when
the bench chains `new Consumer(...).originalPositionFor(...)`. Validated
main vs main, single fixture: all rows within ±5%, mean +1.8%.
Use direct string indexing instead of function call to base64.encode().
Avoids function call overhead and bounds check in hot serialization path.

Benchmark shows ~8.5% serialization improvement (~19ms on 2.35M mappings).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add lookup table for VLQ encoding values -15 to 15, which encode to
a single base64 character. This avoids function call overhead for
the most common small delta values in source maps.

Results: -3% serialization time

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
7rulnik and others added 22 commits May 10, 2026 21:57
The trace bench rig didn't have an `eachMapping` phase, so any change
that touches the per-mapping result-building path inside `eachMapping`
(e.g. the precomputed `_absoluteSources` index) had no measurement
hook. Add two phases — generated order and original order — keyed
under `PHASES=eachmapping-generated,eachmapping-original`.

The phases call `consumer.eachMapping(noop)` and
`consumer.eachMapping(noop, null, ORIGINAL_ORDER)` on the
already-warmed-up `smcjsCurrent`. `_generatedMappings` and
`_originalMappings` are pre-built by the Memory Usage / Init /
Generated Positions calls earlier in the same `bench()` run, so the
reported ops/sec measure only the iteration itself.

Bench-delta's suite-header regex previously required an uppercase
first character; relaxed it to `[A-Za-z]` so `eachMapping speed
(...)` headers are recognized.

Smoke run on preact.js.map shows ~35k ops/sec on both orders;
self-vs-self bench-diff settles at ±0.3% (rig noise floor).
Mirror PR 7rulnik#49's optimization for the third call site that was still
re-resolving source URLs per mapping. `eachMapping` walked
`_generatedMappings` / `_originalMappings` and called
`util.computeSourceURL(sourceRoot, _sources.at(i), sourceMapURL)` on
each entry. The constructor already precomputes the same value per
source-index in `_absoluteSources`; reading from it skips the URL
parse + resolve.

For IndexedSourceMapConsumer, `_sources` is populated with
already-absolute URLs during `_parseMappings`, so set
`_absoluteSources = _sources.toArray()` at the end of that method to
give both consumer types the same field for `eachMapping` to index
into.

Not in any bench (`eachMapping` isn't exercised by the jridgewell
trace/generate suites), but the rationale is identical to 7rulnik#49 and the
gain shows up on any caller that walks all mappings — debuggers,
tooling that re-emits source maps, etc.
7rulnik#56)

Mirror the pattern BasicSourceMapConsumer._buildOriginalMappings already
uses: collect __originalMappings into per-source buckets during parse, then
sort each bucket with compareByOriginalPositionsNoSource. Eliminates the
flat quickSort that ran compareByOriginalPositions (with strcmp on the
source field) over the full flattened array, and adds a per-bucket
skip-sorted probe so well-formed input avoids the sort entirely.

A microbench wrapping each existing fixture into a single-section indexed
map (scripts/bench-indexed-init.js) shows +7–20% on init across all sizes;
none of the standard jridgewell trace fixtures are sectioned, so this
script is the only way to exercise IndexedSourceMapConsumer init.
…rulnik#57)

Mirror the pattern now in IndexedSourceMapConsumer._parseMappings (7rulnik#56)
and _buildOriginalMappings: collect __originalMappings into per-source
buckets during the conversion loop, sort each with
compareByOriginalPositionsNoSource (skip-sort-if-already-sorted), then
concat. Eliminates the flat quickSort with compareByOriginalPositions —
which did strcmp(source, source) per compare — from the only remaining
spot it was used.

Microbench: scripts/bench-fromsourcemap.js primes a generator from each
fixture (via SourceMapGenerator.fromSourceMap) and times
SourceMapConsumer.fromSourceMap on it. +6–22% on most fixtures, +52% on
vscode (where many sources × 2M segments made the strcmp sort dominant).
…ulnik#58)

Consecutive mappings almost always share `mapping.source` (and frequently
`mapping.name`) — bundler output groups mappings by source, then by name.
The previous code called `this._sources.indexOf(mapping.source)` and
`this._names.indexOf(mapping.name)` on every iteration, each hitting the
ArraySet's Map.get for a string already resolved on the previous pass.

Single-slot caches (`lastSourceStr → lastSourceIdx`, same for name) skip
the redundant lookup whenever the string matches. On miss, fall back to
indexOf and refresh the slot. No public surface change.

bench-diff.sh main generate (two-process, SOLO=1 PHASES=generate):

  amp.js.map        +8.3%
  babel.min.js.map  +1.9%
  issue-41.js.map  +14.8%
  preact.js.map     +4.0%
  react.js.map      +4.0%
  vscode.map        +5.0%
  mean              +6.3%
addMapping is the per-mapping bottleneck on the generate side (per
bench-data-followups 7rulnik#4 — slower than encoded output throughput). Two
small wins on the hot path:

1. Replace `util.getArg(aArgs, 'original'|'source'|'name', null)` with
   direct `aArgs.X != null ? aArgs.X : null` reads. Each getArg call did
   a function call + an `'X' in aArgs` prototype-walk. Downstream code
   already uses `!= null` so the undefined-vs-null distinction is moot.
   `generated` keeps getArg so the missing-arg throw is preserved when
   `_skipValidation` is true.

2. Drop the `if (!this._sources.has(s)) this._sources.add(s)` guard —
   ArraySet.add is already idempotent (does its own has() check
   internally before pushing). The outer has() was just an extra function
   call. Same for _names.

Public surface unchanged.

scripts/bench-diff.sh main generate (SOLO=1 PHASES=adding,generate):

  amp.js.map        Adding +65% / Generate +3%
  babel.min.js.map  Adding +41% / Generate -4% (noise)
  issue-41.js.map   Adding +112%
  preact.js.map     Adding +69% / Generate +6%
  react.js.map      Adding +57%
  vscode.map        Adding +68%

  mean +33% across all 12 rows, +65% across addMapping alone.
)

Same pattern as 7rulnik#59 applied to the per-query hot path. Three sites:

1. originalPositionFor (Basic) — `bias` is optional with default GLB.
   Replace `util.getArg(aArgs, 'bias', GLB)` with
   `aArgs.bias != null ? aArgs.bias : GLB`. Saves one function call +
   one `'bias' in aArgs` prototype-walk per trace.

2. generatedPositionFor (Basic) — same `bias` inline.

3. generatedPositionFor (Indexed) — hoist `util.getArg(aArgs, 'source')`
   out of the per-section loop (used to fire once per section, now once
   per call).

4. allGeneratedPositionsFor — `column` is optional with default 0,
   inlined the same way.

Required-arg `getArg` calls (line/column/source) kept as-is to preserve
the documented throw on missing args and the test-coverage shape (the
throw branches in util.js are reachable from many sites; moving them
inline would push uncovered branches into source-map-consumer.js).

scripts/bench-diff.sh main trace (SOLO=1 PHASES=trace-random,
trace-ascending,genpos-speed):

  Trace speed (random):             mean +15%   (+3% to +22%)
  Trace speed (ascending):          mean +14%   (-5% to +20%, mostly +15-20%)
  Generated Positions speed:        mean +11%   (-7% to +37%)
  overall mean across 18 rows:           +13.5%

Negative outliers (issue-41 ascending, vscode genpos-speed) are inside
bench variance on noisy fixtures.
…k#61)

Replace `util.getArg(mapping, 'lastGeneratedColumn', null)` with a direct
property read + null fallback at three return-site call points:

- BasicSourceMapConsumer.generatedPositionFor (per-query return)
- SourceMapConsumer.allGeneratedPositionsFor (per-mapping in result, two
  inner loops)

`mapping.lastGeneratedColumn != null ? mapping.lastGeneratedColumn : null`
matches the existing getArg behavior: returns null both when the field
is missing and when it's explicitly null, returns the value otherwise.
lastGeneratedColumn is only set by computeColumnSpans, so for most
maps it's undefined and the inline avoids the function call entirely.

scripts/bench-diff.sh main trace (SOLO=1 PHASES=genpos-speed):

  amp.js.map        +5.2%
  babel.min.js.map  +5.5%
  issue-41.js.map   +4.6%
  preact.js.map     +4.7%
  react.js.map      +0.3%
  vscode.map       +14.0%
  mean              +5.7%
…ik#62)

* perf: inline lastGeneratedColumn getArg in trace return paths

Replace `util.getArg(mapping, 'lastGeneratedColumn', null)` with a direct
property read + null fallback at three return-site call points:

- BasicSourceMapConsumer.generatedPositionFor (per-query return)
- SourceMapConsumer.allGeneratedPositionsFor (per-mapping in result, two
  inner loops)

`mapping.lastGeneratedColumn != null ? mapping.lastGeneratedColumn : null`
matches the existing getArg behavior: returns null both when the field
is missing and when it's explicitly null, returns the value otherwise.
lastGeneratedColumn is only set by computeColumnSpans, so for most
maps it's undefined and the inline avoids the function call entirely.

scripts/bench-diff.sh main trace (SOLO=1 PHASES=genpos-speed):

  amp.js.map        +5.2%
  babel.min.js.map  +5.5%
  issue-41.js.map   +4.6%
  preact.js.map     +4.7%
  react.js.map      +0.3%
  vscode.map       +14.0%
  mean              +5.7%

* perf: inline optional getArg in SourceMapGenerator constructor

Four sites: file, sourceRoot, skipValidation, ignoreInvalidMapping — all
optional with documented defaults. Same pattern as 7rulnik#59 / 7rulnik#60.

The BasicSourceMapConsumer constructor has the same shape but isn't
included here — its four optional fields (names, sourceRoot,
sourcesContent, file) introduce uncovered default-branches that drop
all-files branch coverage below the 97 threshold (needs new tests
covering minimal-field consumer construction; out of scope for this PR).

scripts/bench-diff.sh main generate (SOLO=1 PHASES=adding):

  amp.js.map        +7.7%
  babel.min.js.map  +7.7%
  issue-41.js.map  +17.3%
  preact.js.map     +7.7%
  react.js.map      +6.6%
  vscode.map        -0.2%   (noise)
  mean              +8.7%

Bigger than the constructor preamble alone explains — likely a hidden-
class effect where direct property writes shape the SourceMapGenerator
instance more predictably than the opaque getArg return.
…eMap (7rulnik#64)

* perf: typed-array MappingList — slab storage + slab-direct serializer + applySourceMap rebuild

Replace lib/mapping-list.js's `Array<{...mappingObject}>` backing store with
an Int32Array slab. 6 i32 slots per mapping (genLine, genCol, srcIdx,
origLine, origCol, nameIdx), -1 sentinel for "no value". Source/name
strings live in the owning SourceMapGenerator's ArraySets; MappingList
stores the resolved indices so the serializer doesn't need a per-mapping
`indexOf` (which previously hit the ArraySet's Map.get even after the
single-slot indexOf cache from 7rulnik#58).

Per bench-data-followups 7rulnik#2 — generator memory ratio ≈ generator speed
ratio. The win is heap-pressure / GC / cache: 350k mapping objects per
addMapping cycle becomes 350k * 24 bytes contiguous slab.

`MappingList.add(genLine, genCol, origLine, origCol, srcIdx, nameIdx)`
takes positional integer args. `SourceMapGenerator.addMapping` resolves
sources/names through the existing ArraySets (which addMapping was already
calling) and passes the integer index in. No more `{ ... }` object literal
allocation per addMapping.

`SourceMapGenerator.applySourceMap` no longer mutates mapping objects
through the unsortedForEach callback — that pattern relied on the callback
receiving the actual stored reference, which slab storage can't provide.
The rewrite walks the old slab via the F_* constants, applies the
transformation, and emits into a fresh MappingList bound to the new
sources/names ArraySets, then swaps all three at once.

`SourceMapGenerator._serializeMappings` reads the slab directly instead of
toArray(). Source/name fields stored in the slab are already the int
indices needed for serialization (resolved when added) — no per-mapping
`indexOf` lookup. The compareByGeneratedPositionsInflated dedup check is
replaced with `ml._equalsPrev(i)` — a slab method that does six i32
equality checks. Same equality classes as the old check (same srcIdx ⇔
same source string after interning) so the dedup still works.

`unsortedForEach` and `toArray` remain API-compatible by materializing
JS objects on demand from the slab. Internal hot paths bypass them.

* perf: BasicSourceMapConsumer.fromSourceMap reads MappingList slab directly

Drop the `aSourceMap._mappings.toArray().slice()` materialization. The
generator's MappingList already stores source/name as integer indices
into its _sources / _names ArraySets, and the new consumer's _sources /
_names were just initialized from the same toArray() output — so the
indices are identical and no per-mapping `indexOf` is needed.

Reads i32 fields straight from `ml._buf` via the F_* layout constants
exported from `lib/mapping-list.js`.

* test: coverage for typed-array MappingList and slab paths

- test/internal/test-mapping-list.js (new): unit tests for the MappingList
  surface — unsortedForEach / toArray materialization, the 6-level
  sortedness cascade in `add`, the matching cascade in `_sort`'s
  comparator, the `_equalsPrev` dedup helper, and slab capacity growth.
- test/internal/test-source-map-consumer-internals.js: add a fromSourceMap
  test that exercises a source-less generated mapping (case-1 per
  _validateMapping) so the `srcIdx === -1` slab-read branch is covered.
- test/internal/test-util.js: pin direct genLine/genCol coverage for
  compareByGeneratedPositionsInflated. The function was previously
  covered transitively through MappingList.add's generatedPositionAfter;
  the new slab-backed MappingList doesn't call it, so those early-return
  branches need direct test coverage.

* test: cover applySourceMap with source-less mappings + drop unreachable origCol guard

Two coverage holes flagged by the per-branch lcov:
- lib/source-map-generator.js:253 — the `srcIdx === -1 ? null : ...`
  ternary's `null` arm only fires when applySourceMap walks a source-less
  mapping, and existing applySourceMap tests are all fully-sourced.
- lib/source-map-generator.js:259 — `origCol === -1 ? 0 : origCol` was
  unreachable. addMapping sets `origLine` and `origCol` together, so
  inside the `origLine !== -1` branch above, `origCol === -1` never
  fires. Dropping the guard removes the dead branch.

Adds an applySourceMap test in test-source-map-consumer-internals.js
that feeds the outer generator a source-less mapping alongside a
fully-sourced one and asserts the source-less mapping passes through
unchanged while the sourced one transforms.

Bumps all-files branch coverage 96.94 → 97.21 (above the 97 threshold).
source-map-generator.js is now 100/100/100.
…7rulnik#65)

Three per-mapping hot paths followed `add()` with `indexOf()` to grab the
inserted/existing index. Both call into the same Map: `add` does a
has+set+get-equivalent, `indexOf` does a redundant get. Returning the
index from `add` lets callers get the result for free — one Map op per
source/name instead of two.

Affected:
  * SourceMapGenerator.addMapping
  * SourceMapGenerator.applySourceMap
  * IndexedSourceMapConsumer._parseMappings

Bench (SOLO=1 PHASES=adding generate vs main, two-process):
  addMapping mean +21.4% across jridgewell fixtures
  (preact +30.3%, react +21.4%, amp +20.5%, issue-41 +34.8%,
   vscode +21.1%, babel.min +0.2% — flat, very few unique sources)

API: ArraySet.add gains a return value. Existing callers ignoring it
keep working unchanged.
… checks (7rulnik#66)

The previous form had:
  aGenerated && 'line' in aGenerated && 'column' in aGenerated
    && aGenerated.line > 0 && aGenerated.column >= 0

The numeric `> 0` / `>= 0` checks already subsume the `'line' in X`
membership tests — `undefined > 0` and `'abc' > 0` are both false, so
missing or non-numeric coords still fall to the error branches.
The `in` operator does a prototype-chain walk per check; dropping the
four redundant ones removes a measurable per-addMapping cost.

Also reordered: case 2/3 (full mapping) is the hot path on every
bundler emit; check it first and return. The friendly-error path
(original.line/column not numbers) and the generic invalid-mapping
path stay reachable for the cold cases.

Bench (SOLO=1 PHASES=adding generate vs main, two-process):
  preact +10.5%, react +10.2%, amp +7.3%, vscode +6.4%,
  issue-41 +5.2%, babel.min +3.9% — mean ~+7.3%
…rulnik#63)

Four sites — names, sourceRoot, sourcesContent, file — all optional with
documented defaults. Same pattern as 7rulnik#59 / 7rulnik#60 / 7rulnik#62.

Init bench shows mostly noise — mean +1.09% across 12 rows, range
-3.7% to +7.1%. Unlike the SourceMapGenerator ctor change in 7rulnik#62 (which
saw +8.7% on the addMapping bench, attributable to V8 hidden-class
effects helping the downstream hot path), the consumer ctor isn't
followed by a per-mapping hot loop in the same cycle — _parseMappings
dominates init cost, so saving four function calls in the preamble is
unmeasurable.

Keeping it anyway for consistency with the codebase pattern and to
prevent 7rulnik#62's followup readers from wondering why one ctor was inlined
and the other was left alone.

scripts/bench-diff.sh main trace (SOLO=1 PHASES=init):

  amp.js.map        JSON -2.5% / Object -0.8%
  babel.min.js.map  JSON +2.2% / Object +3.7%
  issue-41.js.map   JSON -3.7% / Object  0.0%
  preact.js.map     JSON +4.3% / Object +3.8%
  react.js.map      JSON -1.6% / Object +1.5%
  vscode.map        JSON -1.0% / Object +7.1%
  mean              +1.09%

Coverage holds: branch 97.16 / 98.75 (just above 97 / 98 thresholds).
No new tests needed — existing fixtures already exercise the default
branches.
…rulnik#67)

Three small structural changes to the per-mapping eachMapping loop:

1. Skip `aCallback.bind(context)` when `context === null`. The bind
   produces a bound function V8 can't inline, so every per-mapping call
   dispatches through Function.prototype's internal [[Call]] path. With
   no context (the common case — both bench callsites and most consumers
   omit it), `bind` is unnecessary and the unbound `aCallback` inlines
   normally.

2. Read `this._names._array` directly instead of `this._names.at(idx)`
   per named mapping. Saves the bounds-check + function-call pair —
   matches the slab-direct pattern used in `_serializeMappings` /
   `fromSourceMap`.

3. Hoist `mapping.source` / `mapping.name` into locals before building
   the result object — V8 should CSE this, but explicit locals are
   slightly more inline-friendly.

Bench (`SOLO=1 PHASES=eachmapping-generated,eachmapping-original
scripts/bench-diff.sh main trace`, two-process):

  preact +343%, react +316%, amp +233%, issue-41 +218%, babel.min +214%,
  vscode +173% — mean +243% across 12 rows.

The headline number reflects the bench's NOOP callback amplifying the
bind-vs-inline gap. With a real callback that does work the proportional
win shrinks, but the structural fix (no bound dispatch when context is
null) stands. Baseline error bars on amp are ±8% vs candidate's ±0.5%,
consistent with the bound-dispatch path being in a deopt/reopt cycle.
sourcesContent entries can be null
7rulnik added a commit that referenced this pull request Nov 19, 2026
* Fix typings that don't match runtime, without breaking changes

SourceMapConsumer:
- The constructor accepts a numeric version, null sourcesContent entries
  and a missing names array (new RawSourceMapInput), index maps
  (RawIndexMap, RawSection), JSON strings, and the sourceMapUrl argument.
- Declare the static fromSourceMap.
- allGeneratedPositionsFor takes an optional column and returns lastColumn.

SourceMapGenerator: type the skipValidation and ignoreInvalidMapping
options (SourceMapGeneratorOptions), also for fromSourceMap and
SourceNode#toStringWithSourceMap.

SourceNode: the constructor accepts nulls and chunk arrays, add and
prepend accept nested arrays and SourceNodes and return the node,
replaceRight accepts a RegExp or a replacer function, and children, line,
column, source and name are declared.

Return types that are wrong only in being non-nullable, or a string
version, stay as they are: fixing them breaks callers. A comment on each
says what happens at runtime.

Part of #111
Refs #43
Refs #30
Refs #75

* Keep allGeneratedPositionsFor and SourceNode compatible with existing callers

A required lastColumn broke writing plain positions into the result array (push, concat, indexOf, unshift, splice, reassigning). Make it optional.

Returning the node from add and prepend broke void-returning callbacks like (chunk: string): void => node.add(chunk). Keep void and note the runtime return value instead.

The new SourceNode members (children, line, column, source, name) made a SourceNode typed by another copy of the package, such as an older source-map-js or source-map 0.6, unassignable to this one. Drop them.
@7rulnik

7rulnik commented Nov 19, 2026

Copy link
Copy Markdown
Owner

thanks! fixed in #117

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants