@vite-hub/schedule 0.1.0 → 0.3.1

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 (54) hide show
  1. package/README.md +114 -96
  2. package/dist/console-wEhr0LWn.d.ts +330 -0
  3. package/dist/definition.d.ts +6 -2
  4. package/dist/definition.js +47 -1
  5. package/dist/due-BVMRQ93v.js +144 -0
  6. package/dist/durability.d.ts +14 -0
  7. package/dist/durability.js +23 -0
  8. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  9. package/dist/error-diagnostics-Mpeks7J0.js +166 -0
  10. package/dist/index.d.ts +59 -5
  11. package/dist/index.js +27 -2
  12. package/dist/invariant-DolT9EEx.js +22 -0
  13. package/dist/{kv-storage-Bv9ocZT-.d.ts → kv-storage-C0KZZB6v.d.ts} +2 -2
  14. package/dist/{kv-storage-DWinmLLy.js → kv-storage-iJChCS5A.js} +2 -2
  15. package/dist/object-Da1zyPCR.js +11 -0
  16. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  17. package/dist/{operations-gk2qzhYV.js → operations-DwZWFIUX.js} +75 -22
  18. package/dist/operations.d.ts +27 -4
  19. package/dist/operations.js +127 -730
  20. package/dist/os.d.ts +167 -0
  21. package/dist/os.js +1659 -0
  22. package/dist/runtime/console.d.ts +12 -0
  23. package/dist/runtime/console.js +85 -0
  24. package/dist/runtime/kv.d.ts +1 -1
  25. package/dist/runtime/kv.js +1 -1
  26. package/dist/runtime/process.d.ts +32 -5
  27. package/dist/runtime/process.js +401 -413
  28. package/dist/runtime/state.d.ts +2 -9
  29. package/dist/runtime/state.js +2 -2
  30. package/dist/runtime/static.d.ts +28 -2
  31. package/dist/runtime/static.js +2 -2
  32. package/dist/runtime.d.ts +34 -32
  33. package/dist/runtime.js +6 -5
  34. package/dist/started-BuGmnus4.js +201 -0
  35. package/dist/started-Bx7MDbrl.js +146 -0
  36. package/dist/{execute-BJrgNgQ0.js → started-errors-p7cu_rI7.js} +69 -20
  37. package/dist/{state-DSxmHPn3.js → state-B-Fuyfb4.js} +42 -22
  38. package/dist/state-Do2wV4Tx.d.ts +49 -0
  39. package/dist/{static-6g82xguw.js → static-DQwzzvPg.js} +63 -42
  40. package/dist/store-Df0-fzCl.d.ts +53 -0
  41. package/dist/time-zone-SBldrUgt.js +59 -0
  42. package/dist/{types-CHdV9FQU.d.ts → types-Cw5LjPuc.d.ts} +62 -8
  43. package/dist/vite.d.ts +255 -2
  44. package/dist/vite.js +5876 -2
  45. package/dist/{wait-until-BmIqRo4x.js → wait-until-Dy4Bn3ZN.js} +26 -1
  46. package/package.json +19 -24
  47. package/dist/definition-CMiOg1lg.js +0 -111
  48. package/dist/error-diagnostics-A_8Kp-48.js +0 -116
  49. package/dist/error-diagnostics-in7mif5s.js +0 -45
  50. package/dist/nuxt.d.ts +0 -17
  51. package/dist/nuxt.js +0 -27
  52. package/dist/store-QAOd8bxm.d.ts +0 -11
  53. package/dist/vite-BAVyZ8hZ.d.ts +0 -474
  54. package/dist/vite-BJwZkMrn.js +0 -5193
@@ -1,9 +1,2 @@
1
- import { a as ScheduleDefinitionRegistry, g as ScheduleRunStore, s as ScheduleRegistryDefinition } from "../types-CHdV9FQU.js";
2
- //#region src/runtime/state.d.ts
3
- export declare function setScheduleRuntimeRegistry(registry: ScheduleDefinitionRegistry | undefined): void;
4
- export declare function getScheduleRuntimeRegistry(): ScheduleDefinitionRegistry | undefined;
5
- export declare function setScheduleRunStore(store: ScheduleRunStore | undefined): void;
6
- export declare function getScheduleRunStore(): ScheduleRunStore;
7
- export declare function loadScheduleDefinition(name: string): Promise<ScheduleRegistryDefinition | undefined>;
8
- export declare function resetScheduleRuntime(): void;
9
- //#endregion
1
+ import { a as getScheduleRuntimeRegistry, c as registerProcessScheduleDefinitions, d as setScheduleRunStore, f as setScheduleRuntimeRegistry, i as getScheduleRunStore, l as resetScheduleRuntime, n as getProcessScheduleDefinitions, o as getStartedScheduleRuntime, p as setStartedScheduleRuntime, r as getScheduleOccurrenceClaims, s as loadScheduleDefinition, t as StartedScheduleRuntime, u as setScheduleOccurrenceClaims } from "../state-Do2wV4Tx.js";
2
+ export { StartedScheduleRuntime, getProcessScheduleDefinitions, getScheduleOccurrenceClaims, getScheduleRunStore, getScheduleRuntimeRegistry, getStartedScheduleRuntime, loadScheduleDefinition, registerProcessScheduleDefinitions, resetScheduleRuntime, setScheduleOccurrenceClaims, setScheduleRunStore, setScheduleRuntimeRegistry, setStartedScheduleRuntime };
@@ -1,2 +1,2 @@
1
- import { a as setScheduleRunStore, i as resetScheduleRuntime, n as getScheduleRuntimeRegistry, o as setScheduleRuntimeRegistry, r as loadScheduleDefinition, t as getScheduleRunStore } from "../state-DSxmHPn3.js";
2
- export { getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, setScheduleRunStore, setScheduleRuntimeRegistry };
1
+ import { a as getStartedScheduleRuntime, c as resetScheduleRuntime, d as setScheduleRuntimeRegistry, f as setStartedScheduleRuntime, i as getScheduleRuntimeRegistry, l as setScheduleOccurrenceClaims, n as getScheduleOccurrenceClaims, o as loadScheduleDefinition, r as getScheduleRunStore, s as registerProcessScheduleDefinitions, t as getProcessScheduleDefinitions, u as setScheduleRunStore } from "../state-B-Fuyfb4.js";
2
+ export { getProcessScheduleDefinitions, getScheduleOccurrenceClaims, getScheduleRunStore, getScheduleRuntimeRegistry, getStartedScheduleRuntime, loadScheduleDefinition, registerProcessScheduleDefinitions, resetScheduleRuntime, setScheduleOccurrenceClaims, setScheduleRunStore, setScheduleRuntimeRegistry, setStartedScheduleRuntime };
@@ -1,4 +1,4 @@
1
- import { a as ScheduleDefinitionRegistry, n as ScheduleDefinition, u as ScheduleRunContext } from "../types-CHdV9FQU.js";
1
+ import { a as ScheduleDefinitionRegistry, n as ScheduleDefinition, u as ScheduleRunContext } from "../types-Cw5LjPuc.js";
2
2
  //#region src/runtime/static.d.ts
3
3
  export interface ExecuteStaticScheduleOptions {
4
4
  cron: string;
@@ -9,12 +9,23 @@ export interface ExecuteStaticScheduleOptions {
9
9
  }
10
10
  export interface ExecuteMatchingStaticSchedulesOptions {
11
11
  cron: string;
12
+ /** Cron per Schedule name that the host registered in place of the Definition's cron. */
13
+ cronOverrides?: Readonly<Record<string, string>>;
12
14
  registry: ScheduleDefinitionRegistry;
13
15
  scheduledAt?: Date;
16
+ /**
17
+ * UTC cron that the host registered for each Schedule with a `timeZone`. A wake runs such a Schedule only when its
18
+ * own cron is due in its time zone at that minute. `cronOverrides` wins over this map.
19
+ */
20
+ timeZoneCrons?: Readonly<Record<string, string>>;
14
21
  waitUntil?: (promise: PromiseLike<unknown>) => void;
15
22
  }
16
23
  export interface ExecuteCloudflareStaticSchedulesOptions {
24
+ /** Cron per Schedule name that the host registered in place of the Definition's cron. */
25
+ cronOverrides?: Readonly<Record<string, string>>;
17
26
  registry: ScheduleDefinitionRegistry;
27
+ /** UTC cron that the host registered for each Schedule with a `timeZone`. */
28
+ timeZoneCrons?: Readonly<Record<string, string>>;
18
29
  waitUntil?: (promise: PromiseLike<unknown>) => void;
19
30
  }
20
31
  interface CloudflareScheduledEventLike {
@@ -37,11 +48,26 @@ export declare function missingScheduleDefinitionError(name: string): Error;
37
48
  export declare function isScheduleCronAuthorized(authorization: string | null | undefined, cronSecret: string): boolean;
38
49
  export declare function normalizeCron(cron: string): string;
39
50
  export declare function normalizeScheduleRuntimeError(error: unknown): Error;
51
+ /**
52
+ * Estimates a wake minute from callback time when the host supplies no scheduled timestamp. This is the newest UTC
53
+ * cron match within one day, or the current minute when none matches. It cannot identify a delayed or retried wake
54
+ * after another cron match; callers must not treat it as the provider's occurrence identity.
55
+ */
56
+ export declare function scheduledWakeTime(cron: string, now?: Date): Date;
57
+ /**
58
+ * Returns `true` when a host wake at `scheduledAt` is an occurrence of the Definition's cron in its `timeZone`. The host
59
+ * runs a wider UTC cron for a time-zoned Schedule, so the runtime skips the wakes that are not local occurrences.
60
+ */
61
+ export declare function isTimeZoneWakeDue(definition: ScheduleDefinition & {
62
+ cron: string;
63
+ }, name: string, scheduledAt: Date): boolean;
40
64
  export declare function createStaticScheduleRun(options: Omit<ExecuteStaticScheduleOptions, "definition" | "waitUntil"> & {
41
65
  waitUntil: NonNullable<ExecuteStaticScheduleOptions["waitUntil"]>;
42
66
  }): StaticScheduleRun;
43
67
  export declare function executeStaticSchedule(options: ExecuteStaticScheduleOptions): Promise<unknown>;
44
68
  export declare function executeMatchingStaticSchedules(options: ExecuteMatchingStaticSchedulesOptions): Promise<unknown[]>;
45
69
  export declare function executeCloudflareStaticSchedules(event: CloudflareScheduledEventLike, options: ExecuteCloudflareStaticSchedulesOptions): Promise<unknown[]>;
46
- export declare function unwrapScheduleDefinition(loaded: unknown): ScheduleDefinition | undefined;
70
+ export declare function unwrapScheduleDefinition(loaded: unknown): (ScheduleDefinition & {
71
+ cron: string;
72
+ }) | undefined;
47
73
  //#endregion
@@ -1,2 +1,2 @@
1
- import { a as isScheduleCronAuthorized, c as normalizeScheduleRuntimeError, i as executeStaticSchedule, l as unwrapScheduleDefinition, n as executeCloudflareStaticSchedules, o as missingScheduleDefinitionError, r as executeMatchingStaticSchedules, s as normalizeCron, t as createStaticScheduleRun } from "../static-6g82xguw.js";
2
- export { createStaticScheduleRun, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule, isScheduleCronAuthorized, missingScheduleDefinitionError, normalizeCron, normalizeScheduleRuntimeError, unwrapScheduleDefinition };
1
+ import { a as isScheduleCronAuthorized, c as normalizeCron, d as unwrapScheduleDefinition, i as executeStaticSchedule, l as normalizeScheduleRuntimeError, n as executeCloudflareStaticSchedules, o as isTimeZoneWakeDue, r as executeMatchingStaticSchedules, s as missingScheduleDefinitionError, t as createStaticScheduleRun, u as scheduledWakeTime } from "../static-DQwzzvPg.js";
2
+ export { createStaticScheduleRun, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule, isScheduleCronAuthorized, isTimeZoneWakeDue, missingScheduleDefinitionError, normalizeCron, normalizeScheduleRuntimeError, scheduledWakeTime, unwrapScheduleDefinition };
package/dist/runtime.d.ts CHANGED
@@ -1,37 +1,39 @@
1
1
  /// <reference path="./registry-module.d.ts" />
2
- import { a as ScheduleDefinitionRegistry, 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-CHdV9FQU.js";
3
- import { n as createScheduleKVStorage, t as ScheduleKVStorage } from "./kv-storage-Bv9ocZT-.js";
4
- import { n as createKVScheduleRunStore, r as createMemoryScheduleRunStore, t as KVScheduleStoreOptions } from "./store-QAOd8bxm.js";
2
+ 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-Cw5LjPuc.js";
3
+ import { a as createScheduleRun, c as runScheduleFrom, n as createKVScheduleRunStore, o as executeSchedule, r as createMemoryScheduleRunStore, s as executeStaticSchedule, t as KVScheduleStoreOptions } from "./store-Df0-fzCl.js";
4
+ import { n as createScheduleKVStorage, t as ScheduleKVStorage } from "./kv-storage-C0KZZB6v.js";
5
5
  import { normalizeCron, unwrapScheduleDefinition } from "./runtime/static.js";
6
- import { getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, setScheduleRunStore, setScheduleRuntimeRegistry } from "./runtime/state.js";
7
- //#region src/runtime/execute.d.ts
8
- interface ExecuteScheduleOptions {
9
- /** Return the persisted failed run when the handler throws. Guards still throw. */
10
- captureHandlerFailure?: boolean;
11
- definition: ScheduleDefinition;
12
- runStore?: ScheduleRunStore;
13
- runIdSuffix?: string;
14
- scheduleId: string;
15
- source?: "direct" | "manual" | "static";
16
- scheduledAt?: Date;
17
- target: string;
18
- waitUntil?: (promise: PromiseLike<unknown>) => void;
6
+ import { d as setScheduleRunStore, i as getScheduleRunStore, l as resetScheduleRuntime } from "./state-Do2wV4Tx.js";
7
+ //#region src/runtime/started.d.ts
8
+ interface InstallStartedSchedulesOptions {
9
+ /**
10
+ * How far back, in milliseconds, the first tick after a start runs cron minutes that no tick checked. Use it only with
11
+ * a run store that survives restarts, because the run ids dedupe minutes that already ran. Defaults to `0`.
12
+ */
13
+ catchUpMs?: number;
14
+ /** Schedule Definitions without `cron`, by name. */
15
+ registry: ScheduleDefinitionRegistry;
16
+ store: StartedScheduleStore;
19
17
  }
20
- interface ExecuteStaticScheduleOptions {
21
- cron: string;
22
- definition: ScheduleDefinition;
23
- name: string;
24
- scheduledAt?: Date;
25
- waitUntil?: (promise: PromiseLike<unknown>) => void;
18
+ /** Installs the store and the Definitions that `startSchedule()` and the tick use. The generated Nitro plugin calls it. */
19
+ export declare function installStartedSchedules(options: InstallStartedSchedulesOptions): void;
20
+ /** Keeps started Schedules in this process only. They are lost on restart. Use it in tests. */
21
+ export declare function createMemoryStartedScheduleStore(): StartedScheduleStore;
22
+ interface KVStartedScheduleStoreOptions {
23
+ kvStore: ScheduleKVStorage;
24
+ /** Key prefix. Defaults to `vitehub:schedule`, the prefix of the KV Schedule Run store. */
25
+ prefix?: string;
26
26
  }
27
- interface RunScheduleOptions {
28
- /** Loads the definition from this registry instead of the one installed with `setScheduleRuntimeRegistry()`. */
29
- registry?: ScheduleDefinitionRegistry;
30
- }
31
- export declare function createScheduleRun(options: Omit<ExecuteScheduleOptions, "definition" | "waitUntil">): Promise<ScheduleRunRecord>;
32
- export declare function executeSchedule(options: ExecuteScheduleOptions): Promise<ScheduleRunRecord>;
33
- export declare function executeStaticSchedule(options: ExecuteStaticScheduleOptions): Promise<ScheduleRunRecord>;
34
- /** Runs a manually dispatchable static Schedule Definition immediately. */
35
- export declare function runSchedule(name: string, options?: RunScheduleOptions): Promise<ScheduleRunRecord>;
27
+ /**
28
+ * Keeps started Schedules in KV, one key for each Schedule, so they survive restarts and deploys. A record never changes
29
+ * after `put()`, so `list()` reads each key once per process and then only lists the keys.
30
+ */
31
+ export declare function createKVStartedScheduleStore(options: KVStartedScheduleStoreOptions): StartedScheduleStore;
32
+ /**
33
+ * Runs the started Schedules that are due at the minute of `context.scheduledAt`. It is the handler of the
34
+ * `vitehub/started-schedules` Schedule, which the host wakes each minute. A handler failure is recorded in the run of
35
+ * that started Schedule and logged; it does not fail the tick.
36
+ */
37
+ export declare function runStartedSchedules(context: ScheduleRunContext): Promise<void>;
36
38
  //#endregion
37
- export { type KVScheduleStoreOptions, type RunScheduleOptions, 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, getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, normalizeCron, resetScheduleRuntime, setScheduleRunStore, setScheduleRuntimeRegistry, unwrapScheduleDefinition };
39
+ 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 };
package/dist/runtime.js CHANGED
@@ -1,5 +1,6 @@
1
- import { i as runSchedule, n as executeSchedule, r as executeStaticSchedule, t as createScheduleRun } from "./execute-BJrgNgQ0.js";
2
- import { a as setScheduleRunStore, c as createMemoryScheduleRunStore, i as resetScheduleRuntime, n as getScheduleRuntimeRegistry, o as setScheduleRuntimeRegistry, r as loadScheduleDefinition, s as createKVScheduleRunStore, t as getScheduleRunStore } from "./state-DSxmHPn3.js";
3
- import { l as unwrapScheduleDefinition, s as normalizeCron } from "./static-6g82xguw.js";
4
- import { t as createScheduleKVStorage } from "./kv-storage-DWinmLLy.js";
5
- export { createKVScheduleRunStore, createMemoryScheduleRunStore, createScheduleKVStorage, createScheduleRun, executeSchedule, executeStaticSchedule, getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, normalizeCron, resetScheduleRuntime, runSchedule, setScheduleRunStore, setScheduleRuntimeRegistry, unwrapScheduleDefinition };
1
+ import { a as runScheduleFrom, i as executeStaticSchedule, n as createScheduleRun, r as executeSchedule } from "./started-errors-p7cu_rI7.js";
2
+ import { c as resetScheduleRuntime, m as createMemoryScheduleRunStore, p as createKVScheduleRunStore, r as getScheduleRunStore, u as setScheduleRunStore } from "./state-B-Fuyfb4.js";
3
+ import { c as normalizeCron, d as unwrapScheduleDefinition } from "./static-DQwzzvPg.js";
4
+ import { t as createScheduleKVStorage } from "./kv-storage-iJChCS5A.js";
5
+ import { i as runStartedSchedules, n as createMemoryStartedScheduleStore, r as installStartedSchedules, t as createKVStartedScheduleStore } from "./started-BuGmnus4.js";
6
+ export { createKVScheduleRunStore, createKVStartedScheduleStore, createMemoryScheduleRunStore, createMemoryStartedScheduleStore, createScheduleKVStorage, createScheduleRun, executeSchedule, executeStaticSchedule, getScheduleRunStore, installStartedSchedules, normalizeCron, resetScheduleRuntime, runScheduleFrom, runStartedSchedules, setScheduleRunStore, unwrapScheduleDefinition };
@@ -0,0 +1,201 @@
1
+ import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
2
+ import { o as toRunId, r as executeSchedule, t as startedScheduleErrors } from "./started-errors-p7cu_rI7.js";
3
+ import { a as getStartedScheduleRuntime, f as setStartedScheduleRuntime, g as keySegments, h as joinKey, n as getScheduleOccurrenceClaims } from "./state-B-Fuyfb4.js";
4
+ import { t as isScheduleDue } from "./due-BVMRQ93v.js";
5
+ import { normalizeRuntimeDiagnosticError } from "@vite-hub/runtime";
6
+ //#region src/runtime/started.ts
7
+ const minuteMs = 6e4;
8
+ /** Installs the store and the Definitions that `startSchedule()` and the tick use. The generated Nitro plugin calls it. */
9
+ function installStartedSchedules(options) {
10
+ setStartedScheduleRuntime({
11
+ catchUpMs: options.catchUpMs ?? 0,
12
+ registry: options.registry,
13
+ store: options.store
14
+ });
15
+ }
16
+ function serialize(schedule) {
17
+ return {
18
+ ...schedule.at ? { at: schedule.at.toISOString() } : {},
19
+ createdAt: schedule.createdAt.toISOString(),
20
+ ...schedule.cron === void 0 ? {} : { cron: schedule.cron },
21
+ id: schedule.id,
22
+ ...schedule.payload === void 0 ? {} : { payload: schedule.payload },
23
+ name: schedule.name,
24
+ ...schedule.timeZone === void 0 ? {} : { timeZone: schedule.timeZone }
25
+ };
26
+ }
27
+ function deserialize(stored) {
28
+ return {
29
+ ...stored.at ? { at: new Date(stored.at) } : {},
30
+ createdAt: new Date(stored.createdAt),
31
+ ...stored.cron === void 0 ? {} : { cron: stored.cron },
32
+ id: stored.id,
33
+ ...stored.payload === void 0 ? {} : { payload: stored.payload },
34
+ name: stored.name,
35
+ ...stored.timeZone === void 0 ? {} : { timeZone: stored.timeZone }
36
+ };
37
+ }
38
+ /** Keeps started Schedules in this process only. They are lost on restart. Use it in tests. */
39
+ function createMemoryStartedScheduleStore() {
40
+ const schedules = /* @__PURE__ */ new Map();
41
+ return {
42
+ async delete(id) {
43
+ return schedules.delete(id);
44
+ },
45
+ async get(id) {
46
+ const stored = schedules.get(id);
47
+ return stored ? deserialize(stored) : void 0;
48
+ },
49
+ async list() {
50
+ return [...schedules.values()].map(deserialize);
51
+ },
52
+ async put(schedule) {
53
+ schedules.set(schedule.id, serialize(schedule));
54
+ }
55
+ };
56
+ }
57
+ /**
58
+ * Keeps started Schedules in KV, one key for each Schedule, so they survive restarts and deploys. A record never changes
59
+ * after `put()`, so `list()` reads each key once per process and then only lists the keys.
60
+ */
61
+ function createKVStartedScheduleStore(options) {
62
+ const prefix = options.prefix ?? "vitehub:schedule";
63
+ const kv = options.kvStore;
64
+ const key = (id) => joinKey(prefix, "started-schedules", id);
65
+ const read = /* @__PURE__ */ new Map();
66
+ return {
67
+ async delete(id) {
68
+ read.delete(id);
69
+ if (!await kv.has(key(id))) return false;
70
+ await kv.delete(key(id));
71
+ return true;
72
+ },
73
+ async get(id) {
74
+ const stored = await kv.get(key(id));
75
+ return stored ? deserialize(stored) : void 0;
76
+ },
77
+ async list() {
78
+ const ids = new Set((await kv.keys(`${joinKey(prefix, "started-schedules")}/`)).map((entry) => keySegments(entry, 1)[0]));
79
+ for (const id of read.keys()) if (!ids.has(id)) read.delete(id);
80
+ const schedules = [];
81
+ for (const id of ids) {
82
+ let schedule = read.get(id);
83
+ if (!schedule) {
84
+ const stored = await kv.get(key(id));
85
+ if (!stored) continue;
86
+ schedule = deserialize(stored);
87
+ read.set(id, schedule);
88
+ }
89
+ schedules.push(schedule);
90
+ }
91
+ return schedules;
92
+ },
93
+ async put(schedule) {
94
+ await kv.set(key(schedule.id), serialize(schedule));
95
+ }
96
+ };
97
+ }
98
+ function unwrapStartableDefinition(loaded) {
99
+ const candidate = isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default") ? loaded.default : loaded;
100
+ return isRecordOrFunction(candidate) && typeof candidate.handler === "function" && !Object.hasOwn(candidate, "cron") ? candidate : void 0;
101
+ }
102
+ /** The minutes in `[first, last]` when `schedule` is due, after it was created. A one-time Schedule is due once `at` passed. */
103
+ function dueMinutes(schedule, first, last) {
104
+ if (schedule.at) return schedule.at.getTime() <= last ? [schedule.at] : [];
105
+ const due = [];
106
+ const start = Math.max(first, Math.floor(schedule.createdAt.getTime() / minuteMs) * minuteMs + minuteMs);
107
+ for (let minute = start; minute <= last; minute += minuteMs) {
108
+ const scheduledAt = new Date(minute);
109
+ if (isScheduleDue({
110
+ cron: schedule.cron,
111
+ id: schedule.id,
112
+ timeZone: schedule.timeZone
113
+ }, scheduledAt)) due.push(scheduledAt);
114
+ }
115
+ return due;
116
+ }
117
+ /** Runs one occurrence of a started Schedule. Resolves `false` when another process holds it, so a later tick tries again. */
118
+ async function runOccurrence(runtime, schedule, scheduledAt, waitUntil) {
119
+ const definition = unwrapStartableDefinition(await (Object.hasOwn(runtime.registry, schedule.name) ? runtime.registry[schedule.name] : void 0)?.());
120
+ if (!definition) {
121
+ if (schedule.at) await runtime.store.delete(schedule.id);
122
+ throw startedScheduleErrors.SCHEDULE_NOT_STARTABLE({ name: schedule.name });
123
+ }
124
+ const claims = getScheduleOccurrenceClaims();
125
+ const run = async (markFinal) => {
126
+ let final = false;
127
+ try {
128
+ await executeSchedule({
129
+ captureHandlerFailure: true,
130
+ ...claims ? { claimed: true } : {},
131
+ definition: { handler: (context) => definition.handler({
132
+ ...context,
133
+ payload: schedule.payload
134
+ }) },
135
+ onExecution() {
136
+ final = true;
137
+ markFinal?.();
138
+ },
139
+ scheduleId: schedule.id,
140
+ scheduledAt,
141
+ source: "started",
142
+ target: schedule.name,
143
+ waitUntil
144
+ });
145
+ } finally {
146
+ if (schedule.at && final) await runtime.store.delete(schedule.id);
147
+ }
148
+ };
149
+ if (!claims) {
150
+ await run();
151
+ return true;
152
+ }
153
+ return await claims.run(toRunId("started", schedule.id, scheduledAt), run) !== "held";
154
+ }
155
+ /**
156
+ * Runs the started Schedules that are due at the minute of `context.scheduledAt`. It is the handler of the
157
+ * `vitehub/started-schedules` Schedule, which the host wakes each minute. A handler failure is recorded in the run of
158
+ * that started Schedule and logged; it does not fail the tick.
159
+ */
160
+ async function runStartedSchedules(context) {
161
+ const runtime = getStartedScheduleRuntime();
162
+ if (!runtime) throw startedScheduleErrors.SCHEDULE_STORE_MISSING();
163
+ const minute = Math.floor(context.scheduledAt.getTime() / minuteMs) * minuteMs;
164
+ const first = runtime.checkedThrough === void 0 ? minute - runtime.catchUpMs : Math.min(minute, runtime.checkedThrough + minuteMs);
165
+ const schedules = await runtime.store.list();
166
+ const occurrences = schedules.flatMap((schedule) => dueMinutes(schedule, first, minute).map((scheduledAt) => ({
167
+ schedule,
168
+ scheduledAt
169
+ })));
170
+ const held = runtime.held ??= /* @__PURE__ */ new Map();
171
+ const byId = new Map(schedules.map((schedule) => [schedule.id, schedule]));
172
+ for (const [runId, entry] of held) {
173
+ const schedule = byId.get(entry.scheduleId);
174
+ if (!schedule) held.delete(runId);
175
+ else if (!occurrences.some((occurrence) => occurrence.schedule.id === schedule.id && occurrence.scheduledAt.getTime() === entry.scheduledAt.getTime())) occurrences.push({
176
+ schedule,
177
+ scheduledAt: entry.scheduledAt
178
+ });
179
+ }
180
+ const results = await Promise.allSettled(occurrences.map(({ schedule, scheduledAt }) => runOccurrence(runtime, schedule, scheduledAt, context.waitUntil)));
181
+ results.forEach((result, index) => {
182
+ const { schedule, scheduledAt } = occurrences[index];
183
+ const runId = toRunId("started", schedule.id, scheduledAt);
184
+ if (result.status === "fulfilled") {
185
+ if (result.value) held.delete(runId);
186
+ else held.set(runId, {
187
+ scheduleId: schedule.id,
188
+ scheduledAt
189
+ });
190
+ return;
191
+ }
192
+ held.set(runId, {
193
+ scheduleId: schedule.id,
194
+ scheduledAt
195
+ });
196
+ console.error(`[vitehub:schedule] Started Schedule "${schedule.id}" of "${schedule.name}" failed.`, normalizeRuntimeDiagnosticError(result.reason, { includeStack: true }));
197
+ });
198
+ if (results.every((result) => result.status === "fulfilled")) runtime.checkedThrough = Math.max(runtime.checkedThrough ?? minute, minute);
199
+ }
200
+ //#endregion
201
+ export { runStartedSchedules as i, createMemoryStartedScheduleStore as n, installStartedSchedules as r, createKVStartedScheduleStore as t };
@@ -0,0 +1,146 @@
1
+ import { t as isIanaTimeZone } from "./time-zone-SBldrUgt.js";
2
+ import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
3
+ import { r as parseScheduledAt } from "./wait-until-Dy4Bn3ZN.js";
4
+ import { s as randomId, t as startedScheduleErrors } from "./started-errors-p7cu_rI7.js";
5
+ import { a as getStartedScheduleRuntime } from "./state-B-Fuyfb4.js";
6
+ import { parseCronExpression } from "cron-schedule";
7
+ //#region src/started.ts
8
+ const optionKeys = /* @__PURE__ */ new Set([
9
+ "at",
10
+ "cron",
11
+ "payload",
12
+ "timeZone"
13
+ ]);
14
+ function isString(value) {
15
+ return String(value) === value;
16
+ }
17
+ function isJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
18
+ switch (typeof value) {
19
+ case "string":
20
+ case "boolean": return true;
21
+ case "number": return Number.isFinite(value);
22
+ case "object": {
23
+ if (value === null) return true;
24
+ if (ancestors.has(value)) return false;
25
+ const prototype = Object.getPrototypeOf(value);
26
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return false;
27
+ if (Object.getOwnPropertySymbols(value).length) return false;
28
+ ancestors.add(value);
29
+ try {
30
+ if (Array.isArray(value)) {
31
+ for (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index) || !isJsonValue(value[index], ancestors)) return false;
32
+ return true;
33
+ }
34
+ return Object.values(value).every((entry) => isJsonValue(entry, ancestors));
35
+ } finally {
36
+ ancestors.delete(value);
37
+ }
38
+ }
39
+ default: return false;
40
+ }
41
+ }
42
+ function invalid(problem) {
43
+ return [startedScheduleErrors.SCHEDULE_INVALID_OPTIONS({ problem }), void 0];
44
+ }
45
+ function isFiveFieldCron(cron) {
46
+ if (cron.trim() !== cron || cron.split(/\s+/).length !== 5) return false;
47
+ try {
48
+ parseCronExpression(cron);
49
+ return true;
50
+ } catch {
51
+ return false;
52
+ }
53
+ }
54
+ /** Reads the options once at the boundary. The returned record is what the store keeps. */
55
+ function parseOptions(name, options) {
56
+ if (!isRecordOrFunction(options)) return invalid("pass an object with `at` or `cron`.");
57
+ const unknownKey = Object.keys(options).find((key) => !optionKeys.has(key));
58
+ if (unknownKey) return invalid(`\`${unknownKey}\` is not an option.`);
59
+ const { at, cron, payload, timeZone } = options;
60
+ if (at === void 0 === (cron === void 0)) return invalid("pass `at` for one run or `cron` for a repeating Schedule, not both and not neither.");
61
+ const schedule = {
62
+ createdAt: /* @__PURE__ */ new Date(),
63
+ id: randomId("sched"),
64
+ name
65
+ };
66
+ if (at !== void 0) {
67
+ if (timeZone !== void 0) return invalid("`timeZone` applies to `cron`. Give `at` as an ISO 8601 date-time with its offset instead.");
68
+ try {
69
+ schedule.at = parseScheduledAt(at);
70
+ } catch {
71
+ return invalid("`at` must be a Date or an ISO 8601 date-time with a time zone, such as \"2026-11-08T09:00:00Z\".");
72
+ }
73
+ } else {
74
+ if (!isString(cron) || !isFiveFieldCron(cron)) return invalid("`cron` must be a five-field cron expression, such as \"0 9 * * 1-5\".");
75
+ schedule.cron = cron;
76
+ if (timeZone !== void 0) {
77
+ if (!isIanaTimeZone(timeZone)) return invalid("`timeZone` must be an IANA time zone, such as \"Europe/Madrid\".");
78
+ schedule.timeZone = timeZone;
79
+ }
80
+ }
81
+ if (payload !== void 0) {
82
+ let text;
83
+ try {
84
+ if (!isJsonValue(payload)) return invalid("`payload` must be a JSON value.");
85
+ text = JSON.stringify(payload);
86
+ } catch {
87
+ text = void 0;
88
+ }
89
+ if (text === void 0) return invalid("`payload` must be a JSON value.");
90
+ schedule.payload = JSON.parse(text);
91
+ }
92
+ return [void 0, schedule];
93
+ }
94
+ function requireRuntime() {
95
+ const runtime = getStartedScheduleRuntime();
96
+ return runtime ? [void 0, runtime] : [startedScheduleErrors.SCHEDULE_STORE_MISSING(), void 0];
97
+ }
98
+ async function fromStore(work) {
99
+ try {
100
+ return [void 0, await work()];
101
+ } catch (cause) {
102
+ return [startedScheduleErrors.SCHEDULE_STORE_FAILED({ cause }), void 0];
103
+ }
104
+ }
105
+ /**
106
+ * Starts the Schedule Definition `name`, which declares no `cron`, at a time that code picks: once at `at`, or on each
107
+ * occurrence of `cron` in `timeZone` until `cancelSchedule()`. The store keeps it across restarts and deploys. The handler
108
+ * receives `payload` as `context.payload`.
109
+ */
110
+ async function startSchedule(name, options) {
111
+ const [missing, runtime] = requireRuntime();
112
+ if (missing) return [missing, void 0];
113
+ if (!isString(name) || !Object.hasOwn(runtime.registry, name)) return [startedScheduleErrors.SCHEDULE_NOT_STARTABLE({ name: String(name) }), void 0];
114
+ const [error, schedule] = parseOptions(name, options);
115
+ if (error) return [error, void 0];
116
+ const [storeError] = await fromStore(() => runtime.store.put(schedule));
117
+ return storeError ? [storeError, void 0] : [void 0, schedule];
118
+ }
119
+ /** Reads one started Schedule. */
120
+ async function getSchedule(id) {
121
+ const [missing, runtime] = requireRuntime();
122
+ if (missing) return [missing, void 0];
123
+ const [error, schedule] = await fromStore(() => runtime.store.get(id));
124
+ if (error) return [error, void 0];
125
+ return schedule ? [void 0, schedule] : [startedScheduleErrors.SCHEDULE_NOT_FOUND({ id: String(id) }), void 0];
126
+ }
127
+ /** Lists the started Schedules, oldest first. `name` keeps the Schedules of one Definition. */
128
+ async function listSchedules(options = {}) {
129
+ const [missing, runtime] = requireRuntime();
130
+ if (missing) return [missing, void 0];
131
+ const [error, schedules] = await fromStore(() => runtime.store.list());
132
+ if (error) return [error, void 0];
133
+ return [void 0, schedules.filter((schedule) => options.name === void 0 || schedule.name === options.name).sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime())];
134
+ }
135
+ /** Removes a started Schedule, so it does not run again. A run that already started finishes. */
136
+ async function cancelSchedule(id) {
137
+ const [error, schedule] = await getSchedule(id);
138
+ if (error) return [error, void 0];
139
+ const [missing, runtime] = requireRuntime();
140
+ if (missing) return [missing, void 0];
141
+ const [storeError, deleted] = await fromStore(() => runtime.store.delete(id));
142
+ if (storeError) return [storeError, void 0];
143
+ return deleted ? [void 0, schedule] : [startedScheduleErrors.SCHEDULE_NOT_FOUND({ id: String(id) }), void 0];
144
+ }
145
+ //#endregion
146
+ export { startSchedule as i, getSchedule as n, listSchedules as r, cancelSchedule as t };