@vite-hub/schedule 0.0.4 → 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 (62) hide show
  1. package/README.md +139 -58
  2. package/dist/console-wEhr0LWn.d.ts +330 -0
  3. package/dist/definition.d.ts +8 -6
  4. package/dist/definition.js +34 -28
  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 +61 -40
  11. package/dist/index.js +27 -7
  12. package/dist/inspect-DTfAo5gS.js +118 -0
  13. package/dist/invariant-DolT9EEx.js +22 -0
  14. package/dist/kv-storage-C0KZZB6v.d.ts +18 -0
  15. package/dist/{kv-storage-DWinmLLy.js → kv-storage-iJChCS5A.js} +2 -2
  16. package/dist/object-Da1zyPCR.js +11 -0
  17. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  18. package/dist/operations-DwZWFIUX.js +184 -0
  19. package/dist/operations.d.ts +84 -0
  20. package/dist/operations.js +318 -0
  21. package/dist/os.d.ts +167 -0
  22. package/dist/os.js +1659 -0
  23. package/dist/registry-module.d.ts +0 -5
  24. package/dist/runtime/console.d.ts +12 -0
  25. package/dist/runtime/console.js +85 -0
  26. package/dist/runtime/kv.d.ts +4 -0
  27. package/dist/{kv-BJ1I9IlJ.js → runtime/kv.js} +1 -1
  28. package/dist/runtime/process.d.ts +53 -5
  29. package/dist/runtime/process.js +501 -251
  30. package/dist/runtime/state.d.ts +2 -13
  31. package/dist/runtime/state.js +2 -2
  32. package/dist/runtime/static.d.ts +44 -12
  33. package/dist/runtime/static.js +2 -150
  34. package/dist/runtime.d.ts +38 -4
  35. package/dist/runtime.js +6 -3
  36. package/dist/started-BuGmnus4.js +201 -0
  37. package/dist/started-Bx7MDbrl.js +146 -0
  38. package/dist/started-errors-p7cu_rI7.js +250 -0
  39. package/dist/state-B-Fuyfb4.js +468 -0
  40. package/dist/state-Do2wV4Tx.d.ts +49 -0
  41. package/dist/static-DQwzzvPg.js +266 -0
  42. package/dist/store-Df0-fzCl.d.ts +53 -0
  43. package/dist/time-zone-SBldrUgt.js +59 -0
  44. package/dist/types-Cw5LjPuc.d.ts +167 -0
  45. package/dist/vite.d.ts +214 -11
  46. package/dist/vite.js +5876 -3
  47. package/dist/wait-until-Dy4Bn3ZN.js +112 -0
  48. package/package.json +65 -24
  49. package/dist/client-DpCD4YFE.js +0 -233
  50. package/dist/discovery-DkFAN7Wd.d.ts +0 -15
  51. package/dist/discovery-DvU3B6iD.js +0 -753
  52. package/dist/due-Bbh4yIxq.js +0 -59
  53. package/dist/execute-B-pii4wf.js +0 -211
  54. package/dist/nuxt.d.ts +0 -19
  55. package/dist/nuxt.js +0 -26
  56. package/dist/runtime/driver.d.ts +0 -26
  57. package/dist/runtime/driver.js +0 -337
  58. package/dist/state-By7WU_ks.js +0 -472
  59. package/dist/store-t-74rsM_.d.ts +0 -48
  60. package/dist/types-Bcje4dLV.d.ts +0 -136
  61. package/dist/vite-BHs17nWX.js +0 -4166
  62. package/dist/wait-until-BzIwzXw4.js +0 -23
@@ -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 };
@@ -0,0 +1,250 @@
1
+ import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
2
+ import { a as validateScheduledAt, i as scheduleIdempotencyKey, o as createScheduleError, r as parseScheduledAt, t as runWithScheduleWaitUntil } from "./wait-until-Dy4Bn3ZN.js";
3
+ import { r as getScheduleRunStore } from "./state-B-Fuyfb4.js";
4
+ import { defineErrors, serializeResponse, toResponse } from "@vite-hub/runtime";
5
+ import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
6
+ //#region ../internal/src/runtime/random.ts
7
+ function randomId(prefix) {
8
+ const body = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
9
+ return prefix ? `${prefix}_${body}` : body;
10
+ }
11
+ //#endregion
12
+ //#region src/runtime/execute.ts
13
+ function normalizeRunSource(source) {
14
+ return source ?? "direct";
15
+ }
16
+ /** Returns the Schedule Run id for one scheduled occurrence, with an optional unique suffix. */
17
+ function toRunId(source, scheduleId, scheduledAt, runIdSuffix) {
18
+ return `srun_${normalizeRunSource(source)}_${encodeURIComponent(scheduleId)}_${scheduledAt.toISOString()}${runIdSuffix ? `_${runIdSuffix}` : ""}`;
19
+ }
20
+ function toRunError(error) {
21
+ try {
22
+ if (error instanceof Error) return {
23
+ message: error.message,
24
+ name: error.name,
25
+ stack: error.stack
26
+ };
27
+ return { message: String(error) };
28
+ } catch {
29
+ return { message: "[unprintable thrown value]" };
30
+ }
31
+ }
32
+ function requireUpdatedRun(run) {
33
+ if (!run) throw createScheduleError("SCHEDULE_RUN_NOT_FOUND");
34
+ return run;
35
+ }
36
+ async function createOrGetRun(options) {
37
+ const store = options.runStore ?? getScheduleRunStore();
38
+ const id = toRunId(options.source, options.scheduleId, options.scheduledAt, options.runIdSuffix);
39
+ const existing = await store.getRun(id);
40
+ if (existing) return {
41
+ created: false,
42
+ run: existing
43
+ };
44
+ const now = /* @__PURE__ */ new Date();
45
+ const runInput = {
46
+ attemptCount: 0,
47
+ createdAt: now,
48
+ id,
49
+ scheduleId: options.scheduleId,
50
+ scheduledAt: options.scheduledAt,
51
+ status: "pending",
52
+ target: options.target,
53
+ updatedAt: now
54
+ };
55
+ try {
56
+ return {
57
+ created: true,
58
+ run: await store.createRun(runInput)
59
+ };
60
+ } catch (error) {
61
+ const run = await store.getRun(id);
62
+ if (run) return {
63
+ created: false,
64
+ run
65
+ };
66
+ throw error;
67
+ }
68
+ }
69
+ async function startAttempt(run, store = getScheduleRunStore()) {
70
+ const now = /* @__PURE__ */ new Date();
71
+ const attempt = await store.createAttempt({
72
+ createdAt: now,
73
+ id: randomId("satt"),
74
+ runId: run.id,
75
+ startedAt: now,
76
+ status: "running",
77
+ updatedAt: now
78
+ });
79
+ await store.updateRun(run.id, {
80
+ attemptCount: run.attemptCount + 1,
81
+ startedAt: run.startedAt ?? now,
82
+ status: "running",
83
+ updatedAt: now
84
+ });
85
+ return attempt;
86
+ }
87
+ function toHandlerContext(run, attempt, waitUntil) {
88
+ return {
89
+ attemptId: attempt.id,
90
+ id: run.id,
91
+ idempotencyKey: scheduleIdempotencyKey(run.scheduleId, run.scheduledAt),
92
+ runId: run.id,
93
+ scheduleId: run.scheduleId,
94
+ scheduledAt: run.scheduledAt,
95
+ target: run.target,
96
+ waitUntil
97
+ };
98
+ }
99
+ async function completeRun(run, attempt, response, store = getScheduleRunStore()) {
100
+ const now = /* @__PURE__ */ new Date();
101
+ await store.updateAttempt(attempt.id, {
102
+ completedAt: now,
103
+ status: "succeeded",
104
+ updatedAt: now
105
+ });
106
+ return requireUpdatedRun(await store.updateRun(run.id, {
107
+ completedAt: now,
108
+ response,
109
+ status: "succeeded",
110
+ updatedAt: now
111
+ }));
112
+ }
113
+ async function failRun(run, attempt, error, store = getScheduleRunStore()) {
114
+ const now = /* @__PURE__ */ new Date();
115
+ const serializedError = toRunError(error);
116
+ await store.updateAttempt(attempt.id, {
117
+ completedAt: now,
118
+ error: serializedError,
119
+ status: "failed",
120
+ updatedAt: now
121
+ });
122
+ return requireUpdatedRun(await store.updateRun(run.id, {
123
+ completedAt: now,
124
+ error: serializedError,
125
+ status: "failed",
126
+ updatedAt: now
127
+ }));
128
+ }
129
+ const stoppedAttemptError = {
130
+ message: "The process that ran this attempt stopped before the attempt finished.",
131
+ name: "ScheduleAttemptStopped"
132
+ };
133
+ async function failStoppedAttempts(run, store) {
134
+ const now = /* @__PURE__ */ new Date();
135
+ for (const attempt of await store.listAttempts(run.id)) {
136
+ if (attempt.status !== "running") continue;
137
+ await store.updateAttempt(attempt.id, {
138
+ completedAt: now,
139
+ error: stoppedAttemptError,
140
+ status: "failed",
141
+ updatedAt: now
142
+ });
143
+ }
144
+ }
145
+ async function createScheduleRun(options) {
146
+ const scheduledAt = validateScheduledAt(options.scheduledAt ?? /* @__PURE__ */ new Date());
147
+ return (await createOrGetRun({
148
+ ...options,
149
+ scheduledAt
150
+ })).run;
151
+ }
152
+ async function executeSchedule(options) {
153
+ const scheduledAt = validateScheduledAt(options.scheduledAt ?? /* @__PURE__ */ new Date());
154
+ const { created, run } = await createOrGetRun({
155
+ ...options,
156
+ scheduledAt
157
+ });
158
+ const runStore = options.runStore ?? getScheduleRunStore();
159
+ if (!created) {
160
+ if (!options.claimed || run.status === "succeeded" || run.status === "failed") {
161
+ options.onExecution?.();
162
+ return run;
163
+ }
164
+ await failStoppedAttempts(run, runStore);
165
+ }
166
+ const attempt = await startAttempt(run, runStore);
167
+ options.onExecution?.();
168
+ try {
169
+ const value = await runInRunScopes(() => runWithScheduleWaitUntil((waitUntil) => options.definition.handler(toHandlerContext(run, attempt, waitUntil)), options.waitUntil));
170
+ return await completeRun(run, attempt, await serializeResponse(toResponse(value)), runStore);
171
+ } catch (error) {
172
+ const failed = await failRun(run, attempt, error, runStore);
173
+ if (options.captureHandlerFailure) return failed;
174
+ throw error;
175
+ }
176
+ }
177
+ async function executeStaticSchedule(options) {
178
+ return await executeSchedule({
179
+ ...options.claimed ? { claimed: true } : {},
180
+ definition: options.definition,
181
+ onExecution: options.onExecution,
182
+ scheduleId: options.name,
183
+ source: "static",
184
+ scheduledAt: options.scheduledAt,
185
+ target: options.name,
186
+ waitUntil: options.waitUntil
187
+ });
188
+ }
189
+ function isStaticScheduleDefinition(value) {
190
+ return isRecordOrFunction(value) && Object.hasOwn(value, "handler") && typeof value.handler === "function" && Object.hasOwn(value, "cron");
191
+ }
192
+ async function loadStaticScheduleDefinition(name, registry) {
193
+ const entry = Object.hasOwn(registry, name) ? registry[name] : void 0;
194
+ const loaded = typeof entry === "function" ? await entry() : void 0;
195
+ const record = isRecordOrFunction(loaded) ? loaded : void 0;
196
+ return record && isStaticScheduleDefinition(record) ? record : record && Object.hasOwn(record, "default") && isStaticScheduleDefinition(record.default) ? record.default : void 0;
197
+ }
198
+ /** Runs a manually dispatchable static Schedule Definition of `registry` immediately. */
199
+ async function runScheduleFrom(registry, name, options = {}) {
200
+ const definition = typeof name === "string" && name ? await loadStaticScheduleDefinition(name, registry) : void 0;
201
+ if (!definition) throw createScheduleError("SCHEDULE_DEFINITION_NOT_FOUND");
202
+ if (definition.options?.manual !== true) throw createScheduleError("SCHEDULE_MANUAL_RUN_DISABLED");
203
+ const scheduledAt = parseScheduledAt(options.scheduledAt);
204
+ const runStore = getScheduleRunStore();
205
+ const runIdSuffix = randomId("manual");
206
+ try {
207
+ return await executeSchedule({
208
+ definition,
209
+ runIdSuffix,
210
+ runStore,
211
+ scheduleId: name,
212
+ source: "manual",
213
+ scheduledAt,
214
+ target: name
215
+ });
216
+ } catch (error) {
217
+ const run = await runStore.getRun(toRunId("manual", name, scheduledAt, runIdSuffix));
218
+ if (run?.status === "failed") return run;
219
+ throw error;
220
+ }
221
+ }
222
+ //#endregion
223
+ //#region src/started-errors.ts
224
+ const startedScheduleErrors = /*#__PURE__*/ defineErrors({
225
+ docs: "https://vitehub.dev/docs/schedule/diagnostics",
226
+ codes: {
227
+ SCHEDULE_NOT_STARTABLE: {
228
+ why: ({ name }) => `No Schedule Definition without \`cron\` is named "${name}", so \`startSchedule()\` cannot start it.`,
229
+ 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."
230
+ },
231
+ SCHEDULE_INVALID_OPTIONS: {
232
+ why: ({ problem }) => `\`startSchedule()\` options are invalid: ${problem}`,
233
+ fix: "Pass `{ at }` for one run, or `{ cron, timeZone }` for a repeating Schedule, and a JSON `payload`."
234
+ },
235
+ SCHEDULE_NOT_FOUND: {
236
+ why: ({ id }) => `No started Schedule has the id "${id}". It ran its last time, was cancelled, or never existed.`,
237
+ fix: "List the started Schedules with `listSchedules()` or `vitehub schedule list`."
238
+ },
239
+ SCHEDULE_STORE_MISSING: {
240
+ why: "This server has no store for started Schedules.",
241
+ fix: "Add a Schedule Definition without `cron` in `server/schedules/`, enable `kv`, and build with Nitro. On Node, also set `schedule: { runtime: { driver: \"process\" } }`."
242
+ },
243
+ SCHEDULE_STORE_FAILED: {
244
+ why: "The store of started Schedules failed. `error.cause` has the store error.",
245
+ fix: "Check that KV is enabled and reachable from this server, then try again."
246
+ }
247
+ }
248
+ });
249
+ //#endregion
250
+ export { runScheduleFrom as a, executeStaticSchedule as i, createScheduleRun as n, toRunId as o, executeSchedule as r, randomId as s, startedScheduleErrors as t };