@vite-hub/schedule 0.0.1 → 0.0.2

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,1221 @@
1
+ import { a as createImportPath, i as createRuntimeRegistryContents, n as findDefaultExportCall, o as ensureGeneratedDir, r as readObjectProperty, t as discoverScheduleDefinitions } from "./discovery-MXY52MTU.js";
2
+ import { readFileSync, statSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, normalize, relative, resolve } from "node:path";
4
+ import { mkdir, readFile, readdir, rm, rmdir, stat, writeFile } from "node:fs/promises";
5
+ import { fileURLToPath } from "node:url";
6
+ import { build } from "esbuild";
7
+ import { isDeepStrictEqual } from "node:util";
8
+ //#region ../internal/src/build/user-entry.ts
9
+ function toSafeAppName(rootDir) {
10
+ return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
11
+ }
12
+ function createDefaultCloudflareOutputRoot(rootDir) {
13
+ return resolve(rootDir, "dist", toSafeAppName(rootDir));
14
+ }
15
+ //#endregion
16
+ //#region ../internal/src/build/vite.ts
17
+ const projectRootDirectoryMarkers = [
18
+ ["server", "agents"],
19
+ ["server", "schedules"],
20
+ ["server", "templates"],
21
+ ["server", "workspaces"]
22
+ ];
23
+ const projectRootDefinitionFileMarkers = [
24
+ ".ts",
25
+ ".mts",
26
+ ".cts",
27
+ ".js",
28
+ ".mjs",
29
+ ".cjs"
30
+ ].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
31
+ const projectRootFileMarkers = [["package.json"]];
32
+ function createNoExternalMerger(packageName) {
33
+ return (current) => {
34
+ if (current === true) return true;
35
+ if (!current) return [packageName];
36
+ const values = Array.isArray(current) ? current : [current];
37
+ return values.includes(packageName) ? values : [...values, packageName];
38
+ };
39
+ }
40
+ function isServerEnvironment(name, config) {
41
+ return name === "ssr" || config.consumer === "server";
42
+ }
43
+ function shouldSkipViteProviderBuild(command, mode) {
44
+ return command === "serve" || mode === "e2e";
45
+ }
46
+ function resolveViteHubProjectRoot(root, options = {}) {
47
+ const resolvedRoot = resolve(root);
48
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
49
+ if (basename(resolvedRoot) === "app") {
50
+ const parent = dirname(resolvedRoot);
51
+ if (hasProjectRootDirectoryMarker(parent) || hasProjectRootDefinitionFileMarker(parent)) return parent;
52
+ }
53
+ let current = resolvedRoot;
54
+ while (true) {
55
+ if (hasProjectRootMarker(current)) return current;
56
+ const parent = dirname(current);
57
+ if (parent === current) return resolvedRoot;
58
+ current = parent;
59
+ }
60
+ }
61
+ function hasProjectRootDirectoryMarker(root) {
62
+ for (const marker of projectRootDirectoryMarkers) try {
63
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
64
+ } catch (error) {
65
+ if (error.code !== "ENOENT") throw error;
66
+ }
67
+ return false;
68
+ }
69
+ function hasProjectRootMarker(root) {
70
+ if (hasProjectRootDirectoryMarker(root)) return true;
71
+ if (hasProjectRootDefinitionFileMarker(root)) return true;
72
+ for (const marker of projectRootFileMarkers) try {
73
+ if (statSync(resolve(root, ...marker)).isFile()) return true;
74
+ } catch (error) {
75
+ if (error.code !== "ENOENT") throw error;
76
+ }
77
+ return false;
78
+ }
79
+ function hasProjectRootDefinitionFileMarker(root) {
80
+ for (const marker of projectRootDefinitionFileMarkers) try {
81
+ if (statSync(resolve(root, ...marker)).isFile()) return true;
82
+ } catch (error) {
83
+ if (error.code !== "ENOENT") throw error;
84
+ }
85
+ return false;
86
+ }
87
+ //#endregion
88
+ //#region ../internal/src/build/esbuild.ts
89
+ const viteRawNamespace = "vitehub-vite-raw";
90
+ const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
91
+ const markdownTemplateFileSuffix = ".template.md";
92
+ const markdownTemplateModuleQuery = "markdown-template";
93
+ const markdownTemplateRegistryId = "#vitehub/templates";
94
+ const markdownTemplateRegistryPath = ".vitehub/markdown-template/templates.mjs";
95
+ const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
96
+ const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
97
+ function resolveEsbuildAliases(aliases) {
98
+ if (!aliases) return;
99
+ return Object.fromEntries(Object.entries(aliases).filter(([specifier]) => !specifier.endsWith("/")));
100
+ }
101
+ function stripMarkdownCode(template) {
102
+ let fence;
103
+ let inList = false;
104
+ let previousLineBlank = true;
105
+ return template.split("\n").map((line) => {
106
+ const content = line.replace(/^(?: {0,3}> ?)+/, "");
107
+ if (!fence) {
108
+ const listIndented = inList && /^ {4}(?:`{3,}|~{3,})/.test(content);
109
+ const opening = (listIndented ? content.slice(4) : content).match(/^ {0,3}(`{3,}|~{3,})/);
110
+ if (!opening) {
111
+ if (/^ {0,3}(?:[-+*]|\d+[.)])\s+/.test(content)) inList = true;
112
+ else if (content.trim() && !/^ {2,}/.test(content)) inList = false;
113
+ const indentedCode = !inList && previousLineBlank && /^(?: {4}|\t)/.test(content) || inList && previousLineBlank && /^(?: {8}| {4}\t|\t{2})/.test(content);
114
+ previousLineBlank = content.trim() === "";
115
+ return indentedCode ? "" : line;
116
+ }
117
+ fence = {
118
+ marker: opening[1][0],
119
+ length: opening[1].length,
120
+ listIndented
121
+ };
122
+ previousLineBlank = false;
123
+ return "";
124
+ }
125
+ const closing = (fence.listIndented ? content.replace(/^ {4}/, "") : content).match(/^ {0,3}(`+|~+)\s*$/)?.[1];
126
+ if (closing?.[0] === fence.marker && closing.length >= fence.length) fence = void 0;
127
+ previousLineBlank = false;
128
+ return "";
129
+ }).join("\n");
130
+ }
131
+ function extractMarkdownTemplateImportSpecifiers(template) {
132
+ const visible = stripMarkdownCode(template).replace(/(`+)[\s\S]*?\1/g, "").replace(/(!?\[[^\]]*\])\([^)]*\)/g, "$1").replace(/^ {0,3}\[[^\]]+\]:\s*\S+/gm, "").replace(/<[^>]*>/g, "");
133
+ const specifiers = /* @__PURE__ */ new Set();
134
+ for (const match of visible.matchAll(/@(\.\.?\/[^\s<>{}[\]]+)/g)) {
135
+ const token = match[1];
136
+ const trailing = token.match(/[.,;:!?)]*$/)?.[0] || "";
137
+ specifiers.add(token.slice(0, token.length - trailing.length));
138
+ }
139
+ return [...specifiers];
140
+ }
141
+ function parseMarkdownTemplateRequest(id) {
142
+ const queryIndex = id.indexOf("?");
143
+ const path = id.split(/[?#]/, 1)[0];
144
+ if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
145
+ const query = id.slice(queryIndex + 1).split("#", 1)[0];
146
+ if (!new URLSearchParams(query).has(markdownTemplateModuleQuery)) return;
147
+ return { path };
148
+ }
149
+ function renderMarkdownTemplateModule(template, sourceId, imports = {}) {
150
+ return [
151
+ `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
152
+ `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
153
+ `const vitehubMarkdownTemplateSourceId = ${JSON.stringify(sourceId)}`,
154
+ `const vitehubMarkdownTemplateImports = ${JSON.stringify(imports)}`,
155
+ "export default function render(data = {}) {",
156
+ " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data, sourceId: vitehubMarkdownTemplateSourceId, resolveImport: (specifier, importer) => vitehubMarkdownTemplateImports[`${importer}\\0${specifier}`] })",
157
+ "}",
158
+ ""
159
+ ].join("\n");
160
+ }
161
+ function hasViteRawQuery(path) {
162
+ const queryIndex = path.indexOf("?");
163
+ return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
164
+ }
165
+ async function resolveViteRawSpecifier(path, rootDir) {
166
+ if (path.startsWith("/@fs/")) return path.slice(5);
167
+ if (!rootDir || !path.startsWith("/")) return path;
168
+ const rootRelativePath = path.slice(1);
169
+ const publicPath = resolve(rootDir, "public", rootRelativePath);
170
+ try {
171
+ await stat(publicPath);
172
+ return publicPath;
173
+ } catch (error) {
174
+ if (error.code !== "ENOENT") throw error;
175
+ return resolve(rootDir, rootRelativePath);
176
+ }
177
+ }
178
+ function createViteRawPlugin(rootDir, frameworkRuntime) {
179
+ return {
180
+ name: "vitehub-vite-raw",
181
+ setup(build) {
182
+ build.onResolve({
183
+ filter: /^@vite-hub\/markdown-template$/,
184
+ namespace: viteMarkdownTemplateNamespace
185
+ }, async (args) => {
186
+ if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
187
+ return build.resolve("vite-hub/_internal/markdown-template", {
188
+ importer: args.importer,
189
+ kind: args.kind,
190
+ resolveDir: args.resolveDir
191
+ });
192
+ });
193
+ build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
194
+ if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
195
+ const markdownTemplate = parseMarkdownTemplateRequest(args.path);
196
+ const raw = hasViteRawQuery(args.path);
197
+ if (!markdownTemplate && !raw) return;
198
+ const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
199
+ const resolved = await build.resolve(specifier, {
200
+ importer: args.importer,
201
+ kind: args.kind,
202
+ namespace: args.namespace,
203
+ pluginData: markdownTemplate ? {
204
+ ...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
205
+ [skipMarkdownTemplateResolve]: true
206
+ } : args.pluginData,
207
+ resolveDir: args.resolveDir,
208
+ with: args.with
209
+ });
210
+ if (resolved.errors.length) return {
211
+ errors: resolved.errors,
212
+ warnings: resolved.warnings
213
+ };
214
+ if (resolved.external) return {
215
+ external: true,
216
+ namespace: resolved.namespace,
217
+ path: resolved.path,
218
+ pluginData: resolved.pluginData,
219
+ sideEffects: resolved.sideEffects,
220
+ suffix: resolved.suffix,
221
+ warnings: resolved.warnings
222
+ };
223
+ if (resolved.namespace !== "file") return {
224
+ 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.` }],
225
+ warnings: resolved.warnings
226
+ };
227
+ return {
228
+ namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
229
+ path: resolved.path,
230
+ pluginData: resolved.pluginData,
231
+ sideEffects: resolved.sideEffects,
232
+ suffix: resolved.suffix,
233
+ warnings: resolved.warnings
234
+ };
235
+ });
236
+ build.onLoad({
237
+ filter: /.*/,
238
+ namespace: viteRawNamespace
239
+ }, async (args) => ({
240
+ contents: await readFile(args.path),
241
+ loader: "text"
242
+ }));
243
+ build.onLoad({
244
+ filter: /.*/,
245
+ namespace: viteMarkdownTemplateNamespace
246
+ }, async (args) => ({
247
+ contents: await (async () => {
248
+ const template = await readFile(args.path, "utf8");
249
+ const imports = {};
250
+ const visited = new Set([args.path]);
251
+ const visit = async (source, importer) => {
252
+ for (const specifier of extractMarkdownTemplateImportSpecifiers(source)) {
253
+ const key = `${importer}\0${specifier}`;
254
+ if (imports[key]) continue;
255
+ const resolved = await build.resolve(specifier, {
256
+ importer,
257
+ kind: "import-statement",
258
+ pluginData: {
259
+ ...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
260
+ [skipMarkdownTemplateResolve]: true
261
+ },
262
+ resolveDir: dirname(importer)
263
+ });
264
+ if (resolved.errors.length) return Promise.reject(new Error(resolved.errors.map((error) => error.text).join("\n")));
265
+ 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.`);
266
+ const imported = {
267
+ id: resolved.path,
268
+ template: await readFile(resolved.path, "utf8")
269
+ };
270
+ imports[key] = imported;
271
+ if (!visited.has(imported.id)) {
272
+ visited.add(imported.id);
273
+ await visit(imported.template, imported.id);
274
+ }
275
+ }
276
+ };
277
+ await visit(template, args.path);
278
+ return renderMarkdownTemplateModule(template, args.path, imports);
279
+ })(),
280
+ loader: "js",
281
+ resolveDir: dirname(args.path)
282
+ }));
283
+ }
284
+ };
285
+ }
286
+ async function bundleEsmEntry(entryFile, outfile, options = {}) {
287
+ const format = options.format || "esm";
288
+ const platform = options.platform || "neutral";
289
+ const markdownTemplateRoot = options.rootDir && resolveViteHubProjectRoot(options.rootDir);
290
+ const aliases = resolveEsbuildAliases({
291
+ ...markdownTemplateRoot ? { [markdownTemplateRegistryId]: resolve(markdownTemplateRoot, markdownTemplateRegistryPath) } : {},
292
+ ...options.alias
293
+ });
294
+ const frameworkRuntime = Object.keys(aliases || {}).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
295
+ await build({
296
+ alias: aliases,
297
+ banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
298
+ "import { createRequire as __createRequire } from \"node:module\";",
299
+ "import { dirname as __vitehubDirname } from \"node:path\";",
300
+ "import { fileURLToPath as __vitehubFileURLToPath } from \"node:url\";",
301
+ "globalThis.require = __createRequire(import.meta.url);",
302
+ "globalThis.__filename = __vitehubFileURLToPath(import.meta.url);",
303
+ "globalThis.__dirname = __vitehubDirname(globalThis.__filename);"
304
+ ] : []].filter(Boolean).join("\n") } : void 0,
305
+ bundle: true,
306
+ conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
307
+ entryPoints: [entryFile],
308
+ external: options.external,
309
+ format,
310
+ logLevel: "silent",
311
+ mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
312
+ minifyIdentifiers: options.minifyIdentifiers,
313
+ outfile,
314
+ platform,
315
+ plugins: [...options.plugins ?? [], createViteRawPlugin(options.rootDir, frameworkRuntime)],
316
+ sourcemap: false,
317
+ target: "es2022",
318
+ write: true
319
+ });
320
+ }
321
+ //#endregion
322
+ //#region ../internal/src/build/vercel-config.ts
323
+ function createVercelConfigJson() {
324
+ return {
325
+ routes: [{ handle: "filesystem" }, {
326
+ src: "/(.*)",
327
+ dest: "/__server"
328
+ }],
329
+ version: 3
330
+ };
331
+ }
332
+ function createNodeFunctionConfig(extra = {}) {
333
+ return {
334
+ handler: "index.mjs",
335
+ launcherType: "Nodejs",
336
+ runtime: "nodejs22.x",
337
+ shouldAddHelpers: false,
338
+ supportsResponseStreaming: true,
339
+ ...extra
340
+ };
341
+ }
342
+ //#endregion
343
+ //#region ../internal/src/build/deployment-output.ts
344
+ function createDefaultVercelOutputRoot(rootDir) {
345
+ return resolve(rootDir, ".vercel", "output");
346
+ }
347
+ function createDefaultNetlifyOutputRoot(rootDir) {
348
+ return resolve(rootDir, ".netlify", "v1");
349
+ }
350
+ const VITEHUB_MODES = {
351
+ e2e: "e2e",
352
+ blob: "blob",
353
+ chat: "chat",
354
+ db: "db",
355
+ env: "env",
356
+ kv: "kv",
357
+ queue: "queue",
358
+ schedule: "schedule",
359
+ sandbox: "sandbox",
360
+ workspace: "workspace",
361
+ workflow: "workflow"
362
+ };
363
+ function isViteCli(argv) {
364
+ return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
365
+ }
366
+ function getViteCliMode(argv = process.argv) {
367
+ if (!isViteCli(argv)) return;
368
+ const modes = new Set(Object.values(VITEHUB_MODES));
369
+ for (let index = 0; index < argv.length; index += 1) {
370
+ const arg = argv[index];
371
+ const mode = arg === "--mode" || arg === "-m" ? argv[index + 1] : arg.startsWith("--mode=") ? arg.slice(7) : void 0;
372
+ if (mode && modes.has(mode)) return mode;
373
+ }
374
+ }
375
+ function getViteMode(env = process.env) {
376
+ return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
377
+ }
378
+ //#endregion
379
+ //#region src/integrations/vercel.ts
380
+ function getVercelSchedulePath(name) {
381
+ return `/api/vitehub/schedules/vercel/${name.replace(/[^a-z0-9/_-]+/gi, "_")}`;
382
+ }
383
+ //#endregion
384
+ //#region src/internal/provider-output.ts
385
+ const schedulePackageName = "@vite-hub/schedule";
386
+ const scheduleStaticRuntimeImport = "@vite-hub/schedule/runtime/static";
387
+ const productName = "schedule";
388
+ const cloudflareOutputStateFileName = "cloudflare-output.json";
389
+ const denoCronFileName = "deno-cron.mjs";
390
+ const generatedRegistryFileName = "registry.mjs";
391
+ function resolveScheduleRuntimeEntry(metaUrl = import.meta.url) {
392
+ const file = fileURLToPath(metaUrl);
393
+ const normalizedFile = file.replace(/\\/g, "/");
394
+ if (normalizedFile.endsWith("/src/internal/provider-output.ts")) return resolve(dirname(file), "../runtime/static.ts");
395
+ if (normalizedFile.endsWith("/dist/internal/provider-output.js")) return resolve(dirname(file), "../runtime/static.js");
396
+ return normalizedFile.includes("/dist/") ? resolve(dirname(file), "runtime/static.js") : resolve(dirname(file), "dist/runtime/static.js");
397
+ }
398
+ function resolveScheduleDefinitionEntry(metaUrl = import.meta.url) {
399
+ const file = fileURLToPath(metaUrl);
400
+ const normalizedFile = file.replace(/\\/g, "/");
401
+ if (normalizedFile.endsWith("/src/internal/provider-output.ts")) return resolve(dirname(file), "../definition.ts");
402
+ if (normalizedFile.endsWith("/dist/internal/provider-output.js")) return resolve(dirname(file), "../definition.js");
403
+ return normalizedFile.includes("/dist/") ? resolve(dirname(file), "definition.js") : resolve(dirname(file), "dist/definition.js");
404
+ }
405
+ const scheduleRuntimeEntry = resolveScheduleRuntimeEntry();
406
+ const scheduleDefinitionEntry = resolveScheduleDefinitionEntry();
407
+ function staticScheduleDefinitions(definitions) {
408
+ return definitions.filter((definition) => definition.runtimeOnly !== true);
409
+ }
410
+ async function removeEmptyDirectories(directory, rootDir) {
411
+ const root = resolve(rootDir);
412
+ let current = resolve(directory);
413
+ const pathFromRoot = relative(root, current);
414
+ if (!pathFromRoot || pathFromRoot.startsWith("..") || isAbsolute(pathFromRoot)) return;
415
+ while (current !== root) {
416
+ try {
417
+ await rmdir(current);
418
+ } catch (error) {
419
+ const code = error.code;
420
+ if (code === "ENOENT") {
421
+ current = dirname(current);
422
+ continue;
423
+ }
424
+ if (code === "ENOTEMPTY" || code === "EEXIST") return;
425
+ throw error;
426
+ }
427
+ current = dirname(current);
428
+ }
429
+ }
430
+ const cronFieldPattern = /^[*,/\-0-9]+$/;
431
+ function validateProviderCron(cron, scheduleName) {
432
+ const fields = cron.trim().split(/\s+/);
433
+ const hasVercelDayConflict = fields[2] !== "*" && fields[4] !== "*";
434
+ 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.`);
435
+ }
436
+ function readStaticScheduleCron(file, scheduleName) {
437
+ const definition = findDefaultExportCall(readFileSync(file, "utf8"), ["defineSchedule"]);
438
+ const cron = definition && readStaticString(readObjectProperty(definition.argument, "cron"));
439
+ if (!cron) throw new Error(`Schedule "${scheduleName}" must declare a static cron string for provider wake output.`);
440
+ return cron;
441
+ }
442
+ function readStaticString(source) {
443
+ if (!source || !/^["'`]/.test(source)) return;
444
+ const quote = source[0];
445
+ let value = "";
446
+ for (let index = 1; index < source.length; index++) if (source[index] === "\\") value += source[++index] || "";
447
+ else if (source[index] === quote) return source.slice(index + 1).trim() ? void 0 : value;
448
+ else value += source[index];
449
+ }
450
+ function renderProviderEntry(file, registryFile, provider, scheduleName) {
451
+ const runtimeImport = createImportPath(file, scheduleRuntimeEntry);
452
+ return [
453
+ `import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
454
+ `import { executeStaticSchedule } from ${JSON.stringify(runtimeImport)}`,
455
+ "",
456
+ "async function loadScheduleDefinition(name) {",
457
+ " const loader = scheduleRegistry[name]",
458
+ " if (!loader) return undefined",
459
+ " const loaded = await loader()",
460
+ " return loaded?.default ?? loaded",
461
+ "}",
462
+ "",
463
+ "async function runSchedule(name, cron, scheduledAt) {",
464
+ " const definition = await loadScheduleDefinition(name)",
465
+ " if (!definition) {",
466
+ " throw new Error(`Missing schedule definition: ${name}`)",
467
+ " }",
468
+ " return await executeStaticSchedule({ cron, definition, name, scheduledAt })",
469
+ "}",
470
+ "",
471
+ provider === "cloudflare" ? [
472
+ "export default {",
473
+ " async fetch() {",
474
+ " return new Response('ViteHub schedule provider wake endpoint')",
475
+ " },",
476
+ " async scheduled(event, env, ctx) {",
477
+ " const tasks = Object.entries(scheduleRegistry).map(async ([name]) => {",
478
+ " const definition = await loadScheduleDefinition(name)",
479
+ " if (!definition || definition.cron !== event.cron) return",
480
+ " await executeStaticSchedule({ cron: event.cron, definition, name, scheduledAt: new Date(event.scheduledTime), waitUntil: (promise) => ctx.waitUntil(promise) })",
481
+ " })",
482
+ " await Promise.all(tasks)",
483
+ " },",
484
+ "}"
485
+ ].join("\n") : [
486
+ "export default async function scheduleHandler(req, res) {",
487
+ " const cronSecret = process.env.CRON_SECRET",
488
+ " const authorization = req.headers?.authorization || req.headers?.Authorization",
489
+ " if (cronSecret && authorization !== `Bearer ${cronSecret}`) {",
490
+ " res.statusCode = 401",
491
+ " res.end('Unauthorized.')",
492
+ " return",
493
+ " }",
494
+ " const url = new URL(req.url || '/', 'https://vitehub.local')",
495
+ " const prefix = '/api/vitehub/schedules/vercel/'",
496
+ scheduleName === void 0 ? " const name = decodeURIComponent(url.pathname.startsWith(prefix) ? url.pathname.slice(prefix.length) : '')" : ` const name = ${JSON.stringify(scheduleName)}`,
497
+ " const definition = await loadScheduleDefinition(name)",
498
+ " if (!definition) {",
499
+ " res.statusCode = 404",
500
+ " res.end('Missing schedule definition.')",
501
+ " return",
502
+ " }",
503
+ " await runSchedule(name, definition.cron, new Date())",
504
+ " res.statusCode = 204",
505
+ " res.end()",
506
+ "}"
507
+ ].join("\n"),
508
+ ""
509
+ ].join("\n");
510
+ }
511
+ function renderNetlifyScheduleFunction(file, registryFile, scheduleName, cron) {
512
+ const runtimeImport = createImportPath(file, scheduleRuntimeEntry);
513
+ return [
514
+ `import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
515
+ `import { executeStaticSchedule } from ${JSON.stringify(runtimeImport)}`,
516
+ "",
517
+ `const scheduleName = ${JSON.stringify(scheduleName)}`,
518
+ "",
519
+ "export default async function netlifyScheduleHandler(request) {",
520
+ " const loaded = await scheduleRegistry[scheduleName]?.()",
521
+ " const definition = loaded?.default ?? loaded",
522
+ " if (!definition) return new Response('Missing schedule definition.', { status: 404 })",
523
+ ` await executeStaticSchedule({ cron: ${JSON.stringify(cron)}, definition, name: scheduleName, scheduledAt: new Date() })`,
524
+ " return new Response(null, { status: 204 })",
525
+ "}",
526
+ "",
527
+ "export const config = {",
528
+ ` schedule: ${JSON.stringify(cron)},`,
529
+ "}",
530
+ ""
531
+ ].join("\n");
532
+ }
533
+ function sanitizeNetlifyScheduleFunctionName(name) {
534
+ return `vitehub-schedule-${name.toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "schedule"}.mjs`;
535
+ }
536
+ function renderDenoCronEntry(file, registryFile, crons, runtimeImport = scheduleStaticRuntimeImport) {
537
+ const scheduleCrons = Object.fromEntries([...crons.entries()].sort(([left], [right]) => left.localeCompare(right)));
538
+ return [
539
+ `import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
540
+ `import { executeStaticSchedule } from ${JSON.stringify(runtimeImport)}`,
541
+ "",
542
+ `const scheduleCrons = ${JSON.stringify(scheduleCrons, null, 2)}`,
543
+ "",
544
+ "async function loadScheduleDefinition(name) {",
545
+ " const loader = scheduleRegistry[name]",
546
+ " if (!loader) return undefined",
547
+ " const loaded = await loader()",
548
+ " return loaded?.default ?? loaded",
549
+ "}",
550
+ "",
551
+ "for (const [name, cron] of Object.entries(scheduleCrons)) {",
552
+ " Deno.cron(`vitehub:${name}`, cron, async () => {",
553
+ " const definition = await loadScheduleDefinition(name)",
554
+ " if (!definition) {",
555
+ " throw new Error(`Missing schedule definition: ${name}`)",
556
+ " }",
557
+ " await executeStaticSchedule({ cron, definition, name, scheduledAt: new Date() })",
558
+ " })",
559
+ "}",
560
+ "",
561
+ "export const vitehubScheduleDefinitions = Object.keys(scheduleCrons)",
562
+ ""
563
+ ].join("\n");
564
+ }
565
+ function createScheduleDefinitionAliasPlugin() {
566
+ return {
567
+ name: "vitehub-schedule-definition-alias",
568
+ setup(build) {
569
+ build.onResolve({ filter: /^@vite-hub\/schedule$/ }, () => ({ path: scheduleDefinitionEntry }));
570
+ }
571
+ };
572
+ }
573
+ async function writeProviderEntries(rootDir, source, providedDefinitions) {
574
+ const generatedDir = ensureGeneratedDir(rootDir, productName);
575
+ await mkdir(generatedDir, { recursive: true });
576
+ const registryFile = resolve(generatedDir, generatedRegistryFileName);
577
+ const definitions = (providedDefinitions ?? discoverScheduleDefinitions({ rootDir })).filter((definition) => !source || definition.source === source).filter((definition) => definition.runtimeOnly !== true);
578
+ await writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions), "utf8");
579
+ const cloudflareWorkerFile = resolve(generatedDir, "cloudflare-worker.mjs");
580
+ const denoCronFile = resolve(generatedDir, denoCronFileName);
581
+ const vercelServerFile = resolve(generatedDir, "vercel-server.mjs");
582
+ await writeFile(cloudflareWorkerFile, renderProviderEntry(cloudflareWorkerFile, registryFile, "cloudflare"), "utf8");
583
+ await writeFile(vercelServerFile, renderProviderEntry(vercelServerFile, registryFile, "vercel"), "utf8");
584
+ return {
585
+ cloudflareWorkerFile,
586
+ denoCronFile,
587
+ definitions,
588
+ generatedDir,
589
+ registryFile,
590
+ vercelServerFile
591
+ };
592
+ }
593
+ async function readDefinitionCrons(definitions) {
594
+ const crons = /* @__PURE__ */ new Map();
595
+ for (const definition of staticScheduleDefinitions(definitions)) {
596
+ const cron = readStaticScheduleCron(definition.handler, definition.name);
597
+ validateProviderCron(cron, definition.name);
598
+ crons.set(definition.name, cron);
599
+ }
600
+ return crons;
601
+ }
602
+ async function writeVercelScheduleFunctions(options, crons) {
603
+ const definitions = staticScheduleDefinitions(options.definitions);
604
+ const outputRoot = options.outputRoot;
605
+ const functionRoot = resolve(outputRoot, "functions", "api", "vitehub", "schedules", "vercel");
606
+ await rm(functionRoot, {
607
+ force: true,
608
+ recursive: true
609
+ });
610
+ const emittedFunctionNames = /* @__PURE__ */ new Map();
611
+ for (const definition of definitions) {
612
+ const safeName = definition.name.replace(/[^a-z0-9/_-]+/gi, "_").split("/").filter(Boolean).join("/");
613
+ const existingName = emittedFunctionNames.get(safeName);
614
+ if (existingName) throw new Error(`Schedule "${definition.name}" and "${existingName}" both emit the same Vercel function path: ${safeName}`);
615
+ emittedFunctionNames.set(safeName, definition.name);
616
+ const segments = safeName.split("/");
617
+ const functionDir = resolve(functionRoot, ...segments.slice(0, -1), `${segments.at(-1)}.func`);
618
+ const functionFile = resolve(functionDir, "index.mjs");
619
+ const wrapperFile = resolve(functionDir, "index.source.mjs");
620
+ await mkdir(functionDir, { recursive: true });
621
+ await writeFile(wrapperFile, renderProviderEntry(wrapperFile, options.registryFile, "vercel", definition.name), "utf8");
622
+ await bundleEsmEntry(wrapperFile, functionFile, {
623
+ alias: options.bundleAlias,
624
+ format: "esm",
625
+ platform: "node",
626
+ plugins: [createScheduleDefinitionAliasPlugin()],
627
+ rootDir: options.rootDir
628
+ });
629
+ await rm(wrapperFile, { force: true });
630
+ await writeFile(resolve(functionDir, ".vc-config.json"), `${JSON.stringify(createNodeFunctionConfig(), null, 2)}\n`, "utf8");
631
+ }
632
+ const configFile = resolve(outputRoot, "config.json");
633
+ let vercelConfig;
634
+ try {
635
+ vercelConfig = JSON.parse(await readFile(configFile, "utf8"));
636
+ } catch (error) {
637
+ if (error.code !== "ENOENT") throw error;
638
+ if (!definitions.length) {
639
+ await removeEmptyDirectories(functionRoot, options.rootDir);
640
+ return;
641
+ }
642
+ vercelConfig = createVercelConfigJson();
643
+ }
644
+ const schedulePathPrefix = "/api/vitehub/schedules/vercel/";
645
+ const previousCrons = vercelConfig.crons ?? [];
646
+ const existingCrons = previousCrons.filter((cron) => !cron.path.startsWith(schedulePathPrefix));
647
+ if (!definitions.length && existingCrons.length === previousCrons.length) {
648
+ await removeEmptyDirectories(functionRoot, options.rootDir);
649
+ if (previousCrons.length === 0) {
650
+ delete vercelConfig.crons;
651
+ if (isDeepStrictEqual(vercelConfig, createVercelConfigJson())) {
652
+ const outputFiles = await readdir(outputRoot);
653
+ if (outputFiles.length === 1 && outputFiles[0] === "config.json") {
654
+ await rm(configFile, { force: true });
655
+ await removeEmptyDirectories(outputRoot, options.rootDir);
656
+ }
657
+ }
658
+ }
659
+ return;
660
+ }
661
+ const nextCrons = [...existingCrons, ...definitions.map((definition) => ({
662
+ path: getVercelSchedulePath(definition.name),
663
+ schedule: crons.get(definition.name)
664
+ }))];
665
+ if (nextCrons.length) vercelConfig.crons = nextCrons;
666
+ else delete vercelConfig.crons;
667
+ if (!definitions.length) {
668
+ await removeEmptyDirectories(functionRoot, options.rootDir);
669
+ const outputFiles = await readdir(outputRoot);
670
+ if (outputFiles.length === 1 && outputFiles[0] === "config.json" && isDeepStrictEqual(vercelConfig, createVercelConfigJson())) {
671
+ await rm(configFile, { force: true });
672
+ await removeEmptyDirectories(outputRoot, options.rootDir);
673
+ return;
674
+ }
675
+ }
676
+ await writeFile(configFile, `${JSON.stringify(vercelConfig, null, 2)}\n`, "utf8");
677
+ }
678
+ async function createNetlifyScheduleFunctionOutputs(options) {
679
+ const definitions = staticScheduleDefinitions(options.definitions);
680
+ const crons = await readDefinitionCrons(definitions);
681
+ const emitted = /* @__PURE__ */ new Map();
682
+ return definitions.map((definition) => {
683
+ const fileName = sanitizeNetlifyScheduleFunctionName(definition.name);
684
+ const existingName = emitted.get(fileName);
685
+ if (existingName) throw new Error(`Schedule "${definition.name}" and "${existingName}" both emit the same Netlify function file: ${fileName}`);
686
+ emitted.set(fileName, definition.name);
687
+ const file = resolve(options.functionRoot, fileName);
688
+ return {
689
+ cron: crons.get(definition.name),
690
+ file,
691
+ name: definition.name,
692
+ source: renderNetlifyScheduleFunction(file, options.registryFile, definition.name, crons.get(definition.name))
693
+ };
694
+ });
695
+ }
696
+ async function writeNetlifyScheduleFunctions(options) {
697
+ const functionRoot = resolve(options.outputRoot, "functions");
698
+ const existingFiles = await readdir(functionRoot).catch((error) => {
699
+ if (error.code === "ENOENT") return [];
700
+ throw error;
701
+ });
702
+ await Promise.all(existingFiles.filter((file) => /^vitehub-schedule-.+\.mjs$/.test(file)).map((file) => rm(resolve(functionRoot, file), {
703
+ force: true,
704
+ recursive: true
705
+ })));
706
+ const outputs = await createNetlifyScheduleFunctionOutputs({
707
+ definitions: options.definitions,
708
+ functionRoot,
709
+ registryFile: options.registryFile
710
+ });
711
+ if (outputs.length === 0) {
712
+ await removeEmptyDirectories(functionRoot, options.rootDir);
713
+ return;
714
+ }
715
+ await mkdir(functionRoot, { recursive: true });
716
+ await Promise.all(outputs.map(async (output) => writeFile(output.file, output.source, "utf8")));
717
+ }
718
+ async function writeCloudflareScheduleOutput(options) {
719
+ const outputRoot = createDefaultCloudflareOutputRoot(options.rootDir);
720
+ await mkdir(outputRoot, { recursive: true });
721
+ const configFile = resolve(outputRoot, "wrangler.json");
722
+ let wranglerConfig = {};
723
+ try {
724
+ wranglerConfig = JSON.parse(await readFile(configFile, "utf8"));
725
+ } catch (error) {
726
+ if (error.code !== "ENOENT") throw error;
727
+ }
728
+ const existingTriggers = typeof wranglerConfig.triggers === "object" && wranglerConfig.triggers !== null ? wranglerConfig.triggers : {};
729
+ const previousState = await readCloudflareOutputState(options.stateFile);
730
+ const externalCrons = (existingTriggers.crons ?? []).filter((cron) => !previousState?.crons.includes(cron));
731
+ const ownedCrons = options.crons.filter((cron) => !externalCrons.includes(cron));
732
+ const main = typeof wranglerConfig.main === "string" && wranglerConfig.main ? wranglerConfig.main : "index.js";
733
+ wranglerConfig = {
734
+ ...wranglerConfig,
735
+ compatibility_date: wranglerConfig.compatibility_date ?? "2026-04-20",
736
+ compatibility_flags: wranglerConfig.compatibility_flags ?? ["nodejs_compat"],
737
+ main,
738
+ observability: wranglerConfig.observability ?? { enabled: true },
739
+ triggers: {
740
+ ...existingTriggers,
741
+ crons: [...new Set([...externalCrons, ...options.crons])]
742
+ }
743
+ };
744
+ await Promise.all([
745
+ bundleEsmEntry(options.bundleEntry, resolve(outputRoot, main), {
746
+ alias: options.bundleAlias,
747
+ conditions: [
748
+ "workerd",
749
+ "worker",
750
+ "browser",
751
+ "default"
752
+ ],
753
+ format: "esm",
754
+ platform: "neutral",
755
+ plugins: [createScheduleDefinitionAliasPlugin()],
756
+ rootDir: options.rootDir
757
+ }),
758
+ writeFile(configFile, `${JSON.stringify(wranglerConfig, null, 2)}\n`, "utf8"),
759
+ writeFile(options.stateFile, `${JSON.stringify({
760
+ crons: ownedCrons,
761
+ main
762
+ }, null, 2)}\n`, "utf8")
763
+ ]);
764
+ }
765
+ async function readCloudflareOutputState(file) {
766
+ let source;
767
+ try {
768
+ source = await readFile(file, "utf8");
769
+ } catch (error) {
770
+ if (error.code === "ENOENT") return;
771
+ throw error;
772
+ }
773
+ try {
774
+ const state = JSON.parse(source);
775
+ if (!Array.isArray(state.crons) || state.crons.some((cron) => typeof cron !== "string") || typeof state.main !== "string" || !state.main) return;
776
+ return {
777
+ crons: state.crons,
778
+ main: state.main
779
+ };
780
+ } catch {
781
+ return;
782
+ }
783
+ }
784
+ async function cleanCloudflareScheduleOutput(rootDir, stateFile) {
785
+ const state = await readCloudflareOutputState(stateFile);
786
+ if (!state) return;
787
+ const outputRoot = createDefaultCloudflareOutputRoot(rootDir);
788
+ const configFile = resolve(outputRoot, "wrangler.json");
789
+ let configSource;
790
+ try {
791
+ configSource = await readFile(configFile, "utf8");
792
+ } catch (error) {
793
+ if (error.code !== "ENOENT") throw error;
794
+ }
795
+ if (configSource !== void 0) {
796
+ const config = JSON.parse(configSource);
797
+ const triggers = typeof config.triggers === "object" && config.triggers !== null ? config.triggers : void 0;
798
+ const crons = Array.isArray(triggers?.crons) ? triggers.crons.filter((cron) => typeof cron === "string" && !state.crons.includes(cron)) : [];
799
+ if (triggers) config.triggers = {
800
+ ...triggers,
801
+ crons
802
+ };
803
+ await writeFile(configFile, `${JSON.stringify(config, null, 2)}\n`, "utf8");
804
+ }
805
+ await Promise.all([rm(resolve(outputRoot, state.main), { force: true }), rm(stateFile, { force: true })]);
806
+ }
807
+ async function generateProviderOutputs(options) {
808
+ const cloudflareStateFile = resolve(ensureGeneratedDir(options.rootDir, productName), cloudflareOutputStateFileName);
809
+ const artifacts = await writeProviderEntries(options.rootDir, options.source, options.definitions);
810
+ const crons = await readDefinitionCrons(artifacts.definitions);
811
+ if (artifacts.definitions.length > 0) {
812
+ await writeFile(artifacts.denoCronFile, renderDenoCronEntry(artifacts.denoCronFile, artifacts.registryFile, crons, options.runtimeImport), "utf8");
813
+ await writeCloudflareScheduleOutput({
814
+ bundleAlias: options.bundleAlias,
815
+ bundleEntry: artifacts.cloudflareWorkerFile,
816
+ crons: [...new Set(crons.values())],
817
+ rootDir: options.rootDir,
818
+ stateFile: cloudflareStateFile
819
+ });
820
+ } else await Promise.all([
821
+ rm(artifacts.cloudflareWorkerFile, { force: true }),
822
+ rm(artifacts.denoCronFile, { force: true }),
823
+ rm(artifacts.registryFile, { force: true }),
824
+ rm(artifacts.vercelServerFile, { force: true }),
825
+ cleanCloudflareScheduleOutput(options.rootDir, cloudflareStateFile)
826
+ ]);
827
+ await writeVercelScheduleFunctions({
828
+ bundleAlias: options.bundleAlias,
829
+ definitions: artifacts.definitions,
830
+ outputRoot: createDefaultVercelOutputRoot(options.rootDir),
831
+ registryFile: artifacts.registryFile,
832
+ rootDir: options.rootDir
833
+ }, crons);
834
+ await writeNetlifyScheduleFunctions({
835
+ definitions: artifacts.definitions,
836
+ outputRoot: createDefaultNetlifyOutputRoot(options.rootDir),
837
+ registryFile: artifacts.registryFile,
838
+ rootDir: options.rootDir
839
+ });
840
+ return artifacts;
841
+ }
842
+ //#endregion
843
+ //#region src/targets-module.ts
844
+ const SCHEDULE_TARGETS_ID = "#vitehub/schedule/targets";
845
+ function getScheduleTargetNames(definitions) {
846
+ return definitions.filter((definition) => definition.allowRuntimeSchedules).map((definition) => definition.name).sort();
847
+ }
848
+ function createScheduleTargetsContents(definitions, options = {}) {
849
+ const targets = getScheduleTargetNames(definitions);
850
+ const union = targets.length ? targets.map((target) => JSON.stringify(target)).join(" | ") : "never";
851
+ return [
852
+ `export const scheduleTargetNames = ${JSON.stringify(targets)};`,
853
+ options.types ? `export type ScheduleTargetName = ${union};` : "",
854
+ ""
855
+ ].filter((line) => line !== "").join("\n");
856
+ }
857
+ //#endregion
858
+ //#region src/vite.ts
859
+ const SCHEDULE_VITE_PLUGIN_NAME = "@vite-hub/schedule/vite";
860
+ const SCHEDULE_REGISTRY_ID = "#vitehub/schedule/registry";
861
+ const RESOLVED_SCHEDULE_REGISTRY_ID = "\0#vitehub/schedule/registry";
862
+ const RESOLVED_SCHEDULE_TARGETS_ID = `\0${SCHEDULE_TARGETS_ID}`;
863
+ const registryImportAnchor = ".vitehub/schedule/registry.js";
864
+ const generatedNitroSchedulePlugin = ".vitehub/nitro/schedule/plugin.ts";
865
+ const generatedNitroRuntimeRegistry = ".vitehub/nitro/schedule/runtime-registry.js";
866
+ const generatedNitroStaticRegistry = ".vitehub/nitro/schedule/static-registry.js";
867
+ const generatedNitroCloudflareModule = "./.vitehub/nitro/schedule/module.ts";
868
+ const mergeNoExternal = createNoExternalMerger(schedulePackageName);
869
+ function resolveSchedulePluginRoots(root, options = {}) {
870
+ const resolvedViteRoot = resolve(root);
871
+ return {
872
+ projectRoot: resolveViteHubProjectRoot(resolvedViteRoot, { projectRoot: options.projectRoot }),
873
+ viteRoot: resolvedViteRoot
874
+ };
875
+ }
876
+ function isRecord(value) {
877
+ return typeof value === "object" && value !== null;
878
+ }
879
+ function resolveProcessRuntimeOptions(value) {
880
+ if (value === void 0) return;
881
+ if (!isRecord(value) || value.driver !== "process") throw new TypeError("Schedule Process Runtime driver must be \"process\".");
882
+ if (value.prefix !== void 0 && typeof value.prefix !== "string") throw new TypeError("Schedule Process Runtime prefix must be a string.");
883
+ 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.");
884
+ 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.");
885
+ return {
886
+ ...value.concurrency !== void 0 ? { concurrency: value.concurrency } : {},
887
+ driver: "process",
888
+ ...value.intervalMs !== void 0 ? { intervalMs: value.intervalMs } : {},
889
+ ...value.prefix !== void 0 ? { prefix: value.prefix } : {}
890
+ };
891
+ }
892
+ function resolveStringAliases(config) {
893
+ const aliases = {};
894
+ for (const alias of config.resolve.alias) if (typeof alias.find === "string" && typeof alias.replacement === "string") aliases[alias.find] = alias.replacement;
895
+ return aliases;
896
+ }
897
+ function moduleImportSpecifier(fromFile, targetFile) {
898
+ const specifier = relative(dirname(fromFile), targetFile).replace(/\\/g, "/");
899
+ return specifier.startsWith(".") ? specifier : `./${specifier}`;
900
+ }
901
+ function cloneNitroConfig(value) {
902
+ const nitro = isRecord(value) ? { ...value } : {};
903
+ if (Array.isArray(nitro.plugins)) nitro.plugins = [...nitro.plugins];
904
+ if (isRecord(nitro.cloudflare)) {
905
+ const cloudflare = { ...nitro.cloudflare };
906
+ if (isRecord(cloudflare.wrangler)) {
907
+ const wrangler = { ...cloudflare.wrangler };
908
+ if (isRecord(wrangler.triggers)) {
909
+ const triggers = { ...wrangler.triggers };
910
+ if (Array.isArray(triggers.crons)) triggers.crons = triggers.crons.filter((cron) => typeof cron === "string");
911
+ wrangler.triggers = triggers;
912
+ }
913
+ cloudflare.wrangler = wrangler;
914
+ }
915
+ nitro.cloudflare = cloudflare;
916
+ }
917
+ return nitro;
918
+ }
919
+ function mergeNitroScheduleConfig(value, options) {
920
+ const nitro = cloneNitroConfig(value);
921
+ nitro.plugins = Array.isArray(nitro.plugins) && nitro.plugins.includes(options.plugin) ? nitro.plugins : [...Array.isArray(nitro.plugins) ? nitro.plugins : [], options.plugin];
922
+ if (!options.providerWake) return nitro;
923
+ nitro.modules = Array.isArray(nitro.modules) && nitro.modules.includes(generatedNitroCloudflareModule) ? nitro.modules : [...Array.isArray(nitro.modules) ? nitro.modules : [], generatedNitroCloudflareModule];
924
+ nitro.cloudflare ||= {};
925
+ nitro.cloudflare.wrangler ||= {};
926
+ const wrangler = nitro.cloudflare.wrangler;
927
+ const existingTriggers = isRecord(wrangler.triggers) ? wrangler.triggers : {};
928
+ const existingCrons = Array.isArray(existingTriggers.crons) ? existingTriggers.crons.filter((cron) => typeof cron === "string") : [];
929
+ wrangler.triggers = {
930
+ ...existingTriggers,
931
+ crons: [...new Set([...existingCrons, ...options.crons])]
932
+ };
933
+ return nitro;
934
+ }
935
+ function renderNitroSchedulePlugin(options) {
936
+ const importBase = options.importBase ?? "@vite-hub/schedule";
937
+ const providerWake = options.providerDefinitions.length > 0;
938
+ const processRuntime = options.processRuntime;
939
+ const processDriverOptions = processRuntime ? {
940
+ ...processRuntime.concurrency !== void 0 ? { concurrency: processRuntime.concurrency } : {},
941
+ ...processRuntime.intervalMs !== void 0 ? { intervalMs: processRuntime.intervalMs } : {}
942
+ } : void 0;
943
+ const scheduleStoreOptions = processRuntime?.prefix !== void 0 ? { prefix: processRuntime.prefix } : {};
944
+ return [
945
+ "import { definePlugin } from 'nitro'",
946
+ ...providerWake ? [`import scheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.providerRegistryFile))}`, `import { executeCloudflareStaticSchedules } from ${JSON.stringify(options.runtimeImport ?? `${importBase}/runtime/static`)}`] : [],
947
+ ...processRuntime ? [
948
+ `import { createKVRuntimeScheduleStore, createKVScheduleRunStore } from ${JSON.stringify(importBase)}`,
949
+ `import { installScheduleRuntime } from ${JSON.stringify(`${importBase}/runtime/driver`)}`,
950
+ `import { createProcessScheduleWakeDriver } from ${JSON.stringify(`${importBase}/runtime/process`)}`,
951
+ `import runtimeScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.runtimeRegistryFile))}`,
952
+ `import staticScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.staticRegistryFile))}`
953
+ ] : [],
954
+ "",
955
+ ...processRuntime ? [
956
+ `const processDriverOptions = ${JSON.stringify(processDriverOptions, null, 2)}`,
957
+ `const scheduleStoreOptions = ${JSON.stringify(scheduleStoreOptions, null, 2)}`,
958
+ ""
959
+ ] : [],
960
+ "export default definePlugin((nitroApp) => {",
961
+ ...providerWake ? [
962
+ " nitroApp.hooks.hook('cloudflare:scheduled', async (event) => {",
963
+ " await executeCloudflareStaticSchedules(event, { registry: scheduleRegistry })",
964
+ " })"
965
+ ] : [],
966
+ ...processRuntime ? [
967
+ " function captureRuntimeError(error: unknown) {",
968
+ " let runtimeError: Error",
969
+ " try {",
970
+ " runtimeError = error instanceof Error ? error : new Error(String(error))",
971
+ " }",
972
+ " catch {",
973
+ " return",
974
+ " }",
975
+ " try {",
976
+ " console.error('[vitehub:schedule]', runtimeError)",
977
+ " }",
978
+ " catch {}",
979
+ " try {",
980
+ " nitroApp.captureError?.(runtimeError, { tags: ['vitehub-schedule'] })",
981
+ " }",
982
+ " catch {}",
983
+ " }",
984
+ " const runtimeInstallation = installScheduleRuntime({",
985
+ " createDriver: createProcessScheduleWakeDriver(processDriverOptions),",
986
+ " onError: captureRuntimeError,",
987
+ " registry: runtimeScheduleRegistry,",
988
+ " runtimeScheduleStore: createKVRuntimeScheduleStore(scheduleStoreOptions),",
989
+ " scheduleRunStore: createKVScheduleRunStore(scheduleStoreOptions),",
990
+ " staticRegistry: staticScheduleRegistry,",
991
+ " }).then(",
992
+ " controller => ({ controller }),",
993
+ " error => {",
994
+ " captureRuntimeError(error)",
995
+ " return { error }",
996
+ " },",
997
+ " )",
998
+ " nitroApp.hooks.hook('request', async () => {",
999
+ " const result = await runtimeInstallation",
1000
+ " if ('error' in result) throw result.error",
1001
+ " })",
1002
+ " nitroApp.hooks.hook('close', async () => {",
1003
+ " const result = await runtimeInstallation",
1004
+ " if ('controller' in result) await result.controller.close()",
1005
+ " })"
1006
+ ] : [],
1007
+ "})",
1008
+ "",
1009
+ `export const vitehubScheduleDefinitions = ${JSON.stringify(options.providerDefinitions.map((definition) => definition.name))}`,
1010
+ ""
1011
+ ].join("\n");
1012
+ }
1013
+ function renderNitroCloudflareModule(crons) {
1014
+ return [
1015
+ "import type { Nitro } from 'nitro/types'",
1016
+ "",
1017
+ `const crons = ${JSON.stringify(crons)}`,
1018
+ "",
1019
+ "function dedupeCloudflareCrons(nitro: Nitro): void {",
1020
+ " const wrangler = nitro.options.cloudflare?.wrangler",
1021
+ " if (!wrangler?.triggers || !Array.isArray(wrangler.triggers.crons)) return",
1022
+ " wrangler.triggers.crons = [...new Set(wrangler.triggers.crons.filter((cron): cron is string => typeof cron === 'string'))]",
1023
+ "}",
1024
+ "",
1025
+ "export default function vitehubScheduleModule(nitro: Nitro): void {",
1026
+ " nitro.options.cloudflare ??= {}",
1027
+ " nitro.options.cloudflare.wrangler ??= {}",
1028
+ " nitro.options.cloudflare.wrangler.triggers ??= {}",
1029
+ " const existingCrons = Array.isArray(nitro.options.cloudflare.wrangler.triggers.crons) ? nitro.options.cloudflare.wrangler.triggers.crons : []",
1030
+ " nitro.options.cloudflare.wrangler.triggers.crons = [...new Set([...existingCrons, ...crons])]",
1031
+ " nitro.hooks.hook('build:before', dedupeCloudflareCrons)",
1032
+ "}",
1033
+ ""
1034
+ ].join("\n");
1035
+ }
1036
+ function renderScheduleRegistryTypes(importBase = schedulePackageName) {
1037
+ return [
1038
+ `import type { ScheduleRegistryDefinition } from ${JSON.stringify(importBase)}`,
1039
+ "",
1040
+ "declare const registry: Record<string, () => Promise<ScheduleRegistryDefinition | { default?: ScheduleRegistryDefinition }>>",
1041
+ "export default registry",
1042
+ ""
1043
+ ].join("\n");
1044
+ }
1045
+ async function writeNitroSchedulePlugin(root, options) {
1046
+ const pluginFile = resolve(root, generatedNitroSchedulePlugin);
1047
+ const moduleFile = resolve(root, generatedNitroCloudflareModule);
1048
+ const providerRegistryFile = resolve(root, registryImportAnchor);
1049
+ const runtimeRegistryFile = resolve(root, generatedNitroRuntimeRegistry);
1050
+ const staticRegistryFile = resolve(root, generatedNitroStaticRegistry);
1051
+ await mkdir(dirname(pluginFile), { recursive: true });
1052
+ const writes = [writeFile(pluginFile, renderNitroSchedulePlugin({
1053
+ importBase: options.importBase,
1054
+ pluginFile,
1055
+ processRuntime: options.processRuntime,
1056
+ providerDefinitions: options.providerDefinitions,
1057
+ providerRegistryFile,
1058
+ runtimeRegistryFile,
1059
+ staticRegistryFile,
1060
+ runtimeImport: options.runtimeImport
1061
+ }), "utf8")];
1062
+ if (options.processRuntime) {
1063
+ writes.push(writeFile(runtimeRegistryFile, createRuntimeRegistryContents(runtimeRegistryFile, options.runtimeDefinitions), "utf8"));
1064
+ writes.push(writeFile(runtimeRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase), "utf8"));
1065
+ writes.push(writeFile(staticRegistryFile, createRuntimeRegistryContents(staticRegistryFile, options.staticDefinitions), "utf8"));
1066
+ writes.push(writeFile(staticRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase), "utf8"));
1067
+ }
1068
+ if (options.providerDefinitions.length > 0) {
1069
+ await mkdir(dirname(providerRegistryFile), { recursive: true });
1070
+ writes.push(writeFile(providerRegistryFile, createRuntimeRegistryContents(providerRegistryFile, options.providerDefinitions), "utf8"));
1071
+ writes.push(writeFile(providerRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase), "utf8"));
1072
+ writes.push(writeFile(moduleFile, renderNitroCloudflareModule(options.crons), "utf8"));
1073
+ }
1074
+ await Promise.all(writes);
1075
+ return generatedNitroSchedulePlugin;
1076
+ }
1077
+ function hasServerScheduleDefinitions(definitions) {
1078
+ return definitions.some((definition) => definition.runtimeOnly !== true && definition.source === "server-schedules");
1079
+ }
1080
+ function hasViteSuffixScheduleDefinitions(definitions) {
1081
+ return definitions.some((definition) => definition.runtimeOnly !== true && definition.source === "vite-suffix");
1082
+ }
1083
+ function selectNitroScheduleDefinitions(definitions, options) {
1084
+ if (options.providerOutput === false || options.providerOutput === "standalone") return [];
1085
+ const staticDefinitions = definitions.filter((definition) => definition.runtimeOnly !== true);
1086
+ if (options.providerOutput === "nitro") return staticDefinitions;
1087
+ return staticDefinitions.filter((definition) => definition.source === "server-schedules");
1088
+ }
1089
+ function selectStandaloneProviderSource(definitions, options) {
1090
+ if (options.providerOutput === "auto" || options.providerOutput === void 0) return hasServerScheduleDefinitions(definitions) ? "vite-suffix" : void 0;
1091
+ }
1092
+ function shouldInstallNitroSchedulePlugin(definitions, options) {
1093
+ return selectNitroScheduleDefinitions(definitions, options).length > 0 || options.runtime !== void 0;
1094
+ }
1095
+ function shouldEmitStandaloneProviderOutput(definitions, options) {
1096
+ if (options.providerOutput === false || options.providerOutput === "nitro") return false;
1097
+ if (options.providerOutput === "standalone") return definitions.some((definition) => definition.runtimeOnly !== true);
1098
+ if (hasServerScheduleDefinitions(definitions)) return hasViteSuffixScheduleDefinitions(definitions);
1099
+ return definitions.some((definition) => definition.runtimeOnly !== true);
1100
+ }
1101
+ async function createScheduleNitroConfig(options = {}) {
1102
+ const processRuntime = resolveProcessRuntimeOptions(options.runtime);
1103
+ const roots = resolveSchedulePluginRoots(options.root || process.cwd(), options);
1104
+ const definitions = discoverScheduleDefinitions({
1105
+ rootDir: roots.viteRoot,
1106
+ serverRootDir: roots.projectRoot
1107
+ });
1108
+ if (!shouldInstallNitroSchedulePlugin(definitions, options)) return null;
1109
+ const nitroDefinitions = processRuntime && options.providerOutput !== "nitro" ? [] : selectNitroScheduleDefinitions(definitions, options);
1110
+ const crons = options.command === "build" ? [...new Set((await readDefinitionCrons(nitroDefinitions)).values())] : [];
1111
+ const nitroDefinitionNames = new Set(nitroDefinitions.map((definition) => definition.name));
1112
+ const plugin = await writeNitroSchedulePlugin(roots.projectRoot, {
1113
+ crons,
1114
+ importBase: options.importBase,
1115
+ processRuntime,
1116
+ providerDefinitions: nitroDefinitions,
1117
+ runtimeDefinitions: definitions,
1118
+ staticDefinitions: definitions.filter((definition) => definition.runtimeOnly !== true && !nitroDefinitionNames.has(definition.name) && !(processRuntime && options.providerOutput === "standalone")),
1119
+ runtimeImport: options.runtimeImport
1120
+ });
1121
+ return mergeNitroScheduleConfig(options.nitro, {
1122
+ crons,
1123
+ plugin,
1124
+ providerWake: nitroDefinitions.length > 0
1125
+ });
1126
+ }
1127
+ function hubSchedule(options = {}) {
1128
+ const internalOptions = options;
1129
+ let resolved;
1130
+ let emitStandaloneProviderOutput = true;
1131
+ let projectRoot;
1132
+ let standaloneProviderSource;
1133
+ let viteRoot;
1134
+ function discoverViteSchedules() {
1135
+ if (!projectRoot || !viteRoot) return [];
1136
+ return discoverScheduleDefinitions({
1137
+ mode: "vite-suffix",
1138
+ rootDir: viteRoot,
1139
+ serverRootDir: projectRoot
1140
+ });
1141
+ }
1142
+ function discoverRegistrySchedules() {
1143
+ if (!projectRoot || !viteRoot) return [];
1144
+ return discoverScheduleDefinitions({
1145
+ rootDir: viteRoot,
1146
+ serverRootDir: projectRoot
1147
+ });
1148
+ }
1149
+ function createRegistryContents() {
1150
+ const definitions = discoverRegistrySchedules();
1151
+ return createRuntimeRegistryContents(projectRoot ? resolve(projectRoot, registryImportAnchor) : registryImportAnchor, definitions);
1152
+ }
1153
+ function createTargetsContents() {
1154
+ return createScheduleTargetsContents(discoverViteSchedules(), { types: false });
1155
+ }
1156
+ return {
1157
+ name: SCHEDULE_VITE_PLUGIN_NAME,
1158
+ enforce: "pre",
1159
+ async config(config, env) {
1160
+ const roots = resolveSchedulePluginRoots(config.root || process.cwd(), options);
1161
+ const definitions = discoverScheduleDefinitions({
1162
+ rootDir: roots.viteRoot,
1163
+ serverRootDir: roots.projectRoot
1164
+ });
1165
+ emitStandaloneProviderOutput = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options);
1166
+ standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
1167
+ if (!shouldInstallNitroSchedulePlugin(definitions, options)) return null;
1168
+ const nitro = await createScheduleNitroConfig({
1169
+ ...options,
1170
+ command: env.command,
1171
+ nitro: config.nitro,
1172
+ root: config.root || process.cwd()
1173
+ });
1174
+ if (!nitro) return null;
1175
+ config.nitro = nitro;
1176
+ return { nitro };
1177
+ },
1178
+ configResolved(config) {
1179
+ resolved = config;
1180
+ const roots = resolveSchedulePluginRoots(config.root, options);
1181
+ projectRoot = roots.projectRoot;
1182
+ viteRoot = roots.viteRoot;
1183
+ },
1184
+ configEnvironment(name, config) {
1185
+ if (!isServerEnvironment(name, config)) return;
1186
+ return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
1187
+ },
1188
+ handleHotUpdate(context) {
1189
+ const file = normalize(context.file).replace(/\\/g, "/");
1190
+ if (!/\.schedule\.(?:c|m)?[jt]s$/i.test(file) && !/\/server\/schedules\/.*\.(?:c|m)?[jt]s$/i.test(file)) return;
1191
+ const registryModule = context.server.moduleGraph.getModuleById(RESOLVED_SCHEDULE_REGISTRY_ID);
1192
+ if (registryModule) context.server.moduleGraph.invalidateModule(registryModule);
1193
+ const targetsModule = context.server.moduleGraph.getModuleById(RESOLVED_SCHEDULE_TARGETS_ID);
1194
+ if (targetsModule) context.server.moduleGraph.invalidateModule(targetsModule);
1195
+ },
1196
+ resolveId(id) {
1197
+ if (id === SCHEDULE_REGISTRY_ID) return RESOLVED_SCHEDULE_REGISTRY_ID;
1198
+ if (id === "#vitehub/schedule/targets") return RESOLVED_SCHEDULE_TARGETS_ID;
1199
+ },
1200
+ load(id) {
1201
+ if (id === RESOLVED_SCHEDULE_REGISTRY_ID) return createRegistryContents();
1202
+ if (id === RESOLVED_SCHEDULE_TARGETS_ID) return createTargetsContents();
1203
+ },
1204
+ async closeBundle() {
1205
+ if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
1206
+ await generateProviderOutputs({
1207
+ bundleAlias: {
1208
+ ...resolveStringAliases(resolved),
1209
+ ...internalOptions.providerImportAliases
1210
+ },
1211
+ clientOutDir: resolved.build.outDir,
1212
+ ...!emitStandaloneProviderOutput ? { definitions: [] } : {},
1213
+ rootDir: resolved.root,
1214
+ runtimeImport: internalOptions.runtimeImport,
1215
+ source: standaloneProviderSource
1216
+ });
1217
+ }
1218
+ };
1219
+ }
1220
+ //#endregion
1221
+ export { hubSchedule as n, createScheduleNitroConfig as t };