Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
krassx marked this conversation as resolved.
Resolved

# 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
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions docs/PROGRESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<instance>/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.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
116 changes: 116 additions & 0 deletions packages/rrweb/build/dist-sourcemap-guard.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>;
await onmessage({
data: { id: 1, bitmap: { close() {} }, width: 5, height: 5, dataURLOptions: {} },
});
expect(posted).toHaveLength(1);
expect(JSON.stringify(posted[0])).toContain('"id":1');
});
}
});
});
109 changes: 109 additions & 0 deletions packages/rrweb/build/strip-inline-sourcemap.test.ts
Original file line number Diff line number Diff line change
@@ -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<string> => {
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);
});
});
60 changes: 60 additions & 0 deletions packages/rrweb/build/strip-inline-sourcemap.ts
Original file line number Diff line number Diff line change
@@ -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=<file>.map` twice; keep one. */
export function dedupeTrailingSourceMap(code: string): string {
return code.replace(/(\/\/# sourceMappingURL=[^\r\n]*)(\r?\n)\1(?=\r?\n?$)/, '$1');
}
1 change: 1 addition & 0 deletions packages/rrweb/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
},
"devDependencies": {
"@bugsee/rrweb-record": "file:../../vendor/rrweb-record",
"esbuild": "^0.28.2",
"jsdom": "^25.0.1"
},
"publishConfig": {
Expand Down
Loading