From 0a74c1b9d88aa1adfe5fee56190490bbccdfacd0 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 11:41:00 +0500 Subject: [PATCH 01/39] feat(bundler-plugin-core): verify the debug-ID stamp, and delete maps only when keyed Every stamp is now checked before it is trusted: each changed bundle still parses, keeps its sourceMappingURL pointer, is the original bytes plus an appended stamp, and its map is a JSON object whose debugId matches the bundle's comment. In-build the check is all-or-nothing (nothing is written back on a failure); post-emit the originals are snapshotted before inject and a failing file is restored together with its pair. An in-build stamp is re-checked on disk after the bundler wrote it, and against the page's integrity pins. Map deletion now also requires the map to carry a debugId (the CLI does not upload a map without one), so a map that was never keyed is kept and reported. Adds acorn (zero-dependency parser, already in the tree via webpack/rollup) for the parse check, and vite / vite7 as devDependencies for the real-build tests in the next commit. rollupAssetStore adapts a Rollup/Vite output bundle to the asset-store seam and carries the stamped id onto chunk.map (Vite regenerates a lazy chunk's map from it). Co-Authored-By: Claude Sonnet 5.5 --- packages/bundler-plugin-core/package.json | 5 +- .../src/orchestrate.stamp.test.ts | 423 ++++++++++++++++++ .../src/orchestrate.test.ts | 14 +- .../bundler-plugin-core/src/orchestrate.ts | 130 ++++-- .../src/stamp-assets.test.ts | 239 +++++++++- .../bundler-plugin-core/src/stamp-assets.ts | 131 +++++- .../bundler-plugin-core/src/stamp-files.ts | 166 +++++++ .../src/verify-stamp.test.ts | 333 ++++++++++++++ .../bundler-plugin-core/src/verify-stamp.ts | 235 ++++++++++ pnpm-lock.yaml | 47 +- 10 files changed, 1650 insertions(+), 73 deletions(-) create mode 100644 packages/bundler-plugin-core/src/orchestrate.stamp.test.ts create mode 100644 packages/bundler-plugin-core/src/stamp-files.ts create mode 100644 packages/bundler-plugin-core/src/verify-stamp.test.ts create mode 100644 packages/bundler-plugin-core/src/verify-stamp.ts diff --git a/packages/bundler-plugin-core/package.json b/packages/bundler-plugin-core/package.json index 2e63cba96..cdb887ae6 100644 --- a/packages/bundler-plugin-core/package.json +++ b/packages/bundler-plugin-core/package.json @@ -30,6 +30,7 @@ "dependencies": { "@bugsee/cli": "^0.9.0", "@bugsee/core": "workspace:*", + "acorn": "^8.19.0", "magic-string": "^0.30.21", "unplugin": "^2.3.10" }, @@ -38,7 +39,9 @@ "@types/node": "^22.20.5", "esbuild": "^0.28.2", "rollup": "^4.65.1", - "tsup": "^9.0.0" + "tsup": "^9.0.0", + "vite": "^8.3.5", + "vite7": "npm:vite@7.3.6" }, "publishConfig": { "main": "./dist/index.cjs", diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts new file mode 100644 index 000000000..2868f54dc --- /dev/null +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -0,0 +1,423 @@ +// IN-BUILD STAMPING, PART 2 — what happens AFTER `sourcemaps inject` rewrote the output on disk, and what is +// allowed to delete the maps. Real temp directories; a fake CLI that edits them the way a (mis)behaving +// inject would. +import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { listMapFiles, uploadSourcemaps } from './orchestrate'; +import type { SpawnResult } from './run-cli'; + +const base = { + outDir: '/build/dist', + appToken: 'tok', + appVersion: '1.0.0', + appBuild: '7', +}; + +const ID = 'b039c7fb-d958-5fe6-b76f-136179e9a728'; + +describe('post-emit stamp verification', () => { + const STAMP = `\n;1;\n//# debugId=${ID}\n`; + const stampedMap = JSON.stringify({ version: 3, sources: [], mappings: '', debugId: ID }); + const plainMap = JSON.stringify({ version: 3, sources: [], mappings: '' }); + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-verify-')); + }); + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + /** A fake CLI: `inject` rewrites the named files as `rewrite` says; `upload` just succeeds. */ + const cli = (rewrite: Record) => { + const run = vi.fn(async (args: string[]): Promise => { + if (args[1] === 'inject') { + for (const [name, content] of Object.entries(rewrite)) { + await writeFile(join(dir, name), content); + } + } + return { code: 0, stdout: '', stderr: '' }; + }); + return { run }; + }; + const seed = async (): Promise => { + await writeFile(join(dir, 'a.js'), 'a();\n//# sourceMappingURL=a.js.map\n'); + await writeFile(join(dir, 'a.js.map'), plainMap); + await writeFile(join(dir, 'b.js'), 'b();\n//# sourceMappingURL=b.js.map\n'); + await writeFile(join(dir, 'b.js.map'), plainMap); + }; + const read = (name: string): Promise => readFile(join(dir, name), 'utf8'); + const opts = (extra: object = {}) => ({ + ...base, + outDir: dir, + findSri: async () => [], + deleteMaps: false, + ...extra, + }); + + it('restores a bundle (and its map) whose stamp no longer parses, reports it, keeps the good stamp', async () => { + await seed(); + const { run } = cli({ + 'a.js': `a();\n//# sourceMappingURL=a.js.map\n{{${STAMP}`, + 'a.js.map': stampedMap, + 'b.js': `b();\n//# sourceMappingURL=b.js.map\n${STAMP}`, + 'b.js.map': stampedMap, + }); + const errors: unknown[] = []; + const result = await uploadSourcemaps(opts({ run, onError: (e: unknown) => errors.push(e) })); + + // The broken one is exactly as the bundler wrote it — bundle AND map. + expect(await read('a.js')).toBe('a();\n//# sourceMappingURL=a.js.map\n'); + expect(await read('a.js.map')).toBe(plainMap); + // The healthy one keeps its stamp. + expect(await read('b.js')).toContain(`//# debugId=${ID}`); + expect(await read('b.js.map')).toBe(stampedMap); + expect(String(errors[0])).toContain('a.js'); + expect(String(errors[0])).toContain('no longer parses'); + expect(String(errors[0])).toContain('2 file(s) were restored'); + // The upload still happened for what is stamped. + expect(run.mock.calls.some((c) => c[0][0] === 'debug-files')).toBe(true); + expect(result.uploaded).toBe(true); + }); + + it('a map-only failure restores the bundle too, so a pair is never half-stamped', async () => { + await seed(); + const { run } = cli({ + 'a.js': `a();\n//# sourceMappingURL=a.js.map\n${STAMP}`, + 'a.js.map': 'not json', + }); + const errors: unknown[] = []; + await uploadSourcemaps(opts({ run, onError: (e: unknown) => errors.push(e) })); + expect(await read('a.js')).toBe('a();\n//# sourceMappingURL=a.js.map\n'); + expect(await read('a.js.map')).toBe(plainMap); + expect(String(errors[0])).toContain('a.js.map'); + }); + + it('throws under failOnError, with the files restored', async () => { + await seed(); + const { run } = cli({ 'a.js': `a();\n{{${STAMP}`, 'a.js.map': stampedMap }); + await expect(uploadSourcemaps(opts({ run, failOnError: true }))).rejects.toThrow( + /did not verify/, + ); + expect(await read('a.js')).toBe('a();\n//# sourceMappingURL=a.js.map\n'); + }); + + it('a clean stamp raises nothing', async () => { + await seed(); + const { run } = cli({ + 'a.js': `a();\n//# sourceMappingURL=a.js.map\n${STAMP}`, + 'a.js.map': stampedMap, + }); + const onError = vi.fn(); + await uploadSourcemaps(opts({ run, onError })); + expect(onError).not.toHaveBeenCalled(); + }); + + it('is not checked on a dry run (inject wrote nothing)', async () => { + await seed(); + const { run } = cli({ 'a.js': '{{' }); + const onError = vi.fn(); + await uploadSourcemaps(opts({ run, onError, dryRun: true })); + expect(onError).not.toHaveBeenCalled(); + // The fake wrote anyway; the point is that nothing was snapshotted, so nothing was restored. + expect(await read('a.js')).toBe('{{'); + }); + + it('checks exactly the files a `files` run names, and restores them', async () => { + await seed(); + await writeFile(join(dir, 'other.js'), 'other();\n'); + const { run } = cli({ 'a.js': `a();\n{{${STAMP}`, 'other.js': 'CHANGED{{' }); + const errors: unknown[] = []; + await uploadSourcemaps({ + ...base, + outDir: dir, + run, + deleteMaps: false, + onError: (e) => errors.push(e), + files: { scripts: [join(dir, 'a.js')], maps: [join(dir, 'a.js.map')] }, + }); + expect(await read('a.js')).toBe('a();\n//# sourceMappingURL=a.js.map\n'); + // Not named, so not this build's: neither verified nor restored. + expect(await read('other.js')).toBe('CHANGED{{'); + expect(errors).toHaveLength(1); + }); + + it("a missing output directory is the CLI's error to report, not a verification crash", async () => { + const run = vi.fn(async (): Promise => ({ code: 0, stdout: '', stderr: '' })); + const onError = vi.fn(); + const result = await uploadSourcemaps({ + ...base, + outDir: join(dir, 'does-not-exist'), + run, + onError, + deleteMaps: false, + findSri: async () => [], + }); + expect(onError).not.toHaveBeenCalled(); + expect(result.uploaded).toBe(true); + }); + + it('the snapshot skips node_modules, dot-directories and non-stampable files', async () => { + await mkdir(join(dir, 'node_modules')); + await writeFile(join(dir, 'node_modules', 'dep.js'), 'dep();\n'); + await mkdir(join(dir, '.hidden')); + await writeFile(join(dir, '.hidden', 'c.js'), 'c();\n'); + await writeFile(join(dir, 'a.css'), 'a{}'); + const { run } = cli({}); + const onError = vi.fn(); + // Rewrites skipped files: were they snapshotted, the broken result would be flagged and restored. + const spy = vi.fn(async (args: string[]): Promise => { + if (args[1] === 'inject') { + await writeFile(join(dir, 'node_modules', 'dep.js'), '{{'); + await writeFile(join(dir, '.hidden', 'c.js'), '{{'); + } + return run(args); + }); + await uploadSourcemaps(opts({ run: spy, onError })); + expect(onError).not.toHaveBeenCalled(); + expect(await readFile(join(dir, 'node_modules', 'dep.js'), 'utf8')).toBe('{{'); + expect(await readFile(join(dir, '.hidden', 'c.js'), 'utf8')).toBe('{{'); + }); + + it('the snapshot stops at the depth limit, like the map walk (a mis-resolved root must not traverse a disk)', async () => { + let deep = dir; + for (let i = 0; i < 8; i++) { + deep = join(deep, `d${i}`); + await mkdir(deep); + } + await writeFile(join(deep, 'deep.js'), 'deep();\n'); + const spy = vi.fn(async (args: string[]): Promise => { + if (args[1] === 'inject') { + await writeFile(join(deep, 'deep.js'), '{{'); + } + return { code: 0, stdout: '', stderr: '' }; + }); + const onError = vi.fn(); + await uploadSourcemaps(opts({ run: spy, onError })); + expect(onError).not.toHaveBeenCalled(); // beyond the limit: never snapshotted, so never "restored" + expect(await readFile(join(deep, 'deep.js'), 'utf8')).toBe('{{'); + }); + + it('the pre-stamped path never runs inject (and so never restores anything)', async () => { + await seed(); + const { run } = cli({ 'a.js': '{{' }); + await uploadSourcemaps( + opts({ run, onError: () => undefined, preStamped: true, verifySri: async () => [] }), + ); + expect(run.mock.calls.every((c) => c[0][1] !== 'inject')).toBe(true); + expect(await read('a.js')).toBe('a();\n//# sourceMappingURL=a.js.map\n'); + }); +}); + +describe('maps are deleted only when they were actually keyed for upload', () => { + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-keyed-')); + }); + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + const ok = async (): Promise => ({ code: 0, stdout: '', stderr: '' }); + + it('an unstamped map is KEPT (the CLI skips it and exits 0), a stamped one is deleted, and it is said', async () => { + await writeFile(join(dir, 'keyed.js.map'), JSON.stringify({ debugId: ID })); + await writeFile(join(dir, 'snake.js.map'), JSON.stringify({ debug_id: ID })); + await writeFile(join(dir, 'unkeyed.js.map'), '{"version":3}'); + await writeFile(join(dir, 'broken.js.map'), 'not json'); + // A stylesheet map is never uploaded and is deleted regardless (it embeds the source too). + await writeFile(join(dir, 'style.css.map'), '{"version":3}'); + const errors: unknown[] = []; + const result = await uploadSourcemaps({ + ...base, + outDir: dir, + run: ok, + listMapFiles, + findSri: async () => [], + onError: (e) => errors.push(e), + }); + expect((await readdir(dir)).sort()).toEqual(['broken.js.map', 'unkeyed.js.map']); + expect(result.deletedMaps.map((p) => p.split('/').pop()).sort()).toEqual([ + 'keyed.js.map', + 'snake.js.map', + 'style.css.map', + ]); + expect(String(errors[0])).toContain('unkeyed.js.map'); + expect(String(errors[0])).toContain('broken.js.map'); + expect(String(errors[0])).toContain('not uploaded'); + expect(result.uploaded).toBe(true); + }); + + it('throws under failOnError (a map that was not uploaded is a failed upload), after deleting the rest', async () => { + await writeFile(join(dir, 'keyed.js.map'), JSON.stringify({ debugId: ID })); + await writeFile(join(dir, 'unkeyed.js.map'), '{}'); + await expect( + uploadSourcemaps({ + ...base, + outDir: dir, + run: ok, + listMapFiles, + findSri: async () => [], + failOnError: true, + }), + ).rejects.toThrow(/unkeyed\.js\.map/); + expect(await readdir(dir)).toEqual(['unkeyed.js.map']); + }); + + it('applies to a `files` run too, and stays quiet when everything was keyed', async () => { + const keyed = join(dir, 'a.js.map'); + const unkeyed = join(dir, 'b.js.map'); + await writeFile(keyed, JSON.stringify({ debugId: ID })); + await writeFile(unkeyed, '{}'); + const onError = vi.fn(); + const result = await uploadSourcemaps({ + ...base, + outDir: dir, + run: ok, + onError, + files: { scripts: [join(dir, 'a.js'), join(dir, 'b.js')], maps: [keyed, unkeyed] }, + }); + expect(await readdir(dir)).toEqual(['b.js.map']); + expect(result.deletedMaps).toEqual([keyed]); + expect(onError).toHaveBeenCalledOnce(); + + onError.mockClear(); + await writeFile(keyed, JSON.stringify({ debugId: ID })); + await rm(unkeyed); + await uploadSourcemaps({ + ...base, + outDir: dir, + run: ok, + onError, + files: { scripts: [join(dir, 'a.js')], maps: [keyed] }, + }); + expect(onError).not.toHaveBeenCalled(); + }); + + it('a map that vanished before the check is simply not there (nothing to keep or delete)', async () => { + const onError = vi.fn(); + const result = await uploadSourcemaps({ + ...base, + outDir: dir, + run: ok, + listMapFiles: async () => [join(dir, 'gone.js.map')], + findSri: async () => [], + onError, + }); + expect(result.deletedMaps).toEqual([]); + expect(onError).not.toHaveBeenCalled(); + }); + + it('deleteMaps: false never reads or reports a map', async () => { + await writeFile(join(dir, 'unkeyed.js.map'), '{}'); + const onError = vi.fn(); + await uploadSourcemaps({ + ...base, + outDir: dir, + run: ok, + listMapFiles, + findSri: async () => [], + deleteMaps: false, + onError, + }); + expect(onError).not.toHaveBeenCalled(); + expect(await readdir(dir)).toEqual(['unkeyed.js.map']); + }); + + it('a failed upload deletes nothing, keyed or not', async () => { + await writeFile(join(dir, 'keyed.js.map'), JSON.stringify({ debugId: ID })); + const run = vi.fn(async (args: string[]): Promise => { + if (args[0] === 'debug-files') { + throw new Error('exit 20'); + } + return ok(); + }); + const result = await uploadSourcemaps({ + ...base, + outDir: dir, + run, + listMapFiles, + findSri: async () => [], + onError: () => undefined, + }); + expect(result.uploaded).toBe(false); + expect(await readdir(dir)).toEqual(['keyed.js.map']); + }); +}); + +describe('an in-build stamp is checked again on disk, after the bundler wrote the output', () => { + const STAMP = `\n;1;\n//# debugId=${ID}\n`; + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-prestamped-')); + }); + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + const ok = vi.fn(async (): Promise => ({ code: 0, stdout: '', stderr: '' })); + const opts = (extra: object = {}) => ({ + ...base, + outDir: dir, + run: ok, + preStamped: true, + verifySri: async () => [], + ...extra, + }); + + it('reports a map that lost its debugId after the stamp (a bundler regenerated it), and keeps that map', async () => { + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=a.js.map\n${STAMP}`); + await writeFile(join(dir, 'a.js.map'), '{"version":3}'); + const errors: unknown[] = []; + const result = await uploadSourcemaps( + opts({ listMapFiles, onError: (e: unknown) => errors.push(e) }), + ); + expect(String(errors[0])).toContain('a.js.map'); + expect(String(errors[0])).toContain('after the build wrote it'); + // The run goes on (what is keyed is still uploaded), and the unkeyed map is NOT deleted. + expect(result.uploaded).toBe(true); + expect(await readdir(dir)).toContain('a.js.map'); + }); + + it('throws under failOnError, before uploading', async () => { + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=a.js.map\n${STAMP}`); + await writeFile(join(dir, 'a.js.map'), '{"version":3}'); + ok.mockClear(); + await expect(uploadSourcemaps(opts({ failOnError: true }))).rejects.toThrow(/a\.js\.map/); + expect(ok).not.toHaveBeenCalled(); + }); + + it('is quiet for a build whose bundles and maps agree', async () => { + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=a.js.map\n${STAMP}`); + await writeFile(join(dir, 'a.js.map'), JSON.stringify({ debugId: ID })); + const onError = vi.fn(); + await uploadSourcemaps(opts({ onError, deleteMaps: false })); + expect(onError).not.toHaveBeenCalled(); + }); + + it('is skipped on a dry run, where nothing was stamped', async () => { + await writeFile(join(dir, 'a.js'), 'a();\n'); + await writeFile(join(dir, 'a.js.map'), '{"version":3}'); + const onError = vi.fn(); + await uploadSourcemaps(opts({ onError, dryRun: true })); + expect(onError).not.toHaveBeenCalled(); + }); + + it('checks the named files of a `files` run only', async () => { + await writeFile(join(dir, 'a.js'), `a();\n${STAMP}`); + await writeFile(join(dir, 'a.js.map'), JSON.stringify({ debugId: ID })); + await writeFile(join(dir, 'foreign.js'), 'f();\n'); + await writeFile(join(dir, 'foreign.js.map'), '{"version":3}'); + const onError = vi.fn(); + await uploadSourcemaps( + opts({ + onError, + deleteMaps: false, + files: { + scripts: [join(dir, 'a.js')], + maps: [join(dir, 'a.js.map')], + }, + }), + ); + expect(onError).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/bundler-plugin-core/src/orchestrate.test.ts b/packages/bundler-plugin-core/src/orchestrate.test.ts index 1496b1d3b..8b955625c 100644 --- a/packages/bundler-plugin-core/src/orchestrate.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.test.ts @@ -20,6 +20,12 @@ function fakeRun() { return { run, calls }; } +/** Every candidate map counts as keyed: for tests about WHICH paths are deleted, with fake paths. */ +const allKeyed = async (maps: readonly string[]) => ({ + deletable: [...maps], + kept: [] as string[], +}); + const base = { outDir: '/build/dist', appToken: 'tok', @@ -218,6 +224,7 @@ describe('uploadSourcemaps', () => { ...base, run: runOrdered, deleteMapFiles, + partitionMaps: allKeyed, listMapFiles: async () => ['/build/dist/app.js.map'], }); // Only the maps that existed when the upload started (the snapshot) may be deleted. @@ -323,7 +330,10 @@ describe('deletes only the maps that existed when the upload started', () => { }); it('a map another build writes while the upload is in flight survives', async () => { - await writeFile(join(dir, 'first.js.map'), '{}'); + await writeFile( + join(dir, 'first.js.map'), + '{"debugId":"b039c7fb-d958-5fe6-b76f-136179e9a728"}', + ); const run = vi.fn(async (args: string[]): Promise => { if (args[0] === 'debug-files') { // The upload is in flight: a second build into the same directory writes its map now. @@ -787,6 +797,7 @@ describe("a run over the build's own files", () => { files: { scripts, maps }, run, deleteMapFiles, + partitionMaps: allKeyed, listMapFiles: list, }); expect(calls[0]?.args).toEqual(['sourcemaps', 'inject', ...scripts, ...maps]); @@ -807,6 +818,7 @@ describe("a run over the build's own files", () => { files: { scripts, maps, stylesheetMaps: css }, run, deleteMapFiles, + partitionMaps: allKeyed, }); expect(calls.flatMap((c) => c.args)).not.toContain('/b/a.css.map'); expect(deleteMapFiles).toHaveBeenCalledWith('/b', [...maps, ...css]); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 692eb9a8a..8701659b7 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -5,7 +5,16 @@ import { readdir, unlink } from 'node:fs/promises'; import { join } from 'node:path'; import { type RunBugseeCliOptions, runBugseeCli, type SpawnResult } from './run-cli'; import { findIntegrityMismatches, findSriProtectedScripts, type SriProtectedScript } from './sri'; +import { + MAX_WALK_DEPTH, + NEVER_WALK, + partitionByKeyed, + type SnapshotTarget, + snapshotStampFiles, + verifyAndRestore, +} from './stamp-files'; import type { VcsMetadata } from './vcs'; +import { formatIssues, verifyStampedPairs } from './verify-stamp'; /** The `runBugseeCli` shape, injectable for tests. */ export type RunFn = (args: string[], options: RunBugseeCliOptions) => Promise; @@ -55,6 +64,11 @@ export interface UploadSourcemapsOptions { }; /** Injectable `.map` lister for the delete snapshot of a directory run (default {@link listMapFiles}). */ listMapFiles?: (dir: string) => Promise; + /** + * Injectable keyed-map check for the deletion step (default {@link partitionByKeyed}): which of the + * candidate maps carry a debug-id, i.e. were actually keyed for upload, and so may be deleted. + */ + partitionMaps?: typeof partitionByKeyed; /** Injectable SRI scan (default {@link findSriProtectedScripts}). */ findSri?: (dir: string) => Promise; /** @@ -94,33 +108,6 @@ export interface UploadSourcemapsResult { vcs?: VcsMetadata; } -/** - * Directories never descended into when deleting `.map` files. - * - * A relative `output.file` resolves the output dir to `'.'` — `path.dirname('bundle.js') === '.'`, an - * entirely ordinary Rollup library config — so the walk started at the PROJECT ROOT. With no exclusions it - * unlinked dependency source maps under `node_modules/` (breaking debugging until a reinstall) and a - * developer's own authored maps under `src/`. Silent, unrecoverable loss in the working tree, on by default. - */ -const NEVER_WALK = new Set([ - 'node_modules', - 'src', - '.git', - '.next', - '.nuxt', - '.svelte-kit', - '.cache', - 'test', - 'tests', - '__tests__', -]); - -/** - * Depth limit for the walk. Build output is shallow (`dist/assets/chunk.js.map` is 2); an unbounded walk - * from a mis-resolved root could traverse an entire disk. - */ -const MAX_DELETE_DEPTH = 6; - /** Paths per CLI call: keeps a build with thousands of outputs under the OS command-line length limit. */ export const MAX_PATHS_PER_CALL = 200; function inBatches(items: readonly T[]): T[][] { @@ -133,7 +120,7 @@ function inBatches(items: readonly T[]): T[][] { /** Recursively list every build `*.map` under `dir`. */ export async function listMapFiles(dir: string, depth = 0): Promise { - if (depth > MAX_DELETE_DEPTH) { + if (depth > MAX_WALK_DEPTH) { return []; } const found: string[] = []; @@ -213,10 +200,11 @@ export async function uploadSourcemaps( const error = new Error( `${first.script} no longer matches the integrity hash ${first.html} pins` + (broken.length > 1 ? ` (and ${broken.length - 1} more)` : '') + - `, so the browser will refuse to run it. Bugsee stamps debug-IDs inside the build at ` + - `PROCESS_ASSETS_STAGE_DEV_TOOLING + 1, before webpack-subresource-integrity hashes at ` + - `PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE; a plugin that hashes EARLIER than that sees the ` + - `bytes before the stamp. Move that plugin's hashing later, or disable this plugin for this build.`, + `, so the browser will refuse to run it. Bugsee stamps debug-IDs inside the build, before the ` + + `bundler writes its output (webpack/Rspack: PROCESS_ASSETS_STAGE_DEV_TOOLING + 1; Vite/Rollup: ` + + `generateBundle, order 'pre'). A plugin that hashes EARLIER than that sees the bytes before the ` + + `stamp, and one that rewrites the file AFTER it changes bytes that were already hashed. Run the ` + + `hashing after this plugin (list this plugin first), or disable this plugin for this build.`, ); if (options.failOnError === true) { throw error; @@ -226,6 +214,28 @@ export async function uploadSourcemaps( // upload was skipped; here it was not. (options.onError ?? ((e: unknown) => console.warn(`[bugsee] ${String(e)}`)))(error); } + // 0''. The same stamp, as it is on disk after the bundler wrote the output. A later step can rewrite a + // chunk or REGENERATE its map after the in-build stamp (Vite does, for dynamic-import preload + // markers), and a bundle that looks stamped with a map that no longer carries its id cannot be + // symbolicated. Nothing to restore here (no originals), so it is reported; the keyed check at + // deletion keeps any map that lost its id. Not on a dry run: nothing was stamped. + if (!dryRun) { + const written = await snapshotStampFiles( + files === undefined ? { dir: outDir } : { files: [...files.scripts, ...files.maps] }, + ); + const lost = verifyStampedPairs(written); + if (lost.length > 0) { + const failure = new Error( + `the debug-IDs stamped inside the build did not survive intact to disk: they changed after the build wrote it, ` + + `or something rewrote a bundle or its map after Bugsee stamped it (${formatIssues(lost)}). ` + + `Affected maps cannot be matched to their bundle.`, + ); + if (options.failOnError === true) { + throw failure; + } + onError(failure); + } + } } else { // 0. Refuse outright if the build pins its own script hashes. `sourcemaps inject` appends bytes // to every emitted `.js`, and a hash computed during emit is already in the HTML — measured on @@ -241,11 +251,20 @@ export async function uploadSourcemaps( `hash of ${first.script}` + (pinned.length > 1 ? ` (and ${pinned.length - 1} more)` : '') + `. Injecting a debug-ID rewrites that file, so the browser would refuse to run it and the ` + - `page would load nothing. Source maps were NOT uploaded. See ` + + `page would load nothing. Source maps were NOT uploaded. Bundlers that let this plugin stamp ` + + `inside the build (webpack 5, Rspack, Vite, Rollup) avoid this; if one did and this still fired, its ` + + `in-build stamp failed (see the earlier warning). For esbuild or the standalone CLI, run ` + + `\`bugsee-cli sourcemaps inject\` BEFORE the step that computes the hashes. See ` + `https://github.com/bugsee/bugsee-javascript/blob/main/docs/design/source-maps.md#subresource-integrity`, ); } + // 0b. Take the originals, so a stamp that does not verify can be undone (see below). Not on a dry run: + // inject writes nothing, so there is nothing to undo. + const target: SnapshotTarget = + files === undefined ? { dir: outDir } : { files: [...files.scripts, ...files.maps] }; + const original = dryRun ? undefined : await snapshotStampFiles(target); + // 1. Inject debug-IDs (rewrites the built .js + .map in place). if (files === undefined) { await run(['sourcemaps', 'inject', outDir, ...dryFlag], cliOptions); @@ -256,6 +275,25 @@ export async function uploadSourcemaps( await run(['sourcemaps', 'inject', ...batch, ...dryFlag], cliOptions); } } + + // 1b. VERIFY what inject wrote (verify-stamp.ts): every changed bundle still parses and keeps its map + // pointer, the bytes are the original plus an appended stamp, every map is JSON whose debugId + // matches its bundle. A failure puts the ORIGINAL bytes back (bundle and map as a pair) and is + // reported — a script that no longer parses is a blank page, and shipping it silently is the one + // outcome this must rule out. What did verify stays stamped and is uploaded below; the restored + // maps carry no debugId, so the keyed check at deletion keeps them. + if (original !== undefined) { + const { issues, restored } = await verifyAndRestore(original); + if (issues.length > 0) { + const failure = new Error( + `the debug-ID stamp did not verify, so ${restored.length} file(s) were restored to the bundler's original bytes (${formatIssues(issues)})`, + ); + if (options.failOnError === true) { + throw failure; + } + onError(failure); + } + } } // 2. Upload the maps, keyed by the injected debug-ID (+ version/build metadata). @@ -327,12 +365,26 @@ export async function uploadSourcemaps( onError(failure); return { injected: true, uploaded: true, deletedMaps: [], ...vcsEcho }; } - const deletedMaps = deleteMaps - ? await (options.deleteMapFiles ?? defaultDeleteMapFiles)( - outDir, - files === undefined ? snapshot : [...files.maps, ...(files.stylesheetMaps ?? [])], - ) - : []; + // "The upload command exited 0" is not "this map was uploaded": the CLI skips a map with no debug-id. + // Only a map that carries one was keyed for upload, so only those are deleted (stamp-files.ts). + let deletedMaps: string[] = []; + if (deleteMaps) { + const { deletable, kept } = await (options.partitionMaps ?? partitionByKeyed)( + files === undefined + ? (snapshot as string[]) + : [...files.maps, ...(files.stylesheetMaps ?? [])], + ); + deletedMaps = await (options.deleteMapFiles ?? defaultDeleteMapFiles)(outDir, deletable); + if (kept.length > 0) { + const failure = new Error( + `${kept.length} source map(s) carry no debug-ID, so they were not uploaded and were left on disk: ${kept.join(', ')}`, + ); + if (options.failOnError === true) { + throw failure; + } + onError(failure); + } + } return { injected: true, uploaded: true, deletedMaps, ...vcsEcho }; } catch (error) { // A telemetry side effect must not break a production deploy. Reported, never swallowed; diff --git a/packages/bundler-plugin-core/src/stamp-assets.test.ts b/packages/bundler-plugin-core/src/stamp-assets.test.ts index 646205fe2..b16b4593e 100644 --- a/packages/bundler-plugin-core/src/stamp-assets.test.ts +++ b/packages/bundler-plugin-core/src/stamp-assets.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it, vi } from 'vitest'; import { readDebugId } from './debug-ids'; -import { type AssetStore, stampAssets } from './stamp-assets'; +import { + type AssetStore, + rollupAssetStore, + rollupUnstampableMaps, + StampVerificationError, + stampAssets, +} from './stamp-assets'; /** An in-memory stand-in for a webpack compilation's asset table. */ function memoryStore(initial: Record): AssetStore & { @@ -75,6 +81,8 @@ describe('stampAssets — with the real bugsee-cli', () => { }); }); +const STAMP_COMMENT = '//# debugId=b039c7fb-d958-5fe6-b76f-136179e9a728'; + describe('stampAssets — the round trip', () => { const fakeInject = (edit: (path: string, content: string) => string | undefined) => async (args: string[]) => { @@ -162,7 +170,9 @@ describe('stampAssets — the round trip', () => { // map information it carries survive untouched. const store = memoryStore({ 'a.js': 'x()\n', 'b.js': 'y()\n' }); await stampAssets(store, { - run: fakeInject((path, content) => (path === 'a.js' ? `${content}//# stamped\n` : undefined)), + run: fakeInject((path, content) => + path === 'a.js' ? `${content};1;\n${STAMP_COMMENT}\n` : undefined, + ), }); expect(store.updates).toEqual(['a.js']); }); @@ -225,3 +235,228 @@ describe('stampAssets — the round trip', () => { await expect(access(staged)).rejects.toMatchObject({ code: 'ENOENT' }); }); }); + +describe('stampAssets — verifying the stamp before it is written back', () => { + const inject = + (edit: (path: string, content: string) => string | undefined) => async (args: string[]) => { + const { readdir, readFile, writeFile } = await import('node:fs/promises'); + const { join } = await import('node:path'); + const root = args[2] as string; + for (const entry of await readdir(root, { withFileTypes: true })) { + const next = edit(entry.name, await readFile(join(root, entry.name), 'utf8')); + if (next !== undefined) { + await writeFile(join(root, entry.name), next); + } + } + return { code: 0, stdout: '', stderr: '' }; + }; + + it('writes NOTHING back when any stamped bundle no longer parses (all or nothing)', async () => { + const store = memoryStore({ 'a.js': 'a();\n', 'b.js': 'b();\n' }); + await expect( + stampAssets(store, { + run: inject((path, content) => + path === 'a.js' + ? `${content};1;\n${STAMP_COMMENT}\n` + : `${content}{{\n${STAMP_COMMENT}\n`, + ), + }), + ).rejects.toThrow(StampVerificationError); + expect(store.updates).toEqual([]); + expect(store.assets.get('a.js')).toBe('a();\n'); + }); + + it('names the asset and the reason, and keeps every issue on the error', async () => { + const store = memoryStore({ 'a.js': 'a();\n' }); + const error = (await stampAssets(store, { run: inject((_p, c) => `${c}{{\n`) }).catch( + (e: unknown) => e, + )) as StampVerificationError; + expect(error).toBeInstanceOf(StampVerificationError); + expect(error.message).toContain('a.js'); + expect(error.message).toContain('no longer parses'); + expect(error.issues.map((i) => i.name)).toContain('a.js'); + expect(error.name).toBe('StampVerificationError'); + }); + + it('flags a stamp whose bundle and map disagree', async () => { + const store = memoryStore({ + 'a.js': 'a();\n//# sourceMappingURL=a.js.map\n', + 'a.js.map': '{"version":3,"sources":[],"names":[],"mappings":""}', + }); + await expect( + stampAssets(store, { + run: inject((path, content) => + path === 'a.js' + ? `${content};1;\n${STAMP_COMMENT}\n` + : content.replace(/\}$/, ',"debugId":"4adb7053-e754-594c-96b5-09c18263b153"}'), + ), + }), + ).rejects.toThrow(/does not match/); + expect(store.updates).toEqual([]); + }); + + it('a dry run is not verified (it writes nothing, whatever it finds)', async () => { + const store = memoryStore({ 'a.js': 'a();\n' }); + await expect( + stampAssets(store, { dryRun: true, run: inject((_p, c) => `${c}{{\n`) }), + ).resolves.toEqual({ stamped: [] }); + }); + + it('uses an injected parser', async () => { + const store = memoryStore({ 'a.js': 'a();\n' }); + const parse = vi.fn(() => true); + await stampAssets(store, { + parse, + run: inject((_p, c) => `${c};1;\n${STAMP_COMMENT}\n`), + }); + expect(parse).toHaveBeenCalled(); + }); +}); + +describe('rollupAssetStore — a Rollup / Vite output bundle as an asset table', () => { + const chunk = (fileName: string, code: string, extra: object = {}) => ({ + type: 'chunk' as const, + fileName, + code, + map: { version: 3 }, + ...extra, + }); + const asset = (fileName: string, source: string | Uint8Array) => ({ + type: 'asset' as const, + fileName, + source, + }); + + it('lists chunks and the map / script assets, and nothing else', () => { + const store = rollupAssetStore({ + 'a.js': chunk('a.js', 'x'), + 'a.js.map': asset('a.js.map', '{}'), + 'index.html': asset('index.html', '

'), + 'vendor.js': asset('vendor.js', 'v'), + 'logo.png': asset('logo.png', new Uint8Array([1])), + }); + expect(store.names().sort()).toEqual(['a.js', 'a.js.map', 'vendor.js']); + }); + + it('reads a chunk as its code and an asset as its source, string or bytes', () => { + const store = rollupAssetStore({ + 'a.js': chunk('a.js', 'héllo'), + 'a.js.map': asset('a.js.map', '{"a":1}'), + 'b.js.map': asset('b.js.map', new Uint8Array(Buffer.from('{"b":2}'))), + }); + expect(store.read('a.js').toString('utf8')).toBe('héllo'); + expect(store.read('a.js.map').toString('utf8')).toBe('{"a":1}'); + expect(store.read('b.js.map').toString('utf8')).toBe('{"b":2}'); + }); + + it('writes a chunk back to .code, and an asset back in the type it had', () => { + const bundle = { + 'a.js': chunk('a.js', 'x'), + 'a.js.map': asset('a.js.map', '{}'), + 'b.js.map': asset('b.js.map', new Uint8Array([1])), + }; + const store = rollupAssetStore(bundle); + store.update('a.js', Buffer.from('stamped ✓')); + store.update('a.js.map', Buffer.from('{"debugId":"x"}')); + store.update('b.js.map', Buffer.from('bytes')); + expect(bundle['a.js'].code).toBe('stamped ✓'); + expect(bundle['a.js.map'].source).toBe('{"debugId":"x"}'); + expect(bundle['b.js.map'].source).toBeInstanceOf(Uint8Array); + expect(Buffer.from(bundle['b.js.map'].source as Uint8Array).toString()).toBe('bytes'); + }); + + it('carries the stamped ids onto chunk.map too, so a bundler that rebuilds the map from it keeps them', () => { + // Vite rewrites a chunk with dynamic imports AFTER generateBundle hooks and regenerates its `.map` + // asset from `chunk.map`, keeping only what `chunk.map` carries (its `debugId`). Measured, Vite 7.3/8.3. + const map: Record = { version: 3 }; + const bundle = { + 'a.js': chunk('a.js', 'x', { map }), + 'a.js.map': asset('a.js.map', '{}'), + 'b.js': chunk('b.js', 'y', { map: null }), + 'b.js.map': asset('b.js.map', '{}'), + 'c.js': chunk('c.js', 'z', { map: { version: 3 }, sourcemapFileName: 'maps/c.map' }), + 'maps/c.map': asset('maps/c.map', '{}'), + }; + const store = rollupAssetStore(bundle); + store.update('a.js.map', Buffer.from('{"debugId":"ID-1","debug_id":"ID-1"}')); + store.update('b.js.map', Buffer.from('{"debugId":"ID-2"}')); + store.update('maps/c.map', Buffer.from('{"debug_id":"ID-3"}')); + expect(map).toEqual({ version: 3, debugId: 'ID-1', debug_id: 'ID-1' }); + expect(bundle['b.js'].map).toBeNull(); // nothing to carry onto + expect(bundle['c.js'].map).toEqual({ version: 3, debug_id: 'ID-3', debugId: 'ID-3' }); + }); + + it('leaves chunk.map alone when the new map is not JSON or has no id', () => { + const map: Record = { version: 3 }; + const bundle = { 'a.js': chunk('a.js', 'x', { map }), 'a.js.map': asset('a.js.map', '{}') }; + const store = rollupAssetStore(bundle); + store.update('a.js.map', Buffer.from('not json')); + store.update('a.js.map', Buffer.from('{"version":3}')); + store.update('a.js.map', Buffer.from('[1]')); + expect(map).toEqual({ version: 3 }); + }); + + it('reads an unknown name as empty rather than throwing', () => { + expect(rollupAssetStore({}).read('nope.js').length).toBe(0); + }); + + it('stamps a Rollup bundle through the real bugsee-cli, map included', async () => { + const bundle = { + 'a.js': chunk('a.js', 'console.log(1);\n//# sourceMappingURL=a.js.map'), + 'a.js.map': asset( + 'a.js.map', + '{"version":3,"file":"a.js","sources":["a.ts"],"names":[],"mappings":"AAAA"}', + ), + }; + const result = await stampAssets(rollupAssetStore(bundle)); + const id = readDebugId(bundle['a.js'].code); + expect(id).toMatch(/^[0-9a-f-]{36}$/); + expect(JSON.parse(bundle['a.js.map'].source as string).debugId).toBe(id); + expect(result.stamped).toEqual(['a.js']); + }); +}); + +describe('rollupUnstampableMaps — chunks whose map cannot be stamped in memory', () => { + it('is empty when every mapped chunk has its map as a bundle asset', () => { + expect( + rollupUnstampableMaps({ + 'a.js': { type: 'chunk', fileName: 'a.js', code: '', map: {} }, + 'a.js.map': { type: 'asset', fileName: 'a.js.map', source: '{}' }, + 'b.js': { type: 'chunk', fileName: 'b.js', code: '', map: null }, + }), + ).toEqual([]); + }); + + it('names a chunk that has a map but no map asset (older Rollup, inline maps)', () => { + expect( + rollupUnstampableMaps({ + 'a.js': { type: 'chunk', fileName: 'a.js', code: '', map: {} }, + 'b.js': { type: 'chunk', fileName: 'b.js', code: '', map: {} }, + 'b.js.map': { type: 'asset', fileName: 'b.js.map', source: '{}' }, + }), + ).toEqual(['a.js']); + }); + + it('honours a custom sourcemapFileName', () => { + expect( + rollupUnstampableMaps({ + 'a.js': { + type: 'chunk', + fileName: 'a.js', + code: '', + map: {}, + sourcemapFileName: 'maps/a.map', + }, + 'maps/a.map': { type: 'asset', fileName: 'maps/a.map', source: '{}' }, + }), + ).toEqual([]); + }); + + it('only considers script chunks', () => { + expect( + rollupUnstampableMaps({ + 'a.css': { type: 'chunk', fileName: 'a.css', code: '', map: {} }, + }), + ).toEqual([]); + }); +}); diff --git a/packages/bundler-plugin-core/src/stamp-assets.ts b/packages/bundler-plugin-core/src/stamp-assets.ts index 791732ca6..f0ac4a033 100644 --- a/packages/bundler-plugin-core/src/stamp-assets.ts +++ b/packages/bundler-plugin-core/src/stamp-assets.ts @@ -18,6 +18,7 @@ import { tmpdir } from 'node:os'; import { dirname, isAbsolute, join, normalize, sep } from 'node:path'; import type { RunFn } from './orchestrate'; import { runBugseeCli } from './run-cli'; +import { formatIssues, type StampIssue, verifyStamp } from './verify-stamp'; /** The slice of a compilation's asset table this needs — no bundler types in the core. */ export interface AssetStore { @@ -30,6 +31,21 @@ export interface StampAssetsOptions { /** Preview only: run `inject --dry-run` and write nothing back. */ dryRun?: boolean; run?: RunFn; + /** Injectable JavaScript parser for the post-stamp check (default: acorn, see verify-stamp.ts). */ + parse?: (code: string) => boolean; +} + +/** + * The stamp did not verify (verify-stamp.ts): something inject produced is not safe to ship. Nothing was + * written back. Carries every issue, so a caller can say exactly which asset and why. + */ +export class StampVerificationError extends Error { + readonly issues: StampIssue[]; + constructor(issues: StampIssue[]) { + super(`the debug-ID stamp did not verify, so none of it was applied (${formatIssues(issues)})`); + this.name = 'StampVerificationError'; + this.issues = issues; + } } export interface StampAssetsResult { @@ -84,13 +100,23 @@ export async function stampAssets( if (dryRun) { return { stamped: [] }; } + // Read everything back and verify BEFORE writing anything: a bad stamp must leave the build exactly + // as the bundler produced it, which an interleaved read-and-update could not promise. + const after = new Map(); + for (const name of staged) { + after.set(name, await readFile(join(root, name))); + } + const issues = verifyStamp(before, after, options.parse); + if (issues.length > 0) { + throw new StampVerificationError(issues); + } const stamped: string[] = []; for (const name of staged) { - const after = await readFile(join(root, name)); + const afterBytes = after.get(name) as Buffer; // Only what inject actually changed goes back. An untouched asset keeps its original Source // object, so webpack's caching and any map information it carries are not disturbed. - if (!after.equals(before.get(name) as Buffer)) { - store.update(name, after); + if (!afterBytes.equals(before.get(name) as Buffer)) { + store.update(name, afterBytes); if (BUNDLE.test(name)) { stamped.push(name); } @@ -101,3 +127,102 @@ export async function stampAssets( await rm(root, { recursive: true, force: true }); } } + +/** A Rollup / Vite / Rolldown output chunk, as far as stamping reads or writes it. */ +interface RollupChunkLike { + type: 'chunk'; + fileName: string; + code: string; + map?: unknown; + sourcemapFileName?: string | null; +} + +/** An emitted asset (a `.map` file, a copied script, an image, the HTML). */ +interface RollupAssetLike { + type: 'asset'; + fileName: string; + source: string | Uint8Array; +} + +/** The `bundle` object `generateBundle` receives, keyed by output file name. */ +export type RollupBundleLike = Record; + +/** + * A Rollup / Vite output bundle as an {@link AssetStore}, so `generateBundle` can stamp what is about to + * be written. Chunks are read and written through `.code`; the `.map` files are bundle ASSETS (measured: + * Rollup 4.65, Vite 7.3 and Vite 8.3/Rolldown all list `.map` in the bundle, and their + * `source` is what reaches disk — `chunk.map` is NOT written back, so editing it would silently do + * nothing). An asset keeps the type it had (string or bytes). + */ +export function rollupAssetStore(bundle: RollupBundleLike): AssetStore { + return { + names: () => Object.keys(bundle).filter((name) => STAGED.test(name)), + read: (name) => { + const entry = bundle[name]; + if (entry === undefined) { + return Buffer.alloc(0); + } + const content = entry.type === 'chunk' ? entry.code : entry.source; + return typeof content === 'string' ? Buffer.from(content, 'utf8') : Buffer.from(content); + }, + update: (name, content) => { + const entry = bundle[name] as RollupChunkLike | RollupAssetLike; + if (entry.type === 'chunk') { + entry.code = content.toString('utf8'); + } else { + entry.source = + typeof entry.source === 'string' ? content.toString('utf8') : new Uint8Array(content); + carryDebugId(bundle, name, content); + } + }, + }; +} + +/** + * Put a stamped map's debug-id on the `chunk.map` object that belongs to it. Vite rewrites a chunk with + * dynamic imports after the `generateBundle` hooks (its preload-marker substitution) and REGENERATES the + * `.map` asset from `chunk.map`, keeping only what that object carries — its `debugId` — so an id that + * lives only in the asset would be silently dropped (measured, Vite 7.3 and 8.3). + */ +function carryDebugId(bundle: RollupBundleLike, mapName: string, content: Buffer): void { + let parsed: { debugId?: unknown; debug_id?: unknown }; + try { + parsed = JSON.parse(content.toString('utf8')) as typeof parsed; + } catch { + return; + } + const id = [parsed?.debugId, parsed?.debug_id].find((v) => typeof v === 'string' && v !== ''); + if (id === undefined) { + return; + } + for (const [name, entry] of Object.entries(bundle)) { + if ( + entry.type === 'chunk' && + (entry.sourcemapFileName ?? `${name}.map`) === mapName && + typeof entry.map === 'object' && + entry.map !== null + ) { + Object.assign(entry.map, { debugId: id, debug_id: id }); + } + } +} + +/** + * The script chunks that HAVE a source map (`chunk.map`) but whose map is not a bundle asset, so stamping + * the code in memory could not stamp the map that reaches disk. An older Rollup that writes the `.map` file + * from `chunk.map` at write time, or `sourcemap: 'inline'`. Such a build cannot be stamped in the + * build; it falls back to stamping after emit, exactly as before. + */ +export function rollupUnstampableMaps(bundle: RollupBundleLike): string[] { + const names: string[] = []; + for (const [name, entry] of Object.entries(bundle)) { + if (entry.type !== 'chunk' || !BUNDLE.test(name) || !entry.map) { + continue; + } + const mapName = entry.sourcemapFileName ?? `${name}.map`; + if (bundle[mapName] === undefined) { + names.push(name); + } + } + return names.sort(); +} diff --git a/packages/bundler-plugin-core/src/stamp-files.ts b/packages/bundler-plugin-core/src/stamp-files.ts new file mode 100644 index 000000000..8a5d690a4 --- /dev/null +++ b/packages/bundler-plugin-core/src/stamp-files.ts @@ -0,0 +1,166 @@ +// The on-disk side of stamp verification and of map deletion (orchestrate.ts drives it). +// +// The in-build path verifies in memory (stamp-assets.ts). The POST-EMIT path lets `bugsee-cli` rewrite the +// output in place, so to be able to say "that stamp is not safe, put the original back" the original bytes +// have to be taken BEFORE the rewrite. That is what the snapshot is for: it holds the build's own scripts +// and maps (bounded by the same walk rules the map deletion uses), and nothing else. +import type { Dirent } from 'node:fs'; +import { readdir, readFile, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { type StampIssue, verifyStamp } from './verify-stamp'; + +/** + * Directories never descended into when walking build output. + * + * A relative `output.file` resolves the output dir to `'.'` — `path.dirname('bundle.js') === '.'`, an + * entirely ordinary Rollup library config — so a walk started at the PROJECT ROOT. With no exclusions the + * map deletion unlinked dependency source maps under `node_modules/` and a developer's own authored maps + * under `src/`: silent, unrecoverable loss in the working tree. The same walk now also feeds the + * pre-stamp snapshot, and a restore writes files, so it must have the same fence. + */ +export const NEVER_WALK = new Set([ + 'node_modules', + 'src', + '.git', + '.next', + '.nuxt', + '.svelte-kit', + '.cache', + 'test', + 'tests', + '__tests__', +]); + +/** + * Depth limit for the walk. Build output is shallow (`dist/assets/chunk.js.map` is 2); an unbounded walk + * from a mis-resolved root could traverse an entire disk. + */ +export const MAX_WALK_DEPTH = 6; + +/** What inject can change: the scripts it stamps and the maps it pairs with them. */ +const STAMPABLE = /\.([cm]?js|map)$/; + +/** Every stampable file under `dir`. An unreadable directory contributes nothing (never throws). */ +async function walkStampable(dir: string, depth = 0): Promise { + if (depth > MAX_WALK_DEPTH) { + return []; + } + let entries: Dirent[]; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch { + // Not this layer's error to raise: the CLI reports a missing output directory properly, and + // throwing here would replace that with a worse message. + return []; + } + const found: string[] = []; + for (const entry of entries) { + const full = join(dir, entry.name); + if (entry.isDirectory()) { + if (!NEVER_WALK.has(entry.name) && !entry.name.startsWith('.')) { + found.push(...(await walkStampable(full, depth + 1))); + } + } else if (entry.isFile() && STAMPABLE.test(entry.name)) { + found.push(full); + } + } + return found; +} + +/** Where to look: a directory (walked), or exactly the files a build reported as its own. */ +export type SnapshotTarget = { dir: string } | { files: readonly string[] }; + +/** The bytes of every stampable file in `target`, keyed by absolute path. A file that is gone is skipped. */ +export async function snapshotStampFiles(target: SnapshotTarget): Promise> { + const paths = 'dir' in target ? await walkStampable(target.dir) : target.files; + const snapshot = new Map(); + for (const path of paths) { + try { + snapshot.set(path, await readFile(path)); + } catch { + // Gone between listing and reading (a concurrent build's cleanup): nothing to verify or restore. + } + } + return snapshot; +} + +/** The map of a bundle, or the bundle of a map. */ +const partner = (path: string): string => + path.endsWith('.map') ? path.slice(0, -'.map'.length) : `${path}.map`; + +/** + * Verify what inject left on disk against the `before` snapshot, and put the ORIGINAL bytes back for every + * file that failed — together with its partner (a bundle and its map are restored as a pair, so a build is + * never left half-stamped: a bundle with an id and a map without one is worse than neither). + * + * Returns the issues (empty when the stamp is sound) and the paths restored. + */ +export async function verifyAndRestore( + before: ReadonlyMap, + parser?: (code: string) => boolean, +): Promise<{ issues: StampIssue[]; restored: string[] }> { + const after = new Map(); + for (const path of before.keys()) { + try { + after.set(path, await readFile(path)); + } catch { + // Deleted meanwhile: not part of the comparison. + } + } + const issues = verifyStamp(before, after, parser); + const toRestore = new Set(); + for (const { name } of issues) { + toRestore.add(name); + if (before.has(partner(name))) { + toRestore.add(partner(name)); + } + } + const restored: string[] = []; + for (const path of [...toRestore].sort()) { + await writeFile(path, before.get(path) as Buffer); + restored.push(path); + } + return { issues, restored }; +} + +/** Script maps are the ones inject keys and the CLI uploads; a stylesheet map is neither. */ +const SCRIPT_MAP = /\.[cm]?js\.map$/; + +/** + * Split `maps` into those that may be deleted after an upload and those that must be kept. + * + * `debug-files upload` skips a map with no debug-id and still exits 0 (it counts it as `unkeyed`), so "the + * upload command succeeded" does NOT mean "this map was uploaded". Deleting on that evidence destroys the + * only copy of a mapping whose symbols never left the build machine. A script map is therefore deletable + * only if it carries a `debugId`/`debug_id` — what makes it keyed. Anything else (a stylesheet map, which + * is never uploaded and embeds the source, so privacy still wants it gone) is deletable as before. A map + * that cannot be read or parsed is kept: not confirmed means not deleted. + */ +export async function partitionByKeyed( + maps: readonly string[], +): Promise<{ deletable: string[]; kept: string[] }> { + const deletable: string[] = []; + const kept: string[] = []; + for (const path of maps) { + if (!SCRIPT_MAP.test(path)) { + deletable.push(path); + continue; + } + let text: string; + try { + text = await readFile(path, 'utf8'); + } catch { + // Already gone: nothing to delete and nothing to keep. + continue; + } + let keyed = false; + try { + const parsed = JSON.parse(text) as { debugId?: unknown; debug_id?: unknown } | null; + keyed = [parsed?.debugId, parsed?.debug_id].some((id) => typeof id === 'string' && id !== ''); + } catch { + // Not JSON: cannot have been keyed. + } + (keyed ? deletable : kept).push(path); + } + return { deletable, kept }; +} diff --git a/packages/bundler-plugin-core/src/verify-stamp.test.ts b/packages/bundler-plugin-core/src/verify-stamp.test.ts new file mode 100644 index 000000000..a8b4752c2 --- /dev/null +++ b/packages/bundler-plugin-core/src/verify-stamp.test.ts @@ -0,0 +1,333 @@ +import { describe, expect, it } from 'vitest'; +import { formatIssues, parseScript, verifyStamp, verifyStampedPairs } from './verify-stamp'; + +const ID = 'b039c7fb-d958-5fe6-b76f-136179e9a728'; +const OTHER_ID = '4adb7053-e754-594c-96b5-09c18263b153'; +const STUB = + '\n;!function(){try{var e="undefined"!=typeof window?window:{},n=(new e.Error).stack;n&&(e._bugseeDebugIds=e._bugseeDebugIds||{},e._bugseeDebugIds[n]="' + + ID + + '")}catch(e){}}();\n//# debugId=' + + ID + + '\n'; + +const buf = (text: string): Buffer => Buffer.from(text); +const mapJson = (extra: object = {}): string => + JSON.stringify({ version: 3, sources: ['a.ts'], names: [], mappings: 'AAAA', ...extra }); +const stampedMap = (id = ID): string => mapJson({ debug_id: id, debugId: id }); + +/** One bundle + its map, before and after a faithful stamp. */ +function faithful(): { before: Map; after: Map } { + const code = 'console.log(1);\n//# sourceMappingURL=a.js.map\n'; + return { + before: new Map([ + ['a.js', buf(code)], + ['a.js.map', buf(mapJson())], + ]), + after: new Map([ + ['a.js', buf(code + STUB)], + ['a.js.map', buf(stampedMap())], + ]), + }; +} + +describe('verifyStamp', () => { + it('accepts exactly what `sourcemaps inject` produces', () => { + const { before, after } = faithful(); + expect(verifyStamp(before, after)).toEqual([]); + }); + + it('ignores assets inject did not change (even a bundle that does not parse)', () => { + const bytes = buf('this is not ( javascript'); + expect(verifyStamp(new Map([['x.js', bytes]]), new Map([['x.js', bytes]]))).toEqual([]); + }); + + describe('(i) a stamped bundle still parses', () => { + it('flags a bundle the stamp broke', () => { + const { before, after } = faithful(); + after.set('a.js', buf(`console.log(1);\n//# sourceMappingURL=a.js.map\n${STUB} {{`)); + const issues = verifyStamp(before, after); + expect(issues.map((i) => i.name)).toContain('a.js'); + expect(issues.find((i) => i.name === 'a.js')?.reason).toMatch(/no longer parses/); + }); + + it('does not blame the stamp for a bundle the parser could not read to begin with', () => { + const original = 'const x = 1 +;\n'; // already invalid + const issues = verifyStamp( + new Map([['a.js', buf(original)]]), + new Map([['a.js', buf(original + STUB)]]), + ); + expect(issues).toEqual([]); + }); + + it('parses ES modules, CommonJS and hashbang scripts', () => { + expect(parseScript('import a from "a"; export default a;')).toBe(true); + expect(parseScript('module.exports = 1; return 2;')).toBe(true); + expect(parseScript('#!/usr/bin/env node\nawait 1;')).toBe(true); + expect(parseScript('with (x) { y }')).toBe(true); // sloppy script, not a module + expect(parseScript('let = ;')).toBe(false); + }); + + it('uses an injected parser', () => { + const { before, after } = faithful(); + const seen: string[] = []; + const issues = verifyStamp(before, after, (code) => { + seen.push(code); + return false; + }); + // Parsed once after, and (because that failed) once before to see who is to blame: it failed too. + expect(seen).toHaveLength(2); + expect(issues).toEqual([]); + }); + }); + + describe('(ii) the sourceMappingURL comment', () => { + it('flags a lost sourceMappingURL comment', () => { + const { before, after } = faithful(); + after.set('a.js', buf(`console.log(1);\n${STUB}`)); + expect(verifyStamp(before, after).some((i) => /sourceMappingURL/.test(i.reason))).toBe(true); + }); + + it('flags a changed sourceMappingURL target', () => { + const { before, after } = faithful(); + after.set('a.js', buf(`console.log(1);\n//# sourceMappingURL=b.js.map\n${STUB}`)); + expect(verifyStamp(before, after).some((i) => /sourceMappingURL/.test(i.reason))).toBe(true); + }); + + it('flags a second sourceMappingURL comment sneaking in after the original', () => { + const { before, after } = faithful(); + after.set( + 'a.js', + buf(`console.log(1);\n//# sourceMappingURL=a.js.map\n${STUB}//# sourceMappingURL=z.map\n`), + ); + expect(verifyStamp(before, after).some((i) => /sourceMappingURL/.test(i.reason))).toBe(true); + }); + + it('is not required of a bundle that never had one', () => { + const code = 'console.log(1);\n'; + const issues = verifyStamp( + new Map([['a.js', buf(code)]]), + new Map([['a.js', buf(code + STUB)]]), + ); + expect(issues).toEqual([]); + }); + + it('does not object to a pointer appearing where there was none (only a lost or changed one is a problem)', () => { + const code = 'console.log(1);\n'; + expect( + verifyStamp( + new Map([['a.js', buf(code)]]), + new Map([['a.js', buf(`${code}${STUB}//# sourceMappingURL=a.js.map\n`)]]), + ), + ).toEqual([]); + }); + + it('accepts the legacy //@ spelling and compares by value', () => { + const code = 'console.log(1);\n//@ sourceMappingURL=a.js.map\n'; + expect( + verifyStamp(new Map([['a.js', buf(code)]]), new Map([['a.js', buf(code + STUB)]])), + ).toEqual([]); + }); + }); + + describe('(iii) the map', () => { + it('flags a map that is not valid JSON', () => { + const { before, after } = faithful(); + after.set('a.js.map', buf('{"version":3,')); + const issue = verifyStamp(before, after).find((i) => i.name === 'a.js.map'); + expect(issue?.reason).toMatch(/not valid JSON/); + }); + + it('flags a map that is not an object', () => { + const { before, after } = faithful(); + after.set('a.js.map', buf('[1]')); + expect(verifyStamp(before, after).find((i) => i.name === 'a.js.map')?.reason).toMatch( + /not valid JSON/, + ); + }); + + it('flags a map with no debugId', () => { + const { before, after } = faithful(); + after.set('a.js.map', buf(mapJson({ debug_id: ID }))); + expect(verifyStamp(before, after).find((i) => i.name === 'a.js.map')?.reason).toMatch( + /no debugId/, + ); + }); + + it("flags a map whose debugId differs from its bundle's comment", () => { + const { before, after } = faithful(); + after.set('a.js.map', buf(stampedMap(OTHER_ID))); + const reason = verifyStamp(before, after).find((i) => i.name === 'a.js.map')?.reason; + expect(reason).toContain(OTHER_ID); + expect(reason).toContain(ID); + }); + + it('flags a stamped bundle whose map was left unstamped', () => { + const { before, after } = faithful(); + after.set('a.js.map', before.get('a.js.map') as Buffer); + expect(verifyStamp(before, after).find((i) => i.name === 'a.js.map')?.reason).toMatch( + /no debugId/, + ); + }); + + it('does not require a map for a bundle that has none', () => { + const code = 'console.log(1);\n'; + expect( + verifyStamp(new Map([['a.js', buf(code)]]), new Map([['a.js', buf(code + STUB)]])), + ).toEqual([]); + }); + + it('flags a bundle with no debugId comment at all when it was changed', () => { + const { before, after } = faithful(); + after.set('a.js', buf('console.log(1);\n//# sourceMappingURL=a.js.map\n;1;\n')); + expect(verifyStamp(before, after).find((i) => i.name === 'a.js')?.reason).toMatch( + /no debugId comment/, + ); + }); + + it('checks a changed map that has no changed bundle for JSON validity only', () => { + const bytes = buf(mapJson()); + expect( + verifyStamp(new Map([['a.js.map', bytes]]), new Map([['a.js.map', buf(stampedMap())]])), + ).toEqual([]); + expect( + verifyStamp(new Map([['a.js.map', bytes]]), new Map([['a.js.map', buf('nope')]])).map( + (i) => i.name, + ), + ).toEqual(['a.js.map']); + }); + }); + + describe('(iv) nothing but the stamp was appended', () => { + it('flags a bundle whose original bytes were altered', () => { + const { before, after } = faithful(); + after.set('a.js', buf(`console.log(2);\n//# sourceMappingURL=a.js.map\n${STUB}`)); + expect(verifyStamp(before, after).find((i) => i.name === 'a.js')?.reason).toMatch( + /original bytes/, + ); + }); + + it('does not apply to a bundle that was already stamped (a re-stamp replaces the old stamp)', () => { + const old = `console.log(1);\n;1;\n//# debugId=${OTHER_ID}\n`; + const fresh = `console.log(1);\n;1;\n//# debugId=${ID}\n`; + const issues = verifyStamp( + new Map([ + ['a.js', buf(old)], + ['a.js.map', buf(stampedMap(OTHER_ID))], + ]), + new Map([ + ['a.js', buf(fresh)], + ['a.js.map', buf(stampedMap())], + ]), + ); + expect(issues).toEqual([]); + }); + }); + + it('only looks at .js/.cjs/.mjs bundles and their .map', () => { + const issues = verifyStamp( + new Map([['a.css', buf('a{}')]]), + new Map([['a.css', buf('changed')]]), + ); + expect(issues).toEqual([]); + const cjs = verifyStamp( + new Map([['a.cjs', buf('1;')]]), + new Map([['a.cjs', buf(`1;${STUB}`)]]), + ); + expect(cjs).toEqual([]); + const mjs = verifyStamp(new Map([['a.mjs', buf('1;')]]), new Map([['a.mjs', buf('1;{{')]])); + expect(mjs.map((i) => i.name)).toContain('a.mjs'); + }); + + it('reports every problem, one entry per file and reason', () => { + const { before, after } = faithful(); + after.set('a.js', buf('{{')); + after.set('a.js.map', buf('x')); + const names = verifyStamp(before, after).map((i) => i.name); + expect(names).toContain('a.js'); + expect(names).toContain('a.js.map'); + }); +}); + +describe('verifyStampedPairs — a build as it is on disk, after the bundler wrote it', () => { + const stamped = (id = ID) => + buf(`x();\n//# sourceMappingURL=a.js.map\n${STUB.replace(new RegExp(ID, 'g'), id)}`); + + it('accepts a bundle and a map that agree', () => { + expect( + verifyStampedPairs( + new Map([ + ['/o/a.js', stamped()], + ['/o/a.js.map', buf(stampedMap())], + ]), + ), + ).toEqual([]); + }); + + it('flags a map whose id was lost after the stamp (another plugin regenerated it)', () => { + const issues = verifyStampedPairs( + new Map([ + ['/o/a.js', stamped()], + ['/o/a.js.map', buf(mapJson())], + ]), + ); + expect(issues).toEqual([{ name: '/o/a.js.map', reason: expect.stringMatching(/no debugId/) }]); + }); + + it('flags a map with a different id', () => { + const issues = verifyStampedPairs( + new Map([ + ['/o/a.js', stamped()], + ['/o/a.js.map', buf(stampedMap(OTHER_ID))], + ]), + ); + expect(issues[0]?.reason).toMatch(/does not match/); + }); + + it('flags a map that is not JSON, and a bundle with a map but no stamp at all', () => { + expect( + verifyStampedPairs( + new Map([ + ['/o/a.js', stamped()], + ['/o/a.js.map', buf('nope')], + ]), + )[0]?.reason, + ).toMatch(/not valid JSON/); + const missed = verifyStampedPairs( + new Map([ + ['/o/b.js', buf('y();\n')], + ['/o/b.js.map', buf(mapJson())], + ]), + ); + expect(missed).toEqual([{ name: '/o/b.js', reason: expect.stringMatching(/not stamped/) }]); + }); + + it('flags a map that carries an id while its bundle lost the comment', () => { + const issues = verifyStampedPairs( + new Map([ + ['/o/c.js', buf('z();\n')], + ['/o/c.js.map', buf(stampedMap())], + ]), + ); + expect(issues[0]?.name).toBe('/o/c.js'); + }); + + it('ignores a bundle with no map, a stylesheet map, and files that are not bundles', () => { + expect( + verifyStampedPairs( + new Map([ + ['/o/vendor.js', buf('v();\n')], + ['/o/a.css.map', buf('{}')], + ['/o/a.css', buf('a{}')], + ]), + ), + ).toEqual([]); + }); +}); + +describe('formatIssues', () => { + it('lists the first three and counts the rest', () => { + const issues = ['a', 'b', 'c', 'd', 'e'].map((name) => ({ name, reason: `bad ${name}` })); + expect(formatIssues(issues)).toBe('a: bad a; b: bad b; c: bad c; and 2 more'); + expect(formatIssues(issues.slice(0, 2))).toBe('a: bad a; b: bad b'); + }); +}); diff --git a/packages/bundler-plugin-core/src/verify-stamp.ts b/packages/bundler-plugin-core/src/verify-stamp.ts new file mode 100644 index 000000000..db54a83d9 --- /dev/null +++ b/packages/bundler-plugin-core/src/verify-stamp.ts @@ -0,0 +1,235 @@ +// Check what `bugsee-cli sourcemaps inject` did, before the result is trusted. +// +// Stamping rewrites the user's shipped JavaScript. The Rust inject is well tested, but "well tested" +// is not "verified on THIS build": a bundle with an unusual tail, a map that is not what its +// extension says, or a future inject regression would otherwise ship a script that no longer parses +// (a blank page) or a map whose id does not match its bundle (a crash that silently never +// symbolicates). Both are cheap to rule out on the bytes in hand, and expensive to find in production. +// +// Pure: it takes the bytes from before and after and returns what is wrong. What to DO about it +// (leave the asset alone in-build, restore the file after emit) is the caller's. +import { parse } from 'acorn'; +import { readDebugId } from './debug-ids'; + +/** One thing that is wrong with a stamped asset. */ +export interface StampIssue { + /** The asset, as named in the staged set (its path relative to the output root). */ + name: string; + reason: string; +} + +/** The first few issues as one line, for an error message. */ +export function formatIssues(issues: readonly StampIssue[]): string { + return ( + issues + .slice(0, 3) + .map((issue) => `${issue.name}: ${issue.reason}`) + .join('; ') + (issues.length > 3 ? `; and ${issues.length - 3} more` : '') + ); +} + +/** What inject stamps (`.js`/`.cjs`/`.mjs`); the map of `x.js` is `x.js.map`. */ +const BUNDLE = /\.[cm]?js$/; + +/** A source-map pointer comment, `//# sourceMappingURL=…` or the legacy `//@` spelling. */ +const SOURCE_MAPPING_URL = /^[ \t]*\/\/[#@][ \t]*sourceMappingURL=(\S*)[ \t]*$/gm; + +/** + * Whether `code` is syntactically valid JavaScript, as a module or as a classic script. + * + * Tried as a module first (an ES bundle has `import`/`export`), then as a script, because the two + * grammars differ (`with`, octal escapes and a bare `await` identifier are script-only). Return and + * top-level await are allowed so a CommonJS wrapper body and a worker entry are not false alarms. + */ +export function parseScript(code: string): boolean { + for (const sourceType of ['module', 'script'] as const) { + try { + parse(code, { + ecmaVersion: 'latest', + sourceType, + allowHashBang: true, + allowReturnOutsideFunction: true, + allowAwaitOutsideFunction: true, + }); + return true; + } catch { + // try the other grammar + } + } + return false; +} + +/** The value of the LAST sourceMappingURL comment in `code` — the one a debugger honours. */ +function lastSourceMappingUrl(code: string): string | undefined { + let last: string | undefined; + for (const match of code.matchAll(SOURCE_MAPPING_URL)) { + last = match[1]; + } + return last; +} + +/** Reasons a changed bundle is not a faithful stamp of `before`. */ +function bundleIssues( + before: Buffer, + after: Buffer, + parser: (code: string) => boolean, +): { reasons: string[]; id: string | undefined } { + const reasons: string[] = []; + const beforeText = before.toString('utf8'); + const afterText = after.toString('utf8'); + + // (i) Still parses. Judged against the original: a bundle the parser could not read to begin with + // (syntax newer than it knows) says nothing about the stamp, and must not block the build. + if (!parser(afterText) && parser(beforeText)) { + reasons.push('no longer parses as JavaScript after stamping'); + } + + // (iv) Nothing but an appended stamp. A bundle that was ALREADY stamped is re-stamped in place (the + // old stamp is replaced, not extended), so only a first stamp can be held to "bytes appended". + if (readDebugId(beforeText) === undefined && !after.subarray(0, before.length).equals(before)) { + reasons.push('the original bytes were altered, not just appended to'); + } + + // (ii) The map pointer survived untouched. Inject appends AFTER it (measured, bugsee-cli 0.9.0: the + // runtime stub and the debugId comment follow the sourceMappingURL line), so "still last" would be + // wrong; what must hold is that the comment a debugger resolves is the same one. + const pointer = lastSourceMappingUrl(beforeText); + if (pointer !== undefined && lastSourceMappingUrl(afterText) !== pointer) { + reasons.push(`the sourceMappingURL comment (${pointer}) was lost or changed by stamping`); + } + + const id = readDebugId(afterText); + if (id === undefined) { + reasons.push('no debugId comment after stamping'); + } + return { reasons, id }; +} + +/** The `debugId` of a source map's JSON, `null` when it is not a JSON object, `undefined` when it has none. */ +function mapDebugId(bytes: Buffer): string | null | undefined { + let parsed: unknown; + try { + parsed = JSON.parse(bytes.toString('utf8')); + } catch { + return null; + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + return null; + } + const id = (parsed as { debugId?: unknown }).debugId; + return typeof id === 'string' && id !== '' ? id : undefined; +} + +/** + * Verify a stamp. `before` / `after` map each asset name to its bytes; only assets that DIFFER are + * examined (inject leaves the rest untouched), so `after` may simply be the whole post-inject set. + * + * - every changed bundle still parses, keeps its sourceMappingURL comment, carries a debugId comment, + * and (unless it was already stamped) is the original with bytes appended; + * - every changed map is a JSON object, and the map of a changed bundle carries a `debugId` equal to + * the bundle's comment. + */ +export function verifyStamp( + before: ReadonlyMap, + after: ReadonlyMap, + parser: (code: string) => boolean = parseScript, +): StampIssue[] { + const issues: StampIssue[] = []; + const changed = (name: string): boolean => { + const was = before.get(name); + const now = after.get(name); + return was !== undefined && now !== undefined && !now.equals(was); + }; + const ids = new Map(); + + for (const name of before.keys()) { + if (!BUNDLE.test(name) || !changed(name)) { + continue; + } + const { reasons, id } = bundleIssues( + before.get(name) as Buffer, + after.get(name) as Buffer, + parser, + ); + ids.set(name, id); + for (const reason of reasons) { + issues.push({ name, reason }); + } + } + + // Every stamped bundle's map (changed or not) must now carry the bundle's id. + for (const [bundle, bundleId] of ids) { + const map = `${bundle}.map`; + const bytes = after.get(map); + if (bytes === undefined) { + continue; // a bundle with no map: nothing to symbolicate against, nothing to match + } + const mapId = mapDebugId(bytes); + if (mapId === null) { + issues.push({ name: map, reason: 'the stamped map is not valid JSON (an object)' }); + } else if (mapId === undefined) { + issues.push({ name: map, reason: 'the stamped map has no debugId' }); + } else if (bundleId !== undefined && mapId !== bundleId) { + issues.push({ + name: map, + reason: `the map's debugId ${mapId} does not match its bundle's debugId comment ${bundleId}`, + }); + } + } + + // A changed map whose bundle was not stamped in this run: only held to being a JSON object. + for (const name of before.keys()) { + if (name.endsWith('.map') && changed(name) && !ids.has(name.slice(0, -'.map'.length))) { + if (mapDebugId(after.get(name) as Buffer) === null) { + issues.push({ name, reason: 'the stamped map is not valid JSON (an object)' }); + } + } + } + return issues; +} + +/** + * Check a build AS IT IS ON DISK, with no "before" to compare against — what the in-build path can + * still verify once the bundler has written its output. + * + * Stamping in memory is only as good as what happens to the bytes afterwards: Vite, for one, rewrites + * a chunk's code and REGENERATES its `.map` asset after a `generateBundle` hook has run (its + * dynamic-import preload substitution), which can drop a debugId the stamp put in the map. A bundle with a + * map must carry a debugId comment, and the map the SAME id, or the build ships bytes that look stamped + * and cannot be symbolicated. Bundles without a map are left alone (nothing to match). + */ +export function verifyStampedPairs(files: ReadonlyMap): StampIssue[] { + const issues: StampIssue[] = []; + for (const [name, bytes] of files) { + const mapBytes = files.get(`${name}.map`); + if (!BUNDLE.test(name) || mapBytes === undefined) { + continue; + } + const bundleId = readDebugId(bytes.toString('utf8')); + const mapId = mapDebugId(mapBytes); + if (mapId === null) { + issues.push({ name: `${name}.map`, reason: 'the map is not valid JSON (an object)' }); + } else if (bundleId === undefined && mapId === undefined) { + issues.push({ + name, + reason: 'the bundle was not stamped (no debugId comment, and its map has none)', + }); + } else if (bundleId === undefined) { + issues.push({ + name, + reason: `the bundle lost its debugId comment (its map carries ${mapId})`, + }); + } else if (mapId === undefined) { + issues.push({ + name: `${name}.map`, + reason: `the map has no debugId (its bundle carries ${bundleId})`, + }); + } else if (mapId !== bundleId) { + issues.push({ + name: `${name}.map`, + reason: `the map's debugId ${mapId} does not match its bundle's debugId comment ${bundleId}`, + }); + } + } + return issues; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9abafe02d..8f9fe40e1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -425,6 +425,9 @@ importers: '@bugsee/core': specifier: workspace:* version: link:../core + acorn: + specifier: ^8.19.0 + version: 8.19.0 magic-string: specifier: ^0.30.21 version: 0.30.21 @@ -447,6 +450,12 @@ importers: tsup: specifier: ^9.0.0 version: 9.0.0(@microsoft/api-extractor@7.59.4(@types/node@22.20.5))(jiti@2.7.0)(postcss@8.5.32)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1) + vite: + specifier: ^8.3.5 + version: 8.3.5(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) + vite7: + specifier: npm:vite@7.3.6 + version: vite@7.3.6(@types/node@22.20.5)(jiti@2.7.0)(lightningcss@1.33.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) packages/capture: dependencies: @@ -3989,9 +3998,6 @@ packages: cpu: [x64] os: [win32] - '@rolldown/pluginutils@1.0.1': - resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} - '@rolldown/pluginutils@1.1.1': resolution: {integrity: sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==} @@ -5028,11 +5034,6 @@ packages: peerDependencies: acorn: ^8 - acorn@8.16.0: - resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==} - engines: {node: '>=0.4.0'} - hasBin: true - acorn@8.19.0: resolution: {integrity: sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==} engines: {node: '>=0.4.0'} @@ -12640,8 +12641,6 @@ snapshots: '@rolldown/binding-win32-x64-msvc@1.2.15': optional: true - '@rolldown/pluginutils@1.0.1': {} - '@rolldown/pluginutils@1.1.1': {} '@rollup/plugin-alias@6.0.1(rollup@4.65.1)': @@ -13037,9 +13036,9 @@ snapshots: tslib: 2.8.1 vitest: 4.1.7(@edge-runtime/vm@5.0.0)(@opentelemetry/api@1.10.0)(@types/node@22.20.5)(@vitest/coverage-v8@4.1.7)(jsdom@25.0.1)(vite@8.3.5(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) - '@sveltejs/acorn-typescript@1.0.10(acorn@8.16.0)': + '@sveltejs/acorn-typescript@1.0.10(acorn@8.19.0)': dependencies: - acorn: 8.16.0 + acorn: 8.19.0 '@sveltejs/acorn-typescript@1.0.13(acorn@8.19.0)': dependencies: @@ -13052,10 +13051,10 @@ snapshots: '@sveltejs/kit@2.67.0(@opentelemetry/api@1.10.0)(@sveltejs/vite-plugin-svelte@7.3.1(svelte@5.56.3(@typescript-eslint/types@8.59.4))(vite@8.3.5(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)))(svelte@5.56.3(@typescript-eslint/types@8.59.4))(typescript@6.0.3)(vite@8.3.5(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))': dependencies: '@standard-schema/spec': 1.1.0 - '@sveltejs/acorn-typescript': 1.0.10(acorn@8.16.0) + '@sveltejs/acorn-typescript': 1.0.10(acorn@8.19.0) '@sveltejs/vite-plugin-svelte': 7.3.1(svelte@5.56.3(@typescript-eslint/types@8.59.4))(vite@8.3.5(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) '@types/cookie': 0.6.0 - acorn: 8.16.0 + acorn: 8.19.0 cookie: 0.6.0 devalue: 5.8.1 esm-env: 1.2.2 @@ -13833,8 +13832,6 @@ snapshots: dependencies: acorn: 8.19.0 - acorn@8.16.0: {} - acorn@8.19.0: {} agent-base@7.1.4: {} @@ -15081,10 +15078,6 @@ snapshots: dependencies: reusify: 1.1.0 - fdir@6.5.0(picomatch@4.0.4): - optionalDependencies: - picomatch: 4.0.4 - fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -17603,7 +17596,7 @@ snapshots: rolldown@1.2.15: dependencies: '@oxc-project/types': 0.155.0 - '@rolldown/pluginutils': 1.0.1 + '@rolldown/pluginutils': 1.1.1 optionalDependencies: '@rolldown/binding-android-arm-eabi': 1.2.15 '@rolldown/binding-android-arm64': 1.2.15 @@ -18187,10 +18180,10 @@ snapshots: dependencies: '@jridgewell/remapping': 2.3.5 '@jridgewell/sourcemap-codec': 1.5.5 - '@sveltejs/acorn-typescript': 1.0.10(acorn@8.16.0) + '@sveltejs/acorn-typescript': 1.0.10(acorn@8.19.0) '@types/estree': 1.0.9 '@types/trusted-types': 2.0.7 - acorn: 8.16.0 + acorn: 8.19.0 aria-query: 5.3.1 axobject-query: 4.1.0 clsx: 2.1.1 @@ -18326,8 +18319,8 @@ snapshots: tinyglobby@0.2.16: dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 tinyglobby@0.2.17: dependencies: @@ -18567,7 +18560,7 @@ snapshots: unimport@6.3.0(@rspack/core@2.2.9)(esbuild@0.28.2)(oxc-parser@0.133.0)(rolldown@1.2.15)(rollup@4.65.1)(vite@8.3.5(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32)): dependencies: - acorn: 8.16.0 + acorn: 8.19.0 escape-string-regexp: 5.0.0 estree-walker: 3.0.3 local-pkg: 1.2.1 @@ -18690,7 +18683,7 @@ snapshots: unplugin@2.3.11: dependencies: '@jridgewell/remapping': 2.3.5 - acorn: 8.16.0 + acorn: 8.19.0 picomatch: 4.0.4 webpack-virtual-modules: 0.6.2 From 7f13da8aab697b1dd869a231ff4fff2b468c149b Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 11:41:00 +0500 Subject: [PATCH 02/39] feat(bundler-plugin-core): stamp debug-IDs inside the build for Vite, Rollup and Rspack Vite and Rollup stamp in generateBundle (order 'pre'), before Vite builds index.html and before an SRI plugin hashes; Rspack stamps at PROCESS_ASSETS_STAGE_DEV_TOOLING + 1 like webpack 5 (shared stage). The stamped state is per build (per compilation / per output directory, consumed by the matching write). A failed or impossible in-build stamp falls back to the post-emit path and its SRI refusal. esbuild and the CLI stay post-emit. Real builds (Vite 7, Vite 8/Rolldown, Rollup, Rspack with its built-in SRI plugin) pin hashes of the stamped bytes; a Chromium run loads the Vite and Rollup pages. With the in-build hooks disabled the same builds are refused. Co-Authored-By: Claude Sonnet 5.5 --- .../src/plugin.esbuild-rspack.test.ts | 4 +- .../src/plugin.in-build.real-build.test.ts | 394 ++++++++++++++++++ .../src/plugin.real-build.test.ts | 15 +- .../src/plugin.stamp.test.ts | 378 +++++++++++++++++ packages/bundler-plugin-core/src/plugin.ts | 174 +++++--- .../test/sri-vite-rollup.e2e.ts | 253 +++++++++++ 6 files changed, 1151 insertions(+), 67 deletions(-) create mode 100644 packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts create mode 100644 packages/bundler-plugin-core/src/plugin.stamp.test.ts create mode 100644 packages/instrumentation-tests/test/sri-vite-rollup.e2e.ts diff --git a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts index 931edd822..cbdbe7340 100644 --- a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts +++ b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts @@ -434,11 +434,11 @@ describe('rspack: upload after emit', () => { expect(bundlerOf(1)).toEqual({ isProduction: true, configuration: 'production' }); }); - it('is not stamped in-build: the post-emit run carries no preStamped flag', async () => { + it('a compiler without the in-build API (no thisCompilation) takes the post-emit path: preStamped is false', async () => { const { compiler, taps } = rspackCompiler('/out'); applyRspack({ appToken: 'tok' }, compiler); await taps[0]?.fn(); - expect((uploadSpy.mock.calls[0]?.[2] as { preStamped?: boolean }).preStamped).toBeUndefined(); + expect((uploadSpy.mock.calls[0]?.[2] as { preStamped?: boolean }).preStamped).toBe(false); }); it('is a no-op when the compiler has no usable output path', async () => { diff --git a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts new file mode 100644 index 000000000..6bd957a52 --- /dev/null +++ b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts @@ -0,0 +1,394 @@ +// Stamping INSIDE the build, end to end, with REAL bundlers and the REAL bugsee-cli: Vite 8 (Rolldown), Vite 7 +// (Rollup), Rollup and Rspack, each with a step that pins Subresource Integrity hashes of what it emits. +// +// The claim under test is the one the post-emit design could not make: the hash the page pins is the hash of +// the bytes that are on disk, AFTER the debug-ID stamp, with the maps uploaded and removed. Where a real +// browser run (Chromium) is infeasible here, the emitted bytes are hash-verified against the pinned +// `integrity` with node:crypto — the same comparison the browser makes. +// +// Before this change the same builds were REFUSED by the SRI guard (nothing stamped, nothing uploaded, maps +// left on disk); the "post-emit fallback" test pins that this still holds when the in-build stamp is not +// possible. + +import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { rspack } from '@rspack/core'; +import { rollup } from 'rollup'; +import { type Plugin as VitePlugin, build as viteBuild } from 'vite'; +import { build as vite7Build } from 'vite7'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { bugseeRollupPlugin, bugseeRspackPlugin, bugseeUnplugin } from './plugin'; +import { resolveBugseeCli } from './run-cli'; +import { findIntegrityMismatches } from './sri'; + +let server: Server; +let endpoint: string; +const requests: Array<{ url: string }> = []; +let root: string; + +const cli = resolveBugseeCli(); +const cliProbe = cli.endsWith('.js') + ? spawnSync(process.execPath, [cli, '--version'], { encoding: 'utf8' }) + : spawnSync(cli, ['--version'], { encoding: 'utf8' }); +const cliAvailable = cliProbe.status === 0; +const cliRequired = process.env.CI !== undefined || process.env.BUGSEE_REQUIRE_CLI !== undefined; +if (!cliAvailable && !cliRequired) { + console.warn('[bugsee] bugsee-cli binary not available: skipping the in-build real-build tests'); +} +const describeReal = cliAvailable || cliRequired ? describe : describe.skip; + +beforeAll(async () => { + root = mkdtempSync(join(tmpdir(), 'bugsee-in-build-')); + // Every request is answered "already uploaded", so the upload succeeds without a backend. + server = createServer((req, res) => { + requests.push({ url: req.url ?? '' }); + req.resume(); + req.on('end', () => { + 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 new Promise((r) => server.close(() => r())); + rmSync(root, { recursive: true, force: true }); +}); + +const pluginOptions = () => ({ + appToken: 'in-build-token', + endpoint, + vcs: false, + registerBuild: false as const, + failOnError: true, +}); + +/** An app with a page, an entry and a lazily loaded chunk. */ +function makeApp(name: string, options: { lazy?: boolean } = {}): { dir: string; out: string } { + const lazy = options.lazy ?? true; + const dir = join(realpathSync(root), name); + mkdirSync(dir, { recursive: true }); + writeFileSync( + join(dir, 'index.html'), + '\n', + ); + writeFileSync(join(dir, 'greet.js'), "export const greet = (n) => 'hello ' + n;\n"); + writeFileSync(join(dir, 'lazy.js'), "export default 'lazy chunk ' + Date.now();\n"); + writeFileSync( + join(dir, 'index.js'), + `import { greet } from './greet.js';\nconsole.log(greet('world'));\n${ + lazy ? "import('./lazy.js').then((m) => console.log(m.default));\n" : '' + }`, + ); + writeFileSync(join(dir, 'package.json'), JSON.stringify({ name, version: '1.2.3' })); + return { dir, out: join(dir, 'dist') }; +} + +const sri = (bytes: string | Buffer): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + +interface Pin { + tag: string; + file: string; + integrity: string; +} + +/** Every script / modulepreload in `/index.html` with an integrity, resolved to its file in `out`. */ +function pinsOf(out: string): Pin[] { + const html = readFileSync(join(out, 'index.html'), 'utf8'); + const pins: Pin[] = []; + for (const tag of html.match(/<(?:script|link)\b[^>]*>/g) ?? []) { + const integrity = /\bintegrity="([^"]+)"/.exec(tag)?.[1]; + const url = /\b(?:src|href)="([^"]+)"/.exec(tag)?.[1]; + if (integrity !== undefined && url !== undefined) { + pins.push({ tag, file: join(out, url.replace(/^\.?\//, '')), integrity }); + } + } + return pins; +} + +/** The comparison the browser makes: the pinned digest against the digest of the bytes on disk. */ +function expectPinsMatchDisk(out: string, atLeast = 1): void { + const pins = pinsOf(out); + expect(pins.length).toBeGreaterThanOrEqual(atLeast); + for (const pin of pins) { + expect(sri(readFileSync(pin.file)), `${pin.file} vs ${pin.integrity}`).toBe(pin.integrity); + } +} + +function expectStampedAndUploaded(out: string, before: number, atLeast = 2): void { + const files = readdirSync(out, { recursive: true }) as string[]; + const bundles = files.filter((f) => /\.[cm]?js$/.test(f)); + expect(bundles.length).toBeGreaterThanOrEqual(atLeast); // entry (+ lazy chunk) + for (const bundle of bundles) { + const code = readFileSync(join(out, bundle), 'utf8'); + expect(code, bundle).toMatch(/\/\/# debugId=[0-9a-f-]{36}/); + expect(code, bundle).toContain('_bugseeDebugIds'); + } + // Uploaded, then the client maps were deleted. + expect(requests.length).toBeGreaterThan(before); + expect(files.filter((f) => f.endsWith('.map'))).toEqual([]); +} + +/** Add `integrity` to every script / modulepreload tag whose file is a chunk of the bundle. */ +function pinChunks(html: string, bundle: Record): string { + return html.replace( + /<(?:script|link)\b[^>]*?(?:src|href)="\.?\/?([^"]+\.js)"[^>]*>/g, + (tag, file: string) => { + const entry = bundle[file]; + return entry?.type === 'chunk' && entry.code !== undefined + ? tag.replace(/>$/, ` integrity="${sri(entry.code)}">`) + : tag; + }, + ); +} + +/** A hand-rolled SRI step for Vite that hashes in `transformIndexHtml`, as vite-plugin-sri does. */ +const viteSri = (): VitePlugin => ({ + name: 'hand-rolled-sri', + enforce: 'post', + transformIndexHtml: { + order: 'post', + handler: (html, ctx) => pinChunks(html, (ctx.bundle ?? {}) as never), + }, +}); + +/** A hand-rolled SRI step that hashes LAST, in generateBundle (order post), into the emitted page. */ +const viteLateSri = (): VitePlugin => ({ + name: 'hand-rolled-late-sri', + enforce: 'post', + generateBundle: { + order: 'post', + handler(_options, bundle) { + const page = bundle['index.html']; + if (page?.type === 'asset') { + page.source = pinChunks(String(page.source), bundle as never); + } + }, + }, +}); + +const viteConfig = (app: { dir: string; out: string }, plugins: unknown[], build: object = {}) => + ({ + root: app.dir, + configFile: false, + logLevel: 'silent', + base: './', + plugins, + build: { outDir: app.out, emptyOutDir: true, minify: false, sourcemap: true, ...build }, + }) as never; + +const bugseeVite = (extra: object = {}) => + bugseeUnplugin.vite({ ...pluginOptions(), ...extra }) as VitePlugin; + +describeReal('real Vite builds with an SRI step', () => { + for (const [label, build] of [ + ['Vite 8 (Rolldown)', viteBuild], + ['Vite 7 (Rollup)', vite7Build], + ] as const) { + const slug = label.replace(/\W+/g, ''); + + it(`${label}: an SRI step in transformIndexHtml pins the STAMPED bytes; maps uploaded and removed`, async () => { + const app = makeApp(`vite-html-${slug}`, { lazy: false }); + const before = requests.length; + const warnings: unknown[] = []; + await build( + viteConfig(app, [ + bugseeVite({ failOnError: false, onError: (e: unknown) => warnings.push(e) }), + viteSri(), + ]), + ); + expect(warnings).toEqual([]); + expectStampedAndUploaded(app.out, before, 1); + expectPinsMatchDisk(app.out); + expect(await findIntegrityMismatches(app.out)).toEqual([]); + }); + + it(`${label}: an app with a lazy chunk and an SRI step that hashes last (generateBundle, post)`, async () => { + const app = makeApp(`vite-late-${slug}`); + const before = requests.length; + const warnings: unknown[] = []; + await build( + viteConfig(app, [ + bugseeVite({ failOnError: false, onError: (e: unknown) => warnings.push(e) }), + viteLateSri(), + ]), + ); + expect(warnings.map(String)).toEqual([]); + expectStampedAndUploaded(app.out, before); + expectPinsMatchDisk(app.out); + expect(await findIntegrityMismatches(app.out)).toEqual([]); + }); + } + + it('Vite 8: the match is not an accident of nothing being stamped (a disabled build pins other bytes)', async () => { + const stamped = makeApp('vite-compare-stamped', { lazy: false }); + const plain = makeApp('vite-compare-plain', { lazy: false }); + for (const [app, disabled] of [ + [stamped, false], + [plain, true], + ] as const) { + await viteBuild(viteConfig(app, [bugseeVite({ disabled }), viteSri()])); + } + const entry = (out: string): string => + readFileSync( + join( + out, + 'assets', + readdirSync(join(out, 'assets')).find((f) => f.endsWith('.js')) as string, + ), + 'utf8', + ); + expect(entry(stamped.out)).toContain('debugId'); + expect(entry(plain.out)).not.toContain('debugId'); + expectPinsMatchDisk(stamped.out); + expectPinsMatchDisk(plain.out); + expect(pinsOf(stamped.out)[0]?.integrity).not.toBe(pinsOf(plain.out)[0]?.integrity); + }); + + it('Vite 8: a build whose maps cannot be stamped in memory (inline) falls back to post-emit, where the SRI guard still refuses', async () => { + const app = makeApp('vite-inline', { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + const notices: string[] = []; + await viteBuild( + viteConfig( + app, + [ + bugseeVite({ + failOnError: false, + onError: (e: unknown) => errors.push(e), + onNotice: (m: string) => notices.push(m), + }), + viteSri(), + ], + { sourcemap: 'inline' }, + ), + ); + expect(notices.join('\n')).toContain('after emit'); + expect(errors.map(String).join('\n')).toContain('refusing to stamp debug-IDs'); + // Nothing stamped, nothing uploaded, and the page's pins are intact. + expect(requests.length).toBe(before); + for (const f of readdirSync(join(app.out, 'assets'))) { + expect(readFileSync(join(app.out, 'assets', f), 'utf8')).not.toContain('_bugseeDebugIds'); + } + expectPinsMatchDisk(app.out); + }); +}); + +describeReal('real Rollup build with an SRI step', () => { + it('the pinned hashes match the STAMPED bytes, maps uploaded and removed', async () => { + const app = makeApp('rollup-sri'); + const before = requests.length; + const sriHtml = { + name: 'sri-html', + generateBundle( + this: { emitFile(file: object): void }, + _output: unknown, + bundle: Record< + string, + { type: string; code?: string; isEntry?: boolean; fileName: string } + >, + ) { + const tags = Object.values(bundle) + .filter((entry) => entry.type === 'chunk') + .map((entry) => + entry.isEntry + ? `` + : ``, + ); + this.emitFile({ + type: 'asset', + fileName: 'index.html', + source: `${tags.join('')}`, + }); + }, + }; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin({ ...pluginOptions() }), sriHtml], + }); + await bundle.write({ dir: app.out, sourcemap: true }); + await bundle.close(); + expectStampedAndUploaded(app.out, before); + expectPinsMatchDisk(app.out, 2); + expect(await findIntegrityMismatches(app.out)).toEqual([]); + }); +}); + +describeReal('real Rspack build with the built-in SubresourceIntegrityPlugin', () => { + function runRspack(config: Parameters[0]): Promise<{ errors: unknown[] }> { + return new Promise((resolve, reject) => { + const compiler = rspack(config); + compiler.run((err, stats) => { + compiler.close(() => { + if (err) { + reject(err); + } else { + resolve({ + errors: (stats as { compilation: { errors: unknown[] } }).compilation.errors, + }); + } + }); + }); + }); + } + + it('the pinned hashes (page AND the lazy-chunk table in the runtime) match the STAMPED bytes', async () => { + const app = makeApp('rspack-sri-built-in'); + const before = requests.length; + const warnings: unknown[] = []; + const { errors } = await runRspack({ + context: app.dir, + mode: 'production', + entry: join(app.dir, 'index.js'), + devtool: 'source-map', + output: { path: app.out, crossOriginLoading: 'anonymous' }, + plugins: [ + bugseeRspackPlugin({ ...pluginOptions(), onError: (e: unknown) => warnings.push(e) }), + new rspack.HtmlRspackPlugin({ + template: join(app.dir, 'index.html'), + scriptLoading: 'defer', + }), + new rspack.SubresourceIntegrityPlugin({ hashFuncNames: ['sha384'] }), + ], + }); + console.log('RSERR', errors.map(String)); + expect(errors.map((e) => String((e as Error).message ?? e))).toEqual([]); + expect(warnings.map(String)).toEqual([]); + expectStampedAndUploaded(app.out, before); + expectPinsMatchDisk(app.out); + expect(await findIntegrityMismatches(app.out)).toEqual([]); + // The lazy chunk is not in the HTML; the plugin embeds ITS hash in the runtime. That hash must be of the + // stamped bytes too, or `import()` of the chunk fails in the browser. + const files = readdirSync(app.out).filter((f) => f.endsWith('.js')); + const runtimeText = files.map((f) => readFileSync(join(app.out, f), 'utf8')).join('\n'); + const pinned = new Set(pinsOf(app.out).map((pin) => pin.file)); + const lazy = files.filter((f) => !pinned.has(join(app.out, f))); + expect(lazy.length).toBeGreaterThan(0); + for (const f of lazy) { + expect(runtimeText, `${f} hash is in the runtime table`).toContain( + createHash('sha384') + .update(readFileSync(join(app.out, f))) + .digest('base64'), + ); + } + expect(existsSync(join(app.out, 'index.html'))).toBe(true); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.real-build.test.ts index da0963891..95c91afb8 100644 --- a/packages/bundler-plugin-core/src/plugin.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.real-build.test.ts @@ -175,10 +175,14 @@ describeReal('real Rspack build', () => { expectUploaded(app.out, before); }); - it('REFUSES an SRI build: nothing is stamped or uploaded and the maps stay', async () => { + it('stamps IN the build, so a page pinning a hash the build cannot satisfy is REPORTED (the build still uploads)', async () => { + // Since the in-build stamp (Rspack stamps at PROCESS_ASSETS_STAGE_DEV_TOOLING + 1) nothing is rewritten + // after emit, so the post-emit SRI refusal no longer applies. What can still be wrong is a pin that + // never matched (here: a hand-written page with a made-up hash), and the post-stamp integrity check + // says so instead of shipping it silently. The real-SRI-plugin builds are in + // plugin.in-build.real-build.test.ts. const app = makeApp('rspack-sri'); mkdirSync(app.out, { recursive: true }); - // What an SRI plugin leaves behind: a page pinning the hash of the entry script. writeFileSync( join(app.out, 'index.html'), '', @@ -197,10 +201,9 @@ describeReal('real Rspack build', () => { ], }), ); - expect(errors.map(String).join()).toContain('refusing to stamp debug-IDs'); - expect(requests.length).toBe(before); - expect(readFileSync(join(app.out, 'main.js'), 'utf8')).not.toContain('debugId'); - expect(existsSync(join(app.out, 'main.js.map'))).toBe(true); + expect(errors.map(String).join()).toContain('no longer matches the integrity hash'); + expect(requests.length).toBeGreaterThan(before); + expect(readFileSync(join(app.out, 'main.js'), 'utf8')).toContain('debugId'); }); it('a build with a compile error uploads nothing', async () => { diff --git a/packages/bundler-plugin-core/src/plugin.stamp.test.ts b/packages/bundler-plugin-core/src/plugin.stamp.test.ts new file mode 100644 index 000000000..18c1eb8ec --- /dev/null +++ b/packages/bundler-plugin-core/src/plugin.stamp.test.ts @@ -0,0 +1,378 @@ +import type { UnpluginOptions } from 'unplugin'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { BugseePluginOptions } from './resolve'; + +// Hook wiring for stamping INSIDE the build on Rspack (processAssets), and on Vite / Rollup +// (generateBundle). The stamp itself is stubbed: stamp-assets.test.ts runs the real CLI and +// plugin.in-build.real-build.test.ts runs real Vite / Rollup / Rspack builds end to end. +const { uploadSpy } = vi.hoisted(() => ({ + uploadSpy: vi.fn(async (_resolved: unknown, _outDir: string, _deps?: unknown) => undefined), +})); +vi.mock('./resolve', async (importOriginal) => ({ + ...(await importOriginal()), + runPluginUpload: uploadSpy, +})); +const { stampSpy } = vi.hoisted(() => ({ + stampSpy: vi.fn(async (_store: unknown, _options?: unknown) => ({ stamped: [] as string[] })), +})); +vi.mock('./stamp-assets', async (importOriginal) => ({ + ...(await importOriginal()), + stampAssets: stampSpy, +})); + +const { bugseeUnpluginFactory } = await import('./plugin'); +const makePlugin = (options?: BugseePluginOptions, framework = 'rollup'): UnpluginOptions => + bugseeUnpluginFactory(options, { framework } as never) as UnpluginOptions; + +const depsOf = (call: number) => + uploadSpy.mock.calls[call]?.[2] as { preStamped?: boolean; bundler?: unknown } | undefined; + +beforeEach(() => { + uploadSpy.mockClear(); + stampSpy.mockReset(); + stampSpy.mockImplementation(async () => ({ stamped: [] })); +}); + +describe('rspack: stamps inside the compilation', () => { + const DEV_TOOLING = 500; + class RawSource { + constructor(readonly bytes: Buffer) {} + } + + function rspackCompiler(options: { mode?: string; withApi?: boolean } = {}) { + const afterEmit: Array<() => Promise> = []; + const processAssets: Array<{ name: string; stage: number; fn: () => Promise }> = []; + const updated: Array<{ name: string; source: unknown }> = []; + const compilation = { + hooks: { + processAssets: { + tapPromise: (opts: { name: string; stage: number }, fn: () => Promise) => { + processAssets.push({ ...opts, fn }); + }, + }, + }, + getAssets: () => [{ name: 'main.js' }, { name: 'main.js.map' }], + getAsset: (name: string) => ({ source: { buffer: () => Buffer.from(`content of ${name}`) } }), + updateAsset: (name: string, source: unknown) => { + updated.push({ name, source }); + }, + }; + const compilations: Array<(c: unknown) => void> = []; + const compiler = { + options: { + output: { path: '/build/out' }, + mode: options.mode ?? 'production', + devtool: 'source-map', + }, + hooks: { + afterEmit: { tapPromise: (_n: string, fn: () => Promise) => afterEmit.push(fn) }, + thisCompilation: { tap: (_n: string, fn: (c: unknown) => void) => compilations.push(fn) }, + }, + ...(options.withApi === false + ? {} + : { + rspack: { + Compilation: { PROCESS_ASSETS_STAGE_DEV_TOOLING: DEV_TOOLING }, + sources: { RawSource }, + DefinePlugin: class { + apply() {} + }, + }, + }), + }; + return { + compiler, + processAssets, + updated, + afterEmit: () => afterEmit[0]?.(), + compile: async () => { + for (const fn of compilations) { + fn(compilation); + } + for (const tap of processAssets) { + await tap.fn(); + } + }, + /** A compilation that starts but never reaches its processAssets stage (an earlier error). */ + startOnly: () => { + for (const fn of compilations) { + fn(compilation); + } + }, + }; + } + const apply = (options: BugseePluginOptions, compiler: unknown): void => + (makePlugin(options, 'rspack').rspack as (c: unknown) => void)(compiler); + + it('taps processAssets one stage after the maps are emitted, before an SRI plugin hashes', async () => { + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + expect(r.processAssets).toHaveLength(1); + expect(r.processAssets[0]?.stage).toBe(DEV_TOOLING + 1); + expect(r.processAssets[0]?.name).toBe('bugsee'); + expect(stampSpy).toHaveBeenCalledOnce(); + }); + + it('uploads without re-injecting after emit (preStamped)', async () => { + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + await r.afterEmit(); + expect(depsOf(0)?.preStamped).toBe(true); + }); + + it('reads and writes the compilation asset table, through rspack own RawSource', async () => { + stampSpy.mockImplementation(async (store) => { + const s = store as { + names(): string[]; + read(n: string): Buffer; + update(n: string, c: Buffer): void; + }; + expect(s.names()).toEqual(['main.js', 'main.js.map']); + expect(s.read('main.js').toString()).toBe('content of main.js'); + s.update('main.js', Buffer.from('stamped')); + return { stamped: ['main.js'] }; + }); + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + expect(r.updated[0]?.source).toBeInstanceOf(RawSource); + expect((r.updated[0]?.source as RawSource).bytes.toString()).toBe('stamped'); + }); + + it('passes the dry-run flag on', async () => { + const r = rspackCompiler(); + apply({ appToken: 'tok', dryRun: true }, r.compiler); + await r.compile(); + expect(stampSpy.mock.calls[0]?.[1]).toEqual({ dryRun: true }); + }); + + it('falls back to the post-emit path (SRI refusal included) when the stamp fails', async () => { + stampSpy.mockImplementation(async () => { + throw new Error('bugsee-cli exited 20'); + }); + const onError = vi.fn(); + const r = rspackCompiler(); + apply({ appToken: 'tok', onError }, r.compiler); + await r.compile(); + await r.afterEmit(); + expect(onError).toHaveBeenCalledOnce(); + expect(depsOf(0)?.preStamped).toBe(false); + }); + + it('fails the compilation under failOnError', async () => { + stampSpy.mockImplementation(async () => { + throw new Error('bugsee-cli exited 20'); + }); + const r = rspackCompiler(); + apply({ appToken: 'tok', failOnError: true }, r.compiler); + await expect(r.compile()).rejects.toThrow(/exited 20/); + }); + + it('starts each compilation unstamped (watch mode)', async () => { + const r = rspackCompiler(); + apply({ appToken: 'tok', onError: () => undefined }, r.compiler); + await r.compile(); + await r.afterEmit(); + stampSpy.mockImplementation(async () => { + throw new Error('second build failed to stamp'); + }); + await r.compile(); + await r.afterEmit(); + expect(depsOf(1)?.preStamped).toBe(false); + }); + + it('a compilation that never reaches the stamp stage is not vouched for by the previous one', async () => { + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + r.startOnly(); + await r.afterEmit(); + expect(depsOf(0)?.preStamped).toBe(false); + }); + + it('does not stamp for a disabled plugin', async () => { + const r = rspackCompiler(); + apply({ disabled: true }, r.compiler); + await r.compile(); + expect(r.processAssets).toHaveLength(0); + }); + + it('keeps the post-emit path on a compiler without the rspack API or thisCompilation', async () => { + const r = rspackCompiler({ withApi: false }); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + await r.afterEmit(); + expect(stampSpy).not.toHaveBeenCalled(); + expect(depsOf(0)?.preStamped).toBe(false); + }); +}); + +describe('vite / rollup: stamps in generateBundle, before anything is written or hashed', () => { + type Handler = ( + output: { dir?: string; file?: string }, + bundle: Record, + ) => Promise; + type Hook = { order?: string; handler: Handler }; + const hooksOf = (p: UnpluginOptions, kind: 'vite' | 'rollup') => + p[kind] as unknown as { generateBundle: Hook; writeBundle: (o: object) => Promise }; + + const bundle = (): Record => ({ + 'a.js': { type: 'chunk', fileName: 'a.js', code: 'x', map: {} }, + 'a.js.map': { type: 'asset', fileName: 'a.js.map', source: '{}' }, + }); + + for (const kind of ['vite', 'rollup'] as const) { + describe(kind, () => { + it('runs FIRST (order: pre), so Vite html build and later SRI hashing see stamped bytes', () => { + expect(hooksOf(makePlugin({ appToken: 'tok' }), kind).generateBundle.order).toBe('pre'); + }); + + it('stamps the output bundle through a store over it', async () => { + stampSpy.mockImplementation(async (store) => { + const s = store as { + names(): string[]; + read(n: string): Buffer; + update(n: string, c: Buffer): void; + }; + expect(s.names()).toEqual(['a.js', 'a.js.map']); + expect(s.read('a.js').toString()).toBe('x'); + s.update('a.js', Buffer.from('stamped')); + return { stamped: ['a.js'] }; + }); + const b = bundle(); + await hooksOf(makePlugin({ appToken: 'tok' }), kind).generateBundle.handler( + { dir: '/out' }, + b, + ); + expect((b['a.js'] as { code: string }).code).toBe('stamped'); + }); + + it('then uploads without re-injecting, once: the flag is consumed by the write', async () => { + const p = makePlugin({ appToken: 'tok' }); + const h = hooksOf(p, kind); + await h.generateBundle.handler({ dir: '/out' }, bundle()); + await h.writeBundle({ dir: '/out' }); + await h.writeBundle({ dir: '/out' }); // a write with no generateBundle before it: not stamped + expect(depsOf(0)?.preStamped).toBe(true); + expect(depsOf(1)?.preStamped).toBeUndefined(); + }); + + it('tracks each output directory on its own', async () => { + stampSpy.mockImplementationOnce(async () => ({ stamped: [] })); + stampSpy.mockImplementationOnce(async () => { + throw new Error('second output failed'); + }); + const p = makePlugin({ appToken: 'tok', onError: () => undefined }); + const h = hooksOf(p, kind); + await h.generateBundle.handler({ dir: '/a' }, bundle()); + await h.generateBundle.handler({ file: '/b/out.js' }, bundle()); + await h.writeBundle({ dir: '/a' }); + await h.writeBundle({ file: '/b/out.js' }); + expect(depsOf(0)?.preStamped).toBe(true); + expect(depsOf(1)?.preStamped).toBeUndefined(); + }); + + it('a stale success never vouches for the next build of the same directory', async () => { + const p = makePlugin({ appToken: 'tok', onError: () => undefined }); + const h = hooksOf(p, kind); + await h.generateBundle.handler({ dir: '/out' }, bundle()); + // (the write of build 1 never happened) build 2's stamp fails: + stampSpy.mockImplementationOnce(async () => { + throw new Error('boom'); + }); + await h.generateBundle.handler({ dir: '/out' }, bundle()); + await h.writeBundle({ dir: '/out' }); + expect(depsOf(0)?.preStamped).toBeUndefined(); + }); + + it('a build that cannot be stamped in memory is not vouched for by the previous stamp either', async () => { + const h = hooksOf(makePlugin({ appToken: 'tok', onNotice: () => undefined }), kind); + await h.generateBundle.handler({ dir: '/out' }, bundle()); // stamped; its write never happened + const unstampable = bundle(); + delete unstampable['a.js.map']; + await h.generateBundle.handler({ dir: '/out' }, unstampable); + await h.writeBundle({ dir: '/out' }); + expect(depsOf(0)?.preStamped).toBeUndefined(); + }); + + it('falls back to the post-emit path, reported, when the stamp fails', async () => { + stampSpy.mockImplementation(async () => { + throw new Error('bugsee-cli exited 20'); + }); + const onError = vi.fn(); + const h = hooksOf(makePlugin({ appToken: 'tok', onError }), kind); + await h.generateBundle.handler({ dir: '/out' }, bundle()); + await h.writeBundle({ dir: '/out' }); + expect(onError).toHaveBeenCalledOnce(); + expect(depsOf(0)?.preStamped).toBeUndefined(); + }); + + it('says what happens next when a stamp fails and no handler is set', async () => { + stampSpy.mockImplementation(async () => { + throw new Error('bugsee-cli exited 20'); + }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + await hooksOf(makePlugin({ appToken: 'tok' }), kind).generateBundle.handler( + { dir: '/out' }, + bundle(), + ); + expect(String(warn.mock.calls[0]?.[0])).toMatch( + /in-build debug-ID stamping failed; falling back to stamping after emit: .*exited 20/, + ); + } finally { + warn.mockRestore(); + } + }); + + it('fails the build under failOnError', async () => { + stampSpy.mockImplementation(async () => { + throw new Error('bugsee-cli exited 20'); + }); + await expect( + hooksOf(makePlugin({ appToken: 'tok', failOnError: true }), kind).generateBundle.handler( + { dir: '/out' }, + bundle(), + ), + ).rejects.toThrow(/exited 20/); + }); + + it('passes the dry-run flag on', async () => { + await hooksOf(makePlugin({ appToken: 'tok', dryRun: true }), kind).generateBundle.handler( + { dir: '/out' }, + bundle(), + ); + expect(stampSpy.mock.calls[0]?.[1]).toEqual({ dryRun: true }); + }); + + it('does nothing for a disabled plugin, or an output with no directory', async () => { + await hooksOf(makePlugin({ disabled: true }), kind).generateBundle.handler( + { dir: '/out' }, + bundle(), + ); + await hooksOf(makePlugin({ appToken: 'tok' }), kind).generateBundle.handler({}, bundle()); + expect(stampSpy).not.toHaveBeenCalled(); + }); + + it('a chunk whose map is not a bundle asset cannot be stamped in memory: post-emit fallback, said once', async () => { + const notices: string[] = []; + const h = hooksOf( + makePlugin({ appToken: 'tok', onNotice: (m: string) => notices.push(m) }), + kind, + ); + const b = bundle(); + delete b['a.js.map']; + await h.generateBundle.handler({ dir: '/out' }, b); + await h.generateBundle.handler({ dir: '/out' }, b); + await h.writeBundle({ dir: '/out' }); + expect(stampSpy).not.toHaveBeenCalled(); + expect(notices).toHaveLength(1); + expect(notices[0]).toContain('a.js'); + expect(notices[0]).toContain('after emit'); + expect(depsOf(0)?.preStamped).toBeUndefined(); + }); + }); + } +}); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 90dd9f5b7..b8a7af455 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -22,7 +22,13 @@ import { resolvePluginOptions, runPluginUpload, } from './resolve'; -import { type AssetStore, stampAssets } from './stamp-assets'; +import { + type AssetStore, + type RollupBundleLike, + rollupAssetStore, + rollupUnstampableMaps, + stampAssets, +} from './stamp-assets'; /** The subset of a rollup/vite output-options object we read. */ export interface OutputLike { @@ -74,13 +80,19 @@ interface WebpackCompilerLike { * `RawSource` class must be the ones this compilation uses, not a second copy of webpack or * webpack-sources that happens to resolve from this package. */ - webpack?: { - Compilation: { PROCESS_ASSETS_STAGE_DEV_TOOLING: number }; - sources: { RawSource: new (buffer: Buffer) => unknown }; - DefinePlugin?: DefinePluginCtor; - }; - /** Rspack's own API object (webpack-compatible `DefinePlugin`). */ - rspack?: { DefinePlugin?: DefinePluginCtor }; + webpack?: BundlerApi; + /** + * Rspack's own API object: the same webpack-compatible surface (`Compilation` stages, `sources.RawSource`, + * `DefinePlugin`), which is what lets one in-build stamp stage serve both. + */ + rspack?: BundlerApi; +} + +/** The webpack-compatible API a compiler exposes (webpack 5 as `compiler.webpack`, Rspack as `compiler.rspack`). */ +interface BundlerApi { + Compilation?: { PROCESS_ASSETS_STAGE_DEV_TOOLING: number }; + sources?: { RawSource: new (buffer: Buffer) => unknown }; + DefinePlugin?: DefinePluginCtor; } /** webpack's / rspack's `DefinePlugin`, as far as the identity injection uses it. */ @@ -351,13 +363,97 @@ export const bugseeUnpluginFactory: UnpluginFactory => { + try { + await stampAssets(store, { dryRun: resolved.dryRun }); + // True on a dry run too: the preview must follow the path the real run takes, and the real run + // would not refuse an SRI build — it would stamp it here. + return true; + } catch (error) { + if (resolved.failOnError) { + throw error; + } + ( + resolved.onError ?? + ((e: unknown) => + console.warn( + `[bugsee] in-build debug-ID stamping failed; falling back to stamping after emit: ${String(e)}`, + )) + )(error); + return false; + } + }; + + // webpack 5 and Rspack share the stage: stamp at PROCESS_ASSETS_STAGE_DEV_TOOLING + 1. The source-map + // plugin emits the maps AT 500 (after minification at 400) and webpack-subresource-integrity / + // Rspack's SubresourceIntegrityPlugin hash later (measured: after 700), so one stage past 500 sees the + // final bytes and the SRI plugin then hashes the STAMPED bytes — for the HTML and for the lazy-chunk + // table alike. Nothing is rewritten after emit. Returns whether THIS compilation was stamped; reset per + // compilation, so in watch mode a stamp from the previous build cannot vouch for this one. + const tapProcessAssetsStamp = (compiler: WebpackCompilerLike): (() => boolean) => { + let preStamped = false; + const api = compiler.webpack ?? compiler.rspack; + const stage = api?.Compilation?.PROCESS_ASSETS_STAGE_DEV_TOOLING; + const RawSource = api?.sources?.RawSource; + const thisCompilation = compiler.hooks.thisCompilation; + if (resolved.enabled && stage !== undefined && RawSource !== undefined && thisCompilation) { + thisCompilation.tap(name, (compilation) => { + preStamped = false; + compilation.hooks.processAssets.tapPromise({ name, stage: stage + 1 }, async () => { + preStamped = await stampInBuild(webpackAssetStore(compilation, RawSource)); + }); + }); + } + return () => preStamped; + }; + + // Vite and Rollup: stamp in `generateBundle`, where chunks (`code`) and their `.map` assets are in memory. + // Whether the output directory's bundle was stamped is kept per directory (a Vite app builds a client + // and a server into different ones), set by every generateBundle and CONSUMED by the matching write, so + // a stamp can never carry over to a later build of the same directory. + const stampedOutputs = new Map(); + const stampBundle = async (output: OutputLike, bundle: RollupBundleLike): Promise => { + const outDir = resolveOutputDir(output); + if (outDir === undefined || !resolved.enabled) { + return; + } + stampedOutputs.set(outDir, false); + const unstampable = rollupUnstampableMaps(bundle); + if (unstampable.length > 0) { + say( + `${unstampable.join(', ')} ${unstampable.length > 1 ? 'have' : 'has'} a source map that is not a bundle asset ` + + '(an older Rollup, or `sourcemap: "inline"`), so debug-IDs cannot be stamped inside the build; ' + + 'stamping after emit instead (a build that pins Subresource Integrity hashes is then refused).', + ); + return; + } + stampedOutputs.set(outDir, await stampInBuild(rollupAssetStore(bundle))); + }; + // Not `order: 'pre'` by taste: Vite builds `index.html` (and runs `transformIndexHtml`, where an SRI + // plugin hashes the chunks) in its own generateBundle, so ours must run first. Plugins sharing the + // `pre` order run in the order they appear in `plugins`: list this plugin BEFORE any SRI plugin. + const generateBundleHook = { + order: 'pre' as const, + handler: (output: OutputLike, bundle: RollupBundleLike) => stampBundle(output, bundle), + }; + const uploadForOutput = async ( output: OutputLike, bundler: BundlerBuildContext, ): Promise => { const outDir = resolveOutputDir(output); if (outDir !== undefined) { - await runPluginUpload(forOutput(outDir), outDir, { bundler }); + const preStamped = stampedOutputs.get(outDir) === true; + stampedOutputs.delete(outDir); + await runPluginUpload(forOutput(outDir), outDir, { + bundler, + ...(preStamped ? { preStamped: true } : {}), + }); } }; @@ -417,6 +513,7 @@ export const bugseeUnpluginFactory: UnpluginFactory uploadForOutput(output, viteBuild), }, rollup: { @@ -455,6 +552,7 @@ export const bugseeUnpluginFactory: UnpluginFactory uploadForOutput(output, {}), }, esbuild: { @@ -566,9 +664,10 @@ export const bugseeUnpluginFactory: UnpluginFactory { - preStamped = false; - compilation.hooks.processAssets.tapPromise( - { name, stage: api.Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING + 1 }, - async () => { - try { - await stampAssets(webpackAssetStore(compilation, api.sources.RawSource), { - dryRun: resolved.dryRun, - }); - // True on a dry run too: the preview must follow the path the real run takes, and the - // real run would not refuse an SRI build — it would stamp it here. - preStamped = true; - } catch (error) { - if (resolved.failOnError) { - throw error; - } - // Contained, and NOT silent about what happens next: the post-emit path takes over, - // and it still carries the SRI refusal, so a failed in-build stamp degrades to the old - // safe behaviour rather than to an unchecked page. - ( - resolved.onError ?? - ((e: unknown) => - console.warn( - `[bugsee] in-build debug-ID stamping failed; falling back to stamping after emit: ${String(e)}`, - )) - )(error); - } - }, - ); - }); - } + // THE SRI FIX on webpack 5: stamp inside the compilation (see tapProcessAssetsStamp). + const preStamped = tapProcessAssetsStamp(compiler); compiler.hooks.afterEmit.tapPromise(name, async () => { const dir = compiler.options.output?.path; if (typeof dir === 'string' && dir !== '') { await runPluginUpload(forOutput(dir), dir, { bundler: webpackBuild(compiler.options.mode), - preStamped, + preStamped: preStamped(), }); } }); diff --git a/packages/instrumentation-tests/test/sri-vite-rollup.e2e.ts b/packages/instrumentation-tests/test/sri-vite-rollup.e2e.ts new file mode 100644 index 000000000..508a0e56b --- /dev/null +++ b/packages/instrumentation-tests/test/sri-vite-rollup.e2e.ts @@ -0,0 +1,253 @@ +// Subresource Integrity with Vite and Rollup, end to end in a REAL browser. +// +// sri.e2e.ts proves it for webpack. Vite and Rollup used to stamp AFTER emit (`writeBundle`), so a page whose +// hashes were taken in the build was refused. They now stamp in `generateBundle` (order 'pre'), before the +// hashes are taken. This builds a real app with the real plugin and the real bugsee-cli, pins hashes with a +// hand-rolled SRI step, loads the result in Chromium, and requires: the entry runs, the lazy chunk runs, the +// browser blocks nothing, and the SDK's debug-id registrations are live. +// +// The CONTROL stamps the same Vite build AFTER emit, as the plugin used to; it must be blocked, or a page +// that loads would prove nothing about whether this harness can see the defect. +import { createHash } from 'node:crypto'; +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { tmpdir } from 'node:os'; +import { extname, join, normalize } from 'node:path'; +import { runBugseeCli } from '@bugsee/bundler-plugin-core'; +import { bugseeVitePlugin } from '@bugsee/vite-plugin'; +import { type Browser, chromium } from 'playwright'; +import { rollup } from 'rollup'; +import { type Plugin as VitePlugin, build as viteBuild } from 'vite'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +async function startCollector(): Promise<{ url: string; close: () => Promise }> { + const server = createServer((req, res) => { + req.resume(); + req.on('end', () => { + 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)); + return { + url: `http://127.0.0.1:${(server.address() as { port: number }).port}`, + close: () => new Promise((r) => server.close(() => r())), + }; +} + +const TYPES: Record = { + '.html': 'text/html', + '.js': 'text/javascript', + '.map': 'application/json', +}; + +async function serve(dir: string): Promise<{ url: string; server: Server }> { + const server = createServer((req, res) => { + const path = normalize( + join(dir, (req.url ?? '/').split('?')[0] === '/' ? 'index.html' : (req.url as string)), + ); + if (!path.startsWith(dir)) { + res.statusCode = 403; + res.end(); + return; + } + try { + const body = readFileSync(path); + res.setHeader('content-type', TYPES[extname(path)] ?? 'application/octet-stream'); + res.end(body); + } catch { + res.statusCode = 404; + res.end(); + } + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + return { url: `http://127.0.0.1:${(server.address() as { port: number }).port}/`, server }; +} + +interface PageOutcome { + ran: boolean; + lazy: string | undefined; + debugIds: number; + blocked: string[]; +} + +async function load(browser: Browser, dir: string): Promise { + const { url, server } = await serve(dir); + const page = await browser.newPage(); + const blocked: string[] = []; + page.on('console', (message) => { + if (/integrity|digest/i.test(message.text())) { + blocked.push(message.text()); + } + }); + try { + await page.goto(url); + await page + .waitForFunction(() => (window as { __lazy?: string }).__lazy !== undefined, null, { + timeout: 5_000, + }) + .catch(() => undefined); + const state = await page.evaluate(() => { + const w = window as { __ran?: boolean; __lazy?: string; _bugseeDebugIds?: object }; + return { + ran: w.__ran === true, + lazy: w.__lazy, + debugIds: Object.keys(w._bugseeDebugIds ?? {}).length, + }; + }); + return { ...state, blocked }; + } finally { + await page.close(); + await new Promise((r) => server.close(() => r())); + } +} + +const sri = (bytes: string | Buffer): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + +/** Pin every script / modulepreload that is a chunk of the bundle. */ +function pinChunks(html: string, bundle: Record): string { + return html.replace( + /<(?:script|link)\b[^>]*?(?:src|href)="\/?([^"]+\.js)"[^>]*>/g, + (tag, file: string) => { + const entry = bundle[file]; + return entry?.type === 'chunk' && entry.code !== undefined + ? tag.replace(/>$/, ` integrity="${sri(entry.code)}">`) + : tag; + }, + ); +} + +/** A hand-rolled SRI step that hashes LAST (generateBundle, order post), into the emitted page. */ +const lateSri = (): VitePlugin => ({ + name: 'hand-rolled-late-sri', + enforce: 'post', + generateBundle: { + order: 'post', + handler(_options, bundle) { + const page = bundle['index.html']; + if (page?.type === 'asset') { + page.source = pinChunks(String(page.source), bundle as never); + } + }, + }, +}); + +describe('SRI: a Vite / Rollup page still loads after Bugsee stamps it', () => { + let root: string; + let browser: Browser; + let collector: { url: string; close: () => Promise }; + + const pluginOptions = () => ({ + appToken: 'sri-e2e-token', + endpoint: collector.url, + appVersion: '1.0.0', + appBuild: '1', + vcs: false, + registerBuild: false as const, + failOnError: true, + }); + + beforeAll(async () => { + root = mkdtempSync(join(tmpdir(), 'bugsee-sri-vite-e2e-')); + mkdirSync(join(root, 'src')); + writeFileSync( + join(root, 'index.html'), + '\n', + ); + writeFileSync( + join(root, 'src', 'index.js'), + `window.__ran = true;\nimport('./lazy.js').then((m) => { window.__lazy = m.value; });\n`, + ); + writeFileSync(join(root, 'src', 'lazy.js'), `export const value = 'lazy-ok';\n`); + collector = await startCollector(); + browser = await chromium.launch({ headless: true }); + }, 60_000); + + afterAll(async () => { + await browser?.close(); + await collector?.close(); + if (root) rmSync(root, { recursive: true, force: true }); + }); + + const viteApp = (outDir: string, plugins: unknown[]) => + ({ + root, + configFile: false, + logLevel: 'silent', + plugins, + build: { outDir, emptyOutDir: true, minify: false, sourcemap: true }, + }) as never; + + it('Vite: runs the entry AND the lazy chunk, every bundle stamped, hashes taken after the stamp', async () => { + const outDir = join(root, 'dist-vite'); + await viteBuild(viteApp(outDir, [bugseeVitePlugin(pluginOptions()) as VitePlugin, lateSri()])); + + const bundles = readdirSync(join(outDir, 'assets')).filter((f) => f.endsWith('.js')); + expect(bundles.length).toBeGreaterThanOrEqual(2); + for (const file of bundles) { + expect(readFileSync(join(outDir, 'assets', file), 'utf8'), file).toMatch( + /\/\/# debugId=[0-9a-f-]{36}/, + ); + } + expect(readFileSync(join(outDir, 'index.html'), 'utf8')).toMatch(/integrity="sha384-/); + + const outcome = await load(browser, outDir); + expect(outcome.blocked).toEqual([]); + expect(outcome.ran).toBe(true); + expect(outcome.lazy).toBe('lazy-ok'); + expect(outcome.debugIds).toBeGreaterThanOrEqual(2); + }, 120_000); + + it('Rollup: the same, with a page emitted by a plugin that hashes what Rollup is about to write', async () => { + const outDir = join(root, 'dist-rollup'); + const sriHtml = { + name: 'sri-html', + generateBundle( + this: { emitFile(file: object): void }, + _output: unknown, + bundle: Record< + string, + { type: string; code?: string; isEntry?: boolean; fileName: string } + >, + ) { + const tags = Object.values(bundle) + .filter((entry) => entry.type === 'chunk' && entry.isEntry) + .map( + (entry) => + ``, + ); + this.emitFile({ + type: 'asset', + fileName: 'index.html', + source: `${tags.join('')}`, + }); + }, + }; + const { bugseeRollupPlugin } = await import('@bugsee/bundler-plugin-core'); + const bundle = await rollup({ + input: join(root, 'src', 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions()), sriHtml], + }); + await bundle.write({ dir: outDir, sourcemap: true }); + await bundle.close(); + + const outcome = await load(browser, outDir); + expect(outcome.blocked).toEqual([]); + expect(outcome.ran).toBe(true); + expect(outcome.lazy).toBe('lazy-ok'); + expect(outcome.debugIds).toBeGreaterThanOrEqual(2); + }, 120_000); + + it('CONTROL: the same Vite page stamped AFTER emit is blocked — the bug this exists to prevent', async () => { + const outDir = join(root, 'dist-vite-control'); + await viteBuild(viteApp(outDir, [lateSri()])); + await runBugseeCli(['sourcemaps', 'inject', outDir, '--allow-sri'], {}); + + const outcome = await load(browser, outDir); + expect(outcome.ran).toBe(false); + expect(outcome.blocked.length).toBeGreaterThan(0); + }, 120_000); +}); From de212ad91cf59debdc4e7049cf699c9a1da1ad85 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 11:41:00 +0500 Subject: [PATCH 03/39] docs: in-build stamping, stamp verification and safe map deletion Co-Authored-By: Claude Sonnet 5.5 --- docs/PROGRESS.md | 3 + docs/design/source-maps.md | 120 +++++++++++++++++++------ docs/source-maps-usage.md | 7 +- packages/bundler-plugin-core/README.md | 2 +- 4 files changed, 101 insertions(+), 31 deletions(-) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 7e9c5aa9d..b57d06c64 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1528,3 +1528,6 @@ Verified against current majors, all green with no adapter code changes: `@bugse `launch(undefined)` on Node/Bun died with an opaque `TypeError ... reading 'length'` inside `hashAppToken`, crashing the host at startup. Every runtime composition root (`@bugsee/node` + bun, `@bugsee/electron` `launchMain`/`launchRenderer` (guard before any wiring; a bad-token renderer sends no hello and takes no page slot), `@bugsee/browser` + umbrella/electron-renderer, `@bugsee/vercel-edge` + cloudflare, `@bugsee/webworker`) now calls the shared `createDisabledClientForMissingToken` (`@bugsee/core` `app-token.ts`) first: a missing / empty / whitespace-only / non-string token reports ONE `Bugsee: the app token is missing ...` error through `onError` (else `console.warn`) and returns a DISABLED client (never started, `launch()` is a no-op, claims no carrier slot, so a later valid launch works; the browser one resolves it, `showReportDialog()` resolves `null`). `@bugsee/webview` is untouched (the native host owns the token; the JS side never uses it on the wire). Tests: `app-token.test.ts` + `launch-missing-token.test.ts` per entry. **Follow-up 2 (issue #11).** `sveltekit-e2e` now wires `sveltekit({ preprocess: [componentAnnotatePreprocessor()] })` (the `@bugsee/sveltekit` README Kit 3 call, with the plugin imported by path) and asserts the SSR HTML carries `data-bugsee-component` (mutation-checked: removing `preprocess` fails it). The plugin is imported from its built dist (the e2e builds it first) because Kit 3 re-loads `vite.config.ts` in a plain-Node post-build process that cannot resolve the workspace's extensionless TS source. The README nits were already fixed (#157). Only Rollup 5 (still prerelease, `5.0.0-2` on the `beta` tag) remains open: keep watching. + +### 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. diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 3de0c2085..a3956b27a 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -130,8 +130,8 @@ are Rollup `writeBundle`, esbuild `onEnd` (registered through unplugin's `esbuil or `write: false`, which is what tsup always sets, with a notice; the plugin sets `sourcemap: 'external'` only when it is unset, and says so when it is `false`) and Rspack `afterEmit`, each calling `runPluginUpload` with the same SRI guard as Vite and webpack (#184; real esbuild and Rspack builds are exercised in -`plugin.real-build.test.ts`). Rspack has no in-compilation stamp stage wired, so it takes the post-emit inject path -(an SRI build is refused, not stamped). They do **not** cover **Angular**: its builder does not accept esbuild +`plugin.real-build.test.ts`). Rollup and Rspack stamp INSIDE the build like Vite and webpack 5 (§7.1); only esbuild +takes the post-emit inject path (an SRI build is refused there, not stamped). They do **not** cover **Angular**: its builder does not accept esbuild plugins, so Angular uses the documented CLI post-build recipe (`docs/source-maps-usage.md §2`). Next.js on webpack uses the webpack plugin. Bun, tsup and `tsc`/`swc` stay CLI-post-build (tsup via `onSuccess`). esbuild builds work on **per-build file lists**: the plugin sets `metafile: true` and, in `onEnd`, takes the build's own @@ -162,13 +162,11 @@ SDK's concern (needs `hermes-compose-source-map` + a preserved bundle id). ## 7.1 Subresource Integrity -**The plugin refuses to stamp a build that pins its own script hashes** (`sri.ts`, -`findSriProtectedScripts`). This is not a precaution — it is measured. - `sourcemaps inject` appends the debug-ID comment and the `_bugseeDebugIds` registration to every emitted `.js`. -A build that computed SRI hashes during emit — `webpack-subresource-integrity`, Angular's -`subresourceIntegrity: true` — has already written a hash of the PRE-stamp bytes into the HTML. Measured on a -real webpack 5.111 build loaded in **Chromium 151.0.7922.34**: +Done AFTER the bundler wrote its output, that changes bytes a build step may already have hashed: a build that +computed SRI hashes during emit (`webpack-subresource-integrity`, Rspack's `SubresourceIntegrityPlugin`, a Vite SRI +plugin, Angular's `subresourceIntegrity: true`) has written a hash of the PRE-stamp bytes into the HTML. Measured on +a real webpack 5.111 build loaded in **Chromium 151.0.7922.34**: | | `window.__ran` | console | |---|---|---| @@ -176,28 +174,101 @@ real webpack 5.111 build loaded in **Chromium 151.0.7922.34**: | after inject | **`false`** | `Failed to find a valid digest in the 'integrity' attribute for resource '…/main..js' … The resource has been blocked.` | `index.html` is byte-identical across that pair; only the JS grew, 114 → 472 bytes. The page loads and nothing -runs — strictly worse than having no source maps. +runs — strictly worse than having no source maps. Two mechanisms keep that from happening. + +### Stamp inside the build (the fix) -So `uploadSourcemaps` scans the output directory's HTML *before* anything is written, and when a ``); + this.emitFile({ + type: 'asset', + fileName: 'index.html', + source: `${tags.join('')}`, + }); + }, + }; + const bundle = await rollup({ + input: join(root, 'src', 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions()), html], + }); + await bundle.write({ + dir: out, + sourcemap: true, + entryFileNames: '[name]-[hash].js', + chunkFileNames: '[name]-[hash].js', + }); + await bundle.close(); + await expectHealthy(out, before); + }, 120_000); + + it('Vite: hashed chunk file names, the lazy chunk executes and pointers are consistent', async () => { + const out = join(root, 'dist-vite'); + const before = requests.length; + writeFileSync( + join(root, 'index.html'), + '\n', + ); + await viteBuild({ + root, + configFile: false, + logLevel: 'silent', + plugins: [bugseeVitePlugin(pluginOptions()) as never], + build: { outDir: out, emptyOutDir: true, minify: false, sourcemap: true }, + } as never); + await expectHealthy(out, before); + }, 120_000); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8f9fe40e1..20ed5810f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -758,6 +758,9 @@ importers: '@opentelemetry/sdk-trace-base': specifier: ^2.12.0 version: 2.12.0(@opentelemetry/api@1.10.0) + '@rspack/core': + specifier: 2.2.9 + version: 2.2.9 '@types/jsdom': specifier: ^21.1.7 version: 21.1.7 From 3782b60706d1297a872b5f3781a1c0c644edb2fa Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 14:19:54 +0500 Subject: [PATCH 18/39] fix(bundler-plugin-core): Vite workers keep the debug-id in their map (catch-up before upload) Vite builds a worker through its own sub-build and then puts it in the output: on Vite 8 the worker JS is stamped in memory but its map is regenerated WITHOUT the id, on Vite 7 neither worker file is in the bundle at generateBundle (not stamped at all). Either way the worker could not be symbolicated. Before the upload, the build's OWN (ownFiles) script maps that carry no debug-id are run through `sourcemaps inject` (explicit file list). Measured: inject on an already stamped bundle leaves its bytes unchanged and writes its id into the map, so nothing is stamped twice and an SRI pin on a stamped bundle is not invalidated; an UNSTAMPED bundle pinned by SRI is left alone and said; a public/ copy is never touched; the result is verified and restored like any stamp. - real Vite 7 and 8 builds (new Worker(new URL(...)) and ?worker, failOnError on/off) in the core suite, and in Chromium (lazy-chunk.e2e.ts): the worker runs, registers its id, its map carries the same id - AssetStore.read narrowed to Buffer (the string branch was dead) - docs: worker sub-builds and the catch-up Co-Authored-By: Claude Sonnet 5.5 --- docs/design/source-maps.md | 19 ++ .../src/orchestrate.stamp.test.ts | 176 ++++++++++++++++++ .../bundler-plugin-core/src/orchestrate.ts | 91 ++++++++- .../src/plugin.in-build.real-build.test.ts | 71 +++++++ .../bundler-plugin-core/src/stamp-assets.ts | 5 +- packages/instrumentation-tests/package.json | 1 + .../test/lazy-chunk.e2e.ts | 122 +++++++++++- pnpm-lock.yaml | 79 ++------ 8 files changed, 485 insertions(+), 79 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 0b57c6036..501136ecb 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -276,6 +276,25 @@ affected; a hashed-lazy-chunk real build of each runs in Chromium (`instrumentat which also covers Rspack with `SubresourceIntegrityPlugin` and checks that every bundle's `sourceMappingURL` and map `file` name a file that exists). +### Vite workers (sub-builds), and the catch-up + +Vite builds a worker through its OWN sub-build and then puts it into the output: measured, on Vite 8 the worker's +JS is an asset of the main bundle at `generateBundle` (so it is stamped in memory) while its `.map` is +REGENERATED afterwards WITHOUT the id; on Vite 7 neither worker file is in the bundle at `generateBundle` +(both are emitted later), so the worker is not stamped at all. Either way the worker file and its map end up +without a shared id (a worker crash could not be symbolicated). The user's plugin does not run inside the worker +sub-build unless it is listed in `worker.plugins` (verified with real Vite 7 and 8), so detecting and skipping +that sub-build is not the issue; the fix is a **catch-up before the upload**: the build's OWN (`ownFiles`, the +final bundle at `writeBundle`, which does list the worker and its map) script maps that carry no debug-id are +run through `sourcemaps inject` (an explicit file list). Measured with bugsee-cli 0.9.0: inject on an +already-stamped bundle leaves its bytes unchanged and writes its id into the map, so a bundle stamped in memory +is not stamped twice and a Subresource-Integrity pin on it is not invalidated. A bundle that is NOT stamped yet +and is pinned by an integrity hash is left alone and said (stamping it would break the page). A `public/` copy +is not in `ownFiles` and is never touched. The result is verified (and restored on failure) like any other +stamp. Covered by real Vite 7 and 8 builds with `new Worker(new URL(...))` and `?worker`, and in Chromium +(`instrumentation-tests/test/lazy-chunk.e2e.ts`): the worker runs, registers its id, and its map has the same +id. (The hand-rolled SRI step pins only the entry chunks in `index.html`, never worker files.) + ### Maps that are not the bundle sibling `sourcemapFileNames` can put a map anywhere in the output (`maps/[name].js.map`, bundles in `js/`). `inject` diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index 44770eaf8..d38bab441 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -1013,3 +1013,179 @@ describe('ownFiles: only what THIS build emitted is deleted', () => { expect(await left()).toEqual(['other.css.map']); }); }); + +describe("catch-up: the build's OWN script maps that carry no debug-id (Vite workers) are stamped before the upload", () => { + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-catchup-')); + }); + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + const STAMPED = `w();\n//# sourceMappingURL=w.js.map\n${STAMP_FOR_CATCHUP()}`; + function STAMP_FOR_CATCHUP(): string { + return `\n;1;\n//# debugId=${ID}\n`; + } + const plainMap = '{"version":3,"sources":["w.ts"],"names":[],"mappings":"AAAA"}'; + /** A faithful-enough CLI: inject stamps the bundle if it is not (appending), and puts its id in the map. */ + const cli = () => { + const calls: string[][] = []; + const run = vi.fn(async (args: string[]): Promise => { + calls.push(args); + if (args[1] === 'inject') { + const paths = args.slice(2); + for (const path of paths.filter((x) => /\.js$/.test(x))) { + const code = await readFile(path, 'utf8'); + if (!code.includes('//# debugId=')) { + await writeFile(path, code + STAMP_FOR_CATCHUP()); + } + } + for (const path of paths.filter((x) => x.endsWith('.map'))) { + await writeFile( + path, + JSON.stringify({ ...JSON.parse(await readFile(path, 'utf8')), debugId: ID }), + ); + } + } + return { code: 0, stdout: '', stderr: '' }; + }); + return { run, calls }; + }; + const opts = (extra: object = {}) => ({ + ...base, + outDir: dir, + preStamped: true, + verifySri: async () => [], + findSri: async () => [], + ownFiles: ['w.js', 'w.js.map'], + onNotice: () => undefined, + ...extra, + }); + + it('an already-stamped worker whose map lost its id: injected (idempotent), then uploaded and deleted, no error', async () => { + await writeFile(join(dir, 'w.js'), STAMPED); + await writeFile(join(dir, 'w.js.map'), plainMap); + const { run, calls } = cli(); + const onError = vi.fn(); + const result = await uploadSourcemaps(opts({ run, onError, stampedBundles: ['w.js'] })); + const inject = calls.find((c) => c[1] === 'inject') as string[]; + expect(inject.slice(2)).toEqual([join(dir, 'w.js'), join(dir, 'w.js.map')]); + expect(await readFile(join(dir, 'w.js'), 'utf8')).toBe(STAMPED); // untouched + expect(onError).not.toHaveBeenCalled(); + expect(result.uploaded).toBe(true); + expect(await readdir(dir)).toEqual(['w.js']); + }); + + it('an UNSTAMPED worker (Vite 7: never in the stamped bundle) is stamped with its map, unless SRI pins it', async () => { + await writeFile(join(dir, 'w.js'), 'w();\n//# sourceMappingURL=w.js.map\n'); + await writeFile(join(dir, 'w.js.map'), plainMap); + const { run } = cli(); + await uploadSourcemaps(opts({ run })); + expect(await readFile(join(dir, 'w.js'), 'utf8')).toContain('//# debugId='); + expect(await readdir(dir)).toEqual(['w.js']); + + // Pinned by an integrity hash: stamping would break the page, so it is left alone and said. + await writeFile(join(dir, 'w.js'), 'w();\n//# sourceMappingURL=w.js.map\n'); + await writeFile(join(dir, 'w.js.map'), plainMap); + const notices: string[] = []; + const second = cli(); + await uploadSourcemaps( + opts({ + run: second.run, + findSri: async () => [ + { html: join(dir, 'index.html'), script: join(dir, 'w.js'), integrity: 'sha384-X' }, + ], + onNotice: (m: string) => notices.push(m), + }), + ); + expect(second.calls.some((c) => c[1] === 'inject')).toBe(false); + expect(await readFile(join(dir, 'w.js'), 'utf8')).not.toContain('debugId'); + expect(await readdir(dir)).toContain('w.js.map'); + expect(notices.join('\n')).toContain('w.js'); + expect(notices.join('\n')).toContain('Subresource Integrity'); + }); + + it('says a blocked (SRI-pinned, unstamped) worker on console.warn when no notice sink is given', async () => { + await writeFile(join(dir, 'w.js'), 'w();\n//# sourceMappingURL=w.js.map\n'); + await writeFile(join(dir, 'w.js.map'), plainMap); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + await uploadSourcemaps( + opts({ + run: cli().run, + onNotice: undefined, + findSri: async () => [ + { html: join(dir, 'i.html'), script: join(dir, 'w.js'), integrity: 'sha384-X' }, + ], + }), + ); + expect(String(warn.mock.calls[0]?.[0])).toContain('Subresource Integrity'); + } finally { + warn.mockRestore(); + } + }); + + it('a pinned worker that is ALREADY stamped is still caught up (its bytes do not change)', async () => { + await writeFile(join(dir, 'w.js'), STAMPED); + await writeFile(join(dir, 'w.js.map'), plainMap); + const { run, calls } = cli(); + await uploadSourcemaps( + opts({ + run, + findSri: async () => [ + { html: join(dir, 'i.html'), script: join(dir, 'w.js'), integrity: 'sha384-X' }, + ], + }), + ); + expect(calls.some((c) => c[1] === 'inject')).toBe(true); + expect(await readFile(join(dir, 'w.js'), 'utf8')).toBe(STAMPED); + }); + + it('never touches a map this build did not emit (a publicDir vendor script), nor without ownFiles, nor on a dry run', async () => { + await writeFile(join(dir, 'vendor.js'), 'v();\n//# sourceMappingURL=vendor.js.map\n'); + await writeFile(join(dir, 'vendor.js.map'), plainMap); + for (const extra of [ + {}, + { ownFiles: undefined }, + { dryRun: true, ownFiles: ['vendor.js', 'vendor.js.map'] }, + ]) { + const { run, calls } = cli(); + await uploadSourcemaps(opts({ run, ...extra })); + expect(calls.some((c) => c[1] === 'inject')).toBe(false); + } + expect(await readFile(join(dir, 'vendor.js'), 'utf8')).not.toContain('debugId'); + }); + + it('a map with no bundle beside it, or a css map, is not a catch-up candidate', async () => { + await writeFile(join(dir, 'w.js.map'), plainMap); // no w.js + await writeFile(join(dir, 'a.css.map'), plainMap); + await writeFile(join(dir, 'x.ts'), 'x();\n'); // a file beside the map that is not a script bundle + await writeFile(join(dir, 'x.ts.map'), plainMap); + const { run, calls } = cli(); + const onError = vi.fn(); + await uploadSourcemaps( + opts({ run, onError, ownFiles: ['w.js.map', 'a.css.map', 'x.ts', 'x.ts.map'] }), + ); + expect(calls.some((c) => c[1] === 'inject')).toBe(false); + expect(onError).not.toHaveBeenCalled(); + expect(await readFile(join(dir, 'x.ts'), 'utf8')).toBe('x();\n'); + }); + + it('a catch-up stamp that does not verify is restored and reported (thrown under failOnError)', async () => { + await writeFile(join(dir, 'w.js'), 'w();\n//# sourceMappingURL=w.js.map\n'); + await writeFile(join(dir, 'w.js.map'), plainMap); + const broken = vi.fn(async (args: string[]): Promise => { + if (args[1] === 'inject') { + await writeFile(join(dir, 'w.js'), '{{'); + } + return { code: 0, stdout: '', stderr: '' }; + }); + const errors: unknown[] = []; + await uploadSourcemaps(opts({ run: broken, onError: (e: unknown) => errors.push(e) })); + expect(await readFile(join(dir, 'w.js'), 'utf8')).toBe('w();\n//# sourceMappingURL=w.js.map\n'); + expect(String(errors[0])).toContain('did not verify'); + await expect(uploadSourcemaps(opts({ run: broken, failOnError: true }))).rejects.toThrow( + /did not verify/, + ); + }); +}); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 988b98adb..2f83a7686 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -1,8 +1,9 @@ // SM-A2 — orchestrate a source-map upload by driving `bugsee-cli`: inject debug-IDs, upload the maps, then // delete the client `.map` files (privacy). Each side-effecting step is behind an injectable seam so the // orchestration is unit-tested without a real binary or filesystem. -import { readdir, unlink } from 'node:fs/promises'; +import { access, readdir, readFile, unlink } from 'node:fs/promises'; import { join, relative, resolve } from 'node:path'; +import { readDebugId } from './debug-ids'; import { type RunBugseeCliOptions, runBugseeCli, type SpawnResult } from './run-cli'; import { findIntegrityMismatches, findSriProtectedScripts, type SriProtectedScript } from './sri'; import { @@ -192,6 +193,20 @@ export async function defaultDeleteMapFiles( return deleted; } +/** The error for a stamp that did not verify: what was restored, and anything that could not be. */ +function verifyFailure( + issues: Parameters[0], + restored: readonly string[], + failed: ReadonlyArray<{ path: string; error: string }>, +): Error { + return new Error( + `the debug-ID stamp did not verify, so ${restored.length} file(s) were restored to the bundler's original bytes (${formatIssues(issues)})` + + (failed.length > 0 + ? `; COULD NOT restore ${failed.map((f) => `${f.path} (${f.error})`).join(', ')}, which still carry the unverified stamp` + : ''), + ); +} + /** Where a contained upload failure goes when the user gave no `onError`. */ function defaultUploadErrorHandler(error: unknown): void { console.warn(`[bugsee] source-map upload skipped: ${String(error)}`); @@ -243,6 +258,73 @@ export async function uploadSourcemaps( // upload was skipped; here it was not. (options.onError ?? ((e: unknown) => console.warn(`[bugsee] ${String(e)}`)))(error); } + // 0'''. CATCH UP the build's OWN script maps that still carry no debug-id. Vite builds a worker through a + // sub-build, then copies its code into the output while REGENERATING its map (Vite 8) or emitting both + // after our `generateBundle` (Vite 7): the worker file is stamped without its map carrying the id, or + // not stamped at all. `sourcemaps inject` on an already-stamped bundle leaves its bytes unchanged + // and puts the bundle's id in the map (measured, bugsee-cli 0.9.0), so this is idempotent. Only maps + // this build emitted (`ownFiles`) are touched, never a `public/` copy; a bundle that is not stamped + // yet and is pinned by Subresource Integrity is left alone (stamping it would break the page). + if (!dryRun && files === undefined && options.ownFiles !== undefined) { + const own = ownedBy(outDir, options.ownFiles); + const unkeyed = ( + await (options.partitionMaps ?? partitionByKeyed)( + ( + await (options.listUploadMaps ?? listOutputMaps)(outDir) + ).filter((map) => isUploadableMap(map) && own(map)), + ) + ).kept; + const pairs: Array<{ bundle: string; map: string }> = []; + for (const map of unkeyed) { + const bundle = map.slice(0, -'.map'.length); + if ( + /\.[cm]?js$/i.test(bundle) && + (await access(bundle).then( + () => true, + () => false, + )) + ) { + pairs.push({ bundle, map }); + } + } + if (pairs.length > 0) { + const pinned = new Set( + (await (options.findSri ?? findSriProtectedScripts)(outDir)).map((pin) => + resolve(pin.script), + ), + ); + const eligible: typeof pairs = []; + const blocked: typeof pairs = []; + for (const pair of pairs) { + const stamped = readDebugId(await readFile(pair.bundle, 'utf8')) !== undefined; + (pinned.has(resolve(pair.bundle)) && !stamped ? blocked : eligible).push(pair); + } + if (blocked.length > 0) { + (options.onNotice ?? ((m: string) => console.warn(`[bugsee] ${m}`)))( + `${blocked.length} script(s) this build emitted were not stamped because Subresource Integrity pins them, so their maps were not uploaded: ${blocked.map((pair) => pair.bundle).join(', ')}`, + ); + } + if (eligible.length > 0) { + const targets = eligible.flatMap((pair) => [pair.bundle, pair.map]); + const snapshot = await snapshotStampFiles({ files: targets }, options.spillRoot); + try { + for (const batch of inBatches(targets)) { + await run(['sourcemaps', 'inject', ...batch], cliOptions); + } + const { issues, restored, failed } = await verifyAndRestore(snapshot); + if (issues.length > 0) { + const failure = verifyFailure(issues, restored, failed); + if (options.failOnError === true) { + throw failure; + } + onError(failure); + } + } finally { + await snapshot.dispose(); + } + } + } + } // 0''. The same stamp, as it is on disk after the bundler wrote the output. A later step can rewrite a // chunk or REGENERATE its map after the in-build stamp (Vite does, for dynamic-import preload // markers), and a bundle that looks stamped with a map that no longer carries its id cannot be @@ -332,12 +414,7 @@ export async function uploadSourcemaps( if (original !== undefined) { const { issues, restored, failed } = await verifyAndRestore(original); if (issues.length > 0) { - const failure = new Error( - `the debug-ID stamp did not verify, so ${restored.length} file(s) were restored to the bundler's original bytes (${formatIssues(issues)})` + - (failed.length > 0 - ? `; COULD NOT restore ${failed.map((f) => `${f.path} (${f.error})`).join(', ')}, which still carry the unverified stamp` - : ''), - ); + const failure = verifyFailure(issues, restored, failed); if (options.failOnError === true) { throw failure; } diff --git a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts index 92b314434..ed3999688 100644 --- a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts @@ -1055,3 +1055,74 @@ describeReal('Rspack: # in a file name is part of the name', () => { }); } }); + +// Vite builds a worker through its OWN sub-build and then copies the worker code into the main output while +// REGENERATING the worker's `.map` (Vite 8) or emitting both after our generateBundle (Vite 7): the worker file is +// stamped without its map carrying the id, or not stamped at all. The upload catches up the build's OWN unkeyed +// script maps (inject is idempotent on an already-stamped bundle and puts its id in the map). +describeReal('Vite workers: the worker bundle and its map carry the same debug-id', () => { + const workerApp = (name: string, form: 'url' | 'query'): { dir: string; out: string } => { + const app = makeApp(name, { lazy: false }); + writeFileSync(join(app.dir, 'w.js'), "postMessage('worker-ok');\n"); + writeFileSync( + join(app.dir, 'index.js'), + form === 'url' + ? "const w = new Worker(new URL('./w.js', import.meta.url), { type: 'module' });\nw.onmessage = (e) => console.log(e.data);\n" + : "import W from './w.js?worker';\nconst w = new W();\nw.onmessage = (e) => console.log(e.data);\n", + ); + return app; + }; + const idOf = (code: string): string | undefined => + /\/\/# debugId=([0-9a-f-]{36})/.exec(code)?.[1]; + + for (const [label, build] of [ + ['Vite 8 (Rolldown)', viteBuild], + ['Vite 7 (Rollup)', vite7Build], + ] as const) { + for (const form of ['url', 'query'] as const) { + for (const failOnError of [true, false]) { + it(`${label}, ${form} worker (failOnError ${failOnError}): stamped, same id in its map, uploaded and deleted`, async () => { + const app = workerApp( + `vite-worker-${label.replace(/\W+/g, '')}-${form}-${failOnError}`, + form, + ); + const before = requests.length; + const errors: unknown[] = []; + // Keep the maps for the first build so their ids can be compared. + await build( + viteConfig(app, [ + bugseeVite({ + failOnError, + deleteMaps: false, + onError: (e: unknown) => errors.push(e), + onNotice: () => undefined, + }), + ]), + ); + expect(errors.map(String)).toEqual([]); + expect(requests.length, 'uploaded').toBeGreaterThan(before); + const files = readdirSync(join(app.out, 'assets')); + const bundles = files.filter((f) => f.endsWith('.js')); + expect(bundles.length).toBeGreaterThanOrEqual(2); // main + worker + for (const bundle of bundles) { + const id = idOf(readFileSync(join(app.out, 'assets', bundle), 'utf8')); + expect(id, `${bundle} stamped`).toBeDefined(); + const map = JSON.parse( + readFileSync(join(app.out, 'assets', `${bundle}.map`), 'utf8'), + ) as { debugId?: string }; + expect(map.debugId, `${bundle}.map carries the same id`).toBe(id); + } + // And with the default (delete after a confirmed upload) nothing is left behind. + const app2 = workerApp( + `vite-worker-del-${label.replace(/\W+/g, '')}-${form}-${failOnError}`, + form, + ); + await build(viteConfig(app2, [bugseeVite({ failOnError, onNotice: () => undefined })])); + expect( + (readdirSync(join(app2.out, 'assets')) as string[]).filter((f) => f.endsWith('.map')), + ).toEqual([]); + }); + } + } + } +}); diff --git a/packages/bundler-plugin-core/src/stamp-assets.ts b/packages/bundler-plugin-core/src/stamp-assets.ts index b49eb4b44..60dde7e48 100644 --- a/packages/bundler-plugin-core/src/stamp-assets.ts +++ b/packages/bundler-plugin-core/src/stamp-assets.ts @@ -23,7 +23,7 @@ import { formatIssues, type StampIssue, verifyStamp } from './verify-stamp'; /** The slice of a compilation's asset table this needs — no bundler types in the core. */ export interface AssetStore { names(): string[]; - read(name: string): Buffer | string; + read(name: string): Buffer; update(name: string, content: Buffer): void; /** * Called for EVERY asset about to be written back, before ANY is: throw to refuse the whole stamp (a store @@ -147,8 +147,7 @@ export async function stampAssets( try { const before = new Map(); for (const name of staged) { - const content = store.read(name); - const bytes = typeof content === 'string' ? Buffer.from(content) : content; + const bytes = store.read(name); before.set(stagedAs(name), bytes); const path = join(root, stagedAs(name)); await mkdir(dirname(path), { recursive: true }); diff --git a/packages/instrumentation-tests/package.json b/packages/instrumentation-tests/package.json index c99d16dff..6e7958865 100644 --- a/packages/instrumentation-tests/package.json +++ b/packages/instrumentation-tests/package.json @@ -58,6 +58,7 @@ "tsx": "^4.23.15", "typescript": "^6.0.3", "vite": "^8.3.5", + "vite7": "npm:vite@7.3.6", "vue": "^3.5.0", "webpack": "^5.112.2", "webpack-subresource-integrity": "^5.1.0", diff --git a/packages/instrumentation-tests/test/lazy-chunk.e2e.ts b/packages/instrumentation-tests/test/lazy-chunk.e2e.ts index d39528892..fbfbfb791 100644 --- a/packages/instrumentation-tests/test/lazy-chunk.e2e.ts +++ b/packages/instrumentation-tests/test/lazy-chunk.e2e.ts @@ -7,7 +7,15 @@ // its result back as a string source. // // Real webpack and Rspack builds, the real bugsee-cli, a real Chromium that triggers the lazy `import()`. -import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; import { createServer, type Server } from 'node:http'; import { tmpdir } from 'node:os'; import { dirname, extname, join, normalize } from 'node:path'; @@ -19,6 +27,7 @@ import HtmlWebpackPlugin from 'html-webpack-plugin'; import { type Browser, chromium } from 'playwright'; import { rollup } from 'rollup'; import { build as viteBuild } from 'vite'; +import { build as vite7Build } from 'vite7'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import webpack from 'webpack'; @@ -324,3 +333,114 @@ describe('a content-hashed lazy chunk still loads after the in-build stamp', () await expectHealthy(out, before); }, 120_000); }); + +// Vite builds a worker through its own sub-build and copies it into the output, regenerating (Vite 8) or +// emitting after our generateBundle (Vite 7) its map: the worker bundle must still carry the SAME debug id as its +// map, and the worker must run in a real browser and register its id. +describe('Vite workers in a real browser', () => { + let wroot: string; + let wbrowser: Browser; + beforeAll(async () => { + wroot = realpathSync(mkdtempSync(join(tmpdir(), 'bugsee-worker-e2e-'))); + // The previous describe closed the shared collector in its afterAll: start our own. + collector = createServer((req, res) => { + requests.push(req.url ?? ''); + req.resume(); + req.on('end', () => { + res.setHeader('content-type', 'application/json'); + res.end( + JSON.stringify({ ok: false, error: { type: 'DuplicateSymbolsFoundError', code: 16004 } }), + ); + }); + }); + await new Promise((r) => collector.listen(0, '127.0.0.1', r)); + endpoint = `http://127.0.0.1:${(collector.address() as { port: number }).port}`; + wbrowser = await chromium.launch({ headless: true }); + }, 60_000); + afterAll(async () => { + await wbrowser?.close(); + await new Promise((r) => collector?.close(() => r())); + if (wroot) rmSync(wroot, { recursive: true, force: true }); + }); + + // The registration stub is appended AFTER the worker's own code, so report on a later task. + const WORKER = + 'setTimeout(() => postMessage({ ok: true, ids: Object.keys(self._bugseeDebugIds ?? {}).length }), 0);\n'; + const forms = { + url: "const w = new Worker(new URL('./w.js', import.meta.url), { type: 'module' });\nw.onmessage = (e) => { window.__worker = e.data; };\n", + query: + "import W from './w.js?worker';\nconst w = new W();\nw.onmessage = (e) => { window.__worker = e.data; };\n", + } as const; + + for (const [label, build] of [ + ['Vite 8', viteBuild], + ['Vite 7', vite7Build], + ] as const) { + for (const form of ['url', 'query'] as const) { + for (const failOnError of [true, false]) { + it(`${label}, ${form} worker (failOnError ${failOnError}): runs, registers its id, map carries the same id`, async () => { + const dir = join(wroot, `${label}-${form}-${failOnError}`.replace(/\W+/g, '-')); + mkdirSync(join(dir, 'src'), { recursive: true }); + writeFileSync( + join(dir, 'index.html'), + '\n', + ); + writeFileSync(join(dir, 'src', 'index.js'), forms[form]); + writeFileSync(join(dir, 'src', 'w.js'), WORKER); + const out = join(dir, 'dist'); + const before = requests.length; + const errors: unknown[] = []; + await build({ + root: dir, + configFile: false, + logLevel: 'silent', + plugins: [ + bugseeVitePlugin({ + ...pluginOptions(), + failOnError, + onError: (e: unknown) => errors.push(e), + }) as never, + ], + build: { outDir: out, emptyOutDir: true, minify: false, sourcemap: true }, + } as never); + expect(errors.map(String)).toEqual([]); + expect(requests.length, 'maps uploaded').toBeGreaterThan(before); + // every bundle (main + worker) has a map with the SAME id + const assets = readdirSync(join(out, 'assets')); + const bundles = assets.filter((f) => f.endsWith('.js')); + expect(bundles.length).toBeGreaterThanOrEqual(2); + for (const bundle of bundles) { + const id = /\/\/# debugId=([0-9a-f-]{36})/.exec( + readFileSync(join(out, 'assets', bundle), 'utf8'), + )?.[1]; + expect(id, `${bundle} stamped`).toBeDefined(); + const map = JSON.parse(readFileSync(join(out, 'assets', `${bundle}.map`), 'utf8')) as { + debugId?: string; + }; + expect(map.debugId, `${bundle}.map`).toBe(id); + } + const { url, server } = await serve(out); + const page = await wbrowser.newPage(); + try { + await page.goto(url); + await page + .waitForFunction( + () => (window as { __worker?: unknown }).__worker !== undefined, + null, + { timeout: 5_000 }, + ) + .catch(() => undefined); + const worker = await page.evaluate( + () => (window as { __worker?: { ok: boolean; ids: number } }).__worker, + ); + expect(worker?.ok).toBe(true); + expect(worker?.ids, 'the worker registered its debug id').toBeGreaterThanOrEqual(1); + } finally { + await page.close(); + await new Promise((r) => server.close(() => r())); + } + }, 120_000); + } + } + } +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 20ed5810f..3bc5f2ab8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -790,7 +790,7 @@ importers: version: 0.8.3 html-webpack-plugin: specifier: ^5.6.8 - version: 5.6.8(@rspack/core@2.2.9)(webpack@5.112.2(esbuild@0.28.2)(postcss@8.5.32)) + version: 5.6.8(@rspack/core@2.2.9)(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32)) jsdom: specifier: ^25.0.1 version: 25.0.1 @@ -818,15 +818,18 @@ importers: vite: specifier: ^8.3.5 version: 8.3.5(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) + vite7: + specifier: npm:vite@7.3.6 + version: vite@7.3.6(@types/node@22.20.5)(jiti@2.7.0)(lightningcss@1.33.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) vue: specifier: ^3.5.0 version: 3.5.44(typescript@6.0.3) webpack: specifier: ^5.112.2 - version: 5.112.2(esbuild@0.28.2)(postcss@8.5.32) + version: 5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32) webpack-subresource-integrity: specifier: ^5.1.0 - version: 5.1.0(html-webpack-plugin@5.6.8(@rspack/core@2.2.9)(webpack@5.112.2(esbuild@0.28.2)(postcss@8.5.32)))(webpack@5.112.2(esbuild@0.28.2)(postcss@8.5.32)) + version: 5.1.0(html-webpack-plugin@5.6.8(@rspack/core@2.2.9)(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32)))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32)) zone.js: specifier: 0.16.3 version: 0.16.3 @@ -15396,7 +15399,7 @@ snapshots: html-void-elements@3.0.0: {} - html-webpack-plugin@5.6.8(@rspack/core@2.2.9)(webpack@5.112.2(esbuild@0.28.2)(postcss@8.5.32)): + html-webpack-plugin@5.6.8(@rspack/core@2.2.9)(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32)): dependencies: '@types/html-minifier-terser': 6.1.0 html-minifier-terser: 6.1.0 @@ -15405,7 +15408,7 @@ snapshots: tapable: 2.3.3 optionalDependencies: '@rspack/core': 2.2.9 - webpack: 5.112.2(esbuild@0.28.2)(postcss@8.5.32) + webpack: 5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32) htmlparser2@6.1.0: dependencies: @@ -16149,18 +16152,6 @@ snapshots: esbuild: 0.28.2 lightningcss: 1.33.0 postcss: 8.5.32 - optional: true - - minimizer-webpack-plugin@5.13.1(esbuild@0.28.2)(postcss@8.5.32)(webpack@5.112.2(esbuild@0.28.2)(postcss@8.5.32)): - dependencies: - '@jridgewell/trace-mapping': 0.3.31 - jest-worker: 27.5.1 - schema-utils: 4.8.1(webpack@5.112.2(esbuild@0.28.2)(postcss@8.5.32)) - terser: 5.51.2 - webpack: 5.112.2(esbuild@0.28.2)(postcss@8.5.32) - optionalDependencies: - esbuild: 0.28.2 - postcss: 8.5.32 minipass@7.1.3: {} @@ -17760,16 +17751,6 @@ snapshots: ajv-keywords: 5.1.0(ajv@8.20.0) optionalDependencies: webpack: 5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32) - optional: true - - schema-utils@4.8.1(webpack@5.112.2(esbuild@0.28.2)(postcss@8.5.32)): - dependencies: - '@types/json-schema': 7.0.15 - ajv: 8.20.0 - ajv-formats: 3.0.1(ajv@8.20.0) - ajv-keywords: 5.1.0(ajv@8.20.0) - optionalDependencies: - webpack: 5.112.2(esbuild@0.28.2)(postcss@8.5.32) scule@1.3.0: {} @@ -19108,12 +19089,12 @@ snapshots: webpack-sources@3.6.0: {} - webpack-subresource-integrity@5.1.0(html-webpack-plugin@5.6.8(@rspack/core@2.2.9)(webpack@5.112.2(esbuild@0.28.2)(postcss@8.5.32)))(webpack@5.112.2(esbuild@0.28.2)(postcss@8.5.32)): + webpack-subresource-integrity@5.1.0(html-webpack-plugin@5.6.8(@rspack/core@2.2.9)(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32)))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32)): dependencies: typed-assert: 1.0.9 - webpack: 5.112.2(esbuild@0.28.2)(postcss@8.5.32) + webpack: 5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32) optionalDependencies: - html-webpack-plugin: 5.6.8(@rspack/core@2.2.9)(webpack@5.112.2(esbuild@0.28.2)(postcss@8.5.32)) + html-webpack-plugin: 5.6.8(@rspack/core@2.2.9)(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32)) webpack-virtual-modules@0.6.2: {} @@ -19153,44 +19134,6 @@ snapshots: - sharp - svgo - uglify-js - optional: true - - webpack@5.112.2(esbuild@0.28.2)(postcss@8.5.32): - dependencies: - '@types/estree': 1.0.9 - '@types/json-schema': 7.0.15 - '@webassemblyjs/ast': 1.14.1 - '@webassemblyjs/wasm-edit': 1.14.1 - '@webassemblyjs/wasm-parser': 1.14.1 - browserslist: 4.29.4 - chrome-trace-event: 1.0.4 - enhanced-resolve: 5.26.0 - es-module-lexer: 2.3.2 - events: 3.3.0 - graceful-fs: 4.2.11 - mime-db: 1.54.0 - minimizer-webpack-plugin: 5.13.1(esbuild@0.28.2)(postcss@8.5.32)(webpack@5.112.2(esbuild@0.28.2)(postcss@8.5.32)) - schema-utils: 4.8.1(webpack@5.112.2(esbuild@0.28.2)(postcss@8.5.32)) - tapable: 2.3.3 - watchpack: 2.6.3 - webpack-sources: 3.6.0 - transitivePeerDependencies: - - '@minify-html/node' - - '@napi-rs/image' - - '@swc/core' - - '@swc/css' - - '@swc/html' - - clean-css - - cssnano - - csso - - esbuild - - html-minifier-terser - - imagemin - - lightningcss - - postcss - - sharp - - svgo - - uglify-js whatwg-encoding@3.1.1: dependencies: From 837bd6ca36e4bdb13e90b2b5a3d2165fd7386e45 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 15:41:01 +0500 Subject: [PATCH 19/39] fix(bundler-plugin-core): the worker catch-up never costs the build its other maps The catch-up fed every own unkeyed script map to one `sourcemaps inject` batch; one empty / non-JSON / [] / null map made the CLI exit 11 for the batch, and the throw hit the outer catch: the upload of every correctly stamped map was lost. - maps that are not a JSON object are skipped (left untouched, reported as unkeyed) - a rejected batch is retried pair by pair; a failing pair is reported, the rest stamp - whatever was rewritten is verified and restored; only an unverified stamp that could NOT be restored is a failOnError failure - the whole catch-up is wrapped: an unexpected failure is reported and the upload goes on - "stamped" means the debug-id comment AND the registration (a foreign comment alone would get the registration appended, changing pinned bytes) - real Vite 7/8 builds with an own script + empty / 'not json' / [] / null map (failOnError on/off) upload the other maps; .mjs/.cjs, no-notice, spill-dispose tests Co-Authored-By: Claude Sonnet 5.5 --- docs/design/source-maps.md | 17 +- .../src/orchestrate.stamp.test.ts | 256 +++++++++++++++++- .../bundler-plugin-core/src/orchestrate.ts | 176 ++++++++---- .../src/plugin.in-build.real-build.test.ts | 55 ++++ 4 files changed, 439 insertions(+), 65 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 501136ecb..eb9ec7e8d 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -286,11 +286,18 @@ without a shared id (a worker crash could not be symbolicated). The user's plugi sub-build unless it is listed in `worker.plugins` (verified with real Vite 7 and 8), so detecting and skipping that sub-build is not the issue; the fix is a **catch-up before the upload**: the build's OWN (`ownFiles`, the final bundle at `writeBundle`, which does list the worker and its map) script maps that carry no debug-id are -run through `sourcemaps inject` (an explicit file list). Measured with bugsee-cli 0.9.0: inject on an -already-stamped bundle leaves its bytes unchanged and writes its id into the map, so a bundle stamped in memory -is not stamped twice and a Subresource-Integrity pin on it is not invalidated. A bundle that is NOT stamped yet -and is pinned by an integrity hash is left alone and said (stamping it would break the page). A `public/` copy -is not in `ownFiles` and is never touched. The result is verified (and restored on failure) like any other +run through `sourcemaps inject` (an explicit file list). Measured with bugsee-cli 0.9.0: inject on a +bundle that already carries BOTH its debug-id comment and the runtime registration leaves its bytes unchanged +and writes its id into the map, so such a bundle is not stamped twice and a Subresource-Integrity pin on it is +not invalidated. "Stamped" therefore means both (a foreign `//# debugId=` comment alone would still get the +registration appended): a pinned bundle that is not fully stamped is left alone and said (stamping it would +change pinned bytes). A `public/` copy is not in `ownFiles` and is never touched. The catch-up is **best +effort** and never costs the build its other maps: a map that is not a JSON object (empty, garbage, `[]`, +`null`; the CLI rejects the whole batch for one) is skipped and left untouched, a batch the CLI rejects is +retried pair by pair, a failing pair is reported (`onError`) and the rest still stamp and upload, whatever was +rewritten is verified and restored, and an unexpected failure inside it is reported and the upload goes on. +Only a stamp that did not verify AND could not be restored (an unverified stamp still on disk) is a +`failOnError` failure. The result is verified (and restored on failure) like any other stamp. Covered by real Vite 7 and 8 builds with `new Worker(new URL(...))` and `?worker`, and in Chromium (`instrumentation-tests/test/lazy-chunk.e2e.ts`): the worker runs, registers its id, and its map has the same id. (The hand-rolled SRI step pins only the entry chunks in `index.html`, never worker files.) diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index d38bab441..d89b5b183 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -1024,7 +1024,7 @@ describe("catch-up: the build's OWN script maps that carry no debug-id (Vite wor }); const STAMPED = `w();\n//# sourceMappingURL=w.js.map\n${STAMP_FOR_CATCHUP()}`; function STAMP_FOR_CATCHUP(): string { - return `\n;1;\n//# debugId=${ID}\n`; + return `\n;!function(){try{var e=globalThis;e._bugseeDebugIds=e._bugseeDebugIds||{}}catch(e){}}();\n//# debugId=${ID}\n`; } const plainMap = '{"version":3,"sources":["w.ts"],"names":[],"mappings":"AAAA"}'; /** A faithful-enough CLI: inject stamps the bundle if it is not (appending), and puts its id in the map. */ @@ -1171,7 +1171,7 @@ describe("catch-up: the build's OWN script maps that carry no debug-id (Vite wor expect(await readFile(join(dir, 'x.ts'), 'utf8')).toBe('x();\n'); }); - it('a catch-up stamp that does not verify is restored and reported (thrown under failOnError)', async () => { + it('a catch-up stamp that does not verify is restored and reported', async () => { await writeFile(join(dir, 'w.js'), 'w();\n//# sourceMappingURL=w.js.map\n'); await writeFile(join(dir, 'w.js.map'), plainMap); const broken = vi.fn(async (args: string[]): Promise => { @@ -1184,8 +1184,256 @@ describe("catch-up: the build's OWN script maps that carry no debug-id (Vite wor await uploadSourcemaps(opts({ run: broken, onError: (e: unknown) => errors.push(e) })); expect(await readFile(join(dir, 'w.js'), 'utf8')).toBe('w();\n//# sourceMappingURL=w.js.map\n'); expect(String(errors[0])).toContain('did not verify'); - await expect(uploadSourcemaps(opts({ run: broken, failOnError: true }))).rejects.toThrow( - /did not verify/, + }); +}); + +describe('catch-up is best effort and never costs the build its other maps', () => { + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-catchup2-')); + }); + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + const REG = + '!function(){try{var e=globalThis;e._bugseeDebugIds=e._bugseeDebugIds||{}}catch(e){}}();'; + const STAMP = `\n;${REG}\n//# debugId=${ID}\n`; + const plainMap = '{"version":3,"sources":["w.ts"],"names":[],"mappings":"AAAA"}'; + const keyed = JSON.stringify({ debugId: ID }); + const cli = (failFor?: string) => { + const calls: string[][] = []; + const run = vi.fn(async (args: string[]): Promise => { + calls.push(args); + if (args[1] === 'inject') { + const paths = args.slice(2); + if (failFor !== undefined && paths.some((x) => x.includes(failFor))) { + for (const x of paths.filter((y) => y.includes(failFor) && y.endsWith('.js'))) { + await writeFile(x, '{{'); // a partial, broken rewrite before the CLI dies + } + throw new Error('bugsee-cli exited 11'); + } + for (const x of paths.filter((y) => /\.[cm]?js$/.test(y))) { + const code = await readFile(x, 'utf8'); + if (!code.includes('//# debugId=')) await writeFile(x, code + STAMP); + } + for (const x of paths.filter((y) => y.endsWith('.map'))) { + await writeFile( + x, + JSON.stringify({ ...JSON.parse(await readFile(x, 'utf8')), debugId: ID }), + ); + } + } + return { code: 0, stdout: '', stderr: '' }; + }); + return { run, calls }; + }; + const opts = (extra: object = {}) => ({ + ...base, + outDir: dir, + preStamped: true, + verifySri: async () => [], + findSri: async () => [], + ownFiles: [] as string[], + onNotice: () => undefined, + ...extra, + }); + const own = (...names: string[]) => names.flatMap((n) => [n, `${n}.map`]); + const seedPair = async (name: string, map = plainMap): Promise => { + await writeFile(join(dir, name), `${name}();\n//# sourceMappingURL=${name}.map\n`); + await writeFile(join(dir, `${name}.map`), map); + }; + + for (const [label, bad] of [ + ['empty', ''], + ['not JSON', 'not json'], + ['an array', '[]'], + ['null', 'null'], + ] as const) { + it(`a ${label} own map is skipped (never fed to the CLI), left untouched, and the good worker + a keyed map still upload`, async () => { + await writeFile(join(dir, 'k.js.map'), keyed); // keyed, uploaded and deleted + await seedPair('good.js'); + await seedPair('ext.js', bad); + const { run, calls } = cli(); + const onError = vi.fn(); + const result = await uploadSourcemaps( + opts({ + run, + onError, + failOnError: true, + ownFiles: [...own('good.js', 'ext.js'), 'k.js.map'], + }), + ); + const inject = calls.filter((c) => c[1] === 'inject'); + expect(inject.flatMap((c) => c.slice(2)).some((x) => x.includes('ext.js'))).toBe(false); + expect(onError).not.toHaveBeenCalled(); + expect(result.uploaded).toBe(true); + expect(await readFile(join(dir, 'ext.js.map'), 'utf8')).toBe(bad); + expect(await readdir(dir)).toContain('ext.js.map'); + expect(await readdir(dir)).not.toContain('good.js.map'); // stamped, uploaded, deleted + }); + } + + it('a batch the CLI rejects is retried pair by pair: the good pair is stamped, the bad one restored and reported, the upload goes on', async () => { + await seedPair('good.js'); + await seedPair('bad.js'); + const { run, calls } = cli('bad.js'); + const errors: unknown[] = []; + const result = await uploadSourcemaps( + opts({ run, onError: (e: unknown) => errors.push(e), ownFiles: own('good.js', 'bad.js') }), ); + expect(await readFile(join(dir, 'good.js'), 'utf8')).toContain('//# debugId='); + expect(await readFile(join(dir, 'bad.js'), 'utf8')).toBe( + 'bad.js();\n//# sourceMappingURL=bad.js.map\n', + ); // restored + expect(errors.map(String).join('\n')).toContain('bad.js'); + expect(errors.map(String).join('\n')).toContain('exited 11'); + expect(calls.some((c) => c[0] === 'debug-files')).toBe(true); + expect(result.uploaded).toBe(true); + }); + + it('a CLI failure (rewrite restored) is reported, never thrown, even under failOnError', async () => { + await seedPair('bad.js'); + await writeFile(join(dir, 'k.js.map'), keyed); + const errors: unknown[] = []; + const result = await uploadSourcemaps( + opts({ + run: cli('bad.js').run, + failOnError: true, + onError: (e: unknown) => errors.push(e), + ownFiles: [...own('bad.js'), 'k.js.map'], + }), + ); + expect(result).toBeDefined(); + expect(errors.map(String).join('\n')).toContain('bad.js'); + expect(await readFile(join(dir, 'bad.js'), 'utf8')).toBe( + 'bad.js();\n//# sourceMappingURL=bad.js.map\n', + ); + }); + + it('a stamp that does not verify AND cannot be restored is a failOnError failure (unsafe state)', async () => { + await seedPair('v.js'); + const sneaky = vi.fn(async (args: string[]): Promise => { + if (args[1] === 'inject') { + await writeFile(join(dir, 'v.js'), '{{'); + await chmod(dir, 0o555); // the restore cannot create its temp file + } + return { code: 0, stdout: '', stderr: '' }; + }); + try { + await expect( + uploadSourcemaps( + opts({ run: sneaky, failOnError: true, ownFiles: own('v.js'), onError: () => undefined }), + ), + ).rejects.toThrow(/COULD NOT restore/); + } finally { + await chmod(dir, 0o755); + } + }); + + it('a stamp that does not verify but IS restored is reported (safe state)', async () => { + await seedPair('v.js'); + await writeFile(join(dir, 'k.js.map'), keyed); + const sneaky = vi.fn(async (args: string[]): Promise => { + if (args[1] === 'inject') await writeFile(join(dir, 'v.js'), '{{'); + return { code: 0, stdout: '', stderr: '' }; + }); + const errors: unknown[] = []; + await uploadSourcemaps( + opts({ + run: sneaky, + failOnError: true, + ownFiles: [...own('v.js'), 'k.js.map'], + onError: (e: unknown) => errors.push(e), + }), + ); + expect(String(errors[0])).toContain('did not verify'); + expect(await readFile(join(dir, 'v.js'), 'utf8')).toBe( + 'v.js();\n//# sourceMappingURL=v.js.map\n', + ); + }); + + it('an unexpected failure inside the catch-up is reported and the upload still happens', async () => { + await writeFile(join(dir, 'k.js.map'), keyed); + await seedPair('w.js'); + const { run, calls } = cli(); + const errors: unknown[] = []; + await uploadSourcemaps( + opts({ + run, + onError: (e: unknown) => errors.push(e), + ownFiles: [...own('w.js'), 'k.js.map'], + findSri: async () => { + throw new Error('sri scan exploded'); + }, + }), + ); + expect(errors.map(String).join('\n')).toContain('sri scan exploded'); + expect(calls.some((c) => c[0] === 'debug-files')).toBe(true); + }); + + it('stamps .mjs and .cjs pairs too', async () => { + await seedPair('m.mjs'); + await seedPair('c.cjs'); + const { run, calls } = cli(); + await uploadSourcemaps(opts({ run, ownFiles: own('m.mjs', 'c.cjs') })); + const injected = calls.filter((c) => c[1] === 'inject').flatMap((c) => c.slice(2)); + expect(injected).toEqual(expect.arrayContaining([join(dir, 'm.mjs'), join(dir, 'c.cjs')])); + expect(await readFile(join(dir, 'm.mjs'), 'utf8')).toContain('//# debugId='); + expect(await readFile(join(dir, 'c.cjs'), 'utf8')).toContain('//# debugId='); + }); + + it('says nothing about blocked scripts when none is blocked, and removes its spill directory', async () => { + await seedPair('w.js'); + const notices: string[] = []; + const spillRoot = await mkdtemp(join(tmpdir(), 'bugsee-spill-cu-')); + try { + await uploadSourcemaps( + opts({ + run: cli().run, + ownFiles: own('w.js'), + onNotice: (m: string) => notices.push(m), + spillRoot, + }), + ); + expect(notices.join('\n')).not.toContain('Subresource Integrity'); + expect(await readdir(spillRoot)).toEqual([]); + } finally { + await rm(spillRoot, { recursive: true, force: true }); + } + }); + + it('a pinned bundle with the registration but NO debugId comment is not "stamped" either', async () => { + await writeFile(join(dir, 'r.js'), `r();\n//# sourceMappingURL=r.js.map\n;${REG}\n`); + await writeFile(join(dir, 'r.js.map'), plainMap); + const { run, calls } = cli(); + await uploadSourcemaps( + opts({ + run, + ownFiles: own('r.js'), + findSri: async () => [ + { html: join(dir, 'i.html'), script: join(dir, 'r.js'), integrity: 'sha384-X' }, + ], + }), + ); + expect(calls.some((c) => c[1] === 'inject')).toBe(false); + }); + + it('a pinned bundle with a FOREIGN debugId comment but no registration snippet is not "stamped" (inject would append the snippet): left alone', async () => { + await writeFile(join(dir, 'f.js'), `f();\n//# sourceMappingURL=f.js.map\n//# debugId=${ID}\n`); + await writeFile(join(dir, 'f.js.map'), plainMap); + const { run, calls } = cli(); + const notices: string[] = []; + await uploadSourcemaps( + opts({ + run, + ownFiles: own('f.js'), + onNotice: (m: string) => notices.push(m), + findSri: async () => [ + { html: join(dir, 'i.html'), script: join(dir, 'f.js'), integrity: 'sha384-X' }, + ], + }), + ); + expect(calls.some((c) => c[1] === 'inject')).toBe(false); + expect(notices.join('\n')).toContain('f.js'); }); }); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 2f83a7686..801968e86 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -231,6 +231,114 @@ export async function uploadSourcemaps( const cliOptions: RunBugseeCliOptions = { token: appToken, endpoint }; const onError = options.onError ?? defaultUploadErrorHandler; + const notice = (message: string): void => + (options.onNotice ?? ((m: string) => console.warn(`[bugsee] ${m}`)))(message); + + /** The map is a JSON object (what inject can stamp): not empty, not garbage, not `[]` / `null`. */ + const isMapObject = async (map: string): Promise => { + try { + const parsed: unknown = JSON.parse(await readFile(map, 'utf8')); + return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed); + } catch { + return false; + } + }; + + /** + * CATCH UP the build's OWN script maps that still carry no debug-id. Vite builds a worker through a + * sub-build, then puts its code in the output while REGENERATING its map (Vite 8) or emitting both after + * our `generateBundle` (Vite 7): the worker file is stamped without its map carrying the id, or not stamped + * at all. `sourcemaps inject` on a bundle that already carries the id AND the registration leaves its bytes + * unchanged and puts the id in the map (measured, bugsee-cli 0.9.0). Only maps this build emitted + * (`ownFiles`) are touched, never a `public/` copy; a bundle that is not fully stamped yet and is pinned by + * Subresource Integrity is left alone (stamping it would change pinned bytes). + * + * Robust by construction: a map that is not a JSON object is skipped (the CLI rejects the whole batch for + * one), a rejected batch is retried pair by pair, and whatever was rewritten is verified and restored. + * Returns a failure only when files could not be restored from an unverified stamp (and `failOnError` is on). + */ + const catchUpUnkeyed = async (ownFiles: readonly string[]): Promise => { + const own = ownedBy(outDir, ownFiles); + const unkeyed = ( + await (options.partitionMaps ?? partitionByKeyed)( + ( + await (options.listUploadMaps ?? listOutputMaps)(outDir) + ).filter((map) => isUploadableMap(map) && own(map)), + ) + ).kept; + const pairs: Array<{ bundle: string; map: string }> = []; + for (const map of unkeyed) { + const bundle = map.slice(0, -'.map'.length); + if ( + /\.[cm]?js$/i.test(bundle) && + (await access(bundle).then( + () => true, + () => false, + )) && + (await isMapObject(map)) + ) { + pairs.push({ bundle, map }); + } + } + if (pairs.length === 0) { + return undefined; + } + const pinned = new Set( + (await (options.findSri ?? findSriProtectedScripts)(outDir)).map((pin) => + resolve(pin.script), + ), + ); + const eligible: typeof pairs = []; + const blocked: typeof pairs = []; + for (const pair of pairs) { + const code = await readFile(pair.bundle, 'utf8'); + // "Stamped" means the id AND the registration: a foreign `//# debugId=` comment alone would still get + // the registration appended, which changes pinned bytes. + const stamped = readDebugId(code) !== undefined && code.includes('_bugseeDebugIds'); + (pinned.has(resolve(pair.bundle)) && !stamped ? blocked : eligible).push(pair); + } + if (blocked.length > 0) { + notice( + `${blocked.length} script(s) this build emitted were not fully stamped because Subresource Integrity pins them, so their maps were not uploaded: ${blocked.map((pair) => pair.bundle).join(', ')}`, + ); + } + if (eligible.length === 0) { + return undefined; + } + const targets = eligible.flatMap((pair) => [pair.bundle, pair.map]); + const snapshot = await snapshotStampFiles({ files: targets }, options.spillRoot); + try { + try { + for (const batch of inBatches(targets)) { + await run(['sourcemaps', 'inject', ...batch], cliOptions); + } + } catch { + // The CLI rejected a batch: find out which pair, so one bad file does not cost the others. + for (const pair of eligible) { + try { + await run(['sourcemaps', 'inject', pair.bundle, pair.map], cliOptions); + } catch (error) { + onError(new Error(`bugsee-cli could not stamp ${pair.bundle}: ${String(error)}`)); + } + } + } + // Whatever was rewritten (even by a CLI that then failed) is verified, and restored if it is not sound. + const { issues, restored, failed } = await verifyAndRestore(snapshot); + if (issues.length > 0) { + const failure = verifyFailure(issues, restored, failed); + // Restored means the output is exactly what the bundler wrote (safe): reported. Only files that could + // NOT be restored still carry an unverified stamp, which `failOnError` refuses to ship. + if (options.failOnError === true && failed.length > 0) { + return failure; + } + onError(failure); + } + return undefined; + } finally { + await snapshot.dispose(); + } + }; + let original: StampSnapshot | undefined; try { if (options.preStamped === true) { @@ -266,63 +374,19 @@ export async function uploadSourcemaps( // this build emitted (`ownFiles`) are touched, never a `public/` copy; a bundle that is not stamped // yet and is pinned by Subresource Integrity is left alone (stamping it would break the page). if (!dryRun && files === undefined && options.ownFiles !== undefined) { - const own = ownedBy(outDir, options.ownFiles); - const unkeyed = ( - await (options.partitionMaps ?? partitionByKeyed)( - ( - await (options.listUploadMaps ?? listOutputMaps)(outDir) - ).filter((map) => isUploadableMap(map) && own(map)), - ) - ).kept; - const pairs: Array<{ bundle: string; map: string }> = []; - for (const map of unkeyed) { - const bundle = map.slice(0, -'.map'.length); - if ( - /\.[cm]?js$/i.test(bundle) && - (await access(bundle).then( - () => true, - () => false, - )) - ) { - pairs.push({ bundle, map }); - } - } - if (pairs.length > 0) { - const pinned = new Set( - (await (options.findSri ?? findSriProtectedScripts)(outDir)).map((pin) => - resolve(pin.script), - ), + // Best effort: nothing in the catch-up may cost the build its other maps. Only an applied stamp that + // does not VERIFY is a strict failure (thrown under failOnError); a CLI error is reported and the map + // simply stays unkeyed. + let strict: Error | undefined; + try { + strict = await catchUpUnkeyed(options.ownFiles); + } catch (error) { + onError( + new Error(`stamping this build's remaining script maps failed: ${String(error)}`), ); - const eligible: typeof pairs = []; - const blocked: typeof pairs = []; - for (const pair of pairs) { - const stamped = readDebugId(await readFile(pair.bundle, 'utf8')) !== undefined; - (pinned.has(resolve(pair.bundle)) && !stamped ? blocked : eligible).push(pair); - } - if (blocked.length > 0) { - (options.onNotice ?? ((m: string) => console.warn(`[bugsee] ${m}`)))( - `${blocked.length} script(s) this build emitted were not stamped because Subresource Integrity pins them, so their maps were not uploaded: ${blocked.map((pair) => pair.bundle).join(', ')}`, - ); - } - if (eligible.length > 0) { - const targets = eligible.flatMap((pair) => [pair.bundle, pair.map]); - const snapshot = await snapshotStampFiles({ files: targets }, options.spillRoot); - try { - for (const batch of inBatches(targets)) { - await run(['sourcemaps', 'inject', ...batch], cliOptions); - } - const { issues, restored, failed } = await verifyAndRestore(snapshot); - if (issues.length > 0) { - const failure = verifyFailure(issues, restored, failed); - if (options.failOnError === true) { - throw failure; - } - onError(failure); - } - } finally { - await snapshot.dispose(); - } - } + } + if (strict !== undefined) { + throw strict; } } // 0''. The same stamp, as it is on disk after the bundler wrote the output. A later step can rewrite a diff --git a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts index ed3999688..26968ae67 100644 --- a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts @@ -1126,3 +1126,58 @@ describeReal('Vite workers: the worker bundle and its map carry the same debug-i } } }); + +// A plugin that emits its own script + a map that is not a source map (after our stamp) must cost the build nothing: +// the real CLI rejects a batch containing a non-object map, which used to lose the upload of every stamped map. +describeReal('Vite: an own script with a broken map does not cost the other maps', () => { + const extPlugin = (map: string): VitePlugin => ({ + name: 'emit-ext', + generateBundle: { + order: 'post', + handler() { + (this as unknown as { emitFile(f: object): void }).emitFile({ + type: 'asset', + fileName: 'ext.js', + source: 'ext();\n//# sourceMappingURL=ext.js.map\n', + }); + (this as unknown as { emitFile(f: object): void }).emitFile({ + type: 'asset', + fileName: 'ext.js.map', + source: map, + }); + }, + }, + }); + for (const [label, build] of [ + ['Vite 8', viteBuild], + ['Vite 7', vite7Build], + ] as const) { + for (const bad of ['', 'not json', '[]', 'null']) { + for (const failOnError of [true, false]) { + it(`${label}, map ${JSON.stringify(bad)} (failOnError ${failOnError}): the main maps still upload and are deleted`, async () => { + const app = makeApp( + `vite-badmap-${label.replace(/\W+/g, '')}-${bad.length}-${failOnError}-${Math.abs(bad.charCodeAt(0) || 0)}`, + { lazy: false }, + ); + const before = requests.length; + const errors: unknown[] = []; + await build( + viteConfig(app, [ + bugseeVite({ + failOnError, + onError: (e: unknown) => errors.push(e), + onNotice: () => undefined, + }), + extPlugin(bad), + ]), + ); + expect(errors.map(String)).toEqual([]); + expect(requests.length, 'uploaded').toBeGreaterThan(before); + const files = readdirSync(app.out, { recursive: true }) as string[]; + expect(files.filter((f) => f.endsWith('.map'))).toEqual(['ext.js.map']); + expect(readFileSync(join(app.out, 'ext.js.map'), 'utf8')).toBe(bad); + }); + } + } + } +}); From 9f676020815a369de89282f4b0867104df1839e7 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 15:46:20 +0500 Subject: [PATCH 20/39] fix(bundler-plugin-core): catch-up always verifies/restores, reports accurately, skips unreadable candidates - per-pair retry errors are collected and reported AFTER verifyAndRestore, so a throwing user onError cannot leave a half-written bundle on disk - catch-up problems use wording that is true (the upload continues), not the contained-failure "source-map upload skipped" - a candidate that cannot be read (a directory named *.js, a vanished file) is skipped per pair instead of aborting the whole catch-up - tests: throwing onError, a CLI failing for every pair, default wording, unreadable candidate Co-Authored-By: Claude Sonnet 5.5 --- .../src/orchestrate.stamp.test.ts | 79 +++++++++++++++++++ .../bundler-plugin-core/src/orchestrate.ts | 27 ++++++- 2 files changed, 102 insertions(+), 4 deletions(-) diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index d89b5b183..605d816aa 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -1371,6 +1371,85 @@ describe('catch-up is best effort and never costs the build its other maps', () expect(calls.some((c) => c[0] === 'debug-files')).toBe(true); }); + it('a throwing onError cannot skip the verify/restore of a half-written pair', async () => { + await seedPair('bad.js'); + await writeFile(join(dir, 'k.js.map'), keyed); + await uploadSourcemaps( + opts({ + run: cli('bad.js').run, + ownFiles: [...own('bad.js'), 'k.js.map'], + onError: () => { + throw new Error('user handler exploded'); + }, + }), + ).catch(() => undefined); + // the fake CLI half-wrote `{{` into bad.js before failing: it MUST be back to the bundler's bytes + expect(await readFile(join(dir, 'bad.js'), 'utf8')).toBe( + 'bad.js();\n//# sourceMappingURL=bad.js.map\n', + ); + }); + + it('a CLI that fails for EVERY pair: one report per pair, nothing left half-written, the upload still goes on', async () => { + await seedPair('bad1.js'); + await seedPair('bad2.js'); + await writeFile(join(dir, 'k.js.map'), keyed); + const { run, calls } = cli('bad'); + const errors: unknown[] = []; + await uploadSourcemaps( + opts({ + run, + onError: (e: unknown) => errors.push(e), + ownFiles: [...own('bad1.js', 'bad2.js'), 'k.js.map'], + }), + ); + const perPair = errors.map(String).filter((m) => m.includes('could not stamp')); + expect(perPair).toHaveLength(2); + expect(perPair.join('\n')).toContain('bad1.js'); + expect(perPair.join('\n')).toContain('bad2.js'); + expect(await readFile(join(dir, 'bad1.js'), 'utf8')).toBe( + 'bad1.js();\n//# sourceMappingURL=bad1.js.map\n', + ); + expect(calls.some((c) => c[0] === 'debug-files')).toBe(true); + }); + + it('says what is true by default: the stamp was not applied, the upload CONTINUES (never "upload skipped")', async () => { + await seedPair('bad.js'); + await writeFile(join(dir, 'k.js.map'), keyed); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + await uploadSourcemaps( + opts({ + run: cli('bad.js').run, + onError: undefined, + ownFiles: [...own('bad.js'), 'k.js.map'], + }), + ); + const text = warn.mock.calls.map((c) => String(c[0])).join('\n'); + expect(text).toContain('bad.js'); + expect(text).not.toMatch(/upload skipped/); + expect(text).toMatch(/^\[bugsee\] /m); + } finally { + warn.mockRestore(); + } + }); + + it('a candidate that cannot be read (a directory named w.js, or a file that vanished) is skipped, not fatal', async () => { + await mkdir(join(dir, 'd.js')); // a DIRECTORY with a script name + await writeFile(join(dir, 'd.js.map'), plainMap); + await seedPair('good.js'); + const { run } = cli(); + const errors: unknown[] = []; + await uploadSourcemaps( + opts({ + run, + onError: (e: unknown) => errors.push(e), + ownFiles: [...own('good.js'), 'd.js', 'd.js.map'], + }), + ); + expect(await readFile(join(dir, 'good.js'), 'utf8')).toContain('//# debugId='); + expect(errors.map(String).join('\n')).not.toContain('remaining script maps failed'); + }); + it('stamps .mjs and .cjs pairs too', async () => { await seedPair('m.mjs'); await seedPair('c.cjs'); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 801968e86..7c85e70ce 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -234,6 +234,13 @@ export async function uploadSourcemaps( const notice = (message: string): void => (options.onNotice ?? ((m: string) => console.warn(`[bugsee] ${m}`)))(message); + /** + * Reports something that does NOT stop the upload (the catch-up's problems): the default must not say the + * upload was skipped, as the contained-failure wording does. + */ + const reportContinuing = (error: unknown): void => + (options.onError ?? ((e: unknown) => console.warn(`[bugsee] ${String(e)}`)))(error); + /** The map is a JSON object (what inject can stamp): not empty, not garbage, not `[]` / `null`. */ const isMapObject = async (map: string): Promise => { try { @@ -291,7 +298,12 @@ export async function uploadSourcemaps( const eligible: typeof pairs = []; const blocked: typeof pairs = []; for (const pair of pairs) { - const code = await readFile(pair.bundle, 'utf8'); + let code: string; + try { + code = await readFile(pair.bundle, 'utf8'); + } catch { + continue; // vanished, or not a file: not a candidate + } // "Stamped" means the id AND the registration: a foreign `//# debugId=` comment alone would still get // the registration appended, which changes pinned bytes. const stamped = readDebugId(code) !== undefined && code.includes('_bugseeDebugIds'); @@ -308,6 +320,7 @@ export async function uploadSourcemaps( const targets = eligible.flatMap((pair) => [pair.bundle, pair.map]); const snapshot = await snapshotStampFiles({ files: targets }, options.spillRoot); try { + const pairErrors: Error[] = []; try { for (const batch of inBatches(targets)) { await run(['sourcemaps', 'inject', ...batch], cliOptions); @@ -318,12 +331,18 @@ export async function uploadSourcemaps( try { await run(['sourcemaps', 'inject', pair.bundle, pair.map], cliOptions); } catch (error) { - onError(new Error(`bugsee-cli could not stamp ${pair.bundle}: ${String(error)}`)); + pairErrors.push( + new Error(`bugsee-cli could not stamp ${pair.bundle}: ${String(error)}`), + ); } } } - // Whatever was rewritten (even by a CLI that then failed) is verified, and restored if it is not sound. + // Whatever was rewritten (even by a CLI that then failed) is verified, and restored if it is not sound: + // BEFORE anything is reported, so a user handler that throws cannot skip it. const { issues, restored, failed } = await verifyAndRestore(snapshot); + for (const error of pairErrors) { + reportContinuing(error); + } if (issues.length > 0) { const failure = verifyFailure(issues, restored, failed); // Restored means the output is exactly what the bundler wrote (safe): reported. Only files that could @@ -331,7 +350,7 @@ export async function uploadSourcemaps( if (options.failOnError === true && failed.length > 0) { return failure; } - onError(failure); + reportContinuing(failure); } return undefined; } finally { From 8c798c5ba26467774143480f2b9ee4338e909050 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 15:48:59 +0500 Subject: [PATCH 21/39] test(bundler-plugin-core): pin the catch-up's per-pair read guard A bundle that vanishes between the existence check and the read is skipped (never handed to the CLI, no report) and the other pairs still stamp. Test-only: the guard mutations (continue -> throw, guard removed) are both killed. Co-Authored-By: Claude Sonnet 5.5 --- .../src/orchestrate.stamp.test.ts | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index 605d816aa..918152b0a 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -1450,6 +1450,35 @@ describe('catch-up is best effort and never costs the build its other maps', () expect(errors.map(String).join('\n')).not.toContain('remaining script maps failed'); }); + it('a bundle that VANISHES between the existence check and the read is skipped; the other pairs still stamp', async () => { + await seedPair('a.js'); + await seedPair('good.js'); + const { run, calls } = cli(); + const errors: unknown[] = []; + await uploadSourcemaps( + opts({ + run, + onError: (e: unknown) => errors.push(e), + ownFiles: own('a.js', 'good.js'), + // runs after the candidates were found (a.js existed) and before their bytes are read + findSri: async () => { + await rm(join(dir, 'a.js')); + return []; + }, + }), + ); + expect(await readFile(join(dir, 'good.js'), 'utf8')).toContain('//# debugId='); + expect(errors.map(String).join('\n')).not.toContain('remaining script maps failed'); + // the vanished bundle is never handed to the CLI (and so never reported as failing) + expect( + calls + .filter((c) => c[1] === 'inject') + .flatMap((c) => c.slice(2)) + .some((x) => x.endsWith('a.js')), + ).toBe(false); + expect(errors).toEqual([]); + }); + it('stamps .mjs and .cjs pairs too', async () => { await seedPair('m.mjs'); await seedPair('c.cjs'); From 355d2360d5b61ec284a21e09b5ee40167b01bd4a Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 17:55:06 +0500 Subject: [PATCH 22/39] fix(bundler-plugin-core): address PR #221 review threads and code-scanning alerts CodeQL: case-insensitive tag regexes in the real-build test (bad-tag-filter); cut a webpack asset name at '?' with indexOf instead of a regex on library input (polynomial-redos); contain the e2e servers' paths with path.relative (path-injection, and the raw startsWith prefix accepted a sibling directory). Review threads: - post-emit: a rejected inject restores what it already rewrote before propagating; after a restore the upload is an explicit keyed set (a restored unkeyed map made the CLI reject the directory) - snapshot aborts on a read error that is not ENOENT; verifyAndRestore skips a bundle that vanished, picks the rollback partner by the ORIGINAL pointer, and does not restore a map whose bundle could not be restored - on-disk re-check reports an unreadable named bundle, verifies the map the fallback really loaded, and after webpack's RealContentHashPlugin rename uses the FINAL script names; a changed map is held to an unchanged stamped bundle's id - two bundles claiming one map refuse the in-build stamp - catch-up finds pointer-named maps and ENFORCES that inject leaves a stamped, SRI-pinned bundle alone (restores it if not) - a second output with its own ownFiles waits for the in-flight upload instead of joining it - tests: CLI probe timeout, win32 mode guard, per-compilation taps, upload-call assertions - docs: SRI must hash final bytes, deletion wording, failOnError fallback, check limits Co-Authored-By: Claude Sonnet 5.5 --- docs/design/source-maps.md | 18 +- docs/source-maps-usage.md | 4 +- packages/bundler-plugin-core/README.md | 2 +- .../src/orchestrate.stamp.test.ts | 261 +++++++++++++++++- .../bundler-plugin-core/src/orchestrate.ts | 81 +++++- .../src/plugin.in-build.real-build.test.ts | 16 +- .../src/plugin.real-build.test.ts | 8 +- .../src/plugin.stamp.test.ts | 87 +++++- packages/bundler-plugin-core/src/plugin.ts | 25 +- .../bundler-plugin-core/src/resolve.test.ts | 56 ++++ packages/bundler-plugin-core/src/resolve.ts | 15 +- .../src/stamp-assets.test.ts | 14 + .../bundler-plugin-core/src/stamp-assets.ts | 7 + .../src/stamp-files.test.ts | 149 +++++++++- .../bundler-plugin-core/src/stamp-files.ts | 103 ++++++- .../src/verify-stamp.test.ts | 51 ++++ .../bundler-plugin-core/src/verify-stamp.ts | 27 +- .../test/lazy-chunk.e2e.ts | 14 +- .../test/sri-vite-rollup.e2e.ts | 11 +- .../instrumentation-tests/test/sri.e2e.ts | 11 +- 20 files changed, 896 insertions(+), 64 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index eb9ec7e8d..6586f41ca 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -210,7 +210,7 @@ stamp degrades to the POST-EMIT path below — never to an unchecked page: a chu id on `chunk.map` (`debugId`/`debug_id`), which is the one thing Vite keeps. Both are covered by real builds (`plugin.in-build.real-build.test.ts`, and a Chromium run in `instrumentation-tests/test/sri-vite-rollup.e2e.ts`). - A plugin that rewrites chunks AFTER the Bugsee stamp changes bytes that were already hashed or stamped. The - post-build checks below detect (not prevent) it. + post-build checks below detect (not prevent) it, and only what they check: a debug-ID inconsistency between a bundle and its map, and an HTML integrity pin that no longer matches the bytes. A later plugin that changes executable JS, keeps both debug-IDs, and then emits a pin that matches the changed bytes passes both checks; they report those two inconsistencies, not every rewrite. ### Verify the stamp @@ -302,6 +302,22 @@ stamp. Covered by real Vite 7 and 8 builds with `new Worker(new URL(...))` and ` (`instrumentation-tests/test/lazy-chunk.e2e.ts`): the worker runs, registers its id, and its map has the same id. (The hand-rolled SRI step pins only the entry chunks in `index.html`, never worker files.) +### Hardening details (review follow-ups) + +- **Post-emit inject failures and restores.** A rejected `inject` (any batch) is followed by a verify-and-restore of + everything it may already have rewritten, before the failure propagates. If verification restored any pair, the + upload is an EXPLICIT keyed set (a restored map is unkeyed again, and the CLI rejects a directory that holds one). + A snapshot that cannot read a file (anything but ENOENT) aborts before inject runs. The rollback partner of a bundle + is the map its ORIGINAL pointer named; a map is not restored when its bundle could not be (reported as incomplete). +- **On-disk re-check.** A bundle the stamp named that cannot be read is reported. After webpack's RealContentHashPlugin + renames `[contenthash]` assets, the re-check is given the FINAL script names from the compilation (the names the + stamp reported are stale). A changed map is also held to an unchanged, already-stamped bundle's id. +- **Catch-up.** Pairs are found by the sibling name AND by the own bundles' `sourceMappingURL` (a moved + `maps/w.js.map`). The claim that inject leaves an already-stamped, SRI-pinned bundle alone is ENFORCED: if its bytes + changed they are restored (with its map) and reported. Two bundles claiming one map refuse the in-build stamp. +- **Concurrent outputs.** A second output with its own `ownFiles` for the same directory waits for the in-flight + upload and then runs itself, so its maps are not mistaken for foreign ones. + ### Maps that are not the bundle sibling `sourcemapFileNames` can put a map anywhere in the output (`maps/[name].js.map`, bundles in `js/`). `inject` diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index be668b96a..8a8afa480 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -29,7 +29,7 @@ Other bundlers are exported from `@bugsee/bundler-plugin-core` (same core, `unpl `bugseeRollupPlugin`, `bugseeEsbuildPlugin`, `bugseeRspackPlugin`. Each injects debug-IDs, uploads the maps and deletes them at the end of the build, exactly as the Vite/webpack plugins do (Rollup: stamps in `generateBundle`, uploads in `writeBundle`; esbuild: `onEnd`, so it works with the esbuild JS API and any tool that accepts esbuild plugins AND lets esbuild write the files; Rspack: -stamps in `processAssets`, uploads in `afterEmit`). Vite, Rollup, Rspack and webpack 5 stamp INSIDE the build, so a page whose Subresource Integrity hashes are taken in the build keeps working (list the Bugsee plugin before the SRI plugin; see `docs/design/source-maps.md` §7.1); esbuild stamps after emit and keeps the SRI guard that refuses an SRI build. With esbuild the plugin sets `sourcemap: 'external'` when you did not set `sourcemap` at all (external, so the +stamps in `processAssets`, uploads in `afterEmit`). Vite, Rollup, Rspack and webpack 5 stamp INSIDE the build, so a page whose Subresource Integrity hashes are taken in the build keeps working (list the Bugsee plugin before the SRI plugin, and have the SRI step hash the FINAL bytes: in a lazy-loading Vite app Vite rewrites a chunk after a `transformIndexHtml` SRI step has hashed it, so hash in `generateBundle` with `order: 'post'` instead; see `docs/design/source-maps.md` §7.1); esbuild stamps after emit and keeps the SRI guard that refuses an SRI build. With esbuild the plugin sets `sourcemap: 'external'` when you did not set `sourcemap` at all (external, so the shipped bundle carries no `//# sourceMappingURL` comment pointing at a map that is deleted after upload; the CLI pairs a bundle with its sibling `.map` anyway). An explicit value, including `false`, is left alone: with `false` there are no maps to upload, and the plugin says so through `onNotice`. @@ -48,7 +48,7 @@ directory (the one read-only exception is the Subresource-Integrity check, which `outfile` and `outdir` behave alike, wherever they point. Development builds do not upload and leave the local maps alone unless you set `uploadInDevelopment: true`: Rspack states its mode (only `development` is skipped; `none` and `production` upload), esbuild states none, so only `NODE_ENV=development` marks a -dev build (a bare `esbuild --watch` without it uploads on every rebuild, so set it or disable the plugin there). Every stamp is verified (each bundle still parses, its map pointer is intact, its map carries the same debug-ID), and the `.map` files are deleted only after a confirmed upload and only if they carry a debug-ID. +dev build (a bare `esbuild --watch` without it uploads on every rebuild, so set it or disable the plugin there). Every stamp is verified (each bundle still parses, its map pointer is intact, its map carries the same debug-ID), and `.map` files are deleted only after a confirmed upload. A script map is deleted only if it carries a debug-ID and this build emitted it; this build's own stylesheet and declaration maps (`.css.map`, `.d.ts.map`), which are never uploaded and embed the source, are deleted with them. **tsup is not covered by the esbuild plugin.** tsup always runs esbuild with `write: false` and writes the files itself afterwards, so nothing is on disk when the plugin's end-of-build hook runs. The plugin then uploads nothing diff --git a/packages/bundler-plugin-core/README.md b/packages/bundler-plugin-core/README.md index 64f299fd4..af1a50b28 100644 --- a/packages/bundler-plugin-core/README.md +++ b/packages/bundler-plugin-core/README.md @@ -16,7 +16,7 @@ npm install --save-dev @bugsee/vite-plugin ## What it contains - The `unplugin`-based plugin factory behind both of those packages. -- Rollup, esbuild and Rspack variants: `bugseeRollupPlugin`, `bugseeEsbuildPlugin`, `bugseeRspackPlugin`. They share the same options, but they are exported only from this package and have no dedicated wrapper package; they are less exercised than the Vite and Webpack plugins. The esbuild plugin uploads at the end of the build (`onEnd`, stamping after emit, with the SRI guard that refuses a build pinning integrity hashes). Rollup, Rspack, Vite and webpack 5 stamp the debug-IDs INSIDE the build (Rollup/Vite `generateBundle` with `order: 'pre'`, Rspack/webpack `processAssets`), so Subresource Integrity hashes taken later describe the stamped bytes; list the Bugsee plugin before any SRI plugin. Every stamp is verified (parses, map pointer intact, bundle and map debug-IDs match; a failure leaves the original bytes and falls back to stamping after emit), and `.map` files are deleted only after a confirmed upload and only when they carry a debug-ID. Details and measured ordering limits: `docs/design/source-maps.md` §7.1. Angular's builder does not accept esbuild plugins; use the `bugsee-cli` post-build recipe in `docs/source-maps-usage.md` §2. If you use them, install this package as a dev dependency and import them from `@bugsee/bundler-plugin-core`. +- Rollup, esbuild and Rspack variants: `bugseeRollupPlugin`, `bugseeEsbuildPlugin`, `bugseeRspackPlugin`. They share the same options, but they are exported only from this package and have no dedicated wrapper package; they are less exercised than the Vite and Webpack plugins. The esbuild plugin uploads at the end of the build (`onEnd`, stamping after emit, with the SRI guard that refuses a build pinning integrity hashes). Rollup, Rspack, Vite and webpack 5 stamp the debug-IDs INSIDE the build (Rollup/Vite `generateBundle` with `order: 'pre'`, Rspack/webpack `processAssets`), so Subresource Integrity hashes taken later describe the stamped bytes; list the Bugsee plugin before any SRI plugin. Every stamp is verified (parses, map pointer intact, bundle and map debug-IDs match; a failure leaves the original bytes and falls back to stamping after emit by default; with `failOnError` a failed in-build stamp fails the build instead), and `.map` files are deleted only after a confirmed upload and only when they carry a debug-ID. Details and measured ordering limits: `docs/design/source-maps.md` §7.1. Angular's builder does not accept esbuild plugins; use the `bugsee-cli` post-build recipe in `docs/source-maps-usage.md` §2. If you use them, install this package as a dev dependency and import them from `@bugsee/bundler-plugin-core`. - Settings lookup order: plugin option, then the process environment, then the nearest `.env.bugsee-build-plugin` (only `BUGSEE_APP_TOKEN` / `BUGSEE_APP_VERSION` / `BUGSEE_APP_BUILD` are read from it; searched from the bundler's project directory up to the repo/workspace root, never in or above the home directory; fills gaps only, a blank variable counts as unset; a missing or malformed file never fails the build). Details: `docs/source-maps-usage.md`. - Option resolution (`appToken`, `appVersion`, `appBuild`, `endpoint`, `deleteMaps`, `dryRun`, `disabled`, with environment fallbacks such as `BUGSEE_APP_TOKEN`; the version also falls back to the nearest `package.json` above the bundler's project directory (blank values count as unset; Rollup, which reports no project directory, walks up from the output directory and skips a name-less, version-less marker such as a `dist/cjs/package.json` holding only `{"type":"commonjs"}`), the build to a CI commit id, and a real value is baked into the app bundle as `__BUGSEE_APP_VERSION__` / `__BUGSEE_APP_BUILD__` for the runtime SDK: through `define` on Vite, esbuild, webpack 5 and Rspack, and by rewriting each rendered chunk (with a source map) on Rollup; webpack 4 cannot bake, so there only an explicit value is recorded; a constant you define yourself is what gets recorded when it is a plain string), build-commit detection and the CLI runner. diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index 918152b0a..916067e9d 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -520,7 +520,9 @@ describe('an in-build stamp is checked again on disk, after the bundler wrote th deleteMaps: false, }), ); - expect(onError).not.toHaveBeenCalled(); + // Only the NAMED bundle is looked at (never the project tree): it is missing, so that is said, once. + expect(onError).toHaveBeenCalledOnce(); + expect(String(onError.mock.calls[0]?.[0])).toContain('no-such-bundle-bugsee.js'); }); it('without stampedBundles the on-disk re-check has nothing to name and does not run', async () => { @@ -1545,3 +1547,260 @@ describe('catch-up is best effort and never costs the build its other maps', () expect(notices.join('\n')).toContain('f.js'); }); }); + +describe('post-emit: a rejected inject, and a restore that leaves unkeyed maps', () => { + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-postemit-')); + }); + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + const REG = + '!function(){try{var e=globalThis;e._bugseeDebugIds=e._bugseeDebugIds||{}}catch(e){}}();'; + const STAMP = `\n;${REG}\n//# debugId=${ID}\n`; + const plain = '{"version":3,"sources":["x.ts"],"names":[],"mappings":"AAAA"}'; + const seed = async (name: string): Promise => { + const code = `${name}();\n//# sourceMappingURL=${name}.map\n`; + await writeFile(join(dir, name), code); + await writeFile(join(dir, `${name}.map`), plain); + return code; + }; + + it('restores what a rejected inject already rewrote, then reports the failure (rethrown under failOnError)', async () => { + const original = await seed('a.js'); + const half = vi.fn(async (args: string[]): Promise => { + if (args[1] === 'inject') { + await writeFile(join(dir, 'a.js'), '{{'); // a partial rewrite, then the CLI dies + throw new Error('bugsee-cli exited 11'); + } + return { code: 0, stdout: '', stderr: '' }; + }); + const errors: unknown[] = []; + await uploadSourcemaps({ + ...base, + outDir: dir, + run: half, + findSri: async () => [], + onError: (e) => errors.push(e), + }); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe(original); + expect(String(errors[0])).toContain('exited 11'); + + await writeFile(join(dir, 'a.js'), original); + await expect( + uploadSourcemaps({ + ...base, + outDir: dir, + run: half, + findSri: async () => [], + failOnError: true, + }), + ).rejects.toThrow(/exited 11/); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe(original); + }); + + it('a later `files` batch that fails restores the batches an earlier one already wrote', async () => { + const original = await seed('a.js'); + let batch = 0; + const run = vi.fn(async (args: string[]): Promise => { + if (args[1] === 'inject') { + batch += 1; + if (batch === 1) { + await writeFile(join(dir, 'a.js'), `${original}${STAMP}`); + await writeFile( + join(dir, 'a.js.map'), + JSON.stringify({ ...JSON.parse(plain), debugId: ID }), + ); + } else { + throw new Error('second batch failed'); + } + } + return { code: 0, stdout: '', stderr: '' }; + }); + // 250 paths -> two batches; the first stamps a.js soundly, the second dies: a sound stamp is kept (verified) + const extra = Array.from({ length: 250 }, (_, i) => join(dir, `nope${i}.js`)); + await uploadSourcemaps({ + ...base, + outDir: dir, + run, + onError: () => undefined, + files: { scripts: [join(dir, 'a.js'), ...extra], maps: [join(dir, 'a.js.map')] }, + }); + // verified as sound, so it is NOT rolled back; and nothing half-written is left + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe(`${original}${STAMP}`); + }); + + it('when verification restored some pair, the upload is an EXPLICIT keyed set (a restored unkeyed map would make the CLI reject the directory)', async () => { + await seed('a.js'); + const bOriginal = await seed('b.js'); + const calls: string[][] = []; + const run = vi.fn(async (args: string[]): Promise => { + calls.push(args); + if (args[1] === 'inject') { + await writeFile(join(dir, 'a.js'), '{{'); // unsound: restored with its map + await writeFile(join(dir, 'b.js'), `${bOriginal}${STAMP}`); // sound + await writeFile( + join(dir, 'b.js.map'), + JSON.stringify({ ...JSON.parse(plain), debugId: ID }), + ); + } + return { code: 0, stdout: '', stderr: '' }; + }); + const result = await uploadSourcemaps({ + ...base, + outDir: dir, + run, + findSri: async () => [], + onError: () => undefined, + onNotice: () => undefined, + }); + const upload = calls.find((c) => c[0] === 'debug-files') as string[]; + expect(upload).not.toContain(dir); + expect(upload).toContain(join(dir, 'b.js.map')); + expect(upload).not.toContain(join(dir, 'a.js.map')); + expect(result.uploaded).toBe(true); + expect(await readdir(dir)).toContain('a.js.map'); // restored + unkeyed: kept + expect(await readdir(dir)).not.toContain('b.js.map'); // uploaded + deleted + }); +}); + +describe('catch-up: pointer-named maps, and the "inject leaves a stamped bundle alone" claim is ENFORCED', () => { + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-catchup3-')); + }); + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + const REG = + '!function(){try{var e=globalThis;e._bugseeDebugIds=e._bugseeDebugIds||{}}catch(e){}}();'; + const STAMP = `\n;${REG}\n//# debugId=${ID}\n`; + const plain = '{"version":3,"sources":["w.ts"],"names":[],"mappings":"AAAA"}'; + const opts = (extra: object = {}) => ({ + ...base, + outDir: dir, + preStamped: true, + verifySri: async () => [], + findSri: async () => [], + onNotice: () => undefined, + ...extra, + }); + + it('a worker whose map is NOT the sibling (maps/w.js.map, named by the bundle pointer) is caught up too', async () => { + await mkdir(join(dir, 'maps')); + await writeFile(join(dir, 'w.js'), 'w();\n//# sourceMappingURL=maps/w.js.map\n'); + await writeFile(join(dir, 'maps', 'w.js.map'), plain); + const calls: string[][] = []; + const run = vi.fn(async (args: string[]): Promise => { + calls.push(args); + if (args[1] === 'inject') { + for (const x of args.slice(2)) { + if (x.endsWith('.js')) await writeFile(x, `${await readFile(x, 'utf8')}${STAMP}`); + else + await writeFile( + x, + JSON.stringify({ ...JSON.parse(await readFile(x, 'utf8')), debugId: ID }), + ); + } + } + return { code: 0, stdout: '', stderr: '' }; + }); + await uploadSourcemaps(opts({ run, ownFiles: ['w.js', 'maps/w.js.map'] })); + const inject = calls.find((c) => c[1] === 'inject') as string[]; + expect(inject.slice(2)).toEqual([join(dir, 'w.js'), join(dir, 'maps', 'w.js.map')]); + expect(await readFile(join(dir, 'w.js'), 'utf8')).toContain('//# debugId='); + }); + + it('an already-stamped, SRI-pinned bundle that inject CHANGED anyway is restored (with its map) and reported', async () => { + const stamped = `w();\n//# sourceMappingURL=w.js.map\n${STAMP}`; + await writeFile(join(dir, 'w.js'), stamped); + await writeFile(join(dir, 'w.js.map'), plain); + const run = vi.fn(async (args: string[]): Promise => { + if (args[1] === 'inject') { + await writeFile(join(dir, 'w.js'), `${stamped}\n//# changed by inject\n`); // violates the claim + await writeFile( + join(dir, 'w.js.map'), + JSON.stringify({ ...JSON.parse(plain), debugId: ID }), + ); + } + return { code: 0, stdout: '', stderr: '' }; + }); + const errors: unknown[] = []; + await uploadSourcemaps( + opts({ + run, + ownFiles: ['w.js', 'w.js.map'], + onError: (e: unknown) => errors.push(e), + findSri: async () => [ + { html: join(dir, 'i.html'), script: join(dir, 'w.js'), integrity: 'sha384-X' }, + ], + }), + ); + expect(await readFile(join(dir, 'w.js'), 'utf8')).toBe(stamped); // pinned bytes are back + expect(errors.map(String).join('\n')).toContain('Subresource Integrity'); + }); +}); + +describe('catch-up edge cases (pointer search, failed restore of a pinned bundle)', () => { + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-catchup4-')); + }); + afterEach(async () => { + await chmod(dir, 0o755).catch(() => undefined); + await rm(dir, { recursive: true, force: true }); + }); + const plain = '{"version":3,"sources":["w.ts"],"names":[],"mappings":"AAAA"}'; + const REG = + '!function(){try{var e=globalThis;e._bugseeDebugIds=e._bugseeDebugIds||{}}catch(e){}}();'; + const STAMP = `\n;${REG}\n//# debugId=${ID}\n`; + + it('an own bundle that cannot be read is skipped during the pointer search', async () => { + await mkdir(join(dir, 'maps')); + await writeFile(join(dir, 'maps', 'x.js.map'), plain); // unkeyed, no sibling bundle + const run = vi.fn(async (): Promise => ({ code: 0, stdout: '', stderr: '' })); + const errors: unknown[] = []; + await uploadSourcemaps({ + ...base, + outDir: dir, + run, + preStamped: true, + verifySri: async () => [], + findSri: async () => [], + onNotice: () => undefined, + onError: (e) => errors.push(e), + ownFiles: ['gone.js', 'maps/x.js.map'], // gone.js is listed but absent + }); + expect(errors).toEqual([]); + expect(run.mock.calls.some((c) => c[0][1] === 'inject')).toBe(false); + }); + + it('says which files could not be put back when the pinned bundle inject changed cannot be restored', async () => { + const stamped = `w();\n//# sourceMappingURL=w.js.map\n${STAMP}`; + await writeFile(join(dir, 'w.js'), stamped); + await writeFile(join(dir, 'w.js.map'), plain); + const run = vi.fn(async (args: string[]): Promise => { + if (args[1] === 'inject') { + await writeFile(join(dir, 'w.js'), `${stamped}//x\n`); + await chmod(dir, 0o555); + } + return { code: 0, stdout: '', stderr: '' }; + }); + const errors: unknown[] = []; + await uploadSourcemaps({ + ...base, + outDir: dir, + run, + preStamped: true, + verifySri: async () => [], + onNotice: () => undefined, + ownFiles: ['w.js', 'w.js.map'], + findSri: async () => [ + { html: join(dir, 'i.html'), script: join(dir, 'w.js'), integrity: 'sha384-X' }, + ], + onError: (e) => errors.push(e), + }).catch(() => undefined); + expect(errors.map(String).join('\n')).toContain('could not restore'); + }); +}); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 7c85e70ce..5ddbc69b2 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -2,7 +2,7 @@ // delete the client `.map` files (privacy). Each side-effecting step is behind an injectable seam so the // orchestration is unit-tested without a real binary or filesystem. import { access, readdir, readFile, unlink } from 'node:fs/promises'; -import { join, relative, resolve } from 'node:path'; +import path, { join, relative, resolve } from 'node:path'; import { readDebugId } from './debug-ids'; import { type RunBugseeCliOptions, runBugseeCli, type SpawnResult } from './run-cli'; import { findIntegrityMismatches, findSriProtectedScripts, type SriProtectedScript } from './sri'; @@ -15,14 +15,16 @@ import { NEVER_WALK, ownedBy, partitionByKeyed, + restorePaths, type SnapshotTarget, type StampSnapshot, + sameAsSnapshot, snapshotStampFiles, verifyAndRestore, verifyStampedOnDisk, } from './stamp-files'; import type { VcsMetadata } from './vcs'; -import { formatIssues } from './verify-stamp'; +import { formatIssues, localPointerTarget } from './verify-stamp'; /** The `runBugseeCli` shape, injectable for tests. */ export type RunFn = (args: string[], options: RunBugseeCliOptions) => Promise; @@ -287,6 +289,29 @@ export async function uploadSourcemaps( pairs.push({ bundle, map }); } } + // Maps that are not the bundle's sibling (a moved `maps/w.js.map`): found through the OWN bundles' pointers. + const matched = new Set(pairs.map((pair) => pair.map)); + const loose = unkeyed.filter((map) => !matched.has(map)); + if (loose.length > 0) { + for (const name of ownFiles) { + const bundle = resolve(outDir, name); + if (!/\.[cm]?js$/i.test(bundle)) { + continue; + } + let text: string; + try { + text = await readFile(bundle, 'utf8'); + } catch { + continue; + } + const target = localPointerTarget(bundle, text, path); + const map = + target === undefined ? undefined : loose.find((m) => resolve(m) === resolve(target)); + if (map !== undefined && (await isMapObject(map))) { + pairs.push({ bundle, map }); + } + } + } if (pairs.length === 0) { return undefined; } @@ -297,6 +322,7 @@ export async function uploadSourcemaps( ); const eligible: typeof pairs = []; const blocked: typeof pairs = []; + const pinnedAndStamped: typeof pairs = []; for (const pair of pairs) { let code: string; try { @@ -308,6 +334,9 @@ export async function uploadSourcemaps( // the registration appended, which changes pinned bytes. const stamped = readDebugId(code) !== undefined && code.includes('_bugseeDebugIds'); (pinned.has(resolve(pair.bundle)) && !stamped ? blocked : eligible).push(pair); + if (pinned.has(resolve(pair.bundle)) && stamped) { + pinnedAndStamped.push(pair); + } } if (blocked.length > 0) { notice( @@ -340,6 +369,21 @@ export async function uploadSourcemaps( // Whatever was rewritten (even by a CLI that then failed) is verified, and restored if it is not sound: // BEFORE anything is reported, so a user handler that throws cannot skip it. const { issues, restored, failed } = await verifyAndRestore(snapshot); + // ENFORCE the claim the pinned-bundle exception rests on: inject leaves an already-stamped bundle's + // bytes alone. If it did not, the pinned bytes changed: put them (and the map) back, and say so. + for (const pair of pinnedAndStamped) { + if (!(await sameAsSnapshot(snapshot, pair.bundle))) { + const undone = await restorePaths(snapshot, [pair.bundle, pair.map]); + reportContinuing( + new Error( + `bugsee-cli changed ${pair.bundle}, which Subresource Integrity pins and which was already stamped; its original bytes were restored` + + (undone.length > 0 + ? ` (could not restore: ${undone.map((u) => u.path).join(', ')})` + : ''), + ), + ); + } + } for (const error of pairErrors) { reportContinuing(error); } @@ -359,6 +403,7 @@ export async function uploadSourcemaps( }; let original: StampSnapshot | undefined; + let restoredAny = false; try { if (options.preStamped === true) { // 0'. Stamped in the build, so this run rewrites nothing and cannot break SRI. What it CAN do is @@ -478,14 +523,27 @@ export async function uploadSourcemaps( } // 1. Inject debug-IDs (rewrites the built .js + .map in place). - if (files === undefined) { - await run(['sourcemaps', 'inject', outDir, ...dryFlag], cliOptions); - } else { - // A script and its map may land in different batches: harmless, the debug-id is derived from the - // bundle's content, so each side stamps the same id (measured with 250 entries, none mismatched). - for (const batch of inBatches([...files.scripts, ...files.maps])) { - await run(['sourcemaps', 'inject', ...batch, ...dryFlag], cliOptions); + try { + if (files === undefined) { + await run(['sourcemaps', 'inject', outDir, ...dryFlag], cliOptions); + } else { + // A script and its map may land in different batches: harmless, the debug-id is derived from the + // bundle's content, so each side stamps the same id (measured with 250 entries, none mismatched). + for (const batch of inBatches([...files.scripts, ...files.maps])) { + await run(['sourcemaps', 'inject', ...batch, ...dryFlag], cliOptions); + } } + } catch (error) { + // A rejected inject may already have rewritten files (an earlier batch, or a partial write): verify and + // restore them BEFORE the failure propagates, so no unverified stamp stays on disk. + if (original !== undefined) { + try { + await verifyAndRestore(original); + } catch { + // the inject failure is the one to report + } + } + throw error; } // 1b. VERIFY what inject wrote (verify-stamp.ts): every changed bundle still parses and keeps its map @@ -496,6 +554,7 @@ export async function uploadSourcemaps( // maps carry no debugId, so the keyed check at deletion keeps them. if (original !== undefined) { const { issues, restored, failed } = await verifyAndRestore(original); + restoredAny = restored.length > 0; if (issues.length > 0) { const failure = verifyFailure(issues, restored, failed); if (options.failOnError === true) { @@ -526,7 +585,9 @@ export async function uploadSourcemaps( // deleted afterwards and that is reported. A FILE run (`files`) names its maps up front. // A PRE-STAMPED directory is uploaded as an explicit file set (below), and what is deleted is exactly // that set: no second walk to disagree with the first about which maps exist. - const explicitUpload = files === undefined && options.preStamped === true && !dryRun; + // (Also after a restore: a restored map is unkeyed again, and the CLI rejects a DIRECTORY that holds one.) + const explicitUpload = + files === undefined && (options.preStamped === true || restoredAny) && !dryRun; let uploadedMaps: string[] = []; let unuploadableMaps: string[] = []; let snapshot: string[] | undefined; diff --git a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts index 26968ae67..5902f6cdc 100644 --- a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts @@ -41,8 +41,12 @@ let root: string; const cli = resolveBugseeCli(); const cliProbe = cli.endsWith('.js') - ? spawnSync(process.execPath, [cli, '--version'], { encoding: 'utf8' }) - : spawnSync(cli, ['--version'], { encoding: 'utf8' }); + ? spawnSync(process.execPath, [cli, '--version'], { + encoding: 'utf8', + timeout: 15_000, + killSignal: 'SIGKILL', + }) + : spawnSync(cli, ['--version'], { encoding: 'utf8', timeout: 15_000, killSignal: 'SIGKILL' }); const cliAvailable = cliProbe.status === 0; const cliRequired = process.env.CI !== undefined || process.env.BUGSEE_REQUIRE_CLI !== undefined; if (!cliAvailable && !cliRequired) { @@ -113,9 +117,9 @@ interface Pin { function pinsOf(out: string): Pin[] { const html = readFileSync(join(out, 'index.html'), 'utf8'); const pins: Pin[] = []; - for (const tag of html.match(/<(?:script|link)\b[^>]*>/g) ?? []) { - const integrity = /\bintegrity="([^"]+)"/.exec(tag)?.[1]; - const url = /\b(?:src|href)="([^"]+)"/.exec(tag)?.[1]; + for (const tag of html.match(/<(?:script|link)\b[^>]*>/gi) ?? []) { + const integrity = /\bintegrity="([^"]+)"/i.exec(tag)?.[1]; + const url = /\b(?:src|href)="([^"]+)"/i.exec(tag)?.[1]; if (integrity !== undefined && url !== undefined) { pins.push({ tag, file: join(out, url.replace(/^\.?\//, '')), integrity }); } @@ -149,7 +153,7 @@ function expectStampedAndUploaded(out: string, before: number, atLeast = 2): voi /** Add `integrity` to every script / modulepreload tag whose file is a chunk of the bundle. */ function pinChunks(html: string, bundle: Record): string { return html.replace( - /<(?:script|link)\b[^>]*?(?:src|href)="\.?\/?([^"]+\.js)"[^>]*>/g, + /<(?:script|link)\b[^>]*?(?:src|href)="\.?\/?([^"]+\.js)"[^>]*>/gi, (tag, file: string) => { const entry = bundle[file]; return entry?.type === 'chunk' && entry.code !== undefined diff --git a/packages/bundler-plugin-core/src/plugin.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.real-build.test.ts index 95c91afb8..f1a9a592e 100644 --- a/packages/bundler-plugin-core/src/plugin.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.real-build.test.ts @@ -35,8 +35,12 @@ let delayMs = 0; // with a reason; CI (or BUGSEE_REQUIRE_CLI=1) requires it, so a CI run can never go green testing less. const cli = resolveBugseeCli(); const cliProbe = cli.endsWith('.js') - ? spawnSync(process.execPath, [cli, '--version'], { encoding: 'utf8' }) - : spawnSync(cli, ['--version'], { encoding: 'utf8' }); + ? spawnSync(process.execPath, [cli, '--version'], { + encoding: 'utf8', + timeout: 15_000, + killSignal: 'SIGKILL', + }) + : spawnSync(cli, ['--version'], { encoding: 'utf8', timeout: 15_000, killSignal: 'SIGKILL' }); const cliAvailable = cliProbe.status === 0; const cliRequired = process.env.CI !== undefined || process.env.BUGSEE_REQUIRE_CLI !== undefined; if (!cliAvailable && !cliRequired) { diff --git a/packages/bundler-plugin-core/src/plugin.stamp.test.ts b/packages/bundler-plugin-core/src/plugin.stamp.test.ts index 66818bf62..1e8ea0504 100644 --- a/packages/bundler-plugin-core/src/plugin.stamp.test.ts +++ b/packages/bundler-plugin-core/src/plugin.stamp.test.ts @@ -29,10 +29,16 @@ const outsideError = () => const makePlugin = (options?: BugseePluginOptions, framework = 'rollup'): UnpluginOptions => bugseeUnpluginFactory(options, { framework } as never) as UnpluginOptions; -const depsOf = (call: number) => - uploadSpy.mock.calls[call]?.[2] as - | { preStamped?: boolean; bundler?: unknown; stampedBundles?: string[] } - | undefined; +/** The deps of the nth upload call. A missing call FAILS the test: "the upload was skipped" is never a pass. */ +const depsOf = (call: number) => { + const entry = uploadSpy.mock.calls[call]; + if (entry === undefined) { + throw new Error( + `expected an upload call #${call}, but only ${uploadSpy.mock.calls.length} happened`, + ); + } + return entry[2] as { preStamped?: boolean; bundler?: unknown; stampedBundles?: string[] }; +}; beforeEach(() => { uploadSpy.mockClear(); @@ -98,11 +104,14 @@ describe('rspack: stamps inside the compilation', () => { processAssets, updated, afterEmit: () => afterEmit[0]?.(), + afterEmitWith: (c: unknown) => (afterEmit[0] as (c: unknown) => Promise)(c), compile: async () => { + // Each compilation runs ITS OWN processAssets taps only (taps registered by earlier ones are gone). + const first = processAssets.length; for (const fn of compilations) { fn(compilation); } - for (const tap of processAssets) { + for (const tap of processAssets.slice(first)) { await tap.fn(); } }, @@ -265,6 +274,7 @@ describe('rspack: stamps inside the compilation', () => { }); await r.compile(); await r.afterEmit(); + expect(stampSpy).toHaveBeenCalledTimes(2); // once per compilation, not once per accumulated tap expect(depsOf(1)?.preStamped).toBe(false); }); @@ -353,6 +363,28 @@ describe('rspack: stamps inside the compilation', () => { expect((r.updated[0]?.source as { value: string }).value).toBe('\uFEFFbom'); }); + it('after [contenthash] renames, the on-disk re-check is told the FINAL script names (the stamp ran before the rename)', async () => { + stampSpy.mockImplementation(async () => ({ + stamped: ['main.OLDHASH.js'], + maps: { 'main.OLDHASH.js': 'main.OLDHASH.js.map' }, + bundles: 1, + })); + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + await (r.afterEmitWith as (c: unknown) => Promise)({ + getAssets: () => [ + { name: 'main.NEWHASH.js' }, + { name: 'main.NEWHASH.js.map' }, + { name: 'x.css' }, + { name: 'q.js?h' }, + ], + }); + const deps = depsOf(0) as { stampedBundles?: string[]; stampedMaps?: unknown }; + expect(deps.stampedBundles).toEqual(['main.NEWHASH.js', 'q.js']); + expect(deps.stampedMaps).toBeUndefined(); + }); + it('does not stamp for a disabled plugin', async () => { const r = rspackCompiler(); apply({ disabled: true }, r.compiler); @@ -818,3 +850,48 @@ describe('the zero-staged guard: only ? ends a webpack extension (# is part of t expect((uploadSpy.mock.calls[0]?.[2] as { preStamped?: boolean }).preStamped).toBe(true); }); }); + +describe('webpack: after [contenthash] renames, the on-disk re-check gets the FINAL script names', () => { + it('passes the final script asset names (query cut) and no stale map names', async () => { + stampSpy.mockImplementation(async () => ({ + stamped: ['m.OLD.js'], + maps: { 'm.OLD.js': 'm.OLD.js.map' }, + bundles: 1, + })); + const after: Array<(c?: unknown) => Promise> = []; + const taps: Array<() => Promise> = []; + const compilations: Array<(c: unknown) => void> = []; + const compilation = { + hooks: { + processAssets: { tapPromise: (_o: unknown, fn: () => Promise) => taps.push(fn) }, + }, + getAssets: () => [{ name: 'm.NEW.js' }, { name: 'm.NEW.js.map' }, { name: 'q.js?h' }], + getAsset: () => undefined, + updateAsset: () => undefined, + }; + const compiler = { + options: { output: { path: '/o' }, mode: 'production', devtool: 'source-map' }, + hooks: { + afterEmit: { + tapPromise: (_n: string, fn: (c?: unknown) => Promise) => after.push(fn), + }, + thisCompilation: { tap: (_n: string, fn: (c: unknown) => void) => compilations.push(fn) }, + }, + webpack: { + Compilation: { PROCESS_ASSETS_STAGE_DEV_TOOLING: 500 }, + sources: { RawSource: class {} }, + }, + }; + ( + makePlugin({ appToken: 'tok', onNotice: () => undefined }, 'webpack').webpack as ( + c: unknown, + ) => void + )(compiler); + for (const fn of compilations) fn(compilation); + for (const t of taps) await t(); + await after[0]?.(compilation); + const deps = depsOf(0) as { stampedBundles?: string[]; stampedMaps?: unknown }; + expect(deps.stampedBundles).toEqual(['m.NEW.js', 'q.js']); + expect(deps.stampedMaps).toBeUndefined(); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 7a5c09174..c6d9348e1 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -29,6 +29,7 @@ import { rollupUnstampableMaps, stampAssets, } from './stamp-assets'; +import { cutAtQuery } from './stamp-files'; /** The subset of a rollup/vite output-options object we read. */ export interface OutputLike { @@ -208,7 +209,7 @@ function asText(name: string, content: Buffer): string { * An asset name without its `?query`. Measured on real Rspack builds: webpack/Rspack drop `?...` when they write * a file (`x.js?h` is written as `x.js`) and KEEP `#` (`a#1.js` is written as `a#1.js`), so only `?` is cut. */ -const withoutQuery = (name: string): string => name.replace(/\?.*$/, ''); +const withoutQuery = cutAtQuery; /** * A compilation's asset table as the core's `AssetStore`. @@ -335,6 +336,26 @@ interface AssetNamesLike { getAssets?(): ReadonlyArray<{ name: string }>; } +/** + * The stamp's bundle / map names as the DISK has them. webpack's RealContentHashPlugin renames `[contenthash]` + * assets AFTER the in-build stamp, so the names the stamp reported are stale; when the compilation is known, + * the on-disk re-check is given the final script names instead (every script asset was staged, so every one + * was stamped) and finds each map by its pointer. + */ +const finalStampNames = ( + compilation: AssetNamesLike | undefined, +): { stampedBundles?: string[]; stampedMaps?: undefined } => { + const assets = compilation?.getAssets?.(); + return assets === undefined + ? {} + : { + stampedBundles: assets + .map((asset) => cutAtQuery(asset.name)) + .filter((name) => /\.[cm]?js$/i.test(name)), + stampedMaps: undefined, + }; +}; + /** The names this build emitted, as the `ownFiles` the upload deletes by (absent when not known). */ const ownFilesOf = (compilation: AssetNamesLike | undefined): { ownFiles?: string[] } => { const assets = compilation?.getAssets?.(); @@ -823,6 +844,7 @@ export const bugseeUnpluginFactory: UnpluginFactory { expect(await a).toEqual(await b); // …and the joiner gets the same result, not `undefined` }); + it('a second OUTPUT with its own ownFiles waits for the in-flight run and then runs itself (its maps are not "foreign")', async () => { + const h = held(); + const seen: Array<{ ownFiles?: readonly string[] }> = []; + const upload = async (opts: { outDir: string; ownFiles?: readonly string[] }) => { + seen.push(opts); + return h.uploadSourcemaps(opts); + }; + const a = runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['a.js', 'a.js.map'], + ...noVcs, + }); + const b = runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['b.js', 'b.js.map'], + ...noVcs, + }); + await tick(); + expect(seen.map((o) => o.ownFiles)).toEqual([['a.js', 'a.js.map']]); // B has not started: no race over the tree + h.release(); + await a; + await tick(); + h.release(); + await b; + expect(seen.map((o) => o.ownFiles)).toEqual([ + ['a.js', 'a.js.map'], + ['b.js', 'b.js.map'], + ]); + }); + + it('a failed in-flight run does not stop the waiting second output from running', async () => { + const calls: string[] = []; + let first = true; + const upload = async (opts: { outDir: string; ownFiles?: readonly string[] }) => { + calls.push(String(opts.ownFiles)); + if (first) { + first = false; + throw new Error('first run failed'); + } + return { injected: true, uploaded: true, deletedMaps: [] }; + }; + const a = runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['a.js'], + ...noVcs, + }); + const b = runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['b.js'], + ...noVcs, + }); + await expect(a).rejects.toThrow('first run failed'); + await b; + expect(calls).toEqual(['a.js', 'b.js']); + }); + it("a run over the build's own files neither joins nor is joined, and registers from those bundles only", async () => { const h = held(); const files = { scripts: ['dist/a.mjs'], maps: ['dist/a.mjs.map'] }; diff --git a/packages/bundler-plugin-core/src/resolve.ts b/packages/bundler-plugin-core/src/resolve.ts index a9b56c82f..389ed7575 100644 --- a/packages/bundler-plugin-core/src/resolve.ts +++ b/packages/bundler-plugin-core/src/resolve.ts @@ -304,9 +304,18 @@ export async function runPluginUpload( // gets its result; the entry is released on settle, so `vite build --watch` still uploads every rebuild. // A run over a build's OWN files (`deps.files`) neither joins nor is joined: it touches nothing another run // of the directory touches, so there is nothing to coordinate. - const inFlight = deps.files === undefined ? runsByDir.get(outDir) : undefined; - if (inFlight !== undefined) { - return inFlight; + // A caller that knows which files ITS output emitted (`ownFiles`) does not join: the in-flight run was + // started with another output's names, and would treat this one's maps as "not produced by this build". + // It WAITS for that run (no concurrent pipelines over one tree) and then runs itself. + for (;;) { + const inFlight = deps.files === undefined ? runsByDir.get(outDir) : undefined; + if (inFlight === undefined) { + break; + } + if (deps.ownFiles === undefined) { + return inFlight; + } + await inFlight.catch(() => undefined); } const uploadSourcemaps = deps.uploadSourcemaps ?? defaultUploadSourcemaps; const registerJsBuild = deps.registerJsBuild ?? defaultRegisterJsBuild; diff --git a/packages/bundler-plugin-core/src/stamp-assets.test.ts b/packages/bundler-plugin-core/src/stamp-assets.test.ts index 24c319083..c6aa80ada 100644 --- a/packages/bundler-plugin-core/src/stamp-assets.test.ts +++ b/packages/bundler-plugin-core/src/stamp-assets.test.ts @@ -723,3 +723,17 @@ describe('stampAssets — a store can refuse the write-back (store.check), befor expect(checked).toEqual([]); }); }); + +describe('stampAssets — two bundles that claim the same map', () => { + it('refuses (before inject) rather than stage the map for only one of them', async () => { + const run = vi.fn(async () => ({ code: 0, stdout: '', stderr: '' })); + const store = { + ...memoryStore({ 'a.js': 'a\n', 'b.js': 'b\n', 'shared.map': '{}' }), + mapOf: () => 'shared.map', + }; + await expect(stampAssets(store, { run })).rejects.toThrow( + /shared\.map.*a\.js.*b\.js|shared\.map/, + ); + expect(run).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/bundler-plugin-core/src/stamp-assets.ts b/packages/bundler-plugin-core/src/stamp-assets.ts index 60dde7e48..236331087 100644 --- a/packages/bundler-plugin-core/src/stamp-assets.ts +++ b/packages/bundler-plugin-core/src/stamp-assets.ts @@ -120,6 +120,13 @@ export async function stampAssets( }, ]); } + if (stageName.has(map)) { + // Two bundles claim ONE map: it can be staged beside only one, and the other would be accepted as + // "stamped" with no map to check. Ambiguous, so the stamp is refused. + throw new Error( + `the map ${map} is claimed by more than one bundle (${bundle} and another), so it cannot be stamped`, + ); + } if (stagedSet.has(sibling)) { throw new Error( `the map ${map} of ${bundle} cannot be staged as ${sibling}: another asset already has that name`, diff --git a/packages/bundler-plugin-core/src/stamp-files.test.ts b/packages/bundler-plugin-core/src/stamp-files.test.ts index bfbdb9b8e..632e6a37d 100644 --- a/packages/bundler-plugin-core/src/stamp-files.test.ts +++ b/packages/bundler-plugin-core/src/stamp-files.test.ts @@ -14,6 +14,7 @@ import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { + cutAtQuery, isFencedPath, isProjectRootOrAbove, isUploadableMap, @@ -21,6 +22,8 @@ import { ownedBy, partitionByKeyed, restoreAtomically, + restorePaths, + sameAsSnapshot, snapshotStampFiles, verifyAndRestore, verifyStampedOnDisk, @@ -137,9 +140,11 @@ describe('snapshot + verifyAndRestore', () => { await writeFile(path, await readFile(spill)); }, }); - expect(attempted).toEqual([join(dir, 'a.js'), join(dir, 'a.js.map')]); // bundle first, map still tried - expect(failed).toEqual([{ path: join(dir, 'a.js'), error: expect.stringContaining('EIO') }]); - expect(restored).toEqual([join(dir, 'a.js.map')]); + expect(attempted).toEqual([join(dir, 'a.js')]); // bundle first; its map is NOT tried once the bundle failed + expect(failed.map((f) => f.path)).toEqual([join(dir, 'a.js'), join(dir, 'a.js.map')]); + expect(failed[0]?.error).toContain('EIO'); + expect(failed[1]?.error).toContain('bundle'); // its map is not restored under a still-stamped bundle + expect(restored).toEqual([]); await snap.dispose(); }); @@ -177,7 +182,10 @@ describe("restoreAtomically keeps the target's identity", () => { await writeFile(join(dir, 'cli.js'), 'stamped'); await chmod(join(dir, 'cli.js'), 0o755); await restoreAtomically(join(dir, 'spill'), join(dir, 'cli.js')); - expect((await stat(join(dir, 'cli.js'))).mode & 0o777).toBe(0o755); + if (process.platform !== 'win32') { + // Windows cannot set the execute bits: the exact mode is a POSIX property + expect((await stat(join(dir, 'cli.js'))).mode & 0o777).toBe(0o755); + } expect(await readFile(join(dir, 'cli.js'), 'utf8')).toBe('#!/usr/bin/env node\n'); }); it('restores THROUGH a symlink: the link stays a link and its real file is replaced', async () => { @@ -350,10 +358,10 @@ describe('verifyStampedOnDisk', () => { join(dir, 'maps', 'a.map'), ]); }); - it('falls back to the sibling .map when the pointer names a file that is not there, and skips a missing bundle', async () => { + it('falls back to the sibling .map when the pointer names a file that is not there', async () => { await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=gone.map\n${STAMP}`); await writeFile(join(dir, 'a.js.map'), stampedMap); - expect(await verifyStampedOnDisk([join(dir, 'a.js'), join(dir, 'missing.js')])).toEqual([]); + expect(await verifyStampedOnDisk([join(dir, 'a.js')])).toEqual([]); }); it('the sibling fallback is really used: a pointer at a missing file, an UNSTAMPED .map beside it', async () => { await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=gone.map\n${STAMP}`); @@ -643,3 +651,132 @@ describe('ownedBy — Windows separators and ./ prefixes (win32 path API, on any expect(fenced('C:\\o\\dist\\assets\\a.css.map')).toBe(true); }); }); + +describe('cutAtQuery', () => { + it('cuts at the first ? only (a # stays), and leaves a name with no ? alone', () => { + expect(cutAtQuery('main.js?abc?d')).toBe('main.js'); + expect(cutAtQuery('a#1.js')).toBe('a#1.js'); + expect(cutAtQuery('x.js')).toBe('x.js'); + expect(cutAtQuery('?q')).toBe(''); + }); +}); + +describe('review hardening of the snapshot / restore / on-disk check', () => { + it('a snapshot aborts (and removes its spill) on a read error that is NOT a missing file', async () => { + const spillRoot = await mkdtemp(join(tmpdir(), 'bugsee-spill-abort-')); + try { + await mkdir(join(dir, 'adir')); // readFile(directory) -> EISDIR, not ENOENT + await expect(snapshotStampFiles({ files: [join(dir, 'adir')] }, spillRoot)).rejects.toThrow(); + expect(await readdir(spillRoot)).toEqual([]); + } finally { + await rm(spillRoot, { recursive: true, force: true }); + } + }); + + it('a bundle that disappears after the change scan is skipped; the other bad pair is still restored', async () => { + const aOriginal = 'a();\n//# sourceMappingURL=a.js.map\n'; + await writeFile(join(dir, 'a.js'), aOriginal); + await writeFile(join(dir, 'a.js.map'), plainMap); + await writeFile(join(dir, 'b.js'), 'b();\n//# sourceMappingURL=b.js.map\n'); + await writeFile(join(dir, 'b.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js'), `${aOriginal}{{${STAMP}`); + await writeFile(join(dir, 'b.js'), `b();\n//# sourceMappingURL=b.js.map\n${STAMP}`); + const { rmSync } = await import('node:fs'); + const result = await verifyAndRestore(snap, { + parse: (code) => { + // verifying a.js: b.js vanishes before its own turn + rmSync(join(dir, 'b.js'), { force: true }); + return !code.includes('{{'); + }, + }); + expect(result.restored).toContain(join(dir, 'a.js')); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe(aOriginal); + await snap.dispose(); + }); + + it('the rollback partner is chosen by the ORIGINAL pointer, even if the bad stamp changed it', async () => { + await mkdir(join(dir, 'maps')); + const original = 'm();\n//# sourceMappingURL=maps/m.map\n'; + await writeFile(join(dir, 'm.js'), original); + await writeFile(join(dir, 'maps', 'm.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + // the bad stamp breaks the bundle AND points it somewhere else; the real map got stamped + await writeFile(join(dir, 'm.js'), `m();\n//# sourceMappingURL=elsewhere.map\n{{${STAMP}`); + await writeFile(join(dir, 'maps', 'm.map'), stampedMap); + const { restored } = await verifyAndRestore(snap); + expect(restored).toEqual([join(dir, 'm.js'), join(dir, 'maps', 'm.map')]); + expect(await readFile(join(dir, 'maps', 'm.map'), 'utf8')).toBe(plainMap); + await snap.dispose(); + }); + + it('a map is NOT restored when its bundle could not be (that would leave a stamped bundle beside an unstamped map)', async () => { + const original = 'a();\n//# sourceMappingURL=a.js.map\n'; + await writeFile(join(dir, 'a.js'), original); + await writeFile(join(dir, 'a.js.map'), plainMap); + await writeFile(join(dir, 'z.js'), 'z();\n//# sourceMappingURL=z.js.map\n'); + await writeFile(join(dir, 'z.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js'), `${original}{{${STAMP}`); + await writeFile(join(dir, 'a.js.map'), stampedMap); + await writeFile(join(dir, 'z.js'), `z();\n//# sourceMappingURL=z.js.map\n{{${STAMP}`); + await writeFile(join(dir, 'z.js.map'), stampedMap); + const { restored, failed } = await verifyAndRestore(snap, { + restoreFile: async (spill, target) => { + if (target === join(dir, 'a.js')) throw new Error('EIO'); + await writeFile(target, await readFile(spill)); + }, + }); + expect(restored).toEqual([join(dir, 'z.js'), join(dir, 'z.js.map')]); // the unrelated pair still restores + expect(failed.map((f) => f.path).sort()).toEqual([join(dir, 'a.js'), join(dir, 'a.js.map')]); + expect(failed.find((f) => f.path === join(dir, 'a.js.map'))?.error).toContain('bundle'); + expect(await readFile(join(dir, 'a.js.map'), 'utf8')).toBe(stampedMap); // untouched, reported incomplete + await snap.dispose(); + }); + + it('verifyStampedOnDisk reports a bundle the stamp named that is missing or unreadable', async () => { + const issues = await verifyStampedOnDisk([join(dir, 'gone.js')]); + expect(issues).toEqual([ + { name: join(dir, 'gone.js'), reason: expect.stringContaining('could not be read') }, + ]); + }); + + it('verifyStampedOnDisk verifies the map the fallback ACTUALLY loaded when the known one is missing', async () => { + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=a.js.map\n${STAMP}`); + await writeFile(join(dir, 'a.js.map'), plainMap); // sibling, unkeyed + const known = new Map([[join(dir, 'a.js'), join(dir, 'missing.map')]]); + const issues = await verifyStampedOnDisk([join(dir, 'a.js')], known); + expect(issues.map((i) => i.name)).toEqual([join(dir, 'a.js.map')]); + }); +}); + +describe('sameAsSnapshot / restorePaths', () => { + it('sameAsSnapshot: true for an unchanged or unknown file, false for a changed or removed one', async () => { + await writeFile(join(dir, 'a.js'), 'a();\n'); + const snap = await snapshotStampFiles({ dir }); + expect(await sameAsSnapshot(snap, join(dir, 'a.js'))).toBe(true); + expect(await sameAsSnapshot(snap, join(dir, 'not-in-snapshot.js'))).toBe(true); + await writeFile(join(dir, 'a.js'), 'changed'); + expect(await sameAsSnapshot(snap, join(dir, 'a.js'))).toBe(false); + await rm(join(dir, 'a.js')); + expect(await sameAsSnapshot(snap, join(dir, 'a.js'))).toBe(false); + await snap.dispose(); + }); + + it('restorePaths puts the originals back, skips unknown files, and returns what it could not restore', async () => { + await writeFile(join(dir, 'a.js'), 'orig'); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js'), 'stamped'); + expect(await restorePaths(snap, [join(dir, 'a.js'), join(dir, 'unknown.js')])).toEqual([]); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe('orig'); + await writeFile(join(dir, 'a.js'), 'stamped'); + await chmod(dir, 0o555); + try { + const failed = await restorePaths(snap, [join(dir, 'a.js')]); + expect(failed.map((f) => f.path)).toEqual([join(dir, 'a.js')]); + } finally { + await chmod(dir, 0o755); + } + await snap.dispose(); + }); +}); diff --git a/packages/bundler-plugin-core/src/stamp-files.ts b/packages/bundler-plugin-core/src/stamp-files.ts index a0e2de504..9a28e05e2 100644 --- a/packages/bundler-plugin-core/src/stamp-files.ts +++ b/packages/bundler-plugin-core/src/stamp-files.ts @@ -72,6 +72,12 @@ export function isFencedPath(relative: string): boolean { .some((segment) => NEVER_WALK.has(segment) || segment.startsWith('.')); } +/** The name up to its `?query` (webpack drops it on disk). indexOf, not a regex: it runs on library input. */ +export function cutAtQuery(name: string): string { + const at = name.indexOf('?'); + return at === -1 ? name : name.slice(0, at); +} + /** * Whether a file under `outDir` is one THIS build emitted. By IDENTITY: the names the bundler reports for its * own output (relative to the output directory; separators and a leading `./` normalised, case exact), not @@ -92,9 +98,7 @@ export function ownedBy( // own name is known both literally and without its `?query`, and a file on disk is compared literally: // a stale `x#old.js.map` or `index.js?old` is never mistaken for this build's. const normal = (name: string): string => posix.normalize(name.replace(/\\/g, '/')); - const owned = new Set( - ownFiles.flatMap((name) => [normal(name), normal(name.replace(/\?.*$/, ''))]), - ); + const owned = new Set(ownFiles.flatMap((name) => [normal(name), normal(cutAtQuery(name))])); return (file) => owned.has(normal(api.relative(outDir, file))); } @@ -198,9 +202,14 @@ export async function snapshotStampFiles( let bytes: Buffer; try { bytes = await readFile(original); - } catch { - // Gone between listing and reading (a concurrent build's cleanup): nothing to verify or restore. - continue; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + // Gone between listing and reading (a concurrent build's cleanup): nothing to verify or restore. + continue; + } + // Anything else (EACCES, EISDIR, a transient I/O error) is NOT "gone": injecting with an incomplete + // snapshot would leave a file nothing can verify or restore. Abort (the spill is removed below). + throw error; } const spill = join(spillDir, String(index++)); await writeFile(spill, bytes); @@ -217,6 +226,39 @@ export async function snapshotStampFiles( }; } +/** Whether `file` still has the bytes it had when the snapshot was taken (false when it changed or is gone). */ +export async function sameAsSnapshot(snapshot: StampSnapshot, file: string): Promise { + const entry = snapshot.entries.get(file); + if (entry === undefined) { + return true; + } + try { + return sha1(await readFile(file)) === entry.hash; + } catch { + return false; + } +} + +/** Put the ORIGINAL bytes of these files back (atomically); returns the ones that could not be restored. */ +export async function restorePaths( + snapshot: StampSnapshot, + files: readonly string[], +): Promise> { + const failed: Array<{ path: string; error: string }> = []; + for (const file of files) { + const entry = snapshot.entries.get(file); + if (entry === undefined) { + continue; + } + try { + await restoreAtomically(entry.spill, file); + } catch (error) { + failed.push({ path: file, error: String(error) }); + } + } + return failed; +} + export interface RestoreOptions { /** Injectable JavaScript parser for the verification (default: acorn). */ parse?: (code: string) => boolean; @@ -290,13 +332,29 @@ export async function verifyAndRestore( const paired = new Set(); const stampedBundles = changed.filter((file) => /\.[cm]?js$/i.test(file)); for (const bundle of stampedBundles) { - const after = (await read(bundle)) as Buffer; + const after = await read(bundle); + if (after === undefined) { + continue; // removed since the change scan: nothing to compare, and a restore would not recreate it + } const map = resolveMapName(bundle, after.toString('utf8'), (n) => entries.has(n), path); paired.add(map); - const before = new Map([[bundle, await original(bundle)]]); + const originalBundle = await original(bundle); + // The ROLLBACK partner is the map the ORIGINAL bundle pointed at (a bad stamp may have changed the pointer); + // verification still looks at the current one. + const originalMap = resolveMapName( + bundle, + originalBundle.toString('utf8'), + (n) => entries.has(n), + path, + ); + if (entries.has(originalMap)) { + partner.set(bundle, originalMap); + partner.set(originalMap, bundle); + } + const before = new Map([[bundle, originalBundle]]); const now = new Map([[bundle, after]]); if (entries.has(map)) { - partner.set(bundle, map); + partner.set(bundle, partner.get(bundle) ?? map); partner.set(map, bundle); before.set(map, await original(map)); const mapNow = await read(map); @@ -350,11 +408,24 @@ export async function verifyAndRestore( const order = [...toRestore].sort( (a, b) => Number(a.endsWith('.map')) - Number(b.endsWith('.map')) || a.localeCompare(b), ); + const failedPaths = new Set(); for (const file of order) { + // A map is not restored when its bundle could not be: the stamped bundle would then point at an + // original map that does not carry its new id. Reported as incomplete; unrelated pairs still restore. + const pairedBundle = file.endsWith('.map') ? partner.get(file) : undefined; + if (pairedBundle !== undefined && failedPaths.has(pairedBundle)) { + failedPaths.add(file); + failed.push({ + path: file, + error: `not restored: its bundle ${pairedBundle} could not be restored`, + }); + continue; + } try { await restoreFile((entries.get(file) as SnapshotEntry).spill, file); restored.push(file); } catch (error) { + failedPaths.add(file); failed.push({ path: file, error: String(error) }); } } @@ -377,15 +448,25 @@ export async function verifyStampedOnDisk( let code: Buffer; try { code = await readFile(bundle); - } catch { + } catch (error) { + // The stamp named this bundle, so it must be there: say so rather than skip it (a stale or public + // script is never in `bundles`, so this does not judge them). + issues.push({ + name: bundle, + reason: `the stamped bundle could not be read: ${String(error)}`, + }); continue; } const files = new Map([[bundle, code]]); const pointed = resolveMapName(bundle, code.toString('utf8'), () => true, path); const hinted = known.get(bundle); + // The pair that was ACTUALLY loaded is the one verified (a missing known map must not make a loaded + // sibling go unchecked). + let hint: ReadonlyMap = new Map(); try { const first = hinted ?? pointed; files.set(first, await readFile(first)); + hint = known; // only once the known map was really loaded } catch { // The pointer names no file: the `.map` sibling inject pairs by default. await readFile(`${bundle}.map`).then( @@ -393,7 +474,7 @@ export async function verifyStampedOnDisk( () => undefined, ); } - issues.push(...verifyStampedPairs(files, known)); + issues.push(...verifyStampedPairs(files, hint)); } return issues; } diff --git a/packages/bundler-plugin-core/src/verify-stamp.test.ts b/packages/bundler-plugin-core/src/verify-stamp.test.ts index 9adc5d274..f8addadae 100644 --- a/packages/bundler-plugin-core/src/verify-stamp.test.ts +++ b/packages/bundler-plugin-core/src/verify-stamp.test.ts @@ -502,3 +502,54 @@ describe('pointers with whitespace, and pointers that leave the output', () => { expect(issues.length).toBeGreaterThan(0); }); }); + +describe('a changed map is held to an UNCHANGED stamped bundle', () => { + const REG = + '!function(){try{var e=globalThis;e._bugseeDebugIds=e._bugseeDebugIds||{}}catch(e){}}();'; + const stampedCode = (id: string) => + `a();\n//# sourceMappingURL=a.js.map\n\n;${REG}\n//# debugId=${id}\n`; + it('flags a map that now carries a DIFFERENT id than its (unchanged, already stamped) bundle', () => { + const code = buf(stampedCode(ID)); + const issues = verifyStamp( + new Map([ + ['a.js', code], + ['a.js.map', buf(mapJson())], + ]), + new Map([ + ['a.js', code], + ['a.js.map', buf(stampedMap(OTHER_ID))], + ]), + ); + expect(issues).toHaveLength(1); + expect(issues[0]).toMatchObject({ name: 'a.js.map' }); + expect(issues[0]?.reason).toContain(OTHER_ID); + }); + it('accepts the map that matches it, and a map beside an unstamped bundle (JSON only)', () => { + const code = buf(stampedCode(ID)); + expect( + verifyStamp( + new Map([ + ['a.js', code], + ['a.js.map', buf(mapJson())], + ]), + new Map([ + ['a.js', code], + ['a.js.map', buf(stampedMap(ID))], + ]), + ), + ).toEqual([]); + const plain = buf('a();\n//# sourceMappingURL=a.js.map\n'); + expect( + verifyStamp( + new Map([ + ['a.js', plain], + ['a.js.map', buf(mapJson())], + ]), + new Map([ + ['a.js', plain], + ['a.js.map', buf(stampedMap(OTHER_ID))], + ]), + ), + ).toEqual([]); + }); +}); diff --git a/packages/bundler-plugin-core/src/verify-stamp.ts b/packages/bundler-plugin-core/src/verify-stamp.ts index 59fb99dba..aa830045b 100644 --- a/packages/bundler-plugin-core/src/verify-stamp.ts +++ b/packages/bundler-plugin-core/src/verify-stamp.ts @@ -241,10 +241,35 @@ export function verifyStamp( // A changed map whose bundle was not stamped in this run: only held to being a JSON object. const pairedMaps = new Set(mapOf.values()); + // The id of an UNCHANGED bundle that already carries one, by the map it points at: a map that changed + // must agree with it (the bundle pass skipped it because its bytes did not change). + const unchangedIds = new Map(); + for (const [bundle, bytes] of after) { + if (BUNDLE.test(bundle) && before.has(bundle) && !changed(bundle)) { + const text = bytes.toString('utf8'); + const id = readDebugId(text); + if (id !== undefined) { + unchangedIds.set( + resolveMapName(bundle, text, (n) => after.has(n), api), + id, + ); + } + } + } for (const name of before.keys()) { if (name.endsWith('.map') && changed(name) && !pairedMaps.has(name)) { - if (mapDebugId(after.get(name) as Buffer) === null) { + const mapId = mapDebugId(after.get(name) as Buffer); + if (mapId === null) { issues.push({ name, reason: 'the stamped map is not valid JSON (an object)' }); + } else if ( + mapId !== undefined && + unchangedIds.has(name) && + unchangedIds.get(name) !== mapId + ) { + issues.push({ + name, + reason: `the map's debugId ${mapId} does not match its bundle's debugId comment ${unchangedIds.get(name)}`, + }); } } } diff --git a/packages/instrumentation-tests/test/lazy-chunk.e2e.ts b/packages/instrumentation-tests/test/lazy-chunk.e2e.ts index fbfbfb791..c3423b942 100644 --- a/packages/instrumentation-tests/test/lazy-chunk.e2e.ts +++ b/packages/instrumentation-tests/test/lazy-chunk.e2e.ts @@ -18,7 +18,7 @@ import { } from 'node:fs'; import { createServer, type Server } from 'node:http'; import { tmpdir } from 'node:os'; -import { dirname, extname, join, normalize } from 'node:path'; +import { dirname, extname, isAbsolute, join, relative, resolve } from 'node:path'; import { bugseeRollupPlugin, bugseeRspackPlugin } from '@bugsee/bundler-plugin-core'; import { bugseeVitePlugin } from '@bugsee/vite-plugin'; import { bugseeWebpackPlugin } from '@bugsee/webpack-plugin'; @@ -45,9 +45,15 @@ const TYPES: Record = { async function serve(dir: string): Promise<{ url: string; server: Server }> { const server = createServer((req, res) => { - const path = normalize( - join(dir, (req.url ?? '/').split('?')[0] === '/' ? 'index.html' : (req.url as string)), - ); + // Contain the request inside `dir`: a path-aware check (a raw prefix also accepts a sibling directory). + const requested = (req.url ?? '/').split('?')[0] as string; + const path = resolve(dir, `.${requested === '/' ? '/index.html' : requested}`); + const inside = relative(dir, path); + if (inside.startsWith('..') || isAbsolute(inside)) { + res.statusCode = 403; + res.end(); + return; + } try { res.setHeader('content-type', TYPES[extname(path)] ?? 'application/octet-stream'); res.end(readFileSync(path)); diff --git a/packages/instrumentation-tests/test/sri-vite-rollup.e2e.ts b/packages/instrumentation-tests/test/sri-vite-rollup.e2e.ts index 508a0e56b..0b221c0d6 100644 --- a/packages/instrumentation-tests/test/sri-vite-rollup.e2e.ts +++ b/packages/instrumentation-tests/test/sri-vite-rollup.e2e.ts @@ -12,7 +12,7 @@ import { createHash } from 'node:crypto'; import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { createServer, type Server } from 'node:http'; import { tmpdir } from 'node:os'; -import { extname, join, normalize } from 'node:path'; +import { extname, isAbsolute, join, relative, resolve } from 'node:path'; import { runBugseeCli } from '@bugsee/bundler-plugin-core'; import { bugseeVitePlugin } from '@bugsee/vite-plugin'; import { type Browser, chromium } from 'playwright'; @@ -45,10 +45,11 @@ const TYPES: Record = { async function serve(dir: string): Promise<{ url: string; server: Server }> { const server = createServer((req, res) => { - const path = normalize( - join(dir, (req.url ?? '/').split('?')[0] === '/' ? 'index.html' : (req.url as string)), - ); - if (!path.startsWith(dir)) { + // Contain the request inside `dir`: a path-aware check (a raw prefix also accepts a sibling directory). + const requested = (req.url ?? '/').split('?')[0] as string; + const path = resolve(dir, `.${requested === '/' ? '/index.html' : requested}`); + const inside = relative(dir, path); + if (inside.startsWith('..') || isAbsolute(inside)) { res.statusCode = 403; res.end(); return; diff --git a/packages/instrumentation-tests/test/sri.e2e.ts b/packages/instrumentation-tests/test/sri.e2e.ts index c62744159..a50bc57ba 100644 --- a/packages/instrumentation-tests/test/sri.e2e.ts +++ b/packages/instrumentation-tests/test/sri.e2e.ts @@ -18,7 +18,7 @@ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { createServer, type Server } from 'node:http'; import { tmpdir } from 'node:os'; -import { extname, isAbsolute, join, normalize } from 'node:path'; +import { extname, isAbsolute, join, relative, resolve } from 'node:path'; import { resolveBugseeCli, runBugseeCli } from '@bugsee/bundler-plugin-core'; import { bugseeWebpackPlugin } from '@bugsee/webpack-plugin'; import HtmlWebpackPlugin from 'html-webpack-plugin'; @@ -55,10 +55,11 @@ const TYPES: Record = { /** Serve a build directory over HTTP — SRI with `crossorigin` is not exercised over file://. */ async function serve(dir: string): Promise<{ url: string; server: Server }> { const server = createServer((req, res) => { - const path = normalize( - join(dir, (req.url ?? '/').split('?')[0] === '/' ? 'index.html' : (req.url as string)), - ); - if (!path.startsWith(dir)) { + // Contain the request inside `dir`: a path-aware check (a raw prefix also accepts a sibling directory). + const requested = (req.url ?? '/').split('?')[0] as string; + const path = resolve(dir, `.${requested === '/' ? '/index.html' : requested}`); + const inside = relative(dir, path); + if (inside.startsWith('..') || isAbsolute(inside)) { res.statusCode = 403; res.end(); return; From 436ac9880ac55795c9ee14a3e4bd3aad8458e150 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 17:55:27 +0500 Subject: [PATCH 23/39] test(bundler-plugin-core): type the catch-up edge-case run mock Co-Authored-By: Claude Sonnet 5.5 --- packages/bundler-plugin-core/src/orchestrate.stamp.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index 916067e9d..b50005ccb 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -1759,7 +1759,7 @@ describe('catch-up edge cases (pointer search, failed restore of a pinned bundle it('an own bundle that cannot be read is skipped during the pointer search', async () => { await mkdir(join(dir, 'maps')); await writeFile(join(dir, 'maps', 'x.js.map'), plain); // unkeyed, no sibling bundle - const run = vi.fn(async (): Promise => ({ code: 0, stdout: '', stderr: '' })); + const run = vi.fn(async (_args: string[]): Promise => ({ code: 0, stdout: '', stderr: '' })); const errors: unknown[] = []; await uploadSourcemaps({ ...base, From a67491a084298c5c391da863c85c1f8376023c7e Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 17:55:36 +0500 Subject: [PATCH 24/39] style(bundler-plugin-core): format a test Co-Authored-By: Claude Sonnet 5.5 --- packages/bundler-plugin-core/src/orchestrate.stamp.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index b50005ccb..bf8e1efde 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -1759,7 +1759,9 @@ describe('catch-up edge cases (pointer search, failed restore of a pinned bundle it('an own bundle that cannot be read is skipped during the pointer search', async () => { await mkdir(join(dir, 'maps')); await writeFile(join(dir, 'maps', 'x.js.map'), plain); // unkeyed, no sibling bundle - const run = vi.fn(async (_args: string[]): Promise => ({ code: 0, stdout: '', stderr: '' })); + const run = vi.fn( + async (_args: string[]): Promise => ({ code: 0, stdout: '', stderr: '' }), + ); const errors: unknown[] = []; await uploadSourcemaps({ ...base, From 048700ab419715efa37907ed9783da1a3f230e90 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 18:08:55 +0500 Subject: [PATCH 25/39] fix(bundler-plugin-core): on-disk re-check judges only what the stamp wrote and what still exists Two false-alarm paths from the previous commit, found in review: - Vite/Rollup: stampedBundles are the names at generateBundle time; a later plugin may delete or inline a chunk. The re-check now judges only stamped chunks still in the FINAL bundle (and the matching stampedMaps). - webpack/Rspack: the final-name list took every script asset, including ones a plugin emitted after the stamp stage (sw.js + sw.js.map). The store now marks every asset it writes back in its asset info (`bugseeStamped`), which survives RealContentHashPlugin's rename (measured on real webpack and Rspack), and only marked assets are judged. Co-Authored-By: Claude Sonnet 5.5 --- .../src/plugin.stamp.test.ts | 77 +++++++++++++++++-- packages/bundler-plugin-core/src/plugin.ts | 40 ++++++++-- 2 files changed, 105 insertions(+), 12 deletions(-) diff --git a/packages/bundler-plugin-core/src/plugin.stamp.test.ts b/packages/bundler-plugin-core/src/plugin.stamp.test.ts index 1e8ea0504..5eb9ad173 100644 --- a/packages/bundler-plugin-core/src/plugin.stamp.test.ts +++ b/packages/bundler-plugin-core/src/plugin.stamp.test.ts @@ -71,8 +71,8 @@ describe('rspack: stamps inside the compilation', () => { }, getAssets: () => [{ name: 'main.js' }, { name: 'main.js.map' }], getAsset: (name: string) => ({ source: { buffer: () => Buffer.from(`content of ${name}`) } }), - updateAsset: (name: string, source: unknown) => { - updated.push({ name, source }); + updateAsset: (name: string, source: unknown, info?: unknown) => { + updated.push({ name, source, info } as never); }, }; const compilations: Array<(c: unknown) => void> = []; @@ -374,10 +374,12 @@ describe('rspack: stamps inside the compilation', () => { await r.compile(); await (r.afterEmitWith as (c: unknown) => Promise)({ getAssets: () => [ - { name: 'main.NEWHASH.js' }, + { name: 'main.NEWHASH.js', info: { bugseeStamped: true } }, { name: 'main.NEWHASH.js.map' }, { name: 'x.css' }, - { name: 'q.js?h' }, + { name: 'q.js?h', info: { bugseeStamped: true } }, + { name: 'sw.js' }, // emitted after the stamp stage: never staged, never stamped + { name: 'sw.js.map' }, ], }); const deps = depsOf(0) as { stampedBundles?: string[]; stampedMaps?: unknown }; @@ -385,6 +387,17 @@ describe('rspack: stamps inside the compilation', () => { expect(deps.stampedMaps).toBeUndefined(); }); + it('marks every asset it writes back (asset info survives the contenthash rename)', async () => { + stampSpy.mockImplementation(async (store) => { + (store as { update(n: string, c: Buffer): void }).update('main.js', Buffer.from('stamped')); + return { stamped: ['main.js'], maps: {}, bundles: 1 }; + }); + const r = rspackCompiler(); + apply({ appToken: 'tok' }, r.compiler); + await r.compile(); + expect((r.updated[0] as { info?: unknown }).info).toEqual({ bugseeStamped: true }); + }); + it('does not stamp for a disabled plugin', async () => { const r = rspackCompiler(); apply({ disabled: true }, r.compiler); @@ -865,7 +878,12 @@ describe('webpack: after [contenthash] renames, the on-disk re-check gets the FI hooks: { processAssets: { tapPromise: (_o: unknown, fn: () => Promise) => taps.push(fn) }, }, - getAssets: () => [{ name: 'm.NEW.js' }, { name: 'm.NEW.js.map' }, { name: 'q.js?h' }], + getAssets: () => [ + { name: 'm.NEW.js', info: { bugseeStamped: true } }, + { name: 'm.NEW.js.map' }, + { name: 'q.js?h', info: { bugseeStamped: true } }, + { name: 'sw.js' }, + ], getAsset: () => undefined, updateAsset: () => undefined, }; @@ -895,3 +913,52 @@ describe('webpack: after [contenthash] renames, the on-disk re-check gets the FI expect(deps.stampedMaps).toBeUndefined(); }); }); + +describe('vite/rollup: the on-disk re-check judges only stamped chunks that are still in the FINAL bundle', () => { + it('drops a stamped chunk a later plugin removed from the bundle', async () => { + stampSpy.mockImplementation(async () => ({ + stamped: ['a.js', 'gone.js'], + maps: { 'a.js': 'a.js.map', 'gone.js': 'gone.js.map' }, + bundles: 2, + })); + for (const kind of ['vite', 'rollup'] as const) { + uploadSpy.mockClear(); + const hooks = makePlugin({ appToken: 'tok' })[kind] as unknown as { + generateBundle: { handler: (o: object, b: Record) => Promise }; + writeBundle: (o: object, b?: object) => Promise; + }; + const output = { dir: '/out' }; + await hooks.generateBundle.handler(output, { + 'a.js': { type: 'chunk', fileName: 'a.js', code: 'x', map: {} }, + 'a.js.map': { type: 'asset', fileName: 'a.js.map', source: '{}' }, + }); + await hooks.writeBundle(output, { 'a.js': {}, 'a.js.map': {} }); // gone.js was deleted by a later generateBundle + const deps = depsOf(0) as { stampedBundles?: string[]; stampedMaps?: Record }; + expect(deps.stampedBundles).toEqual(['a.js']); + expect(deps.stampedMaps).toEqual({ 'a.js': 'a.js.map' }); + } + }); +}); + +describe("vite/rollup: without a final bundle the stamp's own names are used unchanged", () => { + it('passes stampedBundles and stampedMaps through when writeBundle gets no bundle', async () => { + stampSpy.mockImplementation(async () => ({ + stamped: ['a.js'], + maps: { 'a.js': 'a.js.map' }, + bundles: 1, + })); + const hooks = makePlugin({ appToken: 'tok' }).rollup as unknown as { + generateBundle: { handler: (o: object, b: Record) => Promise }; + writeBundle: (o: object, b?: object) => Promise; + }; + const output = { dir: '/out' }; + await hooks.generateBundle.handler(output, { + 'a.js': { type: 'chunk', fileName: 'a.js', code: 'x', map: {} }, + 'a.js.map': { type: 'asset', fileName: 'a.js.map', source: '{}' }, + }); + await hooks.writeBundle(output); + const deps = depsOf(0) as { stampedBundles?: string[]; stampedMaps?: Record }; + expect(deps.stampedBundles).toEqual(['a.js']); + expect(deps.stampedMaps).toEqual({ 'a.js': 'a.js.map' }); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index c6d9348e1..927a1f380 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -66,7 +66,7 @@ interface WebpackCompilationLike { info?: { related?: { sourceMap?: string | string[] | null } }; } | undefined; - updateAsset(name: string, source: unknown): void; + updateAsset(name: string, source: unknown, info?: object): void; } /** Minimal shape of the webpack compiler we tap (avoids a webpack type dependency in the core). */ @@ -248,7 +248,11 @@ function webpackAssetStore( // (the runtime asked for a chunk that did not exist: ChunkLoadError). JS and its map are UTF-8 text. check: (name, content) => void asText(name, content), update: (name, content) => - compilation.updateAsset(realName(name), new RawSource(asText(name, content))), + // The info marks what was stamped; it is carried across RealContentHashPlugin's rename (measured on real + // webpack and Rspack), which is how the final names are recovered at `afterEmit`. + compilation.updateAsset(realName(name), new RawSource(asText(name, content)), { + bugseeStamped: true, + }), // The compilation records which asset is a bundle's source map (SourceMapDevToolPlugin: info.related). mapOf: (name) => { const related = compilation.getAsset(realName(name))?.info?.related?.sourceMap; @@ -333,14 +337,14 @@ function esbuildOutputDir(options: EsbuildBuildLike['initialOptions']): string | /** The compilation handed to `afterEmit`: enough to list every asset this build emitted. */ interface AssetNamesLike { - getAssets?(): ReadonlyArray<{ name: string }>; + getAssets?(): ReadonlyArray<{ name: string; info?: object }>; } /** * The stamp's bundle / map names as the DISK has them. webpack's RealContentHashPlugin renames `[contenthash]` * assets AFTER the in-build stamp, so the names the stamp reported are stale; when the compilation is known, - * the on-disk re-check is given the final script names instead (every script asset was staged, so every one - * was stamped) and finds each map by its pointer. + * the on-disk re-check is given the final names of the assets the stamp wrote (marked in their asset info) and + * finds each map by its pointer. */ const finalStampNames = ( compilation: AssetNamesLike | undefined, @@ -349,13 +353,34 @@ const finalStampNames = ( return assets === undefined ? {} : { + // Only assets the stamp itself wrote (marked in their info): a script a plugin emitted after the stamp + // stage was never stamped and must not be judged as if it had been. stampedBundles: assets + .filter( + (asset) => + (asset.info as { bugseeStamped?: boolean } | undefined)?.bugseeStamped === true, + ) .map((asset) => cutAtQuery(asset.name)) .filter((name) => /\.[cm]?js$/i.test(name)), stampedMaps: undefined, }; }; +/** The stamped bundle names that are still in the final bundle (all of them when the bundle is unknown). */ +const stampedStillPresent = ( + names: string[] | undefined, + bundle: object | undefined, +): string[] | undefined => (bundle === undefined ? names : names?.filter((name) => name in bundle)); + +/** The stamped bundle -> map names whose bundle is still in the final bundle. */ +const stampedMapsStillPresent = ( + maps: Record | undefined, + bundle: object | undefined, +): Record | undefined => + bundle === undefined || maps === undefined + ? maps + : Object.fromEntries(Object.entries(maps).filter(([name]) => name in bundle)); + /** The names this build emitted, as the `ownFiles` the upload deletes by (absent when not known). */ const ownFilesOf = (compilation: AssetNamesLike | undefined): { ownFiles?: string[] } => { const assets = compilation?.getAssets?.(); @@ -591,8 +616,9 @@ export const bugseeUnpluginFactory: UnpluginFactory Date: Mon, 23 Nov 2026 18:22:10 +0500 Subject: [PATCH 26/39] fix(bundler-plugin-core): report an unrestorable rewrite, sibling outputs, claimed sibling maps - a rejected post-emit inject whose rewrite could NOT be restored now says which files still hold it (the rethrown error carries it), with or without failOnError - outputs written into one directory announce their names at generateBundle (a new build forgets outputs that never wrote); each run leaves the maps of the still-pending outputs to those outputs: not uploaded by this run and not reported as "not produced by this build" (real Rollup test with six concurrent iife outputs) - a map equal to any bundle's own .map sibling is claimed too: two claimants refuse the stamp - test: the rollback partner is the original pointer's map even when the changed pointer names another snapshotted map (kills the surviving mutation) Co-Authored-By: Claude Sonnet 5.5 --- docs/design/source-maps.md | 8 ++- .../src/orchestrate.stamp.test.ts | 72 +++++++++++++++++++ .../bundler-plugin-core/src/orchestrate.ts | 24 ++++++- .../src/plugin.in-build.real-build.test.ts | 41 +++++++++++ .../src/plugin.stamp.test.ts | 40 +++++++++++ packages/bundler-plugin-core/src/plugin.ts | 20 ++++++ .../bundler-plugin-core/src/resolve.test.ts | 39 ++++++++++ packages/bundler-plugin-core/src/resolve.ts | 47 +++++++++++- .../src/stamp-assets.test.ts | 12 ++++ .../bundler-plugin-core/src/stamp-assets.ts | 19 +++-- .../src/stamp-files.test.ts | 17 +++++ 11 files changed, 326 insertions(+), 13 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 6586f41ca..e8a3f128f 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -316,7 +316,13 @@ id. (The hand-rolled SRI step pins only the entry chunks in `index.html`, never `maps/w.js.map`). The claim that inject leaves an already-stamped, SRI-pinned bundle alone is ENFORCED: if its bytes changed they are restored (with its map) and reported. Two bundles claiming one map refuse the in-build stamp. - **Concurrent outputs.** A second output with its own `ownFiles` for the same directory waits for the in-flight - upload and then runs itself, so its maps are not mistaken for foreign ones. + upload and then runs itself, so its maps are not mistaken for foreign ones. Outputs announce their names at + `generateBundle` (before any of them writes; a new build forgets outputs that never wrote), and each run leaves + the maps of the outputs still pending to those outputs: neither uploaded by this run nor reported as "not produced + by this build". N outputs into one directory make N uploads, not N times everything. +- **A rejected inject whose rewrite could not be restored** says so (the rethrown error carries which files still + hold the unverified rewrite), with or without `failOnError`. Two bundles claiming one map, counting a bundle's + own sibling as a claim, refuse the in-build stamp. ### Maps that are not the bundle sibling diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index bf8e1efde..2a8572dd2 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -1806,3 +1806,75 @@ describe('catch-up edge cases (pointer search, failed restore of a pinned bundle expect(errors.map(String).join('\n')).toContain('could not restore'); }); }); + +describe('round-17 hardening: failed restore after a rejected inject, sibling outputs', () => { + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-r17-')); + }); + afterEach(async () => { + await chmod(dir, 0o755).catch(() => undefined); + await rm(dir, { recursive: true, force: true }); + }); + const keyed = JSON.stringify({ debugId: ID }); + const ok = async (_args: string[]): Promise => ({ code: 0, stdout: '', stderr: '' }); + + it('a rejected inject whose rewrite could NOT be restored says so (default and failOnError)', async () => { + await writeFile(join(dir, 'a.js'), 'a();\n//# sourceMappingURL=a.js.map\n'); + await writeFile(join(dir, 'a.js.map'), '{"version":3}'); + const run = vi.fn(async (args: string[]): Promise => { + if (args[1] === 'inject') { + await writeFile(join(dir, 'a.js'), '{{'); + await chmod(dir, 0o555); // the restore cannot create its temp file + throw new Error('cli died'); + } + return { code: 0, stdout: '', stderr: '' }; + }); + const errors: unknown[] = []; + await uploadSourcemaps({ + ...base, + outDir: dir, + run, + findSri: async () => [], + onError: (e) => errors.push(e), + }); + const text = errors.map(String).join('\n'); + expect(text).toContain('cli died'); + expect(text).toContain('COULD NOT restore'); + expect(text).toContain('a.js'); + + await chmod(dir, 0o755); + await writeFile(join(dir, 'a.js'), 'a();\n//# sourceMappingURL=a.js.map\n'); + await expect( + uploadSourcemaps({ ...base, outDir: dir, run, findSri: async () => [], failOnError: true }), + ).rejects.toThrow(/cli died[\s\S]*COULD NOT restore/); + }); + + it('a map owned by a SIBLING output is neither uploaded by this one nor noticed as foreign', async () => { + await writeFile(join(dir, 'a.js.map'), keyed); + await writeFile(join(dir, 'b.js.map'), keyed); // the sibling output's + await writeFile(join(dir, 'x.js.map'), keyed); // truly foreign + const calls: string[][] = []; + const notices: string[] = []; + await uploadSourcemaps({ + ...base, + outDir: dir, + run: async (args) => { + calls.push(args); + return ok(args); + }, + preStamped: true, + verifySri: async () => [], + ownFiles: ['a.js.map'], + siblingOwnFiles: ['b.js.map'], + onNotice: (m) => notices.push(m), + }); + const upload = calls.find((c) => c[0] === 'debug-files') as string[]; + expect(upload).toContain(join(dir, 'a.js.map')); + expect(upload).toContain(join(dir, 'x.js.map')); // foreign keyed maps are still uploaded (as before) + expect(upload).not.toContain(join(dir, 'b.js.map')); + expect(notices.join('\n')).toContain('x.js.map'); + expect(notices.join('\n')).not.toContain('b.js.map'); + expect(await readdir(dir)).toContain('b.js.map'); // untouched, left for its own output + }); +}); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 5ddbc69b2..dad107aaf 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -100,6 +100,11 @@ export interface UploadSourcemapsOptions { * said. Without it (a directory run where the output is not known) the directory-name fence applies. */ ownFiles?: readonly string[]; + /** + * The names OTHER outputs of the same directory emitted. This output neither uploads nor reports their + * maps: each output handles its own, so N outputs into one directory make N uploads, not N times everything. + */ + siblingOwnFiles?: readonly string[]; /** The in-build stamp's bundle -> map names (relative to `outDir`), for maps the pointer and sibling cannot name. */ stampedMaps?: Readonly>; /** Where a non-failing observation goes (default: nowhere — callers that want it pass the notice sink). */ @@ -538,8 +543,18 @@ export async function uploadSourcemaps( // restore them BEFORE the failure propagates, so no unverified stamp stays on disk. if (original !== undefined) { try { - await verifyAndRestore(original); - } catch { + const { issues, restored, failed } = await verifyAndRestore(original); + if (failed.length > 0) { + // Files still carry the unverified rewrite: that must not go unmentioned. + throw new Error( + `${error instanceof Error ? error.message : String(error)}; ${verifyFailure(issues, restored, failed).message}`, + { cause: error }, + ); + } + } catch (restoreError) { + if (restoreError instanceof Error && restoreError.cause === error) { + throw restoreError; + } // the inject failure is the one to report } } @@ -623,7 +638,10 @@ export async function uploadSourcemaps( // ONE walk: the uploadable maps are classified by key; the stylesheet / declaration maps of the same // walk are never uploaded but embed the source, so they are deleted with the uploaded ones. // Sorted here, so the CLI batches and the notice are stable whatever order a walk returns. - const everything = [...(await (options.listUploadMaps ?? listOutputMaps)(outDir))].sort(); + const siblings = ownedBy(outDir, options.siblingOwnFiles ?? []); + const everything = [...(await (options.listUploadMaps ?? listOutputMaps)(outDir))] + .filter((map) => !siblings(map)) + .sort(); const { deletable, kept } = await (options.partitionMaps ?? partitionByKeyed)( everything.filter(isUploadableMap), ); diff --git a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts index 5902f6cdc..02e433e60 100644 --- a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts @@ -1185,3 +1185,44 @@ describeReal('Vite: an own script with a broken map does not cost the other maps } } }); + +// N Rollup outputs written CONCURRENTLY into one directory: each uploads and deletes ITS OWN maps, once, and none +// reports another's maps as foreign. +describeReal('several Rollup outputs written concurrently into one directory', () => { + it("uploads once per output (not N times everything) and never says another output's maps are foreign", async () => { + const app = makeApp('rollup-many-outputs', { lazy: false }); + const names = ['a', 'b', 'c', 'd', 'e', 'f']; + const before = requests.length; + const notices: string[] = []; + const errors: unknown[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + onNotice: (m: string) => notices.push(m), + onError: (e: unknown) => errors.push(e), + }), + ], + }); + await Promise.all( + names.map((n) => + bundle.write({ + file: join(app.out, `${n}.js`), + format: 'iife', + name: `app_${n}`, + sourcemap: true, + }), + ), + ); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expect(notices.filter((m) => m.includes('not produced by this build'))).toEqual([]); + const files = readdirSync(app.out); + expect(files.filter((f) => f.endsWith('.map'))).toEqual([]); + expect(files.filter((f) => f.endsWith('.js')).sort()).toEqual(names.map((n) => `${n}.js`)); + // one CLI upload call per output: a request per map, so at most the number of outputs + expect(requests.length - before).toBeLessThanOrEqual(names.length); + expect(requests.length - before).toBeGreaterThanOrEqual(1); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.stamp.test.ts b/packages/bundler-plugin-core/src/plugin.stamp.test.ts index 5eb9ad173..4bdc601dc 100644 --- a/packages/bundler-plugin-core/src/plugin.stamp.test.ts +++ b/packages/bundler-plugin-core/src/plugin.stamp.test.ts @@ -962,3 +962,43 @@ describe("vite/rollup: without a final bundle the stamp's own names are used unc expect(deps.stampedMaps).toEqual({ 'a.js': 'a.js.map' }); }); }); + +describe('outputs announce their names at generateBundle, so the first write already knows its siblings', () => { + const hooksOf2 = (kind: 'vite' | 'rollup') => + makePlugin({ appToken: 'tok', onNotice: () => undefined })[kind] as unknown as { + generateBundle: { handler: (o: object, b: Record) => Promise }; + writeBundle: (o: object, b?: object) => Promise; + buildStart?: () => void; + }; + const bundleOf = (name: string) => ({ + [`${name}.js`]: { type: 'chunk', fileName: `${name}.js`, code: 'x', map: {} }, + [`${name}.js.map`]: { type: 'asset', fileName: `${name}.js.map`, source: '{}' }, + }); + const siblingsOf = (call: number) => + (uploadSpy.mock.calls[call]?.[2] as { siblingOwnFiles?: string[] }).siblingOwnFiles; + + for (const kind of ['vite', 'rollup'] as const) { + it(`${kind}: the first output to write is told the others' names; the last is told none`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + const [a, b] = [{ file: '/out/a.js' }, { file: '/out/b.js' }]; + await h.generateBundle.handler(a, bundleOf('a')); + await h.generateBundle.handler(b, bundleOf('b')); + await h.writeBundle(a, bundleOf('a')); + await h.writeBundle(b, bundleOf('b')); + expect(siblingsOf(0)?.slice().sort()).toEqual(['b.js', 'b.js.map']); + expect(siblingsOf(1)).toEqual([]); + }); + + it(`${kind}: a new build forgets outputs that never wrote (buildStart)`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + await h.generateBundle.handler({ file: '/out/dead.js' }, bundleOf('dead')); // never written + h.buildStart?.(); + const live = { file: '/out/live.js' }; + await h.generateBundle.handler(live, bundleOf('live')); + await h.writeBundle(live, bundleOf('live')); + expect(siblingsOf(0)).toEqual([]); + }); + } +}); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 927a1f380..ddddbdc71 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -572,11 +572,18 @@ export const bugseeUnpluginFactory: UnpluginFactory(); + // Outputs written into one directory announce their names at generateBundle (before ANY of them writes), so + // the first to write already knows its siblings and leaves their maps to them. Per plugin instance; a new + // build forgets outputs that never wrote. + const announced = new Map>(); const stampBundle = async (output: OutputLike, bundle: RollupBundleLike): Promise => { const outDir = resolveOutputDir(output); if (outDir === undefined || !resolved.enabled) { return; } + const group = announced.get(outDir) ?? new Map(); + group.set(output, Object.keys(bundle)); + announced.set(outDir, group); stampedOutputs.set(output, { preStamped: false }); const unstampable = rollupUnstampableMaps(bundle); if (unstampable.length > 0) { @@ -607,11 +614,20 @@ export const bugseeUnpluginFactory: UnpluginFactory other !== output) + .flatMap(([, names]) => names); + group?.delete(output); + if (group?.size === 0) { + announced.delete(outDir); + } if (stamp?.abandoned === true) { return; } await runPluginUpload(forOutput(outDir), outDir, { bundler, + ...(bundle !== undefined ? { siblingOwnFiles: siblings } : {}), ...(bundle !== undefined ? { ownFiles: Object.keys(bundle) } : {}), ...(stamp?.preStamped === true ? { @@ -681,6 +697,9 @@ export const bugseeUnpluginFactory: UnpluginFactory uploadForOutput(output, viteBuild, bundle), @@ -720,6 +739,7 @@ export const bugseeUnpluginFactory: UnpluginFactory uploadForOutput(output, {}, bundle), diff --git a/packages/bundler-plugin-core/src/resolve.test.ts b/packages/bundler-plugin-core/src/resolve.test.ts index 01ca01112..06b6eec33 100644 --- a/packages/bundler-plugin-core/src/resolve.test.ts +++ b/packages/bundler-plugin-core/src/resolve.test.ts @@ -276,6 +276,45 @@ describe('one pipeline per output directory', () => { ]); }); + it("every output of one directory is told the OTHER outputs' names (so none uploads or reports another's maps)", async () => { + const seen: Array<{ ownFiles?: readonly string[]; siblingOwnFiles?: readonly string[] }> = []; + const upload = async (opts: { + outDir: string; + ownFiles?: readonly string[]; + siblingOwnFiles?: readonly string[]; + }) => { + seen.push({ ownFiles: opts.ownFiles, siblingOwnFiles: opts.siblingOwnFiles }); + return { injected: true, uploaded: true, deletedMaps: [] }; + }; + const calls = ['a', 'b', 'c'].map((n) => + runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: [`${n}.js`, `${n}.js.map`], + ...noVcs, + }), + ); + await Promise.all(calls); + expect(seen).toHaveLength(3); // sequential: one pipeline per output, never concurrent + expect(seen.map((x) => x.ownFiles?.[0])).toEqual(['a.js', 'b.js', 'c.js']); + expect(seen[0]?.siblingOwnFiles?.slice().sort()).toEqual([ + 'b.js', + 'b.js.map', + 'c.js', + 'c.js.map', + ]); + // a already finished (and handled its own maps), so only c is still pending when b runs + expect(seen[1]?.siblingOwnFiles?.slice().sort()).toEqual(['c.js', 'c.js.map']); + expect(seen[2]?.siblingOwnFiles).toEqual([]); + // once everything settled, a later run sees no leftover siblings + const later = await runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['z.js'], + ...noVcs, + }); + expect(later).toBeDefined(); + expect(seen[3]?.siblingOwnFiles).toEqual([]); + }); + it('a failed in-flight run does not stop the waiting second output from running', async () => { const calls: string[] = []; let first = true; diff --git a/packages/bundler-plugin-core/src/resolve.ts b/packages/bundler-plugin-core/src/resolve.ts index 389ed7575..4230c8730 100644 --- a/packages/bundler-plugin-core/src/resolve.ts +++ b/packages/bundler-plugin-core/src/resolve.ts @@ -265,8 +265,40 @@ export function resolvePluginOptions( /** What a plugin run reports: the source-map upload, plus the build registration when it ran. */ export type PluginRunResult = UploadSourcemapsResult & { build?: RegisterJsBuildResult }; -/** Run the upload for a resolved config against a build output dir — a no-op when the plugin is disabled. */ +/** The ownFiles of every output of a directory that is pending or running (see {@link runPluginUpload}). */ +const ownersByDir = new Map>(); + +/** + * Run the upload for a resolved config against a build output dir — a no-op when the plugin is disabled. + * + * Every output of one directory that knows its own names (`ownFiles`) registers them while it is pending or + * running, so each run can leave the OTHERS' maps to their own output (N outputs: N uploads, not N times all). + */ export async function runPluginUpload( + resolved: ResolvedPluginOptions, + outDir: string, + deps: Parameters[2] = {}, +): Promise { + const mine = deps.files === undefined ? deps.ownFiles : undefined; + if (mine !== undefined) { + const group = ownersByDir.get(outDir) ?? new Set(); + group.add(mine); + ownersByDir.set(outDir, group); + } + try { + return await runPluginUploadInner(resolved, outDir, deps, mine); + } finally { + if (mine !== undefined) { + const group = ownersByDir.get(outDir); + group?.delete(mine); + if (group?.size === 0) { + ownersByDir.delete(outDir); + } + } + } +} + +async function runPluginUploadInner( resolved: ResolvedPluginOptions, outDir: string, deps: { @@ -283,6 +315,8 @@ export async function runPluginUpload( stampedMaps?: Readonly>; /** The names this build emitted (relative to the output directory): what it may delete. */ ownFiles?: readonly string[]; + /** Names other outputs of the same directory announced (their maps are theirs to upload and delete). */ + siblingOwnFiles?: readonly string[]; /** * The build's own outputs (esbuild's metafile). The run then touches exactly these files, never joins another * run of the same directory, and registers from these bundles only. @@ -293,6 +327,7 @@ export async function runPluginUpload( stylesheetMaps?: readonly string[]; }; } = {}, + mine?: readonly string[], ): Promise { if (!resolved.enabled) { return undefined; @@ -339,7 +374,15 @@ export async function runPluginUpload( ...(deps.preStamped === true ? { preStamped: true } : {}), ...(deps.stampedBundles !== undefined ? { stampedBundles: deps.stampedBundles } : {}), ...(deps.stampedMaps !== undefined ? { stampedMaps: deps.stampedMaps } : {}), - ...(deps.ownFiles !== undefined ? { ownFiles: deps.ownFiles } : {}), + ...(deps.ownFiles !== undefined + ? { + ownFiles: deps.ownFiles, + siblingOwnFiles: [ + ...(deps.siblingOwnFiles ?? []), + ...[...(ownersByDir.get(outDir) ?? [])].filter((names) => names !== mine).flat(), + ], + } + : {}), ...(deps.files !== undefined ? { files: deps.files } : {}), }); // AFTER the upload, because the build id is derived from the debug-ids its inject step stamps diff --git a/packages/bundler-plugin-core/src/stamp-assets.test.ts b/packages/bundler-plugin-core/src/stamp-assets.test.ts index c6aa80ada..90e4d0a5a 100644 --- a/packages/bundler-plugin-core/src/stamp-assets.test.ts +++ b/packages/bundler-plugin-core/src/stamp-assets.test.ts @@ -737,3 +737,15 @@ describe('stampAssets — two bundles that claim the same map', () => { expect(run).not.toHaveBeenCalled(); }); }); + +describe("stampAssets — a map that is another bundle's own sibling is claimed too", () => { + it("refuses when b.js names a.js.map (a.js's own sibling map) as its map", async () => { + const run = vi.fn(async () => ({ code: 0, stdout: '', stderr: '' })); + const store = { + ...memoryStore({ 'a.js': 'a\n', 'a.js.map': '{}', 'b.js': 'b\n' }), + mapOf: (name: string) => (name === 'a.js' ? 'a.js.map' : 'a.js.map'), + }; + await expect(stampAssets(store, { run })).rejects.toThrow(/a\.js\.map.*claimed/); + expect(run).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/bundler-plugin-core/src/stamp-assets.ts b/packages/bundler-plugin-core/src/stamp-assets.ts index 236331087..41a09588e 100644 --- a/packages/bundler-plugin-core/src/stamp-assets.ts +++ b/packages/bundler-plugin-core/src/stamp-assets.ts @@ -101,9 +101,21 @@ export async function stampAssets( // A map that is not the bundle's sibling is staged AS the sibling (and written back at its real name). const stageName = new Map(); const stagedSet = new Set(staged); + // Every map a bundle names (its own sibling included) belongs to ONE bundle: two claimants would be + // verified against the same file and one of them accepted with no map of its own. + const claimed = new Map(); for (const bundle of staged.filter((name) => BUNDLE.test(name))) { const map = store.mapOf?.(bundle); const sibling = `${bundle}.map`; + if (map !== undefined) { + const other = claimed.get(map); + if (other !== undefined) { + throw new Error( + `the map ${map} is claimed by more than one bundle (${other} and ${bundle}), so it cannot be stamped`, + ); + } + claimed.set(map, bundle); + } if (map === undefined || map === sibling) { continue; } @@ -120,13 +132,6 @@ export async function stampAssets( }, ]); } - if (stageName.has(map)) { - // Two bundles claim ONE map: it can be staged beside only one, and the other would be accepted as - // "stamped" with no map to check. Ambiguous, so the stamp is refused. - throw new Error( - `the map ${map} is claimed by more than one bundle (${bundle} and another), so it cannot be stamped`, - ); - } if (stagedSet.has(sibling)) { throw new Error( `the map ${map} of ${bundle} cannot be staged as ${sibling}: another asset already has that name`, diff --git a/packages/bundler-plugin-core/src/stamp-files.test.ts b/packages/bundler-plugin-core/src/stamp-files.test.ts index 632e6a37d..f0c087416 100644 --- a/packages/bundler-plugin-core/src/stamp-files.test.ts +++ b/packages/bundler-plugin-core/src/stamp-files.test.ts @@ -780,3 +780,20 @@ describe('sameAsSnapshot / restorePaths', () => { await snap.dispose(); }); }); + +describe("the rollback partner is the ORIGINAL pointer's map even when the changed pointer names ANOTHER snapshotted map", () => { + it('restores maps/m.map (original partner), not x.map (where the bad stamp pointed)', async () => { + await mkdir(join(dir, 'maps')); + const original = 'm();\n//# sourceMappingURL=maps/m.map\n'; + await writeFile(join(dir, 'm.js'), original); + await writeFile(join(dir, 'maps', 'm.map'), plainMap); + await writeFile(join(dir, 'x.map'), plainMap); // an unrelated, snapshotted map + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'm.js'), `m();\n//# sourceMappingURL=x.map\n{{${STAMP}`); + await writeFile(join(dir, 'maps', 'm.map'), stampedMap); // the real map got stamped + const { restored } = await verifyAndRestore(snap); + expect(restored).toContain(join(dir, 'maps', 'm.map')); + expect(await readFile(join(dir, 'maps', 'm.map'), 'utf8')).toBe(plainMap); + await snap.dispose(); + }); +}); From c4bf2ffd0decbf9b334858fdbfd7dce9d8830d59 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 18:32:15 +0500 Subject: [PATCH 27/39] fix(bundler-plugin-core): a generate()-only output cannot hide another output's maps bundle.generate() runs generateBundle but never writes, so its announcement stayed registered and, carrying the same names, made the written output treat its own maps as a sibling's (nothing uploaded, nothing deleted). A name an output emitted is never a sibling's (filtered where the siblings are collected, and own wins in the upload set). Tests: unit (both hooks), orchestrate, and a real Rollup generate() then write() build. Co-Authored-By: Claude Sonnet 5.5 --- .../src/orchestrate.stamp.test.ts | 20 +++++++++++++++++++ .../bundler-plugin-core/src/orchestrate.ts | 4 +++- .../src/plugin.in-build.real-build.test.ts | 20 +++++++++++++++++++ .../src/plugin.stamp.test.ts | 10 ++++++++++ packages/bundler-plugin-core/src/plugin.ts | 6 +++++- 5 files changed, 58 insertions(+), 2 deletions(-) diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index 2a8572dd2..796bfffc6 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -1850,6 +1850,26 @@ describe('round-17 hardening: failed restore after a rejected inject, sibling ou ).rejects.toThrow(/cli died[\s\S]*COULD NOT restore/); }); + it("a name that is BOTH this output's own and listed as a sibling's is this output's (own wins)", async () => { + await writeFile(join(dir, 'a.js.map'), keyed); + const calls: string[][] = []; + await uploadSourcemaps({ + ...base, + outDir: dir, + run: async (args) => { + calls.push(args); + return ok(args); + }, + preStamped: true, + verifySri: async () => [], + ownFiles: ['a.js.map'], + siblingOwnFiles: ['a.js.map'], + onNotice: () => undefined, + }); + expect(calls.find((c) => c[0] === 'debug-files')).toContain(join(dir, 'a.js.map')); + expect(await readdir(dir)).not.toContain('a.js.map'); // uploaded and deleted + }); + it('a map owned by a SIBLING output is neither uploaded by this one nor noticed as foreign', async () => { await writeFile(join(dir, 'a.js.map'), keyed); await writeFile(join(dir, 'b.js.map'), keyed); // the sibling output's diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index dad107aaf..a633606e8 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -639,8 +639,10 @@ export async function uploadSourcemaps( // walk are never uploaded but embed the source, so they are deleted with the uploaded ones. // Sorted here, so the CLI batches and the notice are stable whatever order a walk returns. const siblings = ownedBy(outDir, options.siblingOwnFiles ?? []); + const mineByName = ownedBy(outDir, options.ownFiles ?? []); const everything = [...(await (options.listUploadMaps ?? listOutputMaps)(outDir))] - .filter((map) => !siblings(map)) + // (own wins: a name in both lists is this output's) + .filter((map) => mineByName(map) || !siblings(map)) .sort(); const { deletable, kept } = await (options.partitionMaps ?? partitionByKeyed)( everything.filter(isUploadableMap), diff --git a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts index 02e433e60..9d91e6868 100644 --- a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts @@ -1226,3 +1226,23 @@ describeReal('several Rollup outputs written concurrently into one directory', ( expect(requests.length - before).toBeGreaterThanOrEqual(1); }); }); + +describeReal('Rollup generate() before write() into the same directory', () => { + it('the written output still uploads and deletes its own maps (a generated-only output is not a sibling)', async () => { + const app = makeApp('rollup-generate-then-write', { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ ...pluginOptions(), onError: (e: unknown) => errors.push(e) }), + ], + }); + await bundle.generate({ dir: app.out, sourcemap: true }); // e.g. to measure size: never written + await bundle.write({ dir: app.out, sourcemap: true }); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expect(requests.length).toBeGreaterThan(before); + expect((readdirSync(app.out) as string[]).filter((f) => f.endsWith('.map'))).toEqual([]); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.stamp.test.ts b/packages/bundler-plugin-core/src/plugin.stamp.test.ts index 4bdc601dc..a8b747e64 100644 --- a/packages/bundler-plugin-core/src/plugin.stamp.test.ts +++ b/packages/bundler-plugin-core/src/plugin.stamp.test.ts @@ -990,6 +990,16 @@ describe('outputs announce their names at generateBundle, so the first write alr expect(siblingsOf(1)).toEqual([]); }); + it(`${kind}: an output that only GENERATED (bundle.generate never writes) cannot hide this one's own maps`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + await h.generateBundle.handler({ dir: '/out' }, bundleOf('a')); // generate(): same names, never written + const written = { dir: '/out' }; + await h.generateBundle.handler(written, bundleOf('a')); + await h.writeBundle(written, bundleOf('a')); + expect(siblingsOf(0)).toEqual([]); // a name this output emitted is never a "sibling's" + }); + it(`${kind}: a new build forgets outputs that never wrote (buildStart)`, async () => { uploadSpy.mockClear(); const h = hooksOf2(kind); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index ddddbdc71..cd9e5342c 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -615,9 +615,13 @@ export const bugseeUnpluginFactory: UnpluginFactory other !== output) - .flatMap(([, names]) => names); + .flatMap(([, names]) => names) + .filter((name) => !mine.has(name)); group?.delete(output); if (group?.size === 0) { announced.delete(outDir); From 97da0be3caf4d0d9637a8bf66f64422e83c34d74 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 19:05:25 +0500 Subject: [PATCH 28/39] fix(bundler-plugin-core): coordinate outputs by physical directory; siblings on the post-emit path; keep BugseeCliError - announced/ownersByDir/runsByDir keyed by dirKey (resolve + realpath of the deepest existing ancestor, dangling symlinks followed): dist, dist/, ./dist, absolute and symlink spellings are one directory. - post-emit path with sibling outputs uploads an explicit set (not the directory) and leaves their maps alone. - failOnError: an output with no maps while a sibling has maps has nothing to do and does not fail. - a rejected inject keeps its original error object (BugseeCliError stays one); restore failures are appended. - documented in source-maps.md section 7.1. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- docs/design/source-maps.md | 17 ++++ .../bundler-plugin-core/src/dir-key.test.ts | 68 +++++++++++++ .../src/orchestrate.restore-throws.test.ts | 74 ++++++++++++++ .../src/orchestrate.stamp.test.ts | 96 +++++++++++++++++++ .../bundler-plugin-core/src/orchestrate.ts | 29 ++++-- .../src/plugin.in-build.real-build.test.ts | 78 ++++++++++++++- packages/bundler-plugin-core/src/plugin.ts | 11 ++- .../bundler-plugin-core/src/resolve.test.ts | 22 +++++ packages/bundler-plugin-core/src/resolve.ts | 56 +++++++++-- 9 files changed, 429 insertions(+), 22 deletions(-) create mode 100644 packages/bundler-plugin-core/src/dir-key.test.ts create mode 100644 packages/bundler-plugin-core/src/orchestrate.restore-throws.test.ts diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index e8a3f128f..f0ea30db9 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -324,6 +324,23 @@ id. (The hand-rolled SRI step pins only the entry chunks in `index.html`, never hold the unverified rewrite), with or without `failOnError`. Two bundles claiming one map, counting a bundle's own sibling as a claim, refuse the in-build stamp. +### Several outputs into one directory + +Outputs written concurrently into one directory (several `bundle.write()` calls, or Vite environments) coordinate by +the PHYSICAL directory: `dist`, `dist/`, `./dist`, an absolute path and a symlink to it are one key (the real path +of the deepest existing ancestor plus the not-yet-created rest). Each output announces its names at +`generateBundle`; a run leaves the maps of every still-pending sibling to that sibling, on every path: the explicit +pre-stamped upload, and the post-emit path (which, when siblings exist, also uploads an explicit file set instead of +the directory, so a sibling's maps are neither uploaded, nor reported as "not produced by this build", nor deleted). +**`failOnError` and an output with no maps:** an output whose own map set is empty while at least one announced +sibling of the same directory has maps has nothing to do and does NOT fail ("no source maps with a debug-ID were +found" is for a lone output, or when no sibling has maps either). An output whose own map exists but is unkeyed +still fails. **Known limit:** an output that announced itself but never reaches `writeBundle` (a failed write, a +`generate()`-only output) keeps its announcement until the next `buildStart`; maps another output finds that +carry its names are left on disk, not reported. A name this output itself emitted is never treated as a sibling's. +A rejected inject keeps its ORIGINAL error object (a `BugseeCliError` stays one); a failed restore is appended to its +message. + ### Maps that are not the bundle sibling `sourcemapFileNames` can put a map anywhere in the output (`maps/[name].js.map`, bundles in `js/`). `inject` diff --git a/packages/bundler-plugin-core/src/dir-key.test.ts b/packages/bundler-plugin-core/src/dir-key.test.ts new file mode 100644 index 000000000..aac6eb63a --- /dev/null +++ b/packages/bundler-plugin-core/src/dir-key.test.ts @@ -0,0 +1,68 @@ +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, relative } from 'node:path'; +import { afterAll, describe, expect, it } from 'vitest'; +import { dirKey } from './resolve'; + +const root = realpathSync(mkdtempSync(join(tmpdir(), 'bugsee-dirkey-'))); +afterAll(() => rmSync(root, { recursive: true, force: true })); + +describe('dirKey', () => { + it('is one key for every spelling of an existing directory', () => { + const dist = join(root, 'dist'); + mkdirSync(dist); + const link = join(root, 'link'); + symlinkSync(dist, link); + const spellings = [ + dist, + `${dist}/`, + link, + join(dist, '..', 'dist'), + relative(process.cwd(), dist), + ]; + for (const s of spellings) { + expect(dirKey(s)).toBe(dist); + } + }); + + it('keys a directory that does not exist yet the same as once it does (real path of the existing ancestor)', () => { + const link = join(root, 'plink'); + const real = join(root, 'preal'); + mkdirSync(real); + symlinkSync(real, link); + const before = dirKey(join(link, 'out', 'deep')); + expect(before).toBe(join(real, 'out', 'deep')); + mkdirSync(join(real, 'out', 'deep'), { recursive: true }); + expect(dirKey(join(link, 'out', 'deep'))).toBe(before); + }); + + it('follows a symlink whose target does not exist yet, to the same key as once it does', () => { + const real = join(root, 'later'); + const link = join(root, 'dangling'); + symlinkSync(real, link); + const chain = join(root, 'chain'); + symlinkSync(link, chain); // a link to a dangling link + expect(dirKey(link)).toBe(real); + expect(dirKey(join(chain, 'sub'))).toBe(join(real, 'sub')); + mkdirSync(real); + expect(dirKey(link)).toBe(real); + }); + + it('resolves a RELATIVE dangling symlink target against the link directory', () => { + mkdirSync(join(root, 'holder')); + symlinkSync('../rel-later', join(root, 'holder', 'rel')); + expect(dirKey(join(root, 'holder', 'rel'))).toBe(join(root, 'rel-later')); + }); + + it('does not loop forever on a symlink cycle', () => { + const a = join(root, 'cyc-a'); + const b = join(root, 'cyc-b'); + symlinkSync(b, a); + symlinkSync(a, b); + expect(typeof dirKey(a)).toBe('string'); + }); + + it('falls back to the resolved path when nothing on the way can be resolved', () => { + expect(dirKey('/')).toBe(realpathSync('/')); + }); +}); diff --git a/packages/bundler-plugin-core/src/orchestrate.restore-throws.test.ts b/packages/bundler-plugin-core/src/orchestrate.restore-throws.test.ts new file mode 100644 index 000000000..5b8ec8ed6 --- /dev/null +++ b/packages/bundler-plugin-core/src/orchestrate.restore-throws.test.ts @@ -0,0 +1,74 @@ +// A rejected inject whose restore step ITSELF throws (or reports failures): the inject failure stays the +// reported error (same object, same class), with the restore problem appended, never swapped for a plain Error. +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { uploadSourcemaps } from './orchestrate'; +import { BugseeCliError } from './run-cli'; + +const { restore } = vi.hoisted(() => ({ + restore: { mode: 'throw' as 'throw' | 'failed' }, +})); +vi.mock('./stamp-files', async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + verifyAndRestore: async () => { + if (restore.mode === 'throw') { + throw new Error('disk gone'); + } + return { issues: [], restored: [], failed: [{ path: 'a.js', error: 'EPERM' }] }; + }, + }; +}); + +describe('a rejected inject followed by a restore problem', () => { + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-r18-')); + await writeFile(join(dir, 'a.js'), 'a();\n//# sourceMappingURL=a.js.map\n'); + await writeFile(join(dir, 'a.js.map'), '{"version":3}'); + }); + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + const go = (original: unknown) => + uploadSourcemaps({ + outDir: dir, + appToken: 't', + appVersion: '1', + appBuild: '1', + run: (async () => { + throw original; + }) as never, + findSri: async () => [], + failOnError: true, + ownFiles: ['a.js', 'a.js.map'], + }); + + it.each([ + 'throw', + 'failed', + ] as const)('keeps the original BugseeCliError object when the restore %s', async (mode) => { + restore.mode = mode; + const original = new BugseeCliError('inject died', 3, 'stderr'); + const caught = await go(original).catch((e: unknown) => e); + expect(caught).toBe(original); + expect(caught).toBeInstanceOf(BugseeCliError); + expect((caught as BugseeCliError).code).toBe(3); + expect((caught as Error).message).toContain('inject died'); + expect((caught as Error).message).toContain( + mode === 'throw' ? 'restoring the originals also failed: disk gone' : 'EPERM', + ); + }); + + it('wraps a non-Error rejection, keeping it as the cause', async () => { + restore.mode = 'throw'; + const caught = await go('plain string').catch((e: unknown) => e); + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).cause).toBe('plain string'); + expect((caught as Error).message).toContain('plain string'); + expect((caught as Error).message).toContain('disk gone'); + }); +}); diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index 796bfffc6..85a18109c 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -1898,3 +1898,99 @@ describe('round-17 hardening: failed restore after a rejected inject, sibling ou expect(await readdir(dir)).toContain('b.js.map'); // untouched, left for its own output }); }); + +describe('round-18: sibling outputs on the post-emit path, empty own set under failOnError', () => { + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-r18b-')); + }); + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + const keyed = JSON.stringify({ debugId: ID }); + const ok = async (_args: string[]): Promise => ({ code: 0, stdout: '', stderr: '' }); + + it("without an in-build stamp, a pending sibling's maps are neither uploaded, noticed nor deleted", async () => { + await writeFile(join(dir, 'a.js'), 'a();\n'); + await writeFile(join(dir, 'a.js.map'), keyed); + await writeFile(join(dir, 'b.js.map'), keyed); // the sibling's, not yet through its writeBundle + const calls: string[][] = []; + const notices: string[] = []; + await uploadSourcemaps({ + ...base, + outDir: dir, + run: async (args) => { + calls.push(args); + return ok(args); + }, + findSri: async () => [], + ownFiles: ['a.js', 'a.js.map'], + siblingOwnFiles: ['b.js', 'b.js.map'], + onNotice: (m) => notices.push(m), + }); + const upload = calls.find((c) => c[0] === 'debug-files') as string[]; + expect(upload).toContain(join(dir, 'a.js.map')); + expect(upload).not.toContain(dir); // never the directory + expect(upload).not.toContain(join(dir, 'b.js.map')); + expect(notices.join('\n')).not.toContain('b.js.map'); + expect(await readdir(dir)).toContain('b.js.map'); + expect(await readdir(dir)).not.toContain('a.js.map'); + }); + + it('an output with no maps of its own does not fail while a sibling has maps', async () => { + await writeFile(join(dir, 'u.js'), 'u();\n'); + await writeFile(join(dir, 'm.js.map'), keyed); + const result = await uploadSourcemaps({ + ...base, + outDir: dir, + run: ok, + findSri: async () => [], + failOnError: true, + preStamped: true, + verifySri: async () => [], + ownFiles: ['u.js'], + siblingOwnFiles: ['m.js', 'm.js.map'], + onNotice: () => undefined, + }); + expect(result.uploaded).toBe(false); + expect(await readdir(dir)).toContain('m.js.map'); + }); + + it('a lone unmapped output, or one whose siblings have no maps either, still fails', async () => { + await writeFile(join(dir, 'u.js'), 'u();\n'); + for (const siblingOwnFiles of [undefined, ['v.js']]) { + await expect( + uploadSourcemaps({ + ...base, + outDir: dir, + run: ok, + findSri: async () => [], + failOnError: true, + preStamped: true, + verifySri: async () => [], + ownFiles: ['u.js'], + ...(siblingOwnFiles !== undefined ? { siblingOwnFiles } : {}), + }), + ).rejects.toThrow(/no source maps with a debug-ID were found/); + } + }); + + it('an output whose own map has no debug-ID still fails even if a sibling has maps', async () => { + await writeFile(join(dir, 'u.js'), 'u();\n'); + await writeFile(join(dir, 'u.js.map'), '{"version":3}'); // own, but no debugId + await expect( + uploadSourcemaps({ + ...base, + outDir: dir, + run: ok, + findSri: async () => [], + failOnError: true, + preStamped: true, + verifySri: async () => [], + ownFiles: ['u.js', 'u.js.map'], + siblingOwnFiles: ['m.js.map'], + onNotice: () => undefined, + }), + ).rejects.toThrow(/no source maps with a debug-ID were found/); + }); +}); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index a633606e8..ba175dca3 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -542,20 +542,23 @@ export async function uploadSourcemaps( // A rejected inject may already have rewritten files (an earlier batch, or a partial write): verify and // restore them BEFORE the failure propagates, so no unverified stamp stays on disk. if (original !== undefined) { + let note: string | undefined; try { const { issues, restored, failed } = await verifyAndRestore(original); if (failed.length > 0) { // Files still carry the unverified rewrite: that must not go unmentioned. - throw new Error( - `${error instanceof Error ? error.message : String(error)}; ${verifyFailure(issues, restored, failed).message}`, - { cause: error }, - ); + note = verifyFailure(issues, restored, failed).message; } } catch (restoreError) { - if (restoreError instanceof Error && restoreError.cause === error) { - throw restoreError; + note = `restoring the originals also failed: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`; + } + if (note !== undefined) { + // The ORIGINAL error object is kept (a BugseeCliError stays one); the restore problem is appended. + if (error instanceof Error) { + error.message = `${error.message}; ${note}`; + throw error; } - // the inject failure is the one to report + throw new Error(`${String(error)}; ${note}`, { cause: error }); } } throw error; @@ -602,7 +605,12 @@ export async function uploadSourcemaps( // that set: no second walk to disagree with the first about which maps exist. // (Also after a restore: a restored map is unkeyed again, and the CLI rejects a DIRECTORY that holds one.) const explicitUpload = - files === undefined && (options.preStamped === true || restoredAny) && !dryRun; + files === undefined && + (options.preStamped === true || + restoredAny || + // a sibling output's maps share the directory: upload only the names that are ours, never the directory + (options.siblingOwnFiles?.length ?? 0) > 0) && + !dryRun; let uploadedMaps: string[] = []; let unuploadableMaps: string[] = []; let snapshot: string[] | undefined; @@ -659,8 +667,11 @@ export async function uploadSourcemaps( `${noticed.length} source map(s) in ${outDir} have no readable debug-ID, so they were not uploaded (left on disk untouched): ${noticed.join(', ')}`, ); } + // An output with no maps of its own while a sibling output of the directory has some has nothing to + // do: that is not "this build produced no maps". A lone unmapped output still fails. + const siblingHasMaps = (options.siblingOwnFiles ?? []).some((name) => name.endsWith('.map')); if (deletable.length === 0) { - if (options.failOnError === true) { + if (options.failOnError === true && !(everything.length === 0 && siblingHasMaps)) { throw new Error( `no source maps with a debug-ID were found in ${outDir}, so nothing was uploaded`, ); diff --git a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts index 9d91e6868..518a9d631 100644 --- a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts @@ -20,11 +20,12 @@ import { readFileSync, realpathSync, rmSync, + symlinkSync, writeFileSync, } from 'node:fs'; import { createServer, type Server } from 'node:http'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { join, relative } from 'node:path'; import { rspack } from '@rspack/core'; import { rollup } from 'rollup'; import { type Plugin as VitePlugin, build as viteBuild } from 'vite'; @@ -1246,3 +1247,78 @@ describeReal('Rollup generate() before write() into the same directory', () => { expect((readdirSync(app.out) as string[]).filter((f) => f.endsWith('.map'))).toEqual([]); }); }); + +describeReal('one directory spelled several ways', () => { + it('outputs into `dist`, `dist/`, a symlink to it and a relative spelling coordinate as ONE directory', async () => { + const app = makeApp('rollup-spellings', { lazy: false }); + const link = `${app.out}-link`; + symlinkSync(app.out, link); + const spellings = [app.out, `${app.out}/`, link, relative(process.cwd(), app.out)]; + const before = requests.length; + const notices: string[] = []; + const errors: unknown[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + onNotice: (m: string) => notices.push(m), + onError: (e: unknown) => errors.push(e), + }), + ], + }); + await Promise.all( + spellings.map((dir, i) => + bundle.write({ + dir, + entryFileNames: `s${i}.js`, + format: 'iife', + name: `s${i}`, + sourcemap: true, + }), + ), + ); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expect(notices.filter((m) => m.includes('not produced by this build'))).toEqual([]); + expect((readdirSync(app.out) as string[]).filter((f) => f.endsWith('.map'))).toEqual([]); + expect(requests.length - before).toBeLessThanOrEqual(spellings.length); + expect(requests.length - before).toBeGreaterThanOrEqual(1); + }); +}); + +describeReal('a mapped and an unmapped output into one directory under failOnError', () => { + it('the unmapped output has nothing to do and does not fail the build', async () => { + const app = makeApp('rollup-mapped-unmapped', { lazy: false }); + const errors: unknown[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + failOnError: true, + onError: (e: unknown) => errors.push(e), + }), + ], + }); + await Promise.all([ + bundle.write({ + dir: app.out, + entryFileNames: 'm.js', + format: 'iife', + name: 'm', + sourcemap: true, + }), + bundle.write({ + dir: app.out, + entryFileNames: 'u.js', + format: 'iife', + name: 'u', + sourcemap: false, + }), + ]); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expect((readdirSync(app.out) as string[]).filter((f) => f.endsWith('.map'))).toEqual([]); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index cd9e5342c..0061cd126 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -16,6 +16,7 @@ import { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; import type { BundlerBuildContext } from './register-build'; import { type BugseePluginOptions, + dirKey, notify, type ResolvedIdentity, resolveIdentity, @@ -581,9 +582,10 @@ export const bugseeUnpluginFactory: UnpluginFactory(); + const key = dirKey(outDir); + const group = announced.get(key) ?? new Map(); group.set(output, Object.keys(bundle)); - announced.set(outDir, group); + announced.set(key, group); stampedOutputs.set(output, { preStamped: false }); const unstampable = rollupUnstampableMaps(bundle); if (unstampable.length > 0) { @@ -614,7 +616,8 @@ export const bugseeUnpluginFactory: UnpluginFactory !mine.has(name)); group?.delete(output); if (group?.size === 0) { - announced.delete(outDir); + announced.delete(key); } if (stamp?.abandoned === true) { return; diff --git a/packages/bundler-plugin-core/src/resolve.test.ts b/packages/bundler-plugin-core/src/resolve.test.ts index 06b6eec33..545f9a3a8 100644 --- a/packages/bundler-plugin-core/src/resolve.test.ts +++ b/packages/bundler-plugin-core/src/resolve.test.ts @@ -315,6 +315,28 @@ describe('one pipeline per output directory', () => { expect(seen[3]?.siblingOwnFiles).toEqual([]); }); + it('explicit siblings (announced at generateBundle) and pending ones are BOTH passed; another spelling of the directory is the same directory', async () => { + const seen: Array = []; + const upload = async (opts: { siblingOwnFiles?: readonly string[] }) => { + seen.push(opts.siblingOwnFiles); + return { injected: true, uploaded: true, deletedMaps: [] }; + }; + const a = runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['a.js'], + siblingOwnFiles: ['announced.js.map'], + ...noVcs, + }); + const b = runPluginUpload(resolved, './dist/', { + uploadSourcemaps: upload as never, + ownFiles: ['b.js'], + ...noVcs, + }); + await Promise.all([a, b]); + expect(seen[0]?.slice().sort()).toEqual(['announced.js.map', 'b.js']); + expect(seen[1]).toEqual([]); + }); + it('a failed in-flight run does not stop the waiting second output from running', async () => { const calls: string[] = []; let first = true; diff --git a/packages/bundler-plugin-core/src/resolve.ts b/packages/bundler-plugin-core/src/resolve.ts index 4230c8730..19f3a29f3 100644 --- a/packages/bundler-plugin-core/src/resolve.ts +++ b/packages/bundler-plugin-core/src/resolve.ts @@ -2,6 +2,8 @@ // with environment variables, applies defaults, and decides whether the plugin is active (a token is // required; a build without one is a no-op rather than an error). Pure + injectable for testing. +import { readlinkSync, realpathSync } from 'node:fs'; +import { basename, dirname, join, resolve as resolvePath } from 'node:path'; import { type AppIdentityDeps, appIdentityDefines, @@ -265,6 +267,42 @@ export function resolvePluginOptions( /** What a plugin run reports: the source-map upload, plus the build registration when it ran. */ export type PluginRunResult = UploadSourcemapsResult & { build?: RegisterJsBuildResult }; +/** + * One key per physical directory, whatever the spelling (`dist`, `dist/`, `./dist`, an absolute path, a symlink): + * the real path of the deepest ancestor that exists, plus the not-yet-created rest (a directory that does not + * exist yet when the first output announces itself must key the same once it does). + */ +export function dirKey(dir: string, depth = 0): string { + let head = resolvePath(dir); + const rest: string[] = []; + for (;;) { + try { + return join(realpathSync(head), ...rest); + } catch { + // A symlink whose target does not exist YET (the build will create it) still names that target. + const target = depth < 40 ? readLinkTarget(head) : undefined; + if (target !== undefined) { + return join(dirKey(target, depth + 1), ...rest); + } + const parent = dirname(head); + /* v8 ignore next 3 -- only when even the filesystem root cannot be resolved */ + if (parent === head) { + return join(head, ...rest); + } + rest.unshift(basename(head)); + head = parent; + } + } +} + +function readLinkTarget(path: string): string | undefined { + try { + return resolvePath(dirname(path), readlinkSync(path)); + } catch { + return undefined; // not a symlink (or not there) + } +} + /** The ownFiles of every output of a directory that is pending or running (see {@link runPluginUpload}). */ const ownersByDir = new Map>(); @@ -280,19 +318,20 @@ export async function runPluginUpload( deps: Parameters[2] = {}, ): Promise { const mine = deps.files === undefined ? deps.ownFiles : undefined; + const key = dirKey(outDir); if (mine !== undefined) { - const group = ownersByDir.get(outDir) ?? new Set(); + const group = ownersByDir.get(key) ?? new Set(); group.add(mine); - ownersByDir.set(outDir, group); + ownersByDir.set(key, group); } try { return await runPluginUploadInner(resolved, outDir, deps, mine); } finally { if (mine !== undefined) { - const group = ownersByDir.get(outDir); + const group = ownersByDir.get(key); group?.delete(mine); if (group?.size === 0) { - ownersByDir.delete(outDir); + ownersByDir.delete(key); } } } @@ -337,13 +376,14 @@ async function runPluginUploadInner( // both `dist` — used to start two concurrent pipelines over one tree, with one deleting maps // while the other was still reading them. A concurrent caller JOINS the in-flight run and // gets its result; the entry is released on settle, so `vite build --watch` still uploads every rebuild. + const dirKey0 = dirKey(outDir); // once: a directory created meanwhile must not change the key // A run over a build's OWN files (`deps.files`) neither joins nor is joined: it touches nothing another run // of the directory touches, so there is nothing to coordinate. // A caller that knows which files ITS output emitted (`ownFiles`) does not join: the in-flight run was // started with another output's names, and would treat this one's maps as "not produced by this build". // It WAITS for that run (no concurrent pipelines over one tree) and then runs itself. for (;;) { - const inFlight = deps.files === undefined ? runsByDir.get(outDir) : undefined; + const inFlight = deps.files === undefined ? runsByDir.get(dirKey0) : undefined; if (inFlight === undefined) { break; } @@ -379,7 +419,7 @@ async function runPluginUploadInner( ownFiles: deps.ownFiles, siblingOwnFiles: [ ...(deps.siblingOwnFiles ?? []), - ...[...(ownersByDir.get(outDir) ?? [])].filter((names) => names !== mine).flat(), + ...[...(ownersByDir.get(dirKey0) ?? [])].filter((names) => names !== mine).flat(), ], } : {}), @@ -427,11 +467,11 @@ async function runPluginUploadInner( if (deps.files !== undefined) { return run; } - runsByDir.set(outDir, run); + runsByDir.set(dirKey0, run); void run .catch(() => undefined) .finally(() => { - runsByDir.delete(outDir); + runsByDir.delete(dirKey0); }); return run; } From 117053e8ac4b36551e27774d83145ae1e5ce1c9f Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 19:34:53 +0500 Subject: [PATCH 29/39] fix(bundler-plugin-core): generate()-only outputs are no siblings; canonical dir keys; nested dirs; frozen errors - generateBundle announces only when isWrite !== false; a mapped sibling that already finished still relaxes the failOnError empty-own-set rule (siblingsHaveMaps), so concurrent and ordered mapped+unmapped writes both pass while generate()-then-unmapped-write fails. - dirKey uses realpath.native (case-folded on case-insensitive filesystems). - a parent output treats an announced/pending nested-directory output's maps as its sibling's. - a frozen error with a read-only message is reported as a new error caused by it. - make the spelling real-build test deterministic. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- docs/design/source-maps.md | 23 +++-- .../bundler-plugin-core/src/dir-key.test.ts | 12 ++- .../src/orchestrate.restore-throws.test.ts | 10 ++ .../src/orchestrate.stamp.test.ts | 19 ++++ .../bundler-plugin-core/src/orchestrate.ts | 17 +++- .../src/plugin.in-build.real-build.test.ts | 95 +++++++++++++++++++ .../src/plugin.stamp.test.ts | 72 +++++++++++++- packages/bundler-plugin-core/src/plugin.ts | 40 ++++++-- .../bundler-plugin-core/src/resolve.test.ts | 27 ++++++ packages/bundler-plugin-core/src/resolve.ts | 35 ++++++- 10 files changed, 328 insertions(+), 22 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index f0ea30db9..aa7eae002 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -332,14 +332,21 @@ of the deepest existing ancestor plus the not-yet-created rest). Each output ann `generateBundle`; a run leaves the maps of every still-pending sibling to that sibling, on every path: the explicit pre-stamped upload, and the post-emit path (which, when siblings exist, also uploads an explicit file set instead of the directory, so a sibling's maps are neither uploaded, nor reported as "not produced by this build", nor deleted). -**`failOnError` and an output with no maps:** an output whose own map set is empty while at least one announced -sibling of the same directory has maps has nothing to do and does NOT fail ("no source maps with a debug-ID were -found" is for a lone output, or when no sibling has maps either). An output whose own map exists but is unkeyed -still fails. **Known limit:** an output that announced itself but never reaches `writeBundle` (a failed write, a -`generate()`-only output) keeps its announcement until the next `buildStart`; maps another output finds that -carry its names are left on disk, not reported. A name this output itself emitted is never treated as a sibling's. -A rejected inject keeps its ORIGINAL error object (a `BugseeCliError` stays one); a failed restore is appended to its -message. +**`failOnError` and an output with no maps:** an output whose own map set is empty while a sibling output of the +same directory has maps has nothing to do and does NOT fail ("no source maps with a debug-ID were found" is for a lone +output, or when no sibling has maps either). The sibling counts when it is announced and about to write, or has +already written and finished in this build (an unmapped output that comes LAST must not fail because its mapped +sibling got there first). An output whose own map exists but is unkeyed still fails. **Only an output that will +write is a sibling:** `bundle.generate()` (`isWrite === false`) is never announced, so a generate-only mapped output +cannot make a later unmapped write pass silently. **Nested directories:** an output written into `dist/b` while +another writes `dist` is a sibling of the parent run under its relative path (`b/x.js.map`), because the parent's +directory walk covers it; the nested run never sees the parent's files. **Directory identity** uses the canonical +on-disk spelling (`realpath.native`), so `dist` and `DIST` are one directory on a case-insensitive filesystem. +**Known limit:** an output that announced itself and then never reaches `writeBundle` (a failed write) keeps its +announcement until the next `buildStart`; maps another output finds that carry its names are left on disk, not +reported. A name this output itself emitted is never treated as a sibling's. A rejected inject keeps its ORIGINAL +error object (a `BugseeCliError` stays one; a frozen one is reported as a new error caused by it); a failed restore +is appended to the message. ### Maps that are not the bundle sibling diff --git a/packages/bundler-plugin-core/src/dir-key.test.ts b/packages/bundler-plugin-core/src/dir-key.test.ts index aac6eb63a..95e118383 100644 --- a/packages/bundler-plugin-core/src/dir-key.test.ts +++ b/packages/bundler-plugin-core/src/dir-key.test.ts @@ -1,4 +1,4 @@ -import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, relative } from 'node:path'; import { afterAll, describe, expect, it } from 'vitest'; @@ -62,6 +62,16 @@ describe('dirKey', () => { expect(typeof dirKey(a)).toBe('string'); }); + it('folds case on a case-insensitive filesystem (canonical on-disk spelling)', (ctx) => { + const dir = join(root, 'CaseDir'); + mkdirSync(dir); + if (!existsSync(join(root, 'casedir'))) { + ctx.skip(); // case-sensitive filesystem: two spellings really are two directories + } + expect(dirKey(join(root, 'casedir'))).toBe(dirKey(dir)); + expect(dirKey(join(root, 'CASEDIR', 'sub'))).toBe(join(dirKey(dir), 'sub')); + }); + it('falls back to the resolved path when nothing on the way can be resolved', () => { expect(dirKey('/')).toBe(realpathSync('/')); }); diff --git a/packages/bundler-plugin-core/src/orchestrate.restore-throws.test.ts b/packages/bundler-plugin-core/src/orchestrate.restore-throws.test.ts index 5b8ec8ed6..51159cb3e 100644 --- a/packages/bundler-plugin-core/src/orchestrate.restore-throws.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.restore-throws.test.ts @@ -63,6 +63,16 @@ describe('a rejected inject followed by a restore problem', () => { ); }); + it('a frozen (read-only message) error still reports the restore note, as a new error caused by it', async () => { + restore.mode = 'throw'; + const original = Object.freeze(new BugseeCliError('inject died', 3, 'stderr')); + const caught = await go(original).catch((e: unknown) => e); + expect(caught).not.toBe(original); + expect((caught as Error).cause).toBe(original); + expect((caught as Error).message).toContain('inject died'); + expect((caught as Error).message).toContain('restoring the originals also failed: disk gone'); + }); + it('wraps a non-Error rejection, keeping it as the cause', async () => { restore.mode = 'throw'; const caught = await go('plain string').catch((e: unknown) => e); diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index 85a18109c..615f6bce4 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -1993,4 +1993,23 @@ describe('round-18: sibling outputs on the post-emit path, empty own set under f }), ).rejects.toThrow(/no source maps with a debug-ID were found/); }); + + it('siblingsHaveMaps alone (the sibling already finished) relaxes the empty-own-set failure and avoids a directory upload', async () => { + await writeFile(join(dir, 'u.js'), 'u();\n'); + const calls: string[][] = []; + await uploadSourcemaps({ + ...base, + outDir: dir, + run: async (args) => { + calls.push(args); + return ok(args); + }, + findSri: async () => [], + failOnError: true, + siblingsHaveMaps: true, + ownFiles: ['u.js'], + onNotice: () => undefined, + }); + expect(calls.some((c) => c[0] === 'debug-files')).toBe(false); // nothing to upload, and not the directory + }); }); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index ba175dca3..8c5f763d3 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -105,6 +105,8 @@ export interface UploadSourcemapsOptions { * maps: each output handles its own, so N outputs into one directory make N uploads, not N times everything. */ siblingOwnFiles?: readonly string[]; + /** An output of the directory that has maps already finished in this build (so an unmapped one has nothing to do). */ + siblingsHaveMaps?: boolean; /** The in-build stamp's bundle -> map names (relative to `outDir`), for maps the pointer and sibling cannot name. */ stampedMaps?: Readonly>; /** Where a non-failing observation goes (default: nowhere — callers that want it pass the notice sink). */ @@ -554,11 +556,17 @@ export async function uploadSourcemaps( } if (note !== undefined) { // The ORIGINAL error object is kept (a BugseeCliError stays one); the restore problem is appended. + const message = `${error instanceof Error ? error.message : String(error)}; ${note}`; if (error instanceof Error) { - error.message = `${error.message}; ${note}`; + try { + error.message = message; + } catch { + // a frozen / read-only error: the note must not be lost, so report a new error instead + throw new Error(message, { cause: error }); + } throw error; } - throw new Error(`${String(error)}; ${note}`, { cause: error }); + throw new Error(message, { cause: error }); } } throw error; @@ -609,6 +617,7 @@ export async function uploadSourcemaps( (options.preStamped === true || restoredAny || // a sibling output's maps share the directory: upload only the names that are ours, never the directory + options.siblingsHaveMaps === true || (options.siblingOwnFiles?.length ?? 0) > 0) && !dryRun; let uploadedMaps: string[] = []; @@ -669,7 +678,9 @@ export async function uploadSourcemaps( } // An output with no maps of its own while a sibling output of the directory has some has nothing to // do: that is not "this build produced no maps". A lone unmapped output still fails. - const siblingHasMaps = (options.siblingOwnFiles ?? []).some((name) => name.endsWith('.map')); + const siblingHasMaps = + options.siblingsHaveMaps === true || + (options.siblingOwnFiles ?? []).some((name) => name.endsWith('.map')); if (deletable.length === 0) { if (options.failOnError === true && !(everything.length === 0 && siblingHasMaps)) { throw new Error( diff --git a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts index 518a9d631..d57441559 100644 --- a/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.in-build.real-build.test.ts @@ -1252,6 +1252,7 @@ describeReal('one directory spelled several ways', () => { it('outputs into `dist`, `dist/`, a symlink to it and a relative spelling coordinate as ONE directory', async () => { const app = makeApp('rollup-spellings', { lazy: false }); const link = `${app.out}-link`; + mkdirSync(app.out); // first: Rollup creating a directory through a still-dangling link races the others symlinkSync(app.out, link); const spellings = [app.out, `${app.out}/`, link, relative(process.cwd(), app.out)]; const before = requests.length; @@ -1322,3 +1323,97 @@ describeReal('a mapped and an unmapped output into one directory under failOnErr expect((readdirSync(app.out) as string[]).filter((f) => f.endsWith('.map'))).toEqual([]); }); }); + +describeReal('a generate()-only output is not a sibling', () => { + it('an unmapped write after a never-written mapped generate() still fails under failOnError', async () => { + const app = makeApp('rollup-generate-unmapped', { lazy: false }); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin({ ...pluginOptions(), failOnError: true })], + }); + await bundle.generate({ + dir: app.out, + entryFileNames: 'g.js', + format: 'iife', + name: 'g', + sourcemap: true, + }); + await expect( + bundle.write({ + dir: app.out, + entryFileNames: 'u.js', + format: 'iife', + name: 'u', + sourcemap: false, + }), + ).rejects.toThrow(/no source maps with a debug-ID were found/); + await bundle.close(); + }); +}); + +describeReal('an output into a nested directory of another output', () => { + it('the parent output neither uploads nor reports the nested output maps as foreign', async () => { + const app = makeApp('rollup-nested-dirs', { lazy: false }); + const before = requests.length; + const notices: string[] = []; + const errors: unknown[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + onNotice: (m: string) => notices.push(m), + onError: (e: unknown) => errors.push(e), + }), + ], + }); + await Promise.all([ + bundle.write({ + dir: app.out, + entryFileNames: 'p.js', + format: 'iife', + name: 'p', + sourcemap: true, + }), + bundle.write({ + dir: join(app.out, 'b'), + entryFileNames: 'c.js', + format: 'iife', + name: 'c', + sourcemap: true, + }), + ]); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expect(notices.filter((m) => m.includes('not produced by this build'))).toEqual([]); + expect( + readdirSync(app.out, { recursive: true }).filter((f) => String(f).endsWith('.map')), + ).toEqual([]); + expect(requests.length - before).toBeLessThanOrEqual(2); + }); +}); + +describeReal('a mapped output that FINISHED before an unmapped one, under failOnError', () => { + it('the later unmapped output has nothing to do and does not fail', async () => { + const app = makeApp('rollup-mapped-then-unmapped', { lazy: false }); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin({ ...pluginOptions(), failOnError: true })], + }); + await bundle.write({ + dir: app.out, + entryFileNames: 'm.js', + format: 'iife', + name: 'm', + sourcemap: true, + }); + await bundle.write({ + dir: app.out, + entryFileNames: 'u.js', + format: 'iife', + name: 'u', + sourcemap: false, + }); + await bundle.close(); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.stamp.test.ts b/packages/bundler-plugin-core/src/plugin.stamp.test.ts index a8b747e64..ec947bb33 100644 --- a/packages/bundler-plugin-core/src/plugin.stamp.test.ts +++ b/packages/bundler-plugin-core/src/plugin.stamp.test.ts @@ -966,7 +966,9 @@ describe("vite/rollup: without a final bundle the stamp's own names are used unc describe('outputs announce their names at generateBundle, so the first write already knows its siblings', () => { const hooksOf2 = (kind: 'vite' | 'rollup') => makePlugin({ appToken: 'tok', onNotice: () => undefined })[kind] as unknown as { - generateBundle: { handler: (o: object, b: Record) => Promise }; + generateBundle: { + handler: (o: object, b: Record, isWrite?: boolean) => Promise; + }; writeBundle: (o: object, b?: object) => Promise; buildStart?: () => void; }; @@ -1000,6 +1002,74 @@ describe('outputs announce their names at generateBundle, so the first write alr expect(siblingsOf(0)).toEqual([]); // a name this output emitted is never a "sibling's" }); + it(`${kind}: a generate()-only output (isWrite false) is never announced as a sibling`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + await h.generateBundle.handler({ dir: '/out' }, bundleOf('g'), false); + const written = { dir: '/out' }; + await h.generateBundle.handler(written, bundleOf('w'), true); + await h.writeBundle(written, bundleOf('w')); + expect(siblingsOf(0)).toEqual([]); + }); + + it(`${kind}: an output written into a NESTED directory is a sibling under its relative path`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + const [parent, child] = [{ dir: '/out' }, { dir: '/out/b' }]; + await h.generateBundle.handler(parent, bundleOf('p')); + await h.generateBundle.handler(child, bundleOf('c')); + await h.writeBundle(parent, bundleOf('p')); + await h.writeBundle(child, bundleOf('c')); + expect(siblingsOf(0)?.slice().sort()).toEqual(['b/c.js', 'b/c.js.map']); + expect(siblingsOf(1)).toEqual([]); // the child's walk never sees the parent's files + }); + + it(`${kind}: an unmapped output after a mapped one FINISHED is told a sibling had maps (only for a real write)`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + const flag = (call: number) => + (uploadSpy.mock.calls[call]?.[2] as { siblingsHaveMaps?: boolean }).siblingsHaveMaps; + const [m, u] = [{ dir: '/out' }, { dir: '/out' }]; + await h.generateBundle.handler(m, bundleOf('m'), true); + await h.writeBundle(m, bundleOf('m')); + await h.generateBundle.handler(u, { 'u.js': bundleOf('u')['u.js'] }, true); + await h.writeBundle(u, { 'u.js': bundleOf('u')['u.js'] }); + expect(flag(0)).toBeUndefined(); // an output is not its own sibling + expect(flag(1)).toBe(true); + // a new build forgets it + h.buildStart?.(); + const lone = { dir: '/out' }; + await h.generateBundle.handler(lone, { 'l.js': bundleOf('l')['l.js'] }, true); + await h.writeBundle(lone, { 'l.js': bundleOf('l')['l.js'] }); + expect(flag(2)).toBeUndefined(); + }); + + it(`${kind}: an output WITHOUT maps does not count as one that had maps; an unrelated directory is no sibling`, async () => { + uploadSpy.mockClear(); + const h = hooksOf2(kind); + const flag = (call: number) => + (uploadSpy.mock.calls[call]?.[2] as { siblingsHaveMaps?: boolean }).siblingsHaveMaps; + const js = (n: string) => ({ [`${n}.js`]: bundleOf(n)[`${n}.js`] }); + const [a, b, other, c] = [ + { dir: '/out' }, + { dir: '/out' }, + { dir: '/other' }, + { dir: '/out' }, + ]; + await h.generateBundle.handler(a, js('a'), true); + await h.writeBundle(a, js('a')); + await h.generateBundle.handler(other, bundleOf('o'), true); // mapped, but another directory + await h.generateBundle.handler(b, js('b'), true); + await h.writeBundle(b, js('b')); + expect(flag(0)).toBeUndefined(); + expect(flag(1)).toBeUndefined(); // 'a' had no maps, and '/other' is not this directory + expect(siblingsOf(1)).toEqual([]); // the unrelated announced output is no sibling + await h.writeBundle(other, bundleOf('o')); + await h.generateBundle.handler(c, js('c'), true); + await h.writeBundle(c, js('c')); + expect(flag(3)).toBeUndefined(); // '/other' wrote maps, in a different directory + }); + it(`${kind}: a new build forgets outputs that never wrote (buildStart)`, async () => { uploadSpy.mockClear(); const h = hooksOf2(kind); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 0061cd126..dd7d46819 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -19,6 +19,7 @@ import { dirKey, notify, type ResolvedIdentity, + relativeUnder, resolveIdentity, resolvePluginOptions, runPluginUpload, @@ -577,15 +578,26 @@ export const bugseeUnpluginFactory: UnpluginFactory>(); - const stampBundle = async (output: OutputLike, bundle: RollupBundleLike): Promise => { + // Directories an output WITH maps has already written in this build: an unmapped output that comes after it + // (its sibling already finished and left the registry) still has nothing to do. Cleared with a new build. + const mappedDirs = new Set(); + const stampBundle = async ( + output: OutputLike, + bundle: RollupBundleLike, + isWrite?: boolean, + ): Promise => { const outDir = resolveOutputDir(output); if (outDir === undefined || !resolved.enabled) { return; } const key = dirKey(outDir); - const group = announced.get(key) ?? new Map(); - group.set(output, Object.keys(bundle)); - announced.set(key, group); + // Only an output that WILL write is a sibling: `bundle.generate()` (isWrite === false) never writes, so + // its announcement would hide, as a stale sibling, maps that belong to nobody. + if (isWrite !== false) { + const group = announced.get(key) ?? new Map(); + group.set(output, Object.keys(bundle)); + announced.set(key, group); + } stampedOutputs.set(output, { preStamped: false }); const unstampable = rollupUnstampableMaps(bundle); if (unstampable.length > 0) { @@ -603,7 +615,8 @@ export const bugseeUnpluginFactory: UnpluginFactory stampBundle(output, bundle), + handler: (output: OutputLike, bundle: RollupBundleLike, isWrite?: boolean) => + stampBundle(output, bundle, isWrite), }; const uploadForOutput = async ( @@ -618,13 +631,25 @@ export const bugseeUnpluginFactory: UnpluginFactory dir !== key && relativeUnder(key, dir) !== undefined, + ); // A name THIS output emitted is never a sibling's: a leftover announcement from `bundle.generate()` (which // never writes) has the same names and must not hide this output's own maps. const mine = new Set(Object.keys(bundle ?? {})); + const siblingsHaveMaps = [...mappedDirs].some((dir) => relativeUnder(key, dir) !== undefined); + if ([...mine].some((name) => name.endsWith('.map'))) { + mappedDirs.add(key); + } const siblings = [...(group ?? [])] .filter(([other]) => other !== output) .flatMap(([, names]) => names) - .filter((name) => !mine.has(name)); + .filter((name) => !mine.has(name)) + .concat( + nested.flatMap(([dir, g]) => + [...g.values()].flat().map((name) => `${relativeUnder(key, dir)}/${name}`), + ), + ); group?.delete(output); if (group?.size === 0) { announced.delete(key); @@ -635,6 +660,7 @@ export const bugseeUnpluginFactory: UnpluginFactory @@ -747,6 +774,7 @@ export const bugseeUnpluginFactory: UnpluginFactory uploadForOutput(output, {}, bundle), diff --git a/packages/bundler-plugin-core/src/resolve.test.ts b/packages/bundler-plugin-core/src/resolve.test.ts index 545f9a3a8..a811cc9d2 100644 --- a/packages/bundler-plugin-core/src/resolve.test.ts +++ b/packages/bundler-plugin-core/src/resolve.test.ts @@ -337,6 +337,33 @@ describe('one pipeline per output directory', () => { expect(seen[1]).toEqual([]); }); + it('a pending output of a NESTED directory is a sibling of the parent run, under its relative path', async () => { + const seen: Array = []; + const upload = async (opts: { siblingOwnFiles?: readonly string[] }) => { + seen.push(opts.siblingOwnFiles); + return { injected: true, uploaded: true, deletedMaps: [] }; + }; + await Promise.all([ + runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + ownFiles: ['p.js'], + ...noVcs, + }), + runPluginUpload(resolved, 'dist/b', { + uploadSourcemaps: upload as never, + ownFiles: ['c.js'], + ...noVcs, + }), + runPluginUpload(resolved, 'dist-other', { + uploadSourcemaps: upload as never, + ownFiles: ['o.js'], + ...noVcs, + }), + ]); + expect(seen[0]).toEqual(['b/c.js']); // not dist-other's (a prefix-named sibling directory) + expect(seen[1]).toEqual([]); + }); + it('a failed in-flight run does not stop the waiting second output from running', async () => { const calls: string[] = []; let first = true; diff --git a/packages/bundler-plugin-core/src/resolve.ts b/packages/bundler-plugin-core/src/resolve.ts index 19f3a29f3..cbd13ea83 100644 --- a/packages/bundler-plugin-core/src/resolve.ts +++ b/packages/bundler-plugin-core/src/resolve.ts @@ -3,7 +3,15 @@ // required; a build without one is a no-op rather than an error). Pure + injectable for testing. import { readlinkSync, realpathSync } from 'node:fs'; -import { basename, dirname, join, resolve as resolvePath } from 'node:path'; +import { + basename, + dirname, + isAbsolute, + join, + relative, + resolve as resolvePath, + sep, +} from 'node:path'; import { type AppIdentityDeps, appIdentityDefines, @@ -277,7 +285,7 @@ export function dirKey(dir: string, depth = 0): string { const rest: string[] = []; for (;;) { try { - return join(realpathSync(head), ...rest); + return join(realpathSync.native(head), ...rest); // native: the canonical spelling (case-folded on APFS/NTFS) } catch { // A symlink whose target does not exist YET (the build will create it) still names that target. const target = depth < 40 ? readLinkTarget(head) : undefined; @@ -303,6 +311,16 @@ function readLinkTarget(path: string): string | undefined { } } +/** + * The path of `child` relative to `parent` when it is `parent` itself ('') or inside it, else undefined. A parent + * output's directory walk also covers the maps of an output written into a nested directory (`dist` and + * `dist/b`), so those are siblings too, under their relative path. + */ +export function relativeUnder(parent: string, child: string): string | undefined { + const rel = relative(parent, child); + return rel.startsWith('..') || isAbsolute(rel) ? undefined : rel.split(sep).join('/'); +} + /** The ownFiles of every output of a directory that is pending or running (see {@link runPluginUpload}). */ const ownersByDir = new Map>(); @@ -356,6 +374,8 @@ async function runPluginUploadInner( ownFiles?: readonly string[]; /** Names other outputs of the same directory announced (their maps are theirs to upload and delete). */ siblingOwnFiles?: readonly string[]; + /** An output of this directory that has maps already wrote and finished in this build. */ + siblingsHaveMaps?: boolean; /** * The build's own outputs (esbuild's metafile). The run then touches exactly these files, never joins another * run of the same directory, and registers from these bundles only. @@ -414,12 +434,21 @@ async function runPluginUploadInner( ...(deps.preStamped === true ? { preStamped: true } : {}), ...(deps.stampedBundles !== undefined ? { stampedBundles: deps.stampedBundles } : {}), ...(deps.stampedMaps !== undefined ? { stampedMaps: deps.stampedMaps } : {}), + ...(deps.siblingsHaveMaps === true ? { siblingsHaveMaps: true } : {}), ...(deps.ownFiles !== undefined ? { ownFiles: deps.ownFiles, siblingOwnFiles: [ ...(deps.siblingOwnFiles ?? []), - ...[...(ownersByDir.get(dirKey0) ?? [])].filter((names) => names !== mine).flat(), + ...[...ownersByDir].flatMap(([dir, group]) => { + const prefix = relativeUnder(dirKey0, dir); + return prefix === undefined + ? [] + : [...group] + .filter((names) => names !== mine) + .flat() + .map((name) => (prefix === '' ? name : `${prefix}/${name}`)); + }), ], } : {}), From 0f9a3ef446f2e94b1c19f80b21b245e4755525ed Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 20:57:31 +0500 Subject: [PATCH 30/39] feat(nextjs): withBugsee() source-map upload for webpack and Turbopack builds (#224) * feat(bundler-plugin-core): export stampAssets, AssetStore, notify, resolveIdentity and the env-file loaders The Next.js integration drives the same stamp and upload pipeline from its own per-compilation hooks. Co-Authored-By: Claude Sonnet 5.5 * feat(nextjs): withBugsee() build integration for webpack and Turbopack (@bugsee/nextjs/config) webpack: one plugin per compilation (client, server, edge) stamping inside the compilation and uploading exactly its own emitted files. Turbopack: compiler.runAfterProductionCompile (Next 15.4.1+) stamps and uploads the written .next, pairing bundles with maps by their sourceMappingURL pointer. Composes with user webpack / runAfterProductionCompile / define / productionBrowserSourceMaps and function or async configs; inert for dev, start and export. Co-Authored-By: Claude Sonnet 5.5 * test(nextjs-e2e): real next build for webpack and Turbopack on Next 15.5 and 16.4, with SRI cases Builds a fixture app through the real withBugsee and bugsee-cli against a mock collector and asserts stamped bundles, uploaded debug-IDs, deleted public maps, kept server maps, baked version, and that next start serves the build. Co-Authored-By: Claude Sonnet 5.5 * docs(nextjs): withBugsee README, source-maps design section 7.3, PROGRESS entry, changeset Co-Authored-By: Claude Sonnet 5.5 * docs(source-maps): Turbopack pairs bundles and maps by pointer; shared maps Co-Authored-By: Claude Sonnet 5.5 * test(nextjs-e2e): run the edge-build test's Next by path (the next16 alias shadows the next bin) Co-Authored-By: Claude Sonnet 5.5 * fix(nextjs): review round 1 (cache dirs, contained hook, version floors, idempotence, docs) - build files: a route directory named cache is build output, not skipped - post-build hook never throws unless failOnError (Next fails the build on anything it throws) - Turbopack hook floor is Next 15.4.0 (re-verified against the published tarballs; 15.3.x has none) - compiler.define only with a token and on Next >= 15.1.0 (schema checked: 15.0.x rejects it, 15.3.5 accepts it) - withBugsee applied twice is a no-op the second time - hook notices a project directory that differs from the one the config was resolved for - docs state the public-maps caveats Co-Authored-By: Claude Sonnet 5.5 * fix(nextjs): follow the frozen in-build stamping contract (own files only, query-free store, stamp counts) - Turbopack: a stylesheet map is this build's only when a stylesheet of the build points at it (/*# */ comment); a foreign .css.map or .d.ts.map under .next is never deleted - webpack: query-free asset names and the compilation's recorded source map (info.related) in the store, real asset names handed back as stampedBundles/stampedMaps for the on-disk re-check, a stamp that staged nothing while scripts were emitted falls back to post-emit and says so, an unreachable map abandons the compilation instead of half-stamping it - e2e: foreign pre-seeded .css.map and .d.ts.map (static and server) survive on both bundlers Co-Authored-By: Claude Sonnet 5.5 * fix(nextjs): stamped webpack assets as STRING sources; raw define values; real-browser e2e - nextAssetStore.update writes a string source (RealContentHashPlugin only rewrites hashed names inside string sources: a Buffer left every lazy-chunk URL stale, ChunkLoadError); non-UTF-8 assets are not offered - compiler.define takes RAW values (Next JSON-encodes them): the baked version no longer arrives quoted - nextjs-e2e opens all four Next x bundler builds and the SRI builds in headless Chromium: lazy chunk loads and runs, no 4xx, no console errors, debug-ids registered - legacy /*@ */ stylesheet pointer test; CLAUDE.md and README notes Co-Authored-By: Claude Sonnet 5.5 * refactor(nextjs): use the core's store.check contract for non-text assets; raw-define test Co-Authored-By: Claude Sonnet 5.5 * fix(nextjs): SRI fallback guard, no public maps when no upload is possible, once-per-build notices, packed-dist check - webpack: a failed in-build stamp does not fall back to stamping the written files of an SRI build (experimental.sri or Next's integrity manifest): nothing rewritten, nothing uploaded, notice - productionBrowserSourceMaps is forced on only when this build can upload (not Turbopack + SRI, not Turbopack < 15.4.0); otherwise the app's setting stands and the notice says maps may be public - notices are said once per next build across Next's processes (env marker) - real builds: SRI-webpack fallback (stub CLI refuses only the in-build inject), Turbopack+SRI has no static maps; packed tarballs load through require() and import() - docs: an async webpack function is rejected by Next itself Co-Authored-By: Claude Sonnet 5.5 * fix(nextjs): no public maps Bugsee asked for when nothing is uploaded; one accurate SRI message; clean packed install - webpack: when no upload follows (SRI stamp failure, 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 - a failed in-build stamp is reported once the build knows what follows: on SRI one notice (no 'falling back'), otherwise the fallback message - removed the env notice-dedupe marker (not reproducible on real builds, polluted process.env) - sriManifestNear no longer matches a root file of the same name - real builds: SRI-webpack fallback leaves no static maps; Turbopack+SRI with app-enabled maps keeps them and says so once; packed tarballs installed offline into a clean dir (no monorepo symlinks) Co-Authored-By: Claude Sonnet 5.5 * fix(nextjs): the SRI discard path cannot hide a failure, fail the build, or delete on a dry run - the stamp failure's cause goes through onError / console.warn, never the notice sink, so silent cannot swallow it - removing the browser maps Bugsee turned on is contained: reported via onError/console.warn, rethrown only under failOnError - nothing is deleted on a dry run (the notice says so) - README/handoff: maps enabled by a wrapper applied after withBugsee are still treated as Bugsee's; a dangling sourceMappingURL is harmless Co-Authored-By: Claude Sonnet 5.5 * fix(nextjs): round-6 lows (nothing-staged reason is reported, accurate dry-run notices, every removal attempted) - an SRI build where nothing could be staged reports a reason through onError / console.warn - the dry-run notice only claims 'nothing was deleted' when maps would have been; an abandoned stamp on a dry run says the forced maps stay public - every forced-map removal is attempted, failures collected and reported; failOnError rethrows the first - real builds: failOnError + failed SRI stamp, silent, dryRun Co-Authored-By: Claude Sonnet 5.5 * fix(nextjs): CI-hermetic packed test; review-thread sweep - packed-config e2e no longer runs pnpm install (it failed on a clean CI store): declared third-party deps are linked from the monorepo, the packed @bugsee/* tarballs unpacked; proven with an empty store and a dead registry - build files: no depth cutoff, only ENOENT is 'nothing there' (other read errors reach the failure policy), pointer found from the last 16 KiB instead of reading whole bundles - Turbopack: the server run registers the build when the browser run had nothing to upload; the shared map notice says it stays and is public - webpack: stamped names handed to the core query-free; maps found by the compilation's recorded relationship; the server compilation registers when the app writes no browser maps - withBugsee: not forced on a dry run; the app's own compiler.define version/build labels the upload Co-Authored-By: Claude Sonnet 5.5 * fix(nextjs): re-check the final on-disk bundle names after webpack renames contenthash assets #221's on-disk re-check now reports a stamped bundle it cannot read. The in-build stamp runs before webpack's RealContentHashPlugin renames [contenthash] assets, so the names it recorded no longer exist on disk and every webpack build failed with 'the stamped bundle could not be read'. The plugin now hands the core the paired bundles that carry a debug-ID on disk (final names), and reports a stamped bundle that lost its ID. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr * fix(nextjs): review threads (no-maps notice only when expected, dev-quiet config notices, contained bundle scan) - the 'emitted no source maps' notice only fires when maps were expected (not app-chosen, not on a dry run) - config-time Turbopack notices stay quiet under NODE_ENV=development - an unreadable bundle in the on-disk scan is reported, not counted as lost, and never fails the build unless failOnError Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --------- Co-authored-by: Claude Sonnet 5.5 --- .changeset/nextjs-with-bugsee.md | 6 + .gitignore | 4 + CLAUDE.md | 1 + docs/PROGRESS.md | 3 + docs/design/source-maps.md | 60 +- packages/bundler-plugin-core/src/index.ts | 5 + packages/nextjs-e2e/package.json | 3 + packages/nextjs-e2e/test/edge-build.e2e.ts | 16 +- packages/nextjs-e2e/test/packed-config.e2e.ts | 136 ++ packages/nextjs-e2e/test/source-maps.e2e.ts | 649 +++++++++ packages/nextjs/README.md | 53 + packages/nextjs/package.json | 19 +- .../nextjs/src/config/build-files.test.ts | 263 ++++ packages/nextjs/src/config/build-files.ts | 145 ++ packages/nextjs/src/config/context.test.ts | 133 ++ packages/nextjs/src/config/context.ts | 104 ++ packages/nextjs/src/config/index.ts | 10 + packages/nextjs/src/config/post-build.test.ts | 232 ++++ packages/nextjs/src/config/post-build.ts | 108 ++ packages/nextjs/src/config/sri.test.ts | 53 + packages/nextjs/src/config/sri.ts | 74 ++ .../nextjs/src/config/webpack-plugin.test.ts | 1165 +++++++++++++++++ packages/nextjs/src/config/webpack-plugin.ts | 468 +++++++ .../src/config/with-bugsee.kind.test.ts | 149 +++ .../nextjs/src/config/with-bugsee.test.ts | 505 +++++++ packages/nextjs/src/config/with-bugsee.ts | 275 ++++ packages/nextjs/tsup.config.ts | 10 +- pnpm-lock.yaml | 400 ++++-- 28 files changed, 4916 insertions(+), 133 deletions(-) create mode 100644 .changeset/nextjs-with-bugsee.md create mode 100644 packages/nextjs-e2e/test/packed-config.e2e.ts create mode 100644 packages/nextjs-e2e/test/source-maps.e2e.ts create mode 100644 packages/nextjs/src/config/build-files.test.ts create mode 100644 packages/nextjs/src/config/build-files.ts create mode 100644 packages/nextjs/src/config/context.test.ts create mode 100644 packages/nextjs/src/config/context.ts create mode 100644 packages/nextjs/src/config/index.ts create mode 100644 packages/nextjs/src/config/post-build.test.ts create mode 100644 packages/nextjs/src/config/post-build.ts create mode 100644 packages/nextjs/src/config/sri.test.ts create mode 100644 packages/nextjs/src/config/sri.ts create mode 100644 packages/nextjs/src/config/webpack-plugin.test.ts create mode 100644 packages/nextjs/src/config/webpack-plugin.ts create mode 100644 packages/nextjs/src/config/with-bugsee.kind.test.ts create mode 100644 packages/nextjs/src/config/with-bugsee.test.ts create mode 100644 packages/nextjs/src/config/with-bugsee.ts 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 `