forked from edgedb/edgedb-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compileForDeno.ts
217 lines (187 loc) · 6.36 KB
/
compileForDeno.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
import { ensureDir, walk } from "https://deno.land/[email protected]/fs/mod.ts";
import {
basename,
dirname,
join,
relative,
} from "https://deno.land/[email protected]/path/posix.ts";
import ts from "npm:typescript";
const normalisePath = (path: string) => path.replace(/\\/g, "/");
export async function run({
sourceDir,
destDir,
destEntriesToClean,
pathRewriteRules = [],
importRewriteRules = [],
injectImports = [],
sourceFilter,
}: {
sourceDir: string;
destDir: string;
destEntriesToClean?: string[];
pathRewriteRules?: { match: RegExp; replace: string }[];
importRewriteRules?: {
match: RegExp;
replace: string | ((match: string, sourcePath?: string) => string);
}[];
injectImports?: { imports: string[]; from: string }[];
sourceFilter?: (path: string) => boolean;
}) {
console.log(`Denoifying ${sourceDir}...`);
const destClean = new Set(destEntriesToClean);
try {
for await (const entry of Deno.readDir(destDir)) {
if (!destEntriesToClean || destClean.has(entry.name)) {
await Deno.remove(join(destDir, entry.name), { recursive: true });
}
}
} catch {}
const sourceFilePathMap = new Map<string, string>();
for await (const entry of walk(sourceDir, { includeDirs: false })) {
const sourcePath = normalisePath(entry.path);
if (sourceFilter && !sourceFilter(sourcePath)) {
continue;
}
sourceFilePathMap.set(sourcePath, resolveDestPath(sourcePath));
}
for (const [sourcePath, destPath] of sourceFilePathMap) {
compileFileForDeno(sourcePath, destPath);
}
async function compileFileForDeno(sourcePath: string, destPath: string) {
const file = await Deno.readTextFile(sourcePath);
await ensureDir(dirname(destPath));
if (destPath.endsWith(".deno.ts")) {
return await Deno.writeTextFile(destPath, file);
}
if (destPath.endsWith(".node.ts")) {
return;
}
const parsedSource = ts.createSourceFile(
basename(sourcePath),
file,
ts.ScriptTarget.Latest,
false,
ts.ScriptKind.TS
);
const rewrittenFile: string[] = [];
let cursor = 0;
let isFirstNode = true;
parsedSource.forEachChild((node: any) => {
if (isFirstNode) {
isFirstNode = false;
const neededImports = injectImports.reduce(
(neededImports, { imports, from }) => {
const usedImports = imports.filter((importName) =>
parsedSource.identifiers?.has(importName)
);
if (usedImports.length) {
neededImports.push({
imports: usedImports,
from,
});
}
return neededImports;
},
[] as { imports: string[]; from: string }[]
);
if (neededImports.length) {
const importDecls = neededImports.map((neededImport) => {
const imports = neededImport.imports.join(", ");
// no need to resolve path if it is import from url
const importPath = neededImport.from.startsWith("https://")
? neededImport.from
: resolveImportPath(
relative(dirname(sourcePath), neededImport.from),
sourcePath
);
return `import {${imports}} from "${importPath}";`;
});
const importDecl = importDecls.join("\n") + "\n\n";
const injectPos =
node.getLeadingTriviaWidth?.(parsedSource) ?? node.pos;
rewrittenFile.push(file.slice(cursor, injectPos));
rewrittenFile.push(importDecl);
cursor = injectPos;
}
}
if (
(node.kind === ts.SyntaxKind.ImportDeclaration ||
node.kind === ts.SyntaxKind.ExportDeclaration) &&
node.moduleSpecifier
) {
const pos = node.moduleSpecifier.pos + 2;
const end = node.moduleSpecifier.end - 1;
rewrittenFile.push(file.slice(cursor, pos));
cursor = end;
const importPath = file.slice(pos, end);
let resolvedImportPath = resolveImportPath(importPath, sourcePath);
for (const name of ["adapter", "adapter.shared", "adapter.crypto"]) {
if (resolvedImportPath.endsWith(`/${name}.node.ts`)) {
resolvedImportPath = resolvedImportPath.replace(
`/${name}.node.ts`,
`/${name}.deno.ts`
);
}
}
rewrittenFile.push(resolvedImportPath);
}
});
rewrittenFile.push(file.slice(cursor));
let contents = rewrittenFile.join("");
if (/__dirname/g.test(contents)) {
contents = contents.replaceAll(
/__dirname/g,
"new URL('.', import.meta.url).pathname"
);
}
await Deno.writeTextFile(destPath, contents);
}
function resolveDestPath(sourcePath: string) {
let destPath = sourcePath;
for (const rule of pathRewriteRules) {
destPath = destPath.replace(rule.match, rule.replace);
}
return join(destDir, destPath);
}
function resolveImportPath(importPath: string, sourcePath: string) {
// First check importRewriteRules
for (const rule of importRewriteRules) {
if (rule.match.test(importPath)) {
const path = importPath.replace(rule.match, (match) =>
typeof rule.replace === "function"
? rule.replace(match, sourcePath)
: rule.replace
);
if (
!path.endsWith(".ts") &&
!path.startsWith("node:") &&
!path.startsWith("npm:")
)
return path + ".ts";
return path;
}
}
// then resolve normally
let resolvedPath = join(dirname(sourcePath), importPath);
if (!sourceFilePathMap.has(resolvedPath)) {
// If importPath doesn't exist, first try appending '.ts'
resolvedPath = join(dirname(sourcePath), importPath + ".ts");
if (!sourceFilePathMap.has(resolvedPath)) {
// If that path doesn't exist, next try appending '/index.ts'
resolvedPath = join(dirname(sourcePath), importPath + "/index.ts");
if (!sourceFilePathMap.has(resolvedPath)) {
throw new Error(
`Cannot find imported file '${importPath}' in '${sourcePath}'`
);
}
}
}
const relImportPath = relative(
dirname(sourceFilePathMap.get(sourcePath)!),
sourceFilePathMap.get(resolvedPath)!
);
return relImportPath.startsWith("../")
? relImportPath
: "./" + relImportPath;
}
}