// Copyright 2025 The Lynx Authors. All rights reserved. // Licensed under the Apache License Version 2.0 that can be found in the // LICENSE file in the root directory of this source tree. // eslint-disable-next-line n/no-unsupported-features/node-builtins import { glob, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import path from 'node:path' import { fileURLToPath } from 'node:url' import type { RsbuildPlugin } from '@rsbuild/core' import { afterAll, afterEach, describe, expect, rstest, test, } from '@rstest/core' import { SourceMapConsumer } from 'source-map' import type { NullableMappedPosition, RawSourceMap } from 'source-map' import { findSourceMap } from '@lynx-js/debug-metadata' import type { DebugMetadataAsset } from '@lynx-js/debug-metadata' import type { Output } from '@lynx-js/rspeedy' import { createStubRspeedy as createRspeedy } from './createRspeedy.js' const functionNames = [ 'functionThatThrows', 'innerFunction', 'function renderComponent', ] const tempDirs: string[] = [] afterAll(async () => { await Promise.all(tempDirs.map(async (dir) => { await rm(dir, { recursive: true, force: true }) })) }) afterEach(() => { rstest.unstubAllEnvs() }) async function buildSourcemapFixture( sourceMap: Output['sourceMap'] = undefined, ) { const tmp = await mkdtemp(path.join(tmpdir(), 'rspeedy-react-test')) tempDirs.push(tmp) rstest.stubEnv('DEBUG', 'rspeedy') const { pluginReactLynx } = await import('../src/index.js') const rsbuild = await createRspeedy({ rspeedyConfig: { source: { entry: { main: fileURLToPath( new URL('./fixtures/sourcemap/index.tsx', import.meta.url), ), }, }, output: { distPath: { root: tmp, }, filenameHash: false, minify: false, sourceMap, }, plugins: [ pluginReactLynx(), { name: 'test', pre: ['lynx:react'], setup(api) { api.modifyBundlerChain((chain, { CHAIN_ID }) => { const rule = chain.module .rules.get('css:react:main-thread') .uses.get(CHAIN_ID.USE.IGNORE_CSS) rule.loader( // add .ts suffix to ignore-css-loader // this workaround is needed because vitest // runs on our ts files. rule.get('loader')! + '.ts', ) }) }, } as RsbuildPlugin, // This is to simulate cases that there // are other loaders before our @lynx-js/react/transform // we can pass the sourcemap from previous loaders to our transform { name: 'swc-loader-before-swc-transform', setup(api) { api.modifyBundlerChain((chain) => { const rule = chain.module.rule( 'swc-loader-before-swc-transform', ) rule .test(/\.[jt]sx$/) .use('swc-loader-before-swc-transform') .loader('builtin:swc-loader') .options({ jsc: { parser: { syntax: 'typescript', tsx: true, }, transform: { react: { runtime: 'automatic', }, }, }, sourceMaps: true, }) .end() }) }, } as RsbuildPlugin, ], }, }) const result = await rsbuild.build() await result.close() return tmp } async function getSourceMapFiles(tmp: string) { const sourceMapFiles: string[] = [] for await ( const file of glob([ path.join(tmp, '**/*.map'), // for files inside `.lynx` path.join(tmp, '.*/**/*.map'), ]) ) { sourceMapFiles.push(normalizeSlashes(path.relative(tmp, file))) } return sourceMapFiles.sort() } describe('Sourcemap', () => { test('getSourceMapFiles returns sorted map paths', async () => { const tmp = await mkdtemp(path.join(tmpdir(), 'rspeedy-react-test')) tempDirs.push(tmp) await mkdir(path.join(tmp, '.lynx/main'), { recursive: true }) await mkdir(path.join(tmp, 'static/js/async'), { recursive: true }) await writeFile(path.join(tmp, 'static/js/async/z-last.map'), '') await writeFile(path.join(tmp, '.lynx/main/a-first.map'), '') await writeFile(path.join(tmp, 'static/js/async/m-middle.map'), '') expect(await getSourceMapFiles(tmp)).toEqual([ '.lynx/main/a-first.map', 'static/js/async/m-middle.map', 'static/js/async/z-last.map', ]) }) test('.map assets are dropped before emit', async () => { const tmp = await buildSourcemapFixture(undefined) const sourceMapFiles = await getSourceMapFiles(tmp) expect(sourceMapFiles).toEqual([]) const debugMetadataJson = await Promise.all([ readFile( path.join(tmp, '.lynx/main/debug-metadata.json'), 'utf-8', ), readFile( path.join( tmp, '.lynx/lazy-bundle/fixtures_sourcemap_lazy-bundle-comp.tsx/debug-metadata.json', ), 'utf-8', ), ]) const metadata = debugMetadataJson.map(json => JSON.parse(json) as DebugMetadataAsset ) const mapPathsInMetadata = metadata .flatMap(meta => meta.artifacts) .flatMap(a => a.debugSources) .filter(d => d.kind === 'source-map') .map(d => path.posix.normalize(d.path)) .sort() expect(mapPathsInMetadata).toMatchInlineSnapshot(` [ ".lynx/lazy-bundle/fixtures_sourcemap_lazy-bundle-comp.tsx/background.js.map", ".lynx/lazy-bundle/fixtures_sourcemap_lazy-bundle-comp.tsx/main-thread.js.map", ".lynx/main/background.js.map", ".lynx/main/main-thread.js.map", ".lynx/main/main.css.map", ] `) }, 25_000) test( 'debug-metadata injects a per-chunk source-map release banner', async () => { const tmp = await buildSourcemapFixture(undefined) const mainThread = await readFile( path.join(tmp, '.lynx/main/main-thread.js'), 'utf-8', ) const background = await readFile( path.join(tmp, '.lynx/main/background.js'), 'utf-8', ) const lazyMainThreadPath = path.join( tmp, '.lynx/lazy-bundle/fixtures_sourcemap_lazy-bundle-comp.tsx/main-thread.js', ) const [lazyMainThread, lazyMetadata] = await Promise.all([ readFile(lazyMainThreadPath, 'utf-8'), readFile( path.join(path.dirname(lazyMainThreadPath), 'debug-metadata.json'), 'utf-8', ).then(json => JSON.parse(json) as DebugMetadataAsset), ]) const mtRelease = releaseOf(mainThread) const btRelease = releaseOf(background) const lazyMtRelease = releaseOf(lazyMainThread) const lazyMainThreadMap = findSourceMap(lazyMetadata, { filename: 'main-thread.js.map', })! // `minify: false` keeps the banner var name, so the release is greppable. // The release is `debugmetadata:` + a 160-bit sha1 over the chunk's // modules; the bare hash equals the source-map artifact `key` // reverse-resolution locates the container by. expect(mtRelease, 'main-thread should declare a release').toMatch( /^debugmetadata:[0-9a-f]+$/, ) expect(btRelease, 'background should declare a release').toMatch( /^debugmetadata:[0-9a-f]+$/, ) expect( lazyMtRelease, 'lazy main-thread should declare a release', ).toMatch(/^debugmetadata:[0-9a-f]+$/) expect(lazyMtRelease).toBe(`debugmetadata:${lazyMainThreadMap.key}`) // The injected runtime registers the release with the Lynx engine. expect(mainThread).toContain('_SetSourceMapRelease') expect(background).toContain('_SetSourceMapRelease') expect(lazyMainThread).toContain('_SetSourceMapRelease') expect(lazyMainThread).toContain( '("main-thread",', ) // The `[name]` placeholder in the runtime must be substituted with each // file's own name (engineVersion > 2.13 reports the stack filename, so a // literal `[name]` makes reverse-resolution target a non-existent file). expect(mainThread).toContain('file://main-thread.js') expect(background).toContain('file://background.js') expect(lazyMainThread).toContain('file://main-thread.js') expect(mainThread).not.toContain('file://[name].js') expect(background).not.toContain('file://[name].js') expect(lazyMainThread).not.toContain('file://[name].js') // Per-chunk: main-thread and background carry their own (distinct) hash. expect(mtRelease).not.toBe(btRelease) expect(lazyMtRelease).not.toBe(mtRelease) expect(lazyMtRelease).not.toBe(btRelease) }, 25_000, ) test( 'sourcemap should map from compiled code to original source code', async () => { const tmp = await buildSourcemapFixture({ css: true }) const [mainMetadataJson, asyncMetadataJson] = await Promise.all([ readFile( path.join(tmp, '.lynx/main/debug-metadata.json'), 'utf-8', ), readFile( path.join( tmp, '.lynx/lazy-bundle/fixtures_sourcemap_lazy-bundle-comp.tsx/debug-metadata.json', ), 'utf-8', ), ]) const debugMetadata = JSON.parse(mainMetadataJson) as DebugMetadataAsset const asyncMetadata = JSON.parse(asyncMetadataJson) as DebugMetadataAsset const sourceMapFiles = [debugMetadata, asyncMetadata] .flatMap(meta => meta.artifacts) .flatMap(a => a.debugSources) .filter(d => d.kind === 'source-map') .map(d => path.posix.normalize(d.path)) .sort() expect(sourceMapFiles).toMatchInlineSnapshot(` [ ".lynx/lazy-bundle/fixtures_sourcemap_lazy-bundle-comp.tsx/background.js.map", ".lynx/lazy-bundle/fixtures_sourcemap_lazy-bundle-comp.tsx/main-thread.js.map", ".lynx/main/background.js.map", ".lynx/main/main-thread.js.map", ".lynx/main/main.css.map", ] `) expect(sourceMapFiles).toContain('.lynx/main/main.css.map') const cssSource = await readFile( path.join(tmp, '.lynx/main/main.css'), 'utf-8', ) const cssSourceMap = findSourceMap(debugMetadata, { filename: 'main.css.map', })!.map as RawSourceMap const cssConsumer = await new SourceMapConsumer(cssSourceMap) const cssLine = cssSource .split('\n') .findIndex(line => line.includes('.app')) + 1 const cssColumn = cssSource .split('\n') .at(cssLine - 1)! .indexOf('.app') + 1 const cssSourcePosition = cssConsumer.originalPositionFor({ line: cssLine, column: cssColumn, }) expect(path.basename(cssSourcePosition.source ?? '')).toBe('index.css') const backgroundSource = await readFile( path.join(tmp, '.lynx/main/background.js'), 'utf-8', ) const backgroundSourceMap = findSourceMap(debugMetadata, { filename: 'background.js.map', })!.map as RawSourceMap const consumer = await new SourceMapConsumer(backgroundSourceMap) const functionName2Source: Record = {} functionNames.forEach((name) => { const backgroundSourceLines = backgroundSource.split('\n') let line = -1, column = -1 backgroundSourceLines.forEach((lineContent, index) => { if (lineContent.includes(name)) { line = index + 1 column = lineContent.indexOf(name) + 1 } }) functionName2Source[name] = consumer .originalPositionFor({ line, column, }) if (functionName2Source[name].source) { functionName2Source[name].source = path.basename( functionName2Source[name].source, ) } }) expect(functionName2Source).toMatchInlineSnapshot(` { "function renderComponent": { "column": 0, "line": 319, "name": null, "source": "preact.mjs", }, "functionThatThrows": { "column": 2, "line": 23, "name": "functionThatThrows", "source": "index.tsx", }, "innerFunction": { "column": 2, "line": 14, "name": "innerFunction", "source": "index.tsx", }, } `) const backgroundRuntimeStatement = '__root = root;' const backgroundRuntimeOffset = backgroundSource.indexOf( backgroundRuntimeStatement, ) expect(backgroundRuntimeOffset).toBeGreaterThan(-1) const backgroundRuntimeSourceIndex = backgroundSourceMap.sources .findIndex(source => normalizeSlashes(source).endsWith('/runtime/src/root.ts') ) expect(backgroundRuntimeSourceIndex).toBeGreaterThan(-1) const backgroundRuntimeSourceContent = backgroundSourceMap .sourcesContent?.[backgroundRuntimeSourceIndex] expect(backgroundRuntimeSourceContent).toContain( backgroundRuntimeStatement, ) const backgroundRuntimePosition = consumer.originalPositionFor( generatedPositionAt(backgroundSource, backgroundRuntimeOffset), ) expect(normalizeSlashes(backgroundRuntimePosition.source!)) .toContain('/runtime/src/root.ts') expect(backgroundRuntimePosition).toMatchObject( generatedPositionAt( backgroundRuntimeSourceContent!, backgroundRuntimeSourceContent!.indexOf(backgroundRuntimeStatement), ), ) // clean cssConsumer.destroy() consumer.destroy() const mainMap = findSourceMap(debugMetadata, { filename: 'main-thread.js.map', })!.map as RawSourceMap const lazyMap = findSourceMap(asyncMetadata, { filename: 'main-thread.js.map', })!.map as RawSourceMap const mainThreadSource = await readFile( path.join(tmp, '.lynx/main/main-thread.js'), 'utf-8', ) const runtimeStatement = 'globalThis.lynxWorkletImpl = {' const runtimeOffset = mainThreadSource.indexOf(runtimeStatement) expect(runtimeOffset).toBeGreaterThan(-1) const runtimeSourceIndex = mainMap.sources.findIndex(source => normalizeSlashes(source).endsWith('/worklet-runtime/workletRuntime.ts') ) expect(runtimeSourceIndex).toBeGreaterThan(-1) const runtimeSourceContent = mainMap.sourcesContent?.[runtimeSourceIndex] expect(runtimeSourceContent).toContain(runtimeStatement) await SourceMapConsumer.with(mainMap, null, mainConsumer => { const runtimePosition = mainConsumer.originalPositionFor( generatedPositionAt(mainThreadSource, runtimeOffset), ) expect(normalizeSlashes(runtimePosition.source!)) .toContain('/worklet-runtime/workletRuntime.ts') expect(runtimePosition).toMatchObject( generatedPositionAt( runtimeSourceContent!, runtimeSourceContent!.indexOf(runtimeStatement), ), ) }) const lazySource = await readFile( path.join( tmp, '.lynx/lazy-bundle/fixtures_sourcemap_lazy-bundle-comp.tsx/main-thread.js', ), 'utf-8', ) const registrationOffset = lazySource.indexOf( '("main-thread",', ) expect(registrationOffset).toBeGreaterThan(-1) const registrationSourceOffset = lazySource.indexOf( '\'main thread\'', registrationOffset, ) expect(registrationSourceOffset).toBeGreaterThan(registrationOffset) const registrationPosition = generatedPositionAt( lazySource, registrationSourceOffset, ) await SourceMapConsumer.with(lazyMap, null, lazyConsumer => { const registrationSourcePosition = lazyConsumer.originalPositionFor( registrationPosition, ) const lazySourceIndex = lazyMap.sources.findIndex(source => normalizeSlashes(source).endsWith('/lazy-bundle-comp.tsx') ) expect(lazySourceIndex).toBeGreaterThan(-1) const lazySourceContent = lazyMap.sourcesContent?.[lazySourceIndex] expect(lazySourceContent).toContain('\'main thread\'') const authoredDirectivePosition = generatedPositionAt( lazySourceContent!, lazySourceContent!.indexOf('\'main thread\''), ) expect(registrationSourcePosition).toMatchObject({ source: new URL( './fixtures/sourcemap/lazy-bundle-comp.tsx', import.meta.url, ).href, line: authoredDirectivePosition.line, column: authoredDirectivePosition.column, }) }) }, 25_000, ) }) function normalizeSlashes(file: string) { return file.replaceAll(path.win32.sep, '/') } function generatedPositionAt(source: string, offset: number) { const linesBeforeOffset = source.slice(0, offset).split('\n') return { line: linesBeforeOffset.length, column: linesBeforeOffset.at(-1)!.length, } } function releaseOf(src: string): string | undefined { return (/var __DEBUG_METADATA_RELEASE__ = "([^"]+)"/.exec(src))?.[1] }