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( + /]*?(?:src="([^"]+)"[^>]*?integrity="([^"]+)"|integrity="([^"]+)"[^>]*?src="([^"]+)")/g, + ), + ]; + expect(pins.length).toBeGreaterThan(0); + for (const m of pins) { + const src = (m[1] ?? m[4]) as string; + const integrity = (m[2] ?? m[3]) as string; + const file = join(built.dir, '.next', src.replace(/^\/_next\//, '')); + const [algo] = integrity.split('-'); + const digest = createHash(algo as string) + .update(readFileSync(file)) + .digest('base64'); + expect(integrity, src).toBe(`${algo}-${digest}`); + expect(debugIdOf(file), `${src} was not stamped`).toBeDefined(); + } + expect(built.uploads.length).toBeGreaterThan(0); + // The browser enforces the hashes: the stamped, SRI-pinned page must still run, lazy chunk included. + expectRuns(await openInBrowser(built.dir), { stamped: true }); + }); + + it('turbopack: leaves an SRI build exactly as Next wrote it, and says why', async () => { + const built = await build({ + name: 'sri-turbopack', + next: 'next16', + args: [], + nextConfig: "experimental: { sri: { algorithm: 'sha256' } },", + options: 'failOnError: false,', + }); + expect(built.status, built.log.split('\n').slice(-40).join('\n')).toBe(0); + expect(built.log).toMatch(/Subresource Integrity/); + expect(built.uploads).toEqual([]); + // Unstamped, so the page's hashes still match. + for (const bundle of clientBundles(built.dir)) { + expect(debugIdOf(bundle), bundle).toBeUndefined(); + } + expectRuns(await openInBrowser(built.dir), { stamped: false }); + // Bugsee did not turn browser maps on for a build it cannot upload for: none are written, none are public. + expect(maps(join(built.dir, '.next', 'static'))).toEqual([]); + }); + + it('webpack: a failed in-build stamp does NOT fall back to stamping the written files of an SRI build', async () => { + const built = await build({ + name: 'sri-webpack-fallback', + next: 'next16', + args: ['--webpack'], + options: 'failOnError: false,', + nextConfig: "experimental: { sri: { algorithm: 'sha256' } },", + failInBuildStamp: true, + }); + expect(built.status, built.log.split('\n').slice(-40).join('\n')).toBe(0); + // ONE accurate message: the stamp failed and the fallback was refused. Never "falling back". + expect(built.log).not.toMatch(/falling back to stamping after emit/); + expect(built.log.split('\n').filter((l) => l.includes('Subresource Integrity'))).toHaveLength( + 3, + ); // client, server, edge: one notice each + expect(built.log).toMatch(/nothing was stamped or uploaded/); + expect(built.uploads).toEqual([]); + // Nothing was rewritten, so the pinned hashes still describe the bytes on disk and the page runs. + for (const bundle of walk(join(built.dir, '.next', 'static')).filter((f) => + f.endsWith('.js'), + )) { + expect(debugIdOf(bundle), bundle).toBeUndefined(); + } + expectRuns(await openInBrowser(built.dir), { stamped: false }); + // Bugsee had turned the browser maps on (the app did not ask); with no upload they must not stay public. + expect(maps(join(built.dir, '.next', 'static'))).toEqual([]); + expect(built.log).toMatch(/browser source maps Bugsee had turned on were removed/); + }); + + const sriFailing = (name: string, options: string) => + build({ + name, + next: 'next16', + args: ['--webpack'], + options, + nextConfig: "experimental: { sri: { algorithm: 'sha256' } },", + failInBuildStamp: true, + }); + + it('webpack + SRI + failOnError: a failed stamp fails the build, and no maps are left behind', async () => { + const built = await sriFailing('sri-webpack-strict', 'failOnError: true,'); + expect(built.status).not.toBe(0); + expect(built.log).toMatch(/inject/); + expect(maps(join(built.dir, '.next', 'static'))).toEqual([]); + }); + + it('webpack + SRI + silent: the notices are muted, the cause is still audible', async () => { + const built = await sriFailing('sri-webpack-silent', 'failOnError: false, silent: true,'); + expect(built.status, built.log.split('\n').slice(-30).join('\n')).toBe(0); + expect(built.log).not.toMatch(/Subresource Integrity/); + expect(built.log).toMatch(/in-build debug-ID stamping did not apply/); + expect(maps(join(built.dir, '.next', 'static'))).toEqual([]); + }); + + it('webpack + SRI + dryRun: browser maps are not forced on, so none are written or left public', async () => { + const built = await sriFailing('sri-webpack-dry', 'failOnError: false, dryRun: true,'); + expect(built.status, built.log.split('\n').slice(-30).join('\n')).toBe(0); + expect(built.uploads).toEqual([]); + expect(maps(join(built.dir, '.next', 'static'))).toEqual([]); + expect(built.log).not.toMatch(/Dry run: nothing was deleted/); + }); + + it('turbopack + SRI + maps the APP asked for: they stay, the notice says they are public, said once', async () => { + const built = await build({ + name: 'sri-turbopack-own-maps', + next: 'next16', + args: [], + nextConfig: + "experimental: { sri: { algorithm: 'sha256' } }, productionBrowserSourceMaps: true,", + options: 'failOnError: false,', + }); + expect(built.status, built.log.split('\n').slice(-40).join('\n')).toBe(0); + expect(built.uploads).toEqual([]); + expect(maps(join(built.dir, '.next', 'static')).length).toBeGreaterThan(0); + const said = built.log.split('\n').filter((l) => l.includes('Subresource Integrity')); + expect(said).toHaveLength(1); + expect(said[0]).toMatch(/publicly served/); + expectRuns(await openInBrowser(built.dir), { stamped: false }); + }); +}); + +describe.each([ + { name: 'foreign-webpack', next: 'next16', args: ['--webpack'] }, + { name: 'foreign-turbopack', next: 'next16', args: [] }, +] as Spec[])('withBugsee — files this build did not produce ($name)', (spec) => { + let built: Built; + beforeAll(async () => { + built = await build({ ...spec, seedForeign: true }); + }); + + it('builds', () => { + expect(built.status, built.log.split('\n').slice(-40).join('\n')).toBe(0); + }); + + it('never deletes a stylesheet or declaration map it did not produce', () => { + for (const [dir, name] of FOREIGN) { + const file = join(built.dir, '.next', dir, name); + expect(existsSync(file), `${dir}/${name} was deleted`).toBe(true); + expect(readFileSync(file, 'utf8')).toBe(FOREIGN_BODY); + } + }); + + it('still uploaded and deleted its own maps', () => { + expect(built.uploads.length).toBeGreaterThan(0); + const { unique } = split(join(built.dir, '.next', 'static')); + expect(unique.length).toBeGreaterThan(2); + for (const bundle of unique) { + expect(debugIdOf(bundle), bundle).toBeDefined(); + } + const own = maps(join(built.dir, '.next', 'static')).filter( + (m) => !m.includes('foreign.') && split(join(built.dir, '.next', 'static')).referenced.has(m), + ); + expect(own).toEqual([]); + }); +}); diff --git a/packages/nextjs/README.md b/packages/nextjs/README.md index 0d6bd2f00..485293c3a 100644 --- a/packages/nextjs/README.md +++ b/packages/nextjs/README.md @@ -63,6 +63,58 @@ export const middleware = withBugseeMiddleware((request, event) => { }); ``` +## Source maps (build integration) + +`withBugsee` makes `next build` upload source maps to Bugsee, so a minified browser, server or edge stack trace is shown against your original source. It handles both bundlers: webpack (`next build --webpack`, the default up to Next 15) and Turbopack (the default in Next 16). + +```js +// next.config.mjs +import { withBugsee } from "@bugsee/nextjs/config"; + +export default withBugsee( + { + // your Next config: an object, a (phase) function, or an async one + }, + { + // BUGSEE_APP_TOKEN in the environment (or .env.bugsee-build-plugin) works too + appToken: process.env.BUGSEE_APP_TOKEN, + }, +); +``` + +CommonJS works as well: `const { withBugsee } = require("@bugsee/nextjs/config");` in `next.config.js`. + +What it does, for a production build: + +- Turns on `productionBrowserSourceMaps` (only when you did not set it, and only when this build can actually upload: not for Turbopack with `experimental.sri`, not for Turbopack on Next older than 15.4.0, not on a `dryRun`) so the browser bundles have maps to upload. Where it cannot upload it leaves the option as you set it and says so. +- **webpack**: adds one Bugsee plugin to each of the client, server and edge compilations. Each stamps a debug ID into its bundles inside the build (before Subresource Integrity hashes are taken) and, after emit, uploads the maps of exactly the files that compilation wrote. +- **Turbopack**: has no plugin API, so the upload runs from Next's `compiler.runAfterProductionCompile` hook (Next 15.4.0 or later): after Turbopack wrote `.next` and before Next generates the static pages, it stamps the written bundles with the real `bugsee-cli sourcemaps inject` (verified, and undone if a stamp does not verify), uploads the maps and removes them. +- Deletes the browser maps (`.next/static/**/*.map`, which `next start` and CDNs serve publicly) after a confirmed upload. Server and edge maps stay on disk (`deleteServerMaps` to remove them). +- Bakes `appVersion` / `appBuild` into every bundle (`compiler.define`) for the runtime SDK. + +Your own config is kept: your `webpack` function runs first and its result is extended (Next itself needs a synchronous `webpack` function; an async one fails in Next 16), your `compiler.runAfterProductionCompile` runs before ours, `compiler.define` keys you set win, and `productionBrowserSourceMaps: false` is respected. `next dev`, `next start` and `next export` are not touched. + +Options are those of the Bugsee bundler plugins (`appToken`, `appVersion`, `appBuild`, `endpoint`, `deleteMaps`, `dryRun`, `failOnError`, `stripSourcesContent`, `disabled`, `vcs`, `commit`, `registerBuild`, `onError`, `onNotice`, see `@bugsee/webpack-plugin`), plus: + +| Option | Default | | +| --- | --- | --- | +| `serverSourceMaps` | `true` | Emit and upload server and edge maps. With webpack the server and edge compilations get `devtool: "source-map"` if you left it unset; Next's own `experimental.serverSourceMaps` is never changed. | +| `deleteServerMaps` | `false` | Delete server and edge maps after a confirmed upload. | +| `silent` | `false` | Suppress configuration notices (failures are still reported). | + +Without a token the integration changes nothing about what Next emits (it adds no source maps, no define, no hook) and uploads nothing. + +Things to know: + +- The config is resolved once, at load, from the working directory: the token file, the app version and the installed Next version are looked up there. Run `next build` from the project directory. For a Turbopack build the hook is told which project Next is building, and prints a notice if that differs (for example `next build apps/web` from a monorepo root). +- `withBugsee` turns `productionBrowserSourceMaps` on, so the browser maps are written to `.next/static`, which is served publicly. They are deleted after a confirmed upload. If the upload fails (and `failOnError` is off) they stay there, publicly served, so you can retry. If that is not acceptable, set `failOnError: true` so a failed upload stops the build, or delete `.next/static/**/*.map` in your deploy step. +- Next 15's Turbopack builds point two runtime chunks at one shared map. Those chunks are left unstamped and that map is neither uploaded nor deleted: it stays in `.next/static`, public. It contains Turbopack's runtime source, not your code. +- If your own `compiler.define` sets `__BUGSEE_APP_VERSION__` or `__BUGSEE_APP_BUILD__` to a string, that is the value the runtime SDK reports, and the upload and the build registration are labelled with it too. A non-string value is ignored (the resolved version is used). +- `compiler.define` (the baked version and build) needs Next 15.1.0 or later; the Turbopack upload needs 15.4.0 or later. +- `@bugsee/nextjs` depends on `@bugsee/bundler-plugin-core` (which brings `@bugsee/cli`, acorn, magic-string and unplugin) so that `withBugsee` works with no extra install. Only `next.config` loads it; your app bundles never import it. Making it an optional peer would force every user of the config to install it by hand and break `next build` out of the box, so it stays a regular dependency. + +Turbopack and Subresource Integrity: Turbopack hashes its output (`experimental.sri`) before the post-build hook runs, so stamping afterwards would make the browser refuse your scripts. An SRI build under Turbopack is therefore left exactly as Next wrote it, with a notice, and no maps are uploaded; build with `--webpack` to upload maps for an SRI build (webpack stamps before the hashes are taken). On webpack with `experimental.sri`, if the in-build stamp itself fails, the fallback of stamping the written files is skipped (it would invalidate the pinned hashes) and nothing is uploaded for that compilation, with a notice. The browser maps Bugsee itself turned on are then deleted again; maps you enabled yourself (`productionBrowserSourceMaps: true`) stay in `.next/static`, publicly served, and the notice says so. "Maps you enabled yourself" means `productionBrowserSourceMaps` was set when `withBugsee` ran: if a wrapper applied after `withBugsee` turns it on, Bugsee still counts the maps as its own and removes them in this failure case. A `//# sourceMappingURL` comment may then point at a map that no longer exists (harmless: only devtools ask for it). On a dry run nothing is deleted. + ## Options Both `register(appToken, options)` and `registerClient(appToken, options)` accept the SDK launch options. The most relevant ones: @@ -76,6 +128,7 @@ Both `register(appToken, options)` and `registerClient(appToken, options)` accep - `@bugsee/nextjs`: `register`, `onRequestError`, `createOnRequestError`, `getBugseeTraceData`. - `@bugsee/nextjs/client`: `registerClient`, `onRouterTransitionStart`, plus the React adapter. - `@bugsee/nextjs/middleware`: `withBugseeMiddleware`. +- `@bugsee/nextjs/config`: `withBugsee` (build-time; import it from `next.config`, never from app code). - `@bugsee/nextjs/server` and `@bugsee/nextjs/edge`: the Node.js and Edge compositions that `register()` loads for you. ## Links diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 18f984e32..3d4bbc6c1 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -7,7 +7,7 @@ "url": "git+https://github.com/bugsee/bugsee-javascript.git", "directory": "packages/nextjs" }, - "description": "Next.js meta-adapter: client + server + edge entries", + "description": "Next.js meta-adapter: client + server + edge entries, plus the withBugsee() build integration (source-map upload)", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", @@ -31,6 +31,10 @@ "./middleware": { "types": "./src/middleware.ts", "import": "./src/middleware.ts" + }, + "./config": { + "types": "./src/config/index.ts", + "import": "./src/config/index.ts" } }, "files": [ @@ -49,7 +53,8 @@ "@bugsee/protocol": "workspace:*", "@bugsee/react": "workspace:*", "@bugsee/vercel-edge": "workspace:*", - "@bugsee/bugsee": "workspace:*" + "@bugsee/bugsee": "workspace:*", + "@bugsee/bundler-plugin-core": "workspace:*" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0", @@ -133,6 +138,16 @@ "types": "./dist/middleware.d.cts", "default": "./dist/middleware.cjs" } + }, + "./config": { + "import": { + "types": "./dist/config.d.ts", + "default": "./dist/config.js" + }, + "require": { + "types": "./dist/config.d.cts", + "default": "./dist/config.cjs" + } } }, "access": "public" diff --git a/packages/nextjs/src/config/build-files.test.ts b/packages/nextjs/src/config/build-files.test.ts new file mode 100644 index 000000000..1fea9fb40 --- /dev/null +++ b/packages/nextjs/src/config/build-files.test.ts @@ -0,0 +1,263 @@ +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { collectBuildFiles, mapPointerOf, pairByPointer, partitionBuildFiles } from './build-files'; + +describe('partitionBuildFiles', () => { + it('pairs each bundle with its map and sorts both', () => { + const files = ['/o/b.js.map', '/o/a.js', '/o/b.js', '/o/a.js.map']; + expect(partitionBuildFiles(files)).toEqual({ + scripts: ['/o/a.js', '/o/b.js'], + maps: ['/o/a.js.map', '/o/b.js.map'], + stylesheetMaps: [], + }); + }); + + it('accepts an upper-case extension, as the core does', () => { + expect(partitionBuildFiles(['/o/A.JS', '/o/A.JS.map']).scripts).toEqual(['/o/A.JS']); + }); + + it('accepts .mjs and .cjs bundles', () => { + const files = ['/o/a.mjs', '/o/a.mjs.map', '/o/b.cjs', '/o/b.cjs.map']; + expect(partitionBuildFiles(files).scripts).toEqual(['/o/a.mjs', '/o/b.cjs']); + }); + + it('never stamps a bundle that has no map, and never sends a map that has no bundle', () => { + const files = ['/o/lonely.js', '/o/orphan.js.map', '/o/ok.js', '/o/ok.js.map']; + const parts = partitionBuildFiles(files); + expect(parts.scripts).toEqual(['/o/ok.js']); + expect(parts.maps).toEqual(['/o/ok.js.map']); + }); + + it('keeps stylesheet maps apart: deleted with the rest, never sent', () => { + const files = ['/o/a.css', '/o/a.css.map', '/o/a.js', '/o/a.js.map']; + const parts = partitionBuildFiles(files); + expect(parts.stylesheetMaps).toEqual(['/o/a.css.map']); + expect(parts.maps).toEqual(['/o/a.js.map']); + }); + + it('ignores everything else', () => { + expect(partitionBuildFiles(['/o/a.html', '/o/a.json', '/o/a.png'])).toEqual({ + scripts: [], + maps: [], + stylesheetMaps: [], + }); + }); +}); + +describe('mapPointerOf', () => { + it('resolves the pointer against the bundle directory', () => { + expect(mapPointerOf('/o/chunks/a.js', 'code();\n//# sourceMappingURL=other.js.map\n')).toBe( + '/o/chunks/other.js.map', + ); + expect(mapPointerOf('/o/chunks/a.js', 'x\n//@ sourceMappingURL=../m/a.map')).toBe('/o/m/a.map'); + }); + + it('decodes a percent-encoded pointer (Turbopack names contain brackets)', () => { + expect(mapPointerOf('/o/a.js', 'x\n//# sourceMappingURL=%5Broot%5D__a._.js.map\n')).toBe( + '/o/[root]__a._.js.map', + ); + }); + + it('uses a pointer as written when it is not valid percent-encoding', () => { + expect(mapPointerOf('/o/a.js', 'x\n//# sourceMappingURL=100%.js.map')).toBe('/o/100%.js.map'); + }); + + it('reads a stylesheet pointer from its /*# */ comment, not the // form', () => { + expect(mapPointerOf('/o/a.css', 'a{}\n/*# sourceMappingURL=a.css.map */')).toBe('/o/a.css.map'); + expect(mapPointerOf('/o/a.css', 'a{}\n//# sourceMappingURL=a.css.map')).toBeUndefined(); + expect(mapPointerOf('/o/a.js', 'x\n/*# sourceMappingURL=a.js.map */')).toBeUndefined(); + }); + + it('reads the legacy /*@ */ stylesheet form too', () => { + expect(mapPointerOf('/o/a.css', 'a{}\n/*@ sourceMappingURL=x.css.map*/')).toBe('/o/x.css.map'); + }); + + it('has no pointer for a bundle without a comment, or with an inline map', () => { + expect(mapPointerOf('/o/a.js', 'no comment')).toBeUndefined(); + expect( + mapPointerOf('/o/a.js', 'x\n//# sourceMappingURL=data:application/json;base64,e30='), + ).toBeUndefined(); + }); + + it('only counts the comment that ends the bundle', () => { + expect(mapPointerOf('/o/a.js', '//# sourceMappingURL=a.map\nmore();')).toBeUndefined(); + }); +}); + +describe('pairByPointer', () => { + const code = (map: string): string => `code();\n//# sourceMappingURL=${map}\n`; + const reader = (sources: Record) => async (file: string) => sources[file] ?? ''; + + it('pairs a bundle with a map that is NOT named after it', async () => { + const files = ['/o/0ihtw.js', '/o/1wkfrb.js.map']; + const parts = await pairByPointer(files, reader({ '/o/0ihtw.js': code('1wkfrb.js.map') })); + expect(parts).toEqual({ + scripts: ['/o/0ihtw.js'], + maps: ['/o/1wkfrb.js.map'], + stylesheetMaps: [], + shared: [], + }); + }); + + it('ignores a pointer to a file that is not there', async () => { + const parts = await pairByPointer(['/o/a.js'], reader({ '/o/a.js': code('gone.js.map') })); + expect(parts.scripts).toEqual([]); + }); + + it('ignores a pointer to something that is not a map', async () => { + const parts = await pairByPointer(['/o/a.js', '/o/b.js'], reader({ '/o/a.js': code('b.js') })); + expect(parts.scripts).toEqual([]); + expect(parts.maps).toEqual([]); + }); + + it('pairs neither bundle of a map two bundles share, and reports them', async () => { + const parts = await pairByPointer( + ['/o/a.js', '/o/b.js', '/o/shared.js.map', '/o/c.js', '/o/c.js.map'], + reader({ + '/o/a.js': code('shared.js.map'), + '/o/b.js': code('shared.js.map'), + '/o/c.js': code('c.js.map'), + }), + ); + expect(parts.scripts).toEqual(['/o/c.js']); + expect(parts.maps).toEqual(['/o/c.js.map']); + expect(parts.shared).toEqual(['/o/a.js', '/o/b.js']); + }); + + it('does not read files that are not scripts', async () => { + const read = vi.fn(async () => ''); + await pairByPointer(['/o/a.json', '/o/a.js.map', '/o/a.txt'], read); + expect(read).not.toHaveBeenCalled(); + }); + + it("keeps this build's stylesheet maps apart (a stylesheet points at them): deleted, never sent", async () => { + const css = (map: string): string => `a{}\n/*# sourceMappingURL=${map} */\n`; + const parts = await pairByPointer( + ['/o/a.css', '/o/x1.map'], + reader({ '/o/a.css': css('x1.map') }), + ); + expect(parts.stylesheetMaps).toEqual(['/o/x1.map']); + expect(parts.maps).toEqual([]); + }); + + it("leaves a stylesheet or declaration map nothing points at alone: it is not this build's", async () => { + const parts = await pairByPointer( + ['/o/a.css', '/o/a.css.map', '/o/foreign.css.map', '/o/types.d.ts.map'], + reader({ '/o/a.css': 'a{}\n/*# sourceMappingURL=a.css.map */' }), + ); + expect(parts.stylesheetMaps).toEqual(['/o/a.css.map']); + }); + + it('ignores a stylesheet pointer to a missing or non-map file, or an inline map', async () => { + const parts = await pairByPointer( + ['/o/a.css', '/o/b.css', '/o/c.css', '/o/c.txt'], + reader({ + '/o/a.css': 'a{}/*# sourceMappingURL=gone.css.map */', + '/o/b.css': 'a{}/*# sourceMappingURL=c.txt */', + '/o/c.css': 'a{}/*# sourceMappingURL=data:application/json;base64,e30= */', + }), + ); + expect(parts.stylesheetMaps).toEqual([]); + }); + + it('sorts its output', async () => { + const parts = await pairByPointer( + ['/o/z.js', '/o/a.js', '/o/m1.map', '/o/m0.map'], + reader({ '/o/z.js': code('m1.map'), '/o/a.js': code('m0.map') }), + ); + expect(parts.scripts).toEqual(['/o/a.js', '/o/z.js']); + expect(parts.maps).toEqual(['/o/m0.map', '/o/m1.map']); + }); +}); + +describe('collectBuildFiles', () => { + let root: string; + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'bugsee-bf-')); + }); + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + const put = (rel: string, content = 'x'): void => { + mkdirSync(join(root, rel, '..'), { recursive: true }); + writeFileSync(join(root, rel), content); + }; + const bundle = (rel: string, mapName = `${rel.split('/').pop()}.map`): void => { + put(rel, `code();\n//# sourceMappingURL=${encodeURIComponent(mapName)}\n`); + put(`${rel}/../${mapName}`); + }; + + it('walks nested directories, bracketed names included', async () => { + bundle('chunks/[root-of-the-server]__a._.js'); + bundle('chunks/ssr/b.js'); + const parts = await collectBuildFiles(root); + expect(parts.scripts).toEqual([ + join(root, 'chunks/[root-of-the-server]__a._.js'), + join(root, 'chunks/ssr/b.js'), + ]); + expect(parts.maps).toHaveLength(2); + }); + + it('pairs by the pointer inside the bundle when the map has another name', async () => { + bundle('chunks/0ihtw.js', '1wkfrb.js.map'); + const parts = await collectBuildFiles(root); + expect(parts.scripts).toEqual([join(root, 'chunks/0ihtw.js')]); + expect(parts.maps).toEqual([join(root, 'chunks/1wkfrb.js.map')]); + }); + + it('never descends into node_modules', async () => { + bundle('node_modules/x/a.js'); + bundle('ok.js'); + expect((await collectBuildFiles(root)).scripts).toEqual([join(root, 'ok.js')]); + }); + + it('does descend into a route directory that happens to be called cache', async () => { + bundle('chunks/app/cache/page.js'); + expect((await collectBuildFiles(root)).scripts).toEqual([ + join(root, 'chunks/app/cache/page.js'), + ]); + }); + + it('returns nothing for a directory that does not exist', async () => { + expect(await collectBuildFiles(join(root, 'absent'))).toEqual({ + scripts: [], + maps: [], + stylesheetMaps: [], + shared: [], + }); + }); + + it('collects deeply nested output: no depth cutoff silently drops a route\u2019s bundle', async () => { + const deep = `${Array.from({ length: 30 }, (_, i) => `d${i}`).join('/')}/page.js`; + bundle(deep); + bundle('top.js'); + const scripts = (await collectBuildFiles(root)).scripts; + expect(scripts).toHaveLength(2); + expect(scripts).toContain(join(root, deep)); + }); + + it('reads only the END of a bundle to find its pointer', async () => { + // A pointer-looking comment at the START of a large file is not the bundle\u2019s pointer; only the tail counts. + put('big.js', `//# sourceMappingURL=big.js.map\n${'x'.repeat(40_000)}\nend();\n`); + put('big.js.map'); + expect((await collectBuildFiles(root)).scripts).toEqual([]); + put('big2.js', `${'x'.repeat(40_000)}\n//# sourceMappingURL=big2.js.map\n`); + put('big2.js.map'); + expect((await collectBuildFiles(root)).scripts).toEqual([join(root, 'big2.js')]); + }); + + it('reports a directory it cannot read instead of calling it empty', async () => { + put('locked/a.js'); + chmodSync(join(root, 'locked'), 0o000); + try { + if (process.getuid?.() === 0) { + return; // root reads it anyway + } + await expect(collectBuildFiles(root)).rejects.toThrow(/EACCES/); + } finally { + chmodSync(join(root, 'locked'), 0o755); + } + }); +}); diff --git a/packages/nextjs/src/config/build-files.ts b/packages/nextjs/src/config/build-files.ts new file mode 100644 index 000000000..b36087b2d --- /dev/null +++ b/packages/nextjs/src/config/build-files.ts @@ -0,0 +1,145 @@ +// Which files of a Next build the upload covers, named explicitly. The upload never walks `.next` and never +// takes a directory: it is handed exactly these paths, so it cannot stamp, upload or delete a file that is not +// part of the build it is looking at (the webpack compilations and the Turbopack output share `.next`). +import { open, readdir } from 'node:fs/promises'; +import { dirname, join, resolve } from 'node:path'; + +/** A build's bundles and the maps that belong to them. */ +export interface BuildFiles { + /** Bundles that have a map. A bundle without one cannot be symbolicated, so it is never stamped. */ + scripts: string[]; + /** The maps of those bundles. */ + maps: string[]; + /** Stylesheet maps: never sent, but deleted with the rest after a confirmed upload (they embed the source). */ + stylesheetMaps: string[]; + /** Bundles left out because their map is shared with another bundle (see {@link pairByPointer}). */ + shared?: string[]; + /** Each script's map, where the caller knows the pairing (webpack: sibling name or recorded relationship). */ + pairs?: Record; +} + +const SCRIPT = /\.[cm]?js$/i; +/** How much of the END of a file is read to find its source-map comment (the comment is a line or two). */ +const TAIL_BYTES = 16 * 1024; +/** Directories that are never build output, wherever they appear (a route may well be called `cache`). */ +const SKIP = new Set(['node_modules']); + +/** The last {@link TAIL_BYTES} of a file as text (the whole file when it is smaller). */ +export async function readTail(file: string): Promise { + const handle = await open(file, 'r'); + try { + const { size } = await handle.stat(); + const length = Math.min(size, TAIL_BYTES); + const buffer = Buffer.alloc(length); + await handle.read(buffer, 0, length, size - length); + return buffer.toString('utf8'); + } finally { + await handle.close(); + } +} + +async function listFiles(dir: string): Promise { + let entries: import('node:fs').Dirent[]; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch (error) { + // A directory the build did not produce (no `server` output, say) contributes nothing; any other failure + // (EACCES, EIO) is NOT "nothing to upload" and is left to the caller's failure policy. + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return []; + } + throw error; + } + const found: string[] = []; + for (const entry of entries) { + const full = join(dir, entry.name); + if (entry.isDirectory()) { + if (!SKIP.has(entry.name)) { + found.push(...(await listFiles(full))); + } + } else if (entry.isFile()) { + found.push(full); + } + } + return found; +} + +/** Split a list of files into the bundles that have a map, their maps, and the stylesheet maps. */ +export function partitionBuildFiles(files: readonly string[]): BuildFiles { + const present = new Set(files); + const scripts = files.filter((file) => SCRIPT.test(file) && present.has(`${file}.map`)); + const owned = new Set(scripts); + return { + scripts: scripts.sort(), + maps: files.filter((file) => file.endsWith('.map') && owned.has(file.slice(0, -4))).sort(), + stylesheetMaps: files.filter((file) => file.endsWith('.css.map')).sort(), + }; +} + +/** A bundle's source-map pointer: the last `//# sourceMappingURL=` comment (a `/*# ... *\/` comment in a stylesheet). */ +const POINTER = /\/\/[#@] sourceMappingURL=([^\s'"]+)\s*$/; +const CSS_POINTER = /\/\*[#@] sourceMappingURL=([^\s'"*]+)\s*\*\/\s*$/; + +/** The path a bundle's source-map comment names, or `undefined` when it has none or the map is inline. */ +export function mapPointerOf(file: string, code: string): string | undefined { + const reference = (file.endsWith('.css') ? CSS_POINTER : POINTER).exec(code)?.[1]; + if (reference === undefined || reference.startsWith('data:')) { + return undefined; + } + let decoded = reference; + try { + decoded = decodeURIComponent(reference); + } catch { + // Not percent-encoded after all: use it as written. + } + return resolve(dirname(file), decoded); +} + +/** + * Pair bundles with their maps by the pointer inside each bundle, not by name. Turbopack does not name a map after + * its bundle (measured, Next 16.4: `chunks/0ihtwxitjxx9w.js` ends in `sourceMappingURL=1wkfrb_3m2k-z.js.map`), so + * `.map` finds nothing there. Only a pointer that names a `.map` file that exists counts. + */ +export async function pairByPointer( + files: readonly string[], + read: (file: string) => Promise = readTail, +): Promise { + const present = new Set(files); + const pointers = new Map(); + const users = new Map(); + for (const file of files.filter((f) => SCRIPT.test(f))) { + const map = mapPointerOf(file, await read(file)); + if (map?.endsWith('.map') && present.has(map)) { + pointers.set(file, map); + users.set(map, (users.get(map) ?? 0) + 1); + } + } + // Stylesheet maps are never uploaded but embed the source, so they are deleted with the rest, and only THIS + // build's: a stylesheet map is this build's when one of its stylesheets points at it. A `.css.map` (or a + // `.d.ts.map`) that nothing here points at was put there by something else, and is left alone. + const styles = new Set(); + for (const file of files.filter((f) => f.endsWith('.css'))) { + const map = mapPointerOf(file, await read(file)); + if (map?.endsWith('.map') && present.has(map)) { + styles.add(map); + } + } + // A map belongs to one bundle: a debug-ID is the hash of the bundle AND its map, and a map carries one. Two + // bundles pointing at the same map (Next 15.5's Turbopack does this for its runtime chunks, measured) cannot both + // be keyed to it, so neither is paired: stamping one would leave the other with an id no map answers to. + const paired = [...pointers].filter(([, map]) => users.get(map) === 1); + return { + scripts: paired.map(([file]) => file).sort(), + maps: paired.map(([, map]) => map).sort(), + stylesheetMaps: [...styles].sort(), + shared: [...pointers] + .filter(([, map]) => (users.get(map) as number) > 1) + .map(([file]) => file) + .sort(), + }; +} + +/** The build files under `dir` (recursively), paired by pointer; none when `dir` does not exist. */ +export async function collectBuildFiles(dir: string): Promise { + return pairByPointer(await listFiles(dir)); +} diff --git a/packages/nextjs/src/config/context.test.ts b/packages/nextjs/src/config/context.test.ts new file mode 100644 index 000000000..0c12eb8b6 --- /dev/null +++ b/packages/nextjs/src/config/context.test.ts @@ -0,0 +1,133 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createBugseeContext } from './context'; + +let dir: string; +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'bugsee-ctx-')); + writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'app', version: '4.5.6' })); +}); +afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + delete (globalThis as { __BUGSEE_REAL_ENV_FILE__?: boolean }).__BUGSEE_REAL_ENV_FILE__; +}); + +describe('createBugseeContext', () => { + it('takes the token from the option, then the environment', () => { + expect(createBugseeContext({ appToken: 'opt' }, dir, { env: {} }).resolved.appToken).toBe( + 'opt', + ); + expect( + createBugseeContext({}, dir, { env: { BUGSEE_APP_TOKEN: 'from-env' } }).resolved, + ).toMatchObject({ appToken: 'from-env', enabled: true }); + }); + + it('is disabled without a token, and with disabled: true', () => { + expect(createBugseeContext({}, dir, { env: {} }).resolved.enabled).toBe(false); + expect( + createBugseeContext({ appToken: 't', disabled: true }, dir, { env: {} }).resolved.enabled, + ).toBe(false); + }); + + it('reads the token from .env.bugsee-build-plugin in the project directory', () => { + // The shared test setup hides this file from every test; opt in, as the core's env-file tests do. + (globalThis as { __BUGSEE_REAL_ENV_FILE__?: boolean }).__BUGSEE_REAL_ENV_FILE__ = true; + writeFileSync(join(dir, '.env.bugsee-build-plugin'), 'BUGSEE_APP_TOKEN=from-file\n'); + expect(createBugseeContext({}, dir, { env: {} }).resolved).toMatchObject({ + appToken: 'from-file', + enabled: true, + }); + }); + + it('does not read the env file at all when disabled', () => { + (globalThis as { __BUGSEE_REAL_ENV_FILE__?: boolean }).__BUGSEE_REAL_ENV_FILE__ = true; + writeFileSync(join(dir, '.env.bugsee-build-plugin'), 'BUGSEE_APP_TOKEN=from-file\n'); + expect(createBugseeContext({ disabled: true }, dir, { env: {} }).resolved.appToken).toBe(''); + }); + + it('says once when the env file was found but gave nothing', () => { + (globalThis as { __BUGSEE_REAL_ENV_FILE__?: boolean }).__BUGSEE_REAL_ENV_FILE__ = true; + writeFileSync(join(dir, '.env.bugsee-build-plugin'), Buffer.from([0xff, 0xfe, 0x41, 0x00])); + const notices: string[] = []; + createBugseeContext({ onNotice: (m) => notices.push(m) }, dir, { env: {} }); + expect(notices).toHaveLength(1); + expect(notices[0]).toMatch(/^\[bugsee\] /); + }); + + it('resolves the identity from the project directory, option first', () => { + expect(createBugseeContext({ appToken: 't' }, dir, { env: {} }).resolved).toMatchObject({ + appVersion: '4.5.6', + identityDefines: expect.objectContaining({ __BUGSEE_APP_VERSION__: '"4.5.6"' }), + }); + expect( + createBugseeContext({ appToken: 't', appVersion: '9.9.9', appBuild: '7' }, dir, { env: {} }) + .resolved, + ).toMatchObject({ appVersion: '9.9.9', appBuild: '7' }); + }); + + it('points the VCS root at the project unless told otherwise', () => { + expect(createBugseeContext({}, dir, { env: {} }).resolved.projectRoot).toBe(dir); + expect( + createBugseeContext({ projectRoot: '/repo' }, dir, { env: {} }).resolved.projectRoot, + ).toBe('/repo'); + }); + + it('defaults the Next policy: server maps on, server maps kept', () => { + const context = createBugseeContext({}, dir, { env: {} }); + expect(context.serverSourceMaps).toBe(true); + expect(context.deleteServerMaps).toBe(false); + const custom = createBugseeContext({ serverSourceMaps: false, deleteServerMaps: true }, dir, { + env: {}, + }); + expect(custom.serverSourceMaps).toBe(false); + expect(custom.deleteServerMaps).toBe(true); + }); + + it('sends notices to onNotice with one [bugsee] prefix, de-duplicated', () => { + const notices: string[] = []; + const context = createBugseeContext({ onNotice: (m) => notices.push(m) }, dir, { env: {} }); + context.say('hello'); + context.say('hello'); + context.resolved.onNotice?.('[bugsee] from core'); + expect(notices).toEqual(['[bugsee] hello', '[bugsee] from core']); + }); + + it('warns on the console by default', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + createBugseeContext({}, dir, { env: {} }).say('careful'); + expect(warn).toHaveBeenCalledWith('[bugsee] careful'); + warn.mockRestore(); + }); + + it('says nothing when silent', () => { + const onNotice = vi.fn(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const context = createBugseeContext({ silent: true, onNotice }, dir, { env: {} }); + context.say('quiet'); + context.resolved.onNotice?.('[bugsee] quiet too'); + expect(onNotice).not.toHaveBeenCalled(); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + }); + + it('survives a throwing notice sink', () => { + const context = createBugseeContext( + { + onNotice: () => { + throw new Error('logger down'); + }, + }, + dir, + { env: {} }, + ); + expect(() => context.say('x')).not.toThrow(); + }); + + it('reads process.env when no environment is injected', () => { + vi.stubEnv('BUGSEE_APP_TOKEN', 'ambient'); + expect(createBugseeContext({}, dir).resolved.appToken).toBe('ambient'); + vi.unstubAllEnvs(); + }); +}); diff --git a/packages/nextjs/src/config/context.ts b/packages/nextjs/src/config/context.ts new file mode 100644 index 000000000..6a976c97e --- /dev/null +++ b/packages/nextjs/src/config/context.ts @@ -0,0 +1,104 @@ +// The one place `withBugsee` turns its options into a resolved build context: the plugin options merged with the +// environment (and `.env.bugsee-build-plugin`), the app identity, and the Next-specific policy. Resolved ONCE, at +// config-evaluation time, from the project directory: the define baked into the bundle and the identity the upload +// is labelled with come from this single resolution, so they cannot disagree. +import { + type BugseePluginOptions, + loadBuildPluginEnv, + mergeBuildPluginEnv, + type ResolvedPluginOptions, + resolveIdentity, + resolvePluginOptions, +} from '@bugsee/bundler-plugin-core'; + +/** Options for {@link withBugsee}: everything the bundler plugins take, plus the Next-specific switches. */ +export interface WithBugseeOptions extends BugseePluginOptions { + /** + * Emit AND upload source maps for the server and edge bundles too. Default `true`. + * + * Next only writes server maps with `experimental.serverSourceMaps`; with this on, the webpack server and + * edge compilations get `devtool: 'source-map'` (set after your own `webpack` function ran, only when you + * left `devtool` unset), and Turbopack always emits them. Turn it off to symbolicate browser crashes only. + * This never sets Next's `experimental.serverSourceMaps`, so the server's runtime behaviour is unchanged. + */ + serverSourceMaps?: boolean; + /** + * Delete the server and edge `.map` files after a confirmed upload. Default `false`. + * + * Unlike `.next/static` (served to every visitor, so `deleteMaps` removes those), `.next/server` is never + * served, and a server running with `--enable-source-maps` reads these files at runtime. + */ + deleteServerMaps?: boolean; + /** + * Say nothing about configuration notices (a skipped upload, source maps switched off, a dry run's + * capture). Failures are still reported through `onError` / the console. Default `false`. + */ + silent?: boolean; +} + +/** What every part of the integration reads. */ +export interface BugseeNextContext { + /** The plugin options after env / env-file / identity resolution. */ + resolved: ResolvedPluginOptions; + /** Whether server/edge maps are emitted and uploaded. */ + serverSourceMaps: boolean; + /** Whether server/edge maps are deleted after a confirmed upload. */ + deleteServerMaps: boolean; + /** The app uses `experimental.sri` (set by `withBugsee` from the Next config it wraps). */ + sri?: boolean; + /** `withBugsee` itself turned `productionBrowserSourceMaps` on (the app did not ask for browser maps). */ + forcedMaps?: boolean; + /** Browser source maps are written for this build (the app asked for them, or Bugsee turned them on). */ + browserMaps?: boolean; + /** A notice said once per distinct text (a no-op when `silent`). */ + say(message: string): void; +} + +/** Seams for tests. */ +export interface ContextDeps { + env?: Record; +} + +/** Resolve the integration's context for `projectDir`. Never throws. */ +export function createBugseeContext( + options: WithBugseeOptions, + projectDir: string, + deps: ContextDeps = {}, +): BugseeNextContext { + const said = new Set(); + // `text` already carries the `[bugsee]` prefix: that is what the core hands an `onNotice` sink. + const emit = (text: string): void => { + if (options.silent === true || said.has(text)) { + return; + } + said.add(text); + try { + (options.onNotice ?? console.warn)(text); + } catch { + // A throwing host logger must not cost the build (the same containment the core's notify applies). + } + }; + const sink = (message: string): void => emit(`[bugsee] ${message}`); + const { values, problem } = + options.disabled === true ? { values: {}, problem: undefined } : loadBuildPluginEnv(projectDir); + if (problem !== undefined) { + sink(problem); + } + const merged = mergeBuildPluginEnv(deps.env ?? process.env, values); + const base = resolvePluginOptions(options, merged); + const identity = resolveIdentity(options, merged, projectDir); + return { + resolved: { + ...base, + ...identity, + // The repository the VCS resolver inspects, unless the caller chose one: the project, not the + // process cwd (which in a monorepo is usually the workspace root). + projectRoot: base.projectRoot ?? projectDir, + // Routed through the integration's own sink so `silent` and de-duplication apply to every notice. + onNotice: emit, + }, + serverSourceMaps: options.serverSourceMaps ?? true, + deleteServerMaps: options.deleteServerMaps ?? false, + say: sink, + }; +} diff --git a/packages/nextjs/src/config/index.ts b/packages/nextjs/src/config/index.ts new file mode 100644 index 000000000..ec949c946 --- /dev/null +++ b/packages/nextjs/src/config/index.ts @@ -0,0 +1,10 @@ +// `@bugsee/nextjs/config` — the build-time half of the Next.js integration (source-map upload). Node-only: import it +// from `next.config.{js,mjs,ts}`, never from application code. +export type { BugseeNextContext, WithBugseeOptions } from './context'; +export type { + NextConfigFunction, + NextConfigInput, + NextConfigObject, + WithBugseeDeps, +} from './with-bugsee'; +export { withBugsee } from './with-bugsee'; diff --git a/packages/nextjs/src/config/post-build.test.ts b/packages/nextjs/src/config/post-build.test.ts new file mode 100644 index 000000000..5313d0557 --- /dev/null +++ b/packages/nextjs/src/config/post-build.test.ts @@ -0,0 +1,232 @@ +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it, vi } from 'vitest'; +import type { BuildFiles } from './build-files'; +import type { BugseeNextContext } from './context'; +import { runPostBuild } from './post-build'; + +const files = (name: string): BuildFiles => ({ + scripts: [`/d/${name}.js`], + maps: [`/d/${name}.js.map`], + stylesheetMaps: [], +}); +const none: BuildFiles = { scripts: [], maps: [], stylesheetMaps: [] }; + +function context( + overrides: Partial = {}, + extra: Partial = {}, +): BugseeNextContext { + return { + resolved: { + enabled: true, + appToken: 't', + deleteMaps: true, + registerBuild: 'release', + ...overrides, + } as BugseeNextContext['resolved'], + serverSourceMaps: true, + deleteServerMaps: false, + say: vi.fn(), + ...extra, + }; +} + +const metadata = { projectDir: '/app', distDir: '/app/.next' }; + +function deps(map: Record, sri = false) { + return { + upload: vi.fn(async () => undefined), + collect: vi.fn(async (dir: string) => map[dir] ?? none), + exists: vi.fn(async () => sri), + }; +} + +describe('runPostBuild', () => { + it('does nothing when disabled', async () => { + const d = deps({}); + await runPostBuild(context({ enabled: false }), metadata, d); + expect(d.collect).not.toHaveBeenCalled(); + expect(d.upload).not.toHaveBeenCalled(); + }); + + it('uploads the browser output, then the server output, each over its own explicit files', async () => { + const client = files('client'); + const server = files('server'); + const d = deps({ '/app/.next/static': client, '/app/.next/server': server }); + await runPostBuild(context(), metadata, d); + expect(d.upload).toHaveBeenCalledTimes(2); + type Call = [ + Record, + string, + { files: BuildFiles; preStamped?: boolean; bundler: unknown }, + ]; + const [first, second] = (d.upload as ReturnType).mock.calls as [Call, Call]; + expect(first[1]).toBe('/app/.next/static'); + expect(first[2].files).toBe(client); + expect(first[0]).toMatchObject({ deleteMaps: true, registerBuild: 'release' }); + expect(second[1]).toBe('/app/.next/server'); + expect(second[2].files).toBe(server); + // Server output: the server deletion policy, and the build is registered once (by the browser run). + expect(second[0]).toMatchObject({ deleteMaps: false, registerBuild: false }); + // Stamped AFTER emit: not pre-stamped. + expect(first[2].preStamped).toBeUndefined(); + expect(first[2].bundler).toEqual({ isProduction: true, configuration: 'production' }); + }); + + it('resolves a relative distDir against the project directory', async () => { + const d = deps({ '/app/.next/static': files('c') }); + await runPostBuild(context(), { projectDir: '/app', distDir: '.next' }, d); + expect(d.collect).toHaveBeenCalledWith('/app/.next/static'); + }); + + it('honours deleteServerMaps', async () => { + const d = deps({ '/app/.next/server': files('s') }); + await runPostBuild(context({}, { deleteServerMaps: true }), metadata, d); + const [resolved] = (d.upload as ReturnType).mock.calls[0] as [ + Record, + ]; + expect(resolved).toMatchObject({ deleteMaps: true }); + }); + + it('skips the server output entirely when server maps are off', async () => { + const d = deps({ '/app/.next/static': files('c'), '/app/.next/server': files('s') }); + await runPostBuild(context({}, { serverSourceMaps: false }), metadata, d); + expect(d.collect).not.toHaveBeenCalledWith('/app/.next/server'); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('says so, and uploads nothing for the browser, when it emitted no maps', async () => { + const ctx = context(); + const d = deps({ '/app/.next/server': files('s') }); + await runPostBuild(ctx, metadata, d); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('productionBrowserSourceMaps')); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('says how many bundles were left unstamped because they share a map', async () => { + const ctx = context(); + const d = deps({ + '/app/.next/static': { ...files('c'), shared: ['/d/x.js'] }, + '/app/.next/server': { ...files('s'), shared: ['/d/y.js', '/d/z.js'] }, + }); + await runPostBuild(ctx, metadata, d); + expect(ctx.say).toHaveBeenCalledWith( + expect.stringContaining('3 bundle(s) share one source map'), + ); + expect(d.upload).toHaveBeenCalledTimes(2); + }); + + it('only says the browser emitted no maps when maps were expected', async () => { + const off = context({}, { browserMaps: false }); + await runPostBuild(off, metadata, deps({ '/app/.next/server': files('s') })); + expect(off.say).not.toHaveBeenCalled(); + const expected = context({}, { browserMaps: true }); + await runPostBuild(expected, metadata, deps({ '/app/.next/server': files('s') })); + expect(expected.say).toHaveBeenCalledWith(expect.stringContaining('emitted no source maps')); + }); + + it('says the shared map itself stays (and is public) when it is in .next/static', async () => { + const ctx = context(); + const d = deps({ '/app/.next/static': { ...files('c'), shared: ['/d/x.js'] } }); + await runPostBuild(ctx, metadata, d); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('neither uploaded nor deleted')); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('publicly served')); + }); + + it('registers the build from the server run when the browser had nothing to upload', async () => { + const d = deps({ '/app/.next/server': files('s') }); + await runPostBuild(context(), metadata, d); + const [resolved] = (d.upload as ReturnType).mock.calls[0] as [ + Record, + ]; + expect(resolved.registerBuild).toBe('release'); + }); + + it('stays quiet about shared maps when there are none', async () => { + const ctx = context(); + await runPostBuild(ctx, metadata, deps({ '/app/.next/static': files('c') })); + expect(ctx.say).not.toHaveBeenCalled(); + }); + + it('leaves an SRI build exactly as Next wrote it, and says why', async () => { + const ctx = context(); + const d = deps({ '/app/.next/static': files('c'), '/app/.next/server': files('s') }, true); + await runPostBuild(ctx, metadata, d); + expect(d.exists).toHaveBeenCalledWith('/app/.next/server/subresource-integrity-manifest.json'); + expect(d.collect).not.toHaveBeenCalled(); + expect(d.upload).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('Subresource Integrity')); + }); + + it('leaves the build alone, without looking at the disk, when the config says SRI', async () => { + const ctx = context({}, { sri: true }); + const d = deps({ '/app/.next/static': files('c') }); + await runPostBuild(ctx, metadata, d); + expect(d.exists).not.toHaveBeenCalled(); + expect(d.upload).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('publicly served')); + }); + + it('uses the real upload, collector and filesystem when none are injected', async () => { + const ctx = context(); + // Nothing exists under this directory: no SRI manifest, no files, so no upload, only the notice. + await expect( + runPostBuild(ctx, { projectDir: '/definitely/not/here', distDir: '.next' }), + ).resolves.toBeUndefined(); + expect(ctx.say).toHaveBeenCalledTimes(1); + }); +}); + +describe('runPostBuild: containment', () => { + const boom = (): never => { + throw new Error('disk on fire'); + }; + + it('a failure in collecting files never fails the build by default, and goes to onError', async () => { + const onError = vi.fn(); + const d = { ...deps({}), collect: vi.fn(async () => boom()) }; + await expect(runPostBuild(context({ onError }), metadata, d)).resolves.toBeUndefined(); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'disk on fire' })); + }); + + it('warns on the console when there is no onError', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const d = { ...deps({}), collect: vi.fn(async () => boom()) }; + await runPostBuild(context(), metadata, d); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('disk on fire')); + warn.mockRestore(); + }); + + it('a failure in the upload is contained the same way', async () => { + const onError = vi.fn(); + const d = { ...deps({ '/app/.next/static': files('c') }), upload: vi.fn(async () => boom()) }; + await expect(runPostBuild(context({ onError }), metadata, d)).resolves.toBeUndefined(); + expect(onError).toHaveBeenCalledTimes(1); + }); + + it('rethrows under failOnError', async () => { + const d = { ...deps({}), collect: vi.fn(async () => boom()) }; + await expect(runPostBuild(context({ failOnError: true }), metadata, d)).rejects.toThrow( + 'disk on fire', + ); + }); + + it('an unreadable bundle on disk does not fail the build', async () => { + const dir = mkdtempSync(join(tmpdir(), 'bugsee-pb-')); + try { + mkdirSync(join(dir, '.next', 'static'), { recursive: true }); + const bundle = join(dir, '.next', 'static', 'a.js'); + writeFileSync(bundle, 'x'); + chmodSync(bundle, 0o000); + const onError = vi.fn(); + await expect( + runPostBuild(context({ onError }), { projectDir: dir, distDir: '.next' }), + ).resolves.toBeUndefined(); + // Root can read it anyway; everyone else must see the failure reported, not thrown. + expect(onError).toHaveBeenCalledTimes(process.getuid?.() === 0 ? 0 : 1); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/nextjs/src/config/post-build.ts b/packages/nextjs/src/config/post-build.ts new file mode 100644 index 000000000..a45023f45 --- /dev/null +++ b/packages/nextjs/src/config/post-build.ts @@ -0,0 +1,108 @@ +// The Turbopack side of `withBugsee`. Turbopack has no plugin API, so the upload runs from Next's own +// `compiler.runAfterProductionCompile` hook: after the bundler finished writing `.next` and before Next generates +// the static pages. Everything the hook needs is on disk by then, so this stamps the debug-IDs into the written +// bundles (the real `bugsee-cli sourcemaps inject`, with the same verify-and-restore the post-emit path has), +// uploads the maps and deletes them per policy. +// +// What it cannot do is stamp a build that pins Subresource Integrity (`experimental.sri`): Turbopack writes the +// hashes BEFORE this hook runs (measured, Next 16.4.6: appending a byte to a chunk in the hook makes every +// `integrity` the page carries wrong), so stamping afterwards would ship a page whose scripts the browser +// refuses to run. That build is left exactly as Next wrote it, and the notice says why. +import { join, resolve } from 'node:path'; +import { type ResolvedPluginOptions, runPluginUpload } from '@bugsee/bundler-plugin-core'; +import { type BuildFiles, collectBuildFiles } from './build-files'; +import type { BugseeNextContext } from './context'; +import { isFile, SRI_MANIFEST, TURBOPACK_SRI_NOTICE } from './sri'; + +/** What Next hands `compiler.runAfterProductionCompile`. */ +export interface PostBuildMetadata { + projectDir: string; + distDir: string; +} + +/** Seams for tests. */ +export interface PostBuildDeps { + upload?: typeof runPluginUpload; + collect?: (dir: string) => Promise; + exists?: (path: string) => Promise; +} + +/** Stamp, upload and delete for a finished Turbopack build. Skips (and says why) when it cannot be done safely. */ +export async function runPostBuild( + context: BugseeNextContext, + metadata: PostBuildMetadata, + deps: PostBuildDeps = {}, +): Promise { + const { resolved } = context; + if (!resolved.enabled) { + return; + } + // Next rethrows whatever this hook throws and fails the build, so a telemetry step must not throw (an unreadable + // bundle, a full disk): it is reported, and only `failOnError` lets it stop the build. + try { + await postBuild(context, metadata, deps); + } catch (error) { + if (resolved.failOnError) { + throw error; + } + ( + resolved.onError ?? + ((e: unknown) => console.warn(`[bugsee] source-map upload skipped: ${String(e)}`)) + )(error); + } +} + +async function postBuild( + context: BugseeNextContext, + metadata: PostBuildMetadata, + deps: PostBuildDeps, +): Promise { + const { resolved } = context; + const upload = deps.upload ?? runPluginUpload; + const collect = deps.collect ?? collectBuildFiles; + const exists = deps.exists ?? isFile; + const distDir = resolve(metadata.projectDir, metadata.distDir); + + if (context.sri === true || (await exists(join(distDir, SRI_MANIFEST)))) { + context.say(TURBOPACK_SRI_NOTICE); + return; + } + + const client = await collect(join(distDir, 'static')); + const server = context.serverSourceMaps ? await collect(join(distDir, 'server')) : undefined; + // Only when maps were EXPECTED: an app that turned them off (or a dry run, which never forces them on) chose that. + if (client.scripts.length === 0 && context.browserMaps !== false) { + context.say( + 'the browser build emitted no source maps, so nothing was uploaded for it. Set `productionBrowserSourceMaps: true` (withBugsee does this unless you set it to false).', + ); + } + + const shared = (client.shared?.length ?? 0) + (server?.shared?.length ?? 0); + if (shared > 0) { + context.say( + `${shared} bundle(s) share one source map with another bundle (Next 15's Turbopack does this for its runtime chunks), so they were left unstamped: a map carries one debug-ID. The shared map itself was neither uploaded nor deleted: if it is in \`.next/static\` it is publicly served (it holds Turbopack's runtime source, not yours).`, + ); + } + + const bundler = { isProduction: true, configuration: 'production' }; + const runFor = async ( + dir: string, + files: BuildFiles, + options: Partial, + ): Promise => { + if (files.scripts.length === 0) { + return; + } + await upload({ ...resolved, ...options }, dir, { bundler, files }); + }; + // Browser first (it registers the build once); the server and edge output follows its own deletion policy. + await runFor(join(distDir, 'static'), client, {}); + if (server !== undefined) { + await runFor(join(distDir, 'server'), server, { + deleteMaps: context.deleteServerMaps, + // The build is registered once. When the browser run had nothing to upload (the app turned browser maps off), + // the server run registers it instead, so the build record is not lost. + ...(client.scripts.length === 0 ? {} : { registerBuild: false }), + }); + } +} diff --git a/packages/nextjs/src/config/sri.test.ts b/packages/nextjs/src/config/sri.test.ts new file mode 100644 index 000000000..1080d92c4 --- /dev/null +++ b/packages/nextjs/src/config/sri.test.ts @@ -0,0 +1,53 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { isFile, SRI_MANIFEST, sriManifestNear } from './sri'; + +describe('sriManifestNear', () => { + const only = (path: string) => async (candidate: string) => candidate === path; + + it('finds the manifest from the client, server and edge output directories', async () => { + expect(await sriManifestNear('/o/.next', only(`/o/.next/${SRI_MANIFEST}`))).toBe(true); + const server = '/o/.next/server/subresource-integrity-manifest.json'; + expect(await sriManifestNear('/o/.next/server/chunks', only(server))).toBe(true); + expect(await sriManifestNear('/o/.next/server', only(server))).toBe(true); + }); + + it('does not mistake a root file of that name for Next\u2019s manifest', async () => { + const root = '/o/.next/subresource-integrity-manifest.json'; + expect(await sriManifestNear('/o/.next/chunks', only(root))).toBe(false); + expect( + await sriManifestNear( + '/o/.next/server/app/x', + only('/o/.next/server/app/subresource-integrity-manifest.json'), + ), + ).toBe(false); + expect(await sriManifestNear('/o/proj', only('/o/subresource-integrity-manifest.json'))).toBe( + false, + ); + }); + + it('a manifest-named file in a plain directory is not Next\u2019s', async () => { + expect( + await sriManifestNear('/o/proj', only('/o/proj/subresource-integrity-manifest.json')), + ).toBe(false); + }); + + it('finds nothing when there is none', async () => { + expect(await sriManifestNear('/o/.next', async () => false)).toBe(false); + }); + + it('looks on the real disk by default', async () => { + const dir = mkdtempSync(join(tmpdir(), 'bugsee-sri-')); + try { + expect(await sriManifestNear(dir)).toBe(false); + mkdirSync(join(dir, 'server')); + writeFileSync(join(dir, SRI_MANIFEST), '{}'); + expect(await sriManifestNear(dir)).toBe(true); + expect(await isFile(join(dir, 'server'))).toBe(false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/nextjs/src/config/sri.ts b/packages/nextjs/src/config/sri.ts new file mode 100644 index 000000000..c944cc103 --- /dev/null +++ b/packages/nextjs/src/config/sri.ts @@ -0,0 +1,74 @@ +// Subresource Integrity (`experimental.sri`) and what stamping may do about it, in one place. +// +// Turbopack hashes its output BEFORE the post-build hook runs, so stamping afterwards breaks the page (measured: +// every `integrity` wrong). webpack stamps inside the compilation, before anything hashes, so a stamp that took is +// safe; but a stamp that FAILED and falls back to stamping after emit is not (measured on Next 16.4.6 --webpack: +// the fallback rewrote real bundles and Chromium blocked every script, "Failed to find a valid digest"). The core's +// own SRI scan only sees HTML under the output directory, and Next keeps the integrity manifest elsewhere. +import { stat } from 'node:fs/promises'; +import { basename, dirname, join } from 'node:path'; + +/** Where Next records the integrity hashes it pinned, relative to the dist directory. */ +export const SRI_MANIFEST = join('server', 'subresource-integrity-manifest.json'); + +/** Whether a path is an existing file. */ +export async function isFile(path: string): Promise { + try { + return (await stat(path)).isFile(); + } catch { + return false; + } +} + +/** Whether an integrity manifest sits next to a webpack compilation's output (client `.next`, server `.next/server/chunks`, edge `.next/server`). */ +export async function sriManifestNear( + outDir: string, + exists: (path: string) => Promise = isFile, +): Promise { + const name = 'subresource-integrity-manifest.json'; + // The manifest lives in `/server`. A file of that name anywhere else is not Next's. + const candidates = [join(outDir, SRI_MANIFEST)]; + if (basename(outDir) === 'server') { + candidates.push(join(outDir, name)); + } + if (basename(dirname(outDir)) === 'server') { + candidates.push(join(dirname(outDir), name)); + } + for (const candidate of candidates) { + if (await exists(candidate)) { + return true; + } + } + return false; +} + +const PUBLIC_MAPS = + 'Browser source maps, if Next emits any (`productionBrowserSourceMaps`), stay in `.next/static` and are publicly served.'; + +/** Turbopack + SRI: not stampable, so nothing is uploaded. */ +export const TURBOPACK_SRI_NOTICE = `this build uses Subresource Integrity (\`experimental.sri\`). Turbopack hashes its output before the post-build hook runs, so stamping debug-IDs now would make the browser refuse the scripts. Source maps were NOT uploaded and the build was left unmodified. Build with \`next build --webpack\` to upload source maps for an SRI build. ${PUBLIC_MAPS}`; + +/** + * A webpack in-build stamp failed on an SRI build: the post-emit fallback would break the page, so nothing is + * stamped or uploaded. `mapsRemoved`: the browser maps Bugsee itself had turned on were deleted again, so they are + * not left public; otherwise (the app asked for them) they stay, and the notice says so. + */ +export const FALLBACK_SRI_NOTICE = ( + kind: string, + mapsRemoved: boolean, + options: { dryRun?: boolean; removalFailed?: boolean } = {}, +): string => + `the ${kind} build uses Subresource Integrity (\`experimental.sri\`) and its in-build debug-ID stamp did not apply (the reason is reported separately), so nothing was stamped or uploaded: stamping after emit would invalidate the pinned hashes and make the browser refuse the scripts.` + + (kind !== 'client' + ? '' + : mapsRemoved + ? ' The browser source maps Bugsee had turned on were removed from `.next/static`.' + : options.dryRun === true + ? ` Dry run: nothing was deleted. ${PUBLIC_MAPS}` + : options.removalFailed === true + ? ` The browser maps Bugsee turned on could not all be removed. ${PUBLIC_MAPS}` + : ` ${PUBLIC_MAPS}`); + +/** Turbopack on a Next without the post-build hook. */ +export const NO_HOOK_NOTICE = (version: string): string => + `Next ${version} builds with Turbopack but has no post-build hook to upload from; source maps were NOT uploaded. Upgrade to Next 15.4.0 or later, or build with webpack. Bugsee did not turn browser source maps on for this build.`; diff --git a/packages/nextjs/src/config/webpack-plugin.test.ts b/packages/nextjs/src/config/webpack-plugin.test.ts new file mode 100644 index 000000000..47e4e5a63 --- /dev/null +++ b/packages/nextjs/src/config/webpack-plugin.test.ts @@ -0,0 +1,1165 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { BugseeNextContext } from './context'; +import { + type CompilerLike, + createNextWebpackPlugin, + nextAssetStore, + pairRecorded, + removeFile, + type WebpackPluginDeps, +} from './webpack-plugin'; + +/** + * webpack-sources' RawSource, as far as it matters here: a STRING source is text webpack can still rewrite after + * the stamp (RealContentHashPlugin renames `[contenthash]` references in string sources only), a Buffer source is + * opaque to it. A stamp that hands a Buffer to `updateAsset` leaves lazy-chunk URLs pointing at files that were + * renamed afterwards (measured on real Next builds: ChunkLoadError), so the fake refuses one. + */ +class RawSource { + constructor(readonly content: string | Buffer) {} +} + +type Processor = () => Promise; + +/** A fake webpack compilation holding named assets, recording updates. */ +function fakeCompilation( + assets: Record, + related: Record = {}, +) { + const store = new Map( + Object.entries(assets).map(([k, v]) => [k, Buffer.from(v)]), + ); + let processor: Processor | undefined; + let stage: number | undefined; + return { + store, + run: () => (processor as Processor)(), + stage: () => stage, + compilation: { + hooks: { + processAssets: { + tapPromise: (o: { name: string; stage: number }, fn: Processor) => { + stage = o.stage; + processor = fn; + }, + }, + }, + getAssets: () => [...store.keys()].map((name) => ({ name })), + getAsset: (name: string) => + store.has(name) + ? { + source: { buffer: () => store.get(name) as Buffer }, + info: related[name] === undefined ? {} : { related: { sourceMap: related[name] } }, + } + : undefined, + updateAsset: vi.fn((name: string, source: unknown) => { + const { content } = source as RawSource; + if (typeof content !== 'string') { + throw new Error(`${name}: a Buffer source cannot be rewritten by RealContentHashPlugin`); + } + store.set(name, Buffer.from(content, 'utf8')); + }), + }, + }; +} + +type Compilation = ReturnType['compilation']; + +/** A fake compiler: records taps and lets the test fire them. */ +function fakeCompiler(options: { path?: string; api?: boolean } = {}) { + let onThis: ((c: Compilation) => void) | undefined; + let onEmit: ((c: Compilation) => Promise) | undefined; + const compiler = { + options: { output: { path: options.path ?? '/out/.next/server/chunks' } }, + hooks: { + thisCompilation: { tap: (_n: string, fn: (c: Compilation) => void) => (onThis = fn) }, + afterEmit: { + tapPromise: (_n: string, fn: (c: Compilation) => Promise) => (onEmit = fn), + }, + }, + ...(options.api === false + ? {} + : { + webpack: { + Compilation: { PROCESS_ASSETS_STAGE_DEV_TOOLING: 100 }, + sources: { RawSource }, + }, + }), + } as unknown as CompilerLike; + return { + compiler, + startCompilation: (c: Compilation) => (onThis as (c: Compilation) => void)(c), + emit: (c: Compilation) => (onEmit as (c: Compilation) => Promise)(c), + hasThis: () => onThis !== undefined, + hasEmit: () => onEmit !== undefined, + }; +} + +function context( + overrides: Partial = {}, + extra = {}, +): BugseeNextContext { + return { + resolved: { + enabled: true, + appToken: 't', + deleteMaps: true, + registerBuild: 'release', + dryRun: false, + failOnError: false, + ...overrides, + } as BugseeNextContext['resolved'], + serverSourceMaps: true, + deleteServerMaps: false, + say: vi.fn(), + ...extra, + }; +} + +const deps = (over: WebpackPluginDeps = {}): WebpackPluginDeps => ({ + stamp: vi.fn(async () => ({ stamped: [], maps: {}, bundles: 1 })), + upload: vi.fn(async () => undefined), + exists: vi.fn(async () => true), + hasSriManifest: vi.fn(async () => false), + tail: vi.fn(async () => 'code();\n//# debugId=00000000-0000-5000-8000-000000000001\n'), + remove: vi.fn(async () => undefined), + ...over, +}); + +describe('nextAssetStore', () => { + it('stages `../` asset names under a stand-in directory and maps them back', () => { + const { compilation, store } = fakeCompilation({ + '../app/page.js': 'code', + '../app/page.js.map': 'map', + 'chunks/1.js': 'one', + '../../deep.js': 'deep', + }); + const assets = nextAssetStore(compilation, RawSource); + const names = assets.names(); + expect(names).toEqual([ + '__bugsee_up__/app/page.js', + '__bugsee_up__/app/page.js.map', + 'chunks/1.js', + '__bugsee_up__/__bugsee_up__/deep.js', + ]); + // Nothing staged escapes the staging directory. + expect(names.some((n) => n.startsWith('..') || n.includes('/../'))).toBe(false); + expect(assets.read('__bugsee_up__/app/page.js').toString()).toBe('code'); + expect(assets.read('chunks/1.js').toString()).toBe('one'); + assets.update('__bugsee_up__/app/page.js', Buffer.from('stamped')); + expect(store.get('../app/page.js')?.toString()).toBe('stamped'); + assets.update('chunks/1.js', Buffer.from('stamped-one')); + expect(store.get('chunks/1.js')?.toString()).toBe('stamped-one'); + }); + + it('reads an unknown asset as empty rather than throwing', () => { + const { compilation } = fakeCompilation({}); + expect(nextAssetStore(compilation, RawSource).read('nope.js')).toEqual(Buffer.alloc(0)); + }); +}); + +describe('createNextWebpackPlugin', () => { + it('does nothing when the plugin is not enabled', () => { + const fake = fakeCompiler(); + createNextWebpackPlugin(context({ enabled: false }), 'client', deps()).apply(fake.compiler); + expect(fake.hasThis()).toBe(false); + expect(fake.hasEmit()).toBe(false); + }); + + it('does nothing for server and edge when server maps are off, but still serves the client', () => { + const off = context({}, { serverSourceMaps: false }); + for (const kind of ['server', 'edge'] as const) { + const fake = fakeCompiler(); + createNextWebpackPlugin(off, kind, deps()).apply(fake.compiler); + expect(fake.hasEmit()).toBe(false); + } + const client = fakeCompiler(); + createNextWebpackPlugin(off, 'client', deps()).apply(client.compiler); + expect(client.hasEmit()).toBe(true); + }); + + it('stamps the compilation one stage after dev-tooling', async () => { + const d = deps(); + const fake = fakeCompiler(); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x' }); + fake.startCompilation(c.compilation); + expect(c.stage()).toBe(101); + await c.run(); + expect(d.stamp).toHaveBeenCalledTimes(1); + expect(d.stamp).toHaveBeenCalledWith(expect.any(Object), { dryRun: false }); + }); + + it('passes dryRun to the stamp', async () => { + const d = deps(); + const fake = fakeCompiler(); + createNextWebpackPlugin(context({ dryRun: true }), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x' }); + fake.startCompilation(c.compilation); + await c.run(); + expect(d.stamp).toHaveBeenCalledWith(expect.any(Object), { dryRun: true }); + }); + + it('uploads after emit with the stamped flag, over exactly this compilation’s own files', async () => { + const d = deps(); + const fake = fakeCompiler({ path: '/out/.next/server/chunks' }); + createNextWebpackPlugin(context(), 'server', d).apply(fake.compiler); + const c = fakeCompilation({ + '../app/page.js': 'x', + '../app/page.js.map': 'm', + 'chunks/1.js': 'x', + 'chunks/1.js.map': 'm', + 'no-map.js': 'x', + }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + expect(d.upload).toHaveBeenCalledTimes(1); + const [resolved, outDir, options] = (d.upload as ReturnType).mock.calls[0] as [ + Record, + string, + { bundler: unknown; preStamped: boolean; files: Record }, + ]; + expect(outDir).toBe('/out/.next/server/chunks'); + expect(options.preStamped).toBe(true); + expect(options.bundler).toEqual({ isProduction: true, configuration: 'server' }); + expect(options.files.scripts).toEqual([ + '/out/.next/server/app/page.js', + '/out/.next/server/chunks/chunks/1.js', + ]); + expect(options.files.maps).toEqual([ + '/out/.next/server/app/page.js.map', + '/out/.next/server/chunks/chunks/1.js.map', + ]); + // The server follows the server deletion policy and never registers the build. + expect(resolved).toMatchObject({ deleteMaps: false, registerBuild: false }); + }); + + it('gives the client the client policy: deleted maps, the build registered', async () => { + const d = deps(); + const fake = fakeCompiler({ path: '/out/.next' }); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'static/a.js': 'x', 'static/a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await fake.emit(c.compilation); + const [resolved] = (d.upload as ReturnType).mock.calls[0] as [ + Record, + ]; + expect(resolved).toMatchObject({ deleteMaps: true, registerBuild: 'release' }); + }); + + it('honours deleteServerMaps for server and edge', async () => { + const d = deps(); + const fake = fakeCompiler(); + createNextWebpackPlugin(context({}, { deleteServerMaps: true }), 'edge', d).apply( + fake.compiler, + ); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await fake.emit(c.compilation); + const [resolved] = (d.upload as ReturnType).mock.calls[0] as [ + Record, + ]; + expect(resolved).toMatchObject({ deleteMaps: true }); + }); + + it('only counts assets that exist on disk', async () => { + const d = deps({ exists: vi.fn(async (p: string) => !p.endsWith('gone.js')) }); + const fake = fakeCompiler(); + createNextWebpackPlugin(context(), 'server', d).apply(fake.compiler); + const c = fakeCompilation({ + 'gone.js': 'x', + 'gone.js.map': 'm', + 'here.js': 'x', + 'here.js.map': 'm', + }); + fake.startCompilation(c.compilation); + await fake.emit(c.compilation); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { files: { scripts: string[] } }, + ]; + expect(options.files.scripts).toEqual(['/out/.next/server/chunks/here.js']); + }); + + it('falls back to the post-emit stamp (preStamped false) and warns when the in-build stamp fails', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const d = deps({ + stamp: vi.fn(async () => { + throw new Error('inject broke'); + }), + }); + const fake = fakeCompiler(); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('inject broke')); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { preStamped: boolean }, + ]; + expect(options.preStamped).toBe(false); + warn.mockRestore(); + }); + + it('reports a stamp failure through onError, once the build knows what follows', async () => { + const onError = vi.fn(); + const d = deps({ + stamp: vi.fn(async () => { + throw new Error('boom'); + }), + }); + const fake = fakeCompiler(); + createNextWebpackPlugin(context({ onError }), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x' }); + fake.startCompilation(c.compilation); + await c.run(); + expect(onError).not.toHaveBeenCalled(); + await fake.emit(c.compilation); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'boom' })); + expect(onError).toHaveBeenCalledTimes(1); + }); + + it('rethrows a stamp failure under failOnError', async () => { + const d = deps({ + stamp: vi.fn(async () => { + throw new Error('strict'); + }), + }); + const fake = fakeCompiler(); + createNextWebpackPlugin(context({ failOnError: true }), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x' }); + fake.startCompilation(c.compilation); + await expect(c.run()).rejects.toThrow('strict'); + }); + + it('a stamp from the previous compilation cannot vouch for the next one (watch mode)', async () => { + const d = deps(); + const fake = fakeCompiler(); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const first = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(first.compilation); + await first.run(); + const second = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(second.compilation); + await fake.emit(second.compilation); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { preStamped: boolean }, + ]; + expect(options.preStamped).toBe(false); + }); + + it('skips the in-build stamp when the compiler exposes no webpack API, and still uploads', async () => { + const d = deps(); + const fake = fakeCompiler({ api: false }); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + expect(fake.hasThis()).toBe(false); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + await fake.emit(c.compilation); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('works through Rspack’s API object', async () => { + const d = deps(); + const fake = fakeCompiler(); + const raw = fake.compiler as unknown as { webpack?: unknown; rspack?: unknown }; + raw.rspack = raw.webpack; + raw.webpack = undefined; + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + expect(fake.hasThis()).toBe(true); + }); + + it('says so when the browser build emitted no maps, and does not upload', async () => { + const d = deps(); + const ctx = context(); + const fake = fakeCompiler(); + createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x' }); + fake.startCompilation(c.compilation); + await fake.emit(c.compilation); + expect(d.upload).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('productionBrowserSourceMaps')); + }); + + it('is quiet when a server compilation emitted no maps', async () => { + const d = deps(); + const ctx = context(); + const fake = fakeCompiler(); + createNextWebpackPlugin(ctx, 'server', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x' }); + await fake.emit(c.compilation); + expect(d.upload).not.toHaveBeenCalled(); + expect(ctx.say).not.toHaveBeenCalled(); + }); + + it('does nothing after emit when the compiler has no output path', async () => { + const d = deps(); + const fake = fakeCompiler(); + (fake.compiler as unknown as { options: unknown }).options = {}; + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + await fake.emit(fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }).compilation); + expect(d.upload).not.toHaveBeenCalled(); + }); + + it('uses the real stamp, upload and filesystem when none are injected', async () => { + const fake = fakeCompiler({ path: '/definitely/not/here' }); + createNextWebpackPlugin(context({ enabled: true }), 'server').apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + // Nothing exists on disk, so the real `exists` filters everything out and nothing is uploaded. + await expect(fake.emit(c.compilation)).resolves.toBeUndefined(); + }); +}); + +describe('nextAssetStore: sources webpack can still rewrite', () => { + it('updates an asset with a STRING source, never a Buffer', () => { + const { compilation, store } = fakeCompilation({ 'static/a.js': 'old' }); + const assets = nextAssetStore(compilation, RawSource); + assets.names(); + assets.update('static/a.js', Buffer.from('new \u00e9 text', 'utf8')); + expect(compilation.updateAsset).toHaveBeenCalledTimes(1); + const [, source] = compilation.updateAsset.mock.calls[0] as [string, RawSource]; + expect(source.content).toBe('new \u00e9 text'); + expect(store.get('static/a.js')?.toString('utf8')).toBe('new \u00e9 text'); + }); + + it('refuses bytes that are not valid UTF-8 up front (a string source would corrupt them)', () => { + const { compilation } = fakeCompilation({ 'a.js': 'ok' }); + const assets = nextAssetStore(compilation, RawSource); + expect(() => assets.check?.('a.js', Buffer.from([0xff, 0xfe, 0x00, 0x80]))).toThrow( + /not valid UTF-8/, + ); + expect(() => assets.update('a.js', Buffer.from([0xff, 0xfe]))).toThrow(/not valid UTF-8/); + expect(compilation.updateAsset).not.toHaveBeenCalled(); + expect(() => assets.check?.('a.js', Buffer.from('fine \u00e9'))).not.toThrow(); + }); + + it('keeps a byte-order mark instead of dropping it', () => { + const { compilation, store } = fakeCompilation({ 'b.js': 'y' }); + const assets = nextAssetStore(compilation, RawSource); + assets.update('b.js', Buffer.from('\ufeffwith bom')); + expect(store.get('b.js')?.toString('utf8')).toBe('\ufeffwith bom'); + }); +}); + +describe('nextAssetStore: query-free names and moved maps', () => { + it('presents names without their ?query and maps them back to the real asset', () => { + const { compilation, store } = fakeCompilation({ + 'static/a.js?h1': 'a', + 'static/a.js.map?h1': 'm', + 'static/a#1.js': 'hash kept', + }); + const assets = nextAssetStore(compilation, RawSource); + expect(assets.names()).toEqual(['static/a.js', 'static/a.js.map', 'static/a#1.js']); + expect(assets.read('static/a.js').toString()).toBe('a'); + assets.update('static/a.js', Buffer.from('b')); + expect(store.get('static/a.js?h1')?.toString()).toBe('b'); + expect(assets.real('static/a.js')).toBe('static/a.js?h1'); + expect(assets.real('static/a#1.js')).toBe('static/a#1.js'); + expect(assets.real('unknown.js')).toBe('unknown.js'); + }); + + it('keeps the real names of two assets that would collide once cleaned', () => { + const { compilation } = fakeCompilation({ 'a.js?x': '1', 'a.js?y': '2' }); + expect(nextAssetStore(compilation, RawSource).names()).toEqual(['a.js?x', 'a.js?y']); + }); + + it('names the map the compilation recorded for a bundle, staged like the bundle', () => { + const { compilation } = fakeCompilation( + { + '../app/page.js': 'x', + '../maps/page.js.map?v': 'm', + 'a.js': 'x', + 'a.js.map': 'm', + 'b.js': 'x', + }, + { '../app/page.js': '../maps/page.js.map?v', 'a.js': ['a.js.map', 'other'] }, + ); + const assets = nextAssetStore(compilation, RawSource); + assets.names(); + expect(assets.mapOf?.('__bugsee_up__/app/page.js')).toBe('__bugsee_up__/maps/page.js.map'); + expect(assets.mapOf?.('a.js')).toBe('a.js.map'); + expect(assets.mapOf?.('b.js')).toBeUndefined(); + }); +}); + +describe('createNextWebpackPlugin: the new core contract', () => { + const asset = { + '../app/page.js': 'x', + '../app/page.js.map': 'm', + 'static/c.js': 'x', + 'static/c.js.map': 'm', + }; + + it('hands the on-disk re-check the FINAL names on disk: the bundles that carry a debug-ID now, with their maps', async () => { + // The stamp saw `chunks/1.[old].js`; webpack renamed it afterwards, so the check goes by what is on disk. + const d = deps({ + stamp: vi.fn(async () => ({ + stamped: ['chunks/1.OLDHASH.js'], + maps: { 'chunks/1.OLDHASH.js': 'chunks/1.OLDHASH.js.map' }, + bundles: 1, + })), + tail: vi.fn(async (path: string) => + path.endsWith('1.NEWHASH.js') + ? 'x\n//# debugId=00000000-0000-5000-8000-000000000009\n' + : 'plain', + ), + }); + const fake = fakeCompiler({ path: '/out/.next/server/chunks' }); + createNextWebpackPlugin(context(), 'server', d).apply(fake.compiler); + const c = fakeCompilation({ + '../app/page.js': 'x', + '../app/page.js.map': 'm', + '1.NEWHASH.js': 'x', + '1.NEWHASH.js.map': 'm', + }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { stampedBundles: string[]; stampedMaps: Record }, + ]; + expect(options.stampedBundles).toEqual(['1.NEWHASH.js']); + expect(options.stampedMaps).toEqual({ '1.NEWHASH.js': '1.NEWHASH.js.map' }); + }); + + it('reports a stamped bundle that lost its debug-ID on the way (instead of silently dropping it from the check)', async () => { + const onError = vi.fn(); + const d = deps({ + stamp: vi.fn(async () => ({ stamped: ['a.js'], maps: { 'a.js': 'a.js.map' }, bundles: 1 })), + tail: vi.fn(async () => 'plain, no id'), + }); + const fake = fakeCompiler({ path: '/o' }); + createNextWebpackPlugin(context({ onError }), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('1 of the 1 bundle(s)') }), + ); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('warns on the console for it without onError, and rethrows under failOnError', async () => { + const make = (ctx: BugseeNextContext) => { + const d = deps({ + stamp: vi.fn(async () => ({ stamped: ['a.js'], maps: { 'a.js': 'a.js.map' }, bundles: 1 })), + tail: vi.fn(async () => 'plain'), + }); + const fake = fakeCompiler({ path: '/o' }); + createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + return { + run: async () => { + await c.run(); + await fake.emit(c.compilation); + }, + }; + }; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + await make(context()).run(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('do not carry their debug-ID')); + warn.mockRestore(); + await expect(make(context({ failOnError: true })).run()).rejects.toThrow('do not carry'); + }); + + it('pairs a recorded map elsewhere for the re-check', async () => { + const d = deps({ + stamp: vi.fn(async () => ({ + stamped: ['static/a.js'], + maps: { 'static/a.js': 'maps/a.js.map' }, + bundles: 1, + })), + }); + const fake = fakeCompiler({ path: '/o' }); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation( + { 'static/a.js': 'x', 'maps/a.js.map': 'm' }, + { 'static/a.js': 'maps/a.js.map' }, + ); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { stampedMaps: Record }, + ]; + expect(options.stampedMaps).toEqual({ 'static/a.js': 'maps/a.js.map' }); + }); + + it('does not claim a stamp that staged nothing while the build emitted scripts: says so, stamps after emit', async () => { + const d = deps({ stamp: vi.fn(async () => ({ stamped: [], maps: {}, bundles: 0 })) }); + const ctx = context(); + const fake = fakeCompiler(); + createNextWebpackPlugin(ctx, 'server', d).apply(fake.compiler); + const c = fakeCompilation(asset); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('no debug-ID could be stamped')); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('server build')); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { preStamped: boolean; stampedBundles?: string[] }, + ]; + expect(options.preStamped).toBe(false); + expect(options.stampedBundles).toBeUndefined(); + }); + + it('a compilation with no scripts at all and nothing staged is not an alarm', async () => { + const d = deps({ stamp: vi.fn(async () => ({ stamped: [], maps: {}, bundles: 0 })) }); + const ctx = context(); + const fake = fakeCompiler(); + createNextWebpackPlugin(ctx, 'server', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.json': '{}' }); + fake.startCompilation(c.compilation); + await c.run(); + expect(ctx.say).not.toHaveBeenCalled(); + }); + + it('stamps and uploads nothing when the stamp is refused because a map lies outside the output', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const refusal = Object.assign(new Error('map outside the output'), { unreachableMap: true }); + const d = deps({ + stamp: vi.fn(async () => { + throw refusal; + }), + }); + const fake = fakeCompiler(); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('half-stamp')); + expect(d.upload).not.toHaveBeenCalled(); + warn.mockRestore(); + }); + + it('looks for an asset whose name carries a ?query at the query-free path on disk', async () => { + const seen: string[] = []; + const d = deps({ + exists: vi.fn(async (path: string) => { + seen.push(path); + return true; + }), + }); + const fake = fakeCompiler({ path: '/out/.next' }); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'static/a.js?h': 'x', 'static/a.js.map?h': 'm' }); + await fake.emit(c.compilation); + expect(seen).toEqual(['/out/.next/static/a.js', '/out/.next/static/a.js.map']); + }); +}); + +describe('createNextWebpackPlugin: the post-emit fallback on an SRI build', () => { + const failing = () => + vi.fn(async () => { + throw new Error('inject broke'); + }); + const run = async (ctx: BugseeNextContext, d: WebpackPluginDeps) => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const fake = fakeCompiler(); + createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + warn.mockRestore(); + }; + + it('does not stamp the written files when the app uses SRI (the config says so)', async () => { + const ctx = context({}, { sri: true }); + const d = deps({ stamp: failing() }); + await run(ctx, d); + expect(d.upload).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('Subresource Integrity')); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('client build')); + }); + + it('nor when Next\u2019s integrity manifest sits next to the output', async () => { + const ctx = context(); + const d = deps({ stamp: failing(), hasSriManifest: vi.fn(async () => true) }); + await run(ctx, d); + expect(d.upload).not.toHaveBeenCalled(); + expect(d.hasSriManifest).toHaveBeenCalledWith('/out/.next/server/chunks'); + }); + + it('still falls back without SRI', async () => { + const d = deps({ stamp: failing() }); + await run(context(), d); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('uploads a stamp that took, SRI or not (it ran before anything hashed)', async () => { + const d = deps(); + await run(context({}, { sri: true }), d); + expect(d.upload).toHaveBeenCalledTimes(1); + expect(d.hasSriManifest).not.toHaveBeenCalled(); + }); +}); + +describe('createNextWebpackPlugin: no public maps Bugsee asked for when nothing is uploaded', () => { + const failing = () => + vi.fn(async () => { + throw new Error('inject broke'); + }); + const assets = { + 'static/a.js': 'x', + 'static/a.js.map': 'm', + 'static/a.css': 'c', + 'static/a.css.map': 'cm', + }; + const run = async (kind: 'client' | 'server', ctx: BugseeNextContext, d: WebpackPluginDeps) => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const fake = fakeCompiler({ path: '/out/.next' }); + createNextWebpackPlugin(ctx, kind, d).apply(fake.compiler); + const c = fakeCompilation(assets); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + const warned = warn.mock.calls.map((call) => String(call[0])); + warn.mockRestore(); + return warned; + }; + + it('deletes the browser maps it turned on when an SRI build\u2019s stamp failed (nothing is uploaded)', async () => { + const ctx = context({}, { sri: true, forcedMaps: true }); + const d = deps({ stamp: failing() }); + await run('client', ctx, d); + expect(d.upload).not.toHaveBeenCalled(); + expect(d.remove).toHaveBeenCalledTimes(2); + expect(d.remove).toHaveBeenCalledWith('/out/.next/static/a.js.map'); + expect(d.remove).toHaveBeenCalledWith('/out/.next/static/a.css.map'); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('were removed')); + }); + + it('keeps maps the app asked for, and says they are public', async () => { + const ctx = context({}, { sri: true }); + const d = deps({ stamp: failing() }); + await run('client', ctx, d); + expect(d.remove).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('publicly served')); + }); + + it('never touches a server compilation\u2019s maps (not public)', async () => { + const ctx = context({}, { sri: true, forcedMaps: true }); + const d = deps({ stamp: failing() }); + await run('server', ctx, d); + expect(d.remove).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.not.stringContaining('browser source maps')); + }); + + it('deletes them when the stamp was abandoned (a map outside the output), too', async () => { + const d = deps({ + stamp: vi.fn(async () => { + throw Object.assign(new Error('outside'), { unreachableMap: true }); + }), + }); + await run('client', context({}, { forcedMaps: true }), d); + expect(d.upload).not.toHaveBeenCalled(); + expect(d.remove).toHaveBeenCalledTimes(2); + }); + + it('leaves them alone when the upload runs (it deletes them itself after confirming)', async () => { + const d = deps(); + await run('client', context({}, { forcedMaps: true }), d); + expect(d.upload).toHaveBeenCalledTimes(1); + expect(d.remove).not.toHaveBeenCalled(); + }); + + it('prints ONE accurate message on an SRI build, never "falling back"', async () => { + const onError = vi.fn(); + const ctx = context({ onError }, { sri: true, forcedMaps: true }); + const warned = await run('client', ctx, deps({ stamp: failing() })); + expect(warned.join('\n')).not.toMatch(/falling back/); + expect(ctx.say).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'inject broke' })); + }); + + it('the CAUSE is never hidden by `silent`: with no onError it is a console warning, not a notice', async () => { + const ctx = context({}, { sri: true, forcedMaps: true }); + const warned = await run('client', ctx, deps({ stamp: failing() })); + expect(warned).toHaveLength(1); + expect(warned[0]).toMatch(/in-build debug-ID stamping did not apply: Error: inject broke/); + // The notice does not carry the cause (so a silenced notice cannot be the only place it lives). + expect(vi.mocked(ctx.say).mock.calls[0]?.[0]).not.toContain('inject broke'); + }); + + it('a maps-removal failure never fails the build: reported through onError, then the notice says so', async () => { + const onError = vi.fn(); + const ctx = context({ onError }, { sri: true, forcedMaps: true }); + const d = deps({ + stamp: failing(), + remove: vi.fn(async () => { + throw Object.assign(new Error('EPERM'), { code: 'EPERM' }); + }), + }); + await expect(run('client', ctx, d)).resolves.toBeDefined(); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'EPERM' })); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('could not all be removed')); + }); + + it('warns on the console when removal fails and there is no onError', async () => { + const ctx = context({}, { sri: true, forcedMaps: true }); + const d = deps({ + stamp: failing(), + remove: vi.fn(async () => { + throw new Error('EPERM'); + }), + }); + const warned = await run('client', ctx, d); + expect(warned.some((w) => w.includes('could not remove the browser source maps'))).toBe(true); + }); + + it('rethrows a removal failure under failOnError (reachable when nothing could be staged on an SRI build)', async () => { + const ctx = context({ failOnError: true }, { sri: true, forcedMaps: true }); + const d = deps({ + stamp: vi.fn(async () => ({ stamped: [], maps: {}, bundles: 0 })), + remove: vi.fn(async () => { + throw new Error('EPERM'); + }), + }); + await expect(run('client', ctx, d)).rejects.toThrow('EPERM'); + }); + + it('deletes nothing on a dry run, and says so', async () => { + const ctx = context({ dryRun: true }, { sri: true, forcedMaps: true }); + const d = deps({ stamp: failing() }); + await run('client', ctx, d); + expect(d.remove).not.toHaveBeenCalled(); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('Dry run: nothing was deleted')); + }); + + it('an abandoned stamp deletes nothing on a dry run either', async () => { + const d = deps({ + stamp: vi.fn(async () => { + throw Object.assign(new Error('outside'), { unreachableMap: true }); + }), + }); + await run('client', context({ dryRun: true }, { forcedMaps: true }), d); + expect(d.remove).not.toHaveBeenCalled(); + }); + + it('an SRI build where nothing could be staged (no thrown cause) still reports through onError / console.warn', async () => { + const nothing = () => vi.fn(async () => ({ stamped: [], maps: {}, bundles: 0 })); + const onError = vi.fn(); + await run( + 'client', + context({ onError }, { sri: true, forcedMaps: true }), + deps({ stamp: nothing() }), + ); + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('could be staged') }), + ); + const warned = await run( + 'client', + context({}, { sri: true, forcedMaps: true }), + deps({ stamp: nothing() }), + ); + expect(warned.some((w) => w.includes('could be staged'))).toBe(true); + }); + + it('tries every removal, then reports each failure (partial removal is reported, not hidden)', async () => { + const onError = vi.fn(); + const remove = vi.fn(async (path: string) => { + if (path.endsWith('a.js.map')) throw new Error(`EPERM ${path}`); + }); + const ctx = context({ onError }, { sri: true, forcedMaps: true }); + await run('client', ctx, deps({ stamp: failing(), remove })); + expect(remove).toHaveBeenCalledTimes(2); + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('a.js.map') }), + ); + expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('could not all be removed')); + }); + + it('a throwing onError aborts the hook, as the core\u2019s own does', async () => { + const onError = vi.fn(() => { + throw new Error('host logger down'); + }); + const ctx = context({ onError }, { sri: true, forcedMaps: true }); + await expect( + run( + 'client', + ctx, + deps({ + stamp: failing(), + remove: vi.fn(async () => { + throw new Error('EPERM'); + }), + }), + ), + ).rejects.toThrow('host logger down'); + }); + + it('only claims a dry run deleted nothing when something would have been deleted', async () => { + const forced = context({ dryRun: true }, { sri: true, forcedMaps: true }); + await run('client', forced, deps({ stamp: failing() })); + expect(forced.say).toHaveBeenCalledWith( + expect.stringContaining('Dry run: nothing was deleted'), + ); + const own = context({ dryRun: true }, { sri: true }); + await run('client', own, deps({ stamp: failing() })); + expect(own.say).toHaveBeenCalledWith(expect.not.stringContaining('Dry run')); + expect(own.say).toHaveBeenCalledWith(expect.stringContaining('publicly served')); + }); + + it('an abandoned stamp on a dry run says the forced maps remain public', async () => { + const abandon = () => + vi.fn(async () => { + throw Object.assign(new Error('outside'), { unreachableMap: true }); + }); + const forced = context({ dryRun: true }, { forcedMaps: true }); + await run('client', forced, deps({ stamp: abandon() })); + expect(forced.say).toHaveBeenCalledWith(expect.stringContaining('publicly served')); + const own = context({ dryRun: true }); + await run('client', own, deps({ stamp: abandon() })); + expect(own.say).not.toHaveBeenCalled(); + }); + + it('on a build without SRI the fallback message is printed, once', async () => { + const warned = await run('client', context(), deps({ stamp: failing() })); + expect(warned.filter((w) => w.includes('falling back to stamping after emit'))).toHaveLength(1); + }); + + it('the default remover tolerates a file that is already gone and reports other errors', async () => { + const { mkdtempSync, rmSync, writeFileSync, existsSync } = await import('node:fs'); + const { tmpdir } = await import('node:os'); + const { join } = await import('node:path'); + const dir = mkdtempSync(join(tmpdir(), 'bugsee-rm-')); + try { + writeFileSync(join(dir, 'a.js'), 'x'); + writeFileSync(join(dir, 'a.js.map'), 'm'); + const ctx = context({}, { sri: true, forcedMaps: true }); + const fake = fakeCompiler({ path: dir }); + createNextWebpackPlugin(ctx, 'client', { + ...deps({ stamp: failing() }), + remove: undefined, + exists: undefined, + }).apply(fake.compiler); + const c = fakeCompilation({ + 'a.js': 'x', + 'a.js.map': 'm', + 'gone.js': 'x', + 'gone.js.map': 'm', + }); + fake.startCompilation(c.compilation); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + await c.run(); + await fake.emit(c.compilation); + warn.mockRestore(); + expect(existsSync(join(dir, 'a.js.map'))).toBe(false); + expect(existsSync(join(dir, 'a.js'))).toBe(true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe('removeFile', () => { + it('deletes a file, ignores one that is gone, and reports anything else', async () => { + const { mkdirSync, mkdtempSync, rmSync, writeFileSync, existsSync } = await import('node:fs'); + const { tmpdir } = await import('node:os'); + const { join } = await import('node:path'); + const dir = mkdtempSync(join(tmpdir(), 'bugsee-rmf-')); + try { + writeFileSync(join(dir, 'a.map'), 'm'); + await removeFile(join(dir, 'a.map')); + expect(existsSync(join(dir, 'a.map'))).toBe(false); + await expect(removeFile(join(dir, 'gone.map'))).resolves.toBeUndefined(); + mkdirSync(join(dir, 'd')); + await expect(removeFile(join(dir, 'd'))).rejects.toThrow(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe('pairRecorded', () => { + const emitted = (names: string[]) => names.map((n) => `/o/${n}`); + + it('pairs a script with the map the compilation recorded for it, wherever that map is', () => { + const { compilation } = fakeCompilation( + { 'static/a.js': 'x', 'maps/a.js.map': 'm', 'static/b.js': 'x', 'static/b.js.map': 'm' }, + { 'static/a.js': 'maps/a.js.map' }, + ); + const files = pairRecorded( + compilation, + '/o', + emitted(['static/a.js', 'maps/a.js.map', 'static/b.js', 'static/b.js.map']), + ); + expect(files.scripts).toEqual(['/o/static/a.js', '/o/static/b.js']); + expect(files.maps).toEqual(['/o/maps/a.js.map', '/o/static/b.js.map']); + }); + + it('accepts a recorded list and a ?query on the recorded map', () => { + const { compilation } = fakeCompilation( + { 'a.js': 'x', 'm/a.js.map?v': 'm' }, + { 'a.js': ['m/a.js.map?v', 'other'] }, + ); + expect(pairRecorded(compilation, '/o', emitted(['a.js', 'm/a.js.map'])).maps).toEqual([ + '/o/m/a.js.map', + ]); + }); + + it('ignores a recorded map that was not emitted, and scripts with none recorded', () => { + const { compilation } = fakeCompilation( + { 'a.js': 'x', 'b.js': 'x', 'c.txt': 'x' }, + { 'a.js': 'gone.js.map' }, + ); + const files = pairRecorded(compilation, '/o', emitted(['a.js', 'b.js', 'c.txt'])); + expect(files.scripts).toEqual([]); + expect(files.maps).toEqual([]); + }); + + it('does not pair a script that was not itself emitted', () => { + const { compilation } = fakeCompilation( + { 'a.js': 'x', 'm/a.js.map': 'm' }, + { 'a.js': 'm/a.js.map' }, + ); + expect(pairRecorded(compilation, '/o', emitted(['m/a.js.map'])).scripts).toEqual([]); + }); +}); + +describe('createNextWebpackPlugin: queries, recorded maps, registration', () => { + it('goes by the query-free names on disk (webpack drops ?query when it writes the file)', async () => { + const d = deps({ + stamp: vi.fn(async () => ({ + stamped: ['static/a.js'], + maps: { 'static/a.js': 'static/a.js.map' }, + bundles: 1, + })), + }); + const fake = fakeCompiler({ path: '/o' }); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'static/a.js?v=1': 'x', 'static/a.js.map?v=1': 'm' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + const [, , options] = (d.upload as ReturnType).mock.calls[0] as [ + unknown, + unknown, + { stampedBundles: string[]; stampedMaps: Record }, + ]; + expect(options.stampedBundles).toEqual(['static/a.js']); + expect(options.stampedMaps).toEqual({ 'static/a.js': 'static/a.js.map' }); + }); + + it('uploads maps a script\u2019s recorded relationship names even when none sits beside it', async () => { + const d = deps(); + const fake = fakeCompiler({ path: '/o' }); + createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); + const c = fakeCompilation( + { 'static/a.js': 'x', 'maps/a.js.map': 'm' }, + { 'static/a.js': 'maps/a.js.map' }, + ); + fake.startCompilation(c.compilation); + await fake.emit(c.compilation); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('the server compilation registers the build only when the app writes no browser maps', async () => { + const reg = async (browserMaps: boolean | undefined, kind: 'client' | 'server' | 'edge') => { + const d = deps(); + const fake = fakeCompiler({ path: '/o' }); + createNextWebpackPlugin( + context({}, { ...(browserMaps === undefined ? {} : { browserMaps }) }), + kind, + d, + ).apply(fake.compiler); + const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); + fake.startCompilation(c.compilation); + await fake.emit(c.compilation); + return (d.upload as ReturnType).mock.calls[0]?.[0] as { + registerBuild: unknown; + }; + }; + expect((await reg(false, 'server')).registerBuild).toBe('release'); + expect((await reg(true, 'server')).registerBuild).toBe(false); + expect((await reg(undefined, 'server')).registerBuild).toBe(false); + expect((await reg(false, 'edge')).registerBuild).toBe(false); + expect((await reg(false, 'client')).registerBuild).toBe('release'); + }); +}); + +describe('createNextWebpackPlugin: the on-disk scan and the no-maps notice', () => { + const stampedDeps = (over: WebpackPluginDeps = {}) => + deps({ + stamp: vi.fn(async () => ({ stamped: ['a.js'], maps: { 'a.js': 'a.js.map' }, bundles: 1 })), + ...over, + }); + const emitWith = async ( + ctx: BugseeNextContext, + d: WebpackPluginDeps, + assets: Record, + ) => { + const fake = fakeCompiler({ path: '/o' }); + createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); + const c = fakeCompilation(assets); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + }; + + it('an unreadable bundle never fails the build: reported through onError, not counted as lost', async () => { + const onError = vi.fn(); + const d = stampedDeps({ + tail: vi.fn(async () => { + throw Object.assign(new Error('EBUSY'), { code: 'EBUSY' }); + }), + }); + await expect( + emitWith(context({ onError }), d, { 'a.js': 'x', 'a.js.map': 'm' }), + ).resolves.toBeUndefined(); + expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'EBUSY' })); + expect(d.upload).toHaveBeenCalledTimes(1); + }); + + it('warns on the console for it without onError', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const d = stampedDeps({ + tail: vi.fn(async () => { + throw new Error('EMFILE'); + }), + }); + await emitWith(context(), d, { 'a.js': 'x', 'a.js.map': 'm' }); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('could not read a stamped client bundle'), + ); + warn.mockRestore(); + }); + + it('rethrows an unreadable bundle under failOnError', async () => { + const d = stampedDeps({ + tail: vi.fn(async () => { + throw new Error('EBUSY'); + }), + }); + await expect( + emitWith(context({ failOnError: true }), d, { 'a.js': 'x', 'a.js.map': 'm' }), + ).rejects.toThrow('EBUSY'); + }); + + it('says nothing about missing browser maps when the app chose that (or on a dry run)', async () => { + const off = context({}, { browserMaps: false }); + await emitWith(off, deps(), { 'a.js': 'x' }); + expect(off.say).not.toHaveBeenCalled(); + const expected = context({}, { browserMaps: true }); + await emitWith(expected, deps(), { 'a.js': 'x' }); + expect(expected.say).toHaveBeenCalledWith(expect.stringContaining('emitted no source maps')); + }); +}); diff --git a/packages/nextjs/src/config/webpack-plugin.ts b/packages/nextjs/src/config/webpack-plugin.ts new file mode 100644 index 000000000..a8a1a26f4 --- /dev/null +++ b/packages/nextjs/src/config/webpack-plugin.ts @@ -0,0 +1,468 @@ +// The webpack side of `withBugsee` (`next build --webpack`, and the default for Next <= 15). One plugin instance per +// Next compilation (client, server, edge), each doing two things for ITS OWN assets only: +// +// 1. stamp the debug-IDs inside the compilation, before anything hashes the output (Subresource Integrity), and +// 2. after emit, upload the maps of exactly the files this compilation wrote, then delete them per policy. +// +// It deliberately does not reuse the generic webpack plugin of `@bugsee/webpack-plugin`: measured against a real +// `next build`, that plugin assumes one compilation per output directory. Next's server compilation emits to +// `.next/server/chunks` with asset names like `../app/page.js` (outside its own output path), so the generic +// plugin neither stamped them (an asset name may not escape the staging directory) nor found their maps, and its +// directory-wide upload of `.next` swept up the server compilation's half-written files. +import { stat, unlink } from 'node:fs/promises'; +import { relative, resolve } from 'node:path'; +import { + type AssetStore, + type ResolvedPluginOptions, + runPluginUpload, + stampAssets, +} from '@bugsee/bundler-plugin-core'; +import { type BuildFiles, partitionBuildFiles, readTail } from './build-files'; +import type { BugseeNextContext } from './context'; +import { FALLBACK_SRI_NOTICE, sriManifestNear } from './sri'; + +/** Which of Next's three webpack compilations a plugin instance serves. */ +export type NextCompilationKind = 'client' | 'server' | 'edge'; + +/** The slice of a webpack compilation the stamp and the file list read and write. */ +interface CompilationLike { + hooks: { + processAssets: { + tapPromise: (options: { name: string; stage: number }, fn: () => Promise) => void; + }; + }; + getAssets(): ReadonlyArray<{ name: string }>; + getAsset(name: string): + | { + source: { buffer(): Buffer }; + /** `related.sourceMap` is how SourceMapDevToolPlugin records which asset is a bundle's map. */ + info?: { related?: { sourceMap?: string | string[] | null } }; + } + | undefined; + updateAsset(name: string, source: unknown): void; +} + +/** The slice of a webpack compiler this taps. Read from the compiler, never imported (see core's plugin.ts). */ +export interface CompilerLike { + options: { output?: { path?: string } }; + hooks: { + thisCompilation: { tap: (name: string, fn: (compilation: CompilationLike) => void) => void }; + afterEmit: { + tapPromise: (name: string, fn: (compilation: CompilationLike) => Promise) => void; + }; + }; + webpack?: WebpackApi; + rspack?: WebpackApi; +} + +interface WebpackApi { + Compilation?: { PROCESS_ASSETS_STAGE_DEV_TOOLING?: number }; + sources?: { RawSource?: new (content: string) => unknown }; +} + +/** Seams for tests. */ +export interface WebpackPluginDeps { + stamp?: typeof stampAssets; + upload?: typeof runPluginUpload; + /** Whether a path exists on disk (default `fs.stat`). */ + exists?: (path: string) => Promise; + /** Whether Next's integrity manifest sits next to this output (default: looks on disk). */ + hasSriManifest?: (outDir: string) => Promise; + /** The end of a file as text (default: reads the last 16 KiB). */ + tail?: (path: string) => Promise; + /** Delete a file (default `fs.unlink`; a file that is already gone is fine). */ + remove?: (path: string) => Promise; +} + +const PLUGIN = 'bugsee-next'; +/** The debug-ID comment `bugsee-cli sourcemaps inject` appends to a stamped bundle. */ +const DEBUG_ID = /\/\/# debugId=[0-9a-f-]{36}/; +/** A script asset, query and upper-case extension included (what the core's own plugin counts). */ +const SCRIPT_ASSET = /\.[cm]?js(\?|$)/i; + +/** What the in-build stamp of one compilation established. */ +interface InBuildStamp { + preStamped: boolean; + /** The bundles it stamped and their maps, by real asset name, for the on-disk re-check. */ + /** How many stamped bundles have a map: what must still carry its debug-ID on disk. */ + stampedWithMaps?: number; + /** Why the in-build stamp failed, reported once the build knows what happens next (fallback or not). */ + failure?: unknown; + /** The stamp was refused in a way that makes stamping after emit unsafe too. */ + abandoned?: boolean; +} +/** Stands in for each leading `../` of an asset name inside the staging directory. */ +const UP = '__bugsee_up__'; + +/** Delete a file; one that is already gone is not an error. */ +export async function removeFile(path: string): Promise { + try { + await unlink(path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { + throw error; + } + } +} + +async function fileExists(path: string): Promise { + try { + return (await stat(path)).isFile(); + } catch { + return false; + } +} + +/** + * An asset name without its `?query`: webpack drops `?...` when it writes a file and keeps `#` (measured on real + * builds by the core's own asset store, which this follows). + */ +const withoutQuery = (name: string): string => name.replace(/\?.*$/, ''); + +/** Strict, BOM-preserving UTF-8: a lenient decode would silently corrupt an asset. */ +const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); + +/** The text of an asset's bytes, or a refusal: bytes that are not valid UTF-8 never become a source. */ +function asText(name: string, content: Buffer): string { + try { + return utf8.decode(content); + } catch { + throw new Error(`${name} is not valid UTF-8, so it cannot be stamped as a text source`); + } +} + +/** A compilation's asset table as the core's {@link AssetStore}, plus the way back to real asset names. */ +export interface NextAssetStore extends AssetStore { + /** The real asset name behind a name this store presented. */ + real(name: string): string; +} + +/** + * A compilation's assets as an {@link AssetStore}. Names are presented query-free, and a name that starts with + * `../` (Next's server output sits one level above the compilation's output path) is staged under a stand-in + * directory, consistently for a bundle and its map, so their relative layout survives and nothing can escape the + * staging directory. Two assets that would collide once cleaned keep their real names. + */ +export function nextAssetStore( + compilation: CompilationLike, + RawSource: new (content: string) => unknown, +): NextAssetStore { + const up = (name: string): string => + name.replace(/^(?:\.\.\/)+/, (dots) => `${UP}/`.repeat(dots.length / 3)); + const actual = new Map(); + const refresh = (): void => { + actual.clear(); + const names = compilation.getAssets().map((asset) => asset.name); + const counts = new Map(); + for (const name of names) { + counts.set(up(withoutQuery(name)), (counts.get(up(withoutQuery(name))) ?? 0) + 1); + } + for (const name of names) { + const clean = up(withoutQuery(name)); + actual.set(counts.get(clean) === 1 ? clean : up(name), name); + } + }; + const real = (name: string): string => actual.get(name) ?? name; + return { + names: () => { + refresh(); + return [...actual.keys()]; + }, + read: (name) => compilation.getAsset(real(name))?.source.buffer() ?? Buffer.alloc(0), + // A STRING source on purpose: the stamp runs before webpack's RealContentHashPlugin renames `[contenthash]` + // chunks, and that plugin rewrites the hashed names inside string sources only. A Buffer would keep the + // pre-rename chunk URLs (measured on real Next builds: every lazy chunk 404s, ChunkLoadError). + // Asked by the stamp for every asset BEFORE anything is written, so a bad asset refuses the whole stamp + // instead of leaving half of it applied. + check: (name, content) => void asText(name, content), + update: (name, content) => + compilation.updateAsset(real(name), new RawSource(asText(name, content))), + mapOf: (name) => { + const related = compilation.getAsset(real(name))?.info?.related?.sourceMap; + const map = Array.isArray(related) ? related[0] : related; + return map === undefined || map === null ? undefined : up(withoutQuery(map)); + }, + real, + }; +} + +/** + * The emitted scripts paired with their maps: a map named `