Skip to content

Commit 2f70ec8

Browse files
authored
fix(webpack): keep source map positions in native-class loaders (#11647)
The strip and downlevel loaders rewrite @nativeclass classes before ts-loader runs but returned no source map. The module's map then described the rewritten text: it embedded the ES5 output as the file's source, and every line after a native class resolved to the wrong line (11 lines off in a real 1000-line file). The strip loader also changed the line count when the decorator sat at the start of the file or after blank lines. The strip loader now keeps every newline it replaces and returns an exact map through webpack's ReplaceSource. The downlevel loader maps untouched code to itself and each downleveled class through the ES5 transpile's own map, so ts-loader composes a map back to the original file, including lines inside the class. Emitted code is unchanged. [skip ci]
1 parent 587460b commit 2f70ec8

4 files changed

Lines changed: 483 additions & 84 deletions

File tree

‎packages/webpack5/__tests__/loaders/native-class-loaders.spec.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ function createDownlevelContext(
2323
if (err) throw err;
2424
onDone(source || '', warnings);
2525
},
26+
async() {
27+
return this.callback.bind(this);
28+
},
2629
} as any;
2730
}
2831

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
import ts from 'typescript';
2+
import { SourceMapConsumer, SourceMapGenerator } from 'source-map';
3+
4+
import stripLoader from '../../src/loaders/native-class-strip-loader';
5+
import downlevelLoader from '../../src/loaders/native-class-downlevel-loader';
6+
7+
const RESOURCE = '/app/delegate.ts';
8+
9+
const SOURCE = [
10+
"import { Observable } from '@nativescript/core';",
11+
'',
12+
'',
13+
'@NativeClass()',
14+
'class Delegate extends NSObject {',
15+
'\tstatic ObjCProtocols = [];',
16+
'',
17+
'\tvalue = 1;',
18+
'',
19+
'\trun(): number {',
20+
'\t\treturn this.value + 1;',
21+
'\t}',
22+
'}',
23+
'',
24+
'export function afterClass(): number {',
25+
'\treturn (Delegate.new() as Delegate).run();',
26+
'}',
27+
'',
28+
'export const observable = new Observable();',
29+
].join('\n');
30+
31+
interface LoaderOutput {
32+
code: string;
33+
map?: any;
34+
}
35+
36+
function runLoader(loader: Function, content: string, map?: any) {
37+
return new Promise<LoaderOutput>((resolve, reject) => {
38+
const done = (err: Error | null, code?: string, outputMap?: any) =>
39+
err ? reject(err) : resolve({ code: code ?? '', map: outputMap });
40+
loader.call(
41+
{
42+
resourcePath: RESOURCE,
43+
emitWarning: () => {},
44+
callback: done,
45+
async: () => done,
46+
},
47+
content,
48+
map,
49+
);
50+
});
51+
}
52+
53+
// Compiles like ts-loader: its own map, composed with the incoming one.
54+
async function compileLikeTsLoader({ code, map }: LoaderOutput) {
55+
const output = ts.transpileModule(code, {
56+
fileName: RESOURCE,
57+
compilerOptions: {
58+
module: ts.ModuleKind.ESNext,
59+
target: ts.ScriptTarget.ES2020,
60+
sourceMap: true,
61+
},
62+
});
63+
const tsMap = Object.assign(JSON.parse(output.sourceMapText), {
64+
sources: [RESOURCE],
65+
sourcesContent: [code],
66+
});
67+
if (!map) {
68+
return { code: output.outputText, map: tsMap };
69+
}
70+
const tsConsumer = await new SourceMapConsumer(tsMap);
71+
const inputConsumer = await new SourceMapConsumer({ ...map, file: RESOURCE });
72+
const generator = SourceMapGenerator.fromSourceMap(tsConsumer);
73+
generator.applySourceMap(inputConsumer);
74+
tsConsumer.destroy();
75+
inputConsumer.destroy();
76+
return { code: output.outputText, map: generator.toJSON() };
77+
}
78+
79+
async function build(source: string) {
80+
const stripped = await runLoader(stripLoader, source);
81+
const downleveled = await runLoader(
82+
downlevelLoader,
83+
stripped.code,
84+
stripped.map,
85+
);
86+
return { downleveled, compiled: await compileLikeTsLoader(downleveled) };
87+
}
88+
89+
async function originalLine(output: LoaderOutput, needle: string) {
90+
const lines = output.code.split('\n');
91+
const line = lines.findIndex((text) => text.includes(needle));
92+
expect(line).toBeGreaterThanOrEqual(0);
93+
const consumer = await new SourceMapConsumer(output.map);
94+
try {
95+
return consumer.originalPositionFor({
96+
line: line + 1,
97+
column: lines[line].indexOf(needle),
98+
}).line;
99+
} finally {
100+
consumer.destroy();
101+
}
102+
}
103+
104+
describe('native-class loaders source maps', () => {
105+
it('maps code inside and after a downleveled class to its original line', async () => {
106+
const { downleveled, compiled } = await build(SOURCE);
107+
108+
expect(downleveled.code).not.toContain('class Delegate');
109+
expect(await originalLine(compiled, 'this.value + 1')).toBe(11);
110+
expect(await originalLine(compiled, 'afterClass')).toBe(15);
111+
expect(await originalLine(compiled, 'Delegate.new()')).toBe(16);
112+
expect(await originalLine(compiled, 'new Observable()')).toBe(19);
113+
});
114+
115+
it('embeds the original source in the composed map', async () => {
116+
const { compiled } = await build(SOURCE);
117+
118+
expect(compiled.map.sourcesContent).toEqual([SOURCE]);
119+
});
120+
121+
it('keeps the line count when stripping the decorator', async () => {
122+
const atStart = [
123+
'@NativeClass',
124+
'class A extends NSObject {}',
125+
'export const a = 1;',
126+
].join('\n');
127+
const afterBlankLines = [
128+
'const x = 1;',
129+
'',
130+
'',
131+
'@NativeClass({',
132+
'\tprotocols: [],',
133+
'})',
134+
'class B extends NSObject {}',
135+
].join('\n');
136+
137+
for (const source of [atStart, afterBlankLines]) {
138+
const stripped = await runLoader(stripLoader, source);
139+
expect(stripped.code).toContain('/*__NativeClass__*/');
140+
expect(stripped.code).not.toContain('@NativeClass');
141+
expect(stripped.code.split('\n').length).toBe(source.split('\n').length);
142+
}
143+
});
144+
});

0 commit comments

Comments
 (0)