resuxjs 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1314 @@
1
+ #!/usr/bin/env node
2
+ import { createServer as createHttpServer } from "node:http";
3
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
4
+ import { createRequire } from "node:module";
5
+ import path from "node:path";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import vuePlugin from "@vitejs/plugin-vue";
8
+ import { createServer as createViteServer } from "vite";
9
+ import { buildProject } from "./compiler/index.js";
10
+ import { runCreateResux } from "./create.js";
11
+ import { renderApp, renderDocument } from "./runtime/index.js";
12
+ const version = "0.1.0";
13
+ const require = createRequire(import.meta.url);
14
+ let activeDevBuild = null;
15
+ let devBuildDirty = false;
16
+ let devBuildRevision = 0;
17
+ let devReloadRevision = 0;
18
+ const devReloadClients = new Set();
19
+ export function createResuxNodeHandler(options = {}) {
20
+ const appRoot = path.resolve(options.appRoot ?? process.cwd());
21
+ const outDir = path.resolve(options.outDir ?? path.join(appRoot, ".resux"));
22
+ const buildOptions = {};
23
+ return (request, response) => {
24
+ void handleRequest(request, response, {
25
+ appRoot,
26
+ outDir,
27
+ dev: false,
28
+ buildOptions,
29
+ securityHeaders: options.securityHeaders ?? true
30
+ });
31
+ };
32
+ }
33
+ if (isMainModule()) {
34
+ await runCli(process.argv.slice(2));
35
+ }
36
+ async function runCli(args) {
37
+ const command = readCommand(args);
38
+ const commandArgs = command === args[0] ? args.slice(1) : args;
39
+ if (command === "help") {
40
+ printHelp();
41
+ return;
42
+ }
43
+ if (command === "version") {
44
+ console.log(version);
45
+ return;
46
+ }
47
+ if (command === "init" || command === "create") {
48
+ await runCreateResux(commandArgs);
49
+ return;
50
+ }
51
+ const cliOptions = readCliOptions(commandArgs);
52
+ const appRoot = path.resolve(cliOptions.appRoot);
53
+ const outDir = path.join(appRoot, ".resux");
54
+ const buildOptions = {};
55
+ const securityHeaders = cliOptions.securityHeaders ?? command !== "dev";
56
+ const port = readPort(cliOptions.port ?? process.env.PORT, 3000);
57
+ try {
58
+ if (command === "build") {
59
+ const result = await buildProject(appRoot, outDir, { ...buildOptions, vite: "build" });
60
+ console.log(`Built ${result.routes.length} route(s) into ${path.relative(process.cwd(), outDir)}`);
61
+ }
62
+ else if (command === "deploy") {
63
+ await generateDeploymentFiles(appRoot, cliOptions.deployPreset, cliOptions.force);
64
+ }
65
+ else if (command === "inspect") {
66
+ await inspectProject(appRoot, outDir, buildOptions, cliOptions.json);
67
+ }
68
+ else if (command === "dev") {
69
+ await buildProject(appRoot, outDir, { ...buildOptions, vite: "dev" });
70
+ const vite = await startViteDevServer(outDir);
71
+ startDevWatcher(vite, appRoot, outDir, buildOptions);
72
+ await startServer({ appRoot, outDir, port, host: cliOptions.host, dev: true, buildOptions, vite, securityHeaders });
73
+ }
74
+ else if (command === "preview" || command === "start") {
75
+ if (await previewNeedsBuild(outDir, buildOptions)) {
76
+ await buildProject(appRoot, outDir, { ...buildOptions, vite: "build" });
77
+ }
78
+ await startServer({ appRoot, outDir, port, host: cliOptions.host, dev: false, buildOptions, securityHeaders });
79
+ }
80
+ else {
81
+ console.error(`Unknown command "${command}". Run resux --help for usage.`);
82
+ process.exitCode = 1;
83
+ }
84
+ }
85
+ catch (error) {
86
+ console.error(error instanceof Error ? error.stack ?? error.message : error);
87
+ process.exitCode = 1;
88
+ }
89
+ }
90
+ function isMainModule() {
91
+ return process.argv[1] ? path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) : false;
92
+ }
93
+ function readCommand(args) {
94
+ const first = args[0];
95
+ if (first === "init" || first === "create") {
96
+ return first;
97
+ }
98
+ if (args.includes("--help") || args.includes("-h")) {
99
+ return "help";
100
+ }
101
+ if (args.includes("--version") || args.includes("-v")) {
102
+ return "version";
103
+ }
104
+ if (!first || first.startsWith("-")) {
105
+ return "dev";
106
+ }
107
+ if (first === "help" || first === "version") {
108
+ return first;
109
+ }
110
+ return first;
111
+ }
112
+ function readCliOptions(args) {
113
+ let appRoot = process.cwd();
114
+ let port;
115
+ let host;
116
+ let securityHeaders;
117
+ let json = false;
118
+ let deployPreset = "node";
119
+ let force = false;
120
+ for (let index = 0; index < args.length; index++) {
121
+ const arg = args[index];
122
+ if (arg === "--security-headers") {
123
+ securityHeaders = true;
124
+ }
125
+ else if (arg === "--no-security-headers") {
126
+ securityHeaders = false;
127
+ }
128
+ else if (arg === "--json") {
129
+ json = true;
130
+ }
131
+ else if (arg === "--preset") {
132
+ deployPreset = readDeployPreset(readRequiredOptionValue(args[++index], arg));
133
+ }
134
+ else if (arg.startsWith("--preset=")) {
135
+ deployPreset = readDeployPreset(arg.slice("--preset=".length));
136
+ }
137
+ else if (arg === "--force") {
138
+ force = true;
139
+ }
140
+ else if (arg === "--port" || arg === "-p") {
141
+ port = readRequiredOptionValue(args[++index], arg);
142
+ }
143
+ else if (arg.startsWith("--port=")) {
144
+ port = arg.slice("--port=".length);
145
+ }
146
+ else if (arg === "--host") {
147
+ host = readRequiredOptionValue(args[++index], arg);
148
+ }
149
+ else if (arg.startsWith("--host=")) {
150
+ host = arg.slice("--host=".length);
151
+ }
152
+ else if (arg.startsWith("-")) {
153
+ throw new Error(`Unknown option "${arg}". Run resux --help for usage.`);
154
+ }
155
+ else if (!arg.startsWith("-")) {
156
+ appRoot = arg;
157
+ }
158
+ }
159
+ return { appRoot, port, host, securityHeaders, json, deployPreset, force };
160
+ }
161
+ function readRequiredOptionValue(value, option) {
162
+ if (!value || value.startsWith("-")) {
163
+ throw new Error(`${option} needs a value.`);
164
+ }
165
+ return value;
166
+ }
167
+ function readDeployPreset(value) {
168
+ if (value === "node" || value === "docker" || value === "nitro") {
169
+ return value;
170
+ }
171
+ throw new Error(`Unknown deploy preset "${value}". Expected "node", "docker", or "nitro".`);
172
+ }
173
+ async function previewNeedsBuild(outDir, buildOptions) {
174
+ if (!(await exists(path.join(outDir, "server", "manifest.mjs")))) {
175
+ return true;
176
+ }
177
+ try {
178
+ const manifest = JSON.parse(await readFile(path.join(outDir, "manifest.json"), "utf8"));
179
+ return manifest.features?.vite !== "build" || manifest.features?.server !== "bundle";
180
+ }
181
+ catch {
182
+ return true;
183
+ }
184
+ }
185
+ async function inspectProject(appRoot, outDir, buildOptions, json = false) {
186
+ if (await previewNeedsBuild(outDir, buildOptions)) {
187
+ await buildProject(appRoot, outDir, { ...buildOptions, vite: "build" });
188
+ }
189
+ const manifest = JSON.parse(await readFile(path.join(outDir, "manifest.json"), "utf8"));
190
+ const routeRules = manifest.routeRules ?? {};
191
+ const summary = {
192
+ appRoot,
193
+ outDir,
194
+ counts: {
195
+ routes: manifest.routes?.length ?? 0,
196
+ components: manifest.components?.length ?? 0,
197
+ layouts: manifest.layouts?.length ?? 0,
198
+ plugins: manifest.plugins?.length ?? 0,
199
+ middleware: manifest.middleware?.length ?? 0,
200
+ serverMiddleware: manifest.serverMiddleware?.length ?? 0,
201
+ serverHandlers: manifest.serverHandlers?.length ?? 0,
202
+ routeRules: Object.keys(routeRules).length
203
+ },
204
+ features: {
205
+ vite: manifest.features?.vite ?? "build",
206
+ server: manifest.features?.server ?? "modules"
207
+ },
208
+ routes: manifest.routes ?? [],
209
+ serverHandlers: manifest.serverHandlers ?? [],
210
+ routeRules,
211
+ diagnostics: createInspectDiagnostics(manifest)
212
+ };
213
+ if (json) {
214
+ console.log(JSON.stringify(summary, null, 2));
215
+ return;
216
+ }
217
+ console.log(`Resux app: ${summary.appRoot}`);
218
+ console.log(`Build dir: ${summary.outDir}`);
219
+ console.log(`Routes: ${summary.counts.routes}`);
220
+ console.log(`Components: ${summary.counts.components}`);
221
+ console.log(`Layouts: ${summary.counts.layouts}`);
222
+ console.log(`Plugins: ${summary.counts.plugins}`);
223
+ console.log(`Middleware: ${summary.counts.middleware}`);
224
+ console.log(`Server middleware: ${summary.counts.serverMiddleware}`);
225
+ console.log(`Server handlers: ${summary.counts.serverHandlers}`);
226
+ console.log(`Route rules: ${summary.counts.routeRules}`);
227
+ console.log(`Features: vite=${summary.features.vite}, server=${summary.features.server}`);
228
+ if (summary.diagnostics.length) {
229
+ console.log("\nDiagnostics");
230
+ for (const diagnostic of summary.diagnostics) {
231
+ console.log(` [${diagnostic.level}] ${diagnostic.message}`);
232
+ }
233
+ }
234
+ if (summary.routes.length) {
235
+ console.log("\nRoutes");
236
+ for (const route of summary.routes) {
237
+ console.log(` ${route.path} -> ${path.relative(appRoot, route.file)}`);
238
+ }
239
+ }
240
+ if (summary.serverHandlers.length) {
241
+ console.log("\nServer handlers");
242
+ for (const handler of summary.serverHandlers) {
243
+ console.log(` ${handler.path} -> ${path.relative(appRoot, handler.file)}`);
244
+ }
245
+ }
246
+ if (Object.keys(routeRules).length) {
247
+ console.log("\nRoute rules");
248
+ for (const [routePath, rule] of Object.entries(routeRules)) {
249
+ console.log(` ${routePath} ${JSON.stringify(rule)}`);
250
+ }
251
+ }
252
+ }
253
+ function createInspectDiagnostics(manifest) {
254
+ const diagnostics = [];
255
+ if (!manifest.routes?.length) {
256
+ diagnostics.push({ level: "warning", message: "No pages were discovered. Add .vue files under pages/." });
257
+ }
258
+ if (!manifest.serverHandlers?.length) {
259
+ diagnostics.push({ level: "info", message: "No server handlers were discovered under server/api or server/routes." });
260
+ }
261
+ if (!Object.keys(manifest.routeRules ?? {}).length) {
262
+ diagnostics.push({ level: "info", message: "No route rules are configured." });
263
+ }
264
+ return diagnostics;
265
+ }
266
+ async function generateDeploymentFiles(appRoot, preset, force) {
267
+ await assertDirectory(appRoot);
268
+ const files = [
269
+ {
270
+ relativePath: "DEPLOYMENT.md",
271
+ contents: createDeploymentGuide(preset)
272
+ },
273
+ ...(preset === "nitro"
274
+ ? [
275
+ {
276
+ relativePath: "nitro.config.ts",
277
+ contents: createNitroConfig()
278
+ },
279
+ {
280
+ relativePath: ".resux-nitro/handler.ts",
281
+ contents: createNitroHandler()
282
+ }
283
+ ]
284
+ : []),
285
+ ...(preset === "docker"
286
+ ? [
287
+ {
288
+ relativePath: "Dockerfile",
289
+ contents: createDockerfile()
290
+ },
291
+ {
292
+ relativePath: ".dockerignore",
293
+ contents: createDockerignore()
294
+ }
295
+ ]
296
+ : [])
297
+ ];
298
+ const written = [];
299
+ for (const file of files) {
300
+ written.push(await writeDeploymentFile(appRoot, file.relativePath, file.contents, force));
301
+ }
302
+ console.log(`Generated Resux ${preset} deployment file(s):`);
303
+ for (const file of written) {
304
+ console.log(` ${file}`);
305
+ }
306
+ }
307
+ async function assertDirectory(directory) {
308
+ const stats = await stat(directory);
309
+ if (!stats.isDirectory()) {
310
+ throw new Error(`${directory} is not a directory.`);
311
+ }
312
+ }
313
+ async function writeDeploymentFile(appRoot, relativePath, contents, force) {
314
+ const file = path.join(appRoot, relativePath);
315
+ if (!force && await exists(file)) {
316
+ throw new Error(`${relativePath} already exists. Re-run with --force to overwrite it.`);
317
+ }
318
+ await mkdir(path.dirname(file), { recursive: true });
319
+ await writeFile(file, contents, "utf8");
320
+ return relativePath;
321
+ }
322
+ function createDeploymentGuide(preset) {
323
+ const dockerSection = preset === "docker"
324
+ ? `
325
+ ## Docker
326
+
327
+ \`\`\`sh
328
+ docker build -t resux-app .
329
+ docker run --rm -p 3000:3000 resux-app
330
+ \`\`\`
331
+ `
332
+ : "";
333
+ const nitroSection = preset === "nitro"
334
+ ? `
335
+ ## Nitro
336
+
337
+ Install the Nitro build dependencies:
338
+
339
+ \`\`\`sh
340
+ npm install -D nitropack h3
341
+ \`\`\`
342
+
343
+ Build Resux first, then build the Nitro server:
344
+
345
+ \`\`\`sh
346
+ npm run build
347
+ npx nitro build
348
+ node .output/server/index.mjs
349
+ \`\`\`
350
+
351
+ Nitro reads \`NITRO_PRESET\` for provider-specific output. For example:
352
+
353
+ \`\`\`sh
354
+ NITRO_PRESET=vercel npx nitro build
355
+ \`\`\`
356
+
357
+ The generated Nitro handler wraps the Resux Node request handler, so deploy \`.resux\` with the Nitro output unless your platform runs the Nitro build from the project root.
358
+ `
359
+ : "";
360
+ return `# Deployment
361
+
362
+ ## Node Server
363
+
364
+ \`\`\`sh
365
+ npm install
366
+ npm run build
367
+ npm run start
368
+ \`\`\`
369
+
370
+ The production server reads \`PORT\`, so most Node hosts can run the same start command:
371
+
372
+ \`\`\`sh
373
+ PORT=3000 npm run start
374
+ \`\`\`
375
+
376
+ Health checks can call:
377
+
378
+ \`\`\`txt
379
+ /__resux/health
380
+ \`\`\`
381
+ ${dockerSection}
382
+ ${nitroSection}
383
+ ## Diagnostics
384
+
385
+ \`\`\`sh
386
+ npm run inspect
387
+ npm run inspect -- --json
388
+ \`\`\`
389
+
390
+ Production serving enables Resux default security headers. Disable them only when a host or reverse proxy owns those headers:
391
+
392
+ \`\`\`sh
393
+ resux start . --no-security-headers
394
+ \`\`\`
395
+ `;
396
+ }
397
+ function createNitroConfig() {
398
+ return `import { defineNitroConfig } from "nitropack/config";
399
+
400
+ export default defineNitroConfig({
401
+ handlers: [
402
+ {
403
+ route: "/**",
404
+ handler: "./.resux-nitro/handler.ts"
405
+ }
406
+ ],
407
+ routeRules: {
408
+ "/__resux/route": {
409
+ headers: {
410
+ "cache-control": "no-store"
411
+ }
412
+ },
413
+ "/__resux/dev-events": {
414
+ headers: {
415
+ "cache-control": "no-store"
416
+ }
417
+ },
418
+ "/__resux/handlers/**": {
419
+ headers: {
420
+ "cache-control": "public, max-age=31536000, immutable"
421
+ }
422
+ },
423
+ "/__resux/vue-islands/**": {
424
+ headers: {
425
+ "cache-control": "public, max-age=31536000, immutable"
426
+ }
427
+ },
428
+ "/__resux/runtime-client.mjs": {
429
+ headers: {
430
+ "cache-control": "public, max-age=31536000, immutable"
431
+ }
432
+ },
433
+ "/api/**": {
434
+ headers: {
435
+ "cache-control": "no-store"
436
+ }
437
+ },
438
+ "/**": {
439
+ headers: {
440
+ "cache-control": "no-store"
441
+ }
442
+ }
443
+ },
444
+ prerender: {
445
+ crawlLinks: false,
446
+ routes: []
447
+ }
448
+ });
449
+ `;
450
+ }
451
+ function createNitroHandler() {
452
+ return `import { fromNodeMiddleware } from "h3";
453
+ import { createResuxNodeHandler } from "resuxjs/node";
454
+
455
+ export default fromNodeMiddleware(createResuxNodeHandler());
456
+ `;
457
+ }
458
+ function createDockerfile() {
459
+ return `FROM node:24-alpine AS build
460
+ WORKDIR /app
461
+ COPY package*.json ./
462
+ RUN npm install
463
+ COPY . .
464
+ RUN npm run build
465
+ RUN npm prune --omit=dev
466
+
467
+ FROM node:24-alpine AS runner
468
+ WORKDIR /app
469
+ ENV NODE_ENV=production
470
+ ENV PORT=3000
471
+ COPY --from=build /app /app
472
+ EXPOSE 3000
473
+ CMD ["npm", "run", "start"]
474
+ `;
475
+ }
476
+ function createDockerignore() {
477
+ return `node_modules
478
+ .resux
479
+ dist
480
+ .git
481
+ *.log
482
+ .env
483
+ .env.*
484
+ `;
485
+ }
486
+ async function startViteDevServer(outDir) {
487
+ const vite = await createViteServer({
488
+ root: path.join(outDir, "vite-client"),
489
+ configFile: false,
490
+ publicDir: false,
491
+ appType: "custom",
492
+ clearScreen: false,
493
+ logLevel: "warn",
494
+ plugins: [vuePlugin()],
495
+ resolve: {
496
+ alias: {
497
+ "/__resux/runtime-client.mjs": path.join(outDir, "vite-client", "runtime-client.mjs"),
498
+ vue: require.resolve("vue")
499
+ }
500
+ },
501
+ server: {
502
+ middlewareMode: true,
503
+ hmr: false,
504
+ watch: {
505
+ ignored: ["**/.resux/**", "**/node_modules/**"]
506
+ }
507
+ }
508
+ });
509
+ console.log("Vite dev middleware ready for Resux client modules.");
510
+ return vite;
511
+ }
512
+ function startDevWatcher(vite, appRoot, outDir, buildOptions) {
513
+ vite.watcher.add(appRoot);
514
+ vite.watcher.on("all", (_event, changedPath) => {
515
+ if (shouldSkipDevWatch(changedPath, appRoot, outDir)) {
516
+ return;
517
+ }
518
+ devBuildDirty = true;
519
+ void ensureDevBuild(appRoot, outDir, buildOptions, vite)
520
+ .then((rebuilt) => {
521
+ if (rebuilt) {
522
+ notifyDevReloadClients("hmr");
523
+ }
524
+ })
525
+ .catch((error) => {
526
+ console.error(error instanceof Error ? error.stack ?? error.message : error);
527
+ });
528
+ });
529
+ }
530
+ function shouldSkipDevWatch(changedPath, appRoot, outDir) {
531
+ const resolved = path.resolve(changedPath);
532
+ return resolved.startsWith(path.resolve(outDir))
533
+ || resolved.includes(`${path.sep}node_modules${path.sep}`)
534
+ || resolved.includes(`${path.sep}dist${path.sep}`)
535
+ || !resolved.startsWith(path.resolve(appRoot));
536
+ }
537
+ async function startServer(options) {
538
+ const server = createHttpServer((request, response) => {
539
+ void handleRequest(request, response, options);
540
+ });
541
+ const boundPort = await listenOnAvailablePort(server, options.port, options.host);
542
+ if (boundPort !== options.port) {
543
+ console.log(`Port ${options.port} is busy, using ${boundPort} instead.`);
544
+ }
545
+ console.log(`Resux ${options.dev ? "dev" : "preview"} server running at http://${options.host ?? "localhost"}:${boundPort}`);
546
+ }
547
+ async function listenOnAvailablePort(server, requestedPort, host) {
548
+ const maxAttempts = 20;
549
+ for (let offset = 0; offset < maxAttempts; offset++) {
550
+ const portToTry = requestedPort + offset;
551
+ try {
552
+ await listen(server, portToTry, host);
553
+ return portToTry;
554
+ }
555
+ catch (error) {
556
+ if (!isAddressInUse(error) || offset === maxAttempts - 1) {
557
+ throw error;
558
+ }
559
+ }
560
+ }
561
+ throw new Error(`No available port found from ${requestedPort} to ${requestedPort + maxAttempts - 1}.`);
562
+ }
563
+ function listen(server, portToTry, host) {
564
+ return new Promise((resolve, reject) => {
565
+ const onError = (error) => {
566
+ server.off("listening", onListening);
567
+ reject(error);
568
+ };
569
+ const onListening = () => {
570
+ server.off("error", onError);
571
+ resolve();
572
+ };
573
+ server.once("error", onError);
574
+ server.once("listening", onListening);
575
+ server.listen(portToTry, host);
576
+ });
577
+ }
578
+ function isAddressInUse(error) {
579
+ return error instanceof Error && "code" in error && error.code === "EADDRINUSE";
580
+ }
581
+ function readPort(value, fallback) {
582
+ if (!value) {
583
+ return fallback;
584
+ }
585
+ const parsed = Number(value);
586
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
587
+ throw new Error(`PORT must be an integer from 1 to 65535. Received "${value}".`);
588
+ }
589
+ return parsed;
590
+ }
591
+ function printHelp() {
592
+ console.log(`resux ${version}
593
+
594
+ Usage:
595
+ resux dev [app-root] [options]
596
+ resux init [project-dir] [options]
597
+ resux build [app-root] [options]
598
+ resux preview [app-root] [options]
599
+ resux start [app-root] [options]
600
+ resux inspect [app-root] [options]
601
+ resux deploy [app-root] [options]
602
+
603
+ Commands:
604
+ init Scaffold a new Resux app
605
+ dev Start the Resux dev server with Vite middleware
606
+ build Build server and client output into .resux
607
+ preview Serve the built app, rebuilding when needed
608
+ start Alias for preview, intended for production Node servers
609
+ inspect Print a build manifest summary for debugging
610
+ deploy Generate Node, Docker, or Nitro deployment files
611
+
612
+ Options:
613
+ --security-headers Enable default production security headers
614
+ --no-security-headers
615
+ Disable default production security headers
616
+ --json Print JSON output for inspect
617
+ --preset <preset> Deployment preset for deploy: node, docker, or nitro
618
+ --force Overwrite existing deployment files
619
+ -p, --port <port> Set the server port, default 3000 or PORT
620
+ --host <host> Set the server host
621
+ -v, --version Print the Resux version
622
+ -h, --help Show this help message
623
+ `);
624
+ }
625
+ async function handleRequest(request, response, options) {
626
+ const requestUrl = new URL(request.url ?? "/", "http://localhost");
627
+ try {
628
+ applyDefaultSecurityHeaders(response, options.securityHeaders);
629
+ if (options.dev && options.vite && isViteInternalRequest(requestUrl.pathname)) {
630
+ await serveViteMiddleware(request, response, options.vite);
631
+ return;
632
+ }
633
+ if (options.dev && requestUrl.pathname === "/__resux/dev-events") {
634
+ serveDevEvents(request, response);
635
+ return;
636
+ }
637
+ if (requestUrl.pathname === "/__resux/health") {
638
+ await serveHealthCheck(response, options);
639
+ return;
640
+ }
641
+ if (requestUrl.pathname === "/__resux/route") {
642
+ await serveRoutePayload(response, requestUrl, options);
643
+ return;
644
+ }
645
+ if (requestUrl.pathname.startsWith("/__resux/")) {
646
+ if (activeDevBuild) {
647
+ await activeDevBuild;
648
+ }
649
+ if (options.dev && options.vite && resolveResuxViteAssetUrl(requestUrl.pathname)) {
650
+ await serveViteResuxAsset(response, options.vite, requestUrl.pathname);
651
+ return;
652
+ }
653
+ await serveResuxAsset(response, options.outDir, requestUrl.pathname);
654
+ return;
655
+ }
656
+ if (options.dev) {
657
+ await ensureDevBuild(options.appRoot, options.outDir, options.buildOptions, options.vite);
658
+ }
659
+ const manifest = await importManifest(options.outDir, options.dev);
660
+ const routeRule = matchRouteRule(manifest.routeRules, requestUrl.pathname);
661
+ applyRouteRuleHeaders(response, routeRule);
662
+ if (routeRule?.cors && request.method === "OPTIONS") {
663
+ response.writeHead(204);
664
+ response.end();
665
+ return;
666
+ }
667
+ const middlewareHandled = await runServerMiddleware(request, response, requestUrl, manifest);
668
+ if (middlewareHandled) {
669
+ return;
670
+ }
671
+ if (routeRule?.redirect) {
672
+ serveRouteRuleRedirect(response, routeRule.redirect);
673
+ return;
674
+ }
675
+ const serverHandled = await serveServerHandler(request, response, requestUrl, manifest, routeRule);
676
+ if (serverHandled) {
677
+ return;
678
+ }
679
+ const publicHandled = await servePublicFile(response, options.appRoot, requestUrl.pathname);
680
+ if (publicHandled) {
681
+ return;
682
+ }
683
+ const rendered = await renderRoute(requestUrl, options, manifest);
684
+ if (!rendered) {
685
+ await serveErrorDocument(response, options, manifest, 404, "Page not found");
686
+ return;
687
+ }
688
+ if ("type" in rendered && rendered.type === "redirect") {
689
+ response.writeHead(rendered.statusCode, { location: rendered.to });
690
+ response.end();
691
+ return;
692
+ }
693
+ if ("type" in rendered && rendered.type === "abort") {
694
+ response.writeHead(rendered.statusCode, { "content-type": "text/plain; charset=utf-8" });
695
+ response.end(rendered.message);
696
+ return;
697
+ }
698
+ const html = renderDocument(rendered, "Resux App", { devReload: options.dev });
699
+ response.writeHead(routeRule?.statusCode ?? 200, { "content-type": "text/html; charset=utf-8" });
700
+ response.end(html);
701
+ }
702
+ catch (error) {
703
+ if (response.writableEnded) {
704
+ return;
705
+ }
706
+ await serveErrorDocument(response, options, undefined, 500, error);
707
+ }
708
+ }
709
+ async function serveErrorDocument(response, options, loadedManifest, statusCode, error) {
710
+ const statusMessage = statusCode === 404 ? "Not Found" : "Internal Server Error";
711
+ const errorPayload = createErrorPayload(error, statusCode, statusMessage, options.dev);
712
+ try {
713
+ const manifest = loadedManifest ?? await importManifest(options.outDir, options.dev);
714
+ if (manifest.errorComponent) {
715
+ const rendered = await renderApp({
716
+ app: manifest.app,
717
+ page: manifest.errorComponent,
718
+ pageProps: {
719
+ error: errorPayload
720
+ },
721
+ route: {
722
+ path: statusCode === 404 ? "/404" : "/500",
723
+ params: {},
724
+ query: {}
725
+ },
726
+ components: manifest.components,
727
+ layouts: manifest.layouts,
728
+ modules: manifest.modules,
729
+ vueIslands: manifest.vueIslands,
730
+ runtimeConfig: manifest.runtimeConfig,
731
+ appHead: manifest.appHead,
732
+ plugins: manifest.plugins
733
+ });
734
+ response.writeHead(statusCode, { "content-type": "text/html; charset=utf-8" });
735
+ response.end(renderDocument(rendered, statusMessage, { devReload: options.dev }));
736
+ return;
737
+ }
738
+ }
739
+ catch {
740
+ // Fall back to plain text below if the error component cannot render.
741
+ }
742
+ response.writeHead(statusCode, { "content-type": "text/plain; charset=utf-8" });
743
+ response.end(createPlainErrorBody(errorPayload, options.dev));
744
+ }
745
+ async function serveHealthCheck(response, options) {
746
+ if (options.dev) {
747
+ await ensureDevBuild(options.appRoot, options.outDir, options.buildOptions, options.vite);
748
+ }
749
+ const manifest = JSON.parse(await readFile(path.join(options.outDir, "manifest.json"), "utf8"));
750
+ const body = {
751
+ status: "ok",
752
+ framework: "resux",
753
+ mode: options.dev ? "dev" : "production",
754
+ counts: {
755
+ routes: manifest.routes?.length ?? 0,
756
+ serverMiddleware: manifest.serverMiddleware?.length ?? 0,
757
+ serverHandlers: manifest.serverHandlers?.length ?? 0,
758
+ routeRules: Object.keys(manifest.routeRules ?? {}).length
759
+ },
760
+ features: {
761
+ vite: manifest.features?.vite ?? (options.dev ? "dev" : "build"),
762
+ server: manifest.features?.server ?? (options.dev ? "modules" : "bundle")
763
+ }
764
+ };
765
+ response.writeHead(200, {
766
+ "content-type": "application/json; charset=utf-8",
767
+ "cache-control": "no-store"
768
+ });
769
+ response.end(JSON.stringify(body));
770
+ }
771
+ function createErrorPayload(error, statusCode, statusMessage, dev) {
772
+ const message = error instanceof Error ? error.message : String(error);
773
+ const payload = {
774
+ statusCode,
775
+ statusMessage,
776
+ message
777
+ };
778
+ if (dev && error instanceof Error) {
779
+ payload.name = error.name;
780
+ payload.stack = error.stack;
781
+ if ("cause" in error && error.cause) {
782
+ payload.cause = serializeErrorCause(error.cause);
783
+ }
784
+ }
785
+ return payload;
786
+ }
787
+ function serializeErrorCause(cause) {
788
+ if (cause instanceof Error) {
789
+ return {
790
+ name: cause.name,
791
+ message: cause.message,
792
+ stack: cause.stack
793
+ };
794
+ }
795
+ return cause;
796
+ }
797
+ function createPlainErrorBody(error, dev) {
798
+ if (error.statusCode === 404) {
799
+ return "Not found";
800
+ }
801
+ if (dev && error.stack) {
802
+ return error.stack;
803
+ }
804
+ return error.message;
805
+ }
806
+ async function serveRoutePayload(response, requestUrl, options) {
807
+ const targetPath = requestUrl.searchParams.get("path");
808
+ if (!targetPath || !targetPath.startsWith("/")) {
809
+ response.writeHead(400, { "content-type": "application/json; charset=utf-8" });
810
+ response.end(JSON.stringify({ error: "Route payload requests need a path query like /__resux/route?path=/post/42." }));
811
+ return;
812
+ }
813
+ const targetUrl = new URL(targetPath, "http://localhost");
814
+ if (options.dev) {
815
+ await ensureDevBuild(options.appRoot, options.outDir, options.buildOptions, options.vite);
816
+ }
817
+ const manifest = await importManifest(options.outDir, options.dev);
818
+ const routeRule = matchRouteRule(manifest.routeRules, targetUrl.pathname);
819
+ if (routeRule?.redirect) {
820
+ const redirect = normalizeRouteRuleRedirect(routeRule.redirect);
821
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8" });
822
+ response.end(JSON.stringify({ redirect: redirect.to, statusCode: redirect.statusCode }));
823
+ return;
824
+ }
825
+ const rendered = await renderRoute(targetUrl, options, manifest);
826
+ if (!rendered) {
827
+ response.writeHead(404, { "content-type": "application/json; charset=utf-8" });
828
+ response.end(JSON.stringify({ error: "Not found" }));
829
+ return;
830
+ }
831
+ if ("type" in rendered && rendered.type === "redirect") {
832
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8" });
833
+ response.end(JSON.stringify({ redirect: rendered.to, statusCode: rendered.statusCode }));
834
+ return;
835
+ }
836
+ if ("type" in rendered && rendered.type === "abort") {
837
+ response.writeHead(rendered.statusCode, { "content-type": "application/json; charset=utf-8" });
838
+ response.end(JSON.stringify({ error: rendered.message }));
839
+ return;
840
+ }
841
+ response.writeHead(200, {
842
+ "content-type": "application/json; charset=utf-8",
843
+ "cache-control": "no-store"
844
+ });
845
+ response.end(JSON.stringify(rendered));
846
+ }
847
+ function applyDefaultSecurityHeaders(response, enabled) {
848
+ if (!enabled) {
849
+ return;
850
+ }
851
+ setHeaderIfUnset(response, "x-content-type-options", "nosniff");
852
+ setHeaderIfUnset(response, "referrer-policy", "strict-origin-when-cross-origin");
853
+ setHeaderIfUnset(response, "x-frame-options", "SAMEORIGIN");
854
+ setHeaderIfUnset(response, "cross-origin-opener-policy", "same-origin");
855
+ setHeaderIfUnset(response, "permissions-policy", "camera=(), microphone=(), geolocation=()");
856
+ }
857
+ function setHeaderIfUnset(response, name, value) {
858
+ if (!response.hasHeader(name)) {
859
+ response.setHeader(name, value);
860
+ }
861
+ }
862
+ async function renderRoute(requestUrl, options, loadedManifest) {
863
+ if (options.dev && !loadedManifest) {
864
+ await ensureDevBuild(options.appRoot, options.outDir, options.buildOptions, options.vite);
865
+ }
866
+ const manifest = loadedManifest ?? await importManifest(options.outDir, options.dev);
867
+ const matched = manifest.matchRoute(requestUrl.pathname);
868
+ if (!matched) {
869
+ return null;
870
+ }
871
+ const routeContext = {
872
+ path: requestUrl.pathname,
873
+ params: matched.params,
874
+ query: readQuery(requestUrl)
875
+ };
876
+ const middlewareResult = await runRouteMiddleware(manifest, routeContext, matched.route.meta);
877
+ if (middlewareResult) {
878
+ return middlewareResult;
879
+ }
880
+ return renderApp({
881
+ app: manifest.app,
882
+ page: matched.route.component,
883
+ pageMeta: matched.route.meta,
884
+ route: routeContext,
885
+ components: manifest.components,
886
+ layouts: manifest.layouts,
887
+ modules: manifest.modules,
888
+ vueIslands: manifest.vueIslands,
889
+ runtimeConfig: manifest.runtimeConfig,
890
+ appHead: manifest.appHead,
891
+ plugins: manifest.plugins
892
+ });
893
+ }
894
+ async function runRouteMiddleware(manifest, to, pageMeta) {
895
+ const from = { path: "", params: {}, query: {} };
896
+ const names = normalizeMiddlewareNames(pageMeta?.middleware);
897
+ const selected = [
898
+ ...manifest.middleware.filter((entry) => entry.global),
899
+ ...names.map((name) => manifest.middleware.find((entry) => entry.name === name)).filter(Boolean)
900
+ ];
901
+ for (const entry of selected) {
902
+ const result = await entry.handler(to, from);
903
+ const normalized = normalizeMiddlewareResult(result);
904
+ if (normalized) {
905
+ return normalized;
906
+ }
907
+ }
908
+ return null;
909
+ }
910
+ async function runServerMiddleware(request, response, requestUrl, manifest) {
911
+ for (const entry of manifest.serverMiddleware ?? []) {
912
+ const result = await entry.handler(createServerEvent(request, response, requestUrl, {}));
913
+ if (response.writableEnded) {
914
+ return true;
915
+ }
916
+ if (result === undefined || result === null) {
917
+ continue;
918
+ }
919
+ await sendServerResult(response, result);
920
+ return true;
921
+ }
922
+ return false;
923
+ }
924
+ function normalizeMiddlewareNames(value) {
925
+ if (!value) {
926
+ return [];
927
+ }
928
+ return (Array.isArray(value) ? value : [value]).map((name) => String(name));
929
+ }
930
+ function normalizeMiddlewareResult(result) {
931
+ if (!result) {
932
+ return result === false
933
+ ? { type: "abort", statusCode: 403, message: "Navigation aborted" }
934
+ : null;
935
+ }
936
+ if (typeof result === "string") {
937
+ return { type: "redirect", to: result, statusCode: 302 };
938
+ }
939
+ if (result.type === "redirect") {
940
+ return { type: "redirect", to: result.to, statusCode: result.statusCode ?? 302 };
941
+ }
942
+ if (result.type === "abort") {
943
+ return { type: "abort", message: result.message ?? "Navigation aborted", statusCode: result.statusCode ?? 403 };
944
+ }
945
+ return null;
946
+ }
947
+ function matchRouteRule(routeRules, pathname) {
948
+ if (!routeRules) {
949
+ return null;
950
+ }
951
+ const matched = Object.entries(routeRules)
952
+ .filter(([pattern]) => routeRuleMatches(pattern, pathname))
953
+ .sort(([left], [right]) => routeRuleScore(right) - routeRuleScore(left))[0];
954
+ return matched?.[1] ?? null;
955
+ }
956
+ function routeRuleMatches(pattern, pathname) {
957
+ if (pattern === pathname) {
958
+ return true;
959
+ }
960
+ if (pattern.endsWith("/**")) {
961
+ const prefix = pattern.slice(0, -3);
962
+ return pathname === prefix || pathname.startsWith(`${prefix}/`);
963
+ }
964
+ if (!pattern.includes("*")) {
965
+ return false;
966
+ }
967
+ const source = `^${pattern
968
+ .split("**")
969
+ .map((part) => part.split("*").map(escapeRegExp).join("[^/]*"))
970
+ .join(".*")}$`;
971
+ return new RegExp(source).test(pathname);
972
+ }
973
+ function routeRuleScore(pattern) {
974
+ return pattern.replace(/\*/g, "").length * 10 - (pattern.match(/\*/g)?.length ?? 0);
975
+ }
976
+ function escapeRegExp(value) {
977
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
978
+ }
979
+ function applyRouteRuleHeaders(response, rule) {
980
+ for (const [name, value] of Object.entries(rule?.headers ?? {})) {
981
+ response.setHeader(name, value);
982
+ }
983
+ const cacheControl = routeRuleCacheControl(rule?.cache);
984
+ if (cacheControl) {
985
+ response.setHeader("cache-control", cacheControl);
986
+ }
987
+ applyCorsRule(response, rule?.cors);
988
+ }
989
+ function routeRuleCacheControl(cache) {
990
+ if (cache === undefined) {
991
+ return null;
992
+ }
993
+ if (cache === false) {
994
+ return "no-store";
995
+ }
996
+ if (typeof cache === "string") {
997
+ return cache;
998
+ }
999
+ const parts = [];
1000
+ if (Number.isFinite(cache.maxAge)) {
1001
+ parts.push(`public, max-age=${Math.floor(cache.maxAge)}`);
1002
+ }
1003
+ if (Number.isFinite(cache.swr)) {
1004
+ parts.push(`stale-while-revalidate=${Math.floor(cache.swr)}`);
1005
+ }
1006
+ return parts.join(", ") || null;
1007
+ }
1008
+ function applyCorsRule(response, cors) {
1009
+ if (!cors) {
1010
+ return;
1011
+ }
1012
+ const config = cors === true ? {} : cors;
1013
+ response.setHeader("access-control-allow-origin", config.origin ?? "*");
1014
+ response.setHeader("access-control-allow-methods", (config.methods ?? ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]).join(", "));
1015
+ response.setHeader("access-control-allow-headers", (config.headers ?? ["content-type", "authorization"]).join(", "));
1016
+ if (config.credentials) {
1017
+ response.setHeader("access-control-allow-credentials", "true");
1018
+ }
1019
+ }
1020
+ function serveRouteRuleRedirect(response, redirect) {
1021
+ const normalized = normalizeRouteRuleRedirect(redirect);
1022
+ response.writeHead(normalized.statusCode, { location: normalized.to });
1023
+ response.end();
1024
+ }
1025
+ function normalizeRouteRuleRedirect(redirect) {
1026
+ if (typeof redirect === "string") {
1027
+ return { to: redirect, statusCode: 307 };
1028
+ }
1029
+ return {
1030
+ to: redirect?.to ?? "/",
1031
+ statusCode: redirect?.statusCode ?? 307
1032
+ };
1033
+ }
1034
+ async function serveServerHandler(request, response, requestUrl, manifest, routeRule) {
1035
+ const matched = manifest.matchServerHandler?.(requestUrl.pathname);
1036
+ if (!matched) {
1037
+ return false;
1038
+ }
1039
+ const result = await matched.route.handler(createServerEvent(request, response, requestUrl, matched.params));
1040
+ if (response.writableEnded) {
1041
+ return true;
1042
+ }
1043
+ await sendServerResult(response, result, routeRule?.statusCode ?? 200);
1044
+ return true;
1045
+ }
1046
+ function createServerEvent(request, response, requestUrl, params) {
1047
+ return {
1048
+ path: requestUrl.pathname,
1049
+ method: request.method ?? "GET",
1050
+ query: readQuery(requestUrl),
1051
+ params,
1052
+ node: {
1053
+ req: request,
1054
+ res: response
1055
+ }
1056
+ };
1057
+ }
1058
+ async function sendServerResult(response, result, statusCode = 200) {
1059
+ if (result instanceof Response) {
1060
+ const headers = {};
1061
+ result.headers.forEach((value, key) => {
1062
+ headers[key] = value;
1063
+ });
1064
+ response.writeHead(result.status, headers);
1065
+ response.end(Buffer.from(await result.arrayBuffer()));
1066
+ return;
1067
+ }
1068
+ if (result === false) {
1069
+ response.writeHead(403, { "content-type": "text/plain; charset=utf-8" });
1070
+ response.end("Forbidden");
1071
+ return;
1072
+ }
1073
+ if (isServerRedirectResult(result)) {
1074
+ response.writeHead(result.statusCode ?? 302, { location: result.to });
1075
+ response.end();
1076
+ return;
1077
+ }
1078
+ if (isServerAbortResult(result)) {
1079
+ response.writeHead(result.statusCode ?? 403, { "content-type": "text/plain; charset=utf-8" });
1080
+ response.end(result.message ?? "Request aborted");
1081
+ return;
1082
+ }
1083
+ if (typeof result === "string") {
1084
+ response.writeHead(statusCode, { "content-type": "text/plain; charset=utf-8" });
1085
+ response.end(result);
1086
+ return;
1087
+ }
1088
+ response.writeHead(statusCode, { "content-type": "application/json; charset=utf-8" });
1089
+ response.end(JSON.stringify(result ?? null));
1090
+ }
1091
+ function isServerRedirectResult(value) {
1092
+ return Boolean(value && typeof value === "object" && value.type === "redirect" && typeof value.to === "string");
1093
+ }
1094
+ function isServerAbortResult(value) {
1095
+ return Boolean(value && typeof value === "object" && value.type === "abort");
1096
+ }
1097
+ async function servePublicFile(response, appRoot, pathname) {
1098
+ const publicRoot = path.resolve(appRoot, "public");
1099
+ const resolved = path.resolve(publicRoot, `.${decodeURIComponent(pathname)}`);
1100
+ if (!resolved.startsWith(publicRoot)) {
1101
+ return false;
1102
+ }
1103
+ if (!(await exists(resolved))) {
1104
+ return false;
1105
+ }
1106
+ const fileStats = await stat(resolved);
1107
+ if (!fileStats.isFile()) {
1108
+ return false;
1109
+ }
1110
+ response.writeHead(200, {
1111
+ "content-type": mimeType(resolved),
1112
+ ...(!response.hasHeader("cache-control") ? { "cache-control": "no-store" } : {})
1113
+ });
1114
+ response.end(await readFile(resolved));
1115
+ return true;
1116
+ }
1117
+ function mimeType(file) {
1118
+ const ext = path.extname(file).toLowerCase();
1119
+ const types = {
1120
+ ".css": "text/css; charset=utf-8",
1121
+ ".js": "text/javascript; charset=utf-8",
1122
+ ".mjs": "text/javascript; charset=utf-8",
1123
+ ".json": "application/json; charset=utf-8",
1124
+ ".html": "text/html; charset=utf-8",
1125
+ ".txt": "text/plain; charset=utf-8",
1126
+ ".svg": "image/svg+xml",
1127
+ ".png": "image/png",
1128
+ ".jpg": "image/jpeg",
1129
+ ".jpeg": "image/jpeg",
1130
+ ".webp": "image/webp",
1131
+ ".ico": "image/x-icon"
1132
+ };
1133
+ return types[ext] ?? "application/octet-stream";
1134
+ }
1135
+ async function ensureDevBuild(appRoot, outDir, buildOptions, vite) {
1136
+ const startedAtRevision = devBuildRevision;
1137
+ while (devBuildDirty || activeDevBuild) {
1138
+ if (!activeDevBuild) {
1139
+ devBuildDirty = false;
1140
+ activeDevBuild = buildProject(appRoot, outDir, { ...buildOptions, vite: "dev" })
1141
+ .then(() => {
1142
+ devBuildRevision++;
1143
+ vite?.moduleGraph.invalidateAll();
1144
+ })
1145
+ .finally(() => {
1146
+ activeDevBuild = null;
1147
+ });
1148
+ }
1149
+ await activeDevBuild;
1150
+ }
1151
+ return devBuildRevision !== startedAtRevision;
1152
+ }
1153
+ function serveDevEvents(request, response) {
1154
+ response.writeHead(200, {
1155
+ "content-type": "text/event-stream; charset=utf-8",
1156
+ "cache-control": "no-store, no-transform",
1157
+ connection: "keep-alive"
1158
+ });
1159
+ response.write("retry: 1000\n\n");
1160
+ devReloadClients.add(response);
1161
+ request.on("close", () => {
1162
+ devReloadClients.delete(response);
1163
+ });
1164
+ }
1165
+ function notifyDevReloadClients(eventName = "hmr") {
1166
+ devReloadRevision++;
1167
+ const payload = JSON.stringify({ revision: devReloadRevision });
1168
+ for (const client of [...devReloadClients]) {
1169
+ if (client.destroyed || client.writableEnded) {
1170
+ devReloadClients.delete(client);
1171
+ continue;
1172
+ }
1173
+ try {
1174
+ client.write(`event: ${eventName}\ndata: ${payload}\n\n`);
1175
+ }
1176
+ catch {
1177
+ devReloadClients.delete(client);
1178
+ }
1179
+ }
1180
+ }
1181
+ async function serveViteResuxAsset(response, vite, pathname) {
1182
+ const viteUrl = resolveResuxViteAssetUrl(pathname);
1183
+ if (!viteUrl) {
1184
+ response.writeHead(404);
1185
+ response.end("Not found");
1186
+ return;
1187
+ }
1188
+ const transformed = await vite.transformRequest(viteUrl);
1189
+ if (!transformed) {
1190
+ response.writeHead(404);
1191
+ response.end("Not found");
1192
+ return;
1193
+ }
1194
+ response.writeHead(200, {
1195
+ "content-type": "text/javascript; charset=utf-8",
1196
+ "cache-control": "no-store"
1197
+ });
1198
+ response.end(transformed.code);
1199
+ }
1200
+ async function serveViteMiddleware(request, response, vite) {
1201
+ await new Promise((resolve, reject) => {
1202
+ let settled = false;
1203
+ const finish = () => {
1204
+ if (!settled) {
1205
+ settled = true;
1206
+ resolve();
1207
+ }
1208
+ };
1209
+ response.once("finish", finish);
1210
+ vite.middlewares(request, response, (error) => {
1211
+ response.off("finish", finish);
1212
+ if (settled) {
1213
+ return;
1214
+ }
1215
+ settled = true;
1216
+ if (error) {
1217
+ reject(error instanceof Error ? error : new Error(String(error)));
1218
+ return;
1219
+ }
1220
+ if (!response.writableEnded) {
1221
+ response.writeHead(404);
1222
+ response.end("Not found");
1223
+ }
1224
+ resolve();
1225
+ });
1226
+ });
1227
+ }
1228
+ async function serveResuxAsset(response, outDir, pathname) {
1229
+ const relative = resolveResuxAssetPath(pathname);
1230
+ if (!relative) {
1231
+ response.writeHead(404);
1232
+ response.end("Not found");
1233
+ return;
1234
+ }
1235
+ const resolved = path.resolve(outDir, relative);
1236
+ const allowedRoot = path.resolve(outDir, "client");
1237
+ if (!resolved.startsWith(allowedRoot)) {
1238
+ response.writeHead(403);
1239
+ response.end("Forbidden");
1240
+ return;
1241
+ }
1242
+ if (!(await exists(resolved))) {
1243
+ response.writeHead(404);
1244
+ response.end("Not found");
1245
+ return;
1246
+ }
1247
+ response.writeHead(200, {
1248
+ "content-type": mimeType(resolved),
1249
+ "cache-control": "no-store"
1250
+ });
1251
+ response.end(await readFile(resolved, "utf8"));
1252
+ }
1253
+ function resolveResuxAssetPath(pathname) {
1254
+ if (pathname === "/__resux/runtime-client.mjs") {
1255
+ return "client/runtime-client.mjs";
1256
+ }
1257
+ if (pathname.startsWith("/__resux/handlers/")) {
1258
+ return pathname.replace(/^\/__resux\/handlers\//, "client/handlers/");
1259
+ }
1260
+ if (pathname.startsWith("/__resux/vue-islands/")) {
1261
+ return pathname.replace(/^\/__resux\/vue-islands\//, "client/vue-islands/");
1262
+ }
1263
+ return null;
1264
+ }
1265
+ function resolveResuxViteAssetUrl(pathname) {
1266
+ if (pathname === "/__resux/runtime-client.mjs") {
1267
+ return "/runtime-client.mjs";
1268
+ }
1269
+ if (pathname.startsWith("/__resux/handlers/")) {
1270
+ return pathname.replace(/^\/__resux\/handlers\//, "/handlers/");
1271
+ }
1272
+ if (pathname.startsWith("/__resux/vue-islands/")) {
1273
+ return pathname.replace(/^\/__resux\/vue-islands\//, "/vue-islands/");
1274
+ }
1275
+ return null;
1276
+ }
1277
+ function isViteInternalRequest(pathname) {
1278
+ return pathname === "/runtime-client.mjs"
1279
+ || pathname.startsWith("/@")
1280
+ || pathname.startsWith("/node_modules/.vite/");
1281
+ }
1282
+ async function importManifest(outDir, dev = false) {
1283
+ const file = !dev && await exists(path.join(outDir, "server-bundle", "index.mjs"))
1284
+ ? path.join(outDir, "server-bundle", "index.mjs")
1285
+ : path.join(outDir, "server", "manifest.mjs");
1286
+ const stats = await stat(file);
1287
+ return import(`${pathToFileURL(file).href}?t=${stats.mtimeMs}`);
1288
+ }
1289
+ function readQuery(url) {
1290
+ const query = {};
1291
+ for (const [key, value] of url.searchParams) {
1292
+ const existing = query[key];
1293
+ if (Array.isArray(existing)) {
1294
+ existing.push(value);
1295
+ }
1296
+ else if (existing !== undefined) {
1297
+ query[key] = [existing, value];
1298
+ }
1299
+ else {
1300
+ query[key] = value;
1301
+ }
1302
+ }
1303
+ return query;
1304
+ }
1305
+ async function exists(file) {
1306
+ try {
1307
+ await stat(file);
1308
+ return true;
1309
+ }
1310
+ catch {
1311
+ return false;
1312
+ }
1313
+ }
1314
+ //# sourceMappingURL=index.js.map