Skip to content

sourcemap inject/upload shifts Turbopack chunks by one line without updating indexed source map offsets #2189

Closed

Description

@manuelconcari-ai

Environment

Summary

A Turbopack chunk already registers its debug ID at runtime (_debugIds) and references an indexed source map (sections). When the CLI rewrites such a chunk:

  1. It does not recognize the existing registration, because DEBUGID_REGISTRATION_RE only matches _sentryDebugIds. It therefore prepends a second registration snippet for the same debug ID, which moves the code down by one line.
  2. mutateSourcemap accounts for the inserted line only when the map has a top-level mappings string. In an indexed map, sections[].offset.line stays unchanged.

The JavaScript below the new snippet is now one line lower than its map describes. In the two production events we inspected, Sentry reported js_invalid_sourcemap_location on all four in-app frames in each event. With 0.45.0, the same fixture is left untouched and resolves correctly. The browser SDK already reads Turbopack's _debugIds registry.

Steps to reproduce

Create the four files below in an empty directory, preserving the fixture/ subdirectory. The reproduction needs no Sentry account or token. The fixture is one browser chunk emitted by Next.js 16.4.6 (Turbopack) and its map, with the page source in sourcesContent. The script runs sourcemap inject from both CLI versions on fresh copies of the fixture and resolves the position of the thrown Error.

npm install
npm test
package.json
{
  "name": "sentry-turbopack-index-map-repro",
  "private": true,
  "scripts": {
    "test": "node check.cjs"
  },
  "dependencies": {
    "sentry-045": "npm:sentry@0.45.0",
    "sentry-049": "npm:sentry@0.49.0",
    "@jridgewell/trace-mapping": "0.3.31"
  }
}
check.cjs
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { AnyMap, originalPositionFor } = require('@jridgewell/trace-mapping');

const fixture = path.join(__dirname, 'fixture');
const chunk = '1obvdtwx4rn16.js';
const marker = 'Error("SENTRY_SOURCEMAP_PROBE")';

function readPosition(directory) {
  const source = fs.readFileSync(path.join(directory, chunk), 'utf8');
  const mapName = source.match(/^\/\/# sourceMappingURL=(.+)$/m)[1];
  const map = JSON.parse(fs.readFileSync(path.join(directory, mapName), 'utf8'));
  const lines = source.split('\n');
  const line = lines.findIndex(value => value.includes(marker));
  assert.ok(line >= 0, 'The probe must be present');
  const column = lines[line].indexOf(marker);
  const generated = { line: line + 1, column };
  const original = originalPositionFor(AnyMap(map), generated);
  return { source, generated, original, offset: map.sections[0].offset, debugId: map.debugId };
}

async function run() {
  const before = readPosition(fixture);
  assert.equal(before.original.source, 'turbopack:///[project]/app/page.jsx');
  assert.equal(before.original.line, 4);
  const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'sentry-index-map-'));
  try {
    for (const [alias, version] of [['sentry-045', '0.45.0'], ['sentry-049', '0.49.0']]) {
      const directory = path.join(scratch, version);
      fs.cpSync(fixture, directory, { recursive: true });
      const { createSentrySDK } = require(alias);
      await createSentrySDK({}).sourcemap.inject({ directory });
      const after = readPosition(directory);
      const { line, column } = after.generated;
      const target = after.original.source ? after.original.source + ':' + after.original.line : 'unmapped';
      console.log('sentry ' + version + ' | generated ' + line + ':' + (column + 1) + ' | ' + target + ' | section offset ' + after.offset.line);
      assert.equal(after.debugId, before.debugId);
      assert.deepEqual(after.offset, before.offset);
      if (version === '0.45.0') {
        assert.equal(after.source, before.source);
        assert.deepEqual(after.original, before.original);
      } else {
        assert.equal(after.generated.line, before.generated.line + 1);
        assert.equal(after.generated.column, before.generated.column);
        assert.equal(after.original.source, null);
        assert.equal(after.source.slice(after.source.indexOf('\n') + 1), before.source);
      }
    }
  } finally {
    fs.rmSync(scratch, { recursive: true, force: true });
  }
}

run().catch(error => { console.error(error); process.exitCode = 1; });
fixture/1obvdtwx4rn16.js
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="d37f6edd-754f-4ae8-55a7-5a56ad9b1bb4")}catch(e){}}();
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,29615,t=>{"use strict";var o=t.i(43476);function r(){throw Error("SENTRY_SOURCEMAP_PROBE")}t.s(["default",0,function(){return(0,o.jsx)("button",{onClick:r,children:"Run probe"})}])}]);

//# debugId=d37f6edd-754f-4ae8-55a7-5a56ad9b1bb4
//# sourceMappingURL=1_nu1wwpxe6dj.js.map
fixture/1_nu1wwpxe6dj.js.map
{
  "version": 3,
  "sources": [],
  "debugId": "d37f6edd-754f-4ae8-55a7-5a56ad9b1bb4",
  "sections": [
    {"offset": {"line": 1, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/app/page.jsx"],"sourcesContent":["'use client';\n\nfunction reportProbeFailure() {\n  throw new Error('SENTRY_SOURCEMAP_PROBE');\n}\n\nexport default function Page() {\n  return <button onClick={reportProbeFailure}>Run probe</button>;\n}\n"],"names":["reportProbeFailure","Error","Page","onClick"],"mappings":"wJAEA,SAASA,IACP,MAAM,AAAIC,MAAM,yBAClB,kBAEe,SAASC,EACtB,MAAO,CAAA,EAAA,EAAA,GAAA,EAAC,SAAA,CAAOC,QAASH,WAAoB,aAC9C"}}]
}

Expected result

After inject or upload, the thrown error still resolves to turbopack:///[project]/app/page.jsx:4, as with 0.45.0:

sentry 0.45.0 | generated 2:172 | turbopack:///[project]/app/page.jsx:4 | section offset 1

Actual result

sentry 0.49.0 | generated 3:172 | unmapped | section offset 1

The displayed stack lines and columns are one-based. Source map section offsets are zero-based. Looking up the position one line above (2:172) in the rewritten map returns the original throw site.

We also reproduced this through next build with the same synthetic page and Next.js 16.4.6 in both builds. Before the SDK upload, the chunk and its map were byte-identical between builds. A local HTTP receiver captured the artifact bundles sent by both SDK versions. With 11.12.0 the uploaded JavaScript had the extra line, the map still had section offset 1, and clicking the button in Chromium produced the 3:172 frame.

Possible fix

  • Recognize the runtime registration emitted by Turbopack, including the parenthesized form (e._debugIds || (e._debugIds = {}))[n] = "<id>" shown in the fixture. Skip the extra snippet when that registration already matches the debug ID. A comment alone does not establish that the ID is registered at runtime.
  • When inserting a snippet into a chunk with an indexed map, preserve the mappings at and after the insertion point. For this fixture, incrementing the section's line offset from 1 to 2 would restore the mapping. If a hashbang or Bun pragma places the insertion inside an existing section, that section's own mappings also need to account for the added line.

Activity

  1. linear-code commented on Nov 11, 2026

    @linear-code
  2. sentry-junior commented on Nov 11, 2026

    @sentry-junior
    Contributor

    Thanks @manuelconcari-ai for the excellent report — the self-contained fixture and side-by-side 0.45.0/0.49.0 comparison made this quick to confirm.

    Confirmed on main (de6a899); your reproduction matches exactly (0.49.0 | generated 3:172 | unmapped | section offset 1). Two separate bugs:

    1. Regression in 0.46.0 from Plan SDK-owned migrations for all Sentry SDK upgrades #1630. Since then, a file with an existing debug ID is left alone only if DEBUGID_REGISTRATION_RE finds a registration snippet. That regex only matches _sentryDebugIds writes, so it misses Turbopack's (e._debugIds||(e._debugIds={}))[n]="…", and the CLI adds a duplicate snippet.
    2. Older bug (also in 0.45.0): mutateSourcemap only shifts top-level mappings, so indexed maps (sections) keep stale offsets whenever a snippet is inserted. Removing the existing debug ID from your fixture reproduces the misalignment on 0.45.0 too.

    We're fixing both: recognize Turbopack's registration, and shift indexed-map section offsets (including a section that spans the insertion point). Until a release is out, pinning sentry to 0.45.0 or uploading with --no-rewrite avoids the shift.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions