This repository has been archived by the owner on Dec 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nodeify.ts
205 lines (194 loc) · 5.35 KB
/
nodeify.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
import { writeAll } from "https://deno.land/[email protected]/io/util.ts";
import { red } from "https://deno.land/[email protected]/fmt/colors.ts";
import { toFileUrl } from "https://deno.land/[email protected]/path/mod.ts";
const filterDots = (path: string) => {
const segments = path.split("/");
const result: string[] = [];
for (const segment of segments) {
if (segment === "..") {
result.pop();
continue;
}
if (segment === ".") {
continue;
}
result.push(segment);
}
return result.join("/");
};
export const mapPath = (path: string) => {
const url = new URL(path, "file://.");
const proto = url.protocol.slice(0, -1);
const ext = url.pathname.endsWith(".js")
? ""
: url.pathname.endsWith(".d.ts")
? ""
: ".js";
return filterDots(`${proto}/${url.hostname}${url.pathname}${ext}`);
};
const replaceImportsInModule = (
path: string,
data: string,
outDir: string,
map: Record<string, string>,
fetched: string[],
) => {
const replaced = data.replace(
/from\s*["']([^"']+)["']/g,
(_, x: string) => {
if (/^https?:/.test(x) && x.endsWith(".js")) {
fetchJSModule(x, outDir, map, fetched).catch((err) =>
console.error(err.message)
);
}
return 'from "' +
(/^https?:/.test(x)
? ((y) => y.startsWith(".") ? y : "../" + y)(
"../".repeat(path.split("/").length - 2) + mapPath(x),
)
: ((y) =>
y.endsWith(".js") ? y : y + (y.endsWith(".d.ts") ? "" : ".js"))(
x.startsWith(".") ? x : "./" + x,
)) +
'"';
},
);
return replaced;
};
export const fetchJSModule = async (
url: string,
outDir: string,
map: Record<string, string>,
fetched: string[],
) => {
if (fetched.includes(url)) {
return;
}
fetched.push(url);
const res = await fetch(url);
const data = await res.text();
const path = `${outDir}/${mapPath(url)}`;
await Deno.mkdir(
path.split("/").slice(0, -1).join("/"),
{ recursive: true },
);
const file = await Deno.open(
path,
{ create: true, write: true, truncate: true },
);
await writeAll(
file,
new TextEncoder().encode(
replaceImportsInModule(path, data, outDir, map, fetched),
),
);
file.close();
};
const diagnosticMessageHelper = (d: Deno.Diagnostic): string[] => [
...d.messageText ? [d.messageText] : [],
...d.messageChain ? diagnosticMessageHelper(d.messageChain) : [],
];
const diagnosticMessage = (d: Deno.Diagnostic) =>
diagnosticMessageHelper(d).join("\n");
export const build = async (entrypoint: string, outDir: string) => {
await Deno.remove(outDir).catch(() => {});
await Deno.mkdir(outDir, { recursive: true });
const map: Record<string, string> = {};
const fetched: string[] = [];
const result = await Deno.emit(entrypoint, {
compilerOptions: {
allowJs: true,
checkJs: true,
declaration: true,
},
});
if (result.diagnostics.length > 0) {
for (const diag of result.diagnostics) {
if (diag.fileName?.endsWith(".js") && !diag.fileName.endsWith(".ts.js")) {
await fetchJSModule(diag.fileName, outDir, map, fetched);
}
}
result.diagnostics.forEach((d) =>
console.error(
[
`${red(diagnosticMessage(d))}`,
`\tin ${d.fileName}:${d.start?.line}:${d.start?.character}`,
// `\tat ${d.sourceLine}`,
].join("\n"),
)
);
// Deno.exit(1);
}
for (
const [name, file] of Object.entries(result.files)
.filter(([name]) => !name.endsWith(".map"))
.map(([name, file]) =>
name.startsWith("file:")
? ["." + name.slice(toFileUrl(Deno.cwd()).href.length), file]
: [name, file]
)
) {
const mapped = mapPath(name);
map[name] = mapped;
}
for (
const [name, file] of Object.entries(result.files).map(([name, file]) =>
name.startsWith("file:")
? ["." + name.slice(toFileUrl(Deno.cwd()).href.length), file]
: [name, file]
)
) {
const mapped = map[name];
if (!mapped) {
continue;
}
await Deno.mkdir(`${outDir}/${mapped}`.split("/").slice(0, -1).join("/"), {
recursive: true,
});
const replaced = replaceImportsInModule(name, file, outDir, map, fetched);
await Deno.writeTextFile(`${outDir}/${mapped}`, replaced);
}
const mappedEntrypoint = mapPath(entrypoint);
await Deno.writeTextFile(
`${outDir}/${mappedEntrypoint}`,
`import.meta.main = true;\n${await Deno.readTextFile(
`${outDir}/${mappedEntrypoint}`,
)}`,
);
await Deno.writeTextFile(
`${outDir}/index.js`,
`import "deno.ns/global";\nexport * from "./${mappedEntrypoint}";\n`,
);
const pack = JSON.parse(
await Deno.readTextFile(`${outDir}/package.json`).catch(() => ("{}")),
);
await Deno.writeTextFile(
`${outDir}/package.json`,
JSON.stringify(
{
...pack,
type: "module",
main: "./index.js",
"dependencies": {
"deno.ns": "^0.2.0",
},
},
null,
" ",
),
);
};
if (import.meta.main) {
const [entrypoint, outDir] = Deno.args;
if (!outDir) {
console.error("No outDir argument\nUsage: nodeify <entrypoint> <outDir>");
Deno.exit(1);
}
if (!entrypoint) {
console.error(
"No entrypoint argument\nUsage: nodeify <entrypoint> <outDir>",
);
Deno.exit(1);
}
await build(entrypoint, outDir);
}