@vite-hub/source 0.0.3 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +302 -31
- package/dist/auth-B-tX_rp0.js +1426 -0
- package/dist/client-BwstxtdY.js +8280 -0
- package/dist/client.d.ts +49 -0
- package/dist/client.js +179 -0
- package/dist/collection-B_4w_J8h.d.ts +257 -0
- package/dist/collection-cursor-WzV1Jd6v.js +124 -0
- package/dist/collection-route-BplWPxHR.js +10 -0
- package/dist/drizzle.d.ts +41 -0
- package/dist/drizzle.js +89 -0
- package/dist/error-diagnostics-X0kuFjBT.js +51 -0
- package/dist/file-BX0FSvgE.js +60 -0
- package/dist/file-DadN9dbN.d.ts +19 -0
- package/dist/file.d.ts +2 -0
- package/dist/file.js +2 -0
- package/dist/files.d.ts +15 -0
- package/dist/files.js +38 -0
- package/dist/github.d.ts +20 -0
- package/dist/github.js +1332 -0
- package/dist/glob-BmFqTvJY.js +993 -0
- package/dist/glob.d.ts +23 -0
- package/dist/glob.js +2 -0
- package/dist/index.d.ts +165 -172
- package/dist/index.js +600 -1113
- package/dist/markdown.d.ts +5 -0
- package/dist/markdown.js +10 -0
- package/dist/mcp.d.ts +151 -0
- package/dist/mcp.js +497 -0
- package/dist/mrmime-40h5OOIp.js +448 -0
- package/dist/path-BS8rYm0n.js +1956 -0
- package/dist/path-DOBpV8ol.js +32 -0
- package/dist/server.d.ts +265 -0
- package/dist/server.js +149 -0
- package/dist/sse-D9gqqNPj.js +448 -0
- package/dist/streamableHttp-BL-E7pl5.js +509 -0
- package/dist/types-BigOktIj.d.ts +93 -0
- package/dist/types-CoWcW8oz.js +7590 -0
- package/dist/vite.d.ts +162 -0
- package/dist/vite.js +2284 -0
- package/package.json +102 -17
- package/tsconfig.vite.json +6 -0
- package/types/source/fallback.d.ts +1 -0
- package/types/source/index.d.ts +1 -0
package/dist/vite.js
ADDED
|
@@ -0,0 +1,2284 @@
|
|
|
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";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
6
|
+
import { basename, dirname, extname, isAbsolute, join, parse, relative, resolve } from "node:path";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
import { statSync } from "node:fs";
|
|
9
|
+
import { findExportNames } from "mlly";
|
|
10
|
+
import { parseSync } from "vite";
|
|
11
|
+
//#region ../internal/src/build/vite.ts
|
|
12
|
+
const projectRootDirectoryMarkers = [
|
|
13
|
+
["server", "agents"],
|
|
14
|
+
["server", "channels"],
|
|
15
|
+
["server", "connections"],
|
|
16
|
+
["server", "browsers"],
|
|
17
|
+
["server", "emails"],
|
|
18
|
+
["server", "schedules"],
|
|
19
|
+
["server", "workspaces"]
|
|
20
|
+
];
|
|
21
|
+
const projectRootFileMarkers = [
|
|
22
|
+
["package.json"],
|
|
23
|
+
["nuxt.config.ts"],
|
|
24
|
+
["nuxt.config.mts"],
|
|
25
|
+
["nuxt.config.js"],
|
|
26
|
+
["nuxt.config.mjs"]
|
|
27
|
+
];
|
|
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
|
+
*/
|
|
33
|
+
const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
|
|
34
|
+
function resolveViteHubProjectRoot(root, options = {}) {
|
|
35
|
+
const resolvedRoot = resolve(root);
|
|
36
|
+
const temporaryRoot = resolve(tmpdir());
|
|
37
|
+
const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
|
|
38
|
+
if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
|
|
39
|
+
if (basename(resolvedRoot) === "app") {
|
|
40
|
+
const parent = dirname(resolvedRoot);
|
|
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;
|
|
47
|
+
}
|
|
48
|
+
let current = resolvedRoot;
|
|
49
|
+
while (true) {
|
|
50
|
+
if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
|
|
51
|
+
if (hasProjectRootMarker(current)) return current;
|
|
52
|
+
const parent = dirname(current);
|
|
53
|
+
if (parent === current) return resolvedRoot;
|
|
54
|
+
current = parent;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function hasProjectRootDirectoryMarker(root) {
|
|
58
|
+
for (const marker of projectRootDirectoryMarkers) try {
|
|
59
|
+
if (statSync(resolve(root, ...marker)).isDirectory()) return true;
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (error.code !== "ENOENT") throw error;
|
|
62
|
+
}
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
function hasProjectRootMarker(root) {
|
|
66
|
+
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
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
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
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
|
|
856
|
+
//#region src/vite.ts
|
|
857
|
+
const collectionTypesEntry = ".vitehub/types/source/collections.d.ts";
|
|
858
|
+
const collectionTypesPackageEntry = ".vitehub/types/source/vitehub-source-registry.d.ts";
|
|
859
|
+
const collectionRoutesDirectory = ".vitehub/source/routes";
|
|
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";
|
|
865
|
+
const initialHostRefreshRetryDelay = 25;
|
|
866
|
+
const maximumHostRefreshRetryDelay = 1e3;
|
|
867
|
+
const hostRestartOwnerSettlementTimeout = 3e4;
|
|
868
|
+
async function snapshotDirectoryFiles(directory, files) {
|
|
869
|
+
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
870
|
+
const path = join(directory, entry.name);
|
|
871
|
+
if (entry.isDirectory()) await snapshotDirectoryFiles(path, files);
|
|
872
|
+
else if (entry.isFile()) files.set(path, await readFile(path, "utf8"));
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
async function snapshotGeneratedSourceArtifacts(projectRoot) {
|
|
876
|
+
const files = /* @__PURE__ */ new Map();
|
|
877
|
+
const fixedEntries = [
|
|
878
|
+
collectionTypesEntry,
|
|
879
|
+
collectionTypesPackageEntry,
|
|
880
|
+
contentRouteEntry,
|
|
881
|
+
contentPreviewEntry,
|
|
882
|
+
contentSitemapEntry,
|
|
883
|
+
contentRobotsEntry
|
|
884
|
+
];
|
|
885
|
+
for (const entry of fixedEntries) {
|
|
886
|
+
const path = resolve(projectRoot, entry);
|
|
887
|
+
try {
|
|
888
|
+
files.set(path, await readFile(path, "utf8"));
|
|
889
|
+
} catch (error) {
|
|
890
|
+
if (!(error instanceof Error && Reflect.get(error, "code") === "ENOENT")) throw error;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
const routesDirectory = resolve(projectRoot, collectionRoutesDirectory);
|
|
894
|
+
try {
|
|
895
|
+
await snapshotDirectoryFiles(routesDirectory, files);
|
|
896
|
+
} catch (error) {
|
|
897
|
+
if (!(error instanceof Error && Reflect.get(error, "code") === "ENOENT")) throw error;
|
|
898
|
+
}
|
|
899
|
+
return { files };
|
|
900
|
+
}
|
|
901
|
+
async function restoreGeneratedSourceArtifacts(projectRoot, snapshot) {
|
|
902
|
+
const routesDirectory = resolve(projectRoot, collectionRoutesDirectory);
|
|
903
|
+
await rm(routesDirectory, {
|
|
904
|
+
force: true,
|
|
905
|
+
recursive: true
|
|
906
|
+
});
|
|
907
|
+
for (const entry of [
|
|
908
|
+
collectionTypesEntry,
|
|
909
|
+
collectionTypesPackageEntry,
|
|
910
|
+
contentRouteEntry,
|
|
911
|
+
contentPreviewEntry,
|
|
912
|
+
contentSitemapEntry,
|
|
913
|
+
contentRobotsEntry
|
|
914
|
+
]) {
|
|
915
|
+
const path = resolve(projectRoot, entry);
|
|
916
|
+
if (!snapshot.files.has(path)) await rm(path, { force: true });
|
|
917
|
+
}
|
|
918
|
+
for (const [path, contents] of snapshot.files) {
|
|
919
|
+
await mkdir(dirname(path), { recursive: true });
|
|
920
|
+
await writeFile(path, contents);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
function methodsOverlap(left, right) {
|
|
924
|
+
return !left || !right || left.toLowerCase() === right.toLowerCase();
|
|
925
|
+
}
|
|
926
|
+
function generatedRouteOwner(handler) {
|
|
927
|
+
return handler.route === "/api/content/**" || handler.route === "/sitemap.xml" || handler.route === "/robots.txt" ? "Content" : "Collection";
|
|
928
|
+
}
|
|
929
|
+
function generatedRouteDescription(handler) {
|
|
930
|
+
return handler.method ? `${handler.method.toUpperCase()} handler` : "handler";
|
|
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
|
+
}
|
|
938
|
+
function generatedRouteGuard(generatedHandlers) {
|
|
939
|
+
return {
|
|
940
|
+
name: "vite-hub/generated-route-guard",
|
|
941
|
+
setup(nitro) {
|
|
942
|
+
nitro.hooks.hook("build:before", () => assertGeneratedRoutes(nitro, generatedHandlers));
|
|
943
|
+
}
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
function mergeGeneratedSourceNitroConfig(value, generatedHandlers) {
|
|
947
|
+
const nitro = {};
|
|
948
|
+
if (Object(value) === value && !Array.isArray(value)) Object.assign(nitro, value);
|
|
949
|
+
if (generatedHandlers.length === 0) return nitro;
|
|
950
|
+
const kit = createNitroServerKit(nitro);
|
|
951
|
+
const handlers = kit.config.handlers;
|
|
952
|
+
for (const handler of generatedHandlers) {
|
|
953
|
+
if (handler.plugin) {
|
|
954
|
+
kit.addPlugin(handler.handler);
|
|
955
|
+
continue;
|
|
956
|
+
}
|
|
957
|
+
if (handlers.some((candidate) => candidate.handler === handler.handler && candidate.route === handler.route && candidate.method?.toLowerCase() === handler.method?.toLowerCase())) continue;
|
|
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
|
+
});
|
|
963
|
+
}
|
|
964
|
+
const modules = Array.isArray(nitro.modules) ? [...nitro.modules] : [];
|
|
965
|
+
if (!modules.some((module) => Object(module) === module && Reflect.get(Object(module), "name") === "vite-hub/generated-route-guard")) modules.push(generatedRouteGuard(generatedHandlers));
|
|
966
|
+
kit.config.modules = modules;
|
|
967
|
+
return kit.config;
|
|
968
|
+
}
|
|
969
|
+
function toRuntimeModuleSpecifier(file) {
|
|
970
|
+
return pathToFileURL(file, { windows: /^[A-Z]:[\\/]/i.test(file) }).href;
|
|
971
|
+
}
|
|
972
|
+
function toTypeModuleSpecifier(file) {
|
|
973
|
+
return file.replaceAll("\\", "/");
|
|
974
|
+
}
|
|
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
|
+
}
|
|
1144
|
+
}
|
|
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);
|
|
1147
|
+
}
|
|
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;
|
|
1505
|
+
}
|
|
1506
|
+
async function discoverSourceCollections(options) {
|
|
1507
|
+
const serverDirs = options.serverDirs === void 0 ? [resolve(options.projectRoot, "server")] : options.serverDirs.map((directory) => resolve(options.projectRoot, directory));
|
|
1508
|
+
const collections = (await Promise.all(serverDirs.map(async (serverDir) => {
|
|
1509
|
+
const directory = resolve(serverDir, "collections");
|
|
1510
|
+
return await Promise.all((await collectCollectionFiles(directory)).sort().map(async (file) => {
|
|
1511
|
+
const extension = extname(file);
|
|
1512
|
+
const exportName = basename(file, extension);
|
|
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.` });
|
|
1514
|
+
const name = relative(directory, file).slice(0, -extension.length).replaceAll("\\", "/");
|
|
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.` });
|
|
1517
|
+
return {
|
|
1518
|
+
exportName,
|
|
1519
|
+
file,
|
|
1520
|
+
name,
|
|
1521
|
+
routeEnabled: collectionRouteEnabled(file, source, exportName)
|
|
1522
|
+
};
|
|
1523
|
+
}));
|
|
1524
|
+
}))).flat().sort((left, right) => left.name.localeCompare(right.name));
|
|
1525
|
+
const generatedPaths = /* @__PURE__ */ new Map();
|
|
1526
|
+
for (const collection of collections) {
|
|
1527
|
+
const generatedPath = `${collection.name}.mjs`.toLowerCase();
|
|
1528
|
+
const previous = generatedPaths.get(generatedPath);
|
|
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.` });
|
|
1530
|
+
if (previous) {
|
|
1531
|
+
const [firstName, secondName] = [previous.name, collection.name].sort();
|
|
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.` });
|
|
1533
|
+
}
|
|
1534
|
+
generatedPaths.set(generatedPath, collection);
|
|
1535
|
+
}
|
|
1536
|
+
return collections;
|
|
1537
|
+
}
|
|
1538
|
+
async function writeFileIfChanged(path, contents) {
|
|
1539
|
+
let current;
|
|
1540
|
+
try {
|
|
1541
|
+
current = await readFile(path, "utf8");
|
|
1542
|
+
} catch (error) {
|
|
1543
|
+
if (!(error instanceof Error) || Reflect.get(error, "code") !== "ENOENT") throw error;
|
|
1544
|
+
}
|
|
1545
|
+
if (current === contents) return;
|
|
1546
|
+
await mkdir(dirname(path), { recursive: true });
|
|
1547
|
+
await writeFile(path, contents, "utf8");
|
|
1548
|
+
}
|
|
1549
|
+
async function writeCollectionArtifacts(options, collections) {
|
|
1550
|
+
const output = resolve(options.projectRoot, collectionTypesEntry);
|
|
1551
|
+
const packageOutput = resolve(options.projectRoot, collectionTypesPackageEntry);
|
|
1552
|
+
const routesDirectory = resolve(options.projectRoot, collectionRoutesDirectory);
|
|
1553
|
+
if (collections.length === 0) {
|
|
1554
|
+
await Promise.all([
|
|
1555
|
+
rm(output, { force: true }),
|
|
1556
|
+
rm(packageOutput, { force: true }),
|
|
1557
|
+
rm(routesDirectory, {
|
|
1558
|
+
force: true,
|
|
1559
|
+
recursive: true
|
|
1560
|
+
})
|
|
1561
|
+
]);
|
|
1562
|
+
return [];
|
|
1563
|
+
}
|
|
1564
|
+
const routedCollections = collections.filter((collection) => collection.routeEnabled);
|
|
1565
|
+
await writeFileIfChanged(output, [
|
|
1566
|
+
"declare global {",
|
|
1567
|
+
" interface ViteHubCollectionMap {",
|
|
1568
|
+
...routedCollections.map(({ exportName, file, name }) => ` ${JSON.stringify(name)}: typeof import(${JSON.stringify(toTypeModuleSpecifier(file))})[${JSON.stringify(exportName)}]`),
|
|
1569
|
+
" }",
|
|
1570
|
+
"}",
|
|
1571
|
+
"",
|
|
1572
|
+
"export {}",
|
|
1573
|
+
""
|
|
1574
|
+
].join("\n"));
|
|
1575
|
+
await writeFileIfChanged(packageOutput, "/// <reference path=\"./collections.d.ts\" />\n");
|
|
1576
|
+
const expectedRoutes = new Set(routedCollections.map(({ name }) => resolve(routesDirectory, `${name}.mjs`)));
|
|
1577
|
+
const existingRoutes = await collectCollectionFiles(routesDirectory);
|
|
1578
|
+
await Promise.all(existingRoutes.filter((file) => !expectedRoutes.has(file)).map((file) => rm(file, { force: true })));
|
|
1579
|
+
return await Promise.all(routedCollections.map(async ({ exportName, file, name }) => {
|
|
1580
|
+
const handler = resolve(routesDirectory, `${name}.mjs`);
|
|
1581
|
+
await writeFileIfChanged(handler, [
|
|
1582
|
+
`import { defineCollectionHandler } from ${JSON.stringify(`${options.importBase ?? "@vite-hub/source"}/server`)}`,
|
|
1583
|
+
...options.auth ? [`import { withAuthorization } from ${JSON.stringify(authServerModuleId)}`] : [],
|
|
1584
|
+
`import { ${exportName} as collection } from ${JSON.stringify(toRuntimeModuleSpecifier(file))}`,
|
|
1585
|
+
"",
|
|
1586
|
+
options.auth ? "export default defineCollectionHandler(collection, { withAuthorization })" : "export default defineCollectionHandler(collection)",
|
|
1587
|
+
""
|
|
1588
|
+
].join("\n"));
|
|
1589
|
+
return {
|
|
1590
|
+
handler,
|
|
1591
|
+
method: "get",
|
|
1592
|
+
route: collectionRoutePath(name)
|
|
1593
|
+
};
|
|
1594
|
+
}));
|
|
1595
|
+
}
|
|
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) {
|
|
1601
|
+
const serverDirs = options.serverDirs === void 0 ? [resolve(options.projectRoot, "server")] : options.serverDirs.map((directory) => resolve(options.projectRoot, directory));
|
|
1602
|
+
const candidates = [];
|
|
1603
|
+
for (const serverDir of serverDirs) {
|
|
1604
|
+
let entries;
|
|
1605
|
+
try {
|
|
1606
|
+
entries = await readdir(serverDir, { withFileTypes: true });
|
|
1607
|
+
} catch (error) {
|
|
1608
|
+
if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") continue;
|
|
1609
|
+
throw error;
|
|
1610
|
+
}
|
|
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)));
|
|
1612
|
+
}
|
|
1613
|
+
candidates.sort();
|
|
1614
|
+
if (candidates.length > 1) throw sourceErrorDiagnostics.SOURCE_B0007({ message: "[vitehub] Content is defined in more than one server directory." });
|
|
1615
|
+
const file = candidates[0];
|
|
1616
|
+
if (!file) return;
|
|
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".` });
|
|
1618
|
+
return file;
|
|
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
|
+
}
|
|
1774
|
+
async function writeContentArtifact(options, file) {
|
|
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);
|
|
1779
|
+
if (!file) {
|
|
1780
|
+
await Promise.all([
|
|
1781
|
+
output,
|
|
1782
|
+
preview,
|
|
1783
|
+
sitemap,
|
|
1784
|
+
robots
|
|
1785
|
+
].map((path) => rm(path, { force: true })));
|
|
1786
|
+
return [];
|
|
1787
|
+
}
|
|
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}`,
|
|
1794
|
+
"",
|
|
1795
|
+
"export default defineContentHandler(content)",
|
|
1796
|
+
""
|
|
1797
|
+
].join("\n"));
|
|
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({
|
|
1811
|
+
handler: output,
|
|
1812
|
+
route: "/api/content/**"
|
|
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
|
+
};
|
|
1850
|
+
}
|
|
1851
|
+
async function prepareSourceGeneration(options) {
|
|
1852
|
+
return (await prepareSourceArtifacts(options)).handlers;
|
|
1853
|
+
}
|
|
1854
|
+
function applicationBaseURL(base) {
|
|
1855
|
+
return base?.startsWith("/") && !base.startsWith("//") ? base : "/";
|
|
1856
|
+
}
|
|
1857
|
+
async function generatedHandlerKey(handlers) {
|
|
1858
|
+
return JSON.stringify(await Promise.all(handlers.map(async (handler) => ({
|
|
1859
|
+
...handler,
|
|
1860
|
+
contents: await readFile(handler.handler, "utf8")
|
|
1861
|
+
}))));
|
|
1862
|
+
}
|
|
1863
|
+
function generatedSourceNitroContribution(value, generatedHandlers) {
|
|
1864
|
+
let existing = {};
|
|
1865
|
+
if (Object(value) === value && !Array.isArray(value)) existing = value;
|
|
1866
|
+
const merged = mergeGeneratedSourceNitroConfig(existing, generatedHandlers);
|
|
1867
|
+
const handlers = merged.handlers?.slice(Array.isArray(existing.handlers) ? existing.handlers.length : 0);
|
|
1868
|
+
const modules = merged.modules?.slice(Array.isArray(existing.modules) ? existing.modules.length : 0);
|
|
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;
|
|
1876
|
+
}
|
|
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;
|
|
1880
|
+
return (serverDirs === void 0 ? [resolve(projectRoot, "server")] : serverDirs).some((directory) => {
|
|
1881
|
+
const path = relative(resolve(projectRoot, directory), resolve(file)).replaceAll("\\", "/");
|
|
1882
|
+
if (path.startsWith("../") || isAbsolute(path)) return false;
|
|
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);
|
|
1884
|
+
});
|
|
1885
|
+
}
|
|
1886
|
+
function hubSource(options = {}) {
|
|
1887
|
+
const refreshAuthByRoot = /* @__PURE__ */ new Map();
|
|
1888
|
+
let nitroHost;
|
|
1889
|
+
let nitroHostContribution;
|
|
1890
|
+
const nitroHandlers = [];
|
|
1891
|
+
let latestProjectRoot;
|
|
1892
|
+
const configuredStateByRoot = /* @__PURE__ */ new Map();
|
|
1893
|
+
const closeHostRefreshByEnvironment = /* @__PURE__ */ new WeakMap();
|
|
1894
|
+
const hostRefreshLifecycleByRoot = /* @__PURE__ */ new Map();
|
|
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
|
+
};
|
|
1901
|
+
const configurationTransitionByRoot = /* @__PURE__ */ new Map();
|
|
1902
|
+
let legacyServerBuild = false;
|
|
1903
|
+
const generatedHandlersListeners = /* @__PURE__ */ new Set();
|
|
1904
|
+
const prepareSources = (input, configuredAuth) => {
|
|
1905
|
+
const root = resolve(input.projectRoot);
|
|
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);
|
|
1927
|
+
sourcePreparationByRoot.set(root, preparation);
|
|
1928
|
+
preparation.finally(() => {
|
|
1929
|
+
if (sourcePreparationByRoot.get(root) === preparation) sourcePreparationByRoot.delete(root);
|
|
1930
|
+
}).catch(() => {});
|
|
1931
|
+
return preparation;
|
|
1932
|
+
};
|
|
1933
|
+
const refresh = async (viteConfig) => {
|
|
1934
|
+
const projectRoot = viteConfig?.["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : viteConfig?.root ? resolveViteHubProjectRoot(viteConfig.root) : latestProjectRoot;
|
|
1935
|
+
if (!projectRoot) return;
|
|
1936
|
+
await prepareSources({
|
|
1937
|
+
projectRoot,
|
|
1938
|
+
serverDirs: configuredStateByRoot.get(projectRoot)?.serverDirs
|
|
1939
|
+
});
|
|
1940
|
+
};
|
|
1941
|
+
const onGeneratedHandlersChanged = (listener, listenerOptions = {}) => {
|
|
1942
|
+
const registration = {
|
|
1943
|
+
...listenerOptions,
|
|
1944
|
+
listener,
|
|
1945
|
+
projectRoot: listenerOptions.projectRoot ? resolve(listenerOptions.projectRoot) : latestProjectRoot
|
|
1946
|
+
};
|
|
1947
|
+
generatedHandlersListeners.add(registration);
|
|
1948
|
+
return () => generatedHandlersListeners.delete(registration);
|
|
1949
|
+
};
|
|
1950
|
+
const bindUnresolvedListenerRoots = (root) => {
|
|
1951
|
+
for (const listenerOptions of generatedHandlersListeners.values()) listenerOptions.projectRoot ??= root;
|
|
1952
|
+
};
|
|
1953
|
+
const replaceConfiguredNitroContribution = (value, handlers, configuredNitroContribution) => {
|
|
1954
|
+
let nitro = {};
|
|
1955
|
+
if (Object(value) === value && !Array.isArray(value)) nitro = { ...value };
|
|
1956
|
+
const contributedHandlers = configuredNitroContribution?.handlers ?? [];
|
|
1957
|
+
if (Array.isArray(nitro.handlers) && contributedHandlers.length > 0) nitro.handlers = nitro.handlers.filter((handler) => !contributedHandlers.includes(handler));
|
|
1958
|
+
const contributedModules = configuredNitroContribution?.modules ?? [];
|
|
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));
|
|
1962
|
+
return mergeGeneratedSourceNitroConfig(nitro, handlers);
|
|
1963
|
+
};
|
|
1964
|
+
return {
|
|
1965
|
+
name: "@vite-hub/source/vite",
|
|
1966
|
+
enforce: "post",
|
|
1967
|
+
api: {
|
|
1968
|
+
getContentDefinition,
|
|
1969
|
+
onGeneratedHandlersChanged,
|
|
1970
|
+
prepareSources
|
|
1971
|
+
},
|
|
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) {
|
|
2025
|
+
const viteConfig = config;
|
|
2026
|
+
if (viteConfig["__vitehubNitroConfigContext"]) return;
|
|
2027
|
+
legacyServerBuild = env.command === "build" && config.build?.ssr === true;
|
|
2028
|
+
const projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(viteConfig.root || process.cwd());
|
|
2029
|
+
latestProjectRoot = projectRoot;
|
|
2030
|
+
bindUnresolvedListenerRoots(projectRoot);
|
|
2031
|
+
const serverDirs = viteConfig[VITEHUB_SERVER_DIRS];
|
|
2032
|
+
const previousTransition = configurationTransitionByRoot.get(projectRoot) ?? Promise.resolve();
|
|
2033
|
+
const runTransition = async () => {
|
|
2034
|
+
const previousLifecycle = hostRefreshLifecycleByRoot.get(projectRoot);
|
|
2035
|
+
const previousConfiguredState = configuredStateByRoot.get(projectRoot);
|
|
2036
|
+
previousLifecycle?.pause();
|
|
2037
|
+
try {
|
|
2038
|
+
const handlers = await prepareSources({
|
|
2039
|
+
projectRoot,
|
|
2040
|
+
serverDirs
|
|
2041
|
+
}, viteConfig.auth === false ? false : viteConfig.auth ? true : void 0);
|
|
2042
|
+
const handlerKey = await generatedHandlerKey(handlers);
|
|
2043
|
+
const nitro = generatedSourceNitroContribution(viteConfig.nitro, handlers);
|
|
2044
|
+
configuredStateByRoot.set(projectRoot, {
|
|
2045
|
+
configuredAuth: viteConfig.auth === false ? false : viteConfig.auth ? true : void 0,
|
|
2046
|
+
handlerKey,
|
|
2047
|
+
nitroContribution: nitro,
|
|
2048
|
+
serverDirs: serverDirs?.slice()
|
|
2049
|
+
});
|
|
2050
|
+
const contribution = {
|
|
2051
|
+
define: { __VITEHUB_APP_BASE_URL__: JSON.stringify(applicationBaseURL(viteConfig.base)) },
|
|
2052
|
+
...nitro ? { nitro } : {}
|
|
2053
|
+
};
|
|
2054
|
+
previousLifecycle?.close();
|
|
2055
|
+
return contribution;
|
|
2056
|
+
} catch (error) {
|
|
2057
|
+
try {
|
|
2058
|
+
if (previousConfiguredState) await prepareSources({
|
|
2059
|
+
projectRoot,
|
|
2060
|
+
serverDirs: previousConfiguredState.serverDirs
|
|
2061
|
+
});
|
|
2062
|
+
} finally {
|
|
2063
|
+
previousLifecycle?.resume();
|
|
2064
|
+
}
|
|
2065
|
+
throw error;
|
|
2066
|
+
}
|
|
2067
|
+
};
|
|
2068
|
+
const transition = previousTransition.then(runTransition, runTransition);
|
|
2069
|
+
configurationTransitionByRoot.set(projectRoot, transition);
|
|
2070
|
+
transition.finally(() => {
|
|
2071
|
+
if (configurationTransitionByRoot.get(projectRoot) === transition) configurationTransitionByRoot.delete(projectRoot);
|
|
2072
|
+
}).catch(() => {});
|
|
2073
|
+
return transition;
|
|
2074
|
+
},
|
|
2075
|
+
async configResolved(config) {
|
|
2076
|
+
const viteConfig = config;
|
|
2077
|
+
const projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(config.root);
|
|
2078
|
+
latestProjectRoot = projectRoot;
|
|
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));
|
|
2086
|
+
const previousTransition = configurationTransitionByRoot.get(projectRoot) ?? Promise.resolve();
|
|
2087
|
+
const runTransition = async () => {
|
|
2088
|
+
const configuredState = configuredStateByRoot.get(projectRoot);
|
|
2089
|
+
const serverDirs = viteConfig["__vitehubServerDirs"] ?? configuredState?.serverDirs;
|
|
2090
|
+
const handlers = await prepareSources({
|
|
2091
|
+
projectRoot,
|
|
2092
|
+
serverDirs
|
|
2093
|
+
}, viteConfig.auth === false ? false : viteConfig.auth ? true : void 0);
|
|
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
|
+
}
|
|
2107
|
+
configuredStateByRoot.set(projectRoot, {
|
|
2108
|
+
configuredAuth: viteConfig.auth === false ? false : viteConfig.auth ? true : void 0,
|
|
2109
|
+
handlerKey,
|
|
2110
|
+
nitroContribution: configuredState?.nitroContribution,
|
|
2111
|
+
serverDirs: serverDirs?.slice()
|
|
2112
|
+
});
|
|
2113
|
+
if (!viteConfig["__vitehubNitroConfigContext"]) viteConfig.nitro = replaceConfiguredNitroContribution(viteConfig.nitro, handlers, configuredState?.nitroContribution);
|
|
2114
|
+
};
|
|
2115
|
+
const transition = previousTransition.then(runTransition, runTransition);
|
|
2116
|
+
configurationTransitionByRoot.set(projectRoot, transition);
|
|
2117
|
+
transition.finally(() => {
|
|
2118
|
+
if (configurationTransitionByRoot.get(projectRoot) === transition) configurationTransitionByRoot.delete(projectRoot);
|
|
2119
|
+
}).catch(() => {});
|
|
2120
|
+
return transition;
|
|
2121
|
+
},
|
|
2122
|
+
configureServer(server) {
|
|
2123
|
+
const viteConfig = server.config;
|
|
2124
|
+
const root = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(server.config.root ?? latestProjectRoot ?? process.cwd());
|
|
2125
|
+
const configuredState = configuredStateByRoot.get(root);
|
|
2126
|
+
const lifecycleServerDirs = configuredState?.serverDirs?.slice();
|
|
2127
|
+
let activeHandlerKey = configuredState?.handlerKey ?? "[]";
|
|
2128
|
+
const effectiveServerDirs = lifecycleServerDirs === void 0 ? root ? [resolve(root, "server")] : [] : root ? lifecycleServerDirs.map((directory) => resolve(root, directory)) : [];
|
|
2129
|
+
server.watcher.add(effectiveServerDirs);
|
|
2130
|
+
let hostRefreshRetry;
|
|
2131
|
+
let pausedHostRefreshRetryFile;
|
|
2132
|
+
let hostRefreshRetryDelay = initialHostRefreshRetryDelay;
|
|
2133
|
+
let refreshQueue = Promise.resolve();
|
|
2134
|
+
let serverClosed = false;
|
|
2135
|
+
let serverPaused = false;
|
|
2136
|
+
const clearHostRefreshRetry = () => {
|
|
2137
|
+
if (hostRefreshRetry) clearTimeout(hostRefreshRetry);
|
|
2138
|
+
hostRefreshRetry = void 0;
|
|
2139
|
+
};
|
|
2140
|
+
const closeHostRefresh = () => {
|
|
2141
|
+
serverClosed = true;
|
|
2142
|
+
clearHostRefreshRetry();
|
|
2143
|
+
if (root && hostRefreshLifecycleByRoot.get(root)?.close === closeHostRefresh) hostRefreshLifecycleByRoot.delete(root);
|
|
2144
|
+
};
|
|
2145
|
+
if (root) {
|
|
2146
|
+
hostRefreshLifecycleByRoot.get(root)?.close();
|
|
2147
|
+
hostRefreshLifecycleByRoot.set(root, {
|
|
2148
|
+
close: closeHostRefresh,
|
|
2149
|
+
pause: () => {
|
|
2150
|
+
serverPaused = true;
|
|
2151
|
+
},
|
|
2152
|
+
resume: () => {
|
|
2153
|
+
serverPaused = false;
|
|
2154
|
+
if (pausedHostRefreshRetryFile) {
|
|
2155
|
+
const file = pausedHostRefreshRetryFile;
|
|
2156
|
+
pausedHostRefreshRetryFile = void 0;
|
|
2157
|
+
scheduleHostRefreshRetry(file);
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
});
|
|
2161
|
+
}
|
|
2162
|
+
for (const environment of Object.values(server.environments)) closeHostRefreshByEnvironment.set(environment, closeHostRefresh);
|
|
2163
|
+
const scheduleHostRefreshRetry = (file) => {
|
|
2164
|
+
if (hostRefreshRetry) return;
|
|
2165
|
+
hostRefreshRetry = setTimeout(() => {
|
|
2166
|
+
hostRefreshRetry = void 0;
|
|
2167
|
+
if (serverClosed) return;
|
|
2168
|
+
if (serverPaused) {
|
|
2169
|
+
pausedHostRefreshRetryFile = file;
|
|
2170
|
+
return;
|
|
2171
|
+
}
|
|
2172
|
+
queueHostRefresh(file);
|
|
2173
|
+
}, hostRefreshRetryDelay);
|
|
2174
|
+
hostRefreshRetry.unref?.();
|
|
2175
|
+
hostRefreshRetryDelay = Math.min(hostRefreshRetryDelay * 2, maximumHostRefreshRetryDelay);
|
|
2176
|
+
};
|
|
2177
|
+
function queueHostRefresh(file) {
|
|
2178
|
+
if (serverClosed || !root || !sourceDefinitionPath(file, root, lifecycleServerDirs)) return;
|
|
2179
|
+
if (serverPaused) {
|
|
2180
|
+
pausedHostRefreshRetryFile = file;
|
|
2181
|
+
return;
|
|
2182
|
+
}
|
|
2183
|
+
const result = refreshQueue.then(async () => {
|
|
2184
|
+
if (serverClosed) return;
|
|
2185
|
+
if (serverPaused) {
|
|
2186
|
+
pausedHostRefreshRetryFile = file;
|
|
2187
|
+
return;
|
|
2188
|
+
}
|
|
2189
|
+
const previousArtifacts = await snapshotGeneratedSourceArtifacts(root);
|
|
2190
|
+
const handlers = await prepareSources({
|
|
2191
|
+
projectRoot: root,
|
|
2192
|
+
serverDirs: lifecycleServerDirs
|
|
2193
|
+
});
|
|
2194
|
+
if (serverClosed) return;
|
|
2195
|
+
if (serverPaused) {
|
|
2196
|
+
pausedHostRefreshRetryFile = file;
|
|
2197
|
+
return;
|
|
2198
|
+
}
|
|
2199
|
+
const handlerKey = await generatedHandlerKey(handlers);
|
|
2200
|
+
if (serverClosed) return;
|
|
2201
|
+
if (serverPaused) {
|
|
2202
|
+
pausedHostRefreshRetryFile = file;
|
|
2203
|
+
return;
|
|
2204
|
+
}
|
|
2205
|
+
if (handlerKey === activeHandlerKey) return;
|
|
2206
|
+
const listeners = [...generatedHandlersListeners].filter((listenerOptions) => listenerOptions.projectRoot === root);
|
|
2207
|
+
const passiveListeners = listeners.filter((listenerOptions) => !listenerOptions.handlesHostRestart);
|
|
2208
|
+
for (const { listener } of passiveListeners) Promise.resolve().then(() => listener(handlers)).catch((error) => server.config.logger.error(String(error)));
|
|
2209
|
+
const hostRestartOwners = listeners.filter((listenerOptions) => listenerOptions.handlesHostRestart);
|
|
2210
|
+
const listenerResults = hostRestartOwners.map(async ({ listener }) => {
|
|
2211
|
+
try {
|
|
2212
|
+
await listener(handlers);
|
|
2213
|
+
return true;
|
|
2214
|
+
} catch (error) {
|
|
2215
|
+
server.config.logger.error(String(error));
|
|
2216
|
+
return false;
|
|
2217
|
+
}
|
|
2218
|
+
});
|
|
2219
|
+
let ownerSettlementTimeout;
|
|
2220
|
+
const hostRestartHandled = await Promise.race([
|
|
2221
|
+
Promise.all(listenerResults).then((results) => results.some(Boolean)),
|
|
2222
|
+
Promise.any(listenerResults.map(async (result) => await result || Promise.reject())).then(() => true, () => false),
|
|
2223
|
+
new Promise((resolve) => {
|
|
2224
|
+
ownerSettlementTimeout = setTimeout(() => resolve(false), hostRestartOwnerSettlementTimeout);
|
|
2225
|
+
ownerSettlementTimeout.unref?.();
|
|
2226
|
+
})
|
|
2227
|
+
]);
|
|
2228
|
+
if (ownerSettlementTimeout) clearTimeout(ownerSettlementTimeout);
|
|
2229
|
+
if (serverClosed) return;
|
|
2230
|
+
const hasHostRestartOwner = hostRestartOwners.length > 0;
|
|
2231
|
+
if (hasHostRestartOwner && !hostRestartHandled) {
|
|
2232
|
+
await restoreGeneratedSourceArtifacts(root, previousArtifacts);
|
|
2233
|
+
scheduleHostRefreshRetry(file);
|
|
2234
|
+
return;
|
|
2235
|
+
}
|
|
2236
|
+
if (!hasHostRestartOwner) {
|
|
2237
|
+
const previousEnvironments = server.environments;
|
|
2238
|
+
try {
|
|
2239
|
+
await server.restart();
|
|
2240
|
+
} catch (error) {
|
|
2241
|
+
if (serverClosed) return;
|
|
2242
|
+
await restoreGeneratedSourceArtifacts(root, previousArtifacts);
|
|
2243
|
+
scheduleHostRefreshRetry(file);
|
|
2244
|
+
throw error;
|
|
2245
|
+
}
|
|
2246
|
+
if (serverClosed) return;
|
|
2247
|
+
if (server.environments === previousEnvironments) {
|
|
2248
|
+
await restoreGeneratedSourceArtifacts(root, previousArtifacts);
|
|
2249
|
+
scheduleHostRefreshRetry(file);
|
|
2250
|
+
return;
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
activeHandlerKey = handlerKey;
|
|
2254
|
+
clearHostRefreshRetry();
|
|
2255
|
+
hostRefreshRetryDelay = initialHostRefreshRetryDelay;
|
|
2256
|
+
});
|
|
2257
|
+
refreshQueue = result.catch(() => {});
|
|
2258
|
+
result.catch((error) => server.config.logger.error(String(error)));
|
|
2259
|
+
return result;
|
|
2260
|
+
}
|
|
2261
|
+
const refreshHost = (file) => {
|
|
2262
|
+
if (!root || !sourceDefinitionPath(file, root, lifecycleServerDirs)) return;
|
|
2263
|
+
clearHostRefreshRetry();
|
|
2264
|
+
hostRefreshRetryDelay = initialHostRefreshRetryDelay;
|
|
2265
|
+
return queueHostRefresh(file);
|
|
2266
|
+
};
|
|
2267
|
+
server.watcher.on("add", refreshHost);
|
|
2268
|
+
server.watcher.on("change", refreshHost);
|
|
2269
|
+
server.watcher.on("unlink", refreshHost);
|
|
2270
|
+
},
|
|
2271
|
+
buildStart() {
|
|
2272
|
+
return refresh(this.environment?.config);
|
|
2273
|
+
},
|
|
2274
|
+
buildEnd() {
|
|
2275
|
+
return refresh(this.environment?.config);
|
|
2276
|
+
},
|
|
2277
|
+
closeBundle() {
|
|
2278
|
+
closeHostRefreshByEnvironment.get(this.environment)?.();
|
|
2279
|
+
closeHostRefreshByEnvironment.delete(this.environment);
|
|
2280
|
+
}
|
|
2281
|
+
};
|
|
2282
|
+
}
|
|
2283
|
+
//#endregion
|
|
2284
|
+
export { findContentEntry, hubSource, inspectCollectionDefinitions, inspectContentEntry, inspectContentModule, mergeGeneratedSourceNitroConfig, prepareSourceGeneration, toRuntimeModuleSpecifier, toTypeModuleSpecifier };
|