@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.
- package/README.md +12 -7
- package/dist/{console-wEhr0LWn.d.ts → console-DueeEBcM.d.ts} +2 -0
- package/dist/cron-C1l3TquN.js +70 -0
- package/dist/definition.js +1 -2
- package/dist/{due-sOJvF_6Z.js → due-n120-_nz.js} +22 -7
- package/dist/durability.d.ts +2 -2
- package/dist/durability.js +5 -5
- package/dist/{error-diagnostics-CQ4BUqRe.js → error-diagnostics-C0KyI408.js} +5 -1
- package/dist/{error-diagnostics-BBtYYl8j.js → error-diagnostics-DTmP6baC.js} +1 -5
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -4
- package/dist/{started-name-ruCM1EtQ.js → inspect-DTfAo5gS.js} +1 -5
- package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CI2PJGqu.d.ts} +8 -2
- package/dist/{operations-DqwmJ8MN.js → operations-DlrK9mlH.js} +6 -9
- package/dist/operations.d.ts +1 -1
- package/dist/operations.js +5 -5
- package/dist/os.d.ts +0 -1
- package/dist/os.js +12 -84
- package/dist/out-BbXG-yVX.js +21755 -0
- package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
- package/dist/runtime/console.d.ts +1 -1
- package/dist/runtime/console.js +2 -2
- package/dist/runtime/process.js +24 -45
- package/dist/runtime/state.d.ts +1 -1
- package/dist/runtime/state.js +1 -1
- package/dist/runtime/static.d.ts +2 -73
- package/dist/runtime/static.js +3 -2
- package/dist/runtime.d.ts +3 -3
- package/dist/runtime.js +4 -4
- package/dist/{started-B0pc3JY0.js → started-BWWr7Ufw.js} +3 -4
- package/dist/{started-Bk2Icknk.js → started-BXdWMdji.js} +24 -6
- package/dist/{started-errors-DEmYH-vp.js → started-errors-BMg04lL3.js} +45 -5
- package/dist/started-name-DudQ0fsR.js +5 -0
- package/dist/{state-D4SZH6zk.js → state-BjWnxyhv.js} +70 -117
- package/dist/{state-CPd10SXq.d.ts → state-CJKAhskJ.d.ts} +2 -1
- package/dist/static-BgoOCoe5.js +610 -0
- package/dist/static-CcBWx1kU.d.ts +96 -0
- package/dist/{store-DeMojnXM.d.ts → store-CZHZfttA.d.ts} +2 -6
- package/dist/vite.d.ts +5 -3
- package/dist/vite.js +2251 -130
- package/package.json +4 -4
- package/dist/invariant-DolT9EEx.js +0 -22
- package/dist/static-7JCga3Iu.js +0 -281
- package/dist/wait-until-Dy4Bn3ZN.js +0 -112
|
@@ -0,0 +1,610 @@
|
|
|
1
|
+
import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
|
|
2
|
+
import { t as scheduleErrorDiagnostics } from "./error-diagnostics-DTmP6baC.js";
|
|
3
|
+
import { n as isScheduleDue, r as latestCronMinute, t as cronWithWeekdayNames } from "./due-n120-_nz.js";
|
|
4
|
+
import "./started-name-DudQ0fsR.js";
|
|
5
|
+
import { ViteHubError, normalizeRuntimeDiagnosticError } from "@vite-hub/runtime";
|
|
6
|
+
import { emitRunFailed, toRunFailedError } from "@vite-hub/runtime/internal/run-failed";
|
|
7
|
+
import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
|
|
8
|
+
//#region src/errors.ts
|
|
9
|
+
const scheduleErrorMessages = {
|
|
10
|
+
SCHEDULE_DEFINITION_NOT_FOUND: "Static Schedule Definition was not found.",
|
|
11
|
+
SCHEDULE_INVALID_CRON: "Schedule cron is invalid.",
|
|
12
|
+
SCHEDULE_INVALID_SCHEDULED_AT: "Schedule scheduledAt value is invalid.",
|
|
13
|
+
SCHEDULE_MANUAL_RUN_DISABLED: "Schedule Definition does not allow manual runs. Set manual: true to allow them.",
|
|
14
|
+
SCHEDULE_NOT_DUE: "Schedule is not due.",
|
|
15
|
+
SCHEDULE_RUN_NOT_FOUND: "Schedule Run was not found."
|
|
16
|
+
};
|
|
17
|
+
function isDateValue(value) {
|
|
18
|
+
if (value instanceof Date) return true;
|
|
19
|
+
try {
|
|
20
|
+
Date.prototype.getTime.call(value);
|
|
21
|
+
return true;
|
|
22
|
+
} catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function invalidScheduleValueDetails(field, value) {
|
|
27
|
+
let valueType;
|
|
28
|
+
try {
|
|
29
|
+
valueType = value === null ? "null" : Array.isArray(value) ? "array" : isDateValue(value) ? "date" : typeof value;
|
|
30
|
+
} catch {
|
|
31
|
+
valueType = "unknown";
|
|
32
|
+
}
|
|
33
|
+
return {
|
|
34
|
+
field,
|
|
35
|
+
valueType
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function createScheduleError(code, options = {}) {
|
|
39
|
+
return new ViteHubError(code, scheduleErrorMessages[code], options);
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/runtime/date.ts
|
|
43
|
+
/** The idempotency key of one Schedule occurrence. Two runs of the same Schedule for the same time share it. */
|
|
44
|
+
function scheduleIdempotencyKey(name, scheduledAt) {
|
|
45
|
+
return `schedule:${name}:${scheduledAt.toISOString()}`;
|
|
46
|
+
}
|
|
47
|
+
function isScheduleDate(value) {
|
|
48
|
+
try {
|
|
49
|
+
return !Number.isNaN(Date.prototype.getTime.call(value));
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const scheduledAtText = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/i;
|
|
55
|
+
function parseScheduledAtText(value) {
|
|
56
|
+
const match = scheduledAtText.exec(value);
|
|
57
|
+
if (!match) return;
|
|
58
|
+
const [, year, month, day, hour] = match.map(Number);
|
|
59
|
+
const calendarDay = /* @__PURE__ */ new Date(0);
|
|
60
|
+
calendarDay.setUTCFullYear(year, month - 1, day);
|
|
61
|
+
if (hour > 23 || calendarDay.getUTCMonth() !== month - 1 || calendarDay.getUTCDate() !== day) return;
|
|
62
|
+
const date = new Date(value);
|
|
63
|
+
return Number.isNaN(date.getTime()) ? void 0 : date;
|
|
64
|
+
}
|
|
65
|
+
function validateScheduledAt(scheduledAt) {
|
|
66
|
+
const value = scheduledAt ?? /* @__PURE__ */ new Date();
|
|
67
|
+
if (!isScheduleDate(value)) throw createScheduleError("SCHEDULE_INVALID_SCHEDULED_AT", { details: invalidScheduleValueDetails("scheduledAt", value) });
|
|
68
|
+
return new Date(Date.prototype.getTime.call(value));
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Returns the time a manual run treats as its fire time. A string must be an ISO 8601 date-time with a time zone, such
|
|
72
|
+
* as `2026-01-31T23:59:00Z`. Anything else fails with `SCHEDULE_INVALID_SCHEDULED_AT`. Absent means now.
|
|
73
|
+
*/
|
|
74
|
+
function parseScheduledAt(scheduledAt) {
|
|
75
|
+
if (typeof scheduledAt !== "string") return validateScheduledAt(scheduledAt);
|
|
76
|
+
const parsed = parseScheduledAtText(scheduledAt);
|
|
77
|
+
if (parsed) return parsed;
|
|
78
|
+
throw createScheduleError("SCHEDULE_INVALID_SCHEDULED_AT", { details: invalidScheduleValueDetails("scheduledAt", scheduledAt) });
|
|
79
|
+
}
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region ../internal/src/runtime/request-log.ts
|
|
82
|
+
function isRequestLog(value) {
|
|
83
|
+
return value !== null && typeof value === "object" && typeof Reflect.get(value, "set") === "function" && typeof Reflect.get(value, "warn") === "function" && typeof Reflect.get(value, "error") === "function";
|
|
84
|
+
}
|
|
85
|
+
function contextLog(value) {
|
|
86
|
+
const context = value !== null && typeof value === "object" ? Reflect.get(value, "context") : void 0;
|
|
87
|
+
return context !== null && typeof context === "object" ? Reflect.get(context, "log") : void 0;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* The evlog request logger of a request, or `undefined` when the app does not register evlog. Pass a Nitro v3 event
|
|
91
|
+
* (evlog sets `event.req.context.log`) or its `Request` (`request.context.log`).
|
|
92
|
+
*/
|
|
93
|
+
function requestLog(input) {
|
|
94
|
+
const log = contextLog(input !== null && typeof input === "object" ? Reflect.get(input, "req") : void 0) ?? contextLog(input);
|
|
95
|
+
return isRequestLog(log) ? log : void 0;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The `Symbol.for()` key of the bridge on `globalThis`. Every bundled copy of this module and the Nitro plugin that
|
|
99
|
+
* `vitehub()` generates use the same key.
|
|
100
|
+
*/
|
|
101
|
+
const evlogBridgeKey = "vitehub.evlog";
|
|
102
|
+
function isEvlogBridge(value) {
|
|
103
|
+
return value !== null && typeof value === "object" && typeof Reflect.get(value, "createLogger") === "function";
|
|
104
|
+
}
|
|
105
|
+
/** The evlog bridge of this process, or `undefined` when the app does not register evlog. */
|
|
106
|
+
function evlogBridge() {
|
|
107
|
+
const bridge = globalThis[Symbol.for(evlogBridgeKey)];
|
|
108
|
+
return isEvlogBridge(bridge) ? bridge : void 0;
|
|
109
|
+
}
|
|
110
|
+
function activeBridge() {
|
|
111
|
+
const bridge = evlogBridge();
|
|
112
|
+
try {
|
|
113
|
+
return bridge && bridge.isEnabled?.() !== false ? bridge : void 0;
|
|
114
|
+
} catch {
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* A short name for the cause of a failure, safe to put in a log field: the string `code` of the error, such as
|
|
120
|
+
* `ENOSPC` or a ViteHub diagnostic code, else its class name. Never the message, which can hold paths or values.
|
|
121
|
+
*/
|
|
122
|
+
function errorCode(error) {
|
|
123
|
+
if (error === null || typeof error !== "object") return void 0;
|
|
124
|
+
const code = Reflect.get(error, "code");
|
|
125
|
+
if (typeof code === "string" && code) return code;
|
|
126
|
+
const name = Reflect.get(error, "name");
|
|
127
|
+
return typeof name === "string" && name && name !== "Error" ? name : void 0;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Emits one evlog event of its own, outside a request's wide event. The event also reaches the app's `evlog:drain`
|
|
131
|
+
* hooks. Returns `false` when the app does not register evlog or turned it off, and never throws.
|
|
132
|
+
*/
|
|
133
|
+
function emitLogEvent(event) {
|
|
134
|
+
const bridge = activeBridge();
|
|
135
|
+
if (!bridge) return false;
|
|
136
|
+
try {
|
|
137
|
+
const log = bridge.createLogger({
|
|
138
|
+
action: event.field,
|
|
139
|
+
message: event.message,
|
|
140
|
+
[event.field]: event.fields
|
|
141
|
+
}, event.waitUntil ? { waitUntil: event.waitUntil } : void 0);
|
|
142
|
+
if (event.level === "error") log.error(event.withError && event.error instanceof Error ? event.error : event.message);
|
|
143
|
+
else log[event.level](event.message);
|
|
144
|
+
const emitted = log.emit();
|
|
145
|
+
if (emitted && bridge.drain) {
|
|
146
|
+
const drained = Promise.resolve().then(() => bridge.drain?.(emitted)).catch((error) => {
|
|
147
|
+
console.error("[evlog] drain failed:", error);
|
|
148
|
+
});
|
|
149
|
+
event.waitUntil?.(drained);
|
|
150
|
+
}
|
|
151
|
+
return true;
|
|
152
|
+
} catch {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Logs a failure that the caller survives, with a fixed message and the `code` of the error. With the evlog request
|
|
158
|
+
* logger of `request`, it replaces `[field]` on the request's wide event and adds a warning. Pass `request` only when the
|
|
159
|
+
* request has not answered yet: evlog drops fields after it emits the wide event. Otherwise it emits an event of its
|
|
160
|
+
* own. Without evlog, or with evlog off, it calls `fallback`, which prints to the server console as before. It never
|
|
161
|
+
* throws.
|
|
162
|
+
*/
|
|
163
|
+
function logFailure(failure, fallback) {
|
|
164
|
+
const code = errorCode(failure.error);
|
|
165
|
+
const fields = {
|
|
166
|
+
...failure.fields,
|
|
167
|
+
...code ? { code } : {}
|
|
168
|
+
};
|
|
169
|
+
const log = failure.request !== void 0 && activeBridge() ? requestLog(failure.request) : void 0;
|
|
170
|
+
if (log) try {
|
|
171
|
+
log.set({ [failure.field]: false });
|
|
172
|
+
log.warn(failure.message, { [failure.field]: fields });
|
|
173
|
+
return;
|
|
174
|
+
} catch {}
|
|
175
|
+
if (emitLogEvent({
|
|
176
|
+
...failure,
|
|
177
|
+
fields,
|
|
178
|
+
level: failure.level ?? "warn"
|
|
179
|
+
})) return;
|
|
180
|
+
try {
|
|
181
|
+
fallback();
|
|
182
|
+
} catch {}
|
|
183
|
+
}
|
|
184
|
+
//#endregion
|
|
185
|
+
//#region src/runtime/log.ts
|
|
186
|
+
const loggedKey = Symbol.for("vitehub.schedule.logged-errors");
|
|
187
|
+
const runtimeGlobal = globalThis;
|
|
188
|
+
const logged = runtimeGlobal[loggedKey] ||= /* @__PURE__ */ new WeakSet();
|
|
189
|
+
/**
|
|
190
|
+
* Emits one evlog event for a Schedule run that ran its handler: `{ action: "schedule", schedule }`, at `info` for a
|
|
191
|
+
* success and at `error` with the handler's error for a failure. The handler is the app's own code, so its error goes
|
|
192
|
+
* on the event as a route's error does. Returns whether evlog has the event. Without evlog, it does nothing: the run
|
|
193
|
+
* history keeps the run.
|
|
194
|
+
*/
|
|
195
|
+
function logScheduleRun(run, startedAt, outcome, options = {}) {
|
|
196
|
+
const fields = {
|
|
197
|
+
...run,
|
|
198
|
+
scheduledAt: run.scheduledAt.toISOString(),
|
|
199
|
+
ms: Math.round(performance.now() - startedAt),
|
|
200
|
+
outcome
|
|
201
|
+
};
|
|
202
|
+
const waitUntil = options.waitUntil ? { waitUntil: options.waitUntil } : {};
|
|
203
|
+
return outcome === "failure" ? emitLogEvent({
|
|
204
|
+
field: "schedule",
|
|
205
|
+
fields,
|
|
206
|
+
level: "error",
|
|
207
|
+
message: "Schedule run failed",
|
|
208
|
+
error: options.error,
|
|
209
|
+
withError: true,
|
|
210
|
+
...waitUntil
|
|
211
|
+
}) : emitLogEvent({
|
|
212
|
+
field: "schedule",
|
|
213
|
+
fields,
|
|
214
|
+
level: "info",
|
|
215
|
+
message: "Schedule run succeeded",
|
|
216
|
+
...waitUntil
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
/** Notes that a log event has this error. An error that is not an object cannot be noted: wrap it first. */
|
|
220
|
+
function rememberLoggedScheduleError(error) {
|
|
221
|
+
logged.add(error);
|
|
222
|
+
}
|
|
223
|
+
/** Whether a log event already has this error. */
|
|
224
|
+
function isLoggedScheduleError(error) {
|
|
225
|
+
return typeof error === "object" && error !== null && logged.has(error);
|
|
226
|
+
}
|
|
227
|
+
//#endregion
|
|
228
|
+
//#region src/runtime/wait-until.ts
|
|
229
|
+
function createLocalWaitUntil() {
|
|
230
|
+
const pending = /* @__PURE__ */ new Set();
|
|
231
|
+
let error;
|
|
232
|
+
let failed = false;
|
|
233
|
+
return {
|
|
234
|
+
async flush() {
|
|
235
|
+
while (pending.size > 0) await Promise.allSettled(pending);
|
|
236
|
+
if (failed) throw error;
|
|
237
|
+
},
|
|
238
|
+
waitUntil(value) {
|
|
239
|
+
const promise = Promise.resolve(value);
|
|
240
|
+
pending.add(promise);
|
|
241
|
+
promise.then(() => pending.delete(promise), (reason) => {
|
|
242
|
+
pending.delete(promise);
|
|
243
|
+
if (!failed) error = reason;
|
|
244
|
+
failed = true;
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
/** Complete local deferred work while preserving a handler's failure over a deferred failure. */
|
|
250
|
+
async function runWithScheduleWaitUntil(run, hostWaitUntil) {
|
|
251
|
+
if (hostWaitUntil) return await run(hostWaitUntil);
|
|
252
|
+
const local = createLocalWaitUntil();
|
|
253
|
+
let result;
|
|
254
|
+
try {
|
|
255
|
+
result = await run(local.waitUntil);
|
|
256
|
+
} catch (error) {
|
|
257
|
+
await local.flush().catch(logDeferredFailure);
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
await local.flush();
|
|
261
|
+
return result;
|
|
262
|
+
}
|
|
263
|
+
function logDeferredFailure(error) {
|
|
264
|
+
logFailure({
|
|
265
|
+
field: "schedule",
|
|
266
|
+
fields: { op: "wait-until" },
|
|
267
|
+
level: "error",
|
|
268
|
+
message: "Schedule deferred work failed after the handler failed",
|
|
269
|
+
error
|
|
270
|
+
}, () => console.error("[vitehub:schedule] Deferred work failed after the handler failed.", error));
|
|
271
|
+
}
|
|
272
|
+
//#endregion
|
|
273
|
+
//#region ../internal/src/secret.ts
|
|
274
|
+
const secretEncoder = new TextEncoder();
|
|
275
|
+
/**
|
|
276
|
+
* Compares a request value with an expected secret in constant time for the length of `expected`. Returns `false`
|
|
277
|
+
* when either value is missing or empty. It uses no Node API, so it also runs in Worker runtimes.
|
|
278
|
+
*/
|
|
279
|
+
function isViteHubSecretEqual(actual, expected) {
|
|
280
|
+
if (!actual || !expected) return false;
|
|
281
|
+
const left = secretEncoder.encode(actual);
|
|
282
|
+
const right = secretEncoder.encode(expected);
|
|
283
|
+
let difference = left.length ^ right.length;
|
|
284
|
+
for (let index = 0; index < right.length; index += 1) difference |= (left[index] ?? 0) ^ right[index];
|
|
285
|
+
return difference === 0;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Compares the token of a `Bearer` `Authorization` header with an expected secret in constant time. The scheme is
|
|
289
|
+
* case-insensitive. Returns `false` for another scheme or a missing value.
|
|
290
|
+
*/
|
|
291
|
+
function isViteHubBearerSecretEqual(authorization, expected) {
|
|
292
|
+
return isViteHubSecretEqual(/^Bearer\s+(.+)$/i.exec(authorization ?? "")?.[1], expected);
|
|
293
|
+
}
|
|
294
|
+
Object.freeze({ prefix: "sha256=" });
|
|
295
|
+
//#endregion
|
|
296
|
+
//#region src/runtime/static.ts
|
|
297
|
+
const intrinsicErrorIsError = Error.isError;
|
|
298
|
+
const intrinsicNativeErrorIsError = (() => {
|
|
299
|
+
try {
|
|
300
|
+
const process = globalThis.process;
|
|
301
|
+
const getBuiltinModule = process?.getBuiltinModule;
|
|
302
|
+
if (typeof getBuiltinModule !== "function") return void 0;
|
|
303
|
+
const util = getBuiltinModule.call(process, "util");
|
|
304
|
+
return typeof util?.types?.isNativeError === "function" ? util.types.isNativeError : void 0;
|
|
305
|
+
} catch {
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
})();
|
|
309
|
+
function missingScheduleDefinitionError(name) {
|
|
310
|
+
return scheduleErrorDiagnostics.SCHEDULE_R0034({ message: `Missing schedule definition: ${name}` });
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Checks the `Authorization` header of a Vercel Cron request against `CRON_SECRET` in constant time.
|
|
314
|
+
*/
|
|
315
|
+
function isScheduleCronAuthorized(authorization, cronSecret) {
|
|
316
|
+
return isViteHubBearerSecretEqual(authorization, cronSecret);
|
|
317
|
+
}
|
|
318
|
+
function normalizeCron(cron) {
|
|
319
|
+
return cron.trim().split(/\s+/).join(" ");
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Logs a failure that the Process Runtime reports: as an evlog event `{ schedule: { op: "runtime" } }`, else on the
|
|
323
|
+
* console. A failed run that has its run event is not logged again.
|
|
324
|
+
*/
|
|
325
|
+
function logScheduleRuntimeError(error, runtimeError) {
|
|
326
|
+
if (isLoggedScheduleError(error)) return;
|
|
327
|
+
logFailure({
|
|
328
|
+
field: "schedule",
|
|
329
|
+
fields: { op: "runtime" },
|
|
330
|
+
level: "error",
|
|
331
|
+
message: "Schedule runtime failed",
|
|
332
|
+
error: runtimeError
|
|
333
|
+
}, () => console.error("[vitehub:schedule]", runtimeError));
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Notes that a log event has `error`, and returns it to throw on. A thrown value that is not an object cannot be
|
|
337
|
+
* noted, so it becomes the Error that `normalizeScheduleRuntimeError()` makes of it anyway.
|
|
338
|
+
*/
|
|
339
|
+
function markLoggedScheduleError(error) {
|
|
340
|
+
const marked = typeof error === "object" && error !== null ? error : normalizeScheduleRuntimeError(error);
|
|
341
|
+
rememberLoggedScheduleError(marked);
|
|
342
|
+
return marked;
|
|
343
|
+
}
|
|
344
|
+
function normalizeScheduleRuntimeError(error) {
|
|
345
|
+
if (isScheduleRuntimeError(error)) return error;
|
|
346
|
+
let message;
|
|
347
|
+
try {
|
|
348
|
+
message = String(error);
|
|
349
|
+
} catch {
|
|
350
|
+
message = "[unprintable thrown value]";
|
|
351
|
+
}
|
|
352
|
+
try {
|
|
353
|
+
return scheduleErrorDiagnostics.SCHEDULE_R0035({
|
|
354
|
+
cause: error,
|
|
355
|
+
message
|
|
356
|
+
});
|
|
357
|
+
} catch {
|
|
358
|
+
const fallback = new Error(message);
|
|
359
|
+
Object.defineProperty(fallback, "code", {
|
|
360
|
+
value: "SCHEDULE_R0035",
|
|
361
|
+
enumerable: true
|
|
362
|
+
});
|
|
363
|
+
Object.defineProperty(fallback, "cause", { value: error });
|
|
364
|
+
return fallback;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
function isScheduleRuntimeError(error) {
|
|
368
|
+
try {
|
|
369
|
+
if (error instanceof Error) return true;
|
|
370
|
+
} catch {
|
|
371
|
+
return false;
|
|
372
|
+
}
|
|
373
|
+
if (error === null || typeof error !== "object") return false;
|
|
374
|
+
if (typeof intrinsicNativeErrorIsError === "function") return intrinsicNativeErrorIsError(error);
|
|
375
|
+
try {
|
|
376
|
+
return typeof intrinsicErrorIsError === "function" && intrinsicErrorIsError(error) === true;
|
|
377
|
+
} catch {
|
|
378
|
+
return false;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Estimates a wake minute from callback time when the host supplies no scheduled timestamp. This is the newest UTC
|
|
383
|
+
* cron match within one day, or the current minute when none matches. It cannot identify a delayed or retried wake
|
|
384
|
+
* after another cron match; callers must not treat it as the provider's occurrence identity.
|
|
385
|
+
*/
|
|
386
|
+
function scheduledWakeTime(cron, now = /* @__PURE__ */ new Date()) {
|
|
387
|
+
return latestCronMinute(normalizeCron(cron), now);
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Returns `true` when a host wake at `scheduledAt` is an occurrence of the Definition's cron in its `timeZone`. The host
|
|
391
|
+
* runs a wider UTC cron for a time-zoned Schedule, so the runtime skips the wakes that are not local occurrences.
|
|
392
|
+
*/
|
|
393
|
+
function isTimeZoneWakeDue(definition, name, scheduledAt) {
|
|
394
|
+
const minute = /* @__PURE__ */ new Date(Math.floor(scheduledAt.getTime() / 6e4) * 6e4);
|
|
395
|
+
return isScheduleDue({
|
|
396
|
+
cron: definition.cron,
|
|
397
|
+
id: name,
|
|
398
|
+
...definition.timeZone ? { timeZone: definition.timeZone } : {}
|
|
399
|
+
}, minute);
|
|
400
|
+
}
|
|
401
|
+
function createStaticScheduleRun(options) {
|
|
402
|
+
const scheduledAt = validateScheduledAt(options.scheduledAt);
|
|
403
|
+
return {
|
|
404
|
+
cron: options.cron,
|
|
405
|
+
id: `run_${options.name}_${scheduledAt.toISOString()}`,
|
|
406
|
+
idempotencyKey: scheduleIdempotencyKey(options.name, scheduledAt),
|
|
407
|
+
scheduleId: options.name,
|
|
408
|
+
scheduledAt,
|
|
409
|
+
waitUntil: options.waitUntil
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
async function executeStaticSchedule(options) {
|
|
413
|
+
const scheduledAt = validateScheduledAt(options.scheduledAt);
|
|
414
|
+
const execute = () => runInRunScopes(() => runWithScheduleWaitUntil(async (waitUntil) => {
|
|
415
|
+
const run = createStaticScheduleRun({
|
|
416
|
+
...options,
|
|
417
|
+
scheduledAt,
|
|
418
|
+
waitUntil
|
|
419
|
+
});
|
|
420
|
+
try {
|
|
421
|
+
return await options.definition.handler(run);
|
|
422
|
+
} catch (error) {
|
|
423
|
+
await emitRunFailed({
|
|
424
|
+
event: "schedule.failed",
|
|
425
|
+
schedule: run.scheduleId,
|
|
426
|
+
runId: run.id,
|
|
427
|
+
error: toRunFailedError(error),
|
|
428
|
+
failedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
429
|
+
});
|
|
430
|
+
throw error;
|
|
431
|
+
}
|
|
432
|
+
}, options.waitUntil));
|
|
433
|
+
if (options.name === "vitehub/started-schedules") return await execute();
|
|
434
|
+
const run = {
|
|
435
|
+
name: options.name,
|
|
436
|
+
source: "static",
|
|
437
|
+
scheduledAt
|
|
438
|
+
};
|
|
439
|
+
const startedAt = performance.now();
|
|
440
|
+
return await runWithScheduleWaitUntil(async (waitUntil) => {
|
|
441
|
+
try {
|
|
442
|
+
const value = await execute();
|
|
443
|
+
logScheduleRun(run, startedAt, "success", { waitUntil });
|
|
444
|
+
return value;
|
|
445
|
+
} catch (error) {
|
|
446
|
+
if (logScheduleRun(run, startedAt, "failure", {
|
|
447
|
+
error: normalizeScheduleRuntimeError(error),
|
|
448
|
+
waitUntil
|
|
449
|
+
})) options.onRunLogged?.();
|
|
450
|
+
throw error;
|
|
451
|
+
}
|
|
452
|
+
}, options.waitUntil);
|
|
453
|
+
}
|
|
454
|
+
function isHostCronTrigger(hostCron, trigger) {
|
|
455
|
+
try {
|
|
456
|
+
return cronWithWeekdayNames(hostCron) === trigger;
|
|
457
|
+
} catch {
|
|
458
|
+
return false;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
async function executeMatchingStaticSchedules(options) {
|
|
462
|
+
return await matchStaticSchedules(options);
|
|
463
|
+
}
|
|
464
|
+
async function matchStaticSchedules(options, matchesTrigger) {
|
|
465
|
+
if (typeof options.cron !== "string" || !options.cron.trim()) throw createScheduleError("SCHEDULE_INVALID_CRON", { details: invalidScheduleValueDetails("cron", options.cron) });
|
|
466
|
+
const cron = normalizeCron(options.cron);
|
|
467
|
+
const scheduledAt = validateScheduledAt(options.scheduledAt);
|
|
468
|
+
const runs = [];
|
|
469
|
+
for (const [name, load] of Object.entries(options.registry)) {
|
|
470
|
+
const definition = unwrapScheduleDefinition(await load());
|
|
471
|
+
if (!definition) continue;
|
|
472
|
+
const override = options.cronOverrides && Object.hasOwn(options.cronOverrides, name) ? options.cronOverrides[name] : void 0;
|
|
473
|
+
const timeZoneCron = override === void 0 && options.timeZoneCrons && Object.hasOwn(options.timeZoneCrons, name) ? options.timeZoneCrons[name] : void 0;
|
|
474
|
+
const hostCron = normalizeCron(override ?? timeZoneCron ?? definition.cron);
|
|
475
|
+
if (!(matchesTrigger ? matchesTrigger(name, hostCron, cron, override !== void 0) : hostCron === cron)) continue;
|
|
476
|
+
if (timeZoneCron !== void 0 && !isTimeZoneWakeDue(definition, name, scheduledAt)) continue;
|
|
477
|
+
let logged = false;
|
|
478
|
+
const run = executeStaticSchedule({
|
|
479
|
+
cron: matchesTrigger ? hostCron : options.cron,
|
|
480
|
+
definition,
|
|
481
|
+
name,
|
|
482
|
+
onRunLogged: () => {
|
|
483
|
+
logged = true;
|
|
484
|
+
},
|
|
485
|
+
scheduledAt,
|
|
486
|
+
waitUntil: options.waitUntil
|
|
487
|
+
});
|
|
488
|
+
runs.push({
|
|
489
|
+
logged: () => logged,
|
|
490
|
+
name,
|
|
491
|
+
run
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
const results = await Promise.allSettled(runs.map(({ run }) => run));
|
|
495
|
+
const failures = [];
|
|
496
|
+
results.forEach((result, index) => {
|
|
497
|
+
if (result.status === "fulfilled") return;
|
|
498
|
+
failures.push(result.reason);
|
|
499
|
+
if (!runs[index].logged()) console.error(`[vitehub:schedule] Schedule "${runs[index].name}" failed (cron "${options.cron}").`, normalizeRuntimeDiagnosticError(result.reason, { includeStack: true }));
|
|
500
|
+
});
|
|
501
|
+
if (failures.length === 1) throw failures[0];
|
|
502
|
+
if (failures.length) throw new AggregateError(failures, `[vitehub:schedule] ${failures.length} schedules failed for cron "${options.cron}".`);
|
|
503
|
+
return results.map((result) => result.status === "fulfilled" ? result.value : void 0);
|
|
504
|
+
}
|
|
505
|
+
async function executeCloudflareStaticSchedules(event, options) {
|
|
506
|
+
const scheduled = readCloudflareScheduledEvent(event);
|
|
507
|
+
return await runWithCloudflareServerEnv(event, async (waitUntil) => {
|
|
508
|
+
return await matchStaticSchedules({
|
|
509
|
+
cron: scheduled.cron,
|
|
510
|
+
cronOverrides: options.cronOverrides,
|
|
511
|
+
registry: options.registry,
|
|
512
|
+
scheduledAt: scheduled.scheduledAt,
|
|
513
|
+
timeZoneCrons: options.timeZoneCrons,
|
|
514
|
+
waitUntil
|
|
515
|
+
}, (name, hostCron, trigger, hasOverride) => {
|
|
516
|
+
const registered = options.triggerCrons && Object.hasOwn(options.triggerCrons, name) ? options.triggerCrons[name] : void 0;
|
|
517
|
+
if (registered !== void 0) return normalizeCron(registered) === trigger;
|
|
518
|
+
return hasOverride ? hostCron === trigger : isHostCronTrigger(hostCron, trigger);
|
|
519
|
+
});
|
|
520
|
+
}, options.waitUntil ?? readCloudflareWaitUntil(event));
|
|
521
|
+
}
|
|
522
|
+
function readCloudflareScheduledEvent(event) {
|
|
523
|
+
const cron = event.controller?.cron ?? event.cron;
|
|
524
|
+
if (typeof cron !== "string" || !cron.trim()) throw scheduleErrorDiagnostics.SCHEDULE_R0027({ message: "[vitehub:schedule] Cloudflare scheduled event is missing a cron string." });
|
|
525
|
+
const scheduledTime = event.controller?.scheduledTime ?? event.scheduledTime;
|
|
526
|
+
const scheduledAt = isScheduleDate(scheduledTime) ? new Date(Date.prototype.getTime.call(scheduledTime)) : scheduledTime === void 0 ? /* @__PURE__ */ new Date() : new Date(scheduledTime);
|
|
527
|
+
if (Number.isNaN(scheduledAt.getTime())) throw scheduleErrorDiagnostics.SCHEDULE_R0028({ message: "[vitehub:schedule] Cloudflare scheduled event has an invalid scheduledTime." });
|
|
528
|
+
return {
|
|
529
|
+
cron,
|
|
530
|
+
scheduledAt
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
async function runWithCloudflareServerEnv(event, callback, hostWaitUntil) {
|
|
534
|
+
const globals = globalThis;
|
|
535
|
+
const hadGlobalEnv = Object.prototype.hasOwnProperty.call(globals, "__env__");
|
|
536
|
+
const previousGlobalEnv = globals.__env__;
|
|
537
|
+
const env = readCloudflareEventEnv(event);
|
|
538
|
+
if (env) globals.__env__ = env;
|
|
539
|
+
const pending = /* @__PURE__ */ new Set();
|
|
540
|
+
const waitUntil = hostWaitUntil ? (value) => {
|
|
541
|
+
const promise = Promise.resolve(value);
|
|
542
|
+
pending.add(promise);
|
|
543
|
+
promise.then(() => pending.delete(promise), () => pending.delete(promise));
|
|
544
|
+
hostWaitUntil(promise);
|
|
545
|
+
} : void 0;
|
|
546
|
+
try {
|
|
547
|
+
return await callback(waitUntil);
|
|
548
|
+
} finally {
|
|
549
|
+
if (pending.size === 0) restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv);
|
|
550
|
+
else hostWaitUntil(flushPendingWork(pending).finally(() => {
|
|
551
|
+
restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv);
|
|
552
|
+
}));
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
async function flushPendingWork(pending) {
|
|
556
|
+
while (pending.size > 0) await Promise.allSettled(pending);
|
|
557
|
+
}
|
|
558
|
+
function restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv) {
|
|
559
|
+
if (hadGlobalEnv) globals.__env__ = previousGlobalEnv;
|
|
560
|
+
else delete globals.__env__;
|
|
561
|
+
}
|
|
562
|
+
function isCallable(value) {
|
|
563
|
+
return typeof value === "function" || typeof value === "undefined" && value !== void 0;
|
|
564
|
+
}
|
|
565
|
+
function readCloudflareWaitUntil(event) {
|
|
566
|
+
const context = isRecordOrFunction(event.context) ? event.context : void 0;
|
|
567
|
+
const cloudflareContext = isRecordOrFunction(context?.cloudflare) ? context.cloudflare : void 0;
|
|
568
|
+
const platformContext = isRecordOrFunction(context?._platform) ? context._platform : void 0;
|
|
569
|
+
const platformCloudflareContext = isRecordOrFunction(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
|
|
570
|
+
const request = isRecordOrFunction(event.req) ? event.req : void 0;
|
|
571
|
+
const runtime = isRecordOrFunction(request?.runtime) ? request.runtime : void 0;
|
|
572
|
+
const runtimeCloudflare = isRecordOrFunction(runtime?.cloudflare) ? runtime.cloudflare : void 0;
|
|
573
|
+
const owners = [
|
|
574
|
+
event,
|
|
575
|
+
context,
|
|
576
|
+
cloudflareContext,
|
|
577
|
+
isRecordOrFunction(cloudflareContext?.context) ? cloudflareContext.context : void 0,
|
|
578
|
+
platformCloudflareContext,
|
|
579
|
+
isRecordOrFunction(platformCloudflareContext?.context) ? platformCloudflareContext.context : void 0,
|
|
580
|
+
request,
|
|
581
|
+
runtimeCloudflare,
|
|
582
|
+
isRecordOrFunction(runtimeCloudflare?.context) ? runtimeCloudflare.context : void 0
|
|
583
|
+
];
|
|
584
|
+
for (const owner of owners) {
|
|
585
|
+
const waitUntil = owner?.waitUntil;
|
|
586
|
+
if (isCallable(waitUntil)) return (promise) => Reflect.apply(waitUntil, owner, [promise]);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
function readCloudflareEventEnv(event) {
|
|
590
|
+
if (isRecordOrFunction(event.env)) return event.env;
|
|
591
|
+
const context = isRecordOrFunction(event.context) ? event.context : void 0;
|
|
592
|
+
const cloudflareContext = isRecordOrFunction(context?.cloudflare) ? context.cloudflare : void 0;
|
|
593
|
+
if (isRecordOrFunction(cloudflareContext?.env)) return cloudflareContext.env;
|
|
594
|
+
const platformContext = isRecordOrFunction(context?._platform) ? context._platform : void 0;
|
|
595
|
+
const platformCloudflareContext = isRecordOrFunction(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
|
|
596
|
+
if (isRecordOrFunction(platformCloudflareContext?.env)) return platformCloudflareContext.env;
|
|
597
|
+
const request = isRecordOrFunction(event.req) ? event.req : void 0;
|
|
598
|
+
const runtime = isRecordOrFunction(request?.runtime) ? request.runtime : void 0;
|
|
599
|
+
const runtimeCloudflare = isRecordOrFunction(runtime?.cloudflare) ? runtime.cloudflare : void 0;
|
|
600
|
+
return isRecordOrFunction(runtimeCloudflare?.env) ? runtimeCloudflare.env : void 0;
|
|
601
|
+
}
|
|
602
|
+
function isStaticScheduleDefinition(value) {
|
|
603
|
+
return isRecordOrFunction(value) && Object.hasOwn(value, "cron") && typeof value.cron === "string" && Object.hasOwn(value, "handler") && typeof value.handler === "function";
|
|
604
|
+
}
|
|
605
|
+
function unwrapScheduleDefinition(loaded) {
|
|
606
|
+
const candidate = isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default") ? loaded.default : loaded;
|
|
607
|
+
return isStaticScheduleDefinition(candidate) ? candidate : void 0;
|
|
608
|
+
}
|
|
609
|
+
//#endregion
|
|
610
|
+
export { createScheduleError as S, errorCode as _, isScheduleCronAuthorized as a, scheduleIdempotencyKey as b, markLoggedScheduleError as c, normalizeScheduleRuntimeError as d, scheduledWakeTime as f, emitLogEvent as g, logScheduleRun as h, executeStaticSchedule as i, missingScheduleDefinitionError as l, runWithScheduleWaitUntil as m, executeCloudflareStaticSchedules as n, isTimeZoneWakeDue as o, unwrapScheduleDefinition as p, executeMatchingStaticSchedules as r, logScheduleRuntimeError as s, createStaticScheduleRun as t, normalizeCron as u, logFailure as v, validateScheduledAt as x, parseScheduledAt as y };
|