-
Notifications
You must be signed in to change notification settings - Fork 382
/
transformer.ts
executable file
·92 lines (80 loc) · 2.54 KB
/
transformer.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
/*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: MIT
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
import * as path from 'path';
import { TransformerErrors, generateCompilerError, invariant } from '@lwc/errors';
import { NormalizedCompilerOptions, CompilerOptions, normalizeOptions } from '../compiler/options';
import styleTransform from './style';
import templateTransformer from './template';
import scriptTransformer from './javascript';
import { isString } from '../utils';
import { SourceMap } from '../compiler/compiler';
export interface FileTransformerResult {
code: string;
map: SourceMap | null;
}
/**
* Transforms the passed code. Returning a Promise of an object with the generated code, source map
* and gathered metadata.
*
* @deprecated Use transformSync instead.
*/
export function transform(
src: string,
filename: string,
options: CompilerOptions
): Promise<FileTransformerResult> {
validateArguments(src, filename);
return new Promise((resolve, reject) => {
try {
const res = transformSync(src, filename, options);
resolve(res);
} catch (error) {
reject(error);
}
});
}
/**
* Transform the passed source code. Returning an object with the generated code, source map and
* gathered metadata.
*/
export function transformSync(
src: string,
filename: string,
options: CompilerOptions
): FileTransformerResult {
validateArguments(src, filename);
return transformFile(src, filename, normalizeOptions(options));
}
function validateArguments(src: string, filename: string) {
invariant(isString(src), TransformerErrors.INVALID_SOURCE, [src]);
invariant(isString(filename), TransformerErrors.INVALID_ID, [filename]);
}
export function transformFile(
src: string,
filename: string,
options: NormalizedCompilerOptions
): FileTransformerResult {
let transformer;
switch (path.extname(filename)) {
case '.html':
transformer = templateTransformer;
break;
case '.css':
transformer = styleTransform;
break;
case '.ts':
case '.js':
transformer = scriptTransformer;
break;
default:
throw generateCompilerError(TransformerErrors.NO_AVAILABLE_TRANSFORMER, {
messageArgs: [filename],
origin: { filename },
});
}
return transformer(src, filename, options);
}