diff --git a/.changeset/nextjs-with-bugsee.md b/.changeset/nextjs-with-bugsee.md
new file mode 100644
index 000000000..4c61addc0
--- /dev/null
+++ b/.changeset/nextjs-with-bugsee.md
@@ -0,0 +1,6 @@
+---
+'@bugsee/nextjs': minor
+'@bugsee/bundler-plugin-core': minor
+---
+
+`@bugsee/nextjs/config` adds `withBugsee(nextConfig, options)`: `next build` now stamps debug-IDs and uploads source maps on both webpack and Turbopack (Next 15.4.0+ for Turbopack, through `compiler.runAfterProductionCompile`). Browser maps are deleted after a confirmed upload; server and edge maps are kept. `@bugsee/bundler-plugin-core` exports `stampAssets`, `AssetStore`, `notify`, `resolveIdentity`, `loadBuildPluginEnv` and `mergeBuildPluginEnv` for it.
diff --git a/.gitignore b/.gitignore
index 266576e0b..c3215bf0b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,6 +16,10 @@ reports/
# `biome check .` by the thousand.
.next/
+# Fixture apps the Next source-map e2e generates and builds (packages/nextjs-e2e/test/source-maps.e2e.ts).
+packages/nextjs-e2e/.fixtures/
+packages/nextjs-e2e/.scratch/
+
# tsup writes a bundled config next to the package when tsup.config.ts needs transpiling, and leaves
# it behind if the build is interrupted. Untracked, it fails `biome check .` on a formatting rule.
tsup.config.bundled_*.mjs
diff --git a/CLAUDE.md b/CLAUDE.md
index c0f47b62d..cf56c8e41 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -23,6 +23,7 @@ Runnable SDKs exist for **Node, Browser, Bun, Electron, Cloudflare/Vercel edge,
- Electron platform: `@bugsee/electron` (`docs/design/electron.md`, slices E0–E8, convergent-reviewed) — converges main (Node/`@bugsee/node`) + renderers (Chromium/`@bugsee/browser`) + native (`crashReporter` minidumps) into ONE session. Main OWNS the session; renderers stream capture UP over IPC (reusing the WebView **streaming CaptureStore** core, extracted to `@bugsee/core`) and are driven DOWN via a control channel (session handshake + pause/resume/flush/stop). Native crashes via Electron's built-in `crashReporter` (Crashpad), session-correlated `extra` (no bespoke native SDK). Visual capture D8: **rrweb DOM-replay is the DEFAULT** (rides the renderer streaming path free); **opt-in pixel video** (`video:{source}`) is a permission-gated report-time snapshot source (added the mobile-canonical `video` FileType + a generic node `reportSnapshots`/`fileEncoders` forwarding seam) supporting capturePage + MediaRecorder. Entries: `.`/`./main`/`./renderer`/`./preload`. `electron`/DOM taken as injected args — the package has **no electron/DOM dependency**.
- Extensions / umbrella: `@bugsee/performance` (APM — web-vitals + metric catalog, on-by-default via the umbrella) and `@bugsee/bugsee` (umbrella, with per-runtime browser/node `exports` conditions).
- E2E: `@bugsee/instrumentation-tests` — boots the REAL SDK in real node/bun processes against a mock collector and asserts the uploaded bundle (`pnpm test:e2e`; not in `pnpm test`).
+- Build integration (source maps): **`@bugsee/nextjs/config`** `withBugsee()` — webpack (per-compilation plugin) AND Turbopack (`compiler.runAfterProductionCompile`) upload, real-Next e2e in `@bugsee/nextjs-e2e` (`docs/design/source-maps.md` §7.3).
- Framework adapters: the **per-request context foundation** (portable `RequestContext` + `ContextProvider` in core; `AsyncLocalStorage` binding in node, with `run` + `enterWith`; **correlation-by-tagging** — entries stamped with `contextId`/trace, reports merge the active context) + **`@bugsee/express`** (`requestHandler`/`errorHandler`/`setupExpress`) + **`@bugsee/fastify`** (hook-based `setupFastify`) + **`@bugsee/nestjs`** (`setupNest`: `enterWith` context middleware + a configurable error seam — default non-intrusive interceptor, opt-in global ExceptionFilter or `both` deduped; real-Nest e2e on express+fastify) + **`@bugsee/hono`/`elysia`/`hapi`/`koa`** (each structural-peer, per-framework error-capture probed before building; real-framework e2e) are built. (Restify was built then dropped — unmaintained, doesn't import on Node ≥18.) Plus **incoming-server auto-instrumentation** (`docs/design/incoming-server-instrumentation.md`): a **shared server-instrument core in `@bugsee/node`** (`server-instrument.ts` — plain values → `ServerRequestSpan`; `runServerRequest`/`openServerRequest`/split `openServerContext`+`startServerSpan`/`getActiveServerSpan`; **first-owner-wins re-entrancy** = one context + one `http.server` txn even when the http layer AND an adapter both run; only a `run`-scoped owner is refinable) auto-instruments incoming requests via the **`node:http` `Server.prototype.emit` patch** + native **`Bun.serve`** wraps, **ON BY DEFAULT** (`instrumentIncomingRequests`, default `true`; `false` opts out). **All 7 adapters were refactored onto this core** (each keeps its own `shouldReport`/route extraction). `@bugsee/server-adapters` was **retired** (engine absorbed; `openBugsee*`→`server*`). See `docs/design/framework-adapters.md` + `docs/design/incoming-server-instrumentation.md` (`generic-server-adapter.md` is superseded).
- `launch(appToken, options)` returns the started client (every platform).
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index b57d06c64..c909a11ca 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1531,3 +1531,6 @@ Verified against current majors, all green with no adapter code changes: `@bugse
### Debug-ID stamping inside the build for Vite, Rollup and Rspack; verified stamps; safe map deletion (2026-11-23)
`@bugsee/bundler-plugin-core` now stamps INSIDE the build wherever the bundler has a pre-write hook, so Subresource Integrity hashes taken later describe the stamped bytes: webpack 5 and **Rspack** at `PROCESS_ASSETS_STAGE_DEV_TOOLING + 1` (shared `tapProcessAssetsStamp`), **Vite and Rollup** in `generateBundle` (`order: 'pre'`; `rollupAssetStore` over chunks + `.map` assets; the stamped id is also put on `chunk.map` because Vite regenerates the map of a lazy-loading chunk after user hooks). esbuild and the standalone CLI stay post-emit with the SRI refusal (its message now names the workaround). Every stamp is verified (`verify-stamp.ts`: parses, sourceMappingURL intact, map debugId matches, original bytes + appended stamp): in-build all-or-nothing, post-emit snapshot + restore of the failing pair (`stamp-files.ts`); an in-build stamp is re-checked on disk (`verifyStampedPairs`) and against the HTML (`findIntegrityMismatches`). `.map` deletion now requires a confirmed upload AND a debugId on the map (`partitionByKeyed`). Real-build proof: `plugin.in-build.real-build.test.ts` (Vite 7 + 8, Rollup, Rspack with its built-in SRI plugin) and a Chromium run in `instrumentation-tests/test/sri-vite-rollup.e2e.ts`. Measured ordering limits and what the guards do not see: `docs/design/source-maps.md` §7.1.
+
+### Next.js build integration: `withBugsee` (`@bugsee/nextjs/config`), webpack AND Turbopack (2026-11-23)
+`withBugsee(nextConfig, options)` makes `next build` stamp debug-IDs and upload source maps (gap #1 of the source-map gap analysis). Design + measured limits: `docs/design/source-maps.md` §7.3; user docs: `packages/nextjs/README.md`. **webpack** (`--webpack`, default <= 15): one per-compilation plugin (client, server, edge) stamping inside the compilation (`PROCESS_ASSETS_STAGE_DEV_TOOLING + 1`, SRI-safe) and uploading exactly the files that compilation emitted (`files` mode, nothing walks `.next`). The generic `@bugsee/webpack-plugin` was NOT reused for Next: measured against a real build it cannot stamp the server compilation (assets named `../app/page.js`, output path `.next/server/chunks`) and its directory-wide upload of `.next` collides across the three compilations. **Turbopack** (default 16; `--turbopack` 15.x): `compiler.runAfterProductionCompile` (15.4.0+) runs the real `inject` + upload over `.next/static` and `.next/server`, bundles paired with maps by the `sourceMappingURL` pointer (Turbopack does not name a map after its bundle; Next 15.5 shares one map between two runtime chunks, which are left unstamped with a notice). Measured limits: Turbopack writes the SRI hashes BEFORE the hook, so an `experimental.sri` Turbopack build is left unmodified with a notice (webpack handles SRI); Next 16 errors on a `webpack` function without a `turbopack` config, so none is added on Turbopack builds; `compiler.define` (not `defineServer`) bakes the app identity. Policy: browser maps deleted after a confirmed upload, server/edge maps kept (`deleteServerMaps`). Composes with a user's `webpack`, `compiler.runAfterProductionCompile`, `compiler.define`, `productionBrowserSourceMaps`, function/async configs; inert for dev/start/export. Core change: `@bugsee/bundler-plugin-core` now also exports `stampAssets`, `AssetStore`, `notify`, `resolveIdentity`, `loadBuildPluginEnv`, `mergeBuildPluginEnv`. Found by the independent reviews and fixed: stamped webpack assets are written as STRING sources (a Buffer is opaque to webpack's RealContentHashPlugin, which renames `[contenthash]` chunks after the stamp, so every lazy chunk 404'd; the e2e now opens each build in headless Chromium and asserts the lazy chunk runs), the baked define is the RAW value (Next JSON-encodes `compiler.define` itself; a JSON string arrived double-quoted), own-files-only deletion on Turbopack, contained post-build hook, version floors (hook 15.4.0, define 15.1.0), idempotent application. Real builds (`@bugsee/nextjs-e2e`, `test/source-maps.e2e.ts`, `next` 15.5.28 and 16.4.6 x webpack/Turbopack + SRI cases, real `bugsee-cli`, mock collector, `next start` smoke): see the PR for the run.
diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md
index aa7eae002..b9d1a372a 100644
--- a/docs/design/source-maps.md
+++ b/docs/design/source-maps.md
@@ -520,9 +520,67 @@ Windows hosts were not run. Bun does not map `Error.stack` and has no
---
+## 7.3 Next.js: `withBugsee` (`@bugsee/nextjs/config`)
+
+Status: **BUILT** (`packages/nextjs/src/config/`, real-build e2e `packages/nextjs-e2e/test/source-maps.e2e.ts`).
+`withBugsee(nextConfig, options)` wraps a Next config (object, phase function, async, or a promise) so
+`next build` stamps debug-IDs and uploads source maps, on **both** bundlers. It takes the plugin options of §4
+(through `resolvePluginOptions`, same env / `.env.bugsee-build-plugin` lookup, same identity resolution) plus
+`serverSourceMaps` (default on), `deleteServerMaps` (default off) and `silent`. It never touches `next dev`
+(`next start`, `next export`): a function config is gated on the phase, an object config on `dev` in the webpack
+function and on the hook only existing in a production build.
+
+**Why not the generic webpack plugin (measured).** Adding `@bugsee/webpack-plugin` in `webpack(config)` runs it
+three times (client, server, edge) and breaks on Next's layout: the server compilation's `output.path` is
+`.next/server/chunks` while its assets are named `../app/page.js`, so (1) the in-build stamp skipped them (an asset
+name may not escape the staging directory; the verify step then failed the run) and (2) the plugin's directory-wide
+upload of `.next` swept up the server compilation's files. `withBugsee` therefore ships a small per-compilation
+plugin that reuses the same core (`stampAssets`, `runPluginUpload`) but stages `../` names under a stand-in
+directory and uploads **exactly the files its own compilation emitted** (`files` mode; nothing walks `.next`).
+
+**Detecting the bundler.** `process.env.TURBOPACK` (set by `next build` before the config loads, Next 15.5 and 16
+alike); otherwise webpack. `NEXT_RSPACK` (the experimental Rspack adapter) is not special-cased and unverified.
+
+| | webpack (`--webpack`; default <= 15) | Turbopack (default 16; `--turbopack` in 15.x) |
+|---|---|---|
+| stamp | in the compilation, `PROCESS_ASSETS_STAGE_DEV_TOOLING + 1` (SRI-safe), client + server + edge | after the build, in `compiler.runAfterProductionCompile`: the real `inject` over the written files, with the post-emit verify-and-restore |
+| upload | each compilation's `afterEmit`, its own files | the hook: `.next/static` (browser) then `.next/server` (node + edge), explicit file lists |
+| maps | client: `productionBrowserSourceMaps` (forced on only if unset); server/edge: `devtool: 'source-map'` unless the app set one | always emitted (browser: `productionBrowserSourceMaps`; server maps are emitted regardless of `serverSourceMaps`, measured on 16.4) |
+| SRI (`experimental.sri`) | works: the hashes are of the stamped bytes (verified against the written HTML) | **not stampable**: Turbopack writes `server/subresource-integrity-manifest.json` and the HTML hashes BEFORE the hook (appending one byte in the hook made every `integrity` wrong), so the build is left unmodified, a notice says why, and nothing is uploaded |
+| min Next | any with `webpack()` | 15.4.0 (the first release with `compiler.runAfterProductionCompile`: present in the 15.4.0 types, schema and build, absent in 15.3.x, checked against the published tarballs); older Turbopack builds get a notice. `compiler.define` (the baked version/build) needs 15.1.0; below that it is not added |
+
+**Policy.** Browser maps live in `.next/static`, which `next start` and CDNs serve to every visitor: `deleteMaps`
+(default true) removes them after a *confirmed* upload, exactly as the plugins do (and, as there, a failed upload
+leaves them for a retry). `.next/server` is never served and a server run with source maps reads it, so server and
+edge maps stay unless `deleteServerMaps`. The build is registered once (browser run). The app version and build are baked
+through `compiler.define` (applies to all three runtimes; repeating the keys in `defineServer` is a Next error,
+measured). Only bundles that have a map are stamped on Turbopack, and bundles are paired with maps by the
+`sourceMappingURL` pointer inside each bundle: Turbopack does not name a map after its bundle (Next 16.4:
+`0ihtwxitjxx9w.js` points at `1wkfrb_3m2k-z.js.map`), and Next 15.5's Turbopack points two runtime chunks at ONE map.
+A map carries one debug-ID (the hash of bundle + map), so such bundles are left unstamped (a notice counts them) and
+their shared map stays on disk, unuploaded; they are Turbopack's runtime, not the app.
+
+**SRI fallback guard.** A webpack in-build stamp that failed falls back (core) to stamping the written files; on an SRI build that rewrites bytes Next already pinned (measured: Chromium blocked every script). The per-compilation plugin therefore skips the fallback and the upload when `experimental.sri` is set or Next's integrity manifest sits next to the output (`sri.ts`, shared with the Turbopack step), with a notice. `productionBrowserSourceMaps` is forced on only when this build can upload (not Turbopack + SRI, not Turbopack < 15.4.0), so an upload that cannot happen never leaves Bugsee-requested public maps. On webpack, when no upload follows (an SRI build whose stamp failed, or an abandoned stamp), the browser maps Bugsee itself turned on are deleted from this compilation's own files; maps the app enabled stay and the notice says they are public. Every removal is attempted and each failure reported through `onError` (console warning without one; `failOnError` rethrows the first); a throwing `onError` aborts like the core's. Nothing is deleted on a dry run. The reason a stamp did not apply is always reported through `onError`/console, never only through the (mutable) notice sink.
+
+**Composition.** The app's `webpack` function runs first and its result is extended (Next itself rejects an async one, measured on 16.4.6); its
+`compiler.runAfterProductionCompile` runs before ours; its `compiler.define` keys win; `productionBrowserSourceMaps`
+is respected when set. Without a token the integration changes nothing Next emits.
+
+**Open.** Both runs resolve the app identity, the token file and the installed Next from `process.cwd()` at config
+load, so run `next build` from the project directory (Next passes no project dir to a config function). The
+Turbopack hook does receive `metadata.projectDir` and says so when it differs from the directory the config was
+resolved for (`next build
` from a monorepo root); it does not re-resolve, so the baked define and the upload
+identity cannot disagree. Applying `withBugsee` twice is a no-op the second time (a WeakSet of extended configs). Any
+failure in the post-build hook is contained (reported, never thrown) unless `failOnError`, because Next fails the
+build on anything the hook throws. A failed upload leaves the browser maps in the public `.next/static` (forced on
+by `withBugsee`), and Next 15's shared Turbopack runtime map stays there too (unuploaded, not the app's code). A Turbopack SRI build
+cannot be symbolicated by upload (see the table); an in-hook alternative would have to re-hash the integrity
+manifests and the HTML Next writes later, which is Next's contract, not ours.
+
## 8. Deferred
- A real-`bugsee-cli` integration e2e (needs the built Rust binary in the harness) — follow-up once CI has it.
-- Turbopack loader for Next.js (`turbopack.rules`) — Next-adapter follow-up.
+- ~~Turbopack loader for Next.js (`turbopack.rules`)~~ — superseded by §7.3 (a post-build hook, not a loader: a loader
+ sees one module at a time and cannot stamp a finished chunk).
- Node/edge runtime debug-ID wiring (browser done in SM7) — trivial.
- The exact debug-ID WIRE FORMAT — additive ` debugId=` string suffix now; a structured `debug_meta`/per-frame
field is a refinement gated on the JS-backend symbolication contract.
diff --git a/packages/bundler-plugin-core/src/index.ts b/packages/bundler-plugin-core/src/index.ts
index c2fe56248..7f5854251 100644
--- a/packages/bundler-plugin-core/src/index.ts
+++ b/packages/bundler-plugin-core/src/index.ts
@@ -10,6 +10,7 @@ export {
findPackageVersion,
} from './app-identity';
export { deriveBuildUuid } from './build-id';
+export { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file';
export {
defaultDeleteMapFiles,
type RunFn,
@@ -36,8 +37,11 @@ export {
} from './register-build';
export {
type BugseePluginOptions,
+ notify,
type PluginRunResult,
+ type ResolvedIdentity,
type ResolvedPluginOptions,
+ resolveIdentity,
resolvePluginOptions,
runPluginUpload,
} from './resolve';
@@ -52,6 +56,7 @@ export {
type SpawnResult,
spawnProcess,
} from './run-cli';
+export { type AssetStore, type StampAssetsOptions, stampAssets } from './stamp-assets';
export {
isWorkingTreeDirty,
type ResolveVcsMetadataOptions,
diff --git a/packages/nextjs-e2e/package.json b/packages/nextjs-e2e/package.json
index 267d738ff..529d55136 100644
--- a/packages/nextjs-e2e/package.json
+++ b/packages/nextjs-e2e/package.json
@@ -14,8 +14,11 @@
},
"devDependencies": {
"next": "^15.5.28",
+ "next16": "npm:next@16.4.6",
+ "playwright": "^1.64.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
+ "tsx": "4.23.15",
"vitest": "^4.0.0"
}
}
diff --git a/packages/nextjs-e2e/test/edge-build.e2e.ts b/packages/nextjs-e2e/test/edge-build.e2e.ts
index d48ff8744..c15bcc17c 100644
--- a/packages/nextjs-e2e/test/edge-build.e2e.ts
+++ b/packages/nextjs-e2e/test/edge-build.e2e.ts
@@ -31,11 +31,17 @@ describe('@bugsee/nextjs — real `next build`', () => {
beforeAll(() => {
rmSync(outDir, { recursive: true, force: true });
- build = spawnSync('pnpm', ['exec', 'next', 'build'], {
- cwd: appDir,
- encoding: 'utf8',
- env: { ...process.env, NEXT_TELEMETRY_DISABLED: '1' },
- });
+ // The `next` binary is invoked by path: this package also installs Next 16 (as `next16`, for the source-map
+ // e2e), whose bin of the same name would win a `pnpm exec next`.
+ build = spawnSync(
+ process.execPath,
+ [join(appDir, 'node_modules', 'next', 'dist', 'bin', 'next'), 'build'],
+ {
+ cwd: appDir,
+ encoding: 'utf8',
+ env: { ...process.env, NEXT_TELEMETRY_DISABLED: '1' },
+ },
+ );
});
afterAll(() => {
diff --git a/packages/nextjs-e2e/test/packed-config.e2e.ts b/packages/nextjs-e2e/test/packed-config.e2e.ts
new file mode 100644
index 000000000..5e8bb1621
--- /dev/null
+++ b/packages/nextjs-e2e/test/packed-config.e2e.ts
@@ -0,0 +1,136 @@
+// The PUBLISHED shape of `@bugsee/nextjs/config`: packs `@bugsee/nextjs` and every workspace package it depends on
+// (pnpm applies each `publishConfig`, so `exports` point at `dist`), unpacks them as an app's node_modules, and
+// loads the config entry the way a real next.config does: `require()` from a CJS `next.config.js` and `import` from
+// an ESM `next.config.mjs`. In the repo everything resolves to `src`, so this is the only check of the dual build.
+import { execFileSync } from 'node:child_process';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+const repo = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
+const packages = join(repo, 'packages');
+let app: string;
+
+/** `@bugsee/*` workspace packages reachable from `name` through `dependencies`, `name` included. */
+function workspaceClosure(name: string, seen = new Map()): Map {
+ const dir = join(packages, name.replace('@bugsee/', ''));
+ if (seen.has(name)) return seen;
+ seen.set(name, dir);
+ const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as {
+ dependencies?: Record;
+ optionalDependencies?: Record;
+ };
+ const wanted = { ...manifest.dependencies, ...manifest.optionalDependencies };
+ for (const [dep, range] of Object.entries(wanted)) {
+ if (range.startsWith('workspace:')) workspaceClosure(dep, seen);
+ }
+ return seen;
+}
+
+beforeAll(() => {
+ const closure = workspaceClosure('@bugsee/nextjs');
+ const filters = [...closure.keys()].flatMap((n) => ['--filter', n]);
+ execFileSync('pnpm', ['--dir', repo, ...filters, 'run', '--if-present', 'build'], {
+ stdio: 'ignore',
+ });
+ app = mkdtempSync(join(tmpdir(), 'bugsee-packed-'));
+ const modules = join(app, 'node_modules');
+ mkdirSync(join(modules, '@bugsee'), { recursive: true });
+ // The packed tarballs, unpacked as an app's node_modules (pnpm applies each `publishConfig`).
+ for (const [name, dir] of closure) {
+ const target = join(modules, name);
+ mkdirSync(target, { recursive: true });
+ const out = mkdtempSync(join(tmpdir(), 'bugsee-pack-'));
+ execFileSync('pnpm', ['pack', '--pack-destination', out], { cwd: dir, stdio: 'ignore' });
+ execFileSync('tar', [
+ '-xzf',
+ join(out, readdirSync(out)[0] as string),
+ '-C',
+ target,
+ '--strip-components=1',
+ ]);
+ rmSync(out, { recursive: true, force: true });
+ }
+ // Third-party dependencies, and ONLY the ones the packed manifests DECLARE. No registry, no package store: each
+ // declared dependency is linked from where the monorepo installed it (its own transitive dependencies resolve from
+ // that real location). A dependency a package uses but forgot to declare is therefore missing here, exactly as it
+ // would be for a user, which a monorepo-wide node_modules would hide.
+ for (const [name] of closure) {
+ const packed = JSON.parse(readFileSync(join(modules, name, 'package.json'), 'utf8')) as {
+ dependencies?: Record;
+ optionalDependencies?: Record;
+ };
+ for (const dep of Object.keys({ ...packed.dependencies, ...packed.optionalDependencies })) {
+ if (closure.has(dep)) continue;
+ const installed = join(closure.get(name) as string, 'node_modules', dep);
+ const link = join(modules, dep);
+ if (!existsSync(installed) || existsSync(link)) continue;
+ mkdirSync(dirname(link), { recursive: true });
+ symlinkSync(realpathSync(installed), link);
+ }
+ }
+ writeFileSync(join(app, 'package.json'), JSON.stringify({ name: 'app', version: '3.2.1' }));
+}, 900_000);
+
+afterAll(() => {
+ if (app) rmSync(app, { recursive: true, force: true });
+});
+
+const probe = `
+ const out = withBugsee({ reactStrictMode: true }, { appToken: 't', vcs: false });
+ console.log(JSON.stringify({
+ kind: typeof withBugsee,
+ strict: out.reactStrictMode,
+ maps: out.productionBrowserSourceMaps,
+ version: out.compiler && out.compiler.define && out.compiler.define.__BUGSEE_APP_VERSION__,
+ }));
+`;
+const expected = { kind: 'function', strict: true, maps: true, version: '3.2.1' };
+
+describe('the published @bugsee/nextjs/config', () => {
+ it('exports map to dist, with an import and a require build', () => {
+ const manifest = JSON.parse(
+ readFileSync(join(app, 'node_modules', '@bugsee', 'nextjs', 'package.json'), 'utf8'),
+ ) as { exports: Record };
+ const entry = manifest.exports['./config'];
+ expect(entry?.require.default).toBe('./dist/config.cjs');
+ expect(entry?.import.default).toBe('./dist/config.js');
+ for (const file of [entry?.require.default, entry?.import.default]) {
+ expect(existsSync(join(app, 'node_modules', '@bugsee', 'nextjs', file as string))).toBe(true);
+ }
+ });
+
+ it('works from a CommonJS next.config.js (require)', () => {
+ const out = execFileSync(
+ process.execPath,
+ ['-e', `const { withBugsee } = require('@bugsee/nextjs/config');${probe}`],
+ { cwd: app, encoding: 'utf8', env: { ...process.env, TURBOPACK: '' } },
+ );
+ expect(JSON.parse(out.trim().split('\n').pop() as string)).toEqual(expected);
+ });
+
+ it('works from an ESM next.config.mjs (import)', () => {
+ writeFileSync(
+ join(app, 'probe.mjs'),
+ `import { withBugsee } from '@bugsee/nextjs/config';${probe}`,
+ );
+ const out = execFileSync(process.execPath, ['probe.mjs'], {
+ cwd: app,
+ encoding: 'utf8',
+ env: { ...process.env, TURBOPACK: '' },
+ });
+ expect(JSON.parse(out.trim().split('\n').pop() as string)).toEqual(expected);
+ });
+});
diff --git a/packages/nextjs-e2e/test/source-maps.e2e.ts b/packages/nextjs-e2e/test/source-maps.e2e.ts
new file mode 100644
index 000000000..37cf79025
--- /dev/null
+++ b/packages/nextjs-e2e/test/source-maps.e2e.ts
@@ -0,0 +1,649 @@
+// `withBugsee` against REAL `next build`s, for both bundlers and both Next generations that matter:
+//
+// next 15.5 + webpack (its default) next 15.5 + `--turbopack`
+// next 16.4 + Turbopack (its default) next 16.4 + `--webpack`
+//
+// Each builds a tiny app (a client page with a lazy chunk, a node route, an edge route) through the REAL
+// `@bugsee/nextjs/config`, the REAL `bugsee-cli` and a mock collector, then asserts the outcome on disk and on the
+// wire: the bundles are stamped, the maps reached the collector keyed by those exact debug-IDs, the public maps are
+// gone, the server maps are kept, the version is baked into the bundle, and the build still RUNS (`next start`).
+//
+// Plus the Subresource-Integrity cases: webpack stamps inside the build so the hashes stay right; Turbopack hashes
+// before its post-build hook, so the build is left unmodified and says so.
+import { type ChildProcess, spawn } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import {
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ statSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { createServer, type Server } from 'node:http';
+import { createRequire } from 'node:module';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { type Browser, chromium } from 'playwright';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const pkgDir = join(here, '..');
+const fixturesRoot = join(pkgDir, '.fixtures');
+const require_ = createRequire(import.meta.url);
+const tsxLoader = join(dirname(require_.resolve('tsx/package.json')), 'dist', 'loader.mjs');
+
+let server: Server;
+let browser: Browser;
+let endpoint: string;
+const bodies: string[] = [];
+
+beforeAll(async () => {
+ browser = await chromium.launch({ headless: true });
+ rmSync(fixturesRoot, { recursive: true, force: true });
+ mkdirSync(fixturesRoot, { recursive: true });
+ // Every upload is answered "already have it", so it succeeds without a backend; the body is kept, so a test
+ // can look for the exact debug-IDs that were sent.
+ server = createServer((req, res) => {
+ const chunks: Buffer[] = [];
+ req.on('data', (c: Buffer) => chunks.push(c));
+ req.on('end', () => {
+ bodies.push(Buffer.concat(chunks).toString('latin1'));
+ res.setHeader('content-type', 'application/json');
+ res.end(
+ JSON.stringify({ ok: false, error: { type: 'DuplicateSymbolsFoundError', code: 16004 } }),
+ );
+ });
+ });
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
+ endpoint = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
+});
+afterAll(async () => {
+ await browser?.close();
+ await new Promise((r) => server.close(() => r()));
+ // BUGSEE_E2E_KEEP=1 leaves the built fixtures behind for inspection.
+ if (process.env.BUGSEE_E2E_KEEP === undefined) {
+ rmSync(fixturesRoot, { recursive: true, force: true });
+ }
+});
+
+interface Spec {
+ name: string;
+ /** The dependency name of the Next copy to build with (`next` = 15.5, `next16` = 16.4). */
+ next: 'next' | 'next16';
+ args: string[];
+ /** Extra source for the `withBugsee` options object and the Next config. */
+ options?: string;
+ nextConfig?: string;
+ /** Pre-seed FOREIGN source-map files (stylesheet and declaration maps nothing in this build produced). */
+ seedForeign?: boolean;
+ /** Make `bugsee-cli sourcemaps inject` fail for the IN-BUILD stamp only (the post-emit one reaches the real CLI). */
+ failInBuildStamp?: boolean;
+}
+
+/** The real bugsee-cli binary, as the core resolves it. */
+const realCli = (
+ createRequire(join(pkgDir, '..', 'bundler-plugin-core', 'package.json'))('@bugsee/cli') as {
+ binaryPath(): string;
+ }
+).binaryPath();
+
+/** Where the foreign files are written, relative to the dist dir, and what they contain. */
+const FOREIGN = [
+ ['static', 'foreign.css.map'],
+ ['static', 'foreign.d.ts.map'],
+ ['server', 'foreign.css.map'],
+ ['server', 'foreign.d.ts.map'],
+] as const;
+const FOREIGN_BODY = '{"version":3,"sources":["foreign.css"],"names":[],"mappings":""}';
+
+/** Next config source that writes the foreign files from BOTH bundlers' paths, before Bugsee's step runs. */
+const SEED_HOOK = `
+ compiler: { runAfterProductionCompile: async ({ distDir }) => seed(distDir) },`;
+const SEED_WEBPACK = `
+ webpack(config, { isServer }) {
+ config.plugins.push({ apply(compiler) {
+ compiler.hooks.afterEmit.tap('seed', () => {
+ const out = compiler.options.output.path;
+ seed(isServer ? join(out, '..', '..') : out);
+ });
+ } });
+ return config;
+ },`;
+const SEED_PRELUDE = `
+import { mkdirSync as mk, writeFileSync as wr } from 'node:fs';
+import { join } from 'node:path';
+function seed(dist) {
+ for (const [dir, name] of ${JSON.stringify(FOREIGN)}) {
+ mk(join(dist, dir), { recursive: true });
+ wr(join(dist, dir, name), ${JSON.stringify(FOREIGN_BODY)});
+ }
+}
+`;
+
+interface Built {
+ dir: string;
+ status: number | null;
+ log: string;
+ uploads: string[];
+}
+
+const link = (target: string, path: string): void => {
+ mkdirSync(dirname(path), { recursive: true });
+ symlinkSync(realpathSync(target), path, 'dir');
+};
+
+/** Write a fixture app, build it with `spec`, and return what happened. */
+async function build(spec: Spec): Promise {
+ const dir = join(fixturesRoot, spec.name);
+ mkdirSync(join(dir, 'app', 'lazy'), { recursive: true });
+ mkdirSync(join(dir, 'app', 'api', 'hi'), { recursive: true });
+ mkdirSync(join(dir, 'app', 'edge'), { recursive: true });
+ const modules = join(dir, 'node_modules');
+ link(join(pkgDir, 'node_modules', spec.next), join(modules, 'next'));
+ link(join(pkgDir, 'node_modules', 'react'), join(modules, 'react'));
+ link(join(pkgDir, 'node_modules', 'react-dom'), join(modules, 'react-dom'));
+ link(join(pkgDir, '..', 'nextjs'), join(modules, '@bugsee', 'nextjs'));
+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: spec.name, version: '1.2.3' }));
+ // Plain JavaScript on purpose: a `.ts` file makes Next install TypeScript into the project.
+ writeFileSync(
+ join(dir, 'app', 'layout.jsx'),
+ "import './style.css';\nexport default function Layout({ children }) { return {children}; }\n",
+ );
+ writeFileSync(join(dir, 'app', 'style.css'), 'body { margin: 0; color: rebeccapurple; }\n');
+ writeFileSync(
+ join(dir, 'app', 'page.jsx'),
+ `'use client';
+import { useState } from 'react';
+import dynamic from 'next/dynamic';
+const Lazy = dynamic(() => import('./lazy/lazy.jsx'), { ssr: false });
+const version = typeof __BUGSEE_APP_VERSION__ === 'undefined' ? 'none' : __BUGSEE_APP_VERSION__;
+export default function Page() {
+ const [n, setN] = useState(0);
+ return ;
+}
+`,
+ );
+ writeFileSync(
+ join(dir, 'app', 'lazy', 'lazy.jsx'),
+ 'export default function Lazy() { return
lazy-ok
; }\n',
+ );
+ writeFileSync(
+ join(dir, 'app', 'api', 'hi', 'route.js'),
+ "export const GET = () => new Response('hi');\n",
+ );
+ writeFileSync(
+ join(dir, 'app', 'edge', 'route.js'),
+ "export const runtime = 'edge';\nexport const GET = () => new Response('edge');\n",
+ );
+ writeFileSync(
+ join(dir, 'next.config.mjs'),
+ `import { withBugsee } from '@bugsee/nextjs/config';${spec.seedForeign ? SEED_PRELUDE : ''}
+export default withBugsee(
+ { ${spec.next === 'next' ? 'eslint: { ignoreDuringBuilds: true },' : ''} ${spec.nextConfig ?? ''}${spec.seedForeign ? SEED_HOOK + (spec.args.includes('--webpack') ? SEED_WEBPACK : '') : ''} },
+ { appToken: 'e2e-token', endpoint: ${JSON.stringify(endpoint)}, appVersion: '9.8.7', appBuild: '42',
+ vcs: false, registerBuild: false, failOnError: true, ${spec.options ?? ''} },
+);
+`,
+ );
+ const stub = join(dir, 'cli-stub.js');
+ if (spec.failInBuildStamp) {
+ writeFileSync(
+ stub,
+ `const { spawnSync } = require('node:child_process');
+const args = process.argv.slice(2);
+if (args[0] === 'sourcemaps' && args[1] === 'inject' && String(args[2]).includes('bugsee-stamp-')) {
+ process.stderr.write('stub: the in-build inject is refused\\n');
+ process.exit(11);
+}
+process.exit(spawnSync(${JSON.stringify(realCli)}, args, { stdio: 'inherit' }).status ?? 1);
+`,
+ );
+ }
+ const before = bodies.length;
+ // Asynchronous on purpose: the mock collector lives in THIS process, and a blocking spawn would starve it.
+ const child = spawn(
+ process.execPath,
+ [join(modules, 'next', 'dist', 'bin', 'next'), 'build', ...spec.args],
+ {
+ cwd: dir,
+ env: {
+ ...process.env,
+ NEXT_TELEMETRY_DISABLED: '1',
+ NODE_OPTIONS: `--import ${tsxLoader}`,
+ ...(spec.failInBuildStamp ? { BUGSEE_CLI_PATH: stub } : {}),
+ },
+ },
+ );
+ let log = '';
+ child.stdout.on('data', (c: Buffer) => (log += c.toString()));
+ child.stderr.on('data', (c: Buffer) => (log += c.toString()));
+ const status = await new Promise((r) => child.on('close', r));
+ return { dir, status, log, uploads: bodies.slice(before) };
+}
+
+const walk = (dir: string): string[] =>
+ existsSync(dir)
+ ? readdirSync(dir).flatMap((name) => {
+ const full = join(dir, name);
+ return statSync(full).isDirectory() ? walk(full) : [full];
+ })
+ : [];
+
+const DEBUG_ID = /\/\/# debugId=([0-9a-f-]{36})/;
+const debugIdOf = (file: string): string | undefined =>
+ DEBUG_ID.exec(readFileSync(file, 'utf8'))?.[1];
+
+/** Every bundle under `dir` that points at a map, with the path it points at (the map may be deleted by now). */
+const pointing = (dir: string): Array<{ file: string; map: string }> =>
+ walk(dir)
+ .filter((f) => f.endsWith('.js'))
+ .flatMap((file) => {
+ const ref = /\/\/# sourceMappingURL=(\S+)\s*$/m.exec(readFileSync(file, 'utf8'))?.[1];
+ return ref === undefined ? [] : [{ file, map: join(dirname(file), decodeURIComponent(ref)) }];
+ });
+
+/**
+ * Bundles whose map belongs to them alone, and bundles that share a map with another (Next 15.5's Turbopack does
+ * that for its runtime chunks: a map carries one debug-id, so those are deliberately left unstamped).
+ */
+const split = (dir: string): { unique: string[]; shared: string[]; referenced: Set } => {
+ const all = pointing(dir);
+ const count = new Map();
+ for (const { map } of all) count.set(map, (count.get(map) ?? 0) + 1);
+ return {
+ unique: all.filter(({ map }) => count.get(map) === 1).map(({ file }) => file),
+ shared: all.filter(({ map }) => (count.get(map) as number) > 1).map(({ file }) => file),
+ referenced: new Set(all.map(({ map }) => map)),
+ };
+};
+
+const clientBundles = (dir: string): string[] => split(join(dir, '.next', 'static')).unique;
+
+const maps = (dir: string): string[] => walk(dir).filter((f) => f.endsWith('.map'));
+
+/** `next start` the build and fetch the paths; resolves their statuses. */
+async function runBuild(dir: string, paths: string[]): Promise {
+ const port = 41000 + Math.floor(Math.random() * 2000);
+ const child: ChildProcess = spawn(
+ process.execPath,
+ [join(dir, 'node_modules', 'next', 'dist', 'bin', 'next'), 'start', '-p', String(port)],
+ {
+ cwd: dir,
+ // `next start` loads next.config too, which imports the TypeScript source of @bugsee/nextjs/config.
+ env: { ...process.env, NEXT_TELEMETRY_DISABLED: '1', NODE_OPTIONS: `--import ${tsxLoader}` },
+ stdio: 'ignore',
+ },
+ );
+ try {
+ const statuses: number[] = [];
+ for (const path of paths) {
+ let status = 0;
+ for (let attempt = 0; attempt < 60 && status === 0; attempt++) {
+ try {
+ status = (await fetch(`http://127.0.0.1:${port}${path}`)).status;
+ } catch {
+ await new Promise((r) => setTimeout(r, 500));
+ }
+ }
+ statuses.push(status);
+ }
+ return statuses;
+ } finally {
+ child.kill('SIGKILL');
+ }
+}
+
+interface Page {
+ /** What the page printed to the console as an error, plus uncaught exceptions. */
+ errors: string[];
+ /** Same-origin requests that answered 4xx/5xx (the favicon is not the app's). */
+ failed: string[];
+ /** The text of the lazily loaded component, which renders only if its chunk loaded and ran. */
+ lazy: string | null;
+ /** The text of the page after hydration. */
+ body: string;
+ /** How many bundles registered a debug-id with the runtime (`globalThis._bugseeDebugIds`). */
+ debugIds: number;
+ /** Next's error overlay / error page text, when it replaced the app. */
+ crashed: boolean;
+}
+
+/** `next start` the build and open `/` in headless Chromium: does the app, lazy chunk included, actually RUN? */
+async function openInBrowser(dir: string): Promise {
+ const port = 43000 + Math.floor(Math.random() * 2000);
+ const child: ChildProcess = spawn(
+ process.execPath,
+ [join(dir, 'node_modules', 'next', 'dist', 'bin', 'next'), 'start', '-p', String(port)],
+ {
+ cwd: dir,
+ env: { ...process.env, NEXT_TELEMETRY_DISABLED: '1', NODE_OPTIONS: `--import ${tsxLoader}` },
+ stdio: 'ignore',
+ },
+ );
+ const context = await browser.newContext();
+ try {
+ const page = await context.newPage();
+ const errors: string[] = [];
+ const failed: string[] = [];
+ page.on('console', (m) => {
+ if (m.type() === 'error' && !m.text().includes('favicon')) errors.push(m.text());
+ });
+ page.on('pageerror', (e) => errors.push(String(e)));
+ page.on('response', (r) => {
+ if (r.status() >= 400 && !r.url().includes('favicon'))
+ failed.push(`${r.status()} ${r.url()}`);
+ });
+ let loaded = false;
+ for (let attempt = 0; attempt < 60 && !loaded; attempt++) {
+ try {
+ await page.goto(`http://127.0.0.1:${port}/`, { waitUntil: 'load' });
+ loaded = true;
+ } catch {
+ await new Promise((r) => setTimeout(r, 500));
+ }
+ }
+ expect(loaded, 'next start never answered').toBe(true);
+ // Hydrate, then give the lazy chunk its chance to load and run.
+ await page
+ .locator('button')
+ .first()
+ .click({ timeout: 15_000 })
+ .catch(() => undefined);
+ await page.waitForSelector('#lazy', { timeout: 10_000 }).catch(() => undefined);
+ const body = await page.evaluate(() => document.body.innerText);
+ return {
+ errors,
+ failed,
+ lazy: await page
+ .locator('#lazy')
+ .textContent({ timeout: 1000 })
+ .catch(() => null),
+ body,
+ debugIds: await page.evaluate(
+ () =>
+ Object.keys((globalThis as { _bugseeDebugIds?: object })._bugseeDebugIds ?? {}).length,
+ ),
+ crashed: /Application error|This page couldn.t load|Unhandled Runtime Error/.test(body),
+ };
+ } finally {
+ await context.close();
+ child.kill('SIGKILL');
+ }
+}
+
+/** The assertions every build that was stamped must satisfy once it is OPEN in a browser. */
+function expectRuns(page: Page, options: { stamped: boolean }): void {
+ expect(page.failed, 'a request failed (a stale chunk URL 404s)').toEqual([]);
+ expect(page.errors).toEqual([]);
+ expect(page.crashed, page.body).toBe(false);
+ expect(page.lazy, 'the lazy chunk did not load and run').toBe('lazy-ok');
+ expect(page.body).toContain('v9.8.7');
+ if (options.stamped) {
+ expect(page.debugIds, 'no bundle registered a debug-id').toBeGreaterThan(0);
+ }
+}
+
+const MATRIX: Spec[] = [
+ { name: 'next15-webpack', next: 'next', args: [] },
+ { name: 'next15-turbopack', next: 'next', args: ['--turbopack'] },
+ { name: 'next16-turbopack', next: 'next16', args: [] },
+ { name: 'next16-webpack', next: 'next16', args: ['--webpack'] },
+];
+
+describe.each(MATRIX)('withBugsee — real `next build` ($name)', (spec) => {
+ let built: Built;
+ beforeAll(async () => {
+ built = await build(spec);
+ });
+
+ it('builds, and says nothing was skipped or failed', () => {
+ expect(built.status, built.log.split('\n').slice(-60).join('\n')).toBe(0);
+ // The one expected notice: bundles sharing a map are left alone (asserted below).
+ const notices = built.log.split('\n').filter((l) => l.includes('[bugsee]'));
+ expect(notices.filter((l) => !l.includes('share one source map'))).toEqual([]);
+ });
+
+ it('stamps every client bundle that has a map of its own, and none that share one', () => {
+ const { unique, shared } = split(join(built.dir, '.next', 'static'));
+ expect(unique.length).toBeGreaterThan(2);
+ for (const bundle of unique) {
+ expect(debugIdOf(bundle), bundle).toBeDefined();
+ }
+ for (const bundle of shared) {
+ expect(debugIdOf(bundle), `${bundle} shares a map`).toBeUndefined();
+ }
+ expect(built.log.includes('share one source map')).toBe(shared.length > 0);
+ });
+
+ it('uploaded the maps keyed by exactly those debug-IDs, client and server', () => {
+ expect(built.uploads.length).toBeGreaterThan(0);
+ const sent = built.uploads.join('\n');
+ const ids = split(join(built.dir, '.next'))
+ .unique.map(debugIdOf)
+ .filter((id): id is string => id !== undefined);
+ // Server bundles as well as browser ones carry an id, and every id reached the collector.
+ expect(ids.length).toBeGreaterThan(clientBundles(built.dir).length);
+ for (const id of ids) {
+ expect(sent, `debug-id ${id} was not uploaded`).toContain(id);
+ }
+ });
+
+ it('removes the publicly served client maps and keeps the server maps', () => {
+ // What may remain in `.next/static` is a map no bundle points at (Next ships a polyfill that way) or the map
+ // two unstamped Turbopack runtime chunks share (Next 15.5). Neither is the app's code, neither was uploaded.
+ const staticDir = join(built.dir, '.next', 'static');
+ const { shared, referenced } = split(staticDir);
+ const sharedMaps = new Set(
+ pointing(staticDir)
+ .filter((p) => shared.includes(p.file))
+ .map((p) => p.map),
+ );
+ for (const map of maps(staticDir)) {
+ expect(referenced.has(map) && !sharedMaps.has(map), `${map} is still served`).toBe(false);
+ }
+ const server = split(join(built.dir, '.next', 'server'));
+ const kept = maps(join(built.dir, '.next', 'server')).filter((m) => server.referenced.has(m));
+ expect(kept.length).toBeGreaterThan(0);
+ for (const map of kept) {
+ expect(JSON.parse(readFileSync(map, 'utf8')).debugId, map).toMatch(/^[0-9a-f-]{36}$/);
+ }
+ });
+
+ it('covers the edge route too', () => {
+ const edgeBundles = split(join(built.dir, '.next', 'server')).unique.filter((f) =>
+ /edge/.test(f),
+ );
+ expect(edgeBundles.length).toBeGreaterThan(0);
+ for (const bundle of edgeBundles) {
+ expect(debugIdOf(bundle), bundle).toBeDefined();
+ }
+ });
+
+ it('bakes the app version and build into the bundle', () => {
+ const text = clientBundles(built.dir)
+ .map((f) => readFileSync(f, 'utf8'))
+ .join('\n');
+ expect(text).toContain('9.8.7');
+ });
+
+ it('produces a build that still runs', async () => {
+ expect(await runBuild(built.dir, ['/', '/api/hi', '/edge'])).toEqual([200, 200, 200]);
+ });
+
+ it('runs in a real browser: the lazy chunk loads and executes, debug-ids register, no errors', async () => {
+ expectRuns(await openInBrowser(built.dir), { stamped: true });
+ });
+});
+
+describe('withBugsee — Subresource Integrity', () => {
+ it('webpack: stamps inside the build, so every pinned hash still matches the bytes on disk', async () => {
+ const built = await build({
+ name: 'sri-webpack',
+ next: 'next16',
+ args: ['--webpack'],
+ nextConfig: "experimental: { sri: { algorithm: 'sha256' } },",
+ });
+ expect(built.status, built.log.split('\n').slice(-40).join('\n')).toBe(0);
+ expect(built.log).not.toMatch(/\[bugsee\]/);
+ const html = readFileSync(join(built.dir, '.next', 'server', 'app', 'index.html'), 'utf8');
+ const pins = [
+ ...html.matchAll(
+ /