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