resuxjs 0.2.22 → 0.2.23

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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +65 -8
  3. package/dist/cli.d.ts +9 -0
  4. package/dist/cli.js +1668 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/compiler/index.js +74 -37
  7. package/dist/compiler/index.js.map +1 -1
  8. package/dist/globals.d.ts +32 -24
  9. package/dist/index.d.ts +0 -8
  10. package/dist/index.js +0 -1666
  11. package/dist/index.js.map +1 -1
  12. package/dist/node.d.ts +2 -0
  13. package/dist/node.js +2 -0
  14. package/dist/node.js.map +1 -0
  15. package/dist/reactivity/computed.d.ts +7 -0
  16. package/dist/reactivity/computed.js +53 -0
  17. package/dist/reactivity/computed.js.map +1 -0
  18. package/dist/reactivity/effect.d.ts +17 -0
  19. package/dist/reactivity/effect.js +113 -0
  20. package/dist/reactivity/effect.js.map +1 -0
  21. package/dist/reactivity/index.d.ts +8 -0
  22. package/dist/reactivity/index.js +8 -0
  23. package/dist/reactivity/index.js.map +1 -0
  24. package/dist/reactivity/reactive.d.ts +5 -0
  25. package/dist/reactivity/reactive.js +95 -0
  26. package/dist/reactivity/reactive.js.map +1 -0
  27. package/dist/reactivity/readonly.d.ts +1 -0
  28. package/dist/reactivity/readonly.js +2 -0
  29. package/dist/reactivity/readonly.js.map +1 -0
  30. package/dist/reactivity/ref.d.ts +22 -0
  31. package/dist/reactivity/ref.js +85 -0
  32. package/dist/reactivity/ref.js.map +1 -0
  33. package/dist/reactivity/scheduler.d.ts +6 -0
  34. package/dist/reactivity/scheduler.js +38 -0
  35. package/dist/reactivity/scheduler.js.map +1 -0
  36. package/dist/reactivity/types.d.ts +30 -0
  37. package/dist/reactivity/types.js +2 -0
  38. package/dist/reactivity/types.js.map +1 -0
  39. package/dist/reactivity/utils.d.ts +14 -0
  40. package/dist/reactivity/utils.js +34 -0
  41. package/dist/reactivity/utils.js.map +1 -0
  42. package/dist/reactivity/watch.d.ts +5 -0
  43. package/dist/reactivity/watch.js +98 -0
  44. package/dist/reactivity/watch.js.map +1 -0
  45. package/dist/runtime/index.d.ts +17 -3
  46. package/dist/runtime/index.js +500 -28
  47. package/dist/runtime/index.js.map +1 -1
  48. package/package.json +38 -8
package/dist/cli.js ADDED
@@ -0,0 +1,1668 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { readdirSync, statSync, watch } from "node:fs";
4
+ import { createServer as createHttpServer, } from "node:http";
5
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
6
+ import { createRequire } from "node:module";
7
+ import path from "node:path";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import vuePlugin from "@vitejs/plugin-vue";
10
+ import { createServer as createViteServer } from "vite";
11
+ import { buildProject } from "./compiler/index.js";
12
+ import { runCreateResux } from "./create.js";
13
+ import { renderApp, renderDocument, } from "./runtime/index.js";
14
+ export * from "./runtime/index.js";
15
+ const require = createRequire(import.meta.url);
16
+ const version = require("../package.json").version ?? "0.0.0";
17
+ let activeDevBuild = null;
18
+ let devBuildDirty = false;
19
+ let devBuildRevision = 0;
20
+ let devReloadRevision = 0;
21
+ let devLastBuildSourceMtime = 0;
22
+ const devReloadClients = new Set();
23
+ export function createResuxNodeHandler(options = {}) {
24
+ const appRoot = path.resolve(options.appRoot ?? process.cwd());
25
+ const outDir = path.resolve(options.outDir ?? path.join(appRoot, ".resux"));
26
+ const buildOptions = {};
27
+ return (request, response) => {
28
+ void handleRequest(request, response, {
29
+ appRoot,
30
+ outDir,
31
+ dev: false,
32
+ buildOptions,
33
+ securityHeaders: options.securityHeaders ?? true,
34
+ });
35
+ };
36
+ }
37
+ if (isMainModule()) {
38
+ await runCli(process.argv.slice(2));
39
+ }
40
+ async function runCli(args) {
41
+ const command = readCommand(args);
42
+ const commandArgs = command === args[0] ? args.slice(1) : args;
43
+ if (command === "help") {
44
+ printHelp();
45
+ return;
46
+ }
47
+ if (command === "version") {
48
+ console.log(version);
49
+ return;
50
+ }
51
+ if (command === "init" || command === "create") {
52
+ await runCreateResux(commandArgs);
53
+ return;
54
+ }
55
+ const cliOptions = readCliOptions(commandArgs);
56
+ const appRoot = path.resolve(cliOptions.appRoot);
57
+ const outDir = path.join(appRoot, ".resux");
58
+ const buildOptions = {};
59
+ const securityHeaders = cliOptions.securityHeaders ?? command !== "dev";
60
+ const port = readPort(cliOptions.port ?? process.env.PORT, 3000);
61
+ const tailwind = await resolveTailwindPipeline(appRoot);
62
+ try {
63
+ if (command === "build") {
64
+ await runTailwindBuild(appRoot, tailwind, true);
65
+ const result = await buildProject(appRoot, outDir, {
66
+ ...buildOptions,
67
+ vite: "build",
68
+ });
69
+ console.log(`Built ${result.routes.length} route(s) into ${path.relative(process.cwd(), outDir)}`);
70
+ await ensureNitroBuildFiles(appRoot);
71
+ await runNitroBuild(appRoot);
72
+ }
73
+ else if (command === "compile") {
74
+ await runTailwindBuild(appRoot, tailwind, true);
75
+ const result = await buildProject(appRoot, outDir, {
76
+ ...buildOptions,
77
+ vite: "build",
78
+ });
79
+ console.log(`Compiled ${result.routes.length} route(s) into ${path.relative(process.cwd(), outDir)}`);
80
+ }
81
+ else if (command === "deploy") {
82
+ await generateDeploymentFiles(appRoot, cliOptions.deployPreset, cliOptions.force);
83
+ }
84
+ else if (command === "inspect") {
85
+ await inspectProject(appRoot, outDir, buildOptions, cliOptions.json);
86
+ }
87
+ else if (command === "dev") {
88
+ await runTailwindBuild(appRoot, tailwind, false);
89
+ startTailwindWatch(appRoot, tailwind);
90
+ await buildProject(appRoot, outDir, { ...buildOptions, vite: "dev" });
91
+ const vite = await startViteDevServer(outDir);
92
+ startDevWatcher(vite, appRoot, outDir, buildOptions);
93
+ await startServer({
94
+ appRoot,
95
+ outDir,
96
+ port,
97
+ host: cliOptions.host,
98
+ dev: true,
99
+ buildOptions,
100
+ vite,
101
+ securityHeaders,
102
+ });
103
+ }
104
+ else if (command === "preview" || command === "start") {
105
+ if (await previewNeedsBuild(outDir, buildOptions)) {
106
+ await runTailwindBuild(appRoot, tailwind, true);
107
+ await buildProject(appRoot, outDir, { ...buildOptions, vite: "build" });
108
+ }
109
+ await startServer({
110
+ appRoot,
111
+ outDir,
112
+ port,
113
+ host: cliOptions.host,
114
+ dev: false,
115
+ buildOptions,
116
+ securityHeaders,
117
+ });
118
+ }
119
+ else {
120
+ console.error(`Unknown command "${command}". Run resux --help for usage.`);
121
+ process.exitCode = 1;
122
+ }
123
+ }
124
+ catch (error) {
125
+ console.error(error instanceof Error ? (error.stack ?? error.message) : error);
126
+ process.exitCode = 1;
127
+ }
128
+ }
129
+ async function resolveTailwindPipeline(appRoot) {
130
+ const inputFile = path.join(appRoot, "assets", "css", "tailwind.css");
131
+ if (!(await exists(inputFile))) {
132
+ return null;
133
+ }
134
+ const outputFile = path.join(appRoot, "public", "tailwind.css");
135
+ const configFile = await firstExistingPath([
136
+ path.join(appRoot, "tailwind.config.ts"),
137
+ path.join(appRoot, "tailwind.config.js"),
138
+ path.join(appRoot, "tailwind.config.mjs"),
139
+ path.join(appRoot, "tailwind.config.cjs"),
140
+ ]);
141
+ const cliFile = await resolveTailwindCliFile(appRoot);
142
+ return {
143
+ cliFile,
144
+ inputFile,
145
+ outputFile,
146
+ configFile: configFile ?? undefined,
147
+ };
148
+ }
149
+ async function resolveTailwindCliFile(appRoot) {
150
+ try {
151
+ const appRequire = createRequire(path.join(appRoot, "package.json"));
152
+ const packageJsonPath = appRequire.resolve("tailwindcss/package.json");
153
+ const packageJson = JSON.parse(await readFile(packageJsonPath, "utf8"));
154
+ const binValue = typeof packageJson.bin === "string"
155
+ ? packageJson.bin
156
+ : typeof packageJson.bin?.tailwindcss === "string"
157
+ ? packageJson.bin.tailwindcss
158
+ : Object.values(packageJson.bin ?? {})[0];
159
+ if (!binValue) {
160
+ throw new Error("tailwindcss package does not expose a CLI binary.");
161
+ }
162
+ return path.resolve(path.dirname(packageJsonPath), binValue);
163
+ }
164
+ catch (error) {
165
+ const reason = error instanceof Error ? error.message : String(error);
166
+ throw new Error(`Detected assets/css/tailwind.css but could not resolve tailwindcss CLI from this app. Install it in app dependencies. ${reason}`);
167
+ }
168
+ }
169
+ async function runTailwindBuild(appRoot, pipeline, minify) {
170
+ if (!pipeline) {
171
+ return;
172
+ }
173
+ await mkdir(path.dirname(pipeline.outputFile), { recursive: true });
174
+ const args = [
175
+ pipeline.cliFile,
176
+ "-i",
177
+ pipeline.inputFile,
178
+ "-o",
179
+ pipeline.outputFile,
180
+ ...(pipeline.configFile ? ["--config", pipeline.configFile] : []),
181
+ ...(minify ? ["--minify"] : []),
182
+ ];
183
+ await runChildProcess(process.execPath, args, appRoot);
184
+ console.log(`Tailwind build ${minify ? "(minified) " : ""}${path.relative(appRoot, pipeline.inputFile)} -> ${path.relative(appRoot, pipeline.outputFile)}`);
185
+ }
186
+ function startTailwindWatch(appRoot, pipeline) {
187
+ if (!pipeline) {
188
+ return null;
189
+ }
190
+ const args = [
191
+ pipeline.cliFile,
192
+ "-i",
193
+ pipeline.inputFile,
194
+ "-o",
195
+ pipeline.outputFile,
196
+ ...(pipeline.configFile ? ["--config", pipeline.configFile] : []),
197
+ "--watch",
198
+ ];
199
+ const child = spawn(process.execPath, args, {
200
+ cwd: appRoot,
201
+ stdio: "inherit",
202
+ env: process.env,
203
+ shell: false,
204
+ });
205
+ console.log(`Tailwind watch ${path.relative(appRoot, pipeline.inputFile)} -> ${path.relative(appRoot, pipeline.outputFile)}`);
206
+ child.on("exit", (code, signal) => {
207
+ if (signal || code === null || code === 0) {
208
+ return;
209
+ }
210
+ console.error(`Tailwind watch exited with code ${code}.`);
211
+ process.exit(code ?? 1);
212
+ });
213
+ const stop = () => {
214
+ if (!child.killed && child.exitCode === null) {
215
+ child.kill("SIGTERM");
216
+ }
217
+ };
218
+ process.once("exit", stop);
219
+ process.once("SIGINT", stop);
220
+ process.once("SIGTERM", stop);
221
+ process.once("SIGHUP", stop);
222
+ return child;
223
+ }
224
+ async function runChildProcess(command, args, cwd) {
225
+ await new Promise((resolve, reject) => {
226
+ const child = spawn(command, args, {
227
+ cwd,
228
+ stdio: "inherit",
229
+ env: process.env,
230
+ shell: false,
231
+ });
232
+ child.on("error", reject);
233
+ child.on("exit", (code) => {
234
+ if (code === 0) {
235
+ resolve();
236
+ }
237
+ else {
238
+ reject(new Error(`${path.basename(command)} ${args.join(" ")} exited with code ${code ?? "unknown"}.`));
239
+ }
240
+ });
241
+ });
242
+ }
243
+ async function firstExistingPath(paths) {
244
+ for (const candidate of paths) {
245
+ if (await exists(candidate)) {
246
+ return candidate;
247
+ }
248
+ }
249
+ return null;
250
+ }
251
+ function isMainModule() {
252
+ return process.argv[1]
253
+ ? path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
254
+ : false;
255
+ }
256
+ function readCommand(args) {
257
+ const first = args[0];
258
+ if (first === "init" || first === "create") {
259
+ return first;
260
+ }
261
+ if (args.includes("--help") || args.includes("-h")) {
262
+ return "help";
263
+ }
264
+ if (args.includes("--version") || args.includes("-v")) {
265
+ return "version";
266
+ }
267
+ if (!first || first.startsWith("-")) {
268
+ return "dev";
269
+ }
270
+ if (first === "help" || first === "version") {
271
+ return first;
272
+ }
273
+ return first;
274
+ }
275
+ function readCliOptions(args) {
276
+ let appRoot = process.cwd();
277
+ let port;
278
+ let host;
279
+ let securityHeaders;
280
+ let json = false;
281
+ let deployPreset = "node";
282
+ let force = false;
283
+ for (let index = 0; index < args.length; index++) {
284
+ const arg = args[index];
285
+ if (arg === "--security-headers") {
286
+ securityHeaders = true;
287
+ }
288
+ else if (arg === "--no-security-headers") {
289
+ securityHeaders = false;
290
+ }
291
+ else if (arg === "--json") {
292
+ json = true;
293
+ }
294
+ else if (arg === "--preset") {
295
+ deployPreset = readDeployPreset(readRequiredOptionValue(args[++index], arg));
296
+ }
297
+ else if (arg.startsWith("--preset=")) {
298
+ deployPreset = readDeployPreset(arg.slice("--preset=".length));
299
+ }
300
+ else if (arg === "--force") {
301
+ force = true;
302
+ }
303
+ else if (arg === "--port" || arg === "-p") {
304
+ port = readRequiredOptionValue(args[++index], arg);
305
+ }
306
+ else if (arg.startsWith("--port=")) {
307
+ port = arg.slice("--port=".length);
308
+ }
309
+ else if (arg === "--host") {
310
+ host = readRequiredOptionValue(args[++index], arg);
311
+ }
312
+ else if (arg.startsWith("--host=")) {
313
+ host = arg.slice("--host=".length);
314
+ }
315
+ else if (arg.startsWith("-")) {
316
+ throw new Error(`Unknown option "${arg}". Run resux --help for usage.`);
317
+ }
318
+ else if (!arg.startsWith("-")) {
319
+ appRoot = arg;
320
+ }
321
+ }
322
+ return { appRoot, port, host, securityHeaders, json, deployPreset, force };
323
+ }
324
+ function readRequiredOptionValue(value, option) {
325
+ if (!value || value.startsWith("-")) {
326
+ throw new Error(`${option} needs a value.`);
327
+ }
328
+ return value;
329
+ }
330
+ function readDeployPreset(value) {
331
+ if (value === "node" || value === "docker" || value === "nitro") {
332
+ return value;
333
+ }
334
+ throw new Error(`Unknown deploy preset "${value}". Expected "node", "docker", or "nitro".`);
335
+ }
336
+ async function previewNeedsBuild(outDir, buildOptions) {
337
+ if (!(await exists(path.join(outDir, "server", "manifest.mjs")))) {
338
+ return true;
339
+ }
340
+ try {
341
+ const manifest = JSON.parse(await readFile(path.join(outDir, "manifest.json"), "utf8"));
342
+ return (manifest.features?.vite !== "build" ||
343
+ manifest.features?.server !== "bundle");
344
+ }
345
+ catch {
346
+ return true;
347
+ }
348
+ }
349
+ async function inspectProject(appRoot, outDir, buildOptions, json = false) {
350
+ if (await previewNeedsBuild(outDir, buildOptions)) {
351
+ await buildProject(appRoot, outDir, { ...buildOptions, vite: "build" });
352
+ }
353
+ const manifest = JSON.parse(await readFile(path.join(outDir, "manifest.json"), "utf8"));
354
+ const routeRules = manifest.routeRules ?? {};
355
+ const summary = {
356
+ appRoot,
357
+ outDir,
358
+ counts: {
359
+ routes: manifest.routes?.length ?? 0,
360
+ components: manifest.components?.length ?? 0,
361
+ layouts: manifest.layouts?.length ?? 0,
362
+ plugins: manifest.plugins?.length ?? 0,
363
+ middleware: manifest.middleware?.length ?? 0,
364
+ serverMiddleware: manifest.serverMiddleware?.length ?? 0,
365
+ serverHandlers: manifest.serverHandlers?.length ?? 0,
366
+ routeRules: Object.keys(routeRules).length,
367
+ },
368
+ features: {
369
+ vite: manifest.features?.vite ?? "build",
370
+ server: manifest.features?.server ?? "modules",
371
+ },
372
+ routes: manifest.routes ?? [],
373
+ serverHandlers: manifest.serverHandlers ?? [],
374
+ routeRules,
375
+ diagnostics: createInspectDiagnostics(manifest),
376
+ };
377
+ if (json) {
378
+ console.log(JSON.stringify(summary, null, 2));
379
+ return;
380
+ }
381
+ console.log(`Resux app: ${summary.appRoot}`);
382
+ console.log(`Build dir: ${summary.outDir}`);
383
+ console.log(`Routes: ${summary.counts.routes}`);
384
+ console.log(`Components: ${summary.counts.components}`);
385
+ console.log(`Layouts: ${summary.counts.layouts}`);
386
+ console.log(`Plugins: ${summary.counts.plugins}`);
387
+ console.log(`Middleware: ${summary.counts.middleware}`);
388
+ console.log(`Server middleware: ${summary.counts.serverMiddleware}`);
389
+ console.log(`Server handlers: ${summary.counts.serverHandlers}`);
390
+ console.log(`Route rules: ${summary.counts.routeRules}`);
391
+ console.log(`Features: vite=${summary.features.vite}, server=${summary.features.server}`);
392
+ if (summary.diagnostics.length) {
393
+ console.log("\nDiagnostics");
394
+ for (const diagnostic of summary.diagnostics) {
395
+ console.log(` [${diagnostic.level}] ${diagnostic.message}`);
396
+ }
397
+ }
398
+ if (summary.routes.length) {
399
+ console.log("\nRoutes");
400
+ for (const route of summary.routes) {
401
+ console.log(` ${route.path} -> ${path.relative(appRoot, route.file)}`);
402
+ }
403
+ }
404
+ if (summary.serverHandlers.length) {
405
+ console.log("\nServer handlers");
406
+ for (const handler of summary.serverHandlers) {
407
+ console.log(` ${handler.path} -> ${path.relative(appRoot, handler.file)}`);
408
+ }
409
+ }
410
+ if (Object.keys(routeRules).length) {
411
+ console.log("\nRoute rules");
412
+ for (const [routePath, rule] of Object.entries(routeRules)) {
413
+ console.log(` ${routePath} ${JSON.stringify(rule)}`);
414
+ }
415
+ }
416
+ }
417
+ function createInspectDiagnostics(manifest) {
418
+ const diagnostics = [];
419
+ if (!manifest.routes?.length) {
420
+ diagnostics.push({
421
+ level: "warning",
422
+ message: "No pages were discovered. Add .vue files under pages/.",
423
+ });
424
+ }
425
+ if (!manifest.serverHandlers?.length) {
426
+ diagnostics.push({
427
+ level: "info",
428
+ message: "No server handlers were discovered under server/api or server/routes.",
429
+ });
430
+ }
431
+ if (!Object.keys(manifest.routeRules ?? {}).length) {
432
+ diagnostics.push({
433
+ level: "info",
434
+ message: "No route rules are configured.",
435
+ });
436
+ }
437
+ return diagnostics;
438
+ }
439
+ async function generateDeploymentFiles(appRoot, preset, force) {
440
+ await assertDirectory(appRoot);
441
+ const files = [
442
+ {
443
+ relativePath: "DEPLOYMENT.md",
444
+ contents: createDeploymentGuide(preset),
445
+ },
446
+ ...(preset === "nitro"
447
+ ? [
448
+ {
449
+ relativePath: "nitro.config.ts",
450
+ contents: createNitroConfig(),
451
+ },
452
+ {
453
+ relativePath: ".resux-nitro/handler.ts",
454
+ contents: createNitroHandler(),
455
+ },
456
+ ]
457
+ : []),
458
+ ...(preset === "docker"
459
+ ? [
460
+ {
461
+ relativePath: "Dockerfile",
462
+ contents: createDockerfile(),
463
+ },
464
+ {
465
+ relativePath: ".dockerignore",
466
+ contents: createDockerignore(),
467
+ },
468
+ ]
469
+ : []),
470
+ ];
471
+ const written = [];
472
+ for (const file of files) {
473
+ written.push(await writeDeploymentFile(appRoot, file.relativePath, file.contents, force));
474
+ }
475
+ console.log(`Generated Resux ${preset} deployment file(s):`);
476
+ for (const file of written) {
477
+ console.log(` ${file}`);
478
+ }
479
+ }
480
+ async function ensureNitroBuildFiles(appRoot) {
481
+ if (!(await exists(path.join(appRoot, "nitro.config.ts")))) {
482
+ await writeDeploymentFile(appRoot, "nitro.config.ts", createNitroConfig(), false);
483
+ }
484
+ if (!(await exists(path.join(appRoot, ".resux-nitro", "handler.ts")))) {
485
+ await writeDeploymentFile(appRoot, ".resux-nitro/handler.ts", createNitroHandler(), false);
486
+ }
487
+ }
488
+ async function runNitroBuild(appRoot) {
489
+ const nitroPackageJson = require.resolve("nitropack/package.json");
490
+ const nitroCli = path.join(path.dirname(nitroPackageJson), "dist", "cli", "index.mjs");
491
+ console.log("Building Nitro output into .output");
492
+ await new Promise((resolve, reject) => {
493
+ const child = spawn(process.execPath, [nitroCli, "build"], {
494
+ cwd: appRoot,
495
+ stdio: "inherit",
496
+ env: process.env,
497
+ });
498
+ child.on("error", reject);
499
+ child.on("exit", (code) => {
500
+ if (code === 0) {
501
+ resolve();
502
+ }
503
+ else {
504
+ reject(new Error(`Nitro build exited with code ${code ?? "unknown"}.`));
505
+ }
506
+ });
507
+ });
508
+ }
509
+ async function assertDirectory(directory) {
510
+ const stats = await stat(directory);
511
+ if (!stats.isDirectory()) {
512
+ throw new Error(`${directory} is not a directory.`);
513
+ }
514
+ }
515
+ async function writeDeploymentFile(appRoot, relativePath, contents, force) {
516
+ const file = path.join(appRoot, relativePath);
517
+ if (!force && (await exists(file))) {
518
+ throw new Error(`${relativePath} already exists. Re-run with --force to overwrite it.`);
519
+ }
520
+ await mkdir(path.dirname(file), { recursive: true });
521
+ await writeFile(file, contents, "utf8");
522
+ return relativePath;
523
+ }
524
+ function createDeploymentGuide(preset) {
525
+ const dockerSection = preset === "docker"
526
+ ? `
527
+ ## Docker
528
+
529
+ \`\`\`sh
530
+ docker build -t resux-app .
531
+ docker run --rm -p 3000:3000 resux-app
532
+ \`\`\`
533
+ `
534
+ : "";
535
+ const nitroSection = preset === "nitro"
536
+ ? `
537
+ ## Nitro
538
+
539
+ Install the Nitro build dependencies:
540
+
541
+ \`\`\`sh
542
+ npm install -D nitropack h3
543
+ \`\`\`
544
+
545
+ Build Resux. The default production build creates both \`.resux\` and Nitro \`.output\`:
546
+
547
+ \`\`\`sh
548
+ npm run build
549
+ node .output/server/index.mjs
550
+ \`\`\`
551
+
552
+ Nitro reads \`NITRO_PRESET\` for provider-specific output. For example:
553
+
554
+ \`\`\`sh
555
+ NITRO_PRESET=vercel npx nitro build
556
+ \`\`\`
557
+
558
+ The generated Nitro handler wraps the Resux Node request handler. \`resux build\` runs Nitro from the project root so \`.output\` can be started with Node.
559
+ `
560
+ : "";
561
+ return `# Deployment
562
+
563
+ ## Node Server
564
+
565
+ \`\`\`sh
566
+ npm install
567
+ npm run build
568
+ npm run start
569
+ \`\`\`
570
+
571
+ The production server reads \`PORT\`, so most Node hosts can run the same start command:
572
+
573
+ \`\`\`sh
574
+ PORT=3000 npm run start
575
+ \`\`\`
576
+
577
+ Health checks can call:
578
+
579
+ \`\`\`txt
580
+ /__resux/health
581
+ \`\`\`
582
+ ${dockerSection}
583
+ ${nitroSection}
584
+ ## Diagnostics
585
+
586
+ \`\`\`sh
587
+ npm run inspect
588
+ npm run inspect -- --json
589
+ \`\`\`
590
+
591
+ Production serving enables Resux default security headers. Disable them only when a host or reverse proxy owns those headers:
592
+
593
+ \`\`\`sh
594
+ resux start . --no-security-headers
595
+ \`\`\`
596
+ `;
597
+ }
598
+ function createNitroConfig() {
599
+ return `import { defineNitroConfig } from "nitropack/config";
600
+
601
+ export default defineNitroConfig({
602
+ compatibilityDate: "2026-05-02",
603
+ publicAssets: [
604
+ {
605
+ dir: "public",
606
+ baseURL: "/"
607
+ }
608
+ ],
609
+ handlers: [
610
+ {
611
+ route: "/**",
612
+ handler: "./.resux-nitro/handler.ts"
613
+ }
614
+ ],
615
+ routeRules: {
616
+ "/__resux/route": {
617
+ headers: {
618
+ "cache-control": "no-store"
619
+ }
620
+ },
621
+ "/__resux/dev-events": {
622
+ headers: {
623
+ "cache-control": "no-store"
624
+ }
625
+ },
626
+ "/__resux/handlers/**": {
627
+ headers: {
628
+ "cache-control": "public, max-age=31536000, immutable"
629
+ }
630
+ },
631
+ "/__resux/vue-islands/**": {
632
+ headers: {
633
+ "cache-control": "public, max-age=31536000, immutable"
634
+ }
635
+ },
636
+ "/__resux/runtime-client.mjs": {
637
+ headers: {
638
+ "cache-control": "public, max-age=31536000, immutable"
639
+ }
640
+ },
641
+ "/api/**": {
642
+ headers: {
643
+ "cache-control": "no-store"
644
+ }
645
+ },
646
+ "/**": {
647
+ headers: {
648
+ "cache-control": "no-store"
649
+ }
650
+ }
651
+ },
652
+ prerender: {
653
+ crawlLinks: false,
654
+ routes: []
655
+ }
656
+ });
657
+ `;
658
+ }
659
+ function createNitroHandler() {
660
+ return `import { fromNodeMiddleware } from "h3";
661
+ import { createResuxNodeHandler } from "resuxjs/node";
662
+
663
+ export default fromNodeMiddleware(createResuxNodeHandler());
664
+ `;
665
+ }
666
+ function createDockerfile() {
667
+ return `FROM node:24-alpine AS build
668
+ WORKDIR /app
669
+ COPY package*.json ./
670
+ RUN npm install
671
+ COPY . .
672
+ RUN npm run build
673
+ RUN npm prune --omit=dev
674
+
675
+ FROM node:24-alpine AS runner
676
+ WORKDIR /app
677
+ ENV NODE_ENV=production
678
+ ENV PORT=3000
679
+ COPY --from=build /app /app
680
+ EXPOSE 3000
681
+ CMD ["npm", "run", "start"]
682
+ `;
683
+ }
684
+ function createDockerignore() {
685
+ return `node_modules
686
+ .resux
687
+ dist
688
+ .git
689
+ *.log
690
+ .env
691
+ .env.*
692
+ `;
693
+ }
694
+ async function startViteDevServer(outDir) {
695
+ const hmrPort = 30000 + Math.floor(Math.random() * 20000);
696
+ const vite = await createViteServer({
697
+ root: path.join(outDir, "vite-client"),
698
+ configFile: false,
699
+ publicDir: false,
700
+ appType: "custom",
701
+ clearScreen: false,
702
+ logLevel: "warn",
703
+ plugins: [vuePlugin()],
704
+ resolve: {
705
+ alias: {
706
+ "/__resux/runtime-client.mjs": path.join(outDir, "vite-client", "runtime-client.mjs"),
707
+ vue: require.resolve("vue"),
708
+ },
709
+ },
710
+ server: {
711
+ middlewareMode: true,
712
+ hmr: {
713
+ port: hmrPort,
714
+ },
715
+ watch: {
716
+ ignored: ["**/.resux/**", "**/node_modules/**"],
717
+ },
718
+ },
719
+ });
720
+ console.log("Vite dev middleware ready for Resux client modules.");
721
+ return vite;
722
+ }
723
+ function startDevWatcher(vite, appRoot, outDir, buildOptions) {
724
+ let lastSourceMtime = latestSourceMtime(appRoot, outDir);
725
+ const handleChange = (changedPath) => {
726
+ if (shouldSkipDevWatch(changedPath, appRoot, outDir)) {
727
+ return;
728
+ }
729
+ devBuildDirty = true;
730
+ void ensureDevBuild(appRoot, outDir, buildOptions, vite)
731
+ .then((rebuilt) => {
732
+ if (rebuilt) {
733
+ notifyDevReloadClients("reload");
734
+ }
735
+ })
736
+ .catch((error) => {
737
+ console.error(error instanceof Error ? (error.stack ?? error.message) : error);
738
+ });
739
+ };
740
+ vite.watcher.add([appRoot, path.join(appRoot, "**/*")]);
741
+ vite.watcher.on("all", (_event, changedPath) => {
742
+ handleChange(changedPath);
743
+ });
744
+ try {
745
+ const nativeWatcher = watch(appRoot, { recursive: true }, (_event, filename) => {
746
+ if (filename) {
747
+ handleChange(path.join(appRoot, filename.toString()));
748
+ }
749
+ });
750
+ }
751
+ catch {
752
+ // Vite's watcher above is still active on platforms without recursive fs.watch.
753
+ }
754
+ const poller = setInterval(() => {
755
+ const nextSourceMtime = latestSourceMtime(appRoot, outDir);
756
+ if (nextSourceMtime > lastSourceMtime) {
757
+ lastSourceMtime = nextSourceMtime;
758
+ handleChange(appRoot);
759
+ }
760
+ }, 500);
761
+ }
762
+ function shouldSkipDevWatch(changedPath, appRoot, outDir) {
763
+ const resolved = path.resolve(changedPath);
764
+ return (resolved.startsWith(path.resolve(outDir)) ||
765
+ resolved.includes(`${path.sep}node_modules${path.sep}`) ||
766
+ resolved.includes(`${path.sep}dist${path.sep}`) ||
767
+ !resolved.startsWith(path.resolve(appRoot)));
768
+ }
769
+ function latestSourceMtime(root, outDir) {
770
+ let latest = 0;
771
+ const visit = (current) => {
772
+ if (shouldSkipDevWatch(current, root, outDir) &&
773
+ path.resolve(current) !== path.resolve(root)) {
774
+ return;
775
+ }
776
+ let stats;
777
+ try {
778
+ stats = statSync(current);
779
+ }
780
+ catch {
781
+ return;
782
+ }
783
+ latest = Math.max(latest, stats.mtimeMs);
784
+ if (!stats.isDirectory()) {
785
+ return;
786
+ }
787
+ let entries;
788
+ try {
789
+ entries = readdirSync(current);
790
+ }
791
+ catch {
792
+ return;
793
+ }
794
+ for (const entry of entries) {
795
+ visit(path.join(current, entry));
796
+ }
797
+ };
798
+ visit(root);
799
+ return latest;
800
+ }
801
+ async function startServer(options) {
802
+ const server = createHttpServer((request, response) => {
803
+ void handleRequest(request, response, options);
804
+ });
805
+ const boundPort = await listenOnAvailablePort(server, options.port, options.host);
806
+ if (boundPort !== options.port) {
807
+ console.log(`Port ${options.port} is busy, using ${boundPort} instead.`);
808
+ }
809
+ console.log(`Resux ${options.dev ? "dev" : "preview"} server running at http://${options.host ?? "localhost"}:${boundPort}`);
810
+ }
811
+ async function listenOnAvailablePort(server, requestedPort, host) {
812
+ const maxAttempts = 20;
813
+ for (let offset = 0; offset < maxAttempts; offset++) {
814
+ const portToTry = requestedPort + offset;
815
+ try {
816
+ await listen(server, portToTry, host);
817
+ return portToTry;
818
+ }
819
+ catch (error) {
820
+ if (!isAddressInUse(error) || offset === maxAttempts - 1) {
821
+ throw error;
822
+ }
823
+ }
824
+ }
825
+ throw new Error(`No available port found from ${requestedPort} to ${requestedPort + maxAttempts - 1}.`);
826
+ }
827
+ function listen(server, portToTry, host) {
828
+ return new Promise((resolve, reject) => {
829
+ const onError = (error) => {
830
+ server.off("listening", onListening);
831
+ reject(error);
832
+ };
833
+ const onListening = () => {
834
+ server.off("error", onError);
835
+ resolve();
836
+ };
837
+ server.once("error", onError);
838
+ server.once("listening", onListening);
839
+ server.listen(portToTry, host);
840
+ });
841
+ }
842
+ function isAddressInUse(error) {
843
+ return (error instanceof Error && "code" in error && error.code === "EADDRINUSE");
844
+ }
845
+ function requestOriginFromHeaders(request) {
846
+ const forwardedProto = firstHeaderValue(request.headers["x-forwarded-proto"]);
847
+ const forwardedHost = firstHeaderValue(request.headers["x-forwarded-host"]);
848
+ const encrypted = Boolean(request.socket
849
+ .encrypted);
850
+ const proto = forwardedProto ?? (encrypted ? "https" : "http");
851
+ const host = forwardedHost ?? firstHeaderValue(request.headers.host) ?? "localhost:3000";
852
+ return `${proto}://${host}`;
853
+ }
854
+ function firstHeaderValue(value) {
855
+ if (Array.isArray(value)) {
856
+ return value[0]?.split(",")[0]?.trim();
857
+ }
858
+ return value?.split(",")[0]?.trim();
859
+ }
860
+ function readPort(value, fallback) {
861
+ if (!value) {
862
+ return fallback;
863
+ }
864
+ const parsed = Number(value);
865
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
866
+ throw new Error(`PORT must be an integer from 1 to 65535. Received "${value}".`);
867
+ }
868
+ return parsed;
869
+ }
870
+ function printHelp() {
871
+ console.log(`resux ${version}
872
+
873
+ Usage:
874
+ resux dev [app-root] [options]
875
+ resux init [project-dir] [options]
876
+ resux build [app-root] [options]
877
+ resux compile [app-root] [options]
878
+ resux preview [app-root] [options]
879
+ resux start [app-root] [options]
880
+ resux inspect [app-root] [options]
881
+ resux deploy [app-root] [options]
882
+
883
+ Commands:
884
+ init Scaffold a new Resux app
885
+ dev Start the Resux dev server with Vite middleware
886
+ build Build server/client output into .resux and Nitro .output
887
+ compile Build only the lower-level .resux output
888
+ preview Serve the built app, rebuilding when needed
889
+ start Alias for preview, intended for production Node servers
890
+ inspect Print a build manifest summary for debugging
891
+ deploy Generate Node, Docker, or Nitro deployment files
892
+
893
+ Options:
894
+ --security-headers Enable default production security headers
895
+ --no-security-headers
896
+ Disable default production security headers
897
+ --json Print JSON output for inspect
898
+ --preset <preset> Deployment preset for deploy: node, docker, or nitro
899
+ --force Overwrite existing deployment files
900
+ -p, --port <port> Set the server port, default 3000 or PORT
901
+ --host <host> Set the server host
902
+ -v, --version Print the Resux version
903
+ -h, --help Show this help message
904
+ `);
905
+ }
906
+ async function handleRequest(request, response, options) {
907
+ const requestOrigin = requestOriginFromHeaders(request);
908
+ const requestUrl = new URL(request.url ?? "/", requestOrigin);
909
+ try {
910
+ applyDefaultSecurityHeaders(response, options.securityHeaders);
911
+ if (options.dev &&
912
+ options.vite &&
913
+ isViteInternalRequest(requestUrl.pathname)) {
914
+ await serveViteMiddleware(request, response, options.vite);
915
+ return;
916
+ }
917
+ if (options.dev && requestUrl.pathname === "/__resux/dev-events") {
918
+ serveDevEvents(request, response);
919
+ return;
920
+ }
921
+ if (requestUrl.pathname === "/__resux/health") {
922
+ await serveHealthCheck(response, options);
923
+ return;
924
+ }
925
+ if (requestUrl.pathname === "/__resux/route") {
926
+ await serveRoutePayload(response, requestUrl, options, requestOrigin);
927
+ return;
928
+ }
929
+ if (requestUrl.pathname.startsWith("/__resux/")) {
930
+ if (activeDevBuild) {
931
+ await activeDevBuild;
932
+ }
933
+ if (options.dev &&
934
+ options.vite &&
935
+ resolveResuxViteAssetUrl(requestUrl.pathname)) {
936
+ await serveViteResuxAsset(response, options.vite, requestUrl.pathname);
937
+ return;
938
+ }
939
+ await serveResuxAsset(response, options.outDir, requestUrl.pathname);
940
+ return;
941
+ }
942
+ if (options.dev) {
943
+ await ensureDevBuild(options.appRoot, options.outDir, options.buildOptions, options.vite);
944
+ }
945
+ const manifest = await importManifest(options.outDir, options.dev);
946
+ const routeRule = matchRouteRule(manifest.routeRules, requestUrl.pathname);
947
+ applyRouteRuleHeaders(response, routeRule);
948
+ if (routeRule?.cors && request.method === "OPTIONS") {
949
+ response.writeHead(204);
950
+ response.end();
951
+ return;
952
+ }
953
+ const middlewareHandled = await runServerMiddleware(request, response, requestUrl, manifest);
954
+ if (middlewareHandled) {
955
+ return;
956
+ }
957
+ if (routeRule?.redirect) {
958
+ serveRouteRuleRedirect(response, routeRule.redirect);
959
+ return;
960
+ }
961
+ const serverHandled = await serveServerHandler(request, response, requestUrl, manifest, routeRule);
962
+ if (serverHandled) {
963
+ return;
964
+ }
965
+ const publicHandled = await servePublicFile(response, options.appRoot, requestUrl.pathname);
966
+ if (publicHandled) {
967
+ return;
968
+ }
969
+ const rendered = await renderRoute(requestUrl, options, manifest, requestOrigin);
970
+ if (!rendered) {
971
+ await serveErrorDocument(response, options, manifest, 404, "Page not found");
972
+ return;
973
+ }
974
+ if ("type" in rendered && rendered.type === "redirect") {
975
+ response.writeHead(rendered.statusCode, { location: rendered.to });
976
+ response.end();
977
+ return;
978
+ }
979
+ if ("type" in rendered && rendered.type === "abort") {
980
+ response.writeHead(rendered.statusCode, {
981
+ "content-type": "text/plain; charset=utf-8",
982
+ });
983
+ response.end(rendered.message);
984
+ return;
985
+ }
986
+ const html = renderDocument(rendered, "Resux App", {
987
+ devReload: options.dev,
988
+ });
989
+ response.writeHead(routeRule?.statusCode ?? 200, {
990
+ "content-type": "text/html; charset=utf-8",
991
+ });
992
+ response.end(html);
993
+ }
994
+ catch (error) {
995
+ if (response.writableEnded) {
996
+ return;
997
+ }
998
+ await serveErrorDocument(response, options, undefined, 500, error);
999
+ }
1000
+ }
1001
+ async function serveErrorDocument(response, options, loadedManifest, statusCode, error) {
1002
+ const statusMessage = statusCode === 404 ? "Not Found" : "Internal Server Error";
1003
+ const errorPayload = createErrorPayload(error, statusCode, statusMessage, options.dev);
1004
+ try {
1005
+ const manifest = loadedManifest ?? (await importManifest(options.outDir, options.dev));
1006
+ if (manifest.errorComponent) {
1007
+ const rendered = await renderApp({
1008
+ app: manifest.app,
1009
+ page: manifest.errorComponent,
1010
+ pageProps: {
1011
+ error: errorPayload,
1012
+ },
1013
+ route: {
1014
+ path: statusCode === 404 ? "/404" : "/500",
1015
+ params: {},
1016
+ query: {},
1017
+ },
1018
+ components: manifest.components,
1019
+ layouts: manifest.layouts,
1020
+ modules: manifest.modules,
1021
+ vueIslands: manifest.vueIslands,
1022
+ runtimeConfig: manifest.runtimeConfig,
1023
+ appHead: manifest.appHead,
1024
+ plugins: manifest.plugins,
1025
+ });
1026
+ response.writeHead(statusCode, {
1027
+ "content-type": "text/html; charset=utf-8",
1028
+ });
1029
+ response.end(renderDocument(rendered, statusMessage, { devReload: options.dev }));
1030
+ return;
1031
+ }
1032
+ }
1033
+ catch {
1034
+ // Fall back to plain text below if the error component cannot render.
1035
+ }
1036
+ response.writeHead(statusCode, {
1037
+ "content-type": "text/plain; charset=utf-8",
1038
+ });
1039
+ response.end(createPlainErrorBody(errorPayload, options.dev));
1040
+ }
1041
+ async function serveHealthCheck(response, options) {
1042
+ if (options.dev) {
1043
+ await ensureDevBuild(options.appRoot, options.outDir, options.buildOptions, options.vite);
1044
+ }
1045
+ const manifest = JSON.parse(await readFile(path.join(options.outDir, "manifest.json"), "utf8"));
1046
+ const body = {
1047
+ status: "ok",
1048
+ framework: "resux",
1049
+ mode: options.dev ? "dev" : "production",
1050
+ counts: {
1051
+ routes: manifest.routes?.length ?? 0,
1052
+ serverMiddleware: manifest.serverMiddleware?.length ?? 0,
1053
+ serverHandlers: manifest.serverHandlers?.length ?? 0,
1054
+ routeRules: Object.keys(manifest.routeRules ?? {}).length,
1055
+ },
1056
+ features: {
1057
+ vite: manifest.features?.vite ?? (options.dev ? "dev" : "build"),
1058
+ server: manifest.features?.server ?? (options.dev ? "modules" : "bundle"),
1059
+ },
1060
+ };
1061
+ response.writeHead(200, {
1062
+ "content-type": "application/json; charset=utf-8",
1063
+ "cache-control": "no-store",
1064
+ });
1065
+ response.end(JSON.stringify(body));
1066
+ }
1067
+ function createErrorPayload(error, statusCode, statusMessage, dev) {
1068
+ const message = error instanceof Error ? error.message : String(error);
1069
+ const payload = {
1070
+ statusCode,
1071
+ statusMessage,
1072
+ message,
1073
+ };
1074
+ if (dev && error instanceof Error) {
1075
+ payload.name = error.name;
1076
+ payload.stack = error.stack;
1077
+ if ("cause" in error && error.cause) {
1078
+ payload.cause = serializeErrorCause(error.cause);
1079
+ }
1080
+ }
1081
+ return payload;
1082
+ }
1083
+ function serializeErrorCause(cause) {
1084
+ if (cause instanceof Error) {
1085
+ return {
1086
+ name: cause.name,
1087
+ message: cause.message,
1088
+ stack: cause.stack,
1089
+ };
1090
+ }
1091
+ return cause;
1092
+ }
1093
+ function createPlainErrorBody(error, dev) {
1094
+ if (error.statusCode === 404) {
1095
+ return "Not found";
1096
+ }
1097
+ if (dev && error.stack) {
1098
+ return error.stack;
1099
+ }
1100
+ return error.message;
1101
+ }
1102
+ async function serveRoutePayload(response, requestUrl, options, requestOrigin) {
1103
+ const targetPath = requestUrl.searchParams.get("path");
1104
+ if (!targetPath || !targetPath.startsWith("/")) {
1105
+ response.writeHead(400, {
1106
+ "content-type": "application/json; charset=utf-8",
1107
+ });
1108
+ response.end(JSON.stringify({
1109
+ error: "Route payload requests need a path query like /__resux/route?path=/post/42.",
1110
+ }));
1111
+ return;
1112
+ }
1113
+ const targetUrl = new URL(targetPath, requestOrigin);
1114
+ if (options.dev) {
1115
+ await ensureDevBuild(options.appRoot, options.outDir, options.buildOptions, options.vite);
1116
+ }
1117
+ const manifest = await importManifest(options.outDir, options.dev);
1118
+ const routeRule = matchRouteRule(manifest.routeRules, targetUrl.pathname);
1119
+ if (routeRule?.redirect) {
1120
+ const redirect = normalizeRouteRuleRedirect(routeRule.redirect);
1121
+ response.writeHead(200, {
1122
+ "content-type": "application/json; charset=utf-8",
1123
+ });
1124
+ response.end(JSON.stringify({
1125
+ redirect: redirect.to,
1126
+ statusCode: redirect.statusCode,
1127
+ }));
1128
+ return;
1129
+ }
1130
+ const rendered = await renderRoute(targetUrl, options, manifest, requestOrigin);
1131
+ if (!rendered) {
1132
+ response.writeHead(404, {
1133
+ "content-type": "application/json; charset=utf-8",
1134
+ });
1135
+ response.end(JSON.stringify({ error: "Not found" }));
1136
+ return;
1137
+ }
1138
+ if ("type" in rendered && rendered.type === "redirect") {
1139
+ response.writeHead(200, {
1140
+ "content-type": "application/json; charset=utf-8",
1141
+ });
1142
+ response.end(JSON.stringify({
1143
+ redirect: rendered.to,
1144
+ statusCode: rendered.statusCode,
1145
+ }));
1146
+ return;
1147
+ }
1148
+ if ("type" in rendered && rendered.type === "abort") {
1149
+ response.writeHead(rendered.statusCode, {
1150
+ "content-type": "application/json; charset=utf-8",
1151
+ });
1152
+ response.end(JSON.stringify({ error: rendered.message }));
1153
+ return;
1154
+ }
1155
+ response.writeHead(200, {
1156
+ "content-type": "application/json; charset=utf-8",
1157
+ "cache-control": "no-store",
1158
+ });
1159
+ response.end(JSON.stringify(rendered));
1160
+ }
1161
+ function applyDefaultSecurityHeaders(response, enabled) {
1162
+ if (!enabled) {
1163
+ return;
1164
+ }
1165
+ setHeaderIfUnset(response, "x-content-type-options", "nosniff");
1166
+ setHeaderIfUnset(response, "referrer-policy", "strict-origin-when-cross-origin");
1167
+ setHeaderIfUnset(response, "x-frame-options", "SAMEORIGIN");
1168
+ setHeaderIfUnset(response, "cross-origin-opener-policy", "same-origin");
1169
+ setHeaderIfUnset(response, "permissions-policy", "camera=(), microphone=(), geolocation=()");
1170
+ }
1171
+ function setHeaderIfUnset(response, name, value) {
1172
+ if (!response.hasHeader(name)) {
1173
+ response.setHeader(name, value);
1174
+ }
1175
+ }
1176
+ async function renderRoute(requestUrl, options, loadedManifest, requestOrigin) {
1177
+ if (options.dev && !loadedManifest) {
1178
+ await ensureDevBuild(options.appRoot, options.outDir, options.buildOptions, options.vite);
1179
+ }
1180
+ const manifest = loadedManifest ?? (await importManifest(options.outDir, options.dev));
1181
+ const matched = manifest.matchRoute(requestUrl.pathname);
1182
+ if (!matched) {
1183
+ return null;
1184
+ }
1185
+ const routeContext = {
1186
+ path: requestUrl.pathname,
1187
+ params: matched.params,
1188
+ query: readQuery(requestUrl),
1189
+ origin: requestOrigin ?? requestUrl.origin,
1190
+ };
1191
+ const middlewareResult = await runRouteMiddleware(manifest, routeContext, matched.route.meta);
1192
+ if (middlewareResult) {
1193
+ return middlewareResult;
1194
+ }
1195
+ return renderApp({
1196
+ app: manifest.app,
1197
+ page: matched.route.component,
1198
+ pageMeta: matched.route.meta,
1199
+ route: routeContext,
1200
+ components: manifest.components,
1201
+ layouts: manifest.layouts,
1202
+ modules: manifest.modules,
1203
+ vueIslands: manifest.vueIslands,
1204
+ runtimeConfig: manifest.runtimeConfig,
1205
+ appHead: manifest.appHead,
1206
+ plugins: manifest.plugins,
1207
+ });
1208
+ }
1209
+ async function runRouteMiddleware(manifest, to, pageMeta) {
1210
+ const from = { path: "", params: {}, query: {} };
1211
+ const names = normalizeMiddlewareNames(pageMeta?.middleware);
1212
+ const selected = [
1213
+ ...manifest.middleware.filter((entry) => entry.global),
1214
+ ...names
1215
+ .map((name) => manifest.middleware.find((entry) => entry.name === name))
1216
+ .filter((entry) => Boolean(entry)),
1217
+ ];
1218
+ for (const entry of selected) {
1219
+ const result = (await entry.handler(to, from));
1220
+ const normalized = normalizeMiddlewareResult(result);
1221
+ if (normalized) {
1222
+ return normalized;
1223
+ }
1224
+ }
1225
+ return null;
1226
+ }
1227
+ async function runServerMiddleware(request, response, requestUrl, manifest) {
1228
+ for (const entry of manifest.serverMiddleware ?? []) {
1229
+ const result = await entry.handler(createServerEvent(request, response, requestUrl, {}));
1230
+ if (response.writableEnded) {
1231
+ return true;
1232
+ }
1233
+ if (result === undefined || result === null) {
1234
+ continue;
1235
+ }
1236
+ await sendServerResult(response, result);
1237
+ return true;
1238
+ }
1239
+ return false;
1240
+ }
1241
+ function normalizeMiddlewareNames(value) {
1242
+ if (!value) {
1243
+ return [];
1244
+ }
1245
+ return (Array.isArray(value) ? value : [value]).map((name) => String(name));
1246
+ }
1247
+ function normalizeMiddlewareResult(result) {
1248
+ if (!result) {
1249
+ return result === false
1250
+ ? { type: "abort", statusCode: 403, message: "Navigation aborted" }
1251
+ : null;
1252
+ }
1253
+ if (typeof result === "string") {
1254
+ return { type: "redirect", to: result, statusCode: 302 };
1255
+ }
1256
+ if (result.type === "redirect") {
1257
+ return {
1258
+ type: "redirect",
1259
+ to: result.to,
1260
+ statusCode: result.statusCode ?? 302,
1261
+ };
1262
+ }
1263
+ if (result.type === "abort") {
1264
+ return {
1265
+ type: "abort",
1266
+ message: result.message ?? "Navigation aborted",
1267
+ statusCode: result.statusCode ?? 403,
1268
+ };
1269
+ }
1270
+ return null;
1271
+ }
1272
+ function matchRouteRule(routeRules, pathname) {
1273
+ if (!routeRules) {
1274
+ return null;
1275
+ }
1276
+ const matched = Object.entries(routeRules)
1277
+ .filter(([pattern]) => routeRuleMatches(pattern, pathname))
1278
+ .sort(([left], [right]) => routeRuleScore(right) - routeRuleScore(left))[0];
1279
+ return matched?.[1] ?? null;
1280
+ }
1281
+ function routeRuleMatches(pattern, pathname) {
1282
+ if (pattern === pathname) {
1283
+ return true;
1284
+ }
1285
+ if (pattern.endsWith("/**")) {
1286
+ const prefix = pattern.slice(0, -3);
1287
+ return pathname === prefix || pathname.startsWith(`${prefix}/`);
1288
+ }
1289
+ if (!pattern.includes("*")) {
1290
+ return false;
1291
+ }
1292
+ const source = `^${pattern
1293
+ .split("**")
1294
+ .map((part) => part.split("*").map(escapeRegExp).join("[^/]*"))
1295
+ .join(".*")}$`;
1296
+ return new RegExp(source).test(pathname);
1297
+ }
1298
+ function routeRuleScore(pattern) {
1299
+ return (pattern.replace(/\*/g, "").length * 10 - (pattern.match(/\*/g)?.length ?? 0));
1300
+ }
1301
+ function escapeRegExp(value) {
1302
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1303
+ }
1304
+ function applyRouteRuleHeaders(response, rule) {
1305
+ for (const [name, value] of Object.entries(rule?.headers ?? {})) {
1306
+ response.setHeader(name, value);
1307
+ }
1308
+ const cacheControl = routeRuleCacheControl(rule?.cache);
1309
+ if (cacheControl) {
1310
+ response.setHeader("cache-control", cacheControl);
1311
+ }
1312
+ applyCorsRule(response, rule?.cors);
1313
+ }
1314
+ function routeRuleCacheControl(cache) {
1315
+ if (cache === undefined) {
1316
+ return null;
1317
+ }
1318
+ if (cache === false) {
1319
+ return "no-store";
1320
+ }
1321
+ if (typeof cache === "string") {
1322
+ return cache;
1323
+ }
1324
+ const parts = [];
1325
+ if (Number.isFinite(cache.maxAge)) {
1326
+ parts.push(`public, max-age=${Math.floor(cache.maxAge)}`);
1327
+ }
1328
+ if (Number.isFinite(cache.swr)) {
1329
+ parts.push(`stale-while-revalidate=${Math.floor(cache.swr)}`);
1330
+ }
1331
+ return parts.join(", ") || null;
1332
+ }
1333
+ function applyCorsRule(response, cors) {
1334
+ if (!cors) {
1335
+ return;
1336
+ }
1337
+ const config = cors === true ? {} : cors;
1338
+ response.setHeader("access-control-allow-origin", config.origin ?? "*");
1339
+ response.setHeader("access-control-allow-methods", (config.methods ?? [
1340
+ "GET",
1341
+ "HEAD",
1342
+ "POST",
1343
+ "PUT",
1344
+ "PATCH",
1345
+ "DELETE",
1346
+ "OPTIONS",
1347
+ ]).join(", "));
1348
+ response.setHeader("access-control-allow-headers", (config.headers ?? ["content-type", "authorization"]).join(", "));
1349
+ if (config.credentials) {
1350
+ response.setHeader("access-control-allow-credentials", "true");
1351
+ }
1352
+ }
1353
+ function serveRouteRuleRedirect(response, redirect) {
1354
+ const normalized = normalizeRouteRuleRedirect(redirect);
1355
+ response.writeHead(normalized.statusCode, { location: normalized.to });
1356
+ response.end();
1357
+ }
1358
+ function normalizeRouteRuleRedirect(redirect) {
1359
+ if (typeof redirect === "string") {
1360
+ return { to: redirect, statusCode: 307 };
1361
+ }
1362
+ return {
1363
+ to: redirect?.to ?? "/",
1364
+ statusCode: redirect?.statusCode ?? 307,
1365
+ };
1366
+ }
1367
+ async function serveServerHandler(request, response, requestUrl, manifest, routeRule) {
1368
+ const matched = manifest.matchServerHandler?.(requestUrl.pathname);
1369
+ if (!matched) {
1370
+ return false;
1371
+ }
1372
+ const result = await matched.route.handler(createServerEvent(request, response, requestUrl, matched.params));
1373
+ if (response.writableEnded) {
1374
+ return true;
1375
+ }
1376
+ await sendServerResult(response, result, routeRule?.statusCode ?? 200);
1377
+ return true;
1378
+ }
1379
+ function createServerEvent(request, response, requestUrl, params) {
1380
+ return {
1381
+ path: requestUrl.pathname,
1382
+ method: request.method ?? "GET",
1383
+ query: readQuery(requestUrl),
1384
+ params,
1385
+ node: {
1386
+ req: request,
1387
+ res: response,
1388
+ },
1389
+ };
1390
+ }
1391
+ async function sendServerResult(response, result, statusCode = 200) {
1392
+ if (result instanceof Response) {
1393
+ const headers = {};
1394
+ result.headers.forEach((value, key) => {
1395
+ headers[key] = value;
1396
+ });
1397
+ response.writeHead(result.status, headers);
1398
+ response.end(Buffer.from(await result.arrayBuffer()));
1399
+ return;
1400
+ }
1401
+ if (result === false) {
1402
+ response.writeHead(403, { "content-type": "text/plain; charset=utf-8" });
1403
+ response.end("Forbidden");
1404
+ return;
1405
+ }
1406
+ if (isServerRedirectResult(result)) {
1407
+ response.writeHead(result.statusCode ?? 302, { location: result.to });
1408
+ response.end();
1409
+ return;
1410
+ }
1411
+ if (isServerAbortResult(result)) {
1412
+ response.writeHead(result.statusCode ?? 403, {
1413
+ "content-type": "text/plain; charset=utf-8",
1414
+ });
1415
+ response.end(result.message ?? "Request aborted");
1416
+ return;
1417
+ }
1418
+ if (typeof result === "string") {
1419
+ response.writeHead(statusCode, {
1420
+ "content-type": "text/plain; charset=utf-8",
1421
+ });
1422
+ response.end(result);
1423
+ return;
1424
+ }
1425
+ response.writeHead(statusCode, {
1426
+ "content-type": "application/json; charset=utf-8",
1427
+ });
1428
+ response.end(JSON.stringify(result ?? null));
1429
+ }
1430
+ function isServerRedirectResult(value) {
1431
+ return Boolean(value &&
1432
+ typeof value === "object" &&
1433
+ value.type === "redirect" &&
1434
+ typeof value.to === "string");
1435
+ }
1436
+ function isServerAbortResult(value) {
1437
+ return Boolean(value &&
1438
+ typeof value === "object" &&
1439
+ value.type === "abort");
1440
+ }
1441
+ async function servePublicFile(response, appRoot, pathname) {
1442
+ const publicRoot = path.resolve(appRoot, "public");
1443
+ const resolved = path.resolve(publicRoot, `.${decodeURIComponent(pathname)}`);
1444
+ if (!resolved.startsWith(publicRoot)) {
1445
+ return false;
1446
+ }
1447
+ if (!(await exists(resolved))) {
1448
+ return false;
1449
+ }
1450
+ const fileStats = await stat(resolved);
1451
+ if (!fileStats.isFile()) {
1452
+ return false;
1453
+ }
1454
+ response.writeHead(200, {
1455
+ "content-type": mimeType(resolved),
1456
+ ...(!response.hasHeader("cache-control")
1457
+ ? { "cache-control": "no-store" }
1458
+ : {}),
1459
+ });
1460
+ response.end(await readFile(resolved));
1461
+ return true;
1462
+ }
1463
+ function mimeType(file) {
1464
+ const ext = path.extname(file).toLowerCase();
1465
+ const types = {
1466
+ ".css": "text/css; charset=utf-8",
1467
+ ".js": "text/javascript; charset=utf-8",
1468
+ ".mjs": "text/javascript; charset=utf-8",
1469
+ ".json": "application/json; charset=utf-8",
1470
+ ".html": "text/html; charset=utf-8",
1471
+ ".txt": "text/plain; charset=utf-8",
1472
+ ".svg": "image/svg+xml",
1473
+ ".png": "image/png",
1474
+ ".jpg": "image/jpeg",
1475
+ ".jpeg": "image/jpeg",
1476
+ ".webp": "image/webp",
1477
+ ".ico": "image/x-icon",
1478
+ };
1479
+ return types[ext] ?? "application/octet-stream";
1480
+ }
1481
+ async function ensureDevBuild(appRoot, outDir, buildOptions, vite) {
1482
+ const startedAtRevision = devBuildRevision;
1483
+ const sourceMtime = latestSourceMtime(appRoot, outDir);
1484
+ if (sourceMtime > devLastBuildSourceMtime) {
1485
+ devLastBuildSourceMtime = sourceMtime;
1486
+ devBuildDirty = true;
1487
+ }
1488
+ while (devBuildDirty || activeDevBuild) {
1489
+ if (!activeDevBuild) {
1490
+ devBuildDirty = false;
1491
+ activeDevBuild = buildProject(appRoot, outDir, {
1492
+ ...buildOptions,
1493
+ vite: "dev",
1494
+ })
1495
+ .then(() => {
1496
+ devBuildRevision++;
1497
+ vite?.moduleGraph.invalidateAll();
1498
+ })
1499
+ .finally(() => {
1500
+ activeDevBuild = null;
1501
+ });
1502
+ }
1503
+ await activeDevBuild;
1504
+ }
1505
+ return devBuildRevision !== startedAtRevision;
1506
+ }
1507
+ function serveDevEvents(request, response) {
1508
+ response.writeHead(200, {
1509
+ "content-type": "text/event-stream; charset=utf-8",
1510
+ "cache-control": "no-store, no-transform",
1511
+ connection: "keep-alive",
1512
+ });
1513
+ response.write("retry: 1000\n\n");
1514
+ devReloadClients.add(response);
1515
+ request.on("close", () => {
1516
+ devReloadClients.delete(response);
1517
+ });
1518
+ }
1519
+ function notifyDevReloadClients(eventName = "hmr") {
1520
+ devReloadRevision++;
1521
+ const payload = JSON.stringify({ revision: devReloadRevision });
1522
+ for (const client of [...devReloadClients]) {
1523
+ if (client.destroyed || client.writableEnded) {
1524
+ devReloadClients.delete(client);
1525
+ continue;
1526
+ }
1527
+ try {
1528
+ client.write(`event: ${eventName}\ndata: ${payload}\n\n`);
1529
+ }
1530
+ catch {
1531
+ devReloadClients.delete(client);
1532
+ }
1533
+ }
1534
+ }
1535
+ async function serveViteResuxAsset(response, vite, pathname) {
1536
+ const viteUrl = resolveResuxViteAssetUrl(pathname);
1537
+ if (!viteUrl) {
1538
+ response.writeHead(404);
1539
+ response.end("Not found");
1540
+ return;
1541
+ }
1542
+ const transformed = await vite.transformRequest(viteUrl);
1543
+ if (!transformed) {
1544
+ response.writeHead(404);
1545
+ response.end("Not found");
1546
+ return;
1547
+ }
1548
+ response.writeHead(200, {
1549
+ "content-type": "text/javascript; charset=utf-8",
1550
+ "cache-control": "no-store",
1551
+ });
1552
+ response.end(transformed.code);
1553
+ }
1554
+ async function serveViteMiddleware(request, response, vite) {
1555
+ await new Promise((resolve, reject) => {
1556
+ let settled = false;
1557
+ const finish = () => {
1558
+ if (!settled) {
1559
+ settled = true;
1560
+ resolve();
1561
+ }
1562
+ };
1563
+ response.once("finish", finish);
1564
+ vite.middlewares(request, response, (error) => {
1565
+ response.off("finish", finish);
1566
+ if (settled) {
1567
+ return;
1568
+ }
1569
+ settled = true;
1570
+ if (error) {
1571
+ reject(error instanceof Error ? error : new Error(String(error)));
1572
+ return;
1573
+ }
1574
+ if (!response.writableEnded) {
1575
+ response.writeHead(404);
1576
+ response.end("Not found");
1577
+ }
1578
+ resolve();
1579
+ });
1580
+ });
1581
+ }
1582
+ async function serveResuxAsset(response, outDir, pathname) {
1583
+ const relative = resolveResuxAssetPath(pathname);
1584
+ if (!relative) {
1585
+ response.writeHead(404);
1586
+ response.end("Not found");
1587
+ return;
1588
+ }
1589
+ const resolved = path.resolve(outDir, relative);
1590
+ const allowedRoot = path.resolve(outDir, "client");
1591
+ if (!resolved.startsWith(allowedRoot)) {
1592
+ response.writeHead(403);
1593
+ response.end("Forbidden");
1594
+ return;
1595
+ }
1596
+ if (!(await exists(resolved))) {
1597
+ response.writeHead(404);
1598
+ response.end("Not found");
1599
+ return;
1600
+ }
1601
+ response.writeHead(200, {
1602
+ "content-type": mimeType(resolved),
1603
+ "cache-control": "no-store",
1604
+ });
1605
+ response.end(await readFile(resolved, "utf8"));
1606
+ }
1607
+ function resolveResuxAssetPath(pathname) {
1608
+ if (pathname === "/__resux/runtime-client.mjs") {
1609
+ return "client/runtime-client.mjs";
1610
+ }
1611
+ if (pathname.startsWith("/__resux/handlers/")) {
1612
+ return pathname.replace(/^\/__resux\/handlers\//, "client/handlers/");
1613
+ }
1614
+ if (pathname.startsWith("/__resux/vue-islands/")) {
1615
+ return pathname.replace(/^\/__resux\/vue-islands\//, "client/vue-islands/");
1616
+ }
1617
+ return null;
1618
+ }
1619
+ function resolveResuxViteAssetUrl(pathname) {
1620
+ if (pathname === "/__resux/runtime-client.mjs") {
1621
+ return "/runtime-client.mjs";
1622
+ }
1623
+ if (pathname.startsWith("/__resux/handlers/")) {
1624
+ return pathname.replace(/^\/__resux\/handlers\//, "/handlers/");
1625
+ }
1626
+ if (pathname.startsWith("/__resux/vue-islands/")) {
1627
+ return pathname.replace(/^\/__resux\/vue-islands\//, "/vue-islands/");
1628
+ }
1629
+ return null;
1630
+ }
1631
+ function isViteInternalRequest(pathname) {
1632
+ return (pathname === "/runtime-client.mjs" ||
1633
+ pathname.startsWith("/@") ||
1634
+ pathname.startsWith("/node_modules/.vite/"));
1635
+ }
1636
+ async function importManifest(outDir, dev = false) {
1637
+ const file = !dev && (await exists(path.join(outDir, "server-bundle", "index.mjs")))
1638
+ ? path.join(outDir, "server-bundle", "index.mjs")
1639
+ : path.join(outDir, "server", "manifest.mjs");
1640
+ const stats = await stat(file);
1641
+ return import(`${pathToFileURL(file).href}?t=${stats.mtimeMs}`);
1642
+ }
1643
+ function readQuery(url) {
1644
+ const query = {};
1645
+ for (const [key, value] of url.searchParams) {
1646
+ const existing = query[key];
1647
+ if (Array.isArray(existing)) {
1648
+ existing.push(value);
1649
+ }
1650
+ else if (existing !== undefined) {
1651
+ query[key] = [existing, value];
1652
+ }
1653
+ else {
1654
+ query[key] = value;
1655
+ }
1656
+ }
1657
+ return query;
1658
+ }
1659
+ async function exists(file) {
1660
+ try {
1661
+ await stat(file);
1662
+ return true;
1663
+ }
1664
+ catch {
1665
+ return false;
1666
+ }
1667
+ }
1668
+ //# sourceMappingURL=cli.js.map