@vite-hub/schedule 0.0.0 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,126 @@
1
1
  # @vite-hub/schedule
2
2
 
3
- Reserved package name for ViteHub.
3
+ <p>
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
5
+ <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
6
+ <img alt="Vite" src="https://img.shields.io/badge/Vite-discovery-646cff?style=flat-square">
7
+ <img alt="Schedule" src="https://img.shields.io/badge/Schedule-cron%20runtime-0284c7?style=flat-square">
8
+ </p>
9
+
10
+ `@vite-hub/schedule` keeps cron definitions and runtime schedules behind one schedule registry.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pnpm add @vite-hub/schedule
16
+ ```
17
+
18
+ Add `@vite-hub/kv` when runtime schedules should persist outside memory.
19
+
20
+ ## Minimal API
21
+
22
+ ```ts
23
+ // server/schedules/daily-report.ts
24
+ import { defineSchedule } from "@vite-hub/schedule"
25
+
26
+ export default defineSchedule({
27
+ cron: "0 8 * * *",
28
+ allowRuntimeSchedules: true,
29
+ handler: async ({ scheduledAt }) => {
30
+ console.log(`Generating daily report for ${scheduledAt.toISOString()}`)
31
+ },
32
+ })
33
+ ```
34
+
35
+ ```ts
36
+ // server/schedules/report.ts
37
+ import { defineScheduleTarget } from "@vite-hub/schedule"
38
+
39
+ export default defineScheduleTarget<{ prompt: string }>({
40
+ handler: async ({ input }) => {
41
+ if (input) await generateReport(input.prompt)
42
+ },
43
+ })
44
+ ```
45
+
46
+ ```ts
47
+ // server/api/schedules.post.ts
48
+ import { schedules } from "@vite-hub/schedule/runtime"
49
+ import { defineEventHandler } from "h3"
50
+
51
+ export default defineEventHandler(() => {
52
+ return schedules.create({
53
+ cron: "30 3 * * 1",
54
+ input: { prompt: "Summarize yesterday" },
55
+ target: "report",
56
+ timeZone: "Europe/Copenhagen",
57
+ })
58
+ })
59
+ ```
60
+
61
+ Runtime Schedule updates preserve `timeZone` when it is omitted; set it to `UTC` to reset UTC evaluation. DST gaps skip missing local occurrences, and DST overlaps run both repeated instants.
62
+
63
+ ```ts
64
+ // vite.config.ts
65
+ import { hubSchedule } from "@vite-hub/schedule/vite"
66
+ import { defineConfig } from "vite"
67
+
68
+ export default defineConfig({
69
+ plugins: [
70
+ hubSchedule({
71
+ runtime: {
72
+ driver: "process",
73
+ prefix: "my-app:schedule",
74
+ },
75
+ }),
76
+ ],
77
+ })
78
+ ```
79
+
80
+ The explicit `process` runtime generates Nitro wiring for a long-running process. It runs discovered Static Schedule Definitions and persisted Runtime Schedules through one driver queue, creates both stores through the default KV store configured by `hubKv()`, applies the Schedule prefix, and closes the driver with Nitro. The defaults are prefix `vitehub:schedule`, `intervalMs: 60_000`, and `concurrency: 1`; the interval cannot exceed the one-minute cron resolution. `providerOutput` remains independent, so static provider wake output can be enabled or disabled separately.
81
+
82
+ Run exactly one long-lived process or replica with this driver. The KV run store records occurrences but does not provide distributed leader election or locking. Do not select the process driver for request-scoped or serverless hosts that may stop between requests. Those hosts need a provider or host wake integration through `@vite-hub/schedule/runtime/driver`.
83
+
84
+ ## Vite Integration
85
+
86
+ Use `hubSchedule()` in Vite to discover `server/schedules/<name>.ts` and `src/<name>.schedule.ts`. `defineSchedule()` declarations can produce provider cron output, including [Vercel Cron Jobs](https://vercel.com/docs/cron-jobs/). Cronless `defineScheduleTarget()` declarations are available only to Runtime Schedules and never emit static provider output. For Nitro apps on Cloudflare, Schedule Provider Wake writes generated `.vitehub/nitro/schedule/*` files so Nitro can register the `cloudflare:scheduled` runtime hook and emit `cloudflare.wrangler.triggers.crons` during standalone `nitro build`. In Nuxt apps, install `@vite-hub/schedule/nuxt` so the same Provider Wake output is merged into Nuxt's top-level Nitro config. In automatic mode, `server/schedules/*` routes through Nitro Provider Wake while suffix schedules keep standalone provider output.
87
+
88
+ Runtime Schedule `input` is opaque to Schedule. Create stores a snapshot; update replaces the complete snapshot when `input` is provided and preserves it when omitted. The configured store must support the value's serialization requirements.
89
+
90
+ When a host owns its own Cloudflare scheduled-event bridge, use the runtime helper instead of reimplementing registry matching:
91
+
92
+ ```ts
93
+ import scheduleRegistry from "#vitehub/schedule/registry"
94
+ import { executeCloudflareStaticSchedules } from "@vite-hub/schedule/runtime/static"
95
+
96
+ export default {
97
+ async scheduled(event) {
98
+ await executeCloudflareStaticSchedules(event, { registry: scheduleRegistry })
99
+ },
100
+ }
101
+ ```
102
+
103
+ Cron parsing uses [`cron-schedule`](https://github.com/P4sca1/cron-schedule).
104
+
105
+ ## Runtime Wake Drivers
106
+
107
+ Host integrations can connect dynamic Runtime Schedules to a native scheduler through `@vite-hub/schedule/runtime/driver`:
108
+
109
+ ```ts
110
+ import { installScheduleRuntime } from "@vite-hub/schedule/runtime/driver"
111
+
112
+ const controller = await installScheduleRuntime({
113
+ createDriver: context => hostScheduler.driver(context),
114
+ registry: scheduleRegistry,
115
+ runtimeScheduleStore,
116
+ scheduleRunStore,
117
+ })
118
+ ```
119
+
120
+ The driver receives the complete stored Runtime Schedule snapshot, including disabled records. Installation finishes only after the initial snapshot is reconciled. Later creates, updates, and deletes persist first, reconcile serially, and roll back the stored record if host reconciliation fails. A native wake calls `context.wake({ scheduleId, scheduledAt })`; `controller.close()` releases driver resources without deleting schedule state.
121
+
122
+ Long-running hosts can use `createProcessScheduleWakeDriver()` from `@vite-hub/schedule/runtime/process` when they install the runtime directly. It keeps wake registration inside the current process; it does not install cron, systemd, or another operating-system scheduler.
123
+
124
+ `startScheduleRunner()` has been removed. Existing self-hosted processes should install `createProcessScheduleWakeDriver()` through `installScheduleRuntime()` as shown above, then await `controller.close()` during host shutdown.
125
+
126
+ Learn more at [vitehub.dev](https://vitehub.dev).
@@ -0,0 +1,233 @@
1
+ import { n as executeRuntimeSchedule, o as randomId } from "./execute-BnR8oEKq.js";
2
+ import { h as invalidScheduleValueDetails, i as loadScheduleDefinition, m as createScheduleError, n as getScheduleRunStore, p as assertRuntimeScheduleId, t as getRuntimeScheduleStore } from "./state-BcEhBV8v.js";
3
+ //#region ../internal/src/runtime/time-zone.ts
4
+ const slashlessIanaTimeZones = new Set([
5
+ "CET",
6
+ "CST6CDT",
7
+ "Cuba",
8
+ "EET",
9
+ "EST",
10
+ "EST5EDT",
11
+ "Egypt",
12
+ "Eire",
13
+ "Factory",
14
+ "GB",
15
+ "GB-Eire",
16
+ "GMT",
17
+ "GMT+0",
18
+ "GMT-0",
19
+ "GMT0",
20
+ "Greenwich",
21
+ "HST",
22
+ "Hongkong",
23
+ "Iceland",
24
+ "Iran",
25
+ "Israel",
26
+ "Jamaica",
27
+ "Japan",
28
+ "Kwajalein",
29
+ "Libya",
30
+ "MET",
31
+ "MST",
32
+ "MST7MDT",
33
+ "NZ",
34
+ "NZ-CHAT",
35
+ "Navajo",
36
+ "PRC",
37
+ "PST8PDT",
38
+ "Poland",
39
+ "Portugal",
40
+ "ROC",
41
+ "ROK",
42
+ "Singapore",
43
+ "Turkey",
44
+ "UCT",
45
+ "UTC",
46
+ "Universal",
47
+ "W-SU",
48
+ "WET",
49
+ "Zulu"
50
+ ]);
51
+ function isIanaTimeZone(timeZone) {
52
+ if (typeof timeZone !== "string" || !timeZone.includes("/") && !slashlessIanaTimeZones.has(timeZone)) return false;
53
+ try {
54
+ new Intl.DateTimeFormat("en-US", { timeZone });
55
+ return true;
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+ //#endregion
61
+ //#region src/runtime/client.ts
62
+ const cronRange = {
63
+ dayOfMonth: {
64
+ max: 31,
65
+ min: 1
66
+ },
67
+ dayOfWeek: {
68
+ max: 7,
69
+ min: 0
70
+ },
71
+ hour: {
72
+ max: 23,
73
+ min: 0
74
+ },
75
+ minute: {
76
+ max: 59,
77
+ min: 0
78
+ },
79
+ month: {
80
+ max: 12,
81
+ min: 1
82
+ }
83
+ };
84
+ const cronFieldRanges = [
85
+ cronRange.minute,
86
+ cronRange.hour,
87
+ cronRange.dayOfMonth,
88
+ cronRange.month,
89
+ cronRange.dayOfWeek
90
+ ];
91
+ const runtimeScheduleCreateInputKeys = new Set([
92
+ "cron",
93
+ "enabled",
94
+ "id",
95
+ "input",
96
+ "target",
97
+ "timeZone"
98
+ ]);
99
+ const runtimeScheduleUpdateInputKeys = new Set([
100
+ "cron",
101
+ "enabled",
102
+ "input",
103
+ "target",
104
+ "timeZone"
105
+ ]);
106
+ function parseCronNumber(value, range) {
107
+ if (!/^\d+$/.test(value)) throw new Error("not a number");
108
+ const parsed = Number(value);
109
+ if (!Number.isInteger(parsed) || parsed < range.min || parsed > range.max) throw new Error("out of range");
110
+ return parsed;
111
+ }
112
+ function validateCronPart(part, range) {
113
+ const [value, step, extra] = part.split("/");
114
+ if (extra !== void 0 || value === void 0 || value.length === 0) throw new Error("invalid step");
115
+ if (step !== void 0) {
116
+ if (parseCronNumber(step, {
117
+ max: range.max,
118
+ min: 1
119
+ }) < 1) throw new Error("invalid step");
120
+ }
121
+ if (value === "*") return;
122
+ const [start, end, extraRange] = value.split("-");
123
+ if (extraRange !== void 0 || start === void 0 || start.length === 0) throw new Error("invalid range");
124
+ const parsedStart = parseCronNumber(start, range);
125
+ if (end === void 0) return;
126
+ if (parseCronNumber(end, range) < parsedStart) throw new Error("invalid range");
127
+ }
128
+ function validateRuntimeScheduleCron(cron) {
129
+ if (typeof cron !== "string" || cron.trim() !== cron || cron.length === 0) throw createScheduleError("SCHEDULE_INVALID_CRON", { details: invalidScheduleValueDetails("cron", cron) });
130
+ const fields = cron.split(/\s+/);
131
+ if (fields.length !== 5) throw createScheduleError("SCHEDULE_INVALID_CRON", { details: invalidScheduleValueDetails("cron", cron) });
132
+ try {
133
+ fields.forEach((field, index) => {
134
+ if (field.length === 0) throw new Error("empty field");
135
+ for (const part of field.split(",")) validateCronPart(part, cronFieldRanges[index]);
136
+ });
137
+ } catch {
138
+ throw createScheduleError("SCHEDULE_INVALID_CRON", { details: invalidScheduleValueDetails("cron", cron) });
139
+ }
140
+ }
141
+ function validateRuntimeScheduleTimeZone(timeZone) {
142
+ if (!isIanaTimeZone(timeZone)) throw createScheduleError("SCHEDULE_INVALID_TIME_ZONE", { details: invalidScheduleValueDetails("timeZone", timeZone) });
143
+ }
144
+ async function assertRuntimeTarget(target) {
145
+ if (typeof target !== "string" || !target.trim()) throw createScheduleError("SCHEDULE_INVALID_TARGET", { details: invalidScheduleValueDetails("target", target) });
146
+ const definition = await loadScheduleDefinition(target);
147
+ if (!definition) throw createScheduleError("SCHEDULE_TARGET_NOT_FOUND");
148
+ if (definition.options?.allowRuntimeSchedules !== true) throw createScheduleError("SCHEDULE_TARGET_NOT_ELIGIBLE");
149
+ }
150
+ function assertRuntimeScheduleInputObject(input) {
151
+ if (typeof input !== "object" || input === null || Array.isArray(input)) throw createScheduleError("SCHEDULE_INVALID_INPUT", { details: invalidScheduleValueDetails("input", input) });
152
+ }
153
+ function assertRuntimeScheduleInputKeys(input, allowed) {
154
+ if (Object.keys(input).find((key) => !allowed.has(key))) throw createScheduleError("SCHEDULE_INVALID_INPUT", { details: invalidScheduleValueDetails("input", input) });
155
+ }
156
+ async function validateCreateInput(input) {
157
+ assertRuntimeScheduleInputObject(input);
158
+ assertRuntimeScheduleInputKeys(input, runtimeScheduleCreateInputKeys);
159
+ await assertRuntimeTarget(input.target);
160
+ validateRuntimeScheduleCron(input.cron);
161
+ if (input.id !== void 0) assertRuntimeScheduleId(input.id);
162
+ if (input.enabled !== void 0 && typeof input.enabled !== "boolean") throw createScheduleError("SCHEDULE_INVALID_ENABLED", { details: invalidScheduleValueDetails("enabled", input.enabled) });
163
+ if (input.timeZone !== void 0) validateRuntimeScheduleTimeZone(input.timeZone);
164
+ }
165
+ async function validateUpdateInput(input) {
166
+ assertRuntimeScheduleInputObject(input);
167
+ assertRuntimeScheduleInputKeys(input, runtimeScheduleUpdateInputKeys);
168
+ if (input.target !== void 0) await assertRuntimeTarget(input.target);
169
+ if (input.cron !== void 0) validateRuntimeScheduleCron(input.cron);
170
+ if (input.enabled !== void 0 && typeof input.enabled !== "boolean") throw createScheduleError("SCHEDULE_INVALID_ENABLED", { details: invalidScheduleValueDetails("enabled", input.enabled) });
171
+ if (input.timeZone !== void 0) validateRuntimeScheduleTimeZone(input.timeZone);
172
+ }
173
+ async function updateRuntimeSchedule(id, input) {
174
+ assertRuntimeScheduleId(id);
175
+ await validateUpdateInput(input);
176
+ const updated = await getRuntimeScheduleStore().update(id, {
177
+ ...input,
178
+ updatedAt: /* @__PURE__ */ new Date()
179
+ });
180
+ if (!updated) throw createScheduleError("SCHEDULE_NOT_FOUND");
181
+ return updated;
182
+ }
183
+ const schedules = {
184
+ async create(input) {
185
+ await validateCreateInput(input);
186
+ const now = /* @__PURE__ */ new Date();
187
+ return await getRuntimeScheduleStore().create({
188
+ createdAt: now,
189
+ cron: input.cron,
190
+ enabled: input.enabled ?? true,
191
+ id: input.id ?? randomId("sched"),
192
+ ...input.input !== void 0 ? { input: input.input } : {},
193
+ target: input.target,
194
+ ...input.timeZone ? { timeZone: input.timeZone } : {},
195
+ updatedAt: now
196
+ });
197
+ },
198
+ async delete(id) {
199
+ return await getRuntimeScheduleStore().delete(id);
200
+ },
201
+ async disable(id) {
202
+ return await updateRuntimeSchedule(id, { enabled: false });
203
+ },
204
+ async enable(id) {
205
+ return await updateRuntimeSchedule(id, { enabled: true });
206
+ },
207
+ async get(id) {
208
+ return await getRuntimeScheduleStore().get(id);
209
+ },
210
+ async getRun(id) {
211
+ return await getScheduleRunStore().getRun(id);
212
+ },
213
+ async list() {
214
+ return await getRuntimeScheduleStore().list();
215
+ },
216
+ async listAttempts(runId) {
217
+ return await getScheduleRunStore().listAttempts(runId);
218
+ },
219
+ async listRuns() {
220
+ return await getScheduleRunStore().listRuns();
221
+ },
222
+ async run(id, options = {}) {
223
+ return await executeRuntimeSchedule({
224
+ id,
225
+ scheduledAt: options.scheduledAt
226
+ });
227
+ },
228
+ async update(id, input) {
229
+ return await updateRuntimeSchedule(id, input);
230
+ }
231
+ };
232
+ //#endregion
233
+ export { validateRuntimeScheduleCron as n, schedules as t };
@@ -0,0 +1,7 @@
1
+ import { S as ScheduleTargetDefinitionInput, c as ScheduleDefinition, l as ScheduleDefinitionInput, x as ScheduleTargetDefinition } from "./types-Bcje4dLV.js";
2
+
3
+ //#region src/definition.d.ts
4
+ declare function defineSchedule<TResult = unknown>(input: ScheduleDefinitionInput<TResult>): ScheduleDefinition<TResult>;
5
+ declare function defineScheduleTarget<TInput = unknown, TResult = unknown>(input: ScheduleTargetDefinitionInput<TInput, TResult>): ScheduleTargetDefinition<TInput, TResult>;
6
+ //#endregion
7
+ export { defineSchedule, defineScheduleTarget };
@@ -0,0 +1,42 @@
1
+ //#region src/definition.ts
2
+ const cronFieldPattern = /^[^\s]+$/;
3
+ const scheduleDefinitionKeys = new Set([
4
+ "allowRuntimeSchedules",
5
+ "cron",
6
+ "handler"
7
+ ]);
8
+ const scheduleTargetDefinitionKeys = new Set(["handler"]);
9
+ function isPlainObject(value) {
10
+ return !!value && typeof value === "object" && !Array.isArray(value);
11
+ }
12
+ function validateCron(cron) {
13
+ if (typeof cron !== "string" || cron.trim() !== cron || cron.length === 0) throw new TypeError("`defineSchedule()` requires a cron string.");
14
+ const fields = cron.split(/\s+/);
15
+ if (fields.length !== 5 || !fields.every((field) => cronFieldPattern.test(field))) throw new TypeError("`defineSchedule()` cron must be a five-field UTC cron expression.");
16
+ }
17
+ function defineSchedule(input) {
18
+ if (!isPlainObject(input)) throw new TypeError("`defineSchedule()` expects an object with `cron` and `handler`.");
19
+ const unknownKey = Object.keys(input).find((key) => !scheduleDefinitionKeys.has(key));
20
+ if (unknownKey) throw new TypeError(`\`defineSchedule()\` does not support the "${unknownKey}" option.`);
21
+ validateCron(input.cron);
22
+ if (typeof input.handler !== "function") throw new TypeError("`defineSchedule()` requires a schedule handler.");
23
+ if (typeof input.allowRuntimeSchedules !== "undefined" && typeof input.allowRuntimeSchedules !== "boolean") throw new TypeError("`defineSchedule()` allowRuntimeSchedules must be a boolean.");
24
+ const definition = {
25
+ cron: input.cron,
26
+ handler: input.handler
27
+ };
28
+ if (typeof input.allowRuntimeSchedules !== "undefined") definition.options = { allowRuntimeSchedules: input.allowRuntimeSchedules };
29
+ return definition;
30
+ }
31
+ function defineScheduleTarget(input) {
32
+ if (!isPlainObject(input)) throw new TypeError("`defineScheduleTarget()` expects an object with `handler`.");
33
+ const unknownKey = Object.keys(input).find((key) => !scheduleTargetDefinitionKeys.has(key));
34
+ if (unknownKey) throw new TypeError(`\`defineScheduleTarget()\` does not support the "${unknownKey}" option.`);
35
+ if (typeof input.handler !== "function") throw new TypeError("`defineScheduleTarget()` requires a schedule handler.");
36
+ return {
37
+ handler: input.handler,
38
+ options: { allowRuntimeSchedules: true }
39
+ };
40
+ }
41
+ //#endregion
42
+ export { defineSchedule, defineScheduleTarget };