@vite-hub/source 0.0.2 → 0.0.4
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 +167 -1
- package/dist/auth-Ddw55OUG.js +1261 -0
- package/dist/client-CDfTmtQu.js +7903 -0
- package/dist/client.d.ts +32 -0
- package/dist/client.js +121 -0
- package/dist/collection-B8pXGM2d.js +141 -0
- package/dist/collection-CF2ON__k.d.ts +92 -0
- package/dist/collection-route-Dw7QLFyx.js +6 -0
- package/dist/content/client.d.ts +3 -0
- package/dist/content/client.js +2 -0
- package/dist/content.d.ts +44 -0
- package/dist/content.js +157 -0
- package/dist/file-BSWQg9Qv.js +503 -0
- package/dist/{file-slFAccIZ.d.ts → file-EQ3AjVM6.d.ts} +1 -1
- package/dist/file.d.ts +2 -0
- package/dist/file.js +2 -0
- package/dist/{index-CJpN2j6c.d.ts → github.d.ts} +4 -4
- package/dist/github.js +1033 -0
- package/dist/glob.d.ts +15 -0
- package/dist/glob.js +895 -0
- package/dist/index.d.ts +69 -10
- package/dist/index.js +70 -108
- package/dist/{markdown-Beo-0cqc.d.ts → markdown.d.ts} +3 -3
- package/dist/{sources/markdown.js → markdown.js} +1 -1
- package/dist/mcp.d.ts +152 -0
- package/dist/mcp.js +6115 -0
- package/dist/{path-B5QNI5sY.js → path-BzmU4Eni.js} +2 -10
- package/dist/path-CUhvUREm.js +1936 -0
- package/dist/registry-C8skfCSV.js +120 -0
- package/dist/server.d.ts +15 -0
- package/dist/server.js +71 -0
- package/dist/sse-CE9Q2JqM.js +407 -0
- package/dist/streamableHttp-BszaXLmg.js +491 -0
- package/dist/types-AIBmt_m6.js +6275 -0
- package/dist/types-Bu3WvNX9.d.ts +71 -0
- package/dist/vite.d.ts +41 -0
- package/dist/vite.js +629 -0
- package/package.json +68 -30
- package/tsconfig.vite.json +6 -0
- package/types/source/fallback.d.ts +1 -0
- package/types/source/index.d.ts +1 -0
- package/dist/chunk-D7D4PA-g.js +0 -13
- package/dist/custom-EnZvMLiy.d.ts +0 -6
- package/dist/github-B4lgrzXQ.js +0 -565
- package/dist/glob-CuxZwoC3.d.ts +0 -15
- package/dist/mcp-resources-C7-5Qeh4.d.ts +0 -41
- package/dist/mcp-resources-DSDqTfbK.js +0 -307
- package/dist/sources/custom.d.ts +0 -2
- package/dist/sources/custom.js +0 -6
- package/dist/sources/file.d.ts +0 -2
- package/dist/sources/file.js +0 -57
- package/dist/sources/github.d.ts +0 -2
- package/dist/sources/github.js +0 -2
- package/dist/sources/glob.d.ts +0 -2
- package/dist/sources/glob.js +0 -110
- package/dist/sources/index.d.ts +0 -13
- package/dist/sources/index.js +0 -18
- package/dist/sources/markdown.d.ts +0 -2
- package/dist/sources/mcp-resources.d.ts +0 -2
- package/dist/sources/mcp-resources.js +0 -2
- package/dist/types-f6Lyjq8g.d.ts +0 -73
package/dist/vite.js
ADDED
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
import { t as encodeCollectionRouteSegment } from "./collection-route-Dw7QLFyx.js";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { basename, dirname, extname, isAbsolute, join, parse, relative, resolve } from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { statSync } from "node:fs";
|
|
7
|
+
import { findExportNames } from "mlly";
|
|
8
|
+
//#region ../internal/src/build/vite.ts
|
|
9
|
+
const projectRootDirectoryMarkers = [
|
|
10
|
+
["server", "agents"],
|
|
11
|
+
["server", "channels"],
|
|
12
|
+
["server", "browsers"],
|
|
13
|
+
["server", "emails"],
|
|
14
|
+
["server", "schedules"],
|
|
15
|
+
["server", "workspaces"]
|
|
16
|
+
];
|
|
17
|
+
const projectRootFileMarkers = [["package.json"]];
|
|
18
|
+
const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
|
|
19
|
+
const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
|
|
20
|
+
function resolveViteHubProjectRoot(root, options = {}) {
|
|
21
|
+
const resolvedRoot = resolve(root);
|
|
22
|
+
const temporaryRoot = resolve(tmpdir());
|
|
23
|
+
const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
|
|
24
|
+
if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
|
|
25
|
+
if (basename(resolvedRoot) === "app") {
|
|
26
|
+
const parent = dirname(resolvedRoot);
|
|
27
|
+
if (parent !== sharedTemporaryRoot && hasProjectRootDirectoryMarker(parent)) return parent;
|
|
28
|
+
}
|
|
29
|
+
let current = resolvedRoot;
|
|
30
|
+
while (true) {
|
|
31
|
+
if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
|
|
32
|
+
if (hasProjectRootMarker(current)) return current;
|
|
33
|
+
const parent = dirname(current);
|
|
34
|
+
if (parent === current) return resolvedRoot;
|
|
35
|
+
current = parent;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function hasProjectRootDirectoryMarker(root) {
|
|
39
|
+
for (const marker of projectRootDirectoryMarkers) try {
|
|
40
|
+
if (statSync(resolve(root, ...marker)).isDirectory()) return true;
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (error.code !== "ENOENT") throw error;
|
|
43
|
+
}
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
function hasProjectRootMarker(root) {
|
|
47
|
+
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
48
|
+
for (const marker of projectRootFileMarkers) try {
|
|
49
|
+
if (statSync(resolve(root, ...marker)).isFile()) return true;
|
|
50
|
+
} catch (error) {
|
|
51
|
+
if (error.code !== "ENOENT") throw error;
|
|
52
|
+
}
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
//#endregion
|
|
56
|
+
//#region src/vite.ts
|
|
57
|
+
const collectionTypesEntry = ".vitehub/types/source/collections.d.ts";
|
|
58
|
+
const collectionTypesPackageEntry = ".vitehub/types/source/vitehub-source-registry.d.ts";
|
|
59
|
+
const legacyCollectionTypesEntry = ".vitehub/source/collections.d.ts";
|
|
60
|
+
const collectionRoutesDirectory = ".vitehub/source/routes";
|
|
61
|
+
const contentRouteEntry = ".vitehub/content/route.mjs";
|
|
62
|
+
const initialHostRefreshRetryDelay = 25;
|
|
63
|
+
const maximumHostRefreshRetryDelay = 1e3;
|
|
64
|
+
const hostRestartOwnerSettlementTimeout = 3e4;
|
|
65
|
+
async function snapshotDirectoryFiles(directory, files) {
|
|
66
|
+
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
67
|
+
const path = join(directory, entry.name);
|
|
68
|
+
if (entry.isDirectory()) await snapshotDirectoryFiles(path, files);
|
|
69
|
+
else if (entry.isFile()) files.set(path, await readFile(path, "utf8"));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function snapshotGeneratedSourceArtifacts(projectRoot) {
|
|
73
|
+
const files = /* @__PURE__ */ new Map();
|
|
74
|
+
const fixedEntries = [
|
|
75
|
+
collectionTypesEntry,
|
|
76
|
+
collectionTypesPackageEntry,
|
|
77
|
+
legacyCollectionTypesEntry,
|
|
78
|
+
contentRouteEntry
|
|
79
|
+
];
|
|
80
|
+
for (const entry of fixedEntries) {
|
|
81
|
+
const path = resolve(projectRoot, entry);
|
|
82
|
+
try {
|
|
83
|
+
files.set(path, await readFile(path, "utf8"));
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (!(error instanceof Error && Reflect.get(error, "code") === "ENOENT")) throw error;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const routesDirectory = resolve(projectRoot, collectionRoutesDirectory);
|
|
89
|
+
try {
|
|
90
|
+
await snapshotDirectoryFiles(routesDirectory, files);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (!(error instanceof Error && Reflect.get(error, "code") === "ENOENT")) throw error;
|
|
93
|
+
}
|
|
94
|
+
return { files };
|
|
95
|
+
}
|
|
96
|
+
async function restoreGeneratedSourceArtifacts(projectRoot, snapshot) {
|
|
97
|
+
await rm(resolve(projectRoot, collectionRoutesDirectory), {
|
|
98
|
+
force: true,
|
|
99
|
+
recursive: true
|
|
100
|
+
});
|
|
101
|
+
for (const entry of [
|
|
102
|
+
collectionTypesEntry,
|
|
103
|
+
collectionTypesPackageEntry,
|
|
104
|
+
legacyCollectionTypesEntry,
|
|
105
|
+
contentRouteEntry
|
|
106
|
+
]) {
|
|
107
|
+
const path = resolve(projectRoot, entry);
|
|
108
|
+
if (!snapshot.files.has(path)) await rm(path, { force: true });
|
|
109
|
+
}
|
|
110
|
+
for (const [path, contents] of snapshot.files) {
|
|
111
|
+
await mkdir(dirname(path), { recursive: true });
|
|
112
|
+
await writeFile(path, contents);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function methodsOverlap(left, right) {
|
|
116
|
+
return !left || !right || left.toLowerCase() === right.toLowerCase();
|
|
117
|
+
}
|
|
118
|
+
function generatedRouteOwner(handler) {
|
|
119
|
+
return handler.route === "/api/content/**" ? "Content" : "Collection";
|
|
120
|
+
}
|
|
121
|
+
function generatedRouteDescription(handler) {
|
|
122
|
+
return handler.method ? `${handler.method.toUpperCase()} handler` : "handler";
|
|
123
|
+
}
|
|
124
|
+
function generatedRouteGuard(generatedHandlers) {
|
|
125
|
+
return {
|
|
126
|
+
name: "vite-hub/generated-route-guard",
|
|
127
|
+
setup(nitro) {
|
|
128
|
+
nitro.hooks.hook("build:before", () => {
|
|
129
|
+
for (const generatedHandler of generatedHandlers) if (nitro.scannedHandlers.some((candidate) => candidate.route === generatedHandler.route && methodsOverlap(candidate.method, generatedHandler.method))) throw new TypeError(`[vitehub] Generated ${generatedRouteOwner(generatedHandler)} route ${JSON.stringify(generatedHandler.route)} conflicts with an existing ${generatedRouteDescription(generatedHandler)}. Remove the matching server route.`);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
function mergeGeneratedSourceNitroConfig(value, generatedHandlers) {
|
|
135
|
+
const nitro = {};
|
|
136
|
+
if (Object(value) === value && !Array.isArray(value)) Object.assign(nitro, value);
|
|
137
|
+
if (generatedHandlers.length === 0) return nitro;
|
|
138
|
+
const handlers = Array.isArray(nitro.handlers) ? [...nitro.handlers] : [];
|
|
139
|
+
for (const handler of generatedHandlers) {
|
|
140
|
+
if (handlers.some((candidate) => candidate.handler === handler.handler && candidate.route === handler.route && candidate.method?.toLowerCase() === handler.method?.toLowerCase())) continue;
|
|
141
|
+
if (handlers.some((candidate) => candidate.route === handler.route && methodsOverlap(candidate.method, handler.method))) throw new TypeError(`[vitehub] Generated ${generatedRouteOwner(handler)} route ${JSON.stringify(handler.route)} conflicts with an existing ${generatedRouteDescription(handler)}. Remove the matching server route.`);
|
|
142
|
+
handlers.push(handler);
|
|
143
|
+
}
|
|
144
|
+
const modules = Array.isArray(nitro.modules) ? [...nitro.modules] : [];
|
|
145
|
+
if (!modules.some((module) => Object(module) === module && Reflect.get(Object(module), "name") === "vite-hub/generated-route-guard")) modules.push(generatedRouteGuard(generatedHandlers));
|
|
146
|
+
return {
|
|
147
|
+
...nitro,
|
|
148
|
+
handlers,
|
|
149
|
+
modules
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function toRuntimeModuleSpecifier(file) {
|
|
153
|
+
return pathToFileURL(file, { windows: /^[A-Z]:[\\/]/i.test(file) }).href;
|
|
154
|
+
}
|
|
155
|
+
function toTypeModuleSpecifier(file) {
|
|
156
|
+
return file.replaceAll("\\", "/");
|
|
157
|
+
}
|
|
158
|
+
async function collectCollectionFiles(directory) {
|
|
159
|
+
let entries;
|
|
160
|
+
try {
|
|
161
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
162
|
+
} catch (error) {
|
|
163
|
+
if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") return [];
|
|
164
|
+
throw error;
|
|
165
|
+
}
|
|
166
|
+
const files = [];
|
|
167
|
+
for (const entry of entries) {
|
|
168
|
+
const path = join(directory, entry.name);
|
|
169
|
+
if (entry.isDirectory()) files.push(...await collectCollectionFiles(path));
|
|
170
|
+
else if (entry.isFile() && /\.(?:[cm]?[jt]s)$/.test(entry.name) && !/\.d\.[cm]?ts$/.test(entry.name)) files.push(path);
|
|
171
|
+
}
|
|
172
|
+
return files;
|
|
173
|
+
}
|
|
174
|
+
async function discoverCollections(options) {
|
|
175
|
+
const serverDirs = options.serverDirs === void 0 ? [resolve(options.projectRoot, "server")] : options.serverDirs.map((directory) => resolve(options.projectRoot, directory));
|
|
176
|
+
const collections = (await Promise.all(serverDirs.map(async (serverDir) => {
|
|
177
|
+
const directory = resolve(serverDir, "collections");
|
|
178
|
+
return await Promise.all((await collectCollectionFiles(directory)).sort().map(async (file) => {
|
|
179
|
+
const extension = extname(file);
|
|
180
|
+
const exportName = basename(file, extension);
|
|
181
|
+
if (!/^[A-Z_$][\w$]*$/i.test(exportName)) throw new TypeError(`[vitehub] Collection file ${JSON.stringify(relative(options.projectRoot, file))} must use a valid JavaScript identifier as its filename.`);
|
|
182
|
+
const name = relative(directory, file).slice(0, -extension.length).replaceAll("\\", "/");
|
|
183
|
+
if (!findExportNames(await readFile(file, "utf8")).includes(exportName)) throw new TypeError(`[vitehub] Collection file ${JSON.stringify(relative(options.projectRoot, file))} must export a Collection named ${JSON.stringify(exportName)} to match its filename.`);
|
|
184
|
+
return {
|
|
185
|
+
exportName,
|
|
186
|
+
file,
|
|
187
|
+
name
|
|
188
|
+
};
|
|
189
|
+
}));
|
|
190
|
+
}))).flat().sort((left, right) => left.name.localeCompare(right.name));
|
|
191
|
+
const generatedPaths = /* @__PURE__ */ new Map();
|
|
192
|
+
for (const collection of collections) {
|
|
193
|
+
const generatedPath = `${collection.name}.mjs`.toLowerCase();
|
|
194
|
+
const previous = generatedPaths.get(generatedPath);
|
|
195
|
+
if (previous?.name === collection.name) throw new TypeError(`[vitehub] Collection name ${JSON.stringify(collection.name)} is defined in more than one server directory.`);
|
|
196
|
+
if (previous) {
|
|
197
|
+
const [firstName, secondName] = [previous.name, collection.name].sort();
|
|
198
|
+
throw new TypeError(`[vitehub] Collection names ${JSON.stringify(firstName)} and ${JSON.stringify(secondName)} generate the same route module on case-insensitive filesystems.`);
|
|
199
|
+
}
|
|
200
|
+
generatedPaths.set(generatedPath, collection);
|
|
201
|
+
}
|
|
202
|
+
return collections;
|
|
203
|
+
}
|
|
204
|
+
async function writeFileIfChanged(path, contents) {
|
|
205
|
+
let current;
|
|
206
|
+
try {
|
|
207
|
+
current = await readFile(path, "utf8");
|
|
208
|
+
} catch (error) {
|
|
209
|
+
if (!(error instanceof Error) || Reflect.get(error, "code") !== "ENOENT") throw error;
|
|
210
|
+
}
|
|
211
|
+
if (current === contents) return;
|
|
212
|
+
await mkdir(dirname(path), { recursive: true });
|
|
213
|
+
await writeFile(path, contents, "utf8");
|
|
214
|
+
}
|
|
215
|
+
async function writeCollectionArtifacts(options, collections) {
|
|
216
|
+
const output = resolve(options.projectRoot, collectionTypesEntry);
|
|
217
|
+
const packageOutput = resolve(options.projectRoot, collectionTypesPackageEntry);
|
|
218
|
+
await rm(resolve(options.projectRoot, legacyCollectionTypesEntry), { force: true });
|
|
219
|
+
const routesDirectory = resolve(options.projectRoot, collectionRoutesDirectory);
|
|
220
|
+
if (collections.length === 0) {
|
|
221
|
+
await Promise.all([
|
|
222
|
+
rm(output, { force: true }),
|
|
223
|
+
rm(packageOutput, { force: true }),
|
|
224
|
+
rm(routesDirectory, {
|
|
225
|
+
force: true,
|
|
226
|
+
recursive: true
|
|
227
|
+
})
|
|
228
|
+
]);
|
|
229
|
+
return [];
|
|
230
|
+
}
|
|
231
|
+
await writeFileIfChanged(output, [
|
|
232
|
+
"declare global {",
|
|
233
|
+
" interface ViteHubCollectionMap {",
|
|
234
|
+
...collections.map(({ exportName, file, name }) => ` ${JSON.stringify(name)}: typeof import(${JSON.stringify(toTypeModuleSpecifier(file))})[${JSON.stringify(exportName)}]`),
|
|
235
|
+
" }",
|
|
236
|
+
"}",
|
|
237
|
+
"",
|
|
238
|
+
"export {}",
|
|
239
|
+
""
|
|
240
|
+
].join("\n"));
|
|
241
|
+
await writeFileIfChanged(packageOutput, "/// <reference path=\"./collections.d.ts\" />\n");
|
|
242
|
+
const expectedRoutes = new Set(collections.map(({ name }) => resolve(routesDirectory, `${name}.mjs`)));
|
|
243
|
+
const existingRoutes = await collectCollectionFiles(routesDirectory);
|
|
244
|
+
await Promise.all(existingRoutes.filter((file) => !expectedRoutes.has(file)).map((file) => rm(file, { force: true })));
|
|
245
|
+
return await Promise.all(collections.map(async ({ exportName, file, name }) => {
|
|
246
|
+
const handler = resolve(routesDirectory, `${name}.mjs`);
|
|
247
|
+
await writeFileIfChanged(handler, [
|
|
248
|
+
`import { defineCollectionHandler } from ${JSON.stringify(`${options.importBase ?? "@vite-hub/source"}/server`)}`,
|
|
249
|
+
`import { ${exportName} as collection } from ${JSON.stringify(toRuntimeModuleSpecifier(file))}`,
|
|
250
|
+
"",
|
|
251
|
+
"export default defineCollectionHandler(collection)",
|
|
252
|
+
""
|
|
253
|
+
].join("\n"));
|
|
254
|
+
return {
|
|
255
|
+
handler,
|
|
256
|
+
method: "get",
|
|
257
|
+
route: `/api/${name.split("/").map(encodeCollectionRouteSegment).join("/")}`
|
|
258
|
+
};
|
|
259
|
+
}));
|
|
260
|
+
}
|
|
261
|
+
async function discoverContent(options) {
|
|
262
|
+
const serverDirs = options.serverDirs === void 0 ? [resolve(options.projectRoot, "server")] : options.serverDirs.map((directory) => resolve(options.projectRoot, directory));
|
|
263
|
+
const candidates = [];
|
|
264
|
+
for (const serverDir of serverDirs) {
|
|
265
|
+
let entries;
|
|
266
|
+
try {
|
|
267
|
+
entries = await readdir(serverDir, { withFileTypes: true });
|
|
268
|
+
} catch (error) {
|
|
269
|
+
if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") continue;
|
|
270
|
+
throw error;
|
|
271
|
+
}
|
|
272
|
+
candidates.push(...entries.filter((entry) => entry.isFile() && /^content\.(?:[cm]?[jt]s)$/.test(entry.name) && !/\.d\.[cm]?ts$/.test(entry.name)).map((entry) => join(serverDir, entry.name)));
|
|
273
|
+
}
|
|
274
|
+
candidates.sort();
|
|
275
|
+
if (candidates.length > 1) throw new TypeError("[vitehub] Content is defined in more than one server directory.");
|
|
276
|
+
const file = candidates[0];
|
|
277
|
+
if (!file) return;
|
|
278
|
+
if (!findExportNames(await readFile(file, "utf8")).includes("content")) throw new TypeError(`[vitehub] Content file ${JSON.stringify(relative(options.projectRoot, file))} must export a Comark Content instance named "content".`);
|
|
279
|
+
return file;
|
|
280
|
+
}
|
|
281
|
+
async function writeContentArtifact(options, file) {
|
|
282
|
+
const output = resolve(options.projectRoot, contentRouteEntry);
|
|
283
|
+
if (!file) {
|
|
284
|
+
await rm(output, { force: true });
|
|
285
|
+
return [];
|
|
286
|
+
}
|
|
287
|
+
await writeFileIfChanged(output, [
|
|
288
|
+
`import { defineContentHandler } from ${JSON.stringify(`${options.importBase ?? "@vite-hub/source"}/content`)}`,
|
|
289
|
+
`import { content } from ${JSON.stringify(toRuntimeModuleSpecifier(file))}`,
|
|
290
|
+
"",
|
|
291
|
+
"export default defineContentHandler(content)",
|
|
292
|
+
""
|
|
293
|
+
].join("\n"));
|
|
294
|
+
return [{
|
|
295
|
+
handler: output,
|
|
296
|
+
route: "/api/content/**"
|
|
297
|
+
}];
|
|
298
|
+
}
|
|
299
|
+
async function prepareSourceGeneration(options) {
|
|
300
|
+
const [collections, content] = await Promise.all([discoverCollections(options), discoverContent(options)]);
|
|
301
|
+
return [...await writeCollectionArtifacts(options, collections), ...await writeContentArtifact(options, content)].sort((left, right) => left.route.localeCompare(right.route));
|
|
302
|
+
}
|
|
303
|
+
function applicationBaseURL(base) {
|
|
304
|
+
return base?.startsWith("/") && !base.startsWith("//") ? base : "/";
|
|
305
|
+
}
|
|
306
|
+
async function generatedHandlerKey(handlers) {
|
|
307
|
+
return JSON.stringify(await Promise.all(handlers.map(async (handler) => ({
|
|
308
|
+
...handler,
|
|
309
|
+
contents: await readFile(handler.handler, "utf8")
|
|
310
|
+
}))));
|
|
311
|
+
}
|
|
312
|
+
function generatedSourceNitroContribution(value, generatedHandlers) {
|
|
313
|
+
let existing = {};
|
|
314
|
+
if (Object(value) === value && !Array.isArray(value)) existing = value;
|
|
315
|
+
const merged = mergeGeneratedSourceNitroConfig(existing, generatedHandlers);
|
|
316
|
+
const handlers = merged.handlers?.slice(Array.isArray(existing.handlers) ? existing.handlers.length : 0);
|
|
317
|
+
const modules = merged.modules?.slice(Array.isArray(existing.modules) ? existing.modules.length : 0);
|
|
318
|
+
if (!handlers?.length && !modules?.length) return;
|
|
319
|
+
return {
|
|
320
|
+
...handlers?.length ? { handlers } : {},
|
|
321
|
+
...modules?.length ? { modules } : {}
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
function sourceDefinitionPath(file, projectRoot, serverDirs) {
|
|
325
|
+
return (serverDirs === void 0 ? [resolve(projectRoot, "server")] : serverDirs).some((directory) => {
|
|
326
|
+
const path = relative(resolve(projectRoot, directory), resolve(file)).replaceAll("\\", "/");
|
|
327
|
+
if (path.startsWith("../") || isAbsolute(path)) return false;
|
|
328
|
+
return /^content\.(?:[cm]?[jt]s)$/.test(path) || /^collections\/.+\.(?:[cm]?[jt]s)$/.test(path) && !/\.d\.[cm]?ts$/.test(path);
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
function hubSource(options = {}) {
|
|
332
|
+
let latestProjectRoot;
|
|
333
|
+
const configuredStateByRoot = /* @__PURE__ */ new Map();
|
|
334
|
+
const closeHostRefreshByEnvironment = /* @__PURE__ */ new WeakMap();
|
|
335
|
+
const hostRefreshLifecycleByRoot = /* @__PURE__ */ new Map();
|
|
336
|
+
const sourcePreparationByRoot = /* @__PURE__ */ new Map();
|
|
337
|
+
const configurationTransitionByRoot = /* @__PURE__ */ new Map();
|
|
338
|
+
const generatedHandlersListeners = /* @__PURE__ */ new Set();
|
|
339
|
+
const prepareSources = (input) => {
|
|
340
|
+
const root = resolve(input.projectRoot);
|
|
341
|
+
const preparation = (sourcePreparationByRoot.get(root) ?? Promise.resolve()).then(() => prepareSourceGeneration({
|
|
342
|
+
...input,
|
|
343
|
+
importBase: options.importBase
|
|
344
|
+
}), () => prepareSourceGeneration({
|
|
345
|
+
...input,
|
|
346
|
+
importBase: options.importBase
|
|
347
|
+
}));
|
|
348
|
+
sourcePreparationByRoot.set(root, preparation);
|
|
349
|
+
preparation.finally(() => {
|
|
350
|
+
if (sourcePreparationByRoot.get(root) === preparation) sourcePreparationByRoot.delete(root);
|
|
351
|
+
}).catch(() => {});
|
|
352
|
+
return preparation;
|
|
353
|
+
};
|
|
354
|
+
const refresh = async (viteConfig) => {
|
|
355
|
+
const projectRoot = viteConfig?.["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : viteConfig?.root ? resolveViteHubProjectRoot(viteConfig.root) : latestProjectRoot;
|
|
356
|
+
if (!projectRoot) return;
|
|
357
|
+
await prepareSources({
|
|
358
|
+
projectRoot,
|
|
359
|
+
serverDirs: configuredStateByRoot.get(projectRoot)?.serverDirs
|
|
360
|
+
});
|
|
361
|
+
};
|
|
362
|
+
const onGeneratedHandlersChanged = (listener, listenerOptions = {}) => {
|
|
363
|
+
const registration = {
|
|
364
|
+
...listenerOptions,
|
|
365
|
+
listener,
|
|
366
|
+
projectRoot: listenerOptions.projectRoot ? resolve(listenerOptions.projectRoot) : latestProjectRoot
|
|
367
|
+
};
|
|
368
|
+
generatedHandlersListeners.add(registration);
|
|
369
|
+
return () => generatedHandlersListeners.delete(registration);
|
|
370
|
+
};
|
|
371
|
+
const bindUnresolvedListenerRoots = (root) => {
|
|
372
|
+
for (const listenerOptions of generatedHandlersListeners.values()) listenerOptions.projectRoot ??= root;
|
|
373
|
+
};
|
|
374
|
+
const replaceConfiguredNitroContribution = (value, handlers, configuredNitroContribution) => {
|
|
375
|
+
let nitro = {};
|
|
376
|
+
if (Object(value) === value && !Array.isArray(value)) nitro = { ...value };
|
|
377
|
+
const contributedHandlers = configuredNitroContribution?.handlers ?? [];
|
|
378
|
+
if (Array.isArray(nitro.handlers) && contributedHandlers.length > 0) nitro.handlers = nitro.handlers.filter((handler) => !contributedHandlers.includes(handler));
|
|
379
|
+
const contributedModules = configuredNitroContribution?.modules ?? [];
|
|
380
|
+
if (Array.isArray(nitro.modules) && contributedModules.length > 0) nitro.modules = nitro.modules.filter((module) => !contributedModules.includes(module));
|
|
381
|
+
return mergeGeneratedSourceNitroConfig(nitro, handlers);
|
|
382
|
+
};
|
|
383
|
+
return {
|
|
384
|
+
name: "@vite-hub/source/vite",
|
|
385
|
+
enforce: "post",
|
|
386
|
+
api: {
|
|
387
|
+
onGeneratedHandlersChanged,
|
|
388
|
+
prepareSources
|
|
389
|
+
},
|
|
390
|
+
async config(config) {
|
|
391
|
+
const viteConfig = config;
|
|
392
|
+
if (viteConfig["__vitehubNitroConfigContext"]) return;
|
|
393
|
+
const projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(viteConfig.root || process.cwd());
|
|
394
|
+
latestProjectRoot = projectRoot;
|
|
395
|
+
bindUnresolvedListenerRoots(projectRoot);
|
|
396
|
+
const serverDirs = viteConfig[VITEHUB_SERVER_DIRS];
|
|
397
|
+
const previousTransition = configurationTransitionByRoot.get(projectRoot) ?? Promise.resolve();
|
|
398
|
+
const runTransition = async () => {
|
|
399
|
+
const previousLifecycle = hostRefreshLifecycleByRoot.get(projectRoot);
|
|
400
|
+
const previousConfiguredState = configuredStateByRoot.get(projectRoot);
|
|
401
|
+
previousLifecycle?.pause();
|
|
402
|
+
try {
|
|
403
|
+
const handlers = await prepareSources({
|
|
404
|
+
projectRoot,
|
|
405
|
+
serverDirs
|
|
406
|
+
});
|
|
407
|
+
const handlerKey = await generatedHandlerKey(handlers);
|
|
408
|
+
const nitro = generatedSourceNitroContribution(viteConfig.nitro, handlers);
|
|
409
|
+
configuredStateByRoot.set(projectRoot, {
|
|
410
|
+
handlerKey,
|
|
411
|
+
nitroContribution: nitro,
|
|
412
|
+
serverDirs: serverDirs?.slice()
|
|
413
|
+
});
|
|
414
|
+
const contribution = {
|
|
415
|
+
define: { __VITEHUB_APP_BASE_URL__: JSON.stringify(applicationBaseURL(viteConfig.base)) },
|
|
416
|
+
...nitro ? { nitro } : {}
|
|
417
|
+
};
|
|
418
|
+
previousLifecycle?.close();
|
|
419
|
+
return contribution;
|
|
420
|
+
} catch (error) {
|
|
421
|
+
try {
|
|
422
|
+
if (previousConfiguredState) await prepareSources({
|
|
423
|
+
projectRoot,
|
|
424
|
+
serverDirs: previousConfiguredState.serverDirs
|
|
425
|
+
});
|
|
426
|
+
} finally {
|
|
427
|
+
previousLifecycle?.resume();
|
|
428
|
+
}
|
|
429
|
+
throw error;
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
const transition = previousTransition.then(runTransition, runTransition);
|
|
433
|
+
configurationTransitionByRoot.set(projectRoot, transition);
|
|
434
|
+
transition.finally(() => {
|
|
435
|
+
if (configurationTransitionByRoot.get(projectRoot) === transition) configurationTransitionByRoot.delete(projectRoot);
|
|
436
|
+
}).catch(() => {});
|
|
437
|
+
return transition;
|
|
438
|
+
},
|
|
439
|
+
async configResolved(config) {
|
|
440
|
+
const viteConfig = config;
|
|
441
|
+
const projectRoot = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(config.root);
|
|
442
|
+
latestProjectRoot = projectRoot;
|
|
443
|
+
bindUnresolvedListenerRoots(projectRoot);
|
|
444
|
+
const previousTransition = configurationTransitionByRoot.get(projectRoot) ?? Promise.resolve();
|
|
445
|
+
const runTransition = async () => {
|
|
446
|
+
const configuredState = configuredStateByRoot.get(projectRoot);
|
|
447
|
+
const serverDirs = viteConfig["__vitehubServerDirs"] ?? configuredState?.serverDirs;
|
|
448
|
+
const handlers = await prepareSources({
|
|
449
|
+
projectRoot,
|
|
450
|
+
serverDirs
|
|
451
|
+
});
|
|
452
|
+
const handlerKey = await generatedHandlerKey(handlers);
|
|
453
|
+
configuredStateByRoot.set(projectRoot, {
|
|
454
|
+
handlerKey,
|
|
455
|
+
nitroContribution: configuredState?.nitroContribution,
|
|
456
|
+
serverDirs: serverDirs?.slice()
|
|
457
|
+
});
|
|
458
|
+
if (!viteConfig["__vitehubNitroConfigContext"]) viteConfig.nitro = replaceConfiguredNitroContribution(viteConfig.nitro, handlers, configuredState?.nitroContribution);
|
|
459
|
+
};
|
|
460
|
+
const transition = previousTransition.then(runTransition, runTransition);
|
|
461
|
+
configurationTransitionByRoot.set(projectRoot, transition);
|
|
462
|
+
transition.finally(() => {
|
|
463
|
+
if (configurationTransitionByRoot.get(projectRoot) === transition) configurationTransitionByRoot.delete(projectRoot);
|
|
464
|
+
}).catch(() => {});
|
|
465
|
+
return transition;
|
|
466
|
+
},
|
|
467
|
+
configureServer(server) {
|
|
468
|
+
const viteConfig = server.config;
|
|
469
|
+
const root = viteConfig["__vitehubProjectRoot"] ? resolve(viteConfig[VITEHUB_PROJECT_ROOT]) : resolveViteHubProjectRoot(server.config.root ?? latestProjectRoot ?? process.cwd());
|
|
470
|
+
const configuredState = configuredStateByRoot.get(root);
|
|
471
|
+
const lifecycleServerDirs = configuredState?.serverDirs?.slice();
|
|
472
|
+
let activeHandlerKey = configuredState?.handlerKey ?? "[]";
|
|
473
|
+
const effectiveServerDirs = lifecycleServerDirs === void 0 ? root ? [resolve(root, "server")] : [] : root ? lifecycleServerDirs.map((directory) => resolve(root, directory)) : [];
|
|
474
|
+
server.watcher.add(effectiveServerDirs);
|
|
475
|
+
let hostRefreshRetry;
|
|
476
|
+
let pausedHostRefreshRetryFile;
|
|
477
|
+
let hostRefreshRetryDelay = initialHostRefreshRetryDelay;
|
|
478
|
+
let refreshQueue = Promise.resolve();
|
|
479
|
+
let serverClosed = false;
|
|
480
|
+
let serverPaused = false;
|
|
481
|
+
const clearHostRefreshRetry = () => {
|
|
482
|
+
if (hostRefreshRetry) clearTimeout(hostRefreshRetry);
|
|
483
|
+
hostRefreshRetry = void 0;
|
|
484
|
+
};
|
|
485
|
+
const closeHostRefresh = () => {
|
|
486
|
+
serverClosed = true;
|
|
487
|
+
clearHostRefreshRetry();
|
|
488
|
+
if (root && hostRefreshLifecycleByRoot.get(root)?.close === closeHostRefresh) hostRefreshLifecycleByRoot.delete(root);
|
|
489
|
+
};
|
|
490
|
+
if (root) {
|
|
491
|
+
hostRefreshLifecycleByRoot.get(root)?.close();
|
|
492
|
+
hostRefreshLifecycleByRoot.set(root, {
|
|
493
|
+
close: closeHostRefresh,
|
|
494
|
+
pause: () => {
|
|
495
|
+
serverPaused = true;
|
|
496
|
+
},
|
|
497
|
+
resume: () => {
|
|
498
|
+
serverPaused = false;
|
|
499
|
+
if (pausedHostRefreshRetryFile) {
|
|
500
|
+
const file = pausedHostRefreshRetryFile;
|
|
501
|
+
pausedHostRefreshRetryFile = void 0;
|
|
502
|
+
scheduleHostRefreshRetry(file);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
for (const environment of Object.values(server.environments)) closeHostRefreshByEnvironment.set(environment, closeHostRefresh);
|
|
508
|
+
const scheduleHostRefreshRetry = (file) => {
|
|
509
|
+
if (hostRefreshRetry) return;
|
|
510
|
+
hostRefreshRetry = setTimeout(() => {
|
|
511
|
+
hostRefreshRetry = void 0;
|
|
512
|
+
if (serverClosed) return;
|
|
513
|
+
if (serverPaused) {
|
|
514
|
+
pausedHostRefreshRetryFile = file;
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
queueHostRefresh(file);
|
|
518
|
+
}, hostRefreshRetryDelay);
|
|
519
|
+
hostRefreshRetry.unref?.();
|
|
520
|
+
hostRefreshRetryDelay = Math.min(hostRefreshRetryDelay * 2, maximumHostRefreshRetryDelay);
|
|
521
|
+
};
|
|
522
|
+
function queueHostRefresh(file) {
|
|
523
|
+
if (serverClosed || !root || !sourceDefinitionPath(file, root, lifecycleServerDirs)) return;
|
|
524
|
+
if (serverPaused) {
|
|
525
|
+
pausedHostRefreshRetryFile = file;
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
const result = refreshQueue.then(async () => {
|
|
529
|
+
if (serverClosed) return;
|
|
530
|
+
if (serverPaused) {
|
|
531
|
+
pausedHostRefreshRetryFile = file;
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
const previousArtifacts = await snapshotGeneratedSourceArtifacts(root);
|
|
535
|
+
const handlers = await prepareSources({
|
|
536
|
+
projectRoot: root,
|
|
537
|
+
serverDirs: lifecycleServerDirs
|
|
538
|
+
});
|
|
539
|
+
if (serverClosed) return;
|
|
540
|
+
if (serverPaused) {
|
|
541
|
+
pausedHostRefreshRetryFile = file;
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
const handlerKey = await generatedHandlerKey(handlers);
|
|
545
|
+
if (serverClosed) return;
|
|
546
|
+
if (serverPaused) {
|
|
547
|
+
pausedHostRefreshRetryFile = file;
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
if (handlerKey === activeHandlerKey) return;
|
|
551
|
+
const listeners = [...generatedHandlersListeners].filter((listenerOptions) => listenerOptions.projectRoot === root);
|
|
552
|
+
const passiveListeners = listeners.filter((listenerOptions) => !listenerOptions.handlesHostRestart);
|
|
553
|
+
for (const { listener } of passiveListeners) Promise.resolve().then(() => listener(handlers)).catch((error) => server.config.logger.error(String(error)));
|
|
554
|
+
const hostRestartOwners = listeners.filter((listenerOptions) => listenerOptions.handlesHostRestart);
|
|
555
|
+
const listenerResults = hostRestartOwners.map(async ({ listener }) => {
|
|
556
|
+
try {
|
|
557
|
+
await listener(handlers);
|
|
558
|
+
return true;
|
|
559
|
+
} catch (error) {
|
|
560
|
+
server.config.logger.error(String(error));
|
|
561
|
+
return false;
|
|
562
|
+
}
|
|
563
|
+
});
|
|
564
|
+
let ownerSettlementTimeout;
|
|
565
|
+
const hostRestartHandled = await Promise.race([
|
|
566
|
+
Promise.all(listenerResults).then((results) => results.some(Boolean)),
|
|
567
|
+
Promise.any(listenerResults.map(async (result) => await result || Promise.reject())).then(() => true, () => false),
|
|
568
|
+
new Promise((resolve) => {
|
|
569
|
+
ownerSettlementTimeout = setTimeout(() => resolve(false), hostRestartOwnerSettlementTimeout);
|
|
570
|
+
ownerSettlementTimeout.unref?.();
|
|
571
|
+
})
|
|
572
|
+
]);
|
|
573
|
+
if (ownerSettlementTimeout) clearTimeout(ownerSettlementTimeout);
|
|
574
|
+
if (serverClosed) return;
|
|
575
|
+
const hasHostRestartOwner = hostRestartOwners.length > 0;
|
|
576
|
+
if (hasHostRestartOwner && !hostRestartHandled) {
|
|
577
|
+
await restoreGeneratedSourceArtifacts(root, previousArtifacts);
|
|
578
|
+
scheduleHostRefreshRetry(file);
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
if (!hasHostRestartOwner) {
|
|
582
|
+
const previousEnvironments = server.environments;
|
|
583
|
+
try {
|
|
584
|
+
await server.restart();
|
|
585
|
+
} catch (error) {
|
|
586
|
+
if (serverClosed) return;
|
|
587
|
+
await restoreGeneratedSourceArtifacts(root, previousArtifacts);
|
|
588
|
+
scheduleHostRefreshRetry(file);
|
|
589
|
+
throw error;
|
|
590
|
+
}
|
|
591
|
+
if (serverClosed) return;
|
|
592
|
+
if (server.environments === previousEnvironments) {
|
|
593
|
+
await restoreGeneratedSourceArtifacts(root, previousArtifacts);
|
|
594
|
+
scheduleHostRefreshRetry(file);
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
activeHandlerKey = handlerKey;
|
|
599
|
+
clearHostRefreshRetry();
|
|
600
|
+
hostRefreshRetryDelay = initialHostRefreshRetryDelay;
|
|
601
|
+
});
|
|
602
|
+
refreshQueue = result.catch(() => {});
|
|
603
|
+
result.catch((error) => server.config.logger.error(String(error)));
|
|
604
|
+
return result;
|
|
605
|
+
}
|
|
606
|
+
const refreshHost = (file) => {
|
|
607
|
+
if (!root || !sourceDefinitionPath(file, root, lifecycleServerDirs)) return;
|
|
608
|
+
clearHostRefreshRetry();
|
|
609
|
+
hostRefreshRetryDelay = initialHostRefreshRetryDelay;
|
|
610
|
+
return queueHostRefresh(file);
|
|
611
|
+
};
|
|
612
|
+
server.watcher.on("add", refreshHost);
|
|
613
|
+
server.watcher.on("change", refreshHost);
|
|
614
|
+
server.watcher.on("unlink", refreshHost);
|
|
615
|
+
},
|
|
616
|
+
buildStart() {
|
|
617
|
+
return refresh(this.environment?.config);
|
|
618
|
+
},
|
|
619
|
+
buildEnd() {
|
|
620
|
+
return refresh(this.environment?.config);
|
|
621
|
+
},
|
|
622
|
+
closeBundle() {
|
|
623
|
+
closeHostRefreshByEnvironment.get(this.environment)?.();
|
|
624
|
+
closeHostRefreshByEnvironment.delete(this.environment);
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
//#endregion
|
|
629
|
+
export { hubSource, mergeGeneratedSourceNitroConfig, prepareSourceGeneration, toRuntimeModuleSpecifier, toTypeModuleSpecifier };
|