From 0a74c1b9d88aa1adfe5fee56190490bbccdfacd0 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 11:41:00 +0500 Subject: [PATCH 01/59] 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/59] 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/59] 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 ``, + ); + const pins = await findSriProtectedScripts(root); + await write(root, 'main.js', 'a();\n//# debugId=x'); + return { html, pins }; + }; + + it('rewrites the pinned hash of a changed script, so the page verifies again', async () => { + const { html, pins } = await hashedThenStamped(); + await write(root, 'about.html', '

no hashes here

'); + const { files } = await resealIntegrity(pins, [root]); + expect(files).toEqual([html]); + expect(await findIntegrityMismatches(root)).toEqual([]); + const page = await readFile(html, 'utf8'); + expect(page).toContain(sha('sha384', 'a();\n//# debugId=x')); + expect(page).not.toContain(sha('sha384', 'a();')); + }); + + it('leaves a script that did not change, and its page, alone', async () => { + const { html, pins } = await hashedThenStamped(); + const before = await readFile(html, 'utf8'); + await write(root, 'main.js', 'a();'); // back to the hashed bytes + await write(root, 'about.html', '

no hashes here

'); + expect((await resealIntegrity(pins, [root])).files).toEqual([]); + expect(await readFile(html, 'utf8')).toBe(before); + }); + + it('rewrites every algorithm in the value, and keeps the ones it cannot compute', async () => { + await write(root, 'main.js', 'a();'); + const html = await write( + root, + 'index.html', + ``, + ); + const pins = await findSriProtectedScripts(root); + await write(root, 'main.js', 'a2();'); + await resealIntegrity(pins, [root]); + const page = await readFile(html, 'utf8'); + expect(page).toContain(sha('sha256', 'a2();')); + expect(page).toContain(sha('sha512', 'a2();')); + expect(page).toContain('md5-zzz'); + expect(await findIntegrityMismatches(root)).toEqual([]); + }); + + it('keeps the ?options suffix of a token', async () => { + await write(root, 'main.js', 'a();'); + const html = await write( + root, + 'index.html', + ``, + ); + const pins = await findSriProtectedScripts(root); + await write(root, 'main.js', 'a2();'); + await resealIntegrity(pins, [root]); + expect(await readFile(html, 'utf8')).toContain(`${sha('sha384', 'a2();')}?ct=x`); + }); + + it('also rewrites the copies of the page embedded in server modules, in every directory given', async () => { + const { pins } = await hashedThenStamped(); + const server = await fixture(); + const embedded = await write( + server, + 'assets-chunks/index.html.mjs', + `export default "";`, + ); + const untouched = await write(server, 'notes.txt', sha('sha384', 'a();')); + const { files } = await resealIntegrity(pins, [root, server]); + expect(files).toContain(embedded); + expect(files).not.toContain(untouched); + expect(await readFile(embedded, 'utf8')).toContain(sha('sha384', 'a();\n//# debugId=x')); + expect(await readFile(untouched, 'utf8')).toBe(sha('sha384', 'a();')); + }); + + it('skips a pinned script that is gone, and a directory that is missing', async () => { + await write( + root, + 'index.html', + ``, + ); + const pins = await findSriProtectedScripts(root); + expect(await resealIntegrity(pins, [root, join(root, 'missing')])).toEqual({ files: [] }); + }); + + it('does not descend into node_modules, dot directories or past the depth bound', async () => { + const { pins } = await hashedThenStamped(); + const hidden = await write(root, 'node_modules/x/index.html', sha('sha384', 'a();')); + const dot = await write(root, '.cache/index.html', sha('sha384', 'a();')); + const deep = await write(root, 'a/b/c/d/e/f/g/h/index.html', sha('sha384', 'a();')); + const { files } = await resealIntegrity(pins, [root]); + expect(files).not.toContain(hidden); + expect(files).not.toContain(dot); + expect(files).not.toContain(deep); + }); +}); diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index 3641731ba..b83922b64 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, writeFile } from 'node:fs/promises'; import { isAbsolute, join, normalize, resolve, sep } from 'node:path'; /** One ``; + + it('finds the scripts it pins, resolving relative and root-relative keys', async () => { + const dir = await fixture(); + await write(dir, 'chunk-a.js', 'a'); + await write(dir, 'assets/chunk-b.mjs', 'b'); + await write( + dir, + 'index.html', + importMap({ './chunk-a.js': 'sha384-A', '/assets/chunk-b.mjs': 'sha384-B' }), + ); + expect(await findSriProtectedScripts(dir)).toEqual([ + { html: join(dir, 'index.html'), script: join(dir, 'chunk-a.js'), integrity: 'sha384-A' }, + { + html: join(dir, 'index.html'), + script: join(dir, 'assets', 'chunk-b.mjs'), + integrity: 'sha384-B', + }, + ]); + }); + + it('lists a script pinned both by a tag and by the map once', async () => { + const dir = await fixture(); + await write(dir, 'main.js', 'a'); + await write( + dir, + 'index.html', + `${importMap({ './main.js': 'sha384-M' })}`, + ); + expect(await findSriProtectedScripts(dir)).toHaveLength(1); + }); + + it('ignores a map that is not JSON, has no integrity table, or pins something that is not ours', async () => { + const dir = await fixture(); + await write(dir, 'a.js', 'a'); + await write(dir, 'data.json', '{}'); + await write(dir, 'index.html', importMap('{ not json')); + await write(dir, 'two.html', importMap({ imports: { x: './a.js' } }.imports)); + await write( + dir, + 'three.html', + '', + ); + await write(dir, 'four.html', ''); + await write( + dir, + 'five.html', + importMap({ + 'https://cdn.test/x.js': 'sha384-X', + './data.json': 'sha384-D', + './a.js': '', + './b.js': 42, + }), + ); + expect(await findSriProtectedScripts(dir)).toEqual([]); + }); + + it('does not read a script that is not an import map, or one inside a comment', async () => { + const dir = await fixture(); + await write(dir, 'a.js', 'a'); + await write( + dir, + 'index.html', + `${importMap({ './a.js': 'sha384-A' }, 'type="application/json"')}${importMap({ './a.js': 'sha384-A' }, 'data-type="importmap"')}`, + ); + expect(await findSriProtectedScripts(dir)).toEqual([]); + }); + + it('is re-sealed with the rest of the page, so a stamped lazy chunk still loads', async () => { + const dir = await fixture(); + const digest = (text: string) => createHash('sha384').update(text).digest('base64'); + await write(dir, 'chunk.js', 'lazy();'); + const html = await write( + dir, + 'index.html', + importMap({ './chunk.js': `sha384-${digest('lazy();')}` }), + ); + const pins = await findSriProtectedScripts(dir); + await write(dir, 'chunk.js', 'lazy();\n//# debugId=x'); + expect((await resealIntegrity(pins, [dir])).files).toEqual([html]); + expect(await findIntegrityMismatches(dir)).toEqual([]); + expect(await readFile(html, 'utf8')).toContain(digest('lazy();\n//# debugId=x')); + }); + }); }); // The question a browser actually asks: does the file's digest match what the page pinned? Used after diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index b83922b64..5100e3eeb 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -55,6 +55,31 @@ const INTEGRITY_ATTR = /[\s"'<]integrity\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/i; const SRC_ATTR = /[\s"'<]src\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/i; const HREF_ATTR = /[\s"'<]href\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/i; +// An import map's `integrity` table pins modules by URL — how Angular's esbuild builder (v21+) pins its lazy +// chunks, which no tag mentions. The browser enforces it exactly like a tag's attribute. +const IMPORT_MAP = /]*?\stype\s*=\s*("|')?importmap\1?[^>]*>([\s\S]*?)<\/script\s*>/gi; + +/** `{ integrity, url }` for every entry of every import map's `integrity` table in `markup`. */ +function importMapPins(markup: string): { integrity: string; url: string }[] { + const pins: { integrity: string; url: string }[] = []; + for (const [, , body = ''] of markup.matchAll(IMPORT_MAP)) { + let table: unknown; + try { + table = (JSON.parse(body) as { integrity?: unknown }).integrity; + } catch { + continue; // not JSON: the browser ignores such a map too + } + if (typeof table === 'object' && table !== null) { + for (const [url, integrity] of Object.entries(table)) { + if (typeof integrity === 'string') { + pins.push({ integrity, url }); + } + } + } + } + return pins; +} + const unquote = (value: string): string => (value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")) ? value.slice(1, -1) @@ -141,20 +166,25 @@ export async function findSriProtectedScripts(outDirInput: string): Promise PRELOADS_SCRIPT.test(tag)) .map((tag) => ({ tag, url: HREF_ATTR.exec(tag)?.[1] })), - ]; - for (const { tag, url } of tags) { + ].map(({ tag, url }) => { const integrity = INTEGRITY_ATTR.exec(tag)?.[1]; + return { + integrity: integrity === undefined ? undefined : unquote(integrity), + url: url === undefined ? undefined : unquote(url), + }; + }); + for (const { integrity, url } of [...tags, ...importMapPins(markup)]) { // An empty `integrity` pins nothing — browsers treat it as no check at all. - if (integrity === undefined || unquote(integrity).trim() === '' || url === undefined) { + if (integrity === undefined || integrity.trim() === '' || url === undefined) { continue; } - const script = resolveLocalScript(outDir, htmlDir, unquote(url)); + const script = resolveLocalScript(outDir, htmlDir, 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)) { continue; } seen.add(script); - found.push({ html, script, integrity: unquote(integrity).trim() }); + found.push({ html, script, integrity: integrity.trim() }); } } return found; From e5e93e9f3d4c7978c388a27d3feb9a2598fe7fdc Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 12:14:12 +0500 Subject: [PATCH 10/59] feat(angular): ng add schematic, build wiring and a real-output test ng add @bugsee/angular: hidden production source maps, launch in main.ts, BugseeErrorHandler through addRootProvider (standalone and NgModule), a build:bugsee script and the token in a git-ignored env file. Built as a separate CommonJS entry with the collection and schema; checked against Angular's own schematics in a virtual tree, and for real with Angular CLI 22.3 (ng add, run twice, changes nothing the second time). Adds a test on real Angular 22.3 output with subresourceIntegrity, import map and SSR copy of the page. Co-Authored-By: Claude Sonnet 5.5 --- .changeset/angular-sourcemaps.md | 8 + packages/angular/package.json | 2 +- .../angular/src/schematics/collection.json | 10 + .../src/schematics/ng-add/index.test.ts | 524 ++++++++++++++++++ .../angular/src/schematics/ng-add/index.ts | 301 ++++++++++ .../angular/src/schematics/ng-add/schema.json | 19 + .../angular/src/schematics/ng-add/schema.ts | 7 + .../src/sourcemaps/upload.real-build.test.ts | 204 +++++++ .../fixtures/angular-22/chunk-BE0WtcF2.js | 19 + .../fixtures/angular-22/chunk-BE0WtcF2.js.map | 1 + .../fixtures/angular-22/chunk-C4fphy5n.js | 25 + .../fixtures/angular-22/chunk-C4fphy5n.js.map | 1 + packages/angular/tsup.config.ts | 33 +- 13 files changed, 1152 insertions(+), 2 deletions(-) create mode 100644 .changeset/angular-sourcemaps.md create mode 100644 packages/angular/src/schematics/collection.json create mode 100644 packages/angular/src/schematics/ng-add/index.test.ts create mode 100644 packages/angular/src/schematics/ng-add/index.ts create mode 100644 packages/angular/src/schematics/ng-add/schema.json create mode 100644 packages/angular/src/schematics/ng-add/schema.ts create mode 100644 packages/angular/src/sourcemaps/upload.real-build.test.ts create mode 100644 packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js create mode 100644 packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js.map create mode 100644 packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js create mode 100644 packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js.map diff --git a/.changeset/angular-sourcemaps.md b/.changeset/angular-sourcemaps.md new file mode 100644 index 000000000..ea843eb89 --- /dev/null +++ b/.changeset/angular-sourcemaps.md @@ -0,0 +1,8 @@ +--- +'@bugsee/angular': minor +'@bugsee/bundler-plugin-core': minor +--- + +`ng add @bugsee/angular` and Angular source maps. The schematic enables hidden script source maps in the production configuration, launches the SDK in `main.ts`, registers `BugseeErrorHandler` through Angular's own `addRootProvider` (standalone and NgModule apps; it prints what to add by hand rather than guess when it cannot find the bootstrap), and adds a `build:bugsee` script: `ng build`, then the new `bugsee-angular-upload` command (also `@bugsee/angular/sourcemaps`), which stamps debug-IDs into the browser output, uploads the maps and registers the build. Works on Angular's esbuild `application` builder and the webpack `browser` builder. + +`subresourceIntegrity: true` is supported rather than refused: `@bugsee/bundler-plugin-core` gains `resealSri`, which stamps with `--allow-sri` and re-writes the stale hashes in the pages (and in the copy of the page an SSR build embeds in its server modules), then verifies them. The SRI scan now also reads `` + + `` + + `` + + ``; + writeFileSync(join(browser, 'index.html'), page); + let embedded: string | undefined; + if (options.ssr) { + const server = join(dir, 'dist', 'demo', 'server', 'assets-chunks'); + mkdirSync(server, { recursive: true }); + embedded = join(server, 'index.html.mjs'); + writeFileSync(embedded, `export default ${JSON.stringify(page)};\n`); + } + return { dir, browser, embedded }; +} + +describeReal('uploadAngularSourcemaps on real Angular output with subresourceIntegrity', () => { + it("stamps both bundles, keeps Angular's debug-IDs, re-seals the page, and uploads the maps", async () => { + const { dir, browser } = workspace('sri'); + const before = { + entry: readFileSync(join(browser, ENTRY), 'utf8'), + lazy: readFileSync(join(browser, LAZY), 'utf8'), + }; + const errors: unknown[] = []; + uploads = 0; + + const out = await uploadAngularSourcemaps({ + cwd: dir, + appToken: 'tok', + endpoint, + vcs: false, + registerBuild: false, + env: {}, + onError: (e) => errors.push(e), + }); + + expect(errors).toEqual([]); + expect(out.status).toBe('uploaded'); + expect(out.result).toMatchObject({ injected: true, uploaded: true }); + expect(uploads).toBe(2); + + // Stamped: the runtime registration is appended, and the id Angular wrote is the id that is registered. + for (const [file, original] of [ + [ENTRY, before.entry], + [LAZY, before.lazy], + ] as const) { + const stamped = readFileSync(join(browser, file), 'utf8'); + const id = /\/\/# debugId=([0-9a-f-]{36})/.exec(original)?.[1] as string; + expect(stamped.startsWith(original)).toBe(true); + expect(stamped).toContain('_bugseeDebugIds'); + expect(stamped).toContain(`_bugseeDebugIds[n]="${id}"`); + } + // Uploaded, so the client maps are gone. + expect(existsSync(join(browser, `${ENTRY}.map`))).toBe(false); + expect(existsSync(join(browser, `${LAZY}.map`))).toBe(false); + + // Re-sealed: the page pins what is now on disk, in the script tag and in the import map. + expect(await findIntegrityMismatches(browser)).toEqual([]); + const page = readFileSync(join(browser, 'index.html'), 'utf8'); + expect(page).toContain(sha384(join(browser, ENTRY))); + expect(page).toContain(sha384(join(browser, LAZY))); + }); + + it('also re-seals the copy of the page an SSR build embeds in its server modules', async () => { + const { dir, browser, embedded } = workspace('ssr', { ssr: true }); + const stale = readFileSync(embedded as string, 'utf8'); + const errors: unknown[] = []; + + await uploadAngularSourcemaps({ + cwd: dir, + appToken: 'tok', + endpoint, + vcs: false, + registerBuild: false, + env: {}, + onError: (e) => errors.push(e), + }); + + expect(errors).toEqual([]); + const fresh = readFileSync(embedded as string, 'utf8'); + expect(fresh).not.toBe(stale); + expect(fresh).toContain(sha384(join(browser, ENTRY))); + expect(fresh).toContain(sha384(join(browser, LAZY))); + expect(fresh).toBe( + JSON.stringify(readFileSync(join(browser, 'index.html'), 'utf8')).replace( + /^/, + 'export default ', + ) + ';\n', + ); + }); + + it('the guard still refuses to stamp this build WITHOUT re-sealing: the import map is seen', async () => { + const { browser } = workspace('refused'); + const errors: unknown[] = []; + const result = await uploadSourcemaps({ + outDir: browser, + appToken: 'tok', + appVersion: '1', + appBuild: '1', + endpoint, + onError: (e) => errors.push(e), + }); + expect(result.injected).toBe(false); + expect(String(errors[0])).toContain('Subresource Integrity'); + expect(readFileSync(join(browser, LAZY), 'utf8')).not.toContain('_bugseeDebugIds'); + }); +}); diff --git a/packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js b/packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js new file mode 100644 index 000000000..bff5c21d1 --- /dev/null +++ b/packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js @@ -0,0 +1,19 @@ +import { u as el, c as Ip, l as Sp, d as tl } from './main-DNKCXA7T.js'; + +var s = class a { + static ɵfac = (e) => new (e || a)(); + static ɵcmp = Ip({ + type: a, + selectors: [[`app-lazy`]], + decls: 2, + vars: 0, + consts: [[`id`, `lazy`]], + template: (e, m) => { + e & 1 && (el(0, `p`, 0), Sp(1, `lazy-ready`), tl()); + }, + encapsulation: 2, + }); +}; + +export { s as Lazy }; +//# debugId=9f74a859-8fdd-51b3-ba40-449831d3c20a diff --git a/packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js.map b/packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js.map new file mode 100644 index 000000000..3e80b97ca --- /dev/null +++ b/packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chunk-BE0WtcF2.js","names":["Lazy","_Lazy","rf","ctx","ɵɵdomElementStart","ɵɵtext","ɵɵdomElementEnd","\\u0275fac","\\u0275cmp","t"],"sources":["../src/app/lazy.ts"],"sourcesContent":["import { Component } from '@angular/core';\n\n@Component({ selector: 'app-lazy', template: '

lazy-ready

' })\nexport class Lazy {}\n"],"mappings":"A,gEAGM,IAAOA,EAAP,MAAOC,CAAI,CAAA,OAAAM,KAAA,SAAA,EAAA,CAAA,OAAA,IAAA,GAAJN,EAAI,EAAA,OAAAO,KAAAC,GAAA,CAAA,KAAJR,EAAI,UAAA,CAAA,CAAA,UAAA,CAAA,EAAA,MAAA,EAAA,KAAA,EAAA,OAAA,CAAA,CAAA,KAAA,MAAA,CAAA,EAAA,SAAA,SAAAC,EAAAC,EAAA,CAAAD,EAAA,IAD6BE,GAAA,EAAA,IAAA,CAAA,EAAaC,GAAA,EAAA,YAAA,EAAUC,GAAA,EAAA,EAAA,cAAA,CAAA,CAAA,CAAA,E","debugId":"9f74a859-8fdd-51b3-ba40-449831d3c20a"} \ No newline at end of file diff --git a/packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js b/packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js new file mode 100644 index 000000000..b269ae429 --- /dev/null +++ b/packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js @@ -0,0 +1,25 @@ +var a = 2; +var r = 0.6; +var n = `image/webp`; +function i(e) { + return e === void 0 || !Number.isFinite(e) ? a : Math.min(60, Math.max(1, Math.round(e))); +} +function t(e) { + return e === void 0 || !Number.isFinite(e) ? r : Math.min(1, Math.max(0, e)); +} +function u(e) { + return e === `image/jpeg` ? `image/jpeg` : n; +} +function m(e) { + return e === `all` ? `all` : i(e); +} +function o(e = {}) { + return { + recordCanvas: !0, + sampling: { canvas: m(e.fps) }, + dataURLOptions: { type: u(e.imageType), quality: t(e.quality) }, + }; +} + +export { o as createCanvasRecordConfig }; +//# debugId=0ce56217-9be4-5485-b3d2-3b96675bd2ff diff --git a/packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js.map b/packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js.map new file mode 100644 index 000000000..8a51b42a4 --- /dev/null +++ b/packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chunk-C4fphy5n.js","names":["DEFAULT_FPS","DEFAULT_QUALITY","DEFAULT_IMAGE_TYPE","resolveFps","fps","resolveQuality","quality","resolveImageType","imageType","resolveSamplingCanvas","createCanvasRecordConfig","options"],"sources":["../node_modules/@bugsee/replay-canvas/dist/index.js"],"sourcesContent":["// src/canvas-config.ts\nvar DEFAULT_FPS = 2;\nvar DEFAULT_QUALITY = 0.6;\nvar DEFAULT_IMAGE_TYPE = \"image/webp\";\nfunction resolveFps(fps) {\n if (fps === void 0 || !Number.isFinite(fps)) {\n return DEFAULT_FPS;\n }\n return Math.min(60, Math.max(1, Math.round(fps)));\n}\nfunction resolveQuality(quality) {\n if (quality === void 0 || !Number.isFinite(quality)) {\n return DEFAULT_QUALITY;\n }\n return Math.min(1, Math.max(0, quality));\n}\nfunction resolveImageType(imageType) {\n return imageType === \"image/jpeg\" ? \"image/jpeg\" : DEFAULT_IMAGE_TYPE;\n}\nfunction resolveSamplingCanvas(fps) {\n return fps === \"all\" ? \"all\" : resolveFps(fps);\n}\nfunction createCanvasRecordConfig(options = {}) {\n return {\n recordCanvas: true,\n sampling: { canvas: resolveSamplingCanvas(options.fps) },\n dataURLOptions: {\n type: resolveImageType(options.imageType),\n quality: resolveQuality(options.quality)\n }\n };\n}\n\nexport { createCanvasRecordConfig };\n\n"],"ignoreList":[0],"mappings":"AACA,IAAIA,EAAc,EACdC,IAAAA,EAAkB,GAClBC,IAAAA,EAAqB,aACzB,SAASC,EAAWC,EAAK,CACvB,OAAIA,IAAQ,IAAA,IAAU,CAAC,OAAO,SAASA,CAAG,EACjCJ,EAEF,KAAK,IAAI,GAAI,KAAK,IAAI,EAAG,KAAK,MAAMI,CAAG,CAAC,CAAC,CAClD,CACA,SAASC,EAAeC,EAAS,CAC/B,OAAIA,IAAY,IAAA,IAAU,CAAC,OAAO,SAASA,CAAO,EACzCL,EAEF,KAAK,IAAI,EAAG,KAAK,IAAI,EAAGK,CAAO,CAAC,CACzC,CACA,SAASC,EAAiBC,EAAW,CACnC,OAAOA,IAAc,aAAe,aAAeN,CACrD,CACA,SAASO,EAAsBL,EAAK,CAClC,OAAOA,IAAQ,MAAQ,MAAQD,EAAWC,CAAG,CAC/C,CACA,SAASM,EAAyBC,EAAU,CAAC,EAAG,CAC9C,MAAO,CACL,aAAc,CAAA,EACd,SAAU,CAAE,OAAQF,EAAsBE,EAAQ,GAAG,CAAE,EACvD,eAAgB,CACd,KAAMJ,EAAiBI,EAAQ,SAAS,EACxC,QAASN,EAAeM,EAAQ,OAAO,CACzC,CACF,CACF,C","debugId":"0ce56217-9be4-5485-b3d2-3b96675bd2ff"} \ No newline at end of file diff --git a/packages/angular/tsup.config.ts b/packages/angular/tsup.config.ts index 82e2f36b8..f98d2094f 100644 --- a/packages/angular/tsup.config.ts +++ b/packages/angular/tsup.config.ts @@ -1,4 +1,35 @@ +import { cpSync } from 'node:fs'; import { defineConfig } from 'tsup'; import { baseConfig } from '../../tsup.config.base'; -export default defineConfig(baseConfig); +// Four outputs, because they run in four different places: +// - the runtime entry and the `./sourcemaps` API: ESM + CJS + types (the base preset); +// - the `bugsee-angular-upload` bin: ESM only (it uses top-level await), run by Node; +// - the `ng add` schematic: CommonJS (`.cjs`), loaded by the Angular CLI, with its collection and schema JSON. +// `clean` is off in every one so they cannot delete each other's output; the build script clears dist first. +const shared = { ...baseConfig, clean: false } as const; + +export default defineConfig([ + { + ...shared, + entry: { index: 'src/index.ts', 'sourcemaps/index': 'src/sourcemaps/index.ts' }, + }, + { + ...shared, + dts: false, + format: ['esm'], + platform: 'node', + entry: { 'sourcemaps/bin': 'src/sourcemaps/bin.ts' }, + }, + { + ...shared, + dts: false, + format: ['cjs'], + platform: 'node', + entry: { 'schematics/ng-add/index': 'src/schematics/ng-add/index.ts' }, + onSuccess: async () => { + cpSync('src/schematics/collection.json', 'dist/schematics/collection.json'); + cpSync('src/schematics/ng-add/schema.json', 'dist/schematics/ng-add/schema.json'); + }, + }, +]); From 780fd616a2a367eba5728013676921735d79957d Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 12:14:27 +0500 Subject: [PATCH 11/59] fix(bundler-plugin-core): round-3 review findings - verifyStamp takes the path API its names follow; the restore path passes the native one, so a custom-named map is held to its bundle id on Windows paths - a spill directory that cannot be removed is reported, never thrown, and never masks an earlier error - tests for the verifyStampedOnDisk sibling fallback (both directions) - docs: known limits of the on-disk verification Co-Authored-By: Claude Sonnet 5.5 --- docs/design/source-maps.md | 8 +++ .../bundler-plugin-core/src/orchestrate.ts | 12 +++- .../src/stamp-files.fail.test.ts | 56 ++++++++++++++++++- .../src/stamp-files.test.ts | 18 ++++++ .../bundler-plugin-core/src/stamp-files.ts | 3 +- .../src/verify-stamp.test.ts | 24 ++++++++ .../bundler-plugin-core/src/verify-stamp.ts | 4 +- 7 files changed, 121 insertions(+), 4 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 31e935136..b6974fd80 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -245,6 +245,14 @@ beside them is not mistaken for a miss. A stamped build is also re-checked again its HTML (`findIntegrityMismatches`, `sri.ts`): any ``, ); - const pins = await findSriProtectedScripts(root); + const before = await snapshotScriptDigests([root]); await write(root, 'main.js', 'a();\n//# debugId=x'); - return { html, pins }; + return { html, before }; }; it('rewrites the pinned hash of a changed script, so the page verifies again', async () => { - const { html, pins } = await hashedThenStamped(); + const { html, before } = await hashedThenStamped(); await write(root, 'about.html', '

no hashes here

'); - const { files } = await resealIntegrity(pins, [root]); + const { files } = await resealIntegrity(before, [root]); expect(files).toEqual([html]); expect(await findIntegrityMismatches(root)).toEqual([]); const page = await readFile(html, 'utf8'); @@ -581,12 +570,11 @@ describe('resealIntegrity', () => { }); it('leaves a script that did not change, and its page, alone', async () => { - const { html, pins } = await hashedThenStamped(); - const before = await readFile(html, 'utf8'); + const { html, before } = await hashedThenStamped(); + const page = await readFile(html, 'utf8'); await write(root, 'main.js', 'a();'); // back to the hashed bytes - await write(root, 'about.html', '

no hashes here

'); - expect((await resealIntegrity(pins, [root])).files).toEqual([]); - expect(await readFile(html, 'utf8')).toBe(before); + expect((await resealIntegrity(before, [root])).files).toEqual([]); + expect(await readFile(html, 'utf8')).toBe(page); }); it('rewrites every algorithm in the value, and keeps the ones it cannot compute', async () => { @@ -596,9 +584,9 @@ describe('resealIntegrity', () => { 'index.html', ``, ); - const pins = await findSriProtectedScripts(root); + const before = await snapshotScriptDigests([root]); await write(root, 'main.js', 'a2();'); - await resealIntegrity(pins, [root]); + await resealIntegrity(before, [root]); const page = await readFile(html, 'utf8'); expect(page).toContain(sha('sha256', 'a2();')); expect(page).toContain(sha('sha512', 'a2();')); @@ -613,14 +601,14 @@ describe('resealIntegrity', () => { 'index.html', ``, ); - const pins = await findSriProtectedScripts(root); + const before = await snapshotScriptDigests([root]); await write(root, 'main.js', 'a2();'); - await resealIntegrity(pins, [root]); + await resealIntegrity(before, [root]); expect(await readFile(html, 'utf8')).toContain(`${sha('sha384', 'a2();')}?ct=x`); }); it('also rewrites the copies of the page embedded in server modules, in every directory given', async () => { - const { pins } = await hashedThenStamped(); + const { before } = await hashedThenStamped(); const server = await fixture(); const embedded = await write( server, @@ -628,31 +616,120 @@ describe('resealIntegrity', () => { `export default "";`, ); const untouched = await write(server, 'notes.txt', sha('sha384', 'a();')); - const { files } = await resealIntegrity(pins, [root, server]); + const { files } = await resealIntegrity(before, [root, server]); expect(files).toContain(embedded); expect(files).not.toContain(untouched); expect(await readFile(embedded, 'utf8')).toContain(sha('sha384', 'a();\n//# debugId=x')); expect(await readFile(untouched, 'utf8')).toBe(sha('sha384', 'a();')); }); - it('skips a pinned script that is gone, and a directory that is missing', async () => { - await write( + it('rewrites a hash held in an import map, which no tag mentions', async () => { + await write(root, 'lazy.js', 'lazy();'); + const html = await write( + root, + 'index.html', + ``, + ); + const before = await snapshotScriptDigests([root]); + await write(root, 'lazy.js', 'lazy();\n//# debugId=x'); + expect((await resealIntegrity(before, [root])).files).toEqual([html]); + expect(await findIntegrityMismatches(root)).toEqual([]); + }); + + // What the webpack builder does with `subresourceIntegrity` (measured on @angular-devkit/build-angular 19, Chromium): + // the page pins runtime/main/polyfills, and the RUNTIME script carries the hashes of the lazy chunks, which no page + // pins. A stamped lazy chunk was blocked while the entry scripts ran. The runtime's own bytes change when its table is + // rewritten, so its pin in the page needs a second round. + it("rewrites a hash table held in a script, and then that script's own pin", async () => { + await write(root, 'lazy.js', 'lazy();'); + const table = (lazy: string) => `var t={"lazy":"${lazy}"};run(t);`; + await write(root, 'runtime.js', table(sha('sha384', 'lazy();'))); + const html = await write( + root, + 'index.html', + ``, + ); + const before = await snapshotScriptDigests([root]); + await write(root, 'lazy.js', 'lazy();\n//# debugId=x'); // stamped after it was hashed + + const { files } = await resealIntegrity(before, [root]); + + const fresh = sha('sha384', 'lazy();\n//# debugId=x'); + expect(await readFile(join(root, 'runtime.js'), 'utf8')).toBe(table(fresh)); + expect(await readFile(html, 'utf8')).toContain(sha('sha384', table(fresh))); + expect(files.sort()).toEqual([html, join(root, 'runtime.js')].sort()); + expect(await findIntegrityMismatches(root)).toEqual([]); + }); + + it('re-seals a script that was stamped AND had its table rewritten, once for each change', async () => { + // The runtime chunk is both: the stamp appends to it, and the lazy chunk's new hash goes in it. + await write(root, 'lazy.js', 'lazy();'); + const table = (lazy: string) => `var t={"lazy":"${lazy}"};run(t);`; + const original = table(sha('sha384', 'lazy();')); + await write(root, 'runtime.js', original); + const html = await write( root, 'index.html', - ``, + ``, ); - const pins = await findSriProtectedScripts(root); - expect(await resealIntegrity(pins, [root, join(root, 'missing')])).toEqual({ files: [] }); + const before = await snapshotScriptDigests([root]); + await write(root, 'lazy.js', 'lazy();\n//# debugId=x'); + await write(root, 'runtime.js', `${original}\n//# debugId=y`); + + await resealIntegrity(before, [root]); + + expect(await findIntegrityMismatches(root)).toEqual([]); + const runtime = await readFile(join(root, 'runtime.js'), 'utf8'); + expect(runtime).toContain(sha('sha384', 'lazy();\n//# debugId=x')); + expect(await readFile(html, 'utf8')).toContain(sha('sha384', runtime)); + }); + + it("gives up rather than loop when two scripts hold each other's hash", async () => { + // Content-addressed hashes cannot form a cycle in a real build; a hand-made one must still terminate. + const a = await write(root, 'a.js', 'a-original'); + const b = await write(root, 'b.js', 'b-original'); + const before = await snapshotScriptDigests([root]); + await write(root, 'a.js', `x="${sha('sha384', 'b-original')}";`); + await write(root, 'b.js', `y="${sha('sha384', 'a-original')}";`); + const { files } = await resealIntegrity(before, [root]); + expect(files.sort()).toEqual([a, b].sort()); + }); + + it('skips a script that is gone, and a directory that is missing', async () => { + await write(root, 'gone.js', 'x'); + const before = await snapshotScriptDigests([root]); + await rm(join(root, 'gone.js')); + expect(await resealIntegrity(before, [root, join(root, 'missing')])).toEqual({ files: [] }); }); it('does not descend into node_modules, dot directories or past the depth bound', async () => { - const { pins } = await hashedThenStamped(); + const { before } = await hashedThenStamped(); const hidden = await write(root, 'node_modules/x/index.html', sha('sha384', 'a();')); const dot = await write(root, '.cache/index.html', sha('sha384', 'a();')); const deep = await write(root, 'a/b/c/d/e/f/g/h/index.html', sha('sha384', 'a();')); - const { files } = await resealIntegrity(pins, [root]); + const { files } = await resealIntegrity(before, [root]); expect(files).not.toContain(hidden); expect(files).not.toContain(dot); expect(files).not.toContain(deep); }); }); + +describe('snapshotScriptDigests', () => { + it('records every script under the directories, and nothing else', async () => { + const dir = await fixture(); + const a = await write(dir, 'a.js', 'a'); + const b = await write(dir, 'sub/b.mjs', 'b'); + const c = await write(dir, 'c.cjs', 'c'); + await write(dir, 'd.html', 'd'); + await write(dir, 'e.js.map', 'e'); + await write(dir, 'node_modules/f.js', 'f'); + const snapshot = await snapshotScriptDigests([dir]); + expect([...snapshot.keys()].sort()).toEqual([a, b, c].sort()); + const digest = (alg: string) => createHash(alg).update('a').digest('base64'); + expect(snapshot.get(a)).toEqual({ + sha256: digest('sha256'), + sha384: digest('sha384'), + sha512: digest('sha512'), + }); + }); +}); diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index 5100e3eeb..1073fb7e3 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -252,55 +252,96 @@ export async function findIntegrityMismatches(outDirInput: string): Promise; + +const digestsOf = (bytes: Buffer): Digests => ({ + sha256: createHash('sha256').update(bytes).digest('base64'), + sha384: createHash('sha384').update(bytes).digest('base64'), + sha512: createHash('sha512').update(bytes).digest('base64'), +}); + +/** What every script under some directories hashed to at one moment: the input of {@link resealIntegrity}. */ +export type ScriptDigests = Map; + +/** + * Record the digests of every script (`.js`/`.mjs`/`.cjs`) under `dirs`, BEFORE something rewrites them. * - * `pins` must be what {@link findSriProtectedScripts} returned BEFORE the change — it is where the stale - * digests come from. A pin whose script still matches is left alone; one whose script is gone is skipped. + * Taken from the files, not from the pages that pin them: a hash can live where no tag mentions it — an + * import map's table, or a table inside the webpack builder's runtime chunk, which pins every lazy chunk. + */ +export async function snapshotScriptDigests(dirs: readonly string[]): Promise { + const snapshot: ScriptDigests = new Map(); + for (const dir of dirs) { + for (const file of await walkFiles(resolve(dir), SCRIPT_FILE)) { + snapshot.set(file, digestsOf(await readFile(file))); + } + } + return snapshot; +} + +/** + * Re-seal a build whose scripts changed AFTER their hashes were written: for every script whose bytes differ + * from `before` (a {@link snapshotScriptDigests}), replace its old digests with its current ones, in every HTML + * page, `.mjs` module and script under `dirs`. A script that is gone is skipped. * - * Sound only for a build whose copies of the hashes all live in those files — e.g. Angular's, where the - * integrity attributes are in `index.html` (and, with SSR, in the HTML Angular embeds in its server modules). - * It is NOT sound for `webpack-subresource-integrity`, which also writes the lazy chunks' hashes into the - * runtime chunk; the caller checks the result with {@link findIntegrityMismatches}, and a build with another - * copy of a hash is not claimed to be fixed. Returns the files it rewrote. A missing directory is skipped. + * A digest is the same length whatever it hashes, so a rewrite never moves a byte offset: source maps stay + * valid. Rewriting a table inside a script changes THAT script, so the pass repeats (bounded) until nothing + * is stale; a build whose hashes cannot be brought to rest is left for the caller's + * {@link findIntegrityMismatches} to report. Sound where every copy of a hash is a literal in those files — + * Angular's pages, its SSR copies of them, the webpack builder's runtime table. Not for a hash computed at + * run time. Returns the files it rewrote. A missing directory is skipped. */ export async function resealIntegrity( - pins: readonly SriProtectedScript[], + before: ScriptDigests, dirs: readonly string[], ): Promise<{ files: string[] }> { - const swaps = new Map(); - for (const pin of pins) { - let bytes: Buffer; - try { - bytes = await readFile(pin.script); - } catch { - continue; - } - if (passesIntegrity(pin.integrity, bytes)) { - continue; - } - for (const [alg, digests] of digestsByAlgorithm(pin.integrity)) { - const fresh = createHash(alg).update(bytes).digest('base64'); - for (const digest of digests) { - swaps.set(`${alg}-${digest}`, `${alg}-${fresh}`); - } - } - } + const known: ScriptDigests = new Map( + [...before].map(([file, digests]) => [file, { ...digests }]), + ); const rewritten = new Set(); - for (const dir of dirs) { - for (const file of await walkFiles(resolve(dir), RESEAL_FILE)) { - const before = await readFile(file, 'utf8'); - let after = before; - for (const [stale, fresh] of swaps) { - after = after.split(stale).join(fresh); + for (let pass = 0; pass < MAX_RESEAL_PASSES; pass++) { + const swaps = new Map(); + for (const [file, digests] of known) { + let bytes: Buffer; + try { + bytes = await readFile(file); + } catch { + continue; + } + const now = digestsOf(bytes); + for (const alg of SRI_ALGORITHMS) { + if (now[alg] !== digests[alg]) { + swaps.set(`${alg}-${digests[alg]}`, `${alg}-${now[alg]}`); + // What this script's pages hold now, for the next pass. + digests[alg] = now[alg]; + } } - if (after !== before) { - await writeFile(file, after, 'utf8'); - rewritten.add(file); + } + if (swaps.size === 0) { + break; + } + for (const dir of dirs) { + for (const file of await walkFiles(resolve(dir), RESEAL_FILE)) { + const text = await readFile(file, 'utf8'); + let after = text; + for (const [stale, fresh] of swaps) { + after = after.split(stale).join(fresh); + } + if (after !== text) { + await writeFile(file, after, 'utf8'); + rewritten.add(file); + } } } } From ed55e8e4c04715ac8ac3a73ada911f51e5e17ee3 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 12:23:07 +0500 Subject: [PATCH 14/59] docs: Angular ng add, source-map upload and SRI re-seal Co-Authored-By: Claude Sonnet 5.5 --- docs/PROGRESS.md | 7 ++++ docs/design/source-maps.md | 83 ++++++++++++++++++++++++++++++++++---- docs/source-maps-usage.md | 50 ++++++++++++++++++----- packages/angular/README.md | 47 +++++++++++++++++++-- 4 files changed, 165 insertions(+), 22 deletions(-) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index b57d06c64..f236ec80b 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1531,3 +1531,10 @@ 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. + +### Angular: `ng add @bugsee/angular` and source-map upload, SRI re-seal (2026-11-23) → `feat/angular-sourcemaps` +`@bugsee/angular` gains a **schematic** (`ng add`; `src/schematics/ng-add`, built as CommonJS `dist/schematics/ng-add/index.cjs` + `collection.json`/`schema.json`, package.json `schematics` field; `@angular-devkit/schematics` + `@schematics/angular` are OPTIONAL PEERS `>=16.1` — `addRootProvider` exists from 16.1 — and never reach the runtime entry) and a **build-time entry** `@bugsee/angular/sourcemaps` + the `bugsee-angular-upload` bin (`uploadAngularSourcemaps`, `resolveAngularOutput`, `runCli`). The schematic: hidden script maps in the production configuration (never overriding a setting that already produces maps), `launch(token)` in `main.ts`, `BugseeErrorHandler` through Angular's own `addRootProvider` (standalone and NgModule; when the bootstrap cannot be found it changes no source and prints the lines to add), a `build:bugsee` script (`ng build --configuration production && bugsee-angular-upload ...`), the token in a git-ignored `.env.bugsee-build-plugin`. Idempotent. The upload step reuses `@bugsee/bundler-plugin-core` (no pipeline reimplemented): the esbuild `application` builder has no plugin hook, so it is a post-build step. + +`@bugsee/bundler-plugin-core` additions: **`resealSri`** (snapshot every script's digests, stamp with `--allow-sri`, swap each changed script's old digests for its new ones in the pages, the HTML Angular embeds in its server modules and the webpack builder's runtime hash table, verify) — the refusal stays the default for every other caller; and the SRI scan now reads **`` in the same page, pinning EVERY lazy chunk. A stamped lazy chunk is blocked + (`Failed to find a valid digest in the 'integrity' attribute for resource '…/chunk-X.js' … has been blocked`, + and `Failed to fetch dynamically imported module`) while the entry scripts still run — which is what made this a + finding: the first version of the scan read tags only; +- with SSR/prerender, a second copy of the page as a string in `server/assets-chunks/index*.html.mjs` and in + `server/index.server.html`, which the Node server answers requests from. + +Nothing else in the esbuild builder's output (no runtime table). The legacy webpack `browser` builder differs: +its `runtime.*.js` carries the lazy chunks' hashes (`sriHashes`), which NO page pins (measured on +`@angular-devkit/build-angular` 19: a stamped lazy chunk was blocked while the entry scripts ran). So the stale +hashes cannot be found by reading the pages. They are found by what the files WERE: `snapshotScriptDigests` records +the sha256/384/512 of every script under the output before the stamp, and `resealIntegrity` swaps each changed +script's old digests for its new ones in every HTML, `.mjs` and `.js` file (same length, so no byte offset moves and +the maps stay valid), repeating (bounded) because rewriting the runtime's table changes the runtime's own hash. + +The order that works is the one the CLI documents for `--allow-sri`: stamp, then recompute the hashes. +`uploadSourcemaps({ resealSri: true })` does: snapshot, `inject --allow-sri`, verify the stamp, re-seal, then verify +with `findIntegrityMismatches` (the pages' pins, the one thing a browser checks first). A page that still does not +verify is reported, or thrown under `failOnError`, never silent. A hash computed at run time, or kept in a file +outside the directories given, is not covered and is not claimed to be. + +**Verified for real** (`npm run build:bugsee` from `ng add`, the packed `@bugsee/angular` + `@bugsee/bundler-plugin-core`, +the real `bugsee-cli`, a mock collector, Chromium via Playwright; `outputHashing: all`, `subresourceIntegrity: true`): + +| App | Result | +|---|---| +| Angular 22.3, esbuild `application`, lazy route | every pin matches its file; 5 maps uploaded and deleted; the page runs, the lazy chunk loads, 4 debug-IDs registered, no console error | +| same, stamped with `--allow-sri` and NOT re-sealed (control) | blocked outright: nothing runs | +| Angular 22.3, SSR + prerender | 24 pins across `browser/`, `server/index.server.html` and the 3 `assets-chunks` modules all match; the real `server.mjs` serves a page that runs, 5 debug-IDs, no console error | +| Angular 19.2, webpack `browser` builder | the lazy chunk (blocked before the digest snapshot) now loads; 4 debug-IDs, no console error; control blocked | + +CI keeps the bytes half of this: `upload.real-build.test.ts` runs the real CLI over two real Angular 22.3 chunks with +the SRI page shapes above (script tag, import map, SSR copy); the browser half is not in CI. + +**What it refuses.** A build with a service worker (`ngsw.json` in the output): the manifest pins a hash of every +file, a service worker treats a changed file as corrupt, and rewriting `ngsw.json` was not built. The tool says so and +uploads nothing (throws under `failOnError`). It also stamps `browser/` only: a server bundle's errors are the Node +SDK's, symbolicated by `@bugsee/node`. + +**The legacy webpack `browser` builder** (`@angular-devkit/build-angular:browser`) takes the same route: the post-build +step needs nothing from the builder, and its output is flat (`outputPath` IS the browser directory). Its SRI is the +reason for the digest snapshot above. `@angular-builders/custom-webpack` + `bugseeWebpackPlugin` (the route Sentry +documents) was considered and not built: it would need the plugin's in-build stamp to run before Angular's own SRI +plugin hashes, an ordering nobody verified for Angular's compilation, to cover one legacy builder that the post-build +step already covers with a measured result. --- diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index be668b96a..d8189f960 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -72,7 +72,7 @@ For **Rspack**, set `devtool: 'source-map'`: its production default is `devtool: there is nothing to upload (the plugin says so through `onNotice`). **What these do not cover.** **Angular's builder does not accept esbuild plugins**, so `bugseeEsbuildPlugin` -cannot be used with `ng build`: use the post-build recipe in §2. Bun's bundler, `tsc` and `swc` have no hook +cannot be used with `ng build`: use `ng add @bugsee/angular` (§2). Bun's bundler, `tsc` and `swc` have no hook either (also §2). Next.js on webpack uses the webpack plugin. **Where the settings come from.** The lookup order is: the **plugin option**, then the **process environment**, @@ -184,20 +184,48 @@ BUGSEE_APP_TOKEN=… bugsee-cli debug-files upload ./dist \ --type sourcemaps --version "$APP_VERSION" --build "$APP_BUILD" ``` -**Angular (17+, `ng build` with the esbuild application builder).** There is no plugin hook, so add the CLI as a -step after the build (for example an npm script or a CI step): +**Angular — `ng add @bugsee/angular`.** Run it once in the workspace (`ng add @bugsee/angular --app-token `): ```bash -ng build --source-map # or "sourceMap": true in angular.json; the output lands in dist//browser -export BUGSEE_APP_TOKEN=… # the CLI does not read .env.bugsee-build-plugin -bugsee-cli sourcemaps inject dist//browser -bugsee-cli debug-files upload dist//browser \ - --type sourcemaps --version "$APP_VERSION" --build "$APP_BUILD" +ng add @bugsee/angular +npm run build:bugsee # ng build --configuration production, then bugsee-angular-upload +``` + +It turns on hidden script source maps in the production configuration +(`"sourceMap": { "scripts": true, "styles": false, "hidden": true }`), launches the SDK in `main.ts`, registers +`BugseeErrorHandler` in your providers, adds the `build:bugsee` script, and keeps the token in +`.env.bugsee-build-plugin` (added to `.gitignore`). Where it cannot find your bootstrap it changes no source and prints +the lines to add. Running it again changes nothing. A plain `ng build` does not upload; run `build:bugsee` where you +build for release, with `BUGSEE_APP_TOKEN` set (or the env file present). + +`bugsee-angular-upload` is the step the script runs, and you can run it yourself after any `ng build` (it finds the +output from `angular.json`): `--project`, `--configuration`, `--dist `, `--dry-run`, `--keep-maps`, +`--fail-on-error`, `--strip-sources-content`, `--help`. The same thing is a function: +`import { uploadAngularSourcemaps } from '@bugsee/angular/sourcemaps'`. It works on both Angular builders — the +esbuild `application` builder (the default since 17, output in `dist//browser`) and the webpack +`browser` builder (`outputPath` is the browser directory) — because it only needs the finished output. + +- **`subresourceIntegrity: true` is supported.** Angular writes a hash of every script into `index.html` (the lazy + chunks in an import map, or in the runtime chunk on the webpack builder) and, with SSR, into the copy of that page + its server serves. The step stamps the bundles, + then re-writes those hashes to match and checks them, so the page keeps loading. (The CLI on its own refuses such a + build; this is what `--allow-sri` assumes you do.) +- **A build with a service worker (`serviceWorker` in `angular.json`, an `ngsw.json` in the output) is not stamped.** + `ngsw.json` pins a hash of every file and the service worker rejects a changed one. The step says so and uploads + nothing; build without it for the release you symbolicate. +- **Only `browser/` is uploaded.** An SSR server bundle's errors are reported by the Node SDK. +- `outputHashing: "all"` (the default in production) keeps the file names unique per build; the debug-ID, not the + file name, is what links a frame to its map. + +By hand, without the schematic (any Angular version), the same two steps are: + +```bash +ng build --configuration production # with sourceMap.scripts true in angular.json +BUGSEE_APP_TOKEN=… npx bugsee-angular-upload --configuration production ``` -If you enable `"subresourceIntegrity": true`, bugsee-cli 0.7.13 `inject` refuses to run (it would invalidate the -integrity hashes Angular writes into `index.html`) unless you pass `--allow-sri`, which you should only do if -the hashes are recomputed after it runs; otherwise turn that option off for builds you symbolicate. +Do not run `bugsee-cli sourcemaps inject` yourself on an Angular build that has `subresourceIntegrity`: it refuses +(or, with `--allow-sri`, leaves a page whose hashes no longer match, which the browser blocks). `inject` must run **before deployment** so the shipped bundle carries the debug-ID + the `_bugseeDebugIds` runtime stub the SDK reads. This is exactly what the plugins automate; the CLI is the same engine, just invoked by hand. diff --git a/packages/angular/README.md b/packages/angular/README.md index 7de3d0482..6b36ec236 100644 --- a/packages/angular/README.md +++ b/packages/angular/README.md @@ -16,11 +16,52 @@ pnpm add @bugsee/bugsee @bugsee/angular yarn add @bugsee/bugsee @bugsee/angular ``` -Peer dependencies: `@angular/core` >= 16 and `@angular/router` >= 16 (both optional). +Peer dependencies: `@angular/core` >= 16 and `@angular/router` >= 16 (both optional). `@angular-devkit/schematics` and `@schematics/angular` (>= 16.1, optional) are only used by `ng add` and are already in every Angular workspace. -## Usage +## Quick start: `ng add` -Launch Bugsee as early as possible, at the top of your entry module. In the browser `launch()` returns a Promise of the client. Await it only if you need the client right away. +```sh +ng add @bugsee/angular +``` + +It asks for your app token and then, in the workspace's application: + +- turns on hidden script source maps in the production configuration of `angular.json` (`"sourceMap": { "scripts": true, "styles": false, "hidden": true }`), unless it already produces maps; +- launches the SDK in `main.ts`, before the bootstrap; +- registers `BugseeErrorHandler` as your `ErrorHandler` (standalone `app.config.ts` or `AppModule`); +- adds a `build:bugsee` script, and keeps the token for it in `.env.bugsee-build-plugin` (added to `.gitignore`). + +Where it cannot find your bootstrap it changes no source and prints the lines to add by hand. Running it again changes nothing. With several applications pass `--project `. + +## Source maps + +Build for release with the script it added: + +```sh +npm run build:bugsee # ng build --configuration production && bugsee-angular-upload --configuration production +``` + +`bugsee-angular-upload` stamps debug-IDs into `dist//browser`, uploads the maps, registers the build and removes the local maps, so a crash from the shipped bundle shows your original source. Set `BUGSEE_APP_TOKEN` (or keep the env file) where you run it. A plain `ng build` does not upload. + +You can also run it by hand after any `ng build` (`bugsee-angular-upload --help` lists the options: `--project`, `--configuration`, `--dist`, `--dry-run`, `--keep-maps`, `--fail-on-error`, …), or call it from code: + +```ts +import { uploadAngularSourcemaps } from "@bugsee/angular/sourcemaps"; + +await uploadAngularSourcemaps({ project: "my-app", configuration: "production" }); +``` + +It works with the esbuild `application` builder and the webpack `browser` builder. Notes: + +- `subresourceIntegrity: true` is supported: after stamping, the integrity hashes in `index.html`, in the import map and in the SSR server modules are re-written to match, so the page keeps loading. +- A build with a service worker (`ngsw.json` in the output) is not stamped, since the service worker pins a hash of every file; nothing is uploaded for it. +- Only the browser output is uploaded; errors from an SSR server are reported by the Node SDK. + +Details and the measurements behind them: [source maps](https://github.com/bugsee/bugsee-javascript/blob/main/docs/source-maps-usage.md). + +## Usage by hand + +`ng add` does this for you. To do it yourself, launch Bugsee as early as possible, at the top of your entry module. In the browser `launch()` returns a Promise of the client. Await it only if you need the client right away. ```ts // main.ts From 2e4885f93122cabcf4f62198eb0c2b78d73c64be Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 12:28:15 +0500 Subject: [PATCH 15/59] fix(bundler-plugin-core): upload and delete every uploadable map, whatever its name The explicit upload set only took *.js.map, but the stamp keys a map under any name (sourcemapFileNames '[name].map'), so such a build uploaded nothing and had its map deleted. Candidates are now everything the CLI scans a directory for (every *.map except .css/.d.ts/.d.mts/.d.cts), any uploadable map needs a debug-id to be deleted, and a pre-stamped build deletes exactly the set it uploaded (one walker, no second walk with a different fence). Real-build tests (real CLI, no dry run, failOnError on and off): Rollup, Vite 7 and 8 with sourcemapFileNames, Rspack with [name].map. Co-Authored-By: Claude Sonnet 5.5 --- docs/design/source-maps.md | 23 +++-- .../src/orchestrate.stamp.test.ts | 60 +++++++++++- .../bundler-plugin-core/src/orchestrate.ts | 22 +++-- .../src/plugin.in-build.real-build.test.ts | 98 +++++++++++++++++++ .../src/stamp-files.test.ts | 52 ++++++++-- .../bundler-plugin-core/src/stamp-files.ts | 25 +++-- 6 files changed, 244 insertions(+), 36 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 501b605ac..a2a963ab6 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -259,15 +259,22 @@ A pre-stamped build is uploaded as an **explicit file set**, never as the direct stamp wrote has a debug-id; anything else in the output directory (a `public/` vendor script and its map, a stale map with `emptyOutDir: false`) has none, and the real bugsee-cli (0.9.0, measured, without `--dry-run`) exits non-zero for a directory that holds a map without a debug-id ("source map has no debug_id … nothing was -uploaded"), which would lose EVERY map of the build. So the script maps under the directory (the whole output -directory, fenced only at a project root) are partitioned by whether they carry a debug-id BEFORE the CLI call; -the keyed ones are uploaded by path (in batches), the rest are left on disk untouched and reported as a -**notice** (`onNotice`), not an error: they were never part of the build, so they do not fail `failOnError`. If -nothing is keyed there is no CLI call (a notice; under `failOnError` the "no maps" failure the strict CLI used to -give). A dry run still passes the directory (nothing was stamped; `--dry-run` only warns). Rspack development +uploaded"), which would lose EVERY map of the build. So every uploadable map under the directory (the whole output directory, fenced only at a project +root) is partitioned by whether it carries a debug-id BEFORE the CLI call. "Uploadable" is what the CLI scans a +directory for: **every `*.map` except stylesheet and declaration maps** (`.css.map`, `.d.ts.map`, `.d.mts.map`, +`.d.cts.map`), NOT only `*.js.map`: the stamp keys a map whatever it is called (`sourcemapFileName(s)`, +`[name].map`), and a narrower filter silently dropped such a build's maps (measured on Rollup, Vite and Rspack +with `[name].map`). The keyed ones are uploaded by path (in batches), the rest are left on disk untouched and +reported as a **notice** (`onNotice`), not an error: they were never part of the build, so they do not fail +`failOnError`. If nothing is keyed there is no CLI call (a notice; under `failOnError` the "no maps" failure the +strict CLI used to give). The uploaded set is also the **deletion set**: one walker, and a map is deleted only if +it was in the uploaded set after the upload succeeded (a keyed map under `test/` or a dot-directory is uploaded +AND deleted; nothing the walk merely saw is ever deleted). Consequently stylesheet and declaration maps are not +deleted on this path (they were not uploaded). A dry run still passes the directory (nothing was stamped; `--dry-run` only warns). Rspack development builds that are not uploaded (`uploadInDevelopment` unset) are no longer stamped either. Covered by real builds -(`plugin.in-build.real-build.test.ts`: Vite 7/8 with a `publicDir` vendor script, Rollup with a stale one; real -CLI, no dry run, `failOnError` on). +(`plugin.in-build.real-build.test.ts`: Vite 7/8 with a `publicDir` vendor script, Rollup with a stale one, and `[name].map` custom map +names on Rollup, Vite 7/8 and Rspack; real CLI, no dry run, `failOnError` on and off). Not run for real: webpack +itself (Rspack shares its SourceMapDevToolPlugin filename path). ### Map deletion diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index 7d4eed02f..f145a321f 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -597,8 +597,8 @@ describe('a pre-stamped directory upload names its files (never the directory)', expect(upload).not.toContain(dir); expect(upload).not.toContain(join(dir, 'vendor.js.map')); expect(upload).not.toContain(join(dir, 'style.css.map')); - // Keyed maps and the stylesheet map are deleted; the vendor map is untouched. - expect((await readdir(dir)).sort()).toEqual(['sub', 'vendor.js.map']); + // Only what was uploaded is deleted: the vendor map AND the stylesheet map (never sent) stay. + expect((await readdir(dir)).sort()).toEqual(['style.css.map', 'sub', 'vendor.js.map']); expect(result.uploaded).toBe(true); expect(onError).not.toHaveBeenCalled(); expect(notices).toHaveLength(1); @@ -606,6 +606,62 @@ describe('a pre-stamped directory upload names its files (never the directory)', expect(notices[0]).toContain('not part of this build'); }); + it('uploads and deletes a keyed map of ANY name (index.map), and deletes nothing that was not uploaded', async () => { + await writeFile(join(dir, 'index.map'), keyed); + await mkdir(join(dir, 'test')); + await mkdir(join(dir, '.well-known')); + await writeFile(join(dir, 'test', 'x.js.map'), keyed); + await writeFile(join(dir, '.well-known', 'y.js.map'), keyed); + await writeFile(join(dir, 'unkeyed.map'), '{"version":3}'); + await writeFile(join(dir, 'a.d.ts.map'), '{"version":3}'); + const { run, calls } = record(); + const deleted: string[][] = []; + const result = await uploadSourcemaps( + opts({ + run, + failOnError: true, + onNotice: () => undefined, + deleteMapFiles: async (_d: string, only?: readonly string[]) => { + deleted.push([...(only ?? [])]); + return [...(only ?? [])]; + }, + }), + ); + const upload = calls.find((c) => c[0] === 'debug-files') as string[]; + const uploaded = [ + join(dir, '.well-known', 'y.js.map'), + join(dir, 'index.map'), + join(dir, 'test', 'x.js.map'), + ]; + for (const map of uploaded) { + expect(upload).toContain(map); + } + expect(upload).not.toContain(join(dir, 'unkeyed.map')); + // ONE set: what was uploaded is exactly what is deleted (test/ and dot-directories included). + expect(deleted).toEqual([uploaded]); + expect(result.deletedMaps).toEqual(uploaded); + }); + + it('never deletes a map that was not in the uploaded set, whatever the directory walk saw', async () => { + await writeFile(join(dir, 'a.js.map'), keyed); + const { run } = record(); + const deleted: string[][] = []; + const walk = vi.fn(async () => [join(dir, 'a.js.map'), join(dir, 'foreign.js.map')]); + await uploadSourcemaps( + opts({ + run, + // The deletion snapshot lister would also report this map; it must not be consulted. + listMapFiles: walk, + deleteMapFiles: async (_d: string, only?: readonly string[]) => { + deleted.push([...(only ?? [])]); + return []; + }, + }), + ); + expect(deleted).toEqual([[join(dir, 'a.js.map')]]); + expect(walk).not.toHaveBeenCalled(); + }); + it('with nothing keyed there is nothing to upload: no CLI call, a notice, and a failure only under failOnError', async () => { await writeFile(join(dir, 'vendor.js.map'), '{"version":3}'); const { run, calls } = record(); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index dc2917a3a..768378cb0 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -7,7 +7,7 @@ import { type RunBugseeCliOptions, runBugseeCli, type SpawnResult } from './run- import { findIntegrityMismatches, findSriProtectedScripts, type SriProtectedScript } from './sri'; import { isProjectRootOrAbove, - listScriptMaps, + listUploadableMaps, MAX_WALK_DEPTH, NEVER_WALK, partitionByKeyed, @@ -90,7 +90,7 @@ export interface UploadSourcemapsOptions { stampedBundles?: readonly string[]; /** Where a non-failing observation goes (default: nowhere — callers that want it pass the notice sink). */ onNotice?: (message: string) => void; - /** Injectable lister of the script maps to consider for a pre-stamped directory upload (default {@link listScriptMaps}). */ + /** Injectable lister of the script maps to consider for a pre-stamped directory upload (default {@link listUploadableMaps}). */ listUploadMaps?: (dir: string) => Promise; /** Where the pre-inject originals are spilled (default: the OS temp directory). A test seam. */ spillRoot?: string; @@ -346,9 +346,13 @@ export async function uploadSourcemaps( // A DIRECTORY run snapshots the maps that exist now: they are the ones this upload covers, and only they // may be deleted (a map written meanwhile was never sent). If the snapshot cannot be taken, nothing is // 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; + let uploadedMaps: string[] = []; let snapshot: string[] | undefined; let snapshotError: unknown; - if (files === undefined && deleteMaps && !dryRun) { + if (files === undefined && deleteMaps && !dryRun && !explicitUpload) { try { snapshot = await (options.listMapFiles ?? listMapFiles)(outDir); } catch (error) { @@ -375,9 +379,8 @@ export async function uploadSourcemaps( // its map, a stale map with `emptyOutDir: false`) has none, and the CLI exits non-zero for a directory // holding such a map ("nothing was uploaded"), which would lose EVERY map of the build. Unkeyed maps // are left alone and said, not failed. - const explicitUpload = files === undefined && options.preStamped === true && !dryRun; if (explicitUpload) { - const candidates = await (options.listUploadMaps ?? listScriptMaps)(outDir); + const candidates = await (options.listUploadMaps ?? listUploadableMaps)(outDir); const { deletable, kept } = await (options.partitionMaps ?? partitionByKeyed)(candidates); if (kept.length > 0) { (options.onNotice ?? ((m: string) => console.warn(`[bugsee] ${m}`)))( @@ -394,6 +397,7 @@ export async function uploadSourcemaps( for (const batch of inBatches(deletable)) { await run(uploadArgs(batch), cliOptions); } + uploadedMaps = deletable; } } else if (files === undefined) { await run(uploadArgs([outDir]), cliOptions); @@ -427,9 +431,11 @@ export async function uploadSourcemaps( let deletedMaps: string[] = []; if (deleteMaps) { const { deletable, kept } = await (options.partitionMaps ?? partitionByKeyed)( - files === undefined - ? (snapshot as string[]) - : [...files.maps, ...(files.stylesheetMaps ?? [])], + explicitUpload + ? uploadedMaps + : files === undefined + ? (snapshot as string[]) + : [...files.maps, ...(files.stylesheetMaps ?? [])], ); deletedMaps = await (options.deleteMapFiles ?? defaultDeleteMapFiles)(outDir, deletable); // Unkeyed maps of a pre-stamped build were already said (a notice, above): they were never part of it. 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 b45966505..7b83f1d60 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 @@ -464,3 +464,101 @@ describeReal('an unstamped vendor script + map beside a stamped build', () => { expect(notices.join('\n')).toContain('vendor.js.map'); }); }); + +// The stamp keys a map whatever it is called (`sourcemapFileName(s)`, `[name].map`), so the upload set must be +// everything the CLI scans a directory for, not just `*.js.map`, and a map is deleted only if it was uploaded. +// Real bugsee-cli, no dry run. +describeReal('maps with custom names (sourcemapFileNames: "[name].map")', () => { + for (const failOnError of [true, false]) { + const tag = `failOnError ${failOnError}`; + const expectUploadedAndGone = (out: string, before: number): void => { + const files = readdirSync(out, { recursive: true }) as string[]; + expect(requests.length, 'uploaded').toBeGreaterThan(before); + expect( + files.filter((f) => f.endsWith('.map')), + 'deleted after the confirmed upload', + ).toEqual([]); + for (const bundle of files.filter((f) => /\.[cm]?js$/.test(f))) { + const code = readFileSync(join(out, bundle), 'utf8'); + expect(code, bundle).toMatch(/\/\/# debugId=[0-9a-f-]{36}/); + expect(code, bundle).toMatch(/sourceMappingURL=[^\s]*\.map(?!\.)/); + expect(code, bundle).not.toMatch(/sourceMappingURL=[^\s]*\.js\.map/); + } + }; + + it(`Rollup (${tag})`, async () => { + const app = makeApp(`rollup-custom-${failOnError}`, { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [ + bugseeRollupPlugin({ + ...pluginOptions(), + failOnError, + onError: (e: unknown) => errors.push(e), + }), + ], + }); + await bundle.write({ dir: app.out, sourcemap: true, sourcemapFileNames: '[name].map' }); + await bundle.close(); + expect(errors.map(String)).toEqual([]); + expectUploadedAndGone(app.out, before); + }); + + for (const [label, build] of [ + ['Vite 8 (Rolldown)', viteBuild], + ['Vite 7 (Rollup)', vite7Build], + ] as const) { + it(`${label} (${tag})`, async () => { + const app = makeApp(`vite-custom-${label.replace(/\W+/g, '')}-${failOnError}`, { + lazy: false, + }); + const before = requests.length; + const errors: unknown[] = []; + await build( + viteConfig(app, [bugseeVite({ failOnError, onError: (e: unknown) => errors.push(e) })], { + rollupOptions: { output: { sourcemapFileNames: 'assets/[name].map' } }, + }), + ); + expect(errors.map(String)).toEqual([]); + expectUploadedAndGone(app.out, before); + }); + } + + it(`Rspack (${tag})`, async () => { + const app = makeApp(`rspack-custom-${failOnError}`, { lazy: false }); + const before = requests.length; + const errors: unknown[] = []; + const compile = await new Promise<{ errors: unknown[] }>((resolve, reject) => { + const compiler = rspack({ + context: app.dir, + mode: 'production', + entry: join(app.dir, 'index.js'), + devtool: false, + output: { path: app.out }, + plugins: [ + new rspack.SourceMapDevToolPlugin({ filename: '[name].map' }), + bugseeRspackPlugin({ + ...pluginOptions(), + failOnError, + onError: (e: unknown) => errors.push(e), + }), + ], + }); + compiler.run((err, stats) => { + compiler.close(() => + err + ? reject(err) + : resolve({ + errors: [...(stats as { compilation: { errors: unknown[] } }).compilation.errors], + }), + ); + }); + }); + expect(compile.errors.map(String)).toEqual([]); + expect(errors.map(String)).toEqual([]); + expectUploadedAndGone(app.out, before); + }); + } +}); diff --git a/packages/bundler-plugin-core/src/stamp-files.test.ts b/packages/bundler-plugin-core/src/stamp-files.test.ts index 6c7107a1c..aa136f1ba 100644 --- a/packages/bundler-plugin-core/src/stamp-files.test.ts +++ b/packages/bundler-plugin-core/src/stamp-files.test.ts @@ -15,7 +15,9 @@ import { dirname, join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { isProjectRootOrAbove, - listScriptMaps, + isUploadableMap, + listUploadableMaps, + partitionByKeyed, restoreAtomically, snapshotStampFiles, verifyAndRestore, @@ -375,30 +377,60 @@ describe('verifyStampedOnDisk', () => { }); }); -describe('listScriptMaps', () => { - it('lists script maps of the whole output directory (src/ and dot-dirs included), sorted, never stylesheet maps', async () => { +describe('isUploadableMap — what the CLI scans a directory for', () => { + it('is every .map except stylesheet and declaration maps', () => { + for (const yes of ['a.js.map', 'a.mjs.map', 'index.map', 'dir/b.cjs.map', 'x.bundle.jsx.map']) { + expect(isUploadableMap(yes), yes).toBe(true); + } + for (const no of ['a.css.map', 'a.d.ts.map', 'a.d.mts.map', 'a.d.cts.map', 'a.js', 'map']) { + expect(isUploadableMap(no), no).toBe(false); + } + }); +}); + +describe('partitionByKeyed — any uploadable map needs a key, whatever it is called', () => { + it('keeps an unkeyed index.map, deletes a keyed one, and deletes a stylesheet/declaration map', async () => { + await writeFile(join(dir, 'keyed.map'), stampedMap); + await writeFile(join(dir, 'unkeyed.map'), plainMap); + await writeFile(join(dir, 'a.css.map'), plainMap); + await writeFile(join(dir, 'a.d.ts.map'), plainMap); + const names = ['keyed.map', 'unkeyed.map', 'a.css.map', 'a.d.ts.map'].map((n) => join(dir, n)); + const { deletable, kept } = await partitionByKeyed(names); + expect(kept).toEqual([join(dir, 'unkeyed.map')]); + expect(deletable.sort()).toEqual( + [join(dir, 'a.css.map'), join(dir, 'a.d.ts.map'), join(dir, 'keyed.map')].sort(), + ); + }); +}); + +describe('listUploadableMaps', () => { + it('lists every uploadable map of the whole output directory (any name, src/ and dot-dirs included), sorted', async () => { await mkdir(join(dir, 'src')); await mkdir(join(dir, '.hidden')); + await mkdir(join(dir, 'test')); await writeFile(join(dir, 'src', 'a.js.map'), '{}'); await writeFile(join(dir, '.hidden', 'b.mjs.map'), '{}'); - await writeFile(join(dir, 'z.cjs.map'), '{}'); + await writeFile(join(dir, 'test', 't.map'), '{}'); + await writeFile(join(dir, 'index.map'), '{}'); await writeFile(join(dir, 'c.css.map'), '{}'); - await writeFile(join(dir, 'd.js'), 'x'); - expect((await listScriptMaps(dir)).map((f) => f.slice(dir.length + 1))).toEqual([ + await writeFile(join(dir, 'd.d.ts.map'), '{}'); + await writeFile(join(dir, 'e.js'), 'x'); + expect((await listUploadableMaps(dir)).map((f) => f.slice(dir.length + 1))).toEqual([ '.hidden/b.mjs.map', + 'index.map', 'src/a.js.map', - 'z.cjs.map', + 'test/t.map', ]); }); it('is fenced at the project root', async () => { const start = process.cwd(); await mkdir(join(dir, 'src')); await writeFile(join(dir, 'src', 'a.js.map'), '{}'); - await writeFile(join(dir, 'ok.js.map'), '{}'); + await writeFile(join(dir, 'ok.map'), '{}'); process.chdir(dir); try { - expect((await listScriptMaps(dir)).map((f) => f.slice(dir.length + 1))).toEqual([ - 'ok.js.map', + expect((await listUploadableMaps(dir)).map((f) => f.slice(dir.length + 1))).toEqual([ + 'ok.map', ]); } finally { process.chdir(start); diff --git a/packages/bundler-plugin-core/src/stamp-files.ts b/packages/bundler-plugin-core/src/stamp-files.ts index 813ce1ecb..c61e01f43 100644 --- a/packages/bundler-plugin-core/src/stamp-files.ts +++ b/packages/bundler-plugin-core/src/stamp-files.ts @@ -331,17 +331,26 @@ export async function verifyStampedOnDisk(bundles: readonly string[]): Promise { - const all = await walkStampable(dir, await isProjectRootOrAbove(dir)); - return all.filter((file) => SCRIPT_MAP.test(file)).sort(); +export function isUploadableMap(path: string): boolean { + return path.endsWith('.map') && !NOT_UPLOADED_MAP.test(path); } -/** Script maps are the ones inject keys and the CLI uploads; a stylesheet map is neither. */ -const SCRIPT_MAP = /\.[cm]?js\.map$/; +/** + * Every uploadable map under `dir`, walked like the snapshot: the whole output directory, fenced only at a + * project root. The SINGLE source of both what a pre-stamped build uploads and what it deletes afterwards. + */ +export async function listUploadableMaps(dir: string): Promise { + const all = await walkStampable(dir, await isProjectRootOrAbove(dir)); + return all.filter(isUploadableMap).sort(); +} /** * Split `maps` into those that may be deleted after an upload and those that must be kept. @@ -359,7 +368,7 @@ export async function partitionByKeyed( const deletable: string[] = []; const kept: string[] = []; for (const path of maps) { - if (!SCRIPT_MAP.test(path)) { + if (!isUploadableMap(path)) { deletable.push(path); continue; } From ac5a8ea3996c9f58e1e1e9c8c090513be0757fc5 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 12:34:27 +0500 Subject: [PATCH 16/59] fix(bundler-plugin-core): roll the build back when the re-seal fails A re-seal that threw midway, or left a hash stale, used to leave the stamped files and half-written pages on disk (a blocked page) and upload anyway. It now restores every file the stamp and re-seal may have written from its own snapshot, reports it, and uploads nothing. Also tests that every occurrence of a digest is rewritten. Co-Authored-By: Claude Sonnet 5.5 --- packages/bundler-plugin-core/src/index.ts | 1 + .../src/orchestrate.reseal-rollback.test.ts | 193 ++++++++++++++++++ .../src/orchestrate.test.ts | 4 +- .../bundler-plugin-core/src/orchestrate.ts | 87 +++++++- packages/bundler-plugin-core/src/sri.test.ts | 18 ++ packages/bundler-plugin-core/src/sri.ts | 11 + 6 files changed, 302 insertions(+), 12 deletions(-) create mode 100644 packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts diff --git a/packages/bundler-plugin-core/src/index.ts b/packages/bundler-plugin-core/src/index.ts index 51f96525b..9f52ae5a6 100644 --- a/packages/bundler-plugin-core/src/index.ts +++ b/packages/bundler-plugin-core/src/index.ts @@ -61,6 +61,7 @@ export { export { findIntegrityMismatches, findSriProtectedScripts, + listResealFiles, resealIntegrity, type ScriptDigests, type SriProtectedScript, diff --git a/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts new file mode 100644 index 000000000..69842418b --- /dev/null +++ b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts @@ -0,0 +1,193 @@ +// A re-seal that fails must leave the build as the bundler emitted it. The stamp is already undone when it does not +// verify (step 1b); the re-seal rewrites more than the stamp touched (pages, server modules, runtime tables), so it +// is undone the same way, from its own snapshot, and nothing is uploaded for bundles that went back unstamped. +// Real `bugsee-cli` for the stamp; only the re-seal (or its verdict) is made to fail. +import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { uploadSourcemaps } from './orchestrate'; +import { resolveBugseeCli, runBugseeCli } from './run-cli'; + +const cli = resolveBugseeCli(); +const probe = cli.endsWith('.js') + ? spawnSync(process.execPath, [cli, '--version'], { encoding: 'utf8' }) + : spawnSync(cli, ['--version'], { encoding: 'utf8' }); +const required = process.env.CI !== undefined || process.env.BUGSEE_REQUIRE_CLI !== undefined; +const describeReal = probe.status === 0 || required ? describe : describe.skip; + +const made: string[] = []; +afterEach(() => { + for (const dir of made.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +const sha384 = (text: string) => `sha384-${createHash('sha384').update(text).digest('base64')}`; + +/** An output directory with one hashed bundle + map, a page pinning it, and an SSR copy of the page elsewhere. */ +function build() { + const root = mkdtempSync(join(tmpdir(), 'bugsee-rollback-')); + made.push(root); + const out = join(root, 'browser'); + const server = join(root, 'server'); + mkdirSync(out); + mkdirSync(server); + const js = 'console.log(1);\n//# sourceMappingURL=main.js.map\n'; + writeFileSync(join(out, 'main.js'), js); + writeFileSync( + join(out, 'main.js.map'), + JSON.stringify({ version: 3, file: 'main.js', sources: ['a.ts'], names: [], mappings: 'AAAA' }), + ); + const page = ``; + writeFileSync(join(out, 'index.html'), page); + writeFileSync(join(out, 'about.html'), '

no hashes

'); + writeFileSync(join(server, 'index.html.mjs'), `export default ${JSON.stringify(page)};`); + return { root, out, server }; +} + +const snapshot = (...dirs: string[]) => + Object.fromEntries( + dirs.flatMap((dir) => + readdirSync(dir).map((name) => [join(dir, name), readFileSync(join(dir, name), 'utf8')]), + ), + ); + +const options = (out: string, server: string, extra: Record = {}) => { + const calls: string[] = []; + const run = vi.fn(async (args: string[], o: Parameters[1]) => { + calls.push(args[0] === 'debug-files' ? 'upload' : args.slice(0, 2).join(' ')); + if (args[0] === 'debug-files') { + return { code: 0, stdout: '', stderr: '' }; + } + return runBugseeCli(args, o); + }); + const errors: unknown[] = []; + return { + calls, + errors, + opts: { + outDir: out, + appToken: 'tok', + appVersion: '1', + appBuild: '1', + resealSri: true, + resealDirs: [out, server], + run, + onError: (e: unknown) => errors.push(e), + ...extra, + }, + }; +}; + +describeReal('uploadSourcemaps re-seal rollback', () => { + it('seals a good build (control): page verifies, upload runs', async () => { + const { out, server } = build(); + const { opts, calls, errors } = options(out, server); + const result = await uploadSourcemaps(opts); + expect(errors).toEqual([]); + expect(result.uploaded).toBe(true); + expect(calls).toContain('upload'); + }); + + it('puts every original byte back when the re-seal throws midway, and uploads nothing', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts, calls, errors } = options(out, server, { + reseal: async () => { + // It had already written one file when the disk failed. + writeFileSync(join(out, 'index.html'), 'HALF-SEALED'); + throw new Error('ENOSPC: no space left on device'); + }, + }); + const result = await uploadSourcemaps(opts); + expect(snapshot(out, server)).toEqual(before); + expect(calls).not.toContain('upload'); + expect(result).toMatchObject({ injected: false, uploaded: false, deletedMaps: [] }); + const message = String(errors[0]); + expect(message).toContain('ENOSPC'); + expect(message).toMatch(/restored/); + }); + + it('puts every original byte back when a hash is still stale after the re-seal, and uploads nothing', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts, calls, errors } = options(out, server, { + verifySri: async () => [ + { html: join(out, 'index.html'), script: join(out, 'main.js'), integrity: 'sha384-X' }, + ], + }); + const result = await uploadSourcemaps(opts); + expect(snapshot(out, server)).toEqual(before); + expect(calls).not.toContain('upload'); + expect(result).toMatchObject({ injected: false, uploaded: false }); + expect(String(errors[0])).toContain('still does not match'); + // Only what changed is put back: main.js, its map and the two copies of the page, not about.html. + expect(String(errors[0])).toContain('(4 file(s))'); + // The maps were not deleted either: the unstamped bundles still need them if the user opts out of SRI. + expect(readdirSync(out)).toContain('main.js.map'); + }); + + it('brings back a file the failed re-seal removed', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts } = options(out, server, { + reseal: async () => { + rmSync(join(out, 'index.html')); + throw new Error('boom'); + }, + }); + await uploadSourcemaps(opts); + expect(snapshot(out, server)).toEqual(before); + }); + + it('reports a re-seal that rejects with something that is not an Error', async () => { + const { out, server } = build(); + const { opts, errors } = options(out, server, { + reseal: async () => { + throw 'plain string failure'; + }, + }); + await uploadSourcemaps(opts); + expect(String(errors[0])).toContain('plain string failure'); + }); + + it('removes the temporary copies of the originals it took', async () => { + const { out, server, root } = build(); + const spillRoot = join(root, 'spill'); + mkdirSync(spillRoot); + const { opts } = options(out, server, { spillRoot }); + await uploadSourcemaps(opts); + expect(readdirSync(spillRoot)).toEqual([]); + }); + + it('throws the failure under failOnError, after restoring', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts } = options(out, server, { + failOnError: true, + reseal: async () => { + throw new Error('EACCES'); + }, + }); + await expect(uploadSourcemaps(opts)).rejects.toThrow(/EACCES/); + expect(snapshot(out, server)).toEqual(before); + }); + + it('names a file it could not restore', async () => { + const { out, server } = build(); + const { opts, errors } = options(out, server, { + verifySri: async () => [ + { html: join(out, 'index.html'), script: join(out, 'main.js'), integrity: 'sha384-X' }, + ], + restoreFile: async (_spill: string, target: string) => { + throw new Error(`EPERM on ${target}`); + }, + }); + await uploadSourcemaps(opts); + expect(String(errors[0])).toMatch(/COULD NOT restore/); + expect(String(errors[0])).toContain('EPERM'); + }); +}); diff --git a/packages/bundler-plugin-core/src/orchestrate.test.ts b/packages/bundler-plugin-core/src/orchestrate.test.ts index 3ad31d095..aaa2df7fd 100644 --- a/packages/bundler-plugin-core/src/orchestrate.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.test.ts @@ -950,13 +950,13 @@ describe('uploadSourcemaps with resealSri', () => { ]); }); - it('reports a page that still does not verify, and uploads anyway (the maps are right, the page is not)', async () => { + it('reports a page that still does not verify, restores, and uploads nothing', async () => { const { run, calls } = fakeRun(); const onError = vi.fn(); await uploadSourcemaps({ ...sealed({ verifySri: async () => [pin] }), run, onError }); expect(String(onError.mock.calls[0]?.[0])).toContain('index.html'); expect(String(onError.mock.calls[0]?.[0])).toContain('main.js'); - expect(calls.map((c) => c.args[0])).toContain('debug-files'); + expect(calls.map((c) => c.args[0])).not.toContain('debug-files'); }); it('throws under failOnError when a page still does not verify', async () => { diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index ec4b3a7b6..865ed0c04 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -1,12 +1,14 @@ // 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 { createHash } from 'node:crypto'; +import { readdir, readFile, unlink } from 'node:fs/promises'; import { join, resolve } from 'node:path'; import { type RunBugseeCliOptions, runBugseeCli, type SpawnResult } from './run-cli'; import { findIntegrityMismatches, findSriProtectedScripts, + listResealFiles, resealIntegrity, type SriProtectedScript, snapshotScriptDigests, @@ -17,6 +19,7 @@ import { MAX_WALK_DEPTH, NEVER_WALK, partitionByKeyed, + restoreAtomically, type SnapshotTarget, type StampSnapshot, snapshotStampFiles, @@ -116,6 +119,8 @@ export interface UploadSourcemapsOptions { resealDirs?: readonly string[]; /** Injectable re-sealer (default {@link resealIntegrity}). */ reseal?: typeof resealIntegrity; + /** Injectable restore of one file from its spilled original, for the re-seal rollback (default: write temp, then rename). */ + restoreFile?: (spill: string, target: string) => Promise; /** Injectable script-digest snapshot taken before the stamp (default {@link snapshotScriptDigests}). */ snapshotDigests?: typeof snapshotScriptDigests; /** @@ -231,6 +236,7 @@ export async function uploadSourcemaps( const onError = options.onError ?? defaultUploadErrorHandler; let original: StampSnapshot | undefined; + let sealOriginal: StampSnapshot | undefined; try { if (options.preStamped === true) { // 0'. Stamped in the build, so this run rewrites nothing and cannot break SRI. What it CAN do is @@ -309,6 +315,19 @@ export async function uploadSourcemaps( ? await (options.snapshotDigests ?? snapshotScriptDigests)([outDir]) : undefined; + // 0a'. Everything the stamp AND the re-seal may write — scripts, maps, pages, server modules — so a re-seal + // that fails can put the build back exactly as the bundler emitted it (the stamp's own snapshot below + // does not cover pages or server modules). + if (digests !== undefined) { + const sealPaths = new Set([ + ...(await listResealFiles(options.resealDirs ?? [outDir])), + ...(files === undefined + ? await (options.listMapFiles ?? listMapFiles)(outDir) + : [...files.scripts, ...files.maps]), + ]); + sealOriginal = await snapshotStampFiles({ files: [...sealPaths] }, options.spillRoot); + } + // 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 = @@ -364,21 +383,43 @@ export async function uploadSourcemaps( // are, then check. After 1b, so the bytes sealed are the bytes that stayed on disk (a restored file // still matches its original hash and is left alone). Not on a dry run: nothing was written. if (digests !== undefined) { - await (options.reseal ?? resealIntegrity)(digests, options.resealDirs ?? [outDir]); - const broken = await (options.verifySri ?? findIntegrityMismatches)(outDir); - if (broken.length > 0) { - const [first] = broken as [SriProtectedScript, ...SriProtectedScript[]]; + let sealFailure: Error | undefined; + try { + await (options.reseal ?? resealIntegrity)(digests, options.resealDirs ?? [outDir]); + const broken = await (options.verifySri ?? findIntegrityMismatches)(outDir); + if (broken.length > 0) { + const [first] = broken as [SriProtectedScript, ...SriProtectedScript[]]; + sealFailure = new Error( + `${first.script} still does not match the integrity hash ${first.html} pins` + + (broken.length > 1 ? ` (and ${broken.length - 1} more)` : '') + + ` after the hashes were re-written, so the browser would refuse to run it. A copy of that hash is held in ` + + `a form this step does not rewrite (one computed at run time, or a file outside the directories it covers), ` + + `which it cannot see. Turn Subresource Integrity off for this build, or do not stamp it.`, + ); + } + } catch (error) { + sealFailure = error instanceof Error ? error : new Error(String(error)); + } + if (sealFailure !== undefined) { + // A page that is blocked, or a build half-sealed, is worse than no source maps. Put every file the stamp + // and the re-seal touched back to what the bundler emitted, and upload nothing: the maps belong to bundles + // that no longer carry the debug-ID they were keyed by. + const { restored, failed } = await restoreChanged( + sealOriginal as StampSnapshot, + options.restoreFile, + ); const failure = new Error( - `${first.script} still does not match the integrity hash ${first.html} pins` + - (broken.length > 1 ? ` (and ${broken.length - 1} more)` : '') + - ` after the hashes were re-written, so the browser will refuse to run it. A copy of that hash is held in ` + - `a form this step does not rewrite (one computed at run time, or a file outside the directories it covers), ` + - `which it cannot see. Turn Subresource Integrity off for this build, or do not stamp it.`, + `${sealFailure.message}. The build was restored to the bundler's original bytes (${restored.length} file(s)) ` + + `and nothing was uploaded` + + (failed.length > 0 + ? `; COULD NOT restore ${failed.map((f) => `${f.path} (${f.error})`).join(', ')}, which are still stamped or half-sealed` + : ''), ); if (options.failOnError === true) { throw failure; } onError(failure); + return { injected: false, uploaded: false, deletedMaps: [], ...vcsEcho }; } } } @@ -518,6 +559,7 @@ export async function uploadSourcemaps( // removing the spill directory can fail (EPERM/EBUSY under antivirus on Windows). Said, not thrown. try { await original?.dispose(); + await sealOriginal?.dispose(); } catch (error) { onError( new Error( @@ -527,3 +569,28 @@ export async function uploadSourcemaps( } } } + +/** Put back, atomically, every snapshotted file whose bytes are not the original's. Never throws: failures are returned. */ +async function restoreChanged( + snapshot: StampSnapshot, + restoreFile: (spill: string, target: string) => Promise = restoreAtomically, +): Promise<{ restored: string[]; failed: { path: string; error: string }[] }> { + const restored: string[] = []; + const failed: { path: string; error: string }[] = []; + for (const [path, entry] of snapshot.entries) { + const now = await readFile(path).then( + (bytes) => createHash('sha1').update(bytes).digest('hex'), + () => undefined, + ); + if (now === entry.hash) { + continue; + } + try { + await restoreFile(entry.spill, path); + restored.push(path); + } catch (error) { + failed.push({ path, error: String(error) }); + } + } + return { restored, failed }; +} diff --git a/packages/bundler-plugin-core/src/sri.test.ts b/packages/bundler-plugin-core/src/sri.test.ts index f98352f11..ed7d50e13 100644 --- a/packages/bundler-plugin-core/src/sri.test.ts +++ b/packages/bundler-plugin-core/src/sri.test.ts @@ -695,6 +695,24 @@ describe('resealIntegrity', () => { expect(files.sort()).toEqual([a, b].sort()); }); + it('rewrites EVERY occurrence of a digest, in a page and in a server module', async () => { + await write(root, 'main.js', 'a();'); + const old = sha('sha384', 'a();'); + // Angular emits the same chunk both as a tag and in the import map; the SSR copy repeats the page. + const page = ``; + const html = await write(root, 'index.html', page); + const mjs = await write(root, 'index.html.mjs', `export default ${JSON.stringify(page)};`); + const before = await snapshotScriptDigests([root]); + await write(root, 'main.js', 'a2();'); + await resealIntegrity(before, [root]); + const fresh = sha('sha384', 'a2();'); + for (const file of [html, mjs]) { + const text = await readFile(file, 'utf8'); + expect(text.split(fresh)).toHaveLength(3); + expect(text).not.toContain(old); + } + }); + it('skips a script that is gone, and a directory that is missing', async () => { await write(root, 'gone.js', 'x'); const before = await snapshotScriptDigests([root]); diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index 1073fb7e3..b62e3f4d5 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -260,6 +260,17 @@ const SCRIPT_FILE = /\.[cm]?js$/i; */ const RESEAL_FILE = /\.(x?html?|[cm]?js)$/i; +/** The files {@link resealIntegrity} may rewrite under `dirs`: pages, server modules, scripts. */ +export async function listResealFiles(dirs: readonly string[]): Promise { + const found = new Set(); + for (const dir of dirs) { + for (const file of await walkFiles(resolve(dir), RESEAL_FILE)) { + found.add(file); + } + } + return [...found]; +} + /** Rounds of re-sealing: a table inside a script changes that script's own hash, which is one more round. */ const MAX_RESEAL_PASSES = 5; From f1a0e0a702a03c6f88d1778a99f82b81d056b739 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 12:36:48 +0500 Subject: [PATCH 17/59] fix(angular): keep an existing ErrorHandler, no-op without a token before locating output, minimal lockfile - ng add no longer appends BugseeErrorHandler after an app's own ErrorHandler provider (last wins); it prints how to report from it. - bugsee-angular-upload checks the token before reading angular.json, so a tokenless build stays a no-op. - upload.ts header corrected (Angular 22 pins lazy chunks in an import map). - schematic devDependencies pinned to 22.0.0, which does not pull oxc-parser into the workspace (22.3 did, and re-resolved nuxt's peers). - README: install weight trade-off. Co-Authored-By: Claude Sonnet 5.5 --- packages/angular/README.md | 2 + packages/angular/package.json | 4 +- .../src/schematics/ng-add/index.test.ts | 61 +++ .../angular/src/schematics/ng-add/index.ts | 19 +- .../angular/src/sourcemaps/upload.test.ts | 32 ++ packages/angular/src/sourcemaps/upload.ts | 29 +- pnpm-lock.yaml | 483 +++++------------- 7 files changed, 266 insertions(+), 364 deletions(-) diff --git a/packages/angular/README.md b/packages/angular/README.md index 6b36ec236..a1175fe02 100644 --- a/packages/angular/README.md +++ b/packages/angular/README.md @@ -55,6 +55,8 @@ It works with the esbuild `application` builder and the webpack `browser` builde - `subresourceIntegrity: true` is supported: after stamping, the integrity hashes in `index.html`, in the import map and in the SSR server modules are re-written to match, so the page keeps loading. - A build with a service worker (`ngsw.json` in the output) is not stamped, since the service worker pins a hash of every file; nothing is uploaded for it. +- Install weight: `@bugsee/angular` depends on `@bugsee/bundler-plugin-core` (and through it `@bugsee/cli`, `acorn`, `magic-string`, `unplugin`), because the `bugsee-angular-upload` bin and `@bugsee/angular/sourcemaps` need them. They are build-time only and never reach a browser bundle, but they are installed with the package. Making them an optional peer that `ng add` installs as a devDependency was considered and not done: `ng add` saves the package itself under `dependencies`, the bin would fail for anyone who skips `ng add`, and the extra install step has to be verified against every package manager. +- If your app already provides its own `ErrorHandler`, `ng add` does not add a second one (the last provider wins and would silence yours); it prints how to report from yours with `reportAngularError(error)`, or to wrap it with `createAngularErrorHandler({ delegate })`. - Only the browser output is uploaded; errors from an SSR server are reported by the Node SDK. Details and the measurements behind them: [source maps](https://github.com/bugsee/bugsee-javascript/blob/main/docs/source-maps-usage.md). diff --git a/packages/angular/package.json b/packages/angular/package.json index b0bbabb90..8818e44ac 100644 --- a/packages/angular/package.json +++ b/packages/angular/package.json @@ -92,8 +92,8 @@ }, "devDependencies": { "@bugsee/core": "workspace:*", - "@angular-devkit/schematics": "22.3.0", - "@schematics/angular": "22.3.0", + "@angular-devkit/schematics": "22.0.0", + "@schematics/angular": "22.0.0", "@types/node": "^22.20.5" }, "schematics": "./dist/schematics/collection.json", diff --git a/packages/angular/src/schematics/ng-add/index.test.ts b/packages/angular/src/schematics/ng-add/index.test.ts index ce9629ece..71f465d72 100644 --- a/packages/angular/src/schematics/ng-add/index.test.ts +++ b/packages/angular/src/schematics/ng-add/index.test.ts @@ -438,6 +438,67 @@ describe('ng add @bugsee/angular — an app already using Bugsee', () => { }); }); +describe('ng add @bugsee/angular — an app that already has its own ErrorHandler', () => { + const MINE = `{ provide: ErrorHandler, useClass: MyHandler }`; + + it('standalone: does not add a second handler (the last one wins and would silence theirs), and says what to do', async () => { + const tree = await workspace(); + const config = tree + .readContent('/src/app/app.config.ts') + .replace('providers: [', `providers: [\n ${MINE},`) + .replace(/^/, `import { ErrorHandler } from '@angular/core';\nclass MyHandler {}\n`); + tree.overwrite('/src/app/app.config.ts', config); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/app/app.config.ts')).toBe(config); + expect(tree.readContent('/src/main.ts')).toContain(`launch('T');`); + expect(logged('warn')).toMatch(/already provides its own ErrorHandler/); + expect(logged('warn')).toMatch(/reportAngularError\(error\)/); + expect(logged('warn')).toMatch(/createAngularErrorHandler\(\{ delegate/); + }); + + it('NgModule: the same', async () => { + const tree = await workspace([{ name: 'demo', standalone: false }]); + const modulePath = tree.files.find((f) => /app[.-]module\.ts$/.test(f)) as string; + const module = tree + .readContent(modulePath) + .replace('providers: [', `providers: [\n ${MINE},`) + .replace(/^/, `import { ErrorHandler } from '@angular/core';\nclass MyHandler {}\n`); + tree.overwrite(modulePath, module); + await run(tree, { appToken: 'T' }); + expect(tree.readContent(modulePath)).toBe(module); + expect(logged('warn')).toMatch(/already provides its own ErrorHandler/); + }); + + it('is idempotent with it', async () => { + const tree = await workspace(); + tree.create( + '/src/app/handler.ts', + `export const p = { provide: ErrorHandler,\n useClass: MyHandler };\n`, + ); + const first = await run(tree, { appToken: 'T' }); + const before = snapshot(first); + const second = await run(first, { appToken: 'T' }); + expect(snapshot(second)).toEqual(before); + }); + + it('does not mistake another token that starts with ErrorHandler for it', async () => { + const tree = await workspace(); + tree.create('/src/app/x.ts', `export const p = { provide: ErrorHandlerLike, useClass: X };\n`); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/app/app.config.ts')).toContain('BugseeErrorHandler'); + }); + + it('ignores a test double in a spec file', async () => { + const tree = await workspace(); + tree.create( + '/src/app/x.spec.ts', + `TestBed.configureTestingModule({ providers: [${MINE}] });\n`, + ); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/app/app.config.ts')).toContain('BugseeErrorHandler'); + }); +}); + describe('ng add @bugsee/angular — the build script', () => { const setScripts = (tree: UnitTestTree, scripts: Record, indent = 2) => { tree.overwrite('/package.json', `${JSON.stringify({ name: 'x', scripts }, null, indent)}\n`); diff --git a/packages/angular/src/schematics/ng-add/index.ts b/packages/angular/src/schematics/ng-add/index.ts index 6c9daf1b0..9c489304a 100644 --- a/packages/angular/src/schematics/ng-add/index.ts +++ b/packages/angular/src/schematics/ng-add/index.ts @@ -168,14 +168,31 @@ function instrument(located: Located, token: string): Rule { ); } let provided = false; + let foreign = false; tree.getDir(located.sourceRoot).visit((path) => { - if (path.endsWith('.ts') && tree.readText(path).includes('BugseeErrorHandler')) { + if (!path.endsWith('.ts')) { + return; + } + const text = tree.readText(path); + if (text.includes('BugseeErrorHandler')) { provided = true; + } else if (!path.endsWith('.spec.ts') && /provide\s*:\s*ErrorHandler\b/.test(text)) { + foreign = true; } }); if (provided) { return; } + if (foreign) { + // Providers are last-wins: adding ours would silently replace theirs. They choose how to combine them. + context.logger.warn( + `Bugsee: your app already provides its own ErrorHandler, so BugseeErrorHandler was not added (it would replace ` + + `yours). Report from inside it instead:\n\n import { reportAngularError } from '@bugsee/angular';\n` + + ` handleError(error: unknown) { reportAngularError(error); /* then your handling */ }\n\n` + + `or wrap yours:\n\n { provide: ErrorHandler, useFactory: () => createAngularErrorHandler({ delegate: new MyHandler() }) }\n`, + ); + return; + } try { await apply( addRootProvider( diff --git a/packages/angular/src/sourcemaps/upload.test.ts b/packages/angular/src/sourcemaps/upload.test.ts index e7cd8c142..e1721bfc5 100644 --- a/packages/angular/src/sourcemaps/upload.test.ts +++ b/packages/angular/src/sourcemaps/upload.test.ts @@ -164,6 +164,38 @@ describe('uploadAngularSourcemaps', () => { expect(notices.join('\n')).toContain('BUGSEE_APP_TOKEN'); }); + it('is a no-op without a token even where the output cannot be located (a contributor build with no secret)', async () => { + const notices: string[] = []; + // No angular.json at all. + const none = await uploadAngularSourcemaps( + { cwd, vcs: false, env: {}, onNotice: (m) => notices.push(m) }, + { runPluginUpload: ran() }, + ); + expect(none.status).toBe('disabled'); + // Several applications and no --project. + await write( + 'angular.json', + JSON.stringify({ + projects: { + one: { projectType: 'application', root: '', architect: { build: {} } }, + two: { projectType: 'application', root: '', architect: { build: {} } }, + }, + }), + ); + const several = await uploadAngularSourcemaps( + { cwd, vcs: false, env: {}, onNotice: (m) => notices.push(m) }, + { runPluginUpload: ran() }, + ); + expect(several.status).toBe('disabled'); + expect(notices.filter((m) => m.includes('BUGSEE_APP_TOKEN'))).toHaveLength(2); + }); + + it('still fails on an unlocatable output when there IS a token', async () => { + await expect( + uploadAngularSourcemaps(base({ cwd }), { runPluginUpload: ran() }), + ).rejects.toThrow(/angular\.json/); + }); + it('is silent when disabled on purpose', async () => { await builtApp(); const notices: string[] = []; diff --git a/packages/angular/src/sourcemaps/upload.ts b/packages/angular/src/sourcemaps/upload.ts index 749b4f6e9..c4134c78c 100644 --- a/packages/angular/src/sourcemaps/upload.ts +++ b/packages/angular/src/sourcemaps/upload.ts @@ -3,11 +3,12 @@ // debug-IDs with `bugsee-cli`, upload the maps, register the build, delete the client maps) and adds only what // is Angular's: where the output is, and Subresource Integrity. // -// SRI. With `subresourceIntegrity: true` Angular writes a hash of every script into `index.html` (and, for SSR, -// into the copy of that page it embeds in the server modules). Stamping the scripts afterwards changes their -// bytes, so the hashes are re-written to match (`resealSri`) — sound here because those pages are the only -// place Angular's esbuild builder keeps them (lazy chunks are loaded by `import()`, with no hash). Measured on -// a real @angular/build 22 build; see docs/design/source-maps.md §7.1. +// SRI. With `subresourceIntegrity: true` Angular writes a hash of every script into `index.html` — as tags, and +// (esbuild builder, Angular 21+) as an import map's `integrity` table that pins every lazy chunk — and, for SSR, +// into the copy of that page it embeds in the server modules; the webpack builder also keeps the lazy chunks' +// hashes in its runtime chunk. Stamping the scripts afterwards changes their bytes, so every digest of a changed +// script is re-written wherever it appears (`resealSri`, bundler-plugin-core), and a build that cannot be re-sealed +// is restored. Measured on real @angular/build 22.3 and build-angular 19.2 builds; see docs/design/source-maps.md §7.1. import { existsSync, readdirSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { @@ -96,6 +97,18 @@ export async function uploadAngularSourcemaps( env, ); + if (!resolved.enabled) { + // Before the output is looked up: a build with no token (a contributor's PR, no secrets) is a no-op, and must + // stay one when angular.json cannot be read or names several applications. + if (!options.disabled) { + say('no app token (BUGSEE_APP_TOKEN): nothing was uploaded.'); + } + return { + status: 'disabled', + outDir: options.dist !== undefined ? resolve(cwd, options.dist) : '', + configuration: options.configuration, + }; + } const located = options.dist !== undefined ? undefined @@ -108,12 +121,6 @@ export async function uploadAngularSourcemaps( options.dist !== undefined ? resolve(cwd, options.dist) : (located?.browserDir as string); const configuration = located?.configuration ?? options.configuration; - if (!resolved.enabled) { - if (!options.disabled) { - say('no app token (BUGSEE_APP_TOKEN): nothing was uploaded.'); - } - return { status: 'disabled', outDir, configuration }; - } if (!existsSync(outDir)) { throw new Error( `the build output ${outDir} does not exist. Run \`ng build\` first (this step uploads what it wrote), or ` + diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6254b9fa2..ac81b7009 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -247,14 +247,14 @@ importers: version: link:../web-adapter devDependencies: '@angular-devkit/schematics': - specifier: 22.3.0 - version: 22.3.0 + specifier: 22.0.0 + version: 22.0.0(chokidar@5.0.0) '@bugsee/core': specifier: workspace:* version: link:../core '@schematics/angular': - specifier: 22.3.0 - version: 22.3.0 + specifier: 22.0.0 + version: 22.0.0(chokidar@5.0.0) '@types/node': specifier: ^22.20.5 version: 22.20.5 @@ -1070,7 +1070,7 @@ importers: devDependencies: nuxt: specifier: ^4.6.2 - version: 4.6.2(@babel/plugin-proposal-decorators@7.29.0(@babel/core@7.29.0))(@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.0))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.0))(@biomejs/biome@2.4.16)(@oxc-project/types@0.158.0)(@rspack/core@2.2.9)(@types/node@22.20.5)(@vue/compiler-sfc@3.5.44)(acorn@8.19.0)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(ioredis@5.11.1)(lightningcss@1.33.0)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(rollup-plugin-visualizer@7.1.1(rolldown@1.2.15)(rollup@4.65.1))(rollup@4.65.1)(terser@5.51.2)(tsx@4.23.15)(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))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32))(yaml@2.9.1) + version: 4.6.2(@babel/plugin-proposal-decorators@7.29.0(@babel/core@7.29.0))(@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.0))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.0))(@biomejs/biome@2.4.16)(@oxc-project/types@0.155.0)(@rspack/core@2.2.9)(@types/node@22.20.5)(@vue/compiler-sfc@3.5.44)(acorn@8.19.0)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(ioredis@5.11.1)(lightningcss@1.33.0)(mlly@1.8.2)(rolldown@1.2.15)(rollup-plugin-visualizer@7.1.1(rolldown@1.2.15)(rollup@4.65.1))(rollup@4.65.1)(terser@5.51.2)(tsx@4.23.15)(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))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32))(yaml@2.9.1) vitest: specifier: ^4.0.0 version: 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)) @@ -1469,17 +1469,17 @@ importers: packages: - '@angular-devkit/core@22.3.0': - resolution: {integrity: sha512-6/qXIYkzxO7KXxSD6FSuD8rfCKsMvXPhB9hpWFTtLvacuFtyWMazqnEqUZuFz2oK1qanvcvNkmbZO+6WVzqLJA==} + '@angular-devkit/core@22.0.0': + resolution: {integrity: sha512-GCEalkF17uygXnjHNyeIWuTzm16TDlhNLHsxbeYeJSJ48anwkZisL/L+oFzEmg8BGqx48nMGj2EVe4J8ADrSng==} engines: {node: ^22.22.3 || ^24.15.0 || >=26.0.0, npm: ^6.11.0 || ^7.5.6 || >=8.0.0, yarn: '>= 1.13.0'} peerDependencies: - chokidar: ^6.0.0 + chokidar: ^5.0.0 peerDependenciesMeta: chokidar: optional: true - '@angular-devkit/schematics@22.3.0': - resolution: {integrity: sha512-+g8v7Kh6GMirUslVz1cumWkVMJ22Zr0Id1SkE6DOK3fsvqi8WeyTXe+Lh/m365lrBsPjBES+FAjjroZFvpmz+A==} + '@angular-devkit/schematics@22.0.0': + resolution: {integrity: sha512-Uefa/kgLD15B0wuxIFJuDvnVf2FuzXdnE/aMTd/fGor3otjrdegaU1tCeK9I0smHaiSWNvtLbhUbkNpuNG1cMw==} engines: {node: ^22.22.3 || ^24.15.0 || >=26.0.0, npm: ^6.11.0 || ^7.5.6 || >=8.0.0, yarn: '>= 1.13.0'} '@angular/common@22.0.2': @@ -3645,84 +3645,42 @@ packages: cpu: [arm] os: [android] - '@oxc-parser/binding-android-arm-eabi@0.158.0': - resolution: {integrity: sha512-eZ4sHtg/u9mzPaRPWXZ7MmJ3tSFYPDCoDrnAJEXBOIQfdAy0TnzlaJx7nq0HZwE8DkYLQg6GqGZlcjaJrnijKg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [android] - '@oxc-parser/binding-android-arm64@0.133.0': resolution: {integrity: sha512-KUHmPMziLBp4u+zbrLdB7iWS7KshuZe+RAp7ELnY9SI9nNXBZ+dp8fiBqWOxhXqn+FQg3a4UcQhwmsJOKV8Jjg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] - '@oxc-parser/binding-android-arm64@0.158.0': - resolution: {integrity: sha512-Jqfn2GRXFkEukYBke/d1Hc9a3gB/qA3YRZ1u0D6HecjoOc3d9QvB7YFWyaLDWc139pfH+fIMIeOQ2SNOe1mnvQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [android] - '@oxc-parser/binding-darwin-arm64@0.133.0': resolution: {integrity: sha512-q8dWmnU/8ea2tga9w2f1PinQ5rcMPDUGkF64T189b65YMjUomET4oy5oRldOr4AwOQkneOG/Zttnz1Dvrc62wg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@oxc-parser/binding-darwin-arm64@0.158.0': - resolution: {integrity: sha512-C3/Sl4HE0DE5r64UWBljMTua5aFh14/Urc6o45gK7J8HWjEttJJP26M0bK2eSWcas2zpJZrJlcvwyIxR7YqSZA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [darwin] - '@oxc-parser/binding-darwin-x64@0.133.0': resolution: {integrity: sha512-cOKeIELIB2bJnCKwqx4Rdj+1Lss/U6uCbLxRySZrhyOOQa1flKhwZFjEHRHxk8fU1NKmhK5OnTdPQ4CpjuFuVw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@oxc-parser/binding-darwin-x64@0.158.0': - resolution: {integrity: sha512-IlU6PMqlk2pbqiidJ1dU5moOeVtzQf4x1n8fXixupLUixA6Sdd3a5WHclvGEZhJom4SjSan0EIpPQkXl9TnjeA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [darwin] - '@oxc-parser/binding-freebsd-x64@0.133.0': resolution: {integrity: sha512-OpaSv4pW3KgFrMYQxTaS0aOE4T1DQF3qZE/4B6uqqv1KgPWWd4UQhJALi8PJPX1RRV5K7ThKXRfF7qGg2+3l1A==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] - '@oxc-parser/binding-freebsd-x64@0.158.0': - resolution: {integrity: sha512-0uQD/66qKMzcz99yudx7yPWdPziXXl4S4bMxyOwXFPQ6F53Vr2DYM8Tfl9gd/32R2FXlAIqK9g8aNfwJEa0/Kg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [freebsd] - '@oxc-parser/binding-linux-arm-gnueabihf@0.133.0': resolution: {integrity: sha512-JGK1wlGrGwxBIlVSF7KWTX1/ru6BEtf28fRROztDRkLfiW+Kxa4onnriezMIiogfn9hVw2KzYcKiLjkLR2ns8A==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@oxc-parser/binding-linux-arm-gnueabihf@0.158.0': - resolution: {integrity: sha512-B5ZAgT/cwKVtGa14Z3PEgim8hBTAK//uX/QpwdO2ZKGMqLFDq8myV3jDU1FAGJ0aPZ24SC8X362kKrpFOYmbHg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [linux] - '@oxc-parser/binding-linux-arm-musleabihf@0.133.0': resolution: {integrity: sha512-yuZO533Ftonxn/iyoqQzURzLQHMspvsIyfiCSNi1t/ER4eIQaR0SsmUOUm5b/lmSig7IWIUa5/BrbEkAPwcilQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@oxc-parser/binding-linux-arm-musleabihf@0.158.0': - resolution: {integrity: sha512-ZLuYVsBUejzfdFmOlY9yW+g/iCInw+pirfTu+eMk27wFcpyCG6yfTmS/qzzvKARI/VmoUdaXmEcDNUm9hdq5Cg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [linux] - '@oxc-parser/binding-linux-arm64-gnu@0.133.0': resolution: {integrity: sha512-hvpbqT5pN2rR+3+xtWeizwfR/aZ0vGceg6TqYMl+ToxMpk9/tmnX7kSvQnfEUkoua8mhogzvIKsAkn0wxgblBA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -3730,13 +3688,6 @@ packages: os: [linux] libc: [glibc] - '@oxc-parser/binding-linux-arm64-gnu@0.158.0': - resolution: {integrity: sha512-QHKIX2SW3pnUFfhAKU8P9t36QlkGGfxgodwoKkp+pQNZmA/PF3DbkA8OgUHoeCIE0aFL1t9Sse+2wr6+zohdRA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [glibc] - '@oxc-parser/binding-linux-arm64-musl@0.133.0': resolution: {integrity: sha512-wJQGamIosQBoJHW9+S5XxrtKRo3eyJxsnS1XCPrqN0LHi8uw1pTqqTfn3t/NVuvbBg7Pumn4ez9Eidgcn0xbEg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -3744,13 +3695,6 @@ packages: os: [linux] libc: [musl] - '@oxc-parser/binding-linux-arm64-musl@0.158.0': - resolution: {integrity: sha512-Z57mkQZMjUHh0KxxjmZLNUpqJUT5lPYYpihAOudh4PnQC79Kq7Ujy8KJsmsbla3rU0xV4aCpUKDCfVx0wnYn+Q==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [musl] - '@oxc-parser/binding-linux-ppc64-gnu@0.133.0': resolution: {integrity: sha512-Koaz32/O5+abIfrNGdyndgRvdOZ9jEf5/z3Ep9h3h2QWpdDiUQpVwgH0OcMXCs+l9aXxPLtkupqyVig9W6FDKw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -3758,13 +3702,6 @@ packages: os: [linux] libc: [glibc] - '@oxc-parser/binding-linux-ppc64-gnu@0.158.0': - resolution: {integrity: sha512-jl6537qMp3Tb2D0J1oYzU/xzvYOM7ZDBf4Dhg8WvgkV+wgept/r2rX30PdWTE5gNo6QdHkOTz7le+9yldU1VwQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [ppc64] - os: [linux] - libc: [glibc] - '@oxc-parser/binding-linux-riscv64-gnu@0.133.0': resolution: {integrity: sha512-R4vOjWzxhnNWHnVLeiB6jNuIifdy9vcMXZGPc7StXcxBovI+U2zg1QhZ9o8OjV80oGivs1lX5NfPLzk4IPqlRA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -3772,13 +3709,6 @@ packages: os: [linux] libc: [glibc] - '@oxc-parser/binding-linux-riscv64-gnu@0.158.0': - resolution: {integrity: sha512-BFwDkCZ2K6VuSfBlKLItXkTYMN/8SAcFpZgBohU6qjlq4HrRKBqOXW/J0ViwZ4BHZuNFxgrhUXcM3hcalZnQaA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [riscv64] - os: [linux] - libc: [glibc] - '@oxc-parser/binding-linux-riscv64-musl@0.133.0': resolution: {integrity: sha512-iwgBNUTHiMdxARLYuM0SBlnYeb19iw1Ea5M+4ERZupCsBMLArti6FyZ6UfFjJxIiTDr2oW2DGQFxlQVQ/dW9rA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -3786,13 +3716,6 @@ packages: os: [linux] libc: [musl] - '@oxc-parser/binding-linux-riscv64-musl@0.158.0': - resolution: {integrity: sha512-3YcZPBhpDhD9BUWQct+70To5wJhY36pvn+gA04ArMCdREd76EIXB14IgYsDsRqIgOXSXT1okMpHA6UEamM/QQg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [riscv64] - os: [linux] - libc: [musl] - '@oxc-parser/binding-linux-s390x-gnu@0.133.0': resolution: {integrity: sha512-ZwZNo8FZmB/gVfboQl+wXilBigGl+6nQQs+nITOeAP/HcAOjiHl6XZJL9F/KXNEspODQcbjAiyjUbeCJd9a0fA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -3800,13 +3723,6 @@ packages: os: [linux] libc: [glibc] - '@oxc-parser/binding-linux-s390x-gnu@0.158.0': - resolution: {integrity: sha512-C+HBtM/aauGsp1sRuKHnB6yqrFCfGzGgS/3b/Alwz+bGIgOCm6DiNnFEnA14MOQ1YA63ikjpmTN7LPb505pkCQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [s390x] - os: [linux] - libc: [glibc] - '@oxc-parser/binding-linux-x64-gnu@0.133.0': resolution: {integrity: sha512-govCvWx1dBlED3uu4qXctxpRcouu9I8Kn+DBktGCl760JtlGJzc9l/OmPJKlYWSbrRqKkMZehNeZ/4Wfma7uSA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -3814,13 +3730,6 @@ packages: os: [linux] libc: [glibc] - '@oxc-parser/binding-linux-x64-gnu@0.158.0': - resolution: {integrity: sha512-COR5cFRE6DqmxZGE9QCJG1X7uUYxNdSYkMR7J9igRLnZqZ8ki6kJIa5S4czYHeIjdNyYn4vo1CsK3rQsK5sjrA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [glibc] - '@oxc-parser/binding-linux-x64-musl@0.133.0': resolution: {integrity: sha512-ssTlpXD5Mq9uCssDJPzlRWqBt4Y7Zzd9i+XZhWmK/9Y6KUIuAxVYTYiI8lxcGWi0+3/Cz4A8q9UrD4NK9Y2j7g==} engines: {node: ^20.19.0 || >=22.12.0} @@ -3828,25 +3737,12 @@ packages: os: [linux] libc: [musl] - '@oxc-parser/binding-linux-x64-musl@0.158.0': - resolution: {integrity: sha512-lF8YZdySxTjYnHfitZpbFWpyyxDchZj+TIyvDnzH3AGZlUvyrsu7BeORPdf05cLFwiyb+RPqAae4EJ7uu5xAhg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [musl] - '@oxc-parser/binding-openharmony-arm64@0.133.0': resolution: {integrity: sha512-51aByfXhPtLEdWG4a2Ihdw6cPWV1ei1AarALpFdDP8MLWDLE2NuUMgbo3DERR2Kt8fT/ok1GUvBiLxVGke9uUQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] - '@oxc-parser/binding-openharmony-arm64@0.158.0': - resolution: {integrity: sha512-m2HMKQgNNatcwOeCDCewrW5gvmHE61WFKl2J4KHiCGNpJb6ZI8n3T/JzwxFkt8kY3E27fJwvHM6t3WIEgtPiAA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [openharmony] - '@oxc-parser/binding-wasm32-wasi@0.133.0': resolution: {integrity: sha512-2e16tkKp+wDO2GTAmXfxbBcCmGEaFPIJEIRBBmVKNVXSc8/fJsSIaBGyFTPHM9ST5GNWgJcYIt94rDTks+PLwA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -3858,45 +3754,24 @@ packages: cpu: [arm64] os: [win32] - '@oxc-parser/binding-win32-arm64-msvc@0.158.0': - resolution: {integrity: sha512-Kksc5jIB7cE9vgoePyIQ8sRkXA4kAfO5oDEI6X+JJMGGTRnvtGafQniLXAHur9XU+5hUgMOGoZcyA8L+JvBu6g==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [win32] - '@oxc-parser/binding-win32-ia32-msvc@0.133.0': resolution: {integrity: sha512-Una1bNYv9zCavQrfnDR9wuZVB3itLjCEH4Oz7i6CwAJN/Xq9b+zbbcxmvdkKvvJt4Ngc/MBmIYlbLo3zS4TQ0A==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ia32] os: [win32] - '@oxc-parser/binding-win32-ia32-msvc@0.158.0': - resolution: {integrity: sha512-HhxU9z7t6gqSh7UslTwD/wha5U2uD44Ss7GKtrBSJfG061iDrJ1Qk63N0Dzh3clax9pjJgYFnMpQRt72Q1bP8w==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [ia32] - os: [win32] - '@oxc-parser/binding-win32-x64-msvc@0.133.0': resolution: {integrity: sha512-kjBhCiOGSYTwDJQuuZa7a94JbP8htWu7J0X1KwH74kV2K5eYf6eyJRYmkpCDvr0XEL8tMxYI4WU1VekblFCLgg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] - '@oxc-parser/binding-win32-x64-msvc@0.158.0': - resolution: {integrity: sha512-/SLN0ot62iL6XhmsWyLdU+37vjVCgDP96sOqeCPIFov63odr4DPv9vgq+lIkZMBMOxpWsSMcwDfpERsRAyCl8A==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [win32] - '@oxc-project/types@0.133.0': resolution: {integrity: sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==} '@oxc-project/types@0.155.0': resolution: {integrity: sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==} - '@oxc-project/types@0.158.0': - resolution: {integrity: sha512-xZ66qA4WmLbTLlxH3mqMd8f9UKbaOzOT0ATwFf4DH/14pMgpUrtqtjyYzOQmgfl2a0iRAAMbQ9G1th/67jRzGw==} - '@oxc-transform/binding-android-arm-eabi@0.133.0': resolution: {integrity: sha512-2A79NBpyBKgHJ0FwgC8D1hzp3x2ujyvqq/kG+M76YyDMMkxLhX6A3vjnAnfEKycOoZxuKhwYu8BF9hKq67ykIA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -4493,8 +4368,8 @@ packages: resolution: {integrity: sha512-pIwhWawZXAT0nTXwvcE/InQ7uaVAgSeIzILMb2mBrI01Hz1yEvxrhV2+DE2Fzux8aZY9OJTdLsI+sk9kZDuAJw==} engines: {node: '>=20.9.0'} - '@schematics/angular@22.3.0': - resolution: {integrity: sha512-SqnAJfBfDHuoUMDrhMIpkIYQiDI8mgJuQC8YcEzynbWG+eIsmuS17CgYKj69J7o/9ndEQU9lIi9nAEOYDlLVKQ==} + '@schematics/angular@22.0.0': + resolution: {integrity: sha512-LqjnpBD0knsZulOCiaBxb9vDUYq6RHyF2VMlQI1gkgJaDAd2YcvK3/H2Xy9tEH1oA1ftbo2p0kpzNtJzSwtBcA==} engines: {node: ^22.22.3 || ^24.15.0 || >=26.0.0, npm: ^6.11.0 || ^7.5.6 || >=8.0.0, yarn: '>= 1.13.0'} '@sec-ant/readable-stream@0.4.1': @@ -5581,10 +5456,6 @@ packages: resolution: {integrity: sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==} engines: {node: ^12.17.0 || ^14.13 || >=16.0.0} - chalk@6.0.1: - resolution: {integrity: sha512-/Ce6KNm3vIbWdMlNna6RVIZ/ICQxnJxCicet5LBKK9ZffBkqzDw0xh9EiKSljdRtiIQ1S1z4YgcscUUGzNCWrA==} - engines: {node: '>=22'} - character-entities-html4@2.1.0: resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==} @@ -7744,14 +7615,14 @@ packages: openapi-types@12.1.3: resolution: {integrity: sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==} - ora@10.0.0: - resolution: {integrity: sha512-jlxvSlLi1aKgPUnRf8NMjwyor1CM4K+faxuycHYTvygjjtkM596tQBXGEp/PQAVqzftrCBMRJlw6+RAJS5nOtQ==} - engines: {node: '>=22'} - ora@5.4.1: resolution: {integrity: sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==} engines: {node: '>=10'} + ora@9.4.0: + resolution: {integrity: sha512-84cglkRILFxdtA8hAvLNdMrtBpPNBTrQ9/ulg0FA7xLMnD6mifv+enAIeRmvtv+WgdCE+LPGOfQmtJRrVaIVhQ==} + engines: {node: '>=20'} + outdent@0.5.0: resolution: {integrity: sha512-/jHxFIzoMXdqPzTaCpFzAAWhpkSjZPF4Vsn6jAfNpmbH/ymsmd7Qc6VE9BGn0L6YMj6uwpQLxCECpus4ukKS9Q==} @@ -7763,10 +7634,6 @@ packages: resolution: {integrity: sha512-661RSx+ZcjBmjBYid+Fpp/2F5EbtildpeoZh5HdgnGs+jZ03nqQEQW8yGkt4BGyOC3OMPDQQRl8M5kqD2/g6jw==} engines: {node: ^20.19.0 || >=22.12.0} - oxc-parser@0.158.0: - resolution: {integrity: sha512-BKmaZZXp667kLC8Od/ivIkbw6yaxTSqw8ViI1Tvl21E6r+6NLdwDmo43LpL2Ebt/PDMu1d4tcdBucMSor+cL1g==} - engines: {node: ^20.19.0 || >=22.12.0} - oxc-transform@0.133.0: resolution: {integrity: sha512-9lt2b+hkG6yqe0fUDMHhMk7rgI9uTjNxU9wauQiYnHzc4kZI8JP/OhBqXTIJQTrqRJ8CkSH3O5AhQ13ke28yNg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -9989,21 +9856,23 @@ packages: snapshots: - '@angular-devkit/core@22.3.0': + '@angular-devkit/core@22.0.0(chokidar@5.0.0)': dependencies: ajv: 8.20.0 ajv-formats: 3.0.1(ajv@8.20.0) jsonc-parser: 3.3.1 - picomatch: 4.0.7 + picomatch: 4.0.4 rxjs: 7.8.2 - source-map: 0.8.0 + source-map: 0.7.6 + optionalDependencies: + chokidar: 5.0.0 - '@angular-devkit/schematics@22.3.0': + '@angular-devkit/schematics@22.0.0(chokidar@5.0.0)': dependencies: - '@angular-devkit/core': 22.3.0 + '@angular-devkit/core': 22.0.0(chokidar@5.0.0) jsonc-parser: 3.3.1 - magic-string: 1.4.5 - ora: 10.0.0 + magic-string: 0.30.21 + ora: 9.4.0 rxjs: 7.8.2 transitivePeerDependencies: - chokidar @@ -10856,14 +10725,14 @@ snapshots: transitivePeerDependencies: - magicast - '@dxup/nuxt@0.5.10(@nuxt/schema@4.6.2)(@rspack/core@2.2.9)(confbox@0.3.1)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(oxc-parser@0.158.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))': + '@dxup/nuxt@0.5.10(@nuxt/schema@4.6.2)(@rspack/core@2.2.9)(confbox@0.3.1)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(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: '@dxup/unimport': 0.1.2 - '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) + '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) '@vue/compiler-dom': 3.5.44 chokidar: 5.0.0 knitwork: 1.3.0 - magic-string: 1.4.4 + magic-string: 1.4.5 pathe: 2.0.3 tinyglobby: 0.2.17 unplugin: 3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)) @@ -11842,7 +11711,7 @@ snapshots: - magicast - supports-color - '@nuxt/cli@4.0.1(@nuxt/schema@4.6.2)(jiti@2.7.0)(oxc-parser@0.158.0)(rolldown@1.2.15)(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))': + '@nuxt/cli@4.0.1(@nuxt/schema@4.6.2)(jiti@2.7.0)(rolldown@1.2.15)(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: '@clack/prompts': 1.8.1 args-tokenizer: 0.3.0 @@ -11870,7 +11739,6 @@ snapshots: optionalDependencies: '@nuxt/schema': 4.6.2 jiti: 2.7.0 - oxc-parser: 0.158.0 rolldown: 1.2.15 transitivePeerDependencies: - vite @@ -11894,9 +11762,9 @@ snapshots: - rolldown - unplugin - '@nuxt/devtools-kit@3.4.4(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))(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))': + '@nuxt/devtools-kit@3.4.4(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))(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: - '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) + '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) execa: 8.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) transitivePeerDependencies: @@ -11984,11 +11852,11 @@ snapshots: - utf-8-validate - vue - '@nuxt/devtools@3.4.4(@nuxt/schema@4.6.2)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))(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))(vue@3.5.44(typescript@6.0.3))': + '@nuxt/devtools@3.4.4(@nuxt/schema@4.6.2)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))(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))(vue@3.5.44(typescript@6.0.3))': dependencies: - '@nuxt/devtools-kit': 3.4.4(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))(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)) + '@nuxt/devtools-kit': 3.4.4(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))(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)) '@nuxt/devtools-wizard': 3.4.4 - '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) + '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) '@vue/devtools-core': 8.2.1(vue@3.5.44(typescript@6.0.3)) '@vue/devtools-kit': 8.2.1 birpc: 4.2.0 @@ -12016,7 +11884,7 @@ snapshots: tinyglobby: 0.2.17 unstorage: 1.17.6(db0@0.3.4)(ioredis@5.11.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) - vite-plugin-inspect: 11.4.1(@nuxt/kit@4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))))(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)) + vite-plugin-inspect: 11.4.1(@nuxt/kit@4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))))(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)) vite-plugin-vue-tracer: 1.6.0(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))(vue@3.5.44(typescript@6.0.3)) which: 6.0.1 ws: 8.22.0 @@ -12138,7 +12006,39 @@ snapshots: - magic-string - unplugin - '@nuxt/kit@4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))': + '@nuxt/kit@4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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: + consola: 3.4.2 + defu: 6.1.7 + destr: 2.0.5 + errx: 0.2.2 + exsolve: 1.1.3 + ignore: 7.0.14 + klona: 2.0.6 + microdiff: 1.6.0 + nostics: 1.3.0 + package-manager-detector: 1.9.0 + pathe: 2.0.3 + rc9: 3.1.0 + scule: 1.3.0 + std-env: 4.3.0 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + unctx: 3.0.1(magic-string@1.4.4)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) + verkit: 0.5.0 + optionalDependencies: + '@nuxt/schema': 4.6.2 + confbox: 0.3.1 + dotenv: 17.4.2 + giget: 3.3.1 + jiti: 2.7.0 + mlly: 1.8.2 + rolldown: 1.2.15 + transitivePeerDependencies: + - magic-string + - unplugin + + '@nuxt/kit@4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.5)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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: consola: 3.4.2 defu: 6.1.7 @@ -12156,7 +12056,7 @@ snapshots: std-env: 4.3.0 tinyexec: 1.3.1 tinyglobby: 0.2.17 - unctx: 3.0.1(magic-string@1.4.4)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) + unctx: 3.0.1(magic-string@1.4.5)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) verkit: 0.5.0 optionalDependencies: '@nuxt/schema': 4.6.2 @@ -12165,7 +12065,6 @@ snapshots: giget: 3.3.1 jiti: 2.7.0 mlly: 1.8.2 - oxc-parser: 0.158.0 rolldown: 1.2.15 transitivePeerDependencies: - magic-string @@ -12252,10 +12151,10 @@ snapshots: - webpack - xml2js - '@nuxt/nitro-server@4.6.2(8840b33fa03bd6663a7d7b8bfeb0d3db)': + '@nuxt/nitro-server@4.6.2(c2ba9efba174cf70a0cc6f1acac00459)': dependencies: - '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) - '@unhead/vue': 3.4.3(@oxc-project/types@0.158.0)(@rspack/core@2.2.9)(esbuild@0.28.2)(lightningcss@1.33.0)(oxc-parser@0.158.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))(vue@3.5.44(typescript@6.0.3))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32)) + '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) + '@unhead/vue': 3.4.3(@oxc-project/types@0.155.0)(@rspack/core@2.2.9)(esbuild@0.28.2)(lightningcss@1.33.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))(vue@3.5.44(typescript@6.0.3))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32)) consola: 3.4.2 defu: 6.1.7 destr: 2.0.5 @@ -12269,16 +12168,16 @@ snapshots: klona: 2.0.6 mocked-exports: 0.1.1 my-bad: 0.2.11(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)) - nitropack: 2.13.5(@rspack/core@2.2.9)(oxc-parser@0.158.0)(rolldown@1.2.15)(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)) + nitropack: 2.13.5(@rspack/core@2.2.9)(rolldown@1.2.15)(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)) nostics: 1.3.0 - nuxt: 4.6.2(@babel/plugin-proposal-decorators@7.29.0(@babel/core@7.29.0))(@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.0))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.0))(@biomejs/biome@2.4.16)(@oxc-project/types@0.158.0)(@rspack/core@2.2.9)(@types/node@22.20.5)(@vue/compiler-sfc@3.5.44)(acorn@8.19.0)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(ioredis@5.11.1)(lightningcss@1.33.0)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(rollup-plugin-visualizer@7.1.1(rolldown@1.2.15)(rollup@4.65.1))(rollup@4.65.1)(terser@5.51.2)(tsx@4.23.15)(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))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32))(yaml@2.9.1) + nuxt: 4.6.2(@babel/plugin-proposal-decorators@7.29.0(@babel/core@7.29.0))(@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.0))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.0))(@biomejs/biome@2.4.16)(@oxc-project/types@0.155.0)(@rspack/core@2.2.9)(@types/node@22.20.5)(@vue/compiler-sfc@3.5.44)(acorn@8.19.0)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(ioredis@5.11.1)(lightningcss@1.33.0)(mlly@1.8.2)(rolldown@1.2.15)(rollup-plugin-visualizer@7.1.1(rolldown@1.2.15)(rollup@4.65.1))(rollup@4.65.1)(terser@5.51.2)(tsx@4.23.15)(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))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32))(yaml@2.9.1) ohash: 2.0.12 pathe: 2.0.3 radix3: 1.1.2 rou3: 0.9.2 std-env: 4.3.0 ufo: 1.6.4 - unctx: 3.0.1(magic-string@1.4.4)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) + unctx: 3.0.1(magic-string@1.4.4)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) unrouting: 0.2.3 unstorage: 1.17.6(db0@0.3.4)(ioredis@5.11.1) vue: 3.5.44(typescript@6.0.3) @@ -12372,9 +12271,9 @@ snapshots: rc9: 3.1.0 std-env: 4.3.0 - '@nuxt/telemetry@2.9.1(@nuxt/kit@4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))))': + '@nuxt/telemetry@2.9.1(@nuxt/kit@4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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: - '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) + '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) citty: 0.2.2 consola: 3.4.2 rc9: 3.1.0 @@ -12440,9 +12339,9 @@ snapshots: - vue-tsc - yaml - '@nuxt/vite-builder@4.6.2(462f28d629d30d3505e2631eba38c9d7)': + '@nuxt/vite-builder@4.6.2(a1e0ccda543b914c18281a779172dd8e)': dependencies: - '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) + '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) '@vitejs/plugin-vue': 6.0.10(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))(vue@3.5.44(typescript@6.0.3)) '@vitejs/plugin-vue-jsx': 5.1.6(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))(vue@3.5.44(typescript@6.0.3)) autoprefixer: 10.6.1(postcss@8.5.32) @@ -12458,7 +12357,7 @@ snapshots: knitwork: 1.3.0 mocked-exports: 0.1.1 my-bad: 0.2.11(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)) - nuxt: 4.6.2(@babel/plugin-proposal-decorators@7.29.0(@babel/core@7.29.0))(@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.0))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.0))(@biomejs/biome@2.4.16)(@oxc-project/types@0.158.0)(@rspack/core@2.2.9)(@types/node@22.20.5)(@vue/compiler-sfc@3.5.44)(acorn@8.19.0)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(ioredis@5.11.1)(lightningcss@1.33.0)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(rollup-plugin-visualizer@7.1.1(rolldown@1.2.15)(rollup@4.65.1))(rollup@4.65.1)(terser@5.51.2)(tsx@4.23.15)(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))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32))(yaml@2.9.1) + nuxt: 4.6.2(@babel/plugin-proposal-decorators@7.29.0(@babel/core@7.29.0))(@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.0))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.0))(@biomejs/biome@2.4.16)(@oxc-project/types@0.155.0)(@rspack/core@2.2.9)(@types/node@22.20.5)(@vue/compiler-sfc@3.5.44)(acorn@8.19.0)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(ioredis@5.11.1)(lightningcss@1.33.0)(mlly@1.8.2)(rolldown@1.2.15)(rollup-plugin-visualizer@7.1.1(rolldown@1.2.15)(rollup@4.65.1))(rollup@4.65.1)(terser@5.51.2)(tsx@4.23.15)(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))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32))(yaml@2.9.1) pathe: 2.0.3 pkg-types: 2.4.0 postcss: 8.5.32 @@ -12508,15 +12407,15 @@ snapshots: - vue-tsc - yaml - '@nuxt/vite-server@4.6.2(fbd6fe56bfb27c9b1321a0ad20284586)': + '@nuxt/vite-server@4.6.2(7bfc5fe44a2391dd76cbb71beeb7f1df)': dependencies: - '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) + '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) clickable-path: 0.1.1 defu: 6.1.7 exsolve: 1.1.3 mocked-exports: 0.1.1 my-bad: 0.2.11(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)) - nuxt: 4.6.2(@babel/plugin-proposal-decorators@7.29.0(@babel/core@7.29.0))(@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.0))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.0))(@biomejs/biome@2.4.16)(@oxc-project/types@0.158.0)(@rspack/core@2.2.9)(@types/node@22.20.5)(@vue/compiler-sfc@3.5.44)(acorn@8.19.0)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(ioredis@5.11.1)(lightningcss@1.33.0)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(rollup-plugin-visualizer@7.1.1(rolldown@1.2.15)(rollup@4.65.1))(rollup@4.65.1)(terser@5.51.2)(tsx@4.23.15)(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))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32))(yaml@2.9.1) + nuxt: 4.6.2(@babel/plugin-proposal-decorators@7.29.0(@babel/core@7.29.0))(@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.0))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.0))(@biomejs/biome@2.4.16)(@oxc-project/types@0.155.0)(@rspack/core@2.2.9)(@types/node@22.20.5)(@vue/compiler-sfc@3.5.44)(acorn@8.19.0)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(ioredis@5.11.1)(lightningcss@1.33.0)(mlly@1.8.2)(rolldown@1.2.15)(rollup-plugin-visualizer@7.1.1(rolldown@1.2.15)(rollup@4.65.1))(rollup@4.65.1)(terser@5.51.2)(tsx@4.23.15)(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))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32))(yaml@2.9.1) pathe: 2.0.3 rou3: 0.9.2 srvx: 1.0.5 @@ -12652,99 +12551,51 @@ snapshots: '@oxc-parser/binding-android-arm-eabi@0.133.0': optional: true - '@oxc-parser/binding-android-arm-eabi@0.158.0': - optional: true - '@oxc-parser/binding-android-arm64@0.133.0': optional: true - '@oxc-parser/binding-android-arm64@0.158.0': - optional: true - '@oxc-parser/binding-darwin-arm64@0.133.0': optional: true - '@oxc-parser/binding-darwin-arm64@0.158.0': - optional: true - '@oxc-parser/binding-darwin-x64@0.133.0': optional: true - '@oxc-parser/binding-darwin-x64@0.158.0': - optional: true - '@oxc-parser/binding-freebsd-x64@0.133.0': optional: true - '@oxc-parser/binding-freebsd-x64@0.158.0': - optional: true - '@oxc-parser/binding-linux-arm-gnueabihf@0.133.0': optional: true - '@oxc-parser/binding-linux-arm-gnueabihf@0.158.0': - optional: true - '@oxc-parser/binding-linux-arm-musleabihf@0.133.0': optional: true - '@oxc-parser/binding-linux-arm-musleabihf@0.158.0': - optional: true - '@oxc-parser/binding-linux-arm64-gnu@0.133.0': optional: true - '@oxc-parser/binding-linux-arm64-gnu@0.158.0': - optional: true - '@oxc-parser/binding-linux-arm64-musl@0.133.0': optional: true - '@oxc-parser/binding-linux-arm64-musl@0.158.0': - optional: true - '@oxc-parser/binding-linux-ppc64-gnu@0.133.0': optional: true - '@oxc-parser/binding-linux-ppc64-gnu@0.158.0': - optional: true - '@oxc-parser/binding-linux-riscv64-gnu@0.133.0': optional: true - '@oxc-parser/binding-linux-riscv64-gnu@0.158.0': - optional: true - '@oxc-parser/binding-linux-riscv64-musl@0.133.0': optional: true - '@oxc-parser/binding-linux-riscv64-musl@0.158.0': - optional: true - '@oxc-parser/binding-linux-s390x-gnu@0.133.0': optional: true - '@oxc-parser/binding-linux-s390x-gnu@0.158.0': - optional: true - '@oxc-parser/binding-linux-x64-gnu@0.133.0': optional: true - '@oxc-parser/binding-linux-x64-gnu@0.158.0': - optional: true - '@oxc-parser/binding-linux-x64-musl@0.133.0': optional: true - '@oxc-parser/binding-linux-x64-musl@0.158.0': - optional: true - '@oxc-parser/binding-openharmony-arm64@0.133.0': optional: true - '@oxc-parser/binding-openharmony-arm64@0.158.0': - optional: true - '@oxc-parser/binding-wasm32-wasi@0.133.0': dependencies: '@emnapi/core': 1.10.0 @@ -12755,27 +12606,16 @@ snapshots: '@oxc-parser/binding-win32-arm64-msvc@0.133.0': optional: true - '@oxc-parser/binding-win32-arm64-msvc@0.158.0': - optional: true - '@oxc-parser/binding-win32-ia32-msvc@0.133.0': optional: true - '@oxc-parser/binding-win32-ia32-msvc@0.158.0': - optional: true - '@oxc-parser/binding-win32-x64-msvc@0.133.0': optional: true - '@oxc-parser/binding-win32-x64-msvc@0.158.0': - optional: true - '@oxc-project/types@0.133.0': {} '@oxc-project/types@0.155.0': {} - '@oxc-project/types@0.158.0': {} - '@oxc-transform/binding-android-arm-eabi@0.133.0': optional: true @@ -13165,12 +13005,11 @@ snapshots: transitivePeerDependencies: - '@types/node' - '@schematics/angular@22.3.0': + '@schematics/angular@22.0.0(chokidar@5.0.0)': dependencies: - '@angular-devkit/core': 22.3.0 - '@angular-devkit/schematics': 22.3.0 + '@angular-devkit/core': 22.0.0(chokidar@5.0.0) + '@angular-devkit/schematics': 22.0.0(chokidar@5.0.0) jsonc-parser: 3.3.1 - oxc-parser: 0.158.0 typescript: 6.0.3 transitivePeerDependencies: - chokidar @@ -13655,16 +13494,15 @@ snapshots: '@ungap/structured-clone@1.3.2': {} - '@unhead/bundler@3.4.3(@oxc-project/types@0.158.0)(@rspack/core@2.2.9)(esbuild@0.28.2)(lightningcss@1.33.0)(oxc-parser@0.158.0)(rolldown@1.2.15)(rollup@4.65.1)(unhead@3.4.3(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))(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))': + '@unhead/bundler@3.4.3(@oxc-project/types@0.155.0)(@rspack/core@2.2.9)(esbuild@0.28.2)(lightningcss@1.33.0)(rolldown@1.2.15)(rollup@4.65.1)(unhead@3.4.3(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))(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: magic-string: 1.4.5 - oxc-walker: 1.1.1(@oxc-project/types@0.158.0)(oxc-parser@0.158.0)(rolldown@1.2.15) + oxc-walker: 1.1.1(@oxc-project/types@0.155.0)(rolldown@1.2.15) unhead: 3.4.3(@rspack/core@2.2.9)(esbuild@0.28.2)(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)) unplugin: 3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)) optionalDependencies: esbuild: 0.28.2 lightningcss: 1.33.0 - oxc-parser: 0.158.0 rolldown: 1.2.15 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) @@ -13683,9 +13521,9 @@ snapshots: unhead: 2.1.15 vue: 3.5.44(typescript@6.0.3) - '@unhead/vue@3.4.3(@oxc-project/types@0.158.0)(@rspack/core@2.2.9)(esbuild@0.28.2)(lightningcss@1.33.0)(oxc-parser@0.158.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))(vue@3.5.44(typescript@6.0.3))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32))': + '@unhead/vue@3.4.3(@oxc-project/types@0.155.0)(@rspack/core@2.2.9)(esbuild@0.28.2)(lightningcss@1.33.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))(vue@3.5.44(typescript@6.0.3))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32))': dependencies: - '@unhead/bundler': 3.4.3(@oxc-project/types@0.158.0)(@rspack/core@2.2.9)(esbuild@0.28.2)(lightningcss@1.33.0)(oxc-parser@0.158.0)(rolldown@1.2.15)(rollup@4.65.1)(unhead@3.4.3(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))(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)) + '@unhead/bundler': 3.4.3(@oxc-project/types@0.155.0)(@rspack/core@2.2.9)(esbuild@0.28.2)(lightningcss@1.33.0)(rolldown@1.2.15)(rollup@4.65.1)(unhead@3.4.3(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))(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)) hookable: 6.1.2 unhead: 3.4.3(@rspack/core@2.2.9)(esbuild@0.28.2)(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)) unplugin: 3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)) @@ -14574,8 +14412,6 @@ snapshots: chalk@5.6.2: {} - chalk@6.0.1: {} - character-entities-html4@2.1.0: {} character-entities-legacy@3.0.0: {} @@ -14741,8 +14577,6 @@ snapshots: dependencies: uncrypto: 0.1.3 - crossws@0.4.16: {} - crossws@0.4.16(srvx@0.11.21): optionalDependencies: srvx: 0.11.21 @@ -16146,7 +15980,7 @@ snapshots: '@parcel/watcher-wasm': 2.6.0 citty: 0.2.2 consola: 3.4.2 - crossws: 0.4.16 + crossws: 0.4.16(srvx@1.0.7) defu: 6.1.7 get-port-please: 3.2.0 h3: 1.15.11 @@ -16687,7 +16521,7 @@ snapshots: - vite - webpack - nitropack@2.13.5(@rspack/core@2.2.9)(oxc-parser@0.158.0)(rolldown@1.2.15)(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)): + nitropack@2.13.5(@rspack/core@2.2.9)(rolldown@1.2.15)(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: '@cloudflare/kv-asset-handler': 0.4.2 '@rollup/plugin-alias': 6.0.1(rollup@4.65.1) @@ -16752,7 +16586,7 @@ snapshots: uncrypto: 0.1.3 unctx: 2.5.0 unenv: 2.0.0-rc.24 - unimport: 6.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(oxc-parser@0.158.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)) + unimport: 6.5.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)) unplugin-utils: 0.3.2 unstorage: 1.17.6(db0@0.3.4)(ioredis@5.11.1) untyped: 2.0.0 @@ -16988,20 +16822,20 @@ snapshots: - xml2js - yaml - nuxt@4.6.2(@babel/plugin-proposal-decorators@7.29.0(@babel/core@7.29.0))(@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.0))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.0))(@biomejs/biome@2.4.16)(@oxc-project/types@0.158.0)(@rspack/core@2.2.9)(@types/node@22.20.5)(@vue/compiler-sfc@3.5.44)(acorn@8.19.0)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(ioredis@5.11.1)(lightningcss@1.33.0)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(rollup-plugin-visualizer@7.1.1(rolldown@1.2.15)(rollup@4.65.1))(rollup@4.65.1)(terser@5.51.2)(tsx@4.23.15)(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))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32))(yaml@2.9.1): + nuxt@4.6.2(@babel/plugin-proposal-decorators@7.29.0(@babel/core@7.29.0))(@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.0))(@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.0))(@biomejs/biome@2.4.16)(@oxc-project/types@0.155.0)(@rspack/core@2.2.9)(@types/node@22.20.5)(@vue/compiler-sfc@3.5.44)(acorn@8.19.0)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(ioredis@5.11.1)(lightningcss@1.33.0)(mlly@1.8.2)(rolldown@1.2.15)(rollup-plugin-visualizer@7.1.1(rolldown@1.2.15)(rollup@4.65.1))(rollup@4.65.1)(terser@5.51.2)(tsx@4.23.15)(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))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32))(yaml@2.9.1): dependencies: - '@dxup/nuxt': 0.5.10(@nuxt/schema@4.6.2)(@rspack/core@2.2.9)(confbox@0.3.1)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(oxc-parser@0.158.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)) + '@dxup/nuxt': 0.5.10(@nuxt/schema@4.6.2)(@rspack/core@2.2.9)(confbox@0.3.1)(dotenv@17.4.2)(esbuild@0.28.2)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(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)) '@jridgewell/trace-mapping': 0.3.31 - '@nuxt/cli': 4.0.1(@nuxt/schema@4.6.2)(jiti@2.7.0)(oxc-parser@0.158.0)(rolldown@1.2.15)(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)) + '@nuxt/cli': 4.0.1(@nuxt/schema@4.6.2)(jiti@2.7.0)(rolldown@1.2.15)(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)) '@nuxt/devalue': 2.0.2 - '@nuxt/devtools': 3.4.4(@nuxt/schema@4.6.2)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))(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))(vue@3.5.44(typescript@6.0.3)) - '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) - '@nuxt/nitro-server': 4.6.2(8840b33fa03bd6663a7d7b8bfeb0d3db) + '@nuxt/devtools': 3.4.4(@nuxt/schema@4.6.2)(confbox@0.3.1)(db0@0.3.4)(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))(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))(vue@3.5.44(typescript@6.0.3)) + '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) + '@nuxt/nitro-server': 4.6.2(c2ba9efba174cf70a0cc6f1acac00459) '@nuxt/schema': 4.6.2 - '@nuxt/telemetry': 2.9.1(@nuxt/kit@4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))) - '@nuxt/vite-builder': 4.6.2(462f28d629d30d3505e2631eba38c9d7) - '@nuxt/vite-server': 4.6.2(fbd6fe56bfb27c9b1321a0ad20284586) - '@unhead/vue': 3.4.3(@oxc-project/types@0.158.0)(@rspack/core@2.2.9)(esbuild@0.28.2)(lightningcss@1.33.0)(oxc-parser@0.158.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))(vue@3.5.44(typescript@6.0.3))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32)) + '@nuxt/telemetry': 2.9.1(@nuxt/kit@4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)))) + '@nuxt/vite-builder': 4.6.2(a1e0ccda543b914c18281a779172dd8e) + '@nuxt/vite-server': 4.6.2(7bfc5fe44a2391dd76cbb71beeb7f1df) + '@unhead/vue': 3.4.3(@oxc-project/types@0.155.0)(@rspack/core@2.2.9)(esbuild@0.28.2)(lightningcss@1.33.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))(vue@3.5.44(typescript@6.0.3))(webpack@5.112.2(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.32)) '@vue/shared': 3.5.44 chokidar: 5.0.0 clickable-path: 0.1.1 @@ -17031,7 +16865,7 @@ snapshots: ofetch: 1.5.1 ohash: 2.0.12 on-change: 6.0.2 - oxc-walker: 1.1.1(@oxc-project/types@0.158.0)(oxc-parser@0.158.0)(rolldown@1.2.15) + oxc-walker: 1.1.1(@oxc-project/types@0.155.0)(rolldown@1.2.15) pathe: 2.0.3 perfect-debounce: 2.1.0 picomatch: 4.0.7 @@ -17045,10 +16879,10 @@ snapshots: ufo: 1.6.4 ultrahtml: 1.7.0 uncrypto: 0.1.3 - unctx: 3.0.1(magic-string@1.4.4)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) + unctx: 3.0.1(magic-string@1.4.4)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) undici: 8.12.3 unhead: 3.4.3(@rspack/core@2.2.9)(esbuild@0.28.2)(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)) - unimport: 7.0.2(@rspack/core@2.2.9)(acorn@8.19.0)(esbuild@0.28.2)(oxc-parser@0.158.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)) + unimport: 7.0.2(@rspack/core@2.2.9)(acorn@8.19.0)(esbuild@0.28.2)(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)) unplugin: 3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)) unrouting: 0.2.3 untyped: 2.0.0 @@ -17216,17 +17050,6 @@ snapshots: openapi-types@12.1.3: {} - ora@10.0.0: - dependencies: - chalk: 6.0.1 - cli-cursor: 5.0.0 - cli-spinners: 3.4.0 - is-interactive: 2.0.0 - is-unicode-supported: 2.1.0 - log-symbols: 7.0.1 - stdin-discarder: 0.3.2 - string-width: 8.3.0 - ora@5.4.1: dependencies: bl: 4.1.0 @@ -17239,6 +17062,17 @@ snapshots: strip-ansi: 6.0.1 wcwidth: 1.0.1 + ora@9.4.0: + dependencies: + chalk: 5.6.2 + cli-cursor: 5.0.0 + cli-spinners: 3.4.0 + is-interactive: 2.0.0 + is-unicode-supported: 2.1.0 + log-symbols: 7.0.1 + stdin-discarder: 0.3.2 + string-width: 8.3.0 + outdent@0.5.0: {} oxc-minify@0.133.0: @@ -17289,30 +17123,6 @@ snapshots: '@oxc-parser/binding-win32-ia32-msvc': 0.133.0 '@oxc-parser/binding-win32-x64-msvc': 0.133.0 - oxc-parser@0.158.0: - dependencies: - '@oxc-project/types': 0.158.0 - optionalDependencies: - '@oxc-parser/binding-android-arm-eabi': 0.158.0 - '@oxc-parser/binding-android-arm64': 0.158.0 - '@oxc-parser/binding-darwin-arm64': 0.158.0 - '@oxc-parser/binding-darwin-x64': 0.158.0 - '@oxc-parser/binding-freebsd-x64': 0.158.0 - '@oxc-parser/binding-linux-arm-gnueabihf': 0.158.0 - '@oxc-parser/binding-linux-arm-musleabihf': 0.158.0 - '@oxc-parser/binding-linux-arm64-gnu': 0.158.0 - '@oxc-parser/binding-linux-arm64-musl': 0.158.0 - '@oxc-parser/binding-linux-ppc64-gnu': 0.158.0 - '@oxc-parser/binding-linux-riscv64-gnu': 0.158.0 - '@oxc-parser/binding-linux-riscv64-musl': 0.158.0 - '@oxc-parser/binding-linux-s390x-gnu': 0.158.0 - '@oxc-parser/binding-linux-x64-gnu': 0.158.0 - '@oxc-parser/binding-linux-x64-musl': 0.158.0 - '@oxc-parser/binding-openharmony-arm64': 0.158.0 - '@oxc-parser/binding-win32-arm64-msvc': 0.158.0 - '@oxc-parser/binding-win32-ia32-msvc': 0.158.0 - '@oxc-parser/binding-win32-x64-msvc': 0.158.0 - oxc-transform@0.133.0: optionalDependencies: '@oxc-transform/binding-android-arm-eabi': 0.133.0 @@ -17353,10 +17163,9 @@ snapshots: - vite - webpack - oxc-walker@1.1.1(@oxc-project/types@0.158.0)(oxc-parser@0.158.0)(rolldown@1.2.15): + oxc-walker@1.1.1(@oxc-project/types@0.155.0)(rolldown@1.2.15): optionalDependencies: - '@oxc-project/types': 0.158.0 - oxc-parser: 0.158.0 + '@oxc-project/types': 0.155.0 rolldown: 1.2.15 p-filter@2.1.0: @@ -17936,7 +17745,7 @@ snapshots: rolldown-string@0.3.1(rolldown@1.2.15): dependencies: - magic-string: 1.4.4 + magic-string: 1.4.5 optionalDependencies: rolldown: 1.2.15 @@ -18847,10 +18656,15 @@ snapshots: rolldown: 1.2.15 unplugin: 3.3.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)) - unctx@3.0.1(magic-string@1.4.4)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))): + unctx@3.0.1(magic-string@1.4.4)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))): optionalDependencies: magic-string: 1.4.4 - oxc-parser: 0.158.0 + rolldown: 1.2.15 + unplugin: 3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)) + + unctx@3.0.1(magic-string@1.4.5)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))): + optionalDependencies: + magic-string: 1.4.5 rolldown: 1.2.15 unplugin: 3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)) @@ -18943,7 +18757,7 @@ snapshots: escape-string-regexp: 5.0.0 estree-walker: 3.0.3 local-pkg: 1.2.1 - magic-string: 1.4.4 + magic-string: 1.4.5 mlly: 1.8.2 pathe: 2.0.3 picomatch: 4.0.7 @@ -18967,42 +18781,12 @@ snapshots: - vite - webpack - unimport@6.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(oxc-parser@0.158.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.19.0 - escape-string-regexp: 5.0.0 - estree-walker: 3.0.3 - local-pkg: 1.2.1 - magic-string: 1.4.4 - mlly: 1.8.2 - pathe: 2.0.3 - picomatch: 4.0.7 - pkg-types: 2.4.0 - scule: 1.3.0 - strip-literal: 4.0.0 - tinyglobby: 0.2.17 - unplugin: 3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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)) - unplugin-utils: 0.3.2 - optionalDependencies: - oxc-parser: 0.158.0 - rolldown: 1.2.15 - transitivePeerDependencies: - - '@farmfe/core' - - '@rsbuild/core' - - '@rspack/core' - - bun-types-no-globals - - esbuild - - rollup - - unloader - - vite - - webpack - - unimport@7.0.2(@rspack/core@2.2.9)(acorn@8.19.0)(esbuild@0.28.2)(oxc-parser@0.158.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)): + unimport@7.0.2(@rspack/core@2.2.9)(acorn@8.19.0)(esbuild@0.28.2)(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: escape-string-regexp: 5.0.0 estree-walker: 3.0.3 local-pkg: 1.2.1 - magic-string: 1.4.4 + magic-string: 1.4.5 mlly: 1.8.2 pathe: 2.0.3 picomatch: 4.0.7 @@ -19014,7 +18798,6 @@ snapshots: unplugin-utils: 0.3.2 optionalDependencies: acorn: 8.19.0 - oxc-parser: 0.158.0 rolldown: 1.2.15 transitivePeerDependencies: - '@farmfe/core' @@ -19263,7 +19046,7 @@ snapshots: optionalDependencies: '@nuxt/kit': 4.4.8(magicast@0.5.5) - vite-plugin-inspect@11.4.1(@nuxt/kit@4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))))(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)): + vite-plugin-inspect@11.4.1(@nuxt/kit@4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))))(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: ansis: 4.3.1 error-stack-parser-es: 1.0.5 @@ -19276,7 +19059,7 @@ snapshots: 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) vite-dev-rpc: 2.0.0(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)) optionalDependencies: - '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(oxc-parser@0.158.0)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) + '@nuxt/kit': 4.6.2(@nuxt/schema@4.6.2)(confbox@0.3.1)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.4.4)(mlly@1.8.2)(rolldown@1.2.15)(unplugin@3.5.0(@rspack/core@2.2.9)(esbuild@0.28.2)(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))) vite-plugin-vue-tracer@1.4.0(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))(vue@3.5.44(typescript@6.0.3)): dependencies: @@ -19419,7 +19202,7 @@ snapshots: chokidar: 5.0.0 confbox: 0.3.1 local-pkg: 1.2.1 - magic-string: 1.4.4 + magic-string: 1.4.5 mlly: 1.8.2 muggle-string: 0.4.1 nostics: 1.3.0 From e7a6f105597e7b97cb62a47fa12da4d5fa005ce3 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 12:38:10 +0500 Subject: [PATCH 18/59] fix(bundler-plugin-core): delete stylesheet/declaration maps on the pre-stamped path; don't drop unreadable maps The pre-stamped explicit path deleted only the uploaded set, so .css.map and .d.ts.map files (never uploaded, but they embed the source) stayed in the output. The deletion set is now the uploaded maps plus the never-uploadable maps of the SAME walk, and only when something was uploaded; an unkeyed or unreadable script map is still never deleted. Real Rspack CSS-map build covers it. partitionByKeyed treated any read failure as 'gone'; only ENOENT is now, other failures are kept and reported. The deletion set derives from the first classification (no second read/parse) and the unreachable unkeyed-failure branch for that path is gone. Co-Authored-By: Claude Sonnet 5.5 --- docs/design/source-maps.md | 11 ++-- .../src/orchestrate.stamp.test.ts | 57 +++++++++++++++++-- .../bundler-plugin-core/src/orchestrate.ts | 39 ++++++++----- .../src/plugin.in-build.real-build.test.ts | 41 +++++++++++++ .../src/stamp-files.test.ts | 31 +++++++--- .../bundler-plugin-core/src/stamp-files.ts | 19 +++++-- 6 files changed, 163 insertions(+), 35 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index a2a963ab6..0368532d0 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -267,10 +267,13 @@ directory for: **every `*.map` except stylesheet and declaration maps** (`.css.m with `[name].map`). The keyed ones are uploaded by path (in batches), the rest are left on disk untouched and reported as a **notice** (`onNotice`), not an error: they were never part of the build, so they do not fail `failOnError`. If nothing is keyed there is no CLI call (a notice; under `failOnError` the "no maps" failure the -strict CLI used to give). The uploaded set is also the **deletion set**: one walker, and a map is deleted only if -it was in the uploaded set after the upload succeeded (a keyed map under `test/` or a dot-directory is uploaded -AND deleted; nothing the walk merely saw is ever deleted). Consequently stylesheet and declaration maps are not -deleted on this path (they were not uploaded). A dry run still passes the directory (nothing was stamped; `--dry-run` only warns). Rspack development +strict CLI used to give). The deletion set comes from the SAME walk: exactly the maps that were uploaded (already classified keyed, so +not re-read), plus the stylesheet and declaration maps of that walk, which are never uploaded but embed the +source and so are deleted with them (as on the post-emit and `files` paths). A script map is deleted only if it +was uploaded and the upload was confirmed: an unkeyed or unreadable one is never deleted, and nothing the walk +merely saw is (a keyed map under `test/` or a dot-directory is uploaded AND deleted). The stylesheet and +declaration maps are deleted only if something was uploaded. A map that cannot be read (anything but ENOENT) is +not "gone": it is neither uploaded nor deleted and is reported with the unkeyed ones. A dry run still passes the directory (nothing was stamped; `--dry-run` only warns). Rspack development builds that are not uploaded (`uploadInDevelopment` unset) are no longer stamped either. Covered by real builds (`plugin.in-build.real-build.test.ts`: Vite 7/8 with a `publicDir` vendor script, Rollup with a stale one, and `[name].map` custom map names on Rollup, Vite 7/8 and Rspack; real CLI, no dry run, `failOnError` on and off). Not run for real: webpack diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index f145a321f..e0cd0b80b 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -597,8 +597,9 @@ describe('a pre-stamped directory upload names its files (never the directory)', expect(upload).not.toContain(dir); expect(upload).not.toContain(join(dir, 'vendor.js.map')); expect(upload).not.toContain(join(dir, 'style.css.map')); - // Only what was uploaded is deleted: the vendor map AND the stylesheet map (never sent) stay. - expect((await readdir(dir)).sort()).toEqual(['style.css.map', 'sub', 'vendor.js.map']); + // The uploaded maps AND the stylesheet map (never sent, embeds the source) are deleted; the unkeyed vendor + // script map is untouched. + expect((await readdir(dir)).sort()).toEqual(['sub', 'vendor.js.map']); expect(result.uploaded).toBe(true); expect(onError).not.toHaveBeenCalled(); expect(notices).toHaveLength(1); @@ -637,9 +638,11 @@ describe('a pre-stamped directory upload names its files (never the directory)', expect(upload).toContain(map); } expect(upload).not.toContain(join(dir, 'unkeyed.map')); - // ONE set: what was uploaded is exactly what is deleted (test/ and dot-directories included). - expect(deleted).toEqual([uploaded]); - expect(result.deletedMaps).toEqual(uploaded); + // What was uploaded is deleted (test/ and dot-directories included), plus the declaration map that + // was never uploadable; the UNKEYED script map is in neither. + expect(deleted).toEqual([[...uploaded, join(dir, 'a.d.ts.map')]]); + expect(result.deletedMaps).toEqual([...uploaded, join(dir, 'a.d.ts.map')]); + expect(await readdir(dir)).toContain('unkeyed.map'); }); it('never deletes a map that was not in the uploaded set, whatever the directory walk saw', async () => { @@ -662,6 +665,50 @@ describe('a pre-stamped directory upload names its files (never the directory)', expect(walk).not.toHaveBeenCalled(); }); + it('deletes stylesheet and declaration maps only when an upload happened, and never an unkeyed script map', async () => { + for (const name of ['a.css.map', 'a.d.ts.map', 'a.d.mts.map', 'a.d.cts.map', 'x.js.map']) { + await writeFile(join(dir, name), name === 'x.js.map' ? '{"version":3}' : '{}'); + } + const { run, calls } = record(); + await uploadSourcemaps(opts({ run, onNotice: () => undefined })); + // Nothing keyed -> no upload -> nothing confirmed -> nothing deleted. + expect(calls).toEqual([]); + expect((await readdir(dir)).sort()).toHaveLength(5); + + await writeFile(join(dir, 'k.js.map'), keyed); + await uploadSourcemaps(opts({ run, onNotice: () => undefined })); + expect((await readdir(dir)).sort()).toEqual(['x.js.map']); + }); + + it('a map it cannot read is reported as not uploaded and left alone (never silently skipped)', async () => { + await writeFile(join(dir, 'k.js.map'), keyed); + await writeFile(join(dir, 'locked.js.map'), keyed); + await chmod(join(dir, 'locked.js.map'), 0o000); + const notices: string[] = []; + try { + const { run, calls } = record(); + await uploadSourcemaps( + opts({ run, failOnError: true, onNotice: (m: string) => notices.push(m) }), + ); + const upload = calls.find((c) => c[0] === 'debug-files') as string[]; + expect(upload).toContain(join(dir, 'k.js.map')); + expect(upload).not.toContain(join(dir, 'locked.js.map')); + expect(notices.join('\n')).toContain('locked.js.map'); + } finally { + await chmod(join(dir, 'locked.js.map'), 0o644); + } + }); + + it('does not re-read the maps it already classified when it decides what to delete', async () => { + await writeFile(join(dir, 'k.js.map'), keyed); + const partition = vi.fn(async (maps: readonly string[]) => ({ + deletable: [...maps], + kept: [] as string[], + })); + await uploadSourcemaps(opts({ run: record().run, partitionMaps: partition })); + expect(partition).toHaveBeenCalledOnce(); + }); + it('with nothing keyed there is nothing to upload: no CLI call, a notice, and a failure only under failOnError', async () => { await writeFile(join(dir, 'vendor.js.map'), '{"version":3}'); const { run, calls } = record(); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 768378cb0..d7ed33965 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -7,7 +7,8 @@ import { type RunBugseeCliOptions, runBugseeCli, type SpawnResult } from './run- import { findIntegrityMismatches, findSriProtectedScripts, type SriProtectedScript } from './sri'; import { isProjectRootOrAbove, - listUploadableMaps, + isUploadableMap, + listOutputMaps, MAX_WALK_DEPTH, NEVER_WALK, partitionByKeyed, @@ -90,7 +91,7 @@ export interface UploadSourcemapsOptions { stampedBundles?: readonly string[]; /** Where a non-failing observation goes (default: nowhere — callers that want it pass the notice sink). */ onNotice?: (message: string) => void; - /** Injectable lister of the script maps to consider for a pre-stamped directory upload (default {@link listUploadableMaps}). */ + /** Injectable lister of the script maps to consider for a pre-stamped directory upload (default {@link listOutputMaps}). */ listUploadMaps?: (dir: string) => Promise; /** Where the pre-inject originals are spilled (default: the OS temp directory). A test seam. */ spillRoot?: string; @@ -350,6 +351,7 @@ export async function uploadSourcemaps( // that set: no second walk to disagree with the first about which maps exist. const explicitUpload = files === undefined && options.preStamped === true && !dryRun; let uploadedMaps: string[] = []; + let unuploadableMaps: string[] = []; let snapshot: string[] | undefined; let snapshotError: unknown; if (files === undefined && deleteMaps && !dryRun && !explicitUpload) { @@ -380,11 +382,16 @@ export async function uploadSourcemaps( // holding such a map ("nothing was uploaded"), which would lose EVERY map of the build. Unkeyed maps // are left alone and said, not failed. if (explicitUpload) { - const candidates = await (options.listUploadMaps ?? listUploadableMaps)(outDir); - const { deletable, kept } = await (options.partitionMaps ?? partitionByKeyed)(candidates); + // 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. + const everything = await (options.listUploadMaps ?? listOutputMaps)(outDir); + const { deletable, kept } = await (options.partitionMaps ?? partitionByKeyed)( + everything.filter(isUploadableMap), + ); + unuploadableMaps = everything.filter((map) => !isUploadableMap(map)); if (kept.length > 0) { (options.onNotice ?? ((m: string) => console.warn(`[bugsee] ${m}`)))( - `${kept.length} source map(s) in ${outDir} carry no debug-ID, so they are not part of this build's stamp and were not uploaded (left on disk untouched): ${kept.join(', ')}`, + `${kept.length} source map(s) in ${outDir} have no readable debug-ID, so they are not part of this build's stamp and were not uploaded (left on disk untouched): ${kept.join(', ')}`, ); } if (deletable.length === 0) { @@ -430,18 +437,24 @@ export async function uploadSourcemaps( // 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)( - explicitUpload - ? uploadedMaps - : files === undefined + // A pre-stamped build deletes exactly what it uploaded (already classified keyed, so not re-read) plus + // the maps that were never uploadable, and only if something was uploaded. Any other path classifies + // its candidates here. + let deletable: string[]; + let kept: string[] = []; + if (explicitUpload) { + deletable = uploadedMaps.length > 0 ? [...uploadedMaps, ...unuploadableMaps] : []; + } else { + ({ deletable, kept } = await (options.partitionMaps ?? partitionByKeyed)( + files === undefined ? (snapshot as string[]) : [...files.maps, ...(files.stylesheetMaps ?? [])], - ); + )); + } deletedMaps = await (options.deleteMapFiles ?? defaultDeleteMapFiles)(outDir, deletable); - // Unkeyed maps of a pre-stamped build were already said (a notice, above): they were never part of it. - if (kept.length > 0 && !explicitUpload) { + 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(', ')}`, + `${kept.length} source map(s) have no readable debug-ID, so they were not uploaded and were left on disk: ${kept.join(', ')}`, ); 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 7b83f1d60..76d334560 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 @@ -562,3 +562,44 @@ describeReal('maps with custom names (sourcemapFileNames: "[name].map")', () => }); } }); + +// A stylesheet map is never uploaded, but it embeds the source: it is still deleted with the rest. +describeReal('a stylesheet map beside the stamped maps (Rspack, [file].map)', () => { + it('uploads the keyed js map and deletes the css map too (real CLI, failOnError on)', async () => { + const app = makeApp('rspack-css', { lazy: false }); + writeFileSync(join(app.dir, 'style.css'), 'body { color: red; }\n'); + writeFileSync(join(app.dir, 'index.js'), "import './style.css';\nconsole.log('css');\n"); + const before = requests.length; + const errors: unknown[] = []; + const out = await new Promise<{ errors: unknown[]; files: string[] }>((resolve, reject) => { + const compiler = rspack({ + context: app.dir, + mode: 'production', + entry: join(app.dir, 'index.js'), + devtool: false, + output: { path: app.out }, + module: { rules: [{ test: /\.css$/, type: 'css' }] }, + experiments: { css: true }, + plugins: [ + new rspack.SourceMapDevToolPlugin({ filename: '[file].map' }), + bugseeRspackPlugin({ ...pluginOptions(), onError: (e: unknown) => errors.push(e) }), + ], + }); + compiler.run((err, stats) => { + compiler.close(() => + err + ? reject(err) + : resolve({ + errors: [...(stats as { compilation: { errors: unknown[] } }).compilation.errors], + files: readdirSync(app.out), + }), + ); + }); + }); + expect(out.errors.map(String)).toEqual([]); + expect(errors.map(String)).toEqual([]); + expect(requests.length, 'the keyed js map was uploaded').toBeGreaterThan(before); + expect(out.files.some((f) => f.endsWith('.css'))).toBe(true); + expect(out.files.filter((f) => f.endsWith('.map'))).toEqual([]); + }); +}); diff --git a/packages/bundler-plugin-core/src/stamp-files.test.ts b/packages/bundler-plugin-core/src/stamp-files.test.ts index aa136f1ba..28e6f0c7c 100644 --- a/packages/bundler-plugin-core/src/stamp-files.test.ts +++ b/packages/bundler-plugin-core/src/stamp-files.test.ts @@ -16,7 +16,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { isProjectRootOrAbove, isUploadableMap, - listUploadableMaps, + listOutputMaps, partitionByKeyed, restoreAtomically, snapshotStampFiles, @@ -403,8 +403,25 @@ describe('partitionByKeyed — any uploadable map needs a key, whatever it is ca }); }); -describe('listUploadableMaps', () => { - it('lists every uploadable map of the whole output directory (any name, src/ and dot-dirs included), sorted', async () => { +describe('partitionByKeyed — a map that cannot be read is not "gone"', () => { + it('keeps (never silently drops) a map that fails to read with anything but ENOENT', async () => { + await writeFile(join(dir, 'locked.js.map'), stampedMap); + await chmod(join(dir, 'locked.js.map'), 0o000); + try { + const { deletable, kept } = await partitionByKeyed([ + join(dir, 'locked.js.map'), + join(dir, 'vanished.js.map'), + ]); + expect(kept).toEqual([join(dir, 'locked.js.map')]); + expect(deletable).toEqual([]); // the vanished one is neither kept nor deleted + } finally { + await chmod(join(dir, 'locked.js.map'), 0o644); + } + }); +}); + +describe('listOutputMaps', () => { + it('lists EVERY map of the whole output directory (any name, src/ and dot-dirs included), sorted, stylesheet and declaration maps too', async () => { await mkdir(join(dir, 'src')); await mkdir(join(dir, '.hidden')); await mkdir(join(dir, 'test')); @@ -415,8 +432,10 @@ describe('listUploadableMaps', () => { await writeFile(join(dir, 'c.css.map'), '{}'); await writeFile(join(dir, 'd.d.ts.map'), '{}'); await writeFile(join(dir, 'e.js'), 'x'); - expect((await listUploadableMaps(dir)).map((f) => f.slice(dir.length + 1))).toEqual([ + expect((await listOutputMaps(dir)).map((f) => f.slice(dir.length + 1))).toEqual([ '.hidden/b.mjs.map', + 'c.css.map', + 'd.d.ts.map', 'index.map', 'src/a.js.map', 'test/t.map', @@ -429,9 +448,7 @@ describe('listUploadableMaps', () => { await writeFile(join(dir, 'ok.map'), '{}'); process.chdir(dir); try { - expect((await listUploadableMaps(dir)).map((f) => f.slice(dir.length + 1))).toEqual([ - 'ok.map', - ]); + expect((await listOutputMaps(dir)).map((f) => f.slice(dir.length + 1))).toEqual(['ok.map']); } finally { process.chdir(start); } diff --git a/packages/bundler-plugin-core/src/stamp-files.ts b/packages/bundler-plugin-core/src/stamp-files.ts index c61e01f43..fd7ae1a68 100644 --- a/packages/bundler-plugin-core/src/stamp-files.ts +++ b/packages/bundler-plugin-core/src/stamp-files.ts @@ -344,12 +344,13 @@ export function isUploadableMap(path: string): boolean { } /** - * Every uploadable map under `dir`, walked like the snapshot: the whole output directory, fenced only at a - * project root. The SINGLE source of both what a pre-stamped build uploads and what it deletes afterwards. + * Every map under `dir` (`*.map`, whatever its name), walked like the snapshot: the whole output directory, + * fenced only at a project root. The SINGLE walk behind what a pre-stamped build uploads and deletes; the + * caller splits it with {@link isUploadableMap}. */ -export async function listUploadableMaps(dir: string): Promise { +export async function listOutputMaps(dir: string): Promise { const all = await walkStampable(dir, await isProjectRootOrAbove(dir)); - return all.filter(isUploadableMap).sort(); + return all.filter((file) => file.endsWith('.map')).sort(); } /** @@ -375,8 +376,14 @@ export async function partitionByKeyed( let text: string; try { text = await readFile(path, 'utf8'); - } catch { - // Already gone: nothing to delete and nothing to keep. + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + // Already gone: nothing to delete and nothing to keep. + continue; + } + // Anything else (EACCES, a map too large to read as a string) is NOT "gone": it cannot be confirmed + // keyed, so it is neither uploaded nor deleted, and the caller says so. + kept.push(path); continue; } let keyed = false; From 6d06b4395ece7ce881b53a37793000b7830525fd Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 12:48:09 +0500 Subject: [PATCH 19/59] fix(bundler-plugin-core): stamp moved maps, walk any depth, deterministic and truthful upload - sourcemapFileNames that MOVE a map (maps/[name].js.map, bundles in js/) left the bundle stamped with an id never put in the map, nothing uploaded and the map left in the output. The asset store now says which asset is a bundle's map (mapOf) and stampAssets stages it as the .map sibling (how inject pairs them), writing it back at its real name; a map that cannot be staged, or a sibling name already taken, refuses the in-build stamp so it falls back to post-emit. Real Rollup/Vite 7/Vite 8 builds cover it. - the walk depth cap now bounds only a walk from a project root; an ordinary output directory is walked to any depth, like the CLI scan and inject - the explicit upload sorts its candidates (stable batches and notice order) - uploaded is false when a pre-stamped build had no keyed map to upload - the notice no longer claims unkeyed maps are 'not part of this build' Co-Authored-By: Claude Sonnet 5.5 --- docs/design/source-maps.md | 27 +++- .../src/orchestrate.stamp.test.ts | 77 +++++++++-- .../bundler-plugin-core/src/orchestrate.ts | 13 +- .../src/plugin.in-build.real-build.test.ts | 123 ++++++++++++++++++ .../src/stamp-assets.test.ts | 103 +++++++++++++++ .../bundler-plugin-core/src/stamp-assets.ts | 54 +++++++- .../src/stamp-files.test.ts | 36 +++++ .../bundler-plugin-core/src/stamp-files.ts | 6 +- 8 files changed, 413 insertions(+), 26 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 0368532d0..382e467d5 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -245,13 +245,26 @@ beside them is not mistaken for a miss. A stamped build is also re-checked again its HTML (`findIntegrityMismatches`, `sri.ts`): any ``, + ); + const html0 = await readFile(join(root, 'index.html'), 'utf8'); + await write('favicon.ico', 'ico'); + const ngsw = await write( + 'ngsw.json', + manifest({ + '/main.js': sha1('a();'), + '/index.html': sha1(html0), + '/favicon.ico': sha1('ico'), + }), + ); + const before = await snapshotScriptDigests([root]); + await write('main.js', 'a();\n//# debugId=x'); + const { files } = await resealIntegrity(before, [root]); + expect(files).toContain(ngsw); + const html1 = await readFile(join(root, 'index.html'), 'utf8'); + expect(await readFile(ngsw, 'utf8')).toBe( + manifest({ + '/main.js': sha1('a();\n//# debugId=x'), + '/index.html': sha1(html1), + '/favicon.ico': sha1('ico'), + }), + ); + expect(await findStaleServiceWorkerEntries([root])).toEqual([]); + }); + + it('does it for the manifest of every locale', async () => { + for (const locale of ['en-US', 'fr']) { + await write(`${locale}/main.js`, `${locale}();`); + await write(`${locale}/ngsw.json`, manifest({ '/main.js': sha1(`${locale}();`) })); + } + const before = await snapshotScriptDigests([root]); + await write('fr/main.js', 'fr();\n//# debugId=y'); + await resealIntegrity(before, [root]); + expect(await findStaleServiceWorkerEntries([root])).toEqual([]); + expect(await readFile(join(root, 'en-US/ngsw.json'), 'utf8')).toContain(sha1('en-US();')); + expect(await readFile(join(root, 'fr/ngsw.json'), 'utf8')).toContain( + sha1('fr();\n//# debugId=y'), + ); + }); + + it('finds the file under a base href, by dropping leading path segments', async () => { + await write('main.js', 'a();'); + await write('ngsw.json', manifest({ '/app/v2/main.js': sha1('a();') })); + await write('main.js', 'changed'); + expect(await findStaleServiceWorkerEntries([root])).toEqual([ + { manifest: join(root, 'ngsw.json'), url: '/app/v2/main.js' }, + ]); + await resealIntegrity(new Map(), [root]); + expect(await findStaleServiceWorkerEntries([root])).toEqual([]); + }); + + it('leaves an entry whose file is not there, and a manifest that is not JSON or has no table', async () => { + await write('d/a.js', 'a'); + const files = [ + await write('a/ngsw.json', manifest({ '/gone.js': sha1('x') })), + await write('b/ngsw.json', '{ nope'), + await write('c/ngsw.json', '{"index":"/"}'), + await write('d/ngsw.json', '{"hashTable":{"/a.js":5}}'), + ]; + const texts = await Promise.all(files.map((f) => readFile(f, 'utf8'))); + await resealIntegrity(new Map(), [root]); + expect(await Promise.all(files.map((f) => readFile(f, 'utf8')))).toEqual(texts); + expect(await findStaleServiceWorkerEntries([root])).toEqual([]); + }); + + it('does not look in node_modules, and does not follow a key out of the manifest directory', async () => { + await write('node_modules/p/ngsw.json', manifest({ '/m.js': 'x' })); + await write('outside.js', 'o'); + await write('sub/ngsw.json', manifest({ '/../outside.js': 'stale' })); + expect(await findStaleServiceWorkerEntries([root])).toEqual([]); + }); + + it('lists the manifests among the files a re-seal may rewrite', async () => { + const ngsw = await write('x/ngsw.json', '{}'); + expect(await listResealFiles([root])).toContain(ngsw); + }); +}); diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index b62e3f4d5..9ec1ab87c 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -17,7 +17,7 @@ import { createHash } from 'node:crypto'; import type { Dirent } from 'node:fs'; import { readdir, readFile, writeFile } from 'node:fs/promises'; -import { isAbsolute, join, normalize, resolve, sep } from 'node:path'; +import { dirname, isAbsolute, join, normalize, resolve, sep } from 'node:path'; /** One ``); + this.emitFile({ + type: 'asset', + fileName: 'index.html', + source: `${tags.join('')}`, + }); + }, + }; + const bundle = await rollup({ + input: join(root, 'src', 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions()), html], + }); + await bundle.write({ + dir: out, + sourcemap: true, + entryFileNames: '[name]-[hash].js', + chunkFileNames: '[name]-[hash].js', + }); + await bundle.close(); + await expectHealthy(out, before); + }, 120_000); + + it('Vite: hashed chunk file names, the lazy chunk executes and pointers are consistent', async () => { + const out = join(root, 'dist-vite'); + const before = requests.length; + writeFileSync( + join(root, 'index.html'), + '\n', + ); + await viteBuild({ + root, + configFile: false, + logLevel: 'silent', + plugins: [bugseeVitePlugin(pluginOptions()) as never], + build: { outDir: out, emptyOutDir: true, minify: false, sourcemap: true }, + } as never); + await expectHealthy(out, before); + }, 120_000); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8f9fe40e1..20ed5810f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -758,6 +758,9 @@ importers: '@opentelemetry/sdk-trace-base': specifier: ^2.12.0 version: 2.12.0(@opentelemetry/api@1.10.0) + '@rspack/core': + specifier: 2.2.9 + version: 2.2.9 '@types/jsdom': specifier: ^21.1.7 version: 21.1.7 From 3782b60706d1297a872b5f3781a1c0c644edb2fa Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 14:19:54 +0500 Subject: [PATCH 29/59] 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 30/59] 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 31/59] 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 32/59] 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 540e304d364883ba0a9ad31801a8d33e5d9ff6ba Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 16:06:29 +0500 Subject: [PATCH 33/59] fix(angular): --dist on an SSR build re-seals the server modules; reject a line break in the ng-add token With --dist the output root was unknown, so only browser/ was re-sealed and the server's copy of the page kept stale integrity hashes (every script blocked by the real server). When a sibling server/ exists inside the project, its parent is the re-seal scope. ng add refuses a token containing a line break (env file injection). Co-Authored-By: Claude Sonnet 5.5 --- docs/source-maps-usage.md | 2 +- packages/angular/README.md | 2 +- .../src/schematics/ng-add/index.test.ts | 9 ++++ .../angular/src/schematics/ng-add/index.ts | 3 ++ .../src/sourcemaps/upload.real-build.test.ts | 19 +++++++ .../angular/src/sourcemaps/upload.test.ts | 49 +++++++++++++++++++ packages/angular/src/sourcemaps/upload.ts | 22 ++++++++- 7 files changed, 103 insertions(+), 3 deletions(-) diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 53600a11d..ecdc7e64c 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -213,7 +213,7 @@ esbuild `application` builder (the default since 17, output in `dist//b - **A build with a service worker works.** `ngsw.json` (one per locale for a localized build) lists the SHA-1 of every file it caches and the service worker rejects a changed one, so after stamping the step re-computes those entries and checks them; if one cannot be reconciled it restores the build and uploads nothing. -- **If the output moved** (`ng build --output-path other`), pass `--output-path other` (or `--dist `). A +- **If the output moved** (`ng build --output-path other`), pass `--output-path other` (or `--dist `; on an SSR build `--dist` also re-seals the sibling `server/` directory when it sits inside the project). A problem locating the output is printed and the command exits 0, so it cannot fail a pipeline whose build succeeded; `--fail-on-error` makes it exit non-zero. - **Only `browser/` is uploaded.** An SSR server bundle's errors are reported by the Node SDK. diff --git a/packages/angular/README.md b/packages/angular/README.md index dc1144f93..9e76abe7b 100644 --- a/packages/angular/README.md +++ b/packages/angular/README.md @@ -55,7 +55,7 @@ It works with the esbuild `application` builder and the webpack `browser` builde - `subresourceIntegrity: true` is supported: after stamping, the integrity hashes in `index.html`, in the import map and in the SSR server modules are re-written to match, so the page keeps loading. - A build with a service worker works: `ngsw.json` (one per locale for a localized build) lists the SHA-1 of every file it caches, so after stamping those entries are re-computed and checked; if one cannot be reconciled the build is restored and nothing is uploaded. -- If the output is not where `angular.json` says (`ng build --output-path other`), pass `--output-path other` (or `--dist `). A problem locating the output (no `angular.json`, several applications without `--project`, no build output yet) is printed and the command still exits 0, so it cannot fail a pipeline whose build succeeded; add `--fail-on-error` to make it exit non-zero. +- If the output is not where `angular.json` says (`ng build --output-path other`), pass `--output-path other` (or `--dist `; on an SSR build `--dist` also re-seals the sibling `server/` directory when it sits inside the project). A problem locating the output (no `angular.json`, several applications without `--project`, no build output yet) is printed and the command still exits 0, so it cannot fail a pipeline whose build succeeded; add `--fail-on-error` to make it exit non-zero. - Install weight: `@bugsee/angular` depends on `@bugsee/bundler-plugin-core` (and through it `@bugsee/cli`, `acorn`, `magic-string`, `unplugin`), because the `bugsee-angular-upload` bin and `@bugsee/angular/sourcemaps` need them. They are build-time only and never reach a browser bundle, but they are installed with the package. Making them an optional peer that `ng add` installs as a devDependency was considered and not done: `ng add` saves the package itself under `dependencies`, the bin would fail for anyone who skips `ng add`, and the extra install step has to be verified against every package manager. - If your app already provides its own `ErrorHandler`, `ng add` does not add a second one (the last provider wins and would silence yours); it prints how to report from yours with `reportAngularError(error)`, or to wrap it with `createAngularErrorHandler({ delegate })`. - Known limits: the `ErrorHandler` check scans only the project's `sourceRoot`, so a handler provided from a shared (Nx) library is not seen; the deletion rule assumes Angular cleans its output directory (`deleteOutputPath`, default true), so with `deleteOutputPath: false` or a wider `--dist`, a stale foreign map that carries a debug-ID could be deleted; the integrity check does not follow `` for nested prerendered pages (the digest swap still fixes them). diff --git a/packages/angular/src/schematics/ng-add/index.test.ts b/packages/angular/src/schematics/ng-add/index.test.ts index f3c57e8bc..b1e47a1b6 100644 --- a/packages/angular/src/schematics/ng-add/index.test.ts +++ b/packages/angular/src/schematics/ng-add/index.test.ts @@ -196,6 +196,15 @@ describe('ng add @bugsee/angular — without a token', () => { expect(tree.readContent('/src/main.ts')).toContain(`launch('YOUR_APP_TOKEN');`); }); + it('rejects a token with a line break, which would inject a line into the env file', async () => { + const tree = await workspace(); + await expect(run(tree, { appToken: 'abc\nBUGSEE_ENDPOINT=https://evil' })).rejects.toThrow( + /line break/, + ); + await expect(run(tree, { appToken: 'abc\rdef' })).rejects.toThrow(/line break/); + expect(tree.exists('/.env.bugsee-build-plugin')).toBe(false); + }); + it('escapes a quote in the token so the launch call stays valid', async () => { const tree = await run(await workspace(), { appToken: `a'b\\c` }); expect(tree.readContent('/src/main.ts')).toContain(`launch('a\\'b\\\\c');`); diff --git a/packages/angular/src/schematics/ng-add/index.ts b/packages/angular/src/schematics/ng-add/index.ts index b3689ada4..07cb22298 100644 --- a/packages/angular/src/schematics/ng-add/index.ts +++ b/packages/angular/src/schematics/ng-add/index.ts @@ -307,6 +307,9 @@ export function ngAdd(options: Schema = {}): Rule { const located = await locate(tree, options.project); const trimmed = options.appToken?.trim(); const token = trimmed === undefined || trimmed === '' ? undefined : trimmed; + if (token !== undefined && /[\r\n]/.test(token)) { + throw new SchematicsException('The app token must not contain a line break.'); + } return chain([ enableSourceMaps(located.name), instrument(located, token ?? PLACEHOLDER), diff --git a/packages/angular/src/sourcemaps/upload.real-build.test.ts b/packages/angular/src/sourcemaps/upload.real-build.test.ts index 11aecd53b..583f23f26 100644 --- a/packages/angular/src/sourcemaps/upload.real-build.test.ts +++ b/packages/angular/src/sourcemaps/upload.real-build.test.ts @@ -282,6 +282,25 @@ describeReal('uploadAngularSourcemaps on real Angular output with subresourceInt expect(readFileSync(join(browser, 'fr', ENTRY), 'utf8')).toContain('_bugseeDebugIds'); }); + it('--dist on an SSR build re-seals the server copy of the page too (measured without this: every server digest stale)', async () => { + const { dir, browser, embedded } = workspace('dist-ssr', { ssr: true }); + const errors: unknown[] = []; + await uploadAngularSourcemaps({ + cwd: dir, + dist: browser, + appToken: 'tok', + endpoint, + vcs: false, + registerBuild: false, + env: {}, + onError: (e) => errors.push(e), + }); + expect(errors).toEqual([]); + const fresh = readFileSync(embedded as string, 'utf8'); + expect(fresh).toContain(sha384(join(browser, ENTRY))); + expect(fresh).toContain(sha384(join(browser, LAZY))); + }); + it('the guard still refuses to stamp this build WITHOUT re-sealing: the import map is seen', async () => { const { browser } = workspace('refused'); const errors: unknown[] = []; diff --git a/packages/angular/src/sourcemaps/upload.test.ts b/packages/angular/src/sourcemaps/upload.test.ts index c60b650fb..229cacdf2 100644 --- a/packages/angular/src/sourcemaps/upload.test.ts +++ b/packages/angular/src/sourcemaps/upload.test.ts @@ -141,6 +141,55 @@ describe('uploadAngularSourcemaps', () => { }); }); + it('--dist on an SSR build re-seals the whole output root: the server modules embed the page', async () => { + await write('custom/app/browser/main.js', 'x();'); + await write('custom/app/browser/main.js.map', '{}'); + await write('custom/app/server/server.mjs', ''); + const runPluginUpload = ran(); + await uploadAngularSourcemaps(base({ cwd, dist: 'custom/app/browser' }), { runPluginUpload }); + expect(runPluginUpload.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(cwd, 'custom', 'app')], + }); + }); + + it('--dist: a sibling server/ outside the project is not pulled in', async () => { + const outside = await mkdtemp(join(tmpdir(), 'bugsee-ng-out-')); + try { + await mkdir(join(outside, 'browser'), { recursive: true }); + await mkdir(join(outside, 'server')); + await writeFile(join(outside, 'browser', 'main.js'), 'x();'); + const runPluginUpload = ran(); + await uploadAngularSourcemaps(base({ cwd, dist: join(outside, 'browser') }), { + runPluginUpload, + }); + expect(runPluginUpload.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(outside, 'browser')], + }); + } finally { + await rm(outside, { recursive: true, force: true }); + } + }); + + it('--dist directly under the project root never re-seals the project root', async () => { + await write('browser/main.js', 'x();'); + await write('server/server.mjs', ''); + const runPluginUpload = ran(); + await uploadAngularSourcemaps(base({ cwd, dist: 'browser' }), { runPluginUpload }); + expect(runPluginUpload.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(cwd, 'browser')], + }); + }); + + it('--dist whose sibling is not named server/ stays browser-only', async () => { + await write('x/browser/main.js', 'x();'); + await write('x/other/a.mjs', ''); + const runPluginUpload = ran(); + await uploadAngularSourcemaps(base({ cwd, dist: 'x/browser' }), { runPluginUpload }); + expect(runPluginUpload.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(cwd, 'x', 'browser')], + }); + }); + it('reads the token and version from the environment and the env file, like the bundler plugins', async () => { await builtApp(); await write('.env.bugsee-build-plugin', 'BUGSEE_APP_TOKEN=from-file\n'); diff --git a/packages/angular/src/sourcemaps/upload.ts b/packages/angular/src/sourcemaps/upload.ts index 8ae4e48e8..26c2518f3 100644 --- a/packages/angular/src/sourcemaps/upload.ts +++ b/packages/angular/src/sourcemaps/upload.ts @@ -10,7 +10,7 @@ // script is re-written wherever it appears (`resealSri`, bundler-plugin-core), and a build that cannot be re-sealed // is restored. Measured on real @angular/build 22.3 and build-angular 19.2 builds; see docs/design/source-maps.md §7.1. import { existsSync, readdirSync } from 'node:fs'; -import { join, relative, resolve } from 'node:path'; +import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; import { type BugseePluginOptions, type EnvRecord, @@ -155,6 +155,26 @@ export async function uploadAngularSourcemaps( let outDir: string; if (options.dist !== undefined) { outDir = resolve(cwd, options.dist); + // An SSR build's server modules embed the page, hashes included, so its output ROOT must be re-sealed too. Only + // when the sibling server/ exists and the root is inside the project (never the project root itself, or above). + const root = dirname(outDir); + const inside = relative(cwd, root); + if ( + existsSync(join(root, 'server')) && + inside !== '' && + !inside.startsWith('..') && + !isAbsolute(inside) + ) { + located = { + project: options.project ?? '', + builder: undefined, + layout: 'application', + configuration: options.configuration, + baseDir: root, + browserDir: outDir, + serverDir: join(root, 'server'), + }; + } } else if (options.outputPath !== undefined) { // `ng build --output-path `: the base of an application build (browser/ and server/ below it), or the // browser directory itself for a flat one. From c74f033f06289d4a38049f93c8667cecde6c86bf Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 16:18:10 +0500 Subject: [PATCH 34/59] fix(angular,bundler-plugin-core): find the SSR output root from any named output; verify the re-seal over every directory it covers - bugsee-angular-upload locates the output root of an SSR build from --dist (browser or browser/) or --output-path via one probe (browser + real server/ siblings, inside the project, not the project root); otherwise it says it could not re-seal the server pages. Exact path-segment containment (a dir named ..out). - findStaleDigests: after the re-seal no old digest may remain in any file of resealDirs, else the build is rolled back. - ng add rejects tokens with whitespace, quotes, backticks, backslashes or # (env parser / launch call safety). Co-Authored-By: Claude Sonnet 5.5 --- docs/source-maps-usage.md | 2 +- packages/angular/README.md | 2 +- .../src/schematics/ng-add/index.test.ts | 25 +-- .../angular/src/schematics/ng-add/index.ts | 6 +- .../src/sourcemaps/server-root.test.ts | 149 ++++++++++++++++++ .../angular/src/sourcemaps/server-root.ts | 57 +++++++ packages/angular/src/sourcemaps/upload.ts | 65 ++++---- packages/bundler-plugin-core/src/index.ts | 1 + .../src/orchestrate.reseal-rollback.test.ts | 31 ++++ .../bundler-plugin-core/src/orchestrate.ts | 17 ++ .../src/sri.service-worker.test.ts | 41 +++++ packages/bundler-plugin-core/src/sri.ts | 40 +++++ 12 files changed, 383 insertions(+), 53 deletions(-) create mode 100644 packages/angular/src/sourcemaps/server-root.test.ts create mode 100644 packages/angular/src/sourcemaps/server-root.ts diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index ecdc7e64c..662e8e137 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -213,7 +213,7 @@ esbuild `application` builder (the default since 17, output in `dist//b - **A build with a service worker works.** `ngsw.json` (one per locale for a localized build) lists the SHA-1 of every file it caches and the service worker rejects a changed one, so after stamping the step re-computes those entries and checks them; if one cannot be reconciled it restores the build and uploads nothing. -- **If the output moved** (`ng build --output-path other`), pass `--output-path other` (or `--dist `; on an SSR build `--dist` also re-seals the sibling `server/` directory when it sits inside the project). A +- **If the output moved** (`ng build --output-path other`), pass `--output-path other` (or `--dist `). When the output is named by its browser directory (also `browser/`) and a sibling `server/` exists inside the project, the whole output root is re-sealed, because the server embeds the page; if the output root is the project root itself (or outside it) the tool says it cannot, and you should build into its own directory and use `--output-path`. A problem locating the output is printed and the command exits 0, so it cannot fail a pipeline whose build succeeded; `--fail-on-error` makes it exit non-zero. - **Only `browser/` is uploaded.** An SSR server bundle's errors are reported by the Node SDK. diff --git a/packages/angular/README.md b/packages/angular/README.md index 9e76abe7b..fabd7f489 100644 --- a/packages/angular/README.md +++ b/packages/angular/README.md @@ -55,7 +55,7 @@ It works with the esbuild `application` builder and the webpack `browser` builde - `subresourceIntegrity: true` is supported: after stamping, the integrity hashes in `index.html`, in the import map and in the SSR server modules are re-written to match, so the page keeps loading. - A build with a service worker works: `ngsw.json` (one per locale for a localized build) lists the SHA-1 of every file it caches, so after stamping those entries are re-computed and checked; if one cannot be reconciled the build is restored and nothing is uploaded. -- If the output is not where `angular.json` says (`ng build --output-path other`), pass `--output-path other` (or `--dist `; on an SSR build `--dist` also re-seals the sibling `server/` directory when it sits inside the project). A problem locating the output (no `angular.json`, several applications without `--project`, no build output yet) is printed and the command still exits 0, so it cannot fail a pipeline whose build succeeded; add `--fail-on-error` to make it exit non-zero. +- If the output is not where `angular.json` says (`ng build --output-path other`), pass `--output-path other` (or `--dist `). When the output is named by its browser directory (also `browser/`) and a sibling `server/` exists inside the project, the whole output root is re-sealed, because the server embeds the page; if the output root is the project root itself (or outside it) the tool says it cannot, and you should build into its own directory and use `--output-path`. A problem locating the output (no `angular.json`, several applications without `--project`, no build output yet) is printed and the command still exits 0, so it cannot fail a pipeline whose build succeeded; add `--fail-on-error` to make it exit non-zero. - Install weight: `@bugsee/angular` depends on `@bugsee/bundler-plugin-core` (and through it `@bugsee/cli`, `acorn`, `magic-string`, `unplugin`), because the `bugsee-angular-upload` bin and `@bugsee/angular/sourcemaps` need them. They are build-time only and never reach a browser bundle, but they are installed with the package. Making them an optional peer that `ng add` installs as a devDependency was considered and not done: `ng add` saves the package itself under `dependencies`, the bin would fail for anyone who skips `ng add`, and the extra install step has to be verified against every package manager. - If your app already provides its own `ErrorHandler`, `ng add` does not add a second one (the last provider wins and would silence yours); it prints how to report from yours with `reportAngularError(error)`, or to wrap it with `createAngularErrorHandler({ delegate })`. - Known limits: the `ErrorHandler` check scans only the project's `sourceRoot`, so a handler provided from a shared (Nx) library is not seen; the deletion rule assumes Angular cleans its output directory (`deleteOutputPath`, default true), so with `deleteOutputPath: false` or a wider `--dist`, a stale foreign map that carries a debug-ID could be deleted; the integrity check does not follow `` for nested prerendered pages (the digest swap still fixes them). diff --git a/packages/angular/src/schematics/ng-add/index.test.ts b/packages/angular/src/schematics/ng-add/index.test.ts index b1e47a1b6..fa3f1b4d6 100644 --- a/packages/angular/src/schematics/ng-add/index.test.ts +++ b/packages/angular/src/schematics/ng-add/index.test.ts @@ -196,18 +196,21 @@ describe('ng add @bugsee/angular — without a token', () => { expect(tree.readContent('/src/main.ts')).toContain(`launch('YOUR_APP_TOKEN');`); }); - it('rejects a token with a line break, which would inject a line into the env file', async () => { - const tree = await workspace(); - await expect(run(tree, { appToken: 'abc\nBUGSEE_ENDPOINT=https://evil' })).rejects.toThrow( - /line break/, - ); - await expect(run(tree, { appToken: 'abc\rdef' })).rejects.toThrow(/line break/); + it.each([ + ['a line break', 'abc\nBUGSEE_ENDPOINT=https://evil'], + ['a carriage return', 'abc\rdef'], + ['a unicode line separator', 'abc\u2028def'], + ['a space', 'abc def'], + ['a # (the env parser reads it as a comment)', 'abc#def'], + ['a single quote', "a'b"], + ['a double quote', 'a"b'], + ['a backtick', 'a`b'], + ['a backslash', 'a\\b'], + ])('rejects a token with %s, which the env file or the launch call cannot carry safely', async (_name, token) => { + const tree = await workspace(); + await expect(run(tree, { appToken: token })).rejects.toThrow(/must not contain/); expect(tree.exists('/.env.bugsee-build-plugin')).toBe(false); - }); - - it('escapes a quote in the token so the launch call stays valid', async () => { - const tree = await run(await workspace(), { appToken: `a'b\\c` }); - expect(tree.readContent('/src/main.ts')).toContain(`launch('a\\'b\\\\c');`); + expect(tree.readContent('/src/main.ts')).not.toContain('launch('); }); }); diff --git a/packages/angular/src/schematics/ng-add/index.ts b/packages/angular/src/schematics/ng-add/index.ts index 07cb22298..f42f22f30 100644 --- a/packages/angular/src/schematics/ng-add/index.ts +++ b/packages/angular/src/schematics/ng-add/index.ts @@ -307,8 +307,10 @@ export function ngAdd(options: Schema = {}): Rule { const located = await locate(tree, options.project); const trimmed = options.appToken?.trim(); const token = trimmed === undefined || trimmed === '' ? undefined : trimmed; - if (token !== undefined && /[\r\n]/.test(token)) { - throw new SchematicsException('The app token must not contain a line break.'); + if (token !== undefined && /[\s"'`#\\]/.test(token)) { + throw new SchematicsException( + 'The app token must not contain whitespace, a line break, quotes, backticks, backslashes or #.', + ); } return chain([ enableSourceMaps(located.name), diff --git a/packages/angular/src/sourcemaps/server-root.test.ts b/packages/angular/src/sourcemaps/server-root.test.ts new file mode 100644 index 000000000..7e6da88e7 --- /dev/null +++ b/packages/angular/src/sourcemaps/server-root.test.ts @@ -0,0 +1,149 @@ +import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, win32 } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { findServerRoot, isStrictlyInside } from './server-root'; +import { uploadAngularSourcemaps } from './upload'; + +let cwd: string; +beforeEach(async () => { + cwd = await mkdtemp(join(tmpdir(), 'bugsee-ng-root-')); +}); +afterEach(async () => { + await rm(cwd, { recursive: true, force: true }); +}); +const dir = (rel: string) => mkdir(join(cwd, rel), { recursive: true }); +const file = async (rel: string) => { + await dir(join(rel, '..')); + await writeFile(join(cwd, rel), 'x();'); +}; + +describe('isStrictlyInside', () => { + it('is true for a descendant, false for the directory itself, a parent, a sibling and another drive', () => { + expect(isStrictlyInside('/p/a/b', '/p')).toBe(true); + expect(isStrictlyInside('/p', '/p')).toBe(false); + expect(isStrictlyInside('/', '/p')).toBe(false); + expect(isStrictlyInside('/q/a', '/p')).toBe(false); + }); + + it('a directory whose name merely starts with two dots is inside', () => { + expect(isStrictlyInside('/p/..out/browser', '/p')).toBe(true); + }); + + it('on Windows a different drive is not inside (relative() answers with an absolute path)', () => { + expect(isStrictlyInside('D:\\out\\app', 'C:\\proj', win32)).toBe(false); + expect(isStrictlyInside('C:\\proj\\out\\app', 'C:\\proj', win32)).toBe(true); + }); +}); + +describe('findServerRoot', () => { + it('finds the output root of an application build from its browser directory', async () => { + await file('o/browser/main.js'); + await dir('o/server'); + expect(findServerRoot(join(cwd, 'o/browser'), cwd)).toEqual({ root: join(cwd, 'o') }); + }); + + it('finds it from a locale directory of a localized build', async () => { + await file('o/browser/fr/main.js'); + await dir('o/server/fr'); + expect(findServerRoot(join(cwd, 'o/browser/fr'), cwd)).toEqual({ root: join(cwd, 'o') }); + }); + + it('does not take an unrelated server/ for the output root: a browser sibling is required', async () => { + await file('o/dist/main.js'); + await dir('o/server'); + expect(findServerRoot(join(cwd, 'o/dist'), cwd)).toBeUndefined(); + }); + + it('finds nothing without a server/', async () => { + await file('o/browser/fr/main.js'); + expect(findServerRoot(join(cwd, 'o/browser/fr'), cwd)).toBeUndefined(); + expect(findServerRoot(join(cwd, 'o/browser'), cwd)).toBeUndefined(); + }); + + it('does not follow a symlinked server/, and says nothing', async () => { + await file('o/browser/main.js'); + await dir('elsewhere'); + await symlink(join(cwd, 'elsewhere'), join(cwd, 'o/server')); + expect(findServerRoot(join(cwd, 'o/browser'), cwd)).toBeUndefined(); + }); + + it('works under a directory whose name starts with two dots', async () => { + await file('..out/browser/main.js'); + await dir('..out/server'); + expect(findServerRoot(join(cwd, '..out/browser'), cwd)).toEqual({ root: join(cwd, '..out') }); + }); + + it('says it cannot widen when the output root is the project root, instead of re-sealing the project', async () => { + await file('browser/main.js'); + await dir('server'); + const found = findServerRoot(join(cwd, 'browser'), cwd); + expect(found).toMatchObject({ notice: expect.stringContaining('server') }); + expect((found as { notice: string }).notice).toMatch(/--output-path/); + }); + + it('says so when the output root is outside the project', async () => { + const outside = await mkdtemp(join(tmpdir(), 'bugsee-ng-outside-')); + try { + await mkdir(join(outside, 'browser')); + await mkdir(join(outside, 'server')); + const found = findServerRoot(join(outside, 'browser'), cwd); + expect(found).toMatchObject({ notice: expect.stringContaining('outside') }); + } finally { + await rm(outside, { recursive: true, force: true }); + } + }); +}); + +describe('uploadAngularSourcemaps: the server pages are re-sealed whichever way the output is named', () => { + const ran = () => + vi.fn(async (_r: unknown, _d: string, _deps: Record) => ({ + injected: true, + uploaded: true, + deletedMaps: [], + })); + const base = (extra: Record, notices: string[] = []) => ({ + cwd, + appToken: 'tok', + vcs: false, + env: {}, + onNotice: (m: string) => notices.push(m), + ...extra, + }); + const build = async () => { + await file('o/browser/fr/main.js'); + await file('o/browser/fr/main.js.map'); + await dir('o/server/fr'); + }; + + it('--dist /', async () => { + await build(); + const run = ran(); + await uploadAngularSourcemaps(base({ dist: 'o/browser/fr' }), { runPluginUpload: run }); + expect(run.mock.calls[0]?.[2]).toMatchObject({ resealDirs: [join(cwd, 'o')] }); + }); + + it('--output-path (a flat reading of an application output)', async () => { + await build(); + const run = ran(); + await uploadAngularSourcemaps(base({ outputPath: 'o/browser' }), { runPluginUpload: run }); + expect(run.mock.calls[0]?.[2]).toMatchObject({ resealDirs: [join(cwd, 'o')] }); + }); + + it('a nested --dist with no server/ keeps the browser directory only', async () => { + await file('o/browser/fr/main.js'); + const run = ran(); + await uploadAngularSourcemaps(base({ dist: 'o/browser/fr' }), { runPluginUpload: run }); + expect(run.mock.calls[0]?.[2]).toMatchObject({ resealDirs: [join(cwd, 'o/browser/fr')] }); + }); + + it('the project root as output root is said, and not widened', async () => { + await file('browser/main.js'); + await dir('server'); + const run = ran(); + const notices: string[] = []; + await uploadAngularSourcemaps(base({ dist: 'browser' }, notices), { runPluginUpload: run }); + expect(run.mock.calls[0]?.[2]).toMatchObject({ resealDirs: [join(cwd, 'browser')] }); + expect(notices.join('\n')).toMatch(/server.*project root/s); + }); +}); diff --git a/packages/angular/src/sourcemaps/server-root.ts b/packages/angular/src/sourcemaps/server-root.ts new file mode 100644 index 000000000..42c100a4f --- /dev/null +++ b/packages/angular/src/sourcemaps/server-root.ts @@ -0,0 +1,57 @@ +// An SSR build's server modules embed the page, SRI hashes included, so re-sealing the browser directory alone leaves +// the server serving stale hashes (measured: every script blocked). When the output is named by its browser directory +// (`--dist`, or `--output-path` pointing at it) the output ROOT has to be found from it. +import { lstatSync } from 'node:fs'; +import * as path from 'node:path'; + +type PathApi = Pick; + +/** Whether `dir` is strictly below `root` (not equal to it, not above it, not on another drive). */ +export function isStrictlyInside(dir: string, root: string, api: PathApi = path): boolean { + const rel = api.relative(root, dir); + return rel !== '' && rel !== '..' && !rel.startsWith(`..${api.sep}`) && !api.isAbsolute(rel); +} + +const isRealDirectory = (p: string): boolean => { + try { + const info = lstatSync(p); + return info.isDirectory(); // lstat does not follow a symlink, so a symlinked server/ is not a directory here + } catch { + return false; + } +}; + +/** How far above the output directory the root is looked for: `browser/` -> root, `browser//` -> two. */ +const MAX_LEVELS_UP = 2; + +export type ServerRoot = { root: string } | { notice: string } | undefined; + +/** + * The output root of the SSR build `outDir` belongs to: the nearest ancestor (at most {@link MAX_LEVELS_UP} up) that + * has both a `browser/` containing `outDir` and a real (not symlinked) `server/`. Requiring the `browser/` sibling + * keeps an unrelated `server/` from becoming the scope. A root that is the project itself, or outside it, is NOT + * returned (re-sealing a project root, or someone else's directory, is not this tool's call): a notice says so. + */ +export function findServerRoot(outDir: string, cwd: string, api: PathApi = path): ServerRoot { + let root = api.dirname(outDir); + for (let level = 0; level < MAX_LEVELS_UP; level++, root = api.dirname(root)) { + const browser = api.join(root, 'browser'); + const within = outDir === browser || isStrictlyInside(outDir, browser, api); + if (!within || !isRealDirectory(api.join(root, 'server'))) { + continue; + } + if (isStrictlyInside(root, cwd, api)) { + return { root }; + } + return { + notice: + `found ${api.join(root, 'server')} next to the browser output, which embeds the page's integrity hashes, but ` + + (root === cwd + ? 'the output root is the project root' + : 'the output root is outside the project') + + `, so it was not re-sealed and a server-rendered page may keep stale hashes. Build into its own directory and ` + + `pass --output-path .`, + }; + } + return undefined; +} diff --git a/packages/angular/src/sourcemaps/upload.ts b/packages/angular/src/sourcemaps/upload.ts index 26c2518f3..23ba85d52 100644 --- a/packages/angular/src/sourcemaps/upload.ts +++ b/packages/angular/src/sourcemaps/upload.ts @@ -10,7 +10,7 @@ // script is re-written wherever it appears (`resealSri`, bundler-plugin-core), and a build that cannot be re-sealed // is restored. Measured on real @angular/build 22.3 and build-angular 19.2 builds; see docs/design/source-maps.md §7.1. import { existsSync, readdirSync } from 'node:fs'; -import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; +import { join, relative, resolve } from 'node:path'; import { type BugseePluginOptions, type EnvRecord, @@ -23,6 +23,7 @@ import { runPluginUpload, } from '@bugsee/bundler-plugin-core'; import { type AngularOutput, resolveAngularOutput } from './output'; +import { findServerRoot } from './server-root'; export interface AngularUploadOptions extends BugseePluginOptions { /** Workspace directory (angular.json is looked for here and above). Default: the working directory. */ @@ -153,42 +154,30 @@ export async function uploadAngularSourcemaps( }; let located: AngularOutput | undefined; let outDir: string; + // The output ROOT whose pages must be re-sealed: an SSR build's server modules embed the page. + let resealRoot: string | undefined; + const probeServerRoot = (): void => { + const found = findServerRoot(outDir, cwd); + if (found !== undefined && 'root' in found) { + resealRoot = found.root; + } else if (found !== undefined) { + say(found.notice); + } + }; if (options.dist !== undefined) { outDir = resolve(cwd, options.dist); - // An SSR build's server modules embed the page, hashes included, so its output ROOT must be re-sealed too. Only - // when the sibling server/ exists and the root is inside the project (never the project root itself, or above). - const root = dirname(outDir); - const inside = relative(cwd, root); - if ( - existsSync(join(root, 'server')) && - inside !== '' && - !inside.startsWith('..') && - !isAbsolute(inside) - ) { - located = { - project: options.project ?? '', - builder: undefined, - layout: 'application', - configuration: options.configuration, - baseDir: root, - browserDir: outDir, - serverDir: join(root, 'server'), - }; - } + probeServerRoot(); } else if (options.outputPath !== undefined) { - // `ng build --output-path `: the base of an application build (browser/ and server/ below it), or the - // browser directory itself for a flat one. + // `ng build --output-path `: the base of an application build (browser/ and server/ below it), or a + // browser directory itself. const base = resolve(cwd, options.outputPath); - outDir = existsSync(join(base, 'browser')) ? join(base, 'browser') : base; - located = { - project: options.project ?? '', - builder: undefined, - layout: outDir === base ? 'flat' : 'application', - configuration: options.configuration, - baseDir: base, - browserDir: outDir, - ...(outDir === base ? {} : { serverDir: join(base, 'server') }), - }; + if (existsSync(join(base, 'browser'))) { + outDir = join(base, 'browser'); + resealRoot = existsSync(join(base, 'server')) ? base : undefined; + } else { + outDir = base; + probeServerRoot(); + } } else { try { located = resolveAngularOutput({ @@ -204,6 +193,10 @@ export async function uploadAngularSourcemaps( ); } outDir = located.browserDir; + resealRoot = + located.serverDir !== undefined && existsSync(located.serverDir) + ? located.baseDir + : undefined; } const configuration = located?.configuration ?? options.configuration; @@ -230,16 +223,12 @@ export async function uploadAngularSourcemaps( ); } - const server = located?.serverDir; const run = deps.runPluginUpload ?? runPluginUpload; const result = await run(resolved, outDir, { // Only acts when the build pins script hashes; then inject runs with --allow-sri and the page is re-sealed. resealSri: true, // The server modules of an SSR build embed the page, hashes included. - resealDirs: - located !== undefined && server !== undefined && existsSync(server) - ? [located.baseDir] - : [outDir], + resealDirs: [resealRoot ?? outDir], bundler: { isProduction, ...(configuration !== undefined ? { configuration } : {}) }, ownFiles: ownFilesOf(outDir), }); diff --git a/packages/bundler-plugin-core/src/index.ts b/packages/bundler-plugin-core/src/index.ts index ea07a718b..8eb108e2a 100644 --- a/packages/bundler-plugin-core/src/index.ts +++ b/packages/bundler-plugin-core/src/index.ts @@ -61,6 +61,7 @@ export { export { findIntegrityMismatches, findSriProtectedScripts, + findStaleDigests, findStaleServiceWorkerEntries, listResealFiles, resealIntegrity, diff --git a/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts index 20ba6725c..7ca25b400 100644 --- a/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts @@ -10,6 +10,7 @@ import { join } from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { uploadSourcemaps } from './orchestrate'; import { resolveBugseeCli, runBugseeCli } from './run-cli'; +import { resealIntegrity } from './sri'; const cli = resolveBugseeCli(); const probe = cli.endsWith('.js') @@ -191,6 +192,36 @@ describeReal('uploadSourcemaps re-seal rollback', () => { expect(String(errors[0])).toMatch(/restored/); }); + it('restores everything when an old digest is still present in the server modules after the re-seal', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts, calls, errors } = options(out, server, { + verifyDigests: async () => [ + { file: join(server, 'index.html.mjs'), script: join(out, 'main.js') }, + ], + }); + const result = await uploadSourcemaps(opts); + expect(snapshot(out, server)).toEqual(before); + expect(calls).not.toContain('upload'); + expect(result).toMatchObject({ injected: false, uploaded: false }); + expect(String(errors[0])).toContain('index.html.mjs'); + expect(String(errors[0])).toMatch(/restored/); + }); + + it('rolls back when the server copy of the page was not re-sealed (the browser pages alone look fine)', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts, calls, errors } = options(out, server, { + // Re-seals the browser directory only, so index.html verifies but the server module keeps the old digest. + reseal: (digests: Parameters[0]) => resealIntegrity(digests, [out]), + }); + const result = await uploadSourcemaps(opts); + expect(snapshot(out, server)).toEqual(before); + expect(calls).not.toContain('upload'); + expect(result).toMatchObject({ injected: false, uploaded: false }); + expect(String(errors[0])).toContain('index.html.mjs'); + }); + it('seals a build with a real service worker manifest (control)', async () => { const { out, server } = build(); const js = readFileSync(join(out, 'main.js'), 'utf8'); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 962cdc4cd..d0d264462 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -9,6 +9,7 @@ import { type RunBugseeCliOptions, runBugseeCli, type SpawnResult } from './run- import { findIntegrityMismatches, findSriProtectedScripts, + findStaleDigests, findStaleServiceWorkerEntries, listResealFiles, resealIntegrity, @@ -138,6 +139,8 @@ export interface UploadSourcemapsOptions { snapshotDigests?: typeof snapshotScriptDigests; /** Injectable check that service worker manifests match their files after the re-seal (default {@link findStaleServiceWorkerEntries}). */ verifyServiceWorker?: typeof findStaleServiceWorkerEntries; + /** Injectable check that no old digest survives anywhere the re-seal covers (default {@link findStaleDigests}). */ + verifyDigests?: typeof findStaleDigests; /** * FAIL the build when `bugsee-cli` fails. Default `false`. * @@ -593,6 +596,20 @@ export async function uploadSourcemaps( (stale.length > 1 ? ` (and ${stale.length - 1} more)` : '') + ` after the hashes were re-written, so the service worker would treat the app as corrupt and stop serving it`, ); + } else { + // Every directory the re-seal covers, not only the one the pages are scanned in: an SSR build's server + // modules hold a copy of the page that findIntegrityMismatches (HTML under outDir) cannot see. + const left = await (options.verifyDigests ?? findStaleDigests)( + digests, + options.resealDirs ?? [outDir], + ); + if (left.length > 0) { + sealFailure = new Error( + `${left[0]?.file} still holds the old integrity hash of ${left[0]?.script}` + + (left.length > 1 ? ` (and ${left.length - 1} more file(s))` : '') + + ` after the hashes were re-written, so a page served from it would be blocked by the browser`, + ); + } } } } catch (error) { diff --git a/packages/bundler-plugin-core/src/sri.service-worker.test.ts b/packages/bundler-plugin-core/src/sri.service-worker.test.ts index 056323ec4..bea51f830 100644 --- a/packages/bundler-plugin-core/src/sri.service-worker.test.ts +++ b/packages/bundler-plugin-core/src/sri.service-worker.test.ts @@ -8,6 +8,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { + findStaleDigests, findStaleServiceWorkerEntries, listResealFiles, resealIntegrity, @@ -36,6 +37,46 @@ const write = async (rel: string, body: string) => { return full; }; +describe('findStaleDigests', () => { + it('reports every file under the directories that still holds the old digest of a changed script', async () => { + await write('browser/main.js', 'a();'); + await write('browser/keep.js', 'k();'); + const page = ``; + const html = await write('browser/index.html', page); + const mjs = await write( + 'server/assets/index.html.mjs', + `export default ${JSON.stringify(page)};`, + ); + await write('server/notes.txt', page); + const before = await snapshotScriptDigests([join(root, 'browser')]); + await write('browser/main.js', 'a();\n//# debugId=x'); + const stale = await findStaleDigests(before, [root]); + expect(stale.map((s) => s.file).sort()).toEqual([html, mjs].sort()); + expect(stale[0]?.script).toBe(join(root, 'browser/main.js')); + await resealIntegrity(before, [root]); + expect(await findStaleDigests(before, [root])).toEqual([]); + }); + + it('says nothing when no script changed, or a changed script is gone', async () => { + await write('browser/main.js', 'a();'); + await write('browser/index.html', `sha384-${sha('sha384', 'a();')}`); + const before = await snapshotScriptDigests([join(root, 'browser')]); + expect(await findStaleDigests(before, [root])).toEqual([]); + await rm(join(root, 'browser/main.js')); + expect(await findStaleDigests(before, [root])).toEqual([]); + }); + + it('checks every algorithm', async () => { + await write('a.js', 'a();'); + const before = await snapshotScriptDigests([root]); + await write('a.js', 'b();'); + for (const alg of ['sha256', 'sha512']) { + const page = await write(`p-${alg}.html`, `${alg}-${sha(alg, 'a();')}`); + expect((await findStaleDigests(before, [root])).map((s) => s.file)).toContain(page); + } + }); +}); + describe('service worker manifests', () => { it('re-computes the hash of a file that was stamped or re-sealed, leaving the formatting alone', async () => { await write('main.js', 'a();'); diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index 9ec1ab87c..f6ed56652 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -374,6 +374,46 @@ export async function resealIntegrity( return { files: [...rewritten] }; } +/** + * Files under `dirs` that STILL hold an old digest of a script that has changed since `before`: a copy the swap + * did not fix (the check {@link resealIntegrity} is verified by, over every directory it was given, not just the one + * the pages are read from). Empty means every copy it could see was brought up to date. + */ +export async function findStaleDigests( + before: ScriptDigests, + dirs: readonly string[], +): Promise<{ file: string; script: string }[]> { + const tokens: { token: string; script: string }[] = []; + for (const [script, old] of before) { + let bytes: Buffer; + try { + bytes = await readFile(script); + } catch { + continue; + } + const now = digestsOf(bytes); + for (const alg of SRI_ALGORITHMS) { + if (now[alg] !== old[alg]) { + tokens.push({ token: `${alg}-${old[alg]}`, script }); + } + } + } + const stale: { file: string; script: string }[] = []; + if (tokens.length === 0) { + return stale; + } + for (const file of await listResealFiles(dirs)) { + const text = await readFile(file, 'utf8'); + for (const { token, script } of tokens) { + if (text.includes(token)) { + stale.push({ file, script }); + break; + } + } + } + return stale; +} + const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); interface ManifestEntry { From ef4e80bbfa56c180cda1b7ffc779530f920d0c8c Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 16:27:33 +0500 Subject: [PATCH 35/59] fix(angular,bundler-plugin-core): re-seal one locale only, verify the whole output root, notice for a custom browser dir - --dist/--output-path / stamps one locale; re-sealing the whole root swapped digests of identical shared scripts everywhere and blocked the other locales. resealDirs is now that locale plus its server/. - verifyDirs: page pins are verified across the whole output root after the re-seal; a mismatch anywhere rolls back. - server-root: a real server/ sibling with no browser/ parent (outputPath.browser renamed) is said, not silent. - findStaleDigests: one regex pass per file against a map (was a substring search per token per file). Co-Authored-By: Claude Sonnet 5.5 --- docs/source-maps-usage.md | 2 +- packages/angular/README.md | 2 +- .../src/sourcemaps/server-root.test.ts | 61 +++++++++++++++++-- .../angular/src/sourcemaps/server-root.ts | 22 +++++-- .../src/sourcemaps/upload.real-build.test.ts | 52 ++++++++++++++++ packages/angular/src/sourcemaps/upload.ts | 15 ++++- .../src/orchestrate.reseal-rollback.test.ts | 40 ++++++++++++ .../bundler-plugin-core/src/orchestrate.ts | 7 ++- .../bundler-plugin-core/src/resolve.test.ts | 8 ++- packages/bundler-plugin-core/src/resolve.ts | 3 + packages/bundler-plugin-core/src/sri.ts | 14 +++-- 11 files changed, 205 insertions(+), 21 deletions(-) diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 662e8e137..e0e89112a 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -213,7 +213,7 @@ esbuild `application` builder (the default since 17, output in `dist//b - **A build with a service worker works.** `ngsw.json` (one per locale for a localized build) lists the SHA-1 of every file it caches and the service worker rejects a changed one, so after stamping the step re-computes those entries and checks them; if one cannot be reconciled it restores the build and uploads nothing. -- **If the output moved** (`ng build --output-path other`), pass `--output-path other` (or `--dist `). When the output is named by its browser directory (also `browser/`) and a sibling `server/` exists inside the project, the whole output root is re-sealed, because the server embeds the page; if the output root is the project root itself (or outside it) the tool says it cannot, and you should build into its own directory and use `--output-path`. A +- **If the output moved** (`ng build --output-path other`), pass `--output-path other` (or `--dist `). When the output is named by its browser directory (also `browser/`) and a sibling `server/` exists inside the project, the output root is re-sealed, because the server embeds the page (for one locale of several, only that locale and its `server/` pages: Angular emits identical shared scripts into every locale, and the others must keep pinning their unstamped copies); if the output root is the project root itself (or outside it) the tool says it cannot, and you should build into its own directory and use `--output-path`. A problem locating the output is printed and the command exits 0, so it cannot fail a pipeline whose build succeeded; `--fail-on-error` makes it exit non-zero. - **Only `browser/` is uploaded.** An SSR server bundle's errors are reported by the Node SDK. diff --git a/packages/angular/README.md b/packages/angular/README.md index fabd7f489..6286d664a 100644 --- a/packages/angular/README.md +++ b/packages/angular/README.md @@ -55,7 +55,7 @@ It works with the esbuild `application` builder and the webpack `browser` builde - `subresourceIntegrity: true` is supported: after stamping, the integrity hashes in `index.html`, in the import map and in the SSR server modules are re-written to match, so the page keeps loading. - A build with a service worker works: `ngsw.json` (one per locale for a localized build) lists the SHA-1 of every file it caches, so after stamping those entries are re-computed and checked; if one cannot be reconciled the build is restored and nothing is uploaded. -- If the output is not where `angular.json` says (`ng build --output-path other`), pass `--output-path other` (or `--dist `). When the output is named by its browser directory (also `browser/`) and a sibling `server/` exists inside the project, the whole output root is re-sealed, because the server embeds the page; if the output root is the project root itself (or outside it) the tool says it cannot, and you should build into its own directory and use `--output-path`. A problem locating the output (no `angular.json`, several applications without `--project`, no build output yet) is printed and the command still exits 0, so it cannot fail a pipeline whose build succeeded; add `--fail-on-error` to make it exit non-zero. +- If the output is not where `angular.json` says (`ng build --output-path other`), pass `--output-path other` (or `--dist `). When the output is named by its browser directory (also `browser/`) and a sibling `server/` exists inside the project, the output root is re-sealed, because the server embeds the page (for one locale of several, only that locale and its `server/` pages: Angular emits identical shared scripts into every locale, and the others must keep pinning their unstamped copies); if the output root is the project root itself (or outside it) the tool says it cannot, and you should build into its own directory and use `--output-path`. A problem locating the output (no `angular.json`, several applications without `--project`, no build output yet) is printed and the command still exits 0, so it cannot fail a pipeline whose build succeeded; add `--fail-on-error` to make it exit non-zero. - Install weight: `@bugsee/angular` depends on `@bugsee/bundler-plugin-core` (and through it `@bugsee/cli`, `acorn`, `magic-string`, `unplugin`), because the `bugsee-angular-upload` bin and `@bugsee/angular/sourcemaps` need them. They are build-time only and never reach a browser bundle, but they are installed with the package. Making them an optional peer that `ng add` installs as a devDependency was considered and not done: `ng add` saves the package itself under `dependencies`, the bin would fail for anyone who skips `ng add`, and the extra install step has to be verified against every package manager. - If your app already provides its own `ErrorHandler`, `ng add` does not add a second one (the last provider wins and would silence yours); it prints how to report from yours with `reportAngularError(error)`, or to wrap it with `createAngularErrorHandler({ delegate })`. - Known limits: the `ErrorHandler` check scans only the project's `sourceRoot`, so a handler provided from a shared (Nx) library is not seen; the deletion rule assumes Angular cleans its output directory (`deleteOutputPath`, default true), so with `deleteOutputPath: false` or a wider `--dist`, a stale foreign map that carries a debug-ID could be deleted; the integrity check does not follow `` for nested prerendered pages (the digest swap still fixes them). diff --git a/packages/angular/src/sourcemaps/server-root.test.ts b/packages/angular/src/sourcemaps/server-root.test.ts index 7e6da88e7..dfad77694 100644 --- a/packages/angular/src/sourcemaps/server-root.test.ts +++ b/packages/angular/src/sourcemaps/server-root.test.ts @@ -40,19 +40,41 @@ describe('findServerRoot', () => { it('finds the output root of an application build from its browser directory', async () => { await file('o/browser/main.js'); await dir('o/server'); - expect(findServerRoot(join(cwd, 'o/browser'), cwd)).toEqual({ root: join(cwd, 'o') }); + expect(findServerRoot(join(cwd, 'o/browser'), cwd)).toEqual({ + root: join(cwd, 'o'), + browser: join(cwd, 'o/browser'), + }); }); it('finds it from a locale directory of a localized build', async () => { await file('o/browser/fr/main.js'); await dir('o/server/fr'); - expect(findServerRoot(join(cwd, 'o/browser/fr'), cwd)).toEqual({ root: join(cwd, 'o') }); + expect(findServerRoot(join(cwd, 'o/browser/fr'), cwd)).toEqual({ + root: join(cwd, 'o'), + browser: join(cwd, 'o/browser'), + }); }); - it('does not take an unrelated server/ for the output root: a browser sibling is required', async () => { + it('does not take an unrelated server/ for the output root, and says it could not tell', async () => { await file('o/dist/main.js'); await dir('o/server'); - expect(findServerRoot(join(cwd, 'o/dist'), cwd)).toBeUndefined(); + const found = findServerRoot(join(cwd, 'o/dist'), cwd); + expect(found).toMatchObject({ notice: expect.stringContaining('browser') }); + expect((found as { notice: string }).notice).toMatch(/--output-path/); + }); + + it('a custom browser directory name (outputPath.browser) is not guessed: it is said', async () => { + await file('o/client/fr/main.js'); + await dir('o/server/fr'); + expect(findServerRoot(join(cwd, 'o/client/fr'), cwd)).toMatchObject({ + notice: expect.stringContaining('o/server'), + }); + }); + + it('looks at most two levels up: a root three levels above is not found', async () => { + await file('o/browser/a/b/main.js'); + await dir('o/server'); + expect(findServerRoot(join(cwd, 'o/browser/a/b'), cwd)).toBeUndefined(); }); it('finds nothing without a server/', async () => { @@ -71,7 +93,10 @@ describe('findServerRoot', () => { it('works under a directory whose name starts with two dots', async () => { await file('..out/browser/main.js'); await dir('..out/server'); - expect(findServerRoot(join(cwd, '..out/browser'), cwd)).toEqual({ root: join(cwd, '..out') }); + expect(findServerRoot(join(cwd, '..out/browser'), cwd)).toEqual({ + root: join(cwd, '..out'), + browser: join(cwd, '..out/browser'), + }); }); it('says it cannot widen when the output root is the project root, instead of re-sealing the project', async () => { @@ -120,7 +145,22 @@ describe('uploadAngularSourcemaps: the server pages are re-sealed whichever way await build(); const run = ran(); await uploadAngularSourcemaps(base({ dist: 'o/browser/fr' }), { runPluginUpload: run }); - expect(run.mock.calls[0]?.[2]).toMatchObject({ resealDirs: [join(cwd, 'o')] }); + // Only the stamped locale and ITS server counterpart: Angular emits byte-identical shared scripts into every + // locale, so re-sealing the whole root would pin never-stamped scripts of the other locales to stamped digests. + expect(run.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(cwd, 'o/browser/fr'), join(cwd, 'o/server/fr')], + verifyDirs: [join(cwd, 'o')], + }); + }); + + it('--dist (all locales stamped) re-seals the whole root and verifies it', async () => { + await build(); + const run = ran(); + await uploadAngularSourcemaps(base({ dist: 'o/browser' }), { runPluginUpload: run }); + expect(run.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(cwd, 'o')], + verifyDirs: [join(cwd, 'o')], + }); }); it('--output-path (a flat reading of an application output)', async () => { @@ -130,6 +170,15 @@ describe('uploadAngularSourcemaps: the server pages are re-sealed whichever way expect(run.mock.calls[0]?.[2]).toMatchObject({ resealDirs: [join(cwd, 'o')] }); }); + it('--output-path with a browser/ but no server/ is browser-only, and verifies only it', async () => { + await file('b/browser/main.js'); + const run = ran(); + await uploadAngularSourcemaps(base({ outputPath: 'b' }), { runPluginUpload: run }); + const deps = run.mock.calls[0]?.[2] as { resealDirs: string[]; verifyDirs?: string[] }; + expect(deps.resealDirs).toEqual([join(cwd, 'b/browser')]); + expect(deps.verifyDirs).toEqual([join(cwd, 'b/browser')]); + }); + it('a nested --dist with no server/ keeps the browser directory only', async () => { await file('o/browser/fr/main.js'); const run = ran(); diff --git a/packages/angular/src/sourcemaps/server-root.ts b/packages/angular/src/sourcemaps/server-root.ts index 42c100a4f..6afa592ad 100644 --- a/packages/angular/src/sourcemaps/server-root.ts +++ b/packages/angular/src/sourcemaps/server-root.ts @@ -24,7 +24,7 @@ const isRealDirectory = (p: string): boolean => { /** How far above the output directory the root is looked for: `browser/` -> root, `browser//` -> two. */ const MAX_LEVELS_UP = 2; -export type ServerRoot = { root: string } | { notice: string } | undefined; +export type ServerRoot = { root: string; browser: string } | { notice: string } | undefined; /** * The output root of the SSR build `outDir` belongs to: the nearest ancestor (at most {@link MAX_LEVELS_UP} up) that @@ -34,14 +34,18 @@ export type ServerRoot = { root: string } | { notice: string } | undefined; */ export function findServerRoot(outDir: string, cwd: string, api: PathApi = path): ServerRoot { let root = api.dirname(outDir); + let unmatched: string | undefined; for (let level = 0; level < MAX_LEVELS_UP; level++, root = api.dirname(root)) { + if (!isRealDirectory(api.join(root, 'server'))) { + continue; + } const browser = api.join(root, 'browser'); - const within = outDir === browser || isStrictlyInside(outDir, browser, api); - if (!within || !isRealDirectory(api.join(root, 'server'))) { + if (outDir !== browser && !isStrictlyInside(outDir, browser, api)) { + unmatched ??= api.join(root, 'server'); continue; } if (isStrictlyInside(root, cwd, api)) { - return { root }; + return { root, browser }; } return { notice: @@ -53,5 +57,13 @@ export function findServerRoot(outDir: string, cwd: string, api: PathApi = path) `pass --output-path .`, }; } - return undefined; + if (unmatched === undefined) { + return undefined; + } + return { + notice: + `found ${unmatched} near the output, but the output is not inside a browser/ directory next to it (a custom ` + + `outputPath.browser name?), so it cannot tell which is the browser output and did not re-seal the server pages, ` + + `which embed the page's integrity hashes. Pass --output-path .`, + }; } diff --git a/packages/angular/src/sourcemaps/upload.real-build.test.ts b/packages/angular/src/sourcemaps/upload.real-build.test.ts index 583f23f26..9ebb557c7 100644 --- a/packages/angular/src/sourcemaps/upload.real-build.test.ts +++ b/packages/angular/src/sourcemaps/upload.real-build.test.ts @@ -301,6 +301,58 @@ describeReal('uploadAngularSourcemaps on real Angular output with subresourceInt expect(fresh).toContain(sha384(join(browser, LAZY))); }); + // Angular emits byte-identical shared scripts into every locale. Stamping ONE locale must leave the others' pages and + // server copies pinning their never-stamped scripts: re-sealing the whole root would swap the old digest for the + // stamped one everywhere and block the other locales (measured on 22.3: a blank /fr/, "Failed to find a valid digest"). + it('--dist / stamps and re-seals that locale and its server pages only', async () => { + const dir = join(root, 'locales-one'); + const page = (file: string) => + ``; + const files: Record = {}; + for (const locale of ['en-US', 'fr']) { + for (const f of [ENTRY, `${ENTRY}.map`]) { + mkdirSync(join(dir, 'dist/browser', locale), { recursive: true }); + cpSync(join(fixtures, f), join(dir, 'dist/browser', locale, f)); + } + writeFileSync(join(dir, 'dist/browser', locale, 'index.html'), page(ENTRY)); + mkdirSync(join(dir, 'dist/server', locale), { recursive: true }); + writeFileSync( + join(dir, 'dist/server', locale, 'index.html.mjs'), + `export default ${JSON.stringify(page(ENTRY))};\n`, + ); + } + const read = (rel: string) => readFileSync(join(dir, 'dist', rel), 'utf8'); + for (const rel of [ + 'browser/en-US/index.html', + `browser/en-US/${ENTRY}`, + 'server/en-US/index.html.mjs', + ]) { + files[rel] = read(rel); + } + const errors: unknown[] = []; + + await uploadAngularSourcemaps({ + cwd: dir, + dist: 'dist/browser/fr', + appToken: 'tok', + endpoint, + vcs: false, + registerBuild: false, + env: {}, + onError: (e) => errors.push(e), + }); + + expect(errors).toEqual([]); + expect(readFileSync(join(dir, 'dist/browser/fr', ENTRY), 'utf8')).toContain('_bugseeDebugIds'); + for (const [rel, before] of Object.entries(files)) { + expect(read(rel)).toBe(before); // the unstamped locale is byte-for-byte what Angular wrote + } + const fresh = sha384(join(dir, 'dist/browser/fr', ENTRY)); + expect(read('browser/fr/index.html')).toContain(fresh); + expect(read('server/fr/index.html.mjs')).toContain(fresh); + expect(await findIntegrityMismatches(join(dir, 'dist'))).toEqual([]); + }); + it('the guard still refuses to stamp this build WITHOUT re-sealing: the import map is seen', async () => { const { browser } = workspace('refused'); const errors: unknown[] = []; diff --git a/packages/angular/src/sourcemaps/upload.ts b/packages/angular/src/sourcemaps/upload.ts index 23ba85d52..a0efaebc5 100644 --- a/packages/angular/src/sourcemaps/upload.ts +++ b/packages/angular/src/sourcemaps/upload.ts @@ -156,10 +156,13 @@ export async function uploadAngularSourcemaps( let outDir: string; // The output ROOT whose pages must be re-sealed: an SSR build's server modules embed the page. let resealRoot: string | undefined; + // The browser directory of that root (its name is not always `browser`). + let rootBrowser: string | undefined; const probeServerRoot = (): void => { const found = findServerRoot(outDir, cwd); if (found !== undefined && 'root' in found) { resealRoot = found.root; + rootBrowser = found.browser; } else if (found !== undefined) { say(found.notice); } @@ -174,6 +177,7 @@ export async function uploadAngularSourcemaps( if (existsSync(join(base, 'browser'))) { outDir = join(base, 'browser'); resealRoot = existsSync(join(base, 'server')) ? base : undefined; + rootBrowser = outDir; } else { outDir = base; probeServerRoot(); @@ -193,6 +197,7 @@ export async function uploadAngularSourcemaps( ); } outDir = located.browserDir; + rootBrowser = outDir; resealRoot = located.serverDir !== undefined && existsSync(located.serverDir) ? located.baseDir @@ -228,7 +233,15 @@ export async function uploadAngularSourcemaps( // Only acts when the build pins script hashes; then inject runs with --allow-sri and the page is re-sealed. resealSri: true, // The server modules of an SSR build embed the page, hashes included. - resealDirs: [resealRoot ?? outDir], + resealDirs: + resealRoot === undefined || outDir === rootBrowser + ? [resealRoot ?? outDir] + : // One locale of several: stamp and re-seal only it and ITS server pages. Angular emits byte-identical + // shared scripts into every locale, so re-sealing the whole root would pin the other locales' never-stamped + // scripts to stamped digests. + [outDir, join(resealRoot, 'server', relative(rootBrowser as string, outDir))], + // Verified across the whole output root: a pin anywhere that no longer matches its file is a failure. + verifyDirs: [resealRoot ?? outDir], bundler: { isProduction, ...(configuration !== undefined ? { configuration } : {}) }, ownFiles: ownFilesOf(outDir), }); diff --git a/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts index 7ca25b400..cae74fa49 100644 --- a/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts @@ -222,6 +222,46 @@ describeReal('uploadSourcemaps re-seal rollback', () => { expect(String(errors[0])).toContain('index.html.mjs'); }); + it('verifies the page pins over every verifyDirs, and a mismatch in a later one rolls the build back', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const seen: string[] = []; + const { opts, calls, errors } = options(out, server, { + verifyDirs: [out, server], + verifySri: async (dir: string) => { + seen.push(dir); + return dir === server + ? [ + { + html: join(server, 'fr/index.html'), + script: join(server, 'fr/main.js'), + integrity: 'sha384-X', + }, + ] + : []; + }, + }); + const result = await uploadSourcemaps(opts); + expect(seen).toEqual([out, server]); + expect(snapshot(out, server)).toEqual(before); + expect(calls).not.toContain('upload'); + expect(result).toMatchObject({ injected: false, uploaded: false }); + expect(String(errors[0])).toContain('fr/main.js'); + }); + + it('verifies the output directory alone when no verifyDirs is given', async () => { + const { out, server } = build(); + const seen: string[] = []; + const { opts } = options(out, server, { + verifySri: async (dir: string) => { + seen.push(dir); + return []; + }, + }); + await uploadSourcemaps(opts); + expect(seen).toEqual([out]); + }); + it('seals a build with a real service worker manifest (control)', async () => { const { out, server } = build(); const js = readFileSync(join(out, 'main.js'), 'utf8'); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index d0d264462..69a58d3a4 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -131,6 +131,8 @@ export interface UploadSourcemapsOptions { resealSri?: boolean; /** Directories whose HTML / `.mjs` carry a copy of the hashes. Default: `[outDir]`. */ resealDirs?: readonly string[]; + /** Directories whose page pins are verified after the re-seal (default: `[outDir]`): the whole output root of an SSR build. */ + verifyDirs?: readonly string[]; /** Injectable re-sealer (default {@link resealIntegrity}). */ reseal?: typeof resealIntegrity; /** Injectable restore of one file from its spilled original, for the re-seal rollback (default: write temp, then rename). */ @@ -570,7 +572,10 @@ export async function uploadSourcemaps( let sealFailure: Error | undefined; try { await (options.reseal ?? resealIntegrity)(digests, options.resealDirs ?? [outDir]); - const broken = await (options.verifySri ?? findIntegrityMismatches)(outDir); + const broken: SriProtectedScript[] = []; + for (const dir of options.verifyDirs ?? [outDir]) { + broken.push(...(await (options.verifySri ?? findIntegrityMismatches)(dir))); + } if (broken.length > 0) { const [first] = broken as [SriProtectedScript, ...SriProtectedScript[]]; sealFailure = new Error( diff --git a/packages/bundler-plugin-core/src/resolve.test.ts b/packages/bundler-plugin-core/src/resolve.test.ts index b3a75c14e..9a1854156 100644 --- a/packages/bundler-plugin-core/src/resolve.test.ts +++ b/packages/bundler-plugin-core/src/resolve.test.ts @@ -1068,9 +1068,14 @@ describe('runPluginUpload — re-sealing', () => { ...deps, resealSri: true, resealDirs: ['/out', '/server'], + verifyDirs: ['/'], }); expect(deps.uploadSourcemaps).toHaveBeenCalledWith( - expect.objectContaining({ resealSri: true, resealDirs: ['/out', '/server'] }), + expect.objectContaining({ + resealSri: true, + resealDirs: ['/out', '/server'], + verifyDirs: ['/'], + }), ); }); @@ -1080,5 +1085,6 @@ describe('runPluginUpload — re-sealing', () => { const sent = deps.uploadSourcemaps.mock.calls[0]?.[0] as unknown as Record; expect('resealSri' in sent).toBe(false); expect('resealDirs' in sent).toBe(false); + expect('verifyDirs' in sent).toBe(false); }); }); diff --git a/packages/bundler-plugin-core/src/resolve.ts b/packages/bundler-plugin-core/src/resolve.ts index dca39e315..7d66c143f 100644 --- a/packages/bundler-plugin-core/src/resolve.ts +++ b/packages/bundler-plugin-core/src/resolve.ts @@ -281,6 +281,8 @@ export async function runPluginUpload( resealSri?: boolean; /** Directories whose HTML / `.mjs` carry a copy of the hashes. */ resealDirs?: readonly string[]; + /** Directories whose page pins are verified after the re-seal. */ + verifyDirs?: readonly string[]; /** The bundles the in-build stamp wrote (relative to the output directory), for the on-disk re-check. */ stampedBundles?: readonly string[]; /** The in-build stamp's bundle -> map names, for the on-disk re-check. */ @@ -338,6 +340,7 @@ export async function runPluginUpload( ...(deps.files !== undefined ? { files: deps.files } : {}), ...(deps.resealSri === true ? { resealSri: true } : {}), ...(deps.resealDirs !== undefined ? { resealDirs: deps.resealDirs } : {}), + ...(deps.verifyDirs !== undefined ? { verifyDirs: deps.verifyDirs } : {}), }); // AFTER the upload, because the build id is derived from the debug-ids its inject step stamps // into the bundles — and regardless of whether the maps made it, because a build exists either diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index f6ed56652..eae850e58 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -383,7 +383,7 @@ export async function findStaleDigests( before: ScriptDigests, dirs: readonly string[], ): Promise<{ file: string; script: string }[]> { - const tokens: { token: string; script: string }[] = []; + const tokens = new Map(); for (const [script, old] of before) { let bytes: Buffer; try { @@ -394,18 +394,22 @@ export async function findStaleDigests( const now = digestsOf(bytes); for (const alg of SRI_ALGORITHMS) { if (now[alg] !== old[alg]) { - tokens.push({ token: `${alg}-${old[alg]}`, script }); + tokens.set(`${alg}-${old[alg]}`, script); } } } const stale: { file: string; script: string }[] = []; - if (tokens.length === 0) { + if (tokens.size === 0) { return stale; } + // One pass per file over every digest-shaped token (exact lengths: 256 -> 43 chars + `=`, 384 -> 64, 512 -> 86 + `==`), + // looked up in a map, instead of a substring search per changed script per file. + const shaped = /sha256-[A-Za-z0-9+/]{43}=|sha384-[A-Za-z0-9+/]{64}|sha512-[A-Za-z0-9+/]{86}==/g; for (const file of await listResealFiles(dirs)) { const text = await readFile(file, 'utf8'); - for (const { token, script } of tokens) { - if (text.includes(token)) { + for (const [found] of text.matchAll(shaped)) { + const script = tokens.get(found); + if (script !== undefined) { stale.push({ file, script }); break; } From a9c0d73b7d6692457560e9488186ffab20413f64 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 17:53:32 +0500 Subject: [PATCH 36/59] fix: CI packaging guard, re-seal only when needed, no false rollback on pre-existing pins - packaging-guard: npm always packs package.json, so exporting ./package.json (which the Angular CLI needs for ng add) is not an unpacked path. Removing the export would have broken ng add. - re-seal runs only when a page pins a hash or an ngsw.json exists; page pins that were already wrong before the stamp are reported, not a failure (verified before/after). - ngsw hashTable entries are hashed by streaming, and an unreadable target is an error. - server-root: a notice only for something that looks like an Angular server output inside the project. - root-relative src pins resolve from the page's own directory up to the scanned root. Co-Authored-By: Claude Sonnet 5.5 --- .../src/publish-manifest.test.ts | 3 + .../src/sourcemaps/server-root.test.ts | 67 ++++++++++- .../angular/src/sourcemaps/server-root.ts | 23 +++- packages/angular/src/sourcemaps/upload.ts | 3 +- packages/bundler-plugin-core/src/index.ts | 1 + .../src/orchestrate.reseal-rollback.test.ts | 109 ++++++++++++++++-- .../src/orchestrate.test.ts | 10 +- .../bundler-plugin-core/src/orchestrate.ts | 43 ++++++- .../src/sri.service-worker.test.ts | 49 +++++++- packages/bundler-plugin-core/src/sri.test.ts | 35 ++++++ packages/bundler-plugin-core/src/sri.ts | 83 ++++++++++--- 11 files changed, 387 insertions(+), 39 deletions(-) diff --git a/dev-packages/packaging-guard/src/publish-manifest.test.ts b/dev-packages/packaging-guard/src/publish-manifest.test.ts index 4aec4d61a..e396af2d2 100644 --- a/dev-packages/packaging-guard/src/publish-manifest.test.ts +++ b/dev-packages/packaging-guard/src/publish-manifest.test.ts @@ -57,6 +57,9 @@ function referencedPaths(value: unknown, out: string[] = []): string[] { function isPacked(path: string, files: string[] | undefined): boolean { if (files === undefined) return true; // no allowlist: everything not ignored is packed const rel = path.replace(/^\.\//, ''); + // npm always packs package.json, whatever `files` says (as the doc comment above says). The Angular CLI resolves + // `/package.json` through `exports` for `ng add`, so a package may legitimately export it. + if (rel === 'package.json') return true; return files.some((entry) => { const clean = entry.replace(/^\.\//, '').replace(/\/$/, ''); return rel === clean || rel.startsWith(`${clean}/`); diff --git a/packages/angular/src/sourcemaps/server-root.test.ts b/packages/angular/src/sourcemaps/server-root.test.ts index dfad77694..4a03177e7 100644 --- a/packages/angular/src/sourcemaps/server-root.test.ts +++ b/packages/angular/src/sourcemaps/server-root.test.ts @@ -1,4 +1,4 @@ -import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'; +import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, win32 } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -57,7 +57,7 @@ describe('findServerRoot', () => { it('does not take an unrelated server/ for the output root, and says it could not tell', async () => { await file('o/dist/main.js'); - await dir('o/server'); + await file('o/server/server.mjs'); const found = findServerRoot(join(cwd, 'o/dist'), cwd); expect(found).toMatchObject({ notice: expect.stringContaining('browser') }); expect((found as { notice: string }).notice).toMatch(/--output-path/); @@ -65,15 +65,74 @@ describe('findServerRoot', () => { it('a custom browser directory name (outputPath.browser) is not guessed: it is said', async () => { await file('o/client/fr/main.js'); - await dir('o/server/fr'); + await file('o/server/fr/main.server.mjs'); expect(findServerRoot(join(cwd, 'o/client/fr'), cwd)).toMatchObject({ notice: expect.stringContaining('o/server'), }); }); + // A server/ that is not an Angular SSR output is nobody's business: no notice on every CI run. + it('says nothing about a hand-written server/ (Express beside Angular) or a backend next to a client dist', async () => { + await file('server/index.js'); // project root server/ + await file('dist/main.js'); + expect(findServerRoot(join(cwd, 'dist'), cwd)).toBeUndefined(); + await file('apps/dist/client/main.js'); + await file('apps/dist/server/app.js'); // a backend build, no Angular server markers + expect(findServerRoot(join(cwd, 'apps/dist/client'), cwd)).toBeUndefined(); + }); + + it.each([ + 'server.mjs', + 'main.server.mjs', + 'index.server.html', + 'angular-app-manifest.mjs', + 'angular-app-engine-manifest.mjs', + ])('recognises an Angular server output by %s', async (marker) => { + await file('o/client/main.js'); + await file(`o/server/${marker}`); + expect(findServerRoot(join(cwd, 'o/client'), cwd)).toMatchObject({ + notice: expect.any(String), + }); + }); + + it.skipIf(process.getuid?.() === 0)( + 'an unreadable server/ is not taken for an Angular one', + async () => { + await file('o/client/main.js'); + await file('o/server/server.mjs'); + await chmod(join(cwd, 'o/server'), 0o000); + try { + expect(findServerRoot(join(cwd, 'o/client'), cwd)).toBeUndefined(); + } finally { + await chmod(join(cwd, 'o/server'), 0o755); + } + }, + ); + + it('an unmatched server/ outside the project is not reported either', async () => { + const outside = await mkdtemp(join(tmpdir(), 'bugsee-ng-outside2-')); + try { + await mkdir(join(outside, 'server')); + await writeFile(join(outside, 'server', 'server.mjs'), ''); + await mkdir(join(outside, 'client')); + expect(findServerRoot(join(outside, 'client'), cwd)).toBeUndefined(); + } finally { + await rm(outside, { recursive: true, force: true }); + } + }); + + it('names the NEAREST unmatched server/ when two levels both have one', async () => { + await file('o/x/y/main.js'); + await file('o/x/server/server.mjs'); + await file('o/server/server.mjs'); + const found = findServerRoot(join(cwd, 'o/x/y'), cwd) as { notice: string }; + expect(found.notice).toContain(join(cwd, 'o/x/server')); + expect(found.notice).not.toContain(join(cwd, 'o/server')); + }); + it('looks at most two levels up: a root three levels above is not found', async () => { await file('o/browser/a/b/main.js'); - await dir('o/server'); + await file('o/server/server.mjs'); expect(findServerRoot(join(cwd, 'o/browser/a/b'), cwd)).toBeUndefined(); }); diff --git a/packages/angular/src/sourcemaps/server-root.ts b/packages/angular/src/sourcemaps/server-root.ts index 6afa592ad..560edc7e7 100644 --- a/packages/angular/src/sourcemaps/server-root.ts +++ b/packages/angular/src/sourcemaps/server-root.ts @@ -1,7 +1,7 @@ // An SSR build's server modules embed the page, SRI hashes included, so re-sealing the browser directory alone leaves // the server serving stale hashes (measured: every script blocked). When the output is named by its browser directory // (`--dist`, or `--output-path` pointing at it) the output ROOT has to be found from it. -import { lstatSync } from 'node:fs'; +import { lstatSync, readdirSync } from 'node:fs'; import * as path from 'node:path'; type PathApi = Pick; @@ -21,6 +21,23 @@ const isRealDirectory = (p: string): boolean => { } }; +/** Files an Angular SSR build writes to its server output (`server.mjs`, or the engine manifests and server entry). */ +const ANGULAR_SERVER_FILE = + /^(?:server|main\.server)\.mjs$|^index\.server\.html$|^angular-app(?:-engine)?-manifest\.mjs$/; + +/** Whether `dir` looks like Angular's server output: a marker file in it, or in a locale directory of it. */ +function looksLikeAngularServer(dir: string): boolean { + try { + return readdirSync(dir, { withFileTypes: true }).some((entry) => + entry.isDirectory() + ? readdirSync(path.join(dir, entry.name)).some((name) => ANGULAR_SERVER_FILE.test(name)) + : ANGULAR_SERVER_FILE.test(entry.name), + ); + } catch { + return false; + } +} + /** How far above the output directory the root is looked for: `browser/` -> root, `browser//` -> two. */ const MAX_LEVELS_UP = 2; @@ -41,7 +58,9 @@ export function findServerRoot(outDir: string, cwd: string, api: PathApi = path) } const browser = api.join(root, 'browser'); if (outDir !== browser && !isStrictlyInside(outDir, browser, api)) { - unmatched ??= api.join(root, 'server'); + if (isStrictlyInside(root, cwd, api) && looksLikeAngularServer(api.join(root, 'server'))) { + unmatched ??= api.join(root, 'server'); + } continue; } if (isStrictlyInside(root, cwd, api)) { diff --git a/packages/angular/src/sourcemaps/upload.ts b/packages/angular/src/sourcemaps/upload.ts index a0efaebc5..d347561fe 100644 --- a/packages/angular/src/sourcemaps/upload.ts +++ b/packages/angular/src/sourcemaps/upload.ts @@ -230,7 +230,8 @@ export async function uploadAngularSourcemaps( const run = deps.runPluginUpload ?? runPluginUpload; const result = await run(resolved, outDir, { - // Only acts when the build pins script hashes; then inject runs with --allow-sri and the page is re-sealed. + // The re-seal (digest snapshot, spill, swap, verify) runs only when a page pins a script hash or a service worker + // manifest exists; then inject runs with --allow-sri and the hashes are re-written. Otherwise it costs nothing. resealSri: true, // The server modules of an SSR build embed the page, hashes included. resealDirs: diff --git a/packages/bundler-plugin-core/src/index.ts b/packages/bundler-plugin-core/src/index.ts index 8eb108e2a..f35b2a85e 100644 --- a/packages/bundler-plugin-core/src/index.ts +++ b/packages/bundler-plugin-core/src/index.ts @@ -63,6 +63,7 @@ export { findSriProtectedScripts, findStaleDigests, findStaleServiceWorkerEntries, + hasServiceWorkerManifest, listResealFiles, resealIntegrity, type ScriptDigests, diff --git a/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts index cae74fa49..b454693a5 100644 --- a/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts @@ -49,6 +49,12 @@ function build() { return { root, out, server }; } +/** A verifier whose pins are fine until the stamp ran: the first call (before) is clean, later ones report `pins`. */ +const brokenAfterStamp = (pins: { html: string; script: string; integrity: string }[]) => { + let calls = 0; + return async () => (calls++ === 0 ? [] : pins); +}; + const snapshot = (...dirs: string[]) => Object.fromEntries( dirs.flatMap((dir) => @@ -116,9 +122,9 @@ describeReal('uploadSourcemaps re-seal rollback', () => { const { out, server } = build(); const before = snapshot(out, server); const { opts, calls, errors } = options(out, server, { - verifySri: async () => [ + verifySri: brokenAfterStamp([ { html: join(out, 'index.html'), script: join(out, 'main.js'), integrity: 'sha384-X' }, - ], + ]), }); const result = await uploadSourcemaps(opts); expect(snapshot(out, server)).toEqual(before); @@ -230,7 +236,7 @@ describeReal('uploadSourcemaps re-seal rollback', () => { verifyDirs: [out, server], verifySri: async (dir: string) => { seen.push(dir); - return dir === server + return seen.length > 2 && dir === server ? [ { html: join(server, 'fr/index.html'), @@ -242,7 +248,7 @@ describeReal('uploadSourcemaps re-seal rollback', () => { }, }); const result = await uploadSourcemaps(opts); - expect(seen).toEqual([out, server]); + expect(seen).toEqual([out, server, out, server]); // before the stamp, then after the re-seal expect(snapshot(out, server)).toEqual(before); expect(calls).not.toContain('upload'); expect(result).toMatchObject({ injected: false, uploaded: false }); @@ -259,7 +265,96 @@ describeReal('uploadSourcemaps re-seal rollback', () => { }, }); await uploadSourcemaps(opts); - expect(seen).toEqual([out]); + expect(seen).toEqual([out, out]); + }); + + // A pin that was already wrong before we touched anything (a page pinning a file another step changed) is not ours: + // it is said, and it must not roll back a re-seal that did its job. + it('does not roll back for a pin that was already broken before the stamp, and says so', async () => { + const { out, server } = build(); + writeFileSync(join(out, 'vendor.js'), 'vendor();'); + writeFileSync( + join(out, 'other.html'), + ``, + ); + const { opts, calls, errors } = options(out, server, { verifyDirs: [out] }); + const notices: string[] = []; + const result = await uploadSourcemaps({ ...opts, onNotice: (m: string) => notices.push(m) }); + expect(errors).toEqual([]); + expect(result.uploaded).toBe(true); + expect(calls).toContain('upload'); + expect(notices.join('\n')).toMatch(/even before the stamp.*vendor\.js/s); + }); + + it('still rolls back for a pin that WAS valid and is broken after', async () => { + const { out, server } = build(); + let call = 0; + const { opts, calls } = options(out, server, { + // before the stamp nothing is wrong; after the re-seal one page is + verifySri: async () => + call++ === 0 + ? [] + : [ + { + html: join(out, 'index.html'), + script: join(out, 'main.js'), + integrity: 'sha384-X', + }, + ], + }); + const result = await uploadSourcemaps(opts); + expect(result).toMatchObject({ injected: false, uploaded: false }); + expect(calls).not.toContain('upload'); + }); + + it('a pre-existing bad pin that a re-seal run cannot make worse is not a failure, but a NEW one beside it is', async () => { + const { out, server } = build(); + const old = { html: join(out, 'a.html'), script: join(out, 'v.js'), integrity: 'sha384-A' }; + const fresh = { + html: join(out, 'index.html'), + script: join(out, 'main.js'), + integrity: 'sha384-B', + }; + let call = 0; + const { opts, errors } = options(out, server, { + verifySri: async () => (call++ === 0 ? [old] : [old, fresh]), + }); + await uploadSourcemaps(opts); + expect(String(errors[0])).toContain('main.js'); + expect(String(errors[0])).not.toContain('(and'); + }); + + // The re-seal machinery (digest snapshot, a second spill of every file, the swap walk, the verify) is only worth + // its cost when something can need it: a page that pins a hash, or a service worker manifest. + it('skips the whole re-seal when nothing pins a hash and there is no service worker manifest', async () => { + const { out, server } = build(); + writeFileSync(join(out, 'index.html'), '

no pins

'); + const snapshotDigests = vi.fn(async () => new Map()); + const reseal = vi.fn(async () => ({ files: [] })); + const { opts } = options(out, server, { snapshotDigests, reseal, spillRoot: join(out, '..') }); + await uploadSourcemaps(opts); + expect(snapshotDigests).not.toHaveBeenCalled(); + expect(reseal).not.toHaveBeenCalled(); + }); + + it('still re-seals a service worker manifest when no page pins a hash', async () => { + const { out, server } = build(); + writeFileSync(join(out, 'index.html'), '

no pins

'); + const js = readFileSync(join(out, 'main.js'), 'utf8'); + writeFileSync( + join(out, 'ngsw.json'), + JSON.stringify({ hashTable: { '/main.js': createHash('sha1').update(js).digest('hex') } }), + ); + const { opts, errors } = options(out, server); + await uploadSourcemaps(opts); + expect(errors).toEqual([]); + const table = JSON.parse(readFileSync(join(out, 'ngsw.json'), 'utf8')).hashTable; + expect(table['/main.js']).toBe( + createHash('sha1') + .update(readFileSync(join(out, 'main.js'))) + .digest('hex'), + ); + expect(table['/main.js']).not.toBe(createHash('sha1').update(js).digest('hex')); }); it('seals a build with a real service worker manifest (control)', async () => { @@ -283,9 +378,9 @@ describeReal('uploadSourcemaps re-seal rollback', () => { it('names a file it could not restore', async () => { const { out, server } = build(); const { opts, errors } = options(out, server, { - verifySri: async () => [ + verifySri: brokenAfterStamp([ { html: join(out, 'index.html'), script: join(out, 'main.js'), integrity: 'sha384-X' }, - ], + ]), restoreFile: async (_spill: string, target: string) => { throw new Error(`EPERM on ${target}`); }, diff --git a/packages/bundler-plugin-core/src/orchestrate.test.ts b/packages/bundler-plugin-core/src/orchestrate.test.ts index aaa2df7fd..25b0b2515 100644 --- a/packages/bundler-plugin-core/src/orchestrate.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.test.ts @@ -876,6 +876,12 @@ describe("a run over the build's own files", () => { // A build whose only copies of its script hashes are in its HTML (Angular's esbuild builder) can be stamped // after emit, if the hashes are then re-written to match: inject runs with `--allow-sri`, the pages are // re-sealed, and the result is verified. The guard that refuses a hashed build stays for every other caller. +/** Clean before the stamp (first call), reports `pins` afterwards. */ +const afterStamp = (pins: { html: string; script: string; integrity: string }[]) => { + let calls = 0; + return async () => (calls++ === 0 ? [] : pins); +}; + describe('uploadSourcemaps with resealSri', () => { const pin = { html: '/build/dist/index.html', @@ -953,7 +959,7 @@ describe('uploadSourcemaps with resealSri', () => { it('reports a page that still does not verify, restores, and uploads nothing', async () => { const { run, calls } = fakeRun(); const onError = vi.fn(); - await uploadSourcemaps({ ...sealed({ verifySri: async () => [pin] }), run, onError }); + await uploadSourcemaps({ ...sealed({ verifySri: afterStamp([pin]) }), run, onError }); expect(String(onError.mock.calls[0]?.[0])).toContain('index.html'); expect(String(onError.mock.calls[0]?.[0])).toContain('main.js'); expect(calls.map((c) => c.args[0])).not.toContain('debug-files'); @@ -963,7 +969,7 @@ describe('uploadSourcemaps with resealSri', () => { const { run } = fakeRun(); await expect( uploadSourcemaps({ - ...sealed({ verifySri: async () => [pin, pin] }), + ...sealed({ verifySri: afterStamp([pin, pin]) }), run, failOnError: true, }), diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 69a58d3a4..990810f60 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -11,6 +11,7 @@ import { findSriProtectedScripts, findStaleDigests, findStaleServiceWorkerEntries, + hasServiceWorkerManifest, listResealFiles, resealIntegrity, type SriProtectedScript, @@ -133,6 +134,8 @@ export interface UploadSourcemapsOptions { resealDirs?: readonly string[]; /** Directories whose page pins are verified after the re-seal (default: `[outDir]`): the whole output root of an SSR build. */ verifyDirs?: readonly string[]; + /** Injectable: does any directory hold a service worker manifest (default {@link hasServiceWorkerManifest}). */ + hasServiceWorker?: (dirs: readonly string[]) => Promise; /** Injectable re-sealer (default {@link resealIntegrity}). */ reseal?: typeof resealIntegrity; /** Injectable restore of one file from its spilled original, for the re-seal rollback (default: write temp, then rename). */ @@ -501,10 +504,29 @@ export async function uploadSourcemaps( // 0a. The digest of every script as the build emitted it, for the re-seal: the stale hashes are found by // what the files WERE, wherever a copy sits (a tag, an import map, a table in the runtime chunk). Not // on a dry run: nothing is written. - const digests = - resealing && !dryRun - ? await (options.snapshotDigests ?? snapshotScriptDigests)([outDir]) - : undefined; + // Only when something can need it: a page that pins a hash (`pinned`), or a service worker manifest. + // Without either, the snapshot, the second spill, the swap walk and the verify would be pure cost. + const sealDirs = options.resealDirs ?? [outDir]; + const needsReseal = + resealing && + !dryRun && + (pinned.length > 0 || + (await (options.hasServiceWorker ?? hasServiceWorkerManifest)(sealDirs))); + const digests = needsReseal + ? await (options.snapshotDigests ?? snapshotScriptDigests)([outDir]) + : undefined; + const verifyDirs = options.verifyDirs ?? [outDir]; + const verify = options.verifySri ?? findIntegrityMismatches; + const pinKey = (pin: SriProtectedScript): string => `${pin.html}\0${pin.script}`; + // Pins that were wrong BEFORE we touched anything are not ours to fail on. + const preExisting = new Set(); + if (digests !== undefined) { + for (const dir of verifyDirs) { + for (const pin of await verify(dir)) { + preExisting.add(pinKey(pin)); + } + } + } // 0a'. Everything the stamp AND the re-seal may write — scripts, maps, pages, server modules — so a re-seal // that fails can put the build back exactly as the bundler emitted it (the stamp's own snapshot below @@ -573,8 +595,17 @@ export async function uploadSourcemaps( try { await (options.reseal ?? resealIntegrity)(digests, options.resealDirs ?? [outDir]); const broken: SriProtectedScript[] = []; - for (const dir of options.verifyDirs ?? [outDir]) { - broken.push(...(await (options.verifySri ?? findIntegrityMismatches)(dir))); + const already: SriProtectedScript[] = []; + for (const dir of verifyDirs) { + for (const pin of await verify(dir)) { + (preExisting.has(pinKey(pin)) ? already : broken).push(pin); + } + } + if (already.length > 0) { + (options.onNotice ?? ((m: string) => console.warn(`[bugsee] ${m}`)))( + `${already.length} integrity pin(s) did not match their file even before the stamp (for example ` + + `${already[0]?.html} pins ${already[0]?.script}), so they were left as they were and are not a result of this step`, + ); } if (broken.length > 0) { const [first] = broken as [SriProtectedScript, ...SriProtectedScript[]]; diff --git a/packages/bundler-plugin-core/src/sri.service-worker.test.ts b/packages/bundler-plugin-core/src/sri.service-worker.test.ts index bea51f830..43b2ea376 100644 --- a/packages/bundler-plugin-core/src/sri.service-worker.test.ts +++ b/packages/bundler-plugin-core/src/sri.service-worker.test.ts @@ -3,7 +3,7 @@ // corrupt and stops serving it. Measured on @angular/build 22.3 + @angular/service-worker: every entry is // sha1(file bytes), the key is the path from the manifest's directory, and the file is formatted JSON. import { createHash } from 'node:crypto'; -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; @@ -57,6 +57,21 @@ describe('findStaleDigests', () => { expect(await findStaleDigests(before, [root])).toEqual([]); }); + it('lists a file once even when it holds the old digests of several changed scripts', async () => { + await write('a.js', 'a();'); + await write('b.js', 'b();'); + const page = await write( + 'index.html', + `sha384-${sha('sha384', 'a();')} sha384-${sha('sha384', 'b();')}`, + ); + const before = await snapshotScriptDigests([root]); + await write('a.js', 'a2();'); + await write('b.js', 'b2();'); + expect(await findStaleDigests(before, [root])).toEqual([ + { file: page, script: expect.stringMatching(/[ab]\.js$/) }, + ]); + }); + it('says nothing when no script changed, or a changed script is gone', async () => { await write('browser/main.js', 'a();'); await write('browser/index.html', `sha384-${sha('sha384', 'a();')}`); @@ -149,6 +164,38 @@ describe('service worker manifests', () => { expect(await findStaleServiceWorkerEntries([root])).toEqual([]); }); + it('hashes a large listed asset by streaming it (no whole-file buffer), and still reconciles it', async () => { + const big = Buffer.alloc(3 * 1024 * 1024, 7); + await mkdir(join(root, 'media'), { recursive: true }); + await writeFile(join(root, 'media/clip.bin'), big); + await write('ngsw.json', manifest({ '/media/clip.bin': 'stale' })); + expect(await findStaleServiceWorkerEntries([root])).toHaveLength(1); + await resealIntegrity(new Map(), [root]); + expect(await readFile(join(root, 'ngsw.json'), 'utf8')).toContain( + createHash('sha1').update(big).digest('hex'), + ); + }); + + it('an entry that names a directory is skipped, like one whose file is gone', async () => { + await mkdir(join(root, 'assets'), { recursive: true }); + await write('ngsw.json', manifest({ '/assets': 'x' })); + expect(await findStaleServiceWorkerEntries([root])).toEqual([]); + }); + + it.skipIf(process.getuid?.() === 0)( + 'a file it cannot read is an error, not a silent skip', + async () => { + const secret = await write('locked.js', 'x'); + await write('ngsw.json', manifest({ '/locked.js': sha1('x') })); + await chmod(secret, 0o000); + try { + await expect(findStaleServiceWorkerEntries([root])).rejects.toThrow(/EACCES/); + } finally { + await chmod(secret, 0o644); + } + }, + ); + it('does not look in node_modules, and does not follow a key out of the manifest directory', async () => { await write('node_modules/p/ngsw.json', manifest({ '/m.js': 'x' })); await write('outside.js', 'o'); diff --git a/packages/bundler-plugin-core/src/sri.test.ts b/packages/bundler-plugin-core/src/sri.test.ts index ed7d50e13..301f8e8de 100644 --- a/packages/bundler-plugin-core/src/sri.test.ts +++ b/packages/bundler-plugin-core/src/sri.test.ts @@ -346,6 +346,41 @@ describe('findSriProtectedScripts', () => { ]); }); + it('resolves a root-relative src against the directory the page was built into when it is not at the scanned root', async () => { + // Scanning an SSR output root: browser/index.html says `/main.js`, which is browser/main.js, not /main.js. + const dir = await fixture(); + await write(dir, 'browser/main.js', 'a'); + await write(dir, 'browser/fr/chunk.js', 'b'); + await write(dir, 'browser/index.html', ''); + await write( + dir, + 'browser/fr/index.html', + '', + ); + await write(dir, 'top.html', ''); + const scripts = (await findSriProtectedScripts(dir)).map((p) => p.script).sort(); + // top.html's `/main.js` is the scanned root's own (absent) file; the two nested pages find theirs by looking up. + expect(scripts).toEqual( + [join(dir, 'browser/fr/chunk.js'), join(dir, 'browser/main.js'), join(dir, 'main.js')].sort(), + ); + }); + + it('never looks above the scanned root for a root-relative src', async () => { + const dir = await fixture(); + await write(dir, 'main.js', 'outside the scanned directory'); + await write(dir, 'browser/index.html', ''); + const found = await findSriProtectedScripts(join(dir, 'browser')); + expect(found.map((p) => p.script)).toEqual([join(dir, 'browser', 'main.js')]); + }); + + it('a root-relative src that exists nowhere keeps its scanned-root path (a stale pin, as before)', async () => { + const dir = await fixture(); + await write(dir, 'browser/index.html', ''); + expect((await findSriProtectedScripts(dir)).map((p) => p.script)).toEqual([ + join(dir, 'gone.js'), + ]); + }); + it('does not treat a SIBLING directory with a shared prefix as inside the output', async () => { const root = await fixture(); const outDir = join(root, 'dist'); diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index eae850e58..f67291074 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -15,9 +15,9 @@ // runtime chunk (`__webpack_require__.sriHashes`), so patching the HTML alone would still break // every dynamic import. import { createHash } from 'node:crypto'; -import type { Dirent } from 'node:fs'; -import { readdir, readFile, writeFile } from 'node:fs/promises'; -import { dirname, isAbsolute, join, normalize, resolve, sep } from 'node:path'; +import { createReadStream, type Dirent } from 'node:fs'; +import { access, readdir, readFile, writeFile } from 'node:fs/promises'; +import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path'; /** One `'); + await write('server/server.mjs', ''); + const runPluginUpload = ran(); + const out = await uploadAngularSourcemaps(base({ cwd, dist: 'browser' }), { + runPluginUpload, + }); + expect(out.status).toBe('misconfigured'); + expect(runPluginUpload).not.toHaveBeenCalled(); + }); + + it('the project root as output root WITHOUT pins is only said, and still uploads', async () => { + await write('browser/main.js', 'x();'); + await write('server/server.mjs', ''); + const runPluginUpload = ran(); + const notices: string[] = []; + const out = await uploadAngularSourcemaps( + base({ cwd, dist: 'browser', onNotice: (m: string) => notices.push(m) }), + { runPluginUpload }, + ); + expect(out.status).toBe('uploaded'); + expect(notices.join('\n')).toMatch(/project root/); + }); + it('--output-path points at the base of an application build, and at a flat one', async () => { await write('moved/browser/main.js', 'x();'); await write('moved/browser/main.js.map', '{}'); diff --git a/packages/angular/src/sourcemaps/upload.ts b/packages/angular/src/sourcemaps/upload.ts index d347561fe..c4304e0dc 100644 --- a/packages/angular/src/sourcemaps/upload.ts +++ b/packages/angular/src/sourcemaps/upload.ts @@ -9,11 +9,12 @@ // hashes in its runtime chunk. Stamping the scripts afterwards changes their bytes, so every digest of a changed // script is re-written wherever it appears (`resealSri`, bundler-plugin-core), and a build that cannot be re-sealed // is restored. Measured on real @angular/build 22.3 and build-angular 19.2 builds; see docs/design/source-maps.md §7.1. -import { existsSync, readdirSync } from 'node:fs'; +import { existsSync, readdirSync, statSync } from 'node:fs'; import { join, relative, resolve } from 'node:path'; import { type BugseePluginOptions, type EnvRecord, + findSriProtectedScripts, isFencedPath, loadBuildPluginEnv, mergeBuildPluginEnv, @@ -23,7 +24,7 @@ import { runPluginUpload, } from '@bugsee/bundler-plugin-core'; import { type AngularOutput, resolveAngularOutput } from './output'; -import { findServerRoot } from './server-root'; +import { findServerRoot, looksLikeAngularServer } from './server-root'; export interface AngularUploadOptions extends BugseePluginOptions { /** Workspace directory (angular.json is looked for here and above). Default: the working directory. */ @@ -158,13 +159,15 @@ export async function uploadAngularSourcemaps( let resealRoot: string | undefined; // The browser directory of that root (its name is not always `browser`). let rootBrowser: string | undefined; + // An SSR output root that could not be located safely: its server copies of the page are not re-sealed. + let unsafeNotice: string | undefined; const probeServerRoot = (): void => { const found = findServerRoot(outDir, cwd); if (found !== undefined && 'root' in found) { resealRoot = found.root; rootBrowser = found.browser; } else if (found !== undefined) { - say(found.notice); + unsafeNotice = found.notice; // said if the run goes on, part of the refusal if it cannot } }; if (options.dist !== undefined) { @@ -180,6 +183,15 @@ export async function uploadAngularSourcemaps( rootBrowser = outDir; } else { outDir = base; + if (looksLikeAngularServer(join(base, 'server'))) { + // `` holds the server beside a client directory with another name: stamping it would stamp the server. + return misconfigured( + `${base} holds an Angular server output beside its browser output, and the browser directory is not named ` + + `browser/, so the whole of it would be stamped. Give the browser directory itself with --dist.`, + base, + options.configuration, + ); + } probeServerRoot(); } } else { @@ -213,6 +225,21 @@ export async function uploadAngularSourcemaps( configuration, ); } + if (!statSync(outDir).isDirectory()) { + return misconfigured(`the build output ${outDir} is not a directory.`, outDir, configuration); + } + if (unsafeNotice !== undefined) { + if ((await findSriProtectedScripts(outDir)).length > 0) { + // The browser pages pin script hashes and the server copies of them cannot be re-sealed: stamping would leave + // server-rendered pages pinning the old hashes (every script blocked). + return misconfigured( + `${unsafeNotice} The browser pages pin script hashes, so nothing was stamped.`, + outDir, + configuration, + ); + } + say(unsafeNotice); + } const isProduction = !(configuration?.split(',').includes('development') ?? false); if (!isProduction && !resolved.uploadInDevelopment) { say( diff --git a/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts index b454693a5..6ea1991fd 100644 --- a/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts @@ -170,6 +170,24 @@ describeReal('uploadSourcemaps re-seal rollback', () => { expect(readdirSync(spillRoot)).toEqual([]); }); + it('still reports the inject failure when putting the files back also fails', async () => { + const { out, server } = build(); + const { opts, errors } = options(out, server, { + restoreFile: async () => { + throw new Error('EPERM'); + }, + run: async (args: string[], o: Parameters[1]) => { + if (args[1] === 'inject') { + await runBugseeCli(args, o); + throw new Error('bugsee-cli exited 1 on a later file'); + } + return { code: 0, stdout: '', stderr: '' }; + }, + }); + await uploadSourcemaps(opts); + expect(String(errors[0])).toContain('later file'); + }); + it('throws the failure under failOnError, after restoring', async () => { const { out, server } = build(); const before = snapshot(out, server); @@ -326,12 +344,45 @@ describeReal('uploadSourcemaps re-seal rollback', () => { // The re-seal machinery (digest snapshot, a second spill of every file, the swap walk, the verify) is only worth // its cost when something can need it: a page that pins a hash, or a service worker manifest. + it('does NOT skip the re-seal when it covers more than the output directory: the server modules may hold the pin', async () => { + const { out, server } = build(); + writeFileSync(join(out, 'index.html'), '

no pins

'); // only the server module embeds a page + const snapshotDigests = vi.fn(async () => new Map()); + const { opts } = options(out, server, { snapshotDigests, resealDirs: [out, server] }); + await uploadSourcemaps(opts); + expect(snapshotDigests).toHaveBeenCalled(); + }); + + it('puts every byte back when inject fails AFTER it stamped (a later batch fails): no stamped bundle against an un-sealed page', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts, calls, errors } = options(out, server, { + run: async (args: string[], o: Parameters[1]) => { + if (args[1] === 'inject') { + await runBugseeCli(args, o); // stamped on disk... + throw new Error('bugsee-cli exited 1 on a later file'); // ...then the command fails + } + return { code: 0, stdout: '', stderr: '' }; + }, + }); + const result = await uploadSourcemaps(opts); + expect(snapshot(out, server)).toEqual(before); + expect(calls).not.toContain('upload'); + expect(result).toMatchObject({ injected: false, uploaded: false }); + expect(String(errors[0])).toContain('later file'); + }); + it('skips the whole re-seal when nothing pins a hash and there is no service worker manifest', async () => { const { out, server } = build(); writeFileSync(join(out, 'index.html'), '

no pins

'); const snapshotDigests = vi.fn(async () => new Map()); const reseal = vi.fn(async () => ({ files: [] })); - const { opts } = options(out, server, { snapshotDigests, reseal, spillRoot: join(out, '..') }); + const { opts } = options(out, server, { + snapshotDigests, + reseal, + resealDirs: [out], + spillRoot: join(out, '..'), + }); await uploadSourcemaps(opts); expect(snapshotDigests).not.toHaveBeenCalled(); expect(reseal).not.toHaveBeenCalled(); @@ -345,7 +396,7 @@ describeReal('uploadSourcemaps re-seal rollback', () => { join(out, 'ngsw.json'), JSON.stringify({ hashTable: { '/main.js': createHash('sha1').update(js).digest('hex') } }), ); - const { opts, errors } = options(out, server); + const { opts, errors } = options(out, server, { resealDirs: [out] }); await uploadSourcemaps(opts); expect(errors).toEqual([]); const table = JSON.parse(readFileSync(join(out, 'ngsw.json'), 'utf8')).hashTable; diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index c8d15a892..57d3a4e39 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -564,7 +564,10 @@ export async function uploadSourcemaps( const needsReseal = resealing && !dryRun && + // A re-seal that covers more than the output directory (an SSR build's server modules) cannot be skipped on + // what the output directory's HTML shows: a server module may be the only place that embeds a pinned page. (pinned.length > 0 || + sealDirs.some((dir) => resolve(dir) !== resolve(outDir)) || (await (options.hasServiceWorker ?? hasServiceWorkerManifest)(sealDirs))); const digests = needsReseal ? await (options.snapshotDigests ?? snapshotScriptDigests)([outDir]) @@ -627,6 +630,11 @@ export async function uploadSourcemaps( } 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. + // When the pages were meant to be re-sealed, a stamp that stays on disk would sit against pages still pinning + // the old hashes (a blocked page): put EVERYTHING the stamp or the re-seal could write back first. + if (sealOriginal !== undefined) { + await restoreChanged(sealOriginal, options.restoreFile); // never throws: failures come back listed, the inject error below wins + } if (original !== undefined) { let note: string | undefined; try { From 081e5009580591cca9605aa74a74721b14780db0 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 22:34:09 +0500 Subject: [PATCH 52/59] fix(bundler-plugin-core): report a failed restore after inject failure; scan server dirs for digests instead of always re-sealing Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- packages/bundler-plugin-core/src/index.ts | 1 + .../src/orchestrate.reseal-rollback.test.ts | 30 ++++++++++++++ .../bundler-plugin-core/src/orchestrate.ts | 41 +++++++++++++------ packages/bundler-plugin-core/src/sri.ts | 14 +++++++ 4 files changed, 74 insertions(+), 12 deletions(-) diff --git a/packages/bundler-plugin-core/src/index.ts b/packages/bundler-plugin-core/src/index.ts index e66fcc532..6d3b60d6c 100644 --- a/packages/bundler-plugin-core/src/index.ts +++ b/packages/bundler-plugin-core/src/index.ts @@ -66,6 +66,7 @@ export { findSriProtectedScripts, findStaleDigests, findStaleServiceWorkerEntries, + hasDigestTokens, hasServiceWorkerManifest, listResealFiles, resealIntegrity, diff --git a/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts index 6ea1991fd..53a8e88b2 100644 --- a/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts @@ -344,6 +344,36 @@ describeReal('uploadSourcemaps re-seal rollback', () => { // The re-seal machinery (digest snapshot, a second spill of every file, the swap walk, the verify) is only worth // its cost when something can need it: a page that pins a hash, or a service worker manifest. + it('skips the re-seal for an SSR layout too when no page and no server module holds a digest and there is no manifest', async () => { + const { out, server } = build(); + writeFileSync(join(out, 'index.html'), '

no pins

'); + writeFileSync(join(server, 'index.html.mjs'), 'export default "

no pins

";'); + const snapshotDigests = vi.fn(async () => new Map()); + const { opts } = options(out, server, { snapshotDigests, resealDirs: [out, server] }); + await uploadSourcemaps(opts); + expect(snapshotDigests).not.toHaveBeenCalled(); + }); + + it('reports a file it could not put back after a failed inject, naming it', async () => { + const { out, server } = build(); + const { opts, errors } = options(out, server, { + restoreFile: async (_spill: string, target: string) => { + throw new Error(`EBUSY ${target}`); + }, + run: async (args: string[], o: Parameters[1]) => { + if (args[1] === 'inject') { + await runBugseeCli(args, o); + throw new Error('bugsee-cli exited 1 on a later file'); + } + return { code: 0, stdout: '', stderr: '' }; + }, + }); + await uploadSourcemaps(opts); + const message = String(errors[0]); + expect(message).toContain('later file'); + expect(message).toMatch(/COULD NOT restore.*EBUSY.*still stamped/s); + }); + it('does NOT skip the re-seal when it covers more than the output directory: the server modules may hold the pin', async () => { const { out, server } = build(); writeFileSync(join(out, 'index.html'), '

no pins

'); // only the server module embeds a page diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 57d3a4e39..ab9be15a7 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -11,6 +11,7 @@ import { findSriProtectedScripts, findStaleDigests, findStaleServiceWorkerEntries, + hasDigestTokens, hasServiceWorkerManifest, listResealFiles, resealIntegrity, @@ -145,6 +146,8 @@ export interface UploadSourcemapsOptions { verifyDirs?: readonly string[]; /** Injectable: does any directory hold a service worker manifest (default {@link hasServiceWorkerManifest}). */ hasServiceWorker?: (dirs: readonly string[]) => Promise; + /** Injectable: does any file under these directories hold an SRI digest (default {@link hasDigestTokens}). */ + hasDigestTokens?: (dirs: readonly string[]) => Promise; /** Injectable re-sealer (default {@link resealIntegrity}). */ reseal?: typeof resealIntegrity; /** Injectable restore of one file from its spilled original, for the re-seal rollback (default: write temp, then rename). */ @@ -565,9 +568,12 @@ export async function uploadSourcemaps( resealing && !dryRun && // A re-seal that covers more than the output directory (an SSR build's server modules) cannot be skipped on - // what the output directory's HTML shows: a server module may be the only place that embeds a pinned page. + // what the output directory's HTML shows alone: a server module may embed a pinned page, so those directories + // are scanned (cheaply, for a digest-shaped token) rather than assumed to need it. (pinned.length > 0 || - sealDirs.some((dir) => resolve(dir) !== resolve(outDir)) || + (await (options.hasDigestTokens ?? hasDigestTokens)( + sealDirs.filter((dir) => resolve(dir) !== resolve(outDir)), + )) || (await (options.hasServiceWorker ?? hasServiceWorkerManifest)(sealDirs))); const digests = needsReseal ? await (options.snapshotDigests ?? snapshotScriptDigests)([outDir]) @@ -632,19 +638,30 @@ export async function uploadSourcemaps( // restore them BEFORE the failure propagates, so no unverified stamp stays on disk. // When the pages were meant to be re-sealed, a stamp that stays on disk would sit against pages still pinning // the old hashes (a blocked page): put EVERYTHING the stamp or the re-seal could write back first. + let sealNote: string | undefined; if (sealOriginal !== undefined) { - await restoreChanged(sealOriginal, options.restoreFile); // never throws: failures come back listed, the inject error below wins + const undone = await restoreChanged(sealOriginal, options.restoreFile); // never throws: failures come back listed + if (undone.failed.length > 0) { + sealNote = `COULD NOT restore ${undone.failed.map((f) => `${f.path} (${f.error})`).join(', ')}, which are still stamped against integrity hashes that were not updated`; + } } - 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. - note = verifyFailure(issues, restored, failed).message; + { + let note: string | undefined = sealNote; + const addNote = (text: string): void => { + note = note === undefined ? text : `${note}; ${text}`; + }; + if (original !== undefined) { + try { + const { issues, restored, failed } = await verifyAndRestore(original); + if (failed.length > 0) { + // Files still carry the unverified rewrite: that must not go unmentioned. + addNote(verifyFailure(issues, restored, failed).message); + } + } catch (restoreError) { + addNote( + `restoring the originals also failed: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, + ); } - } catch (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. diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index f67291074..653629f54 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -444,6 +444,20 @@ export async function findStaleDigests( return stale; } +/** + * Whether any re-sealable file under `dirs` holds an SRI digest (`sha256-` / `sha384-` / `sha512-` plus base64 of the + * right length): a cheap check of whether a copy of a page's pins could be there at all. + */ +export async function hasDigestTokens(dirs: readonly string[]): Promise { + const shaped = /sha256-[A-Za-z0-9+/]{43}=|sha384-[A-Za-z0-9+/]{64}|sha512-[A-Za-z0-9+/]{86}==/; + for (const file of await listResealFiles(dirs)) { + if (shaped.test(await readFile(file, 'utf8'))) { + return true; + } + } + return false; +} + /** Whether any directory holds an `ngsw.json`: the one thing besides a pinned hash that a re-seal has to fix. */ export async function hasServiceWorkerManifest(dirs: readonly string[]): Promise { for (const dir of dirs) { From dd5b68c3cbf4c8d77c2d1646b0976d0c118246ea Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 13:59:15 +0500 Subject: [PATCH 53/59] fix(bundler-plugin-core): address PR review (generate-only, standalone map id, webpack dev, test strength) - Skip in-build stamping entirely for generate()-only outputs (isWrite === false): no CLI spawn, no staging, no failOnError throw for a build that never writes. - verifyAndRestore: a standalone changed map is now verified against its unchanged, already-stamped bundle's debug-ID (the bundle is resolved via sourceMappingURL / .map) and restored on mismatch. - webpack 5: skip in-build stamping for development builds that are not uploaded, sharing the expression with Rspack (isUnuploadedDevelopment). - stamp-assets tests: assert the exact claim message; drop the constant ternary. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- docs/design/source-maps.md | 8 ++- .../src/plugin.in-build.real-build.test.ts | 32 +++++++++ .../src/plugin.stamp.test.ts | 19 ++++++ packages/bundler-plugin-core/src/plugin.ts | 36 +++++----- .../src/plugin.upload.test.ts | 23 +++++++ .../src/stamp-assets.test.ts | 9 ++- .../src/stamp-files.test.ts | 68 +++++++++++++++++++ .../bundler-plugin-core/src/stamp-files.ts | 27 +++++--- 8 files changed, 189 insertions(+), 33 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 8fa6e725e..f5028a951 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -341,7 +341,8 @@ already written and finished in this build (its names stay known to later output `deleteMaps: false` its maps left on disk are not uploaded a second time) (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 +cannot make a later unmapped write pass silently, and it is not stamped at all (it never reaches `writeBundle`, so no CLI is spawned and +`failOnError` cannot fail a build that writes nothing). **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. @@ -423,8 +424,9 @@ source and so are deleted with them (as on the post-emit and `files` paths). A s was uploaded and the upload was confirmed: an unkeyed or unreadable one is never deleted, and nothing the walk merely saw is (a keyed map under `test/` or a dot-directory is uploaded AND deleted). The stylesheet and declaration maps are deleted only if something was uploaded. A map that cannot be read (anything but ENOENT) is -not "gone": it is neither uploaded nor deleted and is reported with the unkeyed ones. A dry run still passes the directory (nothing was stamped; `--dry-run` only warns). Rspack development -builds that are not uploaded (`uploadInDevelopment` unset) are no longer stamped either. Covered by real builds +not "gone": it is neither uploaded nor deleted and is reported with the unkeyed ones. A dry run still passes the directory (nothing was stamped; `--dry-run` only warns). Rspack and webpack development +builds that are not uploaded (`uploadInDevelopment` unset) are no longer stamped either. A map rewritten beside an unchanged, already-stamped +bundle is held to that bundle's debug-ID (and restored if it differs) on the post-emit path. Covered by real builds (`plugin.in-build.real-build.test.ts`: Vite 7/8 with a `publicDir` vendor script, Rollup with a stale one, and `[name].map` custom map names on Rollup, Vite 7/8 and Rspack; real CLI, no dry run, `failOnError` on and off). Not run for real: webpack itself (Rspack shares its SourceMapDevToolPlugin filename path). 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 dd9956584..7fc9455fb 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 @@ -1370,6 +1370,38 @@ describeReal('a generate()-only output is not a sibling', () => { }); }); +describeReal('a generate()-only output is not stamped', () => { + it('bundle.generate() with a missing CLI does not spawn it or fail under failOnError, while write() still fails', async () => { + const app = makeApp('rollup-generate-nocli', { lazy: false }); + const saved = process.env.BUGSEE_CLI_PATH; + process.env.BUGSEE_CLI_PATH = join(app.dir, 'no-such-bugsee-cli'); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin({ ...pluginOptions(), failOnError: true })], + }); + try { + const generated = await bundle.generate({ + dir: app.out, + format: 'iife', + name: 'g', + sourcemap: true, + }); + expect(generated.output.length).toBeGreaterThan(0); + // the same build that WRITES is stamped, so the missing CLI is a hard failure there + await expect( + bundle.write({ dir: app.out, format: 'iife', name: 'w', sourcemap: true }), + ).rejects.toThrow(); + } finally { + if (saved === undefined) { + delete process.env.BUGSEE_CLI_PATH; + } else { + process.env.BUGSEE_CLI_PATH = saved; + } + 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 }); diff --git a/packages/bundler-plugin-core/src/plugin.stamp.test.ts b/packages/bundler-plugin-core/src/plugin.stamp.test.ts index e6f6eebc3..659089a10 100644 --- a/packages/bundler-plugin-core/src/plugin.stamp.test.ts +++ b/packages/bundler-plugin-core/src/plugin.stamp.test.ts @@ -1013,6 +1013,25 @@ describe('outputs announce their names at generateBundle, so the first write alr expect(siblingsOf(0)).toEqual([]); }); + it(`${kind}: a generate()-only output (isWrite false) is not stamped at all: no CLI, no staging, no failOnError throw`, async () => { + stampSpy.mockReset(); + stampSpy.mockImplementation(async () => { + throw new Error('bugsee-cli is missing'); + }); + const strict = makePlugin({ appToken: 'tok', failOnError: true, onNotice: () => undefined })[ + kind + ] as unknown as ReturnType; + await expect( + strict.generateBundle.handler({ dir: '/out' }, bundleOf('g'), false), + ).resolves.toBeUndefined(); + expect(stampSpy).not.toHaveBeenCalled(); + // the same output that WILL write is stamped, and its failure surfaces under failOnError + await expect( + strict.generateBundle.handler({ dir: '/out' }, bundleOf('g'), true), + ).rejects.toThrow(/bugsee-cli is missing/); + expect(stampSpy).toHaveBeenCalledOnce(); + }); + it(`${kind}: an output written into a NESTED directory is a sibling under its relative path`, 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 ac024b5c7..0e9138602 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -436,6 +436,9 @@ export const bugseeUnpluginFactory: UnpluginFactory + compiler.options.mode === 'development' && !resolved.uploadInDevelopment; // `resolved` is assigned right below; `loadFile` only reads it after that (it is `let` for the hook refresh). let resolved = resolvePluginOptions(options, process.env); let env = mergeBuildPluginEnv(process.env, loadFile(undefined)); @@ -586,18 +589,18 @@ export const bugseeUnpluginFactory: UnpluginFactory => { + // `bundle.generate()` / Vite `build({ write: false })` (isWrite === false) never reaches writeBundle, so + // nothing consumes a stamp: spawning the CLI (and, under failOnError, throwing) would be pure cost for a + // build that writes nothing. It is not announced either: as a stale sibling it would hide maps that + // belong to nobody. const outDir = resolveOutputDir(output); - if (outDir === undefined || !resolved.enabled) { + if (isWrite === false || outDir === undefined || !resolved.enabled) { return; } const key = dirKey(outDir); - // 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); - } + 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) { @@ -901,20 +904,13 @@ export const bugseeUnpluginFactory: UnpluginFactory { const dir = compiler.options.output?.path; diff --git a/packages/bundler-plugin-core/src/plugin.upload.test.ts b/packages/bundler-plugin-core/src/plugin.upload.test.ts index bfc8618e5..bfb013fa9 100644 --- a/packages/bundler-plugin-core/src/plugin.upload.test.ts +++ b/packages/bundler-plugin-core/src/plugin.upload.test.ts @@ -242,6 +242,29 @@ describe('the output hooks actually drive the upload', () => { expect(stampSpy).toHaveBeenCalledOnce(); }); + it('does not stamp a development build that is not uploaded, and does when uploadInDevelopment is set', async () => { + const dev = webpack5Compiler({ mode: 'development' }); + apply({ appToken: 'tok', onNotice: () => undefined }, dev.compiler); + await dev.compile(); + expect(dev.processAssets).toHaveLength(0); + expect(stampSpy).not.toHaveBeenCalled(); + + const optIn = webpack5Compiler({ mode: 'development' }); + apply({ appToken: 'tok', uploadInDevelopment: true }, optIn.compiler); + await optIn.compile(); + expect(optIn.processAssets).toHaveLength(1); + expect(stampSpy).toHaveBeenCalledOnce(); + + for (const mode of ['production', 'none', undefined]) { + stampSpy.mockClear(); + const w = webpack5Compiler(mode === undefined ? {} : { mode }); + apply({ appToken: 'tok' }, w.compiler); + await w.compile(); + expect(w.processAssets).toHaveLength(1); + expect(stampSpy).toHaveBeenCalledOnce(); + } + }); + it('then uploads WITHOUT re-injecting after emit', async () => { const w = webpack5Compiler({ mode: 'production' }); apply({ appToken: 'tok' }, w.compiler); diff --git a/packages/bundler-plugin-core/src/stamp-assets.test.ts b/packages/bundler-plugin-core/src/stamp-assets.test.ts index 90e4d0a5a..9da260da7 100644 --- a/packages/bundler-plugin-core/src/stamp-assets.test.ts +++ b/packages/bundler-plugin-core/src/stamp-assets.test.ts @@ -732,7 +732,7 @@ describe('stampAssets — two bundles that claim the same map', () => { mapOf: () => 'shared.map', }; await expect(stampAssets(store, { run })).rejects.toThrow( - /shared\.map.*a\.js.*b\.js|shared\.map/, + 'the map shared.map is claimed by more than one bundle (a.js and b.js), so it cannot be stamped', ); expect(run).not.toHaveBeenCalled(); }); @@ -743,9 +743,12 @@ describe("stampAssets — a map that is another bundle's own sibling is claimed 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'), + // both bundles name a.js.map: it is a.js's own sibling, and b.js claims it too + mapOf: () => 'a.js.map', }; - await expect(stampAssets(store, { run })).rejects.toThrow(/a\.js\.map.*claimed/); + await expect(stampAssets(store, { run })).rejects.toThrow( + 'the map a.js.map is claimed by more than one bundle (a.js and b.js), so it cannot be stamped', + ); expect(run).not.toHaveBeenCalled(); }); }); diff --git a/packages/bundler-plugin-core/src/stamp-files.test.ts b/packages/bundler-plugin-core/src/stamp-files.test.ts index 5ec777825..781564da8 100644 --- a/packages/bundler-plugin-core/src/stamp-files.test.ts +++ b/packages/bundler-plugin-core/src/stamp-files.test.ts @@ -113,6 +113,74 @@ describe('snapshot + verifyAndRestore', () => { await snap.dispose(); }); + describe('a changed map beside an UNCHANGED, already-stamped bundle is held to that bundle id', () => { + const OTHER = '11111111-2222-5333-8444-555555555555'; + const stamped = `a();\n//# sourceMappingURL=a.js.map\n${STAMP}`; + const mapWith = (id: string) => + JSON.stringify({ version: 3, sources: [], mappings: '', debugId: id }); + + it('fails and restores a map whose debugId differs from the bundle, leaving the bundle alone', async () => { + await writeFile(join(dir, 'a.js'), stamped); + await writeFile(join(dir, 'a.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js.map'), mapWith(OTHER)); // rewritten, valid JSON, WRONG id + const { issues, restored, failed } = await verifyAndRestore(snap); + expect(issues.map((i) => i.name)).toEqual([join(dir, 'a.js.map')]); + expect(issues[0]?.reason).toContain(`${OTHER} does not match`); + expect(restored).toEqual([join(dir, 'a.js.map')]); + expect(failed).toEqual([]); + expect(await readFile(join(dir, 'a.js.map'), 'utf8')).toBe(plainMap); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe(stamped); + await snap.dispose(); + }); + + it('resolves the bundle through a custom-named map pointer too', async () => { + await mkdir(join(dir, 'maps')); + const code = `a();\n//# sourceMappingURL=maps/a.map\n${STAMP}`; + await writeFile(join(dir, 'a.js'), code); + await writeFile(join(dir, 'maps', 'a.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'maps', 'a.map'), mapWith(OTHER)); + const { issues, restored } = await verifyAndRestore(snap); + expect(issues).toHaveLength(1); + expect(restored).toEqual([join(dir, 'maps', 'a.map')]); + await snap.dispose(); + }); + + it('falls back to the .map sibling when the pointer names a file that is not there', async () => { + const code = `a();\n//# sourceMappingURL=missing.map\n${STAMP}`; + await writeFile(join(dir, 'a.js'), code); + await writeFile(join(dir, 'a.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js.map'), mapWith(OTHER)); + const { issues, restored } = await verifyAndRestore(snap); + expect(issues).toHaveLength(1); + expect(restored).toEqual([join(dir, 'a.js.map')]); + await snap.dispose(); + }); + + it('accepts a map that carries the bundle id', async () => { + await writeFile(join(dir, 'a.js'), stamped); + await writeFile(join(dir, 'a.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js.map'), mapWith(ID)); + expect(await verifyAndRestore(snap)).toEqual({ issues: [], restored: [], failed: [] }); + await snap.dispose(); + }); + + it('ignores a bundle that points at a different map, and one deleted meanwhile', async () => { + await writeFile(join(dir, 'a.js'), stamped); // points at a.js.map + await writeFile(join(dir, 'gone.js'), `g();\n//# sourceMappingURL=a.js.map\n${STAMP}`); + await writeFile(join(dir, 'a.js.map'), plainMap); + await writeFile(join(dir, 'b.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await rm(join(dir, 'gone.js')); + await writeFile(join(dir, 'b.js.map'), mapWith(OTHER)); // no bundle names b.js.map: only JSON-checked + expect(await verifyAndRestore(snap)).toEqual({ issues: [], restored: [], failed: [] }); + await snap.dispose(); + }); + }); + it('a changed map with no changed bundle is held to being JSON, and is restored when it is not', async () => { await writeFile(join(dir, 'x.js.map'), plainMap); const snap = await snapshotStampFiles({ dir }); diff --git a/packages/bundler-plugin-core/src/stamp-files.ts b/packages/bundler-plugin-core/src/stamp-files.ts index 958cdebad..0397407e8 100644 --- a/packages/bundler-plugin-core/src/stamp-files.ts +++ b/packages/bundler-plugin-core/src/stamp-files.ts @@ -381,14 +381,25 @@ export async function verifyAndRestore( } for (const file of changed) { if (file.endsWith('.map') && !paired.has(file)) { - issues.push( - ...verifyStamp( - new Map([[file, await original(file)]]), - new Map([[file, (await read(file)) as Buffer]]), - options.parse, - path, - ), - ); + const before = new Map([[file, await original(file)]]); + const now = new Map([[file, (await read(file)) as Buffer]]); + // A map rewritten beside an UNCHANGED bundle (one stamped earlier, which inject left alone) must still + // agree with that bundle's id: hand the bundle to the verifier, as the paired path does. (A CHANGED bundle that + // names this map would have paired it above, so every bundle reaching the check here is unchanged.) + for (const name of entries.keys()) { + if (!/\.[cm]?js$/i.test(name)) { + continue; + } + const bytes = await read(name); + if (bytes === undefined) { + continue; + } + if (resolveMapName(name, bytes.toString('utf8'), (n) => entries.has(n), path) === file) { + before.set(name, bytes); + now.set(name, bytes); + } + } + issues.push(...verifyStamp(before, now, options.parse, path)); } } From 4b3920740fcd66c956af31c7a068688431e1e0ba Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 14:09:50 +0500 Subject: [PATCH 54/59] fix(bundler-plugin-core): webpack stamps in-build in every mode; only Rspack skips unuploaded development builds The webpack development skip added in dd5b68c3 only skipped the in-build stamp: webpack's afterEmit upload has no development gate, so every dev rebuild still ran inject + upload after emit (the CLI moved, not avoided) and the SRI protection was lost. Revert it for webpack, keep it for Rspack (whose afterEmit is gated), and fix the comment and design doc. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- docs/design/source-maps.md | 4 ++-- packages/bundler-plugin-core/src/plugin.ts | 11 +++++----- .../src/plugin.upload.test.ts | 22 +++++++------------ 3 files changed, 16 insertions(+), 21 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index f5028a951..f0b473b71 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -424,8 +424,8 @@ source and so are deleted with them (as on the post-emit and `files` paths). A s was uploaded and the upload was confirmed: an unkeyed or unreadable one is never deleted, and nothing the walk merely saw is (a keyed map under `test/` or a dot-directory is uploaded AND deleted). The stylesheet and declaration maps are deleted only if something was uploaded. A map that cannot be read (anything but ENOENT) is -not "gone": it is neither uploaded nor deleted and is reported with the unkeyed ones. A dry run still passes the directory (nothing was stamped; `--dry-run` only warns). Rspack and webpack development -builds that are not uploaded (`uploadInDevelopment` unset) are no longer stamped either. A map rewritten beside an unchanged, already-stamped +not "gone": it is neither uploaded nor deleted and is reported with the unkeyed ones. A dry run still passes the directory (nothing was stamped; `--dry-run` only warns). Rspack development +builds that are not uploaded (`uploadInDevelopment` unset) are no longer stamped either (webpack's `afterEmit` upload has no development gate, so its in-build stamp stays on in every mode). A map rewritten beside an unchanged, already-stamped bundle is held to that bundle's debug-ID (and restored if it differs) on the post-emit path. Covered by real builds (`plugin.in-build.real-build.test.ts`: Vite 7/8 with a `publicDir` vendor script, Rollup with a stale one, and `[name].map` custom map names on Rollup, Vite 7/8 and Rspack; real CLI, no dry run, `failOnError` on and off). Not run for real: webpack diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 0e9138602..4abb59aed 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -436,7 +436,7 @@ export const bugseeUnpluginFactory: UnpluginFactory compiler.options.mode === 'development' && !resolved.uploadInDevelopment; // `resolved` is assigned right below; `loadFile` only reads it after that (it is `let` for the hook refresh). @@ -945,10 +945,11 @@ export const bugseeUnpluginFactory: UnpluginFactory { const dir = compiler.options.output?.path; diff --git a/packages/bundler-plugin-core/src/plugin.upload.test.ts b/packages/bundler-plugin-core/src/plugin.upload.test.ts index bfb013fa9..df1088a46 100644 --- a/packages/bundler-plugin-core/src/plugin.upload.test.ts +++ b/packages/bundler-plugin-core/src/plugin.upload.test.ts @@ -242,26 +242,20 @@ describe('the output hooks actually drive the upload', () => { expect(stampSpy).toHaveBeenCalledOnce(); }); - it('does not stamp a development build that is not uploaded, and does when uploadInDevelopment is set', async () => { - const dev = webpack5Compiler({ mode: 'development' }); - apply({ appToken: 'tok', onNotice: () => undefined }, dev.compiler); - await dev.compile(); - expect(dev.processAssets).toHaveLength(0); - expect(stampSpy).not.toHaveBeenCalled(); - - const optIn = webpack5Compiler({ mode: 'development' }); - apply({ appToken: 'tok', uploadInDevelopment: true }, optIn.compiler); - await optIn.compile(); - expect(optIn.processAssets).toHaveLength(1); - expect(stampSpy).toHaveBeenCalledOnce(); - - for (const mode of ['production', 'none', undefined]) { + it('stamps in every mode, development included, and uploads after emit as already stamped', async () => { + // webpack has no development gate on its afterEmit upload (unlike Rspack), so skipping the in-build + // stamp there would only move the CLI to afterEmit and lose the SRI protection. + for (const mode of ['development', 'production', 'none', undefined]) { stampSpy.mockClear(); + uploadSpy.mockClear(); const w = webpack5Compiler(mode === undefined ? {} : { mode }); apply({ appToken: 'tok' }, w.compiler); await w.compile(); expect(w.processAssets).toHaveLength(1); expect(stampSpy).toHaveBeenCalledOnce(); + await w.taps[0]?.fn(); + expect(uploadSpy).toHaveBeenCalledOnce(); + expect((uploadSpy.mock.calls[0]?.[2] as { preStamped?: boolean }).preStamped).toBe(true); } }); From db8d1829e451b82be2d0830ead959858006b9483 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 14:32:27 +0500 Subject: [PATCH 55/59] fix(bundler-plugin-core,nextjs): review round on in-build stamping (strict pinned restore, unreadable files, partner ownership, unique restore temp, registration fallback) - catch-up: a pinned+stamped bundle inject changed that cannot be restored is a strict failure under failOnError - catch-up: a reporter that throws while reporting a spill-removal failure cannot replace the strict result - verifyAndRestore: non-ENOENT read errors are reported as incomplete verification; original rollback partners are not overwritten by a changed pointer - verifyStamp: a changed map that lost its id beside an unchanged stamped bundle is an issue - restoreAtomically: unique exclusive temp file per call - nextjs post-build: server run registers the build unless the browser run actually did - tests: native paths (win32-safe) in stamp-files/build-files/post-build tests Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- docs/design/source-maps.md | 4 +- .../src/orchestrate.dispose.test.ts | 48 ++++++++ .../src/orchestrate.stamp.test.ts | 87 ++++++++++++++ .../bundler-plugin-core/src/orchestrate.ts | 33 ++++-- .../src/stamp-files.test.ts | 107 +++++++++++++++++- .../bundler-plugin-core/src/stamp-files.ts | 35 +++++- .../src/verify-stamp.test.ts | 17 +++ .../bundler-plugin-core/src/verify-stamp.ts | 5 + .../nextjs/src/config/build-files.test.ts | 101 ++++++++++------- packages/nextjs/src/config/post-build.test.ts | 86 +++++++++----- packages/nextjs/src/config/post-build.ts | 21 ++-- 11 files changed, 446 insertions(+), 98 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index f0b473b71..4a0e8c203 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -312,10 +312,10 @@ id. (The hand-rolled SRI step pins only the entry chunks in `index.html`, never 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. + stamp reported are stale). A changed map is also held to an unchanged, already-stamped bundle's id, and a changed map that LOST its id beside such a bundle is an issue (valid JSON alone is not enough). A rewritten file that cannot be read for a reason other than `ENOENT` is reported as an incomplete verification (and restored), never treated as deleted; the restore writes through a unique, exclusively created temp file, so concurrent restores in one directory never share one. - **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. + changed they are restored (with its map) and reported; under `failOnError` a pinned bundle that could NOT be restored is a strict failure (the browser would refuse it) and no map is uploaded. 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. Outputs announce their names at `generateBundle` (before any of them writes; a new build forgets outputs that never wrote), and each run leaves diff --git a/packages/bundler-plugin-core/src/orchestrate.dispose.test.ts b/packages/bundler-plugin-core/src/orchestrate.dispose.test.ts index 62ab48b29..cb44c47b7 100644 --- a/packages/bundler-plugin-core/src/orchestrate.dispose.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.dispose.test.ts @@ -65,3 +65,51 @@ describe('catch-up: a failed spill removal does not mask a strict verification f expect(errors.map(String).join('\n')).toContain('EBUSY'); }); }); + +describe('catch-up: a reporter that throws while reporting the removal failure cannot change the strict result', () => { + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-dispose2-')); + await writeFile(join(dir, 'w.js'), 'w();\n//# sourceMappingURL=w.js.map\n'); + await writeFile(join(dir, 'w.js.map'), '{"version":3,"sources":[],"mappings":""}'); + // a separate, already-keyed map that WOULD upload if the strict result were lost + await writeFile(join(dir, 'k.js.map'), JSON.stringify({ version: 3, debugId: 'k-id' })); + }); + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + const go = (calls: string[][], errors: unknown[]) => + uploadSourcemaps({ + outDir: dir, + appToken: 't', + appVersion: '1', + appBuild: '1', + run: async (args) => { + calls.push(args); + return { code: 0, stdout: '', stderr: '' }; + }, + preStamped: true, + verifySri: async () => [], + findSri: async () => [], + onNotice: () => undefined, + onError: (e) => { + errors.push(e); + if ( + String(e).startsWith('Error: could not remove the temporary') || + /^Error: EBUSY/.test(String(e)) + ) { + throw new Error('reporter exploded'); + } + }, + failOnError: true, + ownFiles: ['w.js', 'w.js.map', 'k.js.map'], + }); + + it('failOnError: rejects with the ORIGINAL restore failure, and nothing is uploaded', async () => { + const calls: string[][] = []; + const errors: unknown[] = []; + await expect(go(calls, errors)).rejects.toThrow(/did not verify|could not be restored|EPERM/); + expect(errors.map(String).join('\n')).toContain('EBUSY'); + expect(calls.some((c) => c[0] === 'debug-files')).toBe(false); + }); +}); diff --git a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts index c39c23d77..946c5744b 100644 --- a/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.stamp.test.ts @@ -1829,6 +1829,93 @@ describe('catch-up edge cases (pointer search, failed restore of a pinned bundle }).catch(() => undefined); expect(errors.map(String).join('\n')).toContain('could not restore'); }); + + it('failOnError: a pinned bundle inject changed that cannot be put back is a STRICT failure, even beside a keyed map', async (ctx) => { + if (await cannotBlockWrites()) { + ctx.skip(); + } + 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); + await writeFile(join(dir, 'k.js.map'), JSON.stringify({ version: 3, debugId: ID })); + const calls: string[][] = []; + const run = vi.fn(async (args: string[]): Promise => { + calls.push(args); + if (args[1] === 'inject') { + await writeFile(join(dir, 'w.js'), `${stamped}//x\n`); + await writeFile( + join(dir, 'w.js.map'), + JSON.stringify({ ...JSON.parse(plain), debugId: ID }), + ); + await chmod(dir, 0o555); + } + return { code: 0, stdout: '', stderr: '' }; + }); + const errors: unknown[] = []; + await expect( + uploadSourcemaps({ + ...base, + outDir: dir, + run, + preStamped: true, + failOnError: true, + verifySri: async () => [], + onNotice: () => undefined, + ownFiles: ['w.js', 'w.js.map', 'k.js.map'], + findSri: async () => [ + { html: join(dir, 'i.html'), script: join(dir, 'w.js'), integrity: 'sha384-X' }, + ], + onError: (e) => errors.push(e), + }), + ).rejects.toThrow(/Subresource Integrity[\s\S]*could not restore/); + expect(calls.some((c) => c[0] === 'debug-files')).toBe(false); + }); +}); + +describe('catch-up: a pinned bundle inject changed that IS restored stays a report, even under failOnError', () => { + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-catchup5-')); + }); + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + it('restores the pinned bytes and reports; does not throw', async () => { + const REG = + '!function(){try{var e=globalThis;e._bugseeDebugIds=e._bugseeDebugIds||{}}catch(e){}}();'; + const plain = '{"version":3,"sources":["w.ts"],"names":[],"mappings":"AAAA"}'; + const stamped = `w();\n//# sourceMappingURL=w.js.map\n\n;${REG}\n//# debugId=${ID}\n`; + await writeFile(join(dir, 'w.js'), stamped); + await writeFile(join(dir, 'w.js.map'), plain); + await writeFile(join(dir, 'k.js.map'), JSON.stringify({ version: 3, debugId: ID })); + const run = vi.fn(async (args: string[]): Promise => { + if (args[1] === 'inject') { + await writeFile(join(dir, 'w.js'), `${stamped}//x\n`); + await writeFile( + join(dir, 'w.js.map'), + JSON.stringify({ ...JSON.parse(plain), debugId: ID }), + ); + } + return { code: 0, stdout: '', stderr: '' }; + }); + const errors: unknown[] = []; + await uploadSourcemaps({ + ...base, + outDir: dir, + run, + preStamped: true, + failOnError: true, + verifySri: async () => [], + onNotice: () => undefined, + ownFiles: ['w.js', 'w.js.map', 'k.js.map'], + findSri: async () => [ + { html: join(dir, 'i.html'), script: join(dir, 'w.js'), integrity: 'sha384-X' }, + ], + onError: (e) => errors.push(e), + }); + expect(await readFile(join(dir, 'w.js'), 'utf8')).toBe(stamped); + expect(errors.map(String).join('\n')).toContain('original bytes were restored'); + }); }); describe('round-17 hardening: failed restore after a rejected inject, sibling outputs', () => { diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index bc3a87fc0..12826a5aa 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -379,17 +379,23 @@ export async function uploadSourcemaps( 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. + let pinnedFailure: Error | undefined; 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(', ')})` - : ''), - ), + const failure = 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(', ')})` + : ''), ); + if (undone.length > 0 && options.failOnError === true) { + // The pinned bytes are still changed: the browser would refuse the script. Strict, like any + // other file that could not be restored. + pinnedFailure ??= failure; + } else { + reportContinuing(failure); + } } } for (const error of pairErrors) { @@ -404,10 +410,17 @@ export async function uploadSourcemaps( } reportContinuing(failure); } - return undefined; + return pinnedFailure; } finally { - // A failed spill removal is a diagnostic: it must not replace the (possibly strict) result being returned. - await snapshot.dispose().catch(reportContinuing); + // A failed spill removal is a diagnostic: it must not replace the (possibly strict) result being returned, + // not even through a reporter that throws while saying so. + await snapshot.dispose().catch((error: unknown) => { + try { + reportContinuing(error); + } catch { + // the handler threw: the result of the catch-up stands + } + }); } }; diff --git a/packages/bundler-plugin-core/src/stamp-files.test.ts b/packages/bundler-plugin-core/src/stamp-files.test.ts index 781564da8..7c0eb7823 100644 --- a/packages/bundler-plugin-core/src/stamp-files.test.ts +++ b/packages/bundler-plugin-core/src/stamp-files.test.ts @@ -1,3 +1,4 @@ +import { randomBytes } from 'node:crypto'; import { chmod, lstat, @@ -12,7 +13,7 @@ import { } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cutAtQuery, isFencedPath, @@ -29,6 +30,11 @@ import { verifyStampedOnDisk, } from './stamp-files'; +vi.mock('node:crypto', async (importOriginal) => { + const real = await importOriginal(); + return { ...real, randomBytes: vi.fn(real.randomBytes) }; +}); + /** A root runner (CAP_DAC_OVERRIDE) writes into a 0o555 directory anyway: such tests cannot run there. */ async function cannotBlockWrites(): Promise { const probe = await mkdtemp(join(tmpdir(), 'bugsee-perm-probe-')); @@ -405,7 +411,9 @@ describe('snapshot walk fence (4): only a project root is fenced', () => { await writeFile(join(dir, 'out', '.hidden', 'h.js'), 'h();\n'); await writeFile(join(dir, 'out', 'node_modules', 'n.js'), 'n();\n'); const snap = await snapshotStampFiles({ dir: join(dir, 'out') }); - const names = [...snap.entries.keys()].map((k) => k.slice(join(dir, 'out').length + 1)).sort(); + const names = [...snap.entries.keys()] + .map((k) => k.slice(join(dir, 'out').length + 1).replace(/\\/g, '/')) + .sort(); expect(names).toEqual(['.hidden/h.js', 'node_modules/n.js', 'src/a.js']); await writeFile(join(dir, 'out', 'src', 'a.js'), `a();\n{{${STAMP}`); expect((await verifyAndRestore(snap)).restored).toEqual([join(dir, 'out', 'src', 'a.js')]); @@ -528,7 +536,9 @@ describe('listOutputMaps', () => { await writeFile(join(dir, 'c.css.map'), '{}'); await writeFile(join(dir, 'd.d.ts.map'), '{}'); await writeFile(join(dir, 'e.js'), 'x'); - expect((await listOutputMaps(dir)).map((f) => f.slice(dir.length + 1))).toEqual([ + expect( + (await listOutputMaps(dir)).map((f) => f.slice(dir.length + 1).replace(/\\/g, '/')).sort(), + ).toEqual([ '.hidden/b.mjs.map', 'c.css.map', 'd.d.ts.map', @@ -544,7 +554,9 @@ describe('listOutputMaps', () => { await writeFile(join(dir, 'ok.map'), '{}'); process.chdir(dir); try { - expect((await listOutputMaps(dir)).map((f) => f.slice(dir.length + 1))).toEqual(['ok.map']); + expect( + (await listOutputMaps(dir)).map((f) => f.slice(dir.length + 1).replace(/\\/g, '/')).sort(), + ).toEqual(['ok.map']); } finally { process.chdir(start); } @@ -927,3 +939,90 @@ describe("the rollback partner is the ORIGINAL pointer's map even when the chang await snap.dispose(); }); }); + +describe('restoreAtomically — concurrent restores never share a temp file', () => { + it('two restores in one directory started in the same millisecond both land their own bytes', async () => { + const now = vi.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000); + try { + await writeFile(join(dir, 'spill-a'), 'original-a'); + await writeFile(join(dir, 'spill-b'), 'original-b'); + await writeFile(join(dir, 'a.js'), 'stamped-a'); + await writeFile(join(dir, 'b.js'), 'stamped-b'); + await Promise.all([ + restoreAtomically(join(dir, 'spill-a'), join(dir, 'a.js')), + restoreAtomically(join(dir, 'spill-b'), join(dir, 'b.js')), + ]); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe('original-a'); + expect(await readFile(join(dir, 'b.js'), 'utf8')).toBe('original-b'); + expect((await readdir(dir)).sort()).toEqual(['a.js', 'b.js', 'spill-a', 'spill-b']); + } finally { + now.mockRestore(); + } + }); + it('never removes a temp file it does not own (an exclusive create that finds one fails clean)', async () => { + await writeFile(join(dir, 'spill'), 'original'); + await writeFile(join(dir, 'a.js'), 'stamped'); + (randomBytes as unknown as ReturnType).mockReturnValueOnce(Buffer.alloc(8)); + const temp = join(dir, `.bugsee-restore-${process.pid}-0000000000000000`); + await writeFile(temp, 'someone else'); + await expect(restoreAtomically(join(dir, 'spill'), join(dir, 'a.js'))).rejects.toThrow( + /EEXIST/, + ); + expect(await readFile(temp, 'utf8')).toBe('someone else'); + expect(await readFile(join(dir, 'a.js'), 'utf8')).toBe('stamped'); + }); +}); + +describe('verifyAndRestore — a changed file that cannot be read is not "deleted"', () => { + it('reports a non-ENOENT read failure as an issue (and restores it); a deleted file stays silent', async () => { + await writeFile(join(dir, 'a.js'), 'a();\n'); + await writeFile(join(dir, 'gone.js'), 'g();\n'); + const snap = await snapshotStampFiles({ dir }); + await rm(join(dir, 'gone.js')); + await rm(join(dir, 'a.js')); + await mkdir(join(dir, 'a.js')); // reading a directory: EISDIR, not ENOENT + const result = await verifyAndRestore(snap, { restoreFile: async () => undefined }); + expect(result.issues).toEqual([ + { name: join(dir, 'a.js'), reason: expect.stringMatching(/could not be read.*EISDIR/s) }, + ]); + expect(result.restored).toEqual([join(dir, 'a.js')]); + await snap.dispose(); + }); + it('a failed restore of the unreadable file is returned in `failed` (what failOnError acts on)', async () => { + await writeFile(join(dir, 'a.js'), 'a();\n'); + const snap = await snapshotStampFiles({ dir }); + await rm(join(dir, 'a.js')); + await mkdir(join(dir, 'a.js')); + const result = await verifyAndRestore(snap); + expect(result.issues).toHaveLength(1); + expect(result.failed.map((f) => f.path)).toEqual([join(dir, 'a.js')]); + await snap.dispose(); + }); +}); + +describe("verifyAndRestore — a rewrite that points at ANOTHER bundle's map does not take that map over", () => { + it("restores the other bundle's map when the pointing bundle cannot be restored", async () => { + // a.js is processed first and owns a.js.map; b.js's bad stamp then points at a.js.map. + await writeFile(join(dir, 'a.js'), 'a();\n//# sourceMappingURL=a.js.map\n'); + await writeFile(join(dir, 'b.js'), 'b();\n//# sourceMappingURL=b.js.map\n'); + await writeFile(join(dir, 'a.js.map'), plainMap); + await writeFile(join(dir, 'b.js.map'), plainMap); + const snap = await snapshotStampFiles({ dir }); + await writeFile(join(dir, 'a.js'), `a();\n//# sourceMappingURL=a.js.map\n{{${STAMP}`); + await writeFile(join(dir, 'b.js'), `b();\n//# sourceMappingURL=a.js.map\n{{${STAMP}`); + await writeFile(join(dir, 'a.js.map'), stampedMap); + await writeFile(join(dir, 'b.js.map'), stampedMap); + const { restored, failed } = await verifyAndRestore(snap, { + restoreFile: async (spill, target) => { + if (target === join(dir, 'b.js')) { + throw new Error('EPERM'); + } + await writeFile(target, await readFile(spill)); + }, + }); + expect(failed.map((f) => f.path)).toContain(join(dir, 'b.js')); + expect(restored).toContain(join(dir, 'a.js')); + expect(restored).toContain(join(dir, 'a.js.map')); + await snap.dispose(); + }); +}); diff --git a/packages/bundler-plugin-core/src/stamp-files.ts b/packages/bundler-plugin-core/src/stamp-files.ts index 0397407e8..eb9acdbbe 100644 --- a/packages/bundler-plugin-core/src/stamp-files.ts +++ b/packages/bundler-plugin-core/src/stamp-files.ts @@ -8,7 +8,7 @@ // The originals are SPILLED to a temp directory with a content hash beside them, not held in memory: a // build can have hundreds of megabytes of scripts and maps, and the verification only ever needs one // bundle and its map at a time. -import { createHash } from 'node:crypto'; +import { createHash, randomBytes } from 'node:crypto'; import type { Dirent } from 'node:fs'; import { chmod, @@ -277,15 +277,24 @@ export async function restoreAtomically(spill: string, target: string): Promise< (info) => info.mode & 0o7777, () => undefined, ); - const temp = join(dirname(real), `.bugsee-restore-${process.pid}-${Date.now()}`); + // Unique per call (concurrent runs of one process restore into the same directory) and created exclusively + // (`wx`): a name that already exists is never written to, and never removed by a call that did not create it. + const temp = join( + dirname(real), + `.bugsee-restore-${process.pid}-${randomBytes(8).toString('hex')}`, + ); + const bytes = await readFile(spill); try { - await writeFile(temp, await readFile(spill)); + await writeFile(temp, bytes, { flag: 'wx' }); if (mode !== undefined) { await chmod(temp, mode); } await rename(temp, real); } catch (error) { - await unlink(temp).catch(() => undefined); + // A temp file that already existed (EEXIST) is someone else's: only one this call created is removed. + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') { + await unlink(temp).catch(() => undefined); + } throw error; } } @@ -308,10 +317,15 @@ export async function verifyAndRestore( failed: Array<{ path: string; error: string }>; }> { const { entries } = snapshot; + const unreadable = new Map(); const read = async (file: string): Promise => { try { return await readFile(file); - } catch { + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { + // Not "deleted": a file that cannot be read cannot be verified, and it may still carry a bad rewrite. + unreadable.set(file, String(error)); + } return undefined; // deleted meanwhile: not part of the comparison } }; @@ -355,7 +369,10 @@ export async function verifyAndRestore( const now = new Map([[bundle, after]]); if (entries.has(map)) { partner.set(bundle, partner.get(bundle) ?? map); - partner.set(map, bundle); + // A rollback relationship the ORIGINAL pointers established is never replaced by a changed pointer. + if (!partner.has(map)) { + partner.set(map, bundle); + } before.set(map, await original(map)); const mapNow = await read(map); if (mapNow !== undefined) { @@ -403,6 +420,12 @@ export async function verifyAndRestore( } } + // A file that cannot be read now is an incomplete verification: reported (and restored from its original), + // never silently skipped. Unrelated pairs were still checked above. + for (const [file, error] of unreadable) { + issues.push({ name: file, reason: `it could not be read to verify the stamp: ${error}` }); + } + const toRestore = new Set(); for (const { name } of issues) { toRestore.add(name); diff --git a/packages/bundler-plugin-core/src/verify-stamp.test.ts b/packages/bundler-plugin-core/src/verify-stamp.test.ts index f8addadae..156b65f20 100644 --- a/packages/bundler-plugin-core/src/verify-stamp.test.ts +++ b/packages/bundler-plugin-core/src/verify-stamp.test.ts @@ -524,6 +524,23 @@ describe('a changed map is held to an UNCHANGED stamped bundle', () => { expect(issues[0]).toMatchObject({ name: 'a.js.map' }); expect(issues[0]?.reason).toContain(OTHER_ID); }); + it('flags a changed map that LOST its id beside an unchanged stamped bundle (valid JSON, no debugId)', () => { + const code = buf(stampedCode(ID)); + const issues = verifyStamp( + new Map([ + ['a.js', code], + ['a.js.map', buf(stampedMap(ID))], + ]), + new Map([ + ['a.js', code], + ['a.js.map', buf(mapJson())], + ]), + ); + expect(issues).toHaveLength(1); + expect(issues[0]).toMatchObject({ name: 'a.js.map' }); + expect(issues[0]?.reason).toMatch(/no debugId/); + expect(issues[0]?.reason).toContain(ID); + }); it('accepts the map that matches it, and a map beside an unstamped bundle (JSON only)', () => { const code = buf(stampedCode(ID)); expect( diff --git a/packages/bundler-plugin-core/src/verify-stamp.ts b/packages/bundler-plugin-core/src/verify-stamp.ts index aa830045b..b48fb3f68 100644 --- a/packages/bundler-plugin-core/src/verify-stamp.ts +++ b/packages/bundler-plugin-core/src/verify-stamp.ts @@ -261,6 +261,11 @@ export function verifyStamp( 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)) { + issues.push({ + name, + reason: `the map has no debugId (its bundle carries ${unchangedIds.get(name)})`, + }); } else if ( mapId !== undefined && unchangedIds.has(name) && diff --git a/packages/nextjs/src/config/build-files.test.ts b/packages/nextjs/src/config/build-files.test.ts index 1d6d87a60..068e1df29 100644 --- a/packages/nextjs/src/config/build-files.test.ts +++ b/packages/nextjs/src/config/build-files.test.ts @@ -1,9 +1,12 @@ 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { collectBuildFiles, mapPointerOf, pairByPointer, partitionBuildFiles } from './build-files'; +// `mapPointerOf` resolves against the host's path API, so the pointer fixtures use native absolute paths (win32: `C:\\o\\a.js`). +const p = (path: string): string => resolve(path); + 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']; @@ -48,41 +51,49 @@ describe('partitionBuildFiles', () => { 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(p('/o/chunks/a.js'), 'code();\n//# sourceMappingURL=other.js.map\n')).toBe( + p('/o/chunks/other.js.map'), + ); + expect(mapPointerOf(p('/o/chunks/a.js'), 'x\n//@ sourceMappingURL=../m/a.map')).toBe( + p('/o/m/a.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', + expect(mapPointerOf(p('/o/a.js'), 'x\n//# sourceMappingURL=%5Broot%5D__a._.js.map\n')).toBe( + p('/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'); + expect(mapPointerOf(p('/o/a.js'), 'x\n//# sourceMappingURL=100%.js.map')).toBe( + p('/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(); + expect(mapPointerOf(p('/o/a.css'), 'a{}\n/*# sourceMappingURL=a.css.map */')).toBe( + p('/o/a.css.map'), + ); + expect(mapPointerOf(p('/o/a.css'), 'a{}\n//# sourceMappingURL=a.css.map')).toBeUndefined(); + expect(mapPointerOf(p('/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'); + expect(mapPointerOf(p('/o/a.css'), 'a{}\n/*@ sourceMappingURL=x.css.map*/')).toBe( + p('/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(p('/o/a.js'), 'no comment')).toBeUndefined(); expect( - mapPointerOf('/o/a.js', 'x\n//# sourceMappingURL=data:application/json;base64,e30='), + mapPointerOf(p('/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(); + expect(mapPointerOf(p('/o/a.js'), '//# sourceMappingURL=a.map\nmore();')).toBeUndefined(); }); }); @@ -91,72 +102,78 @@ describe('pairByPointer', () => { 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') })); + const files = [p('/o/0ihtw.js'), p('/o/1wkfrb.js.map')]; + const parts = await pairByPointer(files, reader({ [p('/o/0ihtw.js')]: code('1wkfrb.js.map') })); expect(parts).toEqual({ - scripts: ['/o/0ihtw.js'], - maps: ['/o/1wkfrb.js.map'], + scripts: [p('/o/0ihtw.js')], + maps: [p('/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') })); + const parts = await pairByPointer( + [p('/o/a.js')], + reader({ [p('/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') })); + const parts = await pairByPointer( + [p('/o/a.js'), p('/o/b.js')], + reader({ [p('/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'], + [p('/o/a.js'), p('/o/b.js'), p('/o/shared.js.map'), p('/o/c.js'), p('/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'), + [p('/o/a.js')]: code('shared.js.map'), + [p('/o/b.js')]: code('shared.js.map'), + [p('/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']); + expect(parts.scripts).toEqual([p('/o/c.js')]); + expect(parts.maps).toEqual([p('/o/c.js.map')]); + expect(parts.shared).toEqual([p('/o/a.js'), p('/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); + await pairByPointer([p('/o/a.json'), p('/o/a.js.map'), p('/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') }), + [p('/o/a.css'), p('/o/x1.map')], + reader({ [p('/o/a.css')]: css('x1.map') }), ); - expect(parts.stylesheetMaps).toEqual(['/o/x1.map']); + expect(parts.stylesheetMaps).toEqual([p('/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 */' }), + [p('/o/a.css'), p('/o/a.css.map'), p('/o/foreign.css.map'), p('/o/types.d.ts.map')], + reader({ [p('/o/a.css')]: 'a{}\n/*# sourceMappingURL=a.css.map */' }), ); - expect(parts.stylesheetMaps).toEqual(['/o/a.css.map']); + expect(parts.stylesheetMaps).toEqual([p('/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'], + [p('/o/a.css'), p('/o/b.css'), p('/o/c.css'), p('/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= */', + [p('/o/a.css')]: 'a{}/*# sourceMappingURL=gone.css.map */', + [p('/o/b.css')]: 'a{}/*# sourceMappingURL=c.txt */', + [p('/o/c.css')]: 'a{}/*# sourceMappingURL=data:application/json;base64,e30= */', }), ); expect(parts.stylesheetMaps).toEqual([]); @@ -164,11 +181,11 @@ describe('pairByPointer', () => { 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') }), + [p('/o/z.js'), p('/o/a.js'), p('/o/m1.map'), p('/o/m0.map')], + reader({ [p('/o/z.js')]: code('m1.map'), [p('/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']); + expect(parts.scripts).toEqual([p('/o/a.js'), p('/o/z.js')]); + expect(parts.maps).toEqual([p('/o/m0.map'), p('/o/m1.map')]); }); }); diff --git a/packages/nextjs/src/config/post-build.test.ts b/packages/nextjs/src/config/post-build.test.ts index 2167c69ba..1624f65f1 100644 --- a/packages/nextjs/src/config/post-build.test.ts +++ b/packages/nextjs/src/config/post-build.test.ts @@ -1,11 +1,14 @@ 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 { BuildFiles } from './build-files'; import type { BugseeNextContext } from './context'; import { runPostBuild } from './post-build'; +// Native absolute paths: `runPostBuild` resolves and joins with the host's path API (win32: `C:\\app\\.next`). +const p = (path: string): string => resolve(path); + const files = (name: string): BuildFiles => ({ scripts: [`/d/${name}.js`], maps: [`/d/${name}.js.map`], @@ -32,11 +35,12 @@ function context( }; } -const metadata = { projectDir: '/app', distDir: '/app/.next' }; +const metadata = { projectDir: p('/app'), distDir: p('/app/.next') }; function deps(map: Record, sri = false) { return { - upload: vi.fn(async () => undefined), + // the browser run registered the build (see `registerBuild` below) + upload: vi.fn(async () => ({ build: { registered: true } }) as never), collect: vi.fn(async (dir: string) => map[dir] ?? none), exists: vi.fn(async () => sri), }; @@ -53,7 +57,7 @@ describe('runPostBuild', () => { 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 }); + const d = deps({ [p('/app/.next/static')]: client, [p('/app/.next/server')]: server }); await runPostBuild(context(), metadata, d); expect(d.upload).toHaveBeenCalledTimes(2); type Call = [ @@ -62,10 +66,10 @@ describe('runPostBuild', () => { { 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[1]).toBe(p('/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[1]).toBe(p('/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 }); @@ -74,14 +78,36 @@ describe('runPostBuild', () => { expect(first[2].bundler).toEqual({ isProduction: true, configuration: 'production' }); }); + it('keeps the registration for the server run when the browser run did NOT register the build', async () => { + for (const browserResult of [ + { build: { registered: false, reason: 'failed' } }, + { build: undefined }, + undefined, + ]) { + const d = deps({ + [p('/app/.next/static')]: files('client'), + [p('/app/.next/server')]: files('server'), + }); + d.upload = vi.fn(async (_r: unknown, dir: string) => + dir === p('/app/.next/static') ? browserResult : undefined, + ) as never; + await runPostBuild(context(), metadata, d); + const [, second] = (d.upload as ReturnType).mock.calls as [ + [unknown], + [Record], + ]; + expect(second[0]).toMatchObject({ registerBuild: 'release' }); + } + }); + 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'); + const d = deps({ [p('/app/.next/static')]: files('c') }); + await runPostBuild(context(), { projectDir: p('/app'), distDir: '.next' }, d); + expect(d.collect).toHaveBeenCalledWith(p('/app/.next/static')); }); it('honours deleteServerMaps', async () => { - const d = deps({ '/app/.next/server': files('s') }); + const d = deps({ [p('/app/.next/server')]: files('s') }); await runPostBuild(context({}, { deleteServerMaps: true }), metadata, d); const [resolved] = (d.upload as ReturnType).mock.calls[0] as [ Record, @@ -90,15 +116,15 @@ describe('runPostBuild', () => { }); 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') }); + const d = deps({ [p('/app/.next/static')]: files('c'), [p('/app/.next/server')]: files('s') }); await runPostBuild(context({}, { serverSourceMaps: false }), metadata, d); - expect(d.collect).not.toHaveBeenCalledWith('/app/.next/server'); + expect(d.collect).not.toHaveBeenCalledWith(p('/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') }); + const d = deps({ [p('/app/.next/server')]: files('s') }); await runPostBuild(ctx, metadata, d); expect(ctx.say).toHaveBeenCalledWith(expect.stringContaining('productionBrowserSourceMaps')); expect(d.upload).toHaveBeenCalledTimes(1); @@ -107,8 +133,8 @@ describe('runPostBuild', () => { 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'] }, + [p('/app/.next/static')]: { ...files('c'), shared: ['/d/x.js'] }, + [p('/app/.next/server')]: { ...files('s'), shared: ['/d/y.js', '/d/z.js'] }, }); await runPostBuild(ctx, metadata, d); expect(ctx.say).toHaveBeenCalledWith( @@ -119,23 +145,23 @@ describe('runPostBuild', () => { 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') })); + await runPostBuild(off, metadata, deps({ [p('/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') })); + await runPostBuild(expected, metadata, deps({ [p('/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'] } }); + const d = deps({ [p('/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') }); + const d = deps({ [p('/app/.next/server')]: files('s') }); await runPostBuild(context(), metadata, d); const [resolved] = (d.upload as ReturnType).mock.calls[0] as [ Record, @@ -145,15 +171,20 @@ describe('runPostBuild', () => { it('stays quiet about shared maps when there are none', async () => { const ctx = context(); - await runPostBuild(ctx, metadata, deps({ '/app/.next/static': files('c') })); + await runPostBuild(ctx, metadata, deps({ [p('/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); + const d = deps( + { [p('/app/.next/static')]: files('c'), [p('/app/.next/server')]: files('s') }, + true, + ); await runPostBuild(ctx, metadata, d); - expect(d.exists).toHaveBeenCalledWith('/app/.next/server/subresource-integrity-manifest.json'); + expect(d.exists).toHaveBeenCalledWith( + p('/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')); @@ -161,7 +192,7 @@ describe('runPostBuild', () => { 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') }); + const d = deps({ [p('/app/.next/static')]: files('c') }); await runPostBuild(ctx, metadata, d); expect(d.exists).not.toHaveBeenCalled(); expect(d.upload).not.toHaveBeenCalled(); @@ -200,7 +231,10 @@ describe('runPostBuild: containment', () => { 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()) }; + const d = { + ...deps({ [p('/app/.next/static')]: files('c') }), + upload: vi.fn(async () => boom()), + }; await expect(runPostBuild(context({ onError }), metadata, d)).resolves.toBeUndefined(); expect(onError).toHaveBeenCalledTimes(1); }); @@ -244,7 +278,7 @@ describe('runPostBuild: containment', () => { const remove = vi.fn(async (_path: string): Promise => undefined); const d = { upload: vi.fn(upload) as never, - collect: vi.fn(async (dir: string) => (dir === '/app/.next/static' ? client : none)), + collect: vi.fn(async (dir: string) => (dir === p('/app/.next/static') ? client : none)), exists: vi.fn(async () => false), remove, }; @@ -277,7 +311,7 @@ describe('runPostBuild: containment', () => { const lenient = setup(async () => undefined, { onError: vi.fn() }); lenient.d.collect = vi.fn(async (dir: string) => { - if (dir === '/app/.next/server') throw new Error('EACCES'); + if (dir === p('/app/.next/server')) throw new Error('EACCES'); return client; }); await runPostBuild(lenient.ctx, metadata, lenient.d); diff --git a/packages/nextjs/src/config/post-build.ts b/packages/nextjs/src/config/post-build.ts index 6a9322818..aafe91d13 100644 --- a/packages/nextjs/src/config/post-build.ts +++ b/packages/nextjs/src/config/post-build.ts @@ -9,7 +9,11 @@ // `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 PluginRunResult, + 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'; @@ -115,20 +119,21 @@ async function postBuild( dir: string, files: BuildFiles, options: Partial, - ): Promise => { + ): Promise => { if (files.scripts.length === 0) { - return; + return undefined; } - await upload({ ...resolved, ...options }, dir, { bundler, files }); + return 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, {}); + const browser = 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 }), + // The build is registered once. When the browser run did not register it (it had nothing to upload because + // the app turned browser maps off, or its registration failed without `failOnError`), the server run + // registers it instead, so the build record is not lost. + ...(browser?.build?.registered === true ? { registerBuild: false } : {}), }); } } finally { From 9cea1b1d847eda01537f75d3894e9e465e325ddf Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 14:57:10 +0500 Subject: [PATCH 56/59] 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 57/59] 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 4dbfebb59e189750ae720664570d81ab1f4fd77c Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 20:24:36 +0500 Subject: [PATCH 58/59] fix(bundler-plugin-core): pass --allow-sri only when a re-seal will happen resealSri used to add --allow-sri to every inject, which switched off the CLI's own SRI refusal even for pins this scanner cannot resolve (a scheme-less //host, a root-relative path under --base-href/--deploy-url). It is now passed only when pins were found, or a manifest / server digest needs the re-seal; otherwise the CLI refusal stays on. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .../src/orchestrate.test.ts | 47 +++++++++++++++++++ .../bundler-plugin-core/src/orchestrate.ts | 5 +- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/packages/bundler-plugin-core/src/orchestrate.test.ts b/packages/bundler-plugin-core/src/orchestrate.test.ts index 25b0b2515..b803d53e8 100644 --- a/packages/bundler-plugin-core/src/orchestrate.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.test.ts @@ -992,6 +992,53 @@ describe('uploadSourcemaps with resealSri', () => { ]); }); + // The CLI's own SRI refusal is the safety net for pins OUR scanner cannot resolve (a scheme-less //host, a root-relative + // path under --base-href/--deploy-url): --allow-sri is passed only when a re-seal will actually happen. + it('leaves the CLI refusal ON when resealSri is set but nothing pins a hash and no manifest exists', async () => { + const { run, calls } = fakeRun(); + await uploadSourcemaps({ + ...sealed({ findSri: async () => [], hasServiceWorker: async () => false }), + run, + }); + expect(calls[0]?.args).toEqual(['sourcemaps', 'inject', '/build/dist']); + }); + + it('leaves it on for every batch of a file run too', async () => { + const { run, calls } = fakeRun(); + await uploadSourcemaps({ + ...sealed({ + findSri: async () => [], + hasServiceWorker: async () => false, + files: { scripts: ['/build/dist/main.js'], maps: ['/build/dist/main.js.map'] }, + }), + run, + }); + expect(calls[0]?.args).not.toContain('--allow-sri'); + }); + + it('passes it when only a service worker manifest needs the re-seal', async () => { + const { run, calls } = fakeRun(); + await uploadSourcemaps({ + ...sealed({ findSri: async () => [], hasServiceWorker: async () => true }), + run, + }); + expect(calls[0]?.args).toContain('--allow-sri'); + }); + + it('passes it when a server module holds a digest', async () => { + const { run, calls } = fakeRun(); + await uploadSourcemaps({ + ...sealed({ + findSri: async () => [], + hasServiceWorker: async () => false, + resealDirs: ['/build/dist', '/build/server'], + hasDigestTokens: async () => true, + }), + run, + }); + expect(calls[0]?.args).toContain('--allow-sri'); + }); + it('adds no flag at all when resealSri is off (the refusal path is unchanged)', async () => { const { run, calls } = fakeRun(); await uploadSourcemaps({ diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 9cbcb531a..19b269f09 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -280,7 +280,6 @@ export async function uploadSourcemaps( const dryFlag = dryRun ? ['--dry-run'] : []; // `inject` refuses a hashed build unless told the hashes are re-written afterwards, which resealSri does. const resealing = options.resealSri === true; - const allowSriFlag = resealing ? ['--allow-sri'] : []; const cliOptions: RunBugseeCliOptions = { token: appToken, endpoint }; const onError = options.onError ?? defaultUploadErrorHandler; @@ -588,6 +587,10 @@ export async function uploadSourcemaps( sealDirs.filter((dir) => resolve(dir) !== resolve(outDir)), )) || (await (options.hasServiceWorker ?? hasServiceWorkerManifest)(sealDirs))); + // `--allow-sri` switches off the CLI's own refusal of a hashed build, so it is passed only when the pins were + // found here and will be re-written. A pin this scanner cannot resolve (a scheme-less //host, a root-relative path + // under --base-href/--deploy-url) is then still caught by the CLI. + const allowSriFlag = resealing && (pinned.length > 0 || needsReseal) ? ['--allow-sri'] : []; const digests = needsReseal ? await (options.snapshotDigests ?? snapshotScriptDigests)([outDir]) : undefined; From 623c73bfd1dd0224392e7d89c287f4d0a8626c6b Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 24 Nov 2026 20:25:25 +0500 Subject: [PATCH 59/59] fix(angular): refuse an SSR build whose server output is inside the browser output outputPath.browser: '' puts the browser output in the base with server/ below it; injecting that directory would stamp the server bundles as browser code and upload their maps as browser maps. Said and refused (exit 0 unless --fail-on-error), like the --output-path branch. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxRnbk1iC7HPhhoC2Cr --- .../angular/src/sourcemaps/upload.test.ts | 55 +++++++++++++++++++ packages/angular/src/sourcemaps/upload.ts | 17 +++++- 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/packages/angular/src/sourcemaps/upload.test.ts b/packages/angular/src/sourcemaps/upload.test.ts index 3ad856375..f3c2893f5 100644 --- a/packages/angular/src/sourcemaps/upload.test.ts +++ b/packages/angular/src/sourcemaps/upload.test.ts @@ -321,6 +321,61 @@ describe('uploadAngularSourcemaps', () => { await expect(run({ failOnError: true })).rejects.toThrow(/ng build/); }); + it('outputPath { browser: "" } on an SSR build (server/ inside the browser directory) is refused: it would stamp the server', async () => { + await write( + 'angular.json', + JSON.stringify({ + projects: { + demo: { + projectType: 'application', + root: '', + architect: { + build: { + builder: '@angular/build:application', + options: { outputPath: { base: 'dist/app', browser: '' } }, + }, + }, + }, + }, + }), + ); + await write('dist/app/main.js', 'x();'); + await write('dist/app/server/server.mjs', ''); + const runPluginUpload = ran(); + const notices: string[] = []; + const out = await uploadAngularSourcemaps( + base({ cwd, onNotice: (m: string) => notices.push(m) }), + { runPluginUpload }, + ); + expect(out.status).toBe('misconfigured'); + expect(runPluginUpload).not.toHaveBeenCalled(); + expect(notices.join('\n')).toMatch(/server.*inside.*browser/s); + }); + + it('the same layout WITHOUT a server output is fine', async () => { + await write( + 'angular.json', + JSON.stringify({ + projects: { + demo: { + projectType: 'application', + root: '', + architect: { + build: { + builder: '@angular/build:application', + options: { outputPath: { base: 'dist/app', browser: '' } }, + }, + }, + }, + }, + }), + ); + await write('dist/app/main.js', 'x();'); + await write('dist/app/main.js.map', '{}'); + const out = await uploadAngularSourcemaps(base({ cwd }), { runPluginUpload: ran() }); + expect(out.status).toBe('uploaded'); + }); + it('--dist naming a FILE is a misconfiguration said, not a crash', async () => { await write('a-file', 'x'); const notices: string[] = []; diff --git a/packages/angular/src/sourcemaps/upload.ts b/packages/angular/src/sourcemaps/upload.ts index c4304e0dc..5b3fad80e 100644 --- a/packages/angular/src/sourcemaps/upload.ts +++ b/packages/angular/src/sourcemaps/upload.ts @@ -24,7 +24,7 @@ import { runPluginUpload, } from '@bugsee/bundler-plugin-core'; import { type AngularOutput, resolveAngularOutput } from './output'; -import { findServerRoot, looksLikeAngularServer } from './server-root'; +import { findServerRoot, isStrictlyInside, looksLikeAngularServer } from './server-root'; export interface AngularUploadOptions extends BugseePluginOptions { /** Workspace directory (angular.json is looked for here and above). Default: the working directory. */ @@ -209,6 +209,21 @@ export async function uploadAngularSourcemaps( ); } outDir = located.browserDir; + if ( + located.serverDir !== undefined && + existsSync(located.serverDir) && + isStrictlyInside(located.serverDir, outDir) + ) { + // `outputPath.browser: ''` puts the browser output in the base, with server/ below it: injecting the directory + // would stamp the server bundles as browser code and upload their maps as browser maps. + return misconfigured( + `the server output ${located.serverDir} is inside the browser output ${outDir} (outputPath.browser is empty), ` + + `so stamping the browser output would stamp the server too. Give the browser output its own directory ` + + `(the default browser/).`, + outDir, + located.configuration, + ); + } rootBrowser = outDir; resealRoot = located.serverDir !== undefined && existsSync(located.serverDir)