From 0a74c1b9d88aa1adfe5fee56190490bbccdfacd0 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 11:41:00 +0500 Subject: [PATCH 01/63] 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/63] 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/63] 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 `\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'));\nimport('./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')}`; + +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: 'hidden', ...build }, + }) as never; + +/** Pins every emitted chunk in the page, hashing in generateBundle (post), like an SRI plugin does. */ +const viteSri = (): VitePlugin => ({ + name: 'doctor-sri', + enforce: 'post', + generateBundle: { + order: 'post', + handler(_options, bundle) { + const page = bundle['index.html']; + if (page?.type === 'asset') { + page.source = String(page.source).replace( + /]*?src="\.?\/?([^"]+\.js)"[^>]*>/g, + (tag, file: string) => { + const entry = bundle[file]; + return entry?.type === 'chunk' + ? tag.replace(/>$/, ` integrity="${sri(entry.code)}">`) + : tag; + }, + ); + } + }, + }, +}); + +const doctor = (out: string): Promise => + diagnoseBuildOutput(out, { + env: { BUGSEE_APP_TOKEN: 't', BUGSEE_APP_BUILD: 'b' }, + projectRoot: dirname(out), + }); +const idsOf = (report: DoctorReport, severity?: string): string[] => + report.findings.filter((f) => severity === undefined || f.severity === severity).map((f) => f.id); + +/** The only non-error findings a correctly stamped, maps-kept, hidden-map build is allowed to have. */ +function expectHealthyStamped(report: DoctorReport): void { + expect(idsOf(report, 'error')).toEqual([]); + expect(report.summary.bundles).toBeGreaterThanOrEqual(1); + expect(report.summary.maps).toBe(report.summary.bundles); + expect(idsOf(report).sort()).toEqual( + expect.arrayContaining(['map.hidden', 'map.public-leftover', 'map.sources-content']), + ); + expect(idsOf(report, 'warning')).toEqual(['map.public-leftover']); + expect(report.passed).toEqual( + expect.arrayContaining([ + 'stamp.missing-debug-id', + 'stamp.map-id-mismatch', + 'stamp.missing-registration', + ]), + ); +} + +describeReal('doctor on real, stamped build output', () => { + it('Vite 8 (Rolldown) with hidden maps is healthy', async () => { + const app = makeApp('vite8'); + await viteBuild(viteConfig(app, [bugseeUnplugin.vite(pluginOptions()) as VitePlugin])); + expectHealthyStamped(await doctor(app.out)); + }); + + it('Vite 7 (Rollup) with hidden maps is healthy', async () => { + const app = makeApp('vite7'); + await vite7Build(viteConfig(app, [bugseeUnplugin.vite(pluginOptions()) as VitePlugin])); + expectHealthyStamped(await doctor(app.out)); + }); + + it('Rollup is healthy', async () => { + const app = makeApp('rollup'); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions())], + }); + await bundle.write({ dir: app.out, sourcemap: 'hidden' }); + await bundle.close(); + expectHealthyStamped(await doctor(app.out)); + }); + + it('Rspack (webpack in-build stamping path) with hidden maps is healthy', async () => { + const app = makeApp('rspack'); + await new Promise((resolve, reject) => { + const compiler = rspack({ + context: app.dir, + mode: 'production', + entry: join(app.dir, 'index.js'), + devtool: 'hidden-source-map', + output: { path: app.out }, + plugins: [bugseeRspackPlugin(pluginOptions())], + }); + compiler.run((err) => compiler.close(() => (err ? reject(err) : resolve()))); + }); + expectHealthyStamped(await doctor(app.out)); + }); + + it('Vite with visible maps and the default deleteMaps leaves a dangling pointer (warning, not error)', async () => { + const app = makeApp('vite8-dangling'); + await viteBuild( + viteConfig(app, [bugseeUnplugin.vite(pluginOptions({ deleteMaps: true })) as VitePlugin], { + sourcemap: true, + }), + ); + const report = await doctor(app.out); + expect(report.summary.maps).toBe(0); + expect(idsOf(report, 'error')).toEqual([]); + expect(idsOf(report, 'warning')).toEqual(['map.pointer-dangling']); + }); +}); + +describeReal('doctor on real, problematic build output', () => { + it('an unstamped Vite build (plugin disabled) is an error per bundle', async () => { + const app = makeApp('vite8-unstamped'); + await viteBuild( + viteConfig(app, [bugseeUnplugin.vite(pluginOptions({ disabled: true })) as VitePlugin], { + sourcemap: true, + }), + ); + const report = await doctor(app.out); + const errors = report.findings.filter((f) => f.severity === 'error'); + expect(errors.length).toBeGreaterThan(0); + expect(errors.every((f) => f.id === 'stamp.missing-debug-id')).toBe(true); + expect(report.summary.errors).toBe(report.summary.bundles); + }); + + it('an inline-map Vite build is reported as map.inline', async () => { + const app = makeApp('vite8-inline'); + await viteBuild( + viteConfig(app, [bugseeUnplugin.vite(pluginOptions({ disabled: true })) as VitePlugin], { + sourcemap: 'inline', + }), + ); + const report = await doctor(app.out); + expect(idsOf(report, 'error')).toContain('map.inline'); + expect(report.summary.maps).toBe(0); + }); + + it('SRI: an unstamped build pinning hashes is flagged as a hazard; stamped-first is clean; stamped-after-hash is a mismatch', async () => { + const plain = makeApp('vite8-sri-plain'); + await viteBuild( + viteConfig(plain, [ + bugseeUnplugin.vite(pluginOptions({ disabled: true })) as VitePlugin, + viteSri(), + ]), + ); + const hazard = await doctor(plain.out); + expect(idsOf(hazard)).toContain('sri.unstamped-hazard'); + expect(idsOf(hazard)).not.toContain('sri.mismatch'); + + const first = makeApp('vite8-sri-first'); + await viteBuild( + viteConfig(first, [bugseeUnplugin.vite(pluginOptions()) as VitePlugin, viteSri()]), + ); + const clean = await doctor(first.out); + expect(idsOf(clean)).not.toContain('sri.unstamped-hazard'); + expect(idsOf(clean)).not.toContain('sri.mismatch'); + expect(idsOf(clean, 'error')).toEqual([]); + expect(clean.passed).toContain('sri.mismatch'); + + // The post-emit stamp the in-build design exists to avoid: the page was hashed before the stamp. + const result = await runBugseeCli(['sourcemaps', 'inject', plain.out, '--allow-sri'], { + cwd: plain.dir, + }); + expect(result.code).toBe(0); + const broken = await doctor(plain.out); + expect(idsOf(broken, 'error')).toContain('sri.mismatch'); + expect(idsOf(broken)).not.toContain('sri.unstamped-hazard'); + expect(readdirSync(plain.out).length).toBeGreaterThan(0); + expect(readFileSync(join(plain.out, 'index.html'), 'utf8')).toContain('integrity='); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.test.ts b/packages/bundler-plugin-core/src/doctor.test.ts new file mode 100644 index 000000000..572af741e --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor.test.ts @@ -0,0 +1,560 @@ +import { createHash } from 'node:crypto'; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + DOCTOR_CHECK_IDS, + DOCTOR_SCHEMA_VERSION, + type DoctorReport, + diagnoseBuildOutput, + doctorExitCode, + formatDoctorReport, +} from './doctor'; + +const ID_A = '11111111-1111-4111-8111-111111111111'; +const ID_B = '22222222-2222-4222-8222-222222222222'; + +let root: string; +let dist: string; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'bugsee-doctor-')); + dist = join(root, 'dist'); + mkdirSync(dist); + writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'app', version: '1.0.0' })); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const put = (rel: string, content: string | Buffer): string => { + const path = join(dist, rel); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, content); + return path; +}; + +const stamp = (id: string): string => + `\n!function(){var g=globalThis;g._bugseeDebugIds=g._bugseeDebugIds||{};g._bugseeDebugIds["x"]="${id}"}();\n//# debugId=${id}\n`; + +const mapJson = (extra: Record = {}): string => + JSON.stringify({ + version: 3, + sources: ['a.ts'], + sourcesContent: ['export const a = 1;'], + names: [], + mappings: 'AAAA', + ...extra, + }); + +/** A fully stamped bundle + matching hidden map. */ +const goodPair = (name = 'app.js', id = ID_A): void => { + put(name, `console.log(1);${stamp(id)}`); + put(`${name}.map`, mapJson({ debugId: id })); +}; + +const ENV = { BUGSEE_APP_TOKEN: 'secret-token-value', BUGSEE_APP_BUILD: 'abc' }; +const run = (options: Parameters[1] = {}): Promise => + diagnoseBuildOutput(dist, { env: ENV, projectRoot: root, ...options }); +const ids = (report: DoctorReport): string[] => report.findings.map((f) => f.id); +const sev = (report: DoctorReport, id: string): string | undefined => + report.findings.find((f) => f.id === id)?.severity; + +describe('diagnoseBuildOutput', () => { + it('a stamped bundle with a matching hidden map is clean except the public-leftover warning', async () => { + goodPair(); + const report = await run(); + expect(report.schemaVersion).toBe(DOCTOR_SCHEMA_VERSION); + expect(report.tool).toBe('bugsee-sourcemaps-doctor'); + expect(report.summary).toMatchObject({ errors: 0, bundles: 1, maps: 1 }); + expect(ids(report).sort()).toEqual([ + 'map.hidden', + 'map.public-leftover', + 'map.sources-content', + ]); + expect(sev(report, 'map.public-leftover')).toBe('warning'); + expect(report.passed).toContain('stamp.missing-debug-id'); + expect(report.passed).not.toContain('map.public-leftover'); + // info-only facts are not "passed" checks + expect(report.passed).not.toContain('map.hidden'); + }); + + it('after deleteMaps (bundle stamped, no maps) nothing is wrong', async () => { + put('app.js', `console.log(1);${stamp(ID_A)}`); + const report = await run(); + expect(report.findings).toEqual([]); + expect(doctorExitCode(report)).toBe(0); + expect(doctorExitCode(report, true)).toBe(0); + }); + + it('output.dir-missing: a path that is not a directory', async () => { + const report = await diagnoseBuildOutput(join(root, 'nope'), { env: ENV }); + expect(ids(report)).toEqual(['output.dir-missing']); + expect(report.passed).toEqual([]); + expect(doctorExitCode(report)).toBe(2); + const asFile = await diagnoseBuildOutput(join(root, 'package.json'), { env: ENV }); + expect(ids(asFile)).toEqual(['output.dir-missing']); + }); + + it('output.no-js: a directory with no scripts (and node_modules/src/dot dirs are not searched)', async () => { + put('index.html', ''); + put('node_modules/x/y.js', 'x'); + put('src/z.js', 'x'); + put('.hidden/h.js', 'x'); + const report = await run(); + expect(ids(report)).toContain('output.no-js'); + expect(sev(report, 'output.no-js')).toBe('error'); + expect(report.summary.bundles).toBe(0); + }); + + it('stamp.missing-debug-id: an unstamped bundle WITH a map is an error', async () => { + put('app.js', 'console.log(1);\n//# sourceMappingURL=app.js.map'); + put('app.js.map', mapJson()); + const report = await run(); + const finding = report.findings.find((f) => f.id === 'stamp.missing-debug-id'); + expect(finding).toMatchObject({ severity: 'error', file: 'app.js' }); + expect(finding?.fix).toContain('sourcemaps inject'); + expect(doctorExitCode(report)).toBe(2); + }); + + it('stamp.missing-debug-id: an unstamped bundle with NO map is only a warning', async () => { + put('vendor.js', 'console.log(1);'); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.missing-debug-id')).toMatchObject({ + severity: 'warning', + details: { files: ['vendor.js'] }, + }); + expect(doctorExitCode(report)).toBe(0); + expect(doctorExitCode(report, true)).toBe(1); + }); + + it('stamp.missing-debug-id: a bundle that lost its stamp while its map kept the id', async () => { + put('app.js', 'console.log(1);'); + put('app.js.map', mapJson({ debugId: ID_A })); + const report = await run(); + const found = report.findings.filter((f) => f.id === 'stamp.missing-debug-id'); + expect(found).toHaveLength(1); + expect(found[0]).toMatchObject({ severity: 'error', details: { mapDebugId: ID_A } }); + }); + + it('stamp.missing-registration: a comment alone is not a stamp', async () => { + put('app.js', `console.log(1);\n//# debugId=${ID_A}\n`); + const report = await run(); + expect(sev(report, 'stamp.missing-registration')).toBe('error'); + expect(report.findings.find((f) => f.id === 'stamp.missing-registration')?.details).toEqual({ + files: ['app.js'], + }); + }); + + it('stamp.map-id-mismatch / stamp.map-no-debug-id', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', mapJson({ debugId: ID_B })); + put('b.js', `b${stamp(ID_B)}`); + put('b.js.map', mapJson()); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.map-id-mismatch')).toMatchObject({ + severity: 'error', + file: 'a.js.map', + details: { bundleDebugId: ID_A, mapDebugId: ID_B }, + }); + expect(report.findings.find((f) => f.id === 'stamp.map-no-debug-id')).toMatchObject({ + severity: 'error', + file: 'b.js.map', + }); + }); + + it('accepts the snake_case debug_id spelling in the map and compares case-insensitively', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', mapJson({ debug_id: ID_A.toUpperCase() })); + const report = await run(); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + expect(ids(report)).not.toContain('stamp.map-no-debug-id'); + }); + + it('stamp.mixed: some bundles stamped, some not', async () => { + goodPair('a.js', ID_A); + put('b.js', 'b\n//# sourceMappingURL=b.js.map'); + put('b.js.map', mapJson()); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.mixed')).toMatchObject({ + severity: 'warning', + details: { stamped: 1, unstamped: 1 }, + }); + }); + + it('stamp.duplicate-debug-id: same id, different contents; identical copies are fine', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('b.js', `different${stamp(ID_A)}`); + put('c.js', `same${stamp(ID_B)}`); + put('d.js', `same${stamp(ID_B)}`); + const report = await run(); + const dup = report.findings.filter((f) => f.id === 'stamp.duplicate-debug-id'); + expect(dup).toHaveLength(1); + expect(dup[0]).toMatchObject({ + severity: 'error', + details: { debugId: ID_A, files: ['a.js', 'b.js'] }, + }); + }); + + it('map.pointer-dangling: the pointer names a map that is not there; hidden maps are noted', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=https://cdn.example/b.js.map${stamp(ID_B)}`); + const report = await run(); + const found = report.findings.find((f) => f.id === 'map.pointer-dangling'); + expect(found).toMatchObject({ + severity: 'warning', + details: { pointers: ['a.js -> a.js.map'] }, + }); + }); + + it('a pointer to a map in another directory resolves relative to the bundle', async () => { + put('js/a.js', `a\n//# sourceMappingURL=../maps/a.js.map${stamp(ID_A)}`); + put('maps/a.js.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.map-id-mismatch')?.file).toBe( + 'maps/a.js.map', + ); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('map.inline: a data: map has nothing to upload', async () => { + put('a.js', `a\n//# sourceMappingURL=data:application/json;base64,e30=${stamp(ID_A)}`); + put('b.js', 'b\n//# sourceMappingURL=data:application/json;base64,e30='); + const report = await run(); + expect(report.findings.find((f) => f.id === 'map.inline')).toMatchObject({ + severity: 'error', + details: { files: ['a.js', 'b.js'] }, + }); + // the unstamped inline bundle is an error even though it has no .map file + expect(report.findings.find((f) => f.id === 'stamp.missing-debug-id')).toMatchObject({ + severity: 'error', + file: 'b.js', + }); + }); + + it('map.invalid: not JSON, not an object, wrong version; also for a map nothing points at', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', '{not json'); + put('b.js', `b${stamp(ID_B)}`); + put('b.js.map', '[]'); + put('c.js', 'c'); + put('c.js.map', mapJson({ version: 2 })); + put('style.css.map', 'nope'); + put('other.css.map', mapJson({ version: 2 })); + const report = await run(); + const invalid = report.findings.filter((f) => f.id === 'map.invalid'); + expect(invalid.map((f) => f.file).sort()).toEqual([ + 'a.js.map', + 'b.js.map', + 'c.js.map', + 'other.css.map', + 'style.css.map', + ]); + expect(invalid.find((f) => f.file === 'a.js.map')?.message).toContain('not valid JSON'); + expect(invalid.find((f) => f.file === 'b.js.map')?.message).toContain('not a JSON object'); + expect(invalid.find((f) => f.file === 'c.js.map')?.message).toContain('version is 2'); + }); + + it('map.no-sources: missing or empty `sources`', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', mapJson({ debugId: ID_A, sources: [] })); + put('b.js', `b${stamp(ID_B)}`); + put('b.js.map', JSON.stringify({ version: 3, debugId: ID_B, mappings: '' })); + const report = await run(); + expect(report.findings.filter((f) => f.id === 'map.no-sources').map((f) => f.file)).toEqual([ + 'a.js.map', + 'b.js.map', + ]); + }); + + it('map.sources-content: embedded is a fact; absent AND unresolvable is a warning; absent but on disk is a fact', async () => { + put('a.js', `a${stamp(ID_A)}`); + put( + 'a.js.map', + mapJson({ + debugId: ID_A, + sourcesContent: undefined, + sources: ['../src/gone.ts', 'webpack/runtime/x'], + }), + ); + put('b.js', `b${stamp(ID_B)}`); + mkdirSync(join(root, 'src'), { recursive: true }); + writeFileSync(join(root, 'src', 'here.ts'), 'x'); + put( + 'b.js.map', + mapJson({ debugId: ID_B, sourcesContent: [null], sources: ['../src/here.ts'] }), + ); + const report = await run(); + const a = report.findings.find((f) => f.id === 'map.sources-unresolvable'); + expect(a).toMatchObject({ + severity: 'warning', + file: 'a.js.map', + details: { unresolved: 1, total: 2 }, + }); + expect(a?.message).toContain('../src/gone.ts'); + const b = report.findings.find((f) => f.id === 'map.sources-content' && f.file === 'b.js.map'); + expect(b).toMatchObject({ severity: 'info', details: { embedded: 0, total: 1 } }); + }); + + it('sources resolve through sourceRoot, file:// and bundler-scheme prefixes', async () => { + mkdirSync(join(root, 'src'), { recursive: true }); + writeFileSync(join(root, 'src', 'a.ts'), 'x'); + writeFileSync(join(root, 'src', 'b.ts'), 'x'); + writeFileSync(join(root, 'src', 'c.ts'), 'x'); + put('a.js', `a${stamp(ID_A)}`); + put( + 'a.js.map', + mapJson({ + debugId: ID_A, + sourcesContent: undefined, + sourceRoot: '../src/', + sources: ['a.ts'], + }), + ); + put('b.js', `b${stamp(ID_B)}`); + put( + 'b.js.map', + mapJson({ + debugId: ID_B, + sourcesContent: undefined, + sources: [`file://${join(root, 'src', 'b.ts')}`], + }), + ); + put('c.js', 'c'); + put( + 'c.js.map', + mapJson({ + debugId: ID_A, + sourcesContent: undefined, + sourceRoot: '..', + sources: ['webpack://app/src/c.ts', '\0virtual', ''], + }), + ); + const report = await run(); + expect(ids(report)).not.toContain('map.sources-unresolvable'); + }); + + it('map.too-large: warns above the threshold', async () => { + goodPair(); + const report = await run({ maxMapBytes: 10 }); + expect(report.findings.find((f) => f.id === 'map.too-large')).toMatchObject({ + severity: 'warning', + file: 'app.js.map', + }); + expect((await run()).findings.map((f) => f.id)).not.toContain('map.too-large'); + }); + + it('build.dev-bundle: webpack eval-style output', async () => { + put('main.js', `eval("x\\n//# sourceURL=webpack-internal:///./src/a.ts");`); + const report = await run(); + expect(report.findings.find((f) => f.id === 'build.dev-bundle')).toMatchObject({ + severity: 'warning', + details: { files: ['main.js'] }, + }); + }); + + describe('SRI', () => { + const sri = (bytes: string | Buffer): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + + it('sri.unstamped-hazard: a pinned script that would be broken by stamping', async () => { + const js = 'console.log(1);'; + put('app.js', js); + put('index.html', ``); + const report = await run(); + expect(report.findings.find((f) => f.id === 'sri.unstamped-hazard')).toMatchObject({ + severity: 'warning', + details: { scripts: ['app.js'] }, + }); + expect(ids(report)).not.toContain('sri.mismatch'); + }); + + it('a pin to a script that is not on disk is ignored', async () => { + put('app.js', `c${stamp(ID_A)}`); + put('index.html', ``); + const report = await run(); + expect(ids(report)).not.toContain('sri.unstamped-hazard'); + }); + + it('a stamped script whose pin matches its bytes is fine', async () => { + const js = `console.log(1);${stamp(ID_A)}`; + put('app.js', js); + put('index.html', ``); + const report = await run(); + expect(ids(report)).not.toContain('sri.unstamped-hazard'); + expect(ids(report)).not.toContain('sri.mismatch'); + expect(report.passed).toContain('sri.mismatch'); + }); + + it('sri.mismatch: stamped AFTER the page was hashed', async () => { + put('app.js', `console.log(1);${stamp(ID_A)}`); + put('index.html', ``); + const report = await run(); + expect(report.findings.find((f) => f.id === 'sri.mismatch')).toMatchObject({ + severity: 'error', + details: { scripts: ['app.js'] }, + }); + expect(report.findings.find((f) => f.id === 'sri.mismatch')?.message).toContain('refuses'); + }); + + it('sri.outside-dir: a manifest in the dir or an HTML page in the parent pins hashes', async () => { + put('app.js', `c${stamp(ID_A)}`); + put('asset-manifest.json', JSON.stringify({ 'app.js': { integrity: sri('x') } })); + put('plain-manifest.json', '{}'); + put('readme.txt', 'integrity'); + writeFileSync( + join(root, 'index.html'), + ``, + ); + writeFileSync(join(root, 'about.html'), '

no pins

'); + writeFileSync(join(root, 'pins-manifest.json'), `{"h":"${sri('y')}"}`); + const report = await run(); + const found = report.findings.find((f) => f.id === 'sri.outside-dir'); + expect(found?.severity).toBe('warning'); + expect((found?.details?.files as string[]).sort()).toEqual([ + '../index.html', + '../pins-manifest.json', + 'asset-manifest.json', + ]); + }); + }); + + describe('environment', () => { + it('env.token-missing is an error and never echoes a token; the source is not printed either', async () => { + goodPair(); + const report = await run({ env: {} }); + expect(report.findings.find((f) => f.id === 'env.token-missing')?.severity).toBe('error'); + const withToken = await run({ appToken: 'super-secret' }); + expect(JSON.stringify(withToken)).not.toContain('super-secret'); + expect(JSON.stringify(withToken)).not.toContain('secret-token-value'); + expect(ids(withToken)).not.toContain('env.token-missing'); + // whitespace-only counts as unset + expect(ids(await run({ env: { BUGSEE_APP_TOKEN: ' ' } }))).toContain('env.token-missing'); + expect(ids(await run({ env: {}, appToken: ' ' }))).toContain('env.token-missing'); + }); + + it('env.version-unresolved / env.build-unresolved', async () => { + goodPair(); + const lonely = mkdtempSync(join(tmpdir(), 'bugsee-doctor-lonely-')); + try { + const report = await run({ env: { BUGSEE_APP_TOKEN: 't' }, projectRoot: lonely }); + expect(sev(report, 'env.version-unresolved')).toBe('warning'); + expect(sev(report, 'env.build-unresolved')).toBe('info'); + const explicit = await run({ + env: { BUGSEE_APP_TOKEN: 't' }, + projectRoot: lonely, + appVersion: '9.9.9', + appBuild: '7', + }); + expect(ids(explicit)).not.toContain('env.version-unresolved'); + expect(ids(explicit)).not.toContain('env.build-unresolved'); + } finally { + rmSync(lonely, { recursive: true, force: true }); + } + }); + + it('env.node-env-development', async () => { + goodPair(); + expect( + sev(await run({ env: { ...ENV, NODE_ENV: 'development' } }), 'env.node-env-development'), + ).toBe('warning'); + expect(ids(await run({ env: { ...ENV, NODE_ENV: 'production' } }))).not.toContain( + 'env.node-env-development', + ); + }); + + it('skipEnv drops every env.* check', async () => { + goodPair(); + const report = await run({ env: {}, skipEnv: true }); + expect(ids(report).filter((id) => id.startsWith('env.'))).toEqual([]); + expect(report.passed.filter((id) => id.startsWith('env.'))).toEqual([]); + }); + }); + + it('walks only MAX_WALK_DEPTH levels down', async () => { + put('a/b/c/d/e/f/g/h/deep.js', 'x'); + put('a/b/c/d/e/f/ok.js', 'x'); + const report = await run(); + expect(report.summary.bundles).toBe(1); + }); + + it('a map pointer that resolves to a directory is skipped, not a crash', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + mkdirSync(join(dist, 'a.js.map')); + const report = await run(); + expect(report.summary.bundles).toBe(1); + expect(ids(report)).not.toContain('map.invalid'); + }); + + const describePerm = process.getuid?.() === 0 ? describe.skip : describe; + describePerm('unreadable paths', () => { + it('an unreadable sub-directory contributes nothing; an unreadable parent adds no outside-dir hints', async () => { + put('a.js', `a${stamp(ID_A)}`); + mkdirSync(join(dist, 'locked')); + writeFileSync(join(dist, 'locked', 'x.js'), 'x'); + chmodSync(join(dist, 'locked'), 0o000); + chmodSync(root, 0o300); + try { + const report = await run({ skipEnv: true }); + expect(report.summary.bundles).toBe(1); + expect(ids(report)).not.toContain('sri.outside-dir'); + } finally { + chmodSync(root, 0o700); + chmodSync(join(dist, 'locked'), 0o700); + } + }); + + it('an unreadable manifest is ignored', async () => { + put('a.js', `a${stamp(ID_A)}`); + const manifest = put('asset-manifest.json', '{"integrity":1}'); + chmodSync(manifest, 0o000); + try { + expect(ids(await run({ skipEnv: true }))).not.toContain('sri.outside-dir'); + } finally { + chmodSync(manifest, 0o600); + } + }); + }); + + it('every check ID is unique and namespaced', () => { + expect(new Set(DOCTOR_CHECK_IDS).size).toBe(DOCTOR_CHECK_IDS.length); + for (const id of DOCTOR_CHECK_IDS) { + expect(id).toMatch(/^(output|stamp|map|sri|build|env)\.[a-z-]+$/); + } + }); +}); + +describe('doctorExitCode / formatDoctorReport', () => { + const report = (errors: number, warnings: number): DoctorReport => ({ + schemaVersion: 1, + tool: 'bugsee-sourcemaps-doctor', + dir: '/d', + summary: { errors, warnings, infos: 0, bundles: 0, maps: 0 }, + passed: [], + findings: [], + }); + + it('exit codes: 2 on errors, 1 on warnings only under strict, else 0', () => { + expect(doctorExitCode(report(1, 1), true)).toBe(2); + expect(doctorExitCode(report(0, 1), true)).toBe(1); + expect(doctorExitCode(report(0, 1))).toBe(0); + expect(doctorExitCode(report(0, 0), true)).toBe(0); + }); + + it('renders errors before warnings before notes, with fix hints', async () => { + put('vendor.js', 'x'); + put('app.js', `c${stamp(ID_A)}`); + put('app.js.map', mapJson({ debugId: ID_B })); + const text = formatDoctorReport(await run()); + const error = text.indexOf('ERROR [stamp.map-id-mismatch]'); + const warn = text.indexOf('WARN [stamp.missing-debug-id]'); + const info = text.indexOf('info [map.sources-content]'); + expect(error).toBeGreaterThan(-1); + expect(warn).toBeGreaterThan(error); + expect(info).toBeGreaterThan(warn); + expect(text).toContain(' fix: '); + expect(text).toContain('2 bundle(s), 1 map(s): 1 error(s)'); + }); + + it('says so when there is nothing to report', () => { + expect(formatDoctorReport(report(0, 0))).toContain('No problems found.'); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts new file mode 100644 index 000000000..30af89f2c --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -0,0 +1,735 @@ +// `sourcemaps doctor` — the OFFLINE half. Reads a build output directory exactly as it sits on disk and says +// why a crash from it would (not) symbolicate, without a network call, a token, or a backend. +// +// Every finding has a stable check ID, a severity, a human message and a fix hint, and the report has one +// versioned JSON shape (`DoctorReport`) that the Rust `bugsee-cli sourcemaps doctor` is specified to emit +// too (see the design hand-off), so a CI step can consume either. Pure reads: nothing is written or deleted. +import { createHash } from 'node:crypto'; +import type { Dirent } from 'node:fs'; +import { existsSync } from 'node:fs'; +import { readdir, readFile, stat } from 'node:fs/promises'; +import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; +import { findAppIdentity } from './app-identity'; +import { readDebugId } from './debug-ids'; +import { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; +import type { EnvRecord } from './run-cli'; +import { findIntegrityMismatches, findSriProtectedScripts } from './sri'; +import { MAX_WALK_DEPTH, NEVER_WALK } from './stamp-files'; + +/** Bumped on any incompatible change to `DoctorReport`; the Rust command emits the same number. */ +export const DOCTOR_SCHEMA_VERSION = 1; + +export type DoctorSeverity = 'error' | 'warning' | 'info'; + +/** One thing the doctor found. `id` is stable across releases and is what tooling should match on. */ +export interface DoctorFinding { + id: string; + severity: DoctorSeverity; + message: string; + /** What to do about it. Omitted for purely informational findings. */ + fix?: string; + /** The file concerned, relative to the checked directory (POSIX separators). */ + file?: string; + /** Machine-readable specifics (counts, ids, paths); never contains a secret. */ + details?: Record; +} + +export interface DoctorReport { + schemaVersion: typeof DOCTOR_SCHEMA_VERSION; + tool: 'bugsee-sourcemaps-doctor'; + /** Absolute path of the checked directory. */ + dir: string; + summary: { errors: number; warnings: number; infos: number; bundles: number; maps: number }; + /** Check IDs that ran and found nothing wrong. */ + passed: string[]; + findings: DoctorFinding[]; +} + +export interface DoctorOptions { + /** Environment to resolve the token / version / build from. Defaults to `process.env`. */ + env?: EnvRecord; + /** An explicit token (the `appToken` plugin option). Never echoed. */ + appToken?: string; + appVersion?: string; + appBuild?: string; + /** Where `.env.bugsee-build-plugin` and `package.json` are looked up from. Defaults to the working directory. */ + projectRoot?: string; + /** A map larger than this many bytes is flagged. Default 50 MiB. */ + maxMapBytes?: number; + /** Skip the `env.*` checks (an output-only audit, e.g. in a container with no token). */ + skipEnv?: boolean; +} + +const DEFAULT_MAX_MAP_BYTES = 50 * 1024 * 1024; +const BUNDLE = /\.[cm]?js$/; +const MAP = /\.map$/; +/** The global the runtime stub writes the id into (`@bugsee/browser` reads it at crash time). */ +const REGISTRATION = '_bugseeDebugIds'; +const MAX_LISTED = 5; + +/** Every ID the doctor can emit, in report order. Exported so docs / the Rust port can be checked against it. */ +export const DOCTOR_CHECK_IDS = [ + 'output.dir-missing', + 'output.no-js', + 'stamp.missing-debug-id', + 'stamp.missing-registration', + 'stamp.map-id-mismatch', + 'stamp.map-no-debug-id', + 'stamp.mixed', + 'stamp.duplicate-debug-id', + 'map.pointer-dangling', + 'map.hidden', + 'map.inline', + 'map.invalid', + 'map.no-sources', + 'map.sources-content', + 'map.sources-unresolvable', + 'map.too-large', + 'map.public-leftover', + 'sri.unstamped-hazard', + 'sri.mismatch', + 'sri.outside-dir', + 'build.dev-bundle', + 'env.token-missing', + 'env.version-unresolved', + 'env.build-unresolved', + 'env.node-env-development', +] as const; +export type DoctorCheckId = (typeof DOCTOR_CHECK_IDS)[number]; + +const posix = (path: string): string => path.split('\\').join('/'); + +/** `bundle.js.map` -> the same name as written in the report; always relative to `dir`. */ +const rel = (dir: string, path: string): string => posix(relative(dir, path)); + +async function walk(dir: string, depth = 0): Promise { + if (depth > MAX_WALK_DEPTH) { + return []; + } + let entries: Dirent[]; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch { + 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 walk(full, depth + 1))); + } + } else if (entry.isFile() && (BUNDLE.test(entry.name) || MAP.test(entry.name))) { + found.push(full); + } + } + return found.sort(); +} + +/** The LAST `//# sourceMappingURL=` value a debugger honours. */ +function lastPointer(code: string): string | undefined { + let last: string | undefined; + for (const match of code.matchAll(/^[ \t]*\/\/[#@][ \t]*sourceMappingURL=(\S*)[ \t]*$/gm)) { + last = match[1]; + } + return last; +} + +interface ParsedMap { + ok: true; + json: Record; + debugId: string | undefined; +} + +function parseMap(text: string): ParsedMap | { ok: false; why: string } { + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + return { ok: false, why: 'not valid JSON' }; + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + return { ok: false, why: 'not a JSON object' }; + } + const json = parsed as Record; + const id = [json.debugId, json.debug_id].find((v) => typeof v === 'string' && v !== ''); + return { ok: true, json, debugId: typeof id === 'string' ? id.toLowerCase() : undefined }; +} + +/** Sources that name no file on disk by construction (bundler runtime, virtual modules). */ +const VIRTUAL_SOURCE = /^(webpack\/|\(webpack\)|\0|<|rollup:|vite\/)|\0/; + +/** Resolve a map `sources` entry against the map's directory and `sourceRoot`, as a debugger would. */ +function sourcePath(mapDir: string, sourceRoot: string, source: string): string | undefined { + let path = source; + if (/^file:\/\//.test(path)) { + path = decodeURIComponent(path.replace(/^file:\/\/(?=\/)/, '').replace(/^file:\/\//, '')); + } else if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path)) { + // `webpack://app/./src/x.ts` and friends: the scheme/namespace is not a directory; drop it. + path = path.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*\//i, ''); + } + if (VIRTUAL_SOURCE.test(path) || path === '') { + return undefined; + } + return isAbsolute(path) ? path : resolve(mapDir, sourceRoot, path); +} + +const sha = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex'); + +/** Files in `dir` and its parent that look like a manifest / page and mention integrity hashes. */ +async function integrityOutsideDir(dir: string): Promise { + const hits: string[] = []; + for (const base of [dir, dirname(dir)]) { + let names: string[]; + try { + names = await readdir(base); + } catch { + continue; + } + for (const name of names.sort()) { + const inDir = base === dir; + // HTML inside the dir is the SRI check's own business; a manifest anywhere is not. + const candidate = inDir + ? /manifest.*\.json$/i.test(name) + : /\.html?$|manifest.*\.json$/i.test(name); + if (!candidate) { + continue; + } + try { + const text = await readFile(join(base, name), 'utf8'); + if (/\bintegrity\b|["'](sha(256|384|512))-[A-Za-z0-9+/=]{20,}/i.test(text)) { + hits.push(join(base, name)); + } + } catch { + // unreadable: nothing to say about it + } + } + } + return hits; +} + +/** + * Audit the build output in `dirInput`. Never throws for a problem with the directory (that is a finding); + * never writes; reads maps and bundles in full, but only once each. + */ +export async function diagnoseBuildOutput( + dirInput: string, + options: DoctorOptions = {}, +): Promise { + const dir = resolve(dirInput); + const findings: DoctorFinding[] = []; + const failed = new Set(); + const add = (finding: DoctorFinding): void => { + findings.push(finding); + failed.add(finding.id); + }; + const env = options.env ?? (process.env as EnvRecord); + const maxMapBytes = options.maxMapBytes ?? DEFAULT_MAX_MAP_BYTES; + + let isDir = false; + try { + isDir = (await stat(dir)).isDirectory(); + } catch { + isDir = false; + } + if (!isDir) { + add({ + id: 'output.dir-missing', + severity: 'error', + message: `${dir} does not exist or is not a directory.`, + fix: 'Run the build first, and pass the bundler output directory (e.g. dist, build, .output/public).', + }); + return finish(dir, findings, 0, 0, []); + } + + const files = await walk(dir); + const bundles = files.filter((f) => BUNDLE.test(f)); + const maps = files.filter((f) => MAP.test(f)); + if (bundles.length === 0) { + add({ + id: 'output.no-js', + severity: 'error', + message: `No .js/.cjs/.mjs files found under ${dir} (node_modules, src, test and dot-directories are not searched).`, + fix: 'Point the doctor at the bundler output directory, not the project root or a source tree.', + }); + } + + const mapSet = new Set(maps); + const claimedMaps = new Set(); + const stampedIds = new Map>(); + let stamped = 0; + const unstamped: string[] = []; + const unstampedWithoutMap: string[] = []; + const noRegistration: string[] = []; + const dangling: string[] = []; + const devBundles: string[] = []; + const inline: string[] = []; + const hidden: string[] = []; + const bundleIds = new Map(); + + for (const bundle of bundles) { + const name = rel(dir, bundle); + const bytes = await readFile(bundle); + const code = bytes.toString('utf8'); + const id = readDebugId(code); + bundleIds.set(bundle, id); + + if (/\/\/# sourceURL=webpack-internal:\/\/\/|webpack-internal:\/\/\//.test(code)) { + devBundles.push(name); + } + + // Which map belongs to this bundle: the one its pointer names, else the sibling `.map`. + const pointer = lastPointer(code); + let mapPath: string | undefined; + if (pointer !== undefined && pointer !== '') { + if (/^data:/i.test(pointer)) { + inline.push(name); + } else if (!/^[a-z][a-z0-9+.-]*:/i.test(pointer) && !pointer.startsWith('//')) { + const target = resolve(dirname(bundle), decodeURIComponent(pointer.split(/[?#]/)[0] ?? '')); + if (mapSet.has(target) || existsSync(target)) { + mapPath = target; + } else { + dangling.push(`${name} -> ${pointer}`); + } + } + } + if (mapPath === undefined && mapSet.has(`${bundle}.map`)) { + mapPath = `${bundle}.map`; + if (pointer === undefined) { + hidden.push(name); + } + } + + if (id === undefined) { + unstamped.push(name); + if (mapPath === undefined && !inline.includes(name)) { + unstampedWithoutMap.push(name); + } + } else { + stamped++; + const list = stampedIds.get(id) ?? []; + list.push({ file: name, hash: sha(bytes) }); + stampedIds.set(id, list); + if (!code.includes(REGISTRATION)) { + noRegistration.push(name); + } + } + + if (mapPath !== undefined) { + claimedMaps.add(mapPath); + const mapName = rel(dir, mapPath); + let mapBytes: Buffer; + try { + mapBytes = await readFile(mapPath); + } catch { + continue; + } + const parsed = parseMap(mapBytes.toString('utf8')); + if (!parsed.ok) { + add({ + id: 'map.invalid', + severity: 'error', + file: mapName, + message: `${mapName} is ${parsed.why}, so it cannot be uploaded or used to symbolicate.`, + fix: 'Check the build is not truncating or post-processing the map; rebuild.', + }); + continue; + } + if (id !== undefined && parsed.debugId === undefined) { + add({ + id: 'stamp.map-no-debug-id', + severity: 'error', + file: mapName, + message: `${mapName} has no debugId, but its bundle ${name} carries ${id}; a crash cannot be matched to this map.`, + fix: 'Stamp the bundle and map together (the Bugsee plugin or `bugsee-cli sourcemaps inject`), and make sure no later step regenerates the map.', + details: { bundleDebugId: id }, + }); + } else if (id !== undefined && parsed.debugId !== undefined && parsed.debugId !== id) { + add({ + id: 'stamp.map-id-mismatch', + severity: 'error', + file: mapName, + message: `${mapName} has debugId ${parsed.debugId} but its bundle ${name} carries ${id}.`, + fix: 'Re-run the stamp over the final files; a minifier or copy step ran after stamping.', + details: { bundleDebugId: id, mapDebugId: parsed.debugId }, + }); + } else if (id === undefined && parsed.debugId !== undefined) { + add({ + id: 'stamp.missing-debug-id', + severity: 'error', + file: name, + message: `${name} has no debugId comment, but its map carries ${parsed.debugId}; the bundle lost its stamp.`, + fix: 'Something rewrote the bundle after stamping. Stamp last, or use the in-build stamping plugin.', + details: { mapDebugId: parsed.debugId }, + }); + // Counted once as unstamped above; do not double report below. + unstamped.splice(unstamped.indexOf(name), 1); + } + validateMap(mapPath, mapName, mapBytes.length, parsed.json); + } + } + + // Maps nothing points at (hidden maps of bundles are claimed above; this is the rest, e.g. css maps). + for (const map of maps) { + if (!claimedMaps.has(map)) { + const mapName = rel(dir, map); + try { + const bytes = await readFile(map); + const parsed = parseMap(bytes.toString('utf8')); + if (!parsed.ok) { + add({ + id: 'map.invalid', + severity: 'error', + file: mapName, + message: `${mapName} is ${parsed.why}.`, + fix: 'Check the build is not truncating or post-processing the map; rebuild.', + }); + } else { + validateMap(map, mapName, bytes.length, parsed.json); + } + } catch { + // unreadable: skip + } + } + } + + function validateMap( + mapPath: string, + mapName: string, + size: number, + json: Record, + ): void { + if (json.version !== 3) { + add({ + id: 'map.invalid', + severity: 'error', + file: mapName, + message: `${mapName} is not a source map v3 (version is ${JSON.stringify(json.version)}).`, + fix: 'Only version 3 maps are supported; check the bundler/minifier output.', + }); + return; + } + const sources = Array.isArray(json.sources) ? (json.sources as unknown[]) : undefined; + if (sources === undefined || sources.length === 0) { + add({ + id: 'map.no-sources', + severity: 'error', + file: mapName, + message: `${mapName} has no \`sources\`; it can map nothing back to your code.`, + fix: 'Enable full source maps in the bundler (not a stripped / empty map).', + }); + return; + } + if (size > maxMapBytes) { + add({ + id: 'map.too-large', + severity: 'warning', + file: mapName, + message: `${mapName} is ${(size / 1024 / 1024).toFixed(1)} MiB (limit checked: ${(maxMapBytes / 1024 / 1024).toFixed(0)} MiB); the upload may be slow or rejected.`, + fix: 'Split the bundle, strip sourcesContent (`stripSourcesContent`) or exclude vendor chunks.', + details: { bytes: size, limit: maxMapBytes }, + }); + } + const content = Array.isArray(json.sourcesContent) ? (json.sourcesContent as unknown[]) : []; + const missing = sources.filter((_, i) => typeof content[i] !== 'string').map(String); + if (missing.length === 0) { + findings.push({ + id: 'map.sources-content', + severity: 'info', + file: mapName, + message: `${mapName} embeds sourcesContent for all ${sources.length} sources.`, + }); + return; + } + const sourceRoot = typeof json.sourceRoot === 'string' ? json.sourceRoot : ''; + const mapDir = dirname(mapPath); + const unresolved = missing.filter((source) => { + const path = sourcePath(mapDir, sourceRoot, source); + return path !== undefined && !existsSync(path); + }); + if (unresolved.length > 0) { + add({ + id: 'map.sources-unresolvable', + severity: 'warning', + file: mapName, + message: `${mapName} embeds no sourcesContent for ${unresolved.length} of ${sources.length} sources and they are not on disk (${unresolved.slice(0, MAX_LISTED).join(', ')}${unresolved.length > MAX_LISTED ? ', …' : ''}); frames will show names but no source lines.`, + fix: 'Build with sourcesContent embedded (inlineSources / `sourcesContent: true`), or upload from a machine that still has the sources.', + details: { unresolved: unresolved.length, total: sources.length }, + }); + } else { + findings.push({ + id: 'map.sources-content', + severity: 'info', + file: mapName, + message: `${mapName} does not embed sourcesContent for ${missing.length} sources, but they are resolvable on disk.`, + details: { embedded: sources.length - missing.length, total: sources.length }, + }); + } + } + + // --- aggregate findings ------------------------------------------------------------------------- + for (const name of unstamped) { + const hasMap = !unstampedWithoutMap.includes(name); + if (hasMap || inline.includes(name)) { + add({ + id: 'stamp.missing-debug-id', + severity: 'error', + file: name, + message: `${name} has no debugId comment: crashes from it cannot be matched to a source map.`, + fix: 'Add the Bugsee plugin (it stamps inside the build) or run `bugsee-cli sourcemaps inject ` after the build.', + }); + } + } + if (unstampedWithoutMap.length > 0) { + add({ + id: 'stamp.missing-debug-id', + severity: 'warning', + message: `${unstampedWithoutMap.length} bundle(s) are not stamped and have no map on disk (${unstampedWithoutMap.slice(0, MAX_LISTED).join(', ')}${unstampedWithoutMap.length > MAX_LISTED ? ', …' : ''}); they will not symbolicate.`, + fix: 'Emit source maps and stamp the build; ignore for vendor files you do not want symbolicated.', + details: { files: unstampedWithoutMap }, + }); + } + if (noRegistration.length > 0) { + add({ + id: 'stamp.missing-registration', + severity: 'error', + message: `${noRegistration.length} bundle(s) have a debugId comment but no ${REGISTRATION} registration (${noRegistration.slice(0, MAX_LISTED).join(', ')}); the runtime cannot report the id with a crash.`, + fix: 'Re-stamp with `bugsee-cli sourcemaps inject` (it appends the registration); a hand-added comment is not enough.', + details: { files: noRegistration }, + }); + } + if (stamped > 0 && unstamped.length > 0) { + add({ + id: 'stamp.mixed', + severity: 'warning', + message: `${stamped} bundle(s) are stamped but ${unstamped.length} are not (${unstamped.slice(0, MAX_LISTED).join(', ')}${unstamped.length > MAX_LISTED ? ', …' : ''}): a partial stamp usually means a second build output or a late-emitted file was missed.`, + fix: 'Run the stamp over the whole output directory after the last emit step.', + details: { stamped, unstamped: unstamped.length }, + }); + } + for (const [id, entries] of stampedIds) { + if (new Set(entries.map((e) => e.hash)).size > 1) { + add({ + id: 'stamp.duplicate-debug-id', + severity: 'error', + message: `debugId ${id} appears on ${entries.length} bundles with different contents (${entries.map((e) => e.file).join(', ')}); one will symbolicate with the other's map.`, + fix: 'Strip the old stamps and re-stamp (a copied or cached stamped file was edited), or clean the output dir before building.', + details: { debugId: id, files: entries.map((e) => e.file) }, + }); + } + } + if (dangling.length > 0) { + add({ + id: 'map.pointer-dangling', + severity: 'warning', + message: `${dangling.length} bundle(s) point at a source map that is not on disk (${dangling.slice(0, MAX_LISTED).join(', ')}${dangling.length > MAX_LISTED ? ', …' : ''}); browsers request it and get a 404.`, + fix: 'Emit hidden source maps (sourcemap: "hidden") so no pointer is written, or keep the maps until deploy.', + details: { pointers: dangling }, + }); + } + if (hidden.length > 0) { + findings.push({ + id: 'map.hidden', + severity: 'info', + message: `${hidden.length} bundle(s) have a map but no sourceMappingURL comment (hidden maps): good for privacy.`, + details: { files: hidden }, + }); + } + if (inline.length > 0) { + add({ + id: 'map.inline', + severity: 'error', + message: `${inline.length} bundle(s) carry an inline (data:) source map (${inline.slice(0, MAX_LISTED).join(', ')}); there is no .map file to upload and the map ships to every visitor.`, + fix: 'Switch to external hidden maps (Vite `build.sourcemap: "hidden"`, webpack `devtool: "hidden-source-map"`, esbuild `sourcemap: "external"`).', + details: { files: inline }, + }); + } + if (devBundles.length > 0) { + add({ + id: 'build.dev-bundle', + severity: 'warning', + message: `${devBundles.length} bundle(s) look like a development build (webpack eval-style sourceURL markers: ${devBundles.slice(0, MAX_LISTED).join(', ')}); eval maps are not uploadable and bundles are unminified.`, + fix: 'Build in production mode (mode: "production", NODE_ENV=production) before uploading.', + details: { files: devBundles }, + }); + } + if (maps.length > 0) { + add({ + id: 'map.public-leftover', + severity: 'warning', + message: `${maps.length} .map file(s) are on disk in ${dir}; if this directory is deployed they are served publicly and expose your source.`, + fix: 'Keep `deleteMaps` on (default) so maps are removed after a confirmed upload, or emit hidden maps and exclude *.map from deploys.', + details: { count: maps.length, files: maps.slice(0, MAX_LISTED).map((m) => rel(dir, m)) }, + }); + } + + // --- SRI ------------------------------------------------------------------------------------------ + const pinned = await findSriProtectedScripts(dir); + if (pinned.length > 0) { + const unstampedPinned: typeof pinned = []; + for (const p of pinned) { + let code: string; + try { + code = await readFile(p.script, 'utf8'); + } catch { + continue; // a pin to a file that is not there is stale, not something stamping would break + } + if (readDebugId(code) === undefined) { + unstampedPinned.push(p); + } + } + if (unstampedPinned.length > 0) { + add({ + id: 'sri.unstamped-hazard', + severity: 'warning', + message: `${unstampedPinned.length} script(s) are pinned by an integrity hash in ${rel(dir, unstampedPinned[0]?.html ?? dir)} and are not stamped; stamping them AFTER the page was written would make the browser block them.`, + fix: 'Use the Bugsee plugin (stamps before the SRI plugin hashes; list it first), or re-generate the integrity hashes after `sourcemaps inject`.', + details: { scripts: unstampedPinned.map((p) => rel(dir, p.script)) }, + }); + } + const mismatches = await findIntegrityMismatches(dir); + if (mismatches.length > 0) { + add({ + id: 'sri.mismatch', + severity: 'error', + message: `${mismatches.length} script(s) no longer match the integrity hash pinning them (${mismatches + .slice(0, MAX_LISTED) + .map((m) => rel(dir, m.script)) + .join(', ')}); the browser refuses to run them and the page loads nothing.`, + fix: 'Something rewrote the files after the hashes were computed (usually a post-build stamp). Stamp first, hash last.', + details: { scripts: mismatches.map((m) => rel(dir, m.script)) }, + }); + } + } + const outside = await integrityOutsideDir(dir); + if (outside.length > 0) { + add({ + id: 'sri.outside-dir', + severity: 'warning', + message: `${outside.map((p) => posix(relative(dir, p))).join(', ')} mention integrity hashes but are outside what the doctor can tie to a script; if they pin these bundles, stamping them afterwards breaks the page.`, + fix: 'Check whether the page / manifest pins hashes of these files; if so make stamping happen before they are computed, or regenerate them.', + details: { files: outside.map((p) => posix(relative(dir, p))) }, + }); + } + + // --- environment ---------------------------------------------------------------------------------- + if (options.skipEnv !== true) { + const root = resolve(options.projectRoot ?? process.cwd()); + const fromFile = loadBuildPluginEnv(root); + const merged = mergeBuildPluginEnv(env, fromFile.values); + const optionToken = options.appToken?.trim() ?? ''; + const envToken = merged.BUGSEE_APP_TOKEN?.trim() ?? ''; + if (optionToken === '' && envToken === '') { + add({ + id: 'env.token-missing', + severity: 'error', + message: + 'No Bugsee app token is resolvable (BUGSEE_APP_TOKEN, .env.bugsee-build-plugin, or the appToken option): the plugin is disabled and nothing is uploaded.' + + (fromFile.problem !== undefined ? ` ${fromFile.problem}` : ''), + fix: 'Set BUGSEE_APP_TOKEN in the build environment or in .env.bugsee-build-plugin next to your project.', + }); + } + const identity = findAppIdentity( + { appVersion: options.appVersion, appBuild: options.appBuild }, + merged, + {}, + root, + ); + if (identity.version === undefined) { + add({ + id: 'env.version-unresolved', + severity: 'warning', + message: `No app version is resolvable (BUGSEE_APP_VERSION or a package.json version at or above ${root}); the upload is labelled 0.0.0.`, + fix: 'Set BUGSEE_APP_VERSION, or pass --project-root to the directory holding package.json.', + }); + } + if (identity.build === undefined) { + add({ + id: 'env.build-unresolved', + severity: 'info', + message: + 'No app build id is resolvable (BUGSEE_APP_BUILD or a CI commit variable); the build is labelled 0.', + fix: 'Set BUGSEE_APP_BUILD (e.g. the commit SHA) so builds can be told apart.', + }); + } + if (merged.NODE_ENV === 'development') { + add({ + id: 'env.node-env-development', + severity: 'warning', + message: + 'NODE_ENV is "development": the Bugsee plugins skip the upload for development builds (unless uploadInDevelopment is set).', + fix: 'Build with NODE_ENV=production for the build you deploy.', + }); + } + } + + const passed = DOCTOR_CHECK_IDS.filter( + (id) => + !failed.has(id) && !INFO_ONLY.has(id) && !(options.skipEnv === true && id.startsWith('env.')), + ); + return finish(dir, findings, bundles.length, maps.length, passed); +} + +/** Checks that only ever produce an `info` finding: they are not "passed", they are facts. */ +const INFO_ONLY: ReadonlySet = new Set(['map.hidden', 'map.sources-content']); + +function finish( + dir: string, + findings: DoctorFinding[], + bundles: number, + maps: number, + passed: readonly string[], +): DoctorReport { + const count = (severity: DoctorSeverity): number => + findings.filter((f) => f.severity === severity).length; + return { + schemaVersion: DOCTOR_SCHEMA_VERSION, + tool: 'bugsee-sourcemaps-doctor', + dir, + summary: { + errors: count('error'), + warnings: count('warning'), + infos: count('info'), + bundles, + maps, + }, + passed: [...passed], + findings, + }; +} + +/** 0 clean, 2 errors, 1 warnings only under `strict`. */ +export function doctorExitCode(report: DoctorReport, strict = false): 0 | 1 | 2 { + if (report.summary.errors > 0) { + return 2; + } + return strict && report.summary.warnings > 0 ? 1 : 0; +} + +const MARK: Record = { + error: 'ERROR ', + warning: 'WARN ', + info: 'info ', +}; + +/** The human rendering. Stable enough to read; machines should use the JSON report. */ +export function formatDoctorReport(report: DoctorReport): string { + const lines = [ + `Bugsee source-map doctor: ${report.dir}`, + `${report.summary.bundles} bundle(s), ${report.summary.maps} map(s): ${report.summary.errors} error(s), ${report.summary.warnings} warning(s), ${report.summary.infos} note(s)`, + '', + ]; + const order: DoctorSeverity[] = ['error', 'warning', 'info']; + for (const severity of order) { + for (const finding of report.findings.filter((f) => f.severity === severity)) { + lines.push(`${MARK[severity]}[${finding.id}] ${finding.message}`); + if (finding.fix !== undefined) { + lines.push(` fix: ${finding.fix}`); + } + } + } + if (report.findings.length === 0) { + lines.push('No problems found.'); + } + return lines.join('\n'); +} diff --git a/packages/bundler-plugin-core/src/index.ts b/packages/bundler-plugin-core/src/index.ts index c2fe56248..fc791081e 100644 --- a/packages/bundler-plugin-core/src/index.ts +++ b/packages/bundler-plugin-core/src/index.ts @@ -10,6 +10,18 @@ export { findPackageVersion, } from './app-identity'; export { deriveBuildUuid } from './build-id'; +export { + DOCTOR_CHECK_IDS, + DOCTOR_SCHEMA_VERSION, + type DoctorCheckId, + type DoctorFinding, + type DoctorOptions, + type DoctorReport, + type DoctorSeverity, + diagnoseBuildOutput, + doctorExitCode, + formatDoctorReport, +} from './doctor'; export { defaultDeleteMapFiles, type RunFn, diff --git a/packages/bundler-plugin-core/tsup.config.ts b/packages/bundler-plugin-core/tsup.config.ts index 82e2f36b8..59d4edcd6 100644 --- a/packages/bundler-plugin-core/tsup.config.ts +++ b/packages/bundler-plugin-core/tsup.config.ts @@ -1,4 +1,15 @@ import { defineConfig } from 'tsup'; import { baseConfig } from '../../tsup.config.base'; -export default defineConfig(baseConfig); +export default defineConfig([ + baseConfig, + { + // `bugsee-sourcemaps-doctor`: an ESM-only executable (its entry guard reads `import.meta.url`, which a CJS + // build does not have). `clean: false` so it does not wipe the library build above. + ...baseConfig, + entry: ['src/doctor-cli.ts'], + format: ['esm'], + dts: false, + clean: false, + }, +]); From f1acf01fab02d438b99342d314ee8838a5e641c5 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 11:54:24 +0500 Subject: [PATCH 06/63] docs(source-maps): doctor README, usage section and PROGRESS entry Co-Authored-By: Claude Sonnet 5.5 --- docs/PROGRESS.md | 3 +++ docs/source-maps-usage.md | 27 ++++++++++++++++++++++++++ packages/bundler-plugin-core/README.md | 16 ++++++++++++++- 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index b57d06c64..832247521 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. + +### `sourcemaps doctor`: offline build-output diagnostics (2026-11-23) +`@bugsee/bundler-plugin-core` ships `diagnoseBuildOutput(dir, options)` (`src/doctor.ts`) and the `bugsee-sourcemaps-doctor` bin (`src/doctor-cli.ts`, ESM-only tsup entry, wired through `publishConfig.bin`). 25 check IDs (`DOCTOR_CHECK_IDS`) over the output directory, bundles, maps, SRI (reusing `sri.ts`), leftover maps and the build environment (token, version, build, `NODE_ENV`; the token is never printed), each with a severity and a fix hint, and one versioned JSON report (`schemaVersion: 1`) that the Rust `bugsee-cli sourcemaps doctor` is specified to share. Exit codes 0 ok, 1 warnings only with `--strict`, 2 errors. Real-build proof in `doctor.real-build.test.ts`: Vite 8 and 7, Rollup and Rspack stamped by the real plugin and CLI (healthy), an unstamped build, an inline-map build, and SRI builds (unstamped hazard, stamped-first clean, stamped-after-hash `sri.mismatch` produced by `bugsee-cli sourcemaps inject --allow-sri`). Webpack itself is not a dependency of this package; Rspack stands in for the shared in-build stamp path. Mutator loop: 10 mutations on the decision logic, all killed. **Not done:** an optional post-build `doctor` call in the plugins (the findings need a policy for failing a build; left as a follow-up), the Rust command, and every check that needs the backend (design hand-off: map-present-for-debug-ID, deployed-URL, synthetic symbolicate round trip). diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index be668b96a..656952033 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -220,3 +220,30 @@ stub the SDK reads. This is exactly what the plugins automate; the CLI is the sa - **Not covered: bytecode targets.** React-Native/Hermes compiles JS → bytecode, which drops the injected comment and stub, so the running code reports no debug-ID. That needs a Hermes-specific compose flow and is handled by the separate React-Native SDK, not this (web/node/bun) SDK. + +## 4. Check a build: `bugsee-sourcemaps-doctor` + +When a production crash does not de-minify, run the doctor against the build output you actually deployed (or are about to). It is offline: it reads the files, makes no network call and needs no token for the file checks. + +```bash +npx bugsee-sourcemaps-doctor dist # readable report, fix hint per finding +npx bugsee-sourcemaps-doctor dist --json # for CI (schemaVersion 1) +npx bugsee-sourcemaps-doctor dist --strict # warnings fail the step too (exit 1) +``` + +Exit codes: `0` ok, `1` warnings only (with `--strict`), `2` errors. The package is `@bugsee/bundler-plugin-core`; the same report is available in code as `diagnoseBuildOutput(dir, options)`. + +Typical findings and what to do: + +| ID | Meaning | +|---|---| +| `stamp.missing-debug-id` / `stamp.missing-registration` | A bundle is not stamped (or only has the comment, not the runtime registration). Add the plugin, or run `bugsee-cli sourcemaps inject ` after the build. | +| `stamp.map-id-mismatch` / `stamp.map-no-debug-id` | The map's `debugId` is not the bundle's. A step ran after stamping; stamp last. | +| `map.pointer-dangling` | The bundle's `sourceMappingURL` points at a map that is not on disk (typical after maps are deleted from a `sourcemap: true` build). Use hidden maps. | +| `map.inline` | The map is a `data:` URL inside the bundle: nothing to upload, and it ships to every visitor. | +| `map.sources-unresolvable` | No `sourcesContent` and the sources are not on disk: frames will have no source lines. | +| `map.public-leftover` | `.map` files are in the directory you deploy. Keep `deleteMaps` on or exclude `*.map`. | +| `sri.unstamped-hazard` / `sri.mismatch` / `sri.outside-dir` | Subresource Integrity hashes pin these scripts; stamping after hashing makes the browser block them. | +| `env.token-missing` | No app token is visible to the build; the plugin is disabled and uploads nothing. | + +The doctor prints which source supplied the token (never the token). Checks that need the backend (is the map for this ID uploaded? does the deployed URL serve a stamped bundle?) are not part of this command yet. diff --git a/packages/bundler-plugin-core/README.md b/packages/bundler-plugin-core/README.md index 64f299fd4..29fed0a5a 100644 --- a/packages/bundler-plugin-core/README.md +++ b/packages/bundler-plugin-core/README.md @@ -20,7 +20,21 @@ npm install --save-dev @bugsee/vite-plugin - 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. -The programmatic API beyond the plugins is internal and may change between releases. +## `bugsee-sourcemaps-doctor` + +An offline check of a build output directory: why would a crash from this build not symbolicate? No network, no token needed. + +```bash +npx bugsee-sourcemaps-doctor dist # human report +npx bugsee-sourcemaps-doctor dist --json # machine-readable report (schemaVersion 1) +npx bugsee-sourcemaps-doctor dist --strict # exit 1 on warnings too +``` + +Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks). + +It checks, each with a stable ID, a severity and a fix hint: the output directory and its JavaScript; the debug-ID comment and `_bugseeDebugIds` registration on every bundle; a matching map with the same ID; `sourceMappingURL` pointers (dangling, hidden, inline); map validity (v3, `sources`, `sourcesContent` embedded or resolvable on disk, size); mixed stamped/unstamped bundles; duplicate IDs across different contents; Subresource Integrity hazards and mismatches (including manifests or pages outside the directory); leftover `.map` files that a deploy would serve; development-mode bundles; and the build environment (token present, version and build resolvable, `NODE_ENV`). The token is never printed. Programmatic use: `diagnoseBuildOutput(dir, options)` returns the same report. The backend-assisted checks (is this ID's map uploaded?) are not part of this command; see `docs/source-maps-usage.md` §4. + +The rest of the programmatic API beyond the plugins and the doctor is internal and may change between releases. ## Links From e8495dd05a5b2c72812fc39e5512eb693a26d5dc Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 11:58:57 +0500 Subject: [PATCH 07/63] fix(bundler-plugin-core): review findings on in-build stamping - verify only the bundles the in-build stamp wrote (no whole-directory walk): a vendor script beside the build, stale files and an output dir of '.' no longer raise spurious warnings - spill post-emit originals to a temp dir with hashes instead of holding bytes in memory; one bundle and its map in memory at a time; never snapshot or restore a directory that is the project root or above - key the in-build stamp state by output options (WeakMap), not directory, so concurrent outputs into one folder cannot consume each other's answer - resolve a bundle's map from its sourceMappingURL (custom sourcemapFileName) - restore atomically (temp + rename, bundle before map) and report a failed restore by name - refuse to stage assets whose names differ only by case Co-Authored-By: Claude Sonnet 5.5 --- docs/design/source-maps.md | 23 +- .../src/orchestrate.stamp.test.ts | 94 ++++++- .../bundler-plugin-core/src/orchestrate.ts | 47 +++- .../src/plugin.stamp.test.ts | 81 ++++-- packages/bundler-plugin-core/src/plugin.ts | 53 ++-- packages/bundler-plugin-core/src/resolve.ts | 3 + .../src/stamp-assets.test.ts | 22 ++ .../bundler-plugin-core/src/stamp-assets.ts | 14 + .../src/stamp-files.test.ts | 226 ++++++++++++++++ .../bundler-plugin-core/src/stamp-files.ts | 244 +++++++++++++++--- .../src/verify-stamp.test.ts | 102 +++++++- .../bundler-plugin-core/src/verify-stamp.ts | 56 +++- 12 files changed, 865 insertions(+), 100 deletions(-) create mode 100644 packages/bundler-plugin-core/src/stamp-files.test.ts diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index a3956b27a..f5246f059 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -188,9 +188,12 @@ every later hash is taken over the stamped bytes: | webpack 5, **Rspack** | `compilation.hooks.processAssets` at `PROCESS_ASSETS_STAGE_DEV_TOOLING + 1` (501) | maps are emitted AT 500; `webpack-subresource-integrity` / Rspack's `SubresourceIntegrityPlugin` hash later (measured: after 700), so they hash the stamped bytes — for the HTML and for the lazy-chunk `sriHashes` table in the runtime. Rspack uses the same `compiler.rspack` API (`Compilation`, `sources.RawSource`) as webpack; verified against a real Rspack 2.2.9 build with the built-in SRI plugin. | | **Vite**, **Rollup** | `generateBundle` with `order: 'pre'` | the bundle's chunks (`code`) and their `.map` files (bundle ASSETS: measured on Rollup 4.65, Vite 7.3 and Vite 8.3/Rolldown) are in memory and are what gets written. `order: 'pre'` runs before Vite builds `index.html` (where a `transformIndexHtml` SRI plugin hashes) and before default-order and `post` hooks. | -The in-build stamp is **per build**: webpack/Rspack reset it per compilation; Vite/Rollup record it per output -directory in `generateBundle` and consume it in the matching `writeBundle` (so a stamp can never carry over to a -later build of the same directory, nor from one Vite environment to another). A failed or impossible in-build +The in-build stamp is **per build**: webpack/Rspack reset it per compilation; Vite/Rollup record it per OUTPUT +(keyed by the output-options object both hooks receive, not the directory, so two outputs written concurrently +into one folder cannot consume each other's answer) in `generateBundle` and consume it in the matching +`writeBundle` (so a stamp can never carry over to a later build, nor from one Vite environment to another; a +write that cannot be matched is simply not stamped). Assets whose names differ only by case cannot be staged on +a case-insensitive disk and fall back to post-emit. A failed or impossible in-build stamp degrades to the POST-EMIT path below — never to an unchecked page: a chunk whose map is not a bundle asset (an older Rollup, `sourcemap: 'inline'`) is not stamped in memory and says so once; a failed stamp is reported (thrown under `failOnError`). @@ -224,10 +227,16 @@ After ANY stamp (in-build or post-emit), `verify-stamp.ts` checks it, because st In-build, a failure writes NOTHING back (all or nothing: the asset table is exactly what the bundler produced), reports through `onError` (throws under `failOnError`) and falls back to the post-emit path. Post-emit, the -originals are snapshotted before `inject` (the build's own scripts and maps, same walk fence as map deletion); a -failing file is restored to its original bytes **together with its pair**, and reported. After the bundler wrote -an in-build stamp, `verifyStampedPairs` re-checks the files on disk (every bundle with a map carries a debugId its -map shares), which is what catches a later step regenerating a map. A stamped build is also re-checked against +originals are SPILLED to a temp directory before `inject` with a content hash (not held in memory; one bundle +and its map are in memory at a time), covering the build's own scripts and maps under the same walk fence as map +deletion. A directory that is the project root or above (a bare `output.file` resolves to `.`) is never +snapshotted or restored, and says so. A failing file is restored to its original bytes **together with its pair** +(bundle first, via write-temp-then-rename); a restore that fails is reported by name as still carrying the +unverified stamp. The pair is resolved from the bundle's `sourceMappingURL` (custom `sourcemapFileName(s)` +names), falling back to `.map`. After the bundler wrote an in-build stamp, the files are re-checked on +disk (every bundle with a map carries a debugId its map shares), which is what catches a later step regenerating +a map; only the bundles the stamp wrote are judged, never the directory, so a `public/` script or a stale file +beside them is not mistaken for a miss. A stamped build is also re-checked against its HTML (`findIntegrityMismatches`, `sri.ts`): any ``); + 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 63b5cd5ab0ee40320ccfd71b1f92818b0d68166f Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 14:09:16 +0500 Subject: [PATCH 21/63] =?UTF-8?q?fix(bundler-plugin-core):=20doctor=20revi?= =?UTF-8?q?ew=20round=20=E2=80=94=20strict-usable=20severities,=20never-th?= =?UTF-8?q?row,=20safe=20reads,=20token=20source,=20changeset?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - map.public-leftover is a note unless --deployed; map.pointer-dangling is a note when maps were removed on purpose; --ignore ; -- ends options - never throws (doctor.internal-error), no spread of large lists (also in stamp-files), safe file:// decoding - lstat-first regular-file reads, size before read, pointers outside the directory not read - walk the whole output dir (only node_modules/.git skipped unless project root) - bundler-scheme sources resolve against the project root; Windows file URLs - env.token-source info, missing token is a warning; BOM named in map.invalid - changeset, docs, hardening tests Co-Authored-By: Claude Sonnet 5.5 --- .changeset/sourcemaps-doctor.md | 5 + docs/PROGRESS.md | 2 +- docs/source-maps-usage.md | 13 +- packages/bundler-plugin-core/README.md | 6 +- .../src/doctor-cli.test.ts | 65 ++- .../bundler-plugin-core/src/doctor-cli.ts | 23 +- .../src/doctor.hardening.test.ts | 294 ++++++++++++ .../src/doctor.real-build.test.ts | 18 +- .../bundler-plugin-core/src/doctor.test.ts | 103 ++++- packages/bundler-plugin-core/src/doctor.ts | 426 +++++++++++++----- .../bundler-plugin-core/src/stamp-files.ts | 4 +- 11 files changed, 812 insertions(+), 147 deletions(-) create mode 100644 .changeset/sourcemaps-doctor.md create mode 100644 packages/bundler-plugin-core/src/doctor.hardening.test.ts diff --git a/.changeset/sourcemaps-doctor.md b/.changeset/sourcemaps-doctor.md new file mode 100644 index 000000000..d14b349ec --- /dev/null +++ b/.changeset/sourcemaps-doctor.md @@ -0,0 +1,5 @@ +--- +'@bugsee/bundler-plugin-core': minor +--- + +Adds `bugsee-sourcemaps-doctor`, an offline check of a build output directory (`npx bugsee-sourcemaps-doctor dist`, `--json`, `--strict`, `--deployed`, `--ignore `), and the matching `diagnoseBuildOutput(dir, options)` API with a versioned report (`schemaVersion: 1`). It tells you why a crash from the build would not symbolicate: unstamped bundles or a missing runtime registration, a map whose debugId differs from its bundle's, dangling, hidden or inline source maps, invalid maps and missing `sourcesContent`, duplicate IDs, Subresource Integrity hazards, leftover public maps, development bundles, and the build environment (token source, version, build, `NODE_ENV`; the token value is never printed). Exit 0 ok, 1 warnings with `--strict`, 2 errors. Also: `stamp-files` no longer spreads large file lists onto the call stack (a directory with more than ~125k scripts or maps overflowed it). diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 832247521..474591222 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1533,4 +1533,4 @@ Verified against current majors, all green with no adapter code changes: `@bugse `@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. ### `sourcemaps doctor`: offline build-output diagnostics (2026-11-23) -`@bugsee/bundler-plugin-core` ships `diagnoseBuildOutput(dir, options)` (`src/doctor.ts`) and the `bugsee-sourcemaps-doctor` bin (`src/doctor-cli.ts`, ESM-only tsup entry, wired through `publishConfig.bin`). 25 check IDs (`DOCTOR_CHECK_IDS`) over the output directory, bundles, maps, SRI (reusing `sri.ts`), leftover maps and the build environment (token, version, build, `NODE_ENV`; the token is never printed), each with a severity and a fix hint, and one versioned JSON report (`schemaVersion: 1`) that the Rust `bugsee-cli sourcemaps doctor` is specified to share. Exit codes 0 ok, 1 warnings only with `--strict`, 2 errors. Real-build proof in `doctor.real-build.test.ts`: Vite 8 and 7, Rollup and Rspack stamped by the real plugin and CLI (healthy), an unstamped build, an inline-map build, and SRI builds (unstamped hazard, stamped-first clean, stamped-after-hash `sri.mismatch` produced by `bugsee-cli sourcemaps inject --allow-sri`). Webpack itself is not a dependency of this package; Rspack stands in for the shared in-build stamp path. Mutator loop: 10 mutations on the decision logic, all killed. **Not done:** an optional post-build `doctor` call in the plugins (the findings need a policy for failing a build; left as a follow-up), the Rust command, and every check that needs the backend (design hand-off: map-present-for-debug-ID, deployed-URL, synthetic symbolicate round trip). +`@bugsee/bundler-plugin-core` ships `diagnoseBuildOutput(dir, options)` (`src/doctor.ts`) and the `bugsee-sourcemaps-doctor` bin (`src/doctor-cli.ts`, ESM-only tsup entry, wired through `publishConfig.bin`). 25 check IDs (`DOCTOR_CHECK_IDS`) over the output directory, bundles, maps, SRI (reusing `sri.ts`), leftover maps and the build environment (token, version, build, `NODE_ENV`; the token is never printed), each with a severity and a fix hint, and one versioned JSON report (`schemaVersion: 1`) that the Rust `bugsee-cli sourcemaps doctor` is specified to share. Exit codes 0 ok, 1 warnings only with `--strict`, 2 errors. Review round (PR #222): `--strict` passes straight after a plugin run (`map.public-leftover` is a note unless `--deployed`; `map.pointer-dangling` is a note when no map is left and every bundle is stamped; `--ignore `), the doctor never throws (`doctor.internal-error`; no spread of large lists, safe `file://` decoding), reads only regular files inside the directory with the size checked first (`map.unreadable`, `map.pointer-outside-dir`), walks the whole output directory (only `node_modules`/`.git` skipped unless it is the project root), resolves bundler-scheme sources against the project root, reports the token's source (`env.token-source`; a missing token is a warning), and pairs maps with the stamp's own `localPointerTarget`. The same spread pattern was fixed in `stamp-files.ts`. Real-build proof in `doctor.real-build.test.ts`: Vite 8 and 7, Rollup and Rspack stamped by the real plugin and CLI (healthy), an unstamped build, an inline-map build, and SRI builds (unstamped hazard, stamped-first clean, stamped-after-hash `sri.mismatch` produced by `bugsee-cli sourcemaps inject --allow-sri`). Webpack itself is not a dependency of this package; Rspack stands in for the shared in-build stamp path. Mutator loop: 10 mutations on the decision logic, all killed. **Not done:** an optional post-build `doctor` call in the plugins (the findings need a policy for failing a build; left as a follow-up), the Rust command, and every check that needs the backend (design hand-off: map-present-for-debug-ID, deployed-URL, synthetic symbolicate round trip). diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 656952033..54ad4ba19 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -223,14 +223,17 @@ stub the SDK reads. This is exactly what the plugins automate; the CLI is the sa ## 4. Check a build: `bugsee-sourcemaps-doctor` -When a production crash does not de-minify, run the doctor against the build output you actually deployed (or are about to). It is offline: it reads the files, makes no network call and needs no token for the file checks. +When a production crash does not de-minify, run the doctor against the build output you actually deployed (or are about to). It is offline: it reads the files and makes no network call. The token is only looked up (never printed) so the report can say where it comes from; a missing token is a warning, not an error. ```bash npx bugsee-sourcemaps-doctor dist # readable report, fix hint per finding npx bugsee-sourcemaps-doctor dist --json # for CI (schemaVersion 1) npx bugsee-sourcemaps-doctor dist --strict # warnings fail the step too (exit 1) +npx bugsee-sourcemaps-doctor dist --deployed # the directory is served: leftover .map files warn ``` +`--strict` passes straight after a default plugin run (maps removed after upload, bundles stamped). Other options: `--ignore ` (repeatable), `--project-root`, `--max-map-mb`, `--no-env`, `--`. + Exit codes: `0` ok, `1` warnings only (with `--strict`), `2` errors. The package is `@bugsee/bundler-plugin-core`; the same report is available in code as `diagnoseBuildOutput(dir, options)`. Typical findings and what to do: @@ -239,11 +242,11 @@ Typical findings and what to do: |---|---| | `stamp.missing-debug-id` / `stamp.missing-registration` | A bundle is not stamped (or only has the comment, not the runtime registration). Add the plugin, or run `bugsee-cli sourcemaps inject ` after the build. | | `stamp.map-id-mismatch` / `stamp.map-no-debug-id` | The map's `debugId` is not the bundle's. A step ran after stamping; stamp last. | -| `map.pointer-dangling` | The bundle's `sourceMappingURL` points at a map that is not on disk (typical after maps are deleted from a `sourcemap: true` build). Use hidden maps. | +| `map.pointer-dangling` | The bundle's `sourceMappingURL` points at a map that is not on disk. A note when no `.map` is left and every bundle is stamped (maps removed after upload); otherwise a warning. Use hidden maps to avoid the 404. | | `map.inline` | The map is a `data:` URL inside the bundle: nothing to upload, and it ships to every visitor. | | `map.sources-unresolvable` | No `sourcesContent` and the sources are not on disk: frames will have no source lines. | -| `map.public-leftover` | `.map` files are in the directory you deploy. Keep `deleteMaps` on or exclude `*.map`. | +| `map.public-leftover` | `.map` files are in the directory. A note by default; a warning with `--deployed` (you serve this directory). Keep `deleteMaps` on or exclude `*.map`. | | `sri.unstamped-hazard` / `sri.mismatch` / `sri.outside-dir` | Subresource Integrity hashes pin these scripts; stamping after hashing makes the browser block them. | -| `env.token-missing` | No app token is visible to the build; the plugin is disabled and uploads nothing. | +| `env.token-missing` | No app token is visible to the build (a warning): the plugin is disabled and uploads nothing, which is fine if you upload with `bugsee-cli` by hand. `env.token-source` says where a found token comes from, never its value. | -The doctor prints which source supplied the token (never the token). Checks that need the backend (is the map for this ID uploaded? does the deployed URL serve a stamped bundle?) are not part of this command yet. +The doctor reports which source supplied the token (`env.token-source`: option, environment variable or `.env.bugsee-build-plugin`), never the token. It reads only regular files inside the directory you give it and checks a map's size before reading it. Checks that need the backend (is the map for this ID uploaded? does the deployed URL serve a stamped bundle?) are not part of this command yet. diff --git a/packages/bundler-plugin-core/README.md b/packages/bundler-plugin-core/README.md index 29fed0a5a..1293bf2b9 100644 --- a/packages/bundler-plugin-core/README.md +++ b/packages/bundler-plugin-core/README.md @@ -22,7 +22,7 @@ npm install --save-dev @bugsee/vite-plugin ## `bugsee-sourcemaps-doctor` -An offline check of a build output directory: why would a crash from this build not symbolicate? No network, no token needed. +An offline check of a build output directory: why would a crash from this build not symbolicate? No network call; a token is not required (a missing one is only a warning). ```bash npx bugsee-sourcemaps-doctor dist # human report @@ -30,9 +30,9 @@ npx bugsee-sourcemaps-doctor dist --json # machine-readable report (schemaVe npx bugsee-sourcemaps-doctor dist --strict # exit 1 on warnings too ``` -Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks). +Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks), `--deployed` (the directory is, or is about to be, served: leftover `.map` files become a warning instead of a note), `--ignore ` (drop a check ID; repeatable), `--` (end of options). Straight after a default plugin run `--strict` passes: leftover maps are a note unless `--deployed`, and a pointer to maps removed on purpose from a fully stamped build is a note. -It checks, each with a stable ID, a severity and a fix hint: the output directory and its JavaScript; the debug-ID comment and `_bugseeDebugIds` registration on every bundle; a matching map with the same ID; `sourceMappingURL` pointers (dangling, hidden, inline); map validity (v3, `sources`, `sourcesContent` embedded or resolvable on disk, size); mixed stamped/unstamped bundles; duplicate IDs across different contents; Subresource Integrity hazards and mismatches (including manifests or pages outside the directory); leftover `.map` files that a deploy would serve; development-mode bundles; and the build environment (token present, version and build resolvable, `NODE_ENV`). The token is never printed. Programmatic use: `diagnoseBuildOutput(dir, options)` returns the same report. The backend-assisted checks (is this ID's map uploaded?) are not part of this command; see `docs/source-maps-usage.md` §4. +It checks, each with a stable ID, a severity and a fix hint: the output directory and its JavaScript; the debug-ID comment and `_bugseeDebugIds` registration on every bundle; a matching map with the same ID; `sourceMappingURL` pointers (dangling, hidden, inline); map validity (v3, `sources`, `sourcesContent` embedded or resolvable on disk, size); mixed stamped/unstamped bundles; duplicate IDs across different contents; Subresource Integrity hazards and mismatches (including manifests or pages outside the directory); leftover `.map` files that a deploy would serve; development-mode bundles; and the build environment (token present, version and build resolvable, `NODE_ENV`). The token value is never printed; the report says where it came from (option, environment variable, or `.env.bugsee-build-plugin`), and a missing token is a warning, because uploading by hand is legitimate. The doctor never throws (an internal failure is a `doctor.internal-error` finding), never reads outside the checked directory, never opens a symlink, FIFO or device as a map, and checks a map's size before reading it. Programmatic use: `diagnoseBuildOutput(dir, options)` returns the same report. The backend-assisted checks (is this ID's map uploaded?) are not part of this command; see `docs/source-maps-usage.md` §4. The rest of the programmatic API beyond the plugins and the doctor is internal and may change between releases. diff --git a/packages/bundler-plugin-core/src/doctor-cli.test.ts b/packages/bundler-plugin-core/src/doctor-cli.test.ts index c770093d6..a25bbd343 100644 --- a/packages/bundler-plugin-core/src/doctor-cli.test.ts +++ b/packages/bundler-plugin-core/src/doctor-cli.test.ts @@ -33,7 +33,8 @@ describe('runDoctorCli', () => { writeFileSync(join(dist, 'a.js'), stamped); const { code, out, err } = await cli([dist, '--project-root', root]); expect(code).toBe(0); - expect(out).toContain('No problems found.'); + expect(out).toContain('The app token comes from the BUGSEE_APP_TOKEN environment variable.'); + expect(out).not.toContain('t,'); // the value is never printed expect(err).toBe(''); }); @@ -53,10 +54,61 @@ describe('runDoctorCli', () => { expect((await cli([dist, '--no-env', '--strict'])).code).toBe(1); }); - it('--no-env skips the token check; without it a missing token is an error', async () => { + it('a missing token is a warning (exit 0; 1 under --strict); --no-env drops the check', async () => { writeFileSync(join(dist, 'a.js'), stamped); - expect((await cli([dist, '--no-env'], {} as never)).code).toBe(0); - expect((await cli([dist, '--project-root', root], {} as never)).code).toBe(2); + const base = [dist, '--project-root', root, '--json']; + const warned = await cli(base, {} as never); + expect(warned.code).toBe(0); + expect(JSON.parse(warned.out).findings.map((f: { id: string }) => f.id)).toContain( + 'env.token-missing', + ); + expect((await cli([...base, '--strict'], {} as never)).code).toBe(1); + const skipped = await cli([...base, '--no-env', '--strict'], {} as never); + expect(skipped.code).toBe(0); + }); + + it('--strict passes straight after a plugin run: stamped bundle, maps removed, pointer left', async () => { + writeFileSync(join(dist, 'a.js'), `x\n//# sourceMappingURL=a.js.map${stamped}`); + const { code } = await cli([dist, '--project-root', root, '--strict']); + expect(code).toBe(0); + }); + + it('--deployed makes leftover maps a warning; --ignore drops an ID (repeatable)', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + writeFileSync( + join(dist, 'a.js.map'), + JSON.stringify({ version: 3, debugId: ID, sources: ['a'], sourcesContent: ['x'] }), + ); + const args = [dist, '--no-env', '--strict']; + expect((await cli(args)).code).toBe(0); + expect((await cli([...args, '--deployed'])).code).toBe(1); + const ignored = await cli([ + ...args, + '--deployed', + '--ignore', + 'map.public-leftover', + '--ignore', + 'x', + '--json', + ]); + expect(ignored.code).toBe(0); + expect(JSON.parse(ignored.out).ignored).toEqual(['map.public-leftover']); + }); + + it('`--` ends options, so a directory can start with a dash', async () => { + const odd = join(root, '-odd'); + mkdirSync(odd); + writeFileSync(join(odd, 'a.js'), stamped); + const { code, out } = await cli(['--no-env', '--', odd]); + expect(code).toBe(0); + expect(out).toContain('1 bundle(s)'); + expect((await cli(['--', odd, 'second'])).code).toBe(2); + }); + + it('a single-dash unknown flag is rejected, not taken for the directory', async () => { + const { code, err } = await cli(['-x', dist]); + expect(code).toBe(2); + expect(err).toContain('Unknown option -x'); }); it('--max-map-mb sets the large-map threshold', async () => { @@ -74,6 +126,11 @@ describe('runDoctorCli', () => { expect(JSON.parse(small.out).findings.map((f: { id: string }) => f.id)).toContain( 'map.too-large', ); + // 2000 bytes against 1 MiB: only the right unit (MiB, not KiB) leaves it unflagged + const oneMb = await cli([dist, '--no-env', '--max-map-mb', '1', '--json']); + expect(JSON.parse(oneMb.out).findings.map((f: { id: string }) => f.id)).not.toContain( + 'map.too-large', + ); const big = await cli([dist, '--no-env', '--json']); expect(JSON.parse(big.out).findings.map((f: { id: string }) => f.id)).not.toContain( 'map.too-large', diff --git a/packages/bundler-plugin-core/src/doctor-cli.ts b/packages/bundler-plugin-core/src/doctor-cli.ts index c58c6c4b3..61db662e4 100644 --- a/packages/bundler-plugin-core/src/doctor-cli.ts +++ b/packages/bundler-plugin-core/src/doctor-cli.ts @@ -19,6 +19,9 @@ Options: --project-root Where .env.bugsee-build-plugin and package.json are looked up (default: cwd). --max-map-mb Flag source maps larger than n MiB (default 50). --no-env Skip the token / version / build / NODE_ENV checks. + --deployed The directory is (about to be) served: leftover .map files become a warning. + --ignore Drop a check ID from the report; repeatable. + -- End of options (a directory may start with a dash after it). -h, --help Show this help. Exit codes: 0 ok, 1 warnings only (with --strict), 2 errors.`; @@ -35,6 +38,9 @@ export async function runDoctorCli(argv: readonly string[], io: DoctorCliIo): Pr let json = false; let strict = false; let skipEnv = false; + let deployed = false; + let onlyPositionals = false; + const ignore: string[] = []; let projectRoot: string | undefined; let maxMapBytes: number | undefined; const usage = (message: string): number => { @@ -43,7 +49,14 @@ export async function runDoctorCli(argv: readonly string[], io: DoctorCliIo): Pr }; for (let i = 0; i < argv.length; i++) { const arg = argv[i] as string; - if (arg === '-h' || arg === '--help') { + if (onlyPositionals) { + if (dir !== undefined) { + return usage(`Unexpected argument ${arg}`); + } + dir = arg; + } else if (arg === '--') { + onlyPositionals = true; + } else if (arg === '-h' || arg === '--help') { io.stdout(`${DOCTOR_USAGE}\n`); return 0; } else if (arg === '--json') { @@ -52,13 +65,17 @@ export async function runDoctorCli(argv: readonly string[], io: DoctorCliIo): Pr strict = true; } else if (arg === '--no-env') { skipEnv = true; - } else if (arg === '--project-root' || arg === '--max-map-mb') { + } else if (arg === '--deployed') { + deployed = true; + } else if (arg === '--project-root' || arg === '--max-map-mb' || arg === '--ignore') { const value = argv[++i]; if (value === undefined || value.startsWith('--')) { return usage(`${arg} needs a value`); } if (arg === '--project-root') { projectRoot = value; + } else if (arg === '--ignore') { + ignore.push(value); } else { const mb = Number(value); if (!Number.isFinite(mb) || mb <= 0) { @@ -80,6 +97,8 @@ export async function runDoctorCli(argv: readonly string[], io: DoctorCliIo): Pr const report = await diagnoseBuildOutput(dir, { env: io.env, skipEnv, + deployed, + ignore, ...(projectRoot !== undefined ? { projectRoot } : {}), ...(maxMapBytes !== undefined ? { maxMapBytes } : {}), }); diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts new file mode 100644 index 000000000..cda60273f --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -0,0 +1,294 @@ +// Robustness of the doctor: it must never throw, never read what it should not, never be quadratic, and must +// resolve sources the way the build did. Each test pins one reviewed failure mode. +import { spawnSync } from 'node:child_process'; +import { + chmodSync, + mkdirSync, + mkdtempSync, + rmSync, + symlinkSync, + truncateSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, win32 } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { type DoctorReport, diagnoseBuildOutput, sourcePath, walk } from './doctor'; +import { listOutputMaps } from './stamp-files'; + +const ID_A = '11111111-1111-4111-8111-111111111111'; +const ID_B = '22222222-2222-4222-8222-222222222222'; + +let root: string; +let dist: string; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'bugsee-doctor-hard-')); + dist = join(root, 'dist'); + mkdirSync(dist); + writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'app', version: '1.0.0' })); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const put = (rel: string, content: string | Buffer): string => { + const path = join(dist, rel); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, content); + return path; +}; +const stamp = (id: string): string => + `\n!function(){var g=globalThis;g._bugseeDebugIds=g._bugseeDebugIds||{};g._bugseeDebugIds["x"]="${id}"}();\n//# debugId=${id}\n`; +const mapJson = (extra: Record = {}): string => + JSON.stringify({ + version: 3, + sources: ['a.ts'], + sourcesContent: ['x'], + names: [], + mappings: 'AAAA', + ...extra, + }); +const run = (options: Parameters[1] = {}): Promise => + diagnoseBuildOutput(dist, { projectRoot: root, skipEnv: true, ...options }); +const ids = (report: DoctorReport): string[] => report.findings.map((f) => f.id); +const find = (report: DoctorReport, id: string) => report.findings.find((f) => f.id === id); + +describe('never throws', () => { + it('a source with a bad percent-escape is unknowable, not an exception', async () => { + put('a.js', `a${stamp(ID_A)}`); + put( + 'a.js.map', + mapJson({ debugId: ID_A, sourcesContent: undefined, sources: ['file:///x/%zz.ts'] }), + ); + const report = await run(); + expect(ids(report)).not.toContain('doctor.internal-error'); + expect(ids(report)).not.toContain('map.sources-unresolvable'); + }); + + it('an unexpected internal error becomes a doctor.internal-error finding', async () => { + put('a.js', `a${stamp(ID_A)}`); + const env = new Proxy( + {}, + { + ownKeys() { + throw new Error('boom'); + }, + }, + ); + const report = await diagnoseBuildOutput(dist, { env, projectRoot: root }); + expect(report.findings).toHaveLength(1); + expect(report.findings[0]).toMatchObject({ + id: 'doctor.internal-error', + severity: 'error', + }); + expect(report.findings[0]?.message).toContain('boom'); + expect(report.summary.errors).toBe(1); + expect(report.dir).toBe(dist); + // a non-Error rejection is reported too, and `ignore` still applies + const ignored = await diagnoseBuildOutput(dist, { + env, + projectRoot: root, + ignore: ['doctor.internal-error'], + }); + expect(ignored.findings).toEqual([]); + }); + + it('a non-Error throw is stringified', async () => { + const env = new Proxy( + {}, + { + ownKeys() { + throw 'plain string'; + }, + }, + ); + put('a.js', 'x'); + const report = await diagnoseBuildOutput(dist, { env, projectRoot: root }); + expect(report.findings[0]?.message).toContain('plain string'); + }); +}); + +describe('a directory with very many files', () => { + it('the walks do not overflow the stack (130k files in one directory)', async () => { + const big = join(dist, 'chunks'); + mkdirSync(big); + for (let i = 0; i < 130_000; i++) { + writeFileSync(join(big, i % 2 === 0 ? `c${i}.js` : `c${i}.map`), ''); + } + expect((await walk(dist)).length).toBe(130_000); + expect((await listOutputMaps(dist)).length).toBe(65_000); + }, 120_000); + + it('20k bundles are checked in bounded time with correct counts', async () => { + for (let i = 0; i < 20_000; i++) { + const id = `${(i + 1).toString(16).padStart(8, '0')}-1111-4111-8111-111111111111`; + put(`assets/c${i}.js`, `${i}${stamp(id)}`); + } + const started = Date.now(); + const report = await run(); + expect(Date.now() - started).toBeLessThan(60_000); + expect(report.summary).toMatchObject({ bundles: 20_000, errors: 0, warnings: 0 }); + }, 120_000); +}); + +describe('reads', () => { + const mkfifo = (path: string): boolean => spawnSync('mkfifo', [path]).status === 0; + + it('a pointer outside the output directory is reported and never read (a FIFO would hang)', async () => { + const fifo = join(root, 'pipe.map'); + if (!mkfifo(fifo)) { + return; + } + put('a.js', `a\n//# sourceMappingURL=../pipe.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=../../../../../../dev/zero${stamp(ID_B)}`); + const report = await run(); + expect(find(report, 'map.pointer-outside-dir')).toMatchObject({ + severity: 'warning', + details: { pointers: ['a.js -> ../pipe.map', 'b.js -> ../../../../../../dev/zero'] }, + }); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('a FIFO or symlink named as a map inside the directory is map.unreadable, not opened', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + if (!mkfifo(join(dist, 'a.js.map'))) { + return; + } + put('real.map', mapJson({ debugId: ID_B })); + put('b.js', `b\n//# sourceMappingURL=link.map${stamp(ID_B)}`); + symlinkSync(join(dist, 'real.map'), join(dist, 'link.map')); + const report = await run(); + const unreadable = report.findings.filter((f) => f.id === 'map.unreadable'); + expect(unreadable.map((f) => f.file).sort()).toEqual(['a.js.map', 'link.map']); + expect(unreadable.find((f) => f.file === 'a.js.map')?.message).toContain('not a regular file'); + expect(unreadable.find((f) => f.file === 'link.map')?.message).toContain('symbolic link'); + expect(unreadable.every((f) => f.severity === 'error')).toBe(true); + }); + + it('a map larger than the limit is judged by its size, before it is read (a sparse 3 GiB file)', async () => { + put('a.js', `a${stamp(ID_A)}`); + const big = put('a.js.map', ''); + truncateSync(big, 3 * 1024 ** 3); + const report = await run(); + expect(find(report, 'map.too-large')).toMatchObject({ + severity: 'warning', + file: 'a.js.map', + details: { bytes: 3 * 1024 ** 3, limit: 50 * 1024 * 1024 }, + }); + expect(find(report, 'map.too-large')?.message).toContain('not read'); + expect(ids(report)).not.toContain('map.invalid'); + }); + + it('map.too-large is exact at the boundary: equal is fine, one byte over is not', async () => { + put('a.js', `a${stamp(ID_A)}`); + const text = mapJson({ debugId: ID_A }); + put('a.js.map', text); + const size = Buffer.byteLength(text); + expect(ids(await run({ maxMapBytes: size }))).not.toContain('map.too-large'); + expect(ids(await run({ maxMapBytes: size - 1 }))).toContain('map.too-large'); + // far over the limit also reports (kills a `>= limit * 2` comparison) + expect(ids(await run({ maxMapBytes: Math.floor(size / 2) }))).toContain('map.too-large'); + expect(find(await run({ maxMapBytes: size - 1 }), 'map.too-large')?.details).toEqual({ + bytes: size, + limit: size - 1, + }); + }); + + it('an oversized or non-regular orphan map is reported too', async () => { + put('style.css.map', mapJson()); + put('big.css.map', 'x'.repeat(100)); + const report = await run({ maxMapBytes: 50 }); + expect(find(report, 'map.too-large')?.file).toBe('big.css.map'); + }); + + it.skipIf(process.getuid?.() === 0)('a read error is a finding, not silence', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + const map = put('a.js.map', mapJson({ debugId: ID_A })); + put('b.js', 'b'); + const locked = put('locked.js', 'x'); + chmodSync(map, 0o000); + chmodSync(locked, 0o000); + try { + const report = await run(); + expect(find(report, 'map.unreadable')?.message).toContain('EACCES'); + expect(find(report, 'output.unreadable')).toMatchObject({ + severity: 'error', + details: { files: ['locked.js could not be read (EACCES)'] }, + }); + } finally { + chmodSync(map, 0o600); + chmodSync(locked, 0o600); + } + }); + + it('a script over the size limit is not read and is reported', async () => { + put('huge.js', 'x'.repeat(1000)); + put('ok.js', `a${stamp(ID_A)}`); + const report = await run({ maxBundleBytes: 999 }); + expect(find(report, 'output.unreadable')?.details).toEqual({ + files: ['huge.js is too large to read'], + }); + expect(report.summary.bundles).toBe(2); + expect(ids(await run({ maxBundleBytes: 1000 }))).not.toContain('output.unreadable'); + }); + + it('a map inside the directory but outside the walked set (node_modules) is still paired by its pointer', async () => { + put('a.js', `a\n//# sourceMappingURL=node_modules/a.map${stamp(ID_A)}`); + put('node_modules/a.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('node_modules/a.map'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('an indented sourceMappingURL comment is honoured', async () => { + put('a.js', `a\n \t//# sourceMappingURL=maps/x.map${stamp(ID_A)}`); + put('maps/x.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('maps/x.map'); + }); + + it('a map that starts with a UTF-8 BOM is map.invalid and the message says BOM', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', `\uFEFF${mapJson({ debugId: ID_A })}`); + const report = await run(); + expect(find(report, 'map.invalid')?.message).toContain('BOM'); + expect(find(report, 'map.invalid')?.severity).toBe('error'); + }); +}); + +describe('source resolution', () => { + it('bundler-scheme sources resolve against the project root, not the map directory', async () => { + mkdirSync(join(root, 'src')); + writeFileSync(join(root, 'src', 'x.ts'), 'x'); + put('a.js', `a${stamp(ID_A)}`); + put( + 'deep/a.js.map', + mapJson({ + debugId: ID_A, + sourcesContent: undefined, + sources: ['webpack://app/./src/x.ts', 'webpack://app/./src/missing.ts'], + }), + ); + const report = await run(); + expect(find(report, 'map.sources-unresolvable')?.message).toContain('missing.ts'); + expect(find(report, 'map.sources-unresolvable')?.details).toEqual({ unresolved: 1, total: 2 }); + }); + + it('sourcePath: posix, project root, file URLs, virtual and malformed sources', () => { + expect(sourcePath('/m', '', 'webpack://app/./src/x.ts', '/proj')).toBe('/proj/src/x.ts'); + expect(sourcePath('/m', '', 'webpack://app/./src/x.ts')).toBe('/m/src/x.ts'); + expect(sourcePath('/m/d', '../s', 'a.ts', '/proj')).toBe('/m/s/a.ts'); + expect(sourcePath('/m', '', '/abs/a.ts')).toBe('/abs/a.ts'); + expect(sourcePath('/m', '', 'file:///x/a%20b.ts')).toBe('/x/a b.ts'); + expect(sourcePath('/m', '', 'file:///x/%zz.ts')).toBeUndefined(); + expect(sourcePath('/m', '', 'webpack/runtime/x')).toBeUndefined(); + expect(sourcePath('/m', '', '')).toBeUndefined(); + }); + + it('sourcePath on Windows: drive-letter file URLs and project-relative bundler paths', () => { + expect(sourcePath('C:\\m', '', 'file:///C:/x/a.ts', 'C:\\p', win32)).toBe('C:\\x\\a.ts'); + expect(sourcePath('C:\\m', '', 'webpack://app/./src/x.ts', 'C:\\p', win32)).toBe( + 'C:\\p\\src\\x.ts', + ); + expect(sourcePath('C:\\m', '..\\s', 'a.ts', 'C:\\p', win32)).toBe('C:\\s\\a.ts'); + expect(sourcePath('C:\\m', '', 'D:\\abs\\a.ts', 'C:\\p', win32)).toBe('D:\\abs\\a.ts'); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.real-build.test.ts b/packages/bundler-plugin-core/src/doctor.real-build.test.ts index de23d3e1f..b5e8cb7b0 100644 --- a/packages/bundler-plugin-core/src/doctor.real-build.test.ts +++ b/packages/bundler-plugin-core/src/doctor.real-build.test.ts @@ -21,7 +21,7 @@ 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 { type DoctorReport, diagnoseBuildOutput } from './doctor'; +import { type DoctorReport, diagnoseBuildOutput, doctorExitCode } from './doctor'; import { bugseeRollupPlugin, bugseeRspackPlugin, bugseeUnplugin } from './plugin'; import { resolveBugseeCli, runBugseeCli } from './run-cli'; @@ -119,8 +119,9 @@ const viteSri = (): VitePlugin => ({ }, }); -const doctor = (out: string): Promise => +const doctor = (out: string, extra: { deployed?: boolean } = {}): Promise => diagnoseBuildOutput(out, { + ...extra, env: { BUGSEE_APP_TOKEN: 't', BUGSEE_APP_BUILD: 'b' }, projectRoot: dirname(out), }); @@ -135,7 +136,9 @@ function expectHealthyStamped(report: DoctorReport): void { expect(idsOf(report).sort()).toEqual( expect.arrayContaining(['map.hidden', 'map.public-leftover', 'map.sources-content']), ); - expect(idsOf(report, 'warning')).toEqual(['map.public-leftover']); + // Straight after a plugin run nothing warns (so `--strict` passes); the leftover maps are a note... + expect(idsOf(report, 'warning')).toEqual([]); + expect(idsOf(report, 'info')).toContain('map.public-leftover'); expect(report.passed).toEqual( expect.arrayContaining([ 'stamp.missing-debug-id', @@ -181,7 +184,7 @@ describeReal('doctor on real, stamped build output', () => { sourcemapFileNames: 'maps/[name].map', }); await bundle.close(); - const report = await doctor(app.out); + const report = await doctor(app.out, { deployed: true }); expect(idsOf(report, 'error')).toEqual([]); expect(report.summary.maps).toBe(report.summary.bundles); expect(report.findings.some((f) => f.file?.startsWith('maps/'))).toBe(true); @@ -209,7 +212,7 @@ describeReal('doctor on real, stamped build output', () => { expectHealthyStamped(await doctor(app.out)); }); - it('Vite with visible maps and the default deleteMaps leaves a dangling pointer (warning, not error)', async () => { + it('Vite with visible maps and the default deleteMaps leaves a dangling pointer (a note, and --strict passes)', async () => { const app = makeApp('vite8-dangling'); await viteBuild( viteConfig(app, [bugseeUnplugin.vite(pluginOptions({ deleteMaps: true })) as VitePlugin], { @@ -219,7 +222,10 @@ describeReal('doctor on real, stamped build output', () => { const report = await doctor(app.out); expect(report.summary.maps).toBe(0); expect(idsOf(report, 'error')).toEqual([]); - expect(idsOf(report, 'warning')).toEqual(['map.pointer-dangling']); + // maps removed on purpose and every bundle stamped: a note, so --strict passes right after the plugin + expect(idsOf(report, 'warning')).toEqual([]); + expect(idsOf(report, 'info')).toContain('map.pointer-dangling'); + expect(doctorExitCode(report, true)).toBe(0); }); }); diff --git a/packages/bundler-plugin-core/src/doctor.test.ts b/packages/bundler-plugin-core/src/doctor.test.ts index 2e58f2a5a..5d6051cfc 100644 --- a/packages/bundler-plugin-core/src/doctor.test.ts +++ b/packages/bundler-plugin-core/src/doctor.test.ts @@ -59,28 +59,55 @@ const sev = (report: DoctorReport, id: string): string | undefined => report.findings.find((f) => f.id === id)?.severity; describe('diagnoseBuildOutput', () => { - it('a stamped bundle with a matching hidden map is clean except the public-leftover warning', async () => { + it('a stamped bundle with a matching hidden map has no warnings, only notes (even under --strict)', async () => { goodPair(); const report = await run(); expect(report.schemaVersion).toBe(DOCTOR_SCHEMA_VERSION); expect(report.tool).toBe('bugsee-sourcemaps-doctor'); - expect(report.summary).toMatchObject({ errors: 0, bundles: 1, maps: 1 }); + expect(report.summary).toMatchObject({ errors: 0, warnings: 0, bundles: 1, maps: 1 }); expect(ids(report).sort()).toEqual([ + 'env.token-source', 'map.hidden', 'map.public-leftover', 'map.sources-content', ]); - expect(sev(report, 'map.public-leftover')).toBe('warning'); + expect(sev(report, 'map.public-leftover')).toBe('info'); + expect(doctorExitCode(report, true)).toBe(0); expect(report.passed).toContain('stamp.missing-debug-id'); expect(report.passed).not.toContain('map.public-leftover'); // info-only facts are not "passed" checks expect(report.passed).not.toContain('map.hidden'); + expect(report.passed).not.toContain('env.token-source'); + }); + + it('map.public-leftover is a warning when the directory is deployed', async () => { + goodPair(); + const report = await run({ deployed: true }); + expect(sev(report, 'map.public-leftover')).toBe('warning'); + expect(report.findings.find((f) => f.id === 'map.public-leftover')?.fix).toContain( + '--deployed', + ); + expect(doctorExitCode(report, true)).toBe(1); + }); + + it('ignore drops the listed IDs from findings and passed, and reports what it dropped', async () => { + goodPair(); + const report = await run({ + deployed: true, + ignore: ['map.public-leftover', 'stamp.mixed', 'env.token-source'], + }); + expect(ids(report)).not.toContain('map.public-leftover'); + expect(report.summary.warnings).toBe(0); + expect(report.ignored).toEqual(['map.public-leftover', 'env.token-source']); + expect(report.passed).not.toContain('stamp.mixed'); + expect((await run()).ignored).toBeUndefined(); }); it('after deleteMaps (bundle stamped, no maps) nothing is wrong', async () => { put('app.js', `console.log(1);${stamp(ID_A)}`); const report = await run(); - expect(report.findings).toEqual([]); + expect(report.summary).toMatchObject({ errors: 0, warnings: 0 }); + expect(ids(report)).toEqual(['env.token-source']); expect(doctorExitCode(report)).toBe(0); expect(doctorExitCode(report, true)).toBe(0); }); @@ -94,17 +121,25 @@ describe('diagnoseBuildOutput', () => { expect(ids(asFile)).toEqual(['output.dir-missing']); }); - it('output.no-js: a directory with no scripts (and node_modules/src/dot dirs are not searched)', async () => { + it('output.no-js: a directory with no scripts; node_modules and .git are never searched', async () => { put('index.html', ''); put('node_modules/x/y.js', 'x'); - put('src/z.js', 'x'); - put('.hidden/h.js', 'x'); + put('.git/z.js', 'x'); const report = await run(); expect(ids(report)).toContain('output.no-js'); expect(sev(report, 'output.no-js')).toBe('error'); expect(report.summary.bundles).toBe(0); }); + it('preserveModules-style layouts (dist/src/a.js, dist/test/b.js, dot-dirs) are walked, not dropped', async () => { + put('src/a.js', `a${stamp(ID_A)}`); + put('test/b.js', `b${stamp(ID_B)}`); + put('.hidden/c.js', 'c'); + const report = await run(); + expect(report.summary.bundles).toBe(3); + expect(ids(report)).not.toContain('output.no-js'); + }); + it('stamp.missing-debug-id: an unstamped bundle WITH a map is an error', async () => { put('app.js', 'console.log(1);\n//# sourceMappingURL=app.js.map'); put('app.js.map', mapJson()); @@ -194,15 +229,20 @@ describe('diagnoseBuildOutput', () => { }); }); - it('map.pointer-dangling: the pointer names a map that is not there; hidden maps are noted', async () => { + it('map.pointer-dangling: a note when the maps were removed on purpose; a warning otherwise', async () => { put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); put('b.js', `b\n//# sourceMappingURL=https://cdn.example/b.js.map${stamp(ID_B)}`); - const report = await run(); - const found = report.findings.find((f) => f.id === 'map.pointer-dangling'); - expect(found).toMatchObject({ - severity: 'warning', - details: { pointers: ['a.js -> a.js.map'] }, - }); + const note = await run(); + const found = note.findings.find((f) => f.id === 'map.pointer-dangling'); + expect(found).toMatchObject({ severity: 'info', details: { pointers: ['a.js -> a.js.map'] } }); + expect(doctorExitCode(note, true)).toBe(0); + // a map file elsewhere in the output: the removal was not complete / deliberate + put('other.css.map', mapJson()); + expect(sev(await run(), 'map.pointer-dangling')).toBe('warning'); + rmSync(join(dist, 'other.css.map')); + // an unstamped bundle: nothing says the removal was deliberate + put('c.js', 'c'); + expect(sev(await run(), 'map.pointer-dangling')).toBe('warning'); }); it('a pointer to a map in another directory resolves relative to the bundle', async () => { @@ -433,14 +473,24 @@ describe('diagnoseBuildOutput', () => { }); describe('environment', () => { - it('env.token-missing is an error and never echoes a token; the source is not printed either', async () => { + it('env.token-missing is a warning; the token value is never printed, only where it came from', async () => { goodPair(); const report = await run({ env: {} }); - expect(report.findings.find((f) => f.id === 'env.token-missing')?.severity).toBe('error'); + expect(report.findings.find((f) => f.id === 'env.token-missing')?.severity).toBe('warning'); + expect(ids(report)).not.toContain('env.token-source'); const withToken = await run({ appToken: 'super-secret' }); expect(JSON.stringify(withToken)).not.toContain('super-secret'); expect(JSON.stringify(withToken)).not.toContain('secret-token-value'); expect(ids(withToken)).not.toContain('env.token-missing'); + expect(withToken.findings.find((f) => f.id === 'env.token-source')).toMatchObject({ + severity: 'info', + details: { source: 'option' }, + }); + const fromEnv = await run(); + expect(fromEnv.findings.find((f) => f.id === 'env.token-source')?.details).toEqual({ + source: 'env', + }); + expect(JSON.stringify(fromEnv)).not.toContain('secret-token-value'); // whitespace-only counts as unset expect(ids(await run({ env: { BUGSEE_APP_TOKEN: ' ' } }))).toContain('env.token-missing'); expect(ids(await run({ env: {}, appToken: ' ' }))).toContain('env.token-missing'); @@ -484,11 +534,26 @@ describe('diagnoseBuildOutput', () => { }); }); - it('walks only MAX_WALK_DEPTH levels down', async () => { + it('an output directory is walked at any depth', async () => { put('a/b/c/d/e/f/g/h/deep.js', 'x'); put('a/b/c/d/e/f/ok.js', 'x'); const report = await run(); - expect(report.summary.bundles).toBe(1); + expect(report.summary.bundles).toBe(2); + }); + + it('only a directory that is (or contains) the project root is fenced and depth-capped', async () => { + put('a/b/c/d/e/f/g/h/deep.js', 'x'); + put('a/ok.js', 'x'); + put('src/s.js', 'x'); + put('.cache/c.js', 'x'); + const here = process.cwd(); + process.chdir(dist); + try { + const report = await run({ skipEnv: true }); + expect(report.summary.bundles).toBe(1); + } finally { + process.chdir(here); + } }); it('a map pointer that resolves to a directory is skipped, not a crash', async () => { @@ -532,7 +597,7 @@ describe('diagnoseBuildOutput', () => { it('every check ID is unique and namespaced', () => { expect(new Set(DOCTOR_CHECK_IDS).size).toBe(DOCTOR_CHECK_IDS.length); for (const id of DOCTOR_CHECK_IDS) { - expect(id).toMatch(/^(output|stamp|map|sri|build|env)\.[a-z-]+$/); + expect(id).toMatch(/^(output|stamp|map|sri|build|env|doctor)\.[a-z-]+$/); } }); }); diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts index 3a4911d3a..d70ef8a02 100644 --- a/packages/bundler-plugin-core/src/doctor.ts +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -7,14 +7,15 @@ import { createHash } from 'node:crypto'; import type { Dirent } from 'node:fs'; import { existsSync } from 'node:fs'; -import { readdir, readFile, stat } from 'node:fs/promises'; -import nodePath, { dirname, isAbsolute, join, relative, resolve } from 'node:path'; +import { lstat, readdir, readFile, stat } from 'node:fs/promises'; +import nodePath, { dirname, join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { findAppIdentity } from './app-identity'; import { readDebugId } from './debug-ids'; import { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; import type { EnvRecord } from './run-cli'; import { findIntegrityMismatches, findSriProtectedScripts } from './sri'; -import { MAX_WALK_DEPTH, NEVER_WALK } from './stamp-files'; +import { isProjectRootOrAbove, MAX_WALK_DEPTH, NEVER_WALK } from './stamp-files'; import { localPointerTarget } from './verify-stamp'; /** Bumped on any incompatible change to `DoctorReport`; the Rust command emits the same number. */ @@ -44,6 +45,8 @@ export interface DoctorReport { /** Check IDs that ran and found nothing wrong. */ passed: string[]; findings: DoctorFinding[]; + /** Check IDs dropped by `ignore`; omitted when none were. */ + ignored?: string[]; } export interface DoctorOptions { @@ -59,9 +62,21 @@ export interface DoctorOptions { maxMapBytes?: number; /** Skip the `env.*` checks (an output-only audit, e.g. in a container with no token). */ skipEnv?: boolean; + /** + * The directory is (about to be) served to the public: leftover `.map` files are then a WARNING (they expose + * source) instead of a note. Off by default so `--strict` works straight after a plugin run. + */ + deployed?: boolean; + /** Check IDs to drop from the report (repeatable `--ignore`). */ + ignore?: readonly string[]; + /** A script larger than this many bytes is not read (default 512 MiB). */ + maxBundleBytes?: number; } const DEFAULT_MAX_MAP_BYTES = 50 * 1024 * 1024; +const DEFAULT_MAX_BUNDLE_BYTES = 512 * 1024 * 1024; +/** Files read at once: bounds open handles and the bytes held in memory. */ +const READ_CONCURRENCY = 16; const BUNDLE = /\.[cm]?js$/; const MAP = /\.map$/; /** The global the runtime stub writes the id into (`@bugsee/browser` reads it at crash time). */ @@ -72,6 +87,7 @@ const MAX_LISTED = 5; export const DOCTOR_CHECK_IDS = [ 'output.dir-missing', 'output.no-js', + 'output.unreadable', 'stamp.missing-debug-id', 'stamp.missing-registration', 'stamp.map-id-mismatch', @@ -86,15 +102,19 @@ export const DOCTOR_CHECK_IDS = [ 'map.sources-content', 'map.sources-unresolvable', 'map.too-large', + 'map.unreadable', + 'map.pointer-outside-dir', 'map.public-leftover', 'sri.unstamped-hazard', 'sri.mismatch', 'sri.outside-dir', 'build.dev-bundle', + 'env.token-source', 'env.token-missing', 'env.version-unresolved', 'env.build-unresolved', 'env.node-env-development', + 'doctor.internal-error', ] as const; export type DoctorCheckId = (typeof DOCTOR_CHECK_IDS)[number]; @@ -103,25 +123,40 @@ const posix = (path: string): string => path.split('\\').join('/'); /** `bundle.js.map` -> the same name as written in the report; always relative to `dir`. */ const rel = (dir: string, path: string): string => posix(relative(dir, path)); -async function walk(dir: string, depth = 0): Promise { - if (depth > MAX_WALK_DEPTH) { - return []; - } - let entries: Dirent[]; - try { - entries = await readdir(dir, { withFileTypes: true }); - } catch { - return []; - } +/** + * Every script and map under `root`. An output directory is walked in full (Rollup `preserveModules` writes + * `dist/src/*.js`; a build may emit `dist/test/`), skipping only `node_modules` and `.git`; the fence on + * `src`/`test`/dot-directories and the depth cap apply ONLY when `root` is the project root or above, where + * they keep the walk out of the source tree. Iterative, and never spreads a result list (a directory with + * 100k files must not overflow the call stack). + */ +export async function walk(root: string): Promise { + const fenced = await isProjectRootOrAbove(root); 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 walk(full, depth + 1))); + const pending: Array<{ dir: string; depth: number }> = [{ dir: root, depth: 0 }]; + for (let next = pending.pop(); next !== undefined; next = pending.pop()) { + if (fenced && next.depth > MAX_WALK_DEPTH) { + continue; + } + let entries: Dirent[]; + try { + entries = await readdir(next.dir, { withFileTypes: true }); + } catch { + continue; + } + for (const entry of entries) { + const full = join(next.dir, entry.name); + if (entry.isDirectory()) { + const skip = + entry.name === 'node_modules' || + entry.name === '.git' || + (fenced && (NEVER_WALK.has(entry.name) || entry.name.startsWith('.'))); + if (!skip) { + pending.push({ dir: full, depth: next.depth + 1 }); + } + } else if (entry.isFile() && (BUNDLE.test(entry.name) || MAP.test(entry.name))) { + found.push(full); } - } else if (entry.isFile() && (BUNDLE.test(entry.name) || MAP.test(entry.name))) { - found.push(full); } } return found.sort(); @@ -143,6 +178,12 @@ interface ParsedMap { } function parseMap(text: string): ParsedMap | { ok: false; why: string } { + if (text.startsWith('\uFEFF')) { + return { + ok: false, + why: 'not valid JSON: it starts with a UTF-8 byte order mark (BOM), which the upload rejects', + }; + } let parsed: unknown; try { parsed = JSON.parse(text); @@ -160,19 +201,78 @@ function parseMap(text: string): ParsedMap | { ok: false; why: string } { /** Sources that name no file on disk by construction (bundler runtime, virtual modules). */ const VIRTUAL_SOURCE = /^(webpack\/|\(webpack\)|\0|<|rollup:|vite\/)|\0/; -/** Resolve a map `sources` entry against the map's directory and `sourceRoot`, as a debugger would. */ -function sourcePath(mapDir: string, sourceRoot: string, source: string): string | undefined { +/** + * Resolve a map `sources` entry as a debugger would. `file://` URLs follow `fileURLToPath` (so `file:///C:/x` + * is `C:\x` on Windows and a bad escape is "unknowable", not an exception). A bundler-scheme path + * (`webpack://app/./src/x.ts`) is relative to the PROJECT root, not to the map. Anything else is resolved from + * the map's directory and its `sourceRoot`. Undefined means "names no file on disk" (virtual / unparseable). + */ +export function sourcePath( + mapDir: string, + sourceRoot: string, + source: string, + projectRoot: string = mapDir, + api: typeof nodePath = nodePath, +): string | undefined { let path = source; - if (/^file:\/\//.test(path)) { - path = decodeURIComponent(path.replace(/^file:\/\/(?=\/)/, '').replace(/^file:\/\//, '')); - } else if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path)) { + let fromProject = false; + if (/^file:\/\//i.test(path)) { + try { + return fileURLToPath(path, api === nodePath.win32 ? { windows: true } : undefined); + } catch { + return undefined; + } + } + if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path)) { // `webpack://app/./src/x.ts` and friends: the scheme/namespace is not a directory; drop it. path = path.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*\//i, ''); + fromProject = true; } if (VIRTUAL_SOURCE.test(path) || path === '') { return undefined; } - return isAbsolute(path) ? path : resolve(mapDir, sourceRoot, path); + if (api.isAbsolute(path)) { + return path; + } + return fromProject ? api.resolve(projectRoot, path) : api.resolve(mapDir, sourceRoot, path); +} + +type ReadResult = + | { ok: true; bytes: Buffer } + | { ok: false; reason: string; tooLarge?: { size: number } }; + +/** + * Read a REGULAR file of at most `limit` bytes. `lstat` first, so a FIFO, a device (`/dev/zero`) or a symlink + * is never opened, and the size is judged before a single byte is read. A failure is a value, not a throw. + */ +async function readRegular(path: string, limit: number): Promise { + try { + const info = await lstat(path); + if (!info.isFile()) { + return { + ok: false, + reason: info.isSymbolicLink() ? 'is a symbolic link' : 'is not a regular file', + }; + } + if (info.size > limit) { + return { ok: false, reason: 'is too large to read', tooLarge: { size: info.size } }; + } + return { ok: true, bytes: await readFile(path) }; + } catch (error) { + return { + ok: false, + reason: `could not be read (${(error as NodeJS.ErrnoException).code ?? 'error'})`, + }; + } +} + +/** Whether `target` is `root` itself or inside it. */ +function isInside(root: string, target: string): boolean { + const path = relative(root, target); + return ( + path === '' || + !(path === '..' || path.startsWith(`..${nodePath.sep}`) || nodePath.isAbsolute(path)) + ); } const sha = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex'); @@ -217,6 +317,29 @@ export async function diagnoseBuildOutput( dirInput: string, options: DoctorOptions = {}, ): Promise { + try { + return await diagnose(dirInput, options); + } catch (error) { + // The contract is "never throws": whatever went wrong is the finding. + return finish( + resolve(String(dirInput)), + [ + { + id: 'doctor.internal-error', + severity: 'error', + message: `The doctor failed unexpectedly: ${error instanceof Error ? error.message : String(error)}`, + fix: 'This is a bug in the doctor; re-run with --json and report it with the directory layout.', + }, + ], + 0, + 0, + [], + options.ignore, + ); + } +} + +async function diagnose(dirInput: string, options: DoctorOptions): Promise { const dir = resolve(dirInput); const findings: DoctorFinding[] = []; const failed = new Set(); @@ -226,6 +349,8 @@ export async function diagnoseBuildOutput( }; const env = options.env ?? (process.env as EnvRecord); const maxMapBytes = options.maxMapBytes ?? DEFAULT_MAX_MAP_BYTES; + const maxBundleBytes = options.maxBundleBytes ?? DEFAULT_MAX_BUNDLE_BYTES; + const projectRoot = resolve(options.projectRoot ?? process.cwd()); let isDir = false; try { @@ -240,7 +365,7 @@ export async function diagnoseBuildOutput( message: `${dir} does not exist or is not a directory.`, fix: 'Run the build first, and pass the bundler output directory (e.g. dist, build, .output/public).', }); - return finish(dir, findings, 0, 0, []); + return finish(dir, findings, 0, 0, [], options.ignore); } const files = await walk(dir); @@ -250,32 +375,50 @@ export async function diagnoseBuildOutput( add({ id: 'output.no-js', severity: 'error', - message: `No .js/.cjs/.mjs files found under ${dir} (node_modules, src, test and dot-directories are not searched).`, + message: `No .js/.cjs/.mjs files found under ${dir} (node_modules and .git are not searched).`, fix: 'Point the doctor at the bundler output directory, not the project root or a source tree.', }); } const mapSet = new Set(maps); const claimedMaps = new Set(); - const stampedIds = new Map>(); + const stampedIds = new Map>(); let stamped = 0; - const unstamped: string[] = []; + const unstamped = new Set(); const unstampedWithoutMap: string[] = []; const noRegistration: string[] = []; const dangling: string[] = []; + const outsideDir: string[] = []; const devBundles: string[] = []; - const inline: string[] = []; + const inline = new Set(); const hidden: string[] = []; - const bundleIds = new Map(); + const unreadable: string[] = []; + + // Reads happen in bounded batches; analysis stays sequential so findings keep a deterministic order. + const reads = new Map(); + const readBatch = async (batch: readonly string[]): Promise => { + const results = await Promise.all(batch.map((path) => readRegular(path, maxBundleBytes))); + batch.forEach((path, i) => { + reads.set(path, results[i] as ReadResult); + }); + }; - for (const bundle of bundles) { + for (let at = 0; at < bundles.length; at++) { + if (at % READ_CONCURRENCY === 0) { + reads.clear(); + await readBatch(bundles.slice(at, at + READ_CONCURRENCY)); + } + const bundle = bundles[at] as string; const name = rel(dir, bundle); - const bytes = await readFile(bundle); - const code = bytes.toString('utf8'); + const read = reads.get(bundle) as ReadResult; + if (!read.ok) { + unreadable.push(`${name} ${read.reason}`); + continue; + } + const code = read.bytes.toString('utf8'); const id = readDebugId(code); - bundleIds.set(bundle, id); - if (/\/\/# sourceURL=webpack-internal:\/\/\/|webpack-internal:\/\/\//.test(code)) { + if (code.includes('webpack-internal:///')) { devBundles.push(name); } @@ -284,13 +427,22 @@ export async function diagnoseBuildOutput( let mapPath: string | undefined; if (pointer !== undefined && pointer !== '') { if (/^data:/i.test(pointer)) { - inline.push(name); + inline.add(name); } else { // The pairing rule the stamp itself uses (verify-stamp.ts): a LOCAL pointer, resolved from the // bundle's directory; remote / root-absolute / malformed pointers pair nothing. const target = localPointerTarget(bundle, code, nodePath); if (target !== undefined) { - if (mapSet.has(target) || existsSync(target)) { + if (!isInside(dir, target)) { + // Never read it: a pointer can name `/dev/zero`, a FIFO or someone else's file. + outsideDir.push(`${name} -> ${pointer}`); + } else if ( + mapSet.has(target) || + (await lstat(target).then( + () => true, + () => false, + )) + ) { mapPath = target; } else { dangling.push(`${name} -> ${pointer}`); @@ -306,14 +458,14 @@ export async function diagnoseBuildOutput( } if (id === undefined) { - unstamped.push(name); - if (mapPath === undefined && !inline.includes(name)) { + unstamped.add(name); + if (mapPath === undefined && !inline.has(name)) { unstampedWithoutMap.push(name); } } else { stamped++; const list = stampedIds.get(id) ?? []; - list.push({ file: name, hash: sha(bytes) }); + list.push({ file: name, path: bundle }); stampedIds.set(id, list); if (!code.includes(REGISTRATION)) { noRegistration.push(name); @@ -323,13 +475,12 @@ export async function diagnoseBuildOutput( if (mapPath !== undefined) { claimedMaps.add(mapPath); const mapName = rel(dir, mapPath); - let mapBytes: Buffer; - try { - mapBytes = await readFile(mapPath); - } catch { + const mapRead = await readRegular(mapPath, maxMapBytes); + if (!mapRead.ok) { + reportUnreadableMap(mapName, mapRead); continue; } - const parsed = parseMap(mapBytes.toString('utf8')); + const parsed = parseMap(mapRead.bytes.toString('utf8')); if (!parsed.ok) { add({ id: 'map.invalid', @@ -368,9 +519,9 @@ export async function diagnoseBuildOutput( details: { mapDebugId: parsed.debugId }, }); // Counted once as unstamped above; do not double report below. - unstamped.splice(unstamped.indexOf(name), 1); + unstamped.delete(name); } - validateMap(mapPath, mapName, mapBytes.length, parsed.json); + validateMap(mapPath, mapName, parsed.json); } } @@ -378,32 +529,48 @@ export async function diagnoseBuildOutput( for (const map of maps) { if (!claimedMaps.has(map)) { const mapName = rel(dir, map); - try { - const bytes = await readFile(map); - const parsed = parseMap(bytes.toString('utf8')); - if (!parsed.ok) { - add({ - id: 'map.invalid', - severity: 'error', - file: mapName, - message: `${mapName} is ${parsed.why}.`, - fix: 'Check the build is not truncating or post-processing the map; rebuild.', - }); - } else { - validateMap(map, mapName, bytes.length, parsed.json); - } - } catch { - // unreadable: skip + const mapRead = await readRegular(map, maxMapBytes); + if (!mapRead.ok) { + reportUnreadableMap(mapName, mapRead); + continue; + } + const parsed = parseMap(mapRead.bytes.toString('utf8')); + if (!parsed.ok) { + add({ + id: 'map.invalid', + severity: 'error', + file: mapName, + message: `${mapName} is ${parsed.why}.`, + fix: 'Check the build is not truncating or post-processing the map; rebuild.', + }); + } else { + validateMap(map, mapName, parsed.json); } } } - function validateMap( - mapPath: string, - mapName: string, - size: number, - json: Record, - ): void { + function reportUnreadableMap(mapName: string, read: Extract): void { + if (read.tooLarge !== undefined) { + add({ + id: 'map.too-large', + severity: 'warning', + file: mapName, + message: `${mapName} is ${(read.tooLarge.size / 1024 / 1024).toFixed(1)} MiB (limit checked: ${(maxMapBytes / 1024 / 1024).toFixed(0)} MiB), so it was not read or validated; the upload may be slow or rejected.`, + fix: 'Split the bundle, strip sourcesContent (`stripSourcesContent`) or exclude vendor chunks; raise --max-map-mb to validate it.', + details: { bytes: read.tooLarge.size, limit: maxMapBytes }, + }); + } else { + add({ + id: 'map.unreadable', + severity: 'error', + file: mapName, + message: `${mapName} ${read.reason}, so it cannot be validated or uploaded.`, + fix: 'Make it a regular file inside the output directory (no symlink, FIFO or device).', + }); + } + } + + function validateMap(mapPath: string, mapName: string, json: Record): void { if (json.version !== 3) { add({ id: 'map.invalid', @@ -425,16 +592,6 @@ export async function diagnoseBuildOutput( }); return; } - if (size > maxMapBytes) { - add({ - id: 'map.too-large', - severity: 'warning', - file: mapName, - message: `${mapName} is ${(size / 1024 / 1024).toFixed(1)} MiB (limit checked: ${(maxMapBytes / 1024 / 1024).toFixed(0)} MiB); the upload may be slow or rejected.`, - fix: 'Split the bundle, strip sourcesContent (`stripSourcesContent`) or exclude vendor chunks.', - details: { bytes: size, limit: maxMapBytes }, - }); - } const content = Array.isArray(json.sourcesContent) ? (json.sourcesContent as unknown[]) : []; const missing = sources.filter((_, i) => typeof content[i] !== 'string').map(String); if (missing.length === 0) { @@ -449,7 +606,7 @@ export async function diagnoseBuildOutput( const sourceRoot = typeof json.sourceRoot === 'string' ? json.sourceRoot : ''; const mapDir = dirname(mapPath); const unresolved = missing.filter((source) => { - const path = sourcePath(mapDir, sourceRoot, source); + const path = sourcePath(mapDir, sourceRoot, source, projectRoot); return path !== undefined && !existsSync(path); }); if (unresolved.length > 0) { @@ -473,9 +630,18 @@ export async function diagnoseBuildOutput( } // --- aggregate findings ------------------------------------------------------------------------- + const withoutMap = new Set(unstampedWithoutMap); + if (unreadable.length > 0) { + add({ + id: 'output.unreadable', + severity: 'error', + message: `${unreadable.length} script(s) could not be read (${unreadable.slice(0, MAX_LISTED).join('; ')}${unreadable.length > MAX_LISTED ? '; …' : ''}); they were not checked.`, + fix: 'Make them regular files under the size limit, or exclude them from the output directory.', + details: { files: unreadable }, + }); + } for (const name of unstamped) { - const hasMap = !unstampedWithoutMap.includes(name); - if (hasMap || inline.includes(name)) { + if (!withoutMap.has(name)) { add({ id: 'stamp.missing-debug-id', severity: 'error', @@ -503,17 +669,25 @@ export async function diagnoseBuildOutput( details: { files: noRegistration }, }); } - if (stamped > 0 && unstamped.length > 0) { + if (stamped > 0 && unstamped.size > 0) { add({ id: 'stamp.mixed', severity: 'warning', - message: `${stamped} bundle(s) are stamped but ${unstamped.length} are not (${unstamped.slice(0, MAX_LISTED).join(', ')}${unstamped.length > MAX_LISTED ? ', …' : ''}): a partial stamp usually means a second build output or a late-emitted file was missed.`, + message: `${stamped} bundle(s) are stamped but ${unstamped.size} are not (${[...unstamped].slice(0, MAX_LISTED).join(', ')}${unstamped.size > MAX_LISTED ? ', …' : ''}): a partial stamp usually means a second build output or a late-emitted file was missed.`, fix: 'Run the stamp over the whole output directory after the last emit step.', - details: { stamped, unstamped: unstamped.length }, + details: { stamped, unstamped: unstamped.size }, }); } for (const [id, entries] of stampedIds) { - if (new Set(entries.map((e) => e.hash)).size > 1) { + if (entries.length < 2) { + continue; // hashing is only worth it for an id that appears more than once + } + const hashes = new Set(); + for (const entry of entries) { + const read = await readRegular(entry.path, maxBundleBytes); + hashes.add(read.ok ? sha(read.bytes) : `unreadable:${entry.path}`); + } + if (hashes.size > 1) { add({ id: 'stamp.duplicate-debug-id', severity: 'error', @@ -524,14 +698,26 @@ export async function diagnoseBuildOutput( } } if (dangling.length > 0) { + // No map file anywhere and every bundle stamped: the maps were removed on purpose (the plugin's + // `deleteMaps` after a confirmed upload), so the leftover comment is a note, not a defect to fail on. + const removedOnPurpose = maps.length === 0 && unstamped.size === 0; add({ id: 'map.pointer-dangling', - severity: 'warning', - message: `${dangling.length} bundle(s) point at a source map that is not on disk (${dangling.slice(0, MAX_LISTED).join(', ')}${dangling.length > MAX_LISTED ? ', …' : ''}); browsers request it and get a 404.`, + severity: removedOnPurpose ? 'info' : 'warning', + message: `${dangling.length} bundle(s) point at a source map that is not on disk (${dangling.slice(0, MAX_LISTED).join(', ')}${dangling.length > MAX_LISTED ? ', …' : ''}); browsers request it and get a 404${removedOnPurpose ? ' (harmless for symbolication: the maps were removed and the bundles are stamped)' : ''}.`, fix: 'Emit hidden source maps (sourcemap: "hidden") so no pointer is written, or keep the maps until deploy.', details: { pointers: dangling }, }); } + if (outsideDir.length > 0) { + add({ + id: 'map.pointer-outside-dir', + severity: 'warning', + message: `${outsideDir.length} bundle(s) point at a source map outside ${dir} (${outsideDir.slice(0, MAX_LISTED).join(', ')}${outsideDir.length > MAX_LISTED ? ', …' : ''}); it was not read and cannot be paired.`, + fix: 'Emit the map inside the output directory, or check the sourceMappingURL.', + details: { pointers: outsideDir }, + }); + } if (hidden.length > 0) { findings.push({ id: 'map.hidden', @@ -540,13 +726,13 @@ export async function diagnoseBuildOutput( details: { files: hidden }, }); } - if (inline.length > 0) { + if (inline.size > 0) { add({ id: 'map.inline', severity: 'error', - message: `${inline.length} bundle(s) carry an inline (data:) source map (${inline.slice(0, MAX_LISTED).join(', ')}); there is no .map file to upload and the map ships to every visitor.`, + message: `${inline.size} bundle(s) carry an inline (data:) source map (${[...inline].slice(0, MAX_LISTED).join(', ')}); there is no .map file to upload and the map ships to every visitor.`, fix: 'Switch to external hidden maps (Vite `build.sourcemap: "hidden"`, webpack `devtool: "hidden-source-map"`, esbuild `sourcemap: "external"`).', - details: { files: inline }, + details: { files: [...inline] }, }); } if (devBundles.length > 0) { @@ -561,9 +747,9 @@ export async function diagnoseBuildOutput( if (maps.length > 0) { add({ id: 'map.public-leftover', - severity: 'warning', + severity: options.deployed === true ? 'warning' : 'info', message: `${maps.length} .map file(s) are on disk in ${dir}; if this directory is deployed they are served publicly and expose your source.`, - fix: 'Keep `deleteMaps` on (default) so maps are removed after a confirmed upload, or emit hidden maps and exclude *.map from deploys.', + fix: 'Keep `deleteMaps` on (default) so maps are removed after a confirmed upload, or emit hidden maps and exclude *.map from deploys. Run with --deployed on the directory you actually serve to make this a warning.', details: { count: maps.length, files: maps.slice(0, MAX_LISTED).map((m) => rel(dir, m)) }, }); } @@ -573,13 +759,11 @@ export async function diagnoseBuildOutput( if (pinned.length > 0) { const unstampedPinned: typeof pinned = []; for (const p of pinned) { - let code: string; - try { - code = await readFile(p.script, 'utf8'); - } catch { + const read = await readRegular(p.script, maxBundleBytes); + if (!read.ok) { continue; // a pin to a file that is not there is stale, not something stamping would break } - if (readDebugId(code) === undefined) { + if (readDebugId(read.bytes.toString('utf8')) === undefined) { unstampedPinned.push(p); } } @@ -619,7 +803,7 @@ export async function diagnoseBuildOutput( // --- environment ---------------------------------------------------------------------------------- if (options.skipEnv !== true) { - const root = resolve(options.projectRoot ?? process.cwd()); + const root = projectRoot; const fromFile = loadBuildPluginEnv(root); const merged = mergeBuildPluginEnv(env, fromFile.values); const optionToken = options.appToken?.trim() ?? ''; @@ -627,12 +811,31 @@ export async function diagnoseBuildOutput( if (optionToken === '' && envToken === '') { add({ id: 'env.token-missing', - severity: 'error', + severity: 'warning', message: - 'No Bugsee app token is resolvable (BUGSEE_APP_TOKEN, .env.bugsee-build-plugin, or the appToken option): the plugin is disabled and nothing is uploaded.' + + 'No Bugsee app token is resolvable (BUGSEE_APP_TOKEN, .env.bugsee-build-plugin, or the appToken option): the bundler plugin is disabled and uploads nothing (fine if you upload with bugsee-cli by hand).' + (fromFile.problem !== undefined ? ` ${fromFile.problem}` : ''), fix: 'Set BUGSEE_APP_TOKEN in the build environment or in .env.bugsee-build-plugin next to your project.', }); + } else { + // Where it came from, never the value: the same precedence the plugin applies (option, env, file). + const source = + optionToken !== '' + ? ('option' as const) + : (env.BUGSEE_APP_TOKEN?.trim() ?? '') !== '' + ? ('env' as const) + : ('env-file' as const); + const label = { + option: 'the appToken option', + env: 'the BUGSEE_APP_TOKEN environment variable', + 'env-file': '.env.bugsee-build-plugin', + }[source]; + findings.push({ + id: 'env.token-source', + severity: 'info', + message: `The app token comes from ${label}.`, + details: { source }, + }); } const identity = findAppIdentity( { appVersion: options.appVersion, appBuild: options.appBuild }, @@ -672,11 +875,16 @@ export async function diagnoseBuildOutput( (id) => !failed.has(id) && !INFO_ONLY.has(id) && !(options.skipEnv === true && id.startsWith('env.')), ); - return finish(dir, findings, bundles.length, maps.length, passed); + return finish(dir, findings, bundles.length, maps.length, passed, options.ignore); } /** Checks that only ever produce an `info` finding: they are not "passed", they are facts. */ -const INFO_ONLY: ReadonlySet = new Set(['map.hidden', 'map.sources-content']); +const INFO_ONLY: ReadonlySet = new Set([ + 'map.hidden', + 'map.sources-content', + 'env.token-source', + 'doctor.internal-error', +]); function finish( dir: string, @@ -684,7 +892,12 @@ function finish( bundles: number, maps: number, passed: readonly string[], + ignore: readonly string[] = [], ): DoctorReport { + const dropped = ignore.filter((id) => findings.some((f) => f.id === id)); + if (dropped.length > 0) { + findings = findings.filter((f) => !ignore.includes(f.id)); + } const count = (severity: DoctorSeverity): number => findings.filter((f) => f.severity === severity).length; return { @@ -698,8 +911,9 @@ function finish( bundles, maps, }, - passed: [...passed], + passed: passed.filter((id) => !ignore.includes(id)), findings, + ...(dropped.length > 0 ? { ignored: [...new Set(dropped)] } : {}), }; } diff --git a/packages/bundler-plugin-core/src/stamp-files.ts b/packages/bundler-plugin-core/src/stamp-files.ts index a0e2de504..03a7ffc08 100644 --- a/packages/bundler-plugin-core/src/stamp-files.ts +++ b/packages/bundler-plugin-core/src/stamp-files.ts @@ -121,7 +121,9 @@ async function walkStampable(dir: string, fenced: boolean, depth = 0): Promise Date: Mon, 23 Nov 2026 14:19:54 +0500 Subject: [PATCH 22/63] 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 23/63] 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 24/63] 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 25/63] 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 b39a1814d6e5c0fb3e9b56bba46f54c986caa359 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 15:50:53 +0500 Subject: [PATCH 26/63] test(bundler-plugin-core): doctor over real Vite worker builds after merging the frozen in-build-stamping head Co-Authored-By: Claude Sonnet 5.5 --- .../src/doctor.real-build.test.ts | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/packages/bundler-plugin-core/src/doctor.real-build.test.ts b/packages/bundler-plugin-core/src/doctor.real-build.test.ts index b5e8cb7b0..b4cdd6eeb 100644 --- a/packages/bundler-plugin-core/src/doctor.real-build.test.ts +++ b/packages/bundler-plugin-core/src/doctor.real-build.test.ts @@ -229,6 +229,39 @@ describeReal('doctor on real, stamped build output', () => { }); }); +describeReal('doctor on Vite worker builds (stamped by the upload catch-up)', () => { + const workerApp = (name: string, form: 'url' | 'query'): { dir: string; out: string } => { + const app = makeApp(name); + 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; + }; + for (const [label, build] of [ + ['Vite 8 (Rolldown)', viteBuild], + ['Vite 7 (Rollup)', vite7Build], + ] as const) { + for (const form of ['url', 'query'] as const) { + it(`${label}, ${form} worker: main and worker bundles are stamped and their maps carry the same id`, async () => { + const app = workerApp(`doc-worker-${label.replace(/\W+/g, '')}-${form}`, form); + await build(viteConfig(app, [bugseeUnplugin.vite(pluginOptions()) as VitePlugin])); + const report = await doctor(app.out); + expect(report.summary.bundles).toBeGreaterThanOrEqual(2); // main + worker + expect(report.summary.maps).toBe(report.summary.bundles); + expect(idsOf(report, 'error')).toEqual([]); + expect(idsOf(report, 'warning')).toEqual([]); + expect(report.passed).toEqual( + expect.arrayContaining(['stamp.map-id-mismatch', 'stamp.map-no-debug-id', 'stamp.mixed']), + ); + }); + } + } +}); + describeReal('doctor on real, problematic build output', () => { it('an unstamped Vite build (plugin disabled) is an error per bundle', async () => { const app = makeApp('vite8-unstamped'); From 362316751b15275deccf09321cb107bb5aa2b12f Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 16:11:40 +0500 Subject: [PATCH 27/63] =?UTF-8?q?fix(bundler-plugin-core):=20doctor=20roun?= =?UTF-8?q?d=202=20=E2=80=94=20bounded=20manifest=20reads=20inside=20the?= =?UTF-8?q?=20directory=20only,=20stamper=20pointer=20reader,=20case-insen?= =?UTF-8?q?sitive=20extensions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - sri.outside-dir becomes sri.manifest-hashes: only *manifest*.json in the checked directory, read via the bounded regular-file reader (no FIFO/dev-zero hang, nothing read outside the directory) - pointers read with the stamper's lastSourceMappingUrl (unencoded spaces, last wins) - .JS/.MAP match like the stamper; a map shared by bundles is validated once - --key=value forms, warning on unknown --ignore IDs - survivor tests: isInside, last pointer, debug-id case, virtual sources Co-Authored-By: Claude Sonnet 5.5 --- docs/source-maps-usage.md | 2 +- .../src/doctor-cli.test.ts | 40 +++++++++ .../bundler-plugin-core/src/doctor-cli.ts | 25 +++++- .../src/doctor.hardening.test.ts | 77 +++++++++++++++++- .../bundler-plugin-core/src/doctor.test.ts | 37 +++++---- packages/bundler-plugin-core/src/doctor.ts | 81 +++++++++---------- .../bundler-plugin-core/src/verify-stamp.ts | 2 +- 7 files changed, 199 insertions(+), 65 deletions(-) diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 54ad4ba19..3514556ee 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -246,7 +246,7 @@ Typical findings and what to do: | `map.inline` | The map is a `data:` URL inside the bundle: nothing to upload, and it ships to every visitor. | | `map.sources-unresolvable` | No `sourcesContent` and the sources are not on disk: frames will have no source lines. | | `map.public-leftover` | `.map` files are in the directory. A note by default; a warning with `--deployed` (you serve this directory). Keep `deleteMaps` on or exclude `*.map`. | -| `sri.unstamped-hazard` / `sri.mismatch` / `sri.outside-dir` | Subresource Integrity hashes pin these scripts; stamping after hashing makes the browser block them. | +| `sri.unstamped-hazard` / `sri.mismatch` / `sri.manifest-hashes` | Subresource Integrity hashes pin these scripts; stamping after hashing makes the browser block them. | | `env.token-missing` | No app token is visible to the build (a warning): the plugin is disabled and uploads nothing, which is fine if you upload with `bugsee-cli` by hand. `env.token-source` says where a found token comes from, never its value. | The doctor reports which source supplied the token (`env.token-source`: option, environment variable or `.env.bugsee-build-plugin`), never the token. It reads only regular files inside the directory you give it and checks a map's size before reading it. Checks that need the backend (is the map for this ID uploaded? does the deployed URL serve a stamped bundle?) are not part of this command yet. diff --git a/packages/bundler-plugin-core/src/doctor-cli.test.ts b/packages/bundler-plugin-core/src/doctor-cli.test.ts index a25bbd343..b091358a9 100644 --- a/packages/bundler-plugin-core/src/doctor-cli.test.ts +++ b/packages/bundler-plugin-core/src/doctor-cli.test.ts @@ -137,6 +137,46 @@ describe('runDoctorCli', () => { ); }); + it('--key=value forms work for every option that takes a value', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + writeFileSync( + join(dist, 'a.js.map'), + JSON.stringify({ + version: 3, + debugId: ID, + sources: ['a'], + sourcesContent: ['x'.repeat(2000)], + }), + ); + const small = await cli([dist, '--no-env', '--max-map-mb=0.001', '--json']); + expect(JSON.parse(small.out).findings.map((f: { id: string }) => f.id)).toContain( + 'map.too-large', + ); + const ignored = await cli([ + dist, + '--no-env', + '--ignore=map.public-leftover', + `--project-root=${root}`, + '--json', + ]); + expect(JSON.parse(ignored.out).ignored).toEqual(['map.public-leftover']); + expect((await cli([dist, '--max-map-mb='])).code).toBe(2); + }); + + it('`--=x` is an unknown option, not the end-of-options marker', async () => { + const { code, err } = await cli(['--=x', dist]); + expect(code).toBe(2); + expect(err).toContain('Unknown option --'); + }); + + it('an unknown --ignore ID is warned about on stderr but not fatal', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + const { code, err } = await cli([dist, '--no-env', '--ignore', 'map.public-leftvoer']); + expect(code).toBe(0); + expect(err).toContain('map.public-leftvoer is not a known check ID'); + expect((await cli([dist, '--no-env', '--ignore', 'map.public-leftover'])).err).toBe(''); + }); + it('--help prints usage and exits 0', async () => { for (const flag of ['--help', '-h']) { const { code, out } = await cli([flag]); diff --git a/packages/bundler-plugin-core/src/doctor-cli.ts b/packages/bundler-plugin-core/src/doctor-cli.ts index 61db662e4..f7eb836dd 100644 --- a/packages/bundler-plugin-core/src/doctor-cli.ts +++ b/packages/bundler-plugin-core/src/doctor-cli.ts @@ -6,7 +6,12 @@ // Exit codes: 0 ok, 1 warnings only with --strict, 2 errors (or a usage error). import { realpathSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; -import { diagnoseBuildOutput, doctorExitCode, formatDoctorReport } from './doctor'; +import { + DOCTOR_CHECK_IDS, + diagnoseBuildOutput, + doctorExitCode, + formatDoctorReport, +} from './doctor'; import type { EnvRecord } from './run-cli'; export const DOCTOR_USAGE = `Usage: bugsee-sourcemaps-doctor [options] @@ -48,7 +53,14 @@ export async function runDoctorCli(argv: readonly string[], io: DoctorCliIo): Pr return 2; }; for (let i = 0; i < argv.length; i++) { - const arg = argv[i] as string; + let arg = argv[i] as string; + // `--key=value` is the same as `--key value` + let inline: string | undefined; + const eq = arg.startsWith('--') ? arg.indexOf('=') : -1; + if (eq > 2) { + inline = arg.slice(eq + 1); + arg = arg.slice(0, eq); + } if (onlyPositionals) { if (dir !== undefined) { return usage(`Unexpected argument ${arg}`); @@ -68,13 +80,18 @@ export async function runDoctorCli(argv: readonly string[], io: DoctorCliIo): Pr } else if (arg === '--deployed') { deployed = true; } else if (arg === '--project-root' || arg === '--max-map-mb' || arg === '--ignore') { - const value = argv[++i]; - if (value === undefined || value.startsWith('--')) { + const value = inline ?? argv[++i]; + if (value === undefined || (inline === undefined && value.startsWith('--'))) { return usage(`${arg} needs a value`); } if (arg === '--project-root') { projectRoot = value; } else if (arg === '--ignore') { + if (!(DOCTOR_CHECK_IDS as readonly string[]).includes(value)) { + io.stderr( + `Warning: --ignore ${value} is not a known check ID (see DOCTOR_CHECK_IDS); ignored.\n`, + ); + } ignore.push(value); } else { const mb = Number(value); diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index cda60273f..52124c35d 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -27,7 +27,7 @@ beforeEach(() => { mkdirSync(dist); writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'app', version: '1.0.0' })); }); -afterEach(() => rmSync(root, { recursive: true, force: true })); +afterEach(() => rmSync(root, { recursive: true, force: true }), 120_000); // removing 130k files is slow const put = (rel: string, content: string | Buffer): string => { const path = join(dist, rel); @@ -292,3 +292,78 @@ describe('source resolution', () => { expect(sourcePath('C:\\m', '', 'D:\\abs\\a.ts', 'C:\\p', win32)).toBe('D:\\abs\\a.ts'); }); }); + +describe('pointer reading and pairing (round 2)', () => { + it('a pointer with an unencoded space is read whole (the stamper reads to the end of the line)', async () => { + put('a.js', `a\n//# sourceMappingURL=maps/my map.map${stamp(ID_A)}`); + put('maps/my map.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('maps/my map.map'); + }); + + it('the LAST sourceMappingURL comment wins', async () => { + put('a.js', `a\n//# sourceMappingURL=gone.map\n//# sourceMappingURL=real.map${stamp(ID_A)}`); + put('real.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('real.map'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('uppercase extensions are scripts and maps too, like the stamper', async () => { + put('A.JS', `a${stamp(ID_A)}`); + put('A.JS.map', mapJson({ debugId: ID_B })); + put('C.MAP', mapJson()); + const report = await run(); + expect(report.summary).toMatchObject({ bundles: 1, maps: 2 }); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('A.JS.map'); + }); + + it('a map shared by two bundles is validated once', async () => { + put('a.js', `a\n//# sourceMappingURL=shared.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=shared.map${stamp(ID_A)}`); + put('shared.map', mapJson({ debugId: ID_A, sources: [] })); + const report = await run(); + expect(report.findings.filter((f) => f.id === 'map.no-sources')).toHaveLength(1); + }); + + it('isInside: the parent itself is outside, a `..`-prefixed NAME inside the directory is not', async () => { + put('a.js', `a\n//# sourceMappingURL=..${stamp(ID_A)}`); + put('..b/x.map', mapJson({ debugId: ID_B })); + put('b.js', `b\n//# sourceMappingURL=..b/x.map${stamp(ID_B)}`); + const report = await run(); + expect(find(report, 'map.pointer-outside-dir')?.details).toEqual({ pointers: ['a.js -> ..'] }); + expect(ids(report)).not.toContain('map.unreadable'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('virtual sources never name a file; look-alikes do', () => { + for (const virtual of [ + 'webpack/runtime/x', + '(webpack)/buildin/x.js', + '\0virtual', + 'a\0b.ts', + '', + 'rollup:plugin/x', + 'vite/preload-helper.js', + ]) { + expect(sourcePath('/m', '', virtual), virtual).toBeUndefined(); + } + for (const real of ['webpackx/a.ts', 'viteish/a.ts', 'rollupx.ts', 'webpack.config.js']) { + expect(sourcePath('/m', '', real), real).toBe(`/m/${real}`); + } + }); +}); + +describe.skipIf(process.getuid?.() === 0)('an unreadable output directory', () => { + it('reports output.no-js and does not throw', async () => { + put('a.js', 'x'); + chmodSync(dist, 0o000); + try { + const report = await run(); + expect(ids(report)).toContain('output.no-js'); + expect(ids(report)).not.toContain('doctor.internal-error'); + } finally { + chmodSync(dist, 0o700); + } + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.test.ts b/packages/bundler-plugin-core/src/doctor.test.ts index 5d6051cfc..bb3156617 100644 --- a/packages/bundler-plugin-core/src/doctor.test.ts +++ b/packages/bundler-plugin-core/src/doctor.test.ts @@ -14,6 +14,7 @@ import { const ID_A = '11111111-1111-4111-8111-111111111111'; const ID_B = '22222222-2222-4222-8222-222222222222'; +const ID_L = 'abcdef12-3456-4abc-8def-abcdefabcdef'; let root: string; let dist: string; @@ -197,9 +198,10 @@ describe('diagnoseBuildOutput', () => { }); it('accepts the snake_case debug_id spelling in the map and compares case-insensitively', async () => { - put('a.js', `a${stamp(ID_A)}`); - put('a.js.map', mapJson({ debug_id: ID_A.toUpperCase() })); + put('a.js', `a${stamp(ID_L)}`); + put('a.js.map', mapJson({ debug_id: ID_L.toUpperCase() })); const report = await run(); + expect(ID_L.toUpperCase()).not.toBe(ID_L); expect(ids(report)).not.toContain('stamp.map-id-mismatch'); expect(ids(report)).not.toContain('stamp.map-no-debug-id'); }); @@ -450,25 +452,32 @@ describe('diagnoseBuildOutput', () => { expect(report.findings.find((f) => f.id === 'sri.mismatch')?.message).toContain('refuses'); }); - it('sri.outside-dir: a manifest in the dir or an HTML page in the parent pins hashes', async () => { + it('sri.manifest-hashes: a manifest in the directory pins hashes; the parent directory is never read', async () => { put('app.js', `c${stamp(ID_A)}`); put('asset-manifest.json', JSON.stringify({ 'app.js': { integrity: sri('x') } })); put('plain-manifest.json', '{}'); put('readme.txt', 'integrity'); + // a page and a manifest in the PARENT (e.g. a CDN script with integrity) are not this build's business writeFileSync( join(root, 'index.html'), - ``, + ``, ); - writeFileSync(join(root, 'about.html'), '

no pins

'); writeFileSync(join(root, 'pins-manifest.json'), `{"h":"${sri('y')}"}`); const report = await run(); - const found = report.findings.find((f) => f.id === 'sri.outside-dir'); + const found = report.findings.find((f) => f.id === 'sri.manifest-hashes'); expect(found?.severity).toBe('warning'); - expect((found?.details?.files as string[]).sort()).toEqual([ - '../index.html', - '../pins-manifest.json', - 'asset-manifest.json', - ]); + expect(found?.details?.files).toEqual(['asset-manifest.json']); + }); + + it('a FIFO or oversized file named like a manifest is skipped, never opened', async () => { + put('app.js', `c${stamp(ID_A)}`); + const { spawnSync } = await import('node:child_process'); + if (spawnSync('mkfifo', [join(dist, 'x-manifest.json')]).status !== 0) { + return; + } + put('big-manifest.json', `{"integrity":"${'x'.repeat(100)}"}`); + const report = await run({ maxMapBytes: 50 }); + expect(ids(report)).not.toContain('sri.manifest-hashes'); }); }); @@ -566,7 +575,7 @@ describe('diagnoseBuildOutput', () => { const describePerm = process.getuid?.() === 0 ? describe.skip : describe; describePerm('unreadable paths', () => { - it('an unreadable sub-directory contributes nothing; an unreadable parent adds no outside-dir hints', async () => { + it('an unreadable sub-directory contributes nothing; an unreadable parent is harmless', async () => { put('a.js', `a${stamp(ID_A)}`); mkdirSync(join(dist, 'locked')); writeFileSync(join(dist, 'locked', 'x.js'), 'x'); @@ -575,7 +584,7 @@ describe('diagnoseBuildOutput', () => { try { const report = await run({ skipEnv: true }); expect(report.summary.bundles).toBe(1); - expect(ids(report)).not.toContain('sri.outside-dir'); + expect(ids(report)).not.toContain('sri.manifest-hashes'); } finally { chmodSync(root, 0o700); chmodSync(join(dist, 'locked'), 0o700); @@ -587,7 +596,7 @@ describe('diagnoseBuildOutput', () => { const manifest = put('asset-manifest.json', '{"integrity":1}'); chmodSync(manifest, 0o000); try { - expect(ids(await run({ skipEnv: true }))).not.toContain('sri.outside-dir'); + expect(ids(await run({ skipEnv: true }))).not.toContain('sri.manifest-hashes'); } finally { chmodSync(manifest, 0o600); } diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts index d70ef8a02..2b6bf7c0d 100644 --- a/packages/bundler-plugin-core/src/doctor.ts +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -16,7 +16,7 @@ import { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; import type { EnvRecord } from './run-cli'; import { findIntegrityMismatches, findSriProtectedScripts } from './sri'; import { isProjectRootOrAbove, MAX_WALK_DEPTH, NEVER_WALK } from './stamp-files'; -import { localPointerTarget } from './verify-stamp'; +import { lastSourceMappingUrl, localPointerTarget } from './verify-stamp'; /** Bumped on any incompatible change to `DoctorReport`; the Rust command emits the same number. */ export const DOCTOR_SCHEMA_VERSION = 1; @@ -77,8 +77,8 @@ const DEFAULT_MAX_MAP_BYTES = 50 * 1024 * 1024; const DEFAULT_MAX_BUNDLE_BYTES = 512 * 1024 * 1024; /** Files read at once: bounds open handles and the bytes held in memory. */ const READ_CONCURRENCY = 16; -const BUNDLE = /\.[cm]?js$/; -const MAP = /\.map$/; +const BUNDLE = /\.[cm]?js$/i; +const MAP = /\.map$/i; /** The global the runtime stub writes the id into (`@bugsee/browser` reads it at crash time). */ const REGISTRATION = '_bugseeDebugIds'; const MAX_LISTED = 5; @@ -107,7 +107,7 @@ export const DOCTOR_CHECK_IDS = [ 'map.public-leftover', 'sri.unstamped-hazard', 'sri.mismatch', - 'sri.outside-dir', + 'sri.manifest-hashes', 'build.dev-bundle', 'env.token-source', 'env.token-missing', @@ -162,15 +162,6 @@ export async function walk(root: string): Promise { return found.sort(); } -/** The LAST `//# sourceMappingURL=` value a debugger honours. */ -function lastPointer(code: string): string | undefined { - let last: string | undefined; - for (const match of code.matchAll(/^[ \t]*\/\/[#@][ \t]*sourceMappingURL=(\S*)[ \t]*$/gm)) { - last = match[1]; - } - return last; -} - interface ParsedMap { ok: true; json: Record; @@ -277,33 +268,29 @@ function isInside(root: string, target: string): boolean { const sha = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex'); -/** Files in `dir` and its parent that look like a manifest / page and mention integrity hashes. */ -async function integrityOutsideDir(dir: string): Promise { +/** + * `*manifest*.json` files directly in `dir` that mention integrity hashes. Only the checked directory is ever read + * (a page in the parent is not this build's to judge, and may be anything), through the bounded regular-file + * reader, so a FIFO or a `/dev/zero` symlink named like a manifest is skipped, not opened. + */ +async function manifestsWithIntegrity(dir: string, limit: number): Promise { + let names: string[]; + try { + names = await readdir(dir); + } catch { + return []; + } const hits: string[] = []; - for (const base of [dir, dirname(dir)]) { - let names: string[]; - try { - names = await readdir(base); - } catch { + for (const name of names.sort()) { + if (!/manifest.*\.json$/i.test(name)) { continue; } - for (const name of names.sort()) { - const inDir = base === dir; - // HTML inside the dir is the SRI check's own business; a manifest anywhere is not. - const candidate = inDir - ? /manifest.*\.json$/i.test(name) - : /\.html?$|manifest.*\.json$/i.test(name); - if (!candidate) { - continue; - } - try { - const text = await readFile(join(base, name), 'utf8'); - if (/\bintegrity\b|["'](sha(256|384|512))-[A-Za-z0-9+/=]{20,}/i.test(text)) { - hits.push(join(base, name)); - } - } catch { - // unreadable: nothing to say about it - } + const read = await readRegular(join(dir, name), limit); + if ( + read.ok && + /\bintegrity\b|["'](sha(256|384|512))-[A-Za-z0-9+/=]{20,}/i.test(read.bytes.toString('utf8')) + ) { + hits.push(join(dir, name)); } } return hits; @@ -381,6 +368,7 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise(); const claimedMaps = new Set(); const stampedIds = new Map>(); let stamped = 0; @@ -423,7 +411,7 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise.map`. - const pointer = lastPointer(code); + const pointer = lastSourceMappingUrl(code); let mapPath: string | undefined; if (pointer !== undefined && pointer !== '') { if (/^data:/i.test(pointer)) { @@ -571,6 +559,10 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise): void { + if (validated.has(mapPath)) { + return; // a map shared by several bundles is validated once + } + validated.add(mapPath); if (json.version !== 3) { add({ id: 'map.invalid', @@ -790,14 +782,15 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise 0) { + const manifests = await manifestsWithIntegrity(dir, maxMapBytes); + if (manifests.length > 0) { + const names = manifests.map((p) => rel(dir, p)); add({ - id: 'sri.outside-dir', + id: 'sri.manifest-hashes', severity: 'warning', - message: `${outside.map((p) => posix(relative(dir, p))).join(', ')} mention integrity hashes but are outside what the doctor can tie to a script; if they pin these bundles, stamping them afterwards breaks the page.`, - fix: 'Check whether the page / manifest pins hashes of these files; if so make stamping happen before they are computed, or regenerate them.', - details: { files: outside.map((p) => posix(relative(dir, p))) }, + message: `${names.join(', ')} mention integrity hashes the doctor cannot tie to a script; if they pin these bundles, stamping them afterwards breaks the page.`, + fix: 'Check whether the manifest pins hashes of these files; if so make stamping happen before they are computed, or regenerate them. (A page outside this directory is not read: run the doctor on the directory that holds it.)', + details: { files: names }, }); } diff --git a/packages/bundler-plugin-core/src/verify-stamp.ts b/packages/bundler-plugin-core/src/verify-stamp.ts index 59fb99dba..de047fb93 100644 --- a/packages/bundler-plugin-core/src/verify-stamp.ts +++ b/packages/bundler-plugin-core/src/verify-stamp.ts @@ -63,7 +63,7 @@ export function parseScript(code: string): boolean { } /** The value of the LAST sourceMappingURL comment in `code` — the one a debugger honours. */ -function lastSourceMappingUrl(code: string): string | undefined { +export function lastSourceMappingUrl(code: string): string | undefined { let last: string | undefined; for (const match of code.matchAll(SOURCE_MAPPING_URL)) { last = match[1]; From 58558b134124125e5158a3002c86cce2a088c06c Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 17:47:09 +0500 Subject: [PATCH 28/63] fix(bundler-plugin-core): doctor CLI refuses a value on boolean flags; CRLF test; README strict note Co-Authored-By: Claude Sonnet 5.5 --- packages/bundler-plugin-core/README.md | 2 +- .../src/doctor-cli.test.ts | 29 +++++++++++++++++++ .../bundler-plugin-core/src/doctor-cli.ts | 14 ++++++++- .../src/doctor.hardening.test.ts | 12 ++++++++ 4 files changed, 55 insertions(+), 2 deletions(-) diff --git a/packages/bundler-plugin-core/README.md b/packages/bundler-plugin-core/README.md index 1293bf2b9..686ba235f 100644 --- a/packages/bundler-plugin-core/README.md +++ b/packages/bundler-plugin-core/README.md @@ -30,7 +30,7 @@ npx bugsee-sourcemaps-doctor dist --json # machine-readable report (schemaVe npx bugsee-sourcemaps-doctor dist --strict # exit 1 on warnings too ``` -Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks), `--deployed` (the directory is, or is about to be, served: leftover `.map` files become a warning instead of a note), `--ignore ` (drop a check ID; repeatable), `--` (end of options). Straight after a default plugin run `--strict` passes: leftover maps are a note unless `--deployed`, and a pointer to maps removed on purpose from a fully stamped build is a note. +Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks), `--deployed` (the directory is, or is about to be, served: leftover `.map` files become a warning instead of a note), `--ignore ` (drop a check ID; repeatable), `--` (end of options); `--key=value` works for options that take a value, and `--strict=false`-style values on flags are refused. Before the upload (hidden maps still on disk, the plugin will delete them) and after it (maps removed), `--strict` passes on a healthy build; add `--deployed` only when checking the directory you serve. Straight after a default plugin run `--strict` passes: leftover maps are a note unless `--deployed`, and a pointer to maps removed on purpose from a fully stamped build is a note. It checks, each with a stable ID, a severity and a fix hint: the output directory and its JavaScript; the debug-ID comment and `_bugseeDebugIds` registration on every bundle; a matching map with the same ID; `sourceMappingURL` pointers (dangling, hidden, inline); map validity (v3, `sources`, `sourcesContent` embedded or resolvable on disk, size); mixed stamped/unstamped bundles; duplicate IDs across different contents; Subresource Integrity hazards and mismatches (including manifests or pages outside the directory); leftover `.map` files that a deploy would serve; development-mode bundles; and the build environment (token present, version and build resolvable, `NODE_ENV`). The token value is never printed; the report says where it came from (option, environment variable, or `.env.bugsee-build-plugin`), and a missing token is a warning, because uploading by hand is legitimate. The doctor never throws (an internal failure is a `doctor.internal-error` finding), never reads outside the checked directory, never opens a symlink, FIFO or device as a map, and checks a map's size before reading it. Programmatic use: `diagnoseBuildOutput(dir, options)` returns the same report. The backend-assisted checks (is this ID's map uploaded?) are not part of this command; see `docs/source-maps-usage.md` §4. diff --git a/packages/bundler-plugin-core/src/doctor-cli.test.ts b/packages/bundler-plugin-core/src/doctor-cli.test.ts index b091358a9..abea0d3d2 100644 --- a/packages/bundler-plugin-core/src/doctor-cli.test.ts +++ b/packages/bundler-plugin-core/src/doctor-cli.test.ts @@ -169,6 +169,35 @@ describe('runDoctorCli', () => { expect(err).toContain('Unknown option --'); }); + it.each([ + '--json', + '--strict', + '--no-env', + '--deployed', + '--help', + ])('%s takes no value: `=value` is a usage error, not silently dropped', async (flag) => { + const { code, out, err } = await cli([dist, `${flag}=false`]); + expect(code).toBe(2); + expect(out).toBe(''); + expect(err).toContain(`${flag} does not take a value`); + }); + + it('after `--`, an argument containing `=` is a plain directory name', async () => { + const odd = join(root, '--odd=dir'); + mkdirSync(odd); + writeFileSync(join(odd, 'a.js'), stamped); + const here = process.cwd(); + process.chdir(root); + try { + const { code, out } = await cli(['--no-env', '--', '--odd=dir']); + expect(code).toBe(0); + expect(out).toContain('--odd=dir'); + expect(out).toContain('1 bundle(s)'); + } finally { + process.chdir(here); + } + }); + it('an unknown --ignore ID is warned about on stderr but not fatal', async () => { writeFileSync(join(dist, 'a.js'), stamped); const { code, err } = await cli([dist, '--no-env', '--ignore', 'map.public-leftvoer']); diff --git a/packages/bundler-plugin-core/src/doctor-cli.ts b/packages/bundler-plugin-core/src/doctor-cli.ts index f7eb836dd..ba57929e2 100644 --- a/packages/bundler-plugin-core/src/doctor-cli.ts +++ b/packages/bundler-plugin-core/src/doctor-cli.ts @@ -31,6 +31,15 @@ Options: Exit codes: 0 ok, 1 warnings only (with --strict), 2 errors.`; +/** Flags that take no value: `--strict=false` must be refused, not read as `--strict`. */ +const BOOLEAN_FLAGS: ReadonlySet = new Set([ + '--json', + '--strict', + '--no-env', + '--deployed', + '--help', +]); + export interface DoctorCliIo { stdout: (text: string) => void; stderr: (text: string) => void; @@ -56,11 +65,14 @@ export async function runDoctorCli(argv: readonly string[], io: DoctorCliIo): Pr let arg = argv[i] as string; // `--key=value` is the same as `--key value` let inline: string | undefined; - const eq = arg.startsWith('--') ? arg.indexOf('=') : -1; + const eq = !onlyPositionals && arg.startsWith('--') ? arg.indexOf('=') : -1; if (eq > 2) { inline = arg.slice(eq + 1); arg = arg.slice(0, eq); } + if (inline !== undefined && BOOLEAN_FLAGS.has(arg)) { + return usage(`${arg} does not take a value`); + } if (onlyPositionals) { if (dir !== undefined) { return usage(`Unexpected argument ${arg}`); diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index 52124c35d..cb4a3c715 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -367,3 +367,15 @@ describe.skipIf(process.getuid?.() === 0)('an unreadable output directory', () = } }); }); + +describe('CRLF bundles (a Windows toolchain)', () => { + it('an inline map after a CRLF line is still map.inline, and a pointer with CR is paired', async () => { + put('a.js', `a\r\n//# sourceMappingURL=data:application/json;base64,e30=\r\n${stamp(ID_A)}`); + put('b.js', `b\r\n//# sourceMappingURL=maps/b.map\r\n${stamp(ID_B)}`); + put('maps/b.map', mapJson({ debugId: ID_A })); + const report = await run(); + expect(find(report, 'map.inline')?.details).toEqual({ files: ['a.js'] }); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('maps/b.map'); + expect(ids(report)).not.toContain('map.hidden'); + }); +}); From d811c7b9640ed7478f87629201cf7abf69fcbc56 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 17:54:40 +0500 Subject: [PATCH 29/63] fix(bundler-plugin-core): doctor never follows a symlinked directory out; symlinked scripts reported; hard failures not ignorable Co-Authored-By: Claude Sonnet 5.5 --- docs/source-maps-usage.md | 2 +- packages/bundler-plugin-core/README.md | 4 +- .../src/doctor-cli.test.ts | 27 ++++++ .../bundler-plugin-core/src/doctor-cli.ts | 7 +- .../src/doctor.hardening.test.ts | 91 ++++++++++++++++++- packages/bundler-plugin-core/src/doctor.ts | 38 +++++--- 6 files changed, 152 insertions(+), 17 deletions(-) diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 3514556ee..05617bfbe 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -232,7 +232,7 @@ npx bugsee-sourcemaps-doctor dist --strict # warnings fail the step too (exi npx bugsee-sourcemaps-doctor dist --deployed # the directory is served: leftover .map files warn ``` -`--strict` passes straight after a default plugin run (maps removed after upload, bundles stamped). Other options: `--ignore ` (repeatable), `--project-root`, `--max-map-mb`, `--no-env`, `--`. +`--strict` passes straight after a default plugin run (maps removed after upload, bundles stamped). Other options: `--ignore ` (repeatable; hard failures such as `output.no-js` cannot be ignored), `--project-root`, `--max-map-mb`, `--no-env`, `--`. Exit codes: `0` ok, `1` warnings only (with `--strict`), `2` errors. The package is `@bugsee/bundler-plugin-core`; the same report is available in code as `diagnoseBuildOutput(dir, options)`. diff --git a/packages/bundler-plugin-core/README.md b/packages/bundler-plugin-core/README.md index 686ba235f..6bcad7f7a 100644 --- a/packages/bundler-plugin-core/README.md +++ b/packages/bundler-plugin-core/README.md @@ -30,9 +30,9 @@ npx bugsee-sourcemaps-doctor dist --json # machine-readable report (schemaVe npx bugsee-sourcemaps-doctor dist --strict # exit 1 on warnings too ``` -Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks), `--deployed` (the directory is, or is about to be, served: leftover `.map` files become a warning instead of a note), `--ignore ` (drop a check ID; repeatable), `--` (end of options); `--key=value` works for options that take a value, and `--strict=false`-style values on flags are refused. Before the upload (hidden maps still on disk, the plugin will delete them) and after it (maps removed), `--strict` passes on a healthy build; add `--deployed` only when checking the directory you serve. Straight after a default plugin run `--strict` passes: leftover maps are a note unless `--deployed`, and a pointer to maps removed on purpose from a fully stamped build is a note. +Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks), `--deployed` (the directory is, or is about to be, served: leftover `.map` files become a warning instead of a note), `--ignore ` (drop a check ID; repeatable; `output.dir-missing`, `output.no-js` and `doctor.internal-error` cannot be ignored), `--` (end of options); `--key=value` works for options that take a value, and `--strict=false`-style values on flags are refused. Before the upload (hidden maps still on disk, the plugin will delete them) and after it (maps removed), `--strict` passes on a healthy build; add `--deployed` only when checking the directory you serve. Straight after a default plugin run `--strict` passes: leftover maps are a note unless `--deployed`, and a pointer to maps removed on purpose from a fully stamped build is a note. -It checks, each with a stable ID, a severity and a fix hint: the output directory and its JavaScript; the debug-ID comment and `_bugseeDebugIds` registration on every bundle; a matching map with the same ID; `sourceMappingURL` pointers (dangling, hidden, inline); map validity (v3, `sources`, `sourcesContent` embedded or resolvable on disk, size); mixed stamped/unstamped bundles; duplicate IDs across different contents; Subresource Integrity hazards and mismatches (including manifests or pages outside the directory); leftover `.map` files that a deploy would serve; development-mode bundles; and the build environment (token present, version and build resolvable, `NODE_ENV`). The token value is never printed; the report says where it came from (option, environment variable, or `.env.bugsee-build-plugin`), and a missing token is a warning, because uploading by hand is legitimate. The doctor never throws (an internal failure is a `doctor.internal-error` finding), never reads outside the checked directory, never opens a symlink, FIFO or device as a map, and checks a map's size before reading it. Programmatic use: `diagnoseBuildOutput(dir, options)` returns the same report. The backend-assisted checks (is this ID's map uploaded?) are not part of this command; see `docs/source-maps-usage.md` §4. +It checks, each with a stable ID, a severity and a fix hint: the output directory and its JavaScript; the debug-ID comment and `_bugseeDebugIds` registration on every bundle; a matching map with the same ID; `sourceMappingURL` pointers (dangling, hidden, inline); map validity (v3, `sources`, `sourcesContent` embedded or resolvable on disk, size); mixed stamped/unstamped bundles; duplicate IDs across different contents; Subresource Integrity hazards and mismatches (including manifests or pages outside the directory); leftover `.map` files that a deploy would serve; development-mode bundles; and the build environment (token present, version and build resolvable, `NODE_ENV`). The token value is never printed; the report says where it came from (option, environment variable, or `.env.bugsee-build-plugin`), and a missing token is a warning, because uploading by hand is legitimate. The doctor never throws (an internal failure is a `doctor.internal-error` finding), never reads outside the checked directory, never opens a symlink, FIFO or device as a map or script, never follows a symlinked directory out of the checked directory, and checks a map's size before reading it. Programmatic use: `diagnoseBuildOutput(dir, options)` returns the same report. The backend-assisted checks (is this ID's map uploaded?) are not part of this command; see `docs/source-maps-usage.md` §4. The rest of the programmatic API beyond the plugins and the doctor is internal and may change between releases. diff --git a/packages/bundler-plugin-core/src/doctor-cli.test.ts b/packages/bundler-plugin-core/src/doctor-cli.test.ts index abea0d3d2..f0bc207af 100644 --- a/packages/bundler-plugin-core/src/doctor-cli.test.ts +++ b/packages/bundler-plugin-core/src/doctor-cli.test.ts @@ -198,6 +198,33 @@ describe('runDoctorCli', () => { } }); + it('`--project-root=--x` takes the value; `-- --a=b` is one directory (not truncated at `=`)', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + const { code } = await cli([dist, '--project-root=--x', '--json']); + expect(code).toBe(0); + const here = process.cwd(); + process.chdir(root); + try { + mkdirSync(join(root, '--a=b')); + const out = await cli(['--no-env', '--', '--a=b']); + expect(out.out).toContain('--a=b'); + expect(out.out).toContain('0 bundle(s)'); + } finally { + process.chdir(here); + } + }); + + it('--ignore of a hard-failure ID warns that it cannot be ignored and still fails', async () => { + const { code, err } = await cli([ + join(root, 'nope'), + '--no-env', + '--ignore', + 'output.dir-missing', + ]); + expect(code).toBe(2); + expect(err).toContain('output.dir-missing cannot be ignored'); + }); + it('an unknown --ignore ID is warned about on stderr but not fatal', async () => { writeFileSync(join(dist, 'a.js'), stamped); const { code, err } = await cli([dist, '--no-env', '--ignore', 'map.public-leftvoer']); diff --git a/packages/bundler-plugin-core/src/doctor-cli.ts b/packages/bundler-plugin-core/src/doctor-cli.ts index ba57929e2..25caf6242 100644 --- a/packages/bundler-plugin-core/src/doctor-cli.ts +++ b/packages/bundler-plugin-core/src/doctor-cli.ts @@ -11,6 +11,7 @@ import { diagnoseBuildOutput, doctorExitCode, formatDoctorReport, + NON_IGNORABLE_CHECK_IDS, } from './doctor'; import type { EnvRecord } from './run-cli'; @@ -99,7 +100,11 @@ export async function runDoctorCli(argv: readonly string[], io: DoctorCliIo): Pr if (arg === '--project-root') { projectRoot = value; } else if (arg === '--ignore') { - if (!(DOCTOR_CHECK_IDS as readonly string[]).includes(value)) { + if (NON_IGNORABLE_CHECK_IDS.has(value)) { + io.stderr( + `Warning: ${value} cannot be ignored (it means nothing was checked); it stays in the report.\n`, + ); + } else if (!(DOCTOR_CHECK_IDS as readonly string[]).includes(value)) { io.stderr( `Warning: --ignore ${value} is not a known check ID (see DOCTOR_CHECK_IDS); ignored.\n`, ); diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index cb4a3c715..46fcc9dea 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -82,13 +82,14 @@ describe('never throws', () => { expect(report.findings[0]?.message).toContain('boom'); expect(report.summary.errors).toBe(1); expect(report.dir).toBe(dist); - // a non-Error rejection is reported too, and `ignore` still applies + // a hard failure cannot be ignored away const ignored = await diagnoseBuildOutput(dist, { env, projectRoot: root, ignore: ['doctor.internal-error'], }); - expect(ignored.findings).toEqual([]); + expect(ignored.findings.map((f) => f.id)).toEqual(['doctor.internal-error']); + expect(ignored.ignored).toBeUndefined(); }); it('a non-Error throw is stringified', async () => { @@ -379,3 +380,89 @@ describe('CRLF bundles (a Windows toolchain)', () => { expect(ids(report)).not.toContain('map.hidden'); }); }); + +describe('symlinks never lead outside the output directory (round 3)', () => { + const secretMap = (): string => + JSON.stringify({ + version: 3, + debugId: ID_B, + sources: ['TOP-SECRET-SOURCE-PATH.ts'], + sourcesContent: ['TOP-SECRET-CONTENT'], + mappings: 'AAAA', + }); + + it('a pointer through a symlinked DIRECTORY is not read: no outside content in any output', async () => { + const outside = join(root, 'outside'); + mkdirSync(outside); + writeFileSync(join(outside, 'secret.json'), secretMap()); + symlinkSync(outside, join(dist, 'link')); + put('app.js', `a\n//# sourceMappingURL=link/secret.json${stamp(ID_A)}`); + const report = await run(); + expect(find(report, 'map.pointer-outside-dir')?.details).toEqual({ + pointers: ['app.js -> link/secret.json'], + }); + const everything = JSON.stringify(report); + expect(everything).not.toContain('TOP-SECRET'); + expect(everything).not.toContain(ID_B); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + expect(ids(report)).not.toContain('map.sources-unresolvable'); + }); + + it('a pointer through a symlinked directory that stays INSIDE the directory is read normally', async () => { + put('real/x.map', mapJson({ debugId: ID_B })); + symlinkSync(join(dist, 'real'), join(dist, 'alias')); + put('app.js', `a\n//# sourceMappingURL=alias/x.map${stamp(ID_A)}`); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')).toBeDefined(); + }); + + it('a symlinked directory is never descended into by the walk', async () => { + const outside = join(root, 'outside'); + mkdirSync(outside); + writeFileSync(join(outside, 'o.js'), 'x'); + symlinkSync(outside, join(dist, 'linkdir')); + put('a.js', `a${stamp(ID_A)}`); + expect((await walk(dist)).map((f) => f.slice(dist.length + 1))).toEqual(['a.js']); + }); + + it('a symlinked bundle is reported, not silently invisible (no misleading output.no-js)', async () => { + const real = join(root, 'real.js'); + writeFileSync(real, `a${stamp(ID_A)}`); + symlinkSync(real, join(dist, 'app.js')); + const report = await run(); + expect(ids(report)).not.toContain('output.no-js'); + expect(find(report, 'output.unreadable')?.details).toEqual({ + files: ['app.js is a symbolic link'], + }); + expect(report.summary.bundles).toBe(1); + }); + + it('a manifest that is a symlink to a file outside is not read', async () => { + const outside = join(root, 'outside-manifest.json'); + writeFileSync(outside, '{"integrity":"x"}'); + symlinkSync(outside, join(dist, 'asset-manifest.json')); + put('a.js', `a${stamp(ID_A)}`); + expect(ids(await run())).not.toContain('sri.manifest-hashes'); + }); + + it('an uppercase MANIFEST.JSON is still a manifest', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('ASSET-MANIFEST.JSON', '{"integrity":"x"}'); + expect(ids(await run())).toContain('sri.manifest-hashes'); + }); +}); + +describe('--ignore cannot hide a hard failure (round 3)', () => { + it('output.dir-missing, output.no-js and doctor.internal-error stay in the report', async () => { + const missing = await diagnoseBuildOutput(join(root, 'nope'), { + ignore: ['output.dir-missing'], + skipEnv: true, + }); + expect(ids(missing)).toEqual(['output.dir-missing']); + expect(missing.summary.errors).toBe(1); + expect(missing.ignored).toBeUndefined(); + const empty = await run({ ignore: ['output.no-js', 'map.public-leftover'] }); + expect(ids(empty)).toEqual(['output.no-js']); + expect(empty.ignored).toBeUndefined(); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts index 2b6bf7c0d..87b960379 100644 --- a/packages/bundler-plugin-core/src/doctor.ts +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -7,7 +7,7 @@ import { createHash } from 'node:crypto'; import type { Dirent } from 'node:fs'; import { existsSync } from 'node:fs'; -import { lstat, readdir, readFile, stat } from 'node:fs/promises'; +import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises'; import nodePath, { dirname, join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { findAppIdentity } from './app-identity'; @@ -118,6 +118,13 @@ export const DOCTOR_CHECK_IDS = [ ] as const; export type DoctorCheckId = (typeof DOCTOR_CHECK_IDS)[number]; +/** Hard failures: `--ignore` never hides these (it would turn "nothing was checked" into a pass). */ +export const NON_IGNORABLE_CHECK_IDS: ReadonlySet = new Set([ + 'output.dir-missing', + 'output.no-js', + 'doctor.internal-error', +]); + const posix = (path: string): string => path.split('\\').join('/'); /** `bundle.js.map` -> the same name as written in the report; always relative to `dir`. */ @@ -154,7 +161,10 @@ export async function walk(root: string): Promise { if (!skip) { pending.push({ dir: full, depth: next.depth + 1 }); } - } else if (entry.isFile() && (BUNDLE.test(entry.name) || MAP.test(entry.name))) { + } else if ( + (entry.isFile() || entry.isSymbolicLink()) && + (BUNDLE.test(entry.name) || MAP.test(entry.name)) + ) { found.push(full); } } @@ -234,7 +244,8 @@ type ReadResult = /** * Read a REGULAR file of at most `limit` bytes. `lstat` first, so a FIFO, a device (`/dev/zero`) or a symlink - * is never opened, and the size is judged before a single byte is read. A failure is a value, not a throw. + * is never opened (callers pass only paths that cannot run through a symlinked directory: the walk does not + * descend into one, and a pointer target is `realpath`-checked against the output directory first), and the size is judged before a single byte is read. A failure is a value, not a throw. */ async function readRegular(path: string, limit: number): Promise { try { @@ -355,6 +366,7 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise BUNDLE.test(f)); const maps = files.filter((f) => MAP.test(f)); @@ -424,16 +436,19 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise ${pointer}`); - } else if ( - mapSet.has(target) || - (await lstat(target).then( - () => true, - () => false, - )) - ) { + } else if (mapSet.has(target)) { mapPath = target; } else { - dangling.push(`${name} -> ${pointer}`); + // A symlinked DIRECTORY on the way can lead out although the path looks inside: judge the + // real path, never read through it. + const real = await realpath(target).catch(() => undefined); + if (real === undefined) { + dangling.push(`${name} -> ${pointer}`); + } else if (!isInside(realDir, real)) { + outsideDir.push(`${name} -> ${pointer}`); + } else { + mapPath = target; + } } } } @@ -887,6 +902,7 @@ function finish( passed: readonly string[], ignore: readonly string[] = [], ): DoctorReport { + ignore = ignore.filter((id) => !NON_IGNORABLE_CHECK_IDS.has(id)); const dropped = ignore.filter((id) => findings.some((f) => f.id === id)); if (dropped.length > 0) { findings = findings.filter((f) => !ignore.includes(f.id)); From 355d2360d5b61ec284a21e09b5ee40167b01bd4a Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 17:55:06 +0500 Subject: [PATCH 30/63] 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 31/63] 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 32/63] 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 33/63] 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 34/63] 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 35/63] 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 36/63] 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 37/63] 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 4dfd6df678a4bc1e1f98759e42837eddd48e57b1 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 19:47:15 +0500 Subject: [PATCH 38/63] test(bundler-plugin-core): doctor over multi-output and nested-directory Rollup builds Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .../src/doctor.real-build.test.ts | 62 ++++++++++++++++++- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/packages/bundler-plugin-core/src/doctor.real-build.test.ts b/packages/bundler-plugin-core/src/doctor.real-build.test.ts index b4cdd6eeb..f30dc4b95 100644 --- a/packages/bundler-plugin-core/src/doctor.real-build.test.ts +++ b/packages/bundler-plugin-core/src/doctor.real-build.test.ts @@ -66,7 +66,7 @@ const pluginOptions = (extra: object = {}) => ({ ...extra, }); -function makeApp(name: string): { dir: string; out: string } { +function makeApp(name: string, options: { lazy?: boolean } = {}): { dir: string; out: string } { const dir = join(realpathSync(root), name); mkdirSync(dir, { recursive: true }); writeFileSync( @@ -77,7 +77,9 @@ function makeApp(name: string): { dir: string; out: string } { 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'));\nimport('./lazy.js').then((m) => console.log(m.default));\n", + `import { greet } from './greet.js';\nconsole.log(greet('world'));\n${ + options.lazy === false ? '' : "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') }; @@ -262,6 +264,62 @@ describeReal('doctor on Vite worker builds (stamped by the upload catch-up)', () } }); +describeReal('doctor on multi-output and nested-directory Rollup builds', () => { + it('six outputs into one directory (maps kept) are all stamped, paired and clean', async () => { + const app = makeApp('doc-many-outputs', { lazy: false }); + const names = ['a', 'b', 'c', 'd', 'e', 'f']; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions())], + }); + await Promise.all( + names.map((n) => + bundle.write({ + file: join(app.out, `${n}.js`), + format: 'iife', + name: `app_${n}`, + sourcemap: 'hidden', + }), + ), + ); + await bundle.close(); + const report = await doctor(app.out); + expect(report.summary).toMatchObject({ bundles: 6, maps: 6, errors: 0, warnings: 0 }); + expect(report.passed).toEqual( + expect.arrayContaining(['stamp.map-id-mismatch', 'stamp.duplicate-debug-id']), + ); + }); + + it('an output nested inside another: checking the parent walks both and finds no problem', async () => { + const app = makeApp('doc-nested-outputs', { lazy: false }); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions())], + }); + await Promise.all([ + bundle.write({ + dir: app.out, + entryFileNames: 'p.js', + format: 'iife', + name: 'p', + sourcemap: 'hidden', + }), + bundle.write({ + dir: join(app.out, 'b'), + entryFileNames: 'c.js', + format: 'iife', + name: 'c', + sourcemap: 'hidden', + }), + ]); + await bundle.close(); + const parent = await doctor(app.out); + expect(parent.summary).toMatchObject({ bundles: 2, maps: 2, errors: 0, warnings: 0 }); + const nested = await doctor(join(app.out, 'b')); + expect(nested.summary).toMatchObject({ bundles: 1, maps: 1, errors: 0, warnings: 0 }); + }); +}); + describeReal('doctor on real, problematic build output', () => { it('an unstamped Vite build (plugin disabled) is an error per bundle', async () => { const app = makeApp('vite8-unstamped'); From d6551ec0d65e497872a7eba7ce016729ea37558d Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 19:58:36 +0500 Subject: [PATCH 39/63] fix(bundler-plugin-core): doctor SRI check reads each pinned script once, through the guarded reader Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .../src/doctor.hardening.test.ts | 48 +++++++++++++++++++ .../bundler-plugin-core/src/doctor.test.ts | 2 + packages/bundler-plugin-core/src/doctor.ts | 14 +++++- packages/bundler-plugin-core/src/sri.ts | 2 +- 4 files changed, 63 insertions(+), 3 deletions(-) diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index 46fcc9dea..ec84815b6 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -1,6 +1,7 @@ // Robustness of the doctor: it must never throw, never read what it should not, never be quadratic, and must // resolve sources the way the build did. Each test pins one reviewed failure mode. import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; import { chmodSync, mkdirSync, @@ -466,3 +467,50 @@ describe('--ignore cannot hide a hard failure (round 3)', () => { expect(empty.ignored).toBeUndefined(); }); }); + +describe('SRI reads are as guarded as every other read (review thread)', () => { + const sri = (bytes: string | Buffer): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + const page = (src: string, integrity: string): string => + ``; + + it('a pinned script that is a FIFO never hangs the doctor', async () => { + if (spawnSync('mkfifo', [join(dist, 'app.js')]).status !== 0) { + return; + } + put('index.html', page('app.js', sri('x'))); + const report = await run(); + // the walk does not list a FIFO; the point is that the pin does not open it either + expect(ids(report)).toContain('output.no-js'); + expect(ids(report)).not.toContain('sri.mismatch'); + expect(ids(report)).not.toContain('sri.unstamped-hazard'); + }, 10_000); + + it('a pinned symlink to /dev/zero is refused, never read', async () => { + symlinkSync('/dev/zero', join(dist, 'zero.js')); + put('index.html', page('zero.js', sri('x'))); + const report = await run(); + expect(find(report, 'output.unreadable')?.details).toEqual({ + files: ['zero.js is a symbolic link'], + }); + expect(ids(report)).not.toContain('sri.mismatch'); + }, 10_000); + + it('a pinned script reached through a symlinked directory is not read or hashed', async () => { + const outside = join(root, 'outside'); + mkdirSync(outside); + writeFileSync(join(outside, 'app.js'), `x${stamp(ID_A)}`); + symlinkSync(outside, join(dist, 'vendor')); + put('index.html', page('vendor/app.js', sri('something else'))); + const report = await run(); + expect(ids(report)).not.toContain('sri.mismatch'); + expect(ids(report)).not.toContain('sri.unstamped-hazard'); + }); + + it('a pinned regular script whose bytes no longer match is still sri.mismatch (read once)', async () => { + put('app.js', `c${stamp(ID_A)}`); + put('index.html', page('app.js', sri('c'))); + const report = await run(); + expect(find(report, 'sri.mismatch')?.details).toEqual({ scripts: ['app.js'] }); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.test.ts b/packages/bundler-plugin-core/src/doctor.test.ts index bb3156617..68157522c 100644 --- a/packages/bundler-plugin-core/src/doctor.test.ts +++ b/packages/bundler-plugin-core/src/doctor.test.ts @@ -429,6 +429,8 @@ describe('diagnoseBuildOutput', () => { put('index.html', ``); const report = await run(); expect(ids(report)).not.toContain('sri.unstamped-hazard'); + expect(ids(report)).not.toContain('doctor.internal-error'); + expect(report.summary.errors).toBe(0); }); it('a stamped script whose pin matches its bytes is fine', async () => { diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts index 87b960379..fc2a615f4 100644 --- a/packages/bundler-plugin-core/src/doctor.ts +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -14,7 +14,7 @@ import { findAppIdentity } from './app-identity'; import { readDebugId } from './debug-ids'; import { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; import type { EnvRecord } from './run-cli'; -import { findIntegrityMismatches, findSriProtectedScripts } from './sri'; +import { findSriProtectedScripts, passesIntegrity } from './sri'; import { isProjectRootOrAbove, MAX_WALK_DEPTH, NEVER_WALK } from './stamp-files'; import { lastSourceMappingUrl, localPointerTarget } from './verify-stamp'; @@ -765,11 +765,22 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise 0) { const unstampedPinned: typeof pinned = []; + const mismatches: typeof pinned = []; for (const p of pinned) { + // The same guards as every other read: not through a symlinked directory that leads out, and only a + // regular file of bounded size (a FIFO or `/dev/zero` is never opened). The bytes read here are also + // what the integrity check judges, so nothing is read twice. + const real = await realpath(p.script).catch(() => undefined); + if (real === undefined || !isInside(realDir, real)) { + continue; + } const read = await readRegular(p.script, maxBundleBytes); if (!read.ok) { continue; // a pin to a file that is not there is stale, not something stamping would break } + if (!passesIntegrity(p.integrity, read.bytes)) { + mismatches.push(p); + } if (readDebugId(read.bytes.toString('utf8')) === undefined) { unstampedPinned.push(p); } @@ -783,7 +794,6 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise rel(dir, p.script)) }, }); } - const mismatches = await findIntegrityMismatches(dir); if (mismatches.length > 0) { add({ id: 'sri.mismatch', diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index 3641731ba..e6a9811d3 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -167,7 +167,7 @@ type SriAlgorithm = (typeof SRI_ALGORITHMS)[number]; * ignored; of what remains only the STRONGEST algorithm is compared; any one digest of it matching is * enough. A value with no algorithm the browser knows means no check at all. */ -function passesIntegrity(integrity: string, bytes: Buffer): boolean { +export function passesIntegrity(integrity: string, bytes: Buffer): boolean { const byAlgorithm = new Map(); for (const token of integrity.split(/\s+/)) { // `alg-base64[?options]` — the options suffix is allowed by the grammar and has no effect here. From 0f9a3ef446f2e94b1c19f80b21b245e4755525ed Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 20:57:31 +0500 Subject: [PATCH 40/63] 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 ``); + const report = await run(); + expect(find(report, 'sri.mismatch')?.details).toEqual({ scripts: ['app.js'] }); + expect(ids(report)).not.toContain('sri.pin-unreadable'); + }); + + it('a map reached through two names is validated once', async () => { + put('real/x.map', 'not json'); + symlinkSync(join(dist, 'real'), join(dist, 'alias')); + put('a.js', `a\n//# sourceMappingURL=real/x.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=alias/x.map${stamp(ID_B)}`); + const report = await run(); + expect(report.findings.filter((f) => f.id === 'map.invalid')).toHaveLength(1); + }); +}); + +describe('big outputs stay readable (round 4)', () => { + it('sources-content notes: a few are listed, many become ONE finding with counts', async () => { + for (let i = 0; i < 3; i++) { + put(`s${i}.js`, `a${stamp(`0000000${i}-1111-4111-8111-111111111111`)}`); + put(`s${i}.js.map`, mapJson({ debugId: `0000000${i}-1111-4111-8111-111111111111` })); + } + const few = await run(); + expect(few.findings.filter((f) => f.id === 'map.sources-content')).toHaveLength(3); + // 10 notes (2 x the listing cap) are still listed one by one; the 11th folds them into one finding. + for (let i = 3; i < 10; i++) { + const id = `${i.toString(16).padStart(8, '0')}-1111-4111-8111-111111111111`; + put(`s${i}.js`, `a${stamp(id)}`); + put(`s${i}.js.map`, mapJson({ debugId: id })); + } + const ten = await run(); + expect(ten.findings.filter((f) => f.id === 'map.sources-content')).toHaveLength(10); + for (let i = 10; i < 11; i++) { + const id = `${i.toString(16).padStart(8, '0')}-1111-4111-8111-111111111111`; + put(`s${i}.js`, `a${stamp(id)}`); + put(`s${i}.js.map`, mapJson({ debugId: id })); + } + expect((await run()).findings.filter((f) => f.id === 'map.sources-content')).toHaveLength(1); + for (let i = 11; i < 14; i++) { + const id = `${i.toString(16).padStart(8, '0')}-1111-4111-8111-111111111111`; + put(`s${i}.js`, `a${stamp(id)}`); + put(`s${i}.js.map`, mapJson({ debugId: id })); + } + const many = await run(); + const notes = many.findings.filter((f) => f.id === 'map.sources-content'); + expect(notes).toHaveLength(1); + expect(notes[0]?.details).toEqual({ maps: 14, embedded: 14, resolvableOnDisk: 0 }); + expect(notes[0]?.file).toBeUndefined(); + }); + + it('a list of exactly 100 is not capped and carries no total', async () => { + for (let i = 0; i < 100; i++) { + put(`e${i}.js`, `x${i}`); + } + const finding = find(await run(), 'stamp.missing-debug-id'); + expect((finding?.details?.files as string[]).length).toBe(100); + expect(finding?.details).not.toHaveProperty('total'); + }); + + it('long file lists in details are capped, with the total', async () => { + for (let i = 0; i < 130; i++) { + put(`v${i}.js`, `x${i}`); + } + const report = await run(); + const finding = find(report, 'stamp.missing-debug-id'); + expect((finding?.details?.files as string[]).length).toBe(100); + expect(finding?.details?.total).toBe(130); + put('w.js', 'x'); + const exact = await run(); + expect(find(exact, 'stamp.missing-debug-id')?.details?.total).toBe(131); + }); + + it('an oversized page is reported as sri.html-skipped, and the rest of the audit goes on', async () => { + put('a.js', `a${stamp(ID_A)}`); + const big = put('huge.html', ''); + truncateSync(big, 8 * 1024 * 1024 + 1); + const report = await run(); + expect(find(report, 'sri.html-skipped')).toMatchObject({ + severity: 'warning', + details: { files: ['huge.html'] }, + }); + expect(report.summary.bundles).toBe(1); + }); + + it('a page of pathological unterminated tags does not stall the doctor', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('index.html', '', + '', + '', + '', + '', + '', + ''.repeat(20_000); + const started = Date.now(); + expect(findTags(stripComments(text), 'script')).toHaveLength(20_000); + expect(Date.now() - started).toBeLessThan(FAST_MS); + }); + + it('end to end: a page of unterminated repeats is scanned fast and finds nothing', async () => { + const dir = await fixture(); + await writeFile(join(dir, 'index.html'), ''); + await writeFile(join(dir, 'sub', 'huge.html'), ''); + await truncate(join(dir, 'sub', 'huge.html'), MAX_HTML_BYTES + 1); + const scan = await findSriProtectedScriptsDetailed(dir); + expect(scan.scripts.map((s) => s.script)).toEqual([join(dir, 'a.js')]); + expect(scan.skippedPages).toEqual([ + { html: join(dir, 'sub', 'huge.html'), size: MAX_HTML_BYTES + 1 }, + ]); + }); + + it('a page of exactly MAX_HTML_BYTES is scanned', async () => { + const dir = await fixture(); + const tag = ''; + await writeFile(join(dir, 'p.html'), tag + ' '.repeat(MAX_HTML_BYTES - tag.length)); + const scan = await findSriProtectedScriptsDetailed(dir); + expect(scan.skippedPages).toEqual([]); + expect(scan.scripts).toHaveLength(1); + }); +}); diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index e6a9811d3..e00c67e56 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -18,6 +18,10 @@ import { createHash } from 'node:crypto'; import type { Dirent } from 'node:fs'; import { readdir, readFile } from 'node:fs/promises'; import { isAbsolute, join, normalize, resolve, sep } from 'node:path'; +import { readRegularFile } from './safe-read'; + +/** A page larger than this is not scanned (a real page is a few KB): the scan must stay bounded on hostile input. */ +export const MAX_HTML_BYTES = 8 * 1024 * 1024; /** One `'; + await writeFile(join(dir, 'big.html'), tag + ' '.repeat(MAX_HTML_BYTES + 10)); + expect((await findSriProtectedScripts(dir)).map((s) => s.script)).toEqual([join(dir, 'a.js')]); + }); + it('a page of exactly MAX_HTML_BYTES is scanned', async () => { const dir = await fixture(); const tag = ''; diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index e00c67e56..008f290db 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -160,7 +160,9 @@ const walkHtml = async (dir: string, depth = 0): Promise => { * to report. */ export async function findSriProtectedScripts(outDirInput: string): Promise { - return (await findSriProtectedScriptsDetailed(outDirInput)).scripts; + // No page cap here: this is the guard stamping relies on, and a pin it cannot see is a script stamping would + // break. Only the diagnostic (which must stay bounded on hostile input) passes a cap. + return (await findSriProtectedScriptsDetailed(outDirInput, Number.POSITIVE_INFINITY)).scripts; } /** What {@link findSriProtectedScripts} found, and the pages it did not scan because they are larger than {@link MAX_HTML_BYTES}. */ @@ -169,7 +171,10 @@ export interface SriScan { skippedPages: Array<{ html: string; size: number }>; } -export async function findSriProtectedScriptsDetailed(outDirInput: string): Promise { +export async function findSriProtectedScriptsDetailed( + outDirInput: string, + maxHtmlBytes: number = MAX_HTML_BYTES, +): Promise { // Resolved FIRST: a bundler hands us whatever the user configured, and Rollup passes `output.dir` // through verbatim (`'dist'`) while `output.file: 'bundle.js'` resolves to `'.'`. Comparing an // absolute resolved script path against a relative root made every `src="main.js"` look like it @@ -180,7 +185,7 @@ export async function findSriProtectedScriptsDetailed(outDirInput: string): Prom const found: SriProtectedScript[] = []; const skippedPages: SriScan['skippedPages'] = []; for (const html of pages.sort()) { - const read = await readRegularFile(html, MAX_HTML_BYTES); + const read = await readRegularFile(html, maxHtmlBytes); if (!read.ok) { if (read.tooLarge !== undefined) { skippedPages.push({ html, size: read.tooLarge.size }); From 9cea1b1d847eda01537f75d3894e9e465e325ddf Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 14:57:10 +0500 Subject: [PATCH 51/63] fix(nextjs): honour deleteMaps:false and sweep forced maps on the no-pairs path in the webpack plugin; native paths in its tests - discardForcedMaps keeps maps under deleteMaps:false (refusal/abandon paths); the SRI refusal notice says so - the empty-pair return sweeps the forced browser maps too (dry run and deleteMaps:false still exempt) - webpack-plugin.test: native absolute paths for emitted files and pairRecorded fixtures Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- packages/nextjs/src/config/sri.ts | 10 +- .../nextjs/src/config/webpack-plugin.test.ts | 139 ++++++++++++------ packages/nextjs/src/config/webpack-plugin.ts | 11 +- 3 files changed, 114 insertions(+), 46 deletions(-) diff --git a/packages/nextjs/src/config/sri.ts b/packages/nextjs/src/config/sri.ts index c944cc103..fc8583e84 100644 --- a/packages/nextjs/src/config/sri.ts +++ b/packages/nextjs/src/config/sri.ts @@ -56,7 +56,7 @@ export const TURBOPACK_SRI_NOTICE = `this build uses Subresource Integrity (\`ex export const FALLBACK_SRI_NOTICE = ( kind: string, mapsRemoved: boolean, - options: { dryRun?: boolean; removalFailed?: boolean } = {}, + options: { dryRun?: boolean; removalFailed?: boolean; retained?: 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' @@ -65,9 +65,11 @@ export const FALLBACK_SRI_NOTICE = ( ? ' 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}`); + : options.retained === true + ? ` \`deleteMaps: false\` keeps the browser source maps Bugsee turned on. ${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 => diff --git a/packages/nextjs/src/config/webpack-plugin.test.ts b/packages/nextjs/src/config/webpack-plugin.test.ts index 74abe69a1..078338140 100644 --- a/packages/nextjs/src/config/webpack-plugin.test.ts +++ b/packages/nextjs/src/config/webpack-plugin.test.ts @@ -1,7 +1,8 @@ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { join, resolve } from 'node:path'; import { describe, expect, it, vi } from 'vitest'; + import type { BugseeNextContext } from './context'; import { type CompilerLike, @@ -12,6 +13,10 @@ import { type WebpackPluginDeps, } from './webpack-plugin'; +// Native absolute paths: the plugin resolves and joins with the host's path API (win32: `C:\out\.next`). +// Compilation asset names (`../app/page.js`) stay as the bundler reports them. +const p = (path: string): string => resolve(path); + /** * 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 @@ -73,7 +78,7 @@ 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' } }, + options: { output: { path: options.path ?? p('/out/.next/server/chunks') } }, hooks: { thisCompilation: { tap: (_n: string, fn: (c: Compilation) => void) => (onThis = fn) }, afterEmit: { @@ -205,7 +210,7 @@ describe('createNextWebpackPlugin', () => { 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' }); + const fake = fakeCompiler({ path: p('/out/.next/server/chunks') }); createNextWebpackPlugin(context(), 'server', d).apply(fake.compiler); const c = fakeCompilation({ '../app/page.js': 'x', @@ -223,16 +228,16 @@ describe('createNextWebpackPlugin', () => { string, { bundler: unknown; preStamped: boolean; files: Record }, ]; - expect(outDir).toBe('/out/.next/server/chunks'); + expect(outDir).toBe(p('/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', + p('/out/.next/server/app/page.js'), + p('/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', + p('/out/.next/server/app/page.js.map'), + p('/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 }); @@ -240,7 +245,7 @@ describe('createNextWebpackPlugin', () => { it('gives the client the client policy: deleted maps, the build registered', async () => { const d = deps(); - const fake = fakeCompiler({ path: '/out/.next' }); + const fake = fakeCompiler({ path: p('/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); @@ -283,7 +288,7 @@ describe('createNextWebpackPlugin', () => { unknown, { files: { scripts: string[] } }, ]; - expect(options.files.scripts).toEqual(['/out/.next/server/chunks/here.js']); + expect(options.files.scripts).toEqual([p('/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 () => { @@ -513,7 +518,7 @@ describe('createNextWebpackPlugin: the new core contract', () => { : 'plain', ), }); - const fake = fakeCompiler({ path: '/out/.next/server/chunks' }); + const fake = fakeCompiler({ path: p('/out/.next/server/chunks') }); createNextWebpackPlugin(context(), 'server', d).apply(fake.compiler); const c = fakeCompilation({ '../app/page.js': 'x', @@ -539,7 +544,7 @@ describe('createNextWebpackPlugin: the new core contract', () => { 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' }); + const fake = fakeCompiler({ path: p('/o') }); createNextWebpackPlugin(context({ onError }), 'client', d).apply(fake.compiler); const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); fake.startCompilation(c.compilation); @@ -557,7 +562,7 @@ describe('createNextWebpackPlugin: the new core contract', () => { 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' }); + const fake = fakeCompiler({ path: p('/o') }); createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); const c = fakeCompilation({ 'a.js': 'x', 'a.js.map': 'm' }); fake.startCompilation(c.compilation); @@ -583,7 +588,7 @@ describe('createNextWebpackPlugin: the new core contract', () => { bundles: 1, })), }); - const fake = fakeCompiler({ path: '/o' }); + const fake = fakeCompiler({ path: p('/o') }); createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); const c = fakeCompilation( { 'static/a.js': 'x', 'maps/a.js.map': 'm' }, @@ -658,11 +663,11 @@ describe('createNextWebpackPlugin: the new core contract', () => { return true; }), }); - const fake = fakeCompiler({ path: '/out/.next' }); + const fake = fakeCompiler({ path: p('/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']); + expect(seen).toEqual([p('/out/.next/static/a.js'), p('/out/.next/static/a.js.map')]); }); }); @@ -696,7 +701,7 @@ describe('createNextWebpackPlugin: the post-emit fallback on an SRI build', () = 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'); + expect(d.hasSriManifest).toHaveBeenCalledWith(p('/out/.next/server/chunks')); }); it('still falls back without SRI', async () => { @@ -727,7 +732,7 @@ describe('createNextWebpackPlugin: no public maps Bugsee asked for when nothing const run = async (kind: 'client' | 'server', ctx: BugseeNextContext, d: WebpackPluginDeps) => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); try { - const fake = fakeCompiler({ path: '/out/.next' }); + const fake = fakeCompiler({ path: p('/out/.next') }); createNextWebpackPlugin(ctx, kind, d).apply(fake.compiler); const c = fakeCompilation(assets); fake.startCompilation(c.compilation); @@ -745,8 +750,8 @@ describe('createNextWebpackPlugin: no public maps Bugsee asked for when nothing 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(d.remove).toHaveBeenCalledWith(p('/out/.next/static/a.js.map')); + expect(d.remove).toHaveBeenCalledWith(p('/out/.next/static/a.css.map')); expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('were removed')); }); @@ -782,14 +787,14 @@ describe('createNextWebpackPlugin: no public maps Bugsee asked for when nothing await run('client', context({}, { forcedMaps: true }), d); expect(d.upload).toHaveBeenCalledTimes(1); // the sweep tolerates what the upload already deleted (removeFile ignores ENOENT) and takes what is left - expect(d.remove).toHaveBeenCalledWith('/out/.next/static/a.js.map'); + expect(d.remove).toHaveBeenCalledWith(p('/out/.next/static/a.js.map')); }); it('deletes them when the upload ran but was NOT confirmed (contained failure), and when it throws', async () => { const unconfirmed = deps(); // resolves undefined: nothing confirmed await run('client', context({}, { forcedMaps: true }), unconfirmed); - expect(unconfirmed.remove).toHaveBeenCalledWith('/out/.next/static/a.js.map'); - expect(unconfirmed.remove).toHaveBeenCalledWith('/out/.next/static/a.css.map'); + expect(unconfirmed.remove).toHaveBeenCalledWith(p('/out/.next/static/a.js.map')); + expect(unconfirmed.remove).toHaveBeenCalledWith(p('/out/.next/static/a.css.map')); const notUploaded = deps({ upload: vi.fn(async () => ({ uploaded: false }) as never) }); await run('client', context({}, { forcedMaps: true }), notUploaded); @@ -825,7 +830,7 @@ describe('createNextWebpackPlugin: no public maps Bugsee asked for when nothing const d = deps({ stamp: failing() }); const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); try { - const fake = fakeCompiler({ path: '/out/.next' }); + const fake = fakeCompiler({ path: p('/out/.next') }); createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); const c = fakeCompilation({ 'static/a.js': 'x', 'static/orphan.js.map': 'm' }); fake.startCompilation(c.compilation); @@ -834,7 +839,7 @@ describe('createNextWebpackPlugin: no public maps Bugsee asked for when nothing } finally { warn.mockRestore(); } - expect(d.remove).toHaveBeenCalledWith('/out/.next/static/orphan.js.map'); + expect(d.remove).toHaveBeenCalledWith(p('/out/.next/static/orphan.js.map')); }); it('strict: an SRI build whose scripts could not be staged fails (nothing was rewritten or uploaded)', async () => { @@ -851,7 +856,7 @@ describe('createNextWebpackPlugin: no public maps Bugsee asked for when nothing const stampedOne = () => vi.fn(async () => ({ stamped: [], maps: { 'static/a.js': 'static/a.js.map' }, bundles: 1 })); const emitOnlyScript = async (ctx: BugseeNextContext, d: WebpackPluginDeps) => { - const fake = fakeCompiler({ path: '/out/.next' }); + const fake = fakeCompiler({ path: p('/out/.next') }); createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); const c = fakeCompilation({ 'static/a.js': 'x' }); fake.startCompilation(c.compilation); @@ -876,7 +881,7 @@ describe('createNextWebpackPlugin: no public maps Bugsee asked for when nothing bundles: 1, })), }); - const fake = fakeCompiler({ path: '/out/.next' }); + const fake = fakeCompiler({ path: p('/out/.next') }); const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); try { createNextWebpackPlugin(context(), 'client', lostPair).apply(fake.compiler); @@ -1067,6 +1072,58 @@ describe('createNextWebpackPlugin: no public maps Bugsee asked for when nothing expect(own.say).not.toHaveBeenCalled(); }); + it('deleteMaps: false keeps the forced browser maps when stamping is refused or abandoned, and the notice says so', async () => { + const keep = context({ deleteMaps: false }, { sri: true, forcedMaps: true }); + const d = deps({ stamp: failing() }); + await run('client', keep, d); + expect(d.remove).not.toHaveBeenCalled(); + expect(keep.say).toHaveBeenCalledWith(expect.stringContaining('`deleteMaps: false`')); + expect(keep.say).toHaveBeenCalledWith(expect.stringContaining('publicly served')); + expect(keep.say).toHaveBeenCalledWith(expect.not.stringContaining('were removed')); + + // maps the app asked for are not "the ones Bugsee turned on": the notice does not claim them + const own = context({ deleteMaps: false }, { sri: true }); + await run('client', own, deps({ stamp: failing() })); + expect(own.say).toHaveBeenCalledWith(expect.not.stringContaining('`deleteMaps: false`')); + + const abandoned = deps({ + stamp: vi.fn(async () => { + throw Object.assign(new Error('outside'), { unreachableMap: true }); + }), + }); + const keepAbandoned = context({ deleteMaps: false }, { forcedMaps: true }); + await run('client', keepAbandoned, abandoned); + expect(abandoned.remove).not.toHaveBeenCalled(); + expect(keepAbandoned.say).toHaveBeenCalledWith(expect.stringContaining('`deleteMaps: false`')); + }); + + it('sweeps the forced browser maps when a later stage dropped the last client script but left its map', async () => { + const orphanRun = async (ctx: BugseeNextContext, d: WebpackPluginDeps) => { + const fake = fakeCompiler({ path: p('/out/.next') }); + createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); + const c = fakeCompilation({ 'static/a.js.map': 'm', 'static/a.css.map': 'cm' }); + fake.startCompilation(c.compilation); + await c.run(); + await fake.emit(c.compilation); + }; + const d = deps(); + await orphanRun(context({}, { forcedMaps: true }), d); + expect(d.upload).not.toHaveBeenCalled(); + expect(d.remove).toHaveBeenCalledWith(p('/out/.next/static/a.js.map')); + expect(d.remove).toHaveBeenCalledWith(p('/out/.next/static/a.css.map')); + + // not on a dry run, not with deleteMaps: false, not for maps the app asked for, not for a server compilation + for (const [resolved, extra] of [ + [{ dryRun: true }, { forcedMaps: true }], + [{ deleteMaps: false }, { forcedMaps: true }], + [{}, {}], + ] as const) { + const kept = deps(); + await orphanRun(context(resolved, extra), kept); + expect(kept.remove).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); @@ -1126,7 +1183,7 @@ describe('removeFile', () => { }); describe('pairRecorded', () => { - const emitted = (names: string[]) => names.map((n) => `/o/${n}`); + const emitted = (names: string[]) => names.map((n) => p(`/o/${n}`)); it('pairs a script with the map the compilation recorded for it, wherever that map is', () => { const { compilation } = fakeCompilation( @@ -1135,11 +1192,11 @@ describe('pairRecorded', () => { ); const files = pairRecorded( compilation, - '/o', + p('/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']); + expect(files.scripts).toEqual([p('/o/static/a.js'), p('/o/static/b.js')]); + expect(files.maps).toEqual([p('/o/maps/a.js.map'), p('/o/static/b.js.map')]); }); it('the map the compilation recorded wins over a same-named sibling a later stage emitted', () => { @@ -1149,10 +1206,10 @@ describe('pairRecorded', () => { ); const files = pairRecorded( compilation, - '/o', + p('/o'), emitted(['a.js', 'a.js.map', 'maps/original.map']), ); - expect(files.pairs?.['/o/a.js']).toBe('/o/maps/original.map'); + expect(files.pairs?.[p('/o/a.js')]).toBe(p('/o/maps/original.map')); }); it('accepts a recorded list and a ?query on the recorded map', () => { @@ -1160,8 +1217,8 @@ describe('pairRecorded', () => { { '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', + expect(pairRecorded(compilation, p('/o'), emitted(['a.js', 'm/a.js.map'])).maps).toEqual([ + p('/o/m/a.js.map'), ]); }); @@ -1170,7 +1227,7 @@ describe('pairRecorded', () => { { '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'])); + const files = pairRecorded(compilation, p('/o'), emitted(['a.js', 'b.js', 'c.txt'])); expect(files.scripts).toEqual([]); expect(files.maps).toEqual([]); }); @@ -1180,7 +1237,7 @@ describe('pairRecorded', () => { { '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([]); + expect(pairRecorded(compilation, p('/o'), emitted(['m/a.js.map'])).scripts).toEqual([]); }); }); @@ -1193,7 +1250,7 @@ describe('createNextWebpackPlugin: queries, recorded maps, registration', () => bundles: 1, })), }); - const fake = fakeCompiler({ path: '/o' }); + const fake = fakeCompiler({ path: p('/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); @@ -1210,7 +1267,7 @@ describe('createNextWebpackPlugin: queries, recorded maps, registration', () => it('uploads maps a script\u2019s recorded relationship names even when none sits beside it', async () => { const d = deps(); - const fake = fakeCompiler({ path: '/o' }); + const fake = fakeCompiler({ path: p('/o') }); createNextWebpackPlugin(context(), 'client', d).apply(fake.compiler); const c = fakeCompilation( { 'static/a.js': 'x', 'maps/a.js.map': 'm' }, @@ -1224,7 +1281,7 @@ describe('createNextWebpackPlugin: queries, recorded maps, registration', () => 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' }); + const fake = fakeCompiler({ path: p('/o') }); createNextWebpackPlugin( context({}, { ...(browserMaps === undefined ? {} : { browserMaps }) }), kind, @@ -1256,7 +1313,7 @@ describe('createNextWebpackPlugin: the on-disk scan and the no-maps notice', () d: WebpackPluginDeps, assets: Record, ) => { - const fake = fakeCompiler({ path: '/o' }); + const fake = fakeCompiler({ path: p('/o') }); createNextWebpackPlugin(ctx, 'client', d).apply(fake.compiler); const c = fakeCompilation(assets); fake.startCompilation(c.compilation); diff --git a/packages/nextjs/src/config/webpack-plugin.ts b/packages/nextjs/src/config/webpack-plugin.ts index 87c550fb9..263bd35fc 100644 --- a/packages/nextjs/src/config/webpack-plugin.ts +++ b/packages/nextjs/src/config/webpack-plugin.ts @@ -346,7 +346,8 @@ export function createNextWebpackPlugin( // does. Not on a dry run, which deletes nothing (as the core's own upload never does). const wouldDiscard = kind === 'client' && context.forcedMaps === true; const discardForcedMaps = async (): Promise<{ removed: boolean; failed: boolean }> => { - if (!wouldDiscard || resolved.dryRun) { + // Not on a dry run, and not with `deleteMaps: false` (an explicit "keep", as the core's own upload honours). + if (!wouldDiscard || resolved.dryRun || resolved.deleteMaps === false) { return { removed: false, failed: false }; } const failures: unknown[] = []; @@ -382,6 +383,10 @@ export function createNextWebpackPlugin( context.say( 'dry run: nothing was deleted, so the browser source maps Bugsee turned on stay in `.next/static`, publicly served.', ); + } else if (wouldDiscard && resolved.deleteMaps === false) { + context.say( + '`deleteMaps: false` keeps the browser source maps Bugsee turned on in `.next/static`, publicly served.', + ); } return; } @@ -393,6 +398,7 @@ export function createNextWebpackPlugin( context.say( FALLBACK_SRI_NOTICE(kind, removed, { dryRun: resolved.dryRun && wouldDiscard, + retained: !resolved.dryRun && resolved.deleteMaps === false && wouldDiscard, removalFailed: failed, }), ); @@ -423,6 +429,9 @@ export function createNextWebpackPlugin( )(state.failure); } if (files.scripts.length === 0) { + // A later stage may have dropped the last client script and left its map: that map is still public and + // nothing will upload it, so the forced ones go (same policy as above: not on a dry run, not when kept). + await discardForcedMaps(); if (state.preStamped && (state.stampedWithMaps ?? 0) > 0) { const lost = new Error( `${state.stampedWithMaps} bundle(s) stamped inside the ${kind} build have no map left on disk: something removed them after Bugsee stamped them`, From 71a2ea6136884a96b66bd602bc60ce61a25d0b10 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 14:57:23 +0500 Subject: [PATCH 52/63] docs(source-maps): webpack forced-map sweep honours deleteMaps:false and covers the no-pairs path Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- docs/design/source-maps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 4a0e8c203..91d2c6a8e 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -565,7 +565,7 @@ measured). Only bundles that have a map are stamped on Turbopack, and bundles ar 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. +**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 or with `deleteMaps: false` (the notice then says the maps stay public), and the same sweep runs when a later stage dropped the last client script but left its map. 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` From 38f8218c8fb1410bda6e6ba9c470482d1b4f6cdd Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 15:04:16 +0500 Subject: [PATCH 53/63] feat(bundler-plugin-core): doctor --exclude for files the build did not emit; walk fence needs a package.json and is reported Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .changeset/sourcemaps-doctor.md | 2 +- docs/PROGRESS.md | 2 +- docs/source-maps-usage.md | 2 +- packages/bundler-plugin-core/README.md | 4 +- .../src/doctor-cli.test.ts | 20 +++ .../bundler-plugin-core/src/doctor-cli.ts | 14 +- .../src/doctor.hardening.test.ts | 124 ++++++++++++++++++ .../bundler-plugin-core/src/doctor.test.ts | 3 +- packages/bundler-plugin-core/src/doctor.ts | 100 +++++++++++--- 9 files changed, 247 insertions(+), 24 deletions(-) diff --git a/.changeset/sourcemaps-doctor.md b/.changeset/sourcemaps-doctor.md index 8af309953..9d0f56013 100644 --- a/.changeset/sourcemaps-doctor.md +++ b/.changeset/sourcemaps-doctor.md @@ -2,4 +2,4 @@ '@bugsee/bundler-plugin-core': minor --- -Adds `bugsee-sourcemaps-doctor`, an offline check of a build output directory (`npx bugsee-sourcemaps-doctor dist`, `--json`, `--strict`, `--deployed`, `--ignore `), and the matching `diagnoseBuildOutput(dir, options)` API with a versioned report (`schemaVersion: 1`). It tells you why a crash from the build would not symbolicate: unstamped bundles or a missing runtime registration, a map whose debugId differs from its bundle's, dangling, hidden or inline source maps, invalid maps and missing `sourcesContent`, duplicate IDs, Subresource Integrity hazards, leftover public maps, development bundles, and the build environment (token source, version, build, `NODE_ENV`; the token value is never printed). Exit 0 ok, 1 warnings with `--strict`, 2 errors. Also: `stamp-files` no longer spreads large file lists onto the call stack (a directory with more than ~125k scripts or maps overflowed it). The Subresource Integrity page scan in the build plugins is now linear (quadratic regexes on pages with thousands of unterminated tags or comments are replaced by an `indexOf` scanner, with a differential test pinning identical results) and pages larger than 8 MiB are skipped. +Adds `bugsee-sourcemaps-doctor`, an offline check of a build output directory (`npx bugsee-sourcemaps-doctor dist`, `--json`, `--strict`, `--deployed`, `--ignore `, `--exclude `), and the matching `diagnoseBuildOutput(dir, options)` API with a versioned report (`schemaVersion: 1`). It tells you why a crash from the build would not symbolicate: unstamped bundles or a missing runtime registration, a map whose debugId differs from its bundle's, dangling, hidden or inline source maps, invalid maps and missing `sourcesContent`, duplicate IDs, Subresource Integrity hazards, leftover public maps, development bundles, and the build environment (token source, version, build, `NODE_ENV`; the token value is never printed). Exit 0 ok, 1 warnings with `--strict`, 2 errors. Also: `stamp-files` no longer spreads large file lists onto the call stack (a directory with more than ~125k scripts or maps overflowed it). The Subresource Integrity page scan in the build plugins is now linear (quadratic regexes on pages with thousands of unterminated tags or comments are replaced by an `indexOf` scanner, with a differential test pinning identical results) and pages larger than 8 MiB are skipped. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 0dd14b92b..a7daaed3d 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1533,7 +1533,7 @@ Verified against current majors, all green with no adapter code changes: `@bugse `@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. ### `sourcemaps doctor`: offline build-output diagnostics (2026-11-23) -`@bugsee/bundler-plugin-core` ships `diagnoseBuildOutput(dir, options)` (`src/doctor.ts`) and the `bugsee-sourcemaps-doctor` bin (`src/doctor-cli.ts`, ESM-only tsup entry, wired through `publishConfig.bin`). 32 check IDs (`DOCTOR_CHECK_IDS`) over the output directory, bundles, maps, SRI (reusing `sri.ts`), leftover maps and the build environment (token, version, build, `NODE_ENV`; the token is never printed), each with a severity and a fix hint, and one versioned JSON report (`schemaVersion: 1`) that the Rust `bugsee-cli sourcemaps doctor` is specified to share. Exit codes 0 ok, 1 warnings only with `--strict`, 2 errors. Review round (PR #222): `--strict` passes straight after a plugin run (`map.public-leftover` is a note unless `--deployed`; `map.pointer-dangling` is a note when no map is left and every bundle is stamped; `--ignore `), the doctor never throws (`doctor.internal-error`; no spread of large lists, safe `file://` decoding), reads only regular files inside the directory with the size checked first (`map.unreadable`, `map.pointer-outside-dir`), walks the whole output directory (only `node_modules`/`.git` skipped unless it is the project root), resolves bundler-scheme sources against the project root, reports the token's source (`env.token-source`; a missing token is a warning), and pairs maps with the stamp's own `localPointerTarget`. The same spread pattern was fixed in `stamp-files.ts`. Round 4: the HTML scan in `sri.ts` is linear (an `indexOf` scanner replaced the quadratic comment and script-tag regexes; a differential fuzz test pins identical results) and bounded (pages over 8 MiB are skipped and reported as `sri.html-skipped`); reads go through `safe-read.ts` (open with `O_NOFOLLOW`/`O_NONBLOCK`, type and size judged on the descriptor); in-directory symlinks are followed by real path; FIFOs/sockets/devices named like scripts are reported; a map reached through two names is judged once; long lists and the per-map `map.sources-content` notes are capped/aggregated. Real-build proof in `doctor.real-build.test.ts`: Vite 8 and 7, Rollup and Rspack stamped by the real plugin and CLI (healthy), an unstamped build, an inline-map build, and SRI builds (unstamped hazard, stamped-first clean, stamped-after-hash `sri.mismatch` produced by `bugsee-cli sourcemaps inject --allow-sri`). Webpack itself is not a dependency of this package; Rspack stands in for the shared in-build stamp path. Mutator loop: 10 mutations on the decision logic, all killed. **Not done:** an optional post-build `doctor` call in the plugins (the findings need a policy for failing a build; left as a follow-up), the Rust command, and every check that needs the backend (design hand-off: map-present-for-debug-ID, deployed-URL, synthetic symbolicate round trip). +`@bugsee/bundler-plugin-core` ships `diagnoseBuildOutput(dir, options)` (`src/doctor.ts`) and the `bugsee-sourcemaps-doctor` bin (`src/doctor-cli.ts`, ESM-only tsup entry, wired through `publishConfig.bin`). 34 check IDs (`DOCTOR_CHECK_IDS`) over the output directory, bundles, maps, SRI (reusing `sri.ts`), leftover maps and the build environment (token, version, build, `NODE_ENV`; the token is never printed), each with a severity and a fix hint, and one versioned JSON report (`schemaVersion: 1`) that the Rust `bugsee-cli sourcemaps doctor` is specified to share. Exit codes 0 ok, 1 warnings only with `--strict`, 2 errors. Review round (PR #222): `--strict` passes straight after a plugin run (`map.public-leftover` is a note unless `--deployed`; `map.pointer-dangling` is a note when no map is left and every bundle is stamped; `--ignore `), the doctor never throws (`doctor.internal-error`; no spread of large lists, safe `file://` decoding), reads only regular files inside the directory with the size checked first (`map.unreadable`, `map.pointer-outside-dir`), walks the whole output directory (only `node_modules`/`.git` skipped unless it is the project root), resolves bundler-scheme sources against the project root, reports the token's source (`env.token-source`; a missing token is a warning), and pairs maps with the stamp's own `localPointerTarget`. The same spread pattern was fixed in `stamp-files.ts`. Round 6: `--exclude ` (+ `exclude` option) drops files the build did not emit (`output.excluded`); the walk fence needs a `package.json` as well as cwd and reports what it skipped (`output.walk-fenced`); the stamp's own SRI guard keeps no page cap (only the doctor's scan does). Round 4: the HTML scan in `sri.ts` is linear (an `indexOf` scanner replaced the quadratic comment and script-tag regexes; a differential fuzz test pins identical results) and bounded (pages over 8 MiB are skipped and reported as `sri.html-skipped`); reads go through `safe-read.ts` (open with `O_NOFOLLOW`/`O_NONBLOCK`, type and size judged on the descriptor); in-directory symlinks are followed by real path; FIFOs/sockets/devices named like scripts are reported; a map reached through two names is judged once; long lists and the per-map `map.sources-content` notes are capped/aggregated. Real-build proof in `doctor.real-build.test.ts`: Vite 8 and 7, Rollup and Rspack stamped by the real plugin and CLI (healthy), an unstamped build, an inline-map build, and SRI builds (unstamped hazard, stamped-first clean, stamped-after-hash `sri.mismatch` produced by `bugsee-cli sourcemaps inject --allow-sri`). Webpack itself is not a dependency of this package; Rspack stands in for the shared in-build stamp path. Mutator loop: 10 mutations on the decision logic, all killed. **Not done:** an optional post-build `doctor` call in the plugins (the findings need a policy for failing a build; left as a follow-up), the Rust command, and every check that needs the backend (design hand-off: map-present-for-debug-ID, deployed-URL, synthetic symbolicate round trip). ### 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/source-maps-usage.md b/docs/source-maps-usage.md index d440b7142..f2b56519c 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -232,7 +232,7 @@ npx bugsee-sourcemaps-doctor dist --strict # warnings fail the step too (exi npx bugsee-sourcemaps-doctor dist --deployed # the directory is served: leftover .map files warn ``` -`--strict` passes straight after a default plugin run (maps removed after upload, bundles stamped). Other options: `--ignore ` (repeatable; hard failures such as `output.no-js` cannot be ignored), `--project-root`, `--max-map-mb`, `--no-env`, `--`. +`--strict` passes straight after a default plugin run (maps removed after upload, bundles stamped) when the directory holds only what the build emitted. Scripts copied in (Vite `publicDir`, a copy plugin) are never stamped by the plugin and are indistinguishable from a bundle that lost its stamp: exclude them by path with `--exclude 'public/**'` (repeatable; listed as `output.excluded`). A directory that is a project (has a `package.json`) and is the working directory is walked fenced (no `src`, `test`, dot-directories, depth > 6), and the skipped directories are listed as `output.walk-fenced`. Other options: `--ignore ` (repeatable; hard failures such as `output.no-js` cannot be ignored), `--project-root`, `--max-map-mb`, `--no-env`, `--`. Exit codes: `0` ok, `1` warnings only (with `--strict`), `2` errors. The package is `@bugsee/bundler-plugin-core`; the same report is available in code as `diagnoseBuildOutput(dir, options)`. diff --git a/packages/bundler-plugin-core/README.md b/packages/bundler-plugin-core/README.md index bc459c1b9..6d45a0a55 100644 --- a/packages/bundler-plugin-core/README.md +++ b/packages/bundler-plugin-core/README.md @@ -30,9 +30,9 @@ npx bugsee-sourcemaps-doctor dist --json # machine-readable report (schemaVe npx bugsee-sourcemaps-doctor dist --strict # exit 1 on warnings too ``` -Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks), `--deployed` (the directory is, or is about to be, served: leftover `.map` files become a warning instead of a note), `--ignore ` (drop a check ID; repeatable; `output.dir-missing`, `output.no-js` and `doctor.internal-error` cannot be ignored), `--` (end of options); `--key=value` works for options that take a value, and `--strict=false`-style values on flags are refused. Before the upload (hidden maps still on disk, the plugin will delete them) and after it (maps removed), `--strict` passes on a healthy build; add `--deployed` only when checking the directory you serve. Straight after a default plugin run `--strict` passes: leftover maps are a note unless `--deployed`, and a pointer to maps removed on purpose from a fully stamped build is a note. +Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks), `--deployed` (the directory is, or is about to be, served: leftover `.map` files become a warning instead of a note), `--exclude ` (files the build did not emit, e.g. `public/**` for scripts copied from Vite's `publicDir` or by a copy plugin: the plugin never stamps those and a doctor cannot tell them from a bundle that lost its stamp; repeatable; `*` stays in a directory, `**` crosses them; matches are listed as `output.excluded`), `--ignore ` (drop a check ID; repeatable; `output.dir-missing`, `output.no-js` and `doctor.internal-error` cannot be ignored), `--` (end of options); `--key=value` works for options that take a value, and `--strict=false`-style values on flags are refused. Before the upload (hidden maps still on disk, the plugin will delete them) and after it (maps removed), `--strict` passes on a healthy build; add `--deployed` only when checking the directory you serve. Straight after a default plugin run `--strict` passes for a build whose output directory holds only what the build emitted (add `--exclude` for copied-in scripts): leftover maps are a note unless `--deployed`, and a pointer to maps removed on purpose from a fully stamped build is a note. -It checks, each with a stable ID, a severity and a fix hint: the output directory and its JavaScript; the debug-ID comment and `_bugseeDebugIds` registration on every bundle; a matching map with the same ID; `sourceMappingURL` pointers (dangling, hidden, inline); map validity (v3, `sources`, `sourcesContent` embedded or resolvable on disk, size); mixed stamped/unstamped bundles; duplicate IDs across different contents; Subresource Integrity hazards and mismatches (pages and `*manifest*.json` inside the directory only; a page larger than 8 MiB is reported, not scanned); leftover `.map` files that a deploy would serve; development-mode bundles; and the build environment (token present, version and build resolvable, `NODE_ENV`). The token value is never printed; the report says where it came from (option, environment variable, or `.env.bugsee-build-plugin`), and a missing token is a warning, because uploading by hand is legitimate. The doctor never throws (an internal failure is a `doctor.internal-error` finding), never reads outside the checked directory, never opens a FIFO, socket or device (they are reported), reads a symlink only when its real path stays inside the checked directory (a pnpm-style `assets/app.js -> ../.store/app.js` is fine; one that leads out, dangles or loops is reported), judges type and size on the open file descriptor, and checks a map's size before reading it. Programmatic use: `diagnoseBuildOutput(dir, options)` returns the same report. The backend-assisted checks (is this ID's map uploaded?) are not part of this command; see `docs/source-maps-usage.md` §4. +It checks, each with a stable ID, a severity and a fix hint: the output directory and its JavaScript; the debug-ID comment and `_bugseeDebugIds` registration on every bundle; a matching map with the same ID; `sourceMappingURL` pointers (dangling, hidden, inline); map validity (v3, `sources`, `sourcesContent` embedded or resolvable on disk, size); mixed stamped/unstamped bundles; duplicate IDs across different contents; Subresource Integrity hazards and mismatches (pages and `*manifest*.json` inside the directory only; a page larger than 8 MiB is reported, not scanned); leftover `.map` files that a deploy would serve; development-mode bundles; and the build environment (token present, version and build resolvable, `NODE_ENV`). The token value is never printed; the report says where it came from (option, environment variable, or `.env.bugsee-build-plugin`), and a missing token is a warning, because uploading by hand is legitimate. When the checked directory is itself a project directory (has a `package.json`) and is, or contains, the working directory, the walk skips `src`/`test`/dot-directories and stops below depth 6 so it stays out of a source tree; the skipped directories are listed as `output.walk-fenced`, never silent. The doctor never throws (an internal failure is a `doctor.internal-error` finding), never reads outside the checked directory, never opens a FIFO, socket or device (they are reported), reads a symlink only when its real path stays inside the checked directory (a pnpm-style `assets/app.js -> ../.store/app.js` is fine; one that leads out, dangles or loops is reported), judges type and size on the open file descriptor, and checks a map's size before reading it. Programmatic use: `diagnoseBuildOutput(dir, options)` returns the same report. The backend-assisted checks (is this ID's map uploaded?) are not part of this command; see `docs/source-maps-usage.md` §4. The rest of the programmatic API beyond the plugins and the doctor is internal and may change between releases. diff --git a/packages/bundler-plugin-core/src/doctor-cli.test.ts b/packages/bundler-plugin-core/src/doctor-cli.test.ts index f0bc207af..9e3eca5b6 100644 --- a/packages/bundler-plugin-core/src/doctor-cli.test.ts +++ b/packages/bundler-plugin-core/src/doctor-cli.test.ts @@ -28,6 +28,26 @@ async function cli(argv: string[], env = { BUGSEE_APP_TOKEN: 't', BUGSEE_APP_BUI return { code, out, err }; } +describe('runDoctorCli --exclude', () => { + it('drops matching files before analysis; repeatable; needs a value', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + mkdirSync(join(dist, 'public')); + writeFileSync(join(dist, 'public', 'sw.js'), 'x'); + writeFileSync(join(dist, 'vendor.js'), 'x'); + expect((await cli([dist, '--no-env', '--json'])).code).toBe(0); + const ids = async (args: string[]) => + JSON.parse((await cli([dist, '--no-env', '--json', ...args])).out).findings.map( + (f: { id: string }) => f.id, + ); + expect(await ids(['--exclude', 'public/**'])).toContain('output.excluded'); + expect(await ids(['--exclude', 'public/**'])).toContain('stamp.missing-debug-id'); // vendor.js remains + const both = await ids(['--exclude=public/**', '--exclude', 'vendor.js']); + expect(both).not.toContain('stamp.missing-debug-id'); + expect(both).not.toContain('stamp.mixed'); + expect((await cli([dist, '--exclude'])).code).toBe(2); + }); +}); + describe('runDoctorCli', () => { it('prints the text report and exits 0 for a clean build', async () => { writeFileSync(join(dist, 'a.js'), stamped); diff --git a/packages/bundler-plugin-core/src/doctor-cli.ts b/packages/bundler-plugin-core/src/doctor-cli.ts index 25caf6242..411f96870 100644 --- a/packages/bundler-plugin-core/src/doctor-cli.ts +++ b/packages/bundler-plugin-core/src/doctor-cli.ts @@ -1,7 +1,7 @@ #!/usr/bin/env node // `bugsee-sourcemaps-doctor` — the command-line face of `diagnoseBuildOutput`. // -// bugsee-sourcemaps-doctor [--json] [--strict] [--project-root ] [--max-map-mb ] [--no-env] +// bugsee-sourcemaps-doctor [--json] [--strict] [--project-root ] [--max-map-mb ] [--no-env] [--exclude ] // // Exit codes: 0 ok, 1 warnings only with --strict, 2 errors (or a usage error). import { realpathSync } from 'node:fs'; @@ -27,6 +27,7 @@ Options: --no-env Skip the token / version / build / NODE_ENV checks. --deployed The directory is (about to be) served: leftover .map files become a warning. --ignore Drop a check ID from the report; repeatable. + --exclude Do not check files the build did not emit (e.g. 'public/**'); repeatable. -- End of options (a directory may start with a dash after it). -h, --help Show this help. @@ -56,6 +57,7 @@ export async function runDoctorCli(argv: readonly string[], io: DoctorCliIo): Pr let deployed = false; let onlyPositionals = false; const ignore: string[] = []; + const exclude: string[] = []; let projectRoot: string | undefined; let maxMapBytes: number | undefined; const usage = (message: string): number => { @@ -92,13 +94,20 @@ export async function runDoctorCli(argv: readonly string[], io: DoctorCliIo): Pr skipEnv = true; } else if (arg === '--deployed') { deployed = true; - } else if (arg === '--project-root' || arg === '--max-map-mb' || arg === '--ignore') { + } else if ( + arg === '--project-root' || + arg === '--max-map-mb' || + arg === '--ignore' || + arg === '--exclude' + ) { const value = inline ?? argv[++i]; if (value === undefined || (inline === undefined && value.startsWith('--'))) { return usage(`${arg} needs a value`); } if (arg === '--project-root') { projectRoot = value; + } else if (arg === '--exclude') { + exclude.push(value); } else if (arg === '--ignore') { if (NON_IGNORABLE_CHECK_IDS.has(value)) { io.stderr( @@ -133,6 +142,7 @@ export async function runDoctorCli(argv: readonly string[], io: DoctorCliIo): Pr skipEnv, deployed, ignore, + exclude, ...(projectRoot !== undefined ? { projectRoot } : {}), ...(maxMapBytes !== undefined ? { maxMapBytes } : {}), }); diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index 3487e6b5c..5687b5e41 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -658,3 +658,127 @@ describe('big outputs stay readable (round 4)', () => { expect(ids(report)).not.toContain('doctor.internal-error'); }); }); + +describe('files the build did not emit (round 6)', () => { + const healthy = () => { + put('app.js', `a${stamp(ID_A)}`); + put('app.js.map', mapJson({ debugId: ID_A })); + }; + + it('a copied public/ script (with and without a map) is an error until --exclude drops it', async () => { + healthy(); + put('public/pdf.worker.min.mjs', 'w'); + put('public/pdf.worker.min.mjs.map', mapJson()); + put('public/sw.js', 's'); + const before = await run(); + expect(ids(before)).toContain('stamp.missing-debug-id'); + expect(ids(before)).toContain('stamp.mixed'); + const after = await run({ exclude: ['public/**'] }); + expect(ids(after)).not.toContain('stamp.missing-debug-id'); + expect(ids(after)).not.toContain('stamp.mixed'); + expect(after.summary).toMatchObject({ errors: 0, warnings: 0, bundles: 1, maps: 1 }); + expect(find(after, 'output.excluded')).toMatchObject({ + severity: 'info', + details: { + files: ['public/pdf.worker.min.mjs', 'public/pdf.worker.min.mjs.map', 'public/sw.js'], + }, + }); + }); + + it('an exclude that matches nothing says nothing', async () => { + healthy(); + expect(ids(await run({ exclude: ['nope/**'] }))).not.toContain('output.excluded'); + }); + + it('glob semantics: * stays in a directory, ** crosses them, ? is one character, a trailing / is a directory', async () => { + healthy(); + put('a1.js', 'x'); + put('sub/a2.js', 'x'); + put('sub/deep/a3.js', 'x'); + put('vendor/v.js', 'x'); + put('vendor/xv.js', 'x'); + const excluded = async (pattern: string): Promise => + (find(await run({ exclude: [pattern] }), 'output.excluded')?.details?.files as string[]) ?? + []; + expect(await excluded('a?.js')).toEqual(['a1.js']); + expect(await excluded('*.js')).toEqual(['a1.js', 'app.js']); + expect(await excluded('**/*.js')).toEqual([ + 'a1.js', + 'app.js', + 'sub/a2.js', + 'sub/deep/a3.js', + 'vendor/v.js', + 'vendor/xv.js', + ]); + expect(await excluded('sub/*.js')).toEqual(['sub/a2.js']); + expect(await excluded('sub/**')).toEqual(['sub/a2.js', 'sub/deep/a3.js']); + expect(await excluded('vendor/')).toEqual(['vendor/v.js', 'vendor/xv.js']); + expect(await excluded('a.js')).toEqual([]); // `.` is a literal dot, not "any character" + expect(await excluded('a1+js')).toEqual([]); + expect(await excluded('[a]1.js')).toEqual([]); // regex syntax in a glob is literal + expect(await excluded('sub?a2.js')).toEqual([]); // `?` is never a slash + expect(await excluded('**/v.js')).toEqual(['vendor/v.js']); // `**/` is whole path segments: xv.js is not v.js + expect(await excluded('**/a2.js')).toEqual(['sub/a2.js']); + expect(await excluded('**/p.js')).toEqual([]); + }); + + it('excluding every script leaves output.no-js, which cannot be hidden', async () => { + put('public/sw.js', 's'); + const report = await run({ exclude: ['**'] }); + expect(ids(report)).toContain('output.no-js'); + }); + + it('a long exclusion list is capped, with the total', async () => { + healthy(); + for (let i = 0; i < 120; i++) { + put(`public/f${i}.js`, 'x'); + } + const finding = find(await run({ exclude: ['public/**'] }), 'output.excluded'); + expect((finding?.details?.files as string[]).length).toBe(100); + expect(finding?.details?.total).toBe(120); + }); +}); + +describe('the walk fence is reported, and needs a real project directory (round 6)', () => { + const inDist = async (options: Parameters[0] = {}): Promise => { + const here = process.cwd(); + process.chdir(dist); + try { + return await run(options); + } finally { + process.chdir(here); + } + }; + + it('run from inside an output directory WITHOUT a package.json, src/ and dot-directories are audited', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('src/s.js', 'x'); + put('.cache/c.js', 'x'); + put('a/b/c/d/e/f/g/h/deep.js', 'x'); + const report = await inDist(); + expect(report.summary.bundles).toBe(4); + expect(ids(report)).not.toContain('output.walk-fenced'); + }); + + it('a directory that is the project (has a package.json) is fenced, and the report lists what was skipped', async () => { + put('package.json', '{"name":"p"}'); + put('a.js', `a${stamp(ID_A)}`); + put('src/s.js', 'x'); + put('.cache/c.js', 'x'); + put('tests/t.js', 'x'); + put('a/b/c/d/e/f/g/h/deep.js', 'x'); + const report = await inDist(); + expect(report.summary.bundles).toBe(1); + expect(find(report, 'output.walk-fenced')).toMatchObject({ + severity: 'info', + details: { directories: ['.cache', 'a/b/c/d/e/f/g', 'src', 'tests'] }, + }); + }); + + it('a project directory that is not the working directory is not fenced', async () => { + put('package.json', '{"name":"p"}'); + put('src/s.js', 'x'); + put('a.js', `a${stamp(ID_A)}`); + expect((await run()).summary.bundles).toBe(2); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.test.ts b/packages/bundler-plugin-core/src/doctor.test.ts index 68157522c..8be42b0ef 100644 --- a/packages/bundler-plugin-core/src/doctor.test.ts +++ b/packages/bundler-plugin-core/src/doctor.test.ts @@ -552,11 +552,12 @@ describe('diagnoseBuildOutput', () => { expect(report.summary.bundles).toBe(2); }); - it('only a directory that is (or contains) the project root is fenced and depth-capped', async () => { + it('only a project directory that is (or contains) the working directory is fenced and depth-capped', async () => { put('a/b/c/d/e/f/g/h/deep.js', 'x'); put('a/ok.js', 'x'); put('src/s.js', 'x'); put('.cache/c.js', 'x'); + put('package.json', '{"name":"p"}'); // a directory that IS a project; see doctor.hardening.test.ts const here = process.cwd(); process.chdir(dist); try { diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts index 9de2149af..ead25b1c6 100644 --- a/packages/bundler-plugin-core/src/doctor.ts +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -72,6 +72,13 @@ export interface DoctorOptions { ignore?: readonly string[]; /** A script larger than this many bytes is not read (default 512 MiB). */ maxBundleBytes?: number; + /** + * Globs (relative to the checked directory, POSIX separators; `*` stays in a directory, `**` crosses them, `?` is + * one character, a trailing `/` means the directory) of files the build did NOT emit: a doctor cannot tell a + * script copied in (Vite `publicDir`, a copy plugin) from a bundle that lost its stamp, and the plugin never stamps + * the former. Matching files are dropped before analysis and listed as `output.excluded`. + */ + exclude?: readonly string[]; } const DEFAULT_MAX_MAP_BYTES = 50 * 1024 * 1024; @@ -89,6 +96,8 @@ export const DOCTOR_CHECK_IDS = [ 'output.dir-missing', 'output.no-js', 'output.unreadable', + 'output.excluded', + 'output.walk-fenced', 'stamp.missing-debug-id', 'stamp.missing-registration', 'stamp.map-id-mismatch', @@ -134,18 +143,21 @@ const posix = (path: string): string => path.split('\\').join('/'); const rel = (dir: string, path: string): string => posix(relative(dir, path)); /** - * Every script and map under `root`. An output directory is walked in full (Rollup `preserveModules` writes - * `dist/src/*.js`; a build may emit `dist/test/`), skipping only `node_modules` and `.git`; the fence on - * `src`/`test`/dot-directories and the depth cap apply ONLY when `root` is the project root or above, where - * they keep the walk out of the source tree. Iterative, and never spreads a result list (a directory with - * 100k files must not overflow the call stack). + * Every script and map under `root`, and the directories the fence skipped. An output directory is walked in full + * (Rollup `preserveModules` writes `dist/src/*.js`; a build may emit `dist/test/`), skipping only `node_modules` + * and `.git`; the fence on `src`/`test`/dot-directories and the depth cap apply ONLY when `root` is a project + * directory (has a `package.json`) that is, or contains, the working directory, where they keep the walk out of the + * source tree. What the fence skipped is returned, never silent. Iterative, and never spreads a result list (a + * directory with 100k files must not overflow the call stack). */ -export async function walk(root: string): Promise { - const fenced = await isProjectRootOrAbove(root); +export async function walkDetailed(root: string): Promise<{ files: string[]; skipped: string[] }> { + const fenced = (await isProjectRootOrAbove(root)) && existsSync(join(root, 'package.json')); const found: string[] = []; + const skipped: string[] = []; const pending: Array<{ dir: string; depth: number }> = [{ dir: root, depth: 0 }]; for (let next = pending.pop(); next !== undefined; next = pending.pop()) { if (fenced && next.depth > MAX_WALK_DEPTH) { + skipped.push(rel(root, next.dir)); continue; } let entries: Dirent[]; @@ -157,19 +169,47 @@ export async function walk(root: string): Promise { for (const entry of entries) { const full = join(next.dir, entry.name); if (entry.isDirectory()) { - const skip = - entry.name === 'node_modules' || - entry.name === '.git' || - (fenced && (NEVER_WALK.has(entry.name) || entry.name.startsWith('.'))); - if (!skip) { - pending.push({ dir: full, depth: next.depth + 1 }); + if (entry.name === 'node_modules' || entry.name === '.git') { + continue; + } + if (fenced && (NEVER_WALK.has(entry.name) || entry.name.startsWith('.'))) { + skipped.push(rel(root, full)); + continue; } - } else if (!entry.isDirectory() && (BUNDLE.test(entry.name) || MAP.test(entry.name))) { + pending.push({ dir: full, depth: next.depth + 1 }); + } else if (BUNDLE.test(entry.name) || MAP.test(entry.name)) { found.push(full); } } } - return found.sort(); + return { files: found.sort(), skipped: skipped.sort() }; +} + +export async function walk(root: string): Promise { + return (await walkDetailed(root)).files; +} + +/** A glob (see {@link DoctorOptions.exclude}) as an anchored regular expression over a POSIX relative path. */ +export function globToRegExp(glob: string): RegExp { + const pattern = glob.endsWith('/') ? `${glob}**` : glob; + let source = ''; + for (let i = 0; i < pattern.length; i++) { + const c = pattern.charAt(i); + if (c === '*') { + if (pattern.charAt(i + 1) === '*') { + const slash = pattern.charAt(i + 2) === '/'; + source += slash ? '(?:.*/)?' : '.*'; + i += slash ? 2 : 1; + } else { + source += '[^/]*'; + } + } else if (c === '?') { + source += '[^/]'; + } else { + source += c.replace(/[\\^$.|+()[\]{}]/g, '\\$&'); + } + } + return new RegExp(`^${source}$`); } interface ParsedMap { @@ -374,7 +414,17 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise { + const name = rel(dir, file); + if (patterns.some((pattern) => pattern.test(name))) { + excluded.push(name); + return false; + } + return true; + }); const bundles = files.filter((f) => BUNDLE.test(f)); const maps = files.filter((f) => MAP.test(f)); if (bundles.length === 0) { @@ -386,6 +436,24 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise 0) { + add({ + id: 'output.excluded', + severity: 'info', + message: `${excluded.length} file(s) matched --exclude and were not checked (${excluded.slice(0, MAX_LISTED).join(', ')}${excluded.length > MAX_LISTED ? ', …' : ''}).`, + details: listDetails('files', excluded), + }); + } + if (walked.skipped.length > 0) { + add({ + id: 'output.walk-fenced', + severity: 'info', + message: `${walked.skipped.length} director${walked.skipped.length === 1 ? 'y was' : 'ies were'} not searched because ${dir} looks like a project directory (${walked.skipped.slice(0, MAX_LISTED).join(', ')}${walked.skipped.length > MAX_LISTED ? ', …' : ''}).`, + fix: 'To audit them, run the doctor on the build output directory from the project root (not from inside a directory that has a package.json).', + details: listDetails('directories', walked.skipped), + }); + } + const mapSet = new Set(maps); // A map reached through two names (a symlinked directory, a case-variant pointer) is the same file: judged once. const seenMaps = new Set(); From 8fafe7917750f33c85971a9b73cc025d56560d71 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 15:25:49 +0500 Subject: [PATCH 54/63] fix(bundler-plugin-core): doctor round 7: exclude applies to SRI pins and pointers, unmatched excludes reported, byte-bounded reads, mappings required, all distinct SRI pins, passed only for checks that ran, tsup clean race, docs Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .changeset/sourcemaps-doctor.md | 2 +- docs/PROGRESS.md | 2 +- docs/source-maps-usage.md | 6 +- packages/bundler-plugin-core/README.md | 4 +- packages/bundler-plugin-core/package.json | 2 +- .../src/doctor-cli.test.ts | 8 +- .../bundler-plugin-core/src/doctor-cli.ts | 2 +- .../src/doctor.hardening.test.ts | 154 +++++++++++++++++- packages/bundler-plugin-core/src/doctor.ts | 127 ++++++++++++++- packages/bundler-plugin-core/src/safe-read.ts | 6 +- .../bundler-plugin-core/src/sri.scan.test.ts | 10 ++ packages/bundler-plugin-core/src/sri.ts | 20 ++- packages/bundler-plugin-core/tsup.config.ts | 6 +- 13 files changed, 319 insertions(+), 30 deletions(-) diff --git a/.changeset/sourcemaps-doctor.md b/.changeset/sourcemaps-doctor.md index 9d0f56013..52ee6f9f4 100644 --- a/.changeset/sourcemaps-doctor.md +++ b/.changeset/sourcemaps-doctor.md @@ -2,4 +2,4 @@ '@bugsee/bundler-plugin-core': minor --- -Adds `bugsee-sourcemaps-doctor`, an offline check of a build output directory (`npx bugsee-sourcemaps-doctor dist`, `--json`, `--strict`, `--deployed`, `--ignore `, `--exclude `), and the matching `diagnoseBuildOutput(dir, options)` API with a versioned report (`schemaVersion: 1`). It tells you why a crash from the build would not symbolicate: unstamped bundles or a missing runtime registration, a map whose debugId differs from its bundle's, dangling, hidden or inline source maps, invalid maps and missing `sourcesContent`, duplicate IDs, Subresource Integrity hazards, leftover public maps, development bundles, and the build environment (token source, version, build, `NODE_ENV`; the token value is never printed). Exit 0 ok, 1 warnings with `--strict`, 2 errors. Also: `stamp-files` no longer spreads large file lists onto the call stack (a directory with more than ~125k scripts or maps overflowed it). The Subresource Integrity page scan in the build plugins is now linear (quadratic regexes on pages with thousands of unterminated tags or comments are replaced by an `indexOf` scanner, with a differential test pinning identical results) and pages larger than 8 MiB are skipped. +Adds `bugsee-sourcemaps-doctor`, an offline check of a build output directory (`npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist`, or `npx bugsee-sourcemaps-doctor dist` where the package is installed; `--json`, `--strict`, `--deployed`, `--ignore `, `--exclude `), and the matching `diagnoseBuildOutput(dir, options)` API with a versioned report (`schemaVersion: 1`). It tells you why a crash from the build would not symbolicate: unstamped bundles or a missing runtime registration, a map whose debugId differs from its bundle's, dangling, hidden or inline source maps, invalid maps and missing `sourcesContent`, duplicate IDs, Subresource Integrity hazards, leftover public maps, development bundles, and the build environment (token source, version, build, `NODE_ENV`; the token value is never printed). Exit 0 ok, 1 warnings with `--strict`, 2 errors. Also: `stamp-files` no longer spreads large file lists onto the call stack (a directory with more than ~125k scripts or maps overflowed it). The Subresource Integrity page scan in the build plugins is now linear (quadratic regexes on pages with thousands of unterminated tags or comments are replaced by an `indexOf` scanner, with a differential test pinning identical results) and pages larger than 8 MiB are skipped. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index a7daaed3d..31f1eabcf 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1533,7 +1533,7 @@ Verified against current majors, all green with no adapter code changes: `@bugse `@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. ### `sourcemaps doctor`: offline build-output diagnostics (2026-11-23) -`@bugsee/bundler-plugin-core` ships `diagnoseBuildOutput(dir, options)` (`src/doctor.ts`) and the `bugsee-sourcemaps-doctor` bin (`src/doctor-cli.ts`, ESM-only tsup entry, wired through `publishConfig.bin`). 34 check IDs (`DOCTOR_CHECK_IDS`) over the output directory, bundles, maps, SRI (reusing `sri.ts`), leftover maps and the build environment (token, version, build, `NODE_ENV`; the token is never printed), each with a severity and a fix hint, and one versioned JSON report (`schemaVersion: 1`) that the Rust `bugsee-cli sourcemaps doctor` is specified to share. Exit codes 0 ok, 1 warnings only with `--strict`, 2 errors. Review round (PR #222): `--strict` passes straight after a plugin run (`map.public-leftover` is a note unless `--deployed`; `map.pointer-dangling` is a note when no map is left and every bundle is stamped; `--ignore `), the doctor never throws (`doctor.internal-error`; no spread of large lists, safe `file://` decoding), reads only regular files inside the directory with the size checked first (`map.unreadable`, `map.pointer-outside-dir`), walks the whole output directory (only `node_modules`/`.git` skipped unless it is the project root), resolves bundler-scheme sources against the project root, reports the token's source (`env.token-source`; a missing token is a warning), and pairs maps with the stamp's own `localPointerTarget`. The same spread pattern was fixed in `stamp-files.ts`. Round 6: `--exclude ` (+ `exclude` option) drops files the build did not emit (`output.excluded`); the walk fence needs a `package.json` as well as cwd and reports what it skipped (`output.walk-fenced`); the stamp's own SRI guard keeps no page cap (only the doctor's scan does). Round 4: the HTML scan in `sri.ts` is linear (an `indexOf` scanner replaced the quadratic comment and script-tag regexes; a differential fuzz test pins identical results) and bounded (pages over 8 MiB are skipped and reported as `sri.html-skipped`); reads go through `safe-read.ts` (open with `O_NOFOLLOW`/`O_NONBLOCK`, type and size judged on the descriptor); in-directory symlinks are followed by real path; FIFOs/sockets/devices named like scripts are reported; a map reached through two names is judged once; long lists and the per-map `map.sources-content` notes are capped/aggregated. Real-build proof in `doctor.real-build.test.ts`: Vite 8 and 7, Rollup and Rspack stamped by the real plugin and CLI (healthy), an unstamped build, an inline-map build, and SRI builds (unstamped hazard, stamped-first clean, stamped-after-hash `sri.mismatch` produced by `bugsee-cli sourcemaps inject --allow-sri`). Webpack itself is not a dependency of this package; Rspack stands in for the shared in-build stamp path. Mutator loop: 10 mutations on the decision logic, all killed. **Not done:** an optional post-build `doctor` call in the plugins (the findings need a policy for failing a build; left as a follow-up), the Rust command, and every check that needs the backend (design hand-off: map-present-for-debug-ID, deployed-URL, synthetic symbolicate round trip). +`@bugsee/bundler-plugin-core` ships `diagnoseBuildOutput(dir, options)` (`src/doctor.ts`) and the `bugsee-sourcemaps-doctor` bin (`src/doctor-cli.ts`, ESM-only tsup entry, wired through `publishConfig.bin`). 35 check IDs (`DOCTOR_CHECK_IDS`) over the output directory, bundles, maps, SRI (reusing `sri.ts`), leftover maps and the build environment (token, version, build, `NODE_ENV`; the token is never printed), each with a severity and a fix hint, and one versioned JSON report (`schemaVersion: 1`) that the Rust `bugsee-cli sourcemaps doctor` is specified to share. Exit codes 0 ok, 1 warnings only with `--strict`, 2 errors. Review round (PR #222): `--strict` passes straight after a plugin run (`map.public-leftover` is a note unless `--deployed`; `map.pointer-dangling` is a note when no map is left and every bundle is stamped; `--ignore `), the doctor never throws (`doctor.internal-error`; no spread of large lists, safe `file://` decoding), reads only regular files inside the directory with the size checked first (`map.unreadable`, `map.pointer-outside-dir`), walks the whole output directory (only `node_modules`/`.git` skipped unless it is the project root), resolves bundler-scheme sources against the project root, reports the token's source (`env.token-source`; a missing token is a warning), and pairs maps with the stamp's own `localPointerTarget`. The same spread pattern was fixed in `stamp-files.ts`. Round 7: `--exclude` applies to SRI pins and map pointers, unmatched patterns are reported (`output.exclude-unmatched`), an all-unreadable output cannot pass, reads are bounded by bytes in flight, maps need `mappings`/`sections`, every distinct SRI pin is kept for the doctor, `passed` lists only checks that had input. Round 6: `--exclude ` (+ `exclude` option) drops files the build did not emit (`output.excluded`); the walk fence needs a `package.json` as well as cwd and reports what it skipped (`output.walk-fenced`); the stamp's own SRI guard keeps no page cap (only the doctor's scan does). Round 4: the HTML scan in `sri.ts` is linear (an `indexOf` scanner replaced the quadratic comment and script-tag regexes; a differential fuzz test pins identical results) and bounded (pages over 8 MiB are skipped and reported as `sri.html-skipped`); reads go through `safe-read.ts` (open with `O_NOFOLLOW`/`O_NONBLOCK`, type and size judged on the descriptor); in-directory symlinks are followed by real path; FIFOs/sockets/devices named like scripts are reported; a map reached through two names is judged once; long lists and the per-map `map.sources-content` notes are capped/aggregated. Real-build proof in `doctor.real-build.test.ts`: Vite 8 and 7, Rollup and Rspack stamped by the real plugin and CLI (healthy), an unstamped build, an inline-map build, and SRI builds (unstamped hazard, stamped-first clean, stamped-after-hash `sri.mismatch` produced by `bugsee-cli sourcemaps inject --allow-sri`). Webpack itself is not a dependency of this package; Rspack stands in for the shared in-build stamp path. Mutator loop: 10 mutations on the decision logic, all killed. **Not done:** an optional post-build `doctor` call in the plugins (the findings need a policy for failing a build; left as a follow-up), the Rust command, and every check that needs the backend (design hand-off: map-present-for-debug-ID, deployed-URL, synthetic symbolicate round trip). ### 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/source-maps-usage.md b/docs/source-maps-usage.md index f2b56519c..c415abb04 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -232,7 +232,9 @@ npx bugsee-sourcemaps-doctor dist --strict # warnings fail the step too (exi npx bugsee-sourcemaps-doctor dist --deployed # the directory is served: leftover .map files warn ``` -`--strict` passes straight after a default plugin run (maps removed after upload, bundles stamped) when the directory holds only what the build emitted. Scripts copied in (Vite `publicDir`, a copy plugin) are never stamped by the plugin and are indistinguishable from a bundle that lost its stamp: exclude them by path with `--exclude 'public/**'` (repeatable; listed as `output.excluded`). A directory that is a project (has a `package.json`) and is the working directory is walked fenced (no `src`, `test`, dot-directories, depth > 6), and the skipped directories are listed as `output.walk-fenced`. Other options: `--ignore ` (repeatable; hard failures such as `output.no-js` cannot be ignored), `--project-root`, `--max-map-mb`, `--no-env`, `--`. +The `bugsee-sourcemaps-doctor` binary ships in `@bugsee/bundler-plugin-core`, not in a package of that name: in a project that has it installed (every Bugsee build plugin depends on it) `npx bugsee-sourcemaps-doctor` runs it; otherwise use `npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist`. + +`--strict` passes straight after a default plugin run (maps removed after upload, bundles stamped) when the directory holds only what the build emitted. Scripts copied in (Vite `publicDir`, a copy plugin) are never stamped by the plugin and are indistinguishable from a bundle that lost its stamp: exclude them by path, relative to the checked directory (Vite copies `public/` to the ROOT of the output, so `--exclude sw.js --exclude 'pdf.worker.min.mjs*'`; repeatable; listed as `output.excluded`, and a pattern that matches nothing is reported as `output.exclude-unmatched`). `--exclude` only removes files from the audit, not from what you deploy. A directory that is a project (has a `package.json`) and is the working directory is walked fenced (no `src`, `test`, dot-directories, depth > 6), and the skipped directories are listed as `output.walk-fenced`. Other options: `--ignore ` (repeatable; hard failures such as `output.no-js` cannot be ignored), `--project-root`, `--max-map-mb`, `--no-env`, `--`. Exit codes: `0` ok, `1` warnings only (with `--strict`), `2` errors. The package is `@bugsee/bundler-plugin-core`; the same report is available in code as `diagnoseBuildOutput(dir, options)`. @@ -245,7 +247,7 @@ Typical findings and what to do: | `map.pointer-dangling` | The bundle's `sourceMappingURL` points at a map that is not on disk. A note when no `.map` is left and every bundle is stamped (maps removed after upload); otherwise a warning. Use hidden maps to avoid the 404. | | `map.inline` | The map is a `data:` URL inside the bundle: nothing to upload, and it ships to every visitor. | | `map.sources-unresolvable` | No `sourcesContent` and the sources are not on disk: frames will have no source lines. | -| `map.public-leftover` | `.map` files are in the directory. A note by default; a warning with `--deployed` (you serve this directory). Keep `deleteMaps` on or exclude `*.map`. | +| `map.public-leftover` | `.map` files are in the directory. A note by default; a warning with `--deployed` (you serve this directory). Keep `deleteMaps` on, or remove the maps / leave them out of the deploy (`--exclude` does not help: it only hides them from this audit). | | `sri.unstamped-hazard` / `sri.mismatch` / `sri.manifest-hashes` | Subresource Integrity hashes pin these scripts; stamping after hashing makes the browser block them. | | `env.token-missing` | No app token is visible to the build (a warning): the plugin is disabled and uploads nothing, which is fine if you upload with `bugsee-cli` by hand. `env.token-source` says where a found token comes from, never its value. | diff --git a/packages/bundler-plugin-core/README.md b/packages/bundler-plugin-core/README.md index 6d45a0a55..e846d6b4e 100644 --- a/packages/bundler-plugin-core/README.md +++ b/packages/bundler-plugin-core/README.md @@ -30,7 +30,9 @@ npx bugsee-sourcemaps-doctor dist --json # machine-readable report (schemaVe npx bugsee-sourcemaps-doctor dist --strict # exit 1 on warnings too ``` -Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks), `--deployed` (the directory is, or is about to be, served: leftover `.map` files become a warning instead of a note), `--exclude ` (files the build did not emit, e.g. `public/**` for scripts copied from Vite's `publicDir` or by a copy plugin: the plugin never stamps those and a doctor cannot tell them from a bundle that lost its stamp; repeatable; `*` stays in a directory, `**` crosses them; matches are listed as `output.excluded`), `--ignore ` (drop a check ID; repeatable; `output.dir-missing`, `output.no-js` and `doctor.internal-error` cannot be ignored), `--` (end of options); `--key=value` works for options that take a value, and `--strict=false`-style values on flags are refused. Before the upload (hidden maps still on disk, the plugin will delete them) and after it (maps removed), `--strict` passes on a healthy build; add `--deployed` only when checking the directory you serve. Straight after a default plugin run `--strict` passes for a build whose output directory holds only what the build emitted (add `--exclude` for copied-in scripts): leftover maps are a note unless `--deployed`, and a pointer to maps removed on purpose from a fully stamped build is a note. +The `bugsee-sourcemaps-doctor` binary ships in `@bugsee/bundler-plugin-core`, not in a package of that name: in a project that has it installed (every Bugsee build plugin depends on it) `npx bugsee-sourcemaps-doctor` runs it; otherwise use `npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist`. + +Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks), `--deployed` (the directory is, or is about to be, served: leftover `.map` files become a warning instead of a note), `--exclude ` (files the build did not emit, e.g. `sw.js` or `pdf.worker.min.mjs*` for scripts copied from Vite's `publicDir` (it lands at the ROOT of the output) or by a copy plugin, relative to the checked directory, a leading `./` is fine; a pattern that matches nothing is reported as `output.exclude-unmatched`: the plugin never stamps those and a doctor cannot tell them from a bundle that lost its stamp; repeatable; `*` stays in a directory, `**` crosses them; matches are listed as `output.excluded`), `--ignore ` (drop a check ID; repeatable; `output.dir-missing`, `output.no-js` and `doctor.internal-error` cannot be ignored), `--` (end of options); `--key=value` works for options that take a value, and `--strict=false`-style values on flags are refused. Before the upload (hidden maps still on disk, the plugin will delete them) and after it (maps removed), `--strict` passes on a healthy build; add `--deployed` only when checking the directory you serve. Straight after a default plugin run `--strict` passes for a build whose output directory holds only what the build emitted (add `--exclude` for copied-in scripts): leftover maps are a note unless `--deployed`, and a pointer to maps removed on purpose from a fully stamped build is a note. It checks, each with a stable ID, a severity and a fix hint: the output directory and its JavaScript; the debug-ID comment and `_bugseeDebugIds` registration on every bundle; a matching map with the same ID; `sourceMappingURL` pointers (dangling, hidden, inline); map validity (v3, `sources`, `sourcesContent` embedded or resolvable on disk, size); mixed stamped/unstamped bundles; duplicate IDs across different contents; Subresource Integrity hazards and mismatches (pages and `*manifest*.json` inside the directory only; a page larger than 8 MiB is reported, not scanned); leftover `.map` files that a deploy would serve; development-mode bundles; and the build environment (token present, version and build resolvable, `NODE_ENV`). The token value is never printed; the report says where it came from (option, environment variable, or `.env.bugsee-build-plugin`), and a missing token is a warning, because uploading by hand is legitimate. When the checked directory is itself a project directory (has a `package.json`) and is, or contains, the working directory, the walk skips `src`/`test`/dot-directories and stops below depth 6 so it stays out of a source tree; the skipped directories are listed as `output.walk-fenced`, never silent. The doctor never throws (an internal failure is a `doctor.internal-error` finding), never reads outside the checked directory, never opens a FIFO, socket or device (they are reported), reads a symlink only when its real path stays inside the checked directory (a pnpm-style `assets/app.js -> ../.store/app.js` is fine; one that leads out, dangles or loops is reported), judges type and size on the open file descriptor, and checks a map's size before reading it. Programmatic use: `diagnoseBuildOutput(dir, options)` returns the same report. The backend-assisted checks (is this ID's map uploaded?) are not part of this command; see `docs/source-maps-usage.md` §4. diff --git a/packages/bundler-plugin-core/package.json b/packages/bundler-plugin-core/package.json index 55d4d2f2b..a99052366 100644 --- a/packages/bundler-plugin-core/package.json +++ b/packages/bundler-plugin-core/package.json @@ -22,7 +22,7 @@ ], "sideEffects": false, "scripts": { - "build": "tsup", + "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup", "typecheck": "tsc --noEmit", "test": "vitest run", "test:coverage": "vitest run --coverage" diff --git a/packages/bundler-plugin-core/src/doctor-cli.test.ts b/packages/bundler-plugin-core/src/doctor-cli.test.ts index 9e3eca5b6..5fd416d8c 100644 --- a/packages/bundler-plugin-core/src/doctor-cli.test.ts +++ b/packages/bundler-plugin-core/src/doctor-cli.test.ts @@ -97,7 +97,13 @@ describe('runDoctorCli', () => { writeFileSync(join(dist, 'a.js'), stamped); writeFileSync( join(dist, 'a.js.map'), - JSON.stringify({ version: 3, debugId: ID, sources: ['a'], sourcesContent: ['x'] }), + JSON.stringify({ + version: 3, + debugId: ID, + sources: ['a'], + sourcesContent: ['x'], + mappings: 'AAAA', + }), ); const args = [dist, '--no-env', '--strict']; expect((await cli(args)).code).toBe(0); diff --git a/packages/bundler-plugin-core/src/doctor-cli.ts b/packages/bundler-plugin-core/src/doctor-cli.ts index 411f96870..e1bd06e81 100644 --- a/packages/bundler-plugin-core/src/doctor-cli.ts +++ b/packages/bundler-plugin-core/src/doctor-cli.ts @@ -27,7 +27,7 @@ Options: --no-env Skip the token / version / build / NODE_ENV checks. --deployed The directory is (about to be) served: leftover .map files become a warning. --ignore Drop a check ID from the report; repeatable. - --exclude Do not check files the build did not emit (e.g. 'public/**'); repeatable. + --exclude Do not check files the build did not emit (e.g. sw.js; relative to ); repeatable. -- End of options (a directory may start with a dash after it). -h, --help Show this help. diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index 5687b5e41..0ce6d0d53 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -14,7 +14,7 @@ import { import { tmpdir } from 'node:os'; import { dirname, join, win32 } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { type DoctorReport, diagnoseBuildOutput, sourcePath, walk } from './doctor'; +import { batchEnd, type DoctorReport, diagnoseBuildOutput, sourcePath, walk } from './doctor'; import { listOutputMaps } from './stamp-files'; const ID_A = '11111111-1111-4111-8111-111111111111'; @@ -432,7 +432,8 @@ describe('symlinks never lead outside the output directory (round 3)', () => { writeFileSync(real, `a${stamp(ID_A)}`); symlinkSync(real, join(dist, 'app.js')); const report = await run(); - expect(ids(report)).not.toContain('output.no-js'); + // not the misleading "No .js files found": the script IS there, and nothing could be read + expect(find(report, 'output.no-js')?.message).toContain('could be read'); expect(find(report, 'output.unreadable')?.details).toEqual({ files: ['app.js resolves outside the output directory'], }); @@ -485,7 +486,7 @@ describe('SRI reads are as guarded as every other read (review thread)', () => { expect(find(report, 'output.unreadable')?.details).toEqual({ files: ['app.js is not a regular file'], }); - expect(ids(report)).not.toContain('output.no-js'); + expect(find(report, 'output.no-js')?.message).toContain('could be read'); expect(ids(report)).not.toContain('sri.mismatch'); expect(ids(report)).not.toContain('sri.unstamped-hazard'); expect(find(report, 'sri.pin-unreadable')?.details).toEqual({ @@ -685,9 +686,58 @@ describe('files the build did not emit (round 6)', () => { }); }); - it('an exclude that matches nothing says nothing', async () => { + it('an exclude that matches nothing is SAID (a silent miss looks like a bug in the doctor), as an info', async () => { + healthy(); + const report = await run({ exclude: ['nope/**', 'app.js'] }); + expect(ids(report)).toContain('output.excluded'); // app.js matched + expect(find(report, 'output.exclude-unmatched')).toMatchObject({ + severity: 'info', + details: { patterns: ['nope/**'] }, + }); + expect(ids(await run({ exclude: ['app.js'] }))).not.toContain('output.exclude-unmatched'); + }); + + it('Vite copies publicDir to the ROOT of the output: root-level patterns and a leading ./ both work', async () => { + healthy(); + put('mockServiceWorker.js', 'w'); + put('pdf.worker.min.mjs', 'w'); + put('pdf.worker.min.mjs.map', mapJson()); + const report = await run({ exclude: ['./mockServiceWorker.js', 'pdf.worker.min.mjs*'] }); + expect(report.summary).toMatchObject({ errors: 0, warnings: 0, bundles: 1, maps: 1 }); + expect(find(report, 'output.excluded')?.details).toEqual({ + files: ['mockServiceWorker.js', 'pdf.worker.min.mjs', 'pdf.worker.min.mjs.map'], + }); + expect(ids(report)).not.toContain('output.exclude-unmatched'); + }); + + it('an excluded script pinned by a page is not judged for SRI either', async () => { + healthy(); + put('vendor.js', 'v'); + put('index.html', ``); + const before = await run(); + expect(ids(before)).toContain('sri.mismatch'); + const after = await run({ exclude: ['vendor.js'] }); + expect(ids(after)).not.toContain('sri.mismatch'); + expect(ids(after)).not.toContain('sri.unstamped-hazard'); + }); + + it('a pointer to an excluded map is neither read nor reported', async () => { + put('a.js', `a\n//# sourceMappingURL=maps/a.js.map${stamp(ID_A)}`); + put('maps/a.js.map', mapJson({ debugId: ID_B })); + expect(ids(await run())).toContain('stamp.map-id-mismatch'); + const report = await run({ exclude: ['maps/**'] }); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(find(report, 'output.excluded')?.details).toEqual({ files: ['maps/a.js.map'] }); + }); + + it('the new info-only IDs are facts, never "passed"', async () => { healthy(); - expect(ids(await run({ exclude: ['nope/**'] }))).not.toContain('output.excluded'); + put('public/x.js', 'x'); + const report = await run({ exclude: ['public/**'] }); + expect(report.passed).not.toContain('output.excluded'); + expect(report.passed).not.toContain('output.exclude-unmatched'); + expect(report.passed).not.toContain('output.walk-fenced'); }); it('glob semantics: * stays in a directory, ** crosses them, ? is one character, a trailing / is a directory', async () => { @@ -782,3 +832,97 @@ describe('the walk fence is reported, and needs a real project directory (round expect((await run()).summary.bundles).toBe(2); }); }); + +describe('round 7 review findings', () => { + const mkfifo = (path: string): boolean => spawnSync('mkfifo', [path]).status === 0; + const sri = (bytes: string): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + + it('when EVERY script is unreadable the audit cannot pass, even with --ignore output.unreadable', async () => { + if (!mkfifo(join(dist, 'a.js'))) { + return; + } + const report = await run({ ignore: ['output.unreadable'] }); + expect(find(report, 'output.no-js')).toMatchObject({ severity: 'error' }); + expect(find(report, 'output.no-js')?.message).toContain('could be read'); + }); + + it('some unreadable scripts are an ordinary, ignorable finding', async () => { + put('ok.js', `a${stamp(ID_A)}`); + if (!mkfifo(join(dist, 'a.js'))) { + return; + } + const report = await run({ ignore: ['output.unreadable'] }); + expect(ids(report)).not.toContain('output.no-js'); + }); + + it('a version-3 map without mappings (or sections) is map.invalid', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + put( + 'a.js.map', + JSON.stringify({ version: 3, sources: ['a.ts'], sourcesContent: ['x'], debugId: ID_A }), + ); + const report = await run(); + expect(find(report, 'map.invalid')?.message).toContain('mappings'); + put('a.js.map', mapJson({ debugId: ID_A, mappings: undefined, sections: [] })); + expect(ids(await run())).not.toContain('map.invalid'); + put('a.js.map', mapJson({ debugId: ID_A, mappings: 5 })); + expect(ids(await run())).toContain('map.invalid'); + }); + + it('an unreadable HTML page is reported as not scanned, never silently passed', async () => { + put('a.js', `a${stamp(ID_A)}`); + const page = put('index.html', ``); + chmodSync(page, 0o000); + try { + if (spawnSync('sh', ['-c', `cat '${page}' >/dev/null 2>&1`]).status === 0) { + return; // running as root: the permission does not bite + } + const finding = find(await run(), 'sri.html-skipped'); + expect(finding).toMatchObject({ severity: 'warning', details: { files: ['index.html'] } }); + expect(finding?.message).toContain('could not be read'); + } finally { + chmodSync(page, 0o600); + } + }); + + it('the same script pinned by two pages with different hashes: the stale pin is reported', async () => { + const js = `console.log(1);${stamp(ID_A)}`; + put('a.js', js); + put('a.html', ``); + put('b.html', ``); + const report = await run(); + expect(find(report, 'sri.mismatch')).toMatchObject({ details: { scripts: ['a.js'] } }); + }); + + it('passed lists only checks that had input: nothing for the stamp/map checks of an empty directory', async () => { + const report = await run(); + expect(ids(report)).toContain('output.no-js'); + for (const id of [ + 'stamp.missing-registration', + 'stamp.map-id-mismatch', + 'map.invalid', + 'build.dev-bundle', + ]) { + expect(report.passed).not.toContain(id); + } + put('a.js', `a${stamp(ID_A)}`); + const healthy = await run(); + expect(healthy.passed).toContain('stamp.missing-registration'); + expect(healthy.passed).not.toContain('map.invalid'); // a bundle but no map: nothing to validate + put('a.js.map', mapJson({ debugId: ID_A })); + expect((await run()).passed).toContain('map.invalid'); + }); +}); + +describe('batchEnd bounds the bytes read at once', () => { + it('stops at the count limit, at the byte budget, and always takes at least one', () => { + expect(batchEnd([1, 1, 1, 1], 0, 2, 100)).toBe(2); + expect(batchEnd([10, 10, 10, 10], 0, 16, 25)).toBe(2); + expect(batchEnd([10, 10, 10, 10], 0, 16, 20)).toBe(2); + expect(batchEnd([10, 10, 10, 10], 0, 16, 40)).toBe(4); + expect(batchEnd([500, 1, 1], 0, 16, 100)).toBe(1); + expect(batchEnd([1, 500, 1], 1, 16, 100)).toBe(2); + expect(batchEnd([1, 1], 1, 16, 100)).toBe(2); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts index ead25b1c6..157e588ea 100644 --- a/packages/bundler-plugin-core/src/doctor.ts +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -83,8 +83,29 @@ export interface DoctorOptions { const DEFAULT_MAX_MAP_BYTES = 50 * 1024 * 1024; const DEFAULT_MAX_BUNDLE_BYTES = 512 * 1024 * 1024; -/** Files read at once: bounds open handles and the bytes held in memory. */ +/** Files read at once: bounds open handles. */ const READ_CONCURRENCY = 16; +/** Bytes read at once (a batch of sixteen 512 MiB scripts is 8 GiB): a single larger file is still read, alone. */ +const READ_BYTE_BUDGET = 256 * 1024 * 1024; + +/** + * Where the batch starting at `start` ends (exclusive): at most `maxCount` files and `budget` bytes, but always at + * least one file. `sizes` are what `stat` reported. + */ +export function batchEnd( + sizes: readonly number[], + start: number, + maxCount: number, + budget: number, +): number { + let end = start + 1; + let total = sizes[start] ?? 0; + while (end < sizes.length && end - start < maxCount && total + (sizes[end] ?? 0) <= budget) { + total += sizes[end] ?? 0; + end++; + } + return end; +} const BUNDLE = /\.[cm]?js$/i; const MAP = /\.map$/i; /** The global the runtime stub writes the id into (`@bugsee/browser` reads it at crash time). */ @@ -97,6 +118,7 @@ export const DOCTOR_CHECK_IDS = [ 'output.no-js', 'output.unreadable', 'output.excluded', + 'output.exclude-unmatched', 'output.walk-fenced', 'stamp.missing-debug-id', 'stamp.missing-registration', @@ -415,12 +437,25 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise glob.replace(/^(\.\/)+/, '')); + const patterns = excludeGlobs.map(globToRegExp); + const matchedPatterns = new Set(); + const isExcluded = (path: string): boolean => { + const name = rel(dir, path); + let hit = false; + patterns.forEach((pattern, i) => { + if (pattern.test(name)) { + matchedPatterns.add(i); + hit = true; + } + }); + return hit; + }; const excluded: string[] = []; const files = walked.files.filter((file) => { - const name = rel(dir, file); - if (patterns.some((pattern) => pattern.test(name))) { - excluded.push(name); + if (isExcluded(file)) { + excluded.push(rel(dir, file)); return false; } return true; @@ -444,6 +479,15 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise !matchedPatterns.has(i)); + if (unmatched.length > 0) { + add({ + id: 'output.exclude-unmatched', + severity: 'info', + message: `${unmatched.length} --exclude pattern(s) matched no file (${unmatched.join(', ')}); patterns are relative to ${dir} (Vite copies publicDir to its ROOT: write sw.js, not public/sw.js).`, + details: { patterns: unmatched }, + }); + } if (walked.skipped.length > 0) { add({ id: 'output.walk-fenced', @@ -494,10 +538,21 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise + stat(path).then( + (info) => info.size, + () => 0, + ), + ), + ); + let readEnd = 0; for (let at = 0; at < bundles.length; at++) { - if (at % READ_CONCURRENCY === 0) { + if (at >= readEnd) { reads.clear(); - await readBatch(bundles.slice(at, at + READ_CONCURRENCY)); + readEnd = batchEnd(sizes, at, READ_CONCURRENCY, READ_BYTE_BUDGET); + await readBatch(bundles.slice(at, readEnd)); } const bundle = bundles[at] as string; const name = rel(dir, bundle); @@ -529,6 +584,8 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise ${pointer}`); } else if (mapSet.has(target)) { mapPath = target; + } else if (isExcluded(target)) { + // an excluded map is not the build's: neither read nor reported as dangling } else { // A symlinked DIRECTORY on the way can lead out although the path looks inside: judge the // real path, never read through it. @@ -687,6 +744,16 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise 0 && unreadable.length === bundles.length) { + // Nothing was audited: that must not be ignorable into a pass (`--ignore output.unreadable`). + add({ + id: 'output.no-js', + severity: 'error', + message: `None of the ${bundles.length} script(s) under ${dir} could be read, so nothing was checked.`, + fix: 'Make the scripts regular files that the current user can read, and run the doctor again.', + }); + } if (unreadable.length > 0) { add({ id: 'output.unreadable', @@ -884,7 +960,7 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise !isExcluded(pin.script)); if (sriScan.skippedPages.length > 0) { const names = sriScan.skippedPages.map((page) => rel(dir, page.html)); add({ @@ -895,6 +971,16 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise 0) { + const names = sriScan.unreadablePages.map((page) => rel(dir, page)); + add({ + id: 'sri.html-skipped', + severity: 'warning', + message: `${names.length} page(s) could not be read and were not scanned for integrity pins (${names.slice(0, MAX_LISTED).join(', ')}${names.length > MAX_LISTED ? ', …' : ''}); a script they pin would not be noticed.`, + fix: 'Make the pages readable and run the doctor again.', + details: listDetails('files', names), + }); + } if (pinned.length > 0) { const unstampedPinned: typeof pinned = []; const mismatches: typeof pinned = []; @@ -1031,15 +1117,38 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise id.startsWith('stamp.') || NEEDS_BUNDLES.has(id); const passed = DOCTOR_CHECK_IDS.filter( (id) => - !failed.has(id) && !INFO_ONLY.has(id) && !(options.skipEnv === true && id.startsWith('env.')), + !failed.has(id) && + !INFO_ONLY.has(id) && + !(options.skipEnv === true && id.startsWith('env.')) && + !(bundles.length === 0 && needsBundles(id)) && + !(maps.length === 0 && NEEDS_MAPS.has(id)), ); return finish(dir, findings, bundles.length, maps.length, passed, options.ignore); } +const NEEDS_BUNDLES: ReadonlySet = new Set([ + 'build.dev-bundle', + 'map.pointer-dangling', + 'map.pointer-outside-dir', + 'map.inline', +]); +const NEEDS_MAPS: ReadonlySet = new Set([ + 'map.invalid', + 'map.no-sources', + 'map.sources-unresolvable', + 'map.too-large', + 'map.unreadable', +]); + /** Checks that only ever produce an `info` finding: they are not "passed", they are facts. */ const INFO_ONLY: ReadonlySet = new Set([ + 'output.excluded', + 'output.exclude-unmatched', + 'output.walk-fenced', 'map.hidden', 'map.sources-content', 'env.token-source', diff --git a/packages/bundler-plugin-core/src/safe-read.ts b/packages/bundler-plugin-core/src/safe-read.ts index e5f1352ab..7185718e1 100644 --- a/packages/bundler-plugin-core/src/safe-read.ts +++ b/packages/bundler-plugin-core/src/safe-read.ts @@ -11,7 +11,11 @@ export type ReadResult = | { ok: true; bytes: Buffer } | { ok: false; reason: string; tooLarge?: { size: number } }; -/** `O_NOFOLLOW` / `O_NONBLOCK` are absent on some platforms (Windows): then the descriptor checks still apply. */ +/** + * `O_NOFOLLOW` / `O_NONBLOCK` are absent on some platforms (Windows). There the "never follows a symlink in the last + * component" guarantee is WEAKER: only the descriptor checks (regular file, size) apply, and callers that must stay + * inside a directory (`readInside` in doctor.ts) additionally resolve the real path and check containment first. + */ const OPEN_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0); /** diff --git a/packages/bundler-plugin-core/src/sri.scan.test.ts b/packages/bundler-plugin-core/src/sri.scan.test.ts index 86ce98f44..299eabd16 100644 --- a/packages/bundler-plugin-core/src/sri.scan.test.ts +++ b/packages/bundler-plugin-core/src/sri.scan.test.ts @@ -27,6 +27,16 @@ const SCRIPT_TAG = /]*>/gi; const PRELOAD_TAG = /]*>/gi; const HTML_COMMENT = //g; +it('the detailed scan keeps every distinct pin of a script; the stamp wrapper one per script', async () => { + const dir = await fixture(); + await writeFile(join(dir, 'a.html'), ''); + await writeFile(join(dir, 'b.html'), ''); + await writeFile(join(dir, 'c.html'), ''); + const detailed = await findSriProtectedScriptsDetailed(dir); + expect(detailed.scripts.map((s) => s.integrity)).toEqual(['sha384-AAA', 'sha384-BBB']); + expect(await findSriProtectedScripts(dir)).toHaveLength(1); +}); + it('MAX_HTML_BYTES is 8 MiB', () => { expect(MAX_HTML_BYTES).toBe(8 * 1024 * 1024); }); diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index 008f290db..4e5d40fd3 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -162,13 +162,19 @@ const walkHtml = async (dir: string, depth = 0): Promise => { export async function findSriProtectedScripts(outDirInput: string): Promise { // No page cap here: this is the guard stamping relies on, and a pin it cannot see is a script stamping would // break. Only the diagnostic (which must stay bounded on hostile input) passes a cap. - return (await findSriProtectedScriptsDetailed(outDirInput, Number.POSITIVE_INFINITY)).scripts; + const scripts = (await findSriProtectedScriptsDetailed(outDirInput, Number.POSITIVE_INFINITY)) + .scripts; + // One entry per script (the first pin found): stamping asks "is this script pinned at all", the doctor wants every pin. + const seen = new Set(); + return scripts.filter((pin) => !seen.has(pin.script) && seen.add(pin.script)); } /** What {@link findSriProtectedScripts} found, and the pages it did not scan because they are larger than {@link MAX_HTML_BYTES}. */ export interface SriScan { scripts: SriProtectedScript[]; skippedPages: Array<{ html: string; size: number }>; + /** Pages that exist but could not be read (permissions, a race): their pins were NOT checked. */ + unreadablePages: string[]; } export async function findSriProtectedScriptsDetailed( @@ -184,11 +190,14 @@ export async function findSriProtectedScriptsDetailed( const seen = new Set(); const found: SriProtectedScript[] = []; const skippedPages: SriScan['skippedPages'] = []; + const unreadablePages: string[] = []; for (const html of pages.sort()) { const read = await readRegularFile(html, maxHtmlBytes); if (!read.ok) { if (read.tooLarge !== undefined) { skippedPages.push({ html, size: read.tooLarge.size }); + } else { + unreadablePages.push(html); // any other failure: the page's pins were NOT checked, and that is said } continue; } @@ -208,14 +217,15 @@ export async function findSriProtectedScriptsDetailed( } const script = resolveLocalScript(outDir, htmlDir, unquote(url)); // Only a JS file we emit can be broken by inject; a `.mjs`/`.cjs` counts, a `.wasm` does not. - if (script === undefined || !/\.[cm]?js$/i.test(script) || seen.has(script)) { + const pin = unquote(integrity).trim(); + if (script === undefined || !/\.[cm]?js$/i.test(script) || seen.has(`${script}\0${pin}`)) { continue; } - seen.add(script); - found.push({ html, script, integrity: unquote(integrity).trim() }); + seen.add(`${script}\0${pin}`); + found.push({ html, script, integrity: pin }); } } - return { scripts: found, skippedPages }; + return { scripts: found, skippedPages, unreadablePages }; } /** SRI's hash algorithms, weakest to strongest — the order the spec compares them in. */ diff --git a/packages/bundler-plugin-core/tsup.config.ts b/packages/bundler-plugin-core/tsup.config.ts index 59d4edcd6..68c8411be 100644 --- a/packages/bundler-plugin-core/tsup.config.ts +++ b/packages/bundler-plugin-core/tsup.config.ts @@ -1,11 +1,13 @@ import { defineConfig } from 'tsup'; import { baseConfig } from '../../tsup.config.base'; +// tsup builds the entries below in PARALLEL, so neither may clean `dist` (a clean that runs after the other entry's +// write would delete it and the build would still succeed). The package `build` script empties `dist` first instead. export default defineConfig([ - baseConfig, + { ...baseConfig, clean: false }, { // `bugsee-sourcemaps-doctor`: an ESM-only executable (its entry guard reads `import.meta.url`, which a CJS - // build does not have). `clean: false` so it does not wipe the library build above. + // build does not have). ...baseConfig, entry: ['src/doctor-cli.ts'], format: ['esm'], From efb61bd155b39487f2497a262246defd2827c05d Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 15:38:28 +0500 Subject: [PATCH 55/63] fix(bundler-plugin-core): doctor SRI page walk follows the doctor fence; docs always name the package for npx Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .changeset/sourcemaps-doctor.md | 2 +- docs/PROGRESS.md | 2 +- docs/source-maps-usage.md | 10 ++-- packages/bundler-plugin-core/README.md | 8 ++-- .../src/doctor.hardening.test.ts | 46 +++++++++++++++++++ packages/bundler-plugin-core/src/doctor.ts | 8 ++-- .../bundler-plugin-core/src/sri.scan.test.ts | 21 +++++++++ packages/bundler-plugin-core/src/sri.ts | 16 +++++-- 8 files changed, 94 insertions(+), 19 deletions(-) diff --git a/.changeset/sourcemaps-doctor.md b/.changeset/sourcemaps-doctor.md index 52ee6f9f4..6567f7163 100644 --- a/.changeset/sourcemaps-doctor.md +++ b/.changeset/sourcemaps-doctor.md @@ -2,4 +2,4 @@ '@bugsee/bundler-plugin-core': minor --- -Adds `bugsee-sourcemaps-doctor`, an offline check of a build output directory (`npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist`, or `npx bugsee-sourcemaps-doctor dist` where the package is installed; `--json`, `--strict`, `--deployed`, `--ignore `, `--exclude `), and the matching `diagnoseBuildOutput(dir, options)` API with a versioned report (`schemaVersion: 1`). It tells you why a crash from the build would not symbolicate: unstamped bundles or a missing runtime registration, a map whose debugId differs from its bundle's, dangling, hidden or inline source maps, invalid maps and missing `sourcesContent`, duplicate IDs, Subresource Integrity hazards, leftover public maps, development bundles, and the build environment (token source, version, build, `NODE_ENV`; the token value is never printed). Exit 0 ok, 1 warnings with `--strict`, 2 errors. Also: `stamp-files` no longer spreads large file lists onto the call stack (a directory with more than ~125k scripts or maps overflowed it). The Subresource Integrity page scan in the build plugins is now linear (quadratic regexes on pages with thousands of unterminated tags or comments are replaced by an `indexOf` scanner, with a differential test pinning identical results) and pages larger than 8 MiB are skipped. +Adds `bugsee-sourcemaps-doctor`, an offline check of a build output directory (`npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist`; `--json`, `--strict`, `--deployed`, `--ignore `, `--exclude `), and the matching `diagnoseBuildOutput(dir, options)` API with a versioned report (`schemaVersion: 1`). It tells you why a crash from the build would not symbolicate: unstamped bundles or a missing runtime registration, a map whose debugId differs from its bundle's, dangling, hidden or inline source maps, invalid maps and missing `sourcesContent`, duplicate IDs, Subresource Integrity hazards, leftover public maps, development bundles, and the build environment (token source, version, build, `NODE_ENV`; the token value is never printed). Exit 0 ok, 1 warnings with `--strict`, 2 errors. Also: `stamp-files` no longer spreads large file lists onto the call stack (a directory with more than ~125k scripts or maps overflowed it). The Subresource Integrity page scan in the build plugins is now linear (quadratic regexes on pages with thousands of unterminated tags or comments are replaced by an `indexOf` scanner, with a differential test pinning identical results) and pages larger than 8 MiB are skipped. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 31f1eabcf..7d231e9a2 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1533,7 +1533,7 @@ Verified against current majors, all green with no adapter code changes: `@bugse `@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. ### `sourcemaps doctor`: offline build-output diagnostics (2026-11-23) -`@bugsee/bundler-plugin-core` ships `diagnoseBuildOutput(dir, options)` (`src/doctor.ts`) and the `bugsee-sourcemaps-doctor` bin (`src/doctor-cli.ts`, ESM-only tsup entry, wired through `publishConfig.bin`). 35 check IDs (`DOCTOR_CHECK_IDS`) over the output directory, bundles, maps, SRI (reusing `sri.ts`), leftover maps and the build environment (token, version, build, `NODE_ENV`; the token is never printed), each with a severity and a fix hint, and one versioned JSON report (`schemaVersion: 1`) that the Rust `bugsee-cli sourcemaps doctor` is specified to share. Exit codes 0 ok, 1 warnings only with `--strict`, 2 errors. Review round (PR #222): `--strict` passes straight after a plugin run (`map.public-leftover` is a note unless `--deployed`; `map.pointer-dangling` is a note when no map is left and every bundle is stamped; `--ignore `), the doctor never throws (`doctor.internal-error`; no spread of large lists, safe `file://` decoding), reads only regular files inside the directory with the size checked first (`map.unreadable`, `map.pointer-outside-dir`), walks the whole output directory (only `node_modules`/`.git` skipped unless it is the project root), resolves bundler-scheme sources against the project root, reports the token's source (`env.token-source`; a missing token is a warning), and pairs maps with the stamp's own `localPointerTarget`. The same spread pattern was fixed in `stamp-files.ts`. Round 7: `--exclude` applies to SRI pins and map pointers, unmatched patterns are reported (`output.exclude-unmatched`), an all-unreadable output cannot pass, reads are bounded by bytes in flight, maps need `mappings`/`sections`, every distinct SRI pin is kept for the doctor, `passed` lists only checks that had input. Round 6: `--exclude ` (+ `exclude` option) drops files the build did not emit (`output.excluded`); the walk fence needs a `package.json` as well as cwd and reports what it skipped (`output.walk-fenced`); the stamp's own SRI guard keeps no page cap (only the doctor's scan does). Round 4: the HTML scan in `sri.ts` is linear (an `indexOf` scanner replaced the quadratic comment and script-tag regexes; a differential fuzz test pins identical results) and bounded (pages over 8 MiB are skipped and reported as `sri.html-skipped`); reads go through `safe-read.ts` (open with `O_NOFOLLOW`/`O_NONBLOCK`, type and size judged on the descriptor); in-directory symlinks are followed by real path; FIFOs/sockets/devices named like scripts are reported; a map reached through two names is judged once; long lists and the per-map `map.sources-content` notes are capped/aggregated. Real-build proof in `doctor.real-build.test.ts`: Vite 8 and 7, Rollup and Rspack stamped by the real plugin and CLI (healthy), an unstamped build, an inline-map build, and SRI builds (unstamped hazard, stamped-first clean, stamped-after-hash `sri.mismatch` produced by `bugsee-cli sourcemaps inject --allow-sri`). Webpack itself is not a dependency of this package; Rspack stands in for the shared in-build stamp path. Mutator loop: 10 mutations on the decision logic, all killed. **Not done:** an optional post-build `doctor` call in the plugins (the findings need a policy for failing a build; left as a follow-up), the Rust command, and every check that needs the backend (design hand-off: map-present-for-debug-ID, deployed-URL, synthetic symbolicate round trip). +`@bugsee/bundler-plugin-core` ships `diagnoseBuildOutput(dir, options)` (`src/doctor.ts`) and the `bugsee-sourcemaps-doctor` bin (`src/doctor-cli.ts`, ESM-only tsup entry, wired through `publishConfig.bin`). 35 check IDs (`DOCTOR_CHECK_IDS`) over the output directory, bundles, maps, SRI (reusing `sri.ts`), leftover maps and the build environment (token, version, build, `NODE_ENV`; the token is never printed), each with a severity and a fix hint, and one versioned JSON report (`schemaVersion: 1`) that the Rust `bugsee-cli sourcemaps doctor` is specified to share. Exit codes 0 ok, 1 warnings only with `--strict`, 2 errors. Review round (PR #222): `--strict` passes straight after a plugin run (`map.public-leftover` is a note unless `--deployed`; `map.pointer-dangling` is a note when no map is left and every bundle is stamped; `--ignore `), the doctor never throws (`doctor.internal-error`; no spread of large lists, safe `file://` decoding), reads only regular files inside the directory with the size checked first (`map.unreadable`, `map.pointer-outside-dir`), walks the whole output directory (only `node_modules`/`.git` skipped unless it is the project root), resolves bundler-scheme sources against the project root, reports the token's source (`env.token-source`; a missing token is a warning), and pairs maps with the stamp's own `localPointerTarget`. The same spread pattern was fixed in `stamp-files.ts`. Round 8: the SRI page walk follows the doctor's fence (full walk for an output directory, reported fence otherwise); docs always use `npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor`. Round 7: `--exclude` applies to SRI pins and map pointers, unmatched patterns are reported (`output.exclude-unmatched`), an all-unreadable output cannot pass, reads are bounded by bytes in flight, maps need `mappings`/`sections`, every distinct SRI pin is kept for the doctor, `passed` lists only checks that had input. Round 6: `--exclude ` (+ `exclude` option) drops files the build did not emit (`output.excluded`); the walk fence needs a `package.json` as well as cwd and reports what it skipped (`output.walk-fenced`); the stamp's own SRI guard keeps no page cap (only the doctor's scan does). Round 4: the HTML scan in `sri.ts` is linear (an `indexOf` scanner replaced the quadratic comment and script-tag regexes; a differential fuzz test pins identical results) and bounded (pages over 8 MiB are skipped and reported as `sri.html-skipped`); reads go through `safe-read.ts` (open with `O_NOFOLLOW`/`O_NONBLOCK`, type and size judged on the descriptor); in-directory symlinks are followed by real path; FIFOs/sockets/devices named like scripts are reported; a map reached through two names is judged once; long lists and the per-map `map.sources-content` notes are capped/aggregated. Real-build proof in `doctor.real-build.test.ts`: Vite 8 and 7, Rollup and Rspack stamped by the real plugin and CLI (healthy), an unstamped build, an inline-map build, and SRI builds (unstamped hazard, stamped-first clean, stamped-after-hash `sri.mismatch` produced by `bugsee-cli sourcemaps inject --allow-sri`). Webpack itself is not a dependency of this package; Rspack stands in for the shared in-build stamp path. Mutator loop: 10 mutations on the decision logic, all killed. **Not done:** an optional post-build `doctor` call in the plugins (the findings need a policy for failing a build; left as a follow-up), the Rust command, and every check that needs the backend (design hand-off: map-present-for-debug-ID, deployed-URL, synthetic symbolicate round trip). ### 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/source-maps-usage.md b/docs/source-maps-usage.md index c415abb04..3f0d1fa96 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -226,13 +226,13 @@ stub the SDK reads. This is exactly what the plugins automate; the CLI is the sa When a production crash does not de-minify, run the doctor against the build output you actually deployed (or are about to). It is offline: it reads the files and makes no network call. The token is only looked up (never printed) so the report can say where it comes from; a missing token is a warning, not an error. ```bash -npx bugsee-sourcemaps-doctor dist # readable report, fix hint per finding -npx bugsee-sourcemaps-doctor dist --json # for CI (schemaVersion 1) -npx bugsee-sourcemaps-doctor dist --strict # warnings fail the step too (exit 1) -npx bugsee-sourcemaps-doctor dist --deployed # the directory is served: leftover .map files warn +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist # readable report, fix hint per finding +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --json # for CI (schemaVersion 1) +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --strict # warnings fail the step too (exit 1) +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --deployed # the directory is served: leftover .map files warn ``` -The `bugsee-sourcemaps-doctor` binary ships in `@bugsee/bundler-plugin-core`, not in a package of that name: in a project that has it installed (every Bugsee build plugin depends on it) `npx bugsee-sourcemaps-doctor` runs it; otherwise use `npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist`. +The binary ships in `@bugsee/bundler-plugin-core`, so always name the package as above (a bare `npx bugsee-sourcemaps-doctor` is only safe when it is already linked into `node_modules/.bin`, which pnpm and Yarn do for direct dependencies only; otherwise npx asks the public registry for an unrelated name). `--strict` passes straight after a default plugin run (maps removed after upload, bundles stamped) when the directory holds only what the build emitted. Scripts copied in (Vite `publicDir`, a copy plugin) are never stamped by the plugin and are indistinguishable from a bundle that lost its stamp: exclude them by path, relative to the checked directory (Vite copies `public/` to the ROOT of the output, so `--exclude sw.js --exclude 'pdf.worker.min.mjs*'`; repeatable; listed as `output.excluded`, and a pattern that matches nothing is reported as `output.exclude-unmatched`). `--exclude` only removes files from the audit, not from what you deploy. A directory that is a project (has a `package.json`) and is the working directory is walked fenced (no `src`, `test`, dot-directories, depth > 6), and the skipped directories are listed as `output.walk-fenced`. Other options: `--ignore ` (repeatable; hard failures such as `output.no-js` cannot be ignored), `--project-root`, `--max-map-mb`, `--no-env`, `--`. diff --git a/packages/bundler-plugin-core/README.md b/packages/bundler-plugin-core/README.md index e846d6b4e..a08d9de27 100644 --- a/packages/bundler-plugin-core/README.md +++ b/packages/bundler-plugin-core/README.md @@ -25,12 +25,12 @@ npm install --save-dev @bugsee/vite-plugin An offline check of a build output directory: why would a crash from this build not symbolicate? No network call; a token is not required (a missing one is only a warning). ```bash -npx bugsee-sourcemaps-doctor dist # human report -npx bugsee-sourcemaps-doctor dist --json # machine-readable report (schemaVersion 1) -npx bugsee-sourcemaps-doctor dist --strict # exit 1 on warnings too +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist # human report +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --json # machine-readable report (schemaVersion 1) +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --strict # exit 1 on warnings too ``` -The `bugsee-sourcemaps-doctor` binary ships in `@bugsee/bundler-plugin-core`, not in a package of that name: in a project that has it installed (every Bugsee build plugin depends on it) `npx bugsee-sourcemaps-doctor` runs it; otherwise use `npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist`. +The binary ships in `@bugsee/bundler-plugin-core`, not in a package of its own name, so always name the package (a bare `npx bugsee-sourcemaps-doctor` asks the public registry for an unrelated, unclaimed name unless it happens to be linked into `node_modules/.bin`; pnpm and Yarn link only the bins of direct dependencies). With the package as a direct dependency, `pnpm exec bugsee-sourcemaps-doctor dist` works too. Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks), `--deployed` (the directory is, or is about to be, served: leftover `.map` files become a warning instead of a note), `--exclude ` (files the build did not emit, e.g. `sw.js` or `pdf.worker.min.mjs*` for scripts copied from Vite's `publicDir` (it lands at the ROOT of the output) or by a copy plugin, relative to the checked directory, a leading `./` is fine; a pattern that matches nothing is reported as `output.exclude-unmatched`: the plugin never stamps those and a doctor cannot tell them from a bundle that lost its stamp; repeatable; `*` stays in a directory, `**` crosses them; matches are listed as `output.excluded`), `--ignore ` (drop a check ID; repeatable; `output.dir-missing`, `output.no-js` and `doctor.internal-error` cannot be ignored), `--` (end of options); `--key=value` works for options that take a value, and `--strict=false`-style values on flags are refused. Before the upload (hidden maps still on disk, the plugin will delete them) and after it (maps removed), `--strict` passes on a healthy build; add `--deployed` only when checking the directory you serve. Straight after a default plugin run `--strict` passes for a build whose output directory holds only what the build emitted (add `--exclude` for copied-in scripts): leftover maps are a note unless `--deployed`, and a pointer to maps removed on purpose from a fully stamped build is a note. diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index 0ce6d0d53..7a8b35ce2 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -926,3 +926,49 @@ describe('batchEnd bounds the bytes read at once', () => { expect(batchEnd([1, 1], 1, 16, 100)).toBe(2); }); }); + +describe('the SRI page walk follows the doctor fence (round 8)', () => { + const sri = (bytes: string): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + const pin = (): void => { + put('app.js', `console.log(1);${stamp(ID_A)}`); + }; + + it('an output directory is scanned for pages in test/, dot-directories and deep paths too', async () => { + pin(); + put( + 'tests/index.html', + '', + ); + expect(ids(await run())).toContain('sri.mismatch'); + rmSync(join(dist, 'tests'), { recursive: true }); + put('.well/p.html', ''); + expect(ids(await run())).toContain('sri.mismatch'); + rmSync(join(dist, '.well'), { recursive: true }); + put( + 'a/b/c/d/e/f/g/h/p.html', + '', + ); + expect(ids(await run())).toContain('sri.mismatch'); + }); + + it('a fenced project directory keeps the fence for pages too, and the walk-fenced finding says what was skipped', async () => { + put('package.json', '{"name":"p"}'); + pin(); + put( + 'tests/index.html', + '', + ); + const here = process.cwd(); + process.chdir(dist); + try { + const report = await run(); + expect(ids(report)).not.toContain('sri.mismatch'); + expect(find(report, 'output.walk-fenced')?.details).toEqual({ directories: ['tests'] }); + } finally { + process.chdir(here); + } + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts index 157e588ea..6effd1e8c 100644 --- a/packages/bundler-plugin-core/src/doctor.ts +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -172,7 +172,9 @@ const rel = (dir: string, path: string): string => posix(relative(dir, path)); * source tree. What the fence skipped is returned, never silent. Iterative, and never spreads a result list (a * directory with 100k files must not overflow the call stack). */ -export async function walkDetailed(root: string): Promise<{ files: string[]; skipped: string[] }> { +export async function walkDetailed( + root: string, +): Promise<{ files: string[]; skipped: string[]; fenced: boolean }> { const fenced = (await isProjectRootOrAbove(root)) && existsSync(join(root, 'package.json')); const found: string[] = []; const skipped: string[] = []; @@ -204,7 +206,7 @@ export async function walkDetailed(root: string): Promise<{ files: string[]; ski } } } - return { files: found.sort(), skipped: skipped.sort() }; + return { files: found.sort(), skipped: skipped.sort(), fenced }; } export async function walk(root: string): Promise { @@ -959,7 +961,7 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise !isExcluded(pin.script)); if (sriScan.skippedPages.length > 0) { const names = sriScan.skippedPages.map((page) => rel(dir, page.html)); diff --git a/packages/bundler-plugin-core/src/sri.scan.test.ts b/packages/bundler-plugin-core/src/sri.scan.test.ts index 299eabd16..55472577d 100644 --- a/packages/bundler-plugin-core/src/sri.scan.test.ts +++ b/packages/bundler-plugin-core/src/sri.scan.test.ts @@ -158,3 +158,24 @@ describe('page size is bounded', () => { expect(scan.scripts).toHaveLength(1); }); }); + +describe('the page walk fence is optional', () => { + it('fenced (the default) skips test/ and dot-directories; unfenced scans them, still never node_modules', async () => { + const dir = await fixture(); + const page = ''; + for (const sub of ['tests', '.well', 'node_modules', 'ok']) { + await mkdir(join(dir, sub)); + await writeFile(join(dir, sub, 'p.html'), page.replace('/a.js', `../${sub}.js`)); + } + const fenced = await findSriProtectedScriptsDetailed(dir); + expect(fenced.scripts.map((s) => s.html)).toEqual([join(dir, 'ok', 'p.html')]); + const open = await findSriProtectedScriptsDetailed(dir, MAX_HTML_BYTES, false); + expect(open.scripts.map((s) => s.html).sort()).toEqual( + [ + join(dir, '.well', 'p.html'), + join(dir, 'ok', 'p.html'), + join(dir, 'tests', 'p.html'), + ].sort(), + ); + }); +}); diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index 4e5d40fd3..630caf3cb 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -124,8 +124,8 @@ const resolveLocalScript = (outDir: string, htmlDir: string, src: string): strin return normalize(full).startsWith(rooted) ? full : undefined; }; -const walkHtml = async (dir: string, depth = 0): Promise => { - if (depth > MAX_DEPTH) { +const walkHtml = async (dir: string, fenced: boolean, depth = 0): Promise => { + if (fenced && depth > MAX_DEPTH) { return []; } let entries: Dirent[]; @@ -140,10 +140,14 @@ const walkHtml = async (dir: string, depth = 0): Promise => { for (const entry of entries) { const full = join(dir, entry.name); if (entry.isDirectory()) { - if (NEVER_WALK.has(entry.name) || entry.name.startsWith('.')) { + // Unfenced (an output directory the doctor audits in full) still never enters node_modules or .git. + const skip = fenced + ? NEVER_WALK.has(entry.name) || entry.name.startsWith('.') + : entry.name === 'node_modules' || entry.name === '.git'; + if (skip) { continue; } - for (const page of await walkHtml(full, depth + 1)) { + for (const page of await walkHtml(full, fenced, depth + 1)) { found.push(page); } } else if (entry.isFile() && /\.x?html?$/i.test(entry.name)) { @@ -180,13 +184,15 @@ export interface SriScan { export async function findSriProtectedScriptsDetailed( outDirInput: string, maxHtmlBytes: number = MAX_HTML_BYTES, + /** Skip `test`/dot-directories and stop below depth 6 (the stamp guard's default; the doctor passes its own fence). */ + fenced = true, ): Promise { // Resolved FIRST: a bundler hands us whatever the user configured, and Rollup passes `output.dir` // through verbatim (`'dist'`) while `output.file: 'bundle.js'` resolves to `'.'`. Comparing an // absolute resolved script path against a relative root made every `src="main.js"` look like it // was outside the output directory, so the guard was silently inert for exactly those builds. const outDir = resolve(outDirInput); - const pages = await walkHtml(outDir); + const pages = await walkHtml(outDir, fenced); const seen = new Set(); const found: SriProtectedScript[] = []; const skippedPages: SriScan['skippedPages'] = []; From 0fdf8c88aa39ab45885bba144987efeec16d33e9 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 15:51:07 +0500 Subject: [PATCH 56/63] fix(bundler-plugin-core): doctor pairs a sourceMappingURL with a ?query (webpack/Rspack [name].js?[contenthash]) instead of calling it dangling Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .../src/doctor.hardening.test.ts | 26 +++++++++++++++++++ packages/bundler-plugin-core/src/doctor.ts | 8 ++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index 7a8b35ce2..d71e339cf 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -972,3 +972,29 @@ describe('the SRI page walk follows the doctor fence (round 8)', () => { } }); }); + +describe('a pointer with a ?query (webpack / Rspack [name].js?[contenthash]) (round 9)', () => { + it('pairs the map the query-less path names, and does not call the pointer dangling', async () => { + put('main.js', `a\n//# sourceMappingURL=main.js.map?3872346a403b27a7${stamp(ID_A)}`); + put('main.js.map', mapJson({ debugId: ID_B })); // a different id: proves the map was PAIRED and read + const report = await run(); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(ids(report)).toContain('stamp.map-id-mismatch'); + expect(ids(report)).not.toContain('map.hidden'); + }); + + it('a query on a pointer to a map that is not there is still dangling, reported as written', async () => { + put('main.js', `a\n//# sourceMappingURL=gone.js.map?abc${stamp(ID_A)}`); + expect(find(await run(), 'map.pointer-dangling')?.details).toEqual({ + pointers: ['main.js -> gone.js.map?abc'], + }); + }); + + it('an excluded map named with a query is neither read nor dangling', async () => { + put('main.js', `a\n//# sourceMappingURL=maps/main.js.map?x${stamp(ID_A)}`); + put('maps/main.js.map', mapJson({ debugId: ID_B })); + const report = await run({ exclude: ['maps/**'] }); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts index 6effd1e8c..ec070d60b 100644 --- a/packages/bundler-plugin-core/src/doctor.ts +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -16,7 +16,7 @@ import { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; import type { EnvRecord } from './run-cli'; import { type ReadResult, readRegularFile } from './safe-read'; import { findSriProtectedScriptsDetailed, MAX_HTML_BYTES, passesIntegrity } from './sri'; -import { isProjectRootOrAbove, MAX_WALK_DEPTH, NEVER_WALK } from './stamp-files'; +import { cutAtQuery, isProjectRootOrAbove, MAX_WALK_DEPTH, NEVER_WALK } from './stamp-files'; import { lastSourceMappingUrl, localPointerTarget } from './verify-stamp'; /** Bumped on any incompatible change to `DoctorReport`; the Rust command emits the same number. */ @@ -579,7 +579,11 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise Date: Tue, 24 Nov 2026 16:04:18 +0500 Subject: [PATCH 57/63] fix(bundler-plugin-core): doctor reads sources from index (sectioned) source maps instead of reporting map.no-sources Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .../src/doctor.hardening.test.ts | 72 +++++++++++++++++++ packages/bundler-plugin-core/src/doctor.ts | 37 +++++++++- 2 files changed, 106 insertions(+), 3 deletions(-) diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index d71e339cf..1f1f3ca56 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -998,3 +998,75 @@ describe('a pointer with a ?query (webpack / Rspack [name].js?[contenthash]) (ro expect(ids(report)).not.toContain('stamp.map-id-mismatch'); }); }); + +describe('index (sectioned) source maps (round 10)', () => { + const index = (sections: unknown[], extra: Record = {}): string => + JSON.stringify({ version: 3, sections, ...extra }); + const section = (sources: string[], content?: string[]) => ({ + offset: { line: 0, column: 0 }, + map: { + version: 3, + sources, + ...(content ? { sourcesContent: content } : {}), + names: [], + mappings: 'AAAA', + }, + }); + const pair = (map: string): void => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + put('a.js.map', map); + }; + + it('sources live inside the sections: not map.no-sources, and the embedded content is counted', async () => { + pair(index([section(['a.ts'], ['x']), section(['b.ts'], ['y'])], { debugId: ID_A })); + const report = await run(); + expect(ids(report)).not.toContain('map.no-sources'); + expect(ids(report)).not.toContain('map.invalid'); + expect(find(report, 'map.sources-content')?.message).toContain('all 2 sources'); + }); + + it('sections without sourcesContent and with sources not on disk: map.sources-unresolvable', async () => { + pair(index([section(['a.ts']), section(['b.ts'], ['y'])], { debugId: ID_A })); + const report = await run(); + expect(find(report, 'map.sources-unresolvable')?.details).toEqual({ unresolved: 1, total: 2 }); + }); + + it('an index map whose sections carry no sources is still map.no-sources', async () => { + pair(index([section([]), { offset: { line: 1, column: 0 }, url: 'x.map' }], { debugId: ID_A })); + expect(ids(await run())).toContain('map.no-sources'); + pair(index([], { debugId: ID_A })); + expect(ids(await run())).toContain('map.no-sources'); + }); + + it('content stays aligned per section: a second source without content is the one reported', async () => { + pair(index([section(['a.ts', 'b.ts'], ['x'])], { debugId: ID_A })); + expect(find(await run(), 'map.sources-unresolvable')?.details).toEqual({ + unresolved: 1, + total: 2, + }); + }); + + it('an empty top-level sources array falls through to the sections; a section without a map or sources is skipped', async () => { + pair( + index( + [section(['a.ts'], ['x']), { offset: { line: 1, column: 0 }, map: { version: 3 } }, null], + { debugId: ID_A, sources: [] }, + ), + ); + const report = await run(); + expect(ids(report)).not.toContain('map.no-sources'); + expect(ids(report)).not.toContain('doctor.internal-error'); + expect(find(report, 'map.sources-content')?.message).toContain('all 1 sources'); + }); + + it('top-level sources win over sections', async () => { + pair( + index([section(['z.ts'], ['z'])], { + debugId: ID_A, + sources: ['a.ts'], + sourcesContent: ['x'], + }), + ); + expect(find(await run(), 'map.sources-content')?.message).toContain('all 1 sources'); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts index ec070d60b..340d78bb0 100644 --- a/packages/bundler-plugin-core/src/doctor.ts +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -236,6 +236,38 @@ export function globToRegExp(glob: string): RegExp { return new RegExp(`^${source}$`); } +/** + * The `sources` and their embedded `sourcesContent` (aligned by index) of a map. An ordinary map has them at the top + * level; an INDEX map keeps them inside `sections[].map`, so those are concatenated, each section's content padded to + * its own sources so the alignment survives. + */ +export function mapSources(json: Record): { + sources: unknown[]; + content: unknown[]; +} { + if (Array.isArray(json.sources) && json.sources.length > 0) { + return { + sources: json.sources as unknown[], + content: Array.isArray(json.sourcesContent) ? (json.sourcesContent as unknown[]) : [], + }; + } + const sources: unknown[] = []; + const content: unknown[] = []; + for (const section of Array.isArray(json.sections) ? (json.sections as unknown[]) : []) { + const map = (section as { map?: Record } | null)?.map; + if (typeof map !== 'object' || map === null || !Array.isArray(map.sources)) { + continue; + } + const own = map.sources as unknown[]; + const embedded = Array.isArray(map.sourcesContent) ? (map.sourcesContent as unknown[]) : []; + own.forEach((source, i) => { + sources.push(source); + content.push(embedded[i]); + }); + } + return { sources, content }; +} + interface ParsedMap { ok: true; json: Record; @@ -760,8 +792,8 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise typeof content[i] !== 'string').map(String); if (missing.length === 0) { contentFacts.push({ From 9adba5c3d7169bf9012d395222e5cd0873b95c42 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 16:15:42 +0500 Subject: [PATCH 58/63] fix(bundler-plugin-core): doctor cuts a pointer's query only (not a ? in the directory path); index-map sections resolve sources with their own sourceRoot Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .../src/doctor.hardening.test.ts | 30 +++++++++++++++++++ packages/bundler-plugin-core/src/doctor.ts | 27 ++++++++++++----- 2 files changed, 49 insertions(+), 8 deletions(-) diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index 1f1f3ca56..524353a28 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -1059,6 +1059,20 @@ describe('index (sectioned) source maps (round 10)', () => { expect(find(report, 'map.sources-content')?.message).toContain('all 1 sources'); }); + it("each section's sources are resolved with the section's own sourceRoot", async () => { + put('src/a.ts', 'x'); + const withRoot = { + offset: { line: 0, column: 0 }, + map: { version: 3, sourceRoot: 'src/', sources: ['a.ts'], names: [], mappings: 'AAAA' }, + }; + pair(index([withRoot], { debugId: ID_A })); + expect(ids(await run())).not.toContain('map.sources-unresolvable'); + put('src/a.ts', 'x'); + const wrongRoot = { ...withRoot, map: { ...withRoot.map, sourceRoot: 'nope/' } }; + pair(index([wrongRoot], { debugId: ID_A })); + expect(ids(await run())).toContain('map.sources-unresolvable'); + }); + it('top-level sources win over sections', async () => { pair( index([section(['z.ts'], ['z'])], { @@ -1070,3 +1084,19 @@ describe('index (sectioned) source maps (round 10)', () => { expect(find(await run(), 'map.sources-content')?.message).toContain('all 1 sources'); }); }); + +describe('a ? in the checked directory path (round 11)', () => { + it('the pointer is judged on its own query, not on a ? anywhere in the absolute path', async () => { + const weird = join(root, 'we?ird'); + mkdirSync(weird); + const out = join(weird, 'dist'); + mkdirSync(out); + writeFileSync(join(out, 'a.js'), `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + writeFileSync(join(out, 'a.js.map'), mapJson({ debugId: ID_A })); + const report = await diagnoseBuildOutput(out, { projectRoot: root, skipEnv: true }); + expect(ids(report)).not.toContain('map.pointer-outside-dir'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(ids(report)).not.toContain('map.hidden'); // the pointer paired a.js.map + expect(report.summary.errors + report.summary.warnings).toBe(0); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts index 340d78bb0..0b94131e3 100644 --- a/packages/bundler-plugin-core/src/doctor.ts +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -244,15 +244,19 @@ export function globToRegExp(glob: string): RegExp { export function mapSources(json: Record): { sources: unknown[]; content: unknown[]; + roots: string[]; } { if (Array.isArray(json.sources) && json.sources.length > 0) { + const root = typeof json.sourceRoot === 'string' ? json.sourceRoot : ''; return { sources: json.sources as unknown[], content: Array.isArray(json.sourcesContent) ? (json.sourcesContent as unknown[]) : [], + roots: (json.sources as unknown[]).map(() => root), }; } const sources: unknown[] = []; const content: unknown[] = []; + const roots: string[] = []; for (const section of Array.isArray(json.sections) ? (json.sections as unknown[]) : []) { const map = (section as { map?: Record } | null)?.map; if (typeof map !== 'object' || map === null || !Array.isArray(map.sources)) { @@ -260,12 +264,15 @@ export function mapSources(json: Record): { } const own = map.sources as unknown[]; const embedded = Array.isArray(map.sourcesContent) ? (map.sourcesContent as unknown[]) : []; + // A section is a full map: its sources are relative to ITS sourceRoot. + const root = typeof map.sourceRoot === 'string' ? map.sourceRoot : ''; own.forEach((source, i) => { sources.push(source); content.push(embedded[i]); + roots.push(root); }); } - return { sources, content }; + return { sources, content, roots }; } interface ParsedMap { @@ -615,7 +622,11 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise typeof content[i] !== 'string').map(String); + const missingAt = sources.flatMap((_, i) => (typeof content[i] !== 'string' ? [i] : [])); + const missing = missingAt.map((i) => String(sources[i])); if (missing.length === 0) { contentFacts.push({ file: mapName, @@ -812,11 +824,10 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise { - const path = sourcePath(mapDir, sourceRoot, source, projectRoot); - return path !== undefined && !existsSync(path); + const unresolved = missingAt.flatMap((i) => { + const path = sourcePath(mapDir, roots[i] as string, String(sources[i]), projectRoot); + return path !== undefined && !existsSync(path) ? [String(sources[i])] : []; }); if (unresolved.length > 0) { add({ From 1f3c461907e8f0e4d56c90286aaddcde2a93aec1 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 20:14:22 +0500 Subject: [PATCH 59/63] fix(bundler-plugin-core): doctor: scheme sourceRoot, nested index maps, symlinked pages, exclude-unmatched after every match; test fixtures Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .../src/doctor.hardening.test.ts | 173 ++++++++++++++++-- packages/bundler-plugin-core/src/doctor.ts | 81 ++++---- .../bundler-plugin-core/src/sri.scan.test.ts | 21 ++- packages/bundler-plugin-core/src/sri.ts | 33 +++- 4 files changed, 253 insertions(+), 55 deletions(-) diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index 524353a28..93541ccc0 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -731,6 +731,22 @@ describe('files the build did not emit (round 6)', () => { expect(find(report, 'output.excluded')?.details).toEqual({ files: ['maps/a.js.map'] }); }); + it('a pattern that matches only an SRI pin outside the walked files still counts as matched', async () => { + put('package.json', '{"name":"p"}'); + put('app.js', `a${stamp(ID_A)}`); + put('tests/vendor.js', 'v'); // in a fenced (skipped) directory: not in the walk + put('index.html', ``); + const here = process.cwd(); + process.chdir(dist); + try { + const report = await run({ exclude: ['tests/vendor.js'] }); + expect(ids(report)).not.toContain('output.exclude-unmatched'); + expect(ids(report)).not.toContain('sri.mismatch'); + } finally { + process.chdir(here); + } + }); + it('the new info-only IDs are facts, never "passed"', async () => { healthy(); put('public/x.js', 'x'); @@ -864,7 +880,25 @@ describe('round 7 review findings', () => { ); const report = await run(); expect(find(report, 'map.invalid')?.message).toContain('mappings'); - put('a.js.map', mapJson({ debugId: ID_A, mappings: undefined, sections: [] })); + const sectioned = { + debugId: ID_A, + mappings: undefined, + sources: undefined, + sourcesContent: undefined, + sections: [ + { + offset: { line: 0, column: 0 }, + map: { + version: 3, + sources: ['a.ts'], + sourcesContent: ['x'], + names: [], + mappings: 'AAAA', + }, + }, + ], + }; + put('a.js.map', mapJson(sectioned)); expect(ids(await run())).not.toContain('map.invalid'); put('a.js.map', mapJson({ debugId: ID_A, mappings: 5 })); expect(ids(await run())).toContain('map.invalid'); @@ -975,8 +1009,9 @@ describe('the SRI page walk follows the doctor fence (round 8)', () => { describe('a pointer with a ?query (webpack / Rspack [name].js?[contenthash]) (round 9)', () => { it('pairs the map the query-less path names, and does not call the pointer dangling', async () => { - put('main.js', `a\n//# sourceMappingURL=main.js.map?3872346a403b27a7${stamp(ID_A)}`); - put('main.js.map', mapJson({ debugId: ID_B })); // a different id: proves the map was PAIRED and read + // NOT a sibling: only following the pointer (query cut) can find it, so the mismatch proves the pairing + put('main.js', `a\n//# sourceMappingURL=maps/main.js.map?3872346a403b27a7${stamp(ID_A)}`); + put('maps/main.js.map', mapJson({ debugId: ID_B })); const report = await run(); expect(ids(report)).not.toContain('map.pointer-dangling'); expect(ids(report)).toContain('stamp.map-id-mismatch'); @@ -1073,6 +1108,53 @@ describe('index (sectioned) source maps (round 10)', () => { expect(ids(await run())).toContain('map.sources-unresolvable'); }); + it('nested index maps: leaves are found at any depth, each with its own sourceRoot and content', async () => { + put('lib/b.ts', 'y'); + const leaf = (root: string, sources: string[], content?: string[]) => ({ + offset: { line: 0, column: 0 }, + map: { + version: 3, + sourceRoot: root, + sources, + ...(content ? { sourcesContent: content } : {}), + names: [], + mappings: 'AAAA', + }, + }); + const inner = { + offset: { line: 5, column: 0 }, + map: { version: 3, sections: [leaf('lib/', ['b.ts'])] }, + }; + pair(index([leaf('', ['a.ts'], ['x']), inner], { debugId: ID_A })); + const report = await run(); + expect(ids(report)).not.toContain('map.no-sources'); + expect(ids(report)).not.toContain('map.sources-unresolvable'); // b.ts is under lib/, via the leaf's root + const wrong = { + offset: { line: 5, column: 0 }, + map: { version: 3, sections: [leaf('nope/', ['b.ts'])] }, + }; + pair(index([leaf('', ['a.ts'], ['x']), wrong], { debugId: ID_A })); + expect(find(await run(), 'map.sources-unresolvable')?.details).toEqual({ + unresolved: 1, + total: 2, + }); + }); + + it('a pathologically deep chain of index maps is bounded, not a stack overflow', async () => { + let map: Record = { + version: 3, + sources: ['a.ts'], + sourcesContent: ['x'], + mappings: 'A', + }; + for (let i = 0; i < 5000; i++) { + map = { version: 3, sections: [{ offset: { line: 0, column: 0 }, map }] }; + } + pair(JSON.stringify({ ...map, debugId: ID_A })); + const report = await run(); + expect(ids(report)).not.toContain('doctor.internal-error'); + }); + it('top-level sources win over sections', async () => { pair( index([section(['z.ts'], ['z'])], { @@ -1085,18 +1167,77 @@ describe('index (sectioned) source maps (round 10)', () => { }); }); -describe('a ? in the checked directory path (round 11)', () => { - it('the pointer is judged on its own query, not on a ? anywhere in the absolute path', async () => { - const weird = join(root, 'we?ird'); - mkdirSync(weird); - const out = join(weird, 'dist'); - mkdirSync(out); - writeFileSync(join(out, 'a.js'), `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); - writeFileSync(join(out, 'a.js.map'), mapJson({ debugId: ID_A })); - const report = await diagnoseBuildOutput(out, { projectRoot: root, skipEnv: true }); - expect(ids(report)).not.toContain('map.pointer-outside-dir'); - expect(ids(report)).not.toContain('map.pointer-dangling'); - expect(ids(report)).not.toContain('map.hidden'); // the pointer paired a.js.map - expect(report.summary.errors + report.summary.warnings).toBe(0); +// Windows does not allow a `?` in a path component: the fixture cannot be created there +describe.skipIf(process.platform === 'win32')( + 'a ? in the checked directory path (round 11)', + () => { + it('the pointer is judged on its own query, not on a ? anywhere in the absolute path', async () => { + const weird = join(root, 'we?ird'); + mkdirSync(weird); + const out = join(weird, 'dist'); + mkdirSync(out); + writeFileSync(join(out, 'a.js'), `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + writeFileSync(join(out, 'a.js.map'), mapJson({ debugId: ID_A })); + const report = await diagnoseBuildOutput(out, { projectRoot: root, skipEnv: true }); + expect(ids(report)).not.toContain('map.pointer-outside-dir'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(ids(report)).not.toContain('map.hidden'); // the pointer paired a.js.map + expect(report.summary.errors + report.summary.warnings).toBe(0); + }); + }, +); + +describe('a scheme in sourceRoot (round 12)', () => { + it('sourceRoot + source is one URL: webpack:/// + src/x.ts names /src/x.ts', async () => { + put('../src/x.ts', 'x'); + const body = { debugId: ID_A, sourcesContent: undefined, sources: ['src/x.ts'] }; + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + for (const sourceRoot of ['webpack:///', 'webpack://app/', 'webpack://app']) { + put('a.js.map', mapJson({ ...body, sourceRoot })); + expect(ids(await run()), sourceRoot).not.toContain('map.sources-unresolvable'); + } + put('a.js.map', mapJson({ ...body, sourceRoot: 'webpack:///', sources: ['src/missing.ts'] })); + expect(ids(await run())).toContain('map.sources-unresolvable'); + }); +}); + +describe('symlinked HTML pages are scanned, or reported, never skipped silently (round 12)', () => { + const sri = (bytes: string): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + const stalePage = ``; + + it('a link to a page inside the directory is read through its real path (stale pin found)', async () => { + put('a.js', `console.log(1);${stamp(ID_A)}`); + put('pages/real.html', stalePage.replace('a.js', '../a.js')); + symlinkSync(join(dist, 'pages', 'real.html'), join(dist, 'index.html')); + const report = await run(); + expect(ids(report)).toContain('sri.mismatch'); + }); + + it('a link that leads outside the directory (or dangles) is reported as not scanned', async () => { + put('a.js', `a${stamp(ID_A)}`); + writeFileSync(join(root, 'outside.html'), stalePage); + symlinkSync(join(root, 'outside.html'), join(dist, 'out.html')); + symlinkSync(join(root, 'nowhere.html'), join(dist, 'dangling.html')); + const finding = find(await run(), 'sri.html-skipped'); + expect(finding).toMatchObject({ + severity: 'warning', + details: { files: ['dangling.html', 'out.html'] }, + }); + expect(ids(await run())).not.toContain('sri.mismatch'); + }); +}); + +describe('sourcePath with a scheme sourceRoot (unit)', () => { + it('a source that already carries its own scheme or is absolute ignores the root', () => { + const map = '/p/dist'; + const proj = '/p'; + expect(sourcePath(map, 'webpack:///', 'src/x.ts', proj)).toBe('/p/src/x.ts'); + expect(sourcePath(map, 'webpack:///', 'webpack://app/src/x.ts', proj)).toBe('/p/src/x.ts'); + expect(sourcePath(map, 'webpack:///', 'file:///tmp/y.ts', proj)).toBe('/tmp/y.ts'); + expect(sourcePath(map, 'webpack:///', '/abs/z.ts', proj)).toBe('/abs/z.ts'); + expect(sourcePath(map, 'https://h/r', '/abs/z.ts', proj)).toBe('/abs/z.ts'); + // a non-URL source with a single-colon scheme is not joined to the root either: it resolves from the map + expect(sourcePath(map, 'webpack:///', 'node:fs', proj)).toBe('/p/dist/webpack:/node:fs'); }); }); diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts index 0b94131e3..50505128d 100644 --- a/packages/bundler-plugin-core/src/doctor.ts +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -246,35 +246,40 @@ export function mapSources(json: Record): { content: unknown[]; roots: string[]; } { - if (Array.isArray(json.sources) && json.sources.length > 0) { - const root = typeof json.sourceRoot === 'string' ? json.sourceRoot : ''; - return { - sources: json.sources as unknown[], - content: Array.isArray(json.sourcesContent) ? (json.sourcesContent as unknown[]) : [], - roots: (json.sources as unknown[]).map(() => root), - }; - } const sources: unknown[] = []; const content: unknown[] = []; const roots: string[] = []; - for (const section of Array.isArray(json.sections) ? (json.sections as unknown[]) : []) { - const map = (section as { map?: Record } | null)?.map; - if (typeof map !== 'object' || map === null || !Array.isArray(map.sources)) { - continue; + const collect = (map: Record, depth: number): void => { + if (Array.isArray(map.sources) && map.sources.length > 0) { + // A leaf map: its content and sourceRoot belong to ITS sources only (aligned by index). + const own = map.sources as unknown[]; + const embedded = Array.isArray(map.sourcesContent) ? (map.sourcesContent as unknown[]) : []; + const root = typeof map.sourceRoot === 'string' ? map.sourceRoot : ''; + own.forEach((source, i) => { + sources.push(source); + content.push(embedded[i]); + roots.push(root); + }); + return; } - const own = map.sources as unknown[]; - const embedded = Array.isArray(map.sourcesContent) ? (map.sourcesContent as unknown[]) : []; - // A section is a full map: its sources are relative to ITS sourceRoot. - const root = typeof map.sourceRoot === 'string' ? map.sourceRoot : ''; - own.forEach((source, i) => { - sources.push(source); - content.push(embedded[i]); - roots.push(root); - }); - } + if (depth >= MAX_INDEX_DEPTH) { + return; + } + // An INDEX map keeps its maps inside `sections[].map`, which may be index maps themselves. + for (const section of Array.isArray(map.sections) ? (map.sections as unknown[]) : []) { + const inner = (section as { map?: unknown } | null)?.map; + if (typeof inner === 'object' && inner !== null) { + collect(inner as Record, depth + 1); + } + } + }; + collect(json, 0); return { sources, content, roots }; } +/** Nested index maps are followed this deep (a real one is 1-2 levels); a hostile chain must not overflow the stack. */ +const MAX_INDEX_DEPTH = 32; + interface ParsedMap { ok: true; json: Record; @@ -302,6 +307,9 @@ function parseMap(text: string): ParsedMap | { ok: false; why: string } { return { ok: true, json, debugId: typeof id === 'string' ? id.toLowerCase() : undefined }; } +/** `scheme://...`: a URL, not a directory name. */ +const SCHEME_URL = /^[a-z][a-z0-9+.-]*:\/\//i; + /** Sources that name no file on disk by construction (bundler runtime, virtual modules). */ const VIRTUAL_SOURCE = /^(webpack\/|\(webpack\)|\0|<|rollup:|vite\/)|\0/; @@ -320,6 +328,15 @@ export function sourcePath( ): string | undefined { let path = source; let fromProject = false; + // ECMA-426: the source URL is `sourceRoot + source`. A scheme in the root (`webpack:///` + `src/x.ts`) is the + // same URL as the scheme written into `source`, so it takes the same rule below. + if ( + SCHEME_URL.test(sourceRoot) && + !/^[a-z][a-z0-9+.-]*:/i.test(source) && + !api.isAbsolute(source) + ) { + path = sourceRoot.endsWith('/') ? `${sourceRoot}${source}` : `${sourceRoot}/${source}`; + } if (/^file:\/\//i.test(path)) { try { return fileURLToPath(path, api === nodePath.win32 ? { windows: true } : undefined); @@ -327,7 +344,7 @@ export function sourcePath( return undefined; } } - if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path)) { + if (SCHEME_URL.test(path)) { // `webpack://app/./src/x.ts` and friends: the scheme/namespace is not a directory; drop it. path = path.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*\//i, ''); fromProject = true; @@ -520,15 +537,6 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise !matchedPatterns.has(i)); - if (unmatched.length > 0) { - add({ - id: 'output.exclude-unmatched', - severity: 'info', - message: `${unmatched.length} --exclude pattern(s) matched no file (${unmatched.join(', ')}); patterns are relative to ${dir} (Vite copies publicDir to its ROOT: write sw.js, not public/sw.js).`, - details: { patterns: unmatched }, - }); - } if (walked.skipped.length > 0) { add({ id: 'output.walk-fenced', @@ -1009,6 +1017,15 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise !isExcluded(pin.script)); + const unmatched = excludeGlobs.filter((_, i) => !matchedPatterns.has(i)); + if (unmatched.length > 0) { + add({ + id: 'output.exclude-unmatched', + severity: 'info', + message: `${unmatched.length} --exclude pattern(s) matched no file (${unmatched.join(', ')}); patterns are relative to ${dir} (Vite copies publicDir to its ROOT: write sw.js, not public/sw.js).`, + details: { patterns: unmatched }, + }); + } if (sriScan.skippedPages.length > 0) { const names = sriScan.skippedPages.map((page) => rel(dir, page.html)); add({ diff --git a/packages/bundler-plugin-core/src/sri.scan.test.ts b/packages/bundler-plugin-core/src/sri.scan.test.ts index 55472577d..be9986fab 100644 --- a/packages/bundler-plugin-core/src/sri.scan.test.ts +++ b/packages/bundler-plugin-core/src/sri.scan.test.ts @@ -1,6 +1,6 @@ // The HTML scan must be linear and bounded on hostile input, and must find exactly what the regexes it replaced // found on ordinary input. -import { mkdir, mkdtemp, rm, truncate, writeFile } from 'node:fs/promises'; +import { mkdir, mkdtemp, rm, symlink, truncate, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; @@ -179,3 +179,22 @@ describe('the page walk fence is optional', () => { ); }); }); + +describe('symlinked pages', () => { + it('a link inside the directory is scanned; one outside or dangling is listed as unreadable', async () => { + const dir = await fixture(); + const outside = await fixture(); + const page = ''; + await mkdir(join(dir, 'tests')); // a directory the (default) fence skips: only the link can reach this page + await writeFile(join(dir, 'tests', 'p.html'), page); + await symlink(join(dir, 'tests', 'p.html'), join(dir, 'in.html')); + await writeFile(join(outside, 'o.html'), page); + await symlink(join(outside, 'o.html'), join(dir, 'out.html')); + await symlink(join(outside, 'none.html'), join(dir, 'dangling.html')); + const scan = await findSriProtectedScriptsDetailed(dir); + expect(scan.scripts.map((s) => s.html)).toEqual([join(dir, 'in.html')]); + expect(scan.unreadablePages.sort()).toEqual( + [join(dir, 'dangling.html'), join(dir, 'out.html')].sort(), + ); + }); +}); diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index 630caf3cb..0e38c896e 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -16,7 +16,7 @@ // every dynamic import. import { createHash } from 'node:crypto'; import type { Dirent } from 'node:fs'; -import { readdir, readFile } from 'node:fs/promises'; +import { readdir, readFile, realpath } from 'node:fs/promises'; import { isAbsolute, join, normalize, resolve, sep } from 'node:path'; import { readRegularFile } from './safe-read'; @@ -124,7 +124,12 @@ const resolveLocalScript = (outDir: string, htmlDir: string, src: string): strin return normalize(full).startsWith(rooted) ? full : undefined; }; -const walkHtml = async (dir: string, fenced: boolean, depth = 0): Promise => { +const walkHtml = async ( + dir: string, + fenced: boolean, + links: Set, + depth = 0, +): Promise => { if (fenced && depth > MAX_DEPTH) { return []; } @@ -147,11 +152,14 @@ const walkHtml = async (dir: string, fenced: boolean, depth = 0): Promise(); + const pages = await walkHtml(outDir, fenced, links); + const realOutDir = await realpath(outDir).catch(() => outDir); const seen = new Set(); const found: SriProtectedScript[] = []; const skippedPages: SriScan['skippedPages'] = []; const unreadablePages: string[] = []; for (const html of pages.sort()) { - const read = await readRegularFile(html, maxHtmlBytes); + // A symlinked page is read through its REAL path, and only if that stays inside the output directory (the + // same rule as every other symlinked artifact); one that leads out, or dangles, is a page that was not checked. + let readPath = html; + if (links.has(html)) { + const real = await realpath(html).catch(() => undefined); + if (real === undefined || !(real === realOutDir || real.startsWith(realOutDir + sep))) { + unreadablePages.push(html); + continue; + } + readPath = real; + } + const read = await readRegularFile(readPath, maxHtmlBytes); if (!read.ok) { if (read.tooLarge !== undefined) { skippedPages.push({ html, size: read.tooLarge.size }); From ddd5a7b9eb987f41c39cdc87d96f236a4625e848 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 20:21:41 +0500 Subject: [PATCH 60/63] test(bundler-plugin-core): comment-strip oracle without String.replace (CodeQL incomplete multi-character sanitization) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .../bundler-plugin-core/src/sri.scan.test.ts | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/bundler-plugin-core/src/sri.scan.test.ts b/packages/bundler-plugin-core/src/sri.scan.test.ts index be9986fab..4d1ed3b17 100644 --- a/packages/bundler-plugin-core/src/sri.scan.test.ts +++ b/packages/bundler-plugin-core/src/sri.scan.test.ts @@ -41,6 +41,20 @@ it('MAX_HTML_BYTES is 8 MiB', () => { expect(MAX_HTML_BYTES).toBe(8 * 1024 * 1024); }); +/** + * The reference the linear scanner must agree with: every `` removed by the regex it replaced. Spliced from + * the match positions (not `String.replace`, which is also what a sanitiser would use: this is a test oracle). + */ +const referenceStrip = (text: string): string => { + let out = ''; + let at = 0; + for (const match of text.matchAll(HTML_COMMENT)) { + out += text.slice(at, match.index); + at = (match.index ?? 0) + match[0].length; + } + return out + text.slice(at); +}; + describe('findTags / stripComments agree with the regexes they replaced', () => { const pieces = [ ' for (let i = 0, n = next() % 14; i < n; i++) { text += pieces[next() % pieces.length]; } - expect(stripComments(text), JSON.stringify(text)).toBe(text.replace(HTML_COMMENT, '')); - const markup = text.replace(HTML_COMMENT, ''); + const markup = referenceStrip(text); + expect(stripComments(text), JSON.stringify(text)).toBe(markup); expect(findTags(markup, 'script'), JSON.stringify(text)).toEqual( markup.match(SCRIPT_TAG) ?? [], ); From c77ef5f8b968f776e136d242a8542f74417d4132 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 20:42:32 +0500 Subject: [PATCH 61/63] fix(bundler-plugin-core): doctor reports directories it could not list (output.dir-unreadable); deep index-map test no longer overflows JSON.stringify on Linux Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- docs/PROGRESS.md | 2 +- .../src/doctor.hardening.test.ts | 87 ++++++++++++++++--- .../bundler-plugin-core/src/doctor.test.ts | 2 +- packages/bundler-plugin-core/src/doctor.ts | 21 ++++- packages/bundler-plugin-core/src/sri.ts | 15 ++-- 5 files changed, 107 insertions(+), 20 deletions(-) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 7d231e9a2..fa805d796 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1533,7 +1533,7 @@ Verified against current majors, all green with no adapter code changes: `@bugse `@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. ### `sourcemaps doctor`: offline build-output diagnostics (2026-11-23) -`@bugsee/bundler-plugin-core` ships `diagnoseBuildOutput(dir, options)` (`src/doctor.ts`) and the `bugsee-sourcemaps-doctor` bin (`src/doctor-cli.ts`, ESM-only tsup entry, wired through `publishConfig.bin`). 35 check IDs (`DOCTOR_CHECK_IDS`) over the output directory, bundles, maps, SRI (reusing `sri.ts`), leftover maps and the build environment (token, version, build, `NODE_ENV`; the token is never printed), each with a severity and a fix hint, and one versioned JSON report (`schemaVersion: 1`) that the Rust `bugsee-cli sourcemaps doctor` is specified to share. Exit codes 0 ok, 1 warnings only with `--strict`, 2 errors. Review round (PR #222): `--strict` passes straight after a plugin run (`map.public-leftover` is a note unless `--deployed`; `map.pointer-dangling` is a note when no map is left and every bundle is stamped; `--ignore `), the doctor never throws (`doctor.internal-error`; no spread of large lists, safe `file://` decoding), reads only regular files inside the directory with the size checked first (`map.unreadable`, `map.pointer-outside-dir`), walks the whole output directory (only `node_modules`/`.git` skipped unless it is the project root), resolves bundler-scheme sources against the project root, reports the token's source (`env.token-source`; a missing token is a warning), and pairs maps with the stamp's own `localPointerTarget`. The same spread pattern was fixed in `stamp-files.ts`. Round 8: the SRI page walk follows the doctor's fence (full walk for an output directory, reported fence otherwise); docs always use `npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor`. Round 7: `--exclude` applies to SRI pins and map pointers, unmatched patterns are reported (`output.exclude-unmatched`), an all-unreadable output cannot pass, reads are bounded by bytes in flight, maps need `mappings`/`sections`, every distinct SRI pin is kept for the doctor, `passed` lists only checks that had input. Round 6: `--exclude ` (+ `exclude` option) drops files the build did not emit (`output.excluded`); the walk fence needs a `package.json` as well as cwd and reports what it skipped (`output.walk-fenced`); the stamp's own SRI guard keeps no page cap (only the doctor's scan does). Round 4: the HTML scan in `sri.ts` is linear (an `indexOf` scanner replaced the quadratic comment and script-tag regexes; a differential fuzz test pins identical results) and bounded (pages over 8 MiB are skipped and reported as `sri.html-skipped`); reads go through `safe-read.ts` (open with `O_NOFOLLOW`/`O_NONBLOCK`, type and size judged on the descriptor); in-directory symlinks are followed by real path; FIFOs/sockets/devices named like scripts are reported; a map reached through two names is judged once; long lists and the per-map `map.sources-content` notes are capped/aggregated. Real-build proof in `doctor.real-build.test.ts`: Vite 8 and 7, Rollup and Rspack stamped by the real plugin and CLI (healthy), an unstamped build, an inline-map build, and SRI builds (unstamped hazard, stamped-first clean, stamped-after-hash `sri.mismatch` produced by `bugsee-cli sourcemaps inject --allow-sri`). Webpack itself is not a dependency of this package; Rspack stands in for the shared in-build stamp path. Mutator loop: 10 mutations on the decision logic, all killed. **Not done:** an optional post-build `doctor` call in the plugins (the findings need a policy for failing a build; left as a follow-up), the Rust command, and every check that needs the backend (design hand-off: map-present-for-debug-ID, deployed-URL, synthetic symbolicate round trip). +`@bugsee/bundler-plugin-core` ships `diagnoseBuildOutput(dir, options)` (`src/doctor.ts`) and the `bugsee-sourcemaps-doctor` bin (`src/doctor-cli.ts`, ESM-only tsup entry, wired through `publishConfig.bin`). 36 check IDs (`DOCTOR_CHECK_IDS`) over the output directory, bundles, maps, SRI (reusing `sri.ts`), leftover maps and the build environment (token, version, build, `NODE_ENV`; the token is never printed), each with a severity and a fix hint, and one versioned JSON report (`schemaVersion: 1`) that the Rust `bugsee-cli sourcemaps doctor` is specified to share. Exit codes 0 ok, 1 warnings only with `--strict`, 2 errors. Review round (PR #222): `--strict` passes straight after a plugin run (`map.public-leftover` is a note unless `--deployed`; `map.pointer-dangling` is a note when no map is left and every bundle is stamped; `--ignore `), the doctor never throws (`doctor.internal-error`; no spread of large lists, safe `file://` decoding), reads only regular files inside the directory with the size checked first (`map.unreadable`, `map.pointer-outside-dir`), walks the whole output directory (only `node_modules`/`.git` skipped unless it is the project root), resolves bundler-scheme sources against the project root, reports the token's source (`env.token-source`; a missing token is a warning), and pairs maps with the stamp's own `localPointerTarget`. The same spread pattern was fixed in `stamp-files.ts`. Round 8: the SRI page walk follows the doctor's fence (full walk for an output directory, reported fence otherwise); docs always use `npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor`. Round 7: `--exclude` applies to SRI pins and map pointers, unmatched patterns are reported (`output.exclude-unmatched`), an all-unreadable output cannot pass, reads are bounded by bytes in flight, maps need `mappings`/`sections`, every distinct SRI pin is kept for the doctor, `passed` lists only checks that had input. Round 6: `--exclude ` (+ `exclude` option) drops files the build did not emit (`output.excluded`); the walk fence needs a `package.json` as well as cwd and reports what it skipped (`output.walk-fenced`); the stamp's own SRI guard keeps no page cap (only the doctor's scan does). Round 4: the HTML scan in `sri.ts` is linear (an `indexOf` scanner replaced the quadratic comment and script-tag regexes; a differential fuzz test pins identical results) and bounded (pages over 8 MiB are skipped and reported as `sri.html-skipped`); reads go through `safe-read.ts` (open with `O_NOFOLLOW`/`O_NONBLOCK`, type and size judged on the descriptor); in-directory symlinks are followed by real path; FIFOs/sockets/devices named like scripts are reported; a map reached through two names is judged once; long lists and the per-map `map.sources-content` notes are capped/aggregated. Real-build proof in `doctor.real-build.test.ts`: Vite 8 and 7, Rollup and Rspack stamped by the real plugin and CLI (healthy), an unstamped build, an inline-map build, and SRI builds (unstamped hazard, stamped-first clean, stamped-after-hash `sri.mismatch` produced by `bugsee-cli sourcemaps inject --allow-sri`). Webpack itself is not a dependency of this package; Rspack stands in for the shared in-build stamp path. Mutator loop: 10 mutations on the decision logic, all killed. **Not done:** an optional post-build `doctor` call in the plugins (the findings need a policy for failing a build; left as a follow-up), the Rust command, and every check that needs the backend (design hand-off: map-present-for-debug-ID, deployed-URL, synthetic symbolicate round trip). ### 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/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index 93541ccc0..8e7b421b4 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -14,7 +14,14 @@ import { import { tmpdir } from 'node:os'; import { dirname, join, win32 } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { batchEnd, type DoctorReport, diagnoseBuildOutput, sourcePath, walk } from './doctor'; +import { + batchEnd, + type DoctorReport, + diagnoseBuildOutput, + doctorExitCode, + sourcePath, + walk, +} from './doctor'; import { listOutputMaps } from './stamp-files'; const ID_A = '11111111-1111-4111-8111-111111111111'; @@ -365,10 +372,62 @@ describe.skipIf(process.getuid?.() === 0)('an unreadable output directory', () = const report = await run(); expect(ids(report)).toContain('output.no-js'); expect(ids(report)).not.toContain('doctor.internal-error'); + expect(find(report, 'output.dir-unreadable')?.details).toEqual({ directories: ['.'] }); } finally { chmodSync(dist, 0o700); } }); + + it('an unreadable SUB-directory is an error naming it, never a silent pass', async () => { + put('registerSW.js', `a${stamp(ID_A)}`); + put('assets/index.js', 'unstamped'); + put('assets/deeper/x.js', 'x'); + chmodSync(join(dist, 'assets'), 0o000); + try { + const report = await run(); + expect(find(report, 'output.dir-unreadable')).toMatchObject({ + severity: 'error', + details: { directories: ['assets'] }, + }); + expect(report.passed).not.toContain('output.dir-unreadable'); + expect(doctorExitCode(report, false)).toBe(2); + } finally { + chmodSync(join(dist, 'assets'), 0o700); + } + expect(ids(await run())).not.toContain('output.dir-unreadable'); + }); + + it('several unreadable directories are listed, sorted', async () => { + put('a.js', `a${stamp(ID_A)}`); + for (let i = 2; i >= 0; i--) { + put(`d${i}/p.js`, 'x'); + chmodSync(join(dist, `d${i}`), 0o000); + } + try { + const finding = find(await run(), 'output.dir-unreadable'); + expect(finding?.details).toEqual({ directories: ['d0', 'd1', 'd2'] }); + } finally { + for (let i = 0; i < 3; i++) { + chmodSync(join(dist, `d${i}`), 0o700); + } + } + }); + + it('a directory only the HTML page walk enters (src/, which the fenced script walk skips) is reported too', async () => { + put('package.json', '{"name":"p"}'); + put('a.js', `a${stamp(ID_A)}`); + put('src/p.html', '

'); + chmodSync(join(dist, 'src'), 0o000); + const here = process.cwd(); + process.chdir(dist); + try { + const finding = find(await run(), 'output.dir-unreadable'); + expect(finding?.details).toEqual({ directories: ['src'] }); + } finally { + process.chdir(here); + chmodSync(join(dist, 'src'), 0o700); + } + }); }); describe('CRLF bundles (a Windows toolchain)', () => { @@ -1140,18 +1199,24 @@ describe('index (sectioned) source maps (round 10)', () => { }); }); - it('a pathologically deep chain of index maps is bounded, not a stack overflow', async () => { - let map: Record = { - version: 3, - sources: ['a.ts'], - sourcesContent: ['x'], - mappings: 'A', + it('index maps are followed to a bounded depth (32): a leaf within it is found, one beyond it is not', async () => { + const chain = (depth: number): string => { + let map: Record = { + version: 3, + sources: ['a.ts'], + sourcesContent: ['x'], + mappings: 'A', + }; + for (let i = 0; i < depth; i++) { + map = { version: 3, sections: [{ offset: { line: 0, column: 0 }, map }] }; + } + return JSON.stringify({ ...map, debugId: ID_A }); }; - for (let i = 0; i < 5000; i++) { - map = { version: 3, sections: [{ offset: { line: 0, column: 0 }, map }] }; - } - pair(JSON.stringify({ ...map, debugId: ID_A })); + pair(chain(30)); + expect(ids(await run())).not.toContain('map.no-sources'); + pair(chain(40)); const report = await run(); + expect(ids(report)).toContain('map.no-sources'); expect(ids(report)).not.toContain('doctor.internal-error'); }); diff --git a/packages/bundler-plugin-core/src/doctor.test.ts b/packages/bundler-plugin-core/src/doctor.test.ts index 8be42b0ef..4d307b299 100644 --- a/packages/bundler-plugin-core/src/doctor.test.ts +++ b/packages/bundler-plugin-core/src/doctor.test.ts @@ -578,7 +578,7 @@ describe('diagnoseBuildOutput', () => { const describePerm = process.getuid?.() === 0 ? describe.skip : describe; describePerm('unreadable paths', () => { - it('an unreadable sub-directory contributes nothing; an unreadable parent is harmless', async () => { + it('an unreadable sub-directory contributes nothing (and is reported, see doctor.hardening.test.ts); an unreadable parent is harmless', async () => { put('a.js', `a${stamp(ID_A)}`); mkdirSync(join(dist, 'locked')); writeFileSync(join(dist, 'locked', 'x.js'), 'x'); diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts index 50505128d..f898b53b7 100644 --- a/packages/bundler-plugin-core/src/doctor.ts +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -117,6 +117,7 @@ export const DOCTOR_CHECK_IDS = [ 'output.dir-missing', 'output.no-js', 'output.unreadable', + 'output.dir-unreadable', 'output.excluded', 'output.exclude-unmatched', 'output.walk-fenced', @@ -174,10 +175,11 @@ const rel = (dir: string, path: string): string => posix(relative(dir, path)); */ export async function walkDetailed( root: string, -): Promise<{ files: string[]; skipped: string[]; fenced: boolean }> { +): Promise<{ files: string[]; skipped: string[]; fenced: boolean; unreadable: string[] }> { const fenced = (await isProjectRootOrAbove(root)) && existsSync(join(root, 'package.json')); const found: string[] = []; const skipped: string[] = []; + const unreadable: string[] = []; const pending: Array<{ dir: string; depth: number }> = [{ dir: root, depth: 0 }]; for (let next = pending.pop(); next !== undefined; next = pending.pop()) { if (fenced && next.depth > MAX_WALK_DEPTH) { @@ -188,6 +190,8 @@ export async function walkDetailed( try { entries = await readdir(next.dir, { withFileTypes: true }); } catch { + // A directory whose scripts and maps were NOT seen: reported, never a silent pass. + unreadable.push(rel(root, next.dir) || '.'); continue; } for (const entry of entries) { @@ -206,7 +210,7 @@ export async function walkDetailed( } } } - return { files: found.sort(), skipped: skipped.sort(), fenced }; + return { files: found.sort(), skipped: skipped.sort(), fenced, unreadable: unreadable.sort() }; } export async function walk(root: string): Promise { @@ -1016,6 +1020,19 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise rel(dir, d) || '.')]), + ].sort(); + if (unreadableDirs.length > 0) { + // Scripts, maps and pages in them were NOT checked: a pass would be false. + add({ + id: 'output.dir-unreadable', + severity: 'error', + message: `${unreadableDirs.length} director${unreadableDirs.length === 1 ? 'y' : 'ies'} could not be listed, so nothing in ${unreadableDirs.length === 1 ? 'it was' : 'them was'} checked (${unreadableDirs.slice(0, MAX_LISTED).join(', ')}${unreadableDirs.length > MAX_LISTED ? ', …' : ''}).`, + fix: 'Make the directories readable by the user running the doctor (a build run as root in a container, then checked as another user, is the usual cause) and run it again.', + details: listDetails('directories', unreadableDirs), + }); + } const pinned = sriScan.scripts.filter((pin) => !isExcluded(pin.script)); const unmatched = excludeGlobs.filter((_, i) => !matchedPatterns.has(i)); if (unmatched.length > 0) { diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index 0e38c896e..72636478a 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -128,6 +128,7 @@ const walkHtml = async ( dir: string, fenced: boolean, links: Set, + unreadableDirs: string[], depth = 0, ): Promise => { if (fenced && depth > MAX_DEPTH) { @@ -137,8 +138,9 @@ const walkHtml = async ( try { entries = await readdir(dir, { withFileTypes: true }); } catch { - // A missing or unreadable output directory is not this guard's error to raise: the CLI reports - // it properly ("path does not exist"), and throwing here would replace that with a worse one. + // Handed back so the doctor can say the pages in it were NOT scanned (a missing output directory is the CLI's + // error to raise: it reports it properly, and throwing here would replace that with a worse one). + unreadableDirs.push(dir); return []; } const found: string[] = []; @@ -152,7 +154,7 @@ const walkHtml = async ( if (skip) { continue; } - for (const page of await walkHtml(full, fenced, links, depth + 1)) { + for (const page of await walkHtml(full, fenced, links, unreadableDirs, depth + 1)) { found.push(page); } } else if ((entry.isFile() || entry.isSymbolicLink()) && /\.x?html?$/i.test(entry.name)) { @@ -187,6 +189,8 @@ export interface SriScan { skippedPages: Array<{ html: string; size: number }>; /** Pages that exist but could not be read (permissions, a race): their pins were NOT checked. */ unreadablePages: string[]; + /** Directories that exist but could not be listed: the pages in them were NOT scanned. */ + unreadableDirs: string[]; } export async function findSriProtectedScriptsDetailed( @@ -201,7 +205,8 @@ export async function findSriProtectedScriptsDetailed( // was outside the output directory, so the guard was silently inert for exactly those builds. const outDir = resolve(outDirInput); const links = new Set(); - const pages = await walkHtml(outDir, fenced, links); + const unreadableDirs: string[] = []; + const pages = await walkHtml(outDir, fenced, links, unreadableDirs); const realOutDir = await realpath(outDir).catch(() => outDir); const seen = new Set(); const found: SriProtectedScript[] = []; @@ -252,7 +257,7 @@ export async function findSriProtectedScriptsDetailed( found.push({ html, script, integrity: pin }); } } - return { scripts: found, skippedPages, unreadablePages }; + return { scripts: found, skippedPages, unreadablePages, unreadableDirs }; } /** SRI's hash algorithms, weakest to strongest — the order the spec compares them in. */ From db46ec9adf28bca324e4e6f12adb9c61724776be Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 20:55:45 +0500 Subject: [PATCH 62/63] fix(bundler-plugin-core): --exclude can name an unreadable directory Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .../src/doctor.hardening.test.ts | 30 +++++++++++++++++++ packages/bundler-plugin-core/src/doctor.ts | 17 +++++++++-- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index 8e7b421b4..89f1bff96 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -397,6 +397,36 @@ describe.skipIf(process.getuid?.() === 0)('an unreadable output directory', () = expect(ids(await run())).not.toContain('output.dir-unreadable'); }); + it('--exclude can name an unreadable directory: it leaves output.dir-unreadable, is listed as excluded, and its pattern is matched', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('vendor/x.js', 'x'); + put('assets/y.js', 'y'); + chmodSync(join(dist, 'vendor'), 0o000); + chmodSync(join(dist, 'assets'), 0o000); + try { + for (const pattern of ['vendor/**', 'vendor/', 'vendor', '**']) { + const report = await run({ exclude: [pattern] }); + const left = find(report, 'output.dir-unreadable')?.details?.directories; + expect(left, pattern).toEqual(pattern === '**' ? undefined : ['assets']); + expect(ids(report), pattern).not.toContain('output.exclude-unmatched'); + } + const report = await run({ exclude: ['vendor/**'] }); + expect( + report.findings.some( + (f) => + f.id === 'output.excluded' && + (f.details?.directories as string[] | undefined)?.includes('vendor'), + ), + ).toBe(true); + expect(find(await run({ exclude: ['nope/**'] }), 'output.dir-unreadable')?.details).toEqual({ + directories: ['assets', 'vendor'], + }); + } finally { + chmodSync(join(dist, 'vendor'), 0o700); + chmodSync(join(dist, 'assets'), 0o700); + } + }); + it('several unreadable directories are listed, sorted', async () => { put('a.js', `a${stamp(ID_A)}`); for (let i = 2; i >= 0; i--) { diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts index f898b53b7..5f711d290 100644 --- a/packages/bundler-plugin-core/src/doctor.ts +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -503,8 +503,7 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise glob.replace(/^(\.\/)+/, '')); const patterns = excludeGlobs.map(globToRegExp); const matchedPatterns = new Set(); - const isExcluded = (path: string): boolean => { - const name = rel(dir, path); + const isExcludedName = (name: string): boolean => { let hit = false; patterns.forEach((pattern, i) => { if (pattern.test(name)) { @@ -514,6 +513,7 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise isExcludedName(rel(dir, path)); const excluded: string[] = []; const files = walked.files.filter((file) => { if (isExcluded(file)) { @@ -1020,9 +1020,20 @@ async function diagnose(dirInput: string, options: DoctorOptions): Promise rel(dir, d) || '.')]), ].sort(); + // `--exclude vendor/**` (or `vendor`, `vendor/`) names a directory too: probe the directory and its `dir/` form. + const excludedDirs = allUnreadable.filter((d) => isExcludedName(d) || isExcludedName(`${d}/`)); + const unreadableDirs = allUnreadable.filter((d) => !excludedDirs.includes(d)); + if (excludedDirs.length > 0) { + add({ + id: 'output.excluded', + severity: 'info', + message: `${excludedDirs.length} unreadable director${excludedDirs.length === 1 ? 'y' : 'ies'} matched --exclude and ${excludedDirs.length === 1 ? 'was' : 'were'} not checked (${excludedDirs.slice(0, MAX_LISTED).join(', ')}${excludedDirs.length > MAX_LISTED ? ', …' : ''}).`, + details: listDetails('directories', excludedDirs), + }); + } if (unreadableDirs.length > 0) { // Scripts, maps and pages in them were NOT checked: a pass would be false. add({ From 4a2b3d04e1a4d30e3152c35189bd634fa2b8d31b Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 21:08:46 +0500 Subject: [PATCH 63/63] fix(bundler-plugin-core): --exclude hides an unreadable directory only if it would hide its files, and applies to HTML pages Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .../src/doctor.hardening.test.ts | 34 ++++++++++++++++++- packages/bundler-plugin-core/src/doctor.ts | 17 ++++++---- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts index 89f1bff96..f05010c5f 100644 --- a/packages/bundler-plugin-core/src/doctor.hardening.test.ts +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -404,7 +404,7 @@ describe.skipIf(process.getuid?.() === 0)('an unreadable output directory', () = chmodSync(join(dist, 'vendor'), 0o000); chmodSync(join(dist, 'assets'), 0o000); try { - for (const pattern of ['vendor/**', 'vendor/', 'vendor', '**']) { + for (const pattern of ['vendor/**', 'vendor/', '**/vendor/**', '**']) { const report = await run({ exclude: [pattern] }); const left = find(report, 'output.dir-unreadable')?.details?.directories; expect(left, pattern).toEqual(pattern === '**' ? undefined : ['assets']); @@ -418,6 +418,11 @@ describe.skipIf(process.getuid?.() === 0)('an unreadable output directory', () = (f.details?.directories as string[] | undefined)?.includes('vendor'), ), ).toBe(true); + // a glob that would NOT hide the directory's files if it could be listed must not hide the directory either + for (const pattern of ['vendor', 'vendor*', 'vendor/*', '*', 'assets/*']) { + const kept = find(await run({ exclude: [pattern] }), 'output.dir-unreadable')?.details; + expect(kept, pattern).toEqual({ directories: ['assets', 'vendor'] }); + } expect(find(await run({ exclude: ['nope/**'] }), 'output.dir-unreadable')?.details).toEqual({ directories: ['assets', 'vendor'], }); @@ -739,6 +744,33 @@ describe('big outputs stay readable (round 4)', () => { expect(report.summary.bundles).toBe(1); }); + it('--exclude applies to HTML pages too: an oversized or unreadable excluded page is not reported, and its pattern is matched', async () => { + put('a.js', `a${stamp(ID_A)}`); + truncateSync(put('huge.html', ''), 8 * 1024 * 1024 + 1); + truncateSync(put('keep/huge2.html', ''), 8 * 1024 * 1024 + 1); + const report = await run({ exclude: ['huge.html'] }); + expect(find(report, 'sri.html-skipped')?.details).toEqual({ files: ['keep/huge2.html'] }); + expect(ids(report)).not.toContain('output.exclude-unmatched'); + expect(ids(await run({ exclude: ['**/*.html'] }))).not.toContain('sri.html-skipped'); + }); + + it.skipIf(process.getuid?.() === 0)( + 'an unreadable excluded page is not reported either', + async () => { + put('a.js', `a${stamp(ID_A)}`); + const page = put('locked.html', '

'); + chmodSync(page, 0o000); + try { + expect(ids(await run())).toContain('sri.html-skipped'); + const report = await run({ exclude: ['locked.html'] }); + expect(ids(report)).not.toContain('sri.html-skipped'); + expect(ids(report)).not.toContain('output.exclude-unmatched'); + } finally { + chmodSync(page, 0o600); + } + }, + ); + it('a page of pathological unterminated tags does not stall the doctor', async () => { put('a.js', `a${stamp(ID_A)}`); put('index.html', '