resuxjs 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1599 @@
1
+ import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import { NodeTypes, parse as parseTemplate } from "@vue/compiler-dom";
6
+ import { parse as parseSfc } from "@vue/compiler-sfc";
7
+ import vuePlugin from "@vitejs/plugin-vue";
8
+ import ts from "typescript";
9
+ import { build as viteBuild } from "vite";
10
+ import { getClientRuntimeSource } from "../runtime/index.js";
11
+ const require = createRequire(import.meta.url);
12
+ export class ResuxCompileError extends Error {
13
+ location;
14
+ constructor(message, location) {
15
+ super(location ? `${message} (${location.file}:${location.line}:${location.column})` : message);
16
+ this.name = "ResuxCompileError";
17
+ this.location = location;
18
+ }
19
+ }
20
+ export async function buildProject(appRoot, outDir = path.join(appRoot, ".resux"), options = {}) {
21
+ const absoluteRoot = path.resolve(appRoot);
22
+ const absoluteOut = path.resolve(outDir);
23
+ const buildOptions = {
24
+ vite: options.vite ?? "build",
25
+ server: options.server ?? (options.vite === "dev" ? "modules" : "bundle")
26
+ };
27
+ await cleanGeneratedOutput(absoluteOut);
28
+ await mkdir(path.join(absoluteOut, "server"), { recursive: true });
29
+ await mkdir(path.join(absoluteOut, "server", "plugins"), { recursive: true });
30
+ await mkdir(path.join(absoluteOut, "server", "middleware"), { recursive: true });
31
+ await mkdir(path.join(absoluteOut, "server", "request-middleware"), { recursive: true });
32
+ await mkdir(path.join(absoluteOut, "server", "handlers"), { recursive: true });
33
+ await mkdir(path.join(absoluteOut, "server", "config-modules"), { recursive: true });
34
+ await mkdir(path.join(absoluteOut, "client", "handlers"), { recursive: true });
35
+ await mkdir(path.join(absoluteOut, "client", "vue-islands"), { recursive: true });
36
+ await mkdir(path.join(absoluteOut, "vite-client", "handlers"), { recursive: true });
37
+ await mkdir(path.join(absoluteOut, "vite-client", "vue-islands"), { recursive: true });
38
+ const runtimeConfig = await readRuntimeConfig(absoluteRoot, absoluteOut);
39
+ const routeRules = createRouteRules(runtimeConfig);
40
+ const componentFiles = await discoverAppVueFiles(absoluteRoot, "components");
41
+ const pageFiles = await discoverAppVueFiles(absoluteRoot, "pages");
42
+ const layoutFiles = await discoverAppVueFiles(absoluteRoot, "layouts");
43
+ const appFile = await optionalFile(path.join(absoluteRoot, "app.vue"))
44
+ ?? await optionalFile(path.join(absoluteRoot, "app", "app.vue"));
45
+ const errorFile = await optionalFile(path.join(absoluteRoot, "error.vue"))
46
+ ?? await optionalFile(path.join(absoluteRoot, "app", "error.vue"));
47
+ const pluginFiles = await discoverTopLevelTsFiles(absoluteRoot, "plugins");
48
+ const middlewareFiles = await discoverTopLevelTsFiles(absoluteRoot, "middleware");
49
+ const serverMiddlewareFiles = await discoverTopLevelTsFiles(absoluteRoot, path.join("server", "middleware"));
50
+ const serverHandlerFiles = [
51
+ ...await discoverServerFiles(path.join(absoluteRoot, "server", "api"), "/api"),
52
+ ...await discoverServerFiles(path.join(absoluteRoot, "server", "routes"), "")
53
+ ];
54
+ const vueIslands = await discoverVueIslands(absoluteRoot);
55
+ const allFiles = [...componentFiles, ...layoutFiles, ...pageFiles, ...(appFile ? [appFile] : []), ...(errorFile ? [errorFile] : [])];
56
+ const idByFile = new Map();
57
+ const compiledByFile = new Map();
58
+ let index = 0;
59
+ for (const file of allFiles) {
60
+ idByFile.set(file, `m${index++}`);
61
+ }
62
+ for (const file of allFiles) {
63
+ const component = await compileVueFile(file, {
64
+ id: idByFile.get(file),
65
+ name: inferComponentName(absoluteRoot, file)
66
+ });
67
+ compiledByFile.set(file, component);
68
+ await writeFile(path.join(absoluteOut, "server", `${component.id}.mjs`), component.serverSource, "utf8");
69
+ await writeFile(path.join(absoluteOut, "vite-client", "handlers", `${component.id}.mjs`), component.clientSource, "utf8");
70
+ }
71
+ const routes = createRouteManifest(absoluteRoot, pageFiles, idByFile, compiledByFile);
72
+ const components = allFiles.map((file) => compiledByFile.get(file));
73
+ const layouts = layoutFiles.map((file) => compiledByFile.get(file));
74
+ const plugins = pluginFiles.map((file, pluginIndex) => compilePluginFile(file, pluginIndex));
75
+ const middleware = middlewareFiles.map((file, middlewareIndex) => compileMiddlewareFile(file, middlewareIndex));
76
+ const serverMiddleware = serverMiddlewareFiles.map((file, middlewareIndex) => compileServerMiddlewareFile(file, middlewareIndex));
77
+ const serverHandlers = serverHandlerFiles.map((record, handlerIndex) => compileServerHandlerFile(record.file, handlerIndex, record.path));
78
+ const app = appFile ? compiledByFile.get(appFile) : undefined;
79
+ const error = errorFile ? compiledByFile.get(errorFile) : undefined;
80
+ for (const plugin of plugins) {
81
+ await writeFile(path.join(absoluteOut, "server", "plugins", `${plugin.id}.mjs`), plugin.source, "utf8");
82
+ }
83
+ for (const entry of middleware) {
84
+ await writeFile(path.join(absoluteOut, "server", "middleware", `${entry.id}.mjs`), entry.source, "utf8");
85
+ }
86
+ for (const entry of serverMiddleware) {
87
+ await writeFile(path.join(absoluteOut, "server", "request-middleware", `${entry.id}.mjs`), entry.source, "utf8");
88
+ }
89
+ for (const handler of serverHandlers) {
90
+ await writeFile(path.join(absoluteOut, "server", "handlers", `${handler.id}.mjs`), handler.source, "utf8");
91
+ }
92
+ for (const island of vueIslands) {
93
+ const islandEntryDir = path.join(absoluteOut, "vite-client", "vue-islands");
94
+ await writeFile(path.join(islandEntryDir, `${island.name}.mjs`), createVueIslandClientSource(island, islandEntryDir), "utf8");
95
+ }
96
+ if (buildOptions.vite === "dev") {
97
+ await writeViteClientRuntime(absoluteOut);
98
+ }
99
+ else {
100
+ await buildClientAssets(absoluteRoot, absoluteOut, components, vueIslands);
101
+ }
102
+ await writeFile(path.join(absoluteOut, "server", "manifest.mjs"), createServerManifestSource(routes, components, layouts, plugins, middleware, serverMiddleware, serverHandlers, vueIslands, app, error, runtimeConfig, buildOptions), "utf8");
103
+ if (buildOptions.server === "bundle") {
104
+ await buildServerBundle(absoluteRoot, absoluteOut);
105
+ }
106
+ await writeFile(path.join(absoluteOut, "manifest.json"), JSON.stringify({
107
+ routes,
108
+ components: components.map(({ id, name, file, handlers, meta }) => ({ id, name, file, handlers, meta })),
109
+ layouts: layouts.map(({ id, name, file }) => ({ id, name, file })),
110
+ plugins: plugins.map(({ id, file, mode }) => ({ id, file, mode })),
111
+ middleware: middleware.map(({ id, name, file, global }) => ({ id, name, file, global })),
112
+ serverMiddleware: serverMiddleware.map(({ id, file }) => ({ id, file })),
113
+ serverHandlers: serverHandlers.map(({ id, path: routePath, file, params }) => ({ id, path: routePath, file, params })),
114
+ vueIslands,
115
+ app: app?.id,
116
+ error: error?.id,
117
+ runtimeConfig,
118
+ routeRules,
119
+ features: buildOptions
120
+ }, null, 2), "utf8");
121
+ return {
122
+ appRoot: absoluteRoot,
123
+ outDir: absoluteOut,
124
+ routes,
125
+ components,
126
+ layouts,
127
+ plugins,
128
+ middleware,
129
+ serverMiddleware,
130
+ serverHandlers,
131
+ vueIslands,
132
+ routeRules,
133
+ app,
134
+ error
135
+ };
136
+ }
137
+ async function cleanGeneratedOutput(outDir) {
138
+ await mkdir(outDir, { recursive: true });
139
+ await rm(path.join(outDir, "server"), { recursive: true, force: true });
140
+ await rm(path.join(outDir, "server-bundle"), { recursive: true, force: true });
141
+ await rm(path.join(outDir, "client"), { recursive: true, force: true });
142
+ await rm(path.join(outDir, "vite-client"), { recursive: true, force: true });
143
+ await rm(path.join(outDir, "manifest.json"), { force: true });
144
+ }
145
+ async function buildServerBundle(root, outDir) {
146
+ try {
147
+ await viteBuild({
148
+ root,
149
+ configFile: false,
150
+ publicDir: false,
151
+ appType: "custom",
152
+ clearScreen: false,
153
+ logLevel: "warn",
154
+ build: {
155
+ ssr: path.join(outDir, "server", "manifest.mjs"),
156
+ outDir: path.join(outDir, "server-bundle"),
157
+ emptyOutDir: true,
158
+ minify: "oxc",
159
+ sourcemap: false,
160
+ manifest: false,
161
+ rollupOptions: {
162
+ external: ["resuxjs/runtime"],
163
+ output: {
164
+ format: "es",
165
+ entryFileNames: "index.mjs",
166
+ chunkFileNames: "chunks/[name]-[hash].mjs"
167
+ }
168
+ }
169
+ }
170
+ });
171
+ }
172
+ catch (error) {
173
+ const message = error instanceof Error ? error.message : String(error);
174
+ throw new Error(`Vite server build failed. Ensure vite is installed. ${message}`);
175
+ }
176
+ }
177
+ async function buildClientAssets(root, outDir, components, vueIslands) {
178
+ const inputRoot = path.join(outDir, "vite-client");
179
+ const runtimeInput = await writeViteClientRuntime(outDir);
180
+ const input = {
181
+ "runtime-client": runtimeInput
182
+ };
183
+ for (const component of components) {
184
+ input[`handlers/${component.id}`] = path.join(inputRoot, "handlers", `${component.id}.mjs`);
185
+ }
186
+ for (const island of vueIslands) {
187
+ input[`vue-islands/${island.name}`] = path.join(inputRoot, "vue-islands", `${island.name}.mjs`);
188
+ }
189
+ try {
190
+ await viteBuild({
191
+ root,
192
+ configFile: false,
193
+ publicDir: false,
194
+ appType: "custom",
195
+ clearScreen: false,
196
+ logLevel: "warn",
197
+ plugins: [vuePlugin()],
198
+ resolve: {
199
+ alias: {
200
+ vue: require.resolve("vue")
201
+ }
202
+ },
203
+ build: {
204
+ outDir: path.join(outDir, "client"),
205
+ emptyOutDir: false,
206
+ minify: "oxc",
207
+ sourcemap: false,
208
+ manifest: false,
209
+ rollupOptions: {
210
+ input,
211
+ preserveEntrySignatures: "strict",
212
+ external: (id) => id === "/__resux/runtime-client.mjs",
213
+ output: {
214
+ format: "es",
215
+ entryFileNames: "[name].mjs",
216
+ chunkFileNames: "chunks/[name]-[hash].mjs",
217
+ assetFileNames: "assets/[name]-[hash][extname]"
218
+ }
219
+ }
220
+ }
221
+ });
222
+ }
223
+ catch (error) {
224
+ const message = error instanceof Error ? error.message : String(error);
225
+ throw new Error(`Vite client build failed. Ensure vite is installed. ${message}`);
226
+ }
227
+ finally {
228
+ await rm(inputRoot, { recursive: true, force: true });
229
+ }
230
+ }
231
+ async function writeViteClientRuntime(outDir) {
232
+ const runtimeInput = path.join(outDir, "vite-client", "runtime-client.mjs");
233
+ await writeFile(runtimeInput, getClientRuntimeSource(), "utf8");
234
+ return runtimeInput;
235
+ }
236
+ export async function compileVueFile(file, options) {
237
+ const source = await readFile(file, "utf8");
238
+ return compileVueSource(source, {
239
+ file,
240
+ id: options.id,
241
+ name: options.name ?? pascalCase(path.basename(file, ".vue"))
242
+ });
243
+ }
244
+ export function compileVueSource(source, options) {
245
+ const parsed = parseSfc(source, { filename: options.file });
246
+ const descriptor = parsed.descriptor;
247
+ if (!descriptor.template) {
248
+ throw new ResuxCompileError("Resux components need a <template> block.", locationFromOffset(options.file, source, 0));
249
+ }
250
+ const script = descriptor.scriptSetup?.content ?? "";
251
+ const template = compileTemplate(descriptor.template.content, options.file);
252
+ const analysis = analyzeScript(script, options.file, template.inlineHandlers);
253
+ validateTemplateHandlers(template.handlers, analysis, options.file, source);
254
+ const serverSource = createComponentModuleSource({
255
+ id: options.id,
256
+ name: options.name,
257
+ file: options.file,
258
+ template: template.nodes,
259
+ analysis,
260
+ client: false
261
+ });
262
+ const clientSource = createComponentModuleSource({
263
+ id: options.id,
264
+ name: options.name,
265
+ file: options.file,
266
+ template: template.nodes,
267
+ analysis,
268
+ client: true
269
+ });
270
+ return {
271
+ id: options.id,
272
+ name: options.name,
273
+ file: options.file,
274
+ serverSource,
275
+ clientSource,
276
+ template: template.nodes,
277
+ handlers: [...new Set(template.handlers.map((event) => event.handler))],
278
+ meta: analysis.pageMeta
279
+ };
280
+ }
281
+ export function createRouteManifest(root, files, idByFile, compiledByFile) {
282
+ return files
283
+ .map((file, index) => {
284
+ const pagesRoot = file.includes(`${path.sep}app${path.sep}pages${path.sep}`)
285
+ ? path.join(root, "app", "pages")
286
+ : path.join(root, "pages");
287
+ const relative = normalizePath(path.relative(pagesRoot, file));
288
+ const withoutExtension = relative.replace(/\.vue$/, "");
289
+ const parts = withoutExtension.split("/");
290
+ const params = [];
291
+ const routeParts = parts
292
+ .filter((part, partIndex) => !(part === "index" && partIndex === parts.length - 1))
293
+ .map((part) => {
294
+ const match = /^\[([A-Za-z0-9_]+)\]$/.exec(part);
295
+ if (match) {
296
+ params.push(match[1]);
297
+ return `:${match[1]}`;
298
+ }
299
+ return part;
300
+ });
301
+ const routePath = `/${routeParts.join("/")}`.replace(/\/$/, "") || "/";
302
+ return {
303
+ id: `r${index}`,
304
+ path: routePath,
305
+ file,
306
+ params,
307
+ componentId: idByFile?.get(file) ?? `m${index}`,
308
+ meta: compiledByFile?.get(file)?.meta
309
+ };
310
+ })
311
+ .sort((a, b) => routeScore(b.path) - routeScore(a.path) || a.path.localeCompare(b.path));
312
+ }
313
+ function compileTemplate(template, file) {
314
+ const ast = parseTemplate(template, { comments: false });
315
+ const state = {
316
+ file,
317
+ bindingIndex: 0,
318
+ inlineHandlerIndex: 0,
319
+ handlers: [],
320
+ inlineHandlers: []
321
+ };
322
+ return {
323
+ nodes: ast.children.map((child) => compileTemplateNode(child, state)).filter(Boolean),
324
+ handlers: state.handlers,
325
+ inlineHandlers: state.inlineHandlers
326
+ };
327
+ }
328
+ function compileTemplateNode(node, state) {
329
+ if (node.type === NodeTypes.TEXT) {
330
+ return {
331
+ type: "text",
332
+ value: node.content
333
+ };
334
+ }
335
+ if (node.type === NodeTypes.INTERPOLATION) {
336
+ return {
337
+ type: "interpolation",
338
+ expression: node.content.content,
339
+ bindingId: nextBindingId(state)
340
+ };
341
+ }
342
+ if (node.type !== NodeTypes.ELEMENT) {
343
+ return null;
344
+ }
345
+ const attrs = [];
346
+ const events = [];
347
+ const element = {
348
+ type: "element",
349
+ tag: node.tag,
350
+ attrs,
351
+ events,
352
+ children: node.children.map((child) => compileTemplateNode(child, state)).filter(Boolean)
353
+ };
354
+ for (const prop of node.props) {
355
+ if (prop.type === NodeTypes.ATTRIBUTE) {
356
+ attrs.push({
357
+ kind: "static",
358
+ name: prop.name,
359
+ value: prop.value?.content ?? ""
360
+ });
361
+ continue;
362
+ }
363
+ if (prop.type !== NodeTypes.DIRECTIVE) {
364
+ continue;
365
+ }
366
+ if (prop.name === "bind") {
367
+ const arg = prop.arg?.content;
368
+ const expression = prop.exp?.content;
369
+ if (!arg || !expression) {
370
+ throw new ResuxCompileError("Dynamic bindings need an argument and expression.", locationFromVueNode(state.file, prop));
371
+ }
372
+ attrs.push({
373
+ kind: "dynamic",
374
+ name: arg,
375
+ value: expression,
376
+ bindingId: nextBindingId(state)
377
+ });
378
+ continue;
379
+ }
380
+ if (prop.name === "on") {
381
+ const arg = prop.arg?.content;
382
+ const expression = prop.exp?.content;
383
+ const modifiers = normalizeEventModifiers(prop.modifiers ?? [], state.file, prop);
384
+ if (!arg || !expression) {
385
+ throw new ResuxCompileError("Events need an argument and expression.", locationFromVueNode(state.file, prop));
386
+ }
387
+ const handler = /^[A-Za-z_$][\w$]*$/.test(expression)
388
+ ? expression
389
+ : createInlineEventHandler(expression, state);
390
+ const event = {
391
+ name: arg,
392
+ handler,
393
+ modifiers
394
+ };
395
+ events.push(event);
396
+ state.handlers.push(event);
397
+ continue;
398
+ }
399
+ if (prop.name === "if") {
400
+ const expression = prop.exp?.content;
401
+ if (!expression) {
402
+ throw new ResuxCompileError("v-if needs an expression.", locationFromVueNode(state.file, prop));
403
+ }
404
+ element.if = {
405
+ expression,
406
+ blockId: nextBindingId(state)
407
+ };
408
+ continue;
409
+ }
410
+ if (prop.name === "for") {
411
+ const expression = prop.exp?.content;
412
+ if (!expression) {
413
+ throw new ResuxCompileError("v-for needs an expression.", locationFromVueNode(state.file, prop));
414
+ }
415
+ element.for = parseForExpression(expression, state.file, prop, state);
416
+ continue;
417
+ }
418
+ if (prop.name === "show") {
419
+ const expression = prop.exp?.content;
420
+ if (!expression) {
421
+ throw new ResuxCompileError("v-show needs an expression.", locationFromVueNode(state.file, prop));
422
+ }
423
+ attrs.push({
424
+ kind: "dynamic",
425
+ name: "hidden",
426
+ value: `!(${expression})`,
427
+ bindingId: nextBindingId(state)
428
+ });
429
+ continue;
430
+ }
431
+ if (prop.name === "text") {
432
+ const expression = prop.exp?.content;
433
+ if (!expression) {
434
+ throw new ResuxCompileError("v-text needs an expression.", locationFromVueNode(state.file, prop));
435
+ }
436
+ element.children = [{
437
+ type: "interpolation",
438
+ expression,
439
+ bindingId: nextBindingId(state)
440
+ }];
441
+ continue;
442
+ }
443
+ if (prop.name === "html") {
444
+ const expression = prop.exp?.content;
445
+ if (!expression) {
446
+ throw new ResuxCompileError("v-html needs an expression.", locationFromVueNode(state.file, prop));
447
+ }
448
+ element.html = {
449
+ expression,
450
+ bindingId: nextBindingId(state)
451
+ };
452
+ element.children = [];
453
+ continue;
454
+ }
455
+ if (prop.name === "model") {
456
+ const expression = prop.exp?.content;
457
+ if (!expression) {
458
+ throw new ResuxCompileError("v-model needs an expression.", locationFromVueNode(state.file, prop));
459
+ }
460
+ if (!isAssignableExpression(expression)) {
461
+ throw new ResuxCompileError("v-model needs an assignable expression like \"message.value\".", locationFromVueNode(state.file, prop));
462
+ }
463
+ const model = createModelBinding(node.tag, node.props, expression, state);
464
+ attrs.push({
465
+ kind: "dynamic",
466
+ name: model.attribute,
467
+ value: model.value,
468
+ bindingId: nextBindingId(state)
469
+ });
470
+ const event = {
471
+ name: model.event,
472
+ handler: model.handler,
473
+ modifiers: []
474
+ };
475
+ events.push(event);
476
+ state.handlers.push(event);
477
+ continue;
478
+ }
479
+ throw new ResuxCompileError(`v-${prop.name} is not supported in the MVP.`, locationFromVueNode(state.file, prop));
480
+ }
481
+ return element;
482
+ }
483
+ function createInlineEventHandler(expression, state) {
484
+ const name = nextInlineHandlerName(state);
485
+ state.inlineHandlers.push({
486
+ name,
487
+ source: `function ${name}($event) {\n${expression}\n}`
488
+ });
489
+ return name;
490
+ }
491
+ function createModelBinding(tag, props, expression, state) {
492
+ const normalizedTag = tag.toLowerCase();
493
+ const inputType = normalizedTag === "input" ? staticAttributeValue(props, "type")?.toLowerCase() : undefined;
494
+ const isCheckbox = inputType === "checkbox";
495
+ const handler = nextInlineHandlerName(state);
496
+ const target = "$event.target";
497
+ const assignment = isCheckbox
498
+ ? `${expression} = Boolean(${target} && ${target}.checked)`
499
+ : `${expression} = ${target} ? ${target}.value : ""`;
500
+ state.inlineHandlers.push({
501
+ name: handler,
502
+ source: `function ${handler}($event) {\n${assignment}\n}`
503
+ });
504
+ return {
505
+ attribute: isCheckbox ? "checked" : "value",
506
+ value: expression,
507
+ event: isCheckbox || normalizedTag === "select" ? "change" : "input",
508
+ handler
509
+ };
510
+ }
511
+ function staticAttributeValue(props, name) {
512
+ const attr = props.find((prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === name);
513
+ return attr?.value?.content;
514
+ }
515
+ function isAssignableExpression(expression) {
516
+ return /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^\]]+\])*$/.test(expression.trim());
517
+ }
518
+ function normalizeEventModifiers(modifiers, file, node) {
519
+ const modifierNames = modifiers.map((modifier) => typeof modifier === "string"
520
+ ? modifier
521
+ : String(modifier.content ?? modifier.name ?? modifier));
522
+ const supported = new Set([
523
+ "prevent",
524
+ "stop",
525
+ "self",
526
+ "once",
527
+ "capture",
528
+ "passive",
529
+ "ctrl",
530
+ "shift",
531
+ "alt",
532
+ "meta",
533
+ "exact",
534
+ "left",
535
+ "middle",
536
+ "right",
537
+ "enter",
538
+ "tab",
539
+ "delete",
540
+ "esc",
541
+ "escape",
542
+ "space",
543
+ "up",
544
+ "down",
545
+ "left",
546
+ "right"
547
+ ]);
548
+ const unsupported = modifierNames.find((modifier) => !supported.has(modifier));
549
+ if (unsupported) {
550
+ throw new ResuxCompileError(`Event modifier ".${unsupported}" is not supported in the resumability runtime yet.`, locationFromVueNode(file, node));
551
+ }
552
+ return modifierNames;
553
+ }
554
+ function parseForExpression(expression, file, node, state) {
555
+ const match = /^\s*(?:\(([^)]+)\)|([A-Za-z_$][\w$]*))\s+(?:in|of)\s+(.+)\s*$/.exec(expression);
556
+ if (!match) {
557
+ throw new ResuxCompileError("v-for must look like \"item in items\" or \"(item, index) in items\".", locationFromVueNode(file, node));
558
+ }
559
+ const aliases = (match[1] ?? match[2]).split(",").map((part) => part.trim()).filter(Boolean);
560
+ if (!aliases[0] || aliases.length > 2) {
561
+ throw new ResuxCompileError("v-for supports only value and optional index aliases.", locationFromVueNode(file, node));
562
+ }
563
+ return {
564
+ value: aliases[0],
565
+ index: aliases[1],
566
+ source: match[3],
567
+ blockId: nextBindingId(state)
568
+ };
569
+ }
570
+ function analyzeScript(script, file, inlineHandlers = []) {
571
+ const sourceFile = ts.createSourceFile(file, script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
572
+ const imports = [];
573
+ const body = [];
574
+ const bindings = new Set();
575
+ const handlerNames = new Set();
576
+ const resumableBindings = new Set();
577
+ const handlers = new Map();
578
+ let pageMeta;
579
+ for (const statement of sourceFile.statements) {
580
+ const text = statement.getFullText(sourceFile);
581
+ if (ts.isImportDeclaration(statement) || ts.isImportEqualsDeclaration(statement)) {
582
+ imports.push(text);
583
+ continue;
584
+ }
585
+ if (isDefinePageMetaStatement(statement)) {
586
+ pageMeta = readPageMeta(statement, sourceFile, file);
587
+ continue;
588
+ }
589
+ body.push(text);
590
+ if (ts.isFunctionDeclaration(statement) && statement.name) {
591
+ bindings.add(statement.name.text);
592
+ handlerNames.add(statement.name.text);
593
+ handlers.set(statement.name.text, statement);
594
+ continue;
595
+ }
596
+ if (ts.isVariableStatement(statement)) {
597
+ for (const declaration of statement.declarationList.declarations) {
598
+ for (const name of collectBindingNames(declaration.name)) {
599
+ bindings.add(name);
600
+ }
601
+ if (ts.isIdentifier(declaration.name)) {
602
+ if (isHandlerLikeInitializer(declaration.initializer)) {
603
+ handlerNames.add(declaration.name.text);
604
+ handlers.set(declaration.name.text, declaration);
605
+ }
606
+ if (isResumableInitializer(declaration.initializer)) {
607
+ resumableBindings.add(declaration.name.text);
608
+ }
609
+ }
610
+ }
611
+ }
612
+ }
613
+ if (inlineHandlers.length > 0) {
614
+ const inlineSource = inlineHandlers.map((handler) => handler.source).join("\n");
615
+ const inlineSourceFile = ts.createSourceFile(`${file}?inline-handlers`, inlineSource, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
616
+ body.push(inlineSource);
617
+ for (const statement of inlineSourceFile.statements) {
618
+ if (ts.isFunctionDeclaration(statement) && statement.name) {
619
+ bindings.add(statement.name.text);
620
+ handlerNames.add(statement.name.text);
621
+ handlers.set(statement.name.text, statement);
622
+ }
623
+ }
624
+ }
625
+ return {
626
+ imports: imports.join("\n"),
627
+ setupBody: body.join("\n"),
628
+ bindings: [...bindings],
629
+ handlerNames,
630
+ resumableBindings,
631
+ handlers,
632
+ sourceFile,
633
+ pageMeta
634
+ };
635
+ }
636
+ function isDefinePageMetaStatement(statement) {
637
+ return ts.isExpressionStatement(statement)
638
+ && ts.isCallExpression(statement.expression)
639
+ && ts.isIdentifier(statement.expression.expression)
640
+ && statement.expression.expression.text === "definePageMeta";
641
+ }
642
+ function readPageMeta(statement, sourceFile, file) {
643
+ if (!isDefinePageMetaStatement(statement)) {
644
+ return {};
645
+ }
646
+ const call = statement.expression;
647
+ const firstArg = call.arguments[0];
648
+ if (!firstArg || !ts.isObjectLiteralExpression(firstArg)) {
649
+ throw new ResuxCompileError("definePageMeta only supports an object literal in Resux.", locationFromTsNode(file, sourceFile, statement));
650
+ }
651
+ return readObjectLiteral(firstArg, sourceFile, file);
652
+ }
653
+ function readObjectLiteral(node, sourceFile, file) {
654
+ const output = {};
655
+ for (const property of node.properties) {
656
+ if (!ts.isPropertyAssignment(property)) {
657
+ throw new ResuxCompileError("Only plain object properties are supported here.", locationFromTsNode(file, sourceFile, property));
658
+ }
659
+ const name = readPropertyName(property.name, sourceFile, file);
660
+ output[name] = readLiteralValue(property.initializer, sourceFile, file);
661
+ }
662
+ return output;
663
+ }
664
+ function readLiteralValue(node, sourceFile, file) {
665
+ if (ts.isStringLiteralLike(node)) {
666
+ return node.text;
667
+ }
668
+ if (node.kind === ts.SyntaxKind.TrueKeyword) {
669
+ return true;
670
+ }
671
+ if (node.kind === ts.SyntaxKind.FalseKeyword) {
672
+ return false;
673
+ }
674
+ if (ts.isNumericLiteral(node)) {
675
+ return Number(node.text);
676
+ }
677
+ if (ts.isArrayLiteralExpression(node)) {
678
+ return node.elements.map((element) => readLiteralValue(element, sourceFile, file));
679
+ }
680
+ if (ts.isObjectLiteralExpression(node)) {
681
+ return readObjectLiteral(node, sourceFile, file);
682
+ }
683
+ throw new ResuxCompileError("Only JSON-like literals are supported here.", locationFromTsNode(file, sourceFile, node));
684
+ }
685
+ function readPropertyName(name, sourceFile, file) {
686
+ if (ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
687
+ return name.text;
688
+ }
689
+ throw new ResuxCompileError("Only simple property names are supported here.", locationFromTsNode(file, sourceFile, name));
690
+ }
691
+ function validateTemplateHandlers(events, analysis, file, fullSource) {
692
+ for (const event of events) {
693
+ if (!analysis.handlerNames.has(event.handler)) {
694
+ throw new ResuxCompileError(`Handler "${event.handler}" must be a top-level function or arrow function.`, locationFromOffset(file, fullSource, 0));
695
+ }
696
+ const handlerNode = analysis.handlers.get(event.handler);
697
+ if (!handlerNode) {
698
+ continue;
699
+ }
700
+ const unsupportedCapture = findUnsupportedCapture(handlerNode, event.handler, analysis);
701
+ if (unsupportedCapture) {
702
+ throw new ResuxCompileError(`Handler "${event.handler}" captures "${unsupportedCapture}", which is not resumable in the MVP.`, locationFromTsNode(file, analysis.sourceFile, handlerNode));
703
+ }
704
+ }
705
+ }
706
+ function findUnsupportedCapture(node, handlerName, analysis) {
707
+ const locals = new Set([handlerName, "event"]);
708
+ const allowedGlobals = new Set(["Math", "Number", "String", "Boolean", "Array", "Object", "Date", "JSON", "console", "undefined"]);
709
+ const allowedTopLevel = new Set([...analysis.resumableBindings]);
710
+ function registerPattern(name) {
711
+ for (const binding of collectBindingNames(name)) {
712
+ locals.add(binding);
713
+ }
714
+ }
715
+ if (ts.isFunctionDeclaration(node)) {
716
+ for (const parameter of node.parameters) {
717
+ registerPattern(parameter.name);
718
+ }
719
+ }
720
+ if (ts.isVariableDeclaration(node) && node.initializer && (ts.isArrowFunction(node.initializer) || ts.isFunctionExpression(node.initializer))) {
721
+ for (const parameter of node.initializer.parameters) {
722
+ registerPattern(parameter.name);
723
+ }
724
+ }
725
+ let unsupported = null;
726
+ function visit(current) {
727
+ if (unsupported) {
728
+ return;
729
+ }
730
+ if (ts.isVariableDeclaration(current)) {
731
+ registerPattern(current.name);
732
+ }
733
+ if (ts.isIdentifier(current) && isValueIdentifier(current)) {
734
+ const name = current.text;
735
+ if (!locals.has(name) && !allowedGlobals.has(name) && !allowedTopLevel.has(name)) {
736
+ unsupported = name;
737
+ return;
738
+ }
739
+ }
740
+ ts.forEachChild(current, visit);
741
+ }
742
+ ts.forEachChild(node, visit);
743
+ return unsupported;
744
+ }
745
+ function isValueIdentifier(node) {
746
+ const parent = node.parent;
747
+ if (!parent) {
748
+ return true;
749
+ }
750
+ if (ts.isPropertyAccessExpression(parent) && parent.name === node) {
751
+ return false;
752
+ }
753
+ if (ts.isPropertyAssignment(parent) && parent.name === node) {
754
+ return false;
755
+ }
756
+ if ((ts.isVariableDeclaration(parent) || ts.isFunctionDeclaration(parent) || ts.isParameter(parent)) && parent.name === node) {
757
+ return false;
758
+ }
759
+ if (ts.isBindingElement(parent) && parent.name === node) {
760
+ return false;
761
+ }
762
+ return true;
763
+ }
764
+ function isHandlerLikeInitializer(node) {
765
+ return Boolean(node && (ts.isArrowFunction(node) || ts.isFunctionExpression(node)));
766
+ }
767
+ function isResumableInitializer(node) {
768
+ if (!node) {
769
+ return false;
770
+ }
771
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
772
+ return ["useState", "useAsyncData", "useRoute", "useRuntimeConfig", "useResuxApp", "defineProps"].includes(node.expression.text);
773
+ }
774
+ if (ts.isAwaitExpression(node) && ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression)) {
775
+ return ["useAsyncData", "useFetch"].includes(node.expression.expression.text);
776
+ }
777
+ return false;
778
+ }
779
+ function collectBindingNames(name) {
780
+ if (ts.isIdentifier(name)) {
781
+ return [name.text];
782
+ }
783
+ const names = [];
784
+ for (const element of name.elements) {
785
+ if (ts.isBindingElement(element)) {
786
+ names.push(...collectBindingNames(element.name));
787
+ }
788
+ }
789
+ return names;
790
+ }
791
+ function createComponentModuleSource(options) {
792
+ const importPath = options.client ? "/__resux/runtime-client.mjs" : "resuxjs/runtime";
793
+ const factory = options.client ? "createClientComponent" : "defineComponent";
794
+ const source = [
795
+ `import { ${factory} } from ${JSON.stringify(importPath)};`,
796
+ options.analysis.imports,
797
+ `const __template = ${JSON.stringify(options.template, null, 2)};`,
798
+ `async function __rx_setup(__ctx) {`,
799
+ `const { useState, useAsyncData, useRoute, useHead, useSeoMeta, useRuntimeConfig, useResuxApp, useFetch, $fetch, onMounted, definePageMeta, defineProps } = __ctx;`,
800
+ options.analysis.setupBody,
801
+ `return { ${options.analysis.bindings.join(", ")} };`,
802
+ `}`,
803
+ `export default ${factory}({`,
804
+ `id: ${JSON.stringify(options.id)},`,
805
+ `name: ${JSON.stringify(options.name)},`,
806
+ `file: ${JSON.stringify(normalizePath(options.file))},`,
807
+ `script: __rx_setup,`,
808
+ `template: __template,`,
809
+ `handlers: ${JSON.stringify([...options.analysis.handlerNames])},`,
810
+ `meta: ${JSON.stringify(options.analysis.pageMeta ?? {})}`,
811
+ `});`
812
+ ].join("\n");
813
+ return ts.transpileModule(source, {
814
+ compilerOptions: {
815
+ target: ts.ScriptTarget.ES2022,
816
+ module: ts.ModuleKind.ES2022,
817
+ importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Remove
818
+ }
819
+ }).outputText;
820
+ }
821
+ function createVueIslandClientSource(island, entryDir) {
822
+ const componentImport = relativeImportPath(entryDir, island.file);
823
+ return [
824
+ `import { createApp } from "vue";`,
825
+ `import Component from ${JSON.stringify(componentImport)};`,
826
+ `export function mount(el, props = {}) {`,
827
+ ` const app = createApp(Component, props);`,
828
+ ` app.mount(el);`,
829
+ ` return app;`,
830
+ `}`,
831
+ `export default { mount };`
832
+ ].join("\n");
833
+ }
834
+ function relativeImportPath(fromDir, file) {
835
+ const relative = normalizePath(path.relative(fromDir, file));
836
+ return relative.startsWith(".") ? relative : `./${relative}`;
837
+ }
838
+ function createServerManifestSource(routes, components, layouts, plugins, middleware, serverMiddleware, serverHandlers, vueIslands, app, error, runtimeConfig = {}, buildOptions = {}) {
839
+ const imports = components.map((component) => `import ${component.id} from "./${component.id}.mjs";`).join("\n");
840
+ const pluginImports = plugins.map((plugin) => `import ${plugin.id} from "./plugins/${plugin.id}.mjs";`).join("\n");
841
+ const middlewareImports = middleware.map((entry) => `import ${entry.id} from "./middleware/${entry.id}.mjs";`).join("\n");
842
+ const serverMiddlewareImports = serverMiddleware.map((entry) => `import ${entry.id} from "./request-middleware/${entry.id}.mjs";`).join("\n");
843
+ const handlerImports = serverHandlers.map((handler) => `import ${handler.id} from "./handlers/${handler.id}.mjs";`).join("\n");
844
+ const componentEntries = components.map((component) => `${JSON.stringify(component.name)}: ${component.id}`).join(",\n");
845
+ const layoutEntries = layouts.map((layout) => `${JSON.stringify(layoutNameFromFile(layout.file))}: ${layout.id}`).join(",\n");
846
+ const moduleEntries = components
847
+ .map((component) => `${JSON.stringify(component.id)}: ${JSON.stringify(`/__resux/handlers/${component.id}.mjs`)}`)
848
+ .join(",\n");
849
+ const vueIslandEntries = vueIslands
850
+ .map((island) => `${JSON.stringify(island.name)}: ${JSON.stringify(`/__resux/vue-islands/${island.name}.mjs`)}`)
851
+ .join(",\n");
852
+ const pluginEntries = plugins
853
+ .filter((plugin) => plugin.mode !== "client")
854
+ .map((plugin) => plugin.id)
855
+ .join(",\n");
856
+ const middlewareEntries = middleware
857
+ .map((entry) => `{
858
+ id: ${JSON.stringify(entry.id)},
859
+ name: ${JSON.stringify(entry.name)},
860
+ file: ${JSON.stringify(normalizePath(entry.file))},
861
+ global: ${JSON.stringify(entry.global)},
862
+ handler: ${entry.id}
863
+ }`)
864
+ .join(",\n");
865
+ const serverMiddlewareEntries = serverMiddleware
866
+ .map((entry) => `{
867
+ id: ${JSON.stringify(entry.id)},
868
+ file: ${JSON.stringify(normalizePath(entry.file))},
869
+ handler: ${entry.id}
870
+ }`)
871
+ .join(",\n");
872
+ const serverHandlerEntries = serverHandlers
873
+ .map((handler) => `{
874
+ id: ${JSON.stringify(handler.id)},
875
+ path: ${JSON.stringify(handler.path)},
876
+ file: ${JSON.stringify(normalizePath(handler.file))},
877
+ params: ${JSON.stringify(handler.params)},
878
+ handler: ${handler.id},
879
+ match: createMatcher(${JSON.stringify(handler.path)})
880
+ }`)
881
+ .join(",\n");
882
+ const routeEntries = routes
883
+ .map((route) => {
884
+ const component = components.find((candidate) => candidate.id === route.componentId);
885
+ if (!component) {
886
+ throw new Error(`Missing compiled component for ${route.file}.`);
887
+ }
888
+ return `{
889
+ id: ${JSON.stringify(route.id)},
890
+ path: ${JSON.stringify(route.path)},
891
+ file: ${JSON.stringify(normalizePath(route.file))},
892
+ params: ${JSON.stringify(route.params)},
893
+ meta: ${JSON.stringify(route.meta ?? {})},
894
+ component: ${route.componentId},
895
+ match: createMatcher(${JSON.stringify(route.path)})
896
+ }`;
897
+ })
898
+ .join(",\n");
899
+ const appHead = createAppHead(runtimeConfig);
900
+ const appRuntimeConfig = createRuntimeConfig(runtimeConfig);
901
+ const routeRules = createRouteRules(runtimeConfig);
902
+ return `${imports}
903
+ ${pluginImports}
904
+ ${middlewareImports}
905
+ ${serverMiddlewareImports}
906
+ ${handlerImports}
907
+ export const app = ${app ? app.id : "undefined"};
908
+ export const errorComponent = ${error ? error.id : "undefined"};
909
+ export const components = {
910
+ ${componentEntries}
911
+ };
912
+ export const layouts = {
913
+ ${layoutEntries}
914
+ };
915
+ export const modules = {
916
+ ${moduleEntries}
917
+ };
918
+ export const vueIslands = {
919
+ ${vueIslandEntries}
920
+ };
921
+ export const plugins = [
922
+ ${pluginEntries}
923
+ ];
924
+ export const middleware = [
925
+ ${middlewareEntries}
926
+ ];
927
+ export const serverMiddleware = [
928
+ ${serverMiddlewareEntries}
929
+ ];
930
+ export const serverHandlers = [
931
+ ${serverHandlerEntries}
932
+ ];
933
+ export const runtimeConfig = ${JSON.stringify(appRuntimeConfig, null, 2)};
934
+ export const appHead = ${JSON.stringify(appHead, null, 2)};
935
+ export const routeRules = ${JSON.stringify(routeRules, null, 2)};
936
+ export const routes = [
937
+ ${routeEntries}
938
+ ];
939
+ export function matchRoute(pathname) {
940
+ for (const route of routes) {
941
+ const params = route.match(pathname);
942
+ if (params) return { route, params };
943
+ }
944
+ return null;
945
+ }
946
+ export function matchServerHandler(pathname) {
947
+ for (const route of serverHandlers) {
948
+ const params = route.match(pathname);
949
+ if (params) return { route, params };
950
+ }
951
+ return null;
952
+ }
953
+ function createMatcher(pattern) {
954
+ const names = [];
955
+ const source = pattern === "/" ? "^/$" : "^" + pattern.split("/").map((part) => {
956
+ if (!part) return "";
957
+ if (part.startsWith(":")) {
958
+ names.push(part.slice(1));
959
+ return "/([^/]+)";
960
+ }
961
+ return "/" + part.replace(/[.*+?^${"${"}}()|[\\]\\\\]/g, "\\\\$&");
962
+ }).join("") + "$";
963
+ const regex = new RegExp(source);
964
+ return (pathname) => {
965
+ const match = regex.exec(pathname);
966
+ if (!match) return null;
967
+ const params = {};
968
+ names.forEach((name, index) => {
969
+ params[name] = decodeURIComponent(match[index + 1]);
970
+ });
971
+ return params;
972
+ };
973
+ }
974
+ `;
975
+ }
976
+ function createAppHead(runtimeConfig) {
977
+ const config = runtimeConfig;
978
+ const head = typeof config.app === "object" && config.app && "head" in config.app
979
+ ? config.app.head
980
+ : {};
981
+ const links = Array.isArray(config.css)
982
+ ? config.css.map((href) => ({ rel: "stylesheet", href: String(href) }))
983
+ : [];
984
+ return {
985
+ ...(typeof head === "object" && head ? head : {}),
986
+ link: [
987
+ ...((head?.link) ?? []),
988
+ ...links
989
+ ]
990
+ };
991
+ }
992
+ function createRuntimeConfig(config) {
993
+ const runtimeConfig = config.runtimeConfig;
994
+ return runtimeConfig ?? {};
995
+ }
996
+ function createRouteRules(config) {
997
+ const routeRules = config.routeRules;
998
+ if (!routeRules || typeof routeRules !== "object" || Array.isArray(routeRules)) {
999
+ return {};
1000
+ }
1001
+ const normalized = {};
1002
+ for (const [routePath, rule] of Object.entries(routeRules)) {
1003
+ if (!routePath.startsWith("/") || !rule || typeof rule !== "object" || Array.isArray(rule)) {
1004
+ continue;
1005
+ }
1006
+ const routeRule = rule;
1007
+ normalized[routePath] = {
1008
+ ...(routeRule.headers && typeof routeRule.headers === "object" ? { headers: normalizeStringRecord(routeRule.headers) } : {}),
1009
+ ...(typeof routeRule.redirect === "string" || isRedirectObject(routeRule.redirect)
1010
+ ? { redirect: routeRule.redirect }
1011
+ : {}),
1012
+ ...(isStatusCode(routeRule.statusCode) ? { statusCode: routeRule.statusCode } : {}),
1013
+ ...(normalizeCacheRule(routeRule.cache) !== undefined ? { cache: normalizeCacheRule(routeRule.cache) } : {}),
1014
+ ...(normalizeCorsRule(routeRule.cors) !== undefined ? { cors: normalizeCorsRule(routeRule.cors) } : {})
1015
+ };
1016
+ }
1017
+ return normalized;
1018
+ }
1019
+ function isStatusCode(value) {
1020
+ return Number.isInteger(value) && value >= 100 && value <= 599;
1021
+ }
1022
+ function normalizeCacheRule(value) {
1023
+ if (value === undefined) {
1024
+ return undefined;
1025
+ }
1026
+ if (value === false || typeof value === "string") {
1027
+ return value;
1028
+ }
1029
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1030
+ return undefined;
1031
+ }
1032
+ const cache = {};
1033
+ if (Number.isFinite(value.maxAge) && value.maxAge >= 0) {
1034
+ cache.maxAge = Math.floor(value.maxAge);
1035
+ }
1036
+ if (Number.isFinite(value.swr) && value.swr >= 0) {
1037
+ cache.swr = Math.floor(value.swr);
1038
+ }
1039
+ return Object.keys(cache).length > 0 ? cache : undefined;
1040
+ }
1041
+ function normalizeCorsRule(value) {
1042
+ if (value === undefined) {
1043
+ return undefined;
1044
+ }
1045
+ if (typeof value === "boolean") {
1046
+ return value;
1047
+ }
1048
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1049
+ return undefined;
1050
+ }
1051
+ return {
1052
+ ...(typeof value.origin === "string" ? { origin: value.origin } : {}),
1053
+ ...(Array.isArray(value.methods) ? { methods: value.methods.map(String) } : {}),
1054
+ ...(Array.isArray(value.headers) ? { headers: value.headers.map(String) } : {}),
1055
+ ...(typeof value.credentials === "boolean" ? { credentials: value.credentials } : {})
1056
+ };
1057
+ }
1058
+ function normalizeStringRecord(record) {
1059
+ const output = {};
1060
+ for (const [key, value] of Object.entries(record)) {
1061
+ if (value !== undefined && value !== null) {
1062
+ output[key] = String(value);
1063
+ }
1064
+ }
1065
+ return output;
1066
+ }
1067
+ function isRedirectObject(value) {
1068
+ return Boolean(value
1069
+ && typeof value === "object"
1070
+ && !Array.isArray(value)
1071
+ && typeof value.to === "string");
1072
+ }
1073
+ function layoutNameFromFile(file) {
1074
+ return kebabCase(path.basename(file, ".vue"));
1075
+ }
1076
+ function compilePluginFile(file, index) {
1077
+ const mode = file.includes(".client.") ? "client" : file.includes(".server.") ? "server" : "all";
1078
+ return {
1079
+ id: `p${index}`,
1080
+ file,
1081
+ mode,
1082
+ source: transpileSupportModule(file, `import { defineResuxPlugin } from "resuxjs/runtime";\n`)
1083
+ };
1084
+ }
1085
+ function compileMiddlewareFile(file, index) {
1086
+ const baseName = path.basename(file).replace(/\.(global\.)?[cm]?[tj]s$/, "");
1087
+ const global = /\.global\.[cm]?[tj]s$/.test(file);
1088
+ return {
1089
+ id: `w${index}`,
1090
+ name: kebabCase(baseName),
1091
+ file,
1092
+ global,
1093
+ source: transpileSupportModule(file, `import { defineResuxRouteMiddleware, navigateTo, abortNavigation } from "resuxjs/runtime";\n`)
1094
+ };
1095
+ }
1096
+ function compileServerMiddlewareFile(file, index) {
1097
+ return {
1098
+ id: `s${index}`,
1099
+ file,
1100
+ source: transpileSupportModule(file, `import { defineServerMiddleware, defineEventHandler, eventHandler, readBody, getQuery } from "resuxjs/runtime";\n`)
1101
+ };
1102
+ }
1103
+ function compileServerHandlerFile(file, index, routePath) {
1104
+ const params = collectRouteParams(routePath);
1105
+ return {
1106
+ id: `h${index}`,
1107
+ path: routePath,
1108
+ file,
1109
+ params,
1110
+ source: transpileSupportModule(file, `import { defineEventHandler, eventHandler, readBody, getQuery } from "resuxjs/runtime";\n`)
1111
+ };
1112
+ }
1113
+ function transpileSupportModule(file, prefix = "") {
1114
+ const source = ts.sys.readFile(file) ?? "";
1115
+ return ts.transpileModule(`${prefix}${source}`, {
1116
+ compilerOptions: {
1117
+ target: ts.ScriptTarget.ES2022,
1118
+ module: ts.ModuleKind.ES2022,
1119
+ importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Remove
1120
+ }
1121
+ }).outputText;
1122
+ }
1123
+ async function readRuntimeConfig(root, outDir) {
1124
+ const candidates = [
1125
+ "resux.config.ts",
1126
+ "resux.config.mjs",
1127
+ "resux.config.js"
1128
+ ];
1129
+ for (const candidate of candidates) {
1130
+ const file = await optionalFile(path.join(root, candidate));
1131
+ if (!file) {
1132
+ continue;
1133
+ }
1134
+ const source = normalizeConfigHelpers(await readFile(file, "utf8"));
1135
+ const outputFile = path.join(outDir, "server", "config.mjs");
1136
+ const compiled = ts.transpileModule(source, {
1137
+ compilerOptions: {
1138
+ target: ts.ScriptTarget.ES2022,
1139
+ module: ts.ModuleKind.ES2022
1140
+ }
1141
+ }).outputText;
1142
+ await writeFile(outputFile, compiled, "utf8");
1143
+ const imported = await import(`${pathToFileURL(outputFile).href}?t=${Date.now()}`);
1144
+ const config = (imported.default ?? {});
1145
+ await applyConfiguredModules(config, root, outDir);
1146
+ delete config.modules;
1147
+ return config;
1148
+ }
1149
+ return {};
1150
+ }
1151
+ function normalizeConfigHelpers(source) {
1152
+ return source
1153
+ .replace(/\bdefineResuxConfig\s*\(/g, "(")
1154
+ .replace(/\bdefineResuxModule\s*\(/g, "(");
1155
+ }
1156
+ async function applyConfiguredModules(config, root, outDir) {
1157
+ const modules = Array.isArray(config.modules) ? config.modules : [];
1158
+ const context = createModuleContext(config, root, outDir);
1159
+ for (const moduleEntry of modules) {
1160
+ const { module, options } = await resolveModuleEntry(moduleEntry, root, outDir);
1161
+ const setup = getModuleSetup(module);
1162
+ await setup(createModuleOptions(module, options), context);
1163
+ }
1164
+ }
1165
+ function createModuleContext(config, root, outDir) {
1166
+ return {
1167
+ rootDir: root,
1168
+ buildDir: outDir,
1169
+ options: config,
1170
+ addCss(href) {
1171
+ config.css = [...(Array.isArray(config.css) ? config.css : []), href];
1172
+ },
1173
+ addHead(head) {
1174
+ const app = config.app && typeof config.app === "object" ? config.app : {};
1175
+ const currentHead = app.head && typeof app.head === "object" ? app.head : {};
1176
+ app.head = mergeHeadConfig(currentHead, head);
1177
+ config.app = app;
1178
+ },
1179
+ addRouteRule(routePath, rule) {
1180
+ if (!routePath.startsWith("/")) {
1181
+ throw new Error(`Route rules need an absolute path. Received "${routePath}".`);
1182
+ }
1183
+ config.routeRules = {
1184
+ ...(config.routeRules ?? {}),
1185
+ [routePath]: {
1186
+ ...(config.routeRules?.[routePath] ?? {}),
1187
+ ...rule,
1188
+ headers: {
1189
+ ...(config.routeRules?.[routePath]?.headers ?? {}),
1190
+ ...(rule.headers ?? {})
1191
+ }
1192
+ }
1193
+ };
1194
+ },
1195
+ extendRuntimeConfig(runtimeConfig) {
1196
+ config.runtimeConfig = deepMerge(config.runtimeConfig ?? {}, runtimeConfig);
1197
+ }
1198
+ };
1199
+ }
1200
+ function mergeHeadConfig(current, next) {
1201
+ return {
1202
+ ...current,
1203
+ ...next,
1204
+ meta: [
1205
+ ...(Array.isArray(current.meta) ? current.meta : []),
1206
+ ...(Array.isArray(next.meta) ? next.meta : [])
1207
+ ],
1208
+ link: [
1209
+ ...(Array.isArray(current.link) ? current.link : []),
1210
+ ...(Array.isArray(next.link) ? next.link : [])
1211
+ ]
1212
+ };
1213
+ }
1214
+ function deepMerge(base, next) {
1215
+ const output = { ...base };
1216
+ for (const [key, value] of Object.entries(next)) {
1217
+ const current = output[key];
1218
+ output[key] = isPlainObject(current) && isPlainObject(value)
1219
+ ? deepMerge(current, value)
1220
+ : value;
1221
+ }
1222
+ return output;
1223
+ }
1224
+ function isPlainObject(value) {
1225
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
1226
+ }
1227
+ async function resolveModuleEntry(entry, root, outDir) {
1228
+ if (Array.isArray(entry)) {
1229
+ return {
1230
+ module: await loadModule(entry[0], root, outDir),
1231
+ options: entry[1] ?? {}
1232
+ };
1233
+ }
1234
+ return {
1235
+ module: await loadModule(entry, root, outDir),
1236
+ options: {}
1237
+ };
1238
+ }
1239
+ async function loadModule(module, root, outDir) {
1240
+ if (typeof module === "function" || isPlainObject(module)) {
1241
+ return module;
1242
+ }
1243
+ if (typeof module !== "string") {
1244
+ throw new Error("Resux modules must be functions, module objects, module specifiers, or [module, options] tuples.");
1245
+ }
1246
+ const builtin = resolveBuiltinModule(module);
1247
+ if (builtin) {
1248
+ return builtin;
1249
+ }
1250
+ const resolved = resolveModuleSpecifier(module, root);
1251
+ const imported = await import(`${await moduleImportUrl(resolved, outDir)}?t=${Date.now()}`);
1252
+ return imported.default ?? imported;
1253
+ }
1254
+ function getModuleSetup(module) {
1255
+ if (typeof module === "function") {
1256
+ return module;
1257
+ }
1258
+ if (isPlainObject(module) && typeof module.setup === "function") {
1259
+ return module.setup;
1260
+ }
1261
+ throw new Error("Resux modules must export a setup function or defineResuxModule({ setup }).");
1262
+ }
1263
+ function createModuleOptions(module, options) {
1264
+ if (isPlainObject(module) && isPlainObject(module.defaults)) {
1265
+ return {
1266
+ ...module.defaults,
1267
+ ...(isPlainObject(options) ? options : {})
1268
+ };
1269
+ }
1270
+ return options;
1271
+ }
1272
+ function resolveBuiltinModule(specifier) {
1273
+ const normalized = specifier.startsWith("resux:") ? specifier.slice("resux:".length) : specifier;
1274
+ return builtinModules[normalized] ?? null;
1275
+ }
1276
+ const builtinModules = {
1277
+ seo: {
1278
+ defaults: {},
1279
+ setup(options, resux) {
1280
+ const input = isPlainObject(options) ? options : {};
1281
+ const meta = [];
1282
+ const title = firstString(input.title);
1283
+ const description = firstString(input.description);
1284
+ const image = firstString(input.image);
1285
+ const themeColor = firstString(input.themeColor);
1286
+ const twitterCard = firstString(input.twitterCard) ?? "summary_large_image";
1287
+ if (description) {
1288
+ meta.push({ name: "description", content: description });
1289
+ meta.push({ property: "og:description", content: description });
1290
+ meta.push({ name: "twitter:description", content: description });
1291
+ }
1292
+ if (title) {
1293
+ meta.push({ property: "og:title", content: title });
1294
+ meta.push({ name: "twitter:title", content: title });
1295
+ }
1296
+ if (image) {
1297
+ meta.push({ property: "og:image", content: image });
1298
+ meta.push({ name: "twitter:image", content: image });
1299
+ }
1300
+ if (themeColor) {
1301
+ meta.push({ name: "theme-color", content: themeColor });
1302
+ }
1303
+ if (twitterCard) {
1304
+ meta.push({ name: "twitter:card", content: twitterCard });
1305
+ }
1306
+ resux.addHead({
1307
+ ...(title ? { title } : {}),
1308
+ ...(meta.length ? { meta } : {}),
1309
+ ...(Array.isArray(input.link) ? { link: input.link.filter(isPlainObject) } : {})
1310
+ });
1311
+ }
1312
+ },
1313
+ security: {
1314
+ defaults: {
1315
+ route: "/**",
1316
+ contentSecurityPolicy: false
1317
+ },
1318
+ setup(options, resux) {
1319
+ const input = isPlainObject(options) ? options : {};
1320
+ const routePath = firstString(input.route) ?? "/**";
1321
+ const headers = {
1322
+ "x-content-type-options": "nosniff",
1323
+ "referrer-policy": "strict-origin-when-cross-origin",
1324
+ "x-frame-options": "SAMEORIGIN",
1325
+ "cross-origin-opener-policy": "same-origin",
1326
+ "permissions-policy": "camera=(), microphone=(), geolocation=()",
1327
+ ...(isPlainObject(input.headers) ? normalizeStringRecord(input.headers) : {})
1328
+ };
1329
+ const csp = firstString(input.contentSecurityPolicy);
1330
+ if (csp) {
1331
+ headers["content-security-policy"] = csp;
1332
+ }
1333
+ resux.addRouteRule(routePath, { headers });
1334
+ resux.extendRuntimeConfig({ public: { securityHeaders: true } });
1335
+ }
1336
+ },
1337
+ performance: {
1338
+ defaults: {
1339
+ assetMaxAge: 31536000,
1340
+ routePayloadNoStore: true
1341
+ },
1342
+ setup(options, resux) {
1343
+ const input = isPlainObject(options) ? options : {};
1344
+ const maxAge = Number.isFinite(input.assetMaxAge) ? Math.max(0, Math.floor(input.assetMaxAge)) : 31536000;
1345
+ const assetCache = { maxAge };
1346
+ resux.addRouteRule("/__resux/runtime-client.mjs", { cache: assetCache });
1347
+ resux.addRouteRule("/__resux/handlers/**", { cache: assetCache });
1348
+ resux.addRouteRule("/__resux/vue-islands/**", { cache: assetCache });
1349
+ if (input.routePayloadNoStore !== false) {
1350
+ resux.addRouteRule("/__resux/route", { cache: false });
1351
+ }
1352
+ resux.extendRuntimeConfig({ public: { performanceModule: { assetMaxAge: maxAge } } });
1353
+ }
1354
+ }
1355
+ };
1356
+ function firstString(value) {
1357
+ return typeof value === "string" && value.length > 0 ? value : null;
1358
+ }
1359
+ function resolveModuleSpecifier(specifier, root) {
1360
+ if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("file:")) {
1361
+ const resolved = specifier.startsWith("file:")
1362
+ ? new URL(specifier)
1363
+ : path.resolve(root, specifier);
1364
+ const file = resolved instanceof URL ? fileURLToPath(resolved) : resolved;
1365
+ return resolveLocalModuleFile(file);
1366
+ }
1367
+ return require.resolve(specifier, { paths: [root] });
1368
+ }
1369
+ function resolveLocalModuleFile(file) {
1370
+ const candidates = [
1371
+ file,
1372
+ `${file}.ts`,
1373
+ `${file}.mts`,
1374
+ `${file}.js`,
1375
+ `${file}.mjs`,
1376
+ path.join(file, "index.ts"),
1377
+ path.join(file, "index.mts"),
1378
+ path.join(file, "index.js"),
1379
+ path.join(file, "index.mjs")
1380
+ ];
1381
+ const found = candidates.find((candidate) => ts.sys.fileExists(candidate));
1382
+ if (!found) {
1383
+ throw new Error(`Cannot resolve Resux module "${file}".`);
1384
+ }
1385
+ return found;
1386
+ }
1387
+ async function moduleImportUrl(file, outDir) {
1388
+ if (/\.[cm]?ts$/.test(file)) {
1389
+ const outputFile = path.join(outDir, "server", "config-modules", `${safeModuleFileName(file)}.mjs`);
1390
+ await writeFile(outputFile, transpileConfigSupportModule(file), "utf8");
1391
+ return pathToFileURL(outputFile).href;
1392
+ }
1393
+ return pathToFileURL(file).href;
1394
+ }
1395
+ function transpileConfigSupportModule(file) {
1396
+ const source = normalizeConfigHelpers(ts.sys.readFile(file) ?? "");
1397
+ return ts.transpileModule(source, {
1398
+ compilerOptions: {
1399
+ target: ts.ScriptTarget.ES2022,
1400
+ module: ts.ModuleKind.ES2022,
1401
+ importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Remove
1402
+ }
1403
+ }).outputText;
1404
+ }
1405
+ function safeModuleFileName(file) {
1406
+ return normalizePath(path.resolve(file)).replace(/[^A-Za-z0-9_-]+/g, "_");
1407
+ }
1408
+ function nextBindingId(state) {
1409
+ return `b${state.bindingIndex++}`;
1410
+ }
1411
+ function nextInlineHandlerName(state) {
1412
+ return `__rx_inline_${state.inlineHandlerIndex++}`;
1413
+ }
1414
+ function routeScore(routePath) {
1415
+ return routePath
1416
+ .split("/")
1417
+ .filter(Boolean)
1418
+ .reduce((score, part) => score + (part.startsWith(":") ? 1 : 3), 0);
1419
+ }
1420
+ async function discoverVueFiles(dir) {
1421
+ try {
1422
+ const entries = await readdir(dir, { withFileTypes: true });
1423
+ const files = [];
1424
+ for (const entry of entries) {
1425
+ const fullPath = path.join(dir, entry.name);
1426
+ if (entry.isDirectory()) {
1427
+ files.push(...await discoverVueFiles(fullPath));
1428
+ }
1429
+ else if (entry.isFile() && entry.name.endsWith(".vue")) {
1430
+ files.push(fullPath);
1431
+ }
1432
+ }
1433
+ return files.sort();
1434
+ }
1435
+ catch {
1436
+ return [];
1437
+ }
1438
+ }
1439
+ async function discoverAppVueFiles(root, dirName) {
1440
+ return unique([
1441
+ ...await discoverVueFiles(path.join(root, dirName)),
1442
+ ...await discoverVueFiles(path.join(root, "app", dirName))
1443
+ ]);
1444
+ }
1445
+ async function discoverTopLevelTsFiles(root, dirName) {
1446
+ const dirs = [path.join(root, dirName), path.join(root, "app", dirName)];
1447
+ const files = [];
1448
+ for (const dir of dirs) {
1449
+ try {
1450
+ const entries = await readdir(dir, { withFileTypes: true });
1451
+ for (const entry of entries) {
1452
+ const fullPath = path.join(dir, entry.name);
1453
+ if (entry.isFile() && /\.[cm]?[tj]s$/.test(entry.name)) {
1454
+ files.push(fullPath);
1455
+ }
1456
+ else if (entry.isDirectory()) {
1457
+ const indexFile = await findFirstExisting([
1458
+ path.join(fullPath, "index.ts"),
1459
+ path.join(fullPath, "index.js"),
1460
+ path.join(fullPath, "index.mjs")
1461
+ ]);
1462
+ if (indexFile) {
1463
+ files.push(indexFile);
1464
+ }
1465
+ }
1466
+ }
1467
+ }
1468
+ catch {
1469
+ continue;
1470
+ }
1471
+ }
1472
+ return unique(files).sort();
1473
+ }
1474
+ async function discoverServerFiles(dir, routePrefix) {
1475
+ try {
1476
+ const entries = await readdir(dir, { withFileTypes: true });
1477
+ const files = [];
1478
+ for (const entry of entries) {
1479
+ const fullPath = path.join(dir, entry.name);
1480
+ if (entry.isDirectory()) {
1481
+ files.push(...await discoverServerFiles(fullPath, `${routePrefix}/${entry.name}`));
1482
+ }
1483
+ else if (entry.isFile() && /\.[cm]?[tj]s$/.test(entry.name)) {
1484
+ const name = entry.name.replace(/\.[cm]?[tj]s$/, "");
1485
+ const segment = name === "index" ? "" : `/${name}`;
1486
+ files.push({
1487
+ file: fullPath,
1488
+ path: normalizeRoutePath(`${routePrefix}${segment}`)
1489
+ });
1490
+ }
1491
+ }
1492
+ return files.sort((a, b) => a.path.localeCompare(b.path));
1493
+ }
1494
+ catch {
1495
+ return [];
1496
+ }
1497
+ }
1498
+ async function discoverVueIslands(root) {
1499
+ const islandRoot = path.join(root, "islands", "vue");
1500
+ const files = await discoverVueFiles(islandRoot);
1501
+ return files.map((file) => {
1502
+ const relative = path.relative(islandRoot, file).replace(/\.vue$/, "");
1503
+ return {
1504
+ name: pascalCase(relative),
1505
+ file
1506
+ };
1507
+ });
1508
+ }
1509
+ async function findFirstExisting(files) {
1510
+ for (const file of files) {
1511
+ const found = await optionalFile(file);
1512
+ if (found) {
1513
+ return found;
1514
+ }
1515
+ }
1516
+ return null;
1517
+ }
1518
+ function unique(items) {
1519
+ return [...new Set(items)];
1520
+ }
1521
+ async function optionalFile(file) {
1522
+ try {
1523
+ await readFile(file, "utf8");
1524
+ return file;
1525
+ }
1526
+ catch {
1527
+ return null;
1528
+ }
1529
+ }
1530
+ function inferComponentName(root, file) {
1531
+ const relative = normalizePath(path.relative(root, file));
1532
+ if (relative === "app.vue") {
1533
+ return "App";
1534
+ }
1535
+ return pascalCase(path.basename(file, ".vue"));
1536
+ }
1537
+ function pascalCase(value) {
1538
+ return value
1539
+ .replace(/\[[^\]]+\]/g, (match) => match.slice(1, -1))
1540
+ .split(/[^A-Za-z0-9]+/)
1541
+ .filter(Boolean)
1542
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
1543
+ .join("");
1544
+ }
1545
+ function kebabCase(value) {
1546
+ return value
1547
+ .replace(/\[[^\]]+\]/g, (match) => match.slice(1, -1))
1548
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
1549
+ .replace(/\.global$/, "")
1550
+ .split(/[^A-Za-z0-9]+/)
1551
+ .filter(Boolean)
1552
+ .join("-")
1553
+ .toLowerCase();
1554
+ }
1555
+ function normalizePath(value) {
1556
+ return value.replaceAll("\\", "/");
1557
+ }
1558
+ function normalizeRoutePath(value) {
1559
+ const normalized = value
1560
+ .replaceAll("\\", "/")
1561
+ .replace(/\.[cm]?[tj]s$/, "")
1562
+ .replace(/\[([A-Za-z0-9_]+)\]/g, ":$1")
1563
+ .replace(/\/index$/, "");
1564
+ return (`/${normalized}`.replace(/\/+/g, "/").replace(/\/$/, "")) || "/";
1565
+ }
1566
+ function collectRouteParams(routePath) {
1567
+ return routePath
1568
+ .split("/")
1569
+ .filter((part) => part.startsWith(":"))
1570
+ .map((part) => part.slice(1));
1571
+ }
1572
+ function locationFromVueNode(file, node) {
1573
+ return {
1574
+ file,
1575
+ line: node.loc?.start?.line ?? 1,
1576
+ column: node.loc?.start?.column ?? 1
1577
+ };
1578
+ }
1579
+ function locationFromTsNode(file, sourceFile, node) {
1580
+ const nodeSourceFile = node.getSourceFile() ?? sourceFile;
1581
+ const position = nodeSourceFile.getLineAndCharacterOfPosition(node.getStart(nodeSourceFile));
1582
+ return {
1583
+ file,
1584
+ line: position.line + 1,
1585
+ column: position.character + 1
1586
+ };
1587
+ }
1588
+ function locationFromOffset(file, source, offset) {
1589
+ const lines = source.slice(0, offset).split(/\r?\n/);
1590
+ return {
1591
+ file,
1592
+ line: lines.length,
1593
+ column: lines[lines.length - 1].length + 1
1594
+ };
1595
+ }
1596
+ export function fileUrl(file) {
1597
+ return pathToFileURL(file).href;
1598
+ }
1599
+ //# sourceMappingURL=index.js.map