@vite-hub/schedule 0.6.1 → 0.8.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 (44) hide show
  1. package/README.md +30 -9
  2. package/dist/cron-D0mqg3ql.js +22 -0
  3. package/dist/definition.d.ts +1 -1
  4. package/dist/definition.js +4 -5
  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-DHApCpbQ.js} +8 -35
  9. package/dist/index.d.ts +16 -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/{object-CAK6UYR5.js → object-DNOrQSl5.js} +5 -1
  14. package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-Blwi3jQF.d.ts} +1 -0
  15. package/dist/{operations-BTUQeba1.js → operations-Bog78pOZ.js} +33 -14
  16. package/dist/operations.d.ts +2 -2
  17. package/dist/operations.js +8 -6
  18. package/dist/os.js +3 -3
  19. package/dist/runtime/console.js +25 -11
  20. package/dist/runtime/kv.d.ts +1 -1
  21. package/dist/runtime/kv.js +1 -1
  22. package/dist/runtime/process.d.ts +1 -1
  23. package/dist/runtime/process.js +41 -22
  24. package/dist/runtime/state.d.ts +2 -2
  25. package/dist/runtime/state.js +1 -1
  26. package/dist/runtime/static.d.ts +1 -1
  27. package/dist/runtime/static.js +2 -2
  28. package/dist/runtime.d.ts +6 -6
  29. package/dist/runtime.js +5 -5
  30. package/dist/{started-B1Se_Iwo.js → started-Ck0Wu5Oc.js} +55 -10
  31. package/dist/{started-Bzvr4t5f.js → started-adRbWkWd.js} +7 -5
  32. package/dist/started-errors-D6CnKMqD.js +32 -0
  33. package/dist/state-BoDrff6R.js +586 -0
  34. package/dist/{state-BDEDVlyr.d.ts → state-CRQQfd8h.d.ts} +24 -5
  35. package/dist/{static-DeRvJqcQ.d.ts → static-BFV4x94g.d.ts} +1 -1
  36. package/dist/{static-Bg7Jj92L.js → static-D4nN8HTx.js} +8 -6
  37. package/dist/{store-CEv3cScg.d.ts → store-TOayO0NL.d.ts} +6 -3
  38. package/dist/{types-DTVPVY5O.d.ts → types-Wllh0U8N.d.ts} +35 -4
  39. package/dist/vite.d.ts +4 -2
  40. package/dist/vite.js +561 -187
  41. package/package.json +11 -4
  42. package/dist/started-name-w6n9uDdt.js +0 -4
  43. package/dist/state-BZLy46UJ.js +0 -427
  44. package/dist/{cron-BT3ef48f.js → cron-imqlBgO-.js} +1 -1
@@ -1,5 +1,5 @@
1
- import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
2
- import { t as internalErrorDiagnostics } from "./error-diagnostics-kKXseq8d.js";
1
+ import { r as isRecordOrFunction } from "./object-DNOrQSl5.js";
2
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-CsiNo_oI.js";
3
3
  import { toJsonSchema } from "@valibot/to-json-schema";
4
4
  import * as v from "valibot";
5
5
  // ../internal/src/standard-schema.ts
@@ -139,18 +139,20 @@ function table(rows) {
139
139
  return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" ")).join("\n");
140
140
  }
141
141
  // src/operations.ts
142
- const runtime = () => import("./operations-BTUQeba1.js");
142
+ const runtime = () => import("./operations-Bog78pOZ.js");
143
143
  const id = v.pipe(v.string(), v.minLength(1));
144
144
  function formatRuns({ runs }) {
145
145
  if (runs.length === 0) return "No runs.\n";
146
146
  return `${table([[
147
147
  "RUN",
148
+ "SCHEDULE",
148
149
  "STATUS",
149
150
  "SCHEDULED AT",
150
151
  "ATTEMPTS",
151
152
  "ERROR"
152
153
  ], ...runs.map((run) => [
153
154
  run.id,
155
+ run.scheduleId,
154
156
  run.status,
155
157
  run.scheduledAt,
156
158
  String(run.attemptCount),
@@ -195,9 +197,9 @@ const runs = defineScheduleOperation({
195
197
  namespace: "schedule",
196
198
  positional: ["id"]
197
199
  },
198
- description: "List the recorded runs of one Schedule Definition, newest first.",
200
+ description: "List the recorded Schedule Runs, newest first. Pass `id`, a Schedule Definition name or a started Schedule id, to list the runs of one Schedule.",
199
201
  input: v.object({
200
- id,
202
+ id: v.optional(id),
201
203
  limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(100)))
202
204
  }),
203
205
  kind: "read",
@@ -224,7 +226,7 @@ const run = defineScheduleOperation({
224
226
  namespace: "schedule",
225
227
  positional: ["name"]
226
228
  },
227
- description: "Run a Static Schedule Definition now. The definition must set `manual: true`. `at` runs it as if the cron fired at that ISO 8601 date-time.",
229
+ description: "Run a Static Schedule Definition now, unless it sets `manual: false`. `at` runs it as if the cron fired at that ISO 8601 date-time.",
228
230
  input: v.object({
229
231
  at: v.optional(v.string()),
230
232
  name: id
package/dist/os.js CHANGED
@@ -1,7 +1,7 @@
1
- import { t as isRecord } from "./object-CAK6UYR5.js";
1
+ import { n as isRecord } from "./object-DNOrQSl5.js";
2
2
  import { t as isIanaTimeZone } from "./time-zone-pMp_g8Uu.js";
3
- import { a as parseCronFields, c as timesOfDay, i as isWeekdayRestricted, n as isDayRestricted, o as range, r as isMonthRestricted, s as runsEveryDay, t as arithmeticStep, u as invariantError } from "./cron-BT3ef48f.js";
4
- import { i as timeZoneOffsetMinutes } from "./due-D-0trD1g.js";
3
+ import { a as parseCronFields, c as timesOfDay, i as isWeekdayRestricted, n as isDayRestricted, o as range, r as isMonthRestricted, s as runsEveryDay, t as arithmeticStep, u as invariantError } from "./cron-imqlBgO-.js";
4
+ import { i as timeZoneOffsetMinutes } from "./due-DXgXKgzg.js";
5
5
  import { defineErrors } from "@vite-hub/runtime";
6
6
  import { homedir, userInfo } from "node:os";
7
7
  import { basename, dirname, join, posix, win32 } from "node:path";
@@ -1,5 +1,7 @@
1
- import { n as getProcessScheduleDefinitions, o as getStartedScheduleRuntime } from "../state-BZLy46UJ.js";
1
+ import { g as waitForProcessScheduleRuntime, n as getProcessScheduleDefinitions, o as getStartedScheduleRuntime } from "../state-BoDrff6R.js";
2
+ import { o as resolveManualSchedule } from "../execute-DHApCpbQ.js";
2
3
  // src/runtime/console.ts
4
+ const consoleSchedulesKey = Symbol.for("vitehub.console.schedules");
3
5
  /** The Cron column of the Console: the cron, with the time zone when it is not UTC. */
4
6
  function scheduleConsoleTiming(cron, timeZone) {
5
7
  return timeZone === "UTC" ? cron : `${cron} (${timeZone})`;
@@ -59,23 +61,35 @@ function startedScheduleRecord(schedule) {
59
61
  * build checked.
60
62
  */
61
63
  async function readScheduleConsoleRecords() {
62
- const records = [...getProcessScheduleDefinitions() ?? []].flatMap(([name, definition]) => {
63
- if (definition.cron === void 0) return [];
64
- const timeZone = definition.timeZone ?? "UTC";
65
- return [{
64
+ await waitForProcessScheduleRuntime();
65
+ const registry = Reflect.get(globalThis, consoleSchedulesKey) ?? {};
66
+ const definitions = getProcessScheduleDefinitions();
67
+ const candidates = await Promise.all(Object.keys(registry).map((name) => resolveManualSchedule(registry, name).then(() => name, () => void 0)));
68
+ const runnable = new Set(candidates.filter((name) => name !== void 0));
69
+ const records = [.../* @__PURE__ */ new Set([...definitions?.keys() ?? [], ...runnable])].map((name) => {
70
+ const definition = definitions?.get(name);
71
+ const timeZone = definition?.timeZone ?? "UTC";
72
+ const cron = definition?.cron;
73
+ const canRun = runnable.has(name);
74
+ return {
66
75
  cells: {
76
+ ...canRun ? { manual: "Enabled" } : {},
67
77
  schedule: name,
68
- timing: scheduleConsoleTiming(definition.cron, timeZone)
78
+ ...cron === void 0 ? {} : { timing: scheduleConsoleTiming(cron, timeZone) }
69
79
  },
70
- fields: [{
80
+ fields: [...cron === void 0 ? [] : [{
71
81
  label: "Cron",
72
- value: definition.cron
82
+ value: cron
73
83
  }, {
74
84
  label: "Time zone",
75
85
  value: timeZone
76
- }],
77
- id: `definition:${name}`
78
- }];
86
+ }], ...canRun ? [{
87
+ label: "Manual",
88
+ value: "Enabled"
89
+ }] : []],
90
+ id: `definition:${name}`,
91
+ ...canRun ? { runnable: true } : {}
92
+ };
79
93
  });
80
94
  const started = getStartedScheduleRuntime();
81
95
  if (!started) return records;
@@ -1,2 +1,2 @@
1
- import { t as ScheduleKVStorage } from "../kv-storage-hI2IOjb5.js";
1
+ import { n as ScheduleKVStorage } from "../kv-storage-CKSSQ6Fk.js";
2
2
  export declare const scheduleKVStorage: ScheduleKVStorage;
@@ -1,4 +1,4 @@
1
- import { t as createScheduleKVStorage } from "../kv-storage-Dsr3TL9c.js";
1
+ import { t as createScheduleKVStorage } from "../kv-storage-CszEkof6.js";
2
2
  import * as kvPackage from "@vite-hub/kv";
3
3
  // src/runtime/kv.ts
4
4
  const scheduleKVStorage = createScheduleKVStorage(kvPackage.kv);
@@ -1,4 +1,4 @@
1
- import { a as ScheduleDefinitionRegistry, g as ScheduleRunStore } from "../types-DTVPVY5O.js";
1
+ import { b as ScheduleRunStore, o as ScheduleDefinitionRegistry } from "../types-Wllh0U8N.js";
2
2
  import { LeaseStore } from "@vite-hub/runtime";
3
3
  import { onShutdown } from "@vite-hub/runtime/internal/shutdown";
4
4
  export interface ProcessScheduleRuntimeOptions {
@@ -1,10 +1,11 @@
1
- import { n as isRecordOrFunction } from "../object-CAK6UYR5.js";
2
- import { n as isScheduleDue } from "../due-D-0trD1g.js";
3
- import { t as scheduleErrorDiagnostics } from "../error-diagnostics-B1AaIGWP.js";
4
- import { S as createScheduleError, b as scheduleIdempotencyKey, c as markLoggedScheduleError } from "../static-Bg7Jj92L.js";
5
- import { a as executeStaticSchedule, l as toRunId } from "../started-errors-IG9DlT2A.js";
6
- import { i as runStartedSchedules } from "../started-Bzvr4t5f.js";
7
- import { a as getScheduleRuntimeRegistry, c as registerProcessScheduleDefinitions, d as setScheduleOccurrenceClaims, f as setScheduleRunStore, i as getScheduleRunStore, p as setScheduleRuntimeRegistry, r as getScheduleOccurrenceClaims } from "../state-BZLy46UJ.js";
1
+ import { r as isRecordOrFunction } from "../object-DNOrQSl5.js";
2
+ import { C as createScheduleError, _ as emitLogEvent, c as markLoggedScheduleError, x as scheduleIdempotencyKey } from "../static-D4nN8HTx.js";
3
+ import { n as parseScheduleCronExpression } from "../cron-D0mqg3ql.js";
4
+ import { n as isScheduleDue } from "../due-DXgXKgzg.js";
5
+ import { t as scheduleErrorDiagnostics } from "../error-diagnostics-KvK9MX6w.js";
6
+ import { c as toRunId, i as executeStaticSchedule } from "../execute-DHApCpbQ.js";
7
+ import { i as runStartedSchedules } from "../started-adRbWkWd.js";
8
+ import { a as getScheduleRuntimeRegistry, c as registerProcessScheduleDefinitions, d as setProcessScheduleRuntimeInstallation, f as setScheduleOccurrenceClaims, i as getScheduleRunStore, m as setScheduleRuntimeRegistry, p as setScheduleRunStore, r as getScheduleOccurrenceClaims } from "../state-BoDrff6R.js";
8
9
  import { createMemoryLeaseStore, getInstanceId } from "@vite-hub/runtime";
9
10
  import { onShutdown } from "@vite-hub/runtime/internal/shutdown";
10
11
  // src/internal/process-wake-runtime.ts
@@ -240,26 +241,26 @@ function createOccurrenceClaims(options) {
240
241
  const ttl = options.ttlMs / 1e3;
241
242
  const doneTtl = options.doneTtlMs / 1e3;
242
243
  const owner = options.owner === void 0 ? {} : { owner: options.owner };
243
- return { async run(runId, run) {
244
+ return { async run(runId, run, runOptions) {
244
245
  const [acquireError, lease] = await options.leases.acquire(occurrenceLeaseKey(runId, options.prefix), {
245
246
  ttl,
246
247
  ...owner
247
248
  });
248
249
  if (acquireError) throw acquireError;
249
250
  if (!lease) return "held";
251
+ const stop = keepAlive(lease, options.ttlMs, options.reportError);
250
252
  let release = true;
251
253
  try {
252
254
  const [doneError, done] = await options.leases.get(occurrenceDoneKey(runId, options.prefix));
253
255
  if (doneError) throw doneError;
254
256
  if (done) return "done";
255
- const stop = keepAlive(lease, options.ttlMs, options.reportError);
257
+ if (runOptions?.scheduledAt && (options.now?.() ?? /* @__PURE__ */ new Date()).getTime() >= runOptions.scheduledAt.getTime() + options.doneTtlMs) return "late";
256
258
  let final = false;
257
259
  try {
258
260
  await run(() => {
259
261
  final = true;
260
262
  });
261
263
  } finally {
262
- await stop();
263
264
  if (final) {
264
265
  const [markError, marked] = await options.leases.acquire(occurrenceDoneKey(runId, options.prefix), {
265
266
  ttl: doneTtl,
@@ -267,6 +268,7 @@ function createOccurrenceClaims(options) {
267
268
  });
268
269
  if (markError) {
269
270
  release = false;
271
+ await stop();
270
272
  options.reportError(markError);
271
273
  const [renewError, renewed] = await lease.renew({ ttl: doneTtl });
272
274
  if (renewError) options.reportError(renewError);
@@ -276,6 +278,7 @@ function createOccurrenceClaims(options) {
276
278
  }
277
279
  return "ran";
278
280
  } finally {
281
+ await stop();
279
282
  if (release) {
280
283
  const [releaseError] = await lease.release();
281
284
  if (releaseError) options.reportError(releaseError);
@@ -316,6 +319,7 @@ async function loadStaticDefinitions(registry, timings = {}) {
316
319
  };
317
320
  const definition = unwrapDefinition(await load());
318
321
  if (!definition) return void 0;
322
+ parseScheduleCronExpression(definition.cron, `Schedule "${name}"`);
319
323
  return {
320
324
  cron: definition.cron,
321
325
  definition: async () => definition,
@@ -353,7 +357,25 @@ function resolveLeaseTtlMs(value) {
353
357
  * checked, within `catchUpMs`, for Schedules with a prior cron-triggered run or indeterminate legacy history.
354
358
  * Processes that share `leases` run each occurrence once between them. Call `close()` during host shutdown.
355
359
  */
356
- async function installProcessScheduleRuntime(options) {
360
+ function installProcessScheduleRuntime(options) {
361
+ const startedAt = performance.now();
362
+ const installation = installRuntime(options);
363
+ setProcessScheduleRuntimeInstallation(installation);
364
+ installation.then(() => {
365
+ const ms = Math.round(performance.now() - startedAt);
366
+ if (!emitLogEvent({
367
+ field: "schedule",
368
+ fields: {
369
+ op: "install",
370
+ ms
371
+ },
372
+ level: "info",
373
+ message: "Schedule runtime installed"
374
+ })) console.info(`[vitehub:schedule] runtime installed in ${ms} ms`);
375
+ }, () => {});
376
+ return installation;
377
+ }
378
+ async function installRuntime(options) {
357
379
  const previousRegistry = getScheduleRuntimeRegistry();
358
380
  const previousScheduleRunStore = getScheduleRunStore();
359
381
  const previousClaims = getScheduleOccurrenceClaims();
@@ -363,6 +385,7 @@ async function installProcessScheduleRuntime(options) {
363
385
  const claims = createOccurrenceClaims({
364
386
  doneTtlMs: catchUpMs + leaseTtlMs + 2 * minuteMs,
365
387
  leases: options.leases ?? createMemoryLeaseStore(),
388
+ now: options.now,
366
389
  owner: getInstanceId(),
367
390
  prefix: options.prefix,
368
391
  reportError,
@@ -427,7 +450,7 @@ async function installProcessScheduleRuntime(options) {
427
450
  },
428
451
  scheduledAt: input.scheduledAt,
429
452
  waitUntil
430
- })) === "held") held.set(runId, {
453
+ }), { scheduledAt: input.scheduledAt }) === "held") held.set(runId, {
431
454
  scheduleId: input.scheduleId,
432
455
  scheduledAt: input.scheduledAt,
433
456
  startBy: input.scheduledAt.getTime() + catchUpMs + leaseTtlMs + minuteMs
@@ -452,16 +475,12 @@ async function installProcessScheduleRuntime(options) {
452
475
  const currentMinute = Math.floor((options.now?.() ?? /* @__PURE__ */ new Date()).getTime() / minuteMs) * minuteMs;
453
476
  const since = currentMinute - catchUpMs;
454
477
  for (const entry of definitions.values()) try {
455
- let due = 0;
456
- for (let minute = Math.ceil(since / minuteMs) * minuteMs; minute <= currentMinute; minute += minuteMs) if (isScheduleDue(scheduleCronRecord(entry), new Date(minute))) due++;
457
- if (due === 0) continue;
458
- const runs = await options.scheduleRunStore.listRuns({
459
- idPrefix: "srun_static_",
460
- limit: due,
461
- scheduleId: entry.name
462
- });
463
- for (const run of runs) {
464
- if (run.scheduledAt.getTime() < since) continue;
478
+ const cron = scheduleCronRecord(entry);
479
+ for (let minute = currentMinute - minuteMs; minute >= since; minute -= minuteMs) {
480
+ const scheduledAt = new Date(minute);
481
+ if (!isScheduleDue(cron, scheduledAt)) continue;
482
+ const run = await options.scheduleRunStore.getRun(toRunId("static", entry.name, scheduledAt));
483
+ if (!run) continue;
465
484
  if (run.status !== "pending" && run.status !== "running") continue;
466
485
  held.set(run.id, {
467
486
  scheduleId: entry.name,
@@ -1,2 +1,2 @@
1
- import { a as getScheduleRunStore, c as loadScheduleDefinition, d as setHostScheduleInventory, f as setScheduleOccurrenceClaims, h as setStartedScheduleRuntime, i as getScheduleOccurrenceClaims, l as registerProcessScheduleDefinitions, m as setScheduleRuntimeRegistry, n as getHostScheduleInventory, o as getScheduleRuntimeRegistry, p as setScheduleRunStore, r as getProcessScheduleDefinitions, s as getStartedScheduleRuntime, t as StartedScheduleRuntime, u as resetScheduleRuntime } from "../state-BDEDVlyr.js";
2
- export { StartedScheduleRuntime, getHostScheduleInventory, getProcessScheduleDefinitions, getScheduleOccurrenceClaims, getScheduleRunStore, getScheduleRuntimeRegistry, getStartedScheduleRuntime, loadScheduleDefinition, registerProcessScheduleDefinitions, resetScheduleRuntime, setHostScheduleInventory, setScheduleOccurrenceClaims, setScheduleRunStore, setScheduleRuntimeRegistry, setStartedScheduleRuntime };
1
+ import { _ as waitForProcessScheduleRuntime, a as getScheduleRunStore, c as loadScheduleDefinition, d as setHostScheduleInventory, f as setProcessScheduleRuntimeInstallation, g as setStartedScheduleRuntime, h as setScheduleRuntimeRegistry, i as getScheduleOccurrenceClaims, l as registerProcessScheduleDefinitions, m as setScheduleRunStore, n as getHostScheduleInventory, o as getScheduleRuntimeRegistry, p as setScheduleOccurrenceClaims, r as getProcessScheduleDefinitions, s as getStartedScheduleRuntime, t as StartedScheduleRuntime, u as resetScheduleRuntime } from "../state-CRQQfd8h.js";
2
+ export { StartedScheduleRuntime, getHostScheduleInventory, getProcessScheduleDefinitions, getScheduleOccurrenceClaims, getScheduleRunStore, getScheduleRuntimeRegistry, getStartedScheduleRuntime, loadScheduleDefinition, registerProcessScheduleDefinitions, resetScheduleRuntime, setHostScheduleInventory, setProcessScheduleRuntimeInstallation, setScheduleOccurrenceClaims, setScheduleRunStore, setScheduleRuntimeRegistry, setStartedScheduleRuntime, waitForProcessScheduleRuntime };
@@ -1 +1 @@
1
- export { t as getHostScheduleInventory, n as getProcessScheduleDefinitions, r as getScheduleOccurrenceClaims, i as getScheduleRunStore, a as getScheduleRuntimeRegistry, o as getStartedScheduleRuntime, s as loadScheduleDefinition, c as registerProcessScheduleDefinitions, l as resetScheduleRuntime, u as setHostScheduleInventory, d as setScheduleOccurrenceClaims, f as setScheduleRunStore, p as setScheduleRuntimeRegistry, m as setStartedScheduleRuntime } from "../state-BZLy46UJ.js";
1
+ export { t as getHostScheduleInventory, n as getProcessScheduleDefinitions, r as getScheduleOccurrenceClaims, i as getScheduleRunStore, a as getScheduleRuntimeRegistry, o as getStartedScheduleRuntime, s as loadScheduleDefinition, c as registerProcessScheduleDefinitions, l as resetScheduleRuntime, u as setHostScheduleInventory, d as setProcessScheduleRuntimeInstallation, f as setScheduleOccurrenceClaims, p as setScheduleRunStore, m as setScheduleRuntimeRegistry, h as setStartedScheduleRuntime, g as waitForProcessScheduleRuntime } from "../state-BoDrff6R.js";
@@ -1,2 +1,2 @@
1
- import { _ as unwrapScheduleDefinition, a as createStaticScheduleRun, c as executeStaticSchedule, d as logScheduleRuntimeError, f as markLoggedScheduleError, g as scheduledWakeTime, h as normalizeScheduleRuntimeError, i as StaticScheduleRun, l as isScheduleCronAuthorized, m as normalizeCron, n as ExecuteMatchingStaticSchedulesOptions, o as executeCloudflareStaticSchedules, p as missingScheduleDefinitionError, r as ExecuteStaticScheduleOptions, s as executeMatchingStaticSchedules, t as ExecuteCloudflareStaticSchedulesOptions, u as isTimeZoneWakeDue, v as cronWithWeekdayNames } from "../static-DeRvJqcQ.js";
1
+ import { _ as unwrapScheduleDefinition, a as createStaticScheduleRun, c as executeStaticSchedule, d as logScheduleRuntimeError, f as markLoggedScheduleError, g as scheduledWakeTime, h as normalizeScheduleRuntimeError, i as StaticScheduleRun, l as isScheduleCronAuthorized, m as normalizeCron, n as ExecuteMatchingStaticSchedulesOptions, o as executeCloudflareStaticSchedules, p as missingScheduleDefinitionError, r as ExecuteStaticScheduleOptions, s as executeMatchingStaticSchedules, t as ExecuteCloudflareStaticSchedulesOptions, u as isTimeZoneWakeDue, v as cronWithWeekdayNames } from "../static-BFV4x94g.js";
2
2
  export { ExecuteCloudflareStaticSchedulesOptions, ExecuteMatchingStaticSchedulesOptions, ExecuteStaticScheduleOptions, StaticScheduleRun, createStaticScheduleRun, cronWithWeekdayNames, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule, isScheduleCronAuthorized, isTimeZoneWakeDue, logScheduleRuntimeError, markLoggedScheduleError, missingScheduleDefinitionError, normalizeCron, normalizeScheduleRuntimeError, scheduledWakeTime, unwrapScheduleDefinition };
@@ -1,3 +1,3 @@
1
- import { a as isScheduleCronAuthorized, c as markLoggedScheduleError, d as normalizeScheduleRuntimeError, f as scheduledWakeTime, i as executeStaticSchedule, l as missingScheduleDefinitionError, n as executeCloudflareStaticSchedules, o as isTimeZoneWakeDue, p as unwrapScheduleDefinition, r as executeMatchingStaticSchedules, s as logScheduleRuntimeError, t as createStaticScheduleRun, u as normalizeCron } from "../static-Bg7Jj92L.js";
2
- import { t as cronWithWeekdayNames } from "../due-D-0trD1g.js";
1
+ import { a as isScheduleCronAuthorized, c as markLoggedScheduleError, d as normalizeScheduleRuntimeError, f as scheduledWakeTime, i as executeStaticSchedule, l as missingScheduleDefinitionError, n as executeCloudflareStaticSchedules, o as isTimeZoneWakeDue, p as unwrapScheduleDefinition, r as executeMatchingStaticSchedules, s as logScheduleRuntimeError, t as createStaticScheduleRun, u as normalizeCron } from "../static-D4nN8HTx.js";
2
+ import { t as cronWithWeekdayNames } from "../due-DXgXKgzg.js";
3
3
  export { createStaticScheduleRun, cronWithWeekdayNames, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule, isScheduleCronAuthorized, isTimeZoneWakeDue, logScheduleRuntimeError, markLoggedScheduleError, missingScheduleDefinitionError, normalizeCron, normalizeScheduleRuntimeError, scheduledWakeTime, unwrapScheduleDefinition };
package/dist/runtime.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  /// <reference path="./registry-module.d.ts" />
2
- import { a as createScheduleRun, c as runScheduleFrom, n as createKVScheduleRunStore, o as executeSchedule, r as createMemoryScheduleRunStore, s as executeStaticSchedule, t as KVScheduleStoreOptions } from "./store-CEv3cScg.js";
3
- import { _ as unwrapScheduleDefinition, m as normalizeCron } from "./static-DeRvJqcQ.js";
4
- import { n as createScheduleKVStorage, t as ScheduleKVStorage } from "./kv-storage-hI2IOjb5.js";
5
- import { a as ScheduleDefinitionRegistry, b as StartedScheduleStore, c as ScheduleRunAttemptRecord, f as ScheduleRunListOptions, g as ScheduleRunStore, i as ScheduleDefinitionOptions, n as ScheduleDefinition, o as ScheduleHandler, p as ScheduleRunRecord, s as ScheduleRegistryDefinition, u as ScheduleRunContext } from "./types-DTVPVY5O.js";
6
- import { a as getScheduleRunStore, p as setScheduleRunStore, u as resetScheduleRuntime } from "./state-BDEDVlyr.js";
2
+ import { a as createScheduleRun, c as runScheduleFrom, n as createKVScheduleRunStore, o as executeSchedule, r as createMemoryScheduleRunStore, s as executeStaticSchedule, t as KVScheduleStoreOptions } from "./store-TOayO0NL.js";
3
+ import { _ as unwrapScheduleDefinition, m as normalizeCron } from "./static-BFV4x94g.js";
4
+ import { n as ScheduleKVStorage, r as createScheduleKVStorage, t as ScheduleKVSetOptions } from "./kv-storage-CKSSQ6Fk.js";
5
+ import { E as StartedScheduleStore, _ as ScheduleRunRecord, a as ScheduleDefinitionOptions, b as ScheduleRunStore, f as ScheduleRunAttemptRecord, g as ScheduleRunListOptions, m as ScheduleRunContext, o as ScheduleDefinitionRegistry, r as ScheduleDefinition, s as ScheduleHandler, u as ScheduleRegistryDefinition } from "./types-Wllh0U8N.js";
6
+ import { a as getScheduleRunStore, m as setScheduleRunStore, u as resetScheduleRuntime } from "./state-CRQQfd8h.js";
7
7
  interface InstallStartedSchedulesOptions {
8
8
  /**
9
9
  * How far back, in milliseconds, the first tick after a start runs cron minutes that no tick checked. Use it only with
@@ -34,4 +34,4 @@ export declare function createKVStartedScheduleStore(options: KVStartedScheduleS
34
34
  * that started Schedule and logged; it does not fail the tick.
35
35
  */
36
36
  export declare function runStartedSchedules(context: ScheduleRunContext): Promise<void>;
37
- export { type InstallStartedSchedulesOptions, type KVScheduleStoreOptions, type KVStartedScheduleStoreOptions, type ScheduleDefinition, type ScheduleDefinitionOptions, type ScheduleDefinitionRegistry, type ScheduleHandler, type ScheduleKVStorage, type ScheduleRegistryDefinition, type ScheduleRunAttemptRecord, type ScheduleRunContext, type ScheduleRunListOptions, type ScheduleRunRecord, type ScheduleRunStore, createKVScheduleRunStore, createMemoryScheduleRunStore, createScheduleKVStorage, createScheduleRun, executeSchedule, executeStaticSchedule, getScheduleRunStore, normalizeCron, resetScheduleRuntime, runScheduleFrom, setScheduleRunStore, unwrapScheduleDefinition };
37
+ export { type InstallStartedSchedulesOptions, type KVScheduleStoreOptions, type KVStartedScheduleStoreOptions, type ScheduleDefinition, type ScheduleDefinitionOptions, type ScheduleDefinitionRegistry, type ScheduleHandler, type ScheduleKVSetOptions, type ScheduleKVStorage, type ScheduleRegistryDefinition, type ScheduleRunAttemptRecord, type ScheduleRunContext, type ScheduleRunListOptions, type ScheduleRunRecord, type ScheduleRunStore, createKVScheduleRunStore, createMemoryScheduleRunStore, createScheduleKVStorage, createScheduleRun, executeSchedule, executeStaticSchedule, getScheduleRunStore, normalizeCron, resetScheduleRuntime, runScheduleFrom, setScheduleRunStore, unwrapScheduleDefinition };
package/dist/runtime.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as executeStaticSchedule, c as runScheduleFrom, i as executeSchedule, n as createScheduleRun } from "./started-errors-IG9DlT2A.js";
2
- import { p as unwrapScheduleDefinition, u as normalizeCron } from "./static-Bg7Jj92L.js";
3
- import { t as createScheduleKVStorage } from "./kv-storage-Dsr3TL9c.js";
4
- import { f as setScheduleRunStore, g as createMemoryScheduleRunStore, h as createKVScheduleRunStore, i as getScheduleRunStore, l as resetScheduleRuntime } from "./state-BZLy46UJ.js";
5
- import { i as runStartedSchedules, n as createMemoryStartedScheduleStore, r as installStartedSchedules, t as createKVStartedScheduleStore } from "./started-Bzvr4t5f.js";
1
+ import { i as executeStaticSchedule, r as executeSchedule, s as runScheduleFrom, t as createScheduleRun } from "./execute-DHApCpbQ.js";
2
+ import { p as unwrapScheduleDefinition, u as normalizeCron } from "./static-D4nN8HTx.js";
3
+ import { t as createScheduleKVStorage } from "./kv-storage-CszEkof6.js";
4
+ import { i as getScheduleRunStore, l as resetScheduleRuntime, p as setScheduleRunStore, v as createKVScheduleRunStore, y as createMemoryScheduleRunStore } from "./state-BoDrff6R.js";
5
+ import { i as runStartedSchedules, n as createMemoryStartedScheduleStore, r as installStartedSchedules, t as createKVStartedScheduleStore } from "./started-adRbWkWd.js";
6
6
  export { createKVScheduleRunStore, createKVStartedScheduleStore, createMemoryScheduleRunStore, createMemoryStartedScheduleStore, createScheduleKVStorage, createScheduleRun, executeSchedule, executeStaticSchedule, getScheduleRunStore, installStartedSchedules, normalizeCron, resetScheduleRuntime, runScheduleFrom, runStartedSchedules, setScheduleRunStore, unwrapScheduleDefinition };
@@ -1,9 +1,54 @@
1
- import { t as startedScheduleErrors, u as randomId } from "./started-errors-IG9DlT2A.js";
2
1
  import { t as isIanaTimeZone } from "./time-zone-pMp_g8Uu.js";
3
- import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
4
- import { y as parseScheduledAt } from "./static-Bg7Jj92L.js";
5
- import { o as getStartedScheduleRuntime } from "./state-BZLy46UJ.js";
2
+ import { r as isRecordOrFunction } from "./object-DNOrQSl5.js";
3
+ import { C as createScheduleError, b as parseScheduledAt } from "./static-D4nN8HTx.js";
4
+ import { l as randomId, n as executeManualSchedule, o as resolveManualSchedule } from "./execute-DHApCpbQ.js";
5
+ import { g as waitForProcessScheduleRuntime, o as getStartedScheduleRuntime } from "./state-BoDrff6R.js";
6
+ import { t as startedScheduleErrors } from "./started-errors-D6CnKMqD.js";
6
7
  import { parseCronExpression } from "cron-schedule";
8
+ import { defineErrors } from "@vite-hub/runtime";
9
+ // src/run-errors.ts
10
+ const runScheduleErrors = /*#__PURE__*/ defineErrors({
11
+ docs: "https://vitehub.dev/docs/schedule/diagnostics",
12
+ codes: {
13
+ SCHEDULE_INVALID_SCHEDULED_AT: {
14
+ why: "`runSchedule()` got a `scheduledAt` that is not a valid date-time.",
15
+ fix: "Pass a valid `Date`, or an ISO 8601 date-time with `Z` or an offset, such as `2026-01-31T23:59:00Z`. Leave it out to run as of now."
16
+ },
17
+ SCHEDULE_RUN_STORE_FAILED: {
18
+ why: "The store of Schedule Runs failed, so the run did not start or its record is incomplete. `error.cause` has the store error.",
19
+ fix: "Check that the Schedule run store is reachable from this server. Before retrying, confirm that the handler did not already run or that it is safe to repeat."
20
+ }
21
+ }
22
+ });
23
+ // src/run.ts
24
+ const registryModule = "#vitehub/schedule/registry";
25
+ async function loadScheduleRegistry() {
26
+ try {
27
+ return (await import(
28
+ /* @vite-ignore */
29
+ /* @vitehub-schedule-registry */
30
+ registryModule
31
+ )).default;
32
+ } catch (cause) {
33
+ throw createScheduleError("SCHEDULE_DEFINITION_NOT_FOUND", { cause });
34
+ }
35
+ }
36
+ async function runSchedule(name, options = {}) {
37
+ await waitForProcessScheduleRuntime();
38
+ const registry = await loadScheduleRegistry();
39
+ const definition = await resolveManualSchedule(registry, name);
40
+ let scheduledAt;
41
+ try {
42
+ scheduledAt = parseScheduledAt(options.scheduledAt);
43
+ } catch (cause) {
44
+ return [runScheduleErrors.SCHEDULE_INVALID_SCHEDULED_AT({ cause }), void 0];
45
+ }
46
+ try {
47
+ return [void 0, await executeManualSchedule(definition, name, scheduledAt)];
48
+ } catch (cause) {
49
+ return [runScheduleErrors.SCHEDULE_RUN_STORE_FAILED({ cause }), void 0];
50
+ }
51
+ }
7
52
  // src/started.ts
8
53
  const optionKeys = /* @__PURE__ */ new Set([
9
54
  "at",
@@ -101,12 +146,12 @@ async function fromStore(work) {
101
146
  return [startedScheduleErrors.SCHEDULE_STORE_FAILED({ cause }), void 0];
102
147
  }
103
148
  }
104
- /**
105
- * Starts the Schedule Definition `name`, which declares no `cron`, at a time that code picks: once at `at`, or on each
106
- * occurrence of `cron` in `timeZone` until `cancelSchedule()`. The store keeps it across restarts and deploys. The handler
107
- * receives `payload` as `context.payload`.
108
- */
109
149
  async function startSchedule(name, options) {
150
+ try {
151
+ await waitForProcessScheduleRuntime();
152
+ } catch (cause) {
153
+ return [startedScheduleErrors.SCHEDULE_RUNTIME_INSTALL_FAILED({ cause }), void 0];
154
+ }
110
155
  const [missing, runtime] = requireRuntime();
111
156
  if (missing) return [missing, void 0];
112
157
  if (!isString(name) || !Object.hasOwn(runtime.registry, name)) return [startedScheduleErrors.SCHEDULE_NOT_STARTABLE({ name: String(name) }), void 0];
@@ -141,4 +186,4 @@ async function cancelSchedule(id) {
141
186
  if (storeError) return [storeError, void 0];
142
187
  return deleted ? [void 0, schedule] : [startedScheduleErrors.SCHEDULE_NOT_FOUND({ id: String(id) }), void 0];
143
188
  }
144
- export { startSchedule as i, getSchedule as n, listSchedules as r, cancelSchedule as t };
189
+ export { loadScheduleRegistry as a, startSchedule as i, getSchedule as n, runSchedule as o, listSchedules as r, cancelSchedule as t };
@@ -1,8 +1,9 @@
1
- import { n as isScheduleDue } from "./due-D-0trD1g.js";
2
- import { i as executeSchedule, l as toRunId, t as startedScheduleErrors } from "./started-errors-IG9DlT2A.js";
3
- import { _ as joinKey, m as setStartedScheduleRuntime, o as getStartedScheduleRuntime, r as getScheduleOccurrenceClaims, v as keySegments } from "./state-BZLy46UJ.js";
4
- import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
5
- import { _ as errorCode, v as logFailure } from "./static-Bg7Jj92L.js";
1
+ import { n as isScheduleDue } from "./due-DXgXKgzg.js";
2
+ import { c as toRunId, r as executeSchedule } from "./execute-DHApCpbQ.js";
3
+ import { b as joinKey, h as setStartedScheduleRuntime, o as getStartedScheduleRuntime, r as getScheduleOccurrenceClaims, x as keySegments } from "./state-BoDrff6R.js";
4
+ import { t as startedScheduleErrors } from "./started-errors-D6CnKMqD.js";
5
+ import { r as isRecordOrFunction } from "./object-DNOrQSl5.js";
6
+ import { v as errorCode, y as logFailure } from "./static-D4nN8HTx.js";
6
7
  import { normalizeRuntimeDiagnosticError } from "@vite-hub/runtime";
7
8
  // src/runtime/started.ts
8
9
  const minuteMs = 6e4;
@@ -131,6 +132,7 @@ async function runOccurrence(runtime, schedule, scheduledAt, waitUntil) {
131
132
  ...context,
132
133
  payload: schedule.payload
133
134
  }) },
135
+ oneShot: schedule.at !== void 0,
134
136
  onExecution() {
135
137
  final = true;
136
138
  markFinal?.();
@@ -0,0 +1,32 @@
1
+ import { defineErrors } from "@vite-hub/runtime";
2
+ // src/started-errors.ts
3
+ const startedScheduleErrors = /*#__PURE__*/ defineErrors({
4
+ docs: "https://vitehub.dev/docs/schedule/diagnostics",
5
+ codes: {
6
+ SCHEDULE_INVALID_OPTIONS: {
7
+ why: ({ problem }) => `\`startSchedule()\` options are invalid: ${problem}`,
8
+ fix: "Pass `{ at }` for one run, or `{ cron, timeZone }` for a repeating Schedule, and a JSON `payload`."
9
+ },
10
+ SCHEDULE_NOT_FOUND: {
11
+ why: ({ id }) => `No started Schedule has the id "${id}". It ran its last time, was cancelled, or never existed.`,
12
+ fix: "List the started Schedules with `listSchedules()` or `vitehub schedule list`."
13
+ },
14
+ SCHEDULE_NOT_STARTABLE: {
15
+ why: ({ name }) => `No Schedule Definition without \`cron\` is named "${name}", so \`startSchedule()\` cannot start it.`,
16
+ fix: "Add `server/schedules/<name>.ts` with `export default defineSchedule({ handler })` and no `cron`. A Definition with its own `cron` runs only on that cron."
17
+ },
18
+ SCHEDULE_RUNTIME_INSTALL_FAILED: {
19
+ why: "The Process Runtime did not install. The server cannot deliver started Schedules.",
20
+ fix: "Read `error.cause` or the server startup log, fix the install error, then restart the server."
21
+ },
22
+ SCHEDULE_STORE_FAILED: {
23
+ why: "The store of started Schedules failed. `error.cause` has the store error.",
24
+ fix: "Check that KV is enabled and reachable from this server, then try again."
25
+ },
26
+ SCHEDULE_STORE_MISSING: {
27
+ why: "This server has no store for started Schedules.",
28
+ fix: "Add a Schedule Definition without `cron` in `server/schedules/`, enable `kv`, and build with Nitro. On Node, also set `schedule: { runtime: { driver: \"process\" } }`."
29
+ }
30
+ }
31
+ });
32
+ export { startedScheduleErrors as t };