@vite-hub/schedule 0.0.3 → 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 (50) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +199 -65
  3. package/dist/definition-CMiOg1lg.js +111 -0
  4. package/dist/definition.d.ts +4 -6
  5. package/dist/definition.js +2 -42
  6. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  7. package/dist/error-diagnostics-in7mif5s.js +45 -0
  8. package/dist/execute-BJrgNgQ0.js +201 -0
  9. package/dist/index.d.ts +7 -51
  10. package/dist/index.js +2 -7
  11. package/dist/inspect-DTfAo5gS.js +118 -0
  12. package/dist/kv-storage-Bv9ocZT-.d.ts +18 -0
  13. package/dist/nuxt.d.ts +4 -6
  14. package/dist/nuxt.js +3 -1
  15. package/dist/operations-gk2qzhYV.js +131 -0
  16. package/dist/operations-tNUdj3G4.d.ts +212 -0
  17. package/dist/operations.d.ts +61 -0
  18. package/dist/operations.js +921 -0
  19. package/dist/registry-module.d.ts +0 -5
  20. package/dist/runtime/kv.d.ts +4 -0
  21. package/dist/{kv-BJ1I9IlJ.js → runtime/kv.js} +1 -1
  22. package/dist/runtime/process.d.ts +26 -5
  23. package/dist/runtime/process.js +337 -75
  24. package/dist/runtime/state.d.ts +8 -12
  25. package/dist/runtime/state.js +2 -2
  26. package/dist/runtime/static.d.ts +18 -12
  27. package/dist/runtime/static.js +2 -138
  28. package/dist/runtime.d.ts +36 -4
  29. package/dist/runtime.js +5 -3
  30. package/dist/state-DSxmHPn3.js +448 -0
  31. package/dist/static-6g82xguw.js +245 -0
  32. package/dist/store-QAOd8bxm.d.ts +11 -0
  33. package/dist/types-CHdV9FQU.d.ts +113 -0
  34. package/dist/vite-BAVyZ8hZ.d.ts +474 -0
  35. package/dist/vite-BJwZkMrn.js +5193 -0
  36. package/dist/vite.d.ts +2 -38
  37. package/dist/vite.js +2 -2
  38. package/dist/wait-until-BmIqRo4x.js +87 -0
  39. package/package.json +68 -22
  40. package/dist/client-BMFCy0dX.js +0 -233
  41. package/dist/discovery-BZlat3Kc.js +0 -776
  42. package/dist/due-Bbh4yIxq.js +0 -59
  43. package/dist/execute-ClFYvmp9.js +0 -211
  44. package/dist/runtime/driver.d.ts +0 -26
  45. package/dist/runtime/driver.js +0 -334
  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/vite-BX6_KiRw.js +0 -1218
  50. package/dist/wait-until-CR-JjIOb.js +0 -23
@@ -0,0 +1,245 @@
1
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-in7mif5s.js";
2
+ import { a as invalidScheduleValueDetails, i as createScheduleError, n as isScheduleDate, r as validateScheduledAt, t as runWithScheduleWaitUntil } from "./wait-until-BmIqRo4x.js";
3
+ import { normalizeRuntimeDiagnosticError } from "@vite-hub/runtime";
4
+ import { hasRuntimeType } from "@vite-hub/runtime/internal/runtime-type";
5
+ //#region ../internal/src/secret.ts
6
+ const secretEncoder = new TextEncoder();
7
+ /**
8
+ * Compares a request value with an expected secret in constant time for the length of `expected`. Returns `false`
9
+ * when either value is missing or empty. It uses no Node API, so it also runs in Worker runtimes.
10
+ */
11
+ function isViteHubSecretEqual(actual, expected) {
12
+ if (!actual || !expected) return false;
13
+ const left = secretEncoder.encode(actual);
14
+ const right = secretEncoder.encode(expected);
15
+ let difference = left.length ^ right.length;
16
+ for (let index = 0; index < right.length; index += 1) difference |= (left[index] ?? 0) ^ right[index];
17
+ return difference === 0;
18
+ }
19
+ /**
20
+ * Compares the token of a `Bearer` `Authorization` header with an expected secret in constant time. The scheme is
21
+ * case-insensitive. Returns `false` for another scheme or a missing value.
22
+ */
23
+ function isViteHubBearerSecretEqual(authorization, expected) {
24
+ return isViteHubSecretEqual(/^Bearer\s+(.+)$/i.exec(authorization ?? "")?.[1], expected);
25
+ }
26
+ //#endregion
27
+ //#region src/runtime/static.ts
28
+ const intrinsicErrorIsError = Error.isError;
29
+ const intrinsicNativeErrorIsError = (() => {
30
+ try {
31
+ const process = globalThis.process;
32
+ const getBuiltinModule = process?.getBuiltinModule;
33
+ if (typeof getBuiltinModule !== "function") return void 0;
34
+ const util = getBuiltinModule.call(process, "util");
35
+ return typeof util?.types?.isNativeError === "function" ? util.types.isNativeError : void 0;
36
+ } catch {
37
+ return;
38
+ }
39
+ })();
40
+ function missingScheduleDefinitionError(name) {
41
+ return scheduleErrorDiagnostics.SCHEDULE_R0034({ message: `Missing schedule definition: ${name}` });
42
+ }
43
+ /**
44
+ * Checks the `Authorization` header of a Vercel Cron request against `CRON_SECRET` in constant time.
45
+ */
46
+ function isScheduleCronAuthorized(authorization, cronSecret) {
47
+ return isViteHubBearerSecretEqual(authorization, cronSecret);
48
+ }
49
+ function normalizeCron(cron) {
50
+ return cron.trim().split(/\s+/).join(" ");
51
+ }
52
+ function normalizeScheduleRuntimeError(error) {
53
+ if (isScheduleRuntimeError(error)) return error;
54
+ let message;
55
+ try {
56
+ message = String(error);
57
+ } catch {
58
+ message = "[unprintable thrown value]";
59
+ }
60
+ try {
61
+ return scheduleErrorDiagnostics.SCHEDULE_R0035({
62
+ cause: error,
63
+ message
64
+ });
65
+ } catch {
66
+ const fallback = new Error(message);
67
+ Object.defineProperty(fallback, "code", {
68
+ value: "SCHEDULE_R0035",
69
+ enumerable: true
70
+ });
71
+ Object.defineProperty(fallback, "cause", { value: error });
72
+ return fallback;
73
+ }
74
+ }
75
+ function isScheduleRuntimeError(error) {
76
+ try {
77
+ if (error instanceof Error) return true;
78
+ } catch {
79
+ return false;
80
+ }
81
+ if (error === null || typeof error !== "object") return false;
82
+ if (typeof intrinsicNativeErrorIsError === "function") try {
83
+ return intrinsicNativeErrorIsError(error);
84
+ } catch {}
85
+ try {
86
+ return typeof intrinsicErrorIsError === "function" && intrinsicErrorIsError(error) === true;
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+ function createStaticScheduleRun(options) {
92
+ const scheduledAt = validateScheduledAt(options.scheduledAt);
93
+ return {
94
+ cron: options.cron,
95
+ id: `run_${options.name}_${scheduledAt.toISOString()}`,
96
+ scheduleId: options.name,
97
+ scheduledAt,
98
+ waitUntil: options.waitUntil
99
+ };
100
+ }
101
+ async function executeStaticSchedule(options) {
102
+ return await runWithScheduleWaitUntil((waitUntil) => options.definition.handler(createStaticScheduleRun({
103
+ ...options,
104
+ waitUntil
105
+ })), options.waitUntil);
106
+ }
107
+ async function executeMatchingStaticSchedules(options) {
108
+ if (!hasRuntimeType(options.cron, "string") || !options.cron.trim()) throw createScheduleError("SCHEDULE_INVALID_CRON", { details: invalidScheduleValueDetails("cron", options.cron) });
109
+ const cron = normalizeCron(options.cron);
110
+ const scheduledAt = validateScheduledAt(options.scheduledAt);
111
+ const runs = [];
112
+ for (const [name, load] of Object.entries(options.registry)) {
113
+ const definition = unwrapScheduleDefinition(await load());
114
+ if (!definition || normalizeCron(definition.cron) !== cron) continue;
115
+ runs.push({
116
+ name,
117
+ run: executeStaticSchedule({
118
+ cron: options.cron,
119
+ definition,
120
+ name,
121
+ scheduledAt,
122
+ waitUntil: options.waitUntil
123
+ })
124
+ });
125
+ }
126
+ const results = await Promise.allSettled(runs.map(({ run }) => run));
127
+ const failures = [];
128
+ results.forEach((result, index) => {
129
+ if (result.status === "fulfilled") return;
130
+ failures.push(result.reason);
131
+ console.error(`[vitehub:schedule] Schedule "${runs[index].name}" failed (cron "${options.cron}").`, normalizeRuntimeDiagnosticError(result.reason, { includeStack: true }));
132
+ });
133
+ if (failures.length === 1) throw failures[0];
134
+ if (failures.length) throw new AggregateError(failures, `[vitehub:schedule] ${failures.length} schedules failed for cron "${options.cron}".`);
135
+ return results.map((result) => result.status === "fulfilled" ? result.value : void 0);
136
+ }
137
+ async function executeCloudflareStaticSchedules(event, options) {
138
+ const scheduled = readCloudflareScheduledEvent(event);
139
+ return await runWithCloudflareServerEnv(event, async (waitUntil) => {
140
+ return await executeMatchingStaticSchedules({
141
+ cron: scheduled.cron,
142
+ registry: options.registry,
143
+ scheduledAt: scheduled.scheduledAt,
144
+ waitUntil
145
+ });
146
+ }, options.waitUntil ?? readCloudflareWaitUntil(event));
147
+ }
148
+ function readCloudflareScheduledEvent(event) {
149
+ const cron = event.controller?.cron ?? event.cron;
150
+ if (!hasRuntimeType(cron, "string") || !cron.trim()) throw scheduleErrorDiagnostics.SCHEDULE_R0027({ message: "[vitehub:schedule] Cloudflare scheduled event is missing a cron string." });
151
+ const scheduledTime = event.controller?.scheduledTime ?? event.scheduledTime;
152
+ const scheduledAt = isScheduleDate(scheduledTime) ? new Date(Date.prototype.getTime.call(scheduledTime)) : scheduledTime === void 0 ? /* @__PURE__ */ new Date() : new Date(scheduledTime);
153
+ if (Number.isNaN(scheduledAt.getTime())) throw scheduleErrorDiagnostics.SCHEDULE_R0028({ message: "[vitehub:schedule] Cloudflare scheduled event has an invalid scheduledTime." });
154
+ return {
155
+ cron,
156
+ scheduledAt
157
+ };
158
+ }
159
+ async function runWithCloudflareServerEnv(event, callback, hostWaitUntil) {
160
+ const globals = globalThis;
161
+ const hadGlobalEnv = Object.prototype.hasOwnProperty.call(globals, "__env__");
162
+ const previousGlobalEnv = globals.__env__;
163
+ const env = readCloudflareEventEnv(event);
164
+ if (env) globals.__env__ = env;
165
+ const pending = /* @__PURE__ */ new Set();
166
+ const waitUntil = hostWaitUntil ? (value) => {
167
+ const promise = Promise.resolve(value);
168
+ pending.add(promise);
169
+ promise.then(() => pending.delete(promise), () => pending.delete(promise));
170
+ hostWaitUntil(promise);
171
+ } : void 0;
172
+ try {
173
+ return await callback(waitUntil);
174
+ } finally {
175
+ if (pending.size === 0) restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv);
176
+ else hostWaitUntil(flushPendingWork(pending).finally(() => {
177
+ restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv);
178
+ }));
179
+ }
180
+ }
181
+ async function flushPendingWork(pending) {
182
+ while (pending.size > 0) await Promise.allSettled(pending);
183
+ }
184
+ function restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv) {
185
+ if (hadGlobalEnv) globals.__env__ = previousGlobalEnv;
186
+ else delete globals.__env__;
187
+ }
188
+ function isRecord(value) {
189
+ return Object(value) === value && !Array.isArray(value);
190
+ }
191
+ function isCallable(value) {
192
+ if (value === null || value === void 0 || Object(value) !== value) return false;
193
+ try {
194
+ Function.prototype.toString.call(value);
195
+ return true;
196
+ } catch {
197
+ return false;
198
+ }
199
+ }
200
+ function readCloudflareWaitUntil(event) {
201
+ const context = isRecord(event.context) ? event.context : void 0;
202
+ const cloudflareContext = isRecord(context?.cloudflare) ? context.cloudflare : void 0;
203
+ const platformContext = isRecord(context?._platform) ? context._platform : void 0;
204
+ const platformCloudflareContext = isRecord(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
205
+ const request = isRecord(event.req) ? event.req : void 0;
206
+ const runtime = isRecord(request?.runtime) ? request.runtime : void 0;
207
+ const runtimeCloudflare = isRecord(runtime?.cloudflare) ? runtime.cloudflare : void 0;
208
+ const owners = [
209
+ event,
210
+ context,
211
+ cloudflareContext,
212
+ isRecord(cloudflareContext?.context) ? cloudflareContext.context : void 0,
213
+ platformCloudflareContext,
214
+ isRecord(platformCloudflareContext?.context) ? platformCloudflareContext.context : void 0,
215
+ request,
216
+ runtimeCloudflare,
217
+ isRecord(runtimeCloudflare?.context) ? runtimeCloudflare.context : void 0
218
+ ];
219
+ for (const owner of owners) {
220
+ const waitUntil = owner?.waitUntil;
221
+ if (isCallable(waitUntil)) return (promise) => Reflect.apply(waitUntil, owner, [promise]);
222
+ }
223
+ }
224
+ function readCloudflareEventEnv(event) {
225
+ if (isRecord(event.env)) return event.env;
226
+ const context = isRecord(event.context) ? event.context : void 0;
227
+ const cloudflareContext = isRecord(context?.cloudflare) ? context.cloudflare : void 0;
228
+ if (isRecord(cloudflareContext?.env)) return cloudflareContext.env;
229
+ const platformContext = isRecord(context?._platform) ? context._platform : void 0;
230
+ const platformCloudflareContext = isRecord(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
231
+ if (isRecord(platformCloudflareContext?.env)) return platformCloudflareContext.env;
232
+ const request = isRecord(event.req) ? event.req : void 0;
233
+ const runtime = isRecord(request?.runtime) ? request.runtime : void 0;
234
+ const runtimeCloudflare = isRecord(runtime?.cloudflare) ? runtime.cloudflare : void 0;
235
+ return isRecord(runtimeCloudflare?.env) ? runtimeCloudflare.env : void 0;
236
+ }
237
+ function isStaticScheduleDefinition(value) {
238
+ return isRecord(value) && Object.hasOwn(value, "cron") && hasRuntimeType(value.cron, "string") && Object.hasOwn(value, "handler") && typeof value.handler === "function";
239
+ }
240
+ function unwrapScheduleDefinition(loaded) {
241
+ const candidate = isRecord(loaded) && Object.hasOwn(loaded, "default") ? loaded.default : loaded;
242
+ return isStaticScheduleDefinition(candidate) ? candidate : void 0;
243
+ }
244
+ //#endregion
245
+ export { isScheduleCronAuthorized as a, normalizeScheduleRuntimeError as c, executeStaticSchedule as i, unwrapScheduleDefinition as l, executeCloudflareStaticSchedules as n, missingScheduleDefinitionError as o, executeMatchingStaticSchedules as r, normalizeCron as s, createStaticScheduleRun as t };
@@ -0,0 +1,11 @@
1
+ import { g as ScheduleRunStore } from "./types-CHdV9FQU.js";
2
+ import { t as ScheduleKVStorage } from "./kv-storage-Bv9ocZT-.js";
3
+ //#region src/runtime/store.d.ts
4
+ interface KVScheduleStoreOptions {
5
+ kvStore: ScheduleKVStorage;
6
+ prefix?: string;
7
+ }
8
+ declare function createMemoryScheduleRunStore(): ScheduleRunStore;
9
+ declare function createKVScheduleRunStore(options: KVScheduleStoreOptions): ScheduleRunStore;
10
+ //#endregion
11
+ export { createKVScheduleRunStore as n, createMemoryScheduleRunStore as r, KVScheduleStoreOptions as t };
@@ -0,0 +1,113 @@
1
+ import { SerializedResponse } from "@vite-hub/runtime";
2
+ //#region src/types.d.ts
3
+ interface ScheduleRunContext {
4
+ id: string;
5
+ attemptId?: string;
6
+ runId?: string;
7
+ scheduleId?: string;
8
+ scheduledAt: Date;
9
+ /** Name of the Schedule Definition that runs. */
10
+ target?: string;
11
+ waitUntil(promise: PromiseLike<unknown>): void;
12
+ }
13
+ type ScheduleHandler<TResult = unknown> = {
14
+ bivarianceHack(context: ScheduleRunContext): TResult | Promise<TResult>;
15
+ }["bivarianceHack"];
16
+ interface ScheduleDefinitionInput<TResult = unknown> {
17
+ /** Allows `runSchedule()`, the Console, and `vitehub schedule run` to start this definition outside its cron. */
18
+ manual?: boolean;
19
+ /** Five-field cron expression, evaluated in `timeZone`. */
20
+ cron: string;
21
+ handler: ScheduleHandler<TResult>;
22
+ /**
23
+ * IANA time zone of `cron`, such as `"Europe/Madrid"`. Defaults to `"UTC"`. The process driver follows daylight
24
+ * saving time. Provider cron output (Cloudflare, Vercel, Netlify, Deno) supports only UTC.
25
+ */
26
+ timeZone?: string;
27
+ }
28
+ interface ScheduleDefinitionOptions {
29
+ /** Allows `runSchedule()`, the Console, and `vitehub schedule run` to start this definition outside its cron. */
30
+ manual?: boolean;
31
+ /** IANA time zone of the cron, such as `"Europe/Madrid"`. Defaults to `"UTC"`. */
32
+ timeZone?: string;
33
+ }
34
+ interface ScheduleDefinition<TResult = unknown> {
35
+ cron: string;
36
+ handler: ScheduleHandler<TResult>;
37
+ /** IANA time zone of `cron`. Absent means UTC. */
38
+ timeZone?: string;
39
+ options?: Omit<ScheduleDefinitionOptions, "timeZone">;
40
+ }
41
+ type ScheduleRegistryDefinition = ScheduleDefinition;
42
+ interface ScheduleDefinitionRegistry {
43
+ [name: string]: () => Promise<{
44
+ default?: ScheduleRegistryDefinition;
45
+ } | ScheduleRegistryDefinition>;
46
+ }
47
+ type ScheduleRunStatus = "pending" | "running" | "succeeded" | "failed";
48
+ type ScheduleRunAttemptStatus = "running" | "succeeded" | "failed";
49
+ interface ScheduleRunError {
50
+ message: string;
51
+ name?: string;
52
+ stack?: string;
53
+ }
54
+ /** Serializable representation of a schedule invocation response. */
55
+ type ScheduleRunResponse = SerializedResponse;
56
+ interface ScheduleRunRecord {
57
+ attemptCount: number;
58
+ completedAt?: Date;
59
+ createdAt: Date;
60
+ error?: ScheduleRunError;
61
+ id: string;
62
+ scheduleId: string;
63
+ response?: ScheduleRunResponse;
64
+ scheduledAt: Date;
65
+ startedAt?: Date;
66
+ status: ScheduleRunStatus;
67
+ /** Name of the Schedule Definition that ran. */
68
+ target: string;
69
+ updatedAt: Date;
70
+ }
71
+ interface ScheduleRunAttemptRecord {
72
+ completedAt?: Date;
73
+ createdAt: Date;
74
+ error?: ScheduleRunError;
75
+ id: string;
76
+ runId: string;
77
+ startedAt: Date;
78
+ status: ScheduleRunAttemptStatus;
79
+ updatedAt: Date;
80
+ }
81
+ interface ScheduleRunListOptions {
82
+ /** Maximum number of records, newest scheduled occurrence first. */
83
+ limit?: number;
84
+ scheduleId?: string;
85
+ }
86
+ interface ScheduleRunStore {
87
+ createAttempt: (attempt: ScheduleRunAttemptRecord) => Promise<ScheduleRunAttemptRecord> | ScheduleRunAttemptRecord;
88
+ createRun: (run: ScheduleRunRecord) => Promise<ScheduleRunRecord> | ScheduleRunRecord;
89
+ getAttempt: (id: string) => Promise<ScheduleRunAttemptRecord | undefined> | ScheduleRunAttemptRecord | undefined;
90
+ getRun: (id: string) => Promise<ScheduleRunRecord | undefined> | ScheduleRunRecord | undefined;
91
+ listAttempts: (runId: string) => Promise<ScheduleRunAttemptRecord[]> | ScheduleRunAttemptRecord[];
92
+ /** Reads several histories using one request-scoped key snapshot when supported. */
93
+ listRunsBatch?: (options: ScheduleRunListOptions[]) => Promise<ScheduleRunRecord[][]> | ScheduleRunRecord[][];
94
+ listRuns: (options?: ScheduleRunListOptions) => Promise<ScheduleRunRecord[]> | ScheduleRunRecord[];
95
+ updateAttempt: (id: string, patch: Partial<Pick<ScheduleRunAttemptRecord, "completedAt" | "error" | "status">> & {
96
+ updatedAt: Date;
97
+ }) => Promise<ScheduleRunAttemptRecord | undefined> | ScheduleRunAttemptRecord | undefined;
98
+ updateRun: (id: string, patch: Partial<Pick<ScheduleRunRecord, "attemptCount" | "completedAt" | "error" | "response" | "startedAt" | "status">> & {
99
+ updatedAt: Date;
100
+ }) => Promise<ScheduleRunRecord | undefined> | ScheduleRunRecord | undefined;
101
+ }
102
+ interface DiscoveredScheduleDefinition {
103
+ manual?: boolean;
104
+ /** Plugin that contributed the Definition through `vitehub.schedules`. Only set for contributed Definitions. */
105
+ contributor?: string;
106
+ handler: string;
107
+ name: string;
108
+ /** Why the plugin contributed the Definition. Only set for contributed Definitions. */
109
+ reason?: string;
110
+ source?: "server-schedules" | "vite-plugin-contribution" | "vite-suffix";
111
+ }
112
+ //#endregion
113
+ export { ScheduleDefinitionRegistry as a, ScheduleRunAttemptRecord as c, ScheduleRunError as d, ScheduleRunListOptions as f, ScheduleRunStore as g, ScheduleRunStatus as h, ScheduleDefinitionOptions as i, ScheduleRunAttemptStatus as l, ScheduleRunResponse as m, ScheduleDefinition as n, ScheduleHandler as o, ScheduleRunRecord as p, ScheduleDefinitionInput as r, ScheduleRegistryDefinition as s, DiscoveredScheduleDefinition as t, ScheduleRunContext as u };