@vite-hub/schedule 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +27 -6
  2. package/dist/cron-D0mqg3ql.js +22 -0
  3. package/dist/definition.d.ts +1 -1
  4. package/dist/definition.js +3 -4
  5. package/dist/{due-D-0trD1g.js → due-DXgXKgzg.js} +1 -1
  6. package/dist/{error-diagnostics-kKXseq8d.js → error-diagnostics-CsiNo_oI.js} +3 -3
  7. package/dist/{error-diagnostics-B1AaIGWP.js → error-diagnostics-KvK9MX6w.js} +14 -2
  8. package/dist/{started-errors-IG9DlT2A.js → execute-DoQC2i_V.js} +7 -34
  9. package/dist/index.d.ts +12 -8
  10. package/dist/index.js +1 -51
  11. package/dist/{kv-storage-hI2IOjb5.d.ts → kv-storage-CKSSQ6Fk.d.ts} +7 -3
  12. package/dist/{kv-storage-Dsr3TL9c.js → kv-storage-CszEkof6.js} +2 -2
  13. package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-Blwi3jQF.d.ts} +1 -0
  14. package/dist/{operations-BTUQeba1.js → operations-CEZCefAG.js} +25 -13
  15. package/dist/operations.d.ts +2 -2
  16. package/dist/operations.js +7 -5
  17. package/dist/os.js +2 -2
  18. package/dist/runtime/console.js +24 -11
  19. package/dist/runtime/kv.d.ts +1 -1
  20. package/dist/runtime/kv.js +1 -1
  21. package/dist/runtime/process.d.ts +1 -1
  22. package/dist/runtime/process.js +14 -16
  23. package/dist/runtime/state.d.ts +1 -1
  24. package/dist/runtime/state.js +1 -1
  25. package/dist/runtime/static.d.ts +1 -1
  26. package/dist/runtime/static.js +2 -2
  27. package/dist/runtime.d.ts +6 -6
  28. package/dist/runtime.js +5 -5
  29. package/dist/{started-B1Se_Iwo.js → started-ClJ5XOWH.js} +48 -9
  30. package/dist/started-errors-DVw5cYHR.js +28 -0
  31. package/dist/{started-Bzvr4t5f.js → started-yb49f37g.js} +6 -4
  32. package/dist/state-CcVY3UzB.js +570 -0
  33. package/dist/{state-BDEDVlyr.d.ts → state-LuEgYpwR.d.ts} +1 -1
  34. package/dist/{static-Bg7Jj92L.js → static--wi-oIIb.js} +7 -5
  35. package/dist/{static-DeRvJqcQ.d.ts → static-BFV4x94g.d.ts} +1 -1
  36. package/dist/{store-CEv3cScg.d.ts → store-TOayO0NL.d.ts} +6 -3
  37. package/dist/{types-DTVPVY5O.d.ts → types-Wllh0U8N.d.ts} +35 -4
  38. package/dist/vite.d.ts +4 -2
  39. package/dist/vite.js +377 -118
  40. package/package.json +10 -4
  41. package/dist/started-name-w6n9uDdt.js +0 -4
  42. package/dist/state-BZLy46UJ.js +0 -427
  43. package/dist/{cron-BT3ef48f.js → cron-imqlBgO-.js} +1 -1
package/dist/vite.js CHANGED
@@ -1,22 +1,25 @@
1
1
  import { r as __toESM } from "./rolldown-runtime-DegdyBIC.js";
2
- import { a as parseCronFields, l as invariant, u as invariantError } from "./cron-BT3ef48f.js";
2
+ import { a as parseCronFields, l as invariant, u as invariantError } from "./cron-imqlBgO-.js";
3
3
  import { a as relative$1, i as isAbsolute$1, n as relativeDefinitionFile, o as resolve$1, r as dirname$1 } from "./inspect-CW0qwt9p.js";
4
- import { t as internalErrorDiagnostics } from "./error-diagnostics-kKXseq8d.js";
4
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-CsiNo_oI.js";
5
5
  import { n as isRecordOrFunction, t as isRecord$1 } from "./object-CAK6UYR5.js";
6
- import { t as scheduleErrorDiagnostics } from "./error-diagnostics-B1AaIGWP.js";
7
- import { t as startedSchedulesTickName } from "./started-name-w6n9uDdt.js";
6
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-KvK9MX6w.js";
7
+ import { n as parseScheduleCronExpression, t as assertScheduleCronFields } from "./cron-D0mqg3ql.js";
8
+ import { m as startedSchedulesTickName } from "./static--wi-oIIb.js";
8
9
  import { t as isIanaTimeZone } from "./time-zone-pMp_g8Uu.js";
9
- import { i as timeZoneOffsetMinutes, t as cronWithWeekdayNames } from "./due-D-0trD1g.js";
10
+ import { i as timeZoneOffsetMinutes, t as cronWithWeekdayNames } from "./due-DXgXKgzg.js";
10
11
  import { scheduleConsoleTiming } from "./runtime/console.js";
12
+ import "./state-CcVY3UzB.js";
11
13
  import { builtinModules, createRequire, isBuiltin } from "node:module";
12
14
  import { formatDiagnostic } from "nostics";
13
- import { parseCronExpression } from "cron-schedule";
15
+ import { parseDuration } from "@vite-hub/runtime";
14
16
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
15
17
  import { tmpdir } from "node:os";
16
18
  import { basename, dirname, extname, isAbsolute, join, normalize, parse, relative, resolve, sep } from "node:path";
17
19
  import { fileURLToPath, pathToFileURL } from "node:url";
18
20
  import { access, chmod, copyFile, cp, lstat, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
19
21
  import { createHash, randomUUID } from "node:crypto";
22
+ import MagicString from "magic-string";
20
23
  import { isDeepStrictEqual } from "node:util";
21
24
  import { parseSync } from "vite";
22
25
  // ../internal/src/build/vite.ts
@@ -318,12 +321,32 @@ function mergeOwnedArrays(existing, value, arrays) {
318
321
  const next = { ...value };
319
322
  for (const [field, ownership] of Object.entries(arrays ?? {})) {
320
323
  const incoming = Array.isArray(value[field]) ? value[field] : [];
321
- const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
324
+ const unowned = preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming);
325
+ const merged = ownership.key !== void 0 && ownership.preserveOrder && Array.isArray(existing[field]) ? mergeOrderedEntries(existing[field], unowned, incoming, ownership.key) : [...unowned, ...incoming];
322
326
  if (merged.length) next[field] = merged;
323
327
  else delete next[field];
324
328
  }
325
329
  return next;
326
330
  }
331
+ function mergeOrderedEntries(current, unowned, incoming, key) {
332
+ const preserved = new Set(unowned);
333
+ const replacements = new Map(incoming.flatMap((entry) => {
334
+ const identity = getKeyedArrayEntryValue(entry, key);
335
+ return identity === void 0 ? [] : [[identity, entry]];
336
+ }));
337
+ return [...current.flatMap((entry) => {
338
+ if (preserved.has(entry)) return [entry];
339
+ const identity = getKeyedArrayEntryValue(entry, key);
340
+ if (identity === void 0) return [];
341
+ const replacement = replacements.get(identity);
342
+ if (replacement === void 0) return [];
343
+ replacements.delete(identity);
344
+ return [replacement];
345
+ }), ...incoming.filter((entry) => {
346
+ const identity = getKeyedArrayEntryValue(entry, key);
347
+ return identity === void 0 || replacements.has(identity);
348
+ })];
349
+ }
327
350
  async function persistProviderJsonRecord(file, value, removeIfEmpty) {
328
351
  if (removeIfEmpty && !Object.keys(value).length) {
329
352
  await rm(file, { force: true });
@@ -343,19 +366,31 @@ async function writeProviderOutputConfig(file, value, ownership = {}, options =
343
366
  function mergeProviderOutputConfig(existing, value, ownership = {}) {
344
367
  assertProviderJsonRecord(existing);
345
368
  assertProviderJsonRecord(value);
346
- return {
369
+ const next = {
347
370
  ...deleteOwnedFields(existing, ownership),
348
371
  ...mergeOwnedArrays(existing, value, ownership.arrays)
349
372
  };
373
+ for (const [field, childOwnership] of Object.entries(ownership.objects ?? {})) {
374
+ const current = existing[field];
375
+ const incoming = value[field];
376
+ const merged = mergeProviderOutputConfig(isProviderJsonRecord(current) ? current : {}, isProviderJsonRecord(incoming) ? incoming : {}, childOwnership);
377
+ if (Object.keys(merged).length) next[field] = merged;
378
+ else delete next[field];
379
+ }
380
+ return next;
350
381
  }
351
382
  function stringifyProviderOutputConfig(value) {
352
383
  assertProviderJsonRecord(value);
353
384
  return JSON.stringify(value, null, 2);
354
385
  }
355
386
  async function cleanProviderOutputConfig(file, ownership) {
356
- if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
387
+ if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length && !Object.keys(ownership.objects ?? {}).length) return;
357
388
  const existing = await readProviderJsonRecord(file);
358
389
  if (!existing) return;
390
+ const next = cleanOwnedFields(existing, ownership);
391
+ if (next) await persistProviderJsonRecord(file, next, true);
392
+ }
393
+ function cleanOwnedFields(existing, ownership) {
359
394
  const next = deleteOwnedFields(existing, ownership, true);
360
395
  let changed = (ownership.keys ?? []).some((key) => key in existing);
361
396
  for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
@@ -367,8 +402,16 @@ async function cleanProviderOutputConfig(file, ownership) {
367
402
  changed ||= retained.length > 0 || !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
368
403
  if (preserved.length) next[field] = preserved;
369
404
  }
370
- if (!changed) return;
371
- await persistProviderJsonRecord(file, next, true);
405
+ for (const [field, childOwnership] of Object.entries(ownership.objects ?? {})) {
406
+ const current = existing[field];
407
+ if (!isProviderJsonRecord(current)) continue;
408
+ const cleaned = cleanOwnedFields(current, childOwnership);
409
+ if (!cleaned) continue;
410
+ changed = true;
411
+ if (Object.keys(cleaned).length) next[field] = cleaned;
412
+ else delete next[field];
413
+ }
414
+ if (changed) return next;
372
415
  }
373
416
  // ../internal/src/build/user-entry.ts
374
417
  function toSafeAppName(rootDir) {
@@ -3718,6 +3761,9 @@ const ignoredSourceDirectories = /* @__PURE__ */ new Set([
3718
3761
  "node_modules"
3719
3762
  ]);
3720
3763
  const ignoredGeneratedDirectories = /* @__PURE__ */ new Set([".vitehub", ".vitest-tmp"]);
3764
+ function crossesIgnoredDirectory(parent, child) {
3765
+ return relative(parent, child).split(sep).some((segment) => ignoredSourceDirectories.has(segment) || ignoredGeneratedDirectories.has(segment));
3766
+ }
3721
3767
  function isTransientSourceDirectory(path) {
3722
3768
  return basename(path).startsWith(".drizzle-generate-");
3723
3769
  }
@@ -3813,8 +3859,26 @@ async function linkDependencies(source, target, resolveLinkTarget = (source) =>
3813
3859
  await symlink(resolveLinkTarget(resolvedSourceEntry), targetEntry, process.platform === "win32" ? "junction" : "dir");
3814
3860
  }
3815
3861
  }
3816
- /** Removes retained provider output after readers release it, tolerating transient filesystem contention. */
3817
- async function removeProviderOutputArtifactDir(path) {
3862
+ const keptFailedProviderOutputArtifactDirs = /* @__PURE__ */ new Set();
3863
+ function failureText(failure) {
3864
+ return failure instanceof Error ? `${failure.message}\n${failure.stack ?? ""}` : String(failure);
3865
+ }
3866
+ /**
3867
+ * Removes retained provider output after readers release it, tolerating transient filesystem contention. Pass the
3868
+ * build failure when a failed build discards its generation: with `VITEHUB_KEEP_FAILED_BUILD=1` the folder stays
3869
+ * for inspection.
3870
+ */
3871
+ async function removeProviderOutputArtifactDir(path, failure) {
3872
+ if (failure !== void 0) {
3873
+ const shown = relative(process.cwd(), path) || path;
3874
+ if (/^(?:1|true)$/i.test(process.env.VITEHUB_KEEP_FAILED_BUILD ?? "")) {
3875
+ if (!existsSync(path)) return;
3876
+ if (!keptFailedProviderOutputArtifactDirs.has(path)) console.warn(`[vitehub] The build failed. ViteHub kept its provider sources in ${shown} so you can inspect them. Remove the folder when you are done.`);
3877
+ keptFailedProviderOutputArtifactDirs.add(path);
3878
+ return;
3879
+ }
3880
+ if (failureText(failure).includes(basename(path))) console.warn(`[vitehub] The build error names files in ${shown}, which ViteHub removes after a failed build. Set VITEHUB_KEEP_FAILED_BUILD=1 to keep them.`);
3881
+ }
3818
3882
  await rm(path, {
3819
3883
  force: true,
3820
3884
  maxRetries: 5,
@@ -4071,7 +4135,7 @@ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
4071
4135
  }
4072
4136
  return paths;
4073
4137
  }
4074
- async function traceImportedSources(paths, root, configuredRoots) {
4138
+ async function traceImportedSources(paths, root, configuredRoots, aliases) {
4075
4139
  const entries = paths.filter((path) => traceableSourceExtensions.has(extname(path)));
4076
4140
  if (!entries.length) return /* @__PURE__ */ new Set();
4077
4141
  const { rolldown } = await importRolldown();
@@ -4212,7 +4276,7 @@ async function traceImportedSources(paths, root, configuredRoots) {
4212
4276
  if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
4213
4277
  },
4214
4278
  platform: variant.platform,
4215
- plugins: [tracePlugin],
4279
+ plugins: [createResolvedAliasPlugin(aliases, configuredRoots[0] ?? root, root, false), tracePlugin],
4216
4280
  resolve: { conditionNames: variant.conditions }
4217
4281
  });
4218
4282
  try {
@@ -4358,6 +4422,11 @@ function resolveTsconfigReference(config, reference) {
4358
4422
  if (existsSync(resolved)) return resolved;
4359
4423
  } catch {}
4360
4424
  }
4425
+ function resolveTsconfigProjectReference(config, reference) {
4426
+ const path = resolve(dirname(config), reference);
4427
+ const file = existsSync(path) && statSync(path).isDirectory() ? resolve(path, "tsconfig.json") : path;
4428
+ return existsSync(file) && statSync(file).isFile() ? file : void 0;
4429
+ }
4361
4430
  async function tsconfigSourcesForPaths(root, paths) {
4362
4431
  const pending = [];
4363
4432
  for (const path of paths) {
@@ -4379,11 +4448,9 @@ async function tsconfigSourcesForPaths(root, paths) {
4379
4448
  sources.add(config);
4380
4449
  try {
4381
4450
  const parsed = parseJsonWithComments(await readFile(config, "utf8"));
4382
- const references = Array.isArray(parsed.extends) ? parsed.extends : parsed.extends ? [parsed.extends] : [];
4383
- for (const reference of references) {
4384
- const resolved = resolveTsconfigReference(config, reference);
4385
- if (resolved && !sources.has(resolved)) pending.push(resolved);
4386
- }
4451
+ const extended = (Array.isArray(parsed.extends) ? parsed.extends : parsed.extends ? [parsed.extends] : []).map((reference) => resolveTsconfigReference(config, reference));
4452
+ const projects = (Array.isArray(parsed.references) ? parsed.references : []).map((reference) => typeof reference?.path === "string" ? resolveTsconfigProjectReference(config, reference.path) : void 0);
4453
+ for (const resolved of [...extended, ...projects]) if (resolved && !sources.has(resolved)) pending.push(resolved);
4387
4454
  } catch {}
4388
4455
  }
4389
4456
  return [...sources];
@@ -4419,7 +4486,7 @@ async function retainProviderOutputSources(options) {
4419
4486
  const [index, root] = next.value;
4420
4487
  const requested = paths.filter((path) => path !== root && pathContains$1(root, path));
4421
4488
  const nestedConfiguredRoots = configuredRoots.filter((path) => pathContains$1(root, path));
4422
- const importedSources = await traceImportedSources(requested, root, nestedConfiguredRoots);
4489
+ const importedSources = await traceImportedSources(requested, root, nestedConfiguredRoots, options.aliases);
4423
4490
  const materializedSourcePaths = [...requested, ...importedSources];
4424
4491
  const tsconfigSources = await tsconfigSourcesForPaths(root, materializedSourcePaths);
4425
4492
  materializedSourcePaths.push(...tsconfigSources);
@@ -4507,7 +4574,7 @@ async function retainProviderOutputSources(options) {
4507
4574
  const nestedGeneratedOutput = scopedSegments.some((segment) => ignoredGeneratedDirectories.has(segment));
4508
4575
  const ignoredIndex = scopedSegments.findIndex((segment) => ignoredSourceDirectories.has(segment));
4509
4576
  const packageOutput = scopedSegments[ignoredIndex] === "dist" && !containingConfiguredRoot && (ignoredIndex === 0 ? packageRoots.has(root) : referencedPackages.has(resolve(root, ...scopedSegments.slice(0, ignoredIndex))));
4510
- if (nestedGeneratedOutput || ignoredIndex !== -1 && !packageOutput) 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));
4577
+ if (nestedGeneratedOutput || ignoredIndex !== -1 && !packageOutput) return requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource) && !crossesIgnoredDirectory(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));
4511
4578
  return true;
4512
4579
  };
4513
4580
  await copyRetainedSourceTree(root, stagedRoot, (source) => shouldCopySource(resolve(source)));
@@ -5021,17 +5088,17 @@ var ProviderOutputCatalog = class {
5021
5088
  }
5022
5089
  this.#restoreDeploymentContribution(entry);
5023
5090
  }
5024
- resetDeploymentContributions(generation) {
5091
+ resetDeploymentContributions(generation, failure) {
5025
5092
  if (!generation) {
5026
5093
  for (const reference of this.#deploymentGenerations) {
5027
5094
  const current = reference.deref();
5028
5095
  if (current) current.valid = false;
5029
5096
  }
5030
5097
  this.#deploymentGenerations.clear();
5031
- for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
5098
+ for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry, failure);
5032
5099
  for (const taken of this.#takenDeploymentContributions.values()) {
5033
- if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
5034
- for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback);
5100
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry, failure);
5101
+ for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback, failure);
5035
5102
  }
5036
5103
  this.#deploymentContributions.clear();
5037
5104
  this.#takenDeploymentContributions.clear();
@@ -5040,7 +5107,7 @@ var ProviderOutputCatalog = class {
5040
5107
  generation.valid = false;
5041
5108
  this.#deleteDeploymentGeneration(generation);
5042
5109
  for (const [owner, entries] of this.#deploymentContributions) {
5043
- for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
5110
+ for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry, failure);
5044
5111
  const remaining = entries.filter((entry) => entry.generation !== generation);
5045
5112
  if (remaining.length) this.#deploymentContributions.set(owner, remaining);
5046
5113
  else this.#deploymentContributions.delete(owner);
@@ -5048,10 +5115,10 @@ var ProviderOutputCatalog = class {
5048
5115
  for (const [contribution, taken] of this.#takenDeploymentContributions) {
5049
5116
  const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
5050
5117
  taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
5051
- for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
5118
+ for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback, failure);
5052
5119
  if (taken.entry.generation !== generation) continue;
5053
5120
  this.#takenDeploymentContributions.delete(contribution);
5054
- if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
5121
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry, failure);
5055
5122
  for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
5056
5123
  else this.#restoreDeploymentContribution(fallback);
5057
5124
  }
@@ -5094,7 +5161,7 @@ var ProviderOutputCatalog = class {
5094
5161
  const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
5095
5162
  if (failure) throw failure.reason;
5096
5163
  }
5097
- async completeDeploymentContributions(contributions) {
5164
+ async completeDeploymentContributions(contributions, buildFailure) {
5098
5165
  const discarded = this.#pendingDeploymentDiscards.splice(0);
5099
5166
  const completedGenerations = /* @__PURE__ */ new Set();
5100
5167
  for (const contribution of contributions) {
@@ -5104,7 +5171,7 @@ var ProviderOutputCatalog = class {
5104
5171
  const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
5105
5172
  for (const entry of entries) {
5106
5173
  if (entry.generation) completedGenerations.add(entry.generation);
5107
- if (entry.contribution.discard) discarded.push(entry.contribution.discard());
5174
+ if (entry.contribution.discard) discarded.push(entry.contribution.discard(entry === taken.entry ? buildFailure : void 0));
5108
5175
  }
5109
5176
  }
5110
5177
  for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
@@ -5148,9 +5215,9 @@ var ProviderOutputCatalog = class {
5148
5215
  if (reference) this.#deploymentGenerations.delete(reference);
5149
5216
  this.#deploymentGenerationRefs.delete(generation);
5150
5217
  }
5151
- #queueDeploymentDiscard(entry) {
5218
+ #queueDeploymentDiscard(entry, failure) {
5152
5219
  if (!entry.contribution.discard) return;
5153
- const discard = Promise.resolve().then(entry.contribution.discard);
5220
+ const discard = Promise.resolve().then(async () => await entry.contribution.discard?.(failure));
5154
5221
  discard.catch(() => {});
5155
5222
  this.#pendingDeploymentDiscards.push(discard);
5156
5223
  }
@@ -5995,23 +6062,23 @@ async function resetProviderDeploymentOutputs(catalog, failure, generation) {
5995
6062
  if (!catalog) return;
5996
6063
  const completedReset = providerDeploymentOutputCompletedResets.get(catalog);
5997
6064
  if (completedReset && failure !== void 0 && completedReset.failures.has(failure)) {
5998
- if (generation) catalog.resetDeploymentContributions(generation);
6065
+ if (generation) catalog.resetDeploymentContributions(generation, failure);
5999
6066
  await completedReset.promise;
6000
6067
  return;
6001
6068
  }
6002
6069
  if (completedReset) providerDeploymentOutputCompletedResets.delete(catalog);
6003
- if (generation) catalog.resetDeploymentContributions(generation);
6070
+ if (generation) catalog.resetDeploymentContributions(generation, failure);
6004
6071
  const active = providerDeploymentOutputFinalizations.get(catalog);
6005
6072
  if (active?.reset) {
6006
6073
  if (failure !== void 0 && !active.reset.failures.has(failure)) {
6007
6074
  active.reset.failures.add(failure);
6008
- if (!generation) catalog.resetDeploymentContributions();
6075
+ if (!generation) catalog.resetDeploymentContributions(void 0, failure);
6009
6076
  }
6010
6077
  providerDeploymentOutputCompletedResets.set(catalog, active.reset);
6011
6078
  await active.reset.promise;
6012
6079
  return;
6013
6080
  }
6014
- if (!generation) catalog.resetDeploymentContributions();
6081
+ if (!generation) catalog.resetDeploymentContributions(void 0, failure);
6015
6082
  if (active && (!generation || active.state.generations.has(generation))) {
6016
6083
  active.state.rollback = true;
6017
6084
  active.controller.abort(internalErrorDiagnostics.INTERNAL_B0039({ message: "Provider Output finalization reset" }));
@@ -6160,7 +6227,7 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
6160
6227
  await catalog.completeDeploymentContributions(contributions);
6161
6228
  } catch (error) {
6162
6229
  if (state.rollback) catalog.rollbackDeploymentContributions(contributions);
6163
- else await catalog.completeDeploymentContributions(contributions);
6230
+ else await catalog.completeDeploymentContributions(contributions, error);
6164
6231
  throw error;
6165
6232
  } finally {
6166
6233
  state.generations.clear();
@@ -6644,6 +6711,17 @@ function isServerScheduleDefinition(definition) {
6644
6711
  return definition.source === "server-schedules" || definition.source === "vite-plugin-contribution";
6645
6712
  }
6646
6713
  const scheduleSuffixPattern = /\.schedule\.(?:c|m)?[jt]s$/i;
6714
+ function cronLocation(file, source, offset) {
6715
+ return `[vitehub] ${file}:${source.slice(0, offset).split("\n").length}: \`defineSchedule()\``;
6716
+ }
6717
+ function assertStaticScheduleCron(file) {
6718
+ const source = readFileSync(file, "utf8");
6719
+ const definition = findDefaultExportCall(scanModule(source, file), ["defineSchedule"]);
6720
+ const property = definition?.options && findProperty(definition.options, "cron");
6721
+ if (!property) return;
6722
+ const cron = staticString(property.value);
6723
+ if (cron !== void 0) parseScheduleCronExpression(cron, cronLocation(file, source, property.node.start));
6724
+ }
6647
6725
  function readScheduleDiscoveryMetadata(file, contribution) {
6648
6726
  const source = readFileSync(file, "utf8");
6649
6727
  const module = scanModule(source, file);
@@ -6665,20 +6743,22 @@ function readScheduleDiscoveryMetadata(file, contribution) {
6665
6743
  return {};
6666
6744
  }
6667
6745
  const start = definition.call.start;
6668
- let manual = false;
6669
- let startable = true;
6746
+ const cronProperty = definition.options && findProperty(definition.options, "cron");
6747
+ const cron = staticString(cronProperty?.value);
6748
+ let manual;
6670
6749
  for (const property of definition.options ? objectProperties(definition.options) : []) {
6671
6750
  if (property.key === void 0 || property.computed) unsupported(start, "Schedule discovery cannot resolve spread, computed, or escaped option keys. Declare manual with an unescaped literal key and a literal true or false value.");
6672
- if (property.key === "cron") startable = false;
6673
6751
  if (property.key !== "manual") continue;
6674
6752
  const value = property.node.type === "Property" && property.node.kind === "init" && !property.node.method && property.value?.type === "Literal" && typeof property.value.value === "boolean" ? property.value.value : void 0;
6675
6753
  if (value === void 0) unsupported(start, "Schedule discovery requires manual to be a literal true or false; it cannot evaluate this expression.");
6676
6754
  manual = value === true;
6677
6755
  }
6678
- return startable ? {
6679
- manual,
6680
- startable
6681
- } : { manual };
6756
+ if (!cronProperty) return {
6757
+ manual: false,
6758
+ startable: true
6759
+ };
6760
+ if (cron !== void 0) assertScheduleCronFields(cron, cronLocation(file, source, cronProperty.node.start));
6761
+ return { manual: manual ?? true };
6682
6762
  }
6683
6763
  function createDiscoveredScheduleDefinition(source) {
6684
6764
  return (context) => {
@@ -6756,7 +6836,7 @@ function startedTickSource() {
6756
6836
  `import { defineSchedule } from ${resolveEntry("@vite-hub/schedule")}`,
6757
6837
  `import { runStartedSchedules } from ${resolveEntry("@vite-hub/schedule/runtime")}`,
6758
6838
  "",
6759
- "export default defineSchedule({ cron: \"* * * * *\", handler: runStartedSchedules, manual: true })",
6839
+ "export default defineSchedule({ cron: \"* * * * *\", handler: runStartedSchedules })",
6760
6840
  ""
6761
6841
  ].join("\n");
6762
6842
  }
@@ -6797,6 +6877,33 @@ function discoverScheduleDefinitions(options) {
6797
6877
  function discoverStartableScheduleDefinitions(options) {
6798
6878
  return discoverAllScheduleDefinitions(options).filter((definition) => definition.startable);
6799
6879
  }
6880
+ // src/registry-types.ts
6881
+ const scheduleTypesFile = ".vitehub/schedule.d.ts";
6882
+ function registryEntries(definitions) {
6883
+ return [...new Set(definitions.map((definition) => definition.name))].sort().map((name) => ` ${JSON.stringify(name)}: true`);
6884
+ }
6885
+ /** Types the names that `runSchedule()` (`ScheduleRegistry`) and `startSchedule()` (`StartableScheduleRegistry`) accept. */
6886
+ function createScheduleTypes(definitions, startableDefinitions, importBase = "@vite-hub/schedule") {
6887
+ return [
6888
+ `import ${JSON.stringify(importBase)}`,
6889
+ `declare module ${JSON.stringify(importBase)} {`,
6890
+ " interface ScheduleRegistryState {",
6891
+ " generated: true",
6892
+ " }",
6893
+ " interface ScheduleRegistry {",
6894
+ ...registryEntries(definitions),
6895
+ " }",
6896
+ " interface StartableScheduleRegistry {",
6897
+ ...registryEntries(startableDefinitions),
6898
+ " }",
6899
+ "}",
6900
+ ""
6901
+ ].join("\n");
6902
+ }
6903
+ /** Writes `.vitehub/schedule.d.ts` when its contents change. */
6904
+ async function writeScheduleTypes(root, definitions, startableDefinitions, importBase = "@vite-hub/schedule") {
6905
+ await writeFileIfChanged(resolve(root, scheduleTypesFile), createScheduleTypes(definitions, startableDefinitions, importBase));
6906
+ }
6800
6907
  // src/integrations/vercel.ts
6801
6908
  function getVercelSchedulePath(name) {
6802
6909
  return `/api/vitehub/schedules/vercel/${name.replace(/[^a-z0-9/_-]+/gi, "_")}`;
@@ -6830,12 +6937,12 @@ function utcCronForTimeZone(cron, timeZone, from = /* @__PURE__ */ new Date()) {
6830
6937
  const key = `${cron}\n${timeZone}\n${from.toISOString().slice(0, 10)}`;
6831
6938
  if (utcCronCache.has(key)) return utcCronCache.get(key);
6832
6939
  const offsets = timeZoneOffsets(timeZone, from);
6833
- const utcCron = offsets.length === 1 && offsets[0] === 0 ? void 0 : expandCron(cron, offsets);
6940
+ const utcCron = offsets.length === 1 && offsets[0] === 0 ? void 0 : expandCron(cron, offsets, timeZone);
6834
6941
  utcCronCache.set(key, utcCron);
6835
6942
  return utcCron;
6836
6943
  }
6837
- function expandCron(cron, offsets) {
6838
- const parsed = parseCronExpression(cron);
6944
+ function expandCron(cron, offsets, timeZone) {
6945
+ const parsed = parseScheduleCronExpression(cron, `Schedule with time zone "${timeZone}"`);
6839
6946
  const [minuteField, hourField, dayField, monthField, weekdayField] = cron.trim().split(/\s+/);
6840
6947
  const minutes = /* @__PURE__ */ new Set();
6841
6948
  const hours = /* @__PURE__ */ new Set();
@@ -6965,6 +7072,10 @@ function isProviderCron(cron) {
6965
7072
  function validateProviderCron(cron, scheduleName) {
6966
7073
  if (!isProviderCron(cron)) throw scheduleErrorDiagnostics.SCHEDULE_R0003({ message: `Schedule "${scheduleName}" uses cron "${cron}", but provider wake output only supports five-field UTC cron syntax compatible with Cloudflare, Vercel, and Netlify.` });
6967
7074
  }
7075
+ function validateDefinitionProviderCron(cron, definition, overrides) {
7076
+ if (!isProviderCron(cron) && !(overrides && Object.hasOwn(overrides, definition.name))) assertStaticScheduleCron(definition.handler);
7077
+ validateProviderCron(cron, definition.name);
7078
+ }
6968
7079
  /** Reads the `cron` option of a `defineSchedule()` call. Returns `undefined` when it is missing or not a static string. */
6969
7080
  function readStaticScheduleCronOption(file) {
6970
7081
  const definition = findDefaultExportCall(scanModule(readFileSync(file, "utf8"), file), ["defineSchedule"]);
@@ -7016,7 +7127,7 @@ function readTimeZoneCrons(definitions, overrides) {
7016
7127
  if (timeZone === null) throw scheduleErrorDiagnostics.SCHEDULE_R0003({ message: `Schedule "${definition.name}" declares timeZone with a value that is not a static string. Host cron output reads timeZone at build time, so write it as a string literal, such as \`timeZone: "Europe/Madrid"\`.` });
7017
7128
  if (!isIanaTimeZone(timeZone)) throw scheduleErrorDiagnostics.SCHEDULE_R0003({ message: `Schedule "${definition.name}" declares timeZone ${JSON.stringify(timeZone)}, which is not an IANA time zone, such as "Europe/Madrid".` });
7018
7129
  const cron = readStaticScheduleCron(definition.handler, definition.name);
7019
- validateProviderCron(cron, definition.name);
7130
+ validateDefinitionProviderCron(cron, definition);
7020
7131
  const utcCron = utcCronForTimeZone(cron, timeZone);
7021
7132
  if (utcCron !== void 0) crons[definition.name] = utcCron;
7022
7133
  }
@@ -7248,7 +7359,7 @@ async function readDefinitionCrons(definitions, overrides) {
7248
7359
  const crons = await readRuntimeDefinitionCrons(definitions);
7249
7360
  for (const [name, cron] of Object.entries(readTimeZoneCrons(definitions, overrides))) crons.set(name, cron);
7250
7361
  for (const [name, cron] of Object.entries(overrides ?? {})) if (crons.has(name)) crons.set(name, cron);
7251
- for (const [name, cron] of crons) validateProviderCron(cron, name);
7362
+ for (const definition of definitions) validateDefinitionProviderCron(crons.get(definition.name), definition, overrides);
7252
7363
  return crons;
7253
7364
  }
7254
7365
  async function readRuntimeDefinitionCrons(definitions) {
@@ -7935,7 +8046,7 @@ const scheduleConsoleSection = {
7935
8046
  }
7936
8047
  ],
7937
8048
  kind: "record-table",
7938
- notice: "The host runs each Schedule on its cron, in its time zone (UTC by default). A Definition without cron runs when code starts it with `startSchedule()`; each started Schedule has its own row. Static Definitions with `manual: true` can also run from the Console or `vitehub schedule run`."
8049
+ notice: "The host runs each Schedule on its cron, in its time zone (UTC by default). A Definition without cron runs when code starts it with `startSchedule()`; each started Schedule has its own row. Static Definitions can also run from the Console or `vitehub schedule run`, unless they set `manual: false`. A development server allows this. A deployed app allows it only when you set `console: { invoke: true }`."
7939
8050
  }
7940
8051
  };
7941
8052
  // src/internal/registry-module.ts
@@ -7962,6 +8073,7 @@ async function readScheduleDefinitionCrons(definitions) {
7962
8073
  const SCHEDULE_VITE_PLUGIN_NAME = "@vite-hub/schedule/vite";
7963
8074
  const SCHEDULE_REGISTRY_ID = "#vitehub/schedule/registry";
7964
8075
  const RESOLVED_SCHEDULE_REGISTRY_ID = "\0#vitehub/schedule/registry";
8076
+ const scheduleRegistryImport = /\/\* @vite-ignore \*\/\s*\/\* @vitehub-schedule-registry \*\/\s*[\w$]+/g;
7965
8077
  const generatedNitroSchedulePlugin = ".vitehub/nitro/schedule/plugin.ts";
7966
8078
  const generatedNitroProviderRegistry = ".vitehub/nitro/schedule/provider-registry.js";
7967
8079
  const generatedNitroStaticRegistry = ".vitehub/nitro/schedule/static-registry.js";
@@ -7970,17 +8082,10 @@ const generatedNitroInventoryRegistry = ".vitehub/nitro/schedule/inventory-regis
7970
8082
  const defaultCatchUpMs = 36e5;
7971
8083
  const generatedNitroScheduleModule = "./.vitehub/nitro/schedule/module.mjs";
7972
8084
  const generatedNitroNetlifyEntry = ".vitehub/nitro/schedule/netlify-entry.mjs";
8085
+ const generatedNitroScheduleRunner = ".vitehub/nitro/schedule/runner.mjs";
8086
+ const generatedNitroVercelHandler = ".vitehub/nitro/schedule/vercel-handler.mjs";
8087
+ const generatedNitroVercelRoutes = ".vitehub/nitro/schedule/vercel";
7973
8088
  const mergeNoExternal = createNoExternalMerger(schedulePackageName);
7974
- function invalidateScheduleRegistry(server) {
7975
- const registry = server.moduleGraph.getModuleById(RESOLVED_SCHEDULE_REGISTRY_ID);
7976
- if (registry) server.moduleGraph.invalidateModule(registry);
7977
- for (const environment of Object.values(server.environments ?? {})) {
7978
- const module = environment.moduleGraph.getModuleById(RESOLVED_SCHEDULE_REGISTRY_ID);
7979
- if (!module) continue;
7980
- environment.moduleGraph.invalidateModule(module);
7981
- if (environment.config.consumer === "server") environment.hot.send({ type: "full-reload" });
7982
- }
7983
- }
7984
8089
  function resolveSchedulePluginRoots(root, options = {}) {
7985
8090
  const resolvedViteRoot = resolve(root);
7986
8091
  return {
@@ -8008,6 +8113,17 @@ function resolveProcessRuntimeOptions(value) {
8008
8113
  ...value.prefix !== void 0 ? { prefix: value.prefix } : {}
8009
8114
  };
8010
8115
  }
8116
+ function resolveScheduleRetention(value, processRuntime) {
8117
+ const catchUpMs = processRuntime?.catchUpMs ?? defaultCatchUpMs;
8118
+ if (value === void 0) return catchUpMs > parseDuration("30 days") ? `${catchUpMs}ms` : void 0;
8119
+ const retention = value;
8120
+ const milliseconds = parseDuration(retention, "retention");
8121
+ if (milliseconds <= 0 || processRuntime && milliseconds < catchUpMs) throw scheduleErrorDiagnostics.SCHEDULE_RETENTION_TOO_SHORT({
8122
+ catchUpMs,
8123
+ retention: JSON.stringify(retention)
8124
+ });
8125
+ return retention;
8126
+ }
8011
8127
  const databaseVitePluginName = "@vite-hub/database/vite";
8012
8128
  function hasVitePlugin(plugins, name) {
8013
8129
  return (plugins ?? []).some((plugin) => Array.isArray(plugin) ? hasVitePlugin(plugin, name) : isRecord(plugin) && plugin.name === name);
@@ -8125,7 +8241,10 @@ function renderNitroSchedulePlugin(options) {
8125
8241
  "",
8126
8242
  ...processRuntime ? [
8127
8243
  `const processRuntimeOptions = ${JSON.stringify(processRuntimeOptions, null, 2)}`,
8128
- ...memoryStores ? [] : [`const scheduleStoreOptions = { ...${JSON.stringify(scheduleStoreOptions, null, 2)}, kvStore: scheduleKVStorage }`],
8244
+ ...memoryStores ? [] : [`const scheduleStoreOptions = { ...${JSON.stringify({
8245
+ ...scheduleStoreOptions,
8246
+ ...options.retention ? { retention: options.retention } : {}
8247
+ }, null, 2)}, kvStore: scheduleKVStorage }`],
8129
8248
  ""
8130
8249
  ] : [],
8131
8250
  "export default definePlugin((nitroApp) => {",
@@ -8202,36 +8321,43 @@ function renderNitroSchedulePlugin(options) {
8202
8321
  ""
8203
8322
  ].join("\n");
8204
8323
  }
8205
- function renderNitroScheduleModule(options) {
8206
- const { netlify } = options;
8207
- let netlifyFunctionNames = /* @__PURE__ */ new Map();
8208
- let netlifyNameError;
8209
- try {
8210
- netlifyFunctionNames = netlifyScheduleFunctionNames(netlify.schedules);
8211
- } catch (error) {
8212
- if (!scheduleErrorDiagnostics.SCHEDULE_R0006.is(error)) throw error;
8213
- netlifyNameError = {
8214
- ...error,
8215
- code: error.code,
8216
- message: error.message,
8217
- name: error.name
8324
+ function serializeScheduleError(error) {
8325
+ return {
8326
+ ...error,
8327
+ code: error.code,
8328
+ message: error.message,
8329
+ name: error.name
8330
+ };
8331
+ }
8332
+ function resolveNitroVercelScheduleRoutes(root, schedules, standaloneNames) {
8333
+ const paths = /* @__PURE__ */ new Map();
8334
+ for (const name of [...schedules.map((schedule) => schedule.name), ...standaloneNames]) {
8335
+ const path = getVercelSchedulePath(name);
8336
+ const existing = paths.get(path);
8337
+ if (existing !== void 0) return {
8338
+ error: serializeScheduleError(scheduleErrorDiagnostics.SCHEDULE_R0005({ message: `Schedule "${name}" and "${existing}" both use the same Vercel cron path: ${path}` })),
8339
+ routes: []
8218
8340
  };
8341
+ paths.set(path, name);
8219
8342
  }
8220
- const netlifySchedules = netlify.schedules.map((schedule) => ({
8221
- ...schedule,
8222
- functionName: netlifyFunctionNames.get(schedule.name)
8223
- }));
8224
- const crons = Object.fromEntries(netlify.schedules.map((schedule) => [schedule.name, schedule.cron]));
8225
- const timeZoneNames = netlify.schedules.filter((schedule) => schedule.inTimeZone).map((schedule) => schedule.name);
8226
- const netlifyEntryRuntime = [
8343
+ return { routes: schedules.map(({ name }, index) => ({
8344
+ handler: resolve(root, generatedNitroVercelRoutes, `${index}.mjs`),
8345
+ name,
8346
+ route: getVercelSchedulePath(name)
8347
+ })) };
8348
+ }
8349
+ function renderNitroScheduleRunner(options) {
8350
+ const crons = Object.fromEntries(options.schedules.map((schedule) => [schedule.name, schedule.cron]));
8351
+ const timeZoneNames = options.schedules.filter((schedule) => schedule.inTimeZone).map((schedule) => schedule.name);
8352
+ return [
8227
8353
  "import { useNitroApp } from \"nitro/app\"",
8228
- `import scheduleRegistry from ${JSON.stringify(netlify.registryFile)}`,
8229
- `import { executeStaticSchedule, isTimeZoneWakeDue, missingScheduleDefinitionError, scheduledWakeTime, unwrapScheduleDefinition } from ${JSON.stringify(netlify.runtimeImport)}`,
8354
+ `import scheduleRegistry from ${JSON.stringify(options.registryFile)}`,
8355
+ `import { executeStaticSchedule, isTimeZoneWakeDue, missingScheduleDefinitionError, scheduledWakeTime, unwrapScheduleDefinition } from ${JSON.stringify(options.runtimeImport)}`,
8230
8356
  "",
8231
8357
  `const crons = ${JSON.stringify(crons)}`,
8232
8358
  `const timeZoneNames = new Set(${JSON.stringify(timeZoneNames)})`,
8233
8359
  "",
8234
- "export async function runViteHubNetlifySchedule(name) {",
8360
+ "export async function runViteHubSchedule(name) {",
8235
8361
  " const scheduledAt = scheduledWakeTime(crons[name])",
8236
8362
  " await useNitroApp().ready",
8237
8363
  " const loader = scheduleRegistry[name]",
@@ -8242,6 +8368,52 @@ function renderNitroScheduleModule(options) {
8242
8368
  "}",
8243
8369
  ""
8244
8370
  ].join("\n");
8371
+ }
8372
+ function renderNitroVercelScheduleHandler(options) {
8373
+ return [
8374
+ "import { defineHandler } from \"nitro/h3\"",
8375
+ `import { isScheduleCronAuthorized } from ${JSON.stringify(options.runtimeImport)}`,
8376
+ `import { runViteHubSchedule } from ${JSON.stringify(options.runnerFile)}`,
8377
+ "",
8378
+ "export function defineVercelScheduleHandler(name) {",
8379
+ " return defineHandler(async (event) => {",
8380
+ " const cronSecret = process.env.CRON_SECRET",
8381
+ " if (!cronSecret) return new Response('Unauthorized. Set CRON_SECRET in the Vercel project to run Schedules.', { status: 401 })",
8382
+ " if (!isScheduleCronAuthorized(event.req.headers.get('authorization'), cronSecret)) return new Response('Unauthorized.', { status: 401 })",
8383
+ " await runViteHubSchedule(name)",
8384
+ " return new Response(null, { status: 204 })",
8385
+ " })",
8386
+ "}",
8387
+ ""
8388
+ ].join("\n");
8389
+ }
8390
+ function renderNitroVercelScheduleRoute(handlerFile, name) {
8391
+ return [
8392
+ `import { defineVercelScheduleHandler } from ${JSON.stringify(handlerFile)}`,
8393
+ "",
8394
+ `export default defineVercelScheduleHandler(${JSON.stringify(name)})`,
8395
+ ""
8396
+ ].join("\n");
8397
+ }
8398
+ function renderNitroScheduleModule(options) {
8399
+ let netlifyFunctionNames = /* @__PURE__ */ new Map();
8400
+ let netlifyNameError;
8401
+ try {
8402
+ netlifyFunctionNames = netlifyScheduleFunctionNames(options.schedules);
8403
+ } catch (error) {
8404
+ if (!scheduleErrorDiagnostics.SCHEDULE_R0006.is(error)) throw error;
8405
+ netlifyNameError = serializeScheduleError(error);
8406
+ }
8407
+ const netlifySchedules = options.schedules.map((schedule) => ({
8408
+ ...schedule,
8409
+ functionName: netlifyFunctionNames.get(schedule.name)
8410
+ }));
8411
+ const crons = Object.fromEntries(options.schedules.map((schedule) => [schedule.name, schedule.cron]));
8412
+ const vercelRoutes = options.vercel.routes.map(({ handler, name, route }) => ({
8413
+ handler,
8414
+ route,
8415
+ schedule: crons[name]
8416
+ }));
8245
8417
  return [
8246
8418
  "import { cp, rm, writeFile } from 'node:fs/promises'",
8247
8419
  "import { join } from 'node:path'",
@@ -8249,8 +8421,10 @@ function renderNitroScheduleModule(options) {
8249
8421
  `const crons = ${JSON.stringify(options.crons)}`,
8250
8422
  `const netlifySchedules = ${JSON.stringify(netlifySchedules)}`,
8251
8423
  `const netlifyNameError = ${JSON.stringify(netlifyNameError ?? null)}`,
8252
- `const netlifyEntryFile = ${JSON.stringify(netlify.entryFile)}`,
8253
- `const netlifyEntryRuntime = ${JSON.stringify(netlifyEntryRuntime)}`,
8424
+ `const netlifyEntryFile = ${JSON.stringify(options.netlifyEntryFile)}`,
8425
+ `const runnerFile = ${JSON.stringify(options.runnerFile)}`,
8426
+ `const vercelRoutes = ${JSON.stringify(vercelRoutes)}`,
8427
+ `const vercelPathError = ${JSON.stringify(options.vercel.error ?? null)}`,
8254
8428
  "",
8255
8429
  "function dedupeCloudflareCrons(nitro) {",
8256
8430
  " const wrangler = nitro.options.cloudflare?.wrangler",
@@ -8268,10 +8442,10 @@ function renderNitroScheduleModule(options) {
8268
8442
  " // Netlify deploys each function directory alone, so each one gets its own copy of the server bundle.",
8269
8443
  " await cp(serverDir, functionDir, { filter: source => source !== join(serverDir, 'server.mjs'), recursive: true })",
8270
8444
  " await writeFile(join(functionDir, `${functionName}.mjs`), [",
8271
- " \"import { runViteHubNetlifySchedule } from './main.mjs'\",",
8445
+ " \"import { runViteHubSchedule } from './main.mjs'\",",
8272
8446
  " '',",
8273
8447
  " 'export default async function vitehubNetlifySchedule() {',",
8274
- " ` await runViteHubNetlifySchedule(${JSON.stringify(name)})`,",
8448
+ " ` await runViteHubSchedule(${JSON.stringify(name)})`,",
8275
8449
  " ' return new Response(null, { status: 204 })',",
8276
8450
  " '}',",
8277
8451
  " '',",
@@ -8281,24 +8455,44 @@ function renderNitroScheduleModule(options) {
8281
8455
  " }",
8282
8456
  "}",
8283
8457
  "",
8284
- "export default async function vitehubScheduleModule(nitro) {",
8285
- " nitro.options.cloudflare ??= {}",
8286
- " nitro.options.cloudflare.wrangler ??= {}",
8287
- " nitro.options.cloudflare.wrangler.triggers ??= {}",
8288
- " const existingCrons = Array.isArray(nitro.options.cloudflare.wrangler.triggers.crons) ? nitro.options.cloudflare.wrangler.triggers.crons : []",
8289
- " nitro.options.cloudflare.wrangler.triggers.crons = [...new Set([...existingCrons, ...crons])]",
8290
- " nitro.hooks.hook('build:before', dedupeCloudflareCrons)",
8291
- " if (nitro.options.preset !== 'netlify') return",
8458
+ "async function setupNetlifySchedules(nitro) {",
8292
8459
  " if (netlifyNameError) throw Object.assign(new Error(netlifyNameError.message), netlifyNameError)",
8293
8460
  " if (!netlifySchedules.length) return",
8294
8461
  " // The server bundle keeps Nitro's entry and also exports the Schedule runner for the scheduled functions.",
8295
- " await writeFile(netlifyEntryFile, `export { default } from ${JSON.stringify(nitro.options.entry)}\\n${netlifyEntryRuntime}`)",
8462
+ " await writeFile(netlifyEntryFile, `export { default } from ${JSON.stringify(nitro.options.entry)}\\nexport { runViteHubSchedule } from ${JSON.stringify(runnerFile)}\\n`)",
8296
8463
  " nitro.options.entry = netlifyEntryFile",
8297
8464
  " // Register after all modules have installed their compiled writers, including Database migrations.",
8298
8465
  " nitro.hooks.hookOnce('build:before', () => {",
8299
8466
  " nitro.hooks.hook('compiled', writeNetlifyScheduleFunctions)",
8300
8467
  " })",
8301
8468
  "}",
8469
+ "",
8470
+ "function setupVercelSchedules(nitro) {",
8471
+ " if (vercelPathError) throw Object.assign(new Error(vercelPathError.message), vercelPathError)",
8472
+ " if (!vercelRoutes.length) return",
8473
+ " for (const { handler, route } of vercelRoutes) {",
8474
+ " nitro.options.handlers.push({ route, lazy: true, handler })",
8475
+ " nitro.options.routeRules[route] = { ...nitro.options.routeRules[route], cache: false, isr: false }",
8476
+ " }",
8477
+ " const base = nitro.options.baseURL.replace(/\\/$/, '')",
8478
+ " const vercelCrons = vercelRoutes.map(({ route, schedule }) => ({ path: `${base}${route}`, schedule }))",
8479
+ " nitro.options.vercel ??= {}",
8480
+ " nitro.options.vercel.config ??= {}",
8481
+ " const paths = new Set(vercelCrons.map(cron => cron.path))",
8482
+ " const existing = Array.isArray(nitro.options.vercel.config.crons) ? nitro.options.vercel.config.crons.filter(cron => !paths.has(cron?.path)) : []",
8483
+ " nitro.options.vercel.config.crons = [...existing, ...vercelCrons]",
8484
+ "}",
8485
+ "",
8486
+ "export default async function vitehubScheduleModule(nitro) {",
8487
+ " nitro.options.cloudflare ??= {}",
8488
+ " nitro.options.cloudflare.wrangler ??= {}",
8489
+ " nitro.options.cloudflare.wrangler.triggers ??= {}",
8490
+ " const existingCrons = Array.isArray(nitro.options.cloudflare.wrangler.triggers.crons) ? nitro.options.cloudflare.wrangler.triggers.crons : []",
8491
+ " nitro.options.cloudflare.wrangler.triggers.crons = [...new Set([...existingCrons, ...crons])]",
8492
+ " nitro.hooks.hook('build:before', dedupeCloudflareCrons)",
8493
+ " if (nitro.options.preset === 'netlify') await setupNetlifySchedules(nitro)",
8494
+ " if (nitro.options.preset === 'vercel') setupVercelSchedules(nitro)",
8495
+ "}",
8302
8496
  ""
8303
8497
  ].join("\n");
8304
8498
  }
@@ -8332,6 +8526,7 @@ async function writeNitroSchedulePlugin(root, options) {
8332
8526
  ...options.processTimings ? { processTimings: options.processTimings } : {},
8333
8527
  providerDefinitions: options.providerDefinitions,
8334
8528
  providerRegistryFile,
8529
+ ...options.retention ? { retention: options.retention } : {},
8335
8530
  staticRegistryFile,
8336
8531
  runtimeImport: options.runtimeImport
8337
8532
  }))];
@@ -8350,14 +8545,26 @@ async function writeNitroSchedulePlugin(root, options) {
8350
8545
  if (options.providerDefinitions.length > 0) {
8351
8546
  writes.push(writeFileIfChanged(providerRegistryFile, createRuntimeRegistryContents(providerRegistryFile, options.providerDefinitions)));
8352
8547
  writes.push(writeFileIfChanged(providerRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase)));
8548
+ const runnerFile = resolve(root, generatedNitroScheduleRunner);
8549
+ const vercelHandlerFile = resolve(root, generatedNitroVercelHandler);
8550
+ const runtimeImport = options.runtimeImport ?? scheduleStaticRuntimeModule;
8551
+ writes.push(writeFileIfChanged(runnerFile, renderNitroScheduleRunner({
8552
+ registryFile: providerRegistryFile,
8553
+ runtimeImport,
8554
+ schedules: options.hostSchedules
8555
+ })));
8556
+ writes.push(writeFileIfChanged(vercelHandlerFile, renderNitroVercelScheduleHandler({
8557
+ runnerFile,
8558
+ runtimeImport
8559
+ })));
8560
+ const vercel = resolveNitroVercelScheduleRoutes(root, options.hostSchedules, options.standaloneScheduleNames);
8561
+ for (const { handler, name } of vercel.routes) writes.push(writeFileIfChanged(handler, renderNitroVercelScheduleRoute(vercelHandlerFile, name)));
8353
8562
  writes.push(writeFileIfChanged(moduleFile, renderNitroScheduleModule({
8354
8563
  crons: options.crons,
8355
- netlify: {
8356
- entryFile: resolve(root, generatedNitroNetlifyEntry),
8357
- registryFile: providerRegistryFile,
8358
- runtimeImport: options.runtimeImport ?? scheduleStaticRuntimeModule,
8359
- schedules: options.netlifySchedules
8360
- }
8564
+ netlifyEntryFile: resolve(root, generatedNitroNetlifyEntry),
8565
+ runnerFile,
8566
+ schedules: options.hostSchedules,
8567
+ vercel
8361
8568
  })));
8362
8569
  }
8363
8570
  await Promise.all(writes);
@@ -8404,8 +8611,15 @@ function shouldEmitStandaloneProviderOutput(definitions, options) {
8404
8611
  if (hasServerScheduleDefinitions(definitions)) return hasViteSuffixScheduleDefinitions(definitions);
8405
8612
  return definitions.length > 0;
8406
8613
  }
8614
+ function readNitroPreset(nitro) {
8615
+ return isRecord(nitro) && typeof nitro.preset === "string" ? nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOST || "";
8616
+ }
8617
+ function keepsScheduleRunsInWorkerMemory(nitroPreset, processRuntime, schedules) {
8618
+ return !processRuntime && schedules > 0 && nitroPreset.startsWith("cloudflare");
8619
+ }
8407
8620
  async function createScheduleNitroConfig(options = {}) {
8408
8621
  const processRuntime = resolveProcessRuntimeOptions(options.runtime);
8622
+ const retention = resolveScheduleRetention(options.retention, processRuntime);
8409
8623
  const roots = resolveSchedulePluginRoots(options.root || process.cwd(), options);
8410
8624
  const internal = options;
8411
8625
  const hints = internal.hints ?? {
@@ -8432,9 +8646,11 @@ async function createScheduleNitroConfig(options = {}) {
8432
8646
  });
8433
8647
  const cronOverrides = resolveCronOverrides(options.cron, options.preliminary ? void 0 : definitions, options);
8434
8648
  const installNitroPlugin = shouldInstallNitroSchedulePlugin(definitions, options, startableDefinitions.length);
8435
- const nitroPreset = isRecord(options.nitro) && typeof options.nitro.preset === "string" ? options.nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOST || "";
8649
+ const nitroPreset = readNitroPreset(options.nitro);
8650
+ if (options.command === "build" && !internal.preliminary && keepsScheduleRunsInWorkerMemory(internal.resolvedNitroPreset ?? nitroPreset, Boolean(processRuntime), definitions.length + startableDefinitions.length)) reportViteHubHint(hints, scheduleErrorDiagnostics.SCHEDULE_RUNS_IN_WORKER_MEMORY());
8436
8651
  const standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
8437
- const vercelDefinitions = options.command === "build" && nitroPreset.startsWith("vercel") && (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options) ? definitions.filter((definition) => standaloneProviderSource === void 0 || definition.source === standaloneProviderSource) : [];
8652
+ const standaloneDefinitions = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options) ? definitions.filter((definition) => standaloneProviderSource === void 0 || definition.source === standaloneProviderSource) : [];
8653
+ const vercelDefinitions = options.command === "build" && nitroPreset.startsWith("vercel") ? standaloneDefinitions : [];
8438
8654
  if (!installNitroPlugin && !vercelDefinitions.length) return null;
8439
8655
  let nitro = options.nitro;
8440
8656
  if (vercelDefinitions.length) nitro = mergeNitroVercelCrons(nitro, vercelDefinitions, await readDefinitionCrons(vercelDefinitions, cronOverrides));
@@ -8445,13 +8661,14 @@ async function createScheduleNitroConfig(options = {}) {
8445
8661
  const timeZoneCrons = options.command === "build" ? readTimeZoneCrons(nitroDefinitions, cronOverrides) : {};
8446
8662
  const triggerCrons = Object.fromEntries([...nitroCrons].map(([name, cron]) => [name, cronWithWeekdayNames(cron)]));
8447
8663
  const crons = [...new Set(Object.values(triggerCrons))];
8448
- const netlifySchedules = [...nitroCrons].map(([name, cron]) => ({
8664
+ const hostSchedules = [...nitroCrons].map(([name, cron]) => ({
8449
8665
  cron,
8450
8666
  ...Object.hasOwn(timeZoneCrons, name) ? { inTimeZone: true } : {},
8451
8667
  name
8452
8668
  }));
8453
8669
  const nitroDefinitionNames = new Set(nitroDefinitions.map((definition) => definition.name));
8454
8670
  const staticDefinitions = definitions.filter((definition) => !nitroDefinitionNames.has(definition.name) && !(processRuntime && options.providerOutput === "standalone"));
8671
+ if (processRuntime) for (const definition of staticDefinitions) assertStaticScheduleCron(definition.handler);
8455
8672
  const processTimings = processRuntime && options.command === "build" ? Object.fromEntries(staticDefinitions.flatMap((definition) => {
8456
8673
  const timing = readStaticScheduleTiming(definition.handler);
8457
8674
  return timing ? [[definition.name, timing]] : [];
@@ -8478,11 +8695,13 @@ async function createScheduleNitroConfig(options = {}) {
8478
8695
  importBase: options.importBase,
8479
8696
  leaseDatabaseImport: internal.leaseDatabaseImport,
8480
8697
  memoryProcessStores: internal.memoryProcessStores,
8481
- netlifySchedules,
8698
+ hostSchedules,
8482
8699
  timeZoneCrons,
8483
8700
  processRuntime,
8484
8701
  ...processTimings ? { processTimings } : {},
8485
8702
  providerDefinitions: nitroDefinitions,
8703
+ ...retention ? { retention } : {},
8704
+ standaloneScheduleNames: standaloneDefinitions.map((definition) => definition.name),
8486
8705
  startableDefinitions,
8487
8706
  staticDefinitions,
8488
8707
  runtimeImport: options.runtimeImport
@@ -8535,6 +8754,15 @@ function hubSchedule(options = {}) {
8535
8754
  function createRegistryContents() {
8536
8755
  return renderScheduleRegistryModule(discoverRegistrySchedules());
8537
8756
  }
8757
+ async function writeRegistryTypes(roots, definitions) {
8758
+ const startable = discoverStartableScheduleDefinitions({
8759
+ contributions,
8760
+ rootDir: roots.viteRoot,
8761
+ serverDirs,
8762
+ serverRootDir: roots.projectRoot
8763
+ });
8764
+ await writeScheduleTypes(roots.projectRoot, definitions, startable, internalOptions.importBase);
8765
+ }
8538
8766
  const inspectable = {
8539
8767
  name: SCHEDULE_VITE_PLUGIN_NAME,
8540
8768
  enforce: "pre",
@@ -8549,6 +8777,7 @@ function hubSchedule(options = {}) {
8549
8777
  serverDirs,
8550
8778
  serverRootDir: roots.projectRoot
8551
8779
  });
8780
+ await writeRegistryTypes(roots, definitions);
8552
8781
  emitStandaloneProviderOutput = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options);
8553
8782
  standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
8554
8783
  const nitro = await createScheduleNitroConfig({
@@ -8574,6 +8803,7 @@ function hubSchedule(options = {}) {
8574
8803
  viteRoot = roots.viteRoot;
8575
8804
  contributions = await collectPluginScheduleContributions(config.plugins, roots);
8576
8805
  const definitions = discoverRegistrySchedules();
8806
+ await writeRegistryTypes(roots, definitions);
8577
8807
  emitStandaloneProviderOutput = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options);
8578
8808
  standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
8579
8809
  const storage = processStorageOptions((name) => hasVitePlugin(config.plugins, name));
@@ -8586,6 +8816,7 @@ function hubSchedule(options = {}) {
8586
8816
  nitroOwnsPaths: hasNitroConfigContext(config),
8587
8817
  ...storage,
8588
8818
  hints: config,
8819
+ resolvedNitroPreset: nitroPreset,
8589
8820
  root: config.root,
8590
8821
  serverDirs
8591
8822
  });
@@ -8593,21 +8824,42 @@ function hubSchedule(options = {}) {
8593
8824
  const configWithNitro = config;
8594
8825
  configWithNitro.nitro = nitro;
8595
8826
  }
8596
- } else if (command === "build" && typeof Reflect.get(config, "__vitehubNuxtHints") === "function" && options.runtime && !storage.leaseDatabaseImport) reportViteHubHint({
8597
- ...config,
8598
- command
8599
- }, scheduleErrorDiagnostics.SCHEDULE_PROCESS_CLAIMS_IN_MEMORY());
8827
+ } else if (command === "build" && typeof Reflect.get(config, "__vitehubNuxtHints") === "function") {
8828
+ if (options.runtime && !storage.leaseDatabaseImport) reportViteHubHint({
8829
+ ...config,
8830
+ command
8831
+ }, scheduleErrorDiagnostics.SCHEDULE_PROCESS_CLAIMS_IN_MEMORY());
8832
+ const startable = discoverStartableScheduleDefinitions({
8833
+ contributions,
8834
+ rootDir: roots.viteRoot,
8835
+ serverDirs,
8836
+ serverRootDir: roots.projectRoot
8837
+ });
8838
+ if (keepsScheduleRunsInWorkerMemory(readNitroPreset(config.nitro), Boolean(resolveProcessRuntimeOptions(options.runtime)), definitions.length + startable.length)) reportViteHubHint({
8839
+ ...config,
8840
+ command
8841
+ }, scheduleErrorDiagnostics.SCHEDULE_RUNS_IN_WORKER_MEMORY());
8842
+ }
8600
8843
  },
8601
8844
  configEnvironment(name, config) {
8602
8845
  if (!isServerEnvironment(name, config)) return;
8603
8846
  return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
8604
8847
  },
8605
- async handleHotUpdate(context) {
8848
+ hotUpdate(context) {
8606
8849
  const file = normalize(context.file).replace(/\\/g, "/");
8607
8850
  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)));
8608
8851
  const contributedSchedule = contributions.some((contribution) => normalize(contribution.definition.module).replace(/\\/g, "/") === file);
8609
8852
  if (!/\.schedule\.(?:c|m)?[jt]s$/i.test(file) && !serverSchedule && !contributedSchedule) return;
8610
- invalidateScheduleRegistry(context.server);
8853
+ const environment = this.environment;
8854
+ const registry = environment.moduleGraph.getModuleById(RESOLVED_SCHEDULE_REGISTRY_ID);
8855
+ if (registry) {
8856
+ environment.moduleGraph.invalidateModule(registry);
8857
+ if (environment.config.consumer === "server") environment.hot.send({ type: "full-reload" });
8858
+ }
8859
+ if (projectRoot && viteRoot) return writeRegistryTypes({
8860
+ projectRoot,
8861
+ viteRoot
8862
+ }, discoverRegistrySchedules());
8611
8863
  },
8612
8864
  resolveId: {
8613
8865
  filter: { id: /^#vitehub\/schedule\/registry$/ },
@@ -8618,7 +8870,13 @@ function hubSchedule(options = {}) {
8618
8870
  transform: {
8619
8871
  filter: { code: /\/\* @vitehub-schedule-registry \*\// },
8620
8872
  handler(code) {
8621
- return code.replace(/\/\* @vite-ignore \*\/\s*\/\* @vitehub-schedule-registry \*\/\s*[\w$]+/g, JSON.stringify(SCHEDULE_REGISTRY_ID));
8873
+ const output = new MagicString(code);
8874
+ for (const match of code.matchAll(scheduleRegistryImport)) output.overwrite(match.index, match.index + match[0].length, JSON.stringify(SCHEDULE_REGISTRY_ID));
8875
+ if (!output.hasChanged()) return;
8876
+ return {
8877
+ code: output.toString(),
8878
+ map: output.generateMap({ hires: "boundary" })
8879
+ };
8622
8880
  }
8623
8881
  },
8624
8882
  load: {
@@ -8660,6 +8918,7 @@ function hubSchedule(options = {}) {
8660
8918
  ...workflow?.bundleAlias
8661
8919
  };
8662
8920
  const retainedSources = bundles ? await retainProviderOutputSources({
8921
+ aliases,
8663
8922
  artifactDir: resolve(contributionArtifactDir, "sources"),
8664
8923
  paths: [...definitions.map((definition) => definition.handler), ...providerOutputAliasSources(aliases, [rootDir])],
8665
8924
  roots: [rootDir]
@@ -8676,7 +8935,7 @@ function hubSchedule(options = {}) {
8676
8935
  "@vitejs/devtools-rolldown"
8677
8936
  ] : void 0;
8678
8937
  contributeProviderDeploymentOutput(providerOutput, {
8679
- discard: async () => await removeProviderOutputArtifactDir(contributionArtifactDir),
8938
+ discard: async (failure) => await removeProviderOutputArtifactDir(contributionArtifactDir, failure),
8680
8939
  owner: "schedule",
8681
8940
  rootDir,
8682
8941
  write: async ({ signal }) => {
@@ -8703,7 +8962,7 @@ function hubSchedule(options = {}) {
8703
8962
  }
8704
8963
  }, providerOutputGenerations.get(this));
8705
8964
  } catch (error) {
8706
- if (artifactDir) await removeProviderOutputArtifactDir(artifactDir);
8965
+ if (artifactDir) await removeProviderOutputArtifactDir(artifactDir, error);
8707
8966
  await providerOutputGenerations.reset(this, providerOutput, error);
8708
8967
  throw error;
8709
8968
  }