@vite-hub/schedule 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +12 -7
  2. package/dist/{console-wEhr0LWn.d.ts → console-DueeEBcM.d.ts} +2 -0
  3. package/dist/cron-C1l3TquN.js +70 -0
  4. package/dist/definition.js +1 -2
  5. package/dist/{due-sOJvF_6Z.js → due-n120-_nz.js} +22 -7
  6. package/dist/durability.d.ts +2 -2
  7. package/dist/durability.js +5 -5
  8. package/dist/{error-diagnostics-CQ4BUqRe.js → error-diagnostics-C0KyI408.js} +5 -1
  9. package/dist/{error-diagnostics-BBtYYl8j.js → error-diagnostics-DTmP6baC.js} +1 -5
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.js +3 -4
  12. package/dist/{started-name-ruCM1EtQ.js → inspect-DTfAo5gS.js} +1 -5
  13. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CI2PJGqu.d.ts} +8 -2
  14. package/dist/{operations-DqwmJ8MN.js → operations-DlrK9mlH.js} +6 -9
  15. package/dist/operations.d.ts +1 -1
  16. package/dist/operations.js +5 -5
  17. package/dist/os.d.ts +0 -1
  18. package/dist/os.js +12 -84
  19. package/dist/out-BbXG-yVX.js +21755 -0
  20. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  21. package/dist/runtime/console.d.ts +1 -1
  22. package/dist/runtime/console.js +2 -2
  23. package/dist/runtime/process.js +24 -45
  24. package/dist/runtime/state.d.ts +1 -1
  25. package/dist/runtime/state.js +1 -1
  26. package/dist/runtime/static.d.ts +2 -73
  27. package/dist/runtime/static.js +3 -2
  28. package/dist/runtime.d.ts +3 -3
  29. package/dist/runtime.js +4 -4
  30. package/dist/{started-B0pc3JY0.js → started-BWWr7Ufw.js} +3 -4
  31. package/dist/{started-Bk2Icknk.js → started-BXdWMdji.js} +24 -6
  32. package/dist/{started-errors-DEmYH-vp.js → started-errors-BMg04lL3.js} +45 -5
  33. package/dist/started-name-DudQ0fsR.js +5 -0
  34. package/dist/{state-D4SZH6zk.js → state-BjWnxyhv.js} +70 -117
  35. package/dist/{state-CPd10SXq.d.ts → state-CJKAhskJ.d.ts} +2 -1
  36. package/dist/static-BgoOCoe5.js +610 -0
  37. package/dist/static-CcBWx1kU.d.ts +96 -0
  38. package/dist/{store-DeMojnXM.d.ts → store-CZHZfttA.d.ts} +2 -6
  39. package/dist/vite.d.ts +5 -3
  40. package/dist/vite.js +2251 -130
  41. package/package.json +4 -4
  42. package/dist/invariant-DolT9EEx.js +0 -22
  43. package/dist/static-7JCga3Iu.js +0 -281
  44. package/dist/wait-until-Dy4Bn3ZN.js +0 -112
package/README.md CHANGED
@@ -104,7 +104,7 @@ export default defineSchedule({
104
104
 
105
105
  Static Schedule Definitions use five-field cron expressions. The cron uses UTC unless the definition sets `timeZone` to an IANA name, such as `Europe/Madrid`. `timeZone` works with the Process Runtime and with every host's cron output.
106
106
 
107
- The integration can generate host-specific output for Cloudflare Cron Triggers, Vercel Cron Jobs, Netlify Scheduled Functions, standalone `Deno.cron`, Nitro's Cloudflare schedule hook, and Netlify Scheduled Functions that run in Nitro's server bundle. A build writes only the output of its host: Nitro's resolved preset, or else `nitro.preset`, `NITRO_PRESET`, `SERVER_PRESET`, or `VITEHUB_HOST`. It writes the output of every host only when no host is known. Host selection, local execution, deployment proof, limits, and billing still come from the selected host. Check the [runtime and host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix) before deploying.
107
+ The integration can generate host-specific output for Cloudflare Cron Triggers, Vercel Cron Jobs, Netlify Scheduled Functions, standalone `Deno.cron`, Nitro's Cloudflare schedule hook, and Netlify Scheduled Functions that run in Nitro's server bundle. A build writes only the output of its host: Nitro's resolved preset, or else `nitro.preset`, `NITRO_PRESET`, `SERVER_PRESET`, or `VITEHUB_HOST`. It writes the output of every host only when no host is known. Host selection, local execution, deployment proof, limits, and billing still come from the selected host. Check the [runtime and host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix) before deploying. Write weekdays as standard cron numbers, 0 to 6 from Sunday. Cloudflare and Deno number weekdays 1 to 7 from Sunday, so their output writes weekday names: `0 4 * * 1-5` becomes `0 4 * * MON,TUE,WED,THU,FRI`.
108
108
 
109
109
  Applications that use the framework distribution turn Schedule on with a file in `server/schedules/`, with no `schedule` key, and import the definition helper from `vite-hub/schedule`. On Deno, the build writes standalone cron output and a `.output/main.ts` entrypoint that loads it before the Nitro server.
110
110
 
@@ -156,7 +156,8 @@ export default defineSchedule({
156
156
  cron: "0 7 * * *",
157
157
  timeZone: "Europe/Stockholm",
158
158
  async handler({ idempotencyKey }) {
159
- await email.send({ from, to, subject: "Today's lesson", text, idempotencyKey });
159
+ const [error] = await email.send({ from, to, subject: "Today's lesson", text, idempotencyKey });
160
+ if (error) throw error;
160
161
  },
161
162
  });
162
163
  ```
@@ -197,9 +198,9 @@ Every server checks every Schedule. Before a server runs an occurrence, it takes
197
198
  - If the server loses the Database, or its event loop pauses, for longer than `leaseTtlMs`, its lease can expire while its handler still runs. Another server can run the same occurrence at the same time. The runtime reports renewal failures, but cannot stop the handler or undo its effects. Choose a TTL longer than expected pauses and make external effects idempotent.
198
199
  - If the lease store fails before a run starts, the server reports the error and retries at its next scan while the occurrence is inside `catchUpMs`.
199
200
  - A failed run is final, as on one server. It is not retried.
200
- - When a server stops during a run, for example after a crash, its lease ends after `leaseTtlMs`. Then another server runs the occurrence, unless it has a done marker. With shared run history, the run gets a new attempt, and the stopped attempt is marked as failed. This also works when every server restarts: at start, a server reads the runs inside `catchUpMs` that are still pending or running, and tries them again.
201
+ - When a server stops during a run, for example after a crash, its lease ends after `leaseTtlMs`. Then another server runs the occurrence, unless it has a done marker. A server that found the lease held tries the occurrence again until `catchUpMs` plus `leaseTtlMs` plus one minute after its scheduled minute, also with `catchUpMs: 0`. With shared run history, the run gets a new attempt, and the stopped attempt is marked as failed. This also works when every server restarts: at start, a server reads the runs inside `catchUpMs` that are still pending or running, and tries them again.
201
202
 
202
- The generated runtime keeps the leases in the `vitehub_leases` table of the Default Database, through `useLeases()` from `@vite-hub/database`. That works on Postgres, remote libSQL, and D1. A local libSQL file is safe for one server process only, because `@libsql/client` can lose writes when several processes write to one file. The server prints a warning at the first lease in that case. Without a Database, the leases stay in memory and the build reports the hint `SCHEDULE_PROCESS_CLAIMS_IN_MEMORY` in its output and in `.vitehub/hints.json`: each server then runs every occurrence, so run one server only. The run history stays in KV. Use a KV store that all servers share, such as Upstash, so catch-up and the Console see the runs of every server.
203
+ The generated runtime keeps the leases in the `vitehub_leases` table of the Default Database, through `useLeases()` from `@vite-hub/database`. That works on Postgres, with postgres.js or node-postgres, remote libSQL, and D1. With `VITEHUB_INSTANCES` greater than 1, a Node server with a Postgres or remote libSQL Default Database reports Schedule as `shared` at boot. A local libSQL file is safe for one server process only, because `@libsql/client` can lose writes when several processes write to one file. The server prints a warning at the first lease in that case. Without a Database, the leases stay in memory and the build reports the hint `SCHEDULE_PROCESS_CLAIMS_IN_MEMORY` in its output and in `.vitehub/hints.json`: each server then runs every occurrence, so run one server only. The run history stays in KV. Use a KV store that all servers share, such as Upstash, so catch-up and the Console see the runs of every server.
203
204
 
204
205
  With the Process Runtime, the default `providerOutput: "auto"` emits no host Provider Output, so the process owns Static Schedule wakes. Set `providerOutput: "standalone"` or `"nitro"` to move Static Schedule wakes to that Provider Output. `providerOutput: false` records the same wake ownership as `"auto"` in this configuration.
205
206
 
@@ -250,15 +251,19 @@ Custom stores must apply the `listRuns({ scheduleId, idPrefix, limit })` filters
250
251
 
251
252
  ## Run and inspect schedules
252
253
 
253
- `hubSchedule()` contributes the `schedule.runs`, `schedule.attempts`, `schedule.run`, `schedule.list`, `schedule.start`, and `schedule.cancel` operations. They are the `vitehub schedule runs <id> [--limit <n>]`, `attempts <runId>`, `run <name>`, `list [name]`, `start <name>`, and `cancel <id>` 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.
254
+ `hubSchedule()` contributes the `schedule.runs`, `schedule.attempts`, `schedule.run`, `schedule.list`, `schedule.start`, and `schedule.cancel` operations. They are the `vitehub schedule runs list <id> [--limit <n>]`, `runs get <runId>`, `run <name>`, `list [name]`, `start <name>`, and `cancel <id>` 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.
254
255
 
255
256
  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>` to run it on a deployment that enables `console.invoke`. The command signs the call with `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`, so a CI job needs only that secret. `vitehub secret console-key ci` prints a new key pair. Server code can call `runSchedule(name)` from `@vite-hub/schedule`. It reads the generated registry and returns `[error, run]`. A failed handler gives a run with `status: "failed"`. An invalid `scheduledAt` or a failed run store gives `error`. An unknown name or a Definition without `manual: true` throws. Each manual run gets a new `srun_manual_` id.
256
257
 
257
- Add `--at <ISO date-time>` to run it as if the cron fired at that time, for example `vitehub schedule run close-month --at 2026-01-31T23:59:00Z`. The handler gets the time as `scheduledAt`, and the run records it, so `vitehub schedule runs` lists it under that time. `runSchedule()` takes the same value as `scheduledAt`. The value needs `Z` or an offset. A value without a time zone, a date only, or a day that does not exist fails with `SCHEDULE_INVALID_SCHEDULED_AT` before the handler runs. `runSchedule()` returns it as `error`. The time is not checked against the cron. Manual runs do not advance the Process Runtime's catch-up cursor, even when their scheduled time is in the future.
258
+ Add `--at <ISO date-time>` to run it as if the cron fired at that time, for example `vitehub schedule run close-month --at 2026-01-31T23:59:00Z`. The handler gets the time as `scheduledAt`, and the run records it, so `vitehub schedule runs list` lists it under that time. `runSchedule()` takes the same value as `scheduledAt`. The value needs `Z` or an offset. A value without a time zone, a date only, or a day that does not exist fails with `SCHEDULE_INVALID_SCHEDULED_AT` before the handler runs. `runSchedule()` returns it as `error`. The time is not checked against the cron. Manual runs do not advance the Process Runtime's catch-up cursor, even when their scheduled time is in the future.
258
259
 
259
260
  Discovery reads `manual` as a literal boolean 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.
260
261
 
261
- The Console Schedules section lists Schedule Definitions with their cron, time zone, and manual state. It reads them at build time. When the server runs the Process Runtime, the cron and time zone come from the loaded Definitions on each request, so they are the values that the runtime uses. `vitehub inspect definitions` reads them from the source file and shows `Not a static string` for a value that it cannot read there. Use `vitehub schedule runs <name>` to list the runs that the runtime recorded. The CLI and the Console redact credentials in error messages.
262
+ The Console Schedules section lists Schedule Definitions with their cron, time zone, and manual state. It reads them at build time. When the server runs the Process Runtime, the cron and time zone come from the loaded Definitions on each request, so they are the values that the runtime uses. `vitehub inspect definitions` reads them from the source file and shows `Not a static string` for a value that it cannot read there. Use `vitehub schedule runs list <name>` to list the runs that the runtime recorded. The CLI and the Console redact credentials in error messages.
263
+
264
+ ## Runs in logs
265
+
266
+ With the evlog Nitro module registered, each Schedule handler run inside Nitro gets its own evlog event, `schedule: { name, source, scheduledAt, ms, outcome }`, with the error when it fails. Standalone provider wakes do not send these events. This includes Vercel and Deno cron wakes by default, and Cloudflare or Netlify when you select standalone output. Without evlog, failures go to the console and runtimes with a run store keep their run history. See [Server API](https://vitehub.dev/docs/schedule/server-api#see-schedule-runs-in-logs).
262
267
 
263
268
  ## Import runtime helpers
264
269
 
@@ -48,6 +48,8 @@ interface ViteHubResourceSummary {
48
48
  owner: string;
49
49
  /** Absent when no id is known yet. */
50
50
  source?: ViteHubResourceIdSource;
51
+ /** The resource is in the Wrangler config of a standalone Provider Output Worker, not in Nitro's. */
52
+ standalone?: boolean;
51
53
  }
52
54
  interface ViteHubInspectionContributor {
53
55
  definitions?: readonly ViteHubDefinitionInspector[];
@@ -0,0 +1,70 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ import { parseCronExpression } from "cron-schedule";
3
+ //#region ../internal/src/invariant.ts
4
+ const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
6
+ codes: { INTERNAL_INVARIANT_FAILED: {
7
+ why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
8
+ fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
9
+ } }
10
+ });
11
+ /**
12
+ * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
13
+ * Use a code from the package catalog when a developer can cause the error or fix it.
14
+ */
15
+ function invariantError(what) {
16
+ return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
17
+ }
18
+ /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
19
+ function invariant(condition, what) {
20
+ if (!condition) throw invariantError(what);
21
+ }
22
+ //#endregion
23
+ //#region src/os/cron.ts
24
+ const allMonths = range(1, 12);
25
+ const allWeekdays = range(0, 6);
26
+ function range(first, last) {
27
+ return Array.from({ length: last - first + 1 }, (_, index) => first + index);
28
+ }
29
+ /** Reads a five-field cron. Returns `undefined` for anything else. */
30
+ function parseCronFields(cron) {
31
+ if (cron.trim() !== cron || cron.split(/\s+/).length !== 5) return void 0;
32
+ try {
33
+ const parsed = parseCronExpression(cron);
34
+ const sorted = (values) => [...new Set(values)].sort((left, right) => left - right);
35
+ return {
36
+ minutes: sorted(parsed.minutes),
37
+ hours: sorted(parsed.hours),
38
+ days: sorted(parsed.days),
39
+ months: sorted(parsed.months.map((month) => month + 1)),
40
+ weekdays: sorted(parsed.weekdays.map((weekday) => weekday % 7))
41
+ };
42
+ } catch {
43
+ return;
44
+ }
45
+ }
46
+ function isDayRestricted(fields) {
47
+ return fields.days.length !== 31;
48
+ }
49
+ function isWeekdayRestricted(fields) {
50
+ return fields.weekdays.length !== allWeekdays.length;
51
+ }
52
+ function isMonthRestricted(fields) {
53
+ return fields.months.length !== allMonths.length;
54
+ }
55
+ /** True when every day field holds every value, so the cron runs on every day. */
56
+ function runsEveryDay(fields) {
57
+ return !isDayRestricted(fields) && !isWeekdayRestricted(fields) && !isMonthRestricted(fields);
58
+ }
59
+ /** Minutes of the day when the cron runs, sorted. */
60
+ function timesOfDay(fields) {
61
+ return fields.hours.flatMap((hour) => fields.minutes.map((minute) => hour * 60 + minute));
62
+ }
63
+ /** The step of a sorted list of two or more values with equal gaps, else `undefined`. One value has step 0. */
64
+ function arithmeticStep(values) {
65
+ if (values.length < 2) return 0;
66
+ const step = values[1] - values[0];
67
+ return values.every((value, index) => index === 0 || value - values[index - 1] === step) ? step : void 0;
68
+ }
69
+ //#endregion
70
+ export { parseCronFields as a, timesOfDay as c, isWeekdayRestricted as i, invariant as l, isDayRestricted as n, range as o, isMonthRestricted as r, runsEveryDay as s, arithmeticStep as t, invariantError as u };
@@ -1,6 +1,6 @@
1
1
  import { t as isIanaTimeZone } from "./time-zone-SBldrUgt.js";
2
2
  import { t as isRecord } from "./object-Da1zyPCR.js";
3
- import { t as scheduleErrorDiagnostics } from "./error-diagnostics-BBtYYl8j.js";
3
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-DTmP6baC.js";
4
4
  //#region src/definition.ts
5
5
  const cronFieldPattern = /^[^\s]+$/;
6
6
  const scheduleDefinitionKeys = /* @__PURE__ */ new Set([
@@ -21,7 +21,6 @@ function validateCron(cron) {
21
21
  const fields = cron.split(/\s+/);
22
22
  if (fields.length !== 5 || !fields.every((field) => cronFieldPattern.test(field))) throw scheduleErrorDiagnostics.SCHEDULE_C0002({ message: "`defineSchedule()` cron must be a five-field cron expression." });
23
23
  }
24
- /** The `defineSchedule(cron, handler, options)` form was removed. Name the object form in the error. */
25
24
  const positionalFormMessage = "`defineSchedule(cron, handler)` was removed. Pass one object: `defineSchedule({ cron: \"0 9 * * *\", handler })`, with `manual` and `timeZone` in the same object.";
26
25
  function defineSchedule(input, ...removed) {
27
26
  if (isCronString(input) || removed.length) throw scheduleErrorDiagnostics.SCHEDULE_C0007({ message: positionalFormMessage });
@@ -1,4 +1,4 @@
1
- import { t as scheduleErrorDiagnostics } from "./error-diagnostics-BBtYYl8j.js";
1
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-DTmP6baC.js";
2
2
  import { parseCronExpression } from "cron-schedule";
3
3
  //#region src/runtime/due.ts
4
4
  const weekdayIndexes = /* @__PURE__ */ new Map([
@@ -90,7 +90,6 @@ function localEpochMs(fields) {
90
90
  function sameLocalMinute(left, right) {
91
91
  return left.minute === right.minute && left.hour === right.hour && left.day === right.day && left.month === right.month && left.year === right.year;
92
92
  }
93
- /** Detect a repeated local minute using the actual offset before the transition (including historical 23-hour rollbacks). */
94
93
  function isRepeatedFixedLocalTime(cron, fields, scheduledAt, timeZone) {
95
94
  if (!timeZone || timeZone === "UTC" || cron.minutes.length === hourMinutes || cron.hours.length === 24) return false;
96
95
  const previous = /* @__PURE__ */ new Date(scheduledAt.getTime() - dayMinutes * minuteMs);
@@ -99,10 +98,6 @@ function isRepeatedFixedLocalTime(cron, fields, scheduledAt, timeZone) {
99
98
  if (previousOffset <= currentOffset) return false;
100
99
  return sameLocalMinute(scheduleDateFields(new Date(scheduledAt.getTime() - (previousOffset - currentOffset)), timeZone), fields);
101
100
  }
102
- /**
103
- * Detect a local time that the clock skipped on a spring-forward day, read with the offset from before the gap, as
104
- * RFC 5545 and `Temporal` do. `02:30` in a gap from `02:00` to `03:00` maps to `03:30`, so it runs once that day.
105
- */
106
101
  function matchesSkippedLocalTime(cron, fields, scheduledAt, timeZone) {
107
102
  if (!timeZone || timeZone === "UTC") return false;
108
103
  const currentOffset = localEpochMs(fields) - scheduledAt.getTime();
@@ -140,5 +135,25 @@ function latestCronMinute(cron, at) {
140
135
  for (let time = latest; time > latest - dayMinutes * minuteMs; time -= minuteMs) if (isScheduleDue(record, new Date(time))) return new Date(time);
141
136
  return new Date(latest);
142
137
  }
138
+ const weekdayNames = [
139
+ "SUN",
140
+ "MON",
141
+ "TUE",
142
+ "WED",
143
+ "THU",
144
+ "FRI",
145
+ "SAT"
146
+ ];
147
+ /**
148
+ * Returns `cron` with its weekday field written as names, such as `0 4 * * MON,FRI`. Cloudflare and Deno number
149
+ * weekdays 1-7 from Sunday, so standard 0-6 numbers fire one day early or fail to deploy. Names have one meaning on
150
+ * every host.
151
+ */
152
+ function cronWithWeekdayNames(cron) {
153
+ const fields = cron.trim().split(/\s+/);
154
+ if (fields.length !== 5 || fields[4] === "*") return fields.join(" ");
155
+ fields[4] = parseCronExpression(fields.join(" ")).weekdays.map((day) => weekdayNames[day]).join(",");
156
+ return fields.join(" ");
157
+ }
143
158
  //#endregion
144
- export { latestCronMinute as n, timeZoneOffsetMinutes as r, isScheduleDue as t };
159
+ export { timeZoneOffsetMinutes as i, isScheduleDue as n, latestCronMinute as r, cronWithWeekdayNames as t };
@@ -7,8 +7,8 @@ export interface ScheduleDurabilityInput {
7
7
  leases?: boolean;
8
8
  }
9
9
  /**
10
- * The durability of schedule claims. With SQL leases in a Postgres Default Database, one instance runs each
11
- * occurrence. Without them, each process claims each occurrence for itself.
10
+ * The durability of schedule claims. With SQL leases in a Postgres or remote libSQL Default Database, one instance runs
11
+ * each occurrence. Without them, each process claims each occurrence for itself.
12
12
  */
13
13
  export declare function scheduleDurability(input: ScheduleDurabilityInput, context: DurabilityContext): Durability[];
14
14
  //#endregion
@@ -1,13 +1,13 @@
1
1
  //#region src/durability.ts
2
2
  /**
3
- * The durability of schedule claims. With SQL leases in a Postgres Default Database, one instance runs each
4
- * occurrence. Without them, each process claims each occurrence for itself.
3
+ * The durability of schedule claims. With SQL leases in a Postgres or remote libSQL Default Database, one instance runs
4
+ * each occurrence. Without them, each process claims each occurrence for itself.
5
5
  */
6
6
  function scheduleDurability(input, context) {
7
7
  const database = input.leases ? context.find("database") : void 0;
8
- if (database?.store === "postgres") return [{
8
+ if (database?.scope === "shared" && (database.store === "postgres" || database.store === "libsql")) return [{
9
9
  primitive: "schedule",
10
- store: "postgres",
10
+ store: database.store,
11
11
  scope: "shared",
12
12
  reason: "Leases in the Default Database. One instance runs each occurrence."
13
13
  }];
@@ -16,7 +16,7 @@ function scheduleDurability(input, context) {
16
16
  store: input.driver,
17
17
  scope: "process",
18
18
  reason: database ? `Leases in the ${database.store} Default Database do not lock across processes. Every instance can run every occurrence.` : "This process claims each occurrence. Every instance runs every occurrence.",
19
- fix: input.leases ? "Define the Default Database with `dialect: \"postgresql\"`." : "Run the schedules on one instance only. Schedule has no shared lease store for Node yet."
19
+ fix: input.leases ? "Define the Default Database with `dialect: \"postgresql\"` or a remote libSQL URL." : "Turn on Database and define a Postgres or remote libSQL Default Database. The instances then share Schedule leases."
20
20
  }];
21
21
  }
22
22
  //#endregion
@@ -25,7 +25,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
25
25
  why: ({ message }) => message === void 0 ? "" : String(message)
26
26
  },
27
27
  INTERNAL_R0022: {
28
- fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
28
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields, and the list_operations tool of the ViteHub MCP gives the input schema of each operation.",
29
29
  why: ({ message }) => message === void 0 ? "" : String(message)
30
30
  },
31
31
  INTERNAL_R0024: {
@@ -244,6 +244,10 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
244
244
  why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
245
245
  fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
246
246
  },
247
+ INTERNAL_RUNTIME_PACKAGE_VERSION_CONFLICT: {
248
+ why: ({ first, name, second }) => `[vitehub] One server function needs ${name} from two installations: ${first} and ${second}.`,
249
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`, then build again."
250
+ },
247
251
  INTERNAL_SECRET_PURPOSE_MISSING: {
248
252
  why: "[vitehub] A derived secret requires a purpose.",
249
253
  fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
@@ -8,17 +8,13 @@ const scheduleErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
8
8
  why: "Schedule run is not available. Set manual: true on the Schedule Definition and enable Console invocation.",
9
9
  fix: "Set `manual: true` in defineSchedule() and keep `console.invoke` on (it is on in development)."
10
10
  },
11
- SCHEDULE_HISTORY_INCOMPLETE: {
12
- why: ({ maxRecords, recordCount }) => `Schedule run history is incomplete because ${recordCount} records have no usable metadata index (maximum fallback is ${maxRecords}). Rebuild the schedule run index before listing history.`,
13
- fix: "Rebuild the Schedule run index of the store, as the message says, before you list the history."
14
- },
15
11
  SCHEDULE_OPERATION_FAILED: {
16
12
  why: "Schedule operation failed.",
17
13
  fix: "Read `error.cause` for the error of the Schedule store or handler. Check that the store is reachable, then retry."
18
14
  },
19
15
  SCHEDULE_RUN_NOT_FOUND: {
20
16
  why: "Schedule Run was not found.",
21
- fix: "List the runs of the Schedule with `vitehub schedule runs <name>` and pass one of their ids."
17
+ fix: "List the runs of the Schedule with `vitehub schedule runs list <name>` and pass one of their ids."
22
18
  },
23
19
  SCHEDULE_C0001: {
24
20
  ...dynamicError,
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /// <reference path="./registry-module.d.ts" />
2
2
  import { _ as StartScheduleOptions, a as ScheduleDefinitionRegistry, b as StartedScheduleStore, c as ScheduleRunAttemptRecord, d as ScheduleRunError, f as ScheduleRunListOptions, g as ScheduleRunStore, h as ScheduleRunStatus, l as ScheduleRunAttemptStatus, m as ScheduleRunResponse, n as ScheduleDefinition, o as ScheduleHandler, p as ScheduleRunRecord, r as ScheduleDefinitionInput, s as ScheduleRegistryDefinition, t as DiscoveredScheduleDefinition, u as ScheduleRunContext, v as StartScheduleTiming, y as StartedSchedule } from "./types-Cw5LjPuc.js";
3
3
  import { defineSchedule } from "./definition.js";
4
- import { i as RunScheduleOptions, t as KVScheduleStoreOptions } from "./store-DeMojnXM.js";
4
+ import { i as RunScheduleOptions, t as KVScheduleStoreOptions } from "./store-CZHZfttA.js";
5
5
  import { t as ScheduleKVStorage } from "./kv-storage-Bm9aYLfZ.js";
6
6
  import { ErrorCatalog, Result, ViteHubError } from "@vite-hub/runtime";
7
7
  //#region src/run-errors.d.ts
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { defineSchedule } from "./definition.js";
2
- import { o as createScheduleError, r as parseScheduledAt } from "./wait-until-Dy4Bn3ZN.js";
3
- import { r as executeManualSchedule, s as resolveManualSchedule } from "./started-errors-DEmYH-vp.js";
4
- import { i as startSchedule, n as getSchedule, r as listSchedules, t as cancelSchedule } from "./started-B0pc3JY0.js";
2
+ import { S as createScheduleError, y as parseScheduledAt } from "./static-BgoOCoe5.js";
3
+ import { r as executeManualSchedule, s as resolveManualSchedule } from "./started-errors-BMg04lL3.js";
4
+ import { i as startSchedule, n as getSchedule, r as listSchedules, t as cancelSchedule } from "./started-BWWr7Ufw.js";
5
5
  import { defineErrors } from "@vite-hub/runtime";
6
6
  //#region src/run-errors.ts
7
7
  const runScheduleErrors = /*#__PURE__*/ defineErrors({
@@ -20,7 +20,6 @@ const runScheduleErrors = /*#__PURE__*/ defineErrors({
20
20
  //#endregion
21
21
  //#region src/run.ts
22
22
  const registryModule = "#vitehub/schedule/registry";
23
- /** The registry that the Schedule Vite plugin generates. It loads on the first run, so importing the root stays cheap. */
24
23
  async function loadRegistry() {
25
24
  try {
26
25
  return (await import(
@@ -115,8 +115,4 @@ function redactInspectionText(value) {
115
115
  return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
116
116
  }
117
117
  //#endregion
118
- //#region src/runtime/started-name.ts
119
- /** Name of the Schedule that runs due started Schedules each minute. Discovery adds it when a Definition has no `cron`. */
120
- const startedSchedulesTickName = "vitehub/started-schedules";
121
- //#endregion
122
- export { isAbsolute as a, dirname as i, redactInspectionText as n, relative as o, relativeDefinitionFile as r, resolve as s, startedSchedulesTickName as t };
118
+ export { relative as a, isAbsolute as i, relativeDefinitionFile as n, resolve as o, dirname as r, redactInspectionText as t };
@@ -104,6 +104,11 @@ interface OperationAccess {
104
104
  */
105
105
  readonly sections: "all" | readonly string[];
106
106
  readonly user?: OperationUser;
107
+ /**
108
+ * Who signed the call: `"console"` when the ViteHub Console signed it for a person, whose `user` is then a Console
109
+ * account and not an app user, or `"cli"` for a key. Not set for other calls.
110
+ */
111
+ readonly via?: "console" | "cli";
107
112
  }
108
113
  interface OperationContext {
109
114
  /** The checked Console access of the call. */
@@ -166,7 +171,8 @@ interface OperationDefinition<Input, Output> {
166
171
  /** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
167
172
  input: StandardSchemaV1<unknown, Input>;
168
173
  output?: StandardSchemaV1<unknown, Output>;
169
- cli?: {
174
+ /** `false`: no `vitehub` command. The Console and MCP still call the operation. */
175
+ cli?: false | {
170
176
  /** Defaults: namespace = section, command = verb. */
171
177
  namespace?: string;
172
178
  /** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
@@ -207,7 +213,7 @@ interface OperationDefinition<Input, Output> {
207
213
  /** An operation of any input and output, as a registry holds it. */
208
214
  interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "mcp" | "output" | "readOnlyWhen" | "run" | "scope" | "section"> {
209
215
  readOnlyWhen?: (input: never) => boolean;
210
- cli?: {
216
+ cli?: false | {
211
217
  namespace?: string;
212
218
  command?: string;
213
219
  default?: boolean;
@@ -1,8 +1,9 @@
1
- import { t as scheduleErrorDiagnostics } from "./error-diagnostics-BBtYYl8j.js";
2
- import { c as runScheduleFrom, o as loadStaticScheduleDefinition } from "./started-errors-DEmYH-vp.js";
3
- import { i as getScheduleRunStore, n as getProcessScheduleDefinitions, o as getStartedScheduleRuntime, t as getHostScheduleInventory } from "./state-D4SZH6zk.js";
4
- import { i as startSchedule, r as listSchedules, t as cancelSchedule } from "./started-B0pc3JY0.js";
5
- import { n as redactInspectionText } from "./started-name-ruCM1EtQ.js";
1
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-DTmP6baC.js";
2
+ import { c as runScheduleFrom, o as loadStaticScheduleDefinition } from "./started-errors-BMg04lL3.js";
3
+ import "./started-name-DudQ0fsR.js";
4
+ import { i as getScheduleRunStore, n as getProcessScheduleDefinitions, o as getStartedScheduleRuntime, t as getHostScheduleInventory } from "./state-BjWnxyhv.js";
5
+ import { i as startSchedule, r as listSchedules, t as cancelSchedule } from "./started-BWWr7Ufw.js";
6
+ import { t as redactInspectionText } from "./inspect-DTfAo5gS.js";
6
7
  //#region src/runtime/operations.ts
7
8
  function isoDate(value) {
8
9
  if (value === void 0) return;
@@ -77,7 +78,6 @@ async function listScheduleRuns(scheduleId, options = {}) {
77
78
  async function listScheduleRunAttempts(runId) {
78
79
  return [...await getScheduleRunStore().listAttempts(runId)].sort((left, right) => new Date(left.startedAt).getTime() - new Date(right.startedAt).getTime()).map(summarizeScheduleRunAttempt);
79
80
  }
80
- /** Gives an operation error its HTTP status and the redacted message that the CLI and the Console report. */
81
81
  function withStatus(error, status, fix) {
82
82
  return Object.defineProperties(error, {
83
83
  ...fix && !Reflect.get(error, "fix") ? { fix: {
@@ -103,13 +103,11 @@ function withStatus(error, status, fix) {
103
103
  const errorFix = { SCHEDULE_INVALID_SCHEDULED_AT: "Pass `at` as an ISO 8601 date-time with a time zone, such as 2026-01-31T23:59:00Z or 2026-01-31T23:59:00+01:00." };
104
104
  const errorStatus = {
105
105
  SCHEDULE_DEFINITION_NOT_FOUND: 404,
106
- SCHEDULE_HISTORY_INCOMPLETE: 503,
107
106
  SCHEDULE_INVALID_SCHEDULED_AT: 400,
108
107
  SCHEDULE_MANUAL_RUN_DISABLED: 403,
109
108
  SCHEDULE_OPERATION_FAILED: 500,
110
109
  SCHEDULE_RUN_NOT_FOUND: 404
111
110
  };
112
- /** Gives a Schedule error the status and the redacted message that every surface reports. */
113
111
  async function attempt(work) {
114
112
  try {
115
113
  return await work();
@@ -133,7 +131,6 @@ async function runScheduleAttempts(input) {
133
131
  };
134
132
  });
135
133
  }
136
- /** The manual Static Schedule Definitions that the Console installed. Only `console.invoke` installs them. */
137
134
  const consoleSchedulesKey = Symbol.for("vitehub.console.schedules");
138
135
  /**
139
136
  * Runs a Static Schedule Definition that sets `manual: true`, as if its cron fired at `at` (default: now). The registry holds only those definitions, and it is empty
@@ -1,5 +1,5 @@
1
1
  import { h as ScheduleRunStatus, l as ScheduleRunAttemptStatus } from "./types-Cw5LjPuc.js";
2
- import { t as AnyOperation } from "./operation-definition-nmRu_O3V.js";
2
+ import { t as AnyOperation } from "./operation-definition-CI2PJGqu.js";
3
3
  //#region src/runtime/operations.d.ts
4
4
  /** Error of a run or attempt. The stack is not included. */
5
5
  interface ScheduleRunErrorSummary {
@@ -1,5 +1,5 @@
1
1
  import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
2
- import { t as internalErrorDiagnostics } from "./error-diagnostics-CQ4BUqRe.js";
2
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-C0KyI408.js";
3
3
  import { toJsonSchema } from "@valibot/to-json-schema";
4
4
  import * as v from "valibot";
5
5
  //#region ../internal/src/standard-schema.ts
@@ -143,7 +143,7 @@ function table(rows) {
143
143
  }
144
144
  //#endregion
145
145
  //#region src/operations.ts
146
- const runtime = () => import("./operations-DqwmJ8MN.js");
146
+ const runtime = () => import("./operations-DlrK9mlH.js");
147
147
  const id = v.pipe(v.string(), v.minLength(1));
148
148
  function formatRuns({ runs }) {
149
149
  if (runs.length === 0) return "No runs.\n";
@@ -194,7 +194,7 @@ function defineScheduleOperation(definition) {
194
194
  }
195
195
  const runs = defineScheduleOperation({
196
196
  cli: {
197
- command: "runs",
197
+ command: "runs list",
198
198
  format: formatRuns,
199
199
  namespace: "schedule",
200
200
  positional: ["id"]
@@ -210,12 +210,12 @@ const runs = defineScheduleOperation({
210
210
  });
211
211
  const attempts = defineScheduleOperation({
212
212
  cli: {
213
- command: "attempts",
213
+ command: "runs get",
214
214
  format: formatAttempts,
215
215
  namespace: "schedule",
216
216
  positional: ["id"]
217
217
  },
218
- description: "List the attempts of one Schedule Run, oldest first.",
218
+ description: "Show one Schedule Run with its attempts, oldest first.",
219
219
  input: v.object({ id }),
220
220
  kind: "read",
221
221
  name: "schedule.attempts",
package/dist/os.d.ts CHANGED
@@ -40,7 +40,6 @@ type TimeZoneUnsupported = {
40
40
  timeZone: string;
41
41
  machineTimeZone: string;
42
42
  };
43
- /** A code whose `error.data` holds the values of its message. */
44
43
  type Code<TData> = {
45
44
  fix: string;
46
45
  why: (data: TData) => string;