-
Notifications
You must be signed in to change notification settings - Fork 170
/
helpers.ts
324 lines (301 loc) · 10.9 KB
/
helpers.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
import { basename, dirname, globToRegExp, join } from "https://deno.land/std@0.142.0/path/mod.ts";
import { JSONC } from "https://deno.land/x/jsonc_parser@v0.0.1/src/jsonc.ts";
import { createGenerator, type UnoGenerator } from "../lib/@unocss/core.ts";
import { findFile } from "../lib/fs.ts";
import log from "../lib/log.ts";
import util from "../lib/util.ts";
import { isCanary, VERSION } from "../version.ts";
import type { AlephConfig, ImportMap, JSXConfig, ModuleLoader } from "./types.ts";
export const regFullVersion = /@\d+\.\d+\.\d+/;
export const builtinModuleExts = ["tsx", "ts", "mts", "jsx", "js", "mjs"];
/** Stores and returns the `fn` output in the `globalThis` object */
export async function globalIt<T>(name: string, fn: () => Promise<T>): Promise<T> {
const cache: T | undefined = Reflect.get(globalThis, name);
if (cache !== undefined) {
return cache;
}
const ret = await fn();
if (ret !== undefined) {
Reflect.set(globalThis, name, ret);
}
return ret;
}
/** Stores and returns the `fn` output in the `globalThis` object synchronously. */
export function globalItSync<T>(name: string, fn: () => T): T {
const cache: T | undefined = Reflect.get(globalThis, name);
if (cache !== undefined) {
return cache;
}
const ret = fn();
if (ret !== undefined) {
Reflect.set(globalThis, name, ret);
}
return ret;
}
/* Get Aleph.js package URI. */
export function getAlephPkgUri(): string {
return globalItSync("__ALEPH_PKG_URI", () => {
const uriFromEnv = Deno.env.get("ALEPH_PKG_URI");
if (uriFromEnv) {
return uriFromEnv;
}
const DEV_PORT = Deno.env.get("ALEPH_DEV_PORT");
if (DEV_PORT) {
return `http://localhost:${DEV_PORT}`;
}
const version = Deno.env.get("ALEPH_VERSION") || VERSION;
return `https://deno.land/x/${isCanary ? "aleph_canary" : "aleph"}@${version}`;
});
}
/** Get the UnoCSS generator, return `null` if the presets are empty. */
export function getUnoGenerator(): UnoGenerator | null {
const config: AlephConfig | undefined = Reflect.get(globalThis, "__ALEPH_CONFIG");
if (config === undefined) {
return null;
}
return globalItSync("__UNO_GENERATOR", () => {
if (config?.unocss?.presets) {
return createGenerator(config.unocss);
}
return null;
});
}
/** Get the deployment ID. */
export function getDeploymentId(): string | undefined {
return Deno.env.get("DENO_DEPLOYMENT_ID");
}
/**
* fix remote url to local path.
* e.g. `https://esm.sh/react@17.0.2?dev` -> `/-/esm.sh/react@17.0.2?dev`
*/
export function toLocalPath(url: string): string {
if (util.isLikelyHttpURL(url)) {
let { hostname, pathname, port, protocol, search } = new URL(url);
const isHttp = protocol === "http:";
if ((isHttp && port === "80") || (protocol === "https:" && port === "443")) {
port = "";
}
return [
"/-/",
isHttp && "http_",
hostname,
port && "_" + port,
util.trimSuffix(pathname, "/"),
search,
].filter(Boolean).join("");
}
return url;
}
/**
* restore the remote url from local path.
* e.g. `/-/esm.sh/react@17.0.2` -> `https://esm.sh/react@17.0.2`
*/
export function restoreUrl(pathname: string): string {
let [h, ...rest] = pathname.substring(3).split("/");
let protocol = "https";
if (h.startsWith("http_")) {
h = h.substring(5);
protocol = "http";
}
const [host, port] = h.split("_");
return `${protocol}://${host}${port ? ":" + port : ""}/${rest.join("/")}`;
}
/** init loaders in `CLI` mode, or use prebuild loaders */
export async function initModuleLoaders(importMap?: ImportMap): Promise<ModuleLoader[]> {
const loaders: ModuleLoader[] = [];
if (Deno.env.get("ALEPH_CLI")) {
const { imports, __filename } = importMap ?? await loadImportMap();
for (const key in imports) {
if (/^\*\.{?(\w+, ?)*\w+}?$/i.test(key)) {
let src = imports[key];
if (src.endsWith("!loader")) {
src = util.trimSuffix(src, "!loader");
if (src.startsWith("./") || src.startsWith("../")) {
src = "file://" + join(dirname(__filename), src);
}
let { default: loader } = await import(src);
if (typeof loader === "function") {
loader = new loader();
}
if (loader !== null && typeof loader === "object" && typeof loader.load === "function") {
const glob = "/**/" + key;
const reg = globToRegExp(glob);
const Loader = {
meta: { src, glob },
test: (pathname: string) => reg.test(pathname),
load: (pathname: string, env: Record<string, unknown>) => loader.load(pathname, env),
};
loaders.push(Loader);
}
}
}
}
}
return loaders;
}
/** Load the JSX config base the given import maps and the existing deno config. */
export async function loadJSXConfig(importMap: ImportMap): Promise<JSXConfig> {
const jsxConfig: JSXConfig = {};
const denoConfigFile = await findFile(["deno.jsonc", "deno.json", "tsconfig.json"]);
if (denoConfigFile) {
try {
const { compilerOptions } = await parseJSONFile(denoConfigFile);
const { jsx, jsxImportSource, jsxFactory } = (compilerOptions || {}) as Record<string, unknown>;
if (
(jsx === undefined || jsx === "react-jsx" || jsx === "react-jsxdev") &&
util.isFilledString(jsxImportSource)
) {
jsxConfig.jsxImportSource = jsxImportSource;
jsxConfig.jsxRuntime = jsxImportSource.includes("preact") ? "preact" : "react";
} else if (jsx === undefined || jsx === "react") {
jsxConfig.jsxRuntime = jsxFactory === "h" ? "preact" : "react";
}
} catch (error) {
log.error(`Failed to parse ${basename(denoConfigFile)}: ${error.message}`);
}
} else if (Deno.env.get("ALEPH_DEV")) {
const jsonFile = join(Deno.env.get("ALEPH_DEV_ROOT")!, "deno.json");
const { compilerOptions } = await parseJSONFile(jsonFile);
const { jsx, jsxImportSource, jsxFactory } = (compilerOptions || {}) as Record<string, unknown>;
if (
(jsx === undefined || jsx === "react-jsx" || jsx === "react-jsxdev") &&
util.isFilledString(jsxImportSource)
) {
jsxConfig.jsxImportSource = jsxImportSource;
jsxConfig.jsxRuntime = jsxImportSource.includes("preact") ? "preact" : "react";
} else if (jsx === undefined || jsx === "react") {
jsxConfig.jsxRuntime = jsxFactory === "h" ? "preact" : "react";
}
}
let fuzzRuntimeUrl: string | null = null;
for (const url of Object.values(importMap.imports)) {
let m = url.match(/^https?:\/\/esm\.sh\/(p?react)@(\d+\.\d+\.\d+(-[a-z\d.]+)*)(\?|$)/);
if (!m) {
m = url.match(/^https?:\/\/esm\.sh\/(p?react)@.+/);
}
if (m) {
const { searchParams } = new URL(url);
if (searchParams.has("pin")) {
jsxConfig.jsxRuntimeCdnVersion = util.trimPrefix(searchParams.get("pin")!, "v");
}
if (!jsxConfig.jsxRuntime) {
jsxConfig.jsxRuntime = m[1] as "react" | "preact";
}
if (m[2]) {
jsxConfig.jsxRuntimeVersion = m[2];
if (jsxConfig.jsxImportSource) {
jsxConfig.jsxImportSource = `https://esm.sh/${jsxConfig.jsxRuntime}@${m[2]}`;
}
} else {
fuzzRuntimeUrl = url;
}
break;
}
}
// get acctual react version from esm.sh
if (fuzzRuntimeUrl) {
log.info(`Checking ${jsxConfig.jsxRuntime} version...`);
const text = await fetch(fuzzRuntimeUrl).then((resp) => resp.text());
const m = text.match(/https?:\/\/cdn\.esm\.sh\/(v\d+)\/p?react@(\d+\.\d+\.\d+(-[a-z\d.]+)*)\//);
if (m) {
jsxConfig.jsxRuntimeCdnVersion = m[1].slice(1);
jsxConfig.jsxRuntimeVersion = m[2];
if (jsxConfig.jsxImportSource) {
jsxConfig.jsxImportSource = `https://esm.sh/${jsxConfig.jsxRuntime}@${m[2]}`;
}
log.info(`${jsxConfig.jsxRuntime}@${jsxConfig.jsxRuntimeVersion} is used`);
}
}
return jsxConfig;
}
/** Load the import maps from the json file. */
export async function loadImportMap(cwd?: string): Promise<ImportMap> {
const importMap: ImportMap = { __filename: "", imports: {}, scopes: {} };
if (Deno.env.get("ALEPH_DEV")) {
const alephPkgUri = Deno.env.get("ALEPH_PKG_URI") || `http://localhost:${Deno.env.get("ALEPH_DEV_PORT")}`;
const importMapFile = join(Deno.env.get("ALEPH_DEV_ROOT")!, "import_map.json");
const { __filename, imports, scopes } = await parseImportMap(importMapFile);
Object.assign(importMap, {
__filename,
imports: {
...imports,
"@unocss/": `${alephPkgUri}/lib/@unocss/`,
"aleph/": `${alephPkgUri}/`,
"aleph/server": `${alephPkgUri}/server/mod.ts`,
"aleph/react": `${alephPkgUri}/framework/react/mod.ts`,
"aleph/vue": `${alephPkgUri}/framework/vue/mod.ts`,
},
scopes,
});
}
const importMapFile = await findFile(
["import_map", "import-map", "importmap", "importMap"].map((v) => `${v}.json`),
cwd,
);
if (importMapFile) {
try {
const { __filename, imports, scopes } = await parseImportMap(importMapFile);
Object.assign(importMap, { __filename });
Object.assign(importMap.imports, imports);
Object.assign(importMap.scopes, scopes);
} catch (e) {
log.error("loadImportMap:", e.message);
}
}
return importMap;
}
export function applyImportMap(specifier: string, importMap: ImportMap): string {
if (specifier in importMap.imports) {
return importMap.imports[specifier];
}
for (const key in importMap.imports) {
if (key.endsWith("/") && specifier.startsWith(key)) {
return importMap.imports[key] + specifier.slice(key.length);
}
}
// todo: support scopes
return specifier;
}
export async function parseJSONFile(jsonFile: string): Promise<Record<string, unknown>> {
const raw = await Deno.readTextFile(jsonFile);
if (jsonFile.endsWith(".jsonc")) {
return JSONC.parse(raw);
}
return JSON.parse(raw);
}
export async function parseImportMap(importMapFile: string): Promise<ImportMap> {
const importMap: ImportMap = { __filename: importMapFile, imports: {}, scopes: {} };
const data = await parseJSONFile(importMapFile);
const imports: Record<string, string> = toStringMap(data.imports);
const scopes: Record<string, Record<string, string>> = {};
if (util.isPlainObject(data.scopes)) {
Object.entries(data.scopes).forEach(([scope, imports]) => {
scopes[scope] = toStringMap(imports);
});
}
Object.assign(importMap, { imports, scopes });
return importMap;
}
function toStringMap(v: unknown): Record<string, string> {
const m: Record<string, string> = {};
if (util.isPlainObject(v)) {
Object.entries(v).forEach(([key, value]) => {
if (key === "") {
return;
}
if (util.isFilledString(value)) {
m[key] = value;
return;
}
if (util.isFilledArray(value)) {
for (const v of value) {
if (util.isFilledString(v)) {
m[key] = v;
return;
}
}
}
});
}
return m;
}