diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cdb952f2..72104b43 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -78,6 +78,12 @@ jobs: - name: Publishable packages run: pnpm check:publishable + # A dist whose `//# sourceMappingURL=` comment sits mid-file (e.g. at the tail of an inlined worker + # string) is corrupted by Angular's esbuild builder, which strips such lines. Build the one package + # that inlines a vendored worker, then scan every dist present (0.1.0-beta.6 regression). + - name: Dist survives source-map-comment stripping + run: pnpm --filter @bugsee/rrweb build && pnpm check:dist-sourcemaps + # Per-package coverage gate (turbo runs each package's own test:coverage, # each enforcing 100% line/fn/stmt + ≥90% branch). NOT the root merged # `pnpm test:coverage`, whose single aggregate threshold the scaffold-only diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 072c76ff..4702a4c7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -61,6 +61,10 @@ jobs: - name: Build run: pnpm exec turbo run build + # Every freshly built dist must survive Angular-style source-map-comment stripping (beta.6 regression). + - name: Dist survives source-map-comment stripping + run: pnpm check:dist-sourcemaps + # Inputs go in through the environment, never interpolated into the script text: a `${{ }}` inside # `run:` is textually pasted into the shell, so a crafted tag could execute commands with the # job's id-token. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 443e7af0..c2a089e3 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1485,3 +1485,9 @@ Verified against current majors, all green with no adapter code changes: `@bugse **Electron (closed 2026-11-01):** main's store is the one with the byte cap, and its `onVisualReset` now tells every renderer to restart its replay recorder through a new control command `checkout` (`@bugsee/node` `onVisualReset` option -> `launchMain` -> `createElectronMainControl().checkout()` -> `onCheckout` in the renderer -> the browser launch's `onReplayRestart` hook). The pacing (5 s, doubling to 5 min, reset after 10 min of quiet) is the shared `createVisualResetGate` from `@bugsee/core`, also used by the browser launch. **Still open:** renderers of several windows share one visual lane in main without a window id on the record, so time eviction keeps only the newest base across windows (per-window lanes are the follow-up). **Verified:** mutator loop on the lane logic and the new wiring (all mutants killed, hangs caught by timeout); core 1908, replay 228, browser 1339, browser-utils 230, electron 548 tests; coverage gate holds; typecheck, lint, cycles clean; two convergent review rounds. **Closed 2026-11-01:** the streaming export (`docs/design/streaming-export.md`, slices S0-S6) shipped: `Bundle.body` is a `BundleBody`; reports stream from the store snapshot through `assembleBundleStream` (per-type incremental encoders, fflate streaming zip) into a sink (memory by default, node temp file under `/export/`, Blob available); window trim + replay clamp/orphan-trim apply to every live report; durable staging streams file bodies (`BundleStore.putFrame`); transports pipe/Blob a `BundleBody`; an export failure falls back to a memory build so the report still ships. Measured live-heap cost of the export: +36 MB -> +4 MB on a 20 MB window (section 9). Default `maxDataSize` raised: browser 20 MB (memory) / 30 MB (IndexedDB); Node 50 MB, edge/worker 10 MB unchanged. **Recovery paths (closed later the same day):** capture-recovery and native-crash-recovery stream too (`recovered-bundle.ts`). **Viewer unzip verified 2026-11-01:** the viewer's own `jszip.min.js` (`JSZip.loadAsync`, what its import dialog uses) opens the streamed bundles (memory and file sink), same members and sizes as the buffered bundle apart from the window-trimmed replay; the import dialog reads only `request.json`, so member order is immaterial. **IndexedDB read path measured and fixed 2026-11-01:** its snapshot read the whole window before yielding; it now streams part by part (export heap +33 -> +21 MB on a 20 MB window; buffered +77 MB; design doc section 9). **Per-window replay (owner decision 2026-11-01: pixels compose per display, reconstruction captures per window; `docs/design/per-window-replay.md`):** slices L0-L3 done (lane on records, per-lane store state and reset, backends attach it, one replay member per window, Electron per-window tagging and `checkout`). **Still open:** viewer support for several replay windows (it reads only the first `replay`), a concrete `compose` for the display video; closed-window lanes are retired (L6); pixel video per display (L4: assembler splits by lane with `attrs.displayId`, `createDisplayVideoSource`, Electron screen/window adapters; the host injects `compose`); the ~20 MB assembler residual of the browser export is the window's largest rrweb event being reified (explained, design doc section 9). + +### Hotfix: `@bugsee/rrweb` 0.1.0-beta.6 broke Angular's esbuild `application` builder (2026-11-11) +**Regression.** `ng build` failed with `Unterminated string literal` at `@bugsee/rrweb/dist/index.js`. Angular's JS transformer strips source-map comments from every dependency with `/^\/\/# sourceMappingURL=[^\r\n]*/gm`. rrweb inlines its image-bitmap worker as a template literal, and the vendored `vendor/rrweb-record/record.js` ends that string `...\n//# sourceMappingURL=image-bitmap-data-url-worker-NVDCVKXO.js.map\`` (closing backtick on the SAME line); the regex deleted the backtick and the file ended inside the literal. Beta.5 had the backtick on the next line, so only the comment was eaten. +**Fix (build time, vendor file untouched, sha256 pin intact).** `packages/rrweb/build/strip-inline-sourcemap.ts` (build tooling, outside `src/`): an esbuild `onLoad` plugin removes a line-start `sourceMappingURL` comment followed by a backtick on the same line (only that shape can be inside a template literal); wired in `packages/rrweb/tsup.config.ts` with `expected: 1`, so a vendor bump that adds/removes such a string FAILS the build instead of passing silently. Also an `onSuccess` step collapses tsup's duplicated trailing `//# sourceMappingURL=index.js.map` to one. +**Guard.** `scripts/check-dist-sourcemaps.mjs` (`pnpm check:dist-sourcemaps`, CI step that builds rrweb first, then scans; also a `release.yml` step right after `turbo run build`, before publish): over every `packages/*/dist/**/*.{js,cjs,mjs}`, a column-0 `sourceMappingURL` comment may only sit in the file's trailing run of comment lines (tsup writes it twice in every package, harmless; rrweb's own test additionally pins exactly one), and the file must still parse (esbuild) after Angular's exact regex is applied. `packages/rrweb/build/dist-sourcemap-guard.test.ts` builds the real package into a TEMP dir (`BUGSEE_RRWEB_OUT_DIR` + `--out-dir`, so it never races turbo's own `build` on `dist/`), asserts the same, and extracts the inlined worker literal to syntax-check it and run it in a `vm` smoke. Mutator check: removing the plugin makes both fail (line 6142, "does not parse"). +**Not added:** an Angular `application`-builder smoke (needs a full Angular install and build per run, outside the e2e pattern); the guard emulates the exact failing step instead. Only rrweb is built in CI for the scan, since it is the one package inlining a vendored worker string; any other dist present locally is scanned too. diff --git a/package.json b/package.json index 015fc8a8..25875d80 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,7 @@ "format": "biome format --write .", "check:cycles": "madge --circular --extensions ts packages", "check:publishable": "node scripts/check-publishable.mjs", + "check:dist-sourcemaps": "node scripts/check-dist-sourcemaps.mjs", "mutation": "turbo run mutation", "changeset": "changeset", "version-packages": "changeset version", diff --git a/packages/rrweb/build/dist-sourcemap-guard.test.ts b/packages/rrweb/build/dist-sourcemap-guard.test.ts new file mode 100644 index 00000000..83c11546 --- /dev/null +++ b/packages/rrweb/build/dist-sourcemap-guard.test.ts @@ -0,0 +1,116 @@ +// @vitest-environment node +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import vm from 'node:vm'; +import { transformSync } from 'esbuild'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +// Guards the CLASS of bug behind the 0.1.0-beta.6 Angular break: a `//# sourceMappingURL=` comment at column +// 0 that is not the file's last line is deleted by Angular's esbuild builder, which (when it was the tail of +// the inlined worker template literal) took the closing backtick with it. The checker is +// scripts/check-dist-sourcemaps.mjs (also run in CI over every dist); this suite builds the REAL package +// into a TEMP directory, so it never cleans the package's own dist/ under a concurrent turbo build. +type Guard = { + ANGULAR_STRIP: RegExp; + checkSource: ( + code: string, + format: 'esm' | 'cjs', + parse: (code: string, format: 'esm' | 'cjs') => void, + ) => string[]; +}; + +const here = dirname(fileURLToPath(import.meta.url)); +const pkgDir = resolve(here, '..'); +const guardPath = resolve(pkgDir, '../../scripts/check-dist-sourcemaps.mjs'); +const parse = (code: string, format: 'esm' | 'cjs'): void => { + transformSync(code, { format, loader: 'js', logLevel: 'silent' }); +}; + +/** The inlined worker source: the template literal that opens with `(function() {`, evaluated. */ +function extractWorker(code: string): string { + const m = /= `(\(function\(\) \{[\s\S]*?)`;\n(?:var|const|let) /.exec(code); + if (!m) throw new Error('inlined worker literal not found'); + return vm.runInNewContext(`\`${m[1]}\``) as string; +} + +describe('dist source-map-comment guard', () => { + let guard: Guard; + beforeAll(async () => { + guard = (await import(pathToFileURL(guardPath).href)) as Guard; + }); + + it('flags the beta.6 shape: a comment at column 0 closing a template literal on the same line', () => { + const bad = 'const w = `x();\n//# sourceMappingURL=w.js.map`;\nexport { w };\n'; + const problems = guard.checkSource(bad, 'esm', parse); + expect(problems.some((p) => /followed by more code/.test(p))).toBe(true); + expect(problems.some((p) => /does not parse/.test(p))).toBe(true); + }); + + it('accepts a trailing run of comments (tsup duplicates it) and a single one', () => { + const dup = 'a();\n//# sourceMappingURL=i.map\n//# sourceMappingURL=i.map'; + expect(guard.checkSource(dup, 'esm', parse)).toEqual([]); + expect(guard.checkSource('a();\n//# sourceMappingURL=i.map\n', 'esm', parse)).toEqual([]); + }); + + describe('the built package', () => { + let outDir: string; + beforeAll(() => { + outDir = mkdtempSync(join(tmpdir(), 'rrweb-dist-')); + execFileSync('pnpm', ['exec', 'tsup', '--out-dir', outDir], { + cwd: pkgDir, + stdio: 'pipe', + env: { ...process.env, BUGSEE_RRWEB_OUT_DIR: outDir }, + }); + }, 120_000); + afterAll(() => rmSync(outDir, { recursive: true, force: true })); + + for (const [file, format] of [ + ['index.js', 'esm'], + ['index.cjs', 'cjs'], + ] as const) { + it(`${file} survives Angular's source-map stripping and keeps one trailing comment`, () => { + const code = readFileSync(join(outDir, file), 'utf8'); + expect(guard.checkSource(code, format, parse)).toEqual([]); + expect(code.match(/^\/\/# sourceMappingURL=/gm)).toHaveLength(1); + }); + + it(`${file}: the inlined worker survives the stripping, parses and answers messages`, async () => { + const stripped = readFileSync(join(outDir, file), 'utf8').replace(guard.ANGULAR_STRIP, ''); + const worker = extractWorker(stripped); + expect(worker).not.toContain('sourceMappingURL'); + // syntax check (node --check equivalent) + expect(() => new vm.Script(worker)).not.toThrow(); + // behavioural smoke: run it against a fake worker global + OffscreenCanvas and post a message + const posted: unknown[] = []; + class FakeCanvas { + constructor(readonly w: number) {} + getContext() { + return { drawImage() {} }; + } + async convertToBlob() { + const w = this.w; + return { + type: 'image/png', + arrayBuffer: async () => new Uint8Array([1, 2, 3, w]).buffer, + }; + } + } + const self = { + postMessage: (m: unknown) => posted.push(m), + onmessage: undefined as unknown, + }; + const ctx = vm.createContext({ self, OffscreenCanvas: FakeCanvas, Map, Uint8Array }); + vm.runInContext(worker, ctx); + const onmessage = self.onmessage as (e: unknown) => Promise; + await onmessage({ + data: { id: 1, bitmap: { close() {} }, width: 5, height: 5, dataURLOptions: {} }, + }); + expect(posted).toHaveLength(1); + expect(JSON.stringify(posted[0])).toContain('"id":1'); + }); + } + }); +}); diff --git a/packages/rrweb/build/strip-inline-sourcemap.test.ts b/packages/rrweb/build/strip-inline-sourcemap.test.ts new file mode 100644 index 00000000..8863e889 --- /dev/null +++ b/packages/rrweb/build/strip-inline-sourcemap.test.ts @@ -0,0 +1,109 @@ +// @vitest-environment node +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { build } from 'esbuild'; +import { afterAll, describe, expect, it } from 'vitest'; +import { + dedupeTrailingSourceMap, + stripInlineSourceMap, + stripInlineSourceMapPlugin, +} from './strip-inline-sourcemap'; + +describe('stripInlineSourceMap', () => { + it('removes a sourceMappingURL comment inside a template literal (closing backtick on the same line)', () => { + const src = 'const w = `code();\n//# sourceMappingURL=worker.js.map`;\nexport { w };\n'; + expect(stripInlineSourceMap(src)).toBe('const w = `code();`;\nexport { w };\n'); + }); + + it('handles CRLF and the legacy //@ form', () => { + expect(stripInlineSourceMap('x=`a\r\n//@ sourceMappingURL=a.map`;')).toBe('x=`a`;'); + }); + + it('leaves a real trailing comment (no backtick after it on the line) untouched', () => { + const src = 'a();\n//# sourceMappingURL=index.js.map\n'; + expect(stripInlineSourceMap(src)).toBe(src); + }); + + it('leaves a comment whose closing backtick is on the NEXT line untouched', () => { + const src = 'x=`a\n//# sourceMappingURL=a.map\n`;'; + expect(stripInlineSourceMap(src)).toBe(src); + }); + + it('only matches a comment at the START of a line (not mid-line string concatenation)', () => { + const src = 'const s = "//# sourceMappingURL=" + `x`;'; + expect(stripInlineSourceMap(src)).toBe(src); + const src2 = 'const s = "//# sourceMappingURL=a.map`";'; + expect(stripInlineSourceMap(src2)).toBe(src2); + }); + + it('matches at the very start of the file', () => { + expect(stripInlineSourceMap('//# sourceMappingURL=a.map`x')).toBe('`x'); + }); +}); + +describe('stripInlineSourceMapPlugin (esbuild integration)', () => { + const dirs: string[] = []; + afterAll(() => { + for (const d of dirs) rmSync(d, { recursive: true, force: true }); + }); + + const run = async (body: string, expected?: number): Promise => { + const dir = mkdtempSync(join(tmpdir(), 'rrweb-sm-')); + dirs.push(dir); + const file = join(dir, 'entry.js'); + writeFileSync(file, body); + const out = await build({ + entryPoints: [file], + bundle: true, + write: false, + format: 'esm', + logLevel: 'silent', + plugins: [stripInlineSourceMapPlugin(expected === undefined ? {} : { expected })], + }); + return out.outputFiles[0]?.text ?? ''; + }; + const withComment = 'export const w = `a();\n//# sourceMappingURL=w.js.map`;\n'; + + it('strips the comment from a loaded module so the emitted string stays terminated', async () => { + const text = await run(withComment); + expect(text).not.toContain('sourceMappingURL'); + expect(text).toContain('a();'); + }); + + it('passes a module without such a comment through to esbuild unchanged', async () => { + const text = await run('export const w = 1;\n'); + expect(text).toContain('w = 1'); + }); + + it('succeeds when the number of stripped comments equals the expected count', async () => { + expect(await run(withComment, 1)).not.toContain('sourceMappingURL'); + }); + + it('fails the build loudly when fewer comments are found than expected (vendor changed)', async () => { + await expect(run('export const w = 1;\n', 1)).rejects.toThrow(/expected 1.*found 0/); + }); + + it('fails the build loudly when more comments are found than expected', async () => { + await expect(run(withComment, 0)).rejects.toThrow(/expected 0.*found 1/); + }); +}); + +describe('dedupeTrailingSourceMap', () => { + it('collapses a repeated trailing sourceMappingURL comment to one', () => { + const c = 'a();\n//# sourceMappingURL=index.js.map\n//# sourceMappingURL=index.js.map\n'; + expect(dedupeTrailingSourceMap(c)).toBe('a();\n//# sourceMappingURL=index.js.map\n'); + }); + + it('collapses duplicates when the file has no final newline', () => { + const c = 'a();\n//# sourceMappingURL=i.map\n//# sourceMappingURL=i.map'; + expect(dedupeTrailingSourceMap(c)).toBe('a();\n//# sourceMappingURL=i.map'); + }); + + it('leaves a single trailing comment, and distinct comments, untouched', () => { + const one = 'a();\n//# sourceMappingURL=index.js.map\n'; + expect(dedupeTrailingSourceMap(one)).toBe(one); + const two = 'a();\n//# sourceMappingURL=a.map\n//# sourceMappingURL=b.map\n'; + expect(dedupeTrailingSourceMap(two)).toBe(two); + }); +}); diff --git a/packages/rrweb/build/strip-inline-sourcemap.ts b/packages/rrweb/build/strip-inline-sourcemap.ts new file mode 100644 index 00000000..e7fa17d7 --- /dev/null +++ b/packages/rrweb/build/strip-inline-sourcemap.ts @@ -0,0 +1,60 @@ +// Build-time tooling for tsup.config.ts only. It lives outside src/ because it imports node:fs and must +// never be reachable from the package's runtime entry. +import { readFile } from 'node:fs/promises'; +import type { Plugin } from 'esbuild'; + +// A `//# sourceMappingURL=` comment can be baked INTO a string by the upstream bundler that produced a +// prebuilt dependency (rrweb inlines its image-bitmap worker as a template literal that ends +// "...\n//# sourceMappingURL=worker.js.map`"). Inside a string it is dead text, but a consumer's toolchain +// that strips source-map comments line-wise (Angular's esbuild `application` builder runs +// `/^\/\/# sourceMappingURL=[^\r\n]*/gm` over every dependency) deletes the closing backtick with it and +// the file no longer parses. Removing it at build time means it is never emitted. +// +// Only a comment that STARTS a line and is followed by a backtick ON THE SAME LINE is touched: a real +// comment runs to end of line, so that shape can only be the tail of a template literal, and the line-start +// anchor mirrors exactly what the consumer's regex would hit. +const INLINE_SOURCEMAP_COMMENT = /(?:^|\r?\n)\/\/[#@] sourceMappingURL=[^\r\n`]*(?=`)/g; + +export function stripInlineSourceMap(code: string): string { + return code.replace(INLINE_SOURCEMAP_COMMENT, ''); +} + +function countInlineSourceMaps(code: string): number { + return code.match(INLINE_SOURCEMAP_COMMENT)?.length ?? 0; +} + +/** + * esbuild plugin applying {@link stripInlineSourceMap} to every JS module the bundler loads. + * With `expected`, the build FAILS when the number of stripped comments differs, so a vendor bump that + * adds, removes or reshapes such a string surfaces instead of passing silently. + */ +export function stripInlineSourceMapPlugin(options: { expected?: number } = {}): Plugin { + return { + name: 'bugsee-strip-inline-sourcemap', + setup(build) { + let found = 0; + build.onStart(() => { + found = 0; + }); + build.onLoad({ filter: /\.[cm]?js$/ }, async ({ path }) => { + const code = await readFile(path, 'utf8'); + const n = countInlineSourceMaps(code); + if (n === 0) return undefined; + found += n; + return { contents: stripInlineSourceMap(code), loader: 'js' }; + }); + build.onEnd(() => { + if (options.expected !== undefined && found !== options.expected) { + throw new Error( + `expected ${options.expected} inlined sourceMappingURL comment(s), found ${found}`, + ); + } + }); + }, + }; +} + +/** tsup emits the trailing `//# sourceMappingURL=.map` twice; keep one. */ +export function dedupeTrailingSourceMap(code: string): string { + return code.replace(/(\/\/# sourceMappingURL=[^\r\n]*)(\r?\n)\1(?=\r?\n?$)/, '$1'); +} diff --git a/packages/rrweb/package.json b/packages/rrweb/package.json index 96b41bd4..2e7216c6 100644 --- a/packages/rrweb/package.json +++ b/packages/rrweb/package.json @@ -33,6 +33,7 @@ }, "devDependencies": { "@bugsee/rrweb-record": "file:../../vendor/rrweb-record", + "esbuild": "^0.28.2", "jsdom": "^25.0.1" }, "publishConfig": { diff --git a/packages/rrweb/tsconfig.json b/packages/rrweb/tsconfig.json index 5e8d0e36..a60a0606 100644 --- a/packages/rrweb/tsconfig.json +++ b/packages/rrweb/tsconfig.json @@ -2,9 +2,9 @@ "extends": "../../tsconfig.base.json", "compilerOptions": { "outDir": "dist", - "rootDir": "src", + "rootDir": ".", "lib": ["ES2023", "DOM", "DOM.Iterable"], "types": ["node"] }, - "include": ["src", "test"] + "include": ["src", "build", "test"] } diff --git a/packages/rrweb/tsup.config.ts b/packages/rrweb/tsup.config.ts index cb6d4753..1157c578 100644 --- a/packages/rrweb/tsup.config.ts +++ b/packages/rrweb/tsup.config.ts @@ -1,5 +1,15 @@ +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; import { defineConfig } from 'tsup'; import { baseConfig } from '../../tsup.config.base'; +import { + dedupeTrailingSourceMap, + stripInlineSourceMapPlugin, +} from './build/strip-inline-sourcemap'; + +// The guard test builds into a temp dir (BUGSEE_RRWEB_OUT_DIR + `--out-dir`) so it never cleans the real +// dist/ while a concurrent turbo `build` is writing it. +const outDir = process.env.BUGSEE_RRWEB_OUT_DIR ?? 'dist'; // @bugsee/rrweb: the thin record-path wrapper. // @@ -13,4 +23,16 @@ export default defineConfig({ ...baseConfig, entry: ['src/index.ts'], noExternal: ['@bugsee/rrweb-record'], + // The vendored bundle inlines a worker as a template literal ending in a sourceMappingURL comment; see + // strip-inline-sourcemap.ts (Angular's esbuild builder would otherwise cut the closing backtick). + // Exactly one inlined comment exists in the vendored bundle (the image-bitmap worker); any other count + // means a vendor bump changed it and this transform needs a look. + esbuildPlugins: [stripInlineSourceMapPlugin({ expected: 1 })], + // tsup writes the trailing `//# sourceMappingURL=` twice; keep one so the file has exactly one, last. + onSuccess: async () => { + for (const name of ['index.js', 'index.cjs']) { + const f = join(outDir, name); + writeFileSync(f, dedupeTrailingSourceMap(readFileSync(f, 'utf8'))); + } + }, }); diff --git a/packages/rrweb/vitest.config.ts b/packages/rrweb/vitest.config.ts index 64c95faa..d6cd0891 100644 --- a/packages/rrweb/vitest.config.ts +++ b/packages/rrweb/vitest.config.ts @@ -11,10 +11,10 @@ export default defineConfig({ // this reason; this extends the same convention to the rest. testTimeout: 30_000, environment: 'jsdom', - include: ['src/**/*.test.ts'], + include: ['src/**/*.test.ts', 'build/**/*.test.ts'], coverage: { provider: 'v8', - include: ['src/**/*.ts'], + include: ['src/**/*.ts', 'build/**/*.ts'], exclude: ['src/**/*.test.ts', 'src/**/*.test-d.ts', 'src/**/*.d.ts'], thresholds: { lines: 100, functions: 100, statements: 100, branches: 90 }, }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f2726151..fac97d9a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1191,6 +1191,9 @@ importers: '@bugsee/rrweb-record': specifier: file:../../vendor/rrweb-record version: file:vendor/rrweb-record(@rrweb/types@2.2.1)(rrweb@2.2.1) + esbuild: + specifier: ^0.28.2 + version: 0.28.2 jsdom: specifier: ^25.0.1 version: 25.0.1 diff --git a/scripts/check-dist-sourcemaps.d.mts b/scripts/check-dist-sourcemaps.d.mts new file mode 100644 index 00000000..f05129aa --- /dev/null +++ b/scripts/check-dist-sourcemaps.d.mts @@ -0,0 +1,6 @@ +export const ANGULAR_STRIP: RegExp; +export function checkSource( + code: string, + format: 'esm' | 'cjs', + parse: (code: string, format: 'esm' | 'cjs') => void, +): string[]; diff --git a/scripts/check-dist-sourcemaps.mjs b/scripts/check-dist-sourcemaps.mjs new file mode 100644 index 00000000..64ed86a2 --- /dev/null +++ b/scripts/check-dist-sourcemaps.mjs @@ -0,0 +1,92 @@ +#!/usr/bin/env node +// Release gate: no published dist file may be broken by a consumer that strips source-map comments. +// +// Why: Angular's esbuild `application` builder (and others) run `/^\/\/# sourceMappingURL=[^\r\n]*/gm` +// over every dependency's JS. A `//# sourceMappingURL=` that sits at column 0 anywhere but the file's +// last line is therefore destroyed — and if it is the tail of an inlined template literal (rrweb's worker +// string, 0.1.0-beta.6) the closing backtick goes with it and the file stops parsing. This gate checks, +// for every `packages/*/dist/**/*.{js,cjs,mjs}`: +// (a) a column-0 sourceMappingURL comment appears only in the file's trailing run of comment lines; +// (b) after applying the regex exactly like Angular does, the file still parses. +// +// pnpm --filter @bugsee/rrweb build && node scripts/check-dist-sourcemaps.mjs +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); + +/** Angular's javascript-transformer-worker source-map stripping, verbatim. */ +export const ANGULAR_STRIP = /^\/\/# sourceMappingURL=[^\r\n]*/gm; + +const COMMENT = /^\/\/# sourceMappingURL=/; + +/** + * Line numbers (1-based) of column-0 sourceMappingURL comments that are NOT part of the file's trailing + * run of such comments. tsup writes that trailing comment twice in every package; Angular's regex eats + * trailing lines harmlessly, so only a comment followed by more code is dangerous. + */ +function midFileComments(code) { + const lines = code.split(/\r?\n/); + let end = lines.length; + while (end > 0 && (lines[end - 1] === '' || COMMENT.test(lines[end - 1]))) end--; + const hits = []; + for (let i = 0; i < end; i++) if (COMMENT.test(lines[i])) hits.push(i + 1); + return hits; +} + +/** + * Problems for one file's source. `parse(code, format)` throws when the code does not parse. + * @param {string} code + * @param {'esm'|'cjs'} format + * @param {(code: string, format: 'esm'|'cjs') => void} parse + * @returns {string[]} + */ +export function checkSource(code, format, parse) { + const problems = []; + for (const line of midFileComments(code)) + problems.push(`sourceMappingURL comment at column 0 on line ${line}, followed by more code`); + try { + parse(code.replace(ANGULAR_STRIP, ''), format); + } catch (e) { + problems.push( + `does not parse after Angular's source-map stripping: ${String(e.message).split('\n')[0]}`, + ); + } + return problems; +} + +function* walk(dir) { + for (const name of readdirSync(dir)) { + const p = join(dir, name); + if (statSync(p).isDirectory()) yield* walk(p); + else if (/\.(c|m)?js$/.test(name)) yield p; + } +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const { transformSync } = createRequire(join(root, 'packages/rrweb/package.json'))('esbuild'); + const parse = (code, format) => transformSync(code, { format, loader: 'js', logLevel: 'silent' }); + const errors = []; + let scanned = 0; + for (const pkg of readdirSync(join(root, 'packages'))) { + const dist = join(root, 'packages', pkg, 'dist'); + if (!existsSync(dist)) continue; + for (const file of walk(dist)) { + scanned++; + const format = file.endsWith('.cjs') ? 'cjs' : 'esm'; + for (const p of checkSource(readFileSync(file, 'utf8'), format, parse)) + errors.push(`${file.slice(root.length + 1)}: ${p}`); + } + } + if (!scanned) + errors.push( + 'no packages/*/dist output found — build first (pnpm --filter @bugsee/rrweb build)', + ); + if (errors.length) { + console.error(errors.join('\n')); + process.exit(1); + } + console.log(`${scanned} dist file(s) safe against source-map-comment stripping.`); +}