@vite-hub/schedule 0.0.4 → 0.1.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 (49) hide show
  1. package/README.md +68 -5
  2. package/dist/definition-CMiOg1lg.js +111 -0
  3. package/dist/definition.d.ts +4 -6
  4. package/dist/definition.js +2 -42
  5. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  6. package/dist/error-diagnostics-in7mif5s.js +45 -0
  7. package/dist/execute-BJrgNgQ0.js +201 -0
  8. package/dist/index.d.ts +7 -40
  9. package/dist/index.js +2 -7
  10. package/dist/inspect-DTfAo5gS.js +118 -0
  11. package/dist/kv-storage-Bv9ocZT-.d.ts +18 -0
  12. package/dist/nuxt.d.ts +4 -6
  13. package/dist/nuxt.js +2 -1
  14. package/dist/operations-gk2qzhYV.js +131 -0
  15. package/dist/operations-tNUdj3G4.d.ts +212 -0
  16. package/dist/operations.d.ts +61 -0
  17. package/dist/operations.js +921 -0
  18. package/dist/registry-module.d.ts +0 -5
  19. package/dist/runtime/kv.d.ts +4 -0
  20. package/dist/{kv-BJ1I9IlJ.js → runtime/kv.js} +1 -1
  21. package/dist/runtime/process.d.ts +26 -5
  22. package/dist/runtime/process.js +337 -75
  23. package/dist/runtime/state.d.ts +8 -12
  24. package/dist/runtime/state.js +2 -2
  25. package/dist/runtime/static.d.ts +18 -12
  26. package/dist/runtime/static.js +2 -150
  27. package/dist/runtime.d.ts +36 -4
  28. package/dist/runtime.js +5 -3
  29. package/dist/state-DSxmHPn3.js +448 -0
  30. package/dist/static-6g82xguw.js +245 -0
  31. package/dist/store-QAOd8bxm.d.ts +11 -0
  32. package/dist/types-CHdV9FQU.d.ts +113 -0
  33. package/dist/vite-BAVyZ8hZ.d.ts +474 -0
  34. package/dist/{vite-BHs17nWX.js → vite-BJwZkMrn.js} +1366 -339
  35. package/dist/vite.d.ts +2 -52
  36. package/dist/vite.js +2 -3
  37. package/dist/wait-until-BmIqRo4x.js +87 -0
  38. package/package.json +67 -21
  39. package/dist/client-DpCD4YFE.js +0 -233
  40. package/dist/discovery-DkFAN7Wd.d.ts +0 -15
  41. package/dist/discovery-DvU3B6iD.js +0 -753
  42. package/dist/due-Bbh4yIxq.js +0 -59
  43. package/dist/execute-B-pii4wf.js +0 -211
  44. package/dist/runtime/driver.d.ts +0 -26
  45. package/dist/runtime/driver.js +0 -337
  46. package/dist/state-By7WU_ks.js +0 -472
  47. package/dist/store-t-74rsM_.d.ts +0 -48
  48. package/dist/types-Bcje4dLV.d.ts +0 -136
  49. package/dist/wait-until-BzIwzXw4.js +0 -23
package/README.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # @vite-hub/schedule
2
2
 
3
+ [![npm version](https://comark-ui.onmax.me/badge.svg?source=npm-version&package=%40vite-hub%2Fschedule&icon=npm)](https://npmx.dev/package/@vite-hub/schedule)
4
+ [![npm downloads](https://comark-ui.onmax.me/badge.svg?source=npm-downloads&package=%40vite-hub%2Fschedule&period=month&icon=npm)](https://npmx.dev/package/@vite-hub/schedule)
5
+ [![license](https://comark-ui.onmax.me/badge.svg?label=license&value=Apache-2.0)](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
6
+ [![docs](https://comark-ui.onmax.me/badge.svg?label=docs&value=vitehub.dev)](https://vitehub.dev/docs)
7
+
3
8
  `@vite-hub/schedule` discovers recurring work, generates cron output for supported hosts, and manages recurring schedules that an application creates while it runs.
4
9
 
5
10
  ## Choose the package
@@ -48,10 +53,11 @@ A Runtime Schedule must name a Schedule Target. A Static Schedule Definition can
48
53
 
49
54
  ## Run one occurrence
50
55
 
51
- This smoke test uses the direct owner-package import. If the application installed `vite-hub`, import the same names from `vite-hub/schedule`. It defines a Static Schedule and executes one fixed occurrence without a Vite config or hosted scheduler.
56
+ This smoke test uses the direct owner-package import. If the application installed `vite-hub`, use `vite-hub/schedule` and `vite-hub/schedule/runtime`. It defines a Static Schedule and executes one fixed occurrence without a Vite config or hosted scheduler.
52
57
 
53
58
  ```ts
54
- import { defineSchedule, executeStaticSchedule } from "@vite-hub/schedule";
59
+ import { defineSchedule } from "@vite-hub/schedule";
60
+ import { executeStaticSchedule } from "@vite-hub/schedule/runtime";
55
61
 
56
62
  const dailyReport = defineSchedule({
57
63
  cron: "0 8 * * *",
@@ -157,7 +163,19 @@ Omitting `timeZone` during an update preserves the stored zone. Set it to `UTC`
157
163
 
158
164
  ## Choose storage and wake ownership
159
165
 
160
- Memory stores are the default for direct calls. They are process-local and lose Runtime Schedules and Schedule Run history on restart. Use `createKVRuntimeScheduleStore()` and `createKVScheduleRunStore()` when those records must survive a restart. The default KV-backed stores require `@vite-hub/kv`; custom stores can implement the public store interfaces instead.
166
+ Memory stores are the default for direct calls. They are process-local and lose Runtime Schedules and Schedule Run history on restart. Use `createKVRuntimeScheduleStore({ kvStore })` and `createKVScheduleRunStore({ kvStore })` when those records must survive a restart. Both factories require an explicit `ScheduleKVStorage`. Static schedules, memory stores, and custom storage do not require `@vite-hub/kv`.
167
+
168
+ To use ViteHub KV, install `@vite-hub/kv` and import the adapter explicitly:
169
+
170
+ ```ts
171
+ import { createKVRuntimeScheduleStore, createKVScheduleRunStore } from "@vite-hub/schedule/runtime"
172
+ import { scheduleKVStorage } from "@vite-hub/schedule/runtime/kv"
173
+
174
+ const runtimeScheduleStore = createKVRuntimeScheduleStore({ kvStore: scheduleKVStorage })
175
+ const scheduleRunStore = createKVScheduleRunStore({ kvStore: scheduleKVStorage })
176
+ ```
177
+
178
+ Migration: replace factory calls without `kvStore` with the explicit adapter shown above. Generated Process Runtime wiring selects this adapter automatically. Applications using the framework can import it from `vite-hub/schedule/runtime/kv`.
161
179
 
162
180
  The generated Process Runtime creates both stores through the default KV store configured by `hubKv()`. It scans inside the Node.js process and runs discovered Static Schedule Definitions with stored Runtime Schedules. Configure it only for one long-lived replica:
163
181
 
@@ -185,13 +203,58 @@ With the Process Runtime, the default `providerOutput: "auto"` emits no host Pro
185
203
 
186
204
  `installScheduleRuntime()` returns only after its driver reconciles the complete stored snapshot, including disabled Runtime Schedules. Later creates, updates, and deletes persist first and reconcile one at a time. If host reconciliation fails, ViteHub restores the previous stored record and rejects the change.
187
205
 
188
- When a custom host installs a wake driver, call and await `controller.close()` during shutdown. Closing stops new wakes, drains active wakes and `waitUntil()` work, and releases driver resources. It does not delete Schedule Definitions, Runtime Schedules, or run history. The generated Nitro Process Runtime connects the same close operation to Nitro shutdown and process termination signals.
206
+ When a custom host installs a wake driver, call and await `controller.close()` during shutdown. Closing stops new wakes, drains active wakes and `waitUntil()` work, and releases driver resources. It does not delete Schedule Definitions, Runtime Schedules, or run history. The generated Nitro Process Runtime registers the same close operation with ViteHub shutdown, so it runs on a stop signal before the server closes HTTP, or when Nitro closes. See [graceful shutdown](../runtime/README.md).
207
+
208
+ ## Inspect Runtime Schedules
209
+
210
+ `hubSchedule()` contributes the `schedule.runs`, `schedule.attempts`, and `schedule.run` operations. They are the `vitehub schedule runs <id> [--limit <n>]`, `attempts <runId>`, and `run <name>` commands, and the Console runs them too. Each command accepts `--json` and `--url`. Without `--url` the command calls the dev server of the project, whose Nitro runtime owns the same stores and registry as the running app. The operations import from `@vite-hub/schedule/operations`.
211
+
212
+ Set `manual: true` on a Static Schedule Definition to allow an on-demand run, then invoke it with `vitehub schedule run <name>`. The name is the discovered schedule file name. Add `--url <app-url>` with the Console credentials to run it on a deployment that enables `console.invoke`. A CI job can post a signed dispatch (`vitehub secret derive vitehub:dispatch`) to `/_vitehub/schedules/run` instead.
213
+
214
+ Discovery reads `manual` and `allowRuntimeSchedules` as literal booleans from directly exported Definitions. Use identifier keys or quoted keys without escape sequences. Spreads, computed keys, escaped keys, and metadata getters or methods fail with the source file and line.
215
+
216
+ The Console Schedules section is a record table. Build-time records list Schedule Definitions. `readScheduleConsoleRecords()` from `@vite-hub/schedule/runtime/console` adds Runtime Schedules with enabled state, next run, last run, and run history on each request. The Console is read-only. A Runtime Schedule with `console: { enabled: false }` is hidden there. The CLI and the Console redact credentials in Schedule input and error messages.
217
+
218
+ ## Import runtime helpers
219
+
220
+ The main `@vite-hub/schedule` entry exports `defineSchedule`, `defineScheduleTarget`, `schedules`, `validateRuntimeScheduleCron`, and public types. Import execution, storage, and runtime state helpers from `@vite-hub/schedule/runtime`. Import `discoverScheduleDefinitions` from `@vite-hub/schedule/vite` when writing a build integration. Applications use `vite-hub/schedule` and `vite-hub/schedule/runtime`.
221
+
222
+ Static Schedule execution logs each failed handler as `[vitehub:schedule] Schedule "<name>" failed` with the message, stack, status, and cause chain. The other schedules on the same cron still finish. The run rejects with the error, or with an `AggregateError` when several failed.
223
+
224
+ Runtime execution helpers accept `captureHandlerFailure: true` to return the persisted failed run after a handler error. Pre-execution guards, including disabled schedules, still throw.
225
+ Manual calls reject an existing disabled Runtime Schedule even when the same occurrence has a saved run. Provider wakes acknowledge saved occurrences after disablement without another handler attempt. A new provider occurrence still requires an enabled schedule.
226
+
227
+ This is a breaking import change. Move existing execution, store, and state helper imports to `/runtime`, and discovery imports to `/vite`. Helper behavior is unchanged. The main entry no longer loads file discovery or its build dependencies.
189
228
 
190
229
  ## Documentation and support
191
230
 
192
- - Read the [Schedule guide](https://vitehub.dev/docs/server-primitives/schedule) for every public import, Runtime Helper, store, wake driver, and Vite option.
231
+ - Read the [Schedule guide](https://vitehub.dev/docs/schedule) for every public import, Runtime Helper, store, wake driver, and Vite option.
193
232
  - Check [Provider Output](https://vitehub.dev/docs/reference/provider-output) for generated files and deployment inspection.
194
233
  - Check [runtime and host support](https://vitehub.dev/docs/frameworks-hosts/support-matrix) for current proof and host qualifications.
195
234
  - Report package problems in the [ViteHub issue tracker](https://github.com/vite-hub/vitehub/issues).
196
235
 
197
236
  Cron parsing uses [`cron-schedule`](https://github.com/P4sca1/cron-schedule).
237
+
238
+
239
+ ## Definition-owned target inputs
240
+
241
+ The Vite Integration writes `.vitehub/schedule.d.ts`. Include it in your TypeScript project. The Nuxt Integration includes it automatically. The generated `ScheduleTargetRegistry` maps eligible names to their definitions. `schedules.create()` checks input against the selected target:
242
+
243
+ ```ts
244
+ const record = await schedules.create({
245
+ target: "daily-report",
246
+ cron: "0 9 * * *",
247
+ input: { prompt: "Summarize yesterday" },
248
+ })
249
+ await schedules.update(record.id, {
250
+ target: "daily-report",
251
+ input: { prompt: "Summarize this week" },
252
+ })
253
+ await schedules.update(record.id, { enabled: false })
254
+ ```
255
+
256
+ When an update changes `input`, also supply `target`. When an update changes `target`, supply the new input or `input: undefined` to clear it. An ID alone does not identify a definition type. Stored records can outlive a deployment, so `get()`, `list()`, and `update()` return unknown input. Handler input remains optional; targets must handle records with no input.
257
+
258
+ Use `schedules.dynamic.create()` and `schedules.dynamic.update()` when names or stored input come from external data. The dynamic methods validate target eligibility and Schedule fields. They do not validate a target's business input. Validate that data in the application and again in a target that reads durable records.
259
+
260
+ This is a breaking change: include the generated declarations for typed application calls, and move operational calls with unknown names to `schedules.dynamic`. There is no permissive string overload on typed creation.
@@ -0,0 +1,111 @@
1
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-in7mif5s.js";
2
+ //#region ../internal/src/runtime/time-zone.ts
3
+ const slashlessIanaTimeZones = /* @__PURE__ */ new Set([
4
+ "CET",
5
+ "CST6CDT",
6
+ "Cuba",
7
+ "EET",
8
+ "EST",
9
+ "EST5EDT",
10
+ "Egypt",
11
+ "Eire",
12
+ "Factory",
13
+ "GB",
14
+ "GB-Eire",
15
+ "GMT",
16
+ "GMT+0",
17
+ "GMT-0",
18
+ "GMT0",
19
+ "Greenwich",
20
+ "HST",
21
+ "Hongkong",
22
+ "Iceland",
23
+ "Iran",
24
+ "Israel",
25
+ "Jamaica",
26
+ "Japan",
27
+ "Kwajalein",
28
+ "Libya",
29
+ "MET",
30
+ "MST",
31
+ "MST7MDT",
32
+ "NZ",
33
+ "NZ-CHAT",
34
+ "Navajo",
35
+ "PRC",
36
+ "PST8PDT",
37
+ "Poland",
38
+ "Portugal",
39
+ "ROC",
40
+ "ROK",
41
+ "Singapore",
42
+ "Turkey",
43
+ "UCT",
44
+ "UTC",
45
+ "Universal",
46
+ "W-SU",
47
+ "WET",
48
+ "Zulu"
49
+ ]);
50
+ function isIanaTimeZone(timeZone) {
51
+ if (typeof timeZone !== "string" || !timeZone.includes("/") && !slashlessIanaTimeZones.has(timeZone)) return false;
52
+ try {
53
+ new Intl.DateTimeFormat("en-US", { timeZone });
54
+ return true;
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+ //#endregion
60
+ //#region src/definition.ts
61
+ const cronFieldPattern = /^[^\s]+$/;
62
+ const scheduleDefinitionKeys = /* @__PURE__ */ new Set([
63
+ "manual",
64
+ "cron",
65
+ "handler",
66
+ "timeZone"
67
+ ]);
68
+ const scheduleOptionsKeys = /* @__PURE__ */ new Set(["manual", "timeZone"]);
69
+ function isPlainObject(value) {
70
+ return !!value && typeof value === "object" && !Array.isArray(value);
71
+ }
72
+ function isCronString(value) {
73
+ return value !== null && value !== void 0 && String(value) === value;
74
+ }
75
+ function assertOwnDefinitionFields(input, keys, message, diagnostic) {
76
+ const inheritedKey = [...keys].find((key) => key in input && !Object.hasOwn(input, key));
77
+ if (inheritedKey) throw diagnostic({ message: `${message} The "${inheritedKey}" option must be an own property.` });
78
+ }
79
+ function validateCron(cron) {
80
+ if (typeof cron !== "string" || cron.trim() !== cron || cron.length === 0) throw scheduleErrorDiagnostics.SCHEDULE_C0001({ message: "`defineSchedule()` requires a cron string." });
81
+ const fields = cron.split(/\s+/);
82
+ if (fields.length !== 5 || !fields.every((field) => cronFieldPattern.test(field))) throw scheduleErrorDiagnostics.SCHEDULE_C0002({ message: "`defineSchedule()` cron must be a five-field cron expression." });
83
+ }
84
+ function defineSchedule(cronOrInput, handler, options = {}) {
85
+ if (!isPlainObject(options)) throw scheduleErrorDiagnostics.SCHEDULE_C0003({ message: "`defineSchedule()` options must be an object." });
86
+ assertOwnDefinitionFields(options, scheduleOptionsKeys, "`defineSchedule()` does not accept inherited options.", scheduleErrorDiagnostics.SCHEDULE_C0004);
87
+ if (!isCronString(cronOrInput) && !isPlainObject(cronOrInput)) throw scheduleErrorDiagnostics.SCHEDULE_C0003({ message: "`defineSchedule()` expects an object with `cron` and `handler`." });
88
+ const input = isPlainObject(cronOrInput) ? cronOrInput : {
89
+ ...options,
90
+ cron: cronOrInput,
91
+ handler
92
+ };
93
+ if (!isPlainObject(input)) throw scheduleErrorDiagnostics.SCHEDULE_C0003({ message: "`defineSchedule()` expects an object with `cron` and `handler`." });
94
+ if (!Object.hasOwn(input, "cron") || !Object.hasOwn(input, "handler")) throw scheduleErrorDiagnostics.SCHEDULE_C0003({ message: "`defineSchedule()` expects an object with `cron` and `handler`." });
95
+ assertOwnDefinitionFields(input, scheduleDefinitionKeys, "`defineSchedule()` does not accept inherited options.", scheduleErrorDiagnostics.SCHEDULE_C0004);
96
+ const unknownKey = Object.keys(input).find((key) => !scheduleDefinitionKeys.has(key));
97
+ if (unknownKey) throw scheduleErrorDiagnostics.SCHEDULE_C0004({ message: `\`defineSchedule()\` does not support the "${unknownKey}" option.` });
98
+ validateCron(input.cron);
99
+ if (typeof input.handler !== "function") throw scheduleErrorDiagnostics.SCHEDULE_C0005({ message: "`defineSchedule()` requires a schedule handler." });
100
+ if (input.manual !== void 0 && input.manual !== true && input.manual !== false) throw scheduleErrorDiagnostics.SCHEDULE_C0006({ message: "`defineSchedule()` manual must be a boolean." });
101
+ if (input.timeZone !== void 0 && !isIanaTimeZone(input.timeZone)) throw scheduleErrorDiagnostics.SCHEDULE_C0006({ message: "`defineSchedule()` timeZone must be an IANA time zone, such as \"Europe/Madrid\"." });
102
+ const definition = {
103
+ cron: input.cron,
104
+ handler: input.handler
105
+ };
106
+ if (input.timeZone !== void 0) definition.timeZone = input.timeZone;
107
+ if (input.manual !== void 0) definition.options = { manual: input.manual };
108
+ return definition;
109
+ }
110
+ //#endregion
111
+ export { defineSchedule as t };
@@ -1,7 +1,5 @@
1
- import { S as ScheduleTargetDefinitionInput, c as ScheduleDefinition, l as ScheduleDefinitionInput, x as ScheduleTargetDefinition } from "./types-Bcje4dLV.js";
2
-
1
+ import { i as ScheduleDefinitionOptions, n as ScheduleDefinition, o as ScheduleHandler, r as ScheduleDefinitionInput } from "./types-CHdV9FQU.js";
3
2
  //#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 };
3
+ export declare function defineSchedule<TResult = unknown>(cron: string, handler: ScheduleHandler<TResult>, options?: ScheduleDefinitionOptions): ScheduleDefinition<TResult>;
4
+ export declare function defineSchedule<TResult = unknown>(input: ScheduleDefinitionInput<TResult>): ScheduleDefinition<TResult>;
5
+ //#endregion
@@ -1,42 +1,2 @@
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 };
1
+ import { t as defineSchedule } from "./definition-CMiOg1lg.js";
2
+ export { defineSchedule };
@@ -0,0 +1,116 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region ../internal/src/error-diagnostics.ts
3
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
+ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
6
+ codes: {
7
+ INTERNAL_R0012: dynamicError,
8
+ INTERNAL_R0013: dynamicError,
9
+ INTERNAL_R0014: {
10
+ why: ({ path }) => `Cannot read Provision State from "${path}".`,
11
+ fix: "Check file access and restore valid JSON while preserving existing resource IDs."
12
+ },
13
+ INTERNAL_R0020: {
14
+ fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
15
+ why: ({ message }) => message === void 0 ? "" : String(message)
16
+ },
17
+ INTERNAL_R0021: {
18
+ fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
19
+ why: ({ message }) => message === void 0 ? "" : String(message)
20
+ },
21
+ INTERNAL_R0022: {
22
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
23
+ why: ({ message }) => message === void 0 ? "" : String(message)
24
+ },
25
+ INTERNAL_R0024: {
26
+ fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app with credentials in VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET.",
27
+ why: ({ message }) => message === void 0 ? "" : String(message)
28
+ },
29
+ INTERNAL_R0023: {
30
+ fix: "Ask for access to the section of this operation.",
31
+ why: ({ message }) => message === void 0 ? "" : String(message)
32
+ },
33
+ INTERNAL_B0001: dynamicError,
34
+ INTERNAL_B0002: dynamicError,
35
+ INTERNAL_B0003: dynamicError,
36
+ INTERNAL_B0004: dynamicError,
37
+ INTERNAL_B0005: dynamicError,
38
+ INTERNAL_B0006: dynamicError,
39
+ INTERNAL_B0007: dynamicError,
40
+ INTERNAL_B0008: dynamicError,
41
+ INTERNAL_B0009: dynamicError,
42
+ INTERNAL_B0010: dynamicError,
43
+ INTERNAL_B0011: dynamicError,
44
+ INTERNAL_B0012: dynamicError,
45
+ INTERNAL_B0013: dynamicError,
46
+ INTERNAL_B0014: dynamicError,
47
+ INTERNAL_B0015: dynamicError,
48
+ INTERNAL_B0016: dynamicError,
49
+ INTERNAL_B0017: dynamicError,
50
+ INTERNAL_B0018: dynamicError,
51
+ INTERNAL_B0019: dynamicError,
52
+ INTERNAL_B0020: dynamicError,
53
+ INTERNAL_B0021: dynamicError,
54
+ INTERNAL_B0022: dynamicError,
55
+ INTERNAL_B0023: dynamicError,
56
+ INTERNAL_B0024: dynamicError,
57
+ INTERNAL_B0025: dynamicError,
58
+ INTERNAL_B0026: dynamicError,
59
+ INTERNAL_B0027: dynamicError,
60
+ INTERNAL_B0028: dynamicError,
61
+ INTERNAL_B0029: dynamicError,
62
+ INTERNAL_B0030: dynamicError,
63
+ INTERNAL_B0031: dynamicError,
64
+ INTERNAL_B0032: dynamicError,
65
+ INTERNAL_B0033: dynamicError,
66
+ INTERNAL_B0034: dynamicError,
67
+ INTERNAL_B0035: dynamicError,
68
+ INTERNAL_B0036: dynamicError,
69
+ INTERNAL_B0037: dynamicError,
70
+ INTERNAL_B0038: dynamicError,
71
+ INTERNAL_B0039: dynamicError,
72
+ INTERNAL_B0040: dynamicError,
73
+ INTERNAL_B0041: dynamicError,
74
+ INTERNAL_B0042: dynamicError,
75
+ INTERNAL_B0043: dynamicError,
76
+ INTERNAL_B0044: dynamicError,
77
+ INTERNAL_B0045: dynamicError,
78
+ INTERNAL_B0046: dynamicError,
79
+ INTERNAL_B0047: dynamicError,
80
+ INTERNAL_B0048: {
81
+ fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
82
+ why: ({ message }) => message === void 0 ? "" : String(message)
83
+ },
84
+ INTERNAL_B0049: {
85
+ fix: "Set `cli: { namespace, command }` on one of the two operations.",
86
+ why: ({ message }) => message === void 0 ? "" : String(message)
87
+ },
88
+ INTERNAL_B0050: {
89
+ fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
90
+ why: ({ message }) => message === void 0 ? "" : String(message)
91
+ },
92
+ INTERNAL_R0025: {
93
+ fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
94
+ why: ({ message }) => message === void 0 ? "" : String(message)
95
+ },
96
+ INTERNAL_R0026: {
97
+ why: "The server parsed a destructive operation that the CLI did not confirm.",
98
+ fix: "Review the operation, then run it again with --yes to confirm the change."
99
+ },
100
+ INTERNAL_C0001: dynamicError,
101
+ INTERNAL_C0002: dynamicError,
102
+ INTERNAL_R0001: dynamicError,
103
+ INTERNAL_R0002: dynamicError,
104
+ INTERNAL_R0003: dynamicError,
105
+ INTERNAL_R0004: dynamicError,
106
+ INTERNAL_R0005: dynamicError,
107
+ INTERNAL_R0006: dynamicError,
108
+ INTERNAL_R0007: dynamicError,
109
+ INTERNAL_R0008: dynamicError,
110
+ INTERNAL_R0009: dynamicError,
111
+ INTERNAL_R0010: dynamicError,
112
+ INTERNAL_R0011: dynamicError
113
+ }
114
+ });
115
+ //#endregion
116
+ export { internalErrorDiagnostics as t };
@@ -0,0 +1,45 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region src/error-diagnostics.ts
3
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
+ const scheduleErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
6
+ codes: {
7
+ SCHEDULE_C0001: dynamicError,
8
+ SCHEDULE_C0002: dynamicError,
9
+ SCHEDULE_C0003: dynamicError,
10
+ SCHEDULE_C0004: dynamicError,
11
+ SCHEDULE_C0005: dynamicError,
12
+ SCHEDULE_C0006: dynamicError,
13
+ SCHEDULE_R0001: dynamicError,
14
+ SCHEDULE_R0002: dynamicError,
15
+ SCHEDULE_R0003: dynamicError,
16
+ SCHEDULE_R0004: dynamicError,
17
+ SCHEDULE_R0005: dynamicError,
18
+ SCHEDULE_R0006: dynamicError,
19
+ SCHEDULE_R0022: dynamicError,
20
+ SCHEDULE_R0023: dynamicError,
21
+ SCHEDULE_R0024: dynamicError,
22
+ SCHEDULE_R0025: dynamicError,
23
+ SCHEDULE_R0026: dynamicError,
24
+ SCHEDULE_R0027: dynamicError,
25
+ SCHEDULE_R0028: dynamicError,
26
+ SCHEDULE_R0030: dynamicError,
27
+ SCHEDULE_R0031: dynamicError,
28
+ SCHEDULE_R0032: dynamicError,
29
+ SCHEDULE_R0033: dynamicError,
30
+ SCHEDULE_R0034: dynamicError,
31
+ SCHEDULE_R0035: dynamicError,
32
+ SCHEDULE_R0036: dynamicError,
33
+ SCHEDULE_R0037: dynamicError,
34
+ SCHEDULE_R0038: dynamicError,
35
+ SCHEDULE_B0001: dynamicError,
36
+ SCHEDULE_B0002: dynamicError,
37
+ SCHEDULE_B0003: dynamicError,
38
+ SCHEDULE_B0004: dynamicError,
39
+ SCHEDULE_B0005: dynamicError,
40
+ SCHEDULE_B0006: dynamicError,
41
+ SCHEDULE_B0007: dynamicError
42
+ }
43
+ });
44
+ //#endregion
45
+ export { scheduleErrorDiagnostics as t };
@@ -0,0 +1,201 @@
1
+ import { i as createScheduleError, r as validateScheduledAt, t as runWithScheduleWaitUntil } from "./wait-until-BmIqRo4x.js";
2
+ import { r as loadScheduleDefinition, t as getScheduleRunStore } from "./state-DSxmHPn3.js";
3
+ import { serializeResponse, toResponse } from "@vite-hub/runtime";
4
+ //#region ../internal/src/runtime/random.ts
5
+ function randomId(prefix) {
6
+ const body = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
7
+ return prefix ? `${prefix}_${body}` : body;
8
+ }
9
+ //#endregion
10
+ //#region src/runtime/execute.ts
11
+ function normalizeRunSource(source) {
12
+ return source ?? "direct";
13
+ }
14
+ /** Returns the Schedule Run id for one scheduled occurrence, with an optional unique suffix. */
15
+ function toRunId(source, scheduleId, scheduledAt, runIdSuffix) {
16
+ return `srun_${normalizeRunSource(source)}_${encodeURIComponent(scheduleId)}_${scheduledAt.toISOString()}${runIdSuffix ? `_${runIdSuffix}` : ""}`;
17
+ }
18
+ function toRunError(error) {
19
+ try {
20
+ if (error instanceof Error) return {
21
+ message: error.message,
22
+ name: error.name,
23
+ stack: error.stack
24
+ };
25
+ return { message: String(error) };
26
+ } catch {
27
+ return { message: "[unprintable thrown value]" };
28
+ }
29
+ }
30
+ function requireUpdatedRun(run) {
31
+ if (!run) throw createScheduleError("SCHEDULE_RUN_NOT_FOUND");
32
+ return run;
33
+ }
34
+ async function createOrGetRun(options) {
35
+ const store = options.runStore ?? getScheduleRunStore();
36
+ const id = toRunId(options.source, options.scheduleId, options.scheduledAt, options.runIdSuffix);
37
+ const existing = await store.getRun(id);
38
+ if (existing) return {
39
+ created: false,
40
+ run: existing
41
+ };
42
+ const now = /* @__PURE__ */ new Date();
43
+ const runInput = {
44
+ attemptCount: 0,
45
+ createdAt: now,
46
+ id,
47
+ scheduleId: options.scheduleId,
48
+ scheduledAt: options.scheduledAt,
49
+ status: "pending",
50
+ target: options.target,
51
+ updatedAt: now
52
+ };
53
+ try {
54
+ return {
55
+ created: true,
56
+ run: await store.createRun(runInput)
57
+ };
58
+ } catch (error) {
59
+ const run = await store.getRun(id);
60
+ if (run) return {
61
+ created: false,
62
+ run
63
+ };
64
+ throw error;
65
+ }
66
+ }
67
+ async function startAttempt(run, store = getScheduleRunStore()) {
68
+ const now = /* @__PURE__ */ new Date();
69
+ const attempt = await store.createAttempt({
70
+ createdAt: now,
71
+ id: randomId("satt"),
72
+ runId: run.id,
73
+ startedAt: now,
74
+ status: "running",
75
+ updatedAt: now
76
+ });
77
+ await store.updateRun(run.id, {
78
+ attemptCount: run.attemptCount + 1,
79
+ startedAt: run.startedAt ?? now,
80
+ status: "running",
81
+ updatedAt: now
82
+ });
83
+ return attempt;
84
+ }
85
+ function toHandlerContext(run, attempt, waitUntil) {
86
+ return {
87
+ attemptId: attempt.id,
88
+ id: run.id,
89
+ runId: run.id,
90
+ scheduleId: run.scheduleId,
91
+ scheduledAt: run.scheduledAt,
92
+ target: run.target,
93
+ waitUntil
94
+ };
95
+ }
96
+ async function completeRun(run, attempt, response, store = getScheduleRunStore()) {
97
+ const now = /* @__PURE__ */ new Date();
98
+ await store.updateAttempt(attempt.id, {
99
+ completedAt: now,
100
+ status: "succeeded",
101
+ updatedAt: now
102
+ });
103
+ return requireUpdatedRun(await store.updateRun(run.id, {
104
+ completedAt: now,
105
+ response,
106
+ status: "succeeded",
107
+ updatedAt: now
108
+ }));
109
+ }
110
+ async function failRun(run, attempt, error, store = getScheduleRunStore()) {
111
+ const now = /* @__PURE__ */ new Date();
112
+ const serializedError = toRunError(error);
113
+ await store.updateAttempt(attempt.id, {
114
+ completedAt: now,
115
+ error: serializedError,
116
+ status: "failed",
117
+ updatedAt: now
118
+ });
119
+ return requireUpdatedRun(await store.updateRun(run.id, {
120
+ completedAt: now,
121
+ error: serializedError,
122
+ status: "failed",
123
+ updatedAt: now
124
+ }));
125
+ }
126
+ async function createScheduleRun(options) {
127
+ const scheduledAt = validateScheduledAt(options.scheduledAt ?? /* @__PURE__ */ new Date());
128
+ return (await createOrGetRun({
129
+ ...options,
130
+ scheduledAt
131
+ })).run;
132
+ }
133
+ async function executeSchedule(options) {
134
+ const scheduledAt = validateScheduledAt(options.scheduledAt ?? /* @__PURE__ */ new Date());
135
+ const { created, run } = await createOrGetRun({
136
+ ...options,
137
+ scheduledAt
138
+ });
139
+ if (!created) return run;
140
+ const runStore = options.runStore ?? getScheduleRunStore();
141
+ const attempt = await startAttempt(run, runStore);
142
+ try {
143
+ const value = await runWithScheduleWaitUntil((waitUntil) => options.definition.handler(toHandlerContext(run, attempt, waitUntil)), options.waitUntil);
144
+ return await completeRun(run, attempt, await serializeResponse(toResponse(value)), runStore);
145
+ } catch (error) {
146
+ const failed = await failRun(run, attempt, error, runStore);
147
+ if (options.captureHandlerFailure) return failed;
148
+ throw error;
149
+ }
150
+ }
151
+ async function executeStaticSchedule(options) {
152
+ return await executeSchedule({
153
+ definition: options.definition,
154
+ scheduleId: options.name,
155
+ source: "static",
156
+ scheduledAt: options.scheduledAt,
157
+ target: options.name,
158
+ waitUntil: options.waitUntil
159
+ });
160
+ }
161
+ function isObjectRecord(value) {
162
+ return Object(value) === value && !Array.isArray(value);
163
+ }
164
+ function isStaticScheduleDefinition(value) {
165
+ return isObjectRecord(value) && Object.hasOwn(value, "handler") && typeof value.handler === "function" && Object.hasOwn(value, "cron");
166
+ }
167
+ async function loadStaticScheduleDefinition(name, registry) {
168
+ let loaded;
169
+ if (registry) {
170
+ const entry = Object.hasOwn(registry, name) ? registry[name] : void 0;
171
+ loaded = typeof entry === "function" ? await entry() : void 0;
172
+ } else loaded = await loadScheduleDefinition(name);
173
+ const record = isObjectRecord(loaded) ? loaded : void 0;
174
+ return record && isStaticScheduleDefinition(record) ? record : record && Object.hasOwn(record, "default") && isStaticScheduleDefinition(record.default) ? record.default : void 0;
175
+ }
176
+ /** Runs a manually dispatchable static Schedule Definition immediately. */
177
+ async function runSchedule(name, options = {}) {
178
+ const definition = typeof name === "string" && name ? await loadStaticScheduleDefinition(name, options.registry) : void 0;
179
+ if (!definition) throw createScheduleError("SCHEDULE_DEFINITION_NOT_FOUND");
180
+ if (definition.options?.manual !== true) throw createScheduleError("SCHEDULE_MANUAL_RUN_DISABLED");
181
+ const runStore = getScheduleRunStore();
182
+ const scheduledAt = /* @__PURE__ */ new Date();
183
+ const runIdSuffix = randomId("manual");
184
+ try {
185
+ return await executeSchedule({
186
+ definition,
187
+ runIdSuffix,
188
+ runStore,
189
+ scheduleId: name,
190
+ source: "manual",
191
+ scheduledAt,
192
+ target: name
193
+ });
194
+ } catch (error) {
195
+ const run = await runStore.getRun(toRunId("manual", name, scheduledAt, runIdSuffix));
196
+ if (run?.status === "failed") return run;
197
+ throw error;
198
+ }
199
+ }
200
+ //#endregion
201
+ export { runSchedule as i, executeSchedule as n, executeStaticSchedule as r, createScheduleRun as t };