-
Notifications
You must be signed in to change notification settings - Fork 169
/
transformer.ts
168 lines (163 loc) · 6.15 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
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
import MagicString from "https://esm.sh/magic-string@0.26.1";
import { parseDeps, transform } from "../compiler/mod.ts";
import type { TransformOptions, TransformResult } from "../compiler/types.ts";
import { readCode } from "../lib/fs.ts";
import { restoreUrl, toLocalPath } from "../lib/helpers.ts";
import log from "../lib/log.ts";
import util from "../lib/util.ts";
import { bundleCSS } from "./bundle_css.ts";
import { getAlephPkgUri, getUnoGenerator, type JSXConfig } from "./config.ts";
import { isRouteFile } from "./routing.ts";
import { DependencyGraph } from "./graph.ts";
import type { ImportMap, ModuleLoaderContent } from "./types.ts";
export type TransformerOptions = {
buildHash: string;
buildTarget?: TransformOptions["target"];
importMap: ImportMap;
isDev: boolean;
jsxConfig?: JSXConfig;
loaded?: ModuleLoaderContent;
};
export default {
fetch: async (req: Request, options: TransformerOptions): Promise<Response> => {
const { isDev, buildHash, loaded } = options;
const { pathname, searchParams, search } = new URL(req.url);
const specifier = pathname.startsWith("/-/") ? restoreUrl(pathname + search) : `.${pathname}`;
let sourceCode: string;
let mtime: number | undefined;
let lang: string | undefined;
let isCSS: boolean;
let uno: boolean;
if (loaded) {
sourceCode = loaded.code;
mtime = loaded.modtime;
lang = loaded.lang;
isCSS = loaded.lang === "css";
uno = !!loaded.atomicCSS;
} else {
let codeType: string;
[sourceCode, mtime, codeType] = await readCode(specifier);
isCSS = codeType.startsWith("text/css");
uno = pathname.endsWith(".jsx") || pathname.endsWith(".tsx");
}
const etag = mtime
? `${mtime.toString(16)}-${sourceCode.length.toString(16)}-${
sourceCode.charCodeAt(Math.floor(sourceCode.length / 2)).toString(16)
}${buildHash.slice(0, 8)}`
: await util.computeHash("sha-1", sourceCode + buildHash);
if (req.headers.get("If-None-Match") === etag) {
return new Response(null, { status: 304 });
}
let clientDependencyGraph: DependencyGraph;
if (Reflect.has(globalThis, "clientDependencyGraph")) {
clientDependencyGraph = Reflect.get(globalThis, "clientDependencyGraph");
} else {
clientDependencyGraph = new DependencyGraph();
Reflect.set(globalThis, "clientDependencyGraph", clientDependencyGraph);
}
let resBody = "";
let resType = "application/javascript";
if (isCSS) {
const asJsModule = searchParams.has("module");
const { code, deps } = await bundleCSS(specifier, sourceCode, {
// todo: support borwserslist
targets: {
android: 95,
chrome: 95,
edge: 95,
firefox: 90,
safari: 14,
},
minify: !isDev,
cssModules: asJsModule && pathname.endsWith(".module.css"),
asJsModule,
hmr: isDev,
});
clientDependencyGraph.mark(specifier, { deps: deps?.map((specifier) => ({ specifier })) });
resBody = code;
if (!asJsModule) {
resType = "text/css";
}
} else {
const alephPkgUri = getAlephPkgUri();
const { jsxConfig, importMap, buildTarget } = options;
let ret: TransformResult;
if (/^https?:\/\/(cdn\.)esm\.sh\//.test(specifier)) {
// don't transform modules imported from esm.sh
const deps = await parseDeps(specifier, sourceCode, { importMap: JSON.stringify(importMap) });
if (deps.length > 0) {
const s = new MagicString(sourceCode);
deps.forEach((dep) => {
const { importUrl, loc } = dep;
if (loc) {
s.overwrite(loc.start, loc.end, `"${toLocalPath(importUrl)}"`);
}
});
ret = { code: s.toString(), deps };
} else {
ret = { code: sourceCode, deps };
}
} else {
const graphVersions = clientDependencyGraph.modules.filter((mod) =>
!util.isLikelyHttpURL(specifier) && !util.isLikelyHttpURL(mod.specifier) && mod.specifier !== specifier
).reduce((acc, { specifier, version }) => {
acc[specifier] = version.toString(16);
return acc;
}, {} as Record<string, string>);
ret = await transform(specifier, sourceCode, {
...jsxConfig,
lang: lang as TransformOptions["lang"],
stripDataExport: isRouteFile(specifier),
target: buildTarget ?? (isDev ? "es2022" : "es2015"),
alephPkgUri,
importMap: JSON.stringify(importMap),
graphVersions,
initialGraphVersion: clientDependencyGraph.initialVersion.toString(16),
isDev,
});
}
let { code, map, deps } = ret;
let inlineCSS = loaded?.inlineCSS;
if (uno) {
const unoGenerator = getUnoGenerator();
if (unoGenerator) {
const { css } = await unoGenerator.generate(sourceCode, { id: specifier, minify: !isDev });
if (inlineCSS) {
inlineCSS = `${inlineCSS}\n${css}`;
} else {
inlineCSS = css;
}
}
}
if (inlineCSS) {
code += `\nimport { applyCSS as __applyCSS } from "${
toLocalPath(alephPkgUri)
}/framework/core/style.ts";\n__applyCSS(${JSON.stringify(specifier)}, ${JSON.stringify(inlineCSS)});\n`;
deps = [...(deps || []), { specifier: alephPkgUri + "/framework/core/style.ts" }] as typeof deps;
}
clientDependencyGraph.mark(specifier, { deps });
if (map) {
try {
const m = JSON.parse(map);
if (!util.isLikelyHttpURL(specifier)) {
m.sources = [`file://source/${util.trimPrefix(specifier, ".")}`];
}
m.sourcesContent = [sourceCode];
resBody = code +
`\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(JSON.stringify(m))}\n`;
} catch (e) {
log.debug(`[dev] Failed to add source map for '${specifier}'`, e);
resBody = code;
}
} else {
resBody = code;
}
}
return new Response(resBody, {
headers: {
"Content-Type": `${resType}; charset=utf-8`,
"Etag": etag,
},
});
},
};