-
Notifications
You must be signed in to change notification settings - Fork 39
/
compiler_transforms.ts
63 lines (56 loc) · 2.02 KB
/
compiler_transforms.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
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { ts } from "./mod.deps.ts";
// transform `import.meta.url` to a replacement that works in script modules
export const transformImportMeta: ts.TransformerFactory<ts.SourceFile> = (
context,
) => {
const factory = context.factory;
return (sourceFile) => ts.visitEachChild(sourceFile, visitNode, context);
function visitNode(node: ts.Node): ts.Node {
// find `import.meta.url`
if (
ts.isPropertyAccessExpression(node) &&
ts.isMetaProperty(node.expression) &&
node.expression.keywordToken === ts.SyntaxKind.ImportKeyword &&
ts.isIdentifier(node.name)
) {
if (node.name.escapedText === "url") {
return getReplacementImportMetaUrl();
} else if (node.name.escapedText === "main") {
return getReplacementImportMetaMain();
}
}
return ts.visitEachChild(node, visitNode, context);
}
function getReplacementImportMetaUrl() {
// Copy and pasted from ts-ast-viewer.com
// require("url").pathToFileURL(__filename).href
return factory.createPropertyAccessExpression(
factory.createCallExpression(
factory.createPropertyAccessExpression(
factory.createCallExpression(
factory.createIdentifier("require"),
undefined,
[factory.createStringLiteral("url")],
),
factory.createIdentifier("pathToFileURL"),
),
undefined,
[factory.createIdentifier("__filename")],
),
factory.createIdentifier("href"),
);
}
function getReplacementImportMetaMain() {
// Copy and pasted from ts-ast-viewer.com
// (require.main === module)
return factory.createParenthesizedExpression(factory.createBinaryExpression(
factory.createPropertyAccessExpression(
factory.createIdentifier("require"),
factory.createIdentifier("main"),
),
factory.createToken(ts.SyntaxKind.EqualsEqualsEqualsToken),
factory.createIdentifier("module"),
));
}
};