@vite-hub/schedule 0.0.2 → 0.0.4

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,72 +1,174 @@
1
1
  # @vite-hub/schedule
2
2
 
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>
3
+ `@vite-hub/schedule` discovers recurring work, generates cron output for supported hosts, and manages recurring schedules that an application creates while it runs.
9
4
 
10
- `@vite-hub/schedule` keeps cron definitions and runtime schedules behind one schedule registry.
5
+ ## Choose the package
11
6
 
12
- ## Install
7
+ Install `vite-hub` for an application. It includes Schedule and exposes application imports under `vite-hub/schedule`.
8
+
9
+ ```sh
10
+ pnpm add vite-hub
11
+ ```
12
+
13
+ Enable Schedule with the framework integration and import application helpers from its feature path:
14
+
15
+ ```ts
16
+ // vite.config.ts
17
+ import { vitehub } from "vite-hub";
18
+ import { defineConfig } from "vite";
19
+
20
+ export default defineConfig({
21
+ plugins: [vitehub({ preset: "cloudflare", schedule: true })],
22
+ });
23
+ ```
24
+
25
+ ```ts
26
+ import { defineSchedule } from "vite-hub/schedule";
27
+ ```
28
+
29
+ Install the owner package directly when a library or custom integration needs Schedule without the framework distribution.
13
30
 
14
31
  ```sh
15
32
  pnpm add @vite-hub/schedule
16
33
  ```
17
34
 
18
- Add `@vite-hub/kv` when runtime schedules should persist outside memory.
35
+ Direct integrations use `@vite-hub/schedule`, `@vite-hub/schedule/runtime`, and `@vite-hub/schedule/vite`. Add Vite when the project uses `hubSchedule()`. Add `@vite-hub/kv` when using the default KV-backed stores or the generated Process Runtime. Static Schedule Definitions, memory stores, and custom `ScheduleKVStorage` implementations do not require KV.
36
+
37
+ Both packages require Node.js 24.15 or newer.
38
+
39
+ ## Choose the schedule kind
40
+
41
+ | Kind | Create it with | Use it when |
42
+ | -------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
43
+ | Static Schedule Definition | `defineSchedule()` in a discovered source file | The cron is part of the deployment and can produce host Provider Output. |
44
+ | Schedule Target | `defineScheduleTarget()` in a discovered source file | Runtime Schedules need a named handler with no build-time cron. A target never produces static cron output. |
45
+ | Runtime Schedule | `schedules.create()` in server code | The application must create, update, pause, or delete a recurring schedule while it runs. |
46
+
47
+ A Runtime Schedule must name a Schedule Target. A Static Schedule Definition can also become a target when it sets `allowRuntimeSchedules: true`.
48
+
49
+ ## Run one occurrence
50
+
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.
52
+
53
+ ```ts
54
+ import { defineSchedule, executeStaticSchedule } from "@vite-hub/schedule";
55
+
56
+ const dailyReport = defineSchedule({
57
+ cron: "0 8 * * *",
58
+ handler({ scheduledAt }) {
59
+ console.log(`Report scheduled for ${scheduledAt.toISOString()}`);
60
+ },
61
+ });
62
+
63
+ const run = await executeStaticSchedule({
64
+ cron: dailyReport.cron,
65
+ definition: dailyReport,
66
+ name: "daily-report",
67
+ scheduledAt: new Date("2026-08-27T08:00:00.000Z"),
68
+ });
69
+
70
+ console.log(run.status);
71
+ ```
72
+
73
+ ```txt
74
+ Report scheduled for 2026-08-27T08:00:00.000Z
75
+ succeeded
76
+ ```
77
+
78
+ The example uses the default in-memory Schedule Run store. It proves the handler and run bookkeeping, but it does not install a recurring wake or generate Provider Output.
79
+
80
+ ## Discover a static schedule
81
+
82
+ Register the direct owner-package integration in Vite.
83
+
84
+ ```ts
85
+ // vite.config.ts
86
+ import { hubSchedule } from "@vite-hub/schedule/vite";
87
+ import { defineConfig } from "vite";
88
+
89
+ export default defineConfig({
90
+ plugins: [hubSchedule()],
91
+ });
92
+ ```
19
93
 
20
- ## Minimal API
94
+ Then export a definition from `server/schedules/<name>.ts` or `src/<name>.schedule.ts`.
21
95
 
22
96
  ```ts
23
97
  // server/schedules/daily-report.ts
24
- import { defineSchedule } from "@vite-hub/schedule"
98
+ import { defineSchedule } from "@vite-hub/schedule";
25
99
 
26
100
  export default defineSchedule({
27
101
  cron: "0 8 * * *",
28
- allowRuntimeSchedules: true,
29
- handler: async ({ scheduledAt }) => {
30
- console.log(`Generating daily report for ${scheduledAt.toISOString()}`)
102
+ async handler({ scheduledAt, waitUntil }) {
103
+ await sendDailyReport(scheduledAt);
104
+ waitUntil(recordDelivery());
31
105
  },
32
- })
106
+ });
33
107
  ```
34
108
 
109
+ Static Schedule Definitions use five-field UTC cron expressions. They cannot set `timeZone`. The integration can generate host-specific output for Cloudflare Cron Triggers, Vercel Cron Jobs, Netlify Scheduled Functions, standalone `Deno.cron`, and Nitro's Cloudflare schedule hook. 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.
110
+
111
+ Applications that use the framework distribution register Schedule through `vitehub({ preset, schedule: true })` and import the definition helper from `vite-hub/schedule`. The Deno framework preset currently rejects Schedule because standalone Deno cron output sits outside its generated Nitro entrypoint. Use the direct Schedule integration for that output.
112
+
113
+ Direct Nuxt projects can register `@vite-hub/schedule/nuxt` instead of `hubSchedule()`. The module installs the Vite integration and merges Schedule output into Nitro config.
114
+
115
+ ## Create a Runtime Schedule
116
+
117
+ Define a cronless target for work that runs only through Runtime Schedules.
118
+
35
119
  ```ts
36
120
  // server/schedules/report.ts
37
- import { defineScheduleTarget } from "@vite-hub/schedule"
121
+ import { defineScheduleTarget } from "@vite-hub/schedule";
38
122
 
39
123
  export default defineScheduleTarget<{ prompt: string }>({
40
- handler: async ({ input }) => {
41
- if (input) await generateReport(input.prompt)
124
+ async handler({ input }) {
125
+ if (input) await generateReport(input.prompt);
42
126
  },
43
- })
127
+ });
44
128
  ```
45
129
 
130
+ Before creating the recurring record, install the Schedule runtime so it can load the discovered target registry and reconcile stored schedules. A custom host calls `installScheduleRuntime()` from `@vite-hub/schedule/runtime/driver` with its wake driver. A generated Process Runtime does this during application startup.
131
+
132
+ After runtime installation completes, create the recurring record from server code.
133
+
46
134
  ```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
- })
135
+ import { schedules } from "@vite-hub/schedule/runtime";
136
+
137
+ const report = await schedules.create({
138
+ cron: "30 8 * * 1-5",
139
+ id: "weekday-report",
140
+ input: { prompt: "Summarize yesterday" },
141
+ target: "report",
142
+ timeZone: "Europe/Copenhagen",
143
+ });
144
+
145
+ console.log(report.id);
59
146
  ```
60
147
 
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.
148
+ The installed runtime can supply a native wake driver, or one long-lived process can install `createProcessScheduleWakeDriver()` from `@vite-hub/schedule/runtime/process`.
149
+
150
+ Static provider cron output does not automatically wake Runtime Schedules. Provider-backed Runtime Schedules need a host-owned wake driver. Request-scoped and serverless hosts must not use the Process Runtime because the process may stop between requests.
151
+
152
+ ## Understand time zones
153
+
154
+ Static Schedule Definitions and their Provider Output always use UTC. Runtime Schedules use UTC when `timeZone` is absent and accept IANA time-zone names when the cron must follow local clock time.
155
+
156
+ Omitting `timeZone` during an update preserves the stored zone. Set it to `UTC` to return to UTC evaluation. Numeric offsets such as `+01:00` are rejected. During a daylight-saving gap, ViteHub skips a local time that does not exist. During an overlap, both distinct instants that share the repeated local time are due.
157
+
158
+ ## Choose storage and wake ownership
159
+
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.
161
+
162
+ 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:
62
163
 
63
164
  ```ts
64
- // vite.config.ts
65
- import { hubSchedule } from "@vite-hub/schedule/vite"
66
- import { defineConfig } from "vite"
165
+ import { hubKv } from "@vite-hub/kv/vite";
166
+ import { hubSchedule } from "@vite-hub/schedule/vite";
167
+ import { defineConfig } from "vite";
67
168
 
68
169
  export default defineConfig({
69
170
  plugins: [
171
+ hubKv(),
70
172
  hubSchedule({
71
173
  runtime: {
72
174
  driver: "process",
@@ -74,53 +176,22 @@ export default defineConfig({
74
176
  },
75
177
  }),
76
178
  ],
77
- })
179
+ });
78
180
  ```
79
181
 
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.
182
+ Its defaults are prefix `vitehub:schedule`, scan interval `60_000` milliseconds, and concurrency `1`. The interval cannot exceed one minute. `concurrency` limits wake delivery only inside that process. The KV run store records occurrences but does not provide distributed leader election or locking, so multiple replicas can execute the same work. A stopped process does not backfill minutes that it missed.
81
183
 
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`.
184
+ 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 while the process continues to run Runtime Schedules. `providerOutput: false` explicitly records the same wake ownership as `"auto"` in this configuration.
83
185
 
84
- ## Vite Integration
186
+ `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.
85
187
 
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.
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.
87
189
 
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.
190
+ ## Documentation and support
89
191
 
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
- ```
192
+ - Read the [Schedule guide](https://vitehub.dev/docs/server-primitives/schedule) for every public import, Runtime Helper, store, wake driver, and Vite option.
193
+ - Check [Provider Output](https://vitehub.dev/docs/reference/provider-output) for generated files and deployment inspection.
194
+ - Check [runtime and host support](https://vitehub.dev/docs/frameworks-hosts/support-matrix) for current proof and host qualifications.
195
+ - Report package problems in the [ViteHub issue tracker](https://github.com/vite-hub/vitehub/issues).
102
196
 
103
197
  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).
@@ -1,5 +1,5 @@
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";
1
+ import { n as executeRuntimeSchedule, o as randomId } from "./execute-B-pii4wf.js";
2
+ import { h as invalidScheduleValueDetails, i as loadScheduleDefinition, m as createScheduleError, n as getScheduleRunStore, p as assertRuntimeScheduleId, t as getRuntimeScheduleStore } from "./state-By7WU_ks.js";
3
3
  //#region ../internal/src/runtime/time-zone.ts
4
4
  const slashlessIanaTimeZones = new Set([
5
5
  "CET",
@@ -0,0 +1,15 @@
1
+ import { t as DiscoveredScheduleDefinition } from "./types-Bcje4dLV.js";
2
+
3
+ //#region src/discovery.d.ts
4
+ declare function discoverScheduleDefinitions(options: {
5
+ mode?: "vite-suffix";
6
+ rootDir: string;
7
+ scanDirs?: string[];
8
+ serverDirs?: string[];
9
+ serverRootDir?: string;
10
+ } | {
11
+ mode: "server-schedules";
12
+ scanDirs: string[];
13
+ }): DiscoveredScheduleDefinition[];
14
+ //#endregion
15
+ export { discoverScheduleDefinitions as t };
@@ -1,6 +1,6 @@
1
- import { readFileSync, readdirSync, realpathSync } from "node:fs";
2
- import { resolve } from "node:path";
3
- import "node:fs/promises";
1
+ import { existsSync, readFileSync, readdirSync, realpathSync } from "node:fs";
2
+ import { isAbsolute, relative, resolve, sep } from "node:path";
3
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
4
4
  import "node:url";
5
5
  //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
6
6
  const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
@@ -161,11 +161,15 @@ function readDirEntries(root) {
161
161
  throw error;
162
162
  }
163
163
  }
164
+ function isGitRepositoryDirectory(directory) {
165
+ return existsSync(resolve$1(directory, ".git"));
166
+ }
164
167
  function listMatchingFiles(root, predicate, options = {}) {
165
168
  const files = [];
166
169
  for (const entry of readDirEntries(root)) {
167
170
  const absolute = resolve$1(root, entry.name);
168
171
  if (entry.isDirectory() && !entry.isSymbolicLink()) {
172
+ if (isGitRepositoryDirectory(absolute)) continue;
169
173
  if (entry.name.startsWith(".")) continue;
170
174
  if (ignoredDirs.has(entry.name)) continue;
171
175
  files.push(...listMatchingFiles(absolute, predicate, options));
@@ -247,50 +251,24 @@ function createImportExpression(registryFile, file) {
247
251
  return `import(${JSON.stringify(importPath.startsWith(".") ? importPath : `./${importPath}`)})`;
248
252
  }
249
253
  function createRuntimeRegistryContents(registryFile, definitions) {
250
- const needsWorkflowRuntime = definitions.some((definition) => definition.steps?.length);
251
- const runtimeImport = needsWorkflowRuntime ? [`import { createWorkflowSteps } from "@vite-hub/workflow/runtime/execute"`, `import { takeInlineWorkflowDefinitionForModule } from "@vite-hub/workflow/runtime/state"`] : [];
252
- const imports = definitions.map((definition) => {
253
- if (!definition.steps?.length) return ` ${JSON.stringify(definition.name)}: async () => ${createImportExpression(registryFile, definition.handler)},`;
254
- const workflowDirectory = /\.(?:c|m)?[jt]s$/i.test(definition.handler) ? dirname$1(definition.handler) : definition.handler;
255
- const stepImports = definition.steps.map((step) => {
256
- const stepName = relative$1(workflowDirectory, step);
257
- return `{ name: ${JSON.stringify(stepName)}, run: (await ${createImportExpression(registryFile, step)}).default }`;
258
- });
259
- const hasIndex = /\.(?:c|m)?[jt]s$/i.test(definition.handler);
260
- const indexImport = hasIndex ? `const index = await ${createImportExpression(registryFile, definition.handler)}` : "";
261
- const handler = hasIndex ? `index.default?.handler ? index.default : takeInlineWorkflowDefinitionForModule(${JSON.stringify(definition.name)}, index) || { handler: index.default }` : "{ handler: async (context) => { let value = context.payload; for (const step of Object.values(context.steps || {})) value = await step(value); return value } }";
262
- return [
263
- ` ${JSON.stringify(definition.name)}: async () => {`,
264
- ` const cached = registryEntryCache.get(${JSON.stringify(definition.name)})`,
265
- " if (cached) return cached",
266
- indexImport ? ` ${indexImport}` : "",
267
- ` const steps = [${stepImports.join(", ")}]`,
268
- ` const definition = ${handler}`,
269
- " const entry = {",
270
- " ...definition,",
271
- " options: { ...definition.options, rootStep: false },",
272
- " handler: async (context) => {",
273
- " const workflowSteps = createWorkflowSteps(context, steps)",
274
- " return await definition.handler({ ...context, steps: workflowSteps })",
275
- " },",
276
- " }",
277
- ` registryEntryCache.set(${JSON.stringify(definition.name)}, entry)`,
278
- " return entry",
279
- " },"
280
- ].filter(Boolean).join("\n");
281
- });
282
254
  return [
283
- ...runtimeImport,
284
- runtimeImport.length ? "" : "",
285
- ...needsWorkflowRuntime ? ["const registryEntryCache = new Map()", ""] : [],
255
+ "",
286
256
  "const registry = {",
287
- ...imports,
257
+ ...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: async () => ${createImportExpression(registryFile, definition.handler)},`),
288
258
  "}",
289
259
  "",
290
260
  "export default registry",
291
261
  ""
292
262
  ].join("\n");
293
263
  }
264
+ async function writeRuntimeRegistryFile(registryFile, definitions) {
265
+ await writeFileIfChanged(registryFile, createRuntimeRegistryContents(registryFile, definitions));
266
+ }
267
+ async function writeFileIfChanged(file, contents) {
268
+ if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
269
+ await mkdir(resolve$1(file, ".."), { recursive: true });
270
+ await writeFile(file, contents, "utf8");
271
+ }
294
272
  //#endregion
295
273
  //#region ../internal/src/source-scanner.ts
296
274
  function isQuote(char) {
@@ -757,11 +735,19 @@ function discoverScheduleDefinitions(options) {
757
735
  normalizeName: normalizeDirectoryScheduleName
758
736
  })]);
759
737
  const roots = resolveDefinitionScanRoots(options.rootDir, options.scanDirs);
760
- const serverScanDirs = resolveDefinitionScanRoots(options.serverRootDir || options.rootDir, options.scanDirs).map((root) => resolve(root, "server"));
761
- return mergeDefinitions("schedule", discoverDefinitions("schedule", [createSuffixDefinitionSource("vite-suffix", roots, scheduleSuffixPattern, normalizeSuffixScheduleName, { createDefinition: createDiscoveredScheduleDefinition("vite-suffix") })]), discoverDefinitions("schedule", [createDirectoryDefinitionSource("server-schedules", serverScanDirs, "schedules", {
738
+ const serverRoots = resolveDefinitionScanRoots(options.serverRootDir || options.rootDir, options.scanDirs);
739
+ const serverScanDirs = options.serverDirs ?? serverRoots.map((root) => resolve(root, "server"));
740
+ for (const directory of serverScanDirs) if (roots.every((root) => {
741
+ const path = relative(resolve(root), resolve(directory));
742
+ return path === ".." || path.startsWith(`..${sep}`) || isAbsolute(path);
743
+ })) roots.push(directory);
744
+ return mergeDefinitions("schedule", discoverDefinitions("schedule", [createSuffixDefinitionSource("vite-suffix", roots, scheduleSuffixPattern, normalizeSuffixScheduleName, { createDefinition: createDiscoveredScheduleDefinition("vite-suffix") })]).filter((definition) => !serverScanDirs.some((directory) => {
745
+ const path = relative(resolve(directory, "schedules"), definition.handler);
746
+ return path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path);
747
+ })), discoverDefinitions("schedule", [createDirectoryDefinitionSource("server-schedules", serverScanDirs, "schedules", {
762
748
  createDefinition: createDiscoveredScheduleDefinition("server-schedules"),
763
749
  normalizeName: normalizeDirectoryScheduleName
764
750
  })]));
765
751
  }
766
752
  //#endregion
767
- export { createImportPath as a, createRuntimeRegistryContents as i, findDefaultExportCall as n, ensureGeneratedDir as o, readObjectProperty as r, discoverScheduleDefinitions as t };
753
+ export { readObjectProperty as a, writeRuntimeRegistryFile as c, dirname$1 as d, relative$1 as f, maskSourceLiterals as i, createImportPath as l, findDefaultExportCall as n, splitTopLevel as o, resolve$1 as p, findMatching as r, createRuntimeRegistryContents as s, discoverScheduleDefinitions as t, ensureGeneratedDir as u };
@@ -1,6 +1,6 @@
1
- import { h as invalidScheduleValueDetails, i as loadScheduleDefinition, m as createScheduleError, n as getScheduleRunStore, p as assertRuntimeScheduleId, t as getRuntimeScheduleStore } from "./state-BcEhBV8v.js";
1
+ import { h as invalidScheduleValueDetails, i as loadScheduleDefinition, m as createScheduleError, n as getScheduleRunStore, p as assertRuntimeScheduleId, t as getRuntimeScheduleStore } from "./state-By7WU_ks.js";
2
2
  import { t as isRuntimeScheduleDue } from "./due-Bbh4yIxq.js";
3
- import { t as createLocalWaitUntil } from "./wait-until-CR-JjIOb.js";
3
+ import { t as createLocalWaitUntil } from "./wait-until-BzIwzXw4.js";
4
4
  //#region ../internal/src/runtime/random.ts
5
5
  function randomId(prefix) {
6
6
  const body = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;