@vite-hub/schedule 0.0.0 → 0.0.1

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.
@@ -0,0 +1,1767 @@
1
+ import { a as hookNitroRuntimeRegistryRefresh, c as ensureGeneratedDir, i as createRuntimeRegistryContents, n as applyNitroRuntimeAliases, o as writeFileIfChanged, r as createNitroRuntimeFilePath, s as createImportPath, t as discoverScheduleDefinitions } from "./discovery-Di9MD-SN.js";
2
+ import fs, { lstatSync, readFileSync, realpathSync, statSync } from "node:fs";
3
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { URL as URL$1, fileURLToPath, pathToFileURL } from "node:url";
5
+ import path, { basename, dirname, isAbsolute, resolve } from "node:path";
6
+ import assert from "node:assert";
7
+ import process$1 from "node:process";
8
+ import v8 from "node:v8";
9
+ import { format, inspect } from "node:util";
10
+ import { build } from "esbuild";
11
+ //#region ../../node_modules/.pnpm/exsolve@1.0.8/node_modules/exsolve/dist/index.mjs
12
+ const nodeBuiltins = [
13
+ "_http_agent",
14
+ "_http_client",
15
+ "_http_common",
16
+ "_http_incoming",
17
+ "_http_outgoing",
18
+ "_http_server",
19
+ "_stream_duplex",
20
+ "_stream_passthrough",
21
+ "_stream_readable",
22
+ "_stream_transform",
23
+ "_stream_wrap",
24
+ "_stream_writable",
25
+ "_tls_common",
26
+ "_tls_wrap",
27
+ "assert",
28
+ "assert/strict",
29
+ "async_hooks",
30
+ "buffer",
31
+ "child_process",
32
+ "cluster",
33
+ "console",
34
+ "constants",
35
+ "crypto",
36
+ "dgram",
37
+ "diagnostics_channel",
38
+ "dns",
39
+ "dns/promises",
40
+ "domain",
41
+ "events",
42
+ "fs",
43
+ "fs/promises",
44
+ "http",
45
+ "http2",
46
+ "https",
47
+ "inspector",
48
+ "inspector/promises",
49
+ "module",
50
+ "net",
51
+ "os",
52
+ "path",
53
+ "path/posix",
54
+ "path/win32",
55
+ "perf_hooks",
56
+ "process",
57
+ "punycode",
58
+ "querystring",
59
+ "readline",
60
+ "readline/promises",
61
+ "repl",
62
+ "stream",
63
+ "stream/consumers",
64
+ "stream/promises",
65
+ "stream/web",
66
+ "string_decoder",
67
+ "sys",
68
+ "timers",
69
+ "timers/promises",
70
+ "tls",
71
+ "trace_events",
72
+ "tty",
73
+ "url",
74
+ "util",
75
+ "util/types",
76
+ "v8",
77
+ "vm",
78
+ "wasi",
79
+ "worker_threads",
80
+ "zlib"
81
+ ];
82
+ const own$1 = {}.hasOwnProperty;
83
+ const classRegExp = /^([A-Z][a-z\d]*)+$/;
84
+ const kTypes = new Set([
85
+ "string",
86
+ "function",
87
+ "number",
88
+ "object",
89
+ "Function",
90
+ "Object",
91
+ "boolean",
92
+ "bigint",
93
+ "symbol"
94
+ ]);
95
+ const messages = /* @__PURE__ */ new Map();
96
+ const nodeInternalPrefix = "__node_internal_";
97
+ let userStackTraceLimit;
98
+ /**
99
+ * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
100
+ * We cannot use Intl.ListFormat because it's not available in
101
+ * --without-intl builds.
102
+ *
103
+ * @param {Array<string>} array
104
+ * An array of strings.
105
+ * @param {string} [type]
106
+ * The list type to be inserted before the last element.
107
+ * @returns {string}
108
+ */
109
+ function formatList(array, type = "and") {
110
+ return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array.at(-1)}`;
111
+ }
112
+ /**
113
+ * Utility function for registering the error codes.
114
+ */
115
+ function createError(sym, value, constructor) {
116
+ messages.set(sym, value);
117
+ return makeNodeErrorWithCode(constructor, sym);
118
+ }
119
+ function makeNodeErrorWithCode(Base, key) {
120
+ return function NodeError(...parameters) {
121
+ const limit = Error.stackTraceLimit;
122
+ if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
123
+ const error = new Base();
124
+ if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
125
+ const message = getMessage(key, parameters, error);
126
+ Object.defineProperties(error, {
127
+ message: {
128
+ value: message,
129
+ enumerable: false,
130
+ writable: true,
131
+ configurable: true
132
+ },
133
+ toString: {
134
+ value() {
135
+ return `${this.name} [${key}]: ${this.message}`;
136
+ },
137
+ enumerable: false,
138
+ writable: true,
139
+ configurable: true
140
+ }
141
+ });
142
+ captureLargerStackTrace(error);
143
+ error.code = key;
144
+ return error;
145
+ };
146
+ }
147
+ function isErrorStackTraceLimitWritable() {
148
+ try {
149
+ if (v8.startupSnapshot.isBuildingSnapshot()) return false;
150
+ } catch {}
151
+ const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
152
+ if (desc === void 0) return Object.isExtensible(Error);
153
+ return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0;
154
+ }
155
+ /**
156
+ * This function removes unnecessary frames from Node.js core errors.
157
+ */
158
+ function hideStackFrames(wrappedFunction) {
159
+ const hidden = nodeInternalPrefix + wrappedFunction.name;
160
+ Object.defineProperty(wrappedFunction, "name", { value: hidden });
161
+ return wrappedFunction;
162
+ }
163
+ const captureLargerStackTrace = hideStackFrames(function(error) {
164
+ const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
165
+ if (stackTraceLimitIsWritable) {
166
+ userStackTraceLimit = Error.stackTraceLimit;
167
+ Error.stackTraceLimit = Number.POSITIVE_INFINITY;
168
+ }
169
+ Error.captureStackTrace(error);
170
+ if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
171
+ return error;
172
+ });
173
+ function getMessage(key, parameters, self) {
174
+ const message = messages.get(key);
175
+ assert.ok(message !== void 0, "expected `message` to be found");
176
+ if (typeof message === "function") {
177
+ assert.ok(message.length <= parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`);
178
+ return Reflect.apply(message, self, parameters);
179
+ }
180
+ const regex = /%[dfijoOs]/g;
181
+ let expectedLength = 0;
182
+ while (regex.exec(message) !== null) expectedLength++;
183
+ assert.ok(expectedLength === parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`);
184
+ if (parameters.length === 0) return message;
185
+ parameters.unshift(message);
186
+ return Reflect.apply(format, null, parameters);
187
+ }
188
+ /**
189
+ * Determine the specific type of a value for type-mismatch errors.
190
+ */
191
+ function determineSpecificType(value) {
192
+ if (value === null || value === void 0) return String(value);
193
+ if (typeof value === "function" && value.name) return `function ${value.name}`;
194
+ if (typeof value === "object") {
195
+ if (value.constructor && value.constructor.name) return `an instance of ${value.constructor.name}`;
196
+ return `${inspect(value, { depth: -1 })}`;
197
+ }
198
+ let inspected = inspect(value, { colors: false });
199
+ if (inspected.length > 28) inspected = `${inspected.slice(0, 25)}...`;
200
+ return `type ${typeof value} (${inspected})`;
201
+ }
202
+ createError("ERR_INVALID_ARG_TYPE", (name, expected, actual) => {
203
+ assert.ok(typeof name === "string", "'name' must be a string");
204
+ if (!Array.isArray(expected)) expected = [expected];
205
+ let message = "The ";
206
+ if (name.endsWith(" argument")) message += `${name} `;
207
+ else {
208
+ const type = name.includes(".") ? "property" : "argument";
209
+ message += `"${name}" ${type} `;
210
+ }
211
+ message += "must be ";
212
+ const types = [];
213
+ const instances = [];
214
+ const other = [];
215
+ for (const value of expected) {
216
+ assert.ok(typeof value === "string", "All expected entries have to be of type string");
217
+ if (kTypes.has(value)) types.push(value.toLowerCase());
218
+ else if (classRegExp.exec(value) === null) {
219
+ assert.ok(value !== "object", "The value \"object\" should be written as \"Object\"");
220
+ other.push(value);
221
+ } else instances.push(value);
222
+ }
223
+ if (instances.length > 0) {
224
+ const pos = types.indexOf("object");
225
+ if (pos !== -1) {
226
+ types.slice(pos, 1);
227
+ instances.push("Object");
228
+ }
229
+ }
230
+ if (types.length > 0) {
231
+ message += `${types.length > 1 ? "one of type" : "of type"} ${formatList(types, "or")}`;
232
+ if (instances.length > 0 || other.length > 0) message += " or ";
233
+ }
234
+ if (instances.length > 0) {
235
+ message += `an instance of ${formatList(instances, "or")}`;
236
+ if (other.length > 0) message += " or ";
237
+ }
238
+ if (other.length > 0) if (other.length > 1) message += `one of ${formatList(other, "or")}`;
239
+ else {
240
+ if (other[0]?.toLowerCase() !== other[0]) message += "an ";
241
+ message += `${other[0]}`;
242
+ }
243
+ message += `. Received ${determineSpecificType(actual)}`;
244
+ return message;
245
+ }, TypeError);
246
+ const ERR_INVALID_MODULE_SPECIFIER = createError(
247
+ "ERR_INVALID_MODULE_SPECIFIER",
248
+ /**
249
+ * @param {string} request
250
+ * @param {string} reason
251
+ * @param {string} [base]
252
+ */
253
+ (request, reason, base) => {
254
+ return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`;
255
+ },
256
+ TypeError
257
+ );
258
+ const ERR_INVALID_PACKAGE_CONFIG = createError("ERR_INVALID_PACKAGE_CONFIG", (path$1, base, message) => {
259
+ return `Invalid package config ${path$1}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
260
+ }, Error);
261
+ const ERR_INVALID_PACKAGE_TARGET = createError("ERR_INVALID_PACKAGE_TARGET", (packagePath, key, target, isImport = false, base) => {
262
+ const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
263
+ if (key === ".") {
264
+ assert.ok(isImport === false);
265
+ return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`;
266
+ }
267
+ return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`;
268
+ }, Error);
269
+ const ERR_MODULE_NOT_FOUND = createError("ERR_MODULE_NOT_FOUND", (path$1, base, exactUrl = false) => {
270
+ return `Cannot find ${exactUrl ? "module" : "package"} '${path$1}' imported from ${base}`;
271
+ }, Error);
272
+ createError("ERR_NETWORK_IMPORT_DISALLOWED", "import of '%s' by %s is not supported: %s", Error);
273
+ const ERR_PACKAGE_IMPORT_NOT_DEFINED = createError("ERR_PACKAGE_IMPORT_NOT_DEFINED", (specifier, packagePath, base) => {
274
+ return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath || ""}package.json` : ""} imported from ${base}`;
275
+ }, TypeError);
276
+ const ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
277
+ "ERR_PACKAGE_PATH_NOT_EXPORTED",
278
+ /**
279
+ * @param {string} packagePath
280
+ * @param {string} subpath
281
+ * @param {string} [base]
282
+ */
283
+ (packagePath, subpath, base) => {
284
+ if (subpath === ".") return `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
285
+ return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
286
+ },
287
+ Error
288
+ );
289
+ const ERR_UNSUPPORTED_DIR_IMPORT = createError("ERR_UNSUPPORTED_DIR_IMPORT", "Directory import '%s' is not supported resolving ES modules imported from %s", Error);
290
+ const ERR_UNSUPPORTED_RESOLVE_REQUEST = createError("ERR_UNSUPPORTED_RESOLVE_REQUEST", "Failed to resolve module specifier \"%s\" from \"%s\": Invalid relative URL or base scheme is not hierarchical.", TypeError);
291
+ const ERR_UNKNOWN_FILE_EXTENSION = createError("ERR_UNKNOWN_FILE_EXTENSION", (extension, path$1) => {
292
+ return `Unknown file extension "${extension}" for ${path$1}`;
293
+ }, TypeError);
294
+ createError("ERR_INVALID_ARG_VALUE", (name, value, reason = "is invalid") => {
295
+ let inspected = inspect(value);
296
+ if (inspected.length > 128) inspected = `${inspected.slice(0, 128)}...`;
297
+ return `The ${name.includes(".") ? "property" : "argument"} '${name}' ${reason}. Received ${inspected}`;
298
+ }, TypeError);
299
+ const hasOwnProperty$1 = {}.hasOwnProperty;
300
+ const cache = /* @__PURE__ */ new Map();
301
+ function read(jsonPath, { base, specifier }) {
302
+ const existing = cache.get(jsonPath);
303
+ if (existing) return existing;
304
+ let string;
305
+ try {
306
+ string = fs.readFileSync(path.toNamespacedPath(jsonPath), "utf8");
307
+ } catch (error) {
308
+ const exception = error;
309
+ if (exception.code !== "ENOENT") throw exception;
310
+ }
311
+ const result = {
312
+ exists: false,
313
+ pjsonPath: jsonPath,
314
+ main: void 0,
315
+ name: void 0,
316
+ type: "none",
317
+ exports: void 0,
318
+ imports: void 0
319
+ };
320
+ if (string !== void 0) {
321
+ let parsed;
322
+ try {
323
+ parsed = JSON.parse(string);
324
+ } catch (error_) {
325
+ const error = new ERR_INVALID_PACKAGE_CONFIG(jsonPath, (base ? `"${specifier}" from ` : "") + fileURLToPath(base || specifier), error_.message);
326
+ error.cause = error_;
327
+ throw error;
328
+ }
329
+ result.exists = true;
330
+ if (hasOwnProperty$1.call(parsed, "name") && typeof parsed.name === "string") result.name = parsed.name;
331
+ if (hasOwnProperty$1.call(parsed, "main") && typeof parsed.main === "string") result.main = parsed.main;
332
+ if (hasOwnProperty$1.call(parsed, "exports")) result.exports = parsed.exports;
333
+ if (hasOwnProperty$1.call(parsed, "imports")) result.imports = parsed.imports;
334
+ if (hasOwnProperty$1.call(parsed, "type") && (parsed.type === "commonjs" || parsed.type === "module")) result.type = parsed.type;
335
+ }
336
+ cache.set(jsonPath, result);
337
+ return result;
338
+ }
339
+ function getPackageScopeConfig(resolved) {
340
+ let packageJSONUrl = new URL("package.json", resolved);
341
+ while (true) {
342
+ if (packageJSONUrl.pathname.endsWith("node_modules/package.json")) break;
343
+ const packageConfig = read(fileURLToPath(packageJSONUrl), { specifier: resolved });
344
+ if (packageConfig.exists) return packageConfig;
345
+ const lastPackageJSONUrl = packageJSONUrl;
346
+ packageJSONUrl = new URL("../package.json", packageJSONUrl);
347
+ if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) break;
348
+ }
349
+ return {
350
+ pjsonPath: fileURLToPath(packageJSONUrl),
351
+ exists: false,
352
+ type: "none"
353
+ };
354
+ }
355
+ const hasOwnProperty = {}.hasOwnProperty;
356
+ const extensionFormatMap = {
357
+ __proto__: null,
358
+ ".json": "json",
359
+ ".cjs": "commonjs",
360
+ ".cts": "commonjs",
361
+ ".js": "module",
362
+ ".ts": "module",
363
+ ".mts": "module",
364
+ ".mjs": "module"
365
+ };
366
+ const protocolHandlers = {
367
+ __proto__: null,
368
+ "data:": getDataProtocolModuleFormat,
369
+ "file:": getFileProtocolModuleFormat,
370
+ "node:": () => "builtin"
371
+ };
372
+ function mimeToFormat(mime) {
373
+ if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)) return "module";
374
+ if (mime === "application/json") return "json";
375
+ return null;
376
+ }
377
+ function getDataProtocolModuleFormat(parsed) {
378
+ const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(parsed.pathname) || [
379
+ null,
380
+ null,
381
+ null
382
+ ];
383
+ return mimeToFormat(mime);
384
+ }
385
+ /**
386
+ * Returns the file extension from a URL.
387
+ *
388
+ * Should give similar result to
389
+ * `require('node:path').extname(require('node:url').fileURLToPath(url))`
390
+ * when used with a `file:` URL.
391
+ *
392
+ */
393
+ function extname(url) {
394
+ const pathname = url.pathname;
395
+ let index = pathname.length;
396
+ while (index--) {
397
+ const code = pathname.codePointAt(index);
398
+ if (code === 47) return "";
399
+ if (code === 46) return pathname.codePointAt(index - 1) === 47 ? "" : pathname.slice(index);
400
+ }
401
+ return "";
402
+ }
403
+ function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
404
+ const ext = extname(url);
405
+ if (ext === ".js") {
406
+ const { type: packageType } = getPackageScopeConfig(url);
407
+ if (packageType !== "none") return packageType;
408
+ return "commonjs";
409
+ }
410
+ if (ext === "") {
411
+ const { type: packageType } = getPackageScopeConfig(url);
412
+ if (packageType === "none" || packageType === "commonjs") return "commonjs";
413
+ return "module";
414
+ }
415
+ const format$1 = extensionFormatMap[ext];
416
+ if (format$1) return format$1;
417
+ if (ignoreErrors) return;
418
+ throw new ERR_UNKNOWN_FILE_EXTENSION(ext, fileURLToPath(url));
419
+ }
420
+ function defaultGetFormatWithoutErrors(url, context) {
421
+ const protocol = url.protocol;
422
+ if (!hasOwnProperty.call(protocolHandlers, protocol)) return null;
423
+ return protocolHandlers[protocol](url, context, true) || null;
424
+ }
425
+ const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
426
+ const own = {}.hasOwnProperty;
427
+ const invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
428
+ const deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
429
+ const invalidPackageNameRegEx = /^\.|%|\\/;
430
+ const patternRegEx = /\*/g;
431
+ const encodedSeparatorRegEx = /%2f|%5c/i;
432
+ const emittedPackageWarnings = /* @__PURE__ */ new Set();
433
+ const doubleSlashRegEx = /[/\\]{2}/;
434
+ function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
435
+ if (process$1.noDeprecation) return;
436
+ const pjsonPath = fileURLToPath(packageJsonUrl);
437
+ const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
438
+ process$1.emitWarning(`Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath(base)}` : ""}.`, "DeprecationWarning", "DEP0166");
439
+ }
440
+ function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
441
+ if (process$1.noDeprecation) return;
442
+ if (defaultGetFormatWithoutErrors(url, { parentURL: base.href }) !== "module") return;
443
+ const urlPath = fileURLToPath(url.href);
444
+ const packagePath = fileURLToPath(new URL$1(".", packageJsonUrl));
445
+ const basePath = fileURLToPath(base);
446
+ if (!main) process$1.emitWarning(`No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(packagePath.length)}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`, "DeprecationWarning", "DEP0151");
447
+ else if (path.resolve(packagePath, main) !== urlPath) process$1.emitWarning(`Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(packagePath.length)}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is deprecated for ES modules.`, "DeprecationWarning", "DEP0151");
448
+ }
449
+ function tryStatSync(path$1) {
450
+ try {
451
+ return statSync(path$1);
452
+ } catch {}
453
+ }
454
+ /**
455
+ * Legacy CommonJS main resolution:
456
+ * 1. let M = pkg_url + (json main field)
457
+ * 2. TRY(M, M.js, M.json, M.node)
458
+ * 3. TRY(M/index.js, M/index.json, M/index.node)
459
+ * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
460
+ * 5. NOT_FOUND
461
+ */
462
+ function fileExists(url) {
463
+ const stats = statSync(url, { throwIfNoEntry: false });
464
+ const isFile = stats ? stats.isFile() : void 0;
465
+ return isFile === null || isFile === void 0 ? false : isFile;
466
+ }
467
+ function legacyMainResolve(packageJsonUrl, packageConfig, base) {
468
+ let guess;
469
+ if (packageConfig.main !== void 0) {
470
+ guess = new URL$1(packageConfig.main, packageJsonUrl);
471
+ if (fileExists(guess)) return guess;
472
+ const tries$1 = [
473
+ `./${packageConfig.main}.js`,
474
+ `./${packageConfig.main}.json`,
475
+ `./${packageConfig.main}.node`,
476
+ `./${packageConfig.main}/index.js`,
477
+ `./${packageConfig.main}/index.json`,
478
+ `./${packageConfig.main}/index.node`
479
+ ];
480
+ let i$1 = -1;
481
+ while (++i$1 < tries$1.length) {
482
+ guess = new URL$1(tries$1[i$1], packageJsonUrl);
483
+ if (fileExists(guess)) break;
484
+ guess = void 0;
485
+ }
486
+ if (guess) {
487
+ emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
488
+ return guess;
489
+ }
490
+ }
491
+ const tries = [
492
+ "./index.js",
493
+ "./index.json",
494
+ "./index.node"
495
+ ];
496
+ let i = -1;
497
+ while (++i < tries.length) {
498
+ guess = new URL$1(tries[i], packageJsonUrl);
499
+ if (fileExists(guess)) break;
500
+ guess = void 0;
501
+ }
502
+ if (guess) {
503
+ emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
504
+ return guess;
505
+ }
506
+ throw new ERR_MODULE_NOT_FOUND(fileURLToPath(new URL$1(".", packageJsonUrl)), fileURLToPath(base));
507
+ }
508
+ function finalizeResolution(resolved, base, preserveSymlinks) {
509
+ if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) throw new ERR_INVALID_MODULE_SPECIFIER(resolved.pathname, String.raw`must not include encoded "/" or "\" characters`, fileURLToPath(base));
510
+ let filePath;
511
+ try {
512
+ filePath = fileURLToPath(resolved);
513
+ } catch (error) {
514
+ Object.defineProperty(error, "input", { value: String(resolved) });
515
+ Object.defineProperty(error, "module", { value: String(base) });
516
+ throw error;
517
+ }
518
+ const stats = tryStatSync(filePath.endsWith("/") ? filePath.slice(-1) : filePath);
519
+ if (stats && stats.isDirectory()) {
520
+ const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath(base));
521
+ error.url = String(resolved);
522
+ throw error;
523
+ }
524
+ if (!stats || !stats.isFile()) {
525
+ const error = new ERR_MODULE_NOT_FOUND(filePath || resolved.pathname, base && fileURLToPath(base), true);
526
+ error.url = String(resolved);
527
+ throw error;
528
+ }
529
+ if (!preserveSymlinks) {
530
+ const real = realpathSync(filePath);
531
+ const { search, hash } = resolved;
532
+ resolved = pathToFileURL(real + (filePath.endsWith(path.sep) ? "/" : ""));
533
+ resolved.search = search;
534
+ resolved.hash = hash;
535
+ }
536
+ return resolved;
537
+ }
538
+ function importNotDefined(specifier, packageJsonUrl, base) {
539
+ return new ERR_PACKAGE_IMPORT_NOT_DEFINED(specifier, packageJsonUrl && fileURLToPath(new URL$1(".", packageJsonUrl)), fileURLToPath(base));
540
+ }
541
+ function exportsNotFound(subpath, packageJsonUrl, base) {
542
+ return new ERR_PACKAGE_PATH_NOT_EXPORTED(fileURLToPath(new URL$1(".", packageJsonUrl)), subpath, base && fileURLToPath(base));
543
+ }
544
+ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
545
+ throw new ERR_INVALID_MODULE_SPECIFIER(request, `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath(packageJsonUrl)}`, base && fileURLToPath(base));
546
+ }
547
+ function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
548
+ target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
549
+ return new ERR_INVALID_PACKAGE_TARGET(fileURLToPath(new URL$1(".", packageJsonUrl)), subpath, target, internal, base && fileURLToPath(base));
550
+ }
551
+ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
552
+ if (subpath !== "" && !pattern && target.at(-1) !== "/") throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
553
+ if (!target.startsWith("./")) {
554
+ if (internal && !target.startsWith("../") && !target.startsWith("/")) {
555
+ let isURL = false;
556
+ try {
557
+ new URL$1(target);
558
+ isURL = true;
559
+ } catch {}
560
+ if (!isURL) return packageResolve(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target + subpath, packageJsonUrl, conditions);
561
+ }
562
+ throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
563
+ }
564
+ if (invalidSegmentRegEx.exec(target.slice(2)) !== null) if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
565
+ if (!isPathMap) {
566
+ const request = pattern ? match.replace("*", () => subpath) : match + subpath;
567
+ emitInvalidSegmentDeprecation(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target, request, match, packageJsonUrl, internal, base, true);
568
+ }
569
+ } else throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
570
+ const resolved = new URL$1(target, packageJsonUrl);
571
+ const resolvedPath = resolved.pathname;
572
+ const packagePath = new URL$1(".", packageJsonUrl).pathname;
573
+ if (!resolvedPath.startsWith(packagePath)) throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
574
+ if (subpath === "") return resolved;
575
+ if (invalidSegmentRegEx.exec(subpath) !== null) {
576
+ const request = pattern ? match.replace("*", () => subpath) : match + subpath;
577
+ if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
578
+ if (!isPathMap) emitInvalidSegmentDeprecation(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target, request, match, packageJsonUrl, internal, base, false);
579
+ } else throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
580
+ }
581
+ if (pattern) return new URL$1(RegExpPrototypeSymbolReplace.call(patternRegEx, resolved.href, () => subpath));
582
+ return new URL$1(subpath, resolved);
583
+ }
584
+ function isArrayIndex(key) {
585
+ const keyNumber = Number(key);
586
+ if (`${keyNumber}` !== key) return false;
587
+ return keyNumber >= 0 && keyNumber < 4294967295;
588
+ }
589
+ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
590
+ if (typeof target === "string") return resolvePackageTargetString(target, subpath, packageSubpath, packageJsonUrl, base, pattern, internal, isPathMap, conditions);
591
+ if (Array.isArray(target)) {
592
+ const targetList = target;
593
+ if (targetList.length === 0) return null;
594
+ let lastException;
595
+ let i = -1;
596
+ while (++i < targetList.length) {
597
+ const targetItem = targetList[i];
598
+ let resolveResult;
599
+ try {
600
+ resolveResult = resolvePackageTarget(packageJsonUrl, targetItem, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions);
601
+ } catch (error) {
602
+ const exception = error;
603
+ lastException = exception;
604
+ if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
605
+ throw error;
606
+ }
607
+ if (resolveResult === void 0) continue;
608
+ if (resolveResult === null) {
609
+ lastException = null;
610
+ continue;
611
+ }
612
+ return resolveResult;
613
+ }
614
+ if (lastException === void 0 || lastException === null) return null;
615
+ throw lastException;
616
+ }
617
+ if (typeof target === "object" && target !== null) {
618
+ const keys = Object.getOwnPropertyNames(target);
619
+ let i = -1;
620
+ while (++i < keys.length) {
621
+ const key = keys[i];
622
+ if (isArrayIndex(key)) throw new ERR_INVALID_PACKAGE_CONFIG(fileURLToPath(packageJsonUrl), fileURLToPath(base), "\"exports\" cannot contain numeric property keys.");
623
+ }
624
+ i = -1;
625
+ while (++i < keys.length) {
626
+ const key = keys[i];
627
+ if (key === "default" || conditions && conditions.has(key)) {
628
+ const conditionalTarget = target[key];
629
+ const resolveResult = resolvePackageTarget(packageJsonUrl, conditionalTarget, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions);
630
+ if (resolveResult === void 0) continue;
631
+ return resolveResult;
632
+ }
633
+ }
634
+ return null;
635
+ }
636
+ if (target === null) return null;
637
+ throw invalidPackageTarget(packageSubpath, target, packageJsonUrl, internal, base);
638
+ }
639
+ function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
640
+ if (typeof exports === "string" || Array.isArray(exports)) return true;
641
+ if (typeof exports !== "object" || exports === null) return false;
642
+ const keys = Object.getOwnPropertyNames(exports);
643
+ let isConditionalSugar = false;
644
+ let i = 0;
645
+ let keyIndex = -1;
646
+ while (++keyIndex < keys.length) {
647
+ const key = keys[keyIndex];
648
+ const currentIsConditionalSugar = key === "" || key[0] !== ".";
649
+ if (i++ === 0) isConditionalSugar = currentIsConditionalSugar;
650
+ else if (isConditionalSugar !== currentIsConditionalSugar) throw new ERR_INVALID_PACKAGE_CONFIG(fileURLToPath(packageJsonUrl), fileURLToPath(base), "\"exports\" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.");
651
+ }
652
+ return isConditionalSugar;
653
+ }
654
+ function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
655
+ if (process$1.noDeprecation) return;
656
+ const pjsonPath = fileURLToPath(pjsonUrl);
657
+ if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
658
+ emittedPackageWarnings.add(pjsonPath + "|" + match);
659
+ process$1.emitWarning(`Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`, "DeprecationWarning", "DEP0155");
660
+ }
661
+ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
662
+ let exports = packageConfig.exports;
663
+ if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) exports = { ".": exports };
664
+ if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
665
+ const target = exports[packageSubpath];
666
+ const resolveResult = resolvePackageTarget(packageJsonUrl, target, "", packageSubpath, base, false, false, false, conditions);
667
+ if (resolveResult === null || resolveResult === void 0) throw exportsNotFound(packageSubpath, packageJsonUrl, base);
668
+ return resolveResult;
669
+ }
670
+ let bestMatch = "";
671
+ let bestMatchSubpath = "";
672
+ const keys = Object.getOwnPropertyNames(exports);
673
+ let i = -1;
674
+ while (++i < keys.length) {
675
+ const key = keys[i];
676
+ const patternIndex = key.indexOf("*");
677
+ if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
678
+ if (packageSubpath.endsWith("/")) emitTrailingSlashPatternDeprecation(packageSubpath, packageJsonUrl, base);
679
+ const patternTrailer = key.slice(patternIndex + 1);
680
+ if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
681
+ bestMatch = key;
682
+ bestMatchSubpath = packageSubpath.slice(patternIndex, packageSubpath.length - patternTrailer.length);
683
+ }
684
+ }
685
+ }
686
+ if (bestMatch) {
687
+ const target = exports[bestMatch];
688
+ const resolveResult = resolvePackageTarget(packageJsonUrl, target, bestMatchSubpath, bestMatch, base, true, false, packageSubpath.endsWith("/"), conditions);
689
+ if (resolveResult === null || resolveResult === void 0) throw exportsNotFound(packageSubpath, packageJsonUrl, base);
690
+ return resolveResult;
691
+ }
692
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
693
+ }
694
+ function patternKeyCompare(a, b) {
695
+ const aPatternIndex = a.indexOf("*");
696
+ const bPatternIndex = b.indexOf("*");
697
+ const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
698
+ const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
699
+ if (baseLengthA > baseLengthB) return -1;
700
+ if (baseLengthB > baseLengthA) return 1;
701
+ if (aPatternIndex === -1) return 1;
702
+ if (bPatternIndex === -1) return -1;
703
+ if (a.length > b.length) return -1;
704
+ if (b.length > a.length) return 1;
705
+ return 0;
706
+ }
707
+ function packageImportsResolve(name, base, conditions) {
708
+ if (name === "#" || name.startsWith("#/") || name.endsWith("/")) throw new ERR_INVALID_MODULE_SPECIFIER(name, "is not a valid internal imports specifier name", fileURLToPath(base));
709
+ let packageJsonUrl;
710
+ const packageConfig = getPackageScopeConfig(base);
711
+ if (packageConfig.exists) {
712
+ packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);
713
+ const imports = packageConfig.imports;
714
+ if (imports) if (own.call(imports, name) && !name.includes("*")) {
715
+ const resolveResult = resolvePackageTarget(packageJsonUrl, imports[name], "", name, base, false, true, false, conditions);
716
+ if (resolveResult !== null && resolveResult !== void 0) return resolveResult;
717
+ } else {
718
+ let bestMatch = "";
719
+ let bestMatchSubpath = "";
720
+ const keys = Object.getOwnPropertyNames(imports);
721
+ let i = -1;
722
+ while (++i < keys.length) {
723
+ const key = keys[i];
724
+ const patternIndex = key.indexOf("*");
725
+ if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
726
+ const patternTrailer = key.slice(patternIndex + 1);
727
+ if (name.length >= key.length && name.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
728
+ bestMatch = key;
729
+ bestMatchSubpath = name.slice(patternIndex, name.length - patternTrailer.length);
730
+ }
731
+ }
732
+ }
733
+ if (bestMatch) {
734
+ const target = imports[bestMatch];
735
+ const resolveResult = resolvePackageTarget(packageJsonUrl, target, bestMatchSubpath, bestMatch, base, true, true, false, conditions);
736
+ if (resolveResult !== null && resolveResult !== void 0) return resolveResult;
737
+ }
738
+ }
739
+ }
740
+ throw importNotDefined(name, packageJsonUrl, base);
741
+ }
742
+ /**
743
+ * @param {string} specifier
744
+ * @param {URL} base
745
+ */
746
+ function parsePackageName(specifier, base) {
747
+ let separatorIndex = specifier.indexOf("/");
748
+ let validPackageName = true;
749
+ let isScoped = false;
750
+ if (specifier[0] === "@") {
751
+ isScoped = true;
752
+ if (separatorIndex === -1 || specifier.length === 0) validPackageName = false;
753
+ else separatorIndex = specifier.indexOf("/", separatorIndex + 1);
754
+ }
755
+ const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
756
+ if (invalidPackageNameRegEx.exec(packageName) !== null) validPackageName = false;
757
+ if (!validPackageName) throw new ERR_INVALID_MODULE_SPECIFIER(specifier, "is not a valid package name", fileURLToPath(base));
758
+ return {
759
+ packageName,
760
+ packageSubpath: "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex)),
761
+ isScoped
762
+ };
763
+ }
764
+ function packageResolve(specifier, base, conditions) {
765
+ if (nodeBuiltins.includes(specifier)) return new URL$1("node:" + specifier);
766
+ const { packageName, packageSubpath, isScoped } = parsePackageName(specifier, base);
767
+ const packageConfig = getPackageScopeConfig(base);
768
+ if (packageConfig.exists && packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) return packageExportsResolve(pathToFileURL(packageConfig.pjsonPath), packageSubpath, packageConfig, base, conditions);
769
+ let packageJsonUrl = new URL$1("./node_modules/" + packageName + "/package.json", base);
770
+ let packageJsonPath = fileURLToPath(packageJsonUrl);
771
+ let lastPath;
772
+ do {
773
+ const stat = tryStatSync(packageJsonPath.slice(0, -13));
774
+ if (!stat || !stat.isDirectory()) {
775
+ lastPath = packageJsonPath;
776
+ packageJsonUrl = new URL$1((isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json", packageJsonUrl);
777
+ packageJsonPath = fileURLToPath(packageJsonUrl);
778
+ continue;
779
+ }
780
+ const packageConfig$1 = read(packageJsonPath, {
781
+ base,
782
+ specifier
783
+ });
784
+ if (packageConfig$1.exports !== void 0 && packageConfig$1.exports !== null) return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig$1, base, conditions);
785
+ if (packageSubpath === ".") return legacyMainResolve(packageJsonUrl, packageConfig$1, base);
786
+ return new URL$1(packageSubpath, packageJsonUrl);
787
+ } while (packageJsonPath.length !== lastPath.length);
788
+ throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base), false);
789
+ }
790
+ function isRelativeSpecifier(specifier) {
791
+ if (specifier[0] === ".") {
792
+ if (specifier.length === 1 || specifier[1] === "/") return true;
793
+ if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) return true;
794
+ }
795
+ return false;
796
+ }
797
+ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
798
+ if (specifier === "") return false;
799
+ if (specifier[0] === "/") return true;
800
+ return isRelativeSpecifier(specifier);
801
+ }
802
+ /**
803
+ * The “Resolver Algorithm Specification” as detailed in the Node docs (which is
804
+ * sync and slightly lower-level than `resolve`).
805
+ *
806
+ * @param {string} specifier
807
+ * `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc.
808
+ * @param {URL} base
809
+ * Full URL (to a file) that `specifier` is resolved relative from.
810
+ * @param {Set<string>} [conditions]
811
+ * Conditions.
812
+ * @param {boolean} [preserveSymlinks]
813
+ * Keep symlinks instead of resolving them.
814
+ * @returns {URL}
815
+ * A URL object to the found thing.
816
+ */
817
+ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
818
+ const protocol = base.protocol;
819
+ const isData = protocol === "data:";
820
+ let resolved;
821
+ if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) try {
822
+ resolved = new URL$1(specifier, base);
823
+ } catch (error_) {
824
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
825
+ error.cause = error_;
826
+ throw error;
827
+ }
828
+ else if (protocol === "file:" && specifier[0] === "#") resolved = packageImportsResolve(specifier, base, conditions);
829
+ else try {
830
+ resolved = new URL$1(specifier);
831
+ } catch (error_) {
832
+ if (isData && !nodeBuiltins.includes(specifier)) {
833
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
834
+ error.cause = error_;
835
+ throw error;
836
+ }
837
+ resolved = packageResolve(specifier, base, conditions);
838
+ }
839
+ assert.ok(resolved !== void 0, "expected to be defined");
840
+ if (resolved.protocol !== "file:") return resolved;
841
+ return finalizeResolution(resolved, base, preserveSymlinks);
842
+ }
843
+ const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
844
+ const isWindows = process.platform === "win32";
845
+ const globalCache = globalThis["__EXSOLVE_CACHE__"] ||= /* @__PURE__ */ new Map();
846
+ /**
847
+ * Synchronously resolves a module url based on the options provided.
848
+ *
849
+ * @param {string} input - The identifier or path of the module to resolve.
850
+ * @param {ResolveOptions} [options] - Options to resolve the module. See {@link ResolveOptions}.
851
+ * @returns {string} The resolved URL as a string.
852
+ */
853
+ function resolveModuleURL(input, options) {
854
+ const parsedInput = _parseInput(input);
855
+ if ("external" in parsedInput) return parsedInput.external;
856
+ const specifier = parsedInput.specifier;
857
+ let url = parsedInput.url;
858
+ let absolutePath = parsedInput.absolutePath;
859
+ let cacheKey;
860
+ let cacheObj;
861
+ if (options?.cache !== false) {
862
+ cacheKey = _cacheKey(absolutePath || specifier, options);
863
+ cacheObj = options?.cache && typeof options?.cache === "object" ? options.cache : globalCache;
864
+ }
865
+ if (cacheObj) {
866
+ const cached = cacheObj.get(cacheKey);
867
+ if (typeof cached === "string") return cached;
868
+ if (cached instanceof Error) {
869
+ if (options?.try) return;
870
+ throw cached;
871
+ }
872
+ }
873
+ if (absolutePath) try {
874
+ const stat = lstatSync(absolutePath);
875
+ if (stat.isSymbolicLink()) {
876
+ absolutePath = realpathSync(absolutePath);
877
+ url = pathToFileURL(absolutePath);
878
+ }
879
+ if (stat.isFile()) {
880
+ if (cacheObj) cacheObj.set(cacheKey, url.href);
881
+ return url.href;
882
+ }
883
+ } catch (error) {
884
+ if (error?.code !== "ENOENT") {
885
+ if (cacheObj) cacheObj.set(cacheKey, error);
886
+ throw error;
887
+ }
888
+ }
889
+ const conditionsSet = options?.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
890
+ const target = specifier || url.href;
891
+ const bases = _normalizeBases(options?.from);
892
+ const suffixes = options?.suffixes || [""];
893
+ const extensions = options?.extensions ? ["", ...options.extensions] : [""];
894
+ let resolved;
895
+ for (const base of bases) {
896
+ for (const suffix of suffixes) {
897
+ let name = _join(target, suffix);
898
+ if (name === ".") name += "/.";
899
+ for (const extension of extensions) {
900
+ resolved = _tryModuleResolve(name + extension, base, conditionsSet);
901
+ if (resolved) break;
902
+ }
903
+ if (resolved) break;
904
+ }
905
+ if (resolved) break;
906
+ }
907
+ if (!resolved) {
908
+ const error = /* @__PURE__ */ new Error(`Cannot resolve module "${input}" (from: ${bases.map((u) => _fmtPath(u)).join(", ")})`);
909
+ error.code = "ERR_MODULE_NOT_FOUND";
910
+ if (cacheObj) cacheObj.set(cacheKey, error);
911
+ if (options?.try) return;
912
+ throw error;
913
+ }
914
+ if (cacheObj) cacheObj.set(cacheKey, resolved.href);
915
+ return resolved.href;
916
+ }
917
+ /**
918
+ * Synchronously resolves a module then converts it to a file path
919
+ *
920
+ * (throws error if reolved path is not file:// scheme)
921
+ *
922
+ * @param {string} id - The identifier or path of the module to resolve.
923
+ * @param {ResolveOptions} [options] - Options to resolve the module. See {@link ResolveOptions}.
924
+ * @returns {string} The resolved URL as a string.
925
+ */
926
+ function resolveModulePath(id, options) {
927
+ const resolved = resolveModuleURL(id, options);
928
+ if (!resolved) return;
929
+ if (!resolved.startsWith("file://") && options?.try) return;
930
+ const absolutePath = fileURLToPath(resolved);
931
+ return isWindows ? _normalizeWinPath(absolutePath) : absolutePath;
932
+ }
933
+ function _tryModuleResolve(specifier, base, conditions) {
934
+ try {
935
+ return moduleResolve(specifier, base, conditions);
936
+ } catch {}
937
+ }
938
+ function _normalizeBases(inputs) {
939
+ const urls = (Array.isArray(inputs) ? inputs : [inputs]).flatMap((input) => _normalizeBase(input));
940
+ if (urls.length === 0) return [pathToFileURL("./")];
941
+ return urls;
942
+ }
943
+ function _normalizeBase(input) {
944
+ if (!input) return [];
945
+ if (_isURL(input)) return [input];
946
+ if (typeof input !== "string") return [];
947
+ if (/^(?:node|data|http|https|file):/.test(input)) return new URL(input);
948
+ try {
949
+ if (input.endsWith("/") || statSync(input).isDirectory()) return pathToFileURL(input + "/");
950
+ return pathToFileURL(input);
951
+ } catch {
952
+ return [pathToFileURL(input + "/"), pathToFileURL(input)];
953
+ }
954
+ }
955
+ function _fmtPath(input) {
956
+ try {
957
+ return fileURLToPath(input);
958
+ } catch {
959
+ return input;
960
+ }
961
+ }
962
+ function _cacheKey(id, opts) {
963
+ return JSON.stringify([
964
+ id,
965
+ (opts?.conditions || ["node", "import"]).sort(),
966
+ opts?.extensions,
967
+ opts?.from,
968
+ opts?.suffixes
969
+ ]);
970
+ }
971
+ function _join(a, b) {
972
+ if (!a || !b || b === "/") return a;
973
+ return (a.endsWith("/") ? a : a + "/") + (b.startsWith("/") ? b.slice(1) : b);
974
+ }
975
+ function _normalizeWinPath(path$1) {
976
+ return path$1.replace(/\\/g, "/").replace(/^[a-z]:\//, (r) => r.toUpperCase());
977
+ }
978
+ function _isURL(input) {
979
+ return input instanceof URL || input?.constructor?.name === "URL";
980
+ }
981
+ function _parseInput(input) {
982
+ if (typeof input === "string") {
983
+ if (input.startsWith("file:")) {
984
+ const url = new URL(input);
985
+ return {
986
+ url,
987
+ absolutePath: fileURLToPath(url)
988
+ };
989
+ }
990
+ if (isAbsolute(input)) return {
991
+ url: pathToFileURL(input),
992
+ absolutePath: input
993
+ };
994
+ if (/^(?:node|data|http|https):/.test(input)) return { external: input };
995
+ if (nodeBuiltins.includes(input) && !input.includes(":")) return { external: `node:${input}` };
996
+ return { specifier: input };
997
+ }
998
+ if (_isURL(input)) {
999
+ if (input.protocol === "file:") return {
1000
+ url: input,
1001
+ absolutePath: fileURLToPath(input)
1002
+ };
1003
+ return { external: input.href };
1004
+ }
1005
+ throw new TypeError("id must be a `string` or `URL`");
1006
+ }
1007
+ //#endregion
1008
+ //#region ../internal/src/nitro.ts
1009
+ function resolveRuntimeEntry$1(srcRelative, packageSubpath, importMetaUrl) {
1010
+ return resolveModulePath(srcRelative, {
1011
+ extensions: [".ts", ".mts"],
1012
+ from: importMetaUrl,
1013
+ try: true
1014
+ }) ?? resolveModulePath(packageSubpath, {
1015
+ extensions: [".js", ".mjs"],
1016
+ from: importMetaUrl
1017
+ });
1018
+ }
1019
+ function isPromiseLike(value) {
1020
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
1021
+ }
1022
+ async function hasNamedVitePlugin(plugin, name) {
1023
+ if (isPromiseLike(plugin)) return hasNamedVitePlugin(await plugin, name);
1024
+ if (Array.isArray(plugin)) {
1025
+ for (const entry of plugin) if (await hasNamedVitePlugin(entry, name)) return true;
1026
+ return false;
1027
+ }
1028
+ return typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === name;
1029
+ }
1030
+ async function assertNoVitePlugin(vite, vitePluginName, integrationName) {
1031
+ if (await hasNamedVitePlugin(vite?.plugins, vitePluginName)) throw new Error(`[vitehub] Do not configure ${vitePluginName} when using ${integrationName}.`);
1032
+ }
1033
+ async function assertNoVitePluginInNitro(nitro, vitePluginName, integrationName) {
1034
+ await assertNoVitePlugin(nitro.options.vite, vitePluginName, integrationName);
1035
+ }
1036
+ function mergeNitroImportsPreset(current, preset) {
1037
+ if (current === false) return current;
1038
+ const existing = current || {};
1039
+ const presets = Array.isArray(existing.presets) ? [...existing.presets] : [];
1040
+ const found = presets.find((entry) => entry?.from === preset.from);
1041
+ if (found && Array.isArray(found.imports)) {
1042
+ const seen = new Set(found.imports);
1043
+ found.imports.push(...preset.imports.filter((name) => !seen.has(name)));
1044
+ } else if (!found) presets.push({
1045
+ from: preset.from,
1046
+ imports: [...preset.imports]
1047
+ });
1048
+ return {
1049
+ ...existing,
1050
+ presets
1051
+ };
1052
+ }
1053
+ //#endregion
1054
+ //#region ../internal/src/build/esbuild.ts
1055
+ async function bundleEsmEntry(entryFile, outfile, options = {}) {
1056
+ const format = options.format || "esm";
1057
+ const platform = options.platform || "neutral";
1058
+ await build({
1059
+ alias: options.alias,
1060
+ banner: format === "esm" && platform === "node" ? { js: "import { createRequire as __createRequire } from \"node:module\";\nvar require = __createRequire(import.meta.url);\n" } : void 0,
1061
+ bundle: true,
1062
+ conditions: options.conditions,
1063
+ entryPoints: [entryFile],
1064
+ external: options.external,
1065
+ format,
1066
+ logLevel: "silent",
1067
+ outfile,
1068
+ platform,
1069
+ sourcemap: false,
1070
+ target: "es2022",
1071
+ write: true
1072
+ });
1073
+ }
1074
+ //#endregion
1075
+ //#region ../internal/src/build/user-entry.ts
1076
+ function toSafeAppName(rootDir) {
1077
+ return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
1078
+ }
1079
+ //#endregion
1080
+ //#region ../internal/src/build/vercel-config.ts
1081
+ function createVercelConfigJson() {
1082
+ return {
1083
+ routes: [{ handle: "filesystem" }, {
1084
+ src: "/(.*)",
1085
+ dest: "/__server"
1086
+ }],
1087
+ version: 3
1088
+ };
1089
+ }
1090
+ function createNodeFunctionConfig(extra = {}) {
1091
+ return {
1092
+ handler: "index.mjs",
1093
+ launcherType: "Nodejs",
1094
+ runtime: "nodejs22.x",
1095
+ shouldAddHelpers: false,
1096
+ supportsResponseStreaming: true,
1097
+ ...extra
1098
+ };
1099
+ }
1100
+ //#endregion
1101
+ //#region ../internal/src/build/deployment-output.ts
1102
+ function shouldSkipViteProviderBuild(command, mode) {
1103
+ return command === "serve" || mode === "e2e";
1104
+ }
1105
+ function createDefaultCloudflareOutputRoot(rootDir) {
1106
+ return resolve(rootDir, "dist", toSafeAppName(rootDir));
1107
+ }
1108
+ function createDefaultVercelOutputRoot(rootDir) {
1109
+ return resolve(rootDir, ".vercel", "output");
1110
+ }
1111
+ //#endregion
1112
+ //#region src/integrations/vercel.ts
1113
+ function getVercelSchedulePath(name) {
1114
+ return `/api/vitehub/schedules/vercel/${name.replace(/[^a-z0-9/_-]+/gi, "_")}`;
1115
+ }
1116
+ //#endregion
1117
+ //#region src/internal/provider-output.ts
1118
+ const schedulePackageName = "@vite-hub/schedule";
1119
+ const productName = "schedule";
1120
+ const generatedRegistryFileName = "registry.mjs";
1121
+ function resolveScheduleRuntimeEntry(metaUrl = import.meta.url) {
1122
+ const file = fileURLToPath(metaUrl);
1123
+ const normalizedFile = file.replace(/\\/g, "/");
1124
+ if (normalizedFile.endsWith("/src/internal/provider-output.ts")) return resolve(dirname(file), "../runtime/static.ts");
1125
+ if (normalizedFile.endsWith("/dist/internal/provider-output.js")) return resolve(dirname(file), "../runtime/static.js");
1126
+ return normalizedFile.includes("/dist/") ? resolve(dirname(file), "runtime/static.js") : resolve(dirname(file), "dist/runtime/static.js");
1127
+ }
1128
+ const scheduleRuntimeEntry = resolveScheduleRuntimeEntry();
1129
+ const cronFieldPattern = /^[*,/\-0-9]+$/;
1130
+ function validateProviderCron(cron, scheduleName) {
1131
+ const fields = cron.trim().split(/\s+/);
1132
+ const hasVercelDayConflict = fields[2] !== "*" && fields[4] !== "*";
1133
+ if (fields.length !== 5 || !fields.every((field) => cronFieldPattern.test(field)) || hasVercelDayConflict) throw new Error(`Schedule "${scheduleName}" uses cron "${cron}", but provider wake output only supports five-field UTC cron syntax compatible with Cloudflare and Vercel.`);
1134
+ }
1135
+ function readStaticScheduleCron(file, scheduleName) {
1136
+ const cron = readDefaultDefineScheduleCron(readFileSync(file, "utf8"));
1137
+ if (!cron) throw new Error(`Schedule "${scheduleName}" must declare a static cron string for provider wake output.`);
1138
+ return cron;
1139
+ }
1140
+ function skipQuoted(source, index) {
1141
+ const quote = source[index];
1142
+ if (quote === "`") return skipTemplateLiteral(source, index);
1143
+ index += 1;
1144
+ while (index < source.length) {
1145
+ if (source[index] === "\\") {
1146
+ index += 2;
1147
+ continue;
1148
+ }
1149
+ if (source[index] === quote) return index + 1;
1150
+ index += 1;
1151
+ }
1152
+ return index;
1153
+ }
1154
+ function skipTemplateExpression(source, index) {
1155
+ let depth = 1;
1156
+ while (index < source.length) {
1157
+ const char = source[index];
1158
+ if (char === "\"" || char === "'" || char === "`") {
1159
+ index = skipQuoted(source, index);
1160
+ continue;
1161
+ }
1162
+ if (source.startsWith("//", index)) {
1163
+ index = skipLineComment(source, index);
1164
+ continue;
1165
+ }
1166
+ if (source.startsWith("/*", index)) {
1167
+ index = skipBlockComment(source, index);
1168
+ continue;
1169
+ }
1170
+ if (char === "/" && canStartRegexLiteral(source, index)) {
1171
+ index = skipRegexLiteral(source, index);
1172
+ continue;
1173
+ }
1174
+ if (char === "{") depth += 1;
1175
+ if (char === "}") {
1176
+ depth -= 1;
1177
+ if (depth === 0) return index + 1;
1178
+ }
1179
+ index += 1;
1180
+ }
1181
+ return index;
1182
+ }
1183
+ function skipTemplateLiteral(source, index) {
1184
+ index += 1;
1185
+ while (index < source.length) {
1186
+ if (source[index] === "\\") {
1187
+ index += 2;
1188
+ continue;
1189
+ }
1190
+ if (source[index] === "`") return index + 1;
1191
+ if (source.startsWith("${", index)) {
1192
+ index = skipTemplateExpression(source, index + 2);
1193
+ continue;
1194
+ }
1195
+ index += 1;
1196
+ }
1197
+ return index;
1198
+ }
1199
+ function skipLineComment(source, index) {
1200
+ const newline = source.indexOf("\n", index + 2);
1201
+ return newline === -1 ? source.length : newline + 1;
1202
+ }
1203
+ function skipBlockComment(source, index) {
1204
+ const close = source.indexOf("*/", index + 2);
1205
+ return close === -1 ? source.length : close + 2;
1206
+ }
1207
+ function isInsideNonCode(source, targetIndex) {
1208
+ for (let index = 0; index < targetIndex; index += 1) {
1209
+ const char = source[index];
1210
+ if (char === "\"" || char === "'" || char === "`") {
1211
+ const quotedEnd = skipQuoted(source, index);
1212
+ if (targetIndex < quotedEnd) return true;
1213
+ index = quotedEnd - 1;
1214
+ continue;
1215
+ }
1216
+ if (source.startsWith("//", index)) {
1217
+ const commentEnd = skipLineComment(source, index);
1218
+ if (targetIndex < commentEnd) return true;
1219
+ index = commentEnd - 1;
1220
+ continue;
1221
+ }
1222
+ if (source.startsWith("/*", index)) {
1223
+ const commentEnd = skipBlockComment(source, index);
1224
+ if (targetIndex < commentEnd) return true;
1225
+ index = commentEnd - 1;
1226
+ }
1227
+ }
1228
+ return false;
1229
+ }
1230
+ function skipIgnorable(source, index) {
1231
+ while (index < source.length) {
1232
+ if (/\s/.test(source[index])) {
1233
+ index += 1;
1234
+ continue;
1235
+ }
1236
+ if (source.startsWith("//", index)) {
1237
+ index = skipLineComment(source, index);
1238
+ continue;
1239
+ }
1240
+ if (source.startsWith("/*", index)) {
1241
+ index = skipBlockComment(source, index);
1242
+ continue;
1243
+ }
1244
+ break;
1245
+ }
1246
+ return index;
1247
+ }
1248
+ function previousSignificantToken(source, index) {
1249
+ let cursor = index - 1;
1250
+ while (cursor >= 0 && /\s/.test(source[cursor])) cursor -= 1;
1251
+ if (cursor < 0) return "";
1252
+ const wordEnd = cursor + 1;
1253
+ while (cursor >= 0 && /[$\w]/.test(source[cursor])) cursor -= 1;
1254
+ if (cursor < wordEnd - 1) return source.slice(cursor + 1, wordEnd);
1255
+ return source[cursor];
1256
+ }
1257
+ function canStartRegexLiteral(source, index) {
1258
+ const token = previousSignificantToken(source, index);
1259
+ return token === "" || token === "await" || token === "case" || token === "delete" || token === "return" || token === "throw" || token === "typeof" || token === "void" || /^[({[=,:;!&|?+\-*%^~<>]$/.test(token);
1260
+ }
1261
+ function skipRegexLiteral(source, index) {
1262
+ let inCharacterClass = false;
1263
+ for (let cursor = index + 1; cursor < source.length; cursor += 1) {
1264
+ const char = source[cursor];
1265
+ if (char === "\\") {
1266
+ cursor += 1;
1267
+ continue;
1268
+ }
1269
+ if (char === "[") {
1270
+ inCharacterClass = true;
1271
+ continue;
1272
+ }
1273
+ if (char === "]") {
1274
+ inCharacterClass = false;
1275
+ continue;
1276
+ }
1277
+ if (char === "/" && !inCharacterClass) {
1278
+ cursor += 1;
1279
+ while (/[a-z]/i.test(source[cursor] ?? "")) cursor += 1;
1280
+ return cursor;
1281
+ }
1282
+ }
1283
+ return source.length;
1284
+ }
1285
+ function readBalancedObject(source, openIndex) {
1286
+ if (source[openIndex] !== "{") return void 0;
1287
+ let depth = 0;
1288
+ for (let index = openIndex; index < source.length; index += 1) {
1289
+ const char = source[index];
1290
+ if (char === "\"" || char === "'" || char === "`") {
1291
+ index = skipQuoted(source, index) - 1;
1292
+ continue;
1293
+ }
1294
+ if (source.startsWith("//", index)) {
1295
+ index = skipLineComment(source, index) - 1;
1296
+ continue;
1297
+ }
1298
+ if (source.startsWith("/*", index)) {
1299
+ index = skipBlockComment(source, index) - 1;
1300
+ continue;
1301
+ }
1302
+ if (char === "/" && canStartRegexLiteral(source, index)) {
1303
+ index = skipRegexLiteral(source, index) - 1;
1304
+ continue;
1305
+ }
1306
+ if (char === "{") depth += 1;
1307
+ if (char === "}") {
1308
+ depth -= 1;
1309
+ if (depth === 0) return source.slice(openIndex + 1, index);
1310
+ }
1311
+ }
1312
+ }
1313
+ function splitTopLevelProperties(source) {
1314
+ const properties = [];
1315
+ let depth = 0;
1316
+ let start = 0;
1317
+ for (let index = 0; index < source.length; index += 1) {
1318
+ const char = source[index];
1319
+ if (char === "\"" || char === "'" || char === "`") {
1320
+ index = skipQuoted(source, index) - 1;
1321
+ continue;
1322
+ }
1323
+ if (source.startsWith("//", index)) {
1324
+ index = skipLineComment(source, index) - 1;
1325
+ continue;
1326
+ }
1327
+ if (source.startsWith("/*", index)) {
1328
+ index = skipBlockComment(source, index) - 1;
1329
+ continue;
1330
+ }
1331
+ if (char === "/" && canStartRegexLiteral(source, index)) {
1332
+ index = skipRegexLiteral(source, index) - 1;
1333
+ continue;
1334
+ }
1335
+ if (char === "{" || char === "[" || char === "(") depth += 1;
1336
+ if (char === "}" || char === "]" || char === ")") depth -= 1;
1337
+ if (char === "," && depth === 0) {
1338
+ properties.push(source.slice(start, index));
1339
+ start = index + 1;
1340
+ }
1341
+ }
1342
+ properties.push(source.slice(start));
1343
+ return properties;
1344
+ }
1345
+ function readStaticStringLiteral(source) {
1346
+ const value = source.trim();
1347
+ const quote = value[0];
1348
+ if (quote !== "\"" && quote !== "'" && quote !== "`") return void 0;
1349
+ let result = "";
1350
+ for (let index = 1; index < value.length; index += 1) {
1351
+ const char = value[index];
1352
+ if (char === "\\") {
1353
+ result += value[index + 1] ?? "";
1354
+ index += 1;
1355
+ continue;
1356
+ }
1357
+ if (char === quote) {
1358
+ if (skipIgnorable(value, index + 1) !== value.length) return;
1359
+ return result;
1360
+ }
1361
+ result += char;
1362
+ }
1363
+ }
1364
+ function readTopLevelCronProperty(objectSource) {
1365
+ for (const property of splitTopLevelProperties(objectSource)) {
1366
+ const colon = property.indexOf(":");
1367
+ if (colon === -1) continue;
1368
+ const keyStart = skipIgnorable(property, 0);
1369
+ if (property.slice(keyStart, colon).trim().replace(/^["'`](.*)["'`]$/s, "$1") !== "cron") continue;
1370
+ const cron = readStaticStringLiteral(property.slice(colon + 1));
1371
+ if (!cron) throw new Error("Schedule must declare a static cron string for provider wake output.");
1372
+ return cron;
1373
+ }
1374
+ }
1375
+ function findTypeParametersEnd(source, index) {
1376
+ let depth = 0;
1377
+ for (let cursor = index; cursor < source.length; cursor += 1) {
1378
+ const char = source[cursor];
1379
+ if (char === "<") depth += 1;
1380
+ if (char === ">" && source[cursor - 1] === "=") continue;
1381
+ if (char === ">") {
1382
+ depth -= 1;
1383
+ if (depth === 0) return cursor;
1384
+ }
1385
+ }
1386
+ return -1;
1387
+ }
1388
+ function readDefineScheduleObjectAfterDefault(source, index) {
1389
+ let cursor = skipIgnorable(source, index);
1390
+ let openParens = 0;
1391
+ while (source[cursor] === "(") {
1392
+ openParens += 1;
1393
+ cursor = skipIgnorable(source, cursor + 1);
1394
+ }
1395
+ if (!source.startsWith("defineSchedule", cursor)) return void 0;
1396
+ cursor += 14;
1397
+ cursor = skipIgnorable(source, cursor);
1398
+ if (source[cursor] === "<") {
1399
+ const close = findTypeParametersEnd(source, cursor);
1400
+ if (close === -1) return void 0;
1401
+ cursor = skipIgnorable(source, close + 1);
1402
+ }
1403
+ if (source[cursor] !== "(") return void 0;
1404
+ cursor = skipIgnorable(source, cursor + 1);
1405
+ const objectSource = readBalancedObject(source, cursor);
1406
+ if (!objectSource) return void 0;
1407
+ let afterObject = skipIgnorable(source, cursor + objectSource.length + 2);
1408
+ if (source[afterObject] === ")") afterObject = skipIgnorable(source, afterObject + 1);
1409
+ while (openParens > 0 && source[afterObject] === ")") {
1410
+ openParens -= 1;
1411
+ afterObject = skipIgnorable(source, afterObject + 1);
1412
+ }
1413
+ return openParens === 0 ? objectSource : void 0;
1414
+ }
1415
+ function readDefaultDefineScheduleCron(source) {
1416
+ let match;
1417
+ const pattern = /\bexport\s+default\b/g;
1418
+ while (match = pattern.exec(source)) {
1419
+ if (isInsideNonCode(source, match.index)) continue;
1420
+ const objectSource = readDefineScheduleObjectAfterDefault(source, match.index + match[0].length);
1421
+ if (!objectSource) continue;
1422
+ return readTopLevelCronProperty(objectSource);
1423
+ }
1424
+ }
1425
+ function renderProviderEntry(file, registryFile, provider, scheduleName) {
1426
+ const runtimeImport = createImportPath(file, scheduleRuntimeEntry);
1427
+ return [
1428
+ `import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
1429
+ `import { executeStaticSchedule } from ${JSON.stringify(runtimeImport)}`,
1430
+ "",
1431
+ "async function loadScheduleDefinition(name) {",
1432
+ " const loader = scheduleRegistry[name]",
1433
+ " if (!loader) return undefined",
1434
+ " const loaded = await loader()",
1435
+ " return loaded?.default ?? loaded",
1436
+ "}",
1437
+ "",
1438
+ "async function runSchedule(name, cron, scheduledAt) {",
1439
+ " const definition = await loadScheduleDefinition(name)",
1440
+ " if (!definition) {",
1441
+ " throw new Error(`Missing schedule definition: ${name}`)",
1442
+ " }",
1443
+ " return await executeStaticSchedule({ cron, definition, name, scheduledAt })",
1444
+ "}",
1445
+ "",
1446
+ provider === "cloudflare" ? [
1447
+ "export default {",
1448
+ " async fetch() {",
1449
+ " return new Response('ViteHub schedule provider wake endpoint')",
1450
+ " },",
1451
+ " async scheduled(event, env, ctx) {",
1452
+ " const tasks = Object.entries(scheduleRegistry).map(async ([name]) => {",
1453
+ " const definition = await loadScheduleDefinition(name)",
1454
+ " if (!definition || definition.cron !== event.cron) return",
1455
+ " await executeStaticSchedule({ cron: event.cron, definition, name, scheduledAt: new Date(event.scheduledTime) })",
1456
+ " })",
1457
+ " await Promise.all(tasks)",
1458
+ " },",
1459
+ "}"
1460
+ ].join("\n") : [
1461
+ "export default async function scheduleHandler(req, res) {",
1462
+ " const cronSecret = process.env.CRON_SECRET",
1463
+ " const authorization = req.headers?.authorization || req.headers?.Authorization",
1464
+ " if (cronSecret && authorization !== `Bearer ${cronSecret}`) {",
1465
+ " res.statusCode = 401",
1466
+ " res.end('Unauthorized.')",
1467
+ " return",
1468
+ " }",
1469
+ " const url = new URL(req.url || '/', 'https://vitehub.local')",
1470
+ " const prefix = '/api/vitehub/schedules/vercel/'",
1471
+ scheduleName === void 0 ? " const name = decodeURIComponent(url.pathname.startsWith(prefix) ? url.pathname.slice(prefix.length) : '')" : ` const name = ${JSON.stringify(scheduleName)}`,
1472
+ " const definition = await loadScheduleDefinition(name)",
1473
+ " if (!definition) {",
1474
+ " res.statusCode = 404",
1475
+ " res.end('Missing schedule definition.')",
1476
+ " return",
1477
+ " }",
1478
+ " await runSchedule(name, definition.cron, new Date())",
1479
+ " res.statusCode = 204",
1480
+ " res.end()",
1481
+ "}"
1482
+ ].join("\n"),
1483
+ ""
1484
+ ].join("\n");
1485
+ }
1486
+ async function writeProviderEntries(rootDir) {
1487
+ const generatedDir = ensureGeneratedDir(rootDir, productName);
1488
+ await mkdir(generatedDir, { recursive: true });
1489
+ const registryFile = resolve(generatedDir, generatedRegistryFileName);
1490
+ const definitions = discoverScheduleDefinitions({ rootDir });
1491
+ await writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions), "utf8");
1492
+ const cloudflareWorkerFile = resolve(generatedDir, "cloudflare-worker.mjs");
1493
+ const vercelServerFile = resolve(generatedDir, "vercel-server.mjs");
1494
+ await writeFile(cloudflareWorkerFile, renderProviderEntry(cloudflareWorkerFile, registryFile, "cloudflare"), "utf8");
1495
+ await writeFile(vercelServerFile, renderProviderEntry(vercelServerFile, registryFile, "vercel"), "utf8");
1496
+ return {
1497
+ cloudflareWorkerFile,
1498
+ definitions,
1499
+ generatedDir,
1500
+ registryFile,
1501
+ vercelServerFile
1502
+ };
1503
+ }
1504
+ async function readDefinitionCrons(definitions) {
1505
+ const crons = /* @__PURE__ */ new Map();
1506
+ for (const definition of definitions) {
1507
+ const cron = readStaticScheduleCron(definition.handler, definition.name);
1508
+ validateProviderCron(cron, definition.name);
1509
+ crons.set(definition.name, cron);
1510
+ }
1511
+ return crons;
1512
+ }
1513
+ async function writeVercelScheduleFunctions(options, crons) {
1514
+ const outputRoot = options.outputRoot;
1515
+ const functionRoot = resolve(outputRoot, "functions", "api", "vitehub", "schedules", "vercel");
1516
+ await rm(functionRoot, {
1517
+ force: true,
1518
+ recursive: true
1519
+ });
1520
+ const emittedFunctionNames = /* @__PURE__ */ new Map();
1521
+ for (const definition of options.definitions) {
1522
+ const safeName = definition.name.replace(/[^a-z0-9/_-]+/gi, "_").split("/").filter(Boolean).join("/");
1523
+ const existingName = emittedFunctionNames.get(safeName);
1524
+ if (existingName) throw new Error(`Schedule "${definition.name}" and "${existingName}" both emit the same Vercel function path: ${safeName}`);
1525
+ emittedFunctionNames.set(safeName, definition.name);
1526
+ const segments = safeName.split("/");
1527
+ const functionDir = resolve(functionRoot, ...segments.slice(0, -1), `${segments.at(-1)}.func`);
1528
+ const functionFile = resolve(functionDir, "index.mjs");
1529
+ const wrapperFile = resolve(functionDir, "index.source.mjs");
1530
+ await mkdir(functionDir, { recursive: true });
1531
+ await writeFile(wrapperFile, renderProviderEntry(wrapperFile, options.registryFile, "vercel", definition.name), "utf8");
1532
+ await bundleEsmEntry(wrapperFile, functionFile, {
1533
+ alias: options.bundleAlias,
1534
+ format: "esm",
1535
+ platform: "node"
1536
+ });
1537
+ await rm(wrapperFile, { force: true });
1538
+ await writeFile(resolve(functionDir, ".vc-config.json"), `${JSON.stringify(createNodeFunctionConfig(), null, 2)}\n`, "utf8");
1539
+ }
1540
+ const configFile = resolve(outputRoot, "config.json");
1541
+ let vercelConfig = createVercelConfigJson();
1542
+ try {
1543
+ vercelConfig = JSON.parse(await readFile(configFile, "utf8"));
1544
+ } catch (error) {
1545
+ if (error.code !== "ENOENT") throw error;
1546
+ }
1547
+ const schedulePathPrefix = "/api/vitehub/schedules/vercel/";
1548
+ const existingCrons = vercelConfig.crons?.filter((cron) => !cron.path.startsWith(schedulePathPrefix)) ?? [];
1549
+ vercelConfig.crons = [...existingCrons, ...options.definitions.map((definition) => ({
1550
+ path: getVercelSchedulePath(definition.name),
1551
+ schedule: crons.get(definition.name)
1552
+ }))];
1553
+ await writeFile(configFile, `${JSON.stringify(vercelConfig, null, 2)}\n`, "utf8");
1554
+ }
1555
+ async function writeCloudflareScheduleOutput(options) {
1556
+ const outputRoot = createDefaultCloudflareOutputRoot(options.rootDir);
1557
+ await mkdir(outputRoot, { recursive: true });
1558
+ const configFile = resolve(outputRoot, "wrangler.json");
1559
+ let wranglerConfig = {};
1560
+ try {
1561
+ wranglerConfig = JSON.parse(await readFile(configFile, "utf8"));
1562
+ } catch (error) {
1563
+ if (error.code !== "ENOENT") throw error;
1564
+ }
1565
+ const existingTriggers = typeof wranglerConfig.triggers === "object" && wranglerConfig.triggers !== null ? wranglerConfig.triggers : {};
1566
+ const main = typeof wranglerConfig.main === "string" && wranglerConfig.main ? wranglerConfig.main : "index.js";
1567
+ wranglerConfig = {
1568
+ ...wranglerConfig,
1569
+ compatibility_date: wranglerConfig.compatibility_date ?? "2026-04-20",
1570
+ compatibility_flags: wranglerConfig.compatibility_flags ?? ["nodejs_compat"],
1571
+ main,
1572
+ observability: wranglerConfig.observability ?? { enabled: true },
1573
+ triggers: {
1574
+ ...existingTriggers,
1575
+ crons: [...new Set([...existingTriggers.crons ?? [], ...options.crons])]
1576
+ }
1577
+ };
1578
+ await Promise.all([bundleEsmEntry(options.bundleEntry, resolve(outputRoot, main), {
1579
+ alias: options.bundleAlias,
1580
+ conditions: [
1581
+ "workerd",
1582
+ "worker",
1583
+ "browser",
1584
+ "default"
1585
+ ],
1586
+ format: "esm",
1587
+ platform: "neutral"
1588
+ }), writeFile(configFile, `${JSON.stringify(wranglerConfig, null, 2)}\n`, "utf8")]);
1589
+ }
1590
+ async function generateProviderOutputs(options) {
1591
+ const artifacts = await writeProviderEntries(options.rootDir);
1592
+ const crons = await readDefinitionCrons(artifacts.definitions);
1593
+ await writeCloudflareScheduleOutput({
1594
+ bundleAlias: options.bundleAlias,
1595
+ bundleEntry: artifacts.cloudflareWorkerFile,
1596
+ crons: [...new Set(crons.values())],
1597
+ rootDir: options.rootDir
1598
+ });
1599
+ await writeVercelScheduleFunctions({
1600
+ bundleAlias: options.bundleAlias,
1601
+ definitions: artifacts.definitions,
1602
+ outputRoot: createDefaultVercelOutputRoot(options.rootDir),
1603
+ registryFile: artifacts.registryFile,
1604
+ rootDir: options.rootDir
1605
+ }, crons);
1606
+ return artifacts;
1607
+ }
1608
+ //#endregion
1609
+ //#region src/targets-module.ts
1610
+ const SCHEDULE_TARGETS_ID = "#vitehub/schedule/targets";
1611
+ function getScheduleTargetNames(definitions) {
1612
+ return definitions.filter((definition) => definition.allowRuntimeSchedules).map((definition) => definition.name).sort();
1613
+ }
1614
+ function createScheduleTargetsContents(definitions, options = {}) {
1615
+ const targets = getScheduleTargetNames(definitions);
1616
+ const union = targets.length ? targets.map((target) => JSON.stringify(target)).join(" | ") : "never";
1617
+ return [
1618
+ `export const scheduleTargetNames = ${JSON.stringify(targets)};`,
1619
+ options.types ? `export type ScheduleTargetName = ${union};` : "",
1620
+ ""
1621
+ ].filter((line) => line !== "").join("\n");
1622
+ }
1623
+ //#endregion
1624
+ //#region src/nitro/module.ts
1625
+ const SCHEDULE_NITRO_IMPORTS_PRESET = {
1626
+ from: "@vite-hub/schedule",
1627
+ imports: ["defineSchedule"]
1628
+ };
1629
+ const SCHEDULE_VITE_PLUGIN_NAME = "@vite-hub/schedule/vite";
1630
+ function resolveRuntimeEntry(srcRelative, packageSubpath) {
1631
+ return resolveRuntimeEntry$1(srcRelative, packageSubpath, import.meta.url);
1632
+ }
1633
+ function createNitroScheduleRegistryPath(rootDir, buildDir) {
1634
+ return createNitroRuntimeFilePath(rootDir, {
1635
+ buildDir,
1636
+ fileName: "nitro-registry.mjs",
1637
+ segments: ["vitehub", "schedule"]
1638
+ });
1639
+ }
1640
+ function createNitroScheduleTargetsPath(rootDir, buildDir) {
1641
+ return createNitroRuntimeFilePath(rootDir, {
1642
+ buildDir,
1643
+ fileName: "targets.mjs",
1644
+ segments: ["vitehub", "schedule"]
1645
+ });
1646
+ }
1647
+ function createNitroSchedulePluginPath(rootDir, buildDir) {
1648
+ return createNitroRuntimeFilePath(rootDir, {
1649
+ buildDir,
1650
+ fileName: "nitro-plugin.ts",
1651
+ segments: ["vitehub", "schedule"]
1652
+ });
1653
+ }
1654
+ function resolveNitroScheduleScanDirs(rootDir, scanDirs) {
1655
+ return scanDirs?.length ? scanDirs : [resolve(rootDir, "server")];
1656
+ }
1657
+ function registerNitroSchedulePlugin(nitro, pluginFile) {
1658
+ nitro.options.plugins ||= [];
1659
+ if (!nitro.options.plugins.includes(pluginFile)) nitro.options.plugins.push(pluginFile);
1660
+ }
1661
+ function createNitroSchedulePluginContents(file, registryFile) {
1662
+ return [
1663
+ "import { definePlugin as defineNitroPlugin } from \"nitro\"",
1664
+ "",
1665
+ "import { executeStaticSchedule } from \"@vite-hub/schedule\"",
1666
+ "import { setScheduleRuntimeRegistry } from \"@vite-hub/schedule/runtime/state\"",
1667
+ "",
1668
+ `import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
1669
+ "",
1670
+ "async function loadScheduleDefinition(name: string) {",
1671
+ " const loader = scheduleRegistry[name]",
1672
+ " if (!loader) return undefined",
1673
+ " const loaded = await loader()",
1674
+ " return loaded?.default ?? loaded",
1675
+ "}",
1676
+ "",
1677
+ "const scheduleNitroPlugin = defineNitroPlugin((nitroApp: any) => {",
1678
+ " setScheduleRuntimeRegistry(scheduleRegistry)",
1679
+ " nitroApp.hooks.hook(\"cloudflare:scheduled\", async ({ controller, event }: { controller?: { cron: string, scheduledTime: number }, event?: { cron: string, scheduledTime: number } }) => {",
1680
+ " const scheduledEvent = event ?? controller",
1681
+ " if (!scheduledEvent) return",
1682
+ " await Promise.all(Object.keys(scheduleRegistry).map(async (name) => {",
1683
+ " const definition = await loadScheduleDefinition(name)",
1684
+ " if (!definition || definition.cron !== scheduledEvent.cron) return",
1685
+ " await executeStaticSchedule({ cron: scheduledEvent.cron, definition, name, scheduledAt: new Date(scheduledEvent.scheduledTime) })",
1686
+ " }))",
1687
+ " })",
1688
+ "})",
1689
+ "",
1690
+ "export default scheduleNitroPlugin",
1691
+ ""
1692
+ ].join("\n");
1693
+ }
1694
+ async function writeNitroScheduleRuntimeFiles(nitro) {
1695
+ const registryFile = createNitroScheduleRegistryPath(nitro.options.rootDir, nitro.options.buildDir);
1696
+ const targetsFile = createNitroScheduleTargetsPath(nitro.options.rootDir, nitro.options.buildDir);
1697
+ const pluginFile = createNitroSchedulePluginPath(nitro.options.rootDir, nitro.options.buildDir);
1698
+ const definitions = discoverScheduleDefinitions({
1699
+ mode: "nitro-server-schedules",
1700
+ scanDirs: resolveNitroScheduleScanDirs(nitro.options.rootDir, nitro.options.scanDirs)
1701
+ });
1702
+ await Promise.all([
1703
+ writeFileIfChanged(registryFile, createRuntimeRegistryContents(registryFile, definitions)),
1704
+ writeFileIfChanged(targetsFile, createScheduleTargetsContents(definitions)),
1705
+ writeFileIfChanged(pluginFile, createNitroSchedulePluginContents(pluginFile, registryFile))
1706
+ ]);
1707
+ return {
1708
+ pluginFile,
1709
+ registryFile,
1710
+ targetsFile
1711
+ };
1712
+ }
1713
+ const scheduleNitroModule = {
1714
+ name: "@vite-hub/schedule",
1715
+ async setup(nitro) {
1716
+ await assertNoVitePluginInNitro(nitro, SCHEDULE_VITE_PLUGIN_NAME, "@vite-hub/schedule/nitro");
1717
+ nitro.options.alias ||= {};
1718
+ nitro.options.alias["@vite-hub/schedule"] = resolveRuntimeEntry("../index", "@vite-hub/schedule");
1719
+ nitro.options.alias["@vite-hub/schedule/runtime"] = resolveRuntimeEntry("../runtime", "@vite-hub/schedule/runtime");
1720
+ nitro.options.alias["@vite-hub/schedule/runtime/state"] = resolveRuntimeEntry("../runtime/state", "@vite-hub/schedule/runtime/state");
1721
+ let runtimeFiles = await writeNitroScheduleRuntimeFiles(nitro);
1722
+ applyNitroRuntimeAliases(nitro, {
1723
+ "#vitehub/schedule/registry": runtimeFiles.registryFile,
1724
+ [SCHEDULE_TARGETS_ID]: runtimeFiles.targetsFile
1725
+ });
1726
+ if (!(nitro.options._config?.imports === false)) nitro.options.imports = mergeNitroImportsPreset(nitro.options.imports === false ? {} : nitro.options.imports, SCHEDULE_NITRO_IMPORTS_PRESET);
1727
+ registerNitroSchedulePlugin(nitro, runtimeFiles.pluginFile);
1728
+ if (nitro.options.preset?.includes("cloudflare")) {
1729
+ const crons = await readDefinitionCrons(discoverScheduleDefinitions({
1730
+ mode: "nitro-server-schedules",
1731
+ scanDirs: resolveNitroScheduleScanDirs(nitro.options.rootDir, nitro.options.scanDirs)
1732
+ }));
1733
+ if (crons.size) {
1734
+ nitro.options.cloudflare ||= {};
1735
+ nitro.options.cloudflare.wrangler ||= {};
1736
+ nitro.options.cloudflare.wrangler.triggers ||= { crons: [] };
1737
+ const existing = nitro.options.cloudflare.wrangler.triggers.crons || [];
1738
+ nitro.options.cloudflare.wrangler.triggers.crons = [...new Set([...existing, ...crons.values()])];
1739
+ }
1740
+ }
1741
+ hookNitroRuntimeRegistryRefresh(nitro, () => writeNitroScheduleRuntimeFiles(nitro), (nextRuntimeFiles) => {
1742
+ runtimeFiles = nextRuntimeFiles;
1743
+ applyNitroRuntimeAliases(nitro, {
1744
+ "#vitehub/schedule/registry": runtimeFiles.registryFile,
1745
+ [SCHEDULE_TARGETS_ID]: runtimeFiles.targetsFile
1746
+ });
1747
+ registerNitroSchedulePlugin(nitro, runtimeFiles.pluginFile);
1748
+ });
1749
+ nitro.hooks.hook("compiled", async (currentNitro) => {
1750
+ if (!currentNitro.options.preset?.includes("vercel")) return;
1751
+ const definitions = discoverScheduleDefinitions({
1752
+ mode: "nitro-server-schedules",
1753
+ scanDirs: resolveNitroScheduleScanDirs(currentNitro.options.rootDir, currentNitro.options.scanDirs)
1754
+ });
1755
+ const crons = await readDefinitionCrons(definitions);
1756
+ await writeVercelScheduleFunctions({
1757
+ bundleAlias: currentNitro.options.alias,
1758
+ definitions,
1759
+ outputRoot: currentNitro.options.output.dir,
1760
+ registryFile: runtimeFiles.registryFile,
1761
+ rootDir: currentNitro.options.rootDir
1762
+ }, crons);
1763
+ });
1764
+ }
1765
+ };
1766
+ //#endregion
1767
+ export { schedulePackageName as a, generateProviderOutputs as i, SCHEDULE_TARGETS_ID as n, shouldSkipViteProviderBuild as o, createScheduleTargetsContents as r, scheduleNitroModule as t };