@vite-hub/source 0.0.4 → 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.
Files changed (48) hide show
  1. package/README.md +219 -82
  2. package/dist/{auth-Ddw55OUG.js → auth-B-tX_rp0.js} +255 -90
  3. package/dist/{client-CDfTmtQu.js → client-BwstxtdY.js} +584 -207
  4. package/dist/client.d.ts +27 -10
  5. package/dist/client.js +71 -13
  6. package/dist/collection-B_4w_J8h.d.ts +257 -0
  7. package/dist/{collection-B8pXGM2d.js → collection-cursor-WzV1Jd6v.js} +37 -54
  8. package/dist/collection-route-BplWPxHR.js +10 -0
  9. package/dist/drizzle.d.ts +41 -0
  10. package/dist/drizzle.js +89 -0
  11. package/dist/error-diagnostics-X0kuFjBT.js +51 -0
  12. package/dist/file-BX0FSvgE.js +60 -0
  13. package/dist/{file-EQ3AjVM6.d.ts → file-DadN9dbN.d.ts} +2 -3
  14. package/dist/file.d.ts +1 -1
  15. package/dist/file.js +1 -1
  16. package/dist/files.d.ts +15 -0
  17. package/dist/files.js +38 -0
  18. package/dist/github.d.ts +8 -5
  19. package/dist/github.js +725 -426
  20. package/dist/glob-BmFqTvJY.js +993 -0
  21. package/dist/glob.d.ts +12 -4
  22. package/dist/glob.js +1 -894
  23. package/dist/index.d.ts +118 -27
  24. package/dist/index.js +623 -14
  25. package/dist/markdown.d.ts +4 -6
  26. package/dist/markdown.js +2 -2
  27. package/dist/mcp.d.ts +3 -4
  28. package/dist/mcp.js +302 -5920
  29. package/dist/{file-BSWQg9Qv.js → mrmime-40h5OOIp.js} +1 -56
  30. package/dist/{path-CUhvUREm.js → path-BS8rYm0n.js} +60 -40
  31. package/dist/{path-BzmU4Eni.js → path-DOBpV8ol.js} +3 -7
  32. package/dist/server.d.ts +256 -6
  33. package/dist/server.js +90 -12
  34. package/dist/{sse-CE9Q2JqM.js → sse-D9gqqNPj.js} +50 -9
  35. package/dist/{streamableHttp-BszaXLmg.js → streamableHttp-BL-E7pl5.js} +40 -22
  36. package/dist/types-BigOktIj.d.ts +93 -0
  37. package/dist/{types-AIBmt_m6.js → types-CoWcW8oz.js} +2502 -1187
  38. package/dist/vite.d.ts +134 -13
  39. package/dist/vite.js +1734 -79
  40. package/package.json +55 -36
  41. package/dist/collection-CF2ON__k.d.ts +0 -92
  42. package/dist/collection-route-Dw7QLFyx.js +0 -6
  43. package/dist/content/client.d.ts +0 -3
  44. package/dist/content/client.js +0 -2
  45. package/dist/content.d.ts +0 -44
  46. package/dist/content.js +0 -157
  47. package/dist/registry-C8skfCSV.js +0 -120
  48. package/dist/types-Bu3WvNX9.d.ts +0 -71
package/dist/vite.js CHANGED
@@ -1,21 +1,35 @@
1
- import { t as encodeCollectionRouteSegment } from "./collection-route-Dw7QLFyx.js";
1
+ import { t as collectionRoutePath } from "./collection-route-BplWPxHR.js";
2
+ import { t as sourceErrorDiagnostics } from "./error-diagnostics-X0kuFjBT.js";
3
+ import { i as resolveGlobInput, r as globFilePath, t as collectGlobFiles } from "./glob-BmFqTvJY.js";
2
4
  import { tmpdir } from "node:os";
3
5
  import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
4
6
  import { basename, dirname, extname, isAbsolute, join, parse, relative, resolve } from "node:path";
5
7
  import { pathToFileURL } from "node:url";
6
8
  import { statSync } from "node:fs";
7
9
  import { findExportNames } from "mlly";
10
+ import { parseSync } from "vite";
8
11
  //#region ../internal/src/build/vite.ts
9
12
  const projectRootDirectoryMarkers = [
10
13
  ["server", "agents"],
11
14
  ["server", "channels"],
15
+ ["server", "connections"],
12
16
  ["server", "browsers"],
13
17
  ["server", "emails"],
14
18
  ["server", "schedules"],
15
19
  ["server", "workspaces"]
16
20
  ];
17
- const projectRootFileMarkers = [["package.json"]];
21
+ const projectRootFileMarkers = [
22
+ ["package.json"],
23
+ ["nuxt.config.ts"],
24
+ ["nuxt.config.mts"],
25
+ ["nuxt.config.js"],
26
+ ["nuxt.config.mjs"]
27
+ ];
18
28
  const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
29
+ /**
30
+ * Server directories that ViteHub scans for Definitions. The first entry is the application.
31
+ * Later entries are Nuxt layers in Nuxt priority order.
32
+ */
19
33
  const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
20
34
  function resolveViteHubProjectRoot(root, options = {}) {
21
35
  const resolvedRoot = resolve(root);
@@ -24,7 +38,12 @@ function resolveViteHubProjectRoot(root, options = {}) {
24
38
  if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
25
39
  if (basename(resolvedRoot) === "app") {
26
40
  const parent = dirname(resolvedRoot);
27
- if (parent !== sharedTemporaryRoot && hasProjectRootDirectoryMarker(parent)) return parent;
41
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
42
+ "nuxt.config.ts",
43
+ "nuxt.config.mts",
44
+ "nuxt.config.js",
45
+ "nuxt.config.mjs"
46
+ ]))) return parent;
28
47
  }
29
48
  let current = resolvedRoot;
30
49
  while (true) {
@@ -45,20 +64,804 @@ function hasProjectRootDirectoryMarker(root) {
45
64
  }
46
65
  function hasProjectRootMarker(root) {
47
66
  if (hasProjectRootDirectoryMarker(root)) return true;
48
- for (const marker of projectRootFileMarkers) try {
49
- if (statSync(resolve(root, ...marker)).isFile()) return true;
50
- } catch (error) {
51
- if (error.code !== "ENOENT") throw error;
67
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
68
+ }
69
+ function hasProjectRootFileMarker(root, markers) {
70
+ for (const marker of markers) {
71
+ const path = Array.isArray(marker) ? marker : [marker];
72
+ try {
73
+ if (statSync(resolve(root, ...path)).isFile()) return true;
74
+ } catch (error) {
75
+ if (error.code !== "ENOENT") throw error;
76
+ }
52
77
  }
53
78
  return false;
54
79
  }
55
80
  //#endregion
81
+ //#region ../internal/src/nitro-kit.ts
82
+ function cloneArray(value) {
83
+ return Array.isArray(value) ? [...value] : [];
84
+ }
85
+ function isRecord(value) {
86
+ return Object(value) === value && !Array.isArray(value);
87
+ }
88
+ function sameHandler(left, right) {
89
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
90
+ }
91
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
92
+ function createNitroServerKit(value = {}) {
93
+ const config = isRecord(value) ? { ...value } : {};
94
+ const handlers = cloneArray(config.handlers);
95
+ const plugins = cloneArray(config.plugins);
96
+ config.handlers = handlers;
97
+ config.plugins = plugins;
98
+ return {
99
+ config,
100
+ addHandler(handler, position = "end") {
101
+ if (handlers.some((candidate) => isRecord(candidate) && sameHandler(candidate, handler))) return;
102
+ if (position === "start") handlers.unshift({ ...handler });
103
+ else handlers.push({ ...handler });
104
+ },
105
+ addPlugin(plugin, position = "end") {
106
+ if (plugins.includes(plugin)) return;
107
+ if (position === "start") plugins.unshift(plugin);
108
+ else plugins.push(plugin);
109
+ }
110
+ };
111
+ }
112
+ //#endregion
113
+ //#region ../internal/src/build/scan-module.ts
114
+ /**
115
+ * Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
116
+ * the oxc parser that Vite ships through Rolldown, and never runs it. Values that are not static literals read as
117
+ * `dynamic`, so callers can report their own diagnostics.
118
+ */
119
+ /** The value of an expression that the scanner cannot read without running the module. */
120
+ const dynamic$1 = Symbol("dynamic");
121
+ function languageOf(file) {
122
+ if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
123
+ if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
124
+ if (/\.(?:c|m)?js$/i.test(file)) return "js";
125
+ return "ts";
126
+ }
127
+ /** Parses a module once. `file` selects the grammar from its extension and defaults to TypeScript. */
128
+ function scanModule(source, file = "module.ts") {
129
+ const result = parseSync(file, source, {
130
+ lang: languageOf(file),
131
+ preserveParens: false,
132
+ sourceType: "module"
133
+ });
134
+ return {
135
+ comments: result.comments,
136
+ errors: result.errors,
137
+ file,
138
+ program: result.program,
139
+ source
140
+ };
141
+ }
142
+ function isNode$1(value) {
143
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
144
+ }
145
+ /** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
146
+ function walk$1(node, visit, parent) {
147
+ if (visit(node, parent) === false) return;
148
+ const fields = node;
149
+ for (const key in fields) {
150
+ const child = fields[key];
151
+ if (typeof child !== "object" || child === null || key === "parent") continue;
152
+ if (Array.isArray(child)) {
153
+ for (const item of child) if (isNode$1(item)) walk$1(item, visit, node);
154
+ } else if (isNode$1(child)) walk$1(child, visit, node);
155
+ }
156
+ }
157
+ /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
158
+ function unwrapExpression(node) {
159
+ while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
160
+ return node;
161
+ }
162
+ /** A call argument without assertions, or undefined for a spread or missing argument. */
163
+ function argumentExpression(argument) {
164
+ return argument === void 0 || argument.type === "SpreadElement" ? void 0 : unwrapExpression(argument);
165
+ }
166
+ /** Calls whose callee is a plain identifier in `names`, such as `defineCollection(...)`, in source order. */
167
+ function findCalls(module, names) {
168
+ const wanted = new Set(names);
169
+ const calls = [];
170
+ walk$1(module.program, (node) => {
171
+ if (node.type === "CallExpression" && node.callee.type === "Identifier" && wanted.has(node.callee.name)) calls.push(node);
172
+ });
173
+ return calls.sort((left, right) => left.start - right.start);
174
+ }
175
+ function staticKey(property) {
176
+ const key = property.key;
177
+ if (key.type === "Identifier" && !property.computed) return key.name;
178
+ if (key.type === "PrivateIdentifier") return;
179
+ const value = staticValue(key);
180
+ return typeof value === "string" || typeof value === "number" || typeof value === "bigint" ? String(value) : void 0;
181
+ }
182
+ /** The members of an object literal in source order. */
183
+ function objectProperties(object) {
184
+ return object.properties.map((node) => node.type === "SpreadElement" ? {
185
+ computed: false,
186
+ key: void 0,
187
+ node,
188
+ value: void 0
189
+ } : {
190
+ computed: node.computed,
191
+ key: staticKey(node),
192
+ node,
193
+ value: unwrapExpression(node.value)
194
+ });
195
+ }
196
+ /** The last member named `name`, which is the one that the object keeps at runtime. */
197
+ function findProperty(object, name) {
198
+ return objectProperties(object).findLast((property) => property.key === name);
199
+ }
200
+ /** The value of a template literal without substitutions. */
201
+ function staticTemplate(node) {
202
+ if (node.expressions.length) return dynamic$1;
203
+ return node.quasis[0]?.value.cooked ?? dynamic$1;
204
+ }
205
+ const escapePattern = /\\(u\{[^}]*\}?|u[\s\S]{0,4}|x[\s\S]{0,2}|0\d|[\s\S])/g;
206
+ /**
207
+ * True when a string literal has an escape that strict mode code rejects. The parser recovers from some bad escapes
208
+ * and accepts legacy octal escapes, so the scanner checks them again.
209
+ */
210
+ function hasInvalidEscape(raw) {
211
+ for (const [, escape = ""] of raw.matchAll(escapePattern)) if (escape.startsWith("u{")) {
212
+ const code = escape.slice(2, -1);
213
+ if (!escape.endsWith("}") || !/^[\da-fA-F]+$/.test(code) || Number.parseInt(code, 16) > 1114111) return true;
214
+ } else if (escape.startsWith("u")) {
215
+ if (!/^u[\da-fA-F]{4}$/.test(escape)) return true;
216
+ } else if (escape.startsWith("x")) {
217
+ if (!/^x[\da-fA-F]{2}$/.test(escape)) return true;
218
+ } else if (/^(?:[1-9]|0\d)$/.test(escape)) return true;
219
+ return false;
220
+ }
221
+ /**
222
+ * Reads a literal value: strings, numbers, booleans, `null`, `undefined`, template literals without substitutions,
223
+ * and arrays and objects of these. Any other expression gives `dynamic`.
224
+ */
225
+ function staticValue(node) {
226
+ node = unwrapExpression(node);
227
+ switch (node.type) {
228
+ case "Literal":
229
+ if ("regex" in node) return dynamic$1;
230
+ return typeof node.value === "string" && hasInvalidEscape(node.raw ?? "") ? dynamic$1 : node.value;
231
+ case "TemplateLiteral": return staticTemplate(node);
232
+ case "Identifier": return node.name === "undefined" ? void 0 : dynamic$1;
233
+ case "UnaryExpression": {
234
+ if (node.operator === "void") return staticValue(node.argument) === dynamic$1 ? dynamic$1 : void 0;
235
+ const value = staticValue(node.argument);
236
+ if (node.operator === "-" && (typeof value === "number" || typeof value === "bigint")) return -value;
237
+ return dynamic$1;
238
+ }
239
+ case "ArrayExpression": {
240
+ const values = [];
241
+ for (const element of node.elements) {
242
+ if (element === null || element.type === "SpreadElement") return dynamic$1;
243
+ const value = staticValue(element);
244
+ if (value === dynamic$1) return dynamic$1;
245
+ values.push(value);
246
+ }
247
+ return values;
248
+ }
249
+ case "ObjectExpression": {
250
+ const values = {};
251
+ for (const property of objectProperties(node)) {
252
+ if (property.key === void 0 || property.node.type !== "Property" || property.node.kind !== "init" || property.node.method || property.value === void 0) return dynamic$1;
253
+ const value = staticValue(property.value);
254
+ if (value === dynamic$1) return dynamic$1;
255
+ Object.defineProperty(values, property.key, {
256
+ configurable: true,
257
+ enumerable: true,
258
+ value,
259
+ writable: true
260
+ });
261
+ }
262
+ return values;
263
+ }
264
+ default: return dynamic$1;
265
+ }
266
+ }
267
+ /** The static string value of an expression, or undefined when it is not a string literal. */
268
+ function staticString(node) {
269
+ if (node === void 0) return;
270
+ const value = staticValue(node);
271
+ return typeof value === "string" ? value : void 0;
272
+ }
273
+ //#endregion
274
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
275
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
276
+ function normalizeWindowsPath(input = "") {
277
+ if (!input) return input;
278
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
279
+ }
280
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
281
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
282
+ function cwd() {
283
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
284
+ return "/";
285
+ }
286
+ const resolve$1 = function(...arguments_) {
287
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
288
+ let resolvedPath = "";
289
+ let resolvedAbsolute = false;
290
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
291
+ const path = index >= 0 ? arguments_[index] : cwd();
292
+ if (!path || path.length === 0) continue;
293
+ resolvedPath = `${path}/${resolvedPath}`;
294
+ resolvedAbsolute = isAbsolute$1(path);
295
+ }
296
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
297
+ if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
298
+ return resolvedPath.length > 0 ? resolvedPath : ".";
299
+ };
300
+ function normalizeString(path, allowAboveRoot) {
301
+ let res = "";
302
+ let lastSegmentLength = 0;
303
+ let lastSlash = -1;
304
+ let dots = 0;
305
+ let char = null;
306
+ for (let index = 0; index <= path.length; ++index) {
307
+ if (index < path.length) char = path[index];
308
+ else if (char === "/") break;
309
+ else char = "/";
310
+ if (char === "/") {
311
+ if (lastSlash === index - 1 || dots === 1);
312
+ else if (dots === 2) {
313
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
314
+ if (res.length > 2) {
315
+ const lastSlashIndex = res.lastIndexOf("/");
316
+ if (lastSlashIndex === -1) {
317
+ res = "";
318
+ lastSegmentLength = 0;
319
+ } else {
320
+ res = res.slice(0, lastSlashIndex);
321
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
322
+ }
323
+ lastSlash = index;
324
+ dots = 0;
325
+ continue;
326
+ } else if (res.length > 0) {
327
+ res = "";
328
+ lastSegmentLength = 0;
329
+ lastSlash = index;
330
+ dots = 0;
331
+ continue;
332
+ }
333
+ }
334
+ if (allowAboveRoot) {
335
+ res += res.length > 0 ? "/.." : "..";
336
+ lastSegmentLength = 2;
337
+ }
338
+ } else {
339
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
340
+ else res = path.slice(lastSlash + 1, index);
341
+ lastSegmentLength = index - lastSlash - 1;
342
+ }
343
+ lastSlash = index;
344
+ dots = 0;
345
+ } else if (char === "." && dots !== -1) ++dots;
346
+ else dots = -1;
347
+ }
348
+ return res;
349
+ }
350
+ const isAbsolute$1 = function(p) {
351
+ return _IS_ABSOLUTE_RE.test(p);
352
+ };
353
+ const relative$1 = function(from, to) {
354
+ const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
355
+ const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
356
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
357
+ const _fromCopy = [..._from];
358
+ for (const segment of _fromCopy) {
359
+ if (_to[0] !== segment) break;
360
+ _from.shift();
361
+ _to.shift();
362
+ }
363
+ return [..._from.map(() => ".."), ..._to].join("/");
364
+ };
365
+ //#endregion
366
+ //#region ../internal/src/inspect.ts
367
+ function relativeDefinitionFile(projectRoot, file) {
368
+ return relative$1(projectRoot, file).replaceAll("\\", "/");
369
+ }
370
+ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
371
+ new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
372
+ new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
373
+ //#endregion
374
+ //#region src/internal/collection-discovery.ts
375
+ /** The initializers of top-level `const`, `let`, and `var` declarations named `name`. */
376
+ function declarationInitializers(module, name, exportedOnly) {
377
+ return module.program.body.flatMap((statement) => {
378
+ const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : exportedOnly ? void 0 : statement;
379
+ if (declaration?.type !== "VariableDeclaration") return [];
380
+ return declaration.declarations.flatMap((declarator) => declarator.id.type === "Identifier" && declarator.id.name === name && declarator.init ? [declarator.init] : []);
381
+ });
382
+ }
383
+ /** The local binding that `export { local as exportName }` exports, without a module source. */
384
+ function exportedLocalName(module, exportName) {
385
+ for (const statement of module.program.body) {
386
+ if (statement.type !== "ExportNamedDeclaration" || statement.source || statement.exportKind === "type") continue;
387
+ for (const specifier of statement.specifiers) if ((specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value) === exportName && specifier.local.type === "Identifier") return specifier.local.name;
388
+ }
389
+ }
390
+ /**
391
+ * Finds the `defineCollection(...)` call that initializes the named export. An initializer with more than one call,
392
+ * such as a conditional, has no known call: the scanner cannot know which branch runs.
393
+ */
394
+ function findCollectionDefinitionCall(source, exportName, file) {
395
+ const module = scanModule(source, file);
396
+ const calls = findCalls(module, ["defineCollection"]);
397
+ const callIn = (initializer) => {
398
+ const matches = calls.filter((call) => call.start >= initializer.start && call.end <= initializer.end);
399
+ return matches.length === 1 ? matches[0] : void 0;
400
+ };
401
+ for (const initializer of declarationInitializers(module, exportName, true)) {
402
+ const call = callIn(initializer);
403
+ if (call) return call;
404
+ }
405
+ const localName = exportedLocalName(module, exportName);
406
+ if (localName === void 0) return;
407
+ for (const initializer of declarationInitializers(module, localName, false)) {
408
+ const call = callIn(initializer);
409
+ if (call) return call;
410
+ }
411
+ }
412
+ function collectionRouteDisabled(call) {
413
+ if (!call) return false;
414
+ const options = argumentExpression(call.arguments[1] ?? call.arguments[0]);
415
+ const route = options?.type === "ObjectExpression" ? findProperty(options, "route")?.value : void 0;
416
+ return route !== void 0 && staticValue(route) === false;
417
+ }
418
+ async function collectCollectionFiles(directory) {
419
+ let entries;
420
+ try {
421
+ entries = await readdir(directory, { withFileTypes: true });
422
+ } catch (error) {
423
+ if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") return [];
424
+ throw error;
425
+ }
426
+ const files = [];
427
+ for (const entry of entries) {
428
+ const path = join(directory, entry.name);
429
+ if (entry.isDirectory()) files.push(...await collectCollectionFiles(path));
430
+ else if (entry.isFile() && /\.(?:[cm]?[jt]s)$/.test(entry.name) && !/\.d\.[cm]?ts$/.test(entry.name)) files.push(path);
431
+ }
432
+ return files;
433
+ }
434
+ /** Lists Collection modules under `<serverDir>/collections`. It reads the files and does not import them. */
435
+ async function discoverCollections(options) {
436
+ const serverDirs = options.serverDirs === void 0 ? [resolve(options.projectRoot, "server")] : options.serverDirs.map((directory) => resolve(options.projectRoot, directory));
437
+ const collections = (await Promise.all(serverDirs.map(async (serverDir) => {
438
+ const directory = resolve(serverDir, "collections");
439
+ return await Promise.all((await collectCollectionFiles(directory)).sort().map(async (file) => {
440
+ const extension = extname(file);
441
+ const exportName = basename(file, extension);
442
+ if (!/^[A-Z_$][\w$]*$/i.test(exportName)) throw sourceErrorDiagnostics.SOURCE_B0003({ message: `[vitehub] Collection file ${JSON.stringify(relative(options.projectRoot, file))} must use a valid JavaScript identifier as its filename.` });
443
+ const name = relative(directory, file).slice(0, -extension.length).replaceAll("\\", "/");
444
+ const source = await readFile(file, "utf8");
445
+ if (!findExportNames(source).includes(exportName)) throw sourceErrorDiagnostics.SOURCE_B0004({ message: `[vitehub] Collection file ${JSON.stringify(relative(options.projectRoot, file))} must export a Collection named ${JSON.stringify(exportName)} to match its filename.` });
446
+ const definition = findCollectionDefinitionCall(source, exportName, file);
447
+ return {
448
+ definition,
449
+ exportName,
450
+ file,
451
+ name,
452
+ route: !collectionRouteDisabled(definition)
453
+ };
454
+ }));
455
+ }))).flat().sort((left, right) => left.name.localeCompare(right.name));
456
+ const generatedPaths = /* @__PURE__ */ new Map();
457
+ for (const collection of collections) {
458
+ const generatedPath = `${collection.name}.mjs`.toLowerCase();
459
+ const previous = generatedPaths.get(generatedPath);
460
+ if (previous?.name === collection.name) throw sourceErrorDiagnostics.SOURCE_B0005({ message: `[vitehub] Collection name ${JSON.stringify(collection.name)} is defined in more than one server directory.` });
461
+ if (previous) {
462
+ const [firstName, secondName] = [previous.name, collection.name].sort();
463
+ throw sourceErrorDiagnostics.SOURCE_B0006({ message: `[vitehub] Collection names ${JSON.stringify(firstName)} and ${JSON.stringify(secondName)} generate the same route module on case-insensitive filesystems.` });
464
+ }
465
+ generatedPaths.set(generatedPath, collection);
466
+ }
467
+ return collections;
468
+ }
469
+ //#endregion
470
+ //#region src/inspect.ts
471
+ const dynamic = "Dynamic";
472
+ function objectLiteral(value) {
473
+ return value?.type === "ObjectExpression" ? value : void 0;
474
+ }
475
+ function readMember(object, name) {
476
+ const property = object && findProperty(object, name);
477
+ if (property?.node.type !== "Property" || property.value === void 0) return;
478
+ return {
479
+ method: property.node.method || property.node.kind !== "init",
480
+ value: property.value
481
+ };
482
+ }
483
+ /** An identifier path such as `schema` or `tables.articles`, as written without whitespace. */
484
+ function identifierPath(value, optional) {
485
+ if (value.type === "Identifier") return value.name;
486
+ if (value.type !== "MemberExpression" || value.computed || value.property.type !== "Identifier" || value.optional && !optional) return;
487
+ const object = identifierPath(value.object, optional);
488
+ return object === void 0 ? void 0 : `${object}${value.optional ? "?." : "."}${value.property.name}`;
489
+ }
490
+ function callArguments(values) {
491
+ return values.flatMap((value) => argumentExpression(value) ?? []);
492
+ }
493
+ function readCall(value) {
494
+ if (value.type !== "CallExpression" || value.optional) return;
495
+ const callee = identifierPath(value.callee, false);
496
+ return callee === void 0 ? void 0 : {
497
+ arguments: callArguments(value.arguments),
498
+ callee
499
+ };
500
+ }
501
+ function describeString(member) {
502
+ return staticString(member.value) ?? dynamic;
503
+ }
504
+ function describeInteger(member) {
505
+ const value = member.value;
506
+ return value.type === "Literal" && typeof value.value === "number" && /^\d+(?:_\d+)*$/.test(value.raw ?? "") ? String(value.value) : dynamic;
507
+ }
508
+ function describeStringList(member) {
509
+ if (member.value.type !== "ArrayExpression") return dynamic;
510
+ const values = member.value.elements.map((element) => element === null || element.type === "SpreadElement" ? void 0 : staticString(element));
511
+ if (values.some((value) => value === void 0)) return dynamic;
512
+ return values.length ? values.join(", ") : "None";
513
+ }
514
+ /** Shows an identifier path as written and a call as `callee(...)`. Other expressions show as `Inline`. */
515
+ function describeExpression(member) {
516
+ if (member.method) return "Inline";
517
+ const path = identifierPath(member.value, true);
518
+ if (path !== void 0) return path;
519
+ const call = readCall(member.value);
520
+ return call ? `${call.callee}(...)` : "Inline";
521
+ }
522
+ function isFunction(member) {
523
+ return member.method || member.value.type === "ArrowFunctionExpression" || member.value.type === "FunctionExpression";
524
+ }
525
+ function pushSchema(fields, label, member) {
526
+ if (!member) return;
527
+ fields.push({
528
+ label,
529
+ value: describeExpression(member)
530
+ });
531
+ const call = member.method ? void 0 : readCall(member.value);
532
+ const shape = call && /(?:^|\.)(?:object|strictObject|looseObject)$/.test(call.callee) ? objectLiteral(call.arguments[0]) : void 0;
533
+ if (!shape) return;
534
+ const names = objectProperties(shape).map((property) => property.key);
535
+ fields.push({
536
+ label: `${label} fields`,
537
+ value: names.every((name) => name !== void 0) ? names.join(", ") || "None" : dynamic
538
+ });
539
+ }
540
+ function pushLimits(fields, options) {
541
+ const defaultLimit = readMember(options, "defaultLimit");
542
+ const maxLimit = readMember(options, "maxLimit");
543
+ if (defaultLimit) fields.push({
544
+ label: "Default limit",
545
+ value: describeInteger(defaultLimit)
546
+ });
547
+ if (maxLimit) fields.push({
548
+ label: "Max limit",
549
+ value: describeInteger(maxLimit)
550
+ });
551
+ }
552
+ function describeArraySort(member) {
553
+ const sort = objectLiteral(member.value);
554
+ const field = readMember(sort, "field");
555
+ const direction = readMember(sort, "direction");
556
+ const fieldName = field && staticString(field.value);
557
+ const directionName = direction ? staticString(direction.value) : "asc";
558
+ return fieldName && directionName ? `${fieldName} ${directionName}` : dynamic;
559
+ }
560
+ function describeTableSort(member) {
561
+ const orderBy = objectLiteral(member.value);
562
+ const column = readMember(orderBy, "column");
563
+ const direction = readMember(orderBy, "direction");
564
+ const tieBreaker = readMember(orderBy, "tieBreaker");
565
+ const directionName = direction && staticString(direction.value);
566
+ if (!column || !directionName) return dynamic;
567
+ const sort = `${describeExpression(column)} ${directionName}`;
568
+ return tieBreaker ? `${sort}, then ${describeExpression(tieBreaker)}` : sort;
569
+ }
570
+ function arrayFields(options) {
571
+ const fields = [];
572
+ pushSchema(fields, "Schema", readMember(options, "schema"));
573
+ const key = readMember(options, "key");
574
+ const sort = readMember(options, "sort");
575
+ if (key) fields.push({
576
+ label: "Key",
577
+ value: describeString(key)
578
+ });
579
+ if (sort) fields.push({
580
+ label: "Sort",
581
+ value: describeArraySort(sort)
582
+ });
583
+ for (const [property, label] of [
584
+ ["filters", "Filters"],
585
+ ["search", "Search"],
586
+ ["facets", "Facets"]
587
+ ]) {
588
+ const member = readMember(options, property);
589
+ if (member) fields.push({
590
+ label,
591
+ value: describeStringList(member)
592
+ });
593
+ }
594
+ pushLimits(fields, options);
595
+ return fields;
596
+ }
597
+ function tableFields(options) {
598
+ const fields = [];
599
+ const table = readMember(options, "table");
600
+ const orderBy = readMember(options, "orderBy");
601
+ const where = readMember(options, "where");
602
+ if (table) fields.push({
603
+ label: "Table",
604
+ value: describeExpression(table)
605
+ });
606
+ if (orderBy) fields.push({
607
+ label: "Sort",
608
+ value: describeTableSort(orderBy)
609
+ });
610
+ pushSchema(fields, "Query schema", readMember(options, "querySchema"));
611
+ if (where) fields.push({
612
+ label: "Where",
613
+ value: isFunction(where) ? "Callback" : dynamic
614
+ });
615
+ pushLimits(fields, options);
616
+ return fields;
617
+ }
618
+ /** Fields of a custom source object and of the options in `defineCollection(load, options)`. */
619
+ function loaderFields(options) {
620
+ const pagination = readMember(options, "pagination");
621
+ const fields = [{
622
+ label: "Pagination",
623
+ value: !pagination ? "Cursor" : staticString(pagination.value) === "provider" ? "Provider" : dynamic
624
+ }];
625
+ pushSchema(fields, "Cursor schema", readMember(options, "cursorSchema"));
626
+ pushSchema(fields, "Query schema", readMember(options, "querySchema"));
627
+ pushLimits(fields, options);
628
+ return fields;
629
+ }
630
+ function sourceFields(member) {
631
+ if (!member || member.method) return [{
632
+ label: "Source",
633
+ value: "unknown"
634
+ }];
635
+ const custom = objectLiteral(member.value);
636
+ if (custom) return [{
637
+ label: "Source",
638
+ value: "custom"
639
+ }, ...loaderFields(custom)];
640
+ const call = readCall(member.value);
641
+ if (!call) return [{
642
+ label: "Source",
643
+ value: "unknown"
644
+ }];
645
+ const fields = [{
646
+ label: "Source",
647
+ value: call.callee
648
+ }];
649
+ const helper = call.callee.split(".").at(-1);
650
+ const optionsValue = helper === "array" ? call.arguments[1] : helper === "table" ? call.arguments[0] : void 0;
651
+ if (optionsValue === void 0) return fields;
652
+ const options = objectLiteral(optionsValue);
653
+ if (!options) return [...fields, {
654
+ label: "Options",
655
+ value: dynamic
656
+ }];
657
+ return [...fields, ...helper === "array" ? arrayFields(options) : tableFields(options)];
658
+ }
659
+ function definitionFields(collection) {
660
+ const call = collection.definition;
661
+ if (!call) return [{
662
+ label: "Source",
663
+ value: "unknown"
664
+ }];
665
+ const [first, second] = callArguments(call.arguments);
666
+ const loaderForm = second !== void 0;
667
+ const options = objectLiteral(loaderForm ? second : first);
668
+ const fields = loaderForm ? [{
669
+ label: "Source",
670
+ value: "loader"
671
+ }, ...options ? loaderFields(options) : []] : sourceFields(readMember(options, "source"));
672
+ if (!options) return [...fields, {
673
+ label: "Options",
674
+ value: dynamic
675
+ }];
676
+ const authorize = readMember(options, "authorize");
677
+ fields.push({
678
+ label: "Transform",
679
+ value: readMember(options, "transform") ? "Yes" : "No"
680
+ });
681
+ if (authorize) fields.push({
682
+ label: "Authorize",
683
+ value: !authorize.method && staticValue(authorize.value) === true ? "Signed-in session" : isFunction(authorize) ? "Callback" : dynamic
684
+ });
685
+ return fields;
686
+ }
687
+ function summarizeCollection(projectRoot, collection) {
688
+ return {
689
+ fields: [...definitionFields(collection), {
690
+ label: "Route",
691
+ value: collection.route ? `GET ${collectionRoutePath(collection.name)}` : "Disabled"
692
+ }],
693
+ file: relativeDefinitionFile(projectRoot, collection.file),
694
+ name: collection.name,
695
+ source: "server-collections"
696
+ };
697
+ }
698
+ /**
699
+ * Lists Collections in `server/collections` with their source kind and static options. It reads the module text and
700
+ * does not import it, so values that are computed at runtime show as `Dynamic`.
701
+ */
702
+ async function inspectCollectionDefinitions(options) {
703
+ return (await discoverCollections(options)).map((collection) => summarizeCollection(options.projectRoot, collection));
704
+ }
705
+ //#endregion
706
+ //#region src/internal/bundle-glob.ts
707
+ /**
708
+ * Bundling glob(): a ViteHub server build swaps each `glob()` call whose options are literals for a module that holds
709
+ * the files it matches, through files(). Hosts without a file system, such as Cloudflare Workers, then serve the same
710
+ * keys and bytes that glob() reads from disk. `vite dev` keeps glob() as it is.
711
+ */
712
+ /** Prefix of the generated modules' ids. `\0` keeps other plugins from resolving or transforming them. */
713
+ const BUNDLED_GLOB_ID = "\0vitehub-source-glob:";
714
+ /** Matches those ids, for Rolldown's hook filters. */
715
+ const BUNDLED_GLOB_ID_PATTERN = /^\0vitehub-source-glob:/;
716
+ const GLOB_MODULE = /^(?:@vite-hub|vite-hub)\/source\/glob$/;
717
+ const OPTION_KEYS = /* @__PURE__ */ new Set([
718
+ "cwd",
719
+ "dot",
720
+ "followSymlinks",
721
+ "ignore",
722
+ "include",
723
+ "keyCache",
724
+ "prefix"
725
+ ]);
726
+ function isNode(value) {
727
+ return typeof value === "object" && value !== null && typeof value.type === "string";
728
+ }
729
+ function walk(node, visit) {
730
+ visit(node);
731
+ for (const value of Object.values(node)) if (Array.isArray(value)) value.forEach((child) => isNode(child) && walk(child, visit));
732
+ else if (isNode(value)) walk(value, visit);
733
+ }
734
+ /** A literal's value, or undefined for anything that is not one. */
735
+ function literal(node) {
736
+ if (!node) return void 0;
737
+ if (node.type === "Literal") return node.value;
738
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0].value.cooked;
739
+ if (node.type === "ArrayExpression") {
740
+ const items = node.elements.map((element) => element ? literal(element) : void 0);
741
+ return items.every((item) => typeof item === "string") ? items : void 0;
742
+ }
743
+ }
744
+ function globInput(node) {
745
+ const value = literal(node);
746
+ if (typeof value === "string") return value;
747
+ if (node?.type !== "ObjectExpression") return void 0;
748
+ const options = {};
749
+ for (const property of node.properties) {
750
+ if (property.type !== "Property" || property.computed || property.kind !== "init") return void 0;
751
+ const key = property.key;
752
+ const name = key.type === "Identifier" ? key.name : key.value;
753
+ if (typeof name !== "string" || !OPTION_KEYS.has(name)) return void 0;
754
+ const option = literal(property.value);
755
+ if (option === void 0) return void 0;
756
+ options[name] = option;
757
+ }
758
+ return typeof options.include === "string" || Array.isArray(options.include) ? options : void 0;
759
+ }
760
+ /** Every `glob()` call in a module, by the names `glob` was imported under. */
761
+ function findGlobCalls(program) {
762
+ const imported = /* @__PURE__ */ new Map();
763
+ for (const statement of program.body) {
764
+ if (statement.type !== "ImportDeclaration") continue;
765
+ const source = statement.source.value;
766
+ if (typeof source !== "string" || !GLOB_MODULE.test(source)) continue;
767
+ for (const specifier of statement.specifiers) {
768
+ const name = specifier.imported?.name ?? specifier.imported?.value;
769
+ if (specifier.type === "ImportSpecifier" && name === "glob") imported.set(specifier.local.name, source.replace(/\/glob$/, "/files"));
770
+ }
771
+ }
772
+ if (imported.size === 0) return [];
773
+ const calls = [];
774
+ walk(program, (node) => {
775
+ if (node.type !== "CallExpression") return;
776
+ const callee = node.callee;
777
+ const filesModule = callee.type === "Identifier" ? imported.get(callee.name) : void 0;
778
+ if (!filesModule) return;
779
+ const args = node.arguments;
780
+ calls.push({
781
+ start: node.start,
782
+ end: node.end,
783
+ input: args.length === 1 ? globInput(args[0]) : void 0,
784
+ filesModule
785
+ });
786
+ });
787
+ return calls;
788
+ }
789
+ /** The id of the module that holds what one call matches. */
790
+ function bundledGlobId(call) {
791
+ return BUNDLED_GLOB_ID + encodeURIComponent(JSON.stringify({
792
+ filesModule: call.filesModule,
793
+ input: call.input
794
+ }));
795
+ }
796
+ /** The module with each call whose options are literals swapped for its bundled files. */
797
+ function rewriteGlobCalls(code, calls) {
798
+ let output = code;
799
+ const imports = [];
800
+ const bundled = calls.filter((call) => call.input !== void 0);
801
+ bundled.forEach((call, index) => imports.push(`import __vitehubGlob${index} from ${JSON.stringify(bundledGlobId(call))};`));
802
+ for (const [index, call] of [...bundled.entries()].reverse()) output = output.slice(0, call.start) + `__vitehubGlob${index}` + output.slice(call.end);
803
+ return imports.length ? `${imports.join("\n")}\n${output}` : output;
804
+ }
805
+ /** The files a call matches, read as glob() reads them, and the paths to watch. */
806
+ async function collectBundledGlob(input, rootDir) {
807
+ const options = resolveGlobInput(input);
808
+ const { paths, keys } = await collectGlobFiles(rootDir, options);
809
+ const entries = {};
810
+ const watched = [];
811
+ for (const key of keys) {
812
+ const path = await globFilePath(key, paths, options.followSymlinks === true);
813
+ if (!path) continue;
814
+ entries[key] = new Uint8Array(await readFile(path));
815
+ watched.push(path);
816
+ }
817
+ return {
818
+ entries,
819
+ prefix: options.prefix,
820
+ watched
821
+ };
822
+ }
823
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
824
+ /** One file in the generated module: text stays readable, anything else is base64. Both load as bytes, as glob() reads them. */
825
+ function fileExpression(bytes) {
826
+ try {
827
+ const text = utf8.decode(bytes);
828
+ if (!text.includes("\0")) return `text(${JSON.stringify(text)})`;
829
+ } catch {}
830
+ return `bytes(${JSON.stringify(Buffer.from(bytes).toString("base64"))})`;
831
+ }
832
+ /** The generated module: the matched files, served through files(). */
833
+ function renderBundledGlob(filesModule, entries, prefix) {
834
+ const lines = Object.entries(entries).map(([key, bytes]) => ` ${JSON.stringify(key)}: ${fileExpression(bytes)},`);
835
+ return [
836
+ `import { files } from ${JSON.stringify(filesModule)}`,
837
+ `const encoder = new TextEncoder()`,
838
+ `const text = value => encoder.encode(value)`,
839
+ `const bytes = value => Uint8Array.from(atob(value), character => character.charCodeAt(0))`,
840
+ `export default files({`,
841
+ ...lines,
842
+ `}${prefix ? `, { prefix: ${JSON.stringify(prefix)} }` : ""})`,
843
+ ``
844
+ ].join("\n");
845
+ }
846
+ /** Loads a generated module by its id. */
847
+ async function loadBundledGlob(id, rootDir) {
848
+ const { filesModule, input } = JSON.parse(decodeURIComponent(id.slice(21)));
849
+ const { entries, prefix, watched } = await collectBundledGlob(input, rootDir);
850
+ return {
851
+ code: renderBundledGlob(filesModule, entries, prefix),
852
+ watched
853
+ };
854
+ }
855
+ //#endregion
56
856
  //#region src/vite.ts
57
857
  const collectionTypesEntry = ".vitehub/types/source/collections.d.ts";
58
858
  const collectionTypesPackageEntry = ".vitehub/types/source/vitehub-source-registry.d.ts";
59
- const legacyCollectionTypesEntry = ".vitehub/source/collections.d.ts";
60
859
  const collectionRoutesDirectory = ".vitehub/source/routes";
61
860
  const contentRouteEntry = ".vitehub/content/route.mjs";
861
+ const contentPreviewEntry = ".vitehub/content/preview.mjs";
862
+ const contentSitemapEntry = ".vitehub/content/sitemap.mjs";
863
+ const contentRobotsEntry = ".vitehub/content/robots.mjs";
864
+ const authServerModuleId = "#vitehub/auth/server";
62
865
  const initialHostRefreshRetryDelay = 25;
63
866
  const maximumHostRefreshRetryDelay = 1e3;
64
867
  const hostRestartOwnerSettlementTimeout = 3e4;
@@ -74,8 +877,10 @@ async function snapshotGeneratedSourceArtifacts(projectRoot) {
74
877
  const fixedEntries = [
75
878
  collectionTypesEntry,
76
879
  collectionTypesPackageEntry,
77
- legacyCollectionTypesEntry,
78
- contentRouteEntry
880
+ contentRouteEntry,
881
+ contentPreviewEntry,
882
+ contentSitemapEntry,
883
+ contentRobotsEntry
79
884
  ];
80
885
  for (const entry of fixedEntries) {
81
886
  const path = resolve(projectRoot, entry);
@@ -94,15 +899,18 @@ async function snapshotGeneratedSourceArtifacts(projectRoot) {
94
899
  return { files };
95
900
  }
96
901
  async function restoreGeneratedSourceArtifacts(projectRoot, snapshot) {
97
- await rm(resolve(projectRoot, collectionRoutesDirectory), {
902
+ const routesDirectory = resolve(projectRoot, collectionRoutesDirectory);
903
+ await rm(routesDirectory, {
98
904
  force: true,
99
905
  recursive: true
100
906
  });
101
907
  for (const entry of [
102
908
  collectionTypesEntry,
103
909
  collectionTypesPackageEntry,
104
- legacyCollectionTypesEntry,
105
- contentRouteEntry
910
+ contentRouteEntry,
911
+ contentPreviewEntry,
912
+ contentSitemapEntry,
913
+ contentRobotsEntry
106
914
  ]) {
107
915
  const path = resolve(projectRoot, entry);
108
916
  if (!snapshot.files.has(path)) await rm(path, { force: true });
@@ -116,18 +924,22 @@ function methodsOverlap(left, right) {
116
924
  return !left || !right || left.toLowerCase() === right.toLowerCase();
117
925
  }
118
926
  function generatedRouteOwner(handler) {
119
- return handler.route === "/api/content/**" ? "Content" : "Collection";
927
+ return handler.route === "/api/content/**" || handler.route === "/sitemap.xml" || handler.route === "/robots.txt" ? "Content" : "Collection";
120
928
  }
121
929
  function generatedRouteDescription(handler) {
122
930
  return handler.method ? `${handler.method.toUpperCase()} handler` : "handler";
123
931
  }
932
+ function assertGeneratedRoutes(nitro, generatedHandlers) {
933
+ for (const generatedHandler of generatedHandlers) {
934
+ if (generatedHandler.plugin) continue;
935
+ if (nitro.scannedHandlers.some((candidate) => !candidate.middleware && candidate.route === generatedHandler.route && methodsOverlap(candidate.method, generatedHandler.method))) throw sourceErrorDiagnostics.SOURCE_B0001({ message: `[vitehub] Generated ${generatedRouteOwner(generatedHandler)} route ${JSON.stringify(generatedHandler.route)} conflicts with an existing ${generatedRouteDescription(generatedHandler)}. Remove the matching server route.` });
936
+ }
937
+ }
124
938
  function generatedRouteGuard(generatedHandlers) {
125
939
  return {
126
940
  name: "vite-hub/generated-route-guard",
127
941
  setup(nitro) {
128
- nitro.hooks.hook("build:before", () => {
129
- for (const generatedHandler of generatedHandlers) if (nitro.scannedHandlers.some((candidate) => candidate.route === generatedHandler.route && methodsOverlap(candidate.method, generatedHandler.method))) throw new TypeError(`[vitehub] Generated ${generatedRouteOwner(generatedHandler)} route ${JSON.stringify(generatedHandler.route)} conflicts with an existing ${generatedRouteDescription(generatedHandler)}. Remove the matching server route.`);
130
- });
942
+ nitro.hooks.hook("build:before", () => assertGeneratedRoutes(nitro, generatedHandlers));
131
943
  }
132
944
  };
133
945
  }
@@ -135,19 +947,24 @@ function mergeGeneratedSourceNitroConfig(value, generatedHandlers) {
135
947
  const nitro = {};
136
948
  if (Object(value) === value && !Array.isArray(value)) Object.assign(nitro, value);
137
949
  if (generatedHandlers.length === 0) return nitro;
138
- const handlers = Array.isArray(nitro.handlers) ? [...nitro.handlers] : [];
950
+ const kit = createNitroServerKit(nitro);
951
+ const handlers = kit.config.handlers;
139
952
  for (const handler of generatedHandlers) {
953
+ if (handler.plugin) {
954
+ kit.addPlugin(handler.handler);
955
+ continue;
956
+ }
140
957
  if (handlers.some((candidate) => candidate.handler === handler.handler && candidate.route === handler.route && candidate.method?.toLowerCase() === handler.method?.toLowerCase())) continue;
141
- if (handlers.some((candidate) => candidate.route === handler.route && methodsOverlap(candidate.method, handler.method))) throw new TypeError(`[vitehub] Generated ${generatedRouteOwner(handler)} route ${JSON.stringify(handler.route)} conflicts with an existing ${generatedRouteDescription(handler)}. Remove the matching server route.`);
142
- handlers.push(handler);
958
+ if (handlers.some((candidate) => !candidate.middleware && candidate.route === handler.route && methodsOverlap(candidate.method, handler.method))) throw sourceErrorDiagnostics.SOURCE_B0002({ message: `[vitehub] Generated ${generatedRouteOwner(handler)} route ${JSON.stringify(handler.route)} conflicts with an existing ${generatedRouteDescription(handler)}. Remove the matching server route.` });
959
+ kit.addHandler({
960
+ ...handler,
961
+ lazy: true
962
+ });
143
963
  }
144
964
  const modules = Array.isArray(nitro.modules) ? [...nitro.modules] : [];
145
965
  if (!modules.some((module) => Object(module) === module && Reflect.get(Object(module), "name") === "vite-hub/generated-route-guard")) modules.push(generatedRouteGuard(generatedHandlers));
146
- return {
147
- ...nitro,
148
- handlers,
149
- modules
150
- };
966
+ kit.config.modules = modules;
967
+ return kit.config;
151
968
  }
152
969
  function toRuntimeModuleSpecifier(file) {
153
970
  return pathToFileURL(file, { windows: /^[A-Z]:[\\/]/i.test(file) }).href;
@@ -155,36 +972,553 @@ function toRuntimeModuleSpecifier(file) {
155
972
  function toTypeModuleSpecifier(file) {
156
973
  return file.replaceAll("\\", "/");
157
974
  }
158
- async function collectCollectionFiles(directory) {
159
- let entries;
160
- try {
161
- entries = await readdir(directory, { withFileTypes: true });
162
- } catch (error) {
163
- if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") return [];
164
- throw error;
975
+ /** Inspect route metadata without importing Collection modules or evaluating loaders. */
976
+ function collectionRouteEnabled(file, source, exportName) {
977
+ const parsed = parseSync(file, source, { lang: "ts" });
978
+ if (parsed.errors.length) throw new TypeError(`[vitehub] Cannot parse Collection ${file}: ${parsed.errors[0].message}`);
979
+ const moduleScope = { bindings: /* @__PURE__ */ new Map() };
980
+ const scopes = /* @__PURE__ */ new WeakMap();
981
+ const bindPattern = (node, scope, init) => {
982
+ if (!node) return;
983
+ if (node.type === "Identifier" && node.name) scope.bindings.set(node.name, { init });
984
+ else if (node.type === "RestElement") bindPattern(node.argument, scope);
985
+ else if (node.type === "AssignmentPattern") bindPattern(node.left, scope, {
986
+ type: "AssignmentPattern",
987
+ left: init ?? void 0,
988
+ right: node.right
989
+ });
990
+ else if (node.type === "ArrayPattern") for (const element of node.elements ?? []) bindPattern(element, scope);
991
+ else if (node.type === "ObjectPattern") for (const property of node.properties ?? []) {
992
+ const member = {
993
+ type: "MemberExpression",
994
+ object: init ?? void 0,
995
+ property: property.key,
996
+ computed: property.computed
997
+ };
998
+ scopes.set(member, scope);
999
+ bindPattern(property.type === "RestElement" ? property.argument : property.value, scope, property.type === "RestElement" ? void 0 : member);
1000
+ }
1001
+ };
1002
+ const indexScopes = (node, parent, functionScope) => {
1003
+ const isFunction = [
1004
+ "ArrowFunctionExpression",
1005
+ "FunctionExpression",
1006
+ "FunctionDeclaration"
1007
+ ].includes(node.type ?? "");
1008
+ if ((node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") && node.id?.name) parent.bindings.set(node.id.name, { init: node.type === "FunctionDeclaration" ? node : void 0 });
1009
+ const scope = isFunction || [
1010
+ "BlockStatement",
1011
+ "CatchClause",
1012
+ "ForStatement",
1013
+ "ForInStatement",
1014
+ "ForOfStatement",
1015
+ "SwitchStatement"
1016
+ ].includes(node.type ?? "") ? {
1017
+ bindings: /* @__PURE__ */ new Map(),
1018
+ parent
1019
+ } : parent;
1020
+ const nextFunctionScope = isFunction ? scope : functionScope;
1021
+ scopes.set(node, scope);
1022
+ if (isFunction) {
1023
+ for (const param of node.params ?? []) bindPattern(param, scope);
1024
+ if (node.type === "FunctionExpression") bindPattern(node.id, scope);
1025
+ }
1026
+ if (node.type === "CatchClause") bindPattern(node.param, scope);
1027
+ if (node.type === "VariableDeclaration") for (const item of node.declarations ?? []) {
1028
+ const target = node.kind === "var" ? functionScope : scope;
1029
+ bindPattern(item.id, target, item.init);
1030
+ }
1031
+ for (const child of Object.values(node)) if (Array.isArray(child)) {
1032
+ for (const item of child) if (item) indexScopes(item, scope, nextFunctionScope);
1033
+ } else if (child && typeof child === "object") indexScopes(child, scope, nextFunctionScope);
1034
+ };
1035
+ indexScopes(parsed.program, moduleScope, moduleScope);
1036
+ const bindingFor = (node) => {
1037
+ for (let scope = scopes.get(node); scope; scope = scope.parent) if (node.name && scope.bindings.has(node.name)) return scope.bindings.get(node.name);
1038
+ };
1039
+ const indexedWrites = [];
1040
+ const indexWrites = (node, fn, guards = []) => {
1041
+ if ([
1042
+ "ArrowFunctionExpression",
1043
+ "FunctionExpression",
1044
+ "FunctionDeclaration"
1045
+ ].includes(node.type ?? "")) {
1046
+ fn = node;
1047
+ guards = [];
1048
+ }
1049
+ if (node.type === "IfStatement" || node.type === "ConditionalExpression") {
1050
+ if (node.consequent) indexWrites(node.consequent, fn, [...guards, {
1051
+ test: node.test,
1052
+ truthy: true
1053
+ }]);
1054
+ if (node.alternate) indexWrites(node.alternate, fn, [...guards, {
1055
+ test: node.test,
1056
+ truthy: false
1057
+ }]);
1058
+ return;
1059
+ }
1060
+ if (node.type === "LogicalExpression") {
1061
+ if (node.left) indexWrites(node.left, fn, guards);
1062
+ if (node.right) indexWrites(node.right, fn, [...guards, {
1063
+ test: node.operator === "??" ? void 0 : node.left,
1064
+ truthy: node.operator === "&&"
1065
+ }]);
1066
+ return;
1067
+ }
1068
+ if ([
1069
+ "ForStatement",
1070
+ "ForInStatement",
1071
+ "ForOfStatement",
1072
+ "WhileStatement",
1073
+ "DoWhileStatement",
1074
+ "SwitchStatement",
1075
+ "TryStatement"
1076
+ ].includes(node.type ?? "")) guards = [...guards, {
1077
+ test: void 0,
1078
+ truthy: true
1079
+ }];
1080
+ if (node.type === "UnaryExpression" && node.operator === "delete" && node.argument?.type === "MemberExpression") {
1081
+ const target = node.argument.object;
1082
+ const binding = target?.type === "Identifier" ? bindingFor(target) : void 0;
1083
+ if (binding) {
1084
+ const write = {
1085
+ node,
1086
+ fn,
1087
+ guards
1088
+ };
1089
+ (binding.writes ??= []).push(write);
1090
+ indexedWrites.push(write);
1091
+ }
1092
+ }
1093
+ if (node.type === "AssignmentExpression") {
1094
+ const target = node.left?.type === "MemberExpression" ? node.left.object : node.left;
1095
+ const binding = target?.type === "Identifier" ? bindingFor(target) : void 0;
1096
+ if (binding) {
1097
+ const write = {
1098
+ node,
1099
+ fn,
1100
+ guards
1101
+ };
1102
+ (binding.writes ??= []).push(write);
1103
+ indexedWrites.push(write);
1104
+ }
1105
+ }
1106
+ for (const child of Object.values(node)) if (Array.isArray(child)) {
1107
+ for (const item of child) if (item) {
1108
+ indexWrites(item, fn, guards);
1109
+ if (item.type === "ReturnStatement" || item.type === "ThrowStatement") break;
1110
+ }
1111
+ } else if (child && typeof child === "object") indexWrites(child, fn, guards);
1112
+ };
1113
+ indexWrites(parsed.program);
1114
+ let readPosition = Infinity;
1115
+ const activeFunctions = /* @__PURE__ */ new Set();
1116
+ const executedFunctions = /* @__PURE__ */ new Set();
1117
+ const parameterValues = /* @__PURE__ */ new Map();
1118
+ let routeEffectState;
1119
+ const snapshotExecution = () => ({
1120
+ activeFunctions: new Set(activeFunctions),
1121
+ executedFunctions: new Set(executedFunctions),
1122
+ parameterValues: new Map(parameterValues),
1123
+ readPosition,
1124
+ routeEffectState
1125
+ });
1126
+ const restoreExecution = (snapshot) => {
1127
+ activeFunctions.clear();
1128
+ for (const fn of snapshot.activeFunctions) activeFunctions.add(fn);
1129
+ executedFunctions.clear();
1130
+ for (const fn of snapshot.executedFunctions) executedFunctions.add(fn);
1131
+ parameterValues.clear();
1132
+ for (const [binding, value] of snapshot.parameterValues) parameterValues.set(binding, value);
1133
+ readPosition = snapshot.readPosition;
1134
+ routeEffectState = snapshot.routeEffectState;
1135
+ };
1136
+ let exported = moduleScope.bindings.get(exportName);
1137
+ for (const statement of parsed.program.body) {
1138
+ if (statement.type !== "ImportDeclaration") continue;
1139
+ for (const specifier of statement.specifiers ?? []) {
1140
+ const imported = specifier.type === "ImportSpecifier" ? specifier.imported : void 0;
1141
+ const name = imported?.type === "Identifier" ? imported.name : imported?.value;
1142
+ moduleScope.bindings.set(specifier.local.name, { init: { type: name === "defineCollection" ? "CollectionFactory" : specifier.type === "ImportNamespaceSpecifier" ? "CollectionNamespace" : "UnknownImport" } });
1143
+ }
165
1144
  }
166
- const files = [];
167
- for (const entry of entries) {
168
- const path = join(directory, entry.name);
169
- if (entry.isDirectory()) files.push(...await collectCollectionFiles(path));
170
- else if (entry.isFile() && /\.(?:[cm]?[jt]s)$/.test(entry.name) && !/\.d\.[cm]?ts$/.test(entry.name)) files.push(path);
1145
+ for (const statement of parsed.program.body) if (statement.type === "ExportNamedDeclaration") {
1146
+ for (const specifier of statement.specifiers) if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === exportName && specifier.local.type === "Identifier") exported = moduleScope.bindings.get(specifier.local.name);
171
1147
  }
172
- return files;
1148
+ const unwrap = (node, seen = /* @__PURE__ */ new Set()) => {
1149
+ if (node?.type === "AssignmentPattern") {
1150
+ const value = unwrap(node.left, new Set(seen));
1151
+ return !node.left || value?.type === "Literal" && value.value === void 0 ? unwrap(node.right, seen) : value;
1152
+ }
1153
+ if (node?.type === "Identifier" && node.name !== void 0) {
1154
+ const declaration = bindingFor(node);
1155
+ if (!declaration) return node.name === "undefined" ? {
1156
+ type: "Literal",
1157
+ value: void 0
1158
+ } : void 0;
1159
+ let init = parameterValues.has(declaration) ? parameterValues.get(declaration) : declaration.init;
1160
+ for (const write of declaration.writes ?? []) {
1161
+ const state = writeState(write);
1162
+ if (write.node.left?.type === "Identifier" && state !== "skip") init = state === "known" && write.node.operator === "=" ? write.node.right : void 0;
1163
+ }
1164
+ if (!init) return void 0;
1165
+ if (seen.has(declaration)) throw new TypeError(`[vitehub] Circular Collection options in ${file}.`);
1166
+ seen.add(declaration);
1167
+ return unwrap(init, seen);
1168
+ }
1169
+ if (node?.type === "UnaryExpression" && node.operator === "!") {
1170
+ const value = unwrap(node.argument, new Set(seen));
1171
+ return value?.type === "Literal" ? {
1172
+ type: "Literal",
1173
+ value: !Boolean(value.value)
1174
+ } : node;
1175
+ }
1176
+ if (node?.type === "UnaryExpression" && node.operator === "void") return {
1177
+ type: "Literal",
1178
+ value: void 0
1179
+ };
1180
+ if (node && [
1181
+ "TSAsExpression",
1182
+ "TSSatisfiesExpression",
1183
+ "TSNonNullExpression",
1184
+ "ParenthesizedExpression"
1185
+ ].includes(node.type ?? "")) return unwrap(node.expression, seen);
1186
+ if (node?.type === "MemberExpression") {
1187
+ const object = unwrap(node.object, seen);
1188
+ const key = node.computed ? staticString(node.property) : node.property?.name;
1189
+ if (object?.type !== "ObjectExpression" || key === void 0) return void 0;
1190
+ let result = {
1191
+ type: "Literal",
1192
+ value: void 0
1193
+ };
1194
+ for (const property of object.properties ?? []) {
1195
+ if (property.type === "SpreadElement") return void 0;
1196
+ if ((property.computed ? staticString(property.key) : property.key?.name ?? property.key?.value) === key) result = unwrap(property.value, new Set(seen));
1197
+ }
1198
+ return result;
1199
+ }
1200
+ return node ?? void 0;
1201
+ };
1202
+ const writeState = (write) => {
1203
+ if ((write.node.start ?? Infinity) >= readPosition) return "skip";
1204
+ const previousPosition = readPosition;
1205
+ let state = "known";
1206
+ for (const guard of write.guards) {
1207
+ if (!write.fn && !write.replayed) readPosition = guard.test?.start ?? write.node.start ?? readPosition;
1208
+ const test = unwrap(guard.test);
1209
+ if (test?.type !== "Literal") state = "unknown";
1210
+ else if (Boolean(test.value) !== guard.truthy) {
1211
+ readPosition = previousPosition;
1212
+ return "skip";
1213
+ }
1214
+ }
1215
+ if (write.fn && !activeFunctions.has(write.fn)) {
1216
+ if (!executedFunctions.has(write.fn)) {
1217
+ readPosition = previousPosition;
1218
+ return "skip";
1219
+ }
1220
+ const right = unwrap(write.node.right);
1221
+ readPosition = previousPosition;
1222
+ if (right?.type === "Literal" && (right.value === void 0 || right.value === true || right.value === false)) return "known";
1223
+ return "unknown";
1224
+ }
1225
+ readPosition = previousPosition;
1226
+ return state;
1227
+ };
1228
+ const staticString = (node, seen = /* @__PURE__ */ new Set()) => {
1229
+ const value = unwrap(node, seen);
1230
+ if (!value) return void 0;
1231
+ if (value.type === "Literal" && String(value.value) === value.value) return value.value;
1232
+ if (value.type === "TemplateLiteral") {
1233
+ const quasis = value.quasis ?? [];
1234
+ const expressions = value.expressions ?? [];
1235
+ if (quasis.length !== expressions.length + 1) return void 0;
1236
+ let result = "";
1237
+ for (let index = 0; index < quasis.length; index++) {
1238
+ result += quasis[index]?.value?.cooked ?? quasis[index]?.value?.raw ?? "";
1239
+ if (index < expressions.length) {
1240
+ const expression = staticString(expressions[index], new Set(seen));
1241
+ if (expression === void 0) return void 0;
1242
+ result += expression;
1243
+ }
1244
+ }
1245
+ return result;
1246
+ }
1247
+ if (value.type === "BinaryExpression" && value.operator === "+") {
1248
+ const left = staticString(value.left, new Set(seen));
1249
+ const right = staticString(value.right, new Set(seen));
1250
+ return left !== void 0 && right !== void 0 ? left + right : void 0;
1251
+ }
1252
+ };
1253
+ const routeValue = (value) => {
1254
+ if (value?.type === "Literal" && (value.value === true || value.value === false)) return {
1255
+ present: true,
1256
+ value: value.value
1257
+ };
1258
+ if (value?.type === "Literal" && value.value === void 0) return {
1259
+ present: true,
1260
+ value: true
1261
+ };
1262
+ return {
1263
+ present: true,
1264
+ value: value?.type === "Literal" ? true : false
1265
+ };
1266
+ };
1267
+ const staticObjectRoute = (node, seen = /* @__PURE__ */ new Set()) => {
1268
+ if (node?.type === "CallExpression" && node.callee?.type === "MemberExpression" && !node.callee.computed && node.callee.object?.type === "Identifier" && node.callee.object.name === "Object" && node.callee.property?.name === "assign") {
1269
+ let merged = { present: false };
1270
+ for (const argument of node.arguments ?? []) {
1271
+ const current = staticObjectRoute(argument, new Set(seen));
1272
+ if (current?.present) merged = current;
1273
+ else if (current === void 0) merged = {
1274
+ present: true,
1275
+ value: false
1276
+ };
1277
+ }
1278
+ return merged;
1279
+ }
1280
+ const object = unwrap(node, seen);
1281
+ if (object?.type !== "ObjectExpression") return void 0;
1282
+ let route = { present: false };
1283
+ for (const property of object.properties ?? []) {
1284
+ if (property.type === "SpreadElement") {
1285
+ const spreadRoute = staticObjectRoute(property.argument, new Set(seen));
1286
+ if (spreadRoute?.present) route = spreadRoute;
1287
+ else if (spreadRoute === void 0) route = {
1288
+ present: true,
1289
+ value: false
1290
+ };
1291
+ continue;
1292
+ }
1293
+ if ((property.computed ? staticString(property.key) : property.key?.name ?? property.key?.value) !== "route") continue;
1294
+ const value = unwrap(property.value);
1295
+ route = routeValue(value);
1296
+ }
1297
+ if (node?.type === "Identifier") for (const write of bindingFor(node)?.writes ?? []) {
1298
+ const state = writeState(write);
1299
+ if (write.node.left?.type !== "MemberExpression" || state === "skip") continue;
1300
+ if ((write.node.left.computed ? staticString(write.node.left.property) : write.node.left.property?.name) === "route") {
1301
+ if (write.node.type === "UnaryExpression") route = {
1302
+ present: true,
1303
+ value: true
1304
+ };
1305
+ else route = routeValue(state === "known" && write.node.operator === "=" ? unwrap(write.node.right) : void 0);
1306
+ }
1307
+ }
1308
+ if (node?.type === "Identifier") {
1309
+ const init = bindingFor(node)?.init;
1310
+ if (init?.type === "Identifier") for (const write of bindingFor(init)?.writes ?? []) {
1311
+ const state = writeState(write);
1312
+ if (write.node.left?.type !== "MemberExpression" || state === "skip") continue;
1313
+ if ((write.node.left.computed ? staticString(write.node.left.property) : write.node.left.property?.name) === "route") route = write.node.type === "UnaryExpression" ? {
1314
+ present: true,
1315
+ value: true
1316
+ } : routeValue(state === "known" ? unwrap(write.node.right) : void 0);
1317
+ }
1318
+ }
1319
+ if (node?.type === "Identifier") {
1320
+ const alias = unwrap(node);
1321
+ if (alias && alias !== node && alias.type === "Identifier") for (const write of bindingFor(alias)?.writes ?? []) {
1322
+ const state = writeState(write);
1323
+ if (write.node.left?.type === "MemberExpression" && state !== "skip") {
1324
+ if ((write.node.left.computed ? staticString(write.node.left.property) : write.node.left.property?.name) === "route") route = write.node.type === "UnaryExpression" ? {
1325
+ present: true,
1326
+ value: true
1327
+ } : routeValue(state === "known" ? unwrap(write.node.right) : void 0);
1328
+ }
1329
+ }
1330
+ }
1331
+ if (route.present) routeEffectState = route.value !== false;
1332
+ return route;
1333
+ };
1334
+ const routeWritesFor = (functions) => {
1335
+ const writes = [];
1336
+ for (const write of indexedWrites) if (write.fn && functions.has(write.fn)) {
1337
+ const left = write.node.left;
1338
+ if ((left?.type === "MemberExpression" ? left.computed ? staticString(left.property) : left.property?.name : void 0) === "route") writes.push(write);
1339
+ }
1340
+ return writes;
1341
+ };
1342
+ const branchRouteEffect = (functions) => {
1343
+ const values = routeWritesFor(functions).map((write) => write.node.type === "UnaryExpression" ? true : unwrap(write.node.right)).map((value) => value === true ? true : value?.type === "Literal" ? value.value : void 0);
1344
+ if (values.some((value) => value === false)) return false;
1345
+ if (values.some((value) => value === true || value === void 0)) return true;
1346
+ };
1347
+ const findRoute = (node, active = /* @__PURE__ */ new Set()) => {
1348
+ const value = unwrap(node);
1349
+ if (!value || active.has(value)) return void 0;
1350
+ const next = new Set(active).add(value);
1351
+ if (value.type === "ConditionalExpression") {
1352
+ const test = unwrap(value.test);
1353
+ if (test?.type === "Literal") return findRoute(test.value ? value.consequent : value.alternate, next);
1354
+ const branchSnapshot = snapshotExecution();
1355
+ routeEffectState = void 0;
1356
+ const consequent = findRoute(value.consequent, new Set(next));
1357
+ const consequentState = snapshotExecution();
1358
+ const consequentEffect = consequentState.routeEffectState;
1359
+ restoreExecution(branchSnapshot);
1360
+ routeEffectState = void 0;
1361
+ const alternate = findRoute(value.alternate, new Set(next));
1362
+ const alternateState = snapshotExecution();
1363
+ const alternateEffect = alternateState.routeEffectState;
1364
+ restoreExecution(branchSnapshot);
1365
+ for (const fn of consequentState.executedFunctions) if (alternateState.executedFunctions.has(fn)) executedFunctions.add(fn);
1366
+ const consequentBranchEffect = consequentEffect ?? branchRouteEffect(consequentState.executedFunctions);
1367
+ const alternateBranchEffect = alternateEffect ?? branchRouteEffect(alternateState.executedFunctions);
1368
+ if (consequentBranchEffect === false && alternateBranchEffect === false) {
1369
+ for (const fn of [...consequentState.executedFunctions, ...alternateState.executedFunctions]) if (routeWritesFor(/* @__PURE__ */ new Set([fn])).length > 0) executedFunctions.add(fn);
1370
+ routeEffectState = false;
1371
+ return false;
1372
+ }
1373
+ if (consequent !== void 0 && consequent === alternate) return consequent;
1374
+ if (consequentEffect !== void 0 && consequentEffect === alternateEffect) {
1375
+ routeEffectState = consequentEffect;
1376
+ return consequentEffect;
1377
+ }
1378
+ return;
1379
+ }
1380
+ if (value.type === "IfStatement") {
1381
+ const test = unwrap(value.test);
1382
+ if (test?.type === "Literal") return findRoute(test.value ? value.consequent : value.alternate, next);
1383
+ const branchSnapshot = snapshotExecution();
1384
+ routeEffectState = void 0;
1385
+ const consequent = findRoute(value.consequent, new Set(next));
1386
+ const consequentState = snapshotExecution();
1387
+ const consequentEffect = consequentState.routeEffectState ?? branchRouteEffect(consequentState.executedFunctions);
1388
+ restoreExecution(branchSnapshot);
1389
+ routeEffectState = void 0;
1390
+ const alternate = value.alternate ? findRoute(value.alternate, new Set(next)) : void 0;
1391
+ const alternateState = snapshotExecution();
1392
+ const alternateEffect = alternateState.routeEffectState ?? branchRouteEffect(alternateState.executedFunctions);
1393
+ restoreExecution(branchSnapshot);
1394
+ if (consequentEffect === false && alternateEffect === false) {
1395
+ for (const fn of [...consequentState.executedFunctions, ...alternateState.executedFunctions]) if (routeWritesFor(/* @__PURE__ */ new Set([fn])).length > 0) executedFunctions.add(fn);
1396
+ routeEffectState = false;
1397
+ } else if (consequentEffect !== void 0 && consequentEffect === alternateEffect) routeEffectState = consequentEffect;
1398
+ return consequent !== void 0 && alternate !== void 0 && consequent === alternate ? consequent : consequentEffect !== void 0 && consequentEffect === alternateEffect ? consequentEffect : void 0;
1399
+ }
1400
+ if (value.type === "ExpressionStatement") return findRoute(value.expression, next);
1401
+ if (value.type === "VariableDeclaration") {
1402
+ let result;
1403
+ for (const declaration of value.declarations ?? []) {
1404
+ if (!declaration.init) continue;
1405
+ const candidate = findRoute(declaration.init, next);
1406
+ if (candidate !== void 0) result = candidate;
1407
+ }
1408
+ return result;
1409
+ }
1410
+ if (value.type === "ObjectExpression") return staticObjectRoute(value)?.value !== false;
1411
+ if (value.type === "CallExpression") {
1412
+ const args = value.arguments ?? [];
1413
+ const callee = value.callee ?? value.expression;
1414
+ const isCollectionCall = unwrap(callee)?.type === "CollectionFactory" || callee?.type === "Identifier" && callee.name === "defineCollection" && !bindingFor(callee);
1415
+ const isNamespaceCollectionCall = callee?.type === "MemberExpression" && unwrap(callee.object)?.type === "CollectionNamespace" && (callee.computed ? staticString(callee.property) : callee.property?.name) === "defineCollection";
1416
+ if (isCollectionCall || isNamespaceCollectionCall) {
1417
+ const previousPosition = readPosition;
1418
+ readPosition = value.start ?? readPosition;
1419
+ const route = staticObjectRoute(args.length > 1 ? args[1] : args[0]);
1420
+ readPosition = previousPosition;
1421
+ return route?.value !== false;
1422
+ }
1423
+ if (callee?.type === "MemberExpression" && !callee.computed && callee.object?.type === "Identifier" && callee.object.name === "Object" && [
1424
+ "freeze",
1425
+ "seal",
1426
+ "preventExtensions"
1427
+ ].includes(callee.property?.name ?? "")) return findRoute(args[0], next);
1428
+ const fn = unwrap(callee);
1429
+ if (!fn || ![
1430
+ "ArrowFunctionExpression",
1431
+ "FunctionExpression",
1432
+ "FunctionDeclaration"
1433
+ ].includes(fn.type ?? "")) return void 0;
1434
+ const previousPosition = readPosition;
1435
+ readPosition = value.start ?? readPosition;
1436
+ const previousValues = new Map(parameterValues);
1437
+ for (const [index, param] of (fn.params ?? []).entries()) {
1438
+ const binding = bindingFor(param.type === "AssignmentPattern" ? param.left : param);
1439
+ if (!binding) continue;
1440
+ const argument = args[index];
1441
+ const value = unwrap(argument);
1442
+ if (argument && !(value?.type === "Literal" && value.value === void 0 && param.type === "AssignmentPattern")) parameterValues.set(binding, argument);
1443
+ else if (param.type === "AssignmentPattern") parameterValues.delete(binding);
1444
+ else parameterValues.set(binding, {
1445
+ type: "Literal",
1446
+ value: void 0
1447
+ });
1448
+ }
1449
+ activeFunctions.add(fn);
1450
+ executedFunctions.add(fn);
1451
+ const result = findRoute(Array.isArray(fn.body) ? void 0 : fn.body, next);
1452
+ for (const [index, param] of (fn.params ?? []).entries()) {
1453
+ const parameter = bindingFor(param.type === "AssignmentPattern" ? param.left : param);
1454
+ const argument = args[index];
1455
+ const target = argument?.type === "Identifier" ? bindingFor(argument) : void 0;
1456
+ if (!parameter || !target) continue;
1457
+ for (const write of parameter.writes ?? []) {
1458
+ if (write.node.left?.type !== "MemberExpression") continue;
1459
+ if ((write.node.left.computed ? staticString(write.node.left.property) : write.node.left.property?.name) !== "route") continue;
1460
+ const replay = {
1461
+ ...write,
1462
+ fn: void 0,
1463
+ replayed: true
1464
+ };
1465
+ (target.writes ??= []).push(replay);
1466
+ indexedWrites.push(replay);
1467
+ }
1468
+ }
1469
+ activeFunctions.delete(fn);
1470
+ parameterValues.clear();
1471
+ for (const [binding, argument] of previousValues) parameterValues.set(binding, argument);
1472
+ readPosition = previousPosition;
1473
+ return result;
1474
+ }
1475
+ if (value.type === "BlockStatement") {
1476
+ const hasReturn = (candidate) => {
1477
+ if (!candidate) return false;
1478
+ if (candidate.type === "ReturnStatement") return true;
1479
+ for (const child of Object.values(candidate)) if (Array.isArray(child)) {
1480
+ if (child.some((item) => item && typeof item === "object" && hasReturn(item))) return true;
1481
+ } else if (child && typeof child === "object" && hasReturn(child)) return true;
1482
+ return false;
1483
+ };
1484
+ for (const statement of Array.isArray(value.body) ? value.body : []) {
1485
+ if (statement.type === "ReturnStatement") return findRoute(statement.argument ?? statement.expression, next);
1486
+ if (statement.type === "IfStatement") {
1487
+ const result = findRoute(statement, next);
1488
+ if (result !== void 0) return result;
1489
+ if (hasReturn(statement.consequent) || hasReturn(statement.alternate)) return void 0;
1490
+ continue;
1491
+ }
1492
+ if (statement.type === "ExpressionStatement" && statement.expression) findRoute(statement.expression, next);
1493
+ if (statement.type === "VariableDeclaration") {
1494
+ for (const declaration of statement.declarations ?? []) if (declaration.init) findRoute(declaration.init, next);
1495
+ }
1496
+ }
1497
+ }
1498
+ };
1499
+ const exportStart = exported?.init?.start ?? Infinity;
1500
+ for (const statement of parsed.program.body) {
1501
+ if ((statement.start ?? Infinity) >= exportStart) continue;
1502
+ findRoute(statement);
1503
+ }
1504
+ return findRoute(exported?.init) ?? true;
173
1505
  }
174
- async function discoverCollections(options) {
1506
+ async function discoverSourceCollections(options) {
175
1507
  const serverDirs = options.serverDirs === void 0 ? [resolve(options.projectRoot, "server")] : options.serverDirs.map((directory) => resolve(options.projectRoot, directory));
176
1508
  const collections = (await Promise.all(serverDirs.map(async (serverDir) => {
177
1509
  const directory = resolve(serverDir, "collections");
178
1510
  return await Promise.all((await collectCollectionFiles(directory)).sort().map(async (file) => {
179
1511
  const extension = extname(file);
180
1512
  const exportName = basename(file, extension);
181
- if (!/^[A-Z_$][\w$]*$/i.test(exportName)) throw new TypeError(`[vitehub] Collection file ${JSON.stringify(relative(options.projectRoot, file))} must use a valid JavaScript identifier as its filename.`);
1513
+ if (!/^[A-Z_$][\w$]*$/i.test(exportName)) throw sourceErrorDiagnostics.SOURCE_B0003({ message: `[vitehub] Collection file ${JSON.stringify(relative(options.projectRoot, file))} must use a valid JavaScript identifier as its filename.` });
182
1514
  const name = relative(directory, file).slice(0, -extension.length).replaceAll("\\", "/");
183
- if (!findExportNames(await readFile(file, "utf8")).includes(exportName)) throw new TypeError(`[vitehub] Collection file ${JSON.stringify(relative(options.projectRoot, file))} must export a Collection named ${JSON.stringify(exportName)} to match its filename.`);
1515
+ const source = await readFile(file, "utf8");
1516
+ if (!findExportNames(source).includes(exportName)) throw sourceErrorDiagnostics.SOURCE_B0004({ message: `[vitehub] Collection file ${JSON.stringify(relative(options.projectRoot, file))} must export a Collection named ${JSON.stringify(exportName)} to match its filename.` });
184
1517
  return {
185
1518
  exportName,
186
1519
  file,
187
- name
1520
+ name,
1521
+ routeEnabled: collectionRouteEnabled(file, source, exportName)
188
1522
  };
189
1523
  }));
190
1524
  }))).flat().sort((left, right) => left.name.localeCompare(right.name));
@@ -192,10 +1526,10 @@ async function discoverCollections(options) {
192
1526
  for (const collection of collections) {
193
1527
  const generatedPath = `${collection.name}.mjs`.toLowerCase();
194
1528
  const previous = generatedPaths.get(generatedPath);
195
- if (previous?.name === collection.name) throw new TypeError(`[vitehub] Collection name ${JSON.stringify(collection.name)} is defined in more than one server directory.`);
1529
+ if (previous?.name === collection.name) throw sourceErrorDiagnostics.SOURCE_B0005({ message: `[vitehub] Collection name ${JSON.stringify(collection.name)} is defined in more than one server directory.` });
196
1530
  if (previous) {
197
1531
  const [firstName, secondName] = [previous.name, collection.name].sort();
198
- throw new TypeError(`[vitehub] Collection names ${JSON.stringify(firstName)} and ${JSON.stringify(secondName)} generate the same route module on case-insensitive filesystems.`);
1532
+ throw sourceErrorDiagnostics.SOURCE_B0006({ message: `[vitehub] Collection names ${JSON.stringify(firstName)} and ${JSON.stringify(secondName)} generate the same route module on case-insensitive filesystems.` });
199
1533
  }
200
1534
  generatedPaths.set(generatedPath, collection);
201
1535
  }
@@ -215,7 +1549,6 @@ async function writeFileIfChanged(path, contents) {
215
1549
  async function writeCollectionArtifacts(options, collections) {
216
1550
  const output = resolve(options.projectRoot, collectionTypesEntry);
217
1551
  const packageOutput = resolve(options.projectRoot, collectionTypesPackageEntry);
218
- await rm(resolve(options.projectRoot, legacyCollectionTypesEntry), { force: true });
219
1552
  const routesDirectory = resolve(options.projectRoot, collectionRoutesDirectory);
220
1553
  if (collections.length === 0) {
221
1554
  await Promise.all([
@@ -228,10 +1561,11 @@ async function writeCollectionArtifacts(options, collections) {
228
1561
  ]);
229
1562
  return [];
230
1563
  }
1564
+ const routedCollections = collections.filter((collection) => collection.routeEnabled);
231
1565
  await writeFileIfChanged(output, [
232
1566
  "declare global {",
233
1567
  " interface ViteHubCollectionMap {",
234
- ...collections.map(({ exportName, file, name }) => ` ${JSON.stringify(name)}: typeof import(${JSON.stringify(toTypeModuleSpecifier(file))})[${JSON.stringify(exportName)}]`),
1568
+ ...routedCollections.map(({ exportName, file, name }) => ` ${JSON.stringify(name)}: typeof import(${JSON.stringify(toTypeModuleSpecifier(file))})[${JSON.stringify(exportName)}]`),
235
1569
  " }",
236
1570
  "}",
237
1571
  "",
@@ -239,26 +1573,31 @@ async function writeCollectionArtifacts(options, collections) {
239
1573
  ""
240
1574
  ].join("\n"));
241
1575
  await writeFileIfChanged(packageOutput, "/// <reference path=\"./collections.d.ts\" />\n");
242
- const expectedRoutes = new Set(collections.map(({ name }) => resolve(routesDirectory, `${name}.mjs`)));
1576
+ const expectedRoutes = new Set(routedCollections.map(({ name }) => resolve(routesDirectory, `${name}.mjs`)));
243
1577
  const existingRoutes = await collectCollectionFiles(routesDirectory);
244
1578
  await Promise.all(existingRoutes.filter((file) => !expectedRoutes.has(file)).map((file) => rm(file, { force: true })));
245
- return await Promise.all(collections.map(async ({ exportName, file, name }) => {
1579
+ return await Promise.all(routedCollections.map(async ({ exportName, file, name }) => {
246
1580
  const handler = resolve(routesDirectory, `${name}.mjs`);
247
1581
  await writeFileIfChanged(handler, [
248
1582
  `import { defineCollectionHandler } from ${JSON.stringify(`${options.importBase ?? "@vite-hub/source"}/server`)}`,
1583
+ ...options.auth ? [`import { withAuthorization } from ${JSON.stringify(authServerModuleId)}`] : [],
249
1584
  `import { ${exportName} as collection } from ${JSON.stringify(toRuntimeModuleSpecifier(file))}`,
250
1585
  "",
251
- "export default defineCollectionHandler(collection)",
1586
+ options.auth ? "export default defineCollectionHandler(collection, { withAuthorization })" : "export default defineCollectionHandler(collection)",
252
1587
  ""
253
1588
  ].join("\n"));
254
1589
  return {
255
1590
  handler,
256
1591
  method: "get",
257
- route: `/api/${name.split("/").map(encodeCollectionRouteSegment).join("/")}`
1592
+ route: collectionRoutePath(name)
258
1593
  };
259
1594
  }));
260
1595
  }
261
- async function discoverContent(options) {
1596
+ /**
1597
+ * Find the `server/content.{ts,js}` file that exports the application Content runtime as `content`. Returns undefined when
1598
+ * the project has none. The generated `/api/content/**` route and the Console content editor import the same file.
1599
+ */
1600
+ async function findContentEntry(options) {
262
1601
  const serverDirs = options.serverDirs === void 0 ? [resolve(options.projectRoot, "server")] : options.serverDirs.map((directory) => resolve(options.projectRoot, directory));
263
1602
  const candidates = [];
264
1603
  for (const serverDir of serverDirs) {
@@ -272,33 +1611,245 @@ async function discoverContent(options) {
272
1611
  candidates.push(...entries.filter((entry) => entry.isFile() && /^content\.(?:[cm]?[jt]s)$/.test(entry.name) && !/\.d\.[cm]?ts$/.test(entry.name)).map((entry) => join(serverDir, entry.name)));
273
1612
  }
274
1613
  candidates.sort();
275
- if (candidates.length > 1) throw new TypeError("[vitehub] Content is defined in more than one server directory.");
1614
+ if (candidates.length > 1) throw sourceErrorDiagnostics.SOURCE_B0007({ message: "[vitehub] Content is defined in more than one server directory." });
276
1615
  const file = candidates[0];
277
1616
  if (!file) return;
278
- if (!findExportNames(await readFile(file, "utf8")).includes("content")) throw new TypeError(`[vitehub] Content file ${JSON.stringify(relative(options.projectRoot, file))} must export a Comark Content instance named "content".`);
1617
+ if (!findExportNames(await readFile(file, "utf8")).includes("content")) throw sourceErrorDiagnostics.SOURCE_B0008({ message: `[vitehub] Content file ${JSON.stringify(relative(options.projectRoot, file))} must export a Comark Content instance named "content".` });
279
1618
  return file;
280
1619
  }
1620
+ const contentModules = /* @__PURE__ */ new Set(["vite-hub/content", "@vite-hub/content"]);
1621
+ function isAstNode(value) {
1622
+ return value !== null && Object(value) === value && !Array.isArray(value);
1623
+ }
1624
+ function astNodes(value) {
1625
+ return Array.isArray(value) ? value.filter(isAstNode) : [];
1626
+ }
1627
+ function astName(node) {
1628
+ if (!isAstNode(node)) return;
1629
+ if (node.type === "Identifier" && String(node.name) === node.name) return node.name;
1630
+ if (node.type === "Literal" && String(node.value) === node.value) return node.value;
1631
+ }
1632
+ /** Drops `as`, `satisfies`, `!`, and parentheses around an expression. */
1633
+ function unwrapAst(node) {
1634
+ let current = node;
1635
+ while (isAstNode(current) && [
1636
+ "TSAsExpression",
1637
+ "TSSatisfiesExpression",
1638
+ "TSNonNullExpression",
1639
+ "ParenthesizedExpression"
1640
+ ].includes(String(current.type))) current = current.expression;
1641
+ return current;
1642
+ }
1643
+ /**
1644
+ * Read the `defineContent()` call that initializes the `content` export. Collections count as present unless the call
1645
+ * provably has no non-empty `collections` object. SEO routes count only when the call has a `seo` option: a literal
1646
+ * `sitemap` or `robots` that is not `false`, or a `seo` value that discovery cannot follow.
1647
+ */
1648
+ function inspectContentModule(program, contentImportBase) {
1649
+ const maybe = {
1650
+ route: true,
1651
+ collections: true,
1652
+ sitemap: false,
1653
+ robots: false,
1654
+ live: true
1655
+ };
1656
+ const body = isAstNode(program) ? astNodes(program.body) : [];
1657
+ const constants = /* @__PURE__ */ new Map();
1658
+ const defineContentNames = /* @__PURE__ */ new Set();
1659
+ const defineContentNamespaces = /* @__PURE__ */ new Set();
1660
+ const modules = contentImportBase ? /* @__PURE__ */ new Set([...contentModules, contentImportBase]) : contentModules;
1661
+ let contentInit;
1662
+ let contentLocal;
1663
+ for (const statement of body) {
1664
+ if (statement.type === "ImportDeclaration" && isAstNode(statement.source) && modules.has(String(statement.source.value))) for (const specifier of astNodes(statement.specifiers)) {
1665
+ if (specifier.type === "ImportSpecifier" && astName(specifier.imported) === "defineContent") {
1666
+ const local = astName(specifier.local);
1667
+ if (local) defineContentNames.add(local);
1668
+ }
1669
+ if (specifier.type === "ImportNamespaceSpecifier") {
1670
+ const local = astName(specifier.local);
1671
+ if (local) defineContentNamespaces.add(local);
1672
+ }
1673
+ }
1674
+ const exported = statement.type === "ExportNamedDeclaration";
1675
+ const declaration = exported ? statement.declaration : statement;
1676
+ if (isAstNode(declaration) && declaration.type === "VariableDeclaration") for (const declarator of astNodes(declaration.declarations)) {
1677
+ const local = astName(declarator.id);
1678
+ if (!local) continue;
1679
+ if (declaration.kind === "const") constants.set(local, declarator.init);
1680
+ if (exported && local === "content") contentInit = declarator.init;
1681
+ }
1682
+ if (exported && !statement.source) {
1683
+ for (const specifier of astNodes(statement.specifiers)) if (astName(specifier.exported) === "content") contentLocal = astName(specifier.local);
1684
+ }
1685
+ }
1686
+ if (contentInit === void 0 && contentLocal) contentInit = constants.get(contentLocal);
1687
+ const resolveNode = (node) => {
1688
+ const value = unwrapAst(node);
1689
+ const local = isAstNode(value) && value.type === "Identifier" ? astName(value) : void 0;
1690
+ return local && constants.has(local) ? unwrapAst(constants.get(local)) : value;
1691
+ };
1692
+ const properties = (node) => {
1693
+ if (!isAstNode(node) || node.type !== "ObjectExpression") return;
1694
+ const result = /* @__PURE__ */ new Map();
1695
+ for (const property of Array.isArray(node.properties) ? node.properties : []) {
1696
+ if (!isAstNode(property)) return;
1697
+ if (property.type === "SpreadElement") {
1698
+ const spread = properties(resolveNode(property.argument));
1699
+ if (!spread) return;
1700
+ for (const [key, value] of spread) result.set(key, value);
1701
+ continue;
1702
+ }
1703
+ if (property.type !== "Property" || property.computed) return;
1704
+ const key = astName(property.key);
1705
+ if (key) result.set(key, property.value);
1706
+ }
1707
+ return result;
1708
+ };
1709
+ const call = unwrapAst(contentInit);
1710
+ if (!isAstNode(call) || call.type !== "CallExpression") return maybe;
1711
+ const calleeNode = unwrapAst(call.callee);
1712
+ const callee = astName(calleeNode);
1713
+ const namespaceCall = isAstNode(calleeNode) && calleeNode.type === "MemberExpression" && !calleeNode.computed && defineContentNamespaces.has(astName(calleeNode.object) ?? "") && astName(calleeNode.property) === "defineContent";
1714
+ if ((!callee || !defineContentNames.has(callee)) && !namespaceCall) return maybe;
1715
+ const [argument, ...rest] = Array.isArray(call.arguments) ? call.arguments : [];
1716
+ if (argument === void 0) return {
1717
+ route: true,
1718
+ collections: false,
1719
+ sitemap: false,
1720
+ robots: false,
1721
+ live: true
1722
+ };
1723
+ const options = rest.length ? void 0 : properties(resolveNode(argument));
1724
+ if (!options) return {
1725
+ route: true,
1726
+ collections: true,
1727
+ sitemap: true,
1728
+ robots: true,
1729
+ live: true
1730
+ };
1731
+ const route = resolveNode(options.get("route"));
1732
+ const live = unwrapAst(options.get("live"));
1733
+ const features = {
1734
+ route: !(isAstNode(route) && route.type === "Literal" && route.value === false),
1735
+ collections: false,
1736
+ sitemap: false,
1737
+ robots: false,
1738
+ live: !(isAstNode(live) && live.type === "Literal" && live.value === false)
1739
+ };
1740
+ if (options.has("collections")) {
1741
+ const value = resolveNode(options.get("collections"));
1742
+ features.collections = !isAstNode(value) || value.type !== "ObjectExpression" || Array.isArray(value.properties) && value.properties.length > 0;
1743
+ }
1744
+ if (options.has("seo")) {
1745
+ const seo = properties(resolveNode(options.get("seo")));
1746
+ if (!seo) return {
1747
+ ...features,
1748
+ sitemap: true,
1749
+ robots: true
1750
+ };
1751
+ for (const key of ["sitemap", "robots"]) {
1752
+ if (!seo.has(key)) continue;
1753
+ const value = unwrapAst(seo.get(key));
1754
+ features[key] = !(isAstNode(value) && value.type === "Literal" && value.value === false);
1755
+ }
1756
+ }
1757
+ return features;
1758
+ }
1759
+ /** Read what the Content module defines without running it. A file that does not parse counts as defining everything. */
1760
+ async function inspectContentEntry(file, contentImportBase) {
1761
+ const { parseAst } = await import("vite");
1762
+ try {
1763
+ return inspectContentModule(parseAst(await readFile(file, "utf8"), { lang: /\.[cm]?ts$/.test(file) ? "ts" : "js" }), contentImportBase);
1764
+ } catch {
1765
+ return {
1766
+ route: true,
1767
+ collections: true,
1768
+ sitemap: false,
1769
+ robots: false,
1770
+ live: true
1771
+ };
1772
+ }
1773
+ }
281
1774
  async function writeContentArtifact(options, file) {
282
1775
  const output = resolve(options.projectRoot, contentRouteEntry);
1776
+ const preview = resolve(options.projectRoot, contentPreviewEntry);
1777
+ const sitemap = resolve(options.projectRoot, contentSitemapEntry);
1778
+ const robots = resolve(options.projectRoot, contentRobotsEntry);
283
1779
  if (!file) {
284
- await rm(output, { force: true });
1780
+ await Promise.all([
1781
+ output,
1782
+ preview,
1783
+ sitemap,
1784
+ robots
1785
+ ].map((path) => rm(path, { force: true })));
285
1786
  return [];
286
1787
  }
287
- await writeFileIfChanged(output, [
288
- `import { defineContentHandler } from ${JSON.stringify(`${options.importBase ?? "@vite-hub/source"}/content`)}`,
289
- `import { content } from ${JSON.stringify(toRuntimeModuleSpecifier(file))}`,
1788
+ const importBase = JSON.stringify(options.contentImportBase ?? "@vite-hub/content");
1789
+ const contentModule = JSON.stringify(toRuntimeModuleSpecifier(file));
1790
+ const features = await inspectContentEntry(file, options.contentImportBase ?? "@vite-hub/content");
1791
+ if (features.route) await writeFileIfChanged(output, [
1792
+ `import { defineContentHandler } from ${importBase}`,
1793
+ `import { content } from ${contentModule}`,
290
1794
  "",
291
1795
  "export default defineContentHandler(content)",
292
1796
  ""
293
1797
  ].join("\n"));
294
- return [{
1798
+ else await rm(output, { force: true });
1799
+ await writeFileIfChanged(preview, [
1800
+ `import { defineContentPreviewPlugin } from ${importBase}`,
1801
+ `import { content } from ${contentModule}`,
1802
+ "",
1803
+ "export default defineContentPreviewPlugin(content)",
1804
+ ""
1805
+ ].join("\n"));
1806
+ const handlers = [{
1807
+ handler: preview,
1808
+ plugin: true
1809
+ }];
1810
+ if (features.route) handlers.push({
295
1811
  handler: output,
296
1812
  route: "/api/content/**"
297
- }];
1813
+ });
1814
+ for (const [enabled, path, helper, route] of [[
1815
+ features.sitemap,
1816
+ sitemap,
1817
+ "defineContentSitemapHandler",
1818
+ "/sitemap.xml"
1819
+ ], [
1820
+ features.robots,
1821
+ robots,
1822
+ "defineContentRobotsHandler",
1823
+ "/robots.txt"
1824
+ ]]) {
1825
+ if (!enabled) {
1826
+ await rm(path, { force: true });
1827
+ continue;
1828
+ }
1829
+ await writeFileIfChanged(path, [
1830
+ `import { ${helper} } from ${importBase}`,
1831
+ `import { content } from ${contentModule}`,
1832
+ "",
1833
+ `export default ${helper}(content)`,
1834
+ ""
1835
+ ].join("\n"));
1836
+ handlers.push({
1837
+ handler: path,
1838
+ method: "get",
1839
+ route
1840
+ });
1841
+ }
1842
+ return handlers;
1843
+ }
1844
+ async function prepareSourceArtifacts(options) {
1845
+ const [collections, content] = await Promise.all([discoverSourceCollections(options), findContentEntry(options)]);
1846
+ return {
1847
+ handlers: [...await writeCollectionArtifacts(options, collections), ...await writeContentArtifact(options, content)].sort((left, right) => (left.route ?? "").localeCompare(right.route ?? "")),
1848
+ ...content ? { content: { handler: content } } : {}
1849
+ };
298
1850
  }
299
1851
  async function prepareSourceGeneration(options) {
300
- const [collections, content] = await Promise.all([discoverCollections(options), discoverContent(options)]);
301
- return [...await writeCollectionArtifacts(options, collections), ...await writeContentArtifact(options, content)].sort((left, right) => left.route.localeCompare(right.route));
1852
+ return (await prepareSourceArtifacts(options)).handlers;
302
1853
  }
303
1854
  function applicationBaseURL(base) {
304
1855
  return base?.startsWith("/") && !base.startsWith("//") ? base : "/";
@@ -315,36 +1866,64 @@ function generatedSourceNitroContribution(value, generatedHandlers) {
315
1866
  const merged = mergeGeneratedSourceNitroConfig(existing, generatedHandlers);
316
1867
  const handlers = merged.handlers?.slice(Array.isArray(existing.handlers) ? existing.handlers.length : 0);
317
1868
  const modules = merged.modules?.slice(Array.isArray(existing.modules) ? existing.modules.length : 0);
318
- if (!handlers?.length && !modules?.length) return;
319
- return {
320
- ...handlers?.length ? { handlers } : {},
321
- ...modules?.length ? { modules } : {}
322
- };
1869
+ const plugins = merged.plugins?.slice(Array.isArray(existing.plugins) ? existing.plugins.length : 0);
1870
+ if (!handlers?.length && !modules?.length && !plugins?.length) return;
1871
+ const contribution = {};
1872
+ if (handlers?.length) contribution.handlers = handlers;
1873
+ if (modules?.length) contribution.modules = modules;
1874
+ if (plugins?.length) contribution.plugins = plugins;
1875
+ return contribution;
323
1876
  }
324
1877
  function sourceDefinitionPath(file, projectRoot, serverDirs) {
1878
+ const projectRelativePath = relative(resolve(projectRoot), resolve(file)).replaceAll("\\", "/");
1879
+ if (/^server\.auth\.(?:[cm]?[jt]s)$/.test(projectRelativePath)) return true;
325
1880
  return (serverDirs === void 0 ? [resolve(projectRoot, "server")] : serverDirs).some((directory) => {
326
1881
  const path = relative(resolve(projectRoot, directory), resolve(file)).replaceAll("\\", "/");
327
1882
  if (path.startsWith("../") || isAbsolute(path)) return false;
328
- return /^content\.(?:[cm]?[jt]s)$/.test(path) || /^collections\/.+\.(?:[cm]?[jt]s)$/.test(path) && !/\.d\.[cm]?ts$/.test(path);
1883
+ return /^content\.(?:[cm]?[jt]s)$/.test(path) || /^auth\.(?:[cm]?[jt]s)$/.test(path) || /^collections\/.+\.(?:[cm]?[jt]s)$/.test(path) && !/\.d\.[cm]?ts$/.test(path);
329
1884
  });
330
1885
  }
331
1886
  function hubSource(options = {}) {
1887
+ const refreshAuthByRoot = /* @__PURE__ */ new Map();
1888
+ let nitroHost;
1889
+ let nitroHostContribution;
1890
+ const nitroHandlers = [];
332
1891
  let latestProjectRoot;
333
1892
  const configuredStateByRoot = /* @__PURE__ */ new Map();
334
1893
  const closeHostRefreshByEnvironment = /* @__PURE__ */ new WeakMap();
335
1894
  const hostRefreshLifecycleByRoot = /* @__PURE__ */ new Map();
336
1895
  const sourcePreparationByRoot = /* @__PURE__ */ new Map();
1896
+ const contentDefinitionByRoot = /* @__PURE__ */ new Map();
1897
+ const getContentDefinition = (projectRoot) => {
1898
+ const root = projectRoot ? resolve(projectRoot) : latestProjectRoot;
1899
+ return root ? contentDefinitionByRoot.get(root) : void 0;
1900
+ };
337
1901
  const configurationTransitionByRoot = /* @__PURE__ */ new Map();
1902
+ let legacyServerBuild = false;
338
1903
  const generatedHandlersListeners = /* @__PURE__ */ new Set();
339
- const prepareSources = (input) => {
1904
+ const prepareSources = (input, configuredAuth) => {
340
1905
  const root = resolve(input.projectRoot);
341
- const preparation = (sourcePreparationByRoot.get(root) ?? Promise.resolve()).then(() => prepareSourceGeneration({
342
- ...input,
343
- importBase: options.importBase
344
- }), () => prepareSourceGeneration({
345
- ...input,
346
- importBase: options.importBase
347
- }));
1906
+ const previousPreparation = sourcePreparationByRoot.get(root) ?? Promise.resolve();
1907
+ const runPreparation = () => {
1908
+ const configuredState = configuredStateByRoot.get(root);
1909
+ const resolvedConfiguredAuth = configuredAuth === void 0 ? configuredState?.configuredAuth : configuredAuth;
1910
+ const auth = typeof options.auth === "function" ? options.auth({
1911
+ configuredAuth: resolvedConfiguredAuth,
1912
+ projectRoot: root,
1913
+ serverDirs: input.serverDirs
1914
+ }) : options.auth && resolvedConfiguredAuth !== false && Boolean(refreshAuthByRoot.get(root)?.());
1915
+ return prepareSourceArtifacts({
1916
+ ...input,
1917
+ auth,
1918
+ importBase: options.importBase,
1919
+ contentImportBase: options.contentImportBase
1920
+ }).then(({ content, handlers }) => {
1921
+ if (content) contentDefinitionByRoot.set(root, content);
1922
+ else contentDefinitionByRoot.delete(root);
1923
+ return handlers;
1924
+ });
1925
+ };
1926
+ const preparation = previousPreparation.then(runPreparation, runPreparation);
348
1927
  sourcePreparationByRoot.set(root, preparation);
349
1928
  preparation.finally(() => {
350
1929
  if (sourcePreparationByRoot.get(root) === preparation) sourcePreparationByRoot.delete(root);
@@ -378,18 +1957,74 @@ function hubSource(options = {}) {
378
1957
  if (Array.isArray(nitro.handlers) && contributedHandlers.length > 0) nitro.handlers = nitro.handlers.filter((handler) => !contributedHandlers.includes(handler));
379
1958
  const contributedModules = configuredNitroContribution?.modules ?? [];
380
1959
  if (Array.isArray(nitro.modules) && contributedModules.length > 0) nitro.modules = nitro.modules.filter((module) => !contributedModules.includes(module));
1960
+ const contributedPlugins = configuredNitroContribution?.plugins ?? [];
1961
+ if (Array.isArray(nitro.plugins) && contributedPlugins.length > 0) nitro.plugins = nitro.plugins.filter((plugin) => !contributedPlugins.includes(plugin));
381
1962
  return mergeGeneratedSourceNitroConfig(nitro, handlers);
382
1963
  };
383
1964
  return {
384
1965
  name: "@vite-hub/source/vite",
385
1966
  enforce: "post",
386
1967
  api: {
1968
+ getContentDefinition,
387
1969
  onGeneratedHandlersChanged,
388
1970
  prepareSources
389
1971
  },
390
- async config(config) {
1972
+ resolveId: {
1973
+ filter: { id: BUNDLED_GLOB_ID_PATTERN },
1974
+ handler(id) {
1975
+ return id;
1976
+ }
1977
+ },
1978
+ load: {
1979
+ filter: { id: BUNDLED_GLOB_ID_PATTERN },
1980
+ async handler(id) {
1981
+ const { code, watched } = await loadBundledGlob(id, latestProjectRoot ?? resolveViteHubProjectRoot(process.cwd()));
1982
+ for (const file of watched) this.addWatchFile(file);
1983
+ return code;
1984
+ }
1985
+ },
1986
+ transform: {
1987
+ filter: {
1988
+ id: { exclude: /\/node_modules\// },
1989
+ code: "source/glob"
1990
+ },
1991
+ handler(code, _id, options) {
1992
+ const environment = this.environment?.config;
1993
+ if (!(environment ? environment.consumer === "server" : options?.ssr === true && legacyServerBuild) || environment && environment.command !== "build") return;
1994
+ const calls = findGlobCalls(this.parse(code));
1995
+ for (const call of calls.filter((call) => call.input === void 0)) this.warn({
1996
+ message: "[vitehub] glob() here takes options that are not literals, so the build cannot bundle its files. It reads them from disk at runtime, which hosts such as Cloudflare Workers do not have.",
1997
+ pos: call.start
1998
+ });
1999
+ if (calls.some((call) => call.input !== void 0)) return {
2000
+ code: rewriteGlobCalls(code, calls),
2001
+ map: null
2002
+ };
2003
+ }
2004
+ },
2005
+ vitehub: { inspect: () => ({ definitions: [{
2006
+ kind: "collection",
2007
+ label: "Collections",
2008
+ list: () => {
2009
+ const projectRoot = latestProjectRoot ?? resolveViteHubProjectRoot(process.cwd());
2010
+ return inspectCollectionDefinitions({
2011
+ projectRoot,
2012
+ serverDirs: configuredStateByRoot.get(projectRoot)?.serverDirs
2013
+ });
2014
+ }
2015
+ }] }) },
2016
+ nitro: {
2017
+ name: "@vite-hub/source/generated-routes",
2018
+ setup(nitro) {
2019
+ nitroHost = nitro;
2020
+ nitroHostContribution = void 0;
2021
+ generatedRouteGuard(nitroHandlers).setup(nitro);
2022
+ }
2023
+ },
2024
+ async config(config, env) {
391
2025
  const viteConfig = config;
392
2026
  if (viteConfig["__vitehubNitroConfigContext"]) return;
2027
+ legacyServerBuild = env.command === "build" && config.build?.ssr === true;
393
2028
  const projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(viteConfig.root || process.cwd());
394
2029
  latestProjectRoot = projectRoot;
395
2030
  bindUnresolvedListenerRoots(projectRoot);
@@ -403,10 +2038,11 @@ function hubSource(options = {}) {
403
2038
  const handlers = await prepareSources({
404
2039
  projectRoot,
405
2040
  serverDirs
406
- });
2041
+ }, viteConfig.auth === false ? false : viteConfig.auth ? true : void 0);
407
2042
  const handlerKey = await generatedHandlerKey(handlers);
408
2043
  const nitro = generatedSourceNitroContribution(viteConfig.nitro, handlers);
409
2044
  configuredStateByRoot.set(projectRoot, {
2045
+ configuredAuth: viteConfig.auth === false ? false : viteConfig.auth ? true : void 0,
410
2046
  handlerKey,
411
2047
  nitroContribution: nitro,
412
2048
  serverDirs: serverDirs?.slice()
@@ -441,6 +2077,12 @@ function hubSource(options = {}) {
441
2077
  const projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(config.root);
442
2078
  latestProjectRoot = projectRoot;
443
2079
  bindUnresolvedListenerRoots(projectRoot);
2080
+ const authPlugin = (config.plugins ?? []).flat(Infinity).find((plugin) => plugin.name === "@vite-hub/auth/vite");
2081
+ const refreshAuth = Reflect.get(Object(Reflect.get(Object(authPlugin), "api")), "refresh");
2082
+ if (refreshAuth instanceof Function) refreshAuthByRoot.set(projectRoot, () => refreshAuth());
2083
+ else refreshAuthByRoot.delete(projectRoot);
2084
+ viteConfig.define ??= {};
2085
+ viteConfig.define.__VITEHUB_APP_BASE_URL__ = JSON.stringify(applicationBaseURL(config.base));
444
2086
  const previousTransition = configurationTransitionByRoot.get(projectRoot) ?? Promise.resolve();
445
2087
  const runTransition = async () => {
446
2088
  const configuredState = configuredStateByRoot.get(projectRoot);
@@ -448,9 +2090,22 @@ function hubSource(options = {}) {
448
2090
  const handlers = await prepareSources({
449
2091
  projectRoot,
450
2092
  serverDirs
451
- });
2093
+ }, viteConfig.auth === false ? false : viteConfig.auth ? true : void 0);
452
2094
  const handlerKey = await generatedHandlerKey(handlers);
2095
+ if (nitroHost && !viteConfig["__vitehubNitroConfigContext"]) {
2096
+ assertGeneratedRoutes(nitroHost, handlers);
2097
+ const nitro = replaceConfiguredNitroContribution(nitroHost.options, handlers, nitroHostContribution);
2098
+ nitroHostContribution = {
2099
+ handlers: nitro.handlers?.filter((handler) => handlers.some((generated) => !generated.plugin && handler.handler === generated.handler && handler.route === generated.route && handler.method === generated.method)),
2100
+ plugins: handlers.flatMap((generated) => generated.plugin ? [generated.handler] : [])
2101
+ };
2102
+ nitroHost.options.handlers = nitro.handlers;
2103
+ nitroHost.options.plugins = nitro.plugins;
2104
+ nitroHandlers.splice(0, nitroHandlers.length, ...handlers);
2105
+ nitroHost.routing.sync();
2106
+ }
453
2107
  configuredStateByRoot.set(projectRoot, {
2108
+ configuredAuth: viteConfig.auth === false ? false : viteConfig.auth ? true : void 0,
454
2109
  handlerKey,
455
2110
  nitroContribution: configuredState?.nitroContribution,
456
2111
  serverDirs: serverDirs?.slice()
@@ -626,4 +2281,4 @@ function hubSource(options = {}) {
626
2281
  };
627
2282
  }
628
2283
  //#endregion
629
- export { hubSource, mergeGeneratedSourceNitroConfig, prepareSourceGeneration, toRuntimeModuleSpecifier, toTypeModuleSpecifier };
2284
+ export { findContentEntry, hubSource, inspectCollectionDefinitions, inspectContentEntry, inspectContentModule, mergeGeneratedSourceNitroConfig, prepareSourceGeneration, toRuntimeModuleSpecifier, toTypeModuleSpecifier };