Repository navigation
fix(rrweb): strip inlined worker sourceMappingURL comment (Angular build break in beta.6) #197
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'); | ||
| }); | ||
| } | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.