@vite-hub/schedule 0.0.3 → 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.
@@ -0,0 +1,4166 @@
1
+ import { a as readObjectProperty, c as writeRuntimeRegistryFile, d as dirname$1, f as relative$1, i as maskSourceLiterals, l as createImportPath, n as findDefaultExportCall, o as splitTopLevel, p as resolve$1, r as findMatching, s as createRuntimeRegistryContents, t as discoverScheduleDefinitions, u as ensureGeneratedDir } from "./discovery-DvU3B6iD.js";
2
+ import { builtinModules, createRequire } from "node:module";
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync } from "node:fs";
4
+ import { basename, dirname, extname, isAbsolute, normalize, parse, relative, resolve, sep } from "node:path";
5
+ import { cp, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import { randomUUID } from "node:crypto";
8
+ import { tmpdir } from "node:os";
9
+ import { build } from "esbuild";
10
+ import { isDeepStrictEqual } from "node:util";
11
+ //#region ../internal/src/build/client-output.ts
12
+ function hasStaticIndex(clientDir) {
13
+ return existsSync(resolve$1(clientDir, "index.html"));
14
+ }
15
+ async function copyClientOutput(clientDir, targetDir) {
16
+ const resolvedClientDir = resolve$1(clientDir);
17
+ const resolvedTargetDir = resolve$1(targetDir);
18
+ if (resolvedClientDir === resolvedTargetDir) return;
19
+ await rm(resolvedTargetDir, {
20
+ force: true,
21
+ recursive: true
22
+ });
23
+ await mkdir(dirname$1(resolvedTargetDir), { recursive: true });
24
+ const targetRelativePath = relative$1(resolvedClientDir, resolvedTargetDir);
25
+ if (targetRelativePath && !targetRelativePath.startsWith("../")) {
26
+ const [targetRootEntry] = targetRelativePath.split("/", 1);
27
+ await mkdir(resolvedTargetDir, { recursive: true });
28
+ await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), { recursive: true })));
29
+ return;
30
+ }
31
+ await cp(resolvedClientDir, resolvedTargetDir, { recursive: true });
32
+ }
33
+ //#endregion
34
+ //#region ../internal/src/build/provider-output-config.ts
35
+ function isProviderJsonArray(value, ancestors) {
36
+ if (Object.getPrototypeOf(value) !== Array.prototype || ancestors.has(value)) return false;
37
+ if (Reflect.ownKeys(value).length !== value.length + 1) return false;
38
+ ancestors.add(value);
39
+ try {
40
+ for (let index = 0; index < value.length; index++) {
41
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
42
+ if (!descriptor?.enumerable || !("value" in descriptor) || !isProviderJsonValue(descriptor.value, ancestors)) return false;
43
+ }
44
+ return true;
45
+ } finally {
46
+ ancestors.delete(value);
47
+ }
48
+ }
49
+ function isProviderJsonRecordValue(value, ancestors) {
50
+ const prototype = Object.getPrototypeOf(value);
51
+ if (prototype !== Object.prototype && prototype !== null || ancestors.has(value)) return false;
52
+ ancestors.add(value);
53
+ try {
54
+ return Reflect.ownKeys(value).every((key) => {
55
+ if (typeof key !== "string") return false;
56
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
57
+ return descriptor?.enumerable === true && "value" in descriptor && isProviderJsonValue(descriptor.value, ancestors);
58
+ });
59
+ } finally {
60
+ ancestors.delete(value);
61
+ }
62
+ }
63
+ function isProviderJsonValue(value, ancestors) {
64
+ if (value === null || typeof value === "boolean" || typeof value === "string") return true;
65
+ if (typeof value === "number") return Number.isFinite(value);
66
+ if (Array.isArray(value)) return isProviderJsonArray(value, ancestors);
67
+ return typeof value === "object" && isProviderJsonRecordValue(value, ancestors);
68
+ }
69
+ function isProviderJsonRecord(value) {
70
+ try {
71
+ return typeof value === "object" && value !== null && !Array.isArray(value) && isProviderJsonRecordValue(value, /* @__PURE__ */ new Set());
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+ function assertProviderJsonRecord(value) {
77
+ if (!isProviderJsonRecord(value)) throw new TypeError("[vitehub] Provider output config must be a JSON object.");
78
+ }
79
+ function isFileNotFoundError(error) {
80
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
81
+ }
82
+ async function readProviderJsonRecord(file) {
83
+ try {
84
+ const parsed = JSON.parse(await readFile(file, "utf8"));
85
+ assertProviderJsonRecord(parsed);
86
+ return parsed;
87
+ } catch (error) {
88
+ if (isFileNotFoundError(error)) return;
89
+ throw error;
90
+ }
91
+ }
92
+ function deleteOwnedFields(value, ownership, cleanup = false) {
93
+ const next = { ...value };
94
+ for (const key of ownership.keys ?? []) delete next[key];
95
+ for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) if (!cleanup || !arrayOwnership.preserveOnCleanup) delete next[field];
96
+ return next;
97
+ }
98
+ function getKeyedArrayEntryValue(value, key) {
99
+ if (key === void 0) return value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string" ? value : void 0;
100
+ if (!isProviderJsonRecord(value)) return;
101
+ const entryValue = value[key];
102
+ return entryValue === null || typeof entryValue === "boolean" || typeof entryValue === "number" || typeof entryValue === "string" ? entryValue : void 0;
103
+ }
104
+ function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
105
+ const current = Array.isArray(value) ? value : [];
106
+ const replacementKeys = replacements.flatMap((entry) => {
107
+ const key = getKeyedArrayEntryValue(entry, ownership.key);
108
+ return key === void 0 ? [] : [key];
109
+ });
110
+ const ownedKeys = new Set([...ownership.values ?? [], ...replacementKeys]);
111
+ return current.filter((entry) => {
112
+ const key = getKeyedArrayEntryValue(entry, ownership.key);
113
+ return key === void 0 || !ownedKeys.has(key);
114
+ });
115
+ }
116
+ function mergeOwnedArrays(existing, value, arrays) {
117
+ const next = { ...value };
118
+ for (const [field, ownership] of Object.entries(arrays ?? {})) {
119
+ const incoming = Array.isArray(value[field]) ? value[field] : [];
120
+ const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
121
+ if (merged.length) next[field] = merged;
122
+ else delete next[field];
123
+ }
124
+ return next;
125
+ }
126
+ async function persistProviderJsonRecord(file, value, removeIfEmpty) {
127
+ if (removeIfEmpty && !Object.keys(value).length) {
128
+ await rm(file, { force: true });
129
+ return;
130
+ }
131
+ await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
132
+ }
133
+ async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
134
+ const existing = await readProviderJsonRecord(file) ?? {};
135
+ const defaults = options.defaults ?? {};
136
+ assertProviderJsonRecord(defaults);
137
+ await persistProviderJsonRecord(file, mergeProviderOutputConfig({
138
+ ...defaults,
139
+ ...existing
140
+ }, value, ownership), options.removeIfEmpty === true);
141
+ }
142
+ function mergeProviderOutputConfig(existing, value, ownership = {}) {
143
+ assertProviderJsonRecord(existing);
144
+ assertProviderJsonRecord(value);
145
+ return {
146
+ ...deleteOwnedFields(existing, ownership),
147
+ ...mergeOwnedArrays(existing, value, ownership.arrays)
148
+ };
149
+ }
150
+ function stringifyProviderOutputConfig(value) {
151
+ assertProviderJsonRecord(value);
152
+ return JSON.stringify(value, null, 2);
153
+ }
154
+ async function cleanProviderOutputConfig(file, ownership) {
155
+ if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
156
+ const existing = await readProviderJsonRecord(file);
157
+ if (!existing) return;
158
+ const next = deleteOwnedFields(existing, ownership, true);
159
+ let changed = (ownership.keys ?? []).some((key) => key in existing);
160
+ for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
161
+ if (arrayOwnership.preserveOnCleanup) continue;
162
+ if (!(field in existing)) continue;
163
+ const current = existing[field];
164
+ const retained = arrayOwnership.retainOnCleanup ?? [];
165
+ const preserved = [...preserveUnownedKeyedArrayEntries(current, arrayOwnership, retained), ...retained];
166
+ changed ||= retained.length > 0 || !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
167
+ if (preserved.length) next[field] = preserved;
168
+ }
169
+ if (!changed) return;
170
+ await persistProviderJsonRecord(file, next, true);
171
+ }
172
+ //#endregion
173
+ //#region ../internal/src/build/user-entry.ts
174
+ function toSafeAppName(rootDir) {
175
+ return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
176
+ }
177
+ const cloudflareRuntimeExternal = "cloudflare:*";
178
+ function createDefaultCloudflareOutputRoot(rootDir) {
179
+ return resolve(rootDir, "dist", toSafeAppName(rootDir));
180
+ }
181
+ async function writeCloudflareWranglerConfig(options) {
182
+ const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
183
+ const configFile = resolve(outputRoot, "wrangler.json");
184
+ if (!options.wranglerConfig) {
185
+ await cleanProviderOutputConfig(configFile, options.wranglerConfigOwnership ?? {});
186
+ return;
187
+ }
188
+ await mkdir(outputRoot, { recursive: true });
189
+ await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, {
190
+ defaults: options.wranglerConfigDefaults,
191
+ removeIfEmpty: true
192
+ });
193
+ }
194
+ //#endregion
195
+ //#region ../internal/src/object.ts
196
+ function isPlainObject(value) {
197
+ if (value === null || Object(value) !== value || Array.isArray(value)) return false;
198
+ try {
199
+ Function.prototype.toString.call(value);
200
+ return false;
201
+ } catch {
202
+ return true;
203
+ }
204
+ }
205
+ //#endregion
206
+ //#region ../internal/src/build/esbuild.ts
207
+ const viteRawNamespace = "vitehub-vite-raw";
208
+ const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
209
+ const markdownTemplateFileSuffix = ".template.md";
210
+ const markdownTemplateModuleQuery = "markdown-template";
211
+ const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
212
+ const skipResolvedAlias = "vitehubSkipResolvedAlias";
213
+ const encodedAliasPrefixMarker = "\0vitehub-prefix:";
214
+ const encodedAliasExactMarker = "\0vitehub-exact:";
215
+ const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
216
+ function encodeProviderOutputAliases(configAliases) {
217
+ const aliases = Object.create(null);
218
+ for (const [index, alias] of configAliases.entries()) {
219
+ if (alias.find instanceof RegExp) continue;
220
+ const exactSpecifier = Object.hasOwn(aliases, alias.find) ? `${alias.find}${encodedAliasExactMarker}${index}` : alias.find;
221
+ aliases[exactSpecifier] = alias.replacement;
222
+ if (alias.find.endsWith("/")) {
223
+ const prefixSpecifier = `${alias.find}/${encodedAliasPrefixMarker}${index}`;
224
+ aliases[prefixSpecifier] = `${alias.replacement.replace(/\/$/, "")}/`;
225
+ } else aliases[`${alias.find}/${encodedAliasPrefixMarker}${index}`] = `${alias.replacement.replace(/\/$/, "")}/`;
226
+ }
227
+ return aliases;
228
+ }
229
+ function normalizePathSeparators(path) {
230
+ return path.replaceAll("\\", "/");
231
+ }
232
+ function escapeRegExp$1(value) {
233
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
234
+ }
235
+ function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
236
+ if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
237
+ if (!Array.isArray(exportsValue) && !isPlainObject(exportsValue)) return [];
238
+ const candidates = [];
239
+ const exportEntries = isPlainObject(exportsValue) && Object.keys(exportsValue).some((exportKey) => exportKey.startsWith(".")) ? Object.entries(exportsValue) : [[".", exportsValue]];
240
+ for (const [exportKey, target] of exportEntries) {
241
+ const targets = [target];
242
+ while (targets.length) {
243
+ const value = targets.shift();
244
+ if (typeof value === "string") {
245
+ const normalizedTarget = normalizePathSeparators(value).replace(/^\.\//, "");
246
+ const targetParts = normalizedTarget.split("*");
247
+ if (targetParts.length === 1) {
248
+ if (normalizedTarget === packageRelativePath) candidates.push(`${packageName}${exportKey.slice(1)}`);
249
+ continue;
250
+ }
251
+ const targetPattern = `${escapeRegExp$1(targetParts[0])}(.*?)${targetParts.slice(1).map((part, index) => `${index ? "\\1" : ""}${escapeRegExp$1(part)}`).join("")}`;
252
+ const wildcard = new RegExp(`^${targetPattern}$`).exec(packageRelativePath)?.[1];
253
+ if (wildcard === void 0) continue;
254
+ candidates.push(`${packageName}${exportKey.slice(1).replace("*", wildcard)}`);
255
+ } else if (Array.isArray(value)) targets.push(...value);
256
+ else if (isPlainObject(value)) targets.push(...Object.values(value));
257
+ }
258
+ }
259
+ return candidates;
260
+ }
261
+ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
262
+ const entries = Object.entries(aliases || {});
263
+ if (!entries.length) return;
264
+ const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
265
+ const prefixMarkerIndex = encodedSpecifier.lastIndexOf(encodedAliasPrefixMarker);
266
+ const exactMarkerIndex = encodedSpecifier.lastIndexOf(encodedAliasExactMarker);
267
+ const explicitlyEncodedPrefix = prefixMarkerIndex !== -1;
268
+ const markerIndex = Math.max(prefixMarkerIndex, exactMarkerIndex);
269
+ const specifier = markerIndex === -1 ? encodedSpecifier : encodedSpecifier.slice(0, markerIndex);
270
+ const prefix = explicitlyEncodedPrefix || specifier.endsWith("/") && !Object.hasOwn(aliases, `${specifier}/`);
271
+ const resolvedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
272
+ const canonicalSpecifier = isAbsolute(resolvedSpecifier) ? normalizePathSeparators(await realpath(resolvedSpecifier).catch(() => resolvedSpecifier)) : resolvedSpecifier;
273
+ const resolvedReplacement = isAbsolute(replacement) ? normalizePathSeparators(resolve(replacement)) : replacement;
274
+ return {
275
+ canonicalSpecifier: `${canonicalSpecifier}${prefix && !canonicalSpecifier.endsWith("/") ? "/" : ""}`,
276
+ prefix,
277
+ replacement: `${resolvedReplacement}${prefix && !/[\\/]$/.test(resolvedReplacement) ? "/" : ""}`,
278
+ specifier: `${resolvedSpecifier}${prefix && !resolvedSpecifier.endsWith("/") ? "/" : ""}`
279
+ };
280
+ }));
281
+ return {
282
+ name: "vitehub-resolved-alias",
283
+ setup(build) {
284
+ const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
285
+ build.onResolve({ filter: /.*/ }, async (args) => {
286
+ if (args.pluginData?.[skipResolvedAlias]) return;
287
+ const aliases = await resolvedEntries;
288
+ let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
289
+ let matchedAlias = match?.specifier;
290
+ let matchedSpecifier = match ? args.path : void 0;
291
+ let specifier = args.resolveDir && /^\.\.?[\\/]/.test(args.path) ? resolve(args.resolveDir, args.path) : args.path;
292
+ let normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
293
+ let canonicalSpecifier = normalizedSpecifier;
294
+ const canonicalizeSpecifier = async () => {
295
+ canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
296
+ return canonicalSpecifier;
297
+ };
298
+ match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
299
+ if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
300
+ await canonicalizeSpecifier();
301
+ match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
302
+ }
303
+ if (!match && isAbsolute(args.path)) for (const alias of aliases) {
304
+ if (isAbsolute(alias.specifier)) continue;
305
+ const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
306
+ const aliasSegments = packageAlias.split("/");
307
+ if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
308
+ let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
309
+ if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
310
+ const scopeMarker = `/node_modules/${packageAlias}/`;
311
+ const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
312
+ const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
313
+ if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
314
+ }
315
+ const packageMarker = `/node_modules/${packageName}/`;
316
+ const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
317
+ const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
318
+ const cacheKey = [
319
+ alias.specifier,
320
+ alias.prefix,
321
+ resolutionScope,
322
+ args.importer,
323
+ args.resolveDir,
324
+ args.kind,
325
+ args.namespace,
326
+ JSON.stringify(args.with)
327
+ ].join("\0");
328
+ let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
329
+ if (!resolution) {
330
+ resolution = (async () => {
331
+ let resolvedAliasPath;
332
+ if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
333
+ else if (resolutionScope) {
334
+ const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
335
+ const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
336
+ if (!isPlainObject(parsedPackageJson)) return;
337
+ const packageJson = parsedPackageJson;
338
+ if (packageJson.exports === void 0 && !alias.prefix) {
339
+ const resolvedCandidate = await build.resolve(alias.specifier, {
340
+ importer: args.importer,
341
+ kind: args.kind,
342
+ namespace: args.namespace,
343
+ pluginData: {
344
+ ...args.pluginData,
345
+ [skipResolvedAlias]: true
346
+ },
347
+ resolveDir: args.resolveDir,
348
+ with: args.with
349
+ });
350
+ if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
351
+ canonical: alias.specifier,
352
+ normalized: alias.specifier,
353
+ publicSpecifier: alias.specifier
354
+ };
355
+ return;
356
+ }
357
+ const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
358
+ for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
359
+ const resolvedCandidate = await build.resolve(publicSpecifier, {
360
+ importer: args.importer,
361
+ kind: args.kind,
362
+ namespace: args.namespace,
363
+ pluginData: {
364
+ ...args.pluginData,
365
+ [skipResolvedAlias]: true
366
+ },
367
+ resolveDir: args.resolveDir,
368
+ with: args.with
369
+ });
370
+ if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
371
+ if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
372
+ matchingPublicSpecifiers.add(publicSpecifier);
373
+ }
374
+ if (matchingPublicSpecifiers.size === 1) {
375
+ const publicSpecifier = [...matchingPublicSpecifiers][0];
376
+ if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
377
+ canonical: publicSpecifier,
378
+ normalized: publicSpecifier,
379
+ publicSpecifier
380
+ };
381
+ }
382
+ return;
383
+ } else {
384
+ const resolvedAlias = await build.resolve(alias.specifier, {
385
+ importer: args.importer,
386
+ kind: args.kind,
387
+ namespace: args.namespace,
388
+ pluginData: {
389
+ ...args.pluginData,
390
+ [skipResolvedAlias]: true
391
+ },
392
+ resolveDir: args.resolveDir,
393
+ with: args.with
394
+ });
395
+ if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
396
+ resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
397
+ }
398
+ const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
399
+ return {
400
+ canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
401
+ normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
402
+ };
403
+ })();
404
+ if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
405
+ }
406
+ const paths = await resolution;
407
+ if (!paths) continue;
408
+ if (paths.publicSpecifier) {
409
+ match = alias;
410
+ matchedAlias = alias.specifier;
411
+ matchedSpecifier = paths.publicSpecifier;
412
+ break;
413
+ }
414
+ const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
415
+ let canonicalMatch = false;
416
+ if (!normalizedMatch && paths.canonical !== paths.normalized) {
417
+ await canonicalizeSpecifier();
418
+ canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
419
+ }
420
+ if (normalizedMatch || canonicalMatch) {
421
+ match = alias;
422
+ matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
423
+ matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
424
+ break;
425
+ }
426
+ }
427
+ matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
428
+ matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
429
+ if (!match) return;
430
+ const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
431
+ if (!target) return;
432
+ const resolvedTarget = /^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target;
433
+ return build.resolve(resolvedTarget, {
434
+ importer: args.importer,
435
+ kind: args.kind,
436
+ namespace: args.namespace,
437
+ pluginData: {
438
+ ...args.pluginData,
439
+ [skipResolvedAlias]: true
440
+ },
441
+ resolveDir: args.resolveDir,
442
+ with: args.with
443
+ });
444
+ });
445
+ }
446
+ };
447
+ }
448
+ function createViteAliasPlugin(aliases) {
449
+ if (!Array.isArray(aliases)) return;
450
+ const resolvingAlias = "vitehubResolvingAlias";
451
+ return {
452
+ name: "vitehub-vite-alias",
453
+ setup(build) {
454
+ build.onResolve({ filter: /.*/ }, async (args) => {
455
+ if (args.pluginData?.[resolvingAlias]) return;
456
+ const alias = aliases.find(({ find }) => {
457
+ if (typeof find === "string") return args.path === find || args.path.startsWith(`${find}/`);
458
+ find.lastIndex = 0;
459
+ return find.test(args.path);
460
+ });
461
+ if (!alias) return;
462
+ if (alias.customResolver) return { errors: [{ text: `[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(args.path)} because it uses customResolver.` }] };
463
+ if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
464
+ const replacement = typeof alias.find === "string" ? `${alias.replacement}${args.path.slice(alias.find.length)}` : args.path.replace(alias.find, alias.replacement);
465
+ const result = await build.resolve(replacement, {
466
+ importer: args.importer,
467
+ kind: args.kind,
468
+ namespace: args.namespace,
469
+ pluginData: Object.assign({}, args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {}, { [resolvingAlias]: true }),
470
+ resolveDir: args.resolveDir,
471
+ with: args.with
472
+ });
473
+ const pluginData = Object.assign({}, result.pluginData);
474
+ Reflect.deleteProperty(pluginData, resolvingAlias);
475
+ return {
476
+ ...result,
477
+ pluginData
478
+ };
479
+ });
480
+ }
481
+ };
482
+ }
483
+ function stripMarkdownCode(template) {
484
+ let fence;
485
+ let inList = false;
486
+ let previousLineBlank = true;
487
+ return template.split("\n").map((line) => {
488
+ const content = line.replace(/^(?: {0,3}> ?)+/, "");
489
+ if (!fence) {
490
+ const listIndented = inList && /^ {4}(?:`{3,}|~{3,})/.test(content);
491
+ const opening = (listIndented ? content.slice(4) : content).match(/^ {0,3}(`{3,}|~{3,})/);
492
+ if (!opening) {
493
+ if (/^ {0,3}(?:[-+*]|\d+[.)])\s+/.test(content)) inList = true;
494
+ else if (content.trim() && !/^ {2,}/.test(content)) inList = false;
495
+ const indentedCode = !inList && previousLineBlank && /^(?: {4}|\t)/.test(content) || inList && previousLineBlank && /^(?: {8}| {4}\t|\t{2})/.test(content);
496
+ previousLineBlank = content.trim() === "";
497
+ return indentedCode ? "" : line;
498
+ }
499
+ fence = {
500
+ marker: opening[1][0],
501
+ length: opening[1].length,
502
+ listIndented
503
+ };
504
+ previousLineBlank = false;
505
+ return "";
506
+ }
507
+ const closing = (fence.listIndented ? content.replace(/^ {4}/, "") : content).match(/^ {0,3}(`+|~+)\s*$/)?.[1];
508
+ if (closing?.[0] === fence.marker && closing.length >= fence.length) fence = void 0;
509
+ previousLineBlank = false;
510
+ return "";
511
+ }).join("\n");
512
+ }
513
+ function extractMarkdownTemplateImportSpecifiers(template) {
514
+ const visible = stripMarkdownCode(template).replace(/(`+)[\s\S]*?\1/g, "").replace(/(!?\[[^\]]*\])\([^)]*\)/g, "$1").replace(/^ {0,3}\[[^\]]+\]:\s*\S+/gm, "").replace(/<[^>]*>/g, "");
515
+ const specifiers = /* @__PURE__ */ new Set();
516
+ for (const match of visible.matchAll(/@(\.\.?\/[^\s<>{}[\]]+)/g)) {
517
+ const token = match[1];
518
+ const trailing = token.match(/[.,;:!?)]*$/)?.[0] || "";
519
+ specifiers.add(token.slice(0, token.length - trailing.length));
520
+ }
521
+ return [...specifiers];
522
+ }
523
+ function parseMarkdownTemplateRequest(id) {
524
+ const queryIndex = id.indexOf("?");
525
+ const path = id.split(/[?#]/, 1)[0];
526
+ if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
527
+ const query = id.slice(queryIndex + 1).split("#", 1)[0];
528
+ if (!new URLSearchParams(query).has(markdownTemplateModuleQuery)) return;
529
+ return { path };
530
+ }
531
+ function renderMarkdownTemplateModule(template, sourceId, imports = {}) {
532
+ return [
533
+ `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
534
+ `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
535
+ `const vitehubMarkdownTemplateSourceId = ${JSON.stringify(sourceId)}`,
536
+ `const vitehubMarkdownTemplateImports = ${JSON.stringify(imports)}`,
537
+ "export default function render(data = {}) {",
538
+ " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data, sourceId: vitehubMarkdownTemplateSourceId, resolveImport: (specifier, importer) => vitehubMarkdownTemplateImports[`${importer}\\0${specifier}`] })",
539
+ "}",
540
+ ""
541
+ ].join("\n");
542
+ }
543
+ function hasViteRawQuery(path) {
544
+ const queryIndex = path.indexOf("?");
545
+ return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
546
+ }
547
+ async function resolveViteRawSpecifier(path, rootDir) {
548
+ if (path.startsWith("/@fs/")) return path.slice(5);
549
+ if (!rootDir || !path.startsWith("/")) return path;
550
+ const rootRelativePath = path.slice(1);
551
+ const publicPath = resolve(rootDir, "public", rootRelativePath);
552
+ try {
553
+ await stat(publicPath);
554
+ return publicPath;
555
+ } catch (error) {
556
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
557
+ return resolve(rootDir, rootRelativePath);
558
+ }
559
+ }
560
+ function createViteRawPlugin(rootDir, frameworkRuntime) {
561
+ return {
562
+ name: "vitehub-vite-raw",
563
+ setup(build) {
564
+ build.onResolve({
565
+ filter: /^@vite-hub\/markdown-template$/,
566
+ namespace: viteMarkdownTemplateNamespace
567
+ }, async (args) => {
568
+ if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
569
+ return build.resolve("vite-hub/_internal/markdown-template", {
570
+ importer: args.importer,
571
+ kind: args.kind,
572
+ resolveDir: args.resolveDir
573
+ });
574
+ });
575
+ build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
576
+ if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
577
+ const markdownTemplate = parseMarkdownTemplateRequest(args.path);
578
+ const raw = hasViteRawQuery(args.path);
579
+ if (!markdownTemplate && !raw) return;
580
+ const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
581
+ let pluginData = args.pluginData;
582
+ if (markdownTemplate) pluginData = {
583
+ ...args.pluginData,
584
+ [skipMarkdownTemplateResolve]: true
585
+ };
586
+ const resolved = await build.resolve(specifier, {
587
+ importer: args.importer,
588
+ kind: args.kind,
589
+ namespace: args.namespace,
590
+ pluginData,
591
+ resolveDir: args.resolveDir,
592
+ with: args.with
593
+ });
594
+ if (resolved.errors.length) return {
595
+ errors: resolved.errors,
596
+ warnings: resolved.warnings
597
+ };
598
+ if (resolved.external) return {
599
+ external: true,
600
+ namespace: resolved.namespace,
601
+ path: resolved.path,
602
+ pluginData: resolved.pluginData,
603
+ sideEffects: resolved.sideEffects,
604
+ suffix: resolved.suffix,
605
+ warnings: resolved.warnings
606
+ };
607
+ if (resolved.namespace !== "file") return {
608
+ errors: [{ text: markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this raw import in a caller plugin.` }],
609
+ warnings: resolved.warnings
610
+ };
611
+ return {
612
+ namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
613
+ path: resolved.path,
614
+ pluginData: resolved.pluginData,
615
+ sideEffects: resolved.sideEffects,
616
+ suffix: resolved.suffix,
617
+ warnings: resolved.warnings
618
+ };
619
+ });
620
+ build.onLoad({
621
+ filter: /.*/,
622
+ namespace: viteRawNamespace
623
+ }, async (args) => ({
624
+ contents: await readFile(args.path),
625
+ loader: "text"
626
+ }));
627
+ build.onLoad({
628
+ filter: /.*/,
629
+ namespace: viteMarkdownTemplateNamespace
630
+ }, async (args) => ({
631
+ contents: await (async () => {
632
+ const template = await readFile(args.path, "utf8");
633
+ const imports = {};
634
+ const visited = new Set([args.path]);
635
+ const visit = async (source, importer) => {
636
+ for (const specifier of extractMarkdownTemplateImportSpecifiers(source)) {
637
+ const key = `${importer}\0${specifier}`;
638
+ if (imports[key]) continue;
639
+ const resolved = await build.resolve(specifier, {
640
+ importer,
641
+ kind: "import-statement",
642
+ pluginData: {
643
+ ...args.pluginData,
644
+ [skipMarkdownTemplateResolve]: true
645
+ },
646
+ resolveDir: dirname(importer)
647
+ });
648
+ if (resolved.errors.length) return Promise.reject(new Error(resolved.errors.map((error) => error.text).join("\n")));
649
+ if (resolved.external || resolved.namespace !== "file") throw new Error(`[vitehub] Could not resolve Markdown template import ${JSON.stringify(specifier)} from ${JSON.stringify(importer)} to a file.`);
650
+ const imported = {
651
+ id: resolved.path,
652
+ template: await readFile(resolved.path, "utf8")
653
+ };
654
+ imports[key] = imported;
655
+ if (!visited.has(imported.id)) {
656
+ visited.add(imported.id);
657
+ await visit(imported.template, imported.id);
658
+ }
659
+ }
660
+ };
661
+ await visit(template, args.path);
662
+ return renderMarkdownTemplateModule(template, args.path, imports);
663
+ })(),
664
+ loader: "js",
665
+ resolveDir: dirname(args.path)
666
+ }));
667
+ }
668
+ };
669
+ }
670
+ function createFileUrlPlugin() {
671
+ return {
672
+ name: "vitehub-file-url",
673
+ setup(build) {
674
+ build.onResolve({ filter: /^file:/ }, (args) => ({ path: fileURLToPath(args.path) }));
675
+ }
676
+ };
677
+ }
678
+ async function bundleEsmEntry(entryFile, outfile, options = {}) {
679
+ options.signal?.throwIfAborted();
680
+ const format = options.format || "esm";
681
+ const platform = options.platform || "neutral";
682
+ const viteAliasPlugin = createViteAliasPlugin(options.alias);
683
+ const frameworkRuntime = (Array.isArray(options.alias) ? options.alias.flatMap((alias) => typeof alias.find === "string" ? [alias.find] : []) : Object.keys(options.alias || {})).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
684
+ const plugins = [];
685
+ const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd());
686
+ if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
687
+ plugins.push(...options.plugins ?? [], createFileUrlPlugin());
688
+ if (viteAliasPlugin) plugins.push(viteAliasPlugin);
689
+ plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
690
+ const result = await build({
691
+ absWorkingDir: options.workingDir,
692
+ banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
693
+ "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
694
+ " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
695
+ " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
696
+ " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
697
+ "}"
698
+ ] : []].filter(Boolean).join("\n") } : void 0,
699
+ bundle: true,
700
+ conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
701
+ entryPoints: [entryFile],
702
+ external: options.external,
703
+ format,
704
+ logLevel: "silent",
705
+ mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
706
+ resolveExtensions: options.extensions,
707
+ minifyIdentifiers: options.minifyIdentifiers,
708
+ minifyWhitespace: options.minifyWhitespace,
709
+ outfile,
710
+ packages: options.packages,
711
+ platform,
712
+ preserveSymlinks: options.preserveSymlinks,
713
+ plugins,
714
+ sourcemap: false,
715
+ target: "es2022",
716
+ write: options.signal ? false : true
717
+ });
718
+ options.signal?.throwIfAborted();
719
+ if (options.signal) {
720
+ await Promise.all((result.outputFiles ?? []).map(async (output) => {
721
+ await mkdir(dirname(output.path), { recursive: true });
722
+ options.signal.throwIfAborted();
723
+ await writeFile(output.path, output.contents, { signal: options.signal });
724
+ }));
725
+ options.signal.throwIfAborted();
726
+ }
727
+ }
728
+ //#endregion
729
+ //#region ../internal/src/build/provider-output-sources.ts
730
+ function escapeRegExp(value) {
731
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
732
+ }
733
+ /** Rewrites retained source paths after their snapshot is published to a durable generated directory. */
734
+ function rewriteRetainedProviderSourcePaths(contents, retainedSourcesDir, publishedSourcesDir, importers) {
735
+ const serializedRetainedSourcesDir = JSON.stringify(retainedSourcesDir).slice(1, -1);
736
+ const serializedPublishedSourcesDir = JSON.stringify(publishedSourcesDir).slice(1, -1);
737
+ const publishedSeparator = publishedSourcesDir.includes("\\") && !publishedSourcesDir.includes("/") ? "\\" : "/";
738
+ const serializedPublishedSeparator = publishedSeparator === "\\" ? "\\\\" : "/";
739
+ const serializedPath = new RegExp(`${escapeRegExp(serializedRetainedSourcesDir)}((?:(?:\\\\\\\\|/)[^"\\\\/]*)+)`, "g");
740
+ const normalizedContents = contents.replace(serializedPath, (_matched, suffix) => {
741
+ return `${serializedPublishedSourcesDir}${suffix.replaceAll("\\\\", serializedPublishedSeparator).replaceAll("/", serializedPublishedSeparator)}`;
742
+ });
743
+ const replacements = [
744
+ [`${pathToFileURL(retainedSourcesDir).href}/`, `${pathToFileURL(publishedSourcesDir).href}/`],
745
+ [`${serializedRetainedSourcesDir}\\\\`, `${serializedPublishedSourcesDir}${serializedPublishedSeparator}`],
746
+ [`${serializedRetainedSourcesDir}/`, `${serializedPublishedSourcesDir}${serializedPublishedSeparator}`],
747
+ [`${retainedSourcesDir}\\`, `${publishedSourcesDir}${publishedSeparator}`],
748
+ [`${retainedSourcesDir}/`, `${publishedSourcesDir}${publishedSeparator}`]
749
+ ];
750
+ if (importers) replacements.push([`${createImportPath(importers.retained, retainedSourcesDir)}/`, `${createImportPath(importers.published, publishedSourcesDir)}/`]);
751
+ return replacements.reduce((rewritten, [source, destination]) => rewritten.replaceAll(source, destination), normalizedContents);
752
+ }
753
+ /** Repoints retained-tree symlinks at the matching paths in their durable published tree. */
754
+ async function rebasePublishedProviderSourceLinks(stagedSourcesDir, retainedSourcesDir, publishedSourcesDir) {
755
+ const visit = async (directory) => {
756
+ const entries = await readdir(directory, { withFileTypes: true });
757
+ await Promise.all(entries.map(async (entry) => {
758
+ const path = resolve(directory, entry.name);
759
+ if (entry.isDirectory()) {
760
+ await visit(path);
761
+ return;
762
+ }
763
+ if (!entry.isSymbolicLink()) return;
764
+ const link = await readlink(path);
765
+ const retainedTarget = resolve(dirname(path), link);
766
+ if (!pathContains$1(retainedSourcesDir, retainedTarget)) return;
767
+ const target = resolve(publishedSourcesDir, relative(retainedSourcesDir, retainedTarget));
768
+ const publishedLink = resolve(publishedSourcesDir, relative(stagedSourcesDir, path));
769
+ const targetType = await stat(retainedTarget).catch((error) => {
770
+ if (error.code === "ENOENT") return void 0;
771
+ throw error;
772
+ });
773
+ if (!targetType) return;
774
+ const type = targetType.isDirectory() ? process.platform === "win32" ? "junction" : "dir" : "file";
775
+ const rebasedLink = type === "junction" ? target : relative(dirname(publishedLink), target) || ".";
776
+ await rm(path, {
777
+ force: true,
778
+ recursive: true
779
+ });
780
+ await symlink(rebasedLink, path, type);
781
+ }));
782
+ };
783
+ await visit(stagedSourcesDir);
784
+ }
785
+ /** Copies durable generated sources into deployment artifacts and rewrites their serialized runtime location. */
786
+ async function publishProviderSourcesToDeploymentOutputs(options) {
787
+ await Promise.all(options.destinations.map(async (destination) => {
788
+ options.signal?.throwIfAborted();
789
+ await rm(destination.sourcesDir, {
790
+ force: true,
791
+ recursive: true
792
+ });
793
+ if (!existsSync(options.publishedSourcesDir)) return;
794
+ await mkdir(dirname(destination.sourcesDir), { recursive: true });
795
+ await cp(options.publishedSourcesDir, destination.sourcesDir, { recursive: true });
796
+ await rebasePublishedProviderSourceLinks(destination.sourcesDir, options.publishedSourcesDir, destination.sourcesDir);
797
+ await Promise.all(destination.files.map(async (file) => {
798
+ const contents = await readFile(file, "utf8");
799
+ const rewritten = rewriteRetainedProviderSourcePaths(contents, options.publishedSourcesDir, destination.runtimeSourcesDir);
800
+ if (rewritten !== contents) await writeFile(file, rewritten, {
801
+ encoding: "utf8",
802
+ signal: options.signal
803
+ });
804
+ }));
805
+ options.signal?.throwIfAborted();
806
+ }));
807
+ }
808
+ async function rebaseCapturedAbsoluteSourceLinks(stagedSourcesDir, sourceRoot, publishedSourcesDir) {
809
+ const visit = async (directory) => {
810
+ const entries = await readdir(directory, { withFileTypes: true });
811
+ await Promise.all(entries.map(async (entry) => {
812
+ const path = resolve(directory, entry.name);
813
+ if (entry.isDirectory()) {
814
+ await visit(path);
815
+ return;
816
+ }
817
+ if (!entry.isSymbolicLink()) return;
818
+ const link = await readlink(path);
819
+ if (!isAbsolute(link) || !pathContains$1(sourceRoot, link)) return;
820
+ const target = resolve(stagedSourcesDir, relative(sourceRoot, link));
821
+ const publishedTarget = resolve(publishedSourcesDir, relative(sourceRoot, link));
822
+ const targetType = await stat(target).catch((error) => {
823
+ if (error.code === "ENOENT") return void 0;
824
+ throw error;
825
+ });
826
+ if (!targetType) return;
827
+ const type = targetType.isDirectory() ? process.platform === "win32" ? "junction" : "dir" : "file";
828
+ const rebasedLink = type === "junction" ? publishedTarget : relative(dirname(path), target) || ".";
829
+ await rm(path, {
830
+ force: true,
831
+ recursive: true
832
+ });
833
+ await symlink(rebasedLink, path, type);
834
+ }));
835
+ };
836
+ await visit(stagedSourcesDir);
837
+ }
838
+ /** Rewrites both sides of absolute aliases and retains the original key for imports that still use it. */
839
+ function retainProviderOutputAliases(aliases, retainedSources) {
840
+ const retainedAliases = Object.create(null);
841
+ const retain = (specifier, target) => {
842
+ if (!Object.hasOwn(retainedAliases, specifier)) retainedAliases[specifier] = target;
843
+ };
844
+ for (const [specifier, target] of Object.entries(aliases)) {
845
+ const retainedSpecifier = retainedSources.resolve(specifier);
846
+ const retainedTarget = retainedSources.resolve(target);
847
+ retain(specifier, retainedTarget);
848
+ if (retainedSpecifier !== specifier) retain(retainedSpecifier, retainedTarget);
849
+ }
850
+ return retainedAliases;
851
+ }
852
+ const ignoredSourceDirectories = new Set([
853
+ ".git",
854
+ ".netlify",
855
+ ".nuxt",
856
+ ".output",
857
+ ".vercel",
858
+ ".vitehub",
859
+ ".vitest-tmp",
860
+ "coverage",
861
+ "dist",
862
+ "node_modules"
863
+ ]);
864
+ const ignoredGeneratedDirectories = new Set([".vitehub", ".vitest-tmp"]);
865
+ function isTransientSourceDirectory(path) {
866
+ return basename(path).startsWith(".drizzle-generate-");
867
+ }
868
+ function pathContains$1(parent, child) {
869
+ const nested = relative(parent, child);
870
+ return !nested || !nested.startsWith(`..${sep}`) && nested !== ".." && !isAbsolute(nested);
871
+ }
872
+ function packageRoot(file) {
873
+ let current = statSync(file).isDirectory() ? file : dirname(file);
874
+ while (true) {
875
+ if (existsSync(resolve(current, "package.json"))) return current;
876
+ const parent = dirname(current);
877
+ if (parent === current) return statSync(file).isDirectory() ? file : dirname(file);
878
+ current = parent;
879
+ }
880
+ }
881
+ function boundSourceRootOutsideTemporaryStaging(root, source) {
882
+ if (!pathContains$1(root, resolve(tmpdir()))) return root;
883
+ return statSync(source).isDirectory() ? source : dirname(source);
884
+ }
885
+ function dependencyRoots(root) {
886
+ const resolvedRoot = realpathSync(root);
887
+ const roots = [];
888
+ let current = resolvedRoot;
889
+ while (current !== dirname(current)) {
890
+ const nested = resolve(current, "node_modules");
891
+ if (existsSync(nested)) roots.push(nested);
892
+ if (basename(current) === "node_modules") {
893
+ roots.push(current);
894
+ break;
895
+ }
896
+ current = dirname(current);
897
+ }
898
+ return [...new Set(roots)];
899
+ }
900
+ async function linkDependencies(source, target, resolveLinkTarget = (source) => source) {
901
+ await mkdir(target, { recursive: true });
902
+ for (const entry of await readdir(source, { withFileTypes: true })) {
903
+ if (entry.name === ".bin" || entry.name === ".pnpm") continue;
904
+ const sourceEntry = resolve(source, entry.name);
905
+ const targetEntry = resolve(target, entry.name);
906
+ if (!existsSync(sourceEntry)) continue;
907
+ const resolvedSourceEntry = realpathSync(sourceEntry);
908
+ if (!statSync(resolvedSourceEntry).isDirectory()) continue;
909
+ if (entry.name.startsWith("@") && entry.isDirectory() && !entry.isSymbolicLink()) {
910
+ await linkDependencies(sourceEntry, targetEntry, resolveLinkTarget);
911
+ continue;
912
+ }
913
+ if (existsSync(targetEntry)) continue;
914
+ await symlink(resolveLinkTarget(resolvedSourceEntry), targetEntry, process.platform === "win32" ? "junction" : "dir");
915
+ }
916
+ }
917
+ /** Removes retained provider output after readers release it, tolerating transient filesystem contention. */
918
+ async function removeProviderOutputArtifactDir(path) {
919
+ await rm(path, {
920
+ force: true,
921
+ maxRetries: 5,
922
+ recursive: true,
923
+ retryDelay: 50
924
+ });
925
+ }
926
+ function sourceClosureRoot(root) {
927
+ let current = root;
928
+ while (true) {
929
+ if (existsSync(resolve(current, ".git")) || existsSync(resolve(current, "pnpm-workspace.yaml"))) return current;
930
+ const parent = dirname(current);
931
+ if (parent === current) return root;
932
+ current = parent;
933
+ }
934
+ }
935
+ function commonSourceRoot(root, paths) {
936
+ let common = root;
937
+ for (const path of paths) while (!pathContains$1(common, path)) {
938
+ const parent = dirname(common);
939
+ if (parent === common) return common;
940
+ common = parent;
941
+ }
942
+ return common;
943
+ }
944
+ const traceableSourceExtensions = new Set([
945
+ ".cjs",
946
+ ".cts",
947
+ ".js",
948
+ ".jsx",
949
+ ".mjs",
950
+ ".mts",
951
+ ".ts",
952
+ ".tsx"
953
+ ]);
954
+ function resolveComputedModuleSource(file, specifier, resolveFrom = file) {
955
+ try {
956
+ const imported = createRequire(resolveFrom).resolve(specifier);
957
+ return existsSync(imported) ? imported : void 0;
958
+ } catch {
959
+ return;
960
+ }
961
+ }
962
+ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
963
+ const masked = maskSourceLiterals(source);
964
+ const bindings = /* @__PURE__ */ new Map();
965
+ for (const match of source.matchAll(/\b(?:const|let|var)\s+([A-Z_$][\w$]*)\s*=\s*([`"'])(.*?)\2/gis)) {
966
+ const quoteOffset = match[0].indexOf(match[2]);
967
+ if (!/\b(?:const|let|var)\s+[A-Z_$][\w$]*\s*=\s*$/i.test(masked.slice(match.index, match.index + quoteOffset))) continue;
968
+ if (match[2] === "`" && match[3].includes("${")) continue;
969
+ bindings.set(match[1], match[3]);
970
+ }
971
+ const createRequireNames = new Set(["createRequire"]);
972
+ for (const match of source.matchAll(/\bimport\s+(?:[A-Z_$][\w$]*\s*,\s*)?\{([^}]*)\}\s*from\s*([`"'])(?:node:)?module\2/gis)) for (const specifier of match[1].split(",")) {
973
+ const binding = /^\s*createRequire(?:\s+as\s+([A-Z_$][\w$]*))?\s*$/i.exec(specifier)?.[1];
974
+ if (binding) createRequireNames.add(binding);
975
+ }
976
+ for (const match of source.matchAll(/\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\s*\(\s*([`"'])(?:node:)?module\2\s*\)/gis)) for (const property of match[1].split(",")) {
977
+ const binding = /^\s*createRequire(?:\s*:\s*([A-Z_$][\w$]*))?\s*$/i.exec(property)?.[1];
978
+ if (binding) createRequireNames.add(binding);
979
+ }
980
+ const createRequireNamespaceNames = /* @__PURE__ */ new Set();
981
+ for (const match of source.matchAll(/\bimport\s+([A-Z_$][\w$]*)\s*(?:,\s*(?:\{[^}]*\}|\*\s+as\s+[A-Z_$][\w$]*))?\s+from\s*([`"'])(?:node:)?module\2/gis)) createRequireNamespaceNames.add(match[1]);
982
+ for (const match of source.matchAll(/\bimport\s*\*\s*as\s*([A-Z_$][\w$]*)\s*from\s*([`"'])(?:node:)?module\2/gis)) createRequireNamespaceNames.add(match[1]);
983
+ for (const match of source.matchAll(/\b(?:const|let|var)\s+([A-Z_$][\w$]*)\s*=\s*require\s*\(\s*([`"'])(?:node:)?module\2\s*\)/gis)) createRequireNamespaceNames.add(match[1]);
984
+ const isCreateRequireExpression = (expression) => {
985
+ const normalized = expression.replace(/\s/g, "");
986
+ if (createRequireNames.has(normalized)) return true;
987
+ const namespace = /^([A-Z_$][\w$]*)\.createRequire$/i.exec(normalized)?.[1];
988
+ return Boolean(namespace && createRequireNamespaceNames.has(namespace));
989
+ };
990
+ const staticModuleSpecifier = (expression) => {
991
+ const normalized = expression.trim();
992
+ const binding = /^([A-Z_$][\w$]*)$/i.exec(normalized)?.[1];
993
+ if (binding) return bindings.get(binding);
994
+ const literal = /^([`"'])([\s\S]*)\1$/.exec(normalized);
995
+ if (!literal || literal[1] === "`" && literal[2].includes("${")) return void 0;
996
+ return literal[2];
997
+ };
998
+ const createRequireBase = (expression) => {
999
+ const normalized = expression.trim();
1000
+ if (normalized === "import.meta.url" || normalized === "__filename") return file;
1001
+ const direct = staticModuleSpecifier(normalized);
1002
+ if (direct) return direct;
1003
+ const newUrl = /^new\s+URL\s*\(/i.exec(normalized);
1004
+ if (!newUrl) return file;
1005
+ const openParen = normalized.indexOf("(", newUrl.index);
1006
+ const closeParen = findMatching(normalized, openParen, "(", ")");
1007
+ if (closeParen === void 0 || normalized.slice(closeParen + 1).trim()) return file;
1008
+ const [relativeUrl, baseUrl] = splitTopLevel(normalized.slice(openParen + 1, closeParen));
1009
+ const relativePath = relativeUrl ? staticModuleSpecifier(relativeUrl) : void 0;
1010
+ if (!relativePath || baseUrl?.replace(/\s/g, "") !== "import.meta.url") return file;
1011
+ return fileURLToPath(new URL(relativePath, pathToFileURL(file)));
1012
+ };
1013
+ const boundRequireBases = /* @__PURE__ */ new Map();
1014
+ for (const match of masked.matchAll(/\b(?:const|let|var)\s+([A-Z_$][\w$]*)\s*=\s*([A-Z_$][\w$]*(?:\s*\.\s*createRequire)?)\s*\(/gi)) {
1015
+ if (!isCreateRequireExpression(match[2])) continue;
1016
+ const openParen = match.index + match[0].lastIndexOf("(");
1017
+ const closeParen = findMatching(masked, openParen, "(", ")");
1018
+ const base = closeParen === void 0 ? file : createRequireBase(source.slice(openParen + 1, closeParen));
1019
+ boundRequireBases.set(match[1], base);
1020
+ }
1021
+ const boundResolveBases = /* @__PURE__ */ new Map();
1022
+ const recordBoundResolve = (properties, base) => {
1023
+ const resolveBinding = properties.split(",").map((property) => /^\s*resolve(?:\s*:\s*([A-Z_$][\w$]*))?\s*$/i.exec(property)).find(Boolean);
1024
+ if (resolveBinding) boundResolveBases.set(resolveBinding[1] ?? "resolve", base);
1025
+ };
1026
+ for (const match of masked.matchAll(/\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*([A-Z_$][\w$]*(?:\s*\.\s*createRequire)?)\s*\(/gi)) {
1027
+ if (!isCreateRequireExpression(match[2])) continue;
1028
+ const openParen = match.index + match[0].lastIndexOf("(");
1029
+ const closeParen = findMatching(masked, openParen, "(", ")");
1030
+ const base = closeParen === void 0 ? file : createRequireBase(source.slice(openParen + 1, closeParen));
1031
+ recordBoundResolve(match[1], base);
1032
+ }
1033
+ for (const match of masked.matchAll(/\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*([A-Z_$][\w$]*)\b/gi)) {
1034
+ const base = boundRequireBases.get(match[2]);
1035
+ if (base) recordBoundResolve(match[1], base);
1036
+ }
1037
+ const paths = [];
1038
+ const recordRequest = (specifier, kind, resolveFrom = file) => {
1039
+ if (!specifier.startsWith(".") && !isAbsolute(specifier)) {
1040
+ onRuntimePackageRequest?.({
1041
+ kind,
1042
+ resolveFrom,
1043
+ specifier
1044
+ });
1045
+ return;
1046
+ }
1047
+ const imported = resolveComputedModuleSource(file, specifier, resolveFrom);
1048
+ if (imported) paths.push(imported);
1049
+ };
1050
+ for (const request of [
1051
+ {
1052
+ kind: "dynamic-import",
1053
+ pattern: /\bimport\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi
1054
+ },
1055
+ {
1056
+ kind: "require-call",
1057
+ pattern: /\brequire\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi
1058
+ },
1059
+ {
1060
+ kind: "dynamic-import",
1061
+ pattern: /\bimport\s*\.\s*meta\s*\.\s*resolve\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi
1062
+ },
1063
+ {
1064
+ kind: "require-resolve",
1065
+ pattern: /\brequire\s*\.\s*resolve\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi
1066
+ },
1067
+ {
1068
+ kind: "require-call",
1069
+ pattern: /\bmodule\s*\.\s*require\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi
1070
+ }
1071
+ ]) for (const match of masked.matchAll(request.pattern)) {
1072
+ const specifier = bindings.get(match[1]);
1073
+ if (specifier) recordRequest(specifier, request.kind);
1074
+ }
1075
+ for (const match of masked.matchAll(/\b([A-Z_$][\w$]*(?:\s*\.\s*createRequire)?)\s*\(/gi)) {
1076
+ if (!isCreateRequireExpression(match[1])) continue;
1077
+ const openParen = match.index + match[0].lastIndexOf("(");
1078
+ const closeParen = findMatching(masked, openParen, "(", ")");
1079
+ if (closeParen === void 0) continue;
1080
+ const invocation = /^\s*(?:\.\s*resolve\s*)?\(/i.exec(masked.slice(closeParen + 1));
1081
+ if (!invocation) continue;
1082
+ const invocationOpenParen = closeParen + 1 + invocation[0].lastIndexOf("(");
1083
+ const invocationCloseParen = findMatching(masked, invocationOpenParen, "(", ")");
1084
+ if (invocationCloseParen === void 0) continue;
1085
+ const [target] = splitTopLevel(source.slice(invocationOpenParen + 1, invocationCloseParen));
1086
+ const specifier = target ? staticModuleSpecifier(target) : void 0;
1087
+ if (specifier) recordRequest(specifier, /\.\s*resolve/i.test(invocation[0]) ? "require-resolve" : "require-call", createRequireBase(source.slice(openParen + 1, closeParen)));
1088
+ }
1089
+ for (const match of masked.matchAll(/\b([A-Z_$][\w$]*)\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi)) {
1090
+ const specifier = bindings.get(match[2]);
1091
+ if (!specifier) continue;
1092
+ const requireFrom = boundRequireBases.get(match[1]);
1093
+ if (requireFrom) recordRequest(specifier, "require-call", requireFrom);
1094
+ const resolveFrom = boundResolveBases.get(match[1]);
1095
+ if (resolveFrom) recordRequest(specifier, "require-resolve", resolveFrom);
1096
+ }
1097
+ for (const match of masked.matchAll(/\b([A-Z_$][\w$]*)\s*\.\s*resolve\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi)) {
1098
+ const resolveFrom = boundRequireBases.get(match[1]);
1099
+ if (!resolveFrom) continue;
1100
+ const specifier = bindings.get(match[2]);
1101
+ if (specifier) recordRequest(specifier, "require-resolve", resolveFrom);
1102
+ }
1103
+ for (const request of [
1104
+ {
1105
+ kind: "dynamic-import",
1106
+ pattern: /\bimport\s*\.\s*meta\s*\.\s*resolve\s*\(\s*([`"'])(.*?)\1/gi,
1107
+ prefix: /\bimport\s*\.\s*meta\s*\.\s*resolve\s*\(\s*$/i
1108
+ },
1109
+ {
1110
+ kind: "require-resolve",
1111
+ pattern: /\brequire\s*\.\s*resolve\s*\(\s*([`"'])(.*?)\1/gi,
1112
+ prefix: /\brequire\s*\.\s*resolve\s*\(\s*$/i
1113
+ },
1114
+ {
1115
+ kind: "require-call",
1116
+ pattern: /\bmodule\s*\.\s*require\s*\(\s*([`"'])(.*?)\1/gi,
1117
+ prefix: /\bmodule\s*\.\s*require\s*\(\s*$/i
1118
+ }
1119
+ ]) for (const match of source.matchAll(request.pattern)) {
1120
+ const quoteOffset = match[0].indexOf(match[1]);
1121
+ if (!request.prefix.test(masked.slice(match.index, match.index + quoteOffset))) continue;
1122
+ const specifier = match[2];
1123
+ if (match[1] === "`" && specifier.includes("${")) continue;
1124
+ recordRequest(specifier, request.kind);
1125
+ }
1126
+ for (const match of source.matchAll(/\b([A-Z_$][\w$]*)\s*\(\s*([`"'])(.*?)\2/gis)) {
1127
+ const requireFrom = boundRequireBases.get(match[1]);
1128
+ const resolveFrom = boundResolveBases.get(match[1]);
1129
+ if (!requireFrom && !resolveFrom) continue;
1130
+ const quoteOffset = match[0].indexOf(match[2]);
1131
+ if (!/\b[A-Z_$][\w$]*\s*\(\s*$/i.test(masked.slice(match.index, match.index + quoteOffset))) continue;
1132
+ const specifier = match[3];
1133
+ if (match[2] === "`" && specifier.includes("${")) continue;
1134
+ if (requireFrom) recordRequest(specifier, "require-call", requireFrom);
1135
+ if (resolveFrom) recordRequest(specifier, "require-resolve", resolveFrom);
1136
+ }
1137
+ for (const match of source.matchAll(/\b([A-Z_$][\w$]*)\s*\.\s*resolve\s*\(\s*([`"'])(.*?)\2/gis)) {
1138
+ const resolveFrom = boundRequireBases.get(match[1]);
1139
+ if (!resolveFrom) continue;
1140
+ const quoteOffset = match[0].indexOf(match[2]);
1141
+ if (!/\b[A-Z_$][\w$]*\s*\.\s*resolve\s*\(\s*$/i.test(masked.slice(match.index, match.index + quoteOffset))) continue;
1142
+ const specifier = match[3];
1143
+ if (match[2] === "`" && specifier.includes("${")) continue;
1144
+ recordRequest(specifier, "require-resolve", resolveFrom);
1145
+ }
1146
+ return paths;
1147
+ }
1148
+ async function traceImportedSources(paths, root, configuredRoots) {
1149
+ const entries = paths.filter((path) => traceableSourceExtensions.has(extname(path)));
1150
+ if (!entries.length) return /* @__PURE__ */ new Set();
1151
+ const physicalRoot = realpathSync(root);
1152
+ const traceBuildVariants = [
1153
+ { platform: "node" },
1154
+ { platform: "neutral" },
1155
+ {
1156
+ conditions: [
1157
+ "workerd",
1158
+ "worker",
1159
+ "browser",
1160
+ "default"
1161
+ ],
1162
+ platform: "neutral"
1163
+ },
1164
+ {
1165
+ conditions: [
1166
+ "vitehub-hosted",
1167
+ "workerd",
1168
+ "worker",
1169
+ "browser",
1170
+ "default"
1171
+ ],
1172
+ platform: "neutral"
1173
+ },
1174
+ {
1175
+ conditions: [
1176
+ "vitehub-hosted",
1177
+ "node",
1178
+ "default"
1179
+ ],
1180
+ platform: "node"
1181
+ }
1182
+ ];
1183
+ try {
1184
+ const importedSources = new Set(entries);
1185
+ const scannedModuleRequestSources = /* @__PURE__ */ new Set();
1186
+ const tracedEntries = /* @__PURE__ */ new Set();
1187
+ let pendingEntries = entries;
1188
+ while (pendingEntries.length) {
1189
+ const tracedBatch = pendingEntries;
1190
+ pendingEntries = [];
1191
+ for (const entry of tracedBatch) tracedEntries.add(entry);
1192
+ const queriedResourceSources = /* @__PURE__ */ new Set();
1193
+ const importedSourceHints = /* @__PURE__ */ new Set();
1194
+ const results = [];
1195
+ for (const variant of traceBuildVariants) {
1196
+ const [result] = await Promise.allSettled([build({
1197
+ absWorkingDir: root,
1198
+ bundle: true,
1199
+ entryPoints: tracedBatch,
1200
+ format: "esm",
1201
+ logLevel: "silent",
1202
+ metafile: true,
1203
+ outdir: resolve(root, ".vitehub-provider-trace"),
1204
+ packages: "bundle",
1205
+ ...variant,
1206
+ plugins: [{
1207
+ name: "vitehub-provider-vite-resource-query",
1208
+ setup(traceBuild) {
1209
+ const resolvingPackageImportHint = "vitehubResolvingPackageImportHint";
1210
+ traceBuild.onResolve({ filter: /^\.\.?\// }, (request) => {
1211
+ const source = request.resolveDir && resolve(request.resolveDir, request.path.split(/[?#]/, 1)[0]);
1212
+ if (source && existsSync(source)) importedSourceHints.add(source);
1213
+ });
1214
+ traceBuild.onResolve({ filter: /^#/ }, async (request) => {
1215
+ if (request.pluginData?.[resolvingPackageImportHint]) return void 0;
1216
+ if (!request.importer) return void 0;
1217
+ const suffixOffset = request.path.slice(1).search(/[?#]/);
1218
+ const packageImport = suffixOffset === -1 ? request.path : request.path.slice(0, suffixOffset + 1);
1219
+ const resolution = await traceBuild.resolve(packageImport, {
1220
+ importer: request.importer,
1221
+ kind: request.kind,
1222
+ namespace: request.namespace,
1223
+ pluginData: {
1224
+ ...request.pluginData,
1225
+ [resolvingPackageImportHint]: true
1226
+ },
1227
+ resolveDir: request.resolveDir,
1228
+ with: request.with
1229
+ });
1230
+ if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && existsSync(resolution.path)) importedSourceHints.add(resolution.path);
1231
+ });
1232
+ const resolvingBarePackageHint = "vitehubResolvingBarePackageHint";
1233
+ traceBuild.onResolve({ filter: /^[^./#]/ }, async (request) => {
1234
+ if (request.pluginData?.[resolvingBarePackageHint]) return void 0;
1235
+ if (!request.importer) return void 0;
1236
+ const suffixOffset = request.path.search(/[?#]/);
1237
+ const packageImport = suffixOffset === -1 ? request.path : request.path.slice(0, suffixOffset);
1238
+ const resolution = await traceBuild.resolve(packageImport, {
1239
+ importer: request.importer,
1240
+ kind: request.kind,
1241
+ namespace: request.namespace,
1242
+ pluginData: {
1243
+ ...request.pluginData,
1244
+ [resolvingBarePackageHint]: true
1245
+ },
1246
+ resolveDir: request.resolveDir,
1247
+ with: request.with
1248
+ });
1249
+ const source = pathContains$1(root, resolution.path) ? resolution.path : pathContains$1(physicalRoot, resolution.path) ? resolve(root, relative(physicalRoot, resolution.path)) : void 0;
1250
+ if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && source && existsSync(source) && !relative(root, source).split(sep).includes("node_modules")) importedSourceHints.add(source);
1251
+ return {
1252
+ external: true,
1253
+ path: request.path
1254
+ };
1255
+ });
1256
+ traceBuild.onResolve({ filter: /[?#]/ }, (request) => {
1257
+ if (request.pluginData?.[resolvingPackageImportHint]) return void 0;
1258
+ const resourcePath = request.path.split(/[?#]/, 1)[0];
1259
+ let resourceSource;
1260
+ if (request.resolveDir && (resourcePath.startsWith("./") || resourcePath.startsWith("../"))) resourceSource = resolve(request.resolveDir, resourcePath);
1261
+ else if (request.resolveDir && resourcePath.startsWith("/")) {
1262
+ const projectRoot = configuredRoots.filter((configuredRoot) => pathContains$1(configuredRoot, request.resolveDir)).sort((left, right) => right.length - left.length)[0] ?? root;
1263
+ const rootRelativePath = resourcePath.slice(1);
1264
+ const publicSource = resolve(projectRoot, "public", rootRelativePath);
1265
+ resourceSource = existsSync(publicSource) ? publicSource : resolve(projectRoot, rootRelativePath);
1266
+ }
1267
+ if (resourceSource && existsSync(resourceSource)) queriedResourceSources.add(resourceSource);
1268
+ return {
1269
+ external: true,
1270
+ path: request.path
1271
+ };
1272
+ });
1273
+ traceBuild.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (request) => {
1274
+ const sourcePath = pathContains$1(root, request.path) ? request.path : pathContains$1(physicalRoot, request.path) ? resolve(root, relative(physicalRoot, request.path)) : void 0;
1275
+ if (!sourcePath || relative(root, sourcePath).split(sep).includes("node_modules")) return void 0;
1276
+ const source = await readFile(request.path, "utf8").catch(() => void 0);
1277
+ if (!source) return void 0;
1278
+ const runtimeRequests = /* @__PURE__ */ new Map();
1279
+ traceComputedModuleSources(request.path, source, (runtimeRequest) => {
1280
+ runtimeRequests.set(`${runtimeRequest.kind}\0${runtimeRequest.resolveFrom}\0${runtimeRequest.specifier}`, runtimeRequest);
1281
+ });
1282
+ await Promise.all([...runtimeRequests.values()].map(async (runtimeRequest) => {
1283
+ const resolveFrom = runtimeRequest.resolveFrom ?? request.path;
1284
+ const resolution = await traceBuild.resolve(runtimeRequest.specifier, {
1285
+ importer: resolveFrom,
1286
+ kind: runtimeRequest.kind,
1287
+ namespace: request.namespace,
1288
+ resolveDir: dirname(resolveFrom)
1289
+ });
1290
+ const resolvedSource = pathContains$1(root, resolution.path) ? resolution.path : pathContains$1(physicalRoot, resolution.path) ? resolve(root, relative(physicalRoot, resolution.path)) : void 0;
1291
+ if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && resolvedSource && existsSync(resolvedSource) && !relative(root, resolvedSource).split(sep).includes("node_modules")) importedSourceHints.add(resolvedSource);
1292
+ }));
1293
+ });
1294
+ }
1295
+ }],
1296
+ write: false
1297
+ })]);
1298
+ if (result?.status === "fulfilled") results.push(result.value);
1299
+ }
1300
+ for (const result of results) for (const path of Object.keys(result.metafile.inputs)) importedSources.add(resolve(root, path));
1301
+ for (const path of importedSourceHints) {
1302
+ importedSources.add(path);
1303
+ if (traceableSourceExtensions.has(extname(path)) && !tracedEntries.has(path)) pendingEntries.push(path);
1304
+ }
1305
+ for (const resourceSource of queriedResourceSources) {
1306
+ importedSources.add(resourceSource);
1307
+ if (traceableSourceExtensions.has(extname(resourceSource)) && !tracedEntries.has(resourceSource)) pendingEntries.push(resourceSource);
1308
+ }
1309
+ const moduleRequestSources = [...importedSources].filter((path) => traceableSourceExtensions.has(extname(path)) && !scannedModuleRequestSources.has(path));
1310
+ const moduleRequestSourceContents = await Promise.all(moduleRequestSources.map(async (path) => [path, await readFile(path, "utf8")]));
1311
+ for (const [file, source] of moduleRequestSourceContents) {
1312
+ scannedModuleRequestSources.add(file);
1313
+ for (const imported of traceComputedModuleSources(file, source)) {
1314
+ importedSources.add(imported);
1315
+ if (traceableSourceExtensions.has(extname(imported)) && !tracedEntries.has(imported) && !pendingEntries.includes(imported)) pendingEntries.push(imported);
1316
+ }
1317
+ }
1318
+ }
1319
+ return importedSources;
1320
+ } catch {
1321
+ return new Set(entries);
1322
+ }
1323
+ }
1324
+ function symlinkSourcesForRequestedPath(root, path) {
1325
+ const sources = [];
1326
+ let current = path;
1327
+ while (pathContains$1(root, current)) {
1328
+ if (lstatSync(current).isSymbolicLink()) sources.push(current);
1329
+ if (current === root) break;
1330
+ current = dirname(current);
1331
+ }
1332
+ return sources.reverse();
1333
+ }
1334
+ function packageMetadataSourcesForPath(root, path) {
1335
+ const sources = [];
1336
+ let current = statSync(path).isDirectory() ? path : dirname(path);
1337
+ while (pathContains$1(root, current)) {
1338
+ const packageJson = resolve(current, "package.json");
1339
+ if (existsSync(packageJson)) sources.push(packageJson);
1340
+ if (current === root) break;
1341
+ current = dirname(current);
1342
+ }
1343
+ return sources;
1344
+ }
1345
+ function parseJsonWithComments(source) {
1346
+ let output = "";
1347
+ let blockComment = false;
1348
+ let lineComment = false;
1349
+ let quoted = false;
1350
+ for (let index = 0; index < source.length; index += 1) {
1351
+ const char = source[index];
1352
+ const next = source[index + 1];
1353
+ if (lineComment) {
1354
+ if (char === "\n" || char === "\r") {
1355
+ lineComment = false;
1356
+ output += char;
1357
+ } else output += " ";
1358
+ continue;
1359
+ }
1360
+ if (blockComment) {
1361
+ if (char === "*" && next === "/") {
1362
+ blockComment = false;
1363
+ output += " ";
1364
+ index += 1;
1365
+ } else output += char === "\n" || char === "\r" ? char : " ";
1366
+ continue;
1367
+ }
1368
+ if (!quoted && char === "/" && next === "/") {
1369
+ lineComment = true;
1370
+ output += " ";
1371
+ index += 1;
1372
+ continue;
1373
+ }
1374
+ if (!quoted && char === "/" && next === "*") {
1375
+ blockComment = true;
1376
+ output += " ";
1377
+ index += 1;
1378
+ continue;
1379
+ }
1380
+ output += char;
1381
+ if (char === "\"") {
1382
+ let backslashes = 0;
1383
+ for (let previous = index - 1; source[previous] === "\\"; previous -= 1) backslashes += 1;
1384
+ if (backslashes % 2 === 0) quoted = !quoted;
1385
+ }
1386
+ }
1387
+ let withoutTrailingCommas = "";
1388
+ quoted = false;
1389
+ for (let index = 0; index < output.length; index += 1) {
1390
+ const char = output[index];
1391
+ if (char === "\"") {
1392
+ let backslashes = 0;
1393
+ for (let previous = index - 1; output[previous] === "\\"; previous -= 1) backslashes += 1;
1394
+ if (backslashes % 2 === 0) quoted = !quoted;
1395
+ }
1396
+ if (!quoted && char === ",") {
1397
+ let next = index + 1;
1398
+ while (/\s/.test(output[next] ?? "")) next += 1;
1399
+ if (output[next] === "}" || output[next] === "]") continue;
1400
+ }
1401
+ withoutTrailingCommas += char;
1402
+ }
1403
+ return JSON.parse(withoutTrailingCommas);
1404
+ }
1405
+ function resolveTsconfigReference(config, reference) {
1406
+ const candidates = reference.startsWith(".") || isAbsolute(reference) ? [
1407
+ resolve(dirname(config), reference),
1408
+ resolve(dirname(config), `${reference}.json`),
1409
+ resolve(dirname(config), reference, "tsconfig.json")
1410
+ ] : [reference, `${reference}/tsconfig.json`];
1411
+ for (const candidate of candidates) try {
1412
+ const resolved = isAbsolute(candidate) ? candidate : createRequire(config).resolve(candidate);
1413
+ if (existsSync(resolved)) return resolved;
1414
+ } catch {}
1415
+ }
1416
+ async function tsconfigSourcesForPaths(root, paths) {
1417
+ const pending = [];
1418
+ for (const path of paths) {
1419
+ let current = statSync(path).isDirectory() ? path : dirname(path);
1420
+ while (pathContains$1(root, current)) {
1421
+ const config = resolve(current, "tsconfig.json");
1422
+ if (existsSync(config)) {
1423
+ pending.push(config);
1424
+ break;
1425
+ }
1426
+ if (current === root) break;
1427
+ current = dirname(current);
1428
+ }
1429
+ }
1430
+ const sources = /* @__PURE__ */ new Set();
1431
+ while (pending.length) {
1432
+ const config = pending.pop();
1433
+ if (sources.has(config)) continue;
1434
+ sources.add(config);
1435
+ try {
1436
+ const parsed = parseJsonWithComments(await readFile(config, "utf8"));
1437
+ const references = Array.isArray(parsed.extends) ? parsed.extends : parsed.extends ? [parsed.extends] : [];
1438
+ for (const reference of references) {
1439
+ const resolved = resolveTsconfigReference(config, reference);
1440
+ if (resolved && !sources.has(resolved)) pending.push(resolved);
1441
+ }
1442
+ } catch {}
1443
+ }
1444
+ return [...sources];
1445
+ }
1446
+ /** Retains one build generation's source trees while preserving every module's import base. */
1447
+ async function retainProviderOutputSources(options) {
1448
+ const artifactDir = resolve(options.artifactDir);
1449
+ const paths = [...new Set((options.paths ?? []).filter(isAbsolute).map((path) => resolve(path)).filter(existsSync))];
1450
+ const configuredRoots = [...new Set(options.roots.map((root) => resolve(root)).filter(existsSync))];
1451
+ const sourceRootByPath = /* @__PURE__ */ new Map();
1452
+ const packageRoots = /* @__PURE__ */ new Set();
1453
+ for (const path of paths) {
1454
+ const configuredRoot = configuredRoots.filter((root) => pathContains$1(root, path)).sort((left, right) => right.length - left.length)[0];
1455
+ const pathSegments = configuredRoot ? relative(configuredRoot, path).split(sep) : [];
1456
+ const nestedInRetainedOutput = pathSegments.includes(".vitehub") || pathSegments.includes("node_modules");
1457
+ const discoveredPackageRoot = packageRoot(path);
1458
+ const hasNestedPackage = Boolean(configuredRoot && nestedInRetainedOutput && discoveredPackageRoot !== configuredRoot);
1459
+ const sourceRoot = boundSourceRootOutsideTemporaryStaging(configuredRoot && !hasNestedPackage ? sourceClosureRoot(configuredRoot) : discoveredPackageRoot, path);
1460
+ sourceRootByPath.set(path, sourceRoot);
1461
+ if (!configuredRoot || hasNestedPackage) packageRoots.add(sourceRoot);
1462
+ }
1463
+ for (const root of configuredRoots) sourceRootByPath.set(root, boundSourceRootOutsideTemporaryStaging(sourceClosureRoot(root), root));
1464
+ const roots = [...new Set(sourceRootByPath.values())];
1465
+ const retainedRoots = /* @__PURE__ */ new Map();
1466
+ const retainedPaths = /* @__PURE__ */ new Map();
1467
+ const pendingRoots = roots.entries();
1468
+ let firstFailure;
1469
+ const retainNextRoot = async () => {
1470
+ if (firstFailure) return;
1471
+ const next = pendingRoots.next();
1472
+ if (next.done) return;
1473
+ const [index, root] = next.value;
1474
+ const requested = paths.filter((path) => path !== root && pathContains$1(root, path));
1475
+ const nestedConfiguredRoots = configuredRoots.filter((path) => pathContains$1(root, path));
1476
+ const importedSources = await traceImportedSources(requested, root, nestedConfiguredRoots);
1477
+ const materializedSourcePaths = [...requested, ...importedSources];
1478
+ const tsconfigSources = await tsconfigSourcesForPaths(root, materializedSourcePaths);
1479
+ materializedSourcePaths.push(...tsconfigSources);
1480
+ const governingPackageMetadata = materializedSourcePaths.flatMap((path) => packageMetadataSourcesForPath(packageRoot(path), path));
1481
+ const captureRoot = commonSourceRoot(root, [
1482
+ ...importedSources,
1483
+ ...tsconfigSources,
1484
+ ...governingPackageMetadata
1485
+ ]);
1486
+ const retainedContainer = resolve(artifactDir, String(index));
1487
+ const retainedRoot = resolve(retainedContainer, relative(captureRoot, root));
1488
+ retainedRoots.set(root, retainedRoot);
1489
+ const materializedSources = [...new Set([
1490
+ ...materializedSourcePaths,
1491
+ ...governingPackageMetadata,
1492
+ ...materializedSourcePaths.flatMap((path) => packageMetadataSourcesForPath(captureRoot, path))
1493
+ ])];
1494
+ for (const source of materializedSources.filter((source) => !pathContains$1(root, source))) retainedPaths.set(source, resolve(retainedContainer, relative(captureRoot, source)));
1495
+ const requestedSymlinks = [...new Set([root, ...materializedSources].flatMap((path) => symlinkSourcesForRequestedPath(root, path)))].sort((left, right) => relative(root, left).split(sep).length - relative(root, right).split(sep).length);
1496
+ const configuredOutputClosures = nestedConfiguredRoots.flatMap((configuredRoot) => {
1497
+ const segments = relative(root, configuredRoot).split(sep);
1498
+ const ignoredIndex = segments.findIndex((segment) => ignoredGeneratedDirectories.has(segment));
1499
+ if (ignoredIndex === -1 || ignoredIndex === segments.length - 1) return [];
1500
+ return [resolve(root, ...segments.slice(0, ignoredIndex + 2))];
1501
+ });
1502
+ const requestedOutputRoots = requested.flatMap((path) => {
1503
+ const scopedRoot = nestedConfiguredRoots.filter((root) => pathContains$1(root, path)).sort((left, right) => right.length - left.length)[0] ?? root;
1504
+ const segments = relative(scopedRoot, path).split(sep);
1505
+ const ignoredIndex = segments.findIndex((segment) => ignoredSourceDirectories.has(segment));
1506
+ if (ignoredIndex === -1) return [];
1507
+ const generationIndex = ignoredGeneratedDirectories.has(segments[ignoredIndex]) && segments[ignoredIndex + 1]?.endsWith("-generations") ? ignoredIndex + 1 : -1;
1508
+ const retainedSourcesIndex = generationIndex === ignoredIndex + 1 ? segments.findIndex((segment, index) => index > generationIndex && (segment === "sources" || segment.endsWith("-sources"))) : -1;
1509
+ const generatedOutputIndex = ignoredGeneratedDirectories.has(segments[ignoredIndex]) ? Math.min(ignoredIndex + 1, segments.length - 1) : ignoredIndex;
1510
+ const outputRootIndex = retainedSourcesIndex !== -1 ? retainedSourcesIndex : generationIndex !== -1 ? Math.min(generationIndex + 1, segments.length - 1) : generatedOutputIndex;
1511
+ return [resolve(scopedRoot, ...segments.slice(0, outputRootIndex + 1))];
1512
+ });
1513
+ const nestedDependencyRoots = /* @__PURE__ */ new Map();
1514
+ const temporaryRoot = await mkdtemp(resolve(tmpdir(), "vitehub-provider-sources-"));
1515
+ const stagedContainer = resolve(temporaryRoot, "source");
1516
+ const stagedRoot = resolve(stagedContainer, relative(captureRoot, root));
1517
+ try {
1518
+ const shouldCopySource = (resolvedSource) => {
1519
+ if (pathContains$1(artifactDir, resolvedSource)) return false;
1520
+ if (isTransientSourceDirectory(resolvedSource) && !requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource))) return false;
1521
+ if (resolvedSource !== root && existsSync(resolve(resolvedSource, ".git")) && !requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) && ![...importedSources].some((path) => pathContains$1(resolvedSource, path)) && !nestedConfiguredRoots.some((configuredRoot) => pathContains$1(resolvedSource, configuredRoot)) && !configuredOutputClosures.some((outputRoot) => pathContains$1(outputRoot, resolvedSource))) return false;
1522
+ const nested = relative(root, resolvedSource);
1523
+ if (!nested) return true;
1524
+ const segments = nested.split(sep);
1525
+ const dependencyIndex = segments.indexOf("node_modules");
1526
+ if (dependencyIndex !== -1) {
1527
+ if (dependencyIndex === segments.length - 1 && dirname(resolvedSource) !== root) nestedDependencyRoots.set(resolve(retainedRoot, nested), resolvedSource);
1528
+ return false;
1529
+ }
1530
+ const first = segments[0];
1531
+ const containingConfiguredRoot = nestedConfiguredRoots.filter((configuredRoot) => pathContains$1(configuredRoot, resolvedSource)).sort((left, right) => right.length - left.length)[0];
1532
+ const scopedSegments = relative(containingConfiguredRoot ?? root, resolvedSource).split(sep);
1533
+ const scopedFirst = containingConfiguredRoot ? scopedSegments[0] : first;
1534
+ if (scopedFirst === ".nuxt") return requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || scopedSegments.length === 1 || scopedSegments.length === 2 && /^tsconfig(?:\.[^.]+)?\.json$/i.test(scopedSegments[1]);
1535
+ if (scopedSegments.some((segment) => ignoredGeneratedDirectories.has(segment)) || scopedFirst && ignoredSourceDirectories.has(scopedFirst) && !(packageRoots.has(root) && !containingConfiguredRoot && scopedFirst === "dist")) return requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || [...importedSources].some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || requestedOutputRoots.some((outputRoot) => pathContains$1(outputRoot, resolvedSource)) || configuredOutputClosures.some((outputRoot) => pathContains$1(outputRoot, resolvedSource) && !relative(outputRoot, resolvedSource).split(sep).some((segment) => ignoredSourceDirectories.has(segment))) && !nestedConfiguredRoots.some((configuredRoot) => pathContains$1(configuredRoot, resolvedSource)) || nestedConfiguredRoots.some((configuredRoot) => pathContains$1(resolvedSource, configuredRoot));
1536
+ return true;
1537
+ };
1538
+ await cp(root, stagedRoot, {
1539
+ recursive: true,
1540
+ filter: (source) => shouldCopySource(resolve(source))
1541
+ });
1542
+ const escapedMaterializedSources = materializedSources.filter((source) => !pathContains$1(root, source)).filter((source, _, sources) => !sources.some((parent) => parent !== source && statSync(parent).isDirectory() && pathContains$1(parent, source)));
1543
+ for (const source of escapedMaterializedSources) {
1544
+ const retainedSource = resolve(stagedContainer, relative(captureRoot, source));
1545
+ await mkdir(dirname(retainedSource), { recursive: true });
1546
+ await cp(realpathSync(source), retainedSource, { recursive: statSync(source).isDirectory() });
1547
+ }
1548
+ for (const source of requestedSymlinks) {
1549
+ const retainedSource = resolve(stagedRoot, relative(root, source));
1550
+ const sourceTarget = realpathSync(source);
1551
+ await rm(retainedSource, {
1552
+ force: true,
1553
+ recursive: true
1554
+ });
1555
+ await cp(sourceTarget, retainedSource, {
1556
+ recursive: statSync(source).isDirectory(),
1557
+ filter(candidate) {
1558
+ const physicalCandidate = resolve(candidate);
1559
+ const logicalCandidate = resolve(source, relative(sourceTarget, physicalCandidate));
1560
+ return materializedSources.some((path) => pathContains$1(logicalCandidate, path) || pathContains$1(path, logicalCandidate) || pathContains$1(physicalCandidate, path) || pathContains$1(path, physicalCandidate)) && shouldCopySource(logicalCandidate);
1561
+ }
1562
+ });
1563
+ }
1564
+ await rebaseCapturedAbsoluteSourceLinks(stagedContainer, captureRoot, retainedContainer);
1565
+ await mkdir(dirname(retainedContainer), { recursive: true });
1566
+ try {
1567
+ await rename(stagedContainer, retainedContainer);
1568
+ } catch (error) {
1569
+ if (error.code !== "EXDEV") throw error;
1570
+ await cp(stagedContainer, retainedContainer, { recursive: true });
1571
+ }
1572
+ const resolveRetainedDependencyTarget = (source) => {
1573
+ if (!pathContains$1(root, source) || relative(root, source).split(sep).includes("node_modules")) return source;
1574
+ const retainedSource = resolve(retainedRoot, relative(root, source));
1575
+ return existsSync(retainedSource) ? retainedSource : source;
1576
+ };
1577
+ for (const dependencies of dependencyRoots(root)) await linkDependencies(dependencies, resolve(retainedRoot, "node_modules"), resolveRetainedDependencyTarget);
1578
+ for (const source of escapedMaterializedSources) {
1579
+ const sourceDirectory = statSync(source).isDirectory() ? source : dirname(source);
1580
+ for (const dependencies of dependencyRoots(sourceDirectory)) await linkDependencies(dependencies, pathContains$1(captureRoot, dependencies) ? resolve(retainedContainer, relative(captureRoot, dependencies)) : resolve(retainedContainer, "node_modules"), resolveRetainedDependencyTarget);
1581
+ }
1582
+ for (const [target, dependencies] of nestedDependencyRoots) await linkDependencies(dependencies, target, resolveRetainedDependencyTarget);
1583
+ } finally {
1584
+ await rm(temporaryRoot, {
1585
+ force: true,
1586
+ recursive: true
1587
+ });
1588
+ }
1589
+ await retainNextRoot();
1590
+ };
1591
+ await Promise.all(Array.from({ length: Math.min(2, roots.length) }, async () => {
1592
+ try {
1593
+ await retainNextRoot();
1594
+ } catch (error) {
1595
+ firstFailure ??= { error };
1596
+ }
1597
+ }));
1598
+ if (firstFailure) throw firstFailure.error;
1599
+ return { resolve(path) {
1600
+ if (!isAbsolute(path)) return path;
1601
+ const resolvedPath = resolve(path);
1602
+ const retainedPath = retainedPaths.get(resolvedPath);
1603
+ if (retainedPath) return retainedPath;
1604
+ const root = sourceRootByPath.get(resolvedPath) ?? roots.filter((candidate) => pathContains$1(candidate, resolvedPath)).sort((left, right) => right.length - left.length)[0];
1605
+ return root ? resolve(retainedRoots.get(root), relative(root, resolvedPath)) : path;
1606
+ } };
1607
+ }
1608
+ //#endregion
1609
+ //#region ../internal/src/build/vercel-config.ts
1610
+ function createVercelConfigJson() {
1611
+ return {
1612
+ routes: [{ handle: "filesystem" }, {
1613
+ src: "/(.*)",
1614
+ dest: "/__server"
1615
+ }],
1616
+ version: 3
1617
+ };
1618
+ }
1619
+ function createNodeFunctionConfig(extra = {}) {
1620
+ return {
1621
+ handler: "index.mjs",
1622
+ launcherType: "Nodejs",
1623
+ runtime: "nodejs22.x",
1624
+ shouldAddHelpers: false,
1625
+ supportsResponseStreaming: true,
1626
+ ...extra
1627
+ };
1628
+ }
1629
+ //#endregion
1630
+ //#region ../internal/src/build/provider-output-catalog.ts
1631
+ var ProviderOutputCatalog = class {
1632
+ #appliedCloudflareContributions = /* @__PURE__ */ new Map();
1633
+ #cloudflareContributions = /* @__PURE__ */ new Map();
1634
+ #runtimeContributions = /* @__PURE__ */ new Map();
1635
+ #runtimeContributionsByGeneration = /* @__PURE__ */ new WeakMap();
1636
+ #deploymentContributionSequence = 0;
1637
+ #deploymentContributions = /* @__PURE__ */ new Map();
1638
+ #deploymentGenerationRefs = /* @__PURE__ */ new WeakMap();
1639
+ #deploymentGenerations = /* @__PURE__ */ new Set();
1640
+ #pendingDeploymentDiscards = [];
1641
+ #takenDeploymentContributions = /* @__PURE__ */ new Map();
1642
+ appliedCloudflareContributions() {
1643
+ return this.#appliedCloudflareContributions.values();
1644
+ }
1645
+ appliedCloudflareContributionEntries() {
1646
+ return this.#appliedCloudflareContributions.entries();
1647
+ }
1648
+ clearAppliedCloudflareContributions() {
1649
+ this.#appliedCloudflareContributions.clear();
1650
+ }
1651
+ cloudflareContributions() {
1652
+ return this.#cloudflareContributions.entries();
1653
+ }
1654
+ inheritCloudflareContributions(catalog) {
1655
+ for (const [owner, contribution] of catalog.appliedCloudflareContributionEntries()) this.#appliedCloudflareContributions.set(owner, contribution);
1656
+ for (const [owner, contribution] of [...catalog.cloudflareContributions(), ...this.#cloudflareContributions]) this.#cloudflareContributions.set(owner, contribution);
1657
+ }
1658
+ replaceAppliedCloudflareContribution(owner, contribution) {
1659
+ this.#appliedCloudflareContributions.set(owner, contribution);
1660
+ }
1661
+ replaceCloudflareContribution(owner, contribution) {
1662
+ this.#cloudflareContributions.set(owner, contribution);
1663
+ }
1664
+ replaceRuntimeContribution(contribution, generation) {
1665
+ if (!generation) {
1666
+ this.#runtimeContributions.set(contribution.owner, contribution);
1667
+ return;
1668
+ }
1669
+ let contributions = this.#runtimeContributionsByGeneration.get(generation);
1670
+ if (!contributions) {
1671
+ contributions = /* @__PURE__ */ new Map();
1672
+ this.#runtimeContributionsByGeneration.set(generation, contributions);
1673
+ }
1674
+ contributions.set(contribution.owner, contribution);
1675
+ }
1676
+ runtimeContribution(product, generation) {
1677
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.get(product);
1678
+ }
1679
+ runtimeContributions(generation) {
1680
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.entries() ?? (/* @__PURE__ */ new Map()).entries();
1681
+ }
1682
+ resetRuntimeContributions() {
1683
+ this.#runtimeContributions.clear();
1684
+ }
1685
+ createDeploymentGeneration() {
1686
+ const generation = { valid: true };
1687
+ this.#trackDeploymentGeneration(generation);
1688
+ return generation;
1689
+ }
1690
+ replaceDeploymentContribution(contribution, generation) {
1691
+ const entry = {
1692
+ contribution,
1693
+ generation,
1694
+ sequence: this.#deploymentContributionSequence++
1695
+ };
1696
+ if (generation && !generation.valid) {
1697
+ this.#queueDeploymentDiscard(entry);
1698
+ return;
1699
+ }
1700
+ this.#restoreDeploymentContribution(entry);
1701
+ }
1702
+ resetDeploymentContributions(generation) {
1703
+ if (!generation) {
1704
+ for (const reference of this.#deploymentGenerations) {
1705
+ const current = reference.deref();
1706
+ if (current) current.valid = false;
1707
+ }
1708
+ this.#deploymentGenerations.clear();
1709
+ for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
1710
+ for (const taken of this.#takenDeploymentContributions.values()) {
1711
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
1712
+ for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback);
1713
+ }
1714
+ this.#deploymentContributions.clear();
1715
+ this.#takenDeploymentContributions.clear();
1716
+ return;
1717
+ }
1718
+ generation.valid = false;
1719
+ this.#deleteDeploymentGeneration(generation);
1720
+ for (const [owner, entries] of this.#deploymentContributions) {
1721
+ for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
1722
+ const remaining = entries.filter((entry) => entry.generation !== generation);
1723
+ if (remaining.length) this.#deploymentContributions.set(owner, remaining);
1724
+ else this.#deploymentContributions.delete(owner);
1725
+ }
1726
+ for (const [contribution, taken] of this.#takenDeploymentContributions) {
1727
+ const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
1728
+ taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
1729
+ for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
1730
+ if (taken.entry.generation !== generation) continue;
1731
+ this.#takenDeploymentContributions.delete(contribution);
1732
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
1733
+ for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
1734
+ else this.#restoreDeploymentContribution(fallback);
1735
+ }
1736
+ }
1737
+ hasDeploymentContributions() {
1738
+ return this.#deploymentContributions.size > 0;
1739
+ }
1740
+ takeDeploymentContributions() {
1741
+ const contributions = [];
1742
+ for (const [owner, entries] of this.#deploymentContributions) {
1743
+ const entry = entries.at(-1);
1744
+ contributions.push(entry.contribution);
1745
+ this.#takenDeploymentContributions.set(entry.contribution, {
1746
+ committed: false,
1747
+ entry,
1748
+ entryDiscarded: false,
1749
+ fallbacks: entries.slice(0, -1)
1750
+ });
1751
+ this.#deploymentContributions.delete(owner);
1752
+ }
1753
+ return contributions;
1754
+ }
1755
+ deploymentContributionGeneration(contribution) {
1756
+ return this.#takenDeploymentContributions.get(contribution)?.entry.generation;
1757
+ }
1758
+ commitDeploymentContributions(contributions) {
1759
+ for (const contribution of contributions) {
1760
+ const taken = this.#takenDeploymentContributions.get(contribution);
1761
+ if (taken) taken.committed = true;
1762
+ }
1763
+ }
1764
+ async prepareDeploymentContributions(contributions) {
1765
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
1766
+ for (const contribution of contributions) {
1767
+ const taken = this.#takenDeploymentContributions.get(contribution);
1768
+ if (!taken || taken.entryDiscarded || !taken.entry.contribution.discard) continue;
1769
+ taken.entryDiscarded = true;
1770
+ discarded.push(Promise.resolve().then(taken.entry.contribution.discard));
1771
+ }
1772
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
1773
+ if (failure) throw failure.reason;
1774
+ }
1775
+ async completeDeploymentContributions(contributions) {
1776
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
1777
+ const completedGenerations = /* @__PURE__ */ new Set();
1778
+ for (const contribution of contributions) {
1779
+ const taken = this.#takenDeploymentContributions.get(contribution);
1780
+ if (!taken) continue;
1781
+ this.#takenDeploymentContributions.delete(contribution);
1782
+ const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
1783
+ for (const entry of entries) {
1784
+ if (entry.generation) completedGenerations.add(entry.generation);
1785
+ if (entry.contribution.discard) discarded.push(entry.contribution.discard());
1786
+ }
1787
+ }
1788
+ for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
1789
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
1790
+ if (failure) throw failure.reason;
1791
+ }
1792
+ rollbackDeploymentContributions(contributions) {
1793
+ for (const contribution of contributions) {
1794
+ const taken = this.#takenDeploymentContributions.get(contribution);
1795
+ if (!taken) continue;
1796
+ this.#takenDeploymentContributions.delete(contribution);
1797
+ for (const entry of [...taken.fallbacks, taken.entry]) this.#restoreDeploymentContribution(entry);
1798
+ }
1799
+ }
1800
+ #restoreDeploymentContribution(entry) {
1801
+ if (entry.generation && !entry.generation.valid) return;
1802
+ if (entry.generation) this.#trackDeploymentGeneration(entry.generation);
1803
+ const entries = this.#deploymentContributions.get(entry.contribution.owner) ?? [];
1804
+ const replaced = entries.findIndex((candidate) => candidate.generation === entry.generation);
1805
+ if (replaced >= 0) {
1806
+ if (entries[replaced].sequence > entry.sequence) return;
1807
+ entries.splice(replaced, 1);
1808
+ }
1809
+ entries.push(entry);
1810
+ entries.sort((left, right) => left.sequence - right.sequence);
1811
+ this.#deploymentContributions.set(entry.contribution.owner, entries);
1812
+ }
1813
+ #retireDeploymentGeneration(generation) {
1814
+ const pending = [...this.#deploymentContributions.values()].some((entries) => entries.some((entry) => entry.generation === generation));
1815
+ const taken = [...this.#takenDeploymentContributions.values()].some((entry) => entry.entry.generation === generation || entry.fallbacks.some((fallback) => fallback.generation === generation));
1816
+ if (!pending && !taken) this.#deleteDeploymentGeneration(generation);
1817
+ }
1818
+ #trackDeploymentGeneration(generation) {
1819
+ if (this.#deploymentGenerationRefs.has(generation)) return;
1820
+ const reference = new WeakRef(generation);
1821
+ this.#deploymentGenerationRefs.set(generation, reference);
1822
+ this.#deploymentGenerations.add(reference);
1823
+ }
1824
+ #deleteDeploymentGeneration(generation) {
1825
+ const reference = this.#deploymentGenerationRefs.get(generation);
1826
+ if (reference) this.#deploymentGenerations.delete(reference);
1827
+ this.#deploymentGenerationRefs.delete(generation);
1828
+ }
1829
+ #queueDeploymentDiscard(entry) {
1830
+ if (!entry.contribution.discard) return;
1831
+ const discard = Promise.resolve().then(entry.contribution.discard);
1832
+ discard.catch(() => {});
1833
+ this.#pendingDeploymentDiscards.push(discard);
1834
+ }
1835
+ };
1836
+ const providerOutputCatalogRegistry = globalThis;
1837
+ const providerOutputCatalogs = providerOutputCatalogRegistry.__vitehubProviderOutputCatalogs ??= /* @__PURE__ */ new WeakMap();
1838
+ const providerOutputCatalog = Symbol.for("vitehub.provider-output-catalog");
1839
+ function createProviderOutputCatalog() {
1840
+ return new ProviderOutputCatalog();
1841
+ }
1842
+ function useProviderOutputCatalog(config) {
1843
+ const owner = config;
1844
+ let catalog = owner[providerOutputCatalog] ?? providerOutputCatalogs.get(config);
1845
+ if (!catalog) catalog = createProviderOutputCatalog();
1846
+ owner[providerOutputCatalog] = catalog;
1847
+ providerOutputCatalogs.set(config, catalog);
1848
+ return catalog;
1849
+ }
1850
+ //#endregion
1851
+ //#region ../internal/src/build/vite.ts
1852
+ async function collectViteHubProviderImportAliases(plugins) {
1853
+ return Object.assign({}, ...await Promise.all(plugins.map(async (plugin) => await plugin.vitehub?.providerOutput?.getImportAliases?.() ?? {})));
1854
+ }
1855
+ const projectRootDirectoryMarkers = [
1856
+ ["server", "agents"],
1857
+ ["server", "channels"],
1858
+ ["server", "browsers"],
1859
+ ["server", "emails"],
1860
+ ["server", "schedules"],
1861
+ ["server", "workspaces"]
1862
+ ];
1863
+ const projectRootFileMarkers = [["package.json"]];
1864
+ function createNoExternalMerger(packageName) {
1865
+ return (current) => {
1866
+ if (current === true) return true;
1867
+ if (!current) return [packageName];
1868
+ const values = Array.isArray(current) ? current : [current];
1869
+ return values.includes(packageName) ? values : [...values, packageName];
1870
+ };
1871
+ }
1872
+ function isServerEnvironment(name, config) {
1873
+ return name === "ssr" || config.consumer === "server";
1874
+ }
1875
+ function includesNitroVitePlugin(value) {
1876
+ if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
1877
+ if (!value || typeof value !== "object") return false;
1878
+ return "name" in value && value.name === "nitro:main";
1879
+ }
1880
+ function hasNitroConfigContext(config) {
1881
+ return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
1882
+ }
1883
+ function shouldSkipViteProviderBuild(command, mode) {
1884
+ return command === "serve" || mode === "e2e";
1885
+ }
1886
+ function resolveViteHubProjectRoot(root, options = {}) {
1887
+ const resolvedRoot = resolve(root);
1888
+ const temporaryRoot = resolve(tmpdir());
1889
+ const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
1890
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
1891
+ if (basename(resolvedRoot) === "app") {
1892
+ const parent = dirname(resolvedRoot);
1893
+ if (parent !== sharedTemporaryRoot && hasProjectRootDirectoryMarker(parent)) return parent;
1894
+ }
1895
+ let current = resolvedRoot;
1896
+ while (true) {
1897
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
1898
+ if (hasProjectRootMarker(current)) return current;
1899
+ const parent = dirname(current);
1900
+ if (parent === current) return resolvedRoot;
1901
+ current = parent;
1902
+ }
1903
+ }
1904
+ function hasProjectRootDirectoryMarker(root) {
1905
+ for (const marker of projectRootDirectoryMarkers) try {
1906
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
1907
+ } catch (error) {
1908
+ if (error.code !== "ENOENT") throw error;
1909
+ }
1910
+ return false;
1911
+ }
1912
+ function hasProjectRootMarker(root) {
1913
+ if (hasProjectRootDirectoryMarker(root)) return true;
1914
+ for (const marker of projectRootFileMarkers) try {
1915
+ if (statSync(resolve(root, ...marker)).isFile()) return true;
1916
+ } catch (error) {
1917
+ if (error.code !== "ENOENT") throw error;
1918
+ }
1919
+ return false;
1920
+ }
1921
+ //#endregion
1922
+ //#region ../internal/src/build/deployment-output.ts
1923
+ const providerDeploymentOutputRegistry = globalThis;
1924
+ const providerDeploymentOutputWrites = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputWrites ??= /* @__PURE__ */ new Map();
1925
+ const providerDeploymentOutputFinalizations = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputFinalizations ??= /* @__PURE__ */ new WeakMap();
1926
+ const providerDeploymentOutputCompletedResets = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputCompletedResets ??= /* @__PURE__ */ new WeakMap();
1927
+ const providerDeploymentOutputRootStates = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputRootStates ??= /* @__PURE__ */ new Map();
1928
+ const providerDeploymentOutputOwnerOrder = [
1929
+ "agent",
1930
+ "database",
1931
+ "blob",
1932
+ "queue",
1933
+ "rate-limit",
1934
+ "schedule",
1935
+ "workflow",
1936
+ "vite-hub",
1937
+ "browser",
1938
+ "kv",
1939
+ "workspace"
1940
+ ];
1941
+ function throwIfProviderOutputAborted(signal) {
1942
+ if (!signal.aborted) return;
1943
+ throw signal.reason ?? new DOMException("Provider Output finalization aborted.", "AbortError");
1944
+ }
1945
+ async function settleWrites(writes) {
1946
+ const failure = (await Promise.allSettled(writes)).find((result) => result.status === "rejected");
1947
+ if (failure) throw failure.reason;
1948
+ }
1949
+ function resolveClientOutput(rootDir, clientOutDir) {
1950
+ const clientDir = resolve(rootDir, clientOutDir);
1951
+ return {
1952
+ clientDir,
1953
+ staticIndex: hasStaticIndex(clientDir)
1954
+ };
1955
+ }
1956
+ function createDefaultCloudflareStaticOutputDir(rootDir) {
1957
+ return resolve(rootDir, "dist", "client");
1958
+ }
1959
+ function resolveProviderOutputOwnershipFile(outputRoot, fileName) {
1960
+ if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw new TypeError(`Invalid Provider Output ownership file name: ${JSON.stringify(fileName)}`);
1961
+ return resolve(outputRoot, fileName);
1962
+ }
1963
+ async function readProviderOutputOwnershipFile(outputRoot, fileName) {
1964
+ try {
1965
+ const parsed = JSON.parse(await readFile(resolveProviderOutputOwnershipFile(outputRoot, fileName), "utf8"));
1966
+ if (!Array.isArray(parsed) || !parsed.every((value) => typeof value === "string")) throw new TypeError(`Invalid Provider Output ownership file schema: ${JSON.stringify(fileName)}`);
1967
+ return parsed;
1968
+ } catch (error) {
1969
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
1970
+ throw error;
1971
+ }
1972
+ }
1973
+ async function readCloudflareProviderDeploymentOutputState(rootDir, options) {
1974
+ const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
1975
+ let wranglerConfig = {};
1976
+ try {
1977
+ wranglerConfig = JSON.parse(await readFile(resolve(outputRoot, "wrangler.json"), "utf8"));
1978
+ } catch (error) {
1979
+ if (error.code !== "ENOENT") throw error;
1980
+ }
1981
+ return {
1982
+ wranglerConfig,
1983
+ wranglerConfigOwnership: await resolvePersistedProviderOutputOwnership(outputRoot, options.wranglerConfigOwnership, options.wranglerConfigOwnershipFiles)
1984
+ };
1985
+ }
1986
+ async function resolvePersistedProviderOutputOwnership(outputRoot, ownership, files) {
1987
+ if (!files || !Object.keys(files).length) return ownership;
1988
+ const arrays = { ...ownership?.arrays };
1989
+ await Promise.all(Object.entries(files).map(async ([field, fileName]) => {
1990
+ const current = arrays[field];
1991
+ if (!current) throw new TypeError(`Provider Output ownership file for ${JSON.stringify(field)} requires array ownership.`);
1992
+ arrays[field] = {
1993
+ ...current,
1994
+ values: [...await readProviderOutputOwnershipFile(outputRoot, fileName), ...current.values ?? []]
1995
+ };
1996
+ }));
1997
+ return {
1998
+ ...ownership,
1999
+ arrays
2000
+ };
2001
+ }
2002
+ async function writeProviderOutputOwnershipFiles(outputRoot, ownership, files) {
2003
+ await Promise.all(Object.entries(files ?? {}).map(async ([field, fileName]) => {
2004
+ const file = resolveProviderOutputOwnershipFile(outputRoot, fileName);
2005
+ const values = [...new Set(ownership?.arrays?.[field]?.values ?? [])];
2006
+ if (!values.length) {
2007
+ await rm(file, { force: true });
2008
+ return;
2009
+ }
2010
+ await mkdir(outputRoot, { recursive: true });
2011
+ await writeFile(file, `${JSON.stringify(values, null, 2)}\n`, "utf8");
2012
+ }));
2013
+ }
2014
+ function createDefaultVercelOutputRoot(rootDir) {
2015
+ return resolve(rootDir, ".vercel", "output");
2016
+ }
2017
+ function createDefaultNetlifyOutputRoot(rootDir) {
2018
+ return resolve(rootDir, ".netlify", "v1");
2019
+ }
2020
+ function assertNetlifyFunctionName(functionName) {
2021
+ if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
2022
+ }
2023
+ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
2024
+ assertNetlifyFunctionName(functionName);
2025
+ return resolve(functionsRoot, `${functionName}.mjs`);
2026
+ }
2027
+ async function appendNetlifyFunctionConfig(outfile, config) {
2028
+ if (!config) return;
2029
+ await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
2030
+ }
2031
+ async function writeCloudflareDeploymentOutput(options, signal) {
2032
+ signal?.throwIfAborted();
2033
+ const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
2034
+ const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
2035
+ const staticOutputDir = options.staticOutputDir ?? createDefaultCloudflareStaticOutputDir(options.rootDir);
2036
+ const copiesStaticOutput = Boolean(options.bundleEntry && staticIndex && resolve(clientDir) !== resolve(staticOutputDir));
2037
+ const files = Object.entries(options.files ?? {});
2038
+ const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
2039
+ if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw new Error(`Cloudflare output file conflicts with bundle outfile: ${workerOutfile}`);
2040
+ const backupRoot = copiesStaticOutput ? await mkdtemp(resolve(options.rootDir, ".vitehub-cloudflare-output-")) : void 0;
2041
+ const previousOutputRoot = backupRoot ? resolve(backupRoot, "output") : `${outputRoot}.previous`;
2042
+ const previousStaticOutputDir = backupRoot ? resolve(backupRoot, "static") : `${staticOutputDir}.previous`;
2043
+ if (!backupRoot) await rm(previousOutputRoot, {
2044
+ force: true,
2045
+ recursive: true
2046
+ });
2047
+ if (copiesStaticOutput && !backupRoot) await rm(previousStaticOutputDir, {
2048
+ force: true,
2049
+ recursive: true
2050
+ });
2051
+ let hadPreviousOutput = false;
2052
+ let hadPreviousStaticOutput = false;
2053
+ let publicationSucceeded = false;
2054
+ let publicationStarted = false;
2055
+ let outputRestorationSucceeded = false;
2056
+ let staticRestorationSucceeded = false;
2057
+ try {
2058
+ try {
2059
+ await cp(outputRoot, previousOutputRoot, { recursive: true });
2060
+ hadPreviousOutput = true;
2061
+ } catch (error) {
2062
+ if (error.code !== "ENOENT") throw error;
2063
+ }
2064
+ if (copiesStaticOutput) try {
2065
+ await cp(staticOutputDir, previousStaticOutputDir, { recursive: true });
2066
+ hadPreviousStaticOutput = true;
2067
+ } catch (error) {
2068
+ if (error.code !== "ENOENT") throw error;
2069
+ }
2070
+ publicationStarted = true;
2071
+ await mkdir(outputRoot, { recursive: true });
2072
+ const wranglerConfigOwnership = await resolvePersistedProviderOutputOwnership(outputRoot, options.wranglerConfigOwnership ?? { keys: options.wranglerConfigKeys }, options.wranglerConfigOwnershipFiles);
2073
+ const writes = [
2074
+ writeCloudflareWranglerConfig({
2075
+ outputRoot,
2076
+ rootDir: options.rootDir,
2077
+ wranglerConfig: options.wranglerConfig,
2078
+ wranglerConfigDefaults: options.wranglerConfigDefaults,
2079
+ wranglerConfigOwnership
2080
+ }),
2081
+ options.bundleEntry && staticIndex ? copyClientOutput(clientDir, staticOutputDir) : Promise.resolve(),
2082
+ ...files.map(([fileName, contents]) => writeFile(resolve(outputRoot, fileName), contents, "utf8"))
2083
+ ];
2084
+ if (options.bundleEntry && workerOutfile) {
2085
+ const stagedWorkerOutfile = `${workerOutfile}.pending`;
2086
+ writes.push((async () => {
2087
+ try {
2088
+ await rm(stagedWorkerOutfile, {
2089
+ force: true,
2090
+ recursive: true
2091
+ });
2092
+ await bundleEsmEntry(options.bundleEntry, stagedWorkerOutfile, {
2093
+ ...options.bundleOptions,
2094
+ rootDir: options.sourceRootDir ?? options.rootDir,
2095
+ signal
2096
+ });
2097
+ signal?.throwIfAborted();
2098
+ await rename(stagedWorkerOutfile, workerOutfile);
2099
+ } catch (error) {
2100
+ await rm(stagedWorkerOutfile, {
2101
+ force: true,
2102
+ recursive: true
2103
+ });
2104
+ throw error;
2105
+ }
2106
+ })());
2107
+ }
2108
+ await settleWrites(writes);
2109
+ await writeProviderOutputOwnershipFiles(outputRoot, options.wranglerConfigOwnership, options.wranglerConfigOwnershipFiles);
2110
+ signal?.throwIfAborted();
2111
+ publicationSucceeded = true;
2112
+ } catch (error) {
2113
+ if (publicationStarted) {
2114
+ await rm(outputRoot, {
2115
+ force: true,
2116
+ recursive: true
2117
+ });
2118
+ if (hadPreviousOutput) {
2119
+ await cp(previousOutputRoot, outputRoot, { recursive: true });
2120
+ outputRestorationSucceeded = true;
2121
+ }
2122
+ if (copiesStaticOutput) {
2123
+ await rm(staticOutputDir, {
2124
+ force: true,
2125
+ recursive: true
2126
+ });
2127
+ if (hadPreviousStaticOutput) {
2128
+ await cp(previousStaticOutputDir, staticOutputDir, { recursive: true });
2129
+ staticRestorationSucceeded = true;
2130
+ }
2131
+ }
2132
+ }
2133
+ throw error;
2134
+ } finally {
2135
+ if (!publicationStarted || publicationSucceeded || outputRestorationSucceeded || !hadPreviousOutput) await rm(previousOutputRoot, {
2136
+ force: true,
2137
+ recursive: true
2138
+ }).catch(() => void 0);
2139
+ if (copiesStaticOutput && (!publicationStarted || publicationSucceeded || staticRestorationSucceeded || !hadPreviousStaticOutput)) await rm(previousStaticOutputDir, {
2140
+ force: true,
2141
+ recursive: true
2142
+ }).catch(() => void 0);
2143
+ if (backupRoot) await rmdir(backupRoot).catch(() => void 0);
2144
+ }
2145
+ }
2146
+ async function copyVercelClientOutput(rootDir, clientDir, staticOutputDir) {
2147
+ const cloudflareOutputRoot = createDefaultCloudflareOutputRoot(rootDir);
2148
+ const outputRelativePath = relative(clientDir, cloudflareOutputRoot);
2149
+ const excludesCloudflareOutput = outputRelativePath && outputRelativePath !== ".." && !outputRelativePath.startsWith(`..${sep}`) && !isAbsolute(outputRelativePath);
2150
+ await copyClientOutput(clientDir, staticOutputDir);
2151
+ if (resolve(clientDir) === resolve(staticOutputDir) || !excludesCloudflareOutput) return;
2152
+ try {
2153
+ await readFile(resolve(cloudflareOutputRoot, "wrangler.json"));
2154
+ } catch (error) {
2155
+ if (error.code === "ENOENT") return;
2156
+ throw error;
2157
+ }
2158
+ await rm(resolve(staticOutputDir, outputRelativePath), {
2159
+ force: true,
2160
+ recursive: true
2161
+ });
2162
+ }
2163
+ async function writeVercelDeploymentOutput(options, signal) {
2164
+ signal?.throwIfAborted();
2165
+ const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
2166
+ const outputRoot = options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir);
2167
+ const stagedOutputRoot = `${outputRoot}.pending`;
2168
+ const previousOutputRoot = `${outputRoot}.previous`;
2169
+ const functionOutput = options.function ?? { kind: "root" };
2170
+ const serverFunctionName = functionOutput.kind === "root" ? "__server.func" : functionOutput.name;
2171
+ const config = options.config ?? (functionOutput.kind === "root" ? createVercelConfigJson() : {});
2172
+ const serverDir = resolve(stagedOutputRoot, "functions", serverFunctionName);
2173
+ const serverEntry = resolve(serverDir, "index.mjs");
2174
+ const staticOutputDir = options.staticOutputDir ?? resolve(outputRoot, "static");
2175
+ const staticRelativePath = relative(outputRoot, staticOutputDir);
2176
+ const staticInsideOutputRoot = !staticRelativePath.startsWith(`..${sep}`) && !isAbsolute(staticRelativePath);
2177
+ const externalStaticNeedsCommit = staticIndex && !staticInsideOutputRoot && resolve(clientDir) !== resolve(staticOutputDir);
2178
+ const stagedStaticOutputDir = staticInsideOutputRoot ? resolve(stagedOutputRoot, staticRelativePath) : externalStaticNeedsCommit ? `${staticOutputDir}.pending` : staticOutputDir;
2179
+ const previousStaticOutputDir = `${staticOutputDir}.previous`;
2180
+ let replacedOutput = false;
2181
+ let installedOutput = false;
2182
+ let replacedExternalStatic = false;
2183
+ let installedExternalStatic = false;
2184
+ try {
2185
+ await rm(stagedOutputRoot, {
2186
+ force: true,
2187
+ recursive: true
2188
+ });
2189
+ try {
2190
+ await cp(outputRoot, stagedOutputRoot, { recursive: true });
2191
+ } catch (error) {
2192
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
2193
+ }
2194
+ await mkdir(serverDir, { recursive: true });
2195
+ await rm(serverDir, {
2196
+ force: true,
2197
+ recursive: true
2198
+ });
2199
+ await mkdir(serverDir, { recursive: true });
2200
+ try {
2201
+ await cp(resolve(outputRoot, "functions", serverFunctionName, "node_modules"), resolve(serverDir, "node_modules"), { recursive: true });
2202
+ } catch (error) {
2203
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
2204
+ }
2205
+ await bundleEsmEntry(options.bundleEntry, serverEntry, {
2206
+ ...options.bundleOptions,
2207
+ rootDir: options.sourceRootDir ?? options.rootDir,
2208
+ signal
2209
+ });
2210
+ await writeFile(resolve(serverDir, ".vc-config.json"), `${stringifyProviderOutputConfig(options.functionConfig ?? createNodeFunctionConfig())}\n`, "utf8");
2211
+ const failedWrite = (await Promise.allSettled([writeProviderOutputConfig(resolve(stagedOutputRoot, "config.json"), config, { keys: options.configKeys }), staticIndex ? copyVercelClientOutput(options.rootDir, clientDir, stagedStaticOutputDir) : Promise.resolve()])).find((result) => result.status === "rejected");
2212
+ if (failedWrite?.status === "rejected") throw failedWrite.reason;
2213
+ signal?.throwIfAborted();
2214
+ rmSync(previousOutputRoot, {
2215
+ force: true,
2216
+ recursive: true
2217
+ });
2218
+ if (existsSync(outputRoot)) {
2219
+ renameSync(outputRoot, previousOutputRoot);
2220
+ replacedOutput = true;
2221
+ }
2222
+ try {
2223
+ renameSync(stagedOutputRoot, outputRoot);
2224
+ installedOutput = true;
2225
+ } catch (error) {
2226
+ if (replacedOutput && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
2227
+ replacedOutput = false;
2228
+ throw error;
2229
+ }
2230
+ signal?.throwIfAborted();
2231
+ if (externalStaticNeedsCommit) {
2232
+ rmSync(previousStaticOutputDir, {
2233
+ force: true,
2234
+ recursive: true
2235
+ });
2236
+ if (existsSync(staticOutputDir)) {
2237
+ renameSync(staticOutputDir, previousStaticOutputDir);
2238
+ replacedExternalStatic = true;
2239
+ }
2240
+ try {
2241
+ renameSync(stagedStaticOutputDir, staticOutputDir);
2242
+ installedExternalStatic = true;
2243
+ } catch (error) {
2244
+ if (replacedExternalStatic && existsSync(previousStaticOutputDir)) renameSync(previousStaticOutputDir, staticOutputDir);
2245
+ replacedExternalStatic = false;
2246
+ throw error;
2247
+ }
2248
+ signal?.throwIfAborted();
2249
+ }
2250
+ try {
2251
+ rmSync(previousOutputRoot, {
2252
+ force: true,
2253
+ recursive: true
2254
+ });
2255
+ } catch {}
2256
+ if (replacedExternalStatic) try {
2257
+ rmSync(previousStaticOutputDir, {
2258
+ force: true,
2259
+ recursive: true
2260
+ });
2261
+ } catch {}
2262
+ } catch (error) {
2263
+ await rm(stagedOutputRoot, {
2264
+ force: true,
2265
+ recursive: true
2266
+ });
2267
+ if (externalStaticNeedsCommit) await rm(stagedStaticOutputDir, {
2268
+ force: true,
2269
+ recursive: true
2270
+ });
2271
+ if (installedExternalStatic) rmSync(staticOutputDir, {
2272
+ force: true,
2273
+ recursive: true
2274
+ });
2275
+ if (replacedExternalStatic) {
2276
+ if (existsSync(previousStaticOutputDir)) renameSync(previousStaticOutputDir, staticOutputDir);
2277
+ }
2278
+ if (installedOutput) rmSync(outputRoot, {
2279
+ force: true,
2280
+ recursive: true
2281
+ });
2282
+ if (replacedOutput) {
2283
+ if (existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
2284
+ }
2285
+ throw error;
2286
+ }
2287
+ }
2288
+ async function writeNetlifyDeploymentOutput(options, signal) {
2289
+ signal?.throwIfAborted();
2290
+ const outputRoot = options.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir);
2291
+ const stagedOutputRoot = `${outputRoot}.pending`;
2292
+ const previousOutputRoot = `${outputRoot}.previous`;
2293
+ const functionsRoot = resolve(stagedOutputRoot, "functions");
2294
+ let replacedOutput = false;
2295
+ let installedOutput = false;
2296
+ await rm(stagedOutputRoot, {
2297
+ force: true,
2298
+ recursive: true
2299
+ });
2300
+ await rm(previousOutputRoot, {
2301
+ force: true,
2302
+ recursive: true
2303
+ });
2304
+ try {
2305
+ await cp(outputRoot, stagedOutputRoot, { recursive: true });
2306
+ } catch (error) {
2307
+ if (error.code !== "ENOENT") throw error;
2308
+ }
2309
+ const functionWrites = (options.functions ?? []).map(async (func) => {
2310
+ const outfile = resolveNetlifyFunctionFile(functionsRoot, func.functionName);
2311
+ await mkdir(dirname(outfile), { recursive: true });
2312
+ await bundleEsmEntry(func.bundleEntry, outfile, {
2313
+ ...func.bundleOptions,
2314
+ minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers,
2315
+ rootDir: options.sourceRootDir ?? options.rootDir,
2316
+ signal
2317
+ });
2318
+ await appendNetlifyFunctionConfig(outfile, func.config);
2319
+ });
2320
+ try {
2321
+ await mkdir(stagedOutputRoot, { recursive: true });
2322
+ await settleWrites([writeProviderOutputConfig(resolve(stagedOutputRoot, "config.json"), options.config ?? {}, { keys: options.configKeys }), ...functionWrites]);
2323
+ signal?.throwIfAborted();
2324
+ if (existsSync(outputRoot)) {
2325
+ renameSync(outputRoot, previousOutputRoot);
2326
+ replacedOutput = true;
2327
+ }
2328
+ renameSync(stagedOutputRoot, outputRoot);
2329
+ installedOutput = true;
2330
+ signal?.throwIfAborted();
2331
+ } catch (error) {
2332
+ await rm(stagedOutputRoot, {
2333
+ force: true,
2334
+ recursive: true
2335
+ });
2336
+ if (installedOutput) rmSync(outputRoot, {
2337
+ force: true,
2338
+ recursive: true
2339
+ });
2340
+ if (replacedOutput && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
2341
+ throw error;
2342
+ }
2343
+ try {
2344
+ rmSync(previousOutputRoot, {
2345
+ force: true,
2346
+ recursive: true
2347
+ });
2348
+ } catch {}
2349
+ }
2350
+ async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput, signal) {
2351
+ const cleanup = typeof cleanupInput === "function" ? await cleanupInput() : cleanupInput;
2352
+ signal?.throwIfAborted();
2353
+ const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
2354
+ if (!shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup)) return;
2355
+ const wranglerConfigOwnership = await resolvePersistedProviderOutputOwnership(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
2356
+ const writes = (cleanup.fileNames ?? []).map((fileName) => rm(resolve(outputRoot, fileName), {
2357
+ force: true,
2358
+ recursive: true
2359
+ }));
2360
+ writes.push(writeCloudflareWranglerConfig({
2361
+ outputRoot,
2362
+ rootDir,
2363
+ wranglerConfigOwnership
2364
+ }));
2365
+ await Promise.all(writes);
2366
+ await writeProviderOutputOwnershipFiles(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
2367
+ try {
2368
+ await rmdir(outputRoot);
2369
+ } catch (error) {
2370
+ const code = error.code;
2371
+ if (code !== "ENOENT" && code !== "ENOTEMPTY") throw error;
2372
+ }
2373
+ }
2374
+ function shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup) {
2375
+ return !cleanup.requirePersistedOwnership || Object.values(cleanup.wranglerConfigOwnershipFiles ?? {}).some((fileName) => existsSync(resolveProviderOutputOwnershipFile(outputRoot, fileName)));
2376
+ }
2377
+ async function cleanupVercelDeploymentOutput(rootDir, cleanup, signal) {
2378
+ signal?.throwIfAborted();
2379
+ const outputRoot = cleanup.outputRoot ?? createDefaultVercelOutputRoot(rootDir);
2380
+ const writes = [];
2381
+ if (cleanup.serverFunctionName) writes.push(rm(resolve(outputRoot, "functions", cleanup.serverFunctionName), {
2382
+ force: true,
2383
+ recursive: true
2384
+ }));
2385
+ writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
2386
+ await Promise.all(writes);
2387
+ }
2388
+ async function cleanupVercelDeploymentOutputs(rootDir, cleanup, signal) {
2389
+ await Promise.all((Array.isArray(cleanup) ? cleanup : [cleanup]).map((item) => cleanupVercelDeploymentOutput(rootDir, item, signal)));
2390
+ }
2391
+ async function cleanupNetlifyDeploymentOutput(rootDir, cleanup, signal) {
2392
+ signal?.throwIfAborted();
2393
+ const outputRoot = cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(rootDir);
2394
+ const functionsRoot = resolve(outputRoot, "functions");
2395
+ const writes = (cleanup.functionNames ?? []).map((functionName) => rm(resolveNetlifyFunctionFile(functionsRoot, functionName), {
2396
+ force: true,
2397
+ recursive: true
2398
+ }));
2399
+ writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
2400
+ await Promise.all(writes);
2401
+ }
2402
+ async function writeProviderDeploymentOutputsNow(options, signal, transaction) {
2403
+ signal?.throwIfAborted();
2404
+ const clientDir = resolve(options.rootDir, options.clientOutDir);
2405
+ await transaction?.snapshot(providerDeploymentOutputPaths(options), [clientDir]);
2406
+ const writes = [];
2407
+ if (options.cloudflare) writes.push(writeCloudflareDeploymentOutput({
2408
+ ...options.cloudflare,
2409
+ clientOutDir: options.clientOutDir,
2410
+ rootDir: options.rootDir,
2411
+ sourceRootDir: options.sourceRootDir
2412
+ }, signal));
2413
+ if (options.netlify) writes.push(writeNetlifyDeploymentOutput({
2414
+ ...options.netlify,
2415
+ clientOutDir: options.clientOutDir,
2416
+ rootDir: options.rootDir,
2417
+ sourceRootDir: options.sourceRootDir
2418
+ }, signal));
2419
+ if (options.vercel) writes.push(writeVercelDeploymentOutput({
2420
+ ...options.vercel,
2421
+ clientOutDir: options.clientOutDir,
2422
+ rootDir: options.rootDir,
2423
+ sourceRootDir: options.sourceRootDir
2424
+ }, signal));
2425
+ await settleWrites(writes);
2426
+ if (options.cloudflare && transaction) transaction.cloudflareWritten = true;
2427
+ signal?.throwIfAborted();
2428
+ await options.afterWrite?.(signal);
2429
+ signal?.throwIfAborted();
2430
+ const cleanups = [];
2431
+ const cleanupPaths = [];
2432
+ if (!options.cloudflare && options.cleanup?.cloudflare) {
2433
+ let cleanup = typeof options.cleanup.cloudflare === "function" ? await options.cleanup.cloudflare() : options.cleanup.cloudflare;
2434
+ const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
2435
+ if (resolve(outputRoot) === clientDir) cleanup = {
2436
+ ...cleanup,
2437
+ fileNames: []
2438
+ };
2439
+ else if (transaction?.cloudflareWritten) cleanup = {
2440
+ ...cleanup,
2441
+ fileNames: []
2442
+ };
2443
+ if (shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup)) {
2444
+ cleanupPaths.push(outputRoot);
2445
+ cleanups.push(async () => await cleanupCloudflareDeploymentOutput(options.rootDir, cleanup, signal));
2446
+ }
2447
+ }
2448
+ if (!options.netlify && options.cleanup?.netlify) {
2449
+ const cleanup = options.cleanup.netlify;
2450
+ cleanupPaths.push(cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir));
2451
+ cleanups.push(async () => await cleanupNetlifyDeploymentOutput(options.rootDir, cleanup, signal));
2452
+ }
2453
+ if (!options.vercel && options.cleanup?.vercel) {
2454
+ const cleanup = typeof options.cleanup.vercel === "function" ? await options.cleanup.vercel() : options.cleanup.vercel;
2455
+ signal?.throwIfAborted();
2456
+ if (cleanup) {
2457
+ const items = Array.isArray(cleanup) ? cleanup : [cleanup];
2458
+ cleanupPaths.push(...items.map((item) => item.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir)));
2459
+ cleanups.push(async () => await cleanupVercelDeploymentOutputs(options.rootDir, cleanup, signal));
2460
+ }
2461
+ }
2462
+ await transaction?.snapshot(cleanupPaths, [clientDir]);
2463
+ await settleWrites(cleanups.map((cleanup) => cleanup()));
2464
+ signal?.throwIfAborted();
2465
+ }
2466
+ function providerDeploymentOutputPaths(options) {
2467
+ const clientDir = resolve(options.rootDir, options.clientOutDir);
2468
+ return [
2469
+ options.cloudflare && (options.cloudflare.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir)),
2470
+ options.cloudflare?.staticOutputDir,
2471
+ options.netlify?.outputRoot,
2472
+ options.vercel?.outputRoot,
2473
+ options.vercel?.staticOutputDir
2474
+ ].filter((path) => Boolean(path) && resolve(path) !== clientDir);
2475
+ }
2476
+ async function withProviderDeploymentOutputRootLock(rootDir, operation) {
2477
+ const key = resolve(rootDir);
2478
+ const state = providerDeploymentOutputRootStates.get(key) ?? { pending: 0 };
2479
+ providerDeploymentOutputRootStates.set(key, state);
2480
+ state.pending++;
2481
+ const current = (providerDeploymentOutputWrites.get(key) ?? Promise.resolve()).catch(() => void 0).then(async () => await operation(state));
2482
+ providerDeploymentOutputWrites.set(key, current);
2483
+ try {
2484
+ return await current;
2485
+ } finally {
2486
+ if (providerDeploymentOutputWrites.get(key) === current) providerDeploymentOutputWrites.delete(key);
2487
+ state.pending--;
2488
+ if (state.pending === 0 && providerDeploymentOutputRootStates.get(key) === state) providerDeploymentOutputRootStates.delete(key);
2489
+ }
2490
+ }
2491
+ function pathContains(parent, child) {
2492
+ const nested = relative(parent, child);
2493
+ return !nested || !nested.startsWith(`..${sep}`) && nested !== ".." && !isAbsolute(nested);
2494
+ }
2495
+ async function restoreProviderDeploymentOutputSnapshot(snapshot) {
2496
+ if (snapshot.present) await mkdir(dirname(snapshot.path), { recursive: true });
2497
+ const restoreRoot = await mkdtemp(resolve(snapshot.present ? dirname(snapshot.path) : tmpdir(), "vitehub-provider-output-restore-"));
2498
+ const staged = resolve(restoreRoot, "snapshot");
2499
+ const preservedRoot = resolve(restoreRoot, "preserved");
2500
+ try {
2501
+ await mkdir(preservedRoot, { recursive: true });
2502
+ const preserved = snapshot.preservedPaths.map((path, index) => ({
2503
+ backup: resolve(preservedRoot, String(index)),
2504
+ path,
2505
+ present: existsSync(path)
2506
+ }));
2507
+ await Promise.all(preserved.map(async (entry) => {
2508
+ if (entry.present) await cp(entry.path, entry.backup, { recursive: true });
2509
+ }));
2510
+ if (snapshot.present) await cp(snapshot.backup, staged, { recursive: true });
2511
+ await rm(snapshot.path, {
2512
+ force: true,
2513
+ recursive: true
2514
+ });
2515
+ if (snapshot.present) await rename(staged, snapshot.path);
2516
+ for (const entry of preserved) {
2517
+ await rm(entry.path, {
2518
+ force: true,
2519
+ recursive: true
2520
+ });
2521
+ if (entry.present) {
2522
+ await mkdir(dirname(entry.path), { recursive: true });
2523
+ await cp(entry.backup, entry.path, { recursive: true });
2524
+ }
2525
+ }
2526
+ } finally {
2527
+ await rm(restoreRoot, {
2528
+ force: true,
2529
+ recursive: true
2530
+ });
2531
+ }
2532
+ }
2533
+ async function withProviderDeploymentOutputRootTransaction(rootDir, operation, options = {}) {
2534
+ const roots = [
2535
+ createDefaultCloudflareOutputRoot(rootDir),
2536
+ createDefaultNetlifyOutputRoot(rootDir),
2537
+ createDefaultVercelOutputRoot(rootDir),
2538
+ resolve(rootDir, ".vitehub/agent"),
2539
+ resolve(rootDir, ".vitehub/blob/cloudflare-output.json"),
2540
+ resolve(rootDir, ".vitehub/queue/cloudflare-output.json"),
2541
+ resolve(rootDir, ".vitehub/queue/registry.mjs"),
2542
+ resolve(rootDir, ".vitehub/queue/vercel-output.json"),
2543
+ resolve(rootDir, ".vitehub/rate-limit/cloudflare-output.json"),
2544
+ resolve(rootDir, ".vitehub/rate-limit/manifest.json"),
2545
+ resolve(rootDir, ".vitehub/schedule"),
2546
+ resolve(rootDir, ".vitehub/workflow")
2547
+ ];
2548
+ const transactionRoot = await mkdtemp(resolve(tmpdir(), "vitehub-provider-output-"));
2549
+ const snapshots = /* @__PURE__ */ new Map();
2550
+ let snapshotIndex = 0;
2551
+ const transaction = {
2552
+ cloudflareWritten: false,
2553
+ async snapshot(paths, preservedPaths = []) {
2554
+ const resolvedPreservedPaths = [...new Set(preservedPaths.map((path) => resolve(path)))];
2555
+ for (const snapshot of snapshots.values()) {
2556
+ const additions = resolvedPreservedPaths.filter((path) => path !== snapshot.path && pathContains(snapshot.path, path) && !snapshot.preservedPaths.includes(path));
2557
+ snapshot.preservedPaths.push(...additions);
2558
+ if (snapshot.present) await Promise.all(additions.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
2559
+ force: true,
2560
+ recursive: true
2561
+ })));
2562
+ }
2563
+ const pending = [...new Set(paths.map((path) => resolve(path)))].sort((left, right) => left.length - right.length).filter((path, index, all) => !all.slice(0, index).some((parent) => pathContains(parent, path))).filter((path) => ![...snapshots.keys()].some((parent) => pathContains(parent, path))).map((path) => ({
2564
+ backup: resolve(transactionRoot, String(snapshotIndex++)),
2565
+ path,
2566
+ present: existsSync(path),
2567
+ preservedPaths: resolvedPreservedPaths.filter((preserved) => preserved !== path && pathContains(path, preserved))
2568
+ }));
2569
+ const failure = (await Promise.allSettled(pending.map(async (snapshot) => {
2570
+ if (snapshot.present) {
2571
+ await cp(snapshot.path, snapshot.backup, { recursive: true });
2572
+ await Promise.all(snapshot.preservedPaths.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
2573
+ force: true,
2574
+ recursive: true
2575
+ })));
2576
+ }
2577
+ }))).find((result) => result.status === "rejected");
2578
+ if (failure) {
2579
+ await Promise.all(pending.map((snapshot) => rm(snapshot.backup, {
2580
+ force: true,
2581
+ recursive: true
2582
+ })));
2583
+ throw failure.reason;
2584
+ }
2585
+ for (const snapshot of pending) {
2586
+ const children = [...snapshots.values()].filter((child) => pathContains(snapshot.path, child.path));
2587
+ if (snapshot.present) for (const child of children) {
2588
+ const nestedBackup = resolve(snapshot.backup, relative(snapshot.path, child.path));
2589
+ await rm(nestedBackup, {
2590
+ force: true,
2591
+ recursive: true
2592
+ });
2593
+ if (child.present) {
2594
+ await mkdir(dirname(nestedBackup), { recursive: true });
2595
+ await cp(child.backup, nestedBackup, { recursive: true });
2596
+ }
2597
+ }
2598
+ for (const child of children) {
2599
+ snapshots.delete(child.path);
2600
+ await rm(child.backup, {
2601
+ force: true,
2602
+ recursive: true
2603
+ });
2604
+ }
2605
+ snapshot.preservedPaths.push(...children.flatMap((child) => child.preservedPaths).filter((path) => !snapshot.preservedPaths.includes(path)));
2606
+ if (snapshot.present) await Promise.all(snapshot.preservedPaths.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
2607
+ force: true,
2608
+ recursive: true
2609
+ })));
2610
+ snapshots.set(snapshot.path, snapshot);
2611
+ }
2612
+ }
2613
+ };
2614
+ try {
2615
+ if (options.snapshotInitialRoots !== false) await transaction.snapshot(roots);
2616
+ const result = await operation(transaction);
2617
+ await removeProviderOutputArtifactDir(transactionRoot).catch(() => void 0);
2618
+ return result;
2619
+ } catch (error) {
2620
+ const restorations = await Promise.allSettled([...snapshots.values()].map(restoreProviderDeploymentOutputSnapshot));
2621
+ if (restorations.every((result) => result.status === "fulfilled")) await rm(transactionRoot, {
2622
+ force: true,
2623
+ recursive: true
2624
+ });
2625
+ const restorationFailure = restorations.find((result) => result.status === "rejected");
2626
+ if (restorationFailure) throw new AggregateError([error, restorationFailure.reason], "Provider Output rollback failed");
2627
+ throw error;
2628
+ }
2629
+ }
2630
+ function contributeProviderDeploymentOutput(catalog, contribution, generation) {
2631
+ closeProviderDeploymentOutputGenerationCapture(generation);
2632
+ catalog?.replaceDeploymentContribution(contribution, generation);
2633
+ }
2634
+ const providerDeploymentOutputEnvironmentGenerations = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputEnvironmentGenerations ??= /* @__PURE__ */ new WeakMap();
2635
+ const providerDeploymentOutputGenerationEnvironments = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputGenerationEnvironments ??= /* @__PURE__ */ new WeakMap();
2636
+ const providerDeploymentOutputFallbackEnvironment = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputFallbackEnvironment ??= {};
2637
+ function closeProviderDeploymentOutputGenerationCapture(generation) {
2638
+ if (!generation) return;
2639
+ const captured = providerDeploymentOutputGenerationEnvironments.get(generation);
2640
+ if (!captured) return;
2641
+ const generations = providerDeploymentOutputEnvironmentGenerations.get(captured.catalog);
2642
+ if (generations?.get(captured.environment) === generation) generations.delete(captured.environment);
2643
+ providerDeploymentOutputGenerationEnvironments.delete(generation);
2644
+ }
2645
+ function createProviderDeploymentOutputGenerationState() {
2646
+ const generations = /* @__PURE__ */ new WeakMap();
2647
+ const readiness = /* @__PURE__ */ new WeakMap();
2648
+ const localEnvironment = (context) => context?.environment ?? context ?? providerDeploymentOutputFallbackEnvironment;
2649
+ const sharedEnvironment = (context) => context?.environment ?? providerDeploymentOutputFallbackEnvironment;
2650
+ return {
2651
+ capture(context, catalog) {
2652
+ const localEnvironmentKey = localEnvironment(context);
2653
+ readiness.delete(localEnvironmentKey);
2654
+ if (!catalog) {
2655
+ generations.set(localEnvironmentKey, void 0);
2656
+ return;
2657
+ }
2658
+ const environmentKey = sharedEnvironment(context);
2659
+ let catalogGenerations = providerDeploymentOutputEnvironmentGenerations.get(catalog);
2660
+ if (!catalogGenerations) {
2661
+ catalogGenerations = /* @__PURE__ */ new WeakMap();
2662
+ providerDeploymentOutputEnvironmentGenerations.set(catalog, catalogGenerations);
2663
+ }
2664
+ const sharedGeneration = catalogGenerations.get(environmentKey);
2665
+ const generation = !sharedGeneration || generations.get(localEnvironmentKey) === sharedGeneration ? catalog.createDeploymentGeneration() : sharedGeneration;
2666
+ catalogGenerations.set(environmentKey, generation);
2667
+ providerDeploymentOutputGenerationEnvironments.set(generation, {
2668
+ catalog,
2669
+ environment: environmentKey
2670
+ });
2671
+ generations.set(localEnvironmentKey, generation);
2672
+ },
2673
+ defer(context, catalog, contribution) {
2674
+ const localEnvironmentKey = localEnvironment(context);
2675
+ const state = { ready: false };
2676
+ readiness.set(localEnvironmentKey, state);
2677
+ contributeProviderDeploymentOutput(catalog, {
2678
+ ...contribution,
2679
+ ready: () => state.ready
2680
+ }, generations.get(localEnvironmentKey));
2681
+ },
2682
+ get(context) {
2683
+ return generations.get(localEnvironment(context));
2684
+ },
2685
+ ready(context) {
2686
+ const state = readiness.get(localEnvironment(context));
2687
+ if (state) state.ready = true;
2688
+ },
2689
+ async reset(context, catalog, failure) {
2690
+ const localEnvironmentKey = localEnvironment(context);
2691
+ const generation = generations.get(localEnvironmentKey);
2692
+ readiness.delete(localEnvironmentKey);
2693
+ closeProviderDeploymentOutputGenerationCapture(generation);
2694
+ await resetProviderDeploymentOutputs(catalog, failure, generation);
2695
+ }
2696
+ };
2697
+ }
2698
+ async function resetProviderDeploymentOutputs(catalog, failure, generation) {
2699
+ if (!catalog) return;
2700
+ const completedReset = providerDeploymentOutputCompletedResets.get(catalog);
2701
+ if (completedReset && failure !== void 0 && completedReset.failures.has(failure)) {
2702
+ if (generation) catalog.resetDeploymentContributions(generation);
2703
+ await completedReset.promise;
2704
+ return;
2705
+ }
2706
+ if (completedReset) providerDeploymentOutputCompletedResets.delete(catalog);
2707
+ if (generation) catalog.resetDeploymentContributions(generation);
2708
+ const active = providerDeploymentOutputFinalizations.get(catalog);
2709
+ if (active?.reset) {
2710
+ if (failure !== void 0 && !active.reset.failures.has(failure)) {
2711
+ active.reset.failures.add(failure);
2712
+ if (!generation) catalog.resetDeploymentContributions();
2713
+ }
2714
+ providerDeploymentOutputCompletedResets.set(catalog, active.reset);
2715
+ await active.reset.promise;
2716
+ return;
2717
+ }
2718
+ if (!generation) catalog.resetDeploymentContributions();
2719
+ if (active && (!generation || active.state.generations.has(generation))) {
2720
+ active.state.rollback = true;
2721
+ active.controller.abort(/* @__PURE__ */ new Error("Provider Output finalization reset"));
2722
+ active.reset = {
2723
+ failures: new Set([failure]),
2724
+ promise: active.promise.catch(() => void 0)
2725
+ };
2726
+ providerDeploymentOutputCompletedResets.set(catalog, active.reset);
2727
+ await active.reset.promise;
2728
+ } else if (failure !== void 0) providerDeploymentOutputCompletedResets.set(catalog, {
2729
+ failures: new Set([failure]),
2730
+ promise: Promise.resolve()
2731
+ });
2732
+ }
2733
+ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
2734
+ if (!catalog) return;
2735
+ const existing = providerDeploymentOutputFinalizations.get(catalog);
2736
+ if (existing) {
2737
+ try {
2738
+ await existing.promise;
2739
+ } catch (error) {
2740
+ if (!catalog.hasDeploymentContributions()) throw error;
2741
+ existing.handoff ??= (async () => {
2742
+ await existing.promise.catch(() => void 0);
2743
+ if (providerDeploymentOutputFinalizations.get(catalog) === existing) providerDeploymentOutputFinalizations.delete(catalog);
2744
+ await finalizeProviderDeploymentOutputs(catalog, options);
2745
+ })();
2746
+ await existing.handoff;
2747
+ return;
2748
+ }
2749
+ if (providerDeploymentOutputFinalizations.get(catalog) === existing) providerDeploymentOutputFinalizations.delete(catalog);
2750
+ if (catalog.hasDeploymentContributions()) await finalizeProviderDeploymentOutputs(catalog, options);
2751
+ return;
2752
+ }
2753
+ const controller = new AbortController();
2754
+ const state = {
2755
+ generations: /* @__PURE__ */ new Set(),
2756
+ rollback: false
2757
+ };
2758
+ const finalization = (async () => {
2759
+ const order = new Map(providerDeploymentOutputOwnerOrder.map((owner, index) => [owner, index]));
2760
+ const abort = () => controller.abort(options.signal?.reason);
2761
+ if (options.signal?.aborted) abort();
2762
+ else options.signal?.addEventListener("abort", abort, { once: true });
2763
+ try {
2764
+ while (true) {
2765
+ const contributions = catalog.takeDeploymentContributions();
2766
+ if (!contributions.length) return;
2767
+ try {
2768
+ if (contributions.some((contribution) => contribution.ready?.() === false)) {
2769
+ if (controller.signal.aborted) {
2770
+ await catalog.completeDeploymentContributions(contributions);
2771
+ throwIfProviderOutputAborted(controller.signal);
2772
+ }
2773
+ catalog.rollbackDeploymentContributions(contributions);
2774
+ return;
2775
+ }
2776
+ } catch (error) {
2777
+ catalog.rollbackDeploymentContributions(contributions);
2778
+ throw error;
2779
+ }
2780
+ for (const contribution of contributions) {
2781
+ const generation = catalog.deploymentContributionGeneration(contribution);
2782
+ if (generation) state.generations.add(generation);
2783
+ }
2784
+ contributions.sort((left, right) => order.get(left.owner) - order.get(right.owner));
2785
+ const grouped = /* @__PURE__ */ new Map();
2786
+ for (const contribution of contributions) {
2787
+ const rootDir = resolve(contribution.rootDir);
2788
+ const rootContributions = grouped.get(rootDir) ?? [];
2789
+ rootContributions.push(contribution);
2790
+ grouped.set(rootDir, rootContributions);
2791
+ }
2792
+ try {
2793
+ let decideRoots;
2794
+ const rootDecision = new Promise((resolve) => {
2795
+ decideRoots = resolve;
2796
+ });
2797
+ const roots = [...grouped.entries()].map(([rootDir, rootContributions]) => {
2798
+ let ready;
2799
+ let rejectReady;
2800
+ const readiness = new Promise((resolve, reject) => {
2801
+ ready = resolve;
2802
+ rejectReady = reject;
2803
+ });
2804
+ const write = withProviderDeploymentOutputRootLock(rootDir, async () => {
2805
+ await withProviderDeploymentOutputRootTransaction(rootDir, async (transaction) => {
2806
+ try {
2807
+ for (const contribution of rootContributions) {
2808
+ throwIfProviderOutputAborted(controller.signal);
2809
+ await contribution.write({
2810
+ readCloudflareState: async (options) => await readCloudflareProviderDeploymentOutputState(rootDir, options),
2811
+ signal: controller.signal,
2812
+ write: async (writeOptions) => {
2813
+ throwIfProviderOutputAborted(controller.signal);
2814
+ await writeProviderDeploymentOutputsNow(writeOptions, controller.signal, transaction);
2815
+ }
2816
+ });
2817
+ throwIfProviderOutputAborted(controller.signal);
2818
+ }
2819
+ ready();
2820
+ const rollback = await rootDecision;
2821
+ if (rollback !== void 0) throw rollback;
2822
+ throwIfProviderOutputAborted(controller.signal);
2823
+ } catch (error) {
2824
+ controller.abort(error);
2825
+ rejectReady(error);
2826
+ throw error;
2827
+ }
2828
+ }, { snapshotInitialRoots: rootContributions.some((contribution) => contribution.owner !== "kv") });
2829
+ });
2830
+ write.catch(rejectReady);
2831
+ return {
2832
+ readiness,
2833
+ write
2834
+ };
2835
+ });
2836
+ const failedRoot = (await Promise.allSettled(roots.map((root) => root.readiness))).find((result) => result.status === "rejected");
2837
+ if (failedRoot) {
2838
+ decideRoots(failedRoot.reason);
2839
+ await settleWrites(roots.map((root) => root.write));
2840
+ }
2841
+ try {
2842
+ await catalog.prepareDeploymentContributions(contributions);
2843
+ throwIfProviderOutputAborted(controller.signal);
2844
+ } catch (error) {
2845
+ decideRoots(error);
2846
+ await settleWrites(roots.map((root) => root.write));
2847
+ throw error;
2848
+ }
2849
+ catalog.commitDeploymentContributions(contributions);
2850
+ state.generations.clear();
2851
+ decideRoots(void 0);
2852
+ await settleWrites(roots.map((root) => root.write));
2853
+ await catalog.completeDeploymentContributions(contributions);
2854
+ } catch (error) {
2855
+ if (state.rollback) catalog.rollbackDeploymentContributions(contributions);
2856
+ else await catalog.completeDeploymentContributions(contributions);
2857
+ throw error;
2858
+ } finally {
2859
+ state.generations.clear();
2860
+ }
2861
+ }
2862
+ } finally {
2863
+ options.signal?.removeEventListener("abort", abort);
2864
+ }
2865
+ })();
2866
+ const active = {
2867
+ controller,
2868
+ promise: finalization,
2869
+ state
2870
+ };
2871
+ providerDeploymentOutputFinalizations.set(catalog, active);
2872
+ try {
2873
+ await finalization;
2874
+ } finally {
2875
+ if (providerDeploymentOutputFinalizations.get(catalog) === active) providerDeploymentOutputFinalizations.delete(catalog);
2876
+ }
2877
+ }
2878
+ const VITEHUB_MODES = {
2879
+ e2e: "e2e",
2880
+ blob: "blob",
2881
+ chat: "chat",
2882
+ db: "db",
2883
+ env: "env",
2884
+ kv: "kv",
2885
+ queue: "queue",
2886
+ schedule: "schedule",
2887
+ sandbox: "sandbox",
2888
+ workspace: "workspace",
2889
+ workflow: "workflow"
2890
+ };
2891
+ function isViteCli(argv) {
2892
+ return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
2893
+ }
2894
+ function getViteCliMode(argv = process.argv) {
2895
+ if (!isViteCli(argv)) return;
2896
+ const modes = new Set(Object.values(VITEHUB_MODES));
2897
+ for (let index = 0; index < argv.length; index += 1) {
2898
+ const arg = argv[index];
2899
+ const mode = arg === "--mode" || arg === "-m" ? argv[index + 1] : arg.startsWith("--mode=") ? arg.slice(7) : void 0;
2900
+ if (mode && modes.has(mode)) return mode;
2901
+ }
2902
+ }
2903
+ function getViteMode(env = process.env) {
2904
+ return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
2905
+ }
2906
+ //#endregion
2907
+ //#region src/integrations/vercel.ts
2908
+ function getVercelSchedulePath(name) {
2909
+ return `/api/vitehub/schedules/vercel/${name.replace(/[^a-z0-9/_-]+/gi, "_")}`;
2910
+ }
2911
+ //#endregion
2912
+ //#region src/internal/provider-output.ts
2913
+ const schedulePackageName = "@vite-hub/schedule";
2914
+ const scheduleStaticRuntimeImport = "@vite-hub/schedule/runtime/static";
2915
+ const productName = "schedule";
2916
+ const cloudflareOutputStateFileName = "cloudflare-output.json";
2917
+ const cloudflareScheduleWorkerMarker = "vitehub-schedule-provider-output";
2918
+ const deployedScheduleSourcesPath = ".vitehub/schedule/sources";
2919
+ const denoCronFileName = "deno-cron.mjs";
2920
+ const generatedRegistryFileName = "registry.mjs";
2921
+ function resolveScheduleRuntimeEntry(resolveImport = (specifier) => import.meta.resolve(specifier)) {
2922
+ return fileURLToPath(resolveImport(scheduleStaticRuntimeImport));
2923
+ }
2924
+ function resolveScheduleDefinitionEntry(resolveImport = (specifier) => import.meta.resolve(specifier)) {
2925
+ return resolve(dirname(fileURLToPath(resolveImport(`${schedulePackageName}/package.json`))), "dist/definition.js");
2926
+ }
2927
+ const scheduleRuntimeEntry = resolveScheduleRuntimeEntry();
2928
+ const scheduleDefinitionEntry = resolveScheduleDefinitionEntry();
2929
+ function staticScheduleDefinitions(definitions) {
2930
+ return definitions.filter((definition) => definition.runtimeOnly !== true);
2931
+ }
2932
+ async function publishRetainedProviderSources(artifacts, retainedSourcesDir, signal) {
2933
+ signal?.throwIfAborted();
2934
+ const generatedDir = artifacts.generatedDir;
2935
+ const publishedSourcesDir = resolve(generatedDir, "sources");
2936
+ const nextDir = `${generatedDir}.${randomUUID()}.next`;
2937
+ const previousDir = `${generatedDir}.${randomUUID()}.previous`;
2938
+ let movedPrevious = false;
2939
+ let publicationSettled = false;
2940
+ try {
2941
+ await cp(generatedDir, nextDir, { recursive: true });
2942
+ await rm(resolve(nextDir, "sources"), {
2943
+ force: true,
2944
+ recursive: true
2945
+ });
2946
+ const nextSourcesDir = resolve(nextDir, "sources");
2947
+ await cp(retainedSourcesDir, nextSourcesDir, { recursive: true });
2948
+ await rebasePublishedProviderSourceLinks(nextSourcesDir, retainedSourcesDir, publishedSourcesDir);
2949
+ const registryFile = resolve(nextDir, generatedRegistryFileName);
2950
+ await writeFile(registryFile, rewriteRetainedProviderSourcePaths(await readFile(registryFile, "utf8"), retainedSourcesDir, publishedSourcesDir, {
2951
+ published: resolve(generatedDir, generatedRegistryFileName),
2952
+ retained: artifacts.registryFile
2953
+ }), "utf8");
2954
+ signal?.throwIfAborted();
2955
+ await rename(generatedDir, previousDir);
2956
+ movedPrevious = true;
2957
+ await rename(nextDir, generatedDir);
2958
+ signal?.throwIfAborted();
2959
+ publicationSettled = true;
2960
+ await removeProviderOutputArtifactDir(previousDir).catch(() => void 0);
2961
+ } catch (error) {
2962
+ if (publicationSettled) throw error;
2963
+ await rm(nextDir, {
2964
+ force: true,
2965
+ recursive: true
2966
+ });
2967
+ if (movedPrevious) try {
2968
+ await rm(generatedDir, {
2969
+ force: true,
2970
+ recursive: true
2971
+ });
2972
+ await rename(previousDir, generatedDir);
2973
+ } catch (restoreError) {
2974
+ throw new AggregateError([error, restoreError], "Generated Schedule artifact rollback failed");
2975
+ }
2976
+ throw error;
2977
+ }
2978
+ return {
2979
+ ...artifacts,
2980
+ registryFile: resolve(generatedDir, generatedRegistryFileName)
2981
+ };
2982
+ }
2983
+ async function removeEmptyDirectories(directory, rootDir) {
2984
+ const root = resolve(rootDir);
2985
+ let current = resolve(directory);
2986
+ const pathFromRoot = relative(root, current);
2987
+ if (!pathFromRoot || pathFromRoot.startsWith("..") || isAbsolute(pathFromRoot)) return;
2988
+ while (current !== root) {
2989
+ try {
2990
+ await rmdir(current);
2991
+ } catch (error) {
2992
+ const code = error.code;
2993
+ if (code === "ENOENT") {
2994
+ current = dirname(current);
2995
+ continue;
2996
+ }
2997
+ if (code === "ENOTEMPTY" || code === "EEXIST") return;
2998
+ throw error;
2999
+ }
3000
+ current = dirname(current);
3001
+ }
3002
+ }
3003
+ const cronFieldPattern = /^[*,/\-0-9]+$/;
3004
+ function validateProviderCron(cron, scheduleName) {
3005
+ const fields = cron.trim().split(/\s+/);
3006
+ const hasVercelDayConflict = fields[2] !== "*" && fields[4] !== "*";
3007
+ if (fields.length !== 5 || !fields.every((field) => cronFieldPattern.test(field)) || hasVercelDayConflict) throw new Error(`Schedule "${scheduleName}" uses cron "${cron}", but provider wake output only supports five-field UTC cron syntax compatible with Cloudflare, Vercel, and Netlify.`);
3008
+ }
3009
+ function readStaticScheduleCron(file, scheduleName) {
3010
+ const definition = findDefaultExportCall(readFileSync(file, "utf8"), ["defineSchedule"]);
3011
+ const cron = definition && readStaticString(readObjectProperty(definition.argument, "cron"));
3012
+ if (!cron) throw new Error(`Schedule "${scheduleName}" must declare a static cron string for provider wake output.`);
3013
+ return cron;
3014
+ }
3015
+ function readStaticString(source) {
3016
+ if (!source || !/^["'`]/.test(source)) return;
3017
+ const quote = source[0];
3018
+ let value = "";
3019
+ for (let index = 1; index < source.length; index++) if (source[index] === "\\") value += source[++index] || "";
3020
+ else if (source[index] === quote) return source.slice(index + 1).trim() ? void 0 : value;
3021
+ else value += source[index];
3022
+ }
3023
+ function renderProviderEntry(file, registryFile, provider, scheduleName, workflow) {
3024
+ const runtimeImport = createImportPath(file, scheduleRuntimeEntry);
3025
+ const workflowRuntime = provider === "vercel" ? workflow : void 0;
3026
+ return [
3027
+ `import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
3028
+ `import { executeStaticSchedule } from ${JSON.stringify(runtimeImport)}`,
3029
+ ...workflowRuntime ? [
3030
+ `import workflowRegistry from ${JSON.stringify(createImportPath(file, workflowRuntime.registryFile))}`,
3031
+ `import { setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from ${JSON.stringify(`${workflowRuntime.importBase}/runtime/state`)}`,
3032
+ `import { runWithVercelWorkflowRuntimeEvent } from ${JSON.stringify(`${workflowRuntime.importBase}/runtime/vercel-vite`)}`,
3033
+ ...workflowRuntime.native ? [
3034
+ `import { setVercelWorkflowRuntimeModules } from ${JSON.stringify(`${workflowRuntime.importBase}/runtime/vercel-vite`)}`,
3035
+ `import * as workflowApi from "workflow/api"`,
3036
+ `import * as workflowRuntime from "workflow/runtime"`
3037
+ ] : []
3038
+ ] : [],
3039
+ "",
3040
+ workflowRuntime?.native ? "setVercelWorkflowRuntimeModules(workflowApi, workflowRuntime)" : "",
3041
+ "async function loadScheduleDefinition(name) {",
3042
+ " const loader = scheduleRegistry[name]",
3043
+ " if (!loader) return undefined",
3044
+ " const loaded = await loader()",
3045
+ " return loaded?.default ?? loaded",
3046
+ "}",
3047
+ "",
3048
+ "async function runSchedule(name, cron, scheduledAt) {",
3049
+ " const definition = await loadScheduleDefinition(name)",
3050
+ " if (!definition) {",
3051
+ " throw new Error(`Missing schedule definition: ${name}`)",
3052
+ " }",
3053
+ " return await executeStaticSchedule({ cron, definition, name, scheduledAt })",
3054
+ "}",
3055
+ "",
3056
+ provider === "cloudflare" ? [
3057
+ "export default {",
3058
+ " async fetch() {",
3059
+ " return new Response('ViteHub schedule provider wake endpoint')",
3060
+ " },",
3061
+ " async scheduled(event, env, ctx) {",
3062
+ " const tasks = Object.entries(scheduleRegistry).map(async ([name]) => {",
3063
+ " const definition = await loadScheduleDefinition(name)",
3064
+ " if (!definition || definition.cron !== event.cron) return",
3065
+ " await executeStaticSchedule({ cron: event.cron, definition, name, scheduledAt: new Date(event.scheduledTime), waitUntil: (promise) => ctx.waitUntil(promise) })",
3066
+ " })",
3067
+ " await Promise.all(tasks)",
3068
+ " },",
3069
+ "}"
3070
+ ].join("\n") : [
3071
+ "export default async function scheduleHandler(req, res) {",
3072
+ " const cronSecret = process.env.CRON_SECRET",
3073
+ " const authorization = req.headers?.authorization || req.headers?.Authorization",
3074
+ " if (cronSecret && authorization !== `Bearer ${cronSecret}`) {",
3075
+ " res.statusCode = 401",
3076
+ " res.end('Unauthorized.')",
3077
+ " return",
3078
+ " }",
3079
+ " const url = new URL(req.url || '/', 'https://vitehub.local')",
3080
+ " const prefix = '/api/vitehub/schedules/vercel/'",
3081
+ scheduleName === void 0 ? " const name = decodeURIComponent(url.pathname.startsWith(prefix) ? url.pathname.slice(prefix.length) : '')" : ` const name = ${JSON.stringify(scheduleName)}`,
3082
+ " const definition = await loadScheduleDefinition(name)",
3083
+ " if (!definition) {",
3084
+ " res.statusCode = 404",
3085
+ " res.end('Missing schedule definition.')",
3086
+ " return",
3087
+ " }",
3088
+ ...workflowRuntime ? [" setWorkflowRuntimeConfig({ provider: 'vercel' })", " setWorkflowRuntimeRegistry(workflowRegistry)"] : [],
3089
+ workflowRuntime ? " await runWithVercelWorkflowRuntimeEvent(req, res, () => runSchedule(name, definition.cron, new Date()))" : " await runSchedule(name, definition.cron, new Date())",
3090
+ " res.statusCode = 204",
3091
+ " res.end()",
3092
+ "}"
3093
+ ].join("\n"),
3094
+ ""
3095
+ ].join("\n");
3096
+ }
3097
+ function renderNetlifyScheduleFunction(file, registryFile, scheduleName, cron, includedSourcesDir) {
3098
+ const runtimeImport = createImportPath(file, scheduleRuntimeEntry);
3099
+ return [
3100
+ `import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
3101
+ `import { executeStaticSchedule } from ${JSON.stringify(runtimeImport)}`,
3102
+ "",
3103
+ `const scheduleName = ${JSON.stringify(scheduleName)}`,
3104
+ "",
3105
+ "export default async function netlifyScheduleHandler(request) {",
3106
+ " const loaded = await scheduleRegistry[scheduleName]?.()",
3107
+ " const definition = loaded?.default ?? loaded",
3108
+ " if (!definition) return new Response('Missing schedule definition.', { status: 404 })",
3109
+ ` await executeStaticSchedule({ cron: ${JSON.stringify(cron)}, definition, name: scheduleName, scheduledAt: new Date() })`,
3110
+ " return new Response(null, { status: 204 })",
3111
+ "}",
3112
+ "",
3113
+ "export const config = {",
3114
+ ...includedSourcesDir ? [` includedFiles: [${JSON.stringify(`${includedSourcesDir}/**`)}],`] : [],
3115
+ ` schedule: ${JSON.stringify(cron)},`,
3116
+ "}",
3117
+ ""
3118
+ ].join("\n");
3119
+ }
3120
+ function sanitizeNetlifyScheduleFunctionName(name) {
3121
+ return `vitehub-schedule-${name.toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "schedule"}.mjs`;
3122
+ }
3123
+ function renderDenoCronEntry(file, registryFile, crons, runtimeImport = scheduleStaticRuntimeImport) {
3124
+ const scheduleCrons = [...crons.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([name, cron], index) => {
3125
+ const cronId = index.toString(36);
3126
+ const safeName = [...name].map((character) => /^[a-z0-9 _-]$/i.test(character) ? character : "_").join("");
3127
+ const cronNamePrefix = `vitehub-${cronId}-`;
3128
+ return {
3129
+ cron,
3130
+ cronName: `${cronNamePrefix}${safeName.slice(0, 64 - cronNamePrefix.length)}`,
3131
+ name
3132
+ };
3133
+ });
3134
+ return [
3135
+ `import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
3136
+ `import { executeStaticSchedule } from ${JSON.stringify(runtimeImport)}`,
3137
+ "",
3138
+ `const scheduleCrons = ${JSON.stringify(scheduleCrons, null, 2)}`,
3139
+ "",
3140
+ "async function loadScheduleDefinition(name) {",
3141
+ " const loader = scheduleRegistry[name]",
3142
+ " if (!loader) return undefined",
3143
+ " const loaded = await loader()",
3144
+ " return loaded?.default ?? loaded",
3145
+ "}",
3146
+ "",
3147
+ "for (const { cron, cronName, name } of scheduleCrons) {",
3148
+ " Deno.cron(cronName, cron, async () => {",
3149
+ " const definition = await loadScheduleDefinition(name)",
3150
+ " if (!definition) {",
3151
+ " throw new Error(`Missing schedule definition: ${name}`)",
3152
+ " }",
3153
+ " await executeStaticSchedule({ cron, definition, name, scheduledAt: new Date() })",
3154
+ " })",
3155
+ "}",
3156
+ "",
3157
+ "export const vitehubScheduleDefinitions = scheduleCrons.map(({ name }) => name)",
3158
+ ""
3159
+ ].join("\n");
3160
+ }
3161
+ function createScheduleDefinitionAliasPlugin() {
3162
+ return {
3163
+ name: "vitehub-schedule-definition-alias",
3164
+ setup(build) {
3165
+ build.onResolve({ filter: /^@vite-hub\/schedule$/ }, () => ({ path: scheduleDefinitionEntry }));
3166
+ }
3167
+ };
3168
+ }
3169
+ async function writeProviderEntries(rootDir, source, providedDefinitions) {
3170
+ const generatedDir = ensureGeneratedDir(rootDir, productName);
3171
+ const registryFile = resolve(generatedDir, generatedRegistryFileName);
3172
+ const definitions = (providedDefinitions ?? discoverScheduleDefinitions({ rootDir })).filter((definition) => !source || definition.source === source).filter((definition) => definition.runtimeOnly !== true);
3173
+ await writeRuntimeRegistryFile(registryFile, definitions);
3174
+ const cloudflareWorkerFile = resolve(generatedDir, "cloudflare-worker.mjs");
3175
+ const denoCronFile = resolve(generatedDir, denoCronFileName);
3176
+ const vercelServerFile = resolve(generatedDir, "vercel-server.mjs");
3177
+ await writeFile(cloudflareWorkerFile, renderProviderEntry(cloudflareWorkerFile, registryFile, "cloudflare"), "utf8");
3178
+ await writeFile(vercelServerFile, renderProviderEntry(vercelServerFile, registryFile, "vercel"), "utf8");
3179
+ return {
3180
+ cloudflareWorkerFile,
3181
+ denoCronFile,
3182
+ definitions,
3183
+ generatedDir,
3184
+ registryFile,
3185
+ vercelServerFile
3186
+ };
3187
+ }
3188
+ async function readDefinitionCrons(definitions) {
3189
+ const crons = await readRuntimeDefinitionCrons(definitions);
3190
+ for (const [name, cron] of crons) validateProviderCron(cron, name);
3191
+ return crons;
3192
+ }
3193
+ async function readRuntimeDefinitionCrons(definitions) {
3194
+ const crons = /* @__PURE__ */ new Map();
3195
+ for (const definition of staticScheduleDefinitions(definitions)) {
3196
+ const cron = readStaticScheduleCron(definition.handler, definition.name);
3197
+ crons.set(definition.name, cron);
3198
+ }
3199
+ return crons;
3200
+ }
3201
+ async function writeVercelScheduleFunctions(options, crons) {
3202
+ options.signal?.throwIfAborted();
3203
+ const definitions = staticScheduleDefinitions(options.definitions);
3204
+ const outputRoot = options.outputRoot;
3205
+ const functionRoot = resolve(outputRoot, "functions", "api", "vitehub", "schedules", "vercel");
3206
+ const stagedFunctionRoot = `${functionRoot}.pending`;
3207
+ const backupFunctionRoot = resolve(options.rootDir, ".vitehub", "schedule", "vercel-functions.previous");
3208
+ await mkdir(dirname(backupFunctionRoot), { recursive: true });
3209
+ await rm(stagedFunctionRoot, {
3210
+ force: true,
3211
+ recursive: true
3212
+ });
3213
+ options.signal?.throwIfAborted();
3214
+ const emittedFunctionNames = /* @__PURE__ */ new Map();
3215
+ for (const definition of definitions) {
3216
+ const safeName = definition.name.replace(/[^a-z0-9/_-]+/gi, "_").split("/").filter(Boolean).join("/");
3217
+ const existingName = emittedFunctionNames.get(safeName);
3218
+ if (existingName) throw new Error(`Schedule "${definition.name}" and "${existingName}" both emit the same Vercel function path: ${safeName}`);
3219
+ emittedFunctionNames.set(safeName, definition.name);
3220
+ const segments = safeName.split("/");
3221
+ const functionDir = resolve(stagedFunctionRoot, ...segments.slice(0, -1), `${segments.at(-1)}.func`);
3222
+ const functionFile = resolve(functionDir, "index.mjs");
3223
+ const wrapperFile = resolve(functionDir, "index.source.mjs");
3224
+ await mkdir(functionDir, { recursive: true });
3225
+ options.signal?.throwIfAborted();
3226
+ await writeFile(wrapperFile, renderProviderEntry(wrapperFile, options.registryFile, "vercel", definition.name, options.workflow), "utf8");
3227
+ await bundleEsmEntry(wrapperFile, functionFile, {
3228
+ alias: options.bundleAlias,
3229
+ external: options.bundleExternal,
3230
+ format: "esm",
3231
+ platform: "node",
3232
+ plugins: [createScheduleDefinitionAliasPlugin(), ...options.workflow?.bundlePlugins ?? []],
3233
+ rootDir: options.sourceRootDir ?? options.rootDir,
3234
+ signal: options.signal,
3235
+ workingDir: options.sourceRootDir ?? options.rootDir
3236
+ });
3237
+ await publishProviderSourcesToDeploymentOutputs({
3238
+ destinations: [{
3239
+ files: [functionFile],
3240
+ runtimeSourcesDir: `./${deployedScheduleSourcesPath}`,
3241
+ sourcesDir: resolve(functionDir, deployedScheduleSourcesPath)
3242
+ }],
3243
+ publishedSourcesDir: resolve(dirname(options.registryFile), "sources"),
3244
+ signal: options.signal
3245
+ });
3246
+ options.signal?.throwIfAborted();
3247
+ await rm(wrapperFile, { force: true });
3248
+ options.signal?.throwIfAborted();
3249
+ await writeFile(resolve(functionDir, ".vc-config.json"), `${JSON.stringify(createNodeFunctionConfig(), null, 2)}\n`, "utf8");
3250
+ }
3251
+ options.signal?.throwIfAborted();
3252
+ const configFile = resolve(outputRoot, "config.json");
3253
+ const previousConfig = await readFile(configFile).catch((error) => {
3254
+ if (error.code === "ENOENT") return void 0;
3255
+ throw error;
3256
+ });
3257
+ let installedFunctionRoot = false;
3258
+ let publicationCompleted = false;
3259
+ rmSync(backupFunctionRoot, {
3260
+ force: true,
3261
+ recursive: true
3262
+ });
3263
+ try {
3264
+ try {
3265
+ renameSync(functionRoot, backupFunctionRoot);
3266
+ } catch (error) {
3267
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
3268
+ }
3269
+ try {
3270
+ if (definitions.length) {
3271
+ mkdirSync(dirname(functionRoot), { recursive: true });
3272
+ renameSync(stagedFunctionRoot, functionRoot);
3273
+ installedFunctionRoot = true;
3274
+ }
3275
+ } catch (error) {
3276
+ if (existsSync(backupFunctionRoot)) renameSync(backupFunctionRoot, functionRoot);
3277
+ throw error;
3278
+ }
3279
+ let vercelConfig;
3280
+ try {
3281
+ vercelConfig = JSON.parse(await readFile(configFile, "utf8"));
3282
+ options.signal?.throwIfAborted();
3283
+ } catch (error) {
3284
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
3285
+ if (!definitions.length) {
3286
+ await removeEmptyDirectories(functionRoot, options.rootDir);
3287
+ options.signal?.throwIfAborted();
3288
+ publicationCompleted = true;
3289
+ return;
3290
+ }
3291
+ vercelConfig = createVercelConfigJson();
3292
+ }
3293
+ const schedulePathPrefix = "/api/vitehub/schedules/vercel/";
3294
+ const previousCrons = vercelConfig.crons ?? [];
3295
+ const existingCrons = previousCrons.filter((cron) => !cron.path.startsWith(schedulePathPrefix));
3296
+ if (!definitions.length && existingCrons.length === previousCrons.length) {
3297
+ await removeEmptyDirectories(functionRoot, options.rootDir);
3298
+ options.signal?.throwIfAborted();
3299
+ if (previousCrons.length === 0) {
3300
+ delete vercelConfig.crons;
3301
+ if (isDeepStrictEqual(vercelConfig, createVercelConfigJson())) {
3302
+ const outputFiles = await readdir(outputRoot);
3303
+ options.signal?.throwIfAborted();
3304
+ if (outputFiles.length === 1 && outputFiles[0] === "config.json") {
3305
+ await rm(configFile, { force: true });
3306
+ options.signal?.throwIfAborted();
3307
+ await removeEmptyDirectories(outputRoot, options.rootDir);
3308
+ }
3309
+ }
3310
+ }
3311
+ publicationCompleted = true;
3312
+ return;
3313
+ }
3314
+ const nextCrons = [...existingCrons, ...definitions.map((definition) => ({
3315
+ path: getVercelSchedulePath(definition.name),
3316
+ schedule: crons.get(definition.name)
3317
+ }))];
3318
+ if (nextCrons.length) vercelConfig.crons = nextCrons;
3319
+ else delete vercelConfig.crons;
3320
+ if (!definitions.length) {
3321
+ await removeEmptyDirectories(functionRoot, options.rootDir);
3322
+ options.signal?.throwIfAborted();
3323
+ const outputFiles = await readdir(outputRoot);
3324
+ options.signal?.throwIfAborted();
3325
+ if (outputFiles.length === 1 && outputFiles[0] === "config.json" && isDeepStrictEqual(vercelConfig, createVercelConfigJson())) {
3326
+ await rm(configFile, { force: true });
3327
+ options.signal?.throwIfAborted();
3328
+ await removeEmptyDirectories(outputRoot, options.rootDir);
3329
+ publicationCompleted = true;
3330
+ return;
3331
+ }
3332
+ }
3333
+ options.signal?.throwIfAborted();
3334
+ await writeFile(configFile, `${JSON.stringify(vercelConfig, null, 2)}\n`, "utf8");
3335
+ options.signal?.throwIfAborted();
3336
+ await removeEmptyDirectories(outputRoot, options.rootDir);
3337
+ options.signal?.throwIfAborted();
3338
+ publicationCompleted = true;
3339
+ } catch (error) {
3340
+ if (installedFunctionRoot) rmSync(functionRoot, {
3341
+ force: true,
3342
+ recursive: true
3343
+ });
3344
+ if (existsSync(backupFunctionRoot)) renameSync(backupFunctionRoot, functionRoot);
3345
+ if (previousConfig) await writeFile(configFile, previousConfig);
3346
+ else await rm(configFile, { force: true });
3347
+ throw error;
3348
+ } finally {
3349
+ if (publicationCompleted) try {
3350
+ rmSync(backupFunctionRoot, {
3351
+ force: true,
3352
+ recursive: true
3353
+ });
3354
+ } catch {}
3355
+ }
3356
+ }
3357
+ async function createNetlifyScheduleFunctionOutputs(options) {
3358
+ const definitions = staticScheduleDefinitions(options.definitions);
3359
+ const crons = await readDefinitionCrons(definitions);
3360
+ const emitted = /* @__PURE__ */ new Map();
3361
+ return definitions.map((definition) => {
3362
+ const fileName = sanitizeNetlifyScheduleFunctionName(definition.name);
3363
+ const existingName = emitted.get(fileName);
3364
+ if (existingName) throw new Error(`Schedule "${definition.name}" and "${existingName}" both emit the same Netlify function file: ${fileName}`);
3365
+ emitted.set(fileName, definition.name);
3366
+ const file = resolve(options.functionRoot, fileName);
3367
+ return {
3368
+ cron: crons.get(definition.name),
3369
+ file,
3370
+ name: definition.name,
3371
+ source: renderNetlifyScheduleFunction(file, options.registryFile, definition.name, crons.get(definition.name), options.includedSourcesDir)
3372
+ };
3373
+ });
3374
+ }
3375
+ async function writeNetlifyScheduleFunctions(options) {
3376
+ options.signal?.throwIfAborted();
3377
+ const functionRoot = resolve(options.outputRoot, "functions");
3378
+ const publishedSourcesDir = resolve(dirname(options.registryFile), "sources");
3379
+ const netlifySourcesDir = resolve(options.outputRoot, "schedule", "sources");
3380
+ const includedSourcesDir = relative(functionRoot, netlifySourcesDir).replace(/\\/g, "/");
3381
+ const stagedFunctionRoot = `${functionRoot}.pending`;
3382
+ const backupFunctionRoot = `${functionRoot}.previous`;
3383
+ await rm(stagedFunctionRoot, {
3384
+ force: true,
3385
+ recursive: true
3386
+ });
3387
+ await cp(functionRoot, stagedFunctionRoot, {
3388
+ force: true,
3389
+ recursive: true
3390
+ }).catch((error) => {
3391
+ if (error.code !== "ENOENT") throw error;
3392
+ });
3393
+ const existingFiles = await readdir(stagedFunctionRoot).catch((error) => error.code === "ENOENT" ? [] : Promise.reject(error));
3394
+ await Promise.all(existingFiles.filter((file) => /^vitehub-schedule-.+\.mjs$/.test(file)).map((file) => rm(resolve(stagedFunctionRoot, file), {
3395
+ force: true,
3396
+ recursive: true
3397
+ })));
3398
+ const outputs = await createNetlifyScheduleFunctionOutputs({
3399
+ definitions: options.definitions,
3400
+ functionRoot: stagedFunctionRoot,
3401
+ includedSourcesDir: existsSync(publishedSourcesDir) ? includedSourcesDir : void 0,
3402
+ registryFile: options.registryFile
3403
+ });
3404
+ options.signal?.throwIfAborted();
3405
+ if (outputs.length === 0) await mkdir(stagedFunctionRoot, { recursive: true });
3406
+ else {
3407
+ await mkdir(stagedFunctionRoot, { recursive: true });
3408
+ options.signal?.throwIfAborted();
3409
+ await Promise.all(outputs.map(async (output) => writeFile(output.file, output.source, {
3410
+ encoding: "utf8",
3411
+ signal: options.signal
3412
+ })));
3413
+ }
3414
+ await publishProviderSourcesToDeploymentOutputs({
3415
+ destinations: [{
3416
+ files: outputs.map((output) => output.file),
3417
+ runtimeSourcesDir: relative(options.rootDir, netlifySourcesDir).replace(/\\/g, "/"),
3418
+ sourcesDir: netlifySourcesDir
3419
+ }],
3420
+ publishedSourcesDir,
3421
+ signal: options.signal
3422
+ });
3423
+ options.signal?.throwIfAborted();
3424
+ rmSync(backupFunctionRoot, {
3425
+ force: true,
3426
+ recursive: true
3427
+ });
3428
+ try {
3429
+ renameSync(functionRoot, backupFunctionRoot);
3430
+ } catch (error) {
3431
+ if (error.code !== "ENOENT") throw error;
3432
+ }
3433
+ try {
3434
+ renameSync(stagedFunctionRoot, functionRoot);
3435
+ rmSync(backupFunctionRoot, {
3436
+ force: true,
3437
+ recursive: true
3438
+ });
3439
+ } catch (error) {
3440
+ if (existsSync(backupFunctionRoot)) renameSync(backupFunctionRoot, functionRoot);
3441
+ throw error;
3442
+ }
3443
+ if (outputs.length === 0) await removeEmptyDirectories(functionRoot, options.rootDir);
3444
+ }
3445
+ async function writeCloudflareScheduleOutput(options) {
3446
+ options.signal?.throwIfAborted();
3447
+ const outputRoot = createDefaultCloudflareOutputRoot(options.rootDir);
3448
+ await mkdir(outputRoot, { recursive: true });
3449
+ const configFile = resolve(outputRoot, "wrangler.json");
3450
+ let wranglerConfig = {};
3451
+ try {
3452
+ wranglerConfig = JSON.parse(await readFile(configFile, "utf8"));
3453
+ } catch (error) {
3454
+ if (error.code !== "ENOENT") throw error;
3455
+ }
3456
+ const existingTriggers = typeof wranglerConfig.triggers === "object" && wranglerConfig.triggers !== null ? wranglerConfig.triggers : {};
3457
+ const previousState = await readCloudflareOutputState(options.previousStateFile ?? options.stateFile);
3458
+ options.signal?.throwIfAborted();
3459
+ const externalCrons = (existingTriggers.crons ?? []).filter((cron) => !previousState?.crons.includes(cron));
3460
+ const ownedCrons = options.crons.filter((cron) => !externalCrons.includes(cron));
3461
+ const main = typeof wranglerConfig.main === "string" && wranglerConfig.main ? wranglerConfig.main : "index.js";
3462
+ wranglerConfig = {
3463
+ ...wranglerConfig,
3464
+ compatibility_date: wranglerConfig.compatibility_date ?? "2026-04-20",
3465
+ compatibility_flags: wranglerConfig.compatibility_flags ?? ["nodejs_compat"],
3466
+ main,
3467
+ observability: wranglerConfig.observability ?? { enabled: true },
3468
+ triggers: {
3469
+ ...existingTriggers,
3470
+ crons: [...new Set([...externalCrons, ...options.crons])]
3471
+ }
3472
+ };
3473
+ await Promise.all([
3474
+ bundleEsmEntry(options.bundleEntry, resolve(outputRoot, main), {
3475
+ alias: options.bundleAlias,
3476
+ banner: `// ${cloudflareScheduleWorkerMarker}`,
3477
+ conditions: [
3478
+ "workerd",
3479
+ "worker",
3480
+ "browser",
3481
+ "default"
3482
+ ],
3483
+ external: [cloudflareRuntimeExternal, "node:*"],
3484
+ format: "esm",
3485
+ platform: "neutral",
3486
+ plugins: [createScheduleDefinitionAliasPlugin()],
3487
+ rootDir: options.sourceRootDir ?? options.rootDir,
3488
+ signal: options.signal
3489
+ }),
3490
+ writeFile(configFile, `${JSON.stringify(wranglerConfig, null, 2)}\n`, {
3491
+ encoding: "utf8",
3492
+ signal: options.signal
3493
+ }),
3494
+ writeFile(options.stateFile, `${JSON.stringify({
3495
+ crons: ownedCrons,
3496
+ main
3497
+ }, null, 2)}\n`, {
3498
+ encoding: "utf8",
3499
+ signal: options.signal
3500
+ })
3501
+ ]);
3502
+ await publishProviderSourcesToDeploymentOutputs({
3503
+ destinations: [{
3504
+ files: [resolve(outputRoot, main)],
3505
+ runtimeSourcesDir: `./${deployedScheduleSourcesPath}`,
3506
+ sourcesDir: resolve(outputRoot, deployedScheduleSourcesPath)
3507
+ }],
3508
+ publishedSourcesDir: resolve(dirname(options.bundleEntry), "sources"),
3509
+ signal: options.signal
3510
+ });
3511
+ }
3512
+ async function readCloudflareOutputState(file) {
3513
+ let source;
3514
+ try {
3515
+ source = await readFile(file, "utf8");
3516
+ } catch (error) {
3517
+ if (error.code === "ENOENT") return;
3518
+ throw error;
3519
+ }
3520
+ try {
3521
+ const state = JSON.parse(source);
3522
+ if (!Array.isArray(state.crons) || state.crons.some((cron) => typeof cron !== "string") || typeof state.main !== "string" || !state.main) return;
3523
+ return {
3524
+ crons: state.crons,
3525
+ main: state.main
3526
+ };
3527
+ } catch {
3528
+ return;
3529
+ }
3530
+ }
3531
+ async function cleanCloudflareScheduleOutput(rootDir, stateFile, previousStateFile = stateFile) {
3532
+ const state = await readCloudflareOutputState(previousStateFile);
3533
+ if (!state) return;
3534
+ const outputRoot = createDefaultCloudflareOutputRoot(rootDir);
3535
+ const configFile = resolve(outputRoot, "wrangler.json");
3536
+ const workerFile = resolve(outputRoot, state.main);
3537
+ let ownsWorker = false;
3538
+ try {
3539
+ ownsWorker = (await readFile(workerFile, "utf8")).includes(cloudflareScheduleWorkerMarker);
3540
+ } catch (error) {
3541
+ if (error.code !== "ENOENT") throw error;
3542
+ }
3543
+ let configSource;
3544
+ try {
3545
+ configSource = await readFile(configFile, "utf8");
3546
+ } catch (error) {
3547
+ if (error.code !== "ENOENT") throw error;
3548
+ }
3549
+ if (configSource !== void 0) {
3550
+ const config = JSON.parse(configSource);
3551
+ const triggers = typeof config.triggers === "object" && config.triggers !== null ? config.triggers : void 0;
3552
+ const crons = Array.isArray(triggers?.crons) ? triggers.crons.filter((cron) => typeof cron === "string" && !state.crons.includes(cron)) : [];
3553
+ if (triggers) config.triggers = {
3554
+ ...triggers,
3555
+ crons
3556
+ };
3557
+ await writeFile(configFile, `${JSON.stringify(config, null, 2)}\n`, "utf8");
3558
+ }
3559
+ await Promise.all([
3560
+ ...ownsWorker ? [rm(workerFile, { force: true })] : [],
3561
+ rm(resolve(outputRoot, deployedScheduleSourcesPath), {
3562
+ force: true,
3563
+ recursive: true
3564
+ }),
3565
+ rm(stateFile, { force: true })
3566
+ ]);
3567
+ }
3568
+ async function generateProviderOutputsWithinLock(options) {
3569
+ options.signal?.throwIfAborted();
3570
+ const generatedDir = resolve(options.rootDir, ".vitehub", productName);
3571
+ const previousGeneratedDir = `${generatedDir}.${randomUUID()}.previous`;
3572
+ const coordinatesRetainedSources = options.retainedSourcesDir !== void 0;
3573
+ const hadPreviousGeneratedDir = coordinatesRetainedSources && existsSync(generatedDir);
3574
+ if (hadPreviousGeneratedDir) await rename(generatedDir, previousGeneratedDir);
3575
+ const cloudflareStateFile = resolve(generatedDir, cloudflareOutputStateFileName);
3576
+ const previousCloudflareStateFile = hadPreviousGeneratedDir ? resolve(previousGeneratedDir, cloudflareOutputStateFileName) : cloudflareStateFile;
3577
+ let publicationSettled = !coordinatesRetainedSources;
3578
+ try {
3579
+ let artifacts = await writeProviderEntries(options.rootDir, options.source, options.definitions);
3580
+ if (options.retainedSourcesDir && artifacts.definitions.length > 0) artifacts = await publishRetainedProviderSources(artifacts, options.retainedSourcesDir, options.signal);
3581
+ options.signal?.throwIfAborted();
3582
+ const discoveredCrons = options.crons ?? await readDefinitionCrons(artifacts.definitions);
3583
+ const crons = new Map(artifacts.definitions.map((definition) => [definition.name, discoveredCrons.get(definition.name)]));
3584
+ options.signal?.throwIfAborted();
3585
+ if (artifacts.definitions.length > 0) {
3586
+ const stagedDenoCronInputFile = `${artifacts.denoCronFile}.vitehub-input-tmp.mjs`;
3587
+ const stagedDenoCronFile = `${artifacts.denoCronFile}.vitehub-tmp`;
3588
+ try {
3589
+ await writeFile(stagedDenoCronInputFile, renderDenoCronEntry(artifacts.denoCronFile, artifacts.registryFile, crons, options.runtimeImport), "utf8");
3590
+ await bundleEsmEntry(stagedDenoCronInputFile, stagedDenoCronFile, {
3591
+ alias: options.bundleAlias,
3592
+ external: [
3593
+ ...builtinModules,
3594
+ ...builtinModules.map((name) => `node:${name}`),
3595
+ ...options.bundleExternal ?? []
3596
+ ],
3597
+ format: "esm",
3598
+ packages: "external",
3599
+ platform: "neutral",
3600
+ plugins: [createScheduleDefinitionAliasPlugin()],
3601
+ rootDir: options.sourceRootDir ?? options.rootDir,
3602
+ signal: options.signal
3603
+ });
3604
+ await rename(stagedDenoCronFile, artifacts.denoCronFile);
3605
+ } finally {
3606
+ await Promise.all([rm(stagedDenoCronInputFile, { force: true }), rm(stagedDenoCronFile, { force: true })]);
3607
+ }
3608
+ options.signal?.throwIfAborted();
3609
+ await writeCloudflareScheduleOutput({
3610
+ bundleAlias: options.bundleAlias,
3611
+ bundleEntry: artifacts.cloudflareWorkerFile,
3612
+ crons: [...new Set(crons.values())],
3613
+ rootDir: options.rootDir,
3614
+ previousStateFile: previousCloudflareStateFile,
3615
+ sourceRootDir: options.sourceRootDir,
3616
+ stateFile: cloudflareStateFile,
3617
+ signal: options.signal
3618
+ });
3619
+ } else {
3620
+ options.signal?.throwIfAborted();
3621
+ await Promise.all([
3622
+ rm(artifacts.cloudflareWorkerFile, { force: true }),
3623
+ rm(artifacts.denoCronFile, { force: true }),
3624
+ rm(artifacts.registryFile, { force: true }),
3625
+ rm(artifacts.vercelServerFile, { force: true }),
3626
+ cleanCloudflareScheduleOutput(options.rootDir, cloudflareStateFile, previousCloudflareStateFile)
3627
+ ]);
3628
+ }
3629
+ options.signal?.throwIfAborted();
3630
+ await writeVercelScheduleFunctions({
3631
+ bundleAlias: options.bundleAlias,
3632
+ bundleExternal: options.bundleExternal,
3633
+ definitions: artifacts.definitions,
3634
+ outputRoot: createDefaultVercelOutputRoot(options.rootDir),
3635
+ registryFile: artifacts.registryFile,
3636
+ rootDir: options.rootDir,
3637
+ signal: options.signal,
3638
+ sourceRootDir: options.sourceRootDir,
3639
+ workflow: options.workflow
3640
+ }, crons);
3641
+ options.signal?.throwIfAborted();
3642
+ await writeNetlifyScheduleFunctions({
3643
+ definitions: artifacts.definitions,
3644
+ outputRoot: createDefaultNetlifyOutputRoot(options.rootDir),
3645
+ registryFile: artifacts.registryFile,
3646
+ rootDir: options.rootDir,
3647
+ signal: options.signal
3648
+ });
3649
+ publicationSettled = true;
3650
+ if (hadPreviousGeneratedDir) await removeProviderOutputArtifactDir(previousGeneratedDir).catch(() => void 0);
3651
+ return artifacts;
3652
+ } catch (error) {
3653
+ if (!publicationSettled) try {
3654
+ await removeProviderOutputArtifactDir(generatedDir);
3655
+ if (hadPreviousGeneratedDir) await rename(previousGeneratedDir, generatedDir);
3656
+ publicationSettled = true;
3657
+ } catch (restoreError) {
3658
+ throw new AggregateError([error, restoreError], "Generated Schedule artifact rollback failed");
3659
+ }
3660
+ throw error;
3661
+ }
3662
+ }
3663
+ //#endregion
3664
+ //#region src/targets-module.ts
3665
+ const SCHEDULE_TARGETS_ID = "#vitehub/schedule/targets";
3666
+ function getScheduleTargetNames(definitions) {
3667
+ return definitions.filter((definition) => definition.allowRuntimeSchedules).map((definition) => definition.name).sort();
3668
+ }
3669
+ function createScheduleTargetsContents(definitions, options = {}) {
3670
+ const targets = getScheduleTargetNames(definitions);
3671
+ const union = targets.length ? targets.map((target) => JSON.stringify(target)).join(" | ") : "never";
3672
+ return [
3673
+ `export const scheduleTargetNames = ${JSON.stringify(targets)};`,
3674
+ options.types ? `export type ScheduleTargetName = ${union};` : "",
3675
+ ""
3676
+ ].filter((line) => line !== "").join("\n");
3677
+ }
3678
+ //#endregion
3679
+ //#region src/vite.ts
3680
+ async function readScheduleDefinitionCrons(definitions) {
3681
+ return await readRuntimeDefinitionCrons(definitions);
3682
+ }
3683
+ const SCHEDULE_VITE_PLUGIN_NAME = "@vite-hub/schedule/vite";
3684
+ const SCHEDULE_REGISTRY_ID = "#vitehub/schedule/registry";
3685
+ const RESOLVED_SCHEDULE_REGISTRY_ID = "\0#vitehub/schedule/registry";
3686
+ const RESOLVED_SCHEDULE_TARGETS_ID = `\0${SCHEDULE_TARGETS_ID}`;
3687
+ const registryImportAnchor = ".vitehub/schedule/registry.js";
3688
+ const generatedNitroSchedulePlugin = ".vitehub/nitro/schedule/plugin.ts";
3689
+ const generatedNitroProviderRegistry = ".vitehub/nitro/schedule/provider-registry.js";
3690
+ const generatedNitroRuntimeRegistry = ".vitehub/nitro/schedule/runtime-registry.js";
3691
+ const generatedNitroStaticRegistry = ".vitehub/nitro/schedule/static-registry.js";
3692
+ const generatedNitroCloudflareModule = "./.vitehub/nitro/schedule/module.mjs";
3693
+ const mergeNoExternal = createNoExternalMerger(schedulePackageName);
3694
+ function resolveSchedulePluginRoots(root, options = {}) {
3695
+ const resolvedViteRoot = resolve(root);
3696
+ return {
3697
+ projectRoot: resolveViteHubProjectRoot(resolvedViteRoot, { projectRoot: options.projectRoot }),
3698
+ viteRoot: resolvedViteRoot
3699
+ };
3700
+ }
3701
+ function isRecord(value) {
3702
+ return typeof value === "object" && value !== null;
3703
+ }
3704
+ function resolveProcessRuntimeOptions(value) {
3705
+ if (value === void 0) return;
3706
+ if (!isRecord(value) || value.driver !== "process") throw new TypeError("Schedule Process Runtime driver must be \"process\".");
3707
+ if (value.prefix !== void 0 && typeof value.prefix !== "string") throw new TypeError("Schedule Process Runtime prefix must be a string.");
3708
+ if (value.intervalMs !== void 0 && (typeof value.intervalMs !== "number" || !Number.isFinite(value.intervalMs) || value.intervalMs <= 0 || value.intervalMs > 6e4)) throw new TypeError("Schedule Process Runtime intervalMs must be a positive number no greater than 60000.");
3709
+ if (value.concurrency !== void 0 && (typeof value.concurrency !== "number" || !Number.isInteger(value.concurrency) || value.concurrency < 1)) throw new TypeError("Schedule Process Runtime concurrency must be a positive integer.");
3710
+ return {
3711
+ ...value.concurrency !== void 0 ? { concurrency: value.concurrency } : {},
3712
+ driver: "process",
3713
+ ...value.intervalMs !== void 0 ? { intervalMs: value.intervalMs } : {},
3714
+ ...value.prefix !== void 0 ? { prefix: value.prefix } : {}
3715
+ };
3716
+ }
3717
+ function resolveStringAliases(config) {
3718
+ return encodeProviderOutputAliases(config.resolve.alias);
3719
+ }
3720
+ function moduleImportSpecifier(fromFile, targetFile) {
3721
+ const specifier = relative(dirname(fromFile), targetFile).replace(/\\/g, "/");
3722
+ return specifier.startsWith(".") ? specifier : `./${specifier}`;
3723
+ }
3724
+ function cloneNitroConfig(value) {
3725
+ const nitro = isRecord(value) ? { ...value } : {};
3726
+ if (Array.isArray(nitro.plugins)) nitro.plugins = [...nitro.plugins];
3727
+ if (isRecord(nitro.cloudflare)) {
3728
+ const cloudflare = { ...nitro.cloudflare };
3729
+ if (isRecord(cloudflare.wrangler)) {
3730
+ const wrangler = { ...cloudflare.wrangler };
3731
+ if (isRecord(wrangler.triggers)) {
3732
+ const triggers = { ...wrangler.triggers };
3733
+ if (Array.isArray(triggers.crons)) triggers.crons = triggers.crons.filter((cron) => typeof cron === "string");
3734
+ wrangler.triggers = triggers;
3735
+ }
3736
+ cloudflare.wrangler = wrangler;
3737
+ }
3738
+ nitro.cloudflare = cloudflare;
3739
+ }
3740
+ return nitro;
3741
+ }
3742
+ function isGeneratedNitroRegistration(value, generatedPath) {
3743
+ const suffix = generatedPath.replace(/^\.\//, "");
3744
+ return typeof value === "string" && (value === generatedPath || value.replaceAll("\\", "/").endsWith(`/${suffix}`));
3745
+ }
3746
+ function mergeNitroScheduleConfig(value, options) {
3747
+ const nitro = cloneNitroConfig(value);
3748
+ nitro.plugins = [...Array.isArray(nitro.plugins) ? nitro.plugins.filter((plugin) => !isGeneratedNitroRegistration(plugin, generatedNitroSchedulePlugin)) : [], options.plugin];
3749
+ if (!options.providerWake) return nitro;
3750
+ nitro.modules = [...Array.isArray(nitro.modules) ? nitro.modules.filter((module) => !isGeneratedNitroRegistration(module, generatedNitroCloudflareModule)) : [], options.module];
3751
+ nitro.cloudflare ||= {};
3752
+ nitro.cloudflare.wrangler ||= {};
3753
+ const wrangler = nitro.cloudflare.wrangler;
3754
+ const existingTriggers = isRecord(wrangler.triggers) ? wrangler.triggers : {};
3755
+ const existingCrons = Array.isArray(existingTriggers.crons) ? existingTriggers.crons.filter((cron) => typeof cron === "string") : [];
3756
+ wrangler.triggers = {
3757
+ ...existingTriggers,
3758
+ crons: [...new Set([...existingCrons, ...options.crons])]
3759
+ };
3760
+ return nitro;
3761
+ }
3762
+ function mergeNitroVercelCrons(value, definitions, crons) {
3763
+ const nitro = cloneNitroConfig(value);
3764
+ const vercel = isRecord(nitro.vercel) ? { ...nitro.vercel } : {};
3765
+ const config = isRecord(vercel.config) ? { ...vercel.config } : {};
3766
+ const generatedPaths = new Set(definitions.map((definition) => getVercelSchedulePath(definition.name)));
3767
+ config.crons = [...Array.isArray(config.crons) ? config.crons.filter((cron) => isRecord(cron) && typeof cron.path === "string" && !generatedPaths.has(cron.path)) : [], ...definitions.map((definition) => ({
3768
+ path: getVercelSchedulePath(definition.name),
3769
+ schedule: crons.get(definition.name)
3770
+ }))];
3771
+ vercel.config = config;
3772
+ nitro.vercel = vercel;
3773
+ return nitro;
3774
+ }
3775
+ function renderNitroSchedulePlugin(options) {
3776
+ const importBase = options.importBase ?? "@vite-hub/schedule";
3777
+ const providerWake = options.providerDefinitions.length > 0;
3778
+ const processRuntime = options.processRuntime;
3779
+ const processDriverOptions = processRuntime ? {
3780
+ ...processRuntime.concurrency !== void 0 ? { concurrency: processRuntime.concurrency } : {},
3781
+ ...processRuntime.intervalMs !== void 0 ? { intervalMs: processRuntime.intervalMs } : {}
3782
+ } : void 0;
3783
+ const scheduleStoreOptions = processRuntime?.prefix !== void 0 ? { prefix: processRuntime.prefix } : {};
3784
+ return [
3785
+ "import { definePlugin } from 'nitro'",
3786
+ ...providerWake ? [`import scheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.providerRegistryFile))}`, `import { executeCloudflareStaticSchedules } from ${JSON.stringify(options.runtimeImport ?? `${importBase}/runtime/static`)}`] : [],
3787
+ ...processRuntime ? [
3788
+ `import { createKVRuntimeScheduleStore, createKVScheduleRunStore } from ${JSON.stringify(importBase)}`,
3789
+ `import { installScheduleRuntime } from ${JSON.stringify(`${importBase}/runtime/driver`)}`,
3790
+ `import { createProcessScheduleWakeDriver } from ${JSON.stringify(`${importBase}/runtime/process`)}`,
3791
+ `import runtimeScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.runtimeRegistryFile))}`,
3792
+ `import staticScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.staticRegistryFile))}`
3793
+ ] : [],
3794
+ "",
3795
+ ...processRuntime ? [
3796
+ `const processDriverOptions = ${JSON.stringify(processDriverOptions, null, 2)}`,
3797
+ `const scheduleStoreOptions = ${JSON.stringify(scheduleStoreOptions, null, 2)}`,
3798
+ ""
3799
+ ] : [],
3800
+ "export default definePlugin((nitroApp) => {",
3801
+ ...providerWake ? [
3802
+ " nitroApp.hooks.hook('cloudflare:scheduled', async (event) => {",
3803
+ " await executeCloudflareStaticSchedules(event, { registry: scheduleRegistry })",
3804
+ " })"
3805
+ ] : [],
3806
+ ...processRuntime ? [
3807
+ " function captureRuntimeError(error: unknown) {",
3808
+ " let runtimeError: Error",
3809
+ " try {",
3810
+ " runtimeError = error instanceof Error ? error : new Error(String(error))",
3811
+ " }",
3812
+ " catch {",
3813
+ " return",
3814
+ " }",
3815
+ " try {",
3816
+ " console.error('[vitehub:schedule]', runtimeError)",
3817
+ " }",
3818
+ " catch {}",
3819
+ " try {",
3820
+ " nitroApp.captureError?.(runtimeError, { tags: ['vitehub-schedule'] })",
3821
+ " }",
3822
+ " catch {}",
3823
+ " }",
3824
+ " const runtimeInstallation = installScheduleRuntime({",
3825
+ " createDriver: createProcessScheduleWakeDriver(processDriverOptions),",
3826
+ " onError: captureRuntimeError,",
3827
+ " registry: runtimeScheduleRegistry,",
3828
+ " runtimeScheduleStore: createKVRuntimeScheduleStore(scheduleStoreOptions),",
3829
+ " scheduleRunStore: createKVScheduleRunStore(scheduleStoreOptions),",
3830
+ " staticRegistry: staticScheduleRegistry,",
3831
+ " }).then(",
3832
+ " controller => ({ controller }),",
3833
+ " error => {",
3834
+ " captureRuntimeError(error)",
3835
+ " return { error }",
3836
+ " },",
3837
+ " )",
3838
+ " const nodeProcess = globalThis.process",
3839
+ " const shutdownSignals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM']",
3840
+ " let runtimeClose: Promise<void> | undefined",
3841
+ " function removeRuntimeShutdownSignals() {",
3842
+ " for (const signal of shutdownSignals) nodeProcess?.off(signal, closeRuntimeOnSignal)",
3843
+ " }",
3844
+ " function closeRuntime() {",
3845
+ " removeRuntimeShutdownSignals()",
3846
+ " runtimeClose ??= runtimeInstallation.then(async (result) => {",
3847
+ " if ('controller' in result) await result.controller.close()",
3848
+ " })",
3849
+ " return runtimeClose",
3850
+ " }",
3851
+ " function closeRuntimeOnSignal(signal: NodeJS.Signals) {",
3852
+ " void closeRuntime().catch(captureRuntimeError).finally(() => {",
3853
+ " if (nodeProcess) nodeProcess.kill(nodeProcess.pid, signal)",
3854
+ " })",
3855
+ " }",
3856
+ " for (const signal of shutdownSignals) nodeProcess?.prependOnceListener(signal, closeRuntimeOnSignal)",
3857
+ " nitroApp.hooks.hook('request', async () => {",
3858
+ " const result = await runtimeInstallation",
3859
+ " if ('error' in result) throw result.error",
3860
+ " })",
3861
+ " nitroApp.hooks.hook('close', closeRuntime)"
3862
+ ] : [],
3863
+ "})",
3864
+ "",
3865
+ `export const vitehubScheduleDefinitions = ${JSON.stringify(options.providerDefinitions.map((definition) => definition.name))}`,
3866
+ ""
3867
+ ].join("\n");
3868
+ }
3869
+ function renderNitroCloudflareModule(crons) {
3870
+ return [
3871
+ `const crons = ${JSON.stringify(crons)}`,
3872
+ "",
3873
+ "function dedupeCloudflareCrons(nitro) {",
3874
+ " const wrangler = nitro.options.cloudflare?.wrangler",
3875
+ " if (!wrangler?.triggers || !Array.isArray(wrangler.triggers.crons)) return",
3876
+ " wrangler.triggers.crons = [...new Set(wrangler.triggers.crons.filter((cron) => typeof cron === 'string'))]",
3877
+ "}",
3878
+ "",
3879
+ "export default function vitehubScheduleModule(nitro) {",
3880
+ " nitro.options.cloudflare ??= {}",
3881
+ " nitro.options.cloudflare.wrangler ??= {}",
3882
+ " nitro.options.cloudflare.wrangler.triggers ??= {}",
3883
+ " const existingCrons = Array.isArray(nitro.options.cloudflare.wrangler.triggers.crons) ? nitro.options.cloudflare.wrangler.triggers.crons : []",
3884
+ " nitro.options.cloudflare.wrangler.triggers.crons = [...new Set([...existingCrons, ...crons])]",
3885
+ " nitro.hooks.hook('build:before', dedupeCloudflareCrons)",
3886
+ "}",
3887
+ ""
3888
+ ].join("\n");
3889
+ }
3890
+ function renderScheduleRegistryTypes(importBase = schedulePackageName) {
3891
+ return [
3892
+ `import type { ScheduleRegistryDefinition } from ${JSON.stringify(importBase)}`,
3893
+ "",
3894
+ "declare const registry: Record<string, () => Promise<ScheduleRegistryDefinition | { default?: ScheduleRegistryDefinition }>>",
3895
+ "export default registry",
3896
+ ""
3897
+ ].join("\n");
3898
+ }
3899
+ async function writeNitroSchedulePlugin(root, options) {
3900
+ const pluginFile = resolve(root, generatedNitroSchedulePlugin);
3901
+ const moduleFile = resolve(root, generatedNitroCloudflareModule);
3902
+ const providerRegistryFile = resolve(root, generatedNitroProviderRegistry);
3903
+ const runtimeRegistryFile = resolve(root, generatedNitroRuntimeRegistry);
3904
+ const staticRegistryFile = resolve(root, generatedNitroStaticRegistry);
3905
+ await mkdir(dirname(pluginFile), { recursive: true });
3906
+ const writes = [writeFile(pluginFile, renderNitroSchedulePlugin({
3907
+ importBase: options.importBase,
3908
+ pluginFile,
3909
+ processRuntime: options.processRuntime,
3910
+ providerDefinitions: options.providerDefinitions,
3911
+ providerRegistryFile,
3912
+ runtimeRegistryFile,
3913
+ staticRegistryFile,
3914
+ runtimeImport: options.runtimeImport
3915
+ }), "utf8")];
3916
+ if (options.processRuntime) {
3917
+ writes.push(writeFile(runtimeRegistryFile, createRuntimeRegistryContents(runtimeRegistryFile, options.runtimeDefinitions), "utf8"));
3918
+ writes.push(writeFile(runtimeRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase), "utf8"));
3919
+ writes.push(writeFile(staticRegistryFile, createRuntimeRegistryContents(staticRegistryFile, options.staticDefinitions), "utf8"));
3920
+ writes.push(writeFile(staticRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase), "utf8"));
3921
+ }
3922
+ if (options.providerDefinitions.length > 0) {
3923
+ await mkdir(dirname(providerRegistryFile), { recursive: true });
3924
+ writes.push(writeFile(providerRegistryFile, createRuntimeRegistryContents(providerRegistryFile, options.providerDefinitions), "utf8"));
3925
+ writes.push(writeFile(providerRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase), "utf8"));
3926
+ writes.push(writeFile(moduleFile, renderNitroCloudflareModule(options.crons), "utf8"));
3927
+ }
3928
+ await Promise.all(writes);
3929
+ return generatedNitroSchedulePlugin;
3930
+ }
3931
+ function hasServerScheduleDefinitions(definitions) {
3932
+ return definitions.some((definition) => definition.runtimeOnly !== true && definition.source === "server-schedules");
3933
+ }
3934
+ function hasViteSuffixScheduleDefinitions(definitions) {
3935
+ return definitions.some((definition) => definition.runtimeOnly !== true && definition.source === "vite-suffix");
3936
+ }
3937
+ function selectNitroScheduleDefinitions(definitions, options) {
3938
+ if (options.providerOutput === false || options.providerOutput === "standalone") return [];
3939
+ const staticDefinitions = definitions.filter((definition) => definition.runtimeOnly !== true);
3940
+ if (options.providerOutput === "nitro") return staticDefinitions;
3941
+ return staticDefinitions.filter((definition) => definition.source === "server-schedules");
3942
+ }
3943
+ function selectStandaloneProviderSource(definitions, options) {
3944
+ if (options.providerOutput === "auto" || options.providerOutput === void 0) return hasServerScheduleDefinitions(definitions) ? "vite-suffix" : void 0;
3945
+ }
3946
+ function shouldInstallNitroSchedulePlugin(definitions, options) {
3947
+ return selectNitroScheduleDefinitions(definitions, options).length > 0 || options.runtime !== void 0;
3948
+ }
3949
+ function shouldEmitStandaloneProviderOutput(definitions, options) {
3950
+ if (options.providerOutput === false || options.providerOutput === "nitro") return false;
3951
+ if (options.providerOutput === "standalone") return definitions.some((definition) => definition.runtimeOnly !== true);
3952
+ if (hasServerScheduleDefinitions(definitions)) return hasViteSuffixScheduleDefinitions(definitions);
3953
+ return definitions.some((definition) => definition.runtimeOnly !== true);
3954
+ }
3955
+ async function createScheduleNitroConfig(options = {}) {
3956
+ const processRuntime = resolveProcessRuntimeOptions(options.runtime);
3957
+ const roots = resolveSchedulePluginRoots(options.root || process.cwd(), options);
3958
+ const definitions = discoverScheduleDefinitions({
3959
+ rootDir: roots.viteRoot,
3960
+ serverDirs: options.serverDirs,
3961
+ serverRootDir: roots.projectRoot
3962
+ });
3963
+ const installNitroPlugin = shouldInstallNitroSchedulePlugin(definitions, options);
3964
+ const nitroPreset = isRecord(options.nitro) && typeof options.nitro.preset === "string" ? options.nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING || "";
3965
+ const standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
3966
+ const vercelDefinitions = options.command === "build" && nitroPreset.startsWith("vercel") && (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options) ? definitions.filter((definition) => definition.runtimeOnly !== true && (standaloneProviderSource === void 0 || definition.source === standaloneProviderSource)) : [];
3967
+ if (!installNitroPlugin && !vercelDefinitions.length) return null;
3968
+ let nitro = options.nitro;
3969
+ if (vercelDefinitions.length) nitro = mergeNitroVercelCrons(nitro, vercelDefinitions, await readDefinitionCrons(vercelDefinitions));
3970
+ if (!installNitroPlugin) return nitro;
3971
+ const nitroDefinitions = processRuntime && options.providerOutput !== "nitro" ? [] : selectNitroScheduleDefinitions(definitions, options);
3972
+ const crons = options.command === "build" ? [...new Set((await readDefinitionCrons(nitroDefinitions)).values())] : [];
3973
+ const nitroDefinitionNames = new Set(nitroDefinitions.map((definition) => definition.name));
3974
+ const plugin = await writeNitroSchedulePlugin(roots.projectRoot, {
3975
+ crons,
3976
+ importBase: options.importBase,
3977
+ processRuntime,
3978
+ providerDefinitions: nitroDefinitions,
3979
+ runtimeDefinitions: definitions,
3980
+ staticDefinitions: definitions.filter((definition) => definition.runtimeOnly !== true && !nitroDefinitionNames.has(definition.name) && !(processRuntime && options.providerOutput === "standalone")),
3981
+ runtimeImport: options.runtimeImport
3982
+ });
3983
+ return mergeNitroScheduleConfig(nitro, {
3984
+ crons,
3985
+ module: options.nitroOwnsPaths ? resolve(roots.projectRoot, generatedNitroCloudflareModule) : generatedNitroCloudflareModule,
3986
+ plugin: options.nitroOwnsPaths ? resolve(roots.projectRoot, plugin) : plugin,
3987
+ providerWake: nitroDefinitions.length > 0
3988
+ });
3989
+ }
3990
+ function hubSchedule(options = {}) {
3991
+ const internalOptions = options;
3992
+ let resolved;
3993
+ let emitStandaloneProviderOutput = true;
3994
+ let projectRoot;
3995
+ let providerOutput;
3996
+ const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
3997
+ let standaloneProviderSource;
3998
+ let serverDirs;
3999
+ let viteRoot;
4000
+ function discoverViteSchedules() {
4001
+ if (!projectRoot || !viteRoot) return [];
4002
+ return discoverScheduleDefinitions({
4003
+ mode: "vite-suffix",
4004
+ rootDir: viteRoot,
4005
+ serverDirs,
4006
+ serverRootDir: projectRoot
4007
+ });
4008
+ }
4009
+ function discoverRegistrySchedules() {
4010
+ if (!projectRoot || !viteRoot) return [];
4011
+ return discoverScheduleDefinitions({
4012
+ rootDir: viteRoot,
4013
+ serverDirs,
4014
+ serverRootDir: projectRoot
4015
+ });
4016
+ }
4017
+ function createRegistryContents() {
4018
+ const definitions = discoverRegistrySchedules();
4019
+ return createRuntimeRegistryContents(projectRoot ? resolve(projectRoot, registryImportAnchor) : registryImportAnchor, definitions);
4020
+ }
4021
+ function createTargetsContents() {
4022
+ return createScheduleTargetsContents(discoverViteSchedules(), { types: false });
4023
+ }
4024
+ return {
4025
+ name: SCHEDULE_VITE_PLUGIN_NAME,
4026
+ enforce: "pre",
4027
+ async config(config, env) {
4028
+ serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
4029
+ const roots = resolveSchedulePluginRoots(config.root || process.cwd(), options);
4030
+ const definitions = discoverScheduleDefinitions({
4031
+ rootDir: roots.viteRoot,
4032
+ serverDirs,
4033
+ serverRootDir: roots.projectRoot
4034
+ });
4035
+ emitStandaloneProviderOutput = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options);
4036
+ standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
4037
+ const nitro = await createScheduleNitroConfig({
4038
+ ...options,
4039
+ command: env.command,
4040
+ nitroOwnsPaths: hasNitroConfigContext(config),
4041
+ nitro: config.nitro,
4042
+ root: config.root || process.cwd(),
4043
+ serverDirs
4044
+ });
4045
+ if (!nitro) return null;
4046
+ config.nitro = nitro;
4047
+ },
4048
+ configResolved(config) {
4049
+ resolved = config;
4050
+ providerOutput = useProviderOutputCatalog(config);
4051
+ const roots = resolveSchedulePluginRoots(config.root, options);
4052
+ projectRoot = roots.projectRoot;
4053
+ viteRoot = roots.viteRoot;
4054
+ },
4055
+ configEnvironment(name, config) {
4056
+ if (!isServerEnvironment(name, config)) return;
4057
+ return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
4058
+ },
4059
+ handleHotUpdate(context) {
4060
+ const file = normalize(context.file).replace(/\\/g, "/");
4061
+ const serverSchedule = (serverDirs ?? [resolve(projectRoot ?? resolved?.root ?? context.server.config.root, "server")]).map((directory) => `${resolve(directory, "schedules").replace(/\\/g, "/")}/`).some((directory) => file.startsWith(directory) && /\.(?:c|m)?[jt]s$/i.test(file.slice(directory.length)));
4062
+ if (!/\.schedule\.(?:c|m)?[jt]s$/i.test(file) && !serverSchedule) return;
4063
+ const registryModule = context.server.moduleGraph.getModuleById(RESOLVED_SCHEDULE_REGISTRY_ID);
4064
+ if (registryModule) context.server.moduleGraph.invalidateModule(registryModule);
4065
+ const targetsModule = context.server.moduleGraph.getModuleById(RESOLVED_SCHEDULE_TARGETS_ID);
4066
+ if (targetsModule) context.server.moduleGraph.invalidateModule(targetsModule);
4067
+ },
4068
+ resolveId(id) {
4069
+ if (id === SCHEDULE_REGISTRY_ID) return RESOLVED_SCHEDULE_REGISTRY_ID;
4070
+ if (id === "#vitehub/schedule/targets") return RESOLVED_SCHEDULE_TARGETS_ID;
4071
+ },
4072
+ load(id) {
4073
+ if (id === RESOLVED_SCHEDULE_REGISTRY_ID) return createRegistryContents();
4074
+ if (id === RESOLVED_SCHEDULE_TARGETS_ID) return createTargetsContents();
4075
+ },
4076
+ buildStart() {
4077
+ providerOutputGenerations.capture(this, providerOutput);
4078
+ },
4079
+ async buildEnd(error) {
4080
+ if (error) {
4081
+ await providerOutputGenerations.reset(this, providerOutput, error);
4082
+ return;
4083
+ }
4084
+ if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
4085
+ const config = resolved;
4086
+ const rootDir = projectRoot ?? config.root;
4087
+ let artifactDir;
4088
+ try {
4089
+ const definitions = emitStandaloneProviderOutput ? discoverRegistrySchedules() : [];
4090
+ const crons = await readDefinitionCrons(definitions);
4091
+ const prepareWorkflow = (config.plugins ?? []).find((candidate) => candidate.vitehub?.workflow?.prepareScheduleRuntime)?.vitehub?.workflow?.prepareScheduleRuntime;
4092
+ artifactDir = resolve(rootDir, ".vitehub/schedule-generations", randomUUID());
4093
+ const contributionArtifactDir = artifactDir;
4094
+ const workflow = await prepareWorkflow?.(resolve(contributionArtifactDir, "workflow"));
4095
+ const contributedAliases = await collectViteHubProviderImportAliases(config.plugins ?? []);
4096
+ const aliases = {
4097
+ ...resolveStringAliases(config),
4098
+ ...contributedAliases,
4099
+ ...internalOptions.providerImportAliases,
4100
+ ...workflow?.bundleAlias
4101
+ };
4102
+ const retainedSources = definitions.length || workflow ? await retainProviderOutputSources({
4103
+ artifactDir: resolve(contributionArtifactDir, "sources"),
4104
+ paths: [
4105
+ ...definitions.map((definition) => definition.handler),
4106
+ ...Object.keys(aliases),
4107
+ ...Object.values(aliases)
4108
+ ],
4109
+ roots: [rootDir]
4110
+ }) : { resolve: (path) => path };
4111
+ const retainedDefinitions = definitions.map((definition) => ({
4112
+ ...definition,
4113
+ handler: retainedSources.resolve(definition.handler)
4114
+ }));
4115
+ const retainedAliases = retainProviderOutputAliases(aliases, retainedSources);
4116
+ const bundleExternal = workflow ? [
4117
+ "@vitejs/devtools-core",
4118
+ "@vitejs/devtools-kit",
4119
+ "@vitejs/devtools-rolldown"
4120
+ ] : void 0;
4121
+ contributeProviderDeploymentOutput(providerOutput, {
4122
+ discard: async () => await removeProviderOutputArtifactDir(contributionArtifactDir),
4123
+ owner: "schedule",
4124
+ rootDir,
4125
+ write: async ({ signal }) => {
4126
+ signal.throwIfAborted();
4127
+ if ((await generateProviderOutputsWithinLock({
4128
+ bundleAlias: retainedAliases,
4129
+ bundleExternal,
4130
+ clientOutDir: resolve(config.root, config.build.outDir),
4131
+ definitions: retainedDefinitions,
4132
+ crons,
4133
+ rootDir,
4134
+ retainedSourcesDir: resolve(contributionArtifactDir, "sources"),
4135
+ runtimeImport: internalOptions.runtimeImport,
4136
+ signal,
4137
+ source: standaloneProviderSource,
4138
+ sourceRootDir: retainedSources.resolve(rootDir),
4139
+ workflow
4140
+ })).definitions.length === 0) await rm(resolve(rootDir, ".vitehub", "schedule", "sources"), {
4141
+ force: true,
4142
+ recursive: true
4143
+ });
4144
+ }
4145
+ }, providerOutputGenerations.get(this));
4146
+ } catch (error) {
4147
+ if (artifactDir) await removeProviderOutputArtifactDir(artifactDir);
4148
+ await providerOutputGenerations.reset(this, providerOutput, error);
4149
+ throw error;
4150
+ }
4151
+ },
4152
+ async renderError(error) {
4153
+ await providerOutputGenerations.reset(this, providerOutput, error);
4154
+ },
4155
+ closeBundle: {
4156
+ order: "post",
4157
+ sequential: true,
4158
+ async handler() {
4159
+ if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
4160
+ await finalizeProviderDeploymentOutputs(providerOutput);
4161
+ }
4162
+ }
4163
+ };
4164
+ }
4165
+ //#endregion
4166
+ export { hubSchedule as n, readScheduleDefinitionCrons as r, createScheduleNitroConfig as t };