-
Notifications
You must be signed in to change notification settings - Fork 30
/
vite-plugin.ts
362 lines (315 loc) · 9.69 KB
/
vite-plugin.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import reactPlugin from "@vitejs/plugin-react";
import micromatch from "micromatch";
import { PluginOption, normalizePath } from "vite";
import virtual, { updateVirtualModule } from "vite-plugin-virtual";
import { makeRouteManifest } from "./make-route-manifest";
import path from "path";
import { htmlTemplate } from "./html-template";
import chalk from "chalk";
import { TransformOptions } from "@babel/core";
export interface RakkasVitePluginConfig {
srcDir: string;
pagesDir: string;
apiDir: string;
pageExtensions: string[];
endpointExtensions: string[];
apiRoot: string;
configDeps?: string[];
babel?: TransformOptions;
removeRequireHook: boolean;
onConfigChange?: () => void;
}
export async function rakkasVitePlugin(
config: RakkasVitePluginConfig,
): Promise<PluginOption[]> {
const {
srcDir,
pagesDir,
apiDir,
pageExtensions,
endpointExtensions,
apiRoot,
configDeps,
babel = {},
onConfigChange,
removeRequireHook,
} = config;
const componentExtensions = pageExtensions.join("|");
const PAGES = `/${pagesDir}/**/(*.)?page.(${componentExtensions})`;
const LAYOUTS = `/${pagesDir}/**/(*/)?layout.(${componentExtensions})`;
const apiExtensions = endpointExtensions.join("|");
const ENDPOINTS = `/${apiDir}/**/(*.)?endpoint.(${apiExtensions})`;
const MIDDLEWARE = `/${apiDir}/**/(*/)?middleware.(${apiExtensions})`;
const isPage = micromatch.matcher(srcDir + PAGES);
const isLayout = micromatch.matcher(srcDir + LAYOUTS);
const isEndpoint = micromatch.matcher(srcDir + ENDPOINTS);
const isMiddleware = micromatch.matcher(srcDir + MIDDLEWARE);
const indexHtmlPath = path.resolve("src", "index.html");
const normalizedIndexHtmlPath = normalizePath(indexHtmlPath);
const pageRoutesContent = await makeRouteManifest({
srcDir,
routesDir: pagesDir,
finalExtensions: componentExtensions,
wrapperExt: "layout",
leafExt: "page",
rootUrl: "/",
});
const apiRoutesContent = await makeRouteManifest({
srcDir,
routesDir: apiDir,
finalExtensions: apiExtensions,
wrapperExt: "middleware",
leafExt: "endpoint",
rootUrl: apiRoot + "/",
});
const virtualModules = virtual({
"virtual:rakkasjs:page-imports": `
const pages = import.meta.glob(${JSON.stringify(PAGES)});
const layouts = import.meta.glob(${JSON.stringify(LAYOUTS)});
export default Object.assign(pages, layouts);
`,
"virtual:rakkasjs:api-imports": `
const endpoints = import.meta.glob(${JSON.stringify(ENDPOINTS)});
const middleware = import.meta.glob(${JSON.stringify(MIDDLEWARE)});
export default Object.assign(endpoints, middleware);
`,
"virtual:rakkasjs:page-routes": pageRoutesContent,
"virtual:rakkasjs:api-routes": apiRoutesContent,
});
let ssr: boolean;
let command: "build" | "serve";
return [
virtualModules,
{
name: "rakkas",
enforce: "pre",
configResolved(config) {
if (removeRequireHook) {
// This hack is needed to remove a `require` call inserted by this builtin Vite plugin.
(config.plugins as any) = config.plugins.filter(
(x) => x && x.name !== "vite:ssr-require-hook",
);
}
ssr = !!config.build.ssr;
command = config.command;
},
configureServer(server) {
server.watcher.addListener("all", async (e: string, fn: string) => {
if ((isPage(fn) || isLayout(fn)) && (e === "add" || e === "unlink")) {
updateVirtualModule(
virtualModules,
"virtual:rakkasjs:page-routes",
await makeRouteManifest({
srcDir,
routesDir: pagesDir,
finalExtensions: componentExtensions,
wrapperExt: "layout",
leafExt: "page",
rootUrl: "/",
}),
);
} else if (
(isEndpoint(fn) || isMiddleware(fn)) &&
(e === "add" || e === "unlink")
) {
updateVirtualModule(
virtualModules,
"virtual:rakkasjs:api-routes",
await makeRouteManifest({
srcDir,
routesDir: apiDir,
finalExtensions: apiExtensions,
wrapperExt: "middleware",
leafExt: "endpoint",
rootUrl: config.apiRoot + "/",
}),
);
} else if (configDeps && configDeps.includes(fn) && onConfigChange) {
// eslint-disable-next-line no-console
console.log("Config file dependency", chalk.blue(fn), "changed");
onConfigChange();
}
});
},
buildStart() {
if (command === "build") return;
this.addWatchFile(srcDir + PAGES);
this.addWatchFile(srcDir + LAYOUTS);
this.addWatchFile(srcDir + ENDPOINTS);
this.addWatchFile(srcDir + MIDDLEWARE);
if (onConfigChange && configDeps) {
configDeps.forEach((dep) => this.addWatchFile(dep));
}
},
async resolveId(id, importer, options) {
const i = id.indexOf("virtual:rakkasjs");
if (i > 0) {
return this.resolve(id.slice(i), importer, options);
}
if (id === "rakkasjs/server") {
const result = await this.resolve(id, importer, {
...options,
skipSelf: true,
});
if (result) {
const qPos = result.id.indexOf("?");
if (qPos >= 0) {
result.id = result.id.slice(0, result.id.indexOf("?"));
}
}
return result;
} else if (id === "virtual:rakkasjs:server") {
const result = await this.resolve("rakkasjs/server");
return result;
} else if (id === "virtual:rakkasjs:placeholder-loader") {
const result = await this.resolve("rakkasjs/placeholder-loader");
if (result) {
const qPos = result.id.indexOf("?");
if (qPos >= 0) {
result.id = result.id.slice(0, result.id.indexOf("?"));
}
}
return result;
} else if (id === indexHtmlPath) {
return normalizedIndexHtmlPath;
} else if (id === "virtual:rakkasjs:start-client.js") {
return "virtual:rakkasjs:start-client.js";
} else if (id === "virtual:rakkasjs:client-hooks") {
const userVersion = await this.resolve(
path.resolve(srcDir, "client"),
importer,
{
...options,
skipSelf: true,
},
);
return userVersion || id;
} else if (id === "virtual:rakkasjs:server-hooks") {
const userVersion = await this.resolve(
path.resolve(srcDir, "server"),
importer,
{
...options,
skipSelf: true,
},
);
return userVersion || id;
} else if (id === "virtual:rakkasjs:common-hooks") {
const userVersion = await this.resolve(
path.resolve(srcDir, "common"),
importer,
{
...options,
skipSelf: true,
},
);
return userVersion || id;
} else if (id === "virtual:rakkasjs:placeholder") {
const userVersion = await this.resolve(
path.resolve(srcDir, "placeholder"),
importer,
{
...options,
skipSelf: true,
},
);
return userVersion || id;
}
},
async load(id) {
if (id === normalizedIndexHtmlPath) {
return htmlTemplate;
} else if (id === "virtual:rakkasjs:start-client.js") {
return `
import {startClient} from "rakkasjs/client";
import routes from "virtual:rakkasjs:page-routes";
startClient(routes);
`;
} else if (
id === "virtual:rakkasjs:client-hooks" ||
id === "virtual:rakkasjs:server-hooks" ||
id === "virtual:rakkasjs:common-hooks"
) {
// This bogus export is for silencing the "Generated an empty chunk" warning
return "export default null";
} else if (id === "virtual:rakkasjs:placeholder") {
return `export default () => "Loading..."`;
}
},
async transform(code, id, options) {
const ssr: boolean | undefined =
options && (options === true || (options as any).ssr);
if (ssr || command === "build") return;
if (isPage(id) || isLayout(id)) {
const idstr = JSON.stringify(id.slice(srcDir.length));
// return refreshHeader(idstr) + code + refreshFooter(idstr);
return code + refreshFooter(idstr);
}
return code;
},
async generateBundle() {
if (ssr) return;
// TODO: This is pretty stupid, we should just pass the import manifest to the caller using some other technique
const modules: Record<string, string[]> = {};
for (const id of this.getModuleIds()) {
const module = this.getModuleInfo(id);
if (!module) continue;
for (const importer of module.importers) {
modules[importer] = modules[importer] || [];
modules[importer].push(id);
}
}
const pageDeps: Record<string, string[]> = {};
for (const [id, deps] of Object.entries(modules)) {
if (!isPage(id) && !isLayout(id)) continue;
const depSet = new Set<string>();
// eslint-disable-next-line no-inner-declarations
function addDeps(deps: string[]) {
if (!deps.length) return;
const newDeps = new Set<string>();
for (const dep of deps) {
const imports = modules[dep];
if (!imports) continue;
imports.forEach((x) => {
if (!depSet.has(x)) {
depSet.add(x);
newDeps.add(x);
}
});
}
addDeps([...newDeps]);
}
const initialDeps = deps.map((x) => x);
addDeps(initialDeps);
pageDeps[normalizePath(path.relative(srcDir, id))] = [...depSet].map(
(x) => normalizePath(path.relative(srcDir, x)),
);
}
await this.emitFile({
type: "asset",
fileName: "import-manifest.json",
source: JSON.stringify(pageDeps),
});
},
},
...(reactPlugin({
exclude: [PAGES.slice(1), LAYOUTS.slice(1)],
babel,
}) as any),
];
}
const refreshFooter = (id: string) => `// $RefreshReg$()
if (import.meta.hot) {
import.meta.hot.accept((m) => {
function reload() {
if (window.__vite_plugin_react_timeout) {
requestAnimationFrame(reload);
} else {
window.$rakkas$reloader[${id}] && window.$rakkas$reloader[${id}](m);
}
}
console.log("Reloading", ${id});
reload();
});
}
`;