forked from sveltejs/svelte-preprocess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypescript.ts
538 lines (450 loc) · 12.8 KB
/
typescript.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
import { dirname, isAbsolute, join, resolve } from 'path';
import ts from 'typescript';
import { compile } from 'svelte/compiler';
import pkg from 'svelte/package.json';
import MagicString from 'magic-string';
import sorcery from 'sorcery';
import { throwTypescriptError } from '../modules/errors';
import { createTagRegex, parseAttributes, stripTags } from '../modules/markup';
import type { Transformer, Options, TransformerArgs } from '../types';
import { JAVASCRIPT_RESERVED_KEYWORD_SET } from '../modules/utils';
type CompilerOptions = ts.CompilerOptions;
type SourceMapChain = {
content: Record<string, string>;
sourcemaps: Record<string, object>;
};
type InternalTransformerOptions = TransformerArgs<Options.Typescript> & {
basePath: string;
compilerOptions: CompilerOptions;
};
const injectedCodeSeparator = 'const $$$$$$$$ = null;';
/**
* Map of valid tsconfigs (no errors). Key is the path.
*/
const tsconfigMap = new Map<string, any>();
function createFormatDiagnosticsHost(cwd: string): ts.FormatDiagnosticsHost {
return {
getCanonicalFileName: (fileName: string) =>
fileName.replace('.injected.ts', ''),
getCurrentDirectory: () => cwd,
getNewLine: () => ts.sys.newLine,
};
}
function formatDiagnostics(
diagnostics: ts.Diagnostic | ts.Diagnostic[],
basePath: string,
) {
if (Array.isArray(diagnostics)) {
return ts.formatDiagnosticsWithColorAndContext(
diagnostics,
createFormatDiagnosticsHost(basePath),
);
}
return ts.formatDiagnostic(
diagnostics,
createFormatDiagnosticsHost(basePath),
);
}
const importTransformer: ts.TransformerFactory<ts.SourceFile> = (context) => {
const visit: ts.Visitor = (node) => {
if (ts.isImportDeclaration(node)) {
if (node.importClause?.isTypeOnly) {
return ts.createEmptyStatement();
}
return ts.createImportDeclaration(
node.decorators,
node.modifiers,
node.importClause,
node.moduleSpecifier,
);
}
return ts.visitEachChild(node, (child) => visit(child), context);
};
return (node) => ts.visitNode(node, visit);
};
function getScriptContent(markup: string, module: boolean): string {
const regex = createTagRegex('script', 'gi');
let match: RegExpMatchArray | null;
while ((match = regex.exec(markup)) !== null) {
const { context } = parseAttributes(match[1] || '');
if ((context !== 'module' && !module) || (context === 'module' && module)) {
return match[2];
}
}
return '';
}
function createSourceMapChain({
filename,
content,
compilerOptions,
}: {
filename: string;
content: string;
compilerOptions: CompilerOptions;
}): SourceMapChain | undefined {
if (compilerOptions.sourceMap) {
return {
content: {
[filename]: content,
},
sourcemaps: {},
};
}
}
function injectVarsToCode({
content,
markup,
filename,
attributes,
sourceMapChain,
}: {
content: string;
markup?: string;
filename: string;
attributes?: Record<string, any>;
sourceMapChain?: SourceMapChain;
}): string {
if (!markup) return content;
const { vars } = compile(stripTags(markup), {
generate: false,
varsReport: 'full',
errorMode: 'warn',
filename,
});
const sep = `\n${injectedCodeSeparator}\n`;
const varnames = vars.map((v) =>
v.name.startsWith('$') && !v.name.startsWith('$$')
? `${v.name},${v.name.slice(1)}`
: v.name,
);
const contentForCodestores =
content +
// Append instance script content because it's valid
// to import a store in module script and autosubscribe to it in instance script
(attributes?.context === 'module' ? getScriptContent(markup, false) : '');
// This regex extracts all possible store variables
// TODO investigate if it's possible to achieve this with a
// TS transformer (previous attemps have failed)
const codestores = Array.from(
contentForCodestores.match(/\$[^\s();:,[\]{}.?!+-=*/~|&%<>^`"']+/g) || [],
(name) => name.slice(1),
).filter((name) => !JAVASCRIPT_RESERVED_KEYWORD_SET.has(name));
const varsString = [...codestores, ...varnames].join(',');
const injectedVars = `const $$vars$$ = [${varsString}];`;
// Append instance/markup script content because it's valid
// to import things in one and reference it in the other.
const injectedCode =
attributes?.context === 'module'
? `${sep}${getScriptContent(markup, false)}\n${injectedVars}`
: `${sep}${getScriptContent(markup, true)}\n${injectedVars}`;
if (sourceMapChain) {
const s = new MagicString(content);
s.append(injectedCode);
const fname = `${filename}.injected.ts`;
const code = s.toString();
const map = s.generateMap({
source: filename,
file: fname,
});
sourceMapChain.content[fname] = code;
sourceMapChain.sourcemaps[fname] = map;
return code;
}
return `${content}${injectedCode}`;
}
function stripInjectedCode({
transpiledCode,
markup,
filename,
sourceMapChain,
}: {
transpiledCode: string;
markup?: string;
filename: string;
sourceMapChain?: SourceMapChain;
}): string {
if (!markup) return transpiledCode;
const injectedCodeStart = transpiledCode.indexOf(injectedCodeSeparator);
if (sourceMapChain) {
const s = new MagicString(transpiledCode);
const st = s.snip(0, injectedCodeStart);
const source = `${filename}.transpiled.js`;
const file = `${filename}.js`;
const code = st.toString();
const map = st.generateMap({
source,
file,
});
sourceMapChain.content[file] = code;
sourceMapChain.sourcemaps[file] = map;
return code;
}
return transpiledCode.slice(0, injectedCodeStart);
}
async function concatSourceMaps({
filename,
markup,
sourceMapChain,
}: {
filename: string;
markup?: string;
sourceMapChain?: SourceMapChain;
}): Promise<string | object | undefined> {
if (!sourceMapChain) return;
if (!markup) {
return sourceMapChain.sourcemaps[`${filename}.js`];
}
const chain = await sorcery.load(`${filename}.js`, sourceMapChain);
return chain.apply();
}
function getCompilerOptions({
filename,
options,
basePath,
}: {
filename: string;
options: Options.Typescript;
basePath: string;
}): CompilerOptions {
const inputOptions = options.compilerOptions ?? {};
const { errors, options: convertedCompilerOptions } =
options.tsconfigFile !== false || options.tsconfigDirectory
? loadTsconfig(inputOptions, filename, options)
: ts.convertCompilerOptionsFromJson(inputOptions, basePath);
if (errors.length) {
throw new Error(formatDiagnostics(errors, basePath));
}
const compilerOptions: CompilerOptions = {
target: ts.ScriptTarget.ES2015,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
...(convertedCompilerOptions as CompilerOptions),
importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Error,
allowNonTsExtensions: true,
// Clear outDir since it causes source map issues when the files aren't actually written to disk.
outDir: undefined,
};
if (
compilerOptions.target === ts.ScriptTarget.ES3 ||
compilerOptions.target === ts.ScriptTarget.ES5
) {
throw new Error(
`Svelte only supports es6+ syntax. Set your 'compilerOptions.target' to 'es6' or higher.`,
);
}
return compilerOptions;
}
function transpileTs({
code,
fileName,
basePath,
options,
compilerOptions,
transformers,
}: {
code: string;
fileName: string;
basePath: string;
options: Options.Typescript;
compilerOptions: CompilerOptions;
transformers?: ts.CustomTransformers;
}): {
transpiledCode: string;
diagnostics: ts.Diagnostic[] | undefined;
sourceMapText: string | undefined;
} {
const {
outputText: transpiledCode,
sourceMapText,
diagnostics,
} = ts.transpileModule(code, {
fileName,
compilerOptions,
reportDiagnostics: options.reportDiagnostics !== false,
transformers,
});
if (diagnostics && diagnostics.length > 0) {
// could this be handled elsewhere?
const hasError = diagnostics.some(
(d) => d.category === ts.DiagnosticCategory.Error,
);
const formattedDiagnostics = formatDiagnostics(diagnostics, basePath);
console.log(formattedDiagnostics);
if (hasError) {
throwTypescriptError();
}
}
return { transpiledCode, sourceMapText, diagnostics };
}
export function loadTsconfig(
compilerOptionsJSON: any,
filename: string,
tsOptions: Options.Typescript,
) {
if (typeof tsOptions.tsconfigFile === 'boolean') {
return { errors: [], options: compilerOptionsJSON };
}
let basePath = process.cwd();
const fileDirectory = (tsOptions.tsconfigDirectory ||
dirname(filename)) as string;
let tsconfigFile =
tsOptions.tsconfigFile ||
ts.findConfigFile(fileDirectory, ts.sys.fileExists);
if (!tsconfigFile) {
return { errors: [], options: compilerOptionsJSON };
}
tsconfigFile = isAbsolute(tsconfigFile)
? tsconfigFile
: join(basePath, tsconfigFile);
basePath = dirname(tsconfigFile);
if (tsconfigMap.has(tsconfigFile)) {
return {
errors: [],
options: tsconfigMap.get(tsconfigFile),
};
}
const { error, config } = ts.readConfigFile(tsconfigFile, ts.sys.readFile);
if (error) {
throw new Error(formatDiagnostics(error, basePath));
}
// Do this so TS will not search for initial files which might take a while
config.include = [];
let { errors, options } = ts.parseJsonConfigFileContent(
config,
ts.sys,
basePath,
compilerOptionsJSON,
tsconfigFile,
);
// Filter out "no files found error"
errors = errors.filter((d) => d.code !== 18003);
if (errors.length === 0) {
tsconfigMap.set(tsconfigFile, options);
}
return { errors, options };
}
async function mixedImportsTranspiler({
content,
filename = 'source.svelte',
markup,
options = {},
attributes,
compilerOptions,
basePath,
}: InternalTransformerOptions) {
const sourceMapChain = createSourceMapChain({
filename,
content,
compilerOptions,
});
const injectedCode = injectVarsToCode({
content,
markup,
filename,
attributes,
sourceMapChain,
});
const { transpiledCode, sourceMapText, diagnostics } = transpileTs({
code: injectedCode,
fileName: `${filename}.injected.ts`,
basePath,
options,
compilerOptions,
});
if (sourceMapChain && sourceMapText) {
const fname = `${filename}.transpiled.js`;
sourceMapChain.content[fname] = transpiledCode;
sourceMapChain.sourcemaps[fname] = JSON.parse(sourceMapText);
}
const code = stripInjectedCode({
transpiledCode,
markup,
filename,
sourceMapChain,
});
// Sorcery tries to load the code/map from disk if it's empty,
// prevent that because it would try to load inexistent files
// https://github.com/Rich-Harris/sorcery/issues/167
if (!code) {
return { code, diagnostics };
}
const map = await concatSourceMaps({
filename,
markup,
sourceMapChain,
});
return {
code,
map,
diagnostics,
};
}
async function simpleTranspiler({
content,
filename = 'source.svelte',
options = {},
compilerOptions,
basePath,
}: InternalTransformerOptions) {
const { transpiledCode, sourceMapText, diagnostics } = transpileTs({
code: content,
// `preserveValueImports` essentially does the same as our import transformer,
// keeping all imports that are not type imports
transformers: compilerOptions.preserveValueImports
? undefined
: { before: [importTransformer] },
fileName: filename,
basePath,
options,
compilerOptions,
});
return {
code: transpiledCode,
map: sourceMapText,
diagnostics,
};
}
const transformer: Transformer<Options.Typescript> = async ({
content,
filename,
markup,
options = {},
attributes,
}) => {
const basePath = process.cwd();
if (filename == null) return { code: content };
filename = isAbsolute(filename) ? filename : resolve(basePath, filename);
const compilerOptions = getCompilerOptions({ filename, options, basePath });
const versionParts = pkg.version.split('.');
const canUseMixedImportsTranspiler =
+versionParts[0] > 3 || (+versionParts[0] === 3 && +versionParts[1] >= 39);
if (!canUseMixedImportsTranspiler && options.handleMixedImports) {
throw new Error(
'You need at least Svelte 3.39 to use the handleMixedImports option',
);
}
const handleMixedImports =
!compilerOptions.preserveValueImports &&
(options.handleMixedImports === false
? false
: options.handleMixedImports || canUseMixedImportsTranspiler);
return handleMixedImports
? mixedImportsTranspiler({
content,
filename,
markup,
options,
attributes,
compilerOptions,
basePath,
})
: simpleTranspiler({
content,
filename,
markup,
options,
attributes,
compilerOptions,
basePath,
});
};
export { transformer };