@vite-hub/schedule 0.4.1 → 0.5.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.
Files changed (53) hide show
  1. package/README.md +12 -7
  2. package/dist/{console-wEhr0LWn.d.ts → console-DFI1QBkP.d.ts} +2 -4
  3. package/dist/cron-BT3ef48f.js +68 -0
  4. package/dist/definition.d.ts +2 -4
  5. package/dist/definition.js +4 -6
  6. package/dist/{due-sOJvF_6Z.js → due-D-0trD1g.js} +23 -9
  7. package/dist/durability.d.ts +3 -5
  8. package/dist/durability.js +6 -7
  9. package/dist/{error-diagnostics-BBtYYl8j.js → error-diagnostics-B1AaIGWP.js} +2 -7
  10. package/dist/{error-diagnostics-CQ4BUqRe.js → error-diagnostics-kKXseq8d.js} +10 -3
  11. package/dist/index.d.ts +3 -13
  12. package/dist/index.js +5 -8
  13. package/dist/{started-name-ruCM1EtQ.js → inspect-CW0qwt9p.js} +3 -9
  14. package/dist/{kv-storage-2kZtP2CC.js → kv-storage-Dsr3TL9c.js} +1 -2
  15. package/dist/{kv-storage-Bm9aYLfZ.d.ts → kv-storage-hI2IOjb5.d.ts} +0 -2
  16. package/dist/{object-Da1zyPCR.js → object-CAK6UYR5.js} +1 -2
  17. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CqZkx1Rm.d.ts} +8 -6
  18. package/dist/{operations-DqwmJ8MN.js → operations-BTUQeba1.js} +7 -11
  19. package/dist/operations.d.ts +2 -6
  20. package/dist/operations.js +11 -16
  21. package/dist/os.d.ts +0 -9
  22. package/dist/os.js +23 -104
  23. package/dist/out-By90R-Bo.js +22706 -0
  24. package/dist/rolldown-runtime-DegdyBIC.js +25 -0
  25. package/dist/runtime/console.d.ts +2 -4
  26. package/dist/runtime/console.js +3 -4
  27. package/dist/runtime/kv.d.ts +2 -4
  28. package/dist/runtime/kv.js +2 -3
  29. package/dist/runtime/process.d.ts +1 -3
  30. package/dist/runtime/process.js +28 -52
  31. package/dist/runtime/state.d.ts +1 -1
  32. package/dist/runtime/state.js +1 -2
  33. package/dist/runtime/static.d.ts +2 -73
  34. package/dist/runtime/static.js +3 -2
  35. package/dist/runtime.d.ts +5 -7
  36. package/dist/runtime.js +5 -5
  37. package/dist/{started-B0pc3JY0.js → started-B1Se_Iwo.js} +6 -8
  38. package/dist/{started-Bk2Icknk.js → started-Bzvr4t5f.js} +26 -9
  39. package/dist/{started-errors-DEmYH-vp.js → started-errors-IG9DlT2A.js} +49 -12
  40. package/dist/started-name-w6n9uDdt.js +4 -0
  41. package/dist/{state-CPd10SXq.d.ts → state-BDEDVlyr.d.ts} +3 -6
  42. package/dist/{state-D4SZH6zk.js → state-BZLy46UJ.js} +73 -122
  43. package/dist/static-Bg7Jj92L.js +603 -0
  44. package/dist/static-DeRvJqcQ.d.ts +92 -0
  45. package/dist/{store-DeMojnXM.d.ts → store-CEv3cScg.d.ts} +4 -12
  46. package/dist/{time-zone-SBldrUgt.js → time-zone-pMp_g8Uu.js} +1 -2
  47. package/dist/{types-Cw5LjPuc.d.ts → types-DTVPVY5O.d.ts} +0 -2
  48. package/dist/vite.d.ts +6 -20
  49. package/dist/vite.js +2943 -297
  50. package/package.json +9 -9
  51. package/dist/invariant-DolT9EEx.js +0 -22
  52. package/dist/static-7JCga3Iu.js +0 -281
  53. package/dist/wait-until-Dy4Bn3ZN.js +0 -112
package/dist/vite.js CHANGED
@@ -1,10 +1,12 @@
1
- import { t as isIanaTimeZone } from "./time-zone-SBldrUgt.js";
2
- import { n as isRecordOrFunction, t as isRecord$1 } from "./object-Da1zyPCR.js";
3
- import { t as scheduleErrorDiagnostics } from "./error-diagnostics-BBtYYl8j.js";
4
- import { a as isAbsolute$1, i as dirname$1, o as relative$1, r as relativeDefinitionFile, s as resolve$1, t as startedSchedulesTickName } from "./started-name-ruCM1EtQ.js";
5
- import { t as internalErrorDiagnostics } from "./error-diagnostics-CQ4BUqRe.js";
6
- import { n as invariantError, t as invariant } from "./invariant-DolT9EEx.js";
7
- import { r as timeZoneOffsetMinutes } from "./due-sOJvF_6Z.js";
1
+ import { r as __toESM } from "./rolldown-runtime-DegdyBIC.js";
2
+ import { a as parseCronFields, l as invariant, u as invariantError } from "./cron-BT3ef48f.js";
3
+ import { a as relative$1, i as isAbsolute$1, n as relativeDefinitionFile, o as resolve$1, r as dirname$1 } from "./inspect-CW0qwt9p.js";
4
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-kKXseq8d.js";
5
+ import { n as isRecordOrFunction, t as isRecord$1 } from "./object-CAK6UYR5.js";
6
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-B1AaIGWP.js";
7
+ import { t as startedSchedulesTickName } from "./started-name-w6n9uDdt.js";
8
+ import { t as isIanaTimeZone } from "./time-zone-pMp_g8Uu.js";
9
+ import { i as timeZoneOffsetMinutes, t as cronWithWeekdayNames } from "./due-D-0trD1g.js";
8
10
  import { scheduleConsoleTiming } from "./runtime/console.js";
9
11
  import { builtinModules, createRequire, isBuiltin } from "node:module";
10
12
  import { formatDiagnostic } from "nostics";
@@ -13,11 +15,11 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSy
13
15
  import { tmpdir } from "node:os";
14
16
  import { basename, dirname, extname, isAbsolute, join, normalize, parse, relative, resolve, sep } from "node:path";
15
17
  import { fileURLToPath, pathToFileURL } from "node:url";
16
- import { copyFile, cp, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
18
+ import { access, chmod, copyFile, cp, lstat, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
17
19
  import { createHash, randomUUID } from "node:crypto";
18
20
  import { isDeepStrictEqual } from "node:util";
19
21
  import { parseSync } from "vite";
20
- //#region ../internal/src/build/vite.ts
22
+ // ../internal/src/build/vite.ts
21
23
  async function prepareViteHubProviderSources(plugins, sources) {
22
24
  for (const plugin of plugins) await plugin.vitehub?.providerOutput?.prepareSources?.(sources);
23
25
  }
@@ -40,6 +42,9 @@ const projectRootFileMarkers = [
40
42
  ["nuxt.config.js"],
41
43
  ["nuxt.config.mjs"]
42
44
  ];
45
+ function hasViteConfigPlugin(env, name) {
46
+ return Reflect.get(env, Symbol.for(`vitehub.config-plugin:${name}`)) === true;
47
+ }
43
48
  function createNoExternalMerger(packageName) {
44
49
  return (current) => {
45
50
  if (current === true) return true;
@@ -76,6 +81,13 @@ function createProviderOutputEnvironmentOwner(name) {
76
81
  };
77
82
  }
78
83
  const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
84
+ /** The deployment host that `vitehub()` selected, such as `"cloudflare"`. */
85
+ const VITEHUB_DEPLOYMENT_HOST = "__vitehubDeploymentHost";
86
+ /** The deployment host that `vitehub()` selected on this Vite config. */
87
+ function getDeploymentHost(config) {
88
+ const host = Reflect.get(config, VITEHUB_DEPLOYMENT_HOST);
89
+ return typeof host === "string" ? host : void 0;
90
+ }
79
91
  function includesNitroVitePlugin(value) {
80
92
  if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
81
93
  if (!value || typeof value !== "object") return false;
@@ -114,7 +126,7 @@ function hasProjectRootDirectoryMarker(root) {
114
126
  for (const marker of projectRootDirectoryMarkers) try {
115
127
  if (statSync(resolve(root, ...marker)).isDirectory()) return true;
116
128
  } catch (error) {
117
- if (error.code !== "ENOENT") throw error;
129
+ if (!isMissingProjectMarker(error)) throw error;
118
130
  }
119
131
  return false;
120
132
  }
@@ -128,13 +140,16 @@ function hasProjectRootFileMarker(root, markers) {
128
140
  try {
129
141
  if (statSync(resolve(root, ...path)).isFile()) return true;
130
142
  } catch (error) {
131
- if (error.code !== "ENOENT") throw error;
143
+ if (!isMissingProjectMarker(error)) throw error;
132
144
  }
133
145
  }
134
146
  return false;
135
147
  }
136
- //#endregion
137
- //#region ../internal/src/build/paths.ts
148
+ function isMissingProjectMarker(error) {
149
+ const code = error.code;
150
+ return code === "ENOENT" || code === "ENOTDIR";
151
+ }
152
+ // ../internal/src/build/paths.ts
138
153
  function generatedDirSegments(productName) {
139
154
  return [".vitehub", productName];
140
155
  }
@@ -180,8 +195,7 @@ function realpathIfExists(path) {
180
195
  return resolve$1(path);
181
196
  }
182
197
  }
183
- //#endregion
184
- //#region ../internal/src/build/client-output.ts
198
+ // ../internal/src/build/client-output.ts
185
199
  function hasStaticIndex(clientDir) {
186
200
  return existsSync(resolve$1(clientDir, "index.html"));
187
201
  }
@@ -218,8 +232,7 @@ async function copyClientOutput(clientDir, targetDir, excludedDirs = []) {
218
232
  filter
219
233
  });
220
234
  }
221
- //#endregion
222
- //#region ../internal/src/build/provider-output-config.ts
235
+ // ../internal/src/build/provider-output-config.ts
223
236
  function isProviderJsonArray(value, ancestors) {
224
237
  if (Object.getPrototypeOf(value) !== Array.prototype || ancestors.has(value)) return false;
225
238
  if (Reflect.ownKeys(value).length !== value.length + 1) return false;
@@ -357,8 +370,7 @@ async function cleanProviderOutputConfig(file, ownership) {
357
370
  if (!changed) return;
358
371
  await persistProviderJsonRecord(file, next, true);
359
372
  }
360
- //#endregion
361
- //#region ../internal/src/build/user-entry.ts
373
+ // ../internal/src/build/user-entry.ts
362
374
  function toSafeAppName(rootDir) {
363
375
  return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
364
376
  }
@@ -379,8 +391,7 @@ async function writeCloudflareWranglerConfig(options) {
379
391
  removeIfEmpty: true
380
392
  });
381
393
  }
382
- //#endregion
383
- //#region ../internal/src/build/bundle-options.ts
394
+ // ../internal/src/build/bundle-options.ts
384
395
  const encodedAliasPrefixMarker = "\0vitehub-prefix:";
385
396
  const encodedAliasExactMarker = "\0vitehub-exact:";
386
397
  function encodeProviderOutputAliases(configAliases) {
@@ -405,8 +416,7 @@ function resolveViteHubBundleDefines(config) {
405
416
  }
406
417
  return defines;
407
418
  }
408
- //#endregion
409
- //#region ../internal/src/build/ast-walk.ts
419
+ // ../internal/src/build/ast-walk.ts
410
420
  /** The oxc parser grammar for a file, from its extension. Defaults to TypeScript. */
411
421
  function moduleLanguage(file) {
412
422
  if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
@@ -429,8 +439,7 @@ function walk(node, visit, parent) {
429
439
  } else if (isNode(child)) walk(child, visit, node);
430
440
  }
431
441
  }
432
- //#endregion
433
- //#region ../internal/src/build/rolldown.ts
442
+ // ../internal/src/build/rolldown.ts
434
443
  const viteRawPrefix = "\0vitehub-vite-raw:";
435
444
  const markdownTemplatePrefix = "\0vitehub-markdown-template:";
436
445
  const markdownTemplateFileSuffix = ".template.md";
@@ -869,134 +878,2448 @@ function hasImportRejectionHandler(importNode, parents) {
869
878
  if (ancestor.type === "ArrowFunctionExpression" || ancestor.type === "FunctionExpression" || ancestor.type === "FunctionDeclaration") break;
870
879
  child = ancestor;
871
880
  }
872
- return false;
873
- }
874
- function createOptionalImportPlugin() {
875
- const prefix = "\0vitehub-optional-import:";
876
- return {
877
- name: "vitehub-optional-import",
878
- resolveId(source) {
879
- if (source.startsWith(prefix)) return {
880
- id: source.slice(25),
881
- external: "absolute"
882
- };
883
- },
884
- transform: {
885
- order: "post",
886
- filter: { code: /\bimport\s*(?:\(|\/)/ },
887
- async handler(code, id) {
888
- const { parseSync } = await import("vite");
889
- const module = parseSync(id, code, {
890
- lang: moduleLanguage(id),
891
- preserveParens: false,
892
- sourceType: "module"
893
- });
894
- if (module.errors.length) return;
895
- const parents = /* @__PURE__ */ new WeakMap();
896
- const handled = [];
897
- walk(module.program, (node, parent) => {
898
- if (parent) parents.set(node, parent);
899
- if (node.type !== "ImportExpression" || node.source.type !== "Literal" || typeof node.source.value !== "string") return;
900
- if (hasImportRejectionHandler(node, parents)) handled.push({
901
- source: node.source.value,
902
- start: node.source.start,
903
- end: node.source.end
904
- });
905
- });
906
- if (!handled.length) return;
907
- const resolved = await Promise.all(handled.map(({ source }) => this.resolve(source, id, { kind: "dynamic-import" })));
908
- for (const [index, { source, start, end }] of [...handled.entries()].reverse()) if (!resolved[index]) code = code.slice(0, start) + JSON.stringify(prefix + source) + code.slice(end);
909
- return code;
881
+ return false;
882
+ }
883
+ function createOptionalImportPlugin() {
884
+ const prefix = "\0vitehub-optional-import:";
885
+ return {
886
+ name: "vitehub-optional-import",
887
+ resolveId(source) {
888
+ if (source.startsWith(prefix)) return {
889
+ id: source.slice(25),
890
+ external: "absolute"
891
+ };
892
+ },
893
+ transform: {
894
+ order: "post",
895
+ filter: { code: /\bimport\s*(?:\(|\/)/ },
896
+ async handler(code, id) {
897
+ const { parseSync } = await import("vite");
898
+ const module = parseSync(id, code, {
899
+ lang: moduleLanguage(id),
900
+ preserveParens: false,
901
+ sourceType: "module"
902
+ });
903
+ if (module.errors.length) return;
904
+ const parents = /* @__PURE__ */ new WeakMap();
905
+ const handled = [];
906
+ walk(module.program, (node, parent) => {
907
+ if (parent) parents.set(node, parent);
908
+ if (node.type !== "ImportExpression" || node.source.type !== "Literal" || typeof node.source.value !== "string") return;
909
+ if (hasImportRejectionHandler(node, parents)) handled.push({
910
+ source: node.source.value,
911
+ start: node.source.start,
912
+ end: node.source.end
913
+ });
914
+ });
915
+ if (!handled.length) return;
916
+ const resolved = await Promise.all(handled.map(({ source }) => this.resolve(source, id, { kind: "dynamic-import" })));
917
+ for (const [index, { source, start, end }] of [...handled.entries()].reverse()) if (!resolved[index]) code = code.slice(0, start) + JSON.stringify(prefix + source) + code.slice(end);
918
+ return code;
919
+ }
920
+ }
921
+ };
922
+ }
923
+ /** Matches import paths as esbuild's `external` does: `*` is a wildcard, and a package name also matches its subpaths. */
924
+ function createExternalMatcher(patterns) {
925
+ if (!patterns?.length) return;
926
+ const matchers = patterns.map((pattern) => {
927
+ if (pattern.includes("*")) {
928
+ const expression = new RegExp(`^${pattern.split("*").map(escapeRegExp$1).join(".*")}$`);
929
+ return (id) => expression.test(id);
930
+ }
931
+ return isBareSpecifier(pattern) ? (id) => id === pattern || id.startsWith(`${pattern}/`) : (id) => id === pattern;
932
+ });
933
+ return (id) => matchers.some((matches) => matches(id));
934
+ }
935
+ /** Returns the modules of the chunks that no chunk loaded from the entry chunk imports. */
936
+ function findUnusedChunkModules(chunks) {
937
+ const used = new Set(chunks.filter((chunk) => chunk.isEntry));
938
+ for (const chunk of used) for (const other of chunks) if (!used.has(other) && chunk.code.includes(other.fileName)) used.add(other);
939
+ return new Set(chunks.filter((chunk) => !used.has(chunk)).flatMap((chunk) => chunk.moduleIds));
940
+ }
941
+ function createEmptyModulesPlugin(ids) {
942
+ return {
943
+ name: "vitehub-empty-unused-chunks",
944
+ load(id) {
945
+ if (ids.has(id)) return {
946
+ code: "",
947
+ moduleSideEffects: false,
948
+ moduleType: "js"
949
+ };
950
+ }
951
+ };
952
+ }
953
+ async function bundleEsmEntry(entryFile, outfile, options = {}) {
954
+ const { rolldown } = await importRolldown();
955
+ options.signal?.throwIfAborted();
956
+ const format = options.format || "esm";
957
+ const platform = options.platform || "neutral";
958
+ const workingDir = options.workingDir ?? process.cwd();
959
+ const frameworkRuntime = (Array.isArray(options.alias) ? options.alias.flatMap((alias) => typeof alias.find === "string" ? [alias.find] : []) : Object.keys(options.alias || {})).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
960
+ const plugins = [];
961
+ plugins.push(createWasmModulePlugin(dirname(outfile), workingDir, platform !== "node"));
962
+ const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), workingDir, options.resolveEntryPackageAliases);
963
+ if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
964
+ plugins.push(...options.plugins ?? [], createFileUrlPlugin());
965
+ const viteAliasPlugin = createViteAliasPlugin(options.alias, workingDir);
966
+ if (viteAliasPlugin) plugins.push(viteAliasPlugin);
967
+ plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime, workingDir));
968
+ if (options.packages === "external") plugins.push(createExternalPackagesPlugin());
969
+ plugins.push(createOptionalImportPlugin());
970
+ const isExternal = createExternalMatcher(options.external);
971
+ const minify = options.minifyIdentifiers || options.minifySyntax || options.minifyWhitespace ? {
972
+ compress: options.minifySyntax ?? false,
973
+ mangle: options.minifyIdentifiers ? { toplevel: true } : false,
974
+ codegen: { removeWhitespace: options.minifyWhitespace ?? false }
975
+ } : false;
976
+ const banner = [options.banner, ...format === "esm" && platform === "node" ? [
977
+ "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
978
+ " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
979
+ " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
980
+ " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
981
+ "}"
982
+ ] : []].filter(Boolean).join("\n");
983
+ const build = (extraPlugins = [], shimMissingExports = false) => rolldown({
984
+ cwd: workingDir,
985
+ external: isExternal ? (id) => isExternal(id) : void 0,
986
+ input: entryFile,
987
+ onLog(level, log) {
988
+ if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
989
+ },
990
+ moduleTypes: platform === "node" ? { ".wasm": "binary" } : void 0,
991
+ platform,
992
+ plugins: [...extraPlugins, ...plugins],
993
+ resolve: {
994
+ conditionNames: options.conditions ?? (platform === "node" ? ["node"] : void 0),
995
+ extensions: options.extensions,
996
+ mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
997
+ symlinks: !options.preserveSymlinks
998
+ },
999
+ shimMissingExports,
1000
+ transform: {
1001
+ define: options.define,
1002
+ target: "es2022"
1003
+ },
1004
+ tsconfig: options.tsconfig ?? true
1005
+ });
1006
+ const generate = async (bundle, codeSplitting) => (await bundle.generate({
1007
+ banner: banner || void 0,
1008
+ chunkFileNames: codeSplitting ? "chunk-[hash].js" : void 0,
1009
+ codeSplitting,
1010
+ format,
1011
+ keepNames: options.keepNames ?? Boolean(options.minifySyntax || options.minifyIdentifiers),
1012
+ minify,
1013
+ polyfillRequire: !(format === "esm" && platform === "node"),
1014
+ sourcemap: false
1015
+ })).output;
1016
+ let bundle = await build();
1017
+ let output;
1018
+ try {
1019
+ output = await generate(bundle, true);
1020
+ const chunks = output.filter((file) => file.type === "chunk");
1021
+ if (chunks.length > 1 || chunks.some((chunk) => chunk.dynamicImports.includes(chunk.fileName))) {
1022
+ options.signal?.throwIfAborted();
1023
+ const unusedModules = findUnusedChunkModules(chunks);
1024
+ if (unusedModules.size) {
1025
+ await bundle.close();
1026
+ bundle = await build([createEmptyModulesPlugin(unusedModules)], true);
1027
+ }
1028
+ output = await generate(bundle, false);
1029
+ }
1030
+ } finally {
1031
+ await bundle.close();
1032
+ }
1033
+ options.signal?.throwIfAborted();
1034
+ const chunk = output.find((file) => file.type === "chunk" && file.isEntry);
1035
+ await mkdir(dirname(outfile), { recursive: true });
1036
+ await writeFile(outfile, chunk.code, { signal: options.signal });
1037
+ options.signal?.throwIfAborted();
1038
+ }
1039
+ // ../../node_modules/.pnpm/balanced-match@4.0.4/node_modules/balanced-match/dist/esm/index.js
1040
+ const balanced = (a, b, str) => {
1041
+ const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
1042
+ const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
1043
+ const r = ma !== null && mb != null && range(ma, mb, str);
1044
+ return r && {
1045
+ start: r[0],
1046
+ end: r[1],
1047
+ pre: str.slice(0, r[0]),
1048
+ body: str.slice(r[0] + ma.length, r[1]),
1049
+ post: str.slice(r[1] + mb.length)
1050
+ };
1051
+ };
1052
+ const maybeMatch = (reg, str) => {
1053
+ const m = str.match(reg);
1054
+ return m ? m[0] : null;
1055
+ };
1056
+ const range = (a, b, str) => {
1057
+ let begs, beg, left, right = void 0, result;
1058
+ let ai = str.indexOf(a);
1059
+ let bi = str.indexOf(b, ai + 1);
1060
+ let i = ai;
1061
+ if (ai >= 0 && bi > 0) {
1062
+ if (a === b) return [ai, bi];
1063
+ begs = [];
1064
+ left = str.length;
1065
+ while (i >= 0 && !result) {
1066
+ if (i === ai) {
1067
+ begs.push(i);
1068
+ ai = str.indexOf(a, i + 1);
1069
+ } else if (begs.length === 1) {
1070
+ const r = begs.pop();
1071
+ if (r !== void 0) result = [r, bi];
1072
+ } else {
1073
+ beg = begs.pop();
1074
+ if (beg !== void 0 && beg < left) {
1075
+ left = beg;
1076
+ right = bi;
1077
+ }
1078
+ bi = str.indexOf(b, i + 1);
1079
+ }
1080
+ i = ai < bi && ai >= 0 ? ai : bi;
1081
+ }
1082
+ if (begs.length && right !== void 0) result = [left, right];
1083
+ }
1084
+ return result;
1085
+ };
1086
+ // ../../node_modules/.pnpm/brace-expansion@5.0.12/node_modules/brace-expansion/dist/esm/index.js
1087
+ const escSlash = "\0SLASH" + Math.random() + "\0";
1088
+ const escOpen = "\0OPEN" + Math.random() + "\0";
1089
+ const escClose = "\0CLOSE" + Math.random() + "\0";
1090
+ const escComma = "\0COMMA" + Math.random() + "\0";
1091
+ const escPeriod = "\0PERIOD" + Math.random() + "\0";
1092
+ const escSlashPattern = new RegExp(escSlash, "g");
1093
+ const escOpenPattern = new RegExp(escOpen, "g");
1094
+ const escClosePattern = new RegExp(escClose, "g");
1095
+ const escCommaPattern = new RegExp(escComma, "g");
1096
+ const escPeriodPattern = new RegExp(escPeriod, "g");
1097
+ const slashPattern = /\\\\/g;
1098
+ const openPattern = /\\{/g;
1099
+ const closePattern = /\\}/g;
1100
+ const commaPattern = /\\,/g;
1101
+ const periodPattern = /\\\./g;
1102
+ const EXPANSION_MAX = 1e5;
1103
+ const EXPANSION_MAX_LENGTH = 4e6;
1104
+ const EXPANSION_MAX_DEPTH = 1e3;
1105
+ const EXPANSION_MAX_REWRITES = 1e3;
1106
+ function numeric(str) {
1107
+ return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
1108
+ }
1109
+ function escapeBraces(str) {
1110
+ return str.replace(slashPattern, escSlash).replace(openPattern, escOpen).replace(closePattern, escClose).replace(commaPattern, escComma).replace(periodPattern, escPeriod);
1111
+ }
1112
+ function unescapeBraces(str) {
1113
+ return str.replace(escSlashPattern, "\\").replace(escOpenPattern, "{").replace(escClosePattern, "}").replace(escCommaPattern, ",").replace(escPeriodPattern, ".");
1114
+ }
1115
+ function pushAll(target, items) {
1116
+ for (let i = 0; i < items.length; i++) target.push(items[i]);
1117
+ }
1118
+ /**
1119
+ * Basically just str.split(","), but handling cases
1120
+ * where we have nested braced sections, which should be
1121
+ * treated as individual members, like {a,{b,c},d}
1122
+ */
1123
+ function parseCommaParts(str) {
1124
+ const parts = [];
1125
+ let carry = "";
1126
+ for (;;) {
1127
+ const m = balanced("{", "}", str);
1128
+ if (!m) {
1129
+ const tail = str.split(",");
1130
+ tail[0] = carry + tail[0];
1131
+ pushAll(parts, tail);
1132
+ return parts;
1133
+ }
1134
+ const { pre, body, post } = m;
1135
+ const p = pre.split(",");
1136
+ p[0] = carry + p[0];
1137
+ p[p.length - 1] += "{" + body + "}";
1138
+ if (!post.length) {
1139
+ pushAll(parts, p);
1140
+ return parts;
1141
+ }
1142
+ carry = p.pop();
1143
+ pushAll(parts, p);
1144
+ str = post;
1145
+ }
1146
+ }
1147
+ function expand(str, options = {}) {
1148
+ if (!str) return [];
1149
+ const { max = EXPANSION_MAX, maxLength = EXPANSION_MAX_LENGTH, maxDepth = EXPANSION_MAX_DEPTH, maxRewrites = EXPANSION_MAX_REWRITES } = options;
1150
+ if (str.slice(0, 2) === "{}") str = "\\{\\}" + str.slice(2);
1151
+ return expand_(escapeBraces(str), max, maxLength, maxDepth, 0, maxRewrites, true).map(unescapeBraces);
1152
+ }
1153
+ function embrace(str) {
1154
+ return "{" + str + "}";
1155
+ }
1156
+ function isPadded(el) {
1157
+ return /^-?0\d/.test(el);
1158
+ }
1159
+ function lte(i, y) {
1160
+ return i <= y;
1161
+ }
1162
+ function gte(i, y) {
1163
+ return i >= y;
1164
+ }
1165
+ function combine(acc, pre, values, max, maxLength, dropEmpties) {
1166
+ const out = [];
1167
+ let length = 0;
1168
+ for (let a = 0; a < acc.length; a++) for (let v = 0; v < values.length; v++) {
1169
+ if (out.length >= max) return out;
1170
+ const expansion = acc[a] + pre + values[v];
1171
+ if (dropEmpties && !expansion) continue;
1172
+ if (length + expansion.length > maxLength) return out;
1173
+ out.push(expansion);
1174
+ length += expansion.length;
1175
+ }
1176
+ return out;
1177
+ }
1178
+ function expandSequence(body, isAlphaSequence, max, maxLength) {
1179
+ const n = body.split(/\.\./);
1180
+ const N = [];
1181
+ /* c8 ignore start */
1182
+ if (n[0] === void 0 || n[1] === void 0) return N;
1183
+ /* c8 ignore stop */
1184
+ const x = numeric(n[0]);
1185
+ const y = numeric(n[1]);
1186
+ const width = Math.max(n[0].length, n[1].length);
1187
+ let incr = n.length === 3 && n[2] !== void 0 ? Math.max(Math.abs(numeric(n[2])), 1) : 1;
1188
+ let test = lte;
1189
+ if (y < x) {
1190
+ incr *= -1;
1191
+ test = gte;
1192
+ }
1193
+ const pad = n.some(isPadded);
1194
+ let length = 0;
1195
+ for (let i = x; test(i, y) && N.length < max; i += incr) {
1196
+ let c;
1197
+ if (isAlphaSequence) {
1198
+ c = String.fromCharCode(i);
1199
+ if (c === "\\") c = "";
1200
+ } else {
1201
+ c = String(i);
1202
+ if (pad) {
1203
+ const need = width - c.length;
1204
+ if (need > 0) {
1205
+ const z = new Array(need + 1).join("0");
1206
+ if (i < 0) c = "-" + z + c.slice(1);
1207
+ else c = z + c;
1208
+ }
1209
+ }
1210
+ }
1211
+ if (length + c.length > maxLength) break;
1212
+ N.push(c);
1213
+ length += c.length;
1214
+ }
1215
+ return N;
1216
+ }
1217
+ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) {
1218
+ if (depth > maxDepth) return [str];
1219
+ let acc = [""];
1220
+ let rewrites = 0;
1221
+ let dropEmpties = false;
1222
+ let firstGroup = true;
1223
+ for (;;) {
1224
+ const m = balanced("{", "}", str);
1225
+ if (!m) return combine(acc, str, [""], max, maxLength, dropEmpties);
1226
+ const pre = m.pre;
1227
+ if (/\$$/.test(pre)) {
1228
+ acc = combine(acc, pre + "{" + m.body + "}", [""], max, maxLength, dropEmpties && !m.post.length);
1229
+ firstGroup = false;
1230
+ if (!m.post.length) break;
1231
+ str = m.post;
1232
+ continue;
1233
+ }
1234
+ const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
1235
+ const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
1236
+ const isSequence = isNumericSequence || isAlphaSequence;
1237
+ const isOptions = m.body.indexOf(",") >= 0;
1238
+ if (!isSequence && !isOptions) {
1239
+ if (rewrites < maxRewrites && m.post.match(/,(?!,).*\}/)) {
1240
+ rewrites++;
1241
+ str = m.pre + "{" + m.body + escClose + m.post;
1242
+ isTop = true;
1243
+ continue;
1244
+ }
1245
+ return combine(acc, pre + "{" + m.body + "}" + m.post, [""], max, maxLength, dropEmpties);
1246
+ }
1247
+ if (firstGroup) {
1248
+ dropEmpties = isTop && !isSequence;
1249
+ firstGroup = false;
1250
+ }
1251
+ let values;
1252
+ if (isSequence) values = expandSequence(m.body, isAlphaSequence, max, maxLength);
1253
+ else {
1254
+ let n = parseCommaParts(m.body);
1255
+ if (n.length === 1 && n[0] !== void 0) {
1256
+ n = expand_(n[0], max, maxLength, maxDepth, depth + 1, maxRewrites, false).map(embrace);
1257
+ /* c8 ignore start */
1258
+ if (n.length === 1) {
1259
+ acc = combine(acc, pre + n[0], [""], max, maxLength, dropEmpties && !m.post.length);
1260
+ if (!m.post.length) break;
1261
+ str = m.post;
1262
+ continue;
1263
+ }
1264
+ }
1265
+ let dropsEmpties = dropEmpties && !m.post.length && !pre;
1266
+ for (let d = 0; dropsEmpties && d < acc.length; d++) if (acc[d]) dropsEmpties = false;
1267
+ values = [];
1268
+ let valuesLength = 0;
1269
+ outer: for (let j = 0; j < n.length; j++) {
1270
+ const expanded = expand_(n[j], max, maxLength, maxDepth, depth + 1, maxRewrites, false);
1271
+ for (let k = 0; k < expanded.length; k++) {
1272
+ const v = expanded[k];
1273
+ if (dropsEmpties && !v) continue;
1274
+ if (values.length >= max || valuesLength + v.length > maxLength) break outer;
1275
+ values.push(v);
1276
+ valuesLength += v.length;
1277
+ }
1278
+ }
1279
+ }
1280
+ acc = combine(acc, pre, values, max, maxLength, dropEmpties && !m.post.length);
1281
+ if (!m.post.length) break;
1282
+ str = m.post;
1283
+ }
1284
+ return acc;
1285
+ }
1286
+ // ../../node_modules/.pnpm/@isaacs+nonrecursive-glob-match@1.1.0/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/numeric-range.js
1287
+ const digit = (a, b) => a === b ? {
1288
+ t: "lit",
1289
+ ch: String(a)
1290
+ } : {
1291
+ t: "class",
1292
+ re: new RegExp(`^[${a}-${b}]$`)
1293
+ };
1294
+ const prefix = (d, alts) => alts.map((s) => [digit(d, d), ...s]);
1295
+ const fixed = (a, b) => {
1296
+ if (!a) return [[]];
1297
+ let lo = +a[0];
1298
+ let hi = +b[0];
1299
+ const ra = a.slice(1);
1300
+ const rb = b.slice(1);
1301
+ if (lo === hi) return prefix(lo, fixed(ra, rb));
1302
+ const zeros = "0".repeat(ra.length);
1303
+ const nines = "9".repeat(ra.length);
1304
+ const out = [];
1305
+ if (ra !== zeros) out.push(...prefix(lo++, fixed(ra, nines)));
1306
+ const last = rb === nines ? [] : prefix(hi--, fixed(zeros, rb));
1307
+ if (lo <= hi) out.push([digit(lo, hi), ...Array.from(ra, () => digit(0, 9))]);
1308
+ out.push(...last);
1309
+ return out;
1310
+ };
1311
+ const nonneg = (a, b, width) => {
1312
+ if (width) return fixed(String(a).padStart(width, "0"), String(b).padStart(width, "0"));
1313
+ const out = [];
1314
+ for (let len = String(a).length; len <= String(b).length; len++) {
1315
+ const lo = Math.max(a, len === 1 ? 0 : 10 ** (len - 1));
1316
+ const hi = Math.min(b, 10 ** len - 1);
1317
+ out.push(...fixed(String(lo), String(hi)));
1318
+ }
1319
+ return out;
1320
+ };
1321
+ /**
1322
+ * The strings that the bash brace expansion `{lo..hi}` makes, as
1323
+ * the alternatives of an `@(...)` extglob. Each one is a sequence of
1324
+ * digits and digit classes, so there are only a few of them, even for
1325
+ * a large range.
1326
+ *
1327
+ * If either end has a leading zero, such as `{01..10}`, each number
1328
+ * has leading zeros to make it as long as the longer end, counting a
1329
+ * `-` sign. So `{-05..3}` makes `-05` to `-01`, then `000` to `003`.
1330
+ *
1331
+ * Returns undefined if either end is not a safe integer.
1332
+ */
1333
+ const numericRange = (loStr, hiStr) => {
1334
+ let lo = Number(loStr);
1335
+ let hi = Number(hiStr);
1336
+ if (!Number.isSafeInteger(lo) || !Number.isSafeInteger(hi)) return;
1337
+ if (lo > hi) [lo, hi] = [hi, lo];
1338
+ const width = /^-?0\d/.test(loStr) || /^-?0\d/.test(hiStr) ? Math.max(loStr.length, hiStr.length) : 0;
1339
+ const out = [];
1340
+ if (lo < 0) {
1341
+ const neg = nonneg(Math.max(-hi, 1), -lo, width && width - 1);
1342
+ out.push(...neg.map((s) => [{
1343
+ t: "lit",
1344
+ ch: "-"
1345
+ }, ...s]));
1346
+ }
1347
+ if (hi >= 0) out.push(...nonneg(Math.max(lo, 0), hi, width));
1348
+ return out;
1349
+ };
1350
+ // ../../node_modules/.pnpm/@isaacs+nonrecursive-glob-match@1.1.0/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/parse-class.js
1351
+ const posixClasses = {
1352
+ "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}"],
1353
+ "[:alpha:]": ["\\p{L}\\p{Nl}"],
1354
+ "[:ascii:]": ["\\x00-\\x7f"],
1355
+ "[:blank:]": ["\\p{Zs}\\t"],
1356
+ "[:cntrl:]": ["\\p{Cc}"],
1357
+ "[:digit:]": ["\\p{Nd}"],
1358
+ "[:graph:]": ["\\p{Z}\\p{C}", true],
1359
+ "[:lower:]": ["\\p{Ll}"],
1360
+ "[:print:]": ["\\p{C}", true],
1361
+ "[:punct:]": ["\\p{P}\\p{S}"],
1362
+ "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f"],
1363
+ "[:upper:]": ["\\p{Lu}"],
1364
+ "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}"],
1365
+ "[:xdigit:]": ["A-Fa-f0-9"]
1366
+ };
1367
+ const braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&");
1368
+ const noMatch = /$./;
1369
+ const parseClass = (glob, position, nocase = false, form) => {
1370
+ const norm = (c) => {
1371
+ const n = form ? c.normalize(form) : c;
1372
+ return [...n].length === 1 ? n : c;
1373
+ };
1374
+ const pos = position;
1375
+ /* c8 ignore start */
1376
+ if (glob.charAt(pos) !== "[") throw new Error("not in a brace expression");
1377
+ /* c8 ignore stop */
1378
+ const ranges = [];
1379
+ const negs = [];
1380
+ let i = pos + 1;
1381
+ let sawStart = false;
1382
+ let escaping = false;
1383
+ let negate = false;
1384
+ let endPos = pos;
1385
+ let rangeStart = "";
1386
+ WHILE: while (i < glob.length) {
1387
+ const c = String.fromCodePoint(glob.codePointAt(i));
1388
+ if ((c === "!" || c === "^") && i === pos + 1) {
1389
+ negate = true;
1390
+ i++;
1391
+ continue;
1392
+ }
1393
+ if (c === "]" && sawStart && !escaping) {
1394
+ endPos = i + 1;
1395
+ break;
1396
+ }
1397
+ sawStart = true;
1398
+ if (c === "\\") {
1399
+ if (!escaping) {
1400
+ escaping = true;
1401
+ i++;
1402
+ continue;
1403
+ }
1404
+ }
1405
+ if (c === "[" && !escaping) {
1406
+ for (const [cls, [unip, neg]] of Object.entries(posixClasses)) if (glob.startsWith(cls, i)) {
1407
+ if (rangeStart) return [noMatch, glob.length - pos];
1408
+ i += cls.length;
1409
+ if (neg) negs.push(unip);
1410
+ else ranges.push(unip);
1411
+ continue WHILE;
1412
+ }
1413
+ }
1414
+ escaping = false;
1415
+ const n = norm(c);
1416
+ if (rangeStart) {
1417
+ if (n.codePointAt(0) > rangeStart.codePointAt(0)) ranges.push(braceEscape(rangeStart) + "-" + braceEscape(n));
1418
+ else if (n === rangeStart) ranges.push(braceEscape(n));
1419
+ rangeStart = "";
1420
+ i += c.length;
1421
+ continue;
1422
+ }
1423
+ if (glob.startsWith("-]", i + c.length)) {
1424
+ ranges.push(braceEscape(n + "-"));
1425
+ i += c.length + 1;
1426
+ continue;
1427
+ }
1428
+ if (glob.startsWith("-", i + c.length)) {
1429
+ rangeStart = n;
1430
+ i += c.length + 1;
1431
+ continue;
1432
+ }
1433
+ ranges.push(braceEscape(n));
1434
+ i += c.length;
1435
+ }
1436
+ if (endPos < i) return [noMatch, 0];
1437
+ if (!ranges.length && !negs.length) return [noMatch, glob.length - pos];
1438
+ const sranges = "[" + (negate ? "^" : "") + ranges.join("") + "]";
1439
+ const snegs = "[" + (negate ? "" : "^") + negs.join("") + "]";
1440
+ const comb = "^" + (ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs);
1441
+ return [new RegExp(comb, nocase ? "iu" : "u"), endPos - pos];
1442
+ };
1443
+ // ../../node_modules/.pnpm/@isaacs+nonrecursive-glob-match@1.1.0/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.js
1444
+ const MATCH = {
1445
+ t: "match",
1446
+ id: 0
1447
+ };
1448
+ const extTypes = "!?+*@";
1449
+ const lit = (ch) => ({
1450
+ t: "lit",
1451
+ ch
1452
+ });
1453
+ const reEscape = (s) => s.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&");
1454
+ const newFoldRe = (s) => new RegExp(`^${reEscape(s)}$`, "iu");
1455
+ const foldCache = /* @__PURE__ */ new Map();
1456
+ const foldRe = (ch) => {
1457
+ let re = foldCache.get(ch);
1458
+ if (!re) {
1459
+ re = newFoldRe(ch);
1460
+ if (foldCache.size >= 1e3) foldCache.clear();
1461
+ foldCache.set(ch, re);
1462
+ }
1463
+ return re;
1464
+ };
1465
+ const litMatch = (l, c) => {
1466
+ if (c === l.ch) return true;
1467
+ if (!l.re) return false;
1468
+ const code = c.charCodeAt(0);
1469
+ if (code >= 128) return l.re.test(c);
1470
+ const ascii = l.ascii ??= /* @__PURE__ */ new Uint8Array(128);
1471
+ ascii[code] ||= l.re.test(c) ? 1 : 2;
1472
+ return ascii[code] === 1;
1473
+ };
1474
+ const tokenize = (p, nocase, noext, form, mark) => {
1475
+ const toks = [];
1476
+ for (let i = 0; i < p.length;) {
1477
+ const c = String.fromCodePoint(p.codePointAt(i));
1478
+ if (mark) {
1479
+ const m = c === "\\" && p.startsWith(mark, i + 1) ? 1 : 0;
1480
+ if (m || c === mark) {
1481
+ const start = i + m + mark.length;
1482
+ const end = p.indexOf(mark, start);
1483
+ const r = /^(-?\d+)\.\.(-?\d+)$/.exec(p.slice(start, end));
1484
+ const alts = end !== -1 && r && numericRange(r[1], r[2]);
1485
+ if (alts) {
1486
+ toks.push({
1487
+ t: "ext",
1488
+ type: "@",
1489
+ alts
1490
+ });
1491
+ i = end + mark.length;
1492
+ continue;
1493
+ }
1494
+ }
1495
+ }
1496
+ if (c === "\\") {
1497
+ const e = p.codePointAt(i + 1);
1498
+ const ch = e === void 0 ? c : String.fromCodePoint(e);
1499
+ toks.push(lit(ch));
1500
+ i += 1 + ch.length;
1501
+ continue;
1502
+ }
1503
+ if (c === "[") {
1504
+ const [re, consumed] = parseClass(p, i, nocase, form);
1505
+ if (consumed) {
1506
+ toks.push({
1507
+ t: "class",
1508
+ re
1509
+ });
1510
+ i += consumed;
1511
+ continue;
1512
+ }
1513
+ }
1514
+ if (!noext && extTypes.includes(c) && p[i + 1] === "(") {
1515
+ toks.push({
1516
+ t: "open",
1517
+ type: c
1518
+ });
1519
+ i += 2;
1520
+ continue;
1521
+ }
1522
+ toks.push(!noext && c === "|" ? { t: "bar" } : !noext && c === ")" ? { t: "close" } : c === "*" ? { t: "star" } : c === "?" ? { t: "any" } : lit(c));
1523
+ i += c.length;
1524
+ }
1525
+ return toks;
1526
+ };
1527
+ const pair = (toks) => {
1528
+ const pairs = /* @__PURE__ */ new Map();
1529
+ const stack = [];
1530
+ toks.forEach((tok, i) => {
1531
+ if (tok.t === "open") stack.push(i);
1532
+ else if (tok.t === "close" && stack.length) pairs.set(stack.pop(), i);
1533
+ });
1534
+ return pairs;
1535
+ };
1536
+ const build = (toks, pairs, start, end, top) => {
1537
+ let seq = [];
1538
+ const alts = [seq];
1539
+ for (let i = start; i < end; i++) {
1540
+ const tok = toks[i];
1541
+ const close = pairs.get(i);
1542
+ if (tok.t === "open" && close !== void 0) {
1543
+ const sub = build(toks, pairs, i + 1, close, false);
1544
+ seq.push({
1545
+ t: "ext",
1546
+ type: tok.type,
1547
+ alts: sub
1548
+ });
1549
+ i = close;
1550
+ } else if (tok.t === "bar" && !top) alts.push(seq = []);
1551
+ else if (tok.t === "open") seq.push(lit(tok.type), lit("("));
1552
+ else if (tok.t === "bar") seq.push(lit("|"));
1553
+ else if (tok.t === "close") seq.push(lit(")"));
1554
+ else seq.push(tok);
1555
+ }
1556
+ return alts;
1557
+ };
1558
+ const normalize$1 = (items, form) => {
1559
+ const out = [];
1560
+ let run = "";
1561
+ const flush = () => {
1562
+ for (const ch of run.normalize(form)) out.push(lit(ch));
1563
+ run = "";
1564
+ };
1565
+ for (const it of items) {
1566
+ if (it.t === "lit") {
1567
+ run += it.ch;
1568
+ continue;
1569
+ }
1570
+ flush();
1571
+ out.push(it.t === "ext" ? {
1572
+ ...it,
1573
+ alts: it.alts.map((a) => normalize$1(a, form))
1574
+ } : it);
1575
+ }
1576
+ flush();
1577
+ return out;
1578
+ };
1579
+ const compile = (items, nocase) => {
1580
+ let id = 1;
1581
+ const split = (out) => ({
1582
+ t: "split",
1583
+ id: id++,
1584
+ out
1585
+ });
1586
+ const seq = (items, next) => items.reduceRight((next, it) => item(it, next), next);
1587
+ const item = (it, next) => {
1588
+ switch (it.t) {
1589
+ case "lit":
1590
+ const re = nocase ? foldRe(it.ch) : void 0;
1591
+ return {
1592
+ t: "lit",
1593
+ id: id++,
1594
+ ch: it.ch,
1595
+ re,
1596
+ next
1597
+ };
1598
+ case "any":
1599
+ case "star": return {
1600
+ t: it.t,
1601
+ id: id++,
1602
+ next
1603
+ };
1604
+ case "class": return {
1605
+ t: "class",
1606
+ id: id++,
1607
+ re: it.re,
1608
+ next
1609
+ };
1610
+ }
1611
+ const alts = (next) => it.alts.map((a) => seq(a, next));
1612
+ switch (it.type) {
1613
+ case "@": return split(alts(next));
1614
+ case "?": return split([next, ...alts(next)]);
1615
+ case "!": return {
1616
+ t: "neg",
1617
+ id: id++,
1618
+ sub: split(alts(MATCH)),
1619
+ next
1620
+ };
1621
+ }
1622
+ const after = split([]);
1623
+ const entry = split(alts(after));
1624
+ after.out.push(next, entry);
1625
+ return it.type === "*" ? after : entry;
1626
+ };
1627
+ return [seq(items, MATCH), id];
1628
+ };
1629
+ const show = (start) => {
1630
+ const lines = [];
1631
+ const seen = /* @__PURE__ */ new Set();
1632
+ const ref = (n) => n.t === "match" ? "match" : String(n.id);
1633
+ const walk = (n, indent) => {
1634
+ if (n.t === "match" || seen.has(n)) return;
1635
+ seen.add(n);
1636
+ const line = (desc) => lines.push(`${indent}${n.id}: ${desc}`);
1637
+ switch (n.t) {
1638
+ case "split":
1639
+ line(`split -> ${n.out.map(ref).join(", ")}`);
1640
+ for (const o of n.out) walk(o, indent);
1641
+ return;
1642
+ case "neg":
1643
+ line(`!(${ref(n.sub)}) -> ${ref(n.next)}`);
1644
+ walk(n.sub, indent + " ");
1645
+ return walk(n.next, indent);
1646
+ case "lit":
1647
+ line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`);
1648
+ break;
1649
+ case "class":
1650
+ line(`${n.re} -> ${ref(n.next)}`);
1651
+ break;
1652
+ default: line(`${n.t === "any" ? "?" : "*"} -> ${ref(n.next)}`);
1653
+ }
1654
+ walk(n.next, indent);
1655
+ };
1656
+ walk(start, "");
1657
+ return [`start -> ${ref(start)}`, ...lines].join("\n");
1658
+ };
1659
+ var State = class {
1660
+ gen;
1661
+ threads = [];
1662
+ match = false;
1663
+ runs = [];
1664
+ ids = [];
1665
+ constructor(gen) {
1666
+ this.gen = gen;
1667
+ }
1668
+ get dead() {
1669
+ return !this.threads.length && !this.match && !this.runs.length;
1670
+ }
1671
+ };
1672
+ const sameState = (a, b) => {
1673
+ if (a.ids.length !== b.ids.length) return false;
1674
+ if (a.runs.length !== b.runs.length) return false;
1675
+ if (a.ids.some((id, i) => id !== b.ids[i])) return false;
1676
+ return a.runs.every((r) => b.runs.some((o) => o.neg === r.neg && sameState(o.state, r.state)));
1677
+ };
1678
+ const marks = (size) => ({
1679
+ has: new Float64Array(size),
1680
+ seen: new Float64Array(size),
1681
+ gen: 0
1682
+ });
1683
+ var Sim = class {
1684
+ dots;
1685
+ dotStart;
1686
+ #marks;
1687
+ constructor(dots, dotStart, marks) {
1688
+ this.dots = dots;
1689
+ this.dotStart = dotStart;
1690
+ this.#marks = marks;
1691
+ }
1692
+ state() {
1693
+ return new State(++this.#marks.gen);
1694
+ }
1695
+ done(state) {
1696
+ state.ids = state.threads.map((n) => n.id).sort((a, b) => a - b);
1697
+ if (state.match) state.ids.unshift(MATCH.id);
1698
+ return state;
1699
+ }
1700
+ #visit(state, node) {
1701
+ const { seen } = this.#marks;
1702
+ if (seen[node.id] === state.gen) return false;
1703
+ seen[node.id] = state.gen;
1704
+ return true;
1705
+ }
1706
+ #addThread(state, node) {
1707
+ const { has } = this.#marks;
1708
+ if (has[node.id] === state.gen) return false;
1709
+ has[node.id] = state.gen;
1710
+ state.threads.push(node);
1711
+ return true;
1712
+ }
1713
+ restricted(i, top) {
1714
+ return top && (this.dots || this.dotStart && i === 0);
1715
+ }
1716
+ add(state, node, i, top) {
1717
+ switch (node.t) {
1718
+ case "split":
1719
+ if (!this.#visit(state, node)) return;
1720
+ for (const o of node.out) this.add(state, o, i, top);
1721
+ return;
1722
+ case "neg":
1723
+ if (!this.#visit(state, node)) return;
1724
+ const sub = this.state();
1725
+ this.add(sub, node.sub, i, false);
1726
+ this.done(sub);
1727
+ return this.addRun(state, {
1728
+ t: "run",
1729
+ neg: node,
1730
+ state: sub
1731
+ }, i, top);
1732
+ case "star":
1733
+ if (this.restricted(i, top)) return;
1734
+ if (this.#addThread(state, node)) this.add(state, node.next, i, top);
1735
+ return;
1736
+ case "match":
1737
+ state.match = true;
1738
+ return;
1739
+ default: this.#addThread(state, node);
1740
+ }
1741
+ }
1742
+ addRun(state, run, i, top) {
1743
+ for (const r of state.runs) if (r.neg === run.neg && sameState(r.state, run.state)) return;
1744
+ state.runs.push(run);
1745
+ if (!run.state.match) this.add(state, run.neg.next, i, top);
1746
+ }
1747
+ step(state, c, i, top) {
1748
+ const next = this.state();
1749
+ for (const th of state.threads) switch (th.t) {
1750
+ case "lit":
1751
+ if (litMatch(th, c)) this.add(next, th.next, i + 1, top);
1752
+ break;
1753
+ case "any":
1754
+ if (!this.restricted(i, top)) this.add(next, th.next, i + 1, top);
1755
+ break;
1756
+ case "class":
1757
+ if (!this.restricted(i, top) && th.re.test(c)) this.add(next, th.next, i + 1, top);
1758
+ break;
1759
+ case "star": if (!this.restricted(i, top)) this.add(next, th, i + 1, top);
1760
+ }
1761
+ if (!this.restricted(i, top)) for (const run of state.runs) {
1762
+ if (run.state.dead) {
1763
+ this.addRun(next, run, i + 1, top);
1764
+ continue;
1765
+ }
1766
+ const sub = this.step(run.state, c, i, false);
1767
+ this.addRun(next, {
1768
+ t: "run",
1769
+ neg: run.neg,
1770
+ state: sub
1771
+ }, i + 1, top);
1772
+ }
1773
+ return this.done(next);
1774
+ }
1775
+ };
1776
+ const stateKey = (state) => {
1777
+ const ids = state.ids.join();
1778
+ if (!state.runs.length) return ids;
1779
+ return `${ids}|${state.runs.map((r) => `${r.neg.id}(${stateKey(r.state)})`).sort().join("|")}`;
1780
+ };
1781
+ const DFA_BUDGET = 1 << 18;
1782
+ var Dfa = class {
1783
+ #start;
1784
+ #states = /* @__PURE__ */ new Map();
1785
+ #size = 0;
1786
+ #plain;
1787
+ #dotStart;
1788
+ #sim;
1789
+ #dotSim;
1790
+ constructor(start, marks) {
1791
+ this.#start = start;
1792
+ this.#sim = new Sim(false, false, marks);
1793
+ this.#dotSim = new Sim(false, true, marks);
1794
+ }
1795
+ #make(state) {
1796
+ return {
1797
+ state,
1798
+ match: state.match,
1799
+ dead: state.dead,
1800
+ next: /* @__PURE__ */ new Map()
1801
+ };
1802
+ }
1803
+ #intern(state) {
1804
+ const key = stateKey(state);
1805
+ const found = this.#states.get(key);
1806
+ if (found) return found;
1807
+ if (this.#size > DFA_BUDGET) this.#clear();
1808
+ const d = this.#make(state);
1809
+ this.#states.set(key, d);
1810
+ this.#size += key.length + 1;
1811
+ return d;
1812
+ }
1813
+ #clear() {
1814
+ this.#states.clear();
1815
+ this.#size = 0;
1816
+ this.#plain = void 0;
1817
+ this.#dotStart = void 0;
1818
+ }
1819
+ start(dotStart) {
1820
+ if (dotStart) {
1821
+ if (this.#dotStart) return this.#dotStart;
1822
+ const state = this.#dotSim.state();
1823
+ this.#dotSim.add(state, this.#start, 0, true);
1824
+ return this.#dotStart = this.#make(this.#dotSim.done(state));
1825
+ }
1826
+ if (this.#plain) return this.#plain;
1827
+ const state = this.#sim.state();
1828
+ this.#sim.add(state, this.#start, 0, true);
1829
+ return this.#plain = this.#intern(this.#sim.done(state));
1830
+ }
1831
+ next(d, c) {
1832
+ const code = c.charCodeAt(0);
1833
+ const found = code < 128 ? void 0 : d.next.get(c);
1834
+ if (found) return found;
1835
+ const n = d === this.#dotStart ? this.#intern(this.#dotSim.step(d.state, c, 0, true)) : this.#intern(this.#sim.step(d.state, c, 1, true));
1836
+ if (code < 128) {
1837
+ if (!d.ascii) {
1838
+ d.ascii = new Array(128);
1839
+ this.#size += 128;
1840
+ }
1841
+ d.ascii[code] = n;
1842
+ } else d.next.set(c, n);
1843
+ this.#size++;
1844
+ return n;
1845
+ }
1846
+ };
1847
+ const linear = (start) => {
1848
+ const nodes = [];
1849
+ for (let n = start; n.t !== "match"; n = n.next) {
1850
+ if (n.t === "split" || n.t === "neg") return void 0;
1851
+ nodes.push(n);
1852
+ }
1853
+ return nodes;
1854
+ };
1855
+ const testLinear = (nodes, chars, start, end) => {
1856
+ let ni = 0;
1857
+ let ci = start;
1858
+ let starNi = -1;
1859
+ let starCi = 0;
1860
+ while (ci < end) {
1861
+ const n = nodes[ni];
1862
+ if (n?.t === "star") {
1863
+ starNi = ni++;
1864
+ starCi = ci;
1865
+ continue;
1866
+ }
1867
+ const c = chars[ci];
1868
+ if (n && (n.t === "any" || n.t === "lit" && litMatch(n, c) || n.t === "class" && n.re.test(c))) {
1869
+ ni++;
1870
+ ci++;
1871
+ continue;
1872
+ }
1873
+ if (starNi === -1) return false;
1874
+ ni = starNi + 1;
1875
+ ci = ++starCi;
1876
+ }
1877
+ while (nodes[ni]?.t === "star") ni++;
1878
+ return ni === nodes.length;
1879
+ };
1880
+ const lengths = (items) => {
1881
+ let min = 0;
1882
+ let max = 0;
1883
+ for (const it of items) {
1884
+ const [lo, hi] = itemLengths(it);
1885
+ min += lo;
1886
+ max += hi;
1887
+ }
1888
+ return [min, max];
1889
+ };
1890
+ const itemLengths = (it) => {
1891
+ if (it.t === "star") return [0, Infinity];
1892
+ if (it.t !== "ext") return [1, 1];
1893
+ if (it.type === "!") return [0, Infinity];
1894
+ const alts = it.alts.map(lengths);
1895
+ const min = Math.min(...alts.map((a) => a[0]));
1896
+ const max = Math.max(...alts.map((a) => a[1]));
1897
+ const loop = max === 0 ? 0 : Infinity;
1898
+ return it.type === "@" ? [min, max] : it.type === "?" ? [0, max] : it.type === "*" ? [0, loop] : [min, loop];
1899
+ };
1900
+ const hasAffix = (lits, chars, start) => {
1901
+ for (let j = 0; j < lits.length; j++) if (!litMatch(lits[j], chars[start + j])) return false;
1902
+ return true;
1903
+ };
1904
+ const slashOrSurrogate = /[/\ud800-\udfff]/;
1905
+ const surrogate = /[\ud800-\udfff]/;
1906
+ const codePoints = (s) => surrogate.test(s) ? [...s] : s;
1907
+ const noSlash = (s) => {
1908
+ if (s.includes("/")) throw new Error("can only match a single path portion, got: " + s);
1909
+ };
1910
+ var Matcher = class {
1911
+ pattern;
1912
+ options;
1913
+ #start;
1914
+ #size;
1915
+ #marks;
1916
+ #dotsSim;
1917
+ #literal;
1918
+ #literalFold = false;
1919
+ #literalRe;
1920
+ #linear;
1921
+ #wild = false;
1922
+ #min = 0;
1923
+ #max = Infinity;
1924
+ #prefix = [];
1925
+ #suffix = [];
1926
+ #prefixStr;
1927
+ #suffixStr;
1928
+ #affix = false;
1929
+ #dfa;
1930
+ #form;
1931
+ constructor(pattern, options = {}) {
1932
+ if (pattern.includes("/")) throw new Error("can only match a single path portion, got pattern: " + pattern);
1933
+ this.pattern = pattern;
1934
+ this.options = options;
1935
+ const { nocase = false, noext = false, normalize: n } = options;
1936
+ this.#form = n === true ? "NFC" : n || void 0;
1937
+ const literal = /^[?*+@]\(\)$/.test(pattern);
1938
+ const toks = tokenize(pattern, nocase, noext || literal, this.#form, options.rangeMark);
1939
+ let [items] = build(toks, pair(toks), 0, toks.length, true);
1940
+ if (this.#form) items = normalize$1(items, this.#form);
1941
+ const [start, size] = compile(items, nocase);
1942
+ this.#start = start;
1943
+ this.#size = size;
1944
+ if (items.every((it) => it.t === "lit")) {
1945
+ this.#literal = items.map((it) => it.ch).join("");
1946
+ this.#literalFold = nocase;
1947
+ } else {
1948
+ const lit = (it) => it.t !== "lit" ? void 0 : nocase ? {
1949
+ ch: it.ch,
1950
+ re: foldRe(it.ch)
1951
+ } : { ch: it.ch };
1952
+ for (const it of items) {
1953
+ const l = lit(it);
1954
+ if (!l) break;
1955
+ this.#prefix.push(l);
1956
+ }
1957
+ for (let j = items.length - 1; j >= 0; j--) {
1958
+ const l = lit(items[j]);
1959
+ if (!l) break;
1960
+ this.#suffix.unshift(l);
1961
+ }
1962
+ this.#affix = !!(this.#prefix.length || this.#suffix.length);
1963
+ if (!nocase) {
1964
+ this.#prefixStr = this.#prefix.map((l) => l.ch).join("");
1965
+ this.#suffixStr = this.#suffix.map((l) => l.ch).join("");
1966
+ }
1967
+ this.#linear = linear(this.#start)?.slice(this.#prefix.length, -this.#suffix.length || void 0);
1968
+ this.#wild = !!this.#linear?.every((n) => n.t === "star" || n.t === "any");
1969
+ const [min, max] = lengths(items);
1970
+ this.#min = min;
1971
+ this.#max = max;
1972
+ }
1973
+ }
1974
+ test(s) {
1975
+ if (this.#form) {
1976
+ noSlash(s);
1977
+ return this.#test(s.normalize(this.#form));
1978
+ }
1979
+ if (slashOrSurrogate.test(s)) {
1980
+ noSlash(s);
1981
+ return this.#test(s, [...s]);
1982
+ }
1983
+ return this.#test(s, s);
1984
+ }
1985
+ /**
1986
+ * The same as {@link Matcher#test}, but the string is not checked
1987
+ * for `/` chars, so the result for a string that has one is not
1988
+ * defined. Only use it for a string that is known to be one path
1989
+ * portion, such as a part of a path that was split on `/`. It can
1990
+ * be faster, because some patterns do not need to look at each char
1991
+ * of the string.
1992
+ */
1993
+ testUnchecked(s) {
1994
+ return this.#test(this.#form ? s.normalize(this.#form) : s);
1995
+ }
1996
+ #test(s, chars) {
1997
+ if (this.#literal !== void 0) return this.#literalFold ? (this.#literalRe ??= newFoldRe(this.#literal)).test(s) : s === this.#literal;
1998
+ const min = this.#min;
1999
+ const max = this.#max;
2000
+ if (chars === void 0) {
2001
+ const most = s.length;
2002
+ const least = most + 1 >> 1;
2003
+ if (most < min || least > max) return false;
2004
+ if (least < min || most > max) chars = codePoints(s);
2005
+ }
2006
+ if (chars !== void 0 && (chars.length < min || chars.length > max)) return false;
2007
+ const prefix = this.#prefix.length;
2008
+ if (this.#affix) {
2009
+ if (this.#prefixStr !== void 0 && this.#suffixStr !== void 0) {
2010
+ if (!s.startsWith(this.#prefixStr) || !s.endsWith(this.#suffixStr)) return false;
2011
+ } else {
2012
+ chars ??= codePoints(s);
2013
+ const end = chars.length - this.#suffix.length;
2014
+ if (!hasAffix(this.#prefix, chars, 0) || !hasAffix(this.#suffix, chars, end)) return false;
2015
+ }
2016
+ }
2017
+ const dotStart = !this.options.dot && s.startsWith(".");
2018
+ if (this.#linear) {
2019
+ if (s === "." || s === "..") return false;
2020
+ if (dotStart && !prefix) return false;
2021
+ if (this.#wild) return true;
2022
+ chars ??= codePoints(s);
2023
+ const end = chars.length - this.#suffix.length;
2024
+ return testLinear(this.#linear, chars, prefix, end);
2025
+ }
2026
+ chars ??= codePoints(s);
2027
+ if (s === "." || s === "..") {
2028
+ this.#marks ??= marks(this.#size);
2029
+ const sim = this.#dotsSim ??= new Sim(true, false, this.#marks);
2030
+ const start = sim.state();
2031
+ sim.add(start, this.#start, 0, true);
2032
+ let state = sim.done(start);
2033
+ for (let i = 0; i < chars.length; i++) state = sim.step(state, chars[i], i, true);
2034
+ return state.match;
2035
+ }
2036
+ this.#marks ??= marks(this.#size);
2037
+ const dfa = this.#dfa ??= new Dfa(this.#start, this.#marks);
2038
+ let d = dfa.start(dotStart);
2039
+ const str = chars === s;
2040
+ for (let i = 0; i < chars.length; i++) {
2041
+ if (d.dead) return false;
2042
+ const code = str ? s.charCodeAt(i) : chars[i].charCodeAt(0);
2043
+ d = d.ascii?.[code] ?? dfa.next(d, chars[i]);
2044
+ }
2045
+ return d.match;
2046
+ }
2047
+ /** a readable listing of the state machine */
2048
+ toString() {
2049
+ return show(this.#start);
2050
+ }
2051
+ };
2052
+ // ../../node_modules/.pnpm/minimatch@11.0.9/node_modules/minimatch/dist/esm/assert-valid-pattern.js
2053
+ const MAX_PATTERN_LENGTH = 65536;
2054
+ const assertValidPattern = (pattern) => {
2055
+ if (typeof pattern !== "string") throw new TypeError("invalid pattern");
2056
+ if (pattern.length > MAX_PATTERN_LENGTH) throw new TypeError("pattern is too long");
2057
+ };
2058
+ // ../../node_modules/.pnpm/minimatch@11.0.9/node_modules/minimatch/dist/esm/escape.js
2059
+ /**
2060
+ * Escape all magic characters in a glob pattern.
2061
+ *
2062
+ * If the {@link MinimatchOptions.windowsPathsNoEscape}
2063
+ * option is used, then characters are escaped by wrapping in `[]`, because
2064
+ * a magic character wrapped in a character class can only be satisfied by
2065
+ * that exact character. In this mode, `\` is _not_ escaped, because it is
2066
+ * not interpreted as a magic character, but instead as a path separator.
2067
+ *
2068
+ * If the {@link MinimatchOptions.magicalBraces} option is used,
2069
+ * then braces (`{` and `}`) will be escaped.
2070
+ *
2071
+ * A leading `#` or `!` is escaped as well, so that the result is never a
2072
+ * comment or a negated pattern. In `windowsPathsNoEscape` mode, a leading
2073
+ * `!` is written as `@(!)`, because `[!` starts a negated class.
2074
+ */
2075
+ const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false } = {}) => {
2076
+ const e = magicalBraces ? windowsPathsNoEscape ? s.replace(/[?*()[\]{}]/g, "[$&]") : s.replace(/[?*()[\]\\{}]/g, "\\$&") : windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
2077
+ const c = e.charAt(0);
2078
+ if (c === "#") return (windowsPathsNoEscape ? "[#]" : "\\#") + e.slice(1);
2079
+ if (c === "!") return (windowsPathsNoEscape ? "@(!)" : "\\!") + e.slice(1);
2080
+ return e;
2081
+ };
2082
+ // ../../node_modules/.pnpm/minimatch@11.0.9/node_modules/minimatch/dist/esm/unescape.js
2083
+ /**
2084
+ * Un-escape a string that has been escaped with {@link escape}.
2085
+ *
2086
+ * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
2087
+ * square-bracket escapes are removed, but not backslash escapes.
2088
+ *
2089
+ * For example, it will turn the string `'[*]'` into `*`, but it will not
2090
+ * turn `'\\*'` into `'*'`, because `\` is a path separator in
2091
+ * `windowsPathsNoEscape` mode.
2092
+ *
2093
+ * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
2094
+ * backslash escapes are removed.
2095
+ *
2096
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
2097
+ * or unescaped.
2098
+ *
2099
+ * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
2100
+ * unescaped.
2101
+ */
2102
+ const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true } = {}) => {
2103
+ if (windowsPathsNoEscape && s.startsWith("@(!)")) return "!" + unescape(s.slice(4), {
2104
+ windowsPathsNoEscape,
2105
+ magicalBraces
2106
+ });
2107
+ if (magicalBraces) return windowsPathsNoEscape ? s.replace(/\[([^/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^/\\])\]/g, "$1$2").replace(/\\([^/])/g, "$1");
2108
+ return windowsPathsNoEscape ? s.replace(/\[([^/\\{}])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^/\\{}])\]/g, "$1$2").replace(/\\([^/{}])/g, "$1");
2109
+ };
2110
+ // ../../node_modules/.pnpm/minimatch@11.0.9/node_modules/minimatch/dist/esm/index.js
2111
+ const DEFAULT_BRACE_EXPAND_MAX = 1e5;
2112
+ const DEFAULT_GLOB_STAR_RECURSION_MAX = 200;
2113
+ const AWE_KEY = "allowWindowsEscape";
2114
+ const minimatch = (p, pattern, options) => {
2115
+ assertValidPattern(pattern);
2116
+ if (!options?.nocomment && pattern.charAt(0) === "#") return false;
2117
+ return cachedMinimatch(pattern, options).match(p);
2118
+ };
2119
+ let cache = /* @__PURE__ */ new Map();
2120
+ let oldCache = /* @__PURE__ */ new Map();
2121
+ let cacheSize = 0;
2122
+ let cacheTotalWeight = 0;
2123
+ const cacheMax = 256;
2124
+ const cacheMaxWeight = 32768;
2125
+ const cacheMaxEntryWeight = 4096;
2126
+ const cacheWeight = (mm) => {
2127
+ let w = mm.pattern.length;
2128
+ for (const s of mm.globSet) {
2129
+ w += s.length + 1;
2130
+ if (w > cacheMaxEntryWeight) break;
2131
+ }
2132
+ return w;
2133
+ };
2134
+ const tri = (v) => v === void 0 ? 0 : v ? 2 : 1;
2135
+ const booleanWeights = new Map(Object.keys({
2136
+ nobrace: 0,
2137
+ nocomment: 0,
2138
+ nonegate: 0,
2139
+ noglobstar: 0,
2140
+ noext: 0,
2141
+ nonull: 0,
2142
+ partial: 0,
2143
+ dot: 0,
2144
+ nocase: 0,
2145
+ nocaseMagicOnly: 0,
2146
+ magicalBraces: 0,
2147
+ matchBase: 0,
2148
+ flipNegate: 0,
2149
+ preserveMultipleSlashes: 0,
2150
+ windowsNoMagicRoot: 0
2151
+ }).map((k, i) => [k, 24 * 3 ** i]));
2152
+ const optionsKey = (o) => {
2153
+ let n = 0;
2154
+ let wpe = false;
2155
+ for (const k in o) {
2156
+ const v = o[k];
2157
+ switch (k) {
2158
+ case "windowsPathsNoEscape":
2159
+ if (v) wpe = true;
2160
+ break;
2161
+ case AWE_KEY:
2162
+ if (v === false) wpe = true;
2163
+ break;
2164
+ case "platform": {
2165
+ const p = v || defaultPlatform;
2166
+ if (p === defaultPlatform) break;
2167
+ if (p === "darwin") n += 3;
2168
+ else if (p === "win32") n += 6;
2169
+ else if (p === "linux") n += 9;
2170
+ else return JSON.stringify(o);
2171
+ break;
2172
+ }
2173
+ case "optimizationLevel":
2174
+ if (v === void 0) break;
2175
+ n += v >= 2 ? 1 : v >= 1 ? 0 : 2;
2176
+ break;
2177
+ case "braceExpandMax":
2178
+ if (v !== void 0 && v !== DEFAULT_BRACE_EXPAND_MAX) return JSON.stringify(o);
2179
+ break;
2180
+ case "maxGlobstarRecursion":
2181
+ if (v !== void 0 && v !== DEFAULT_GLOB_STAR_RECURSION_MAX) return JSON.stringify(o);
2182
+ break;
2183
+ case "normalize":
2184
+ if (v !== void 0) return JSON.stringify(o);
2185
+ break;
2186
+ default: n += (booleanWeights.get(k) ?? 0) * tri(v);
2187
+ }
2188
+ }
2189
+ return wpe ? n + 12 : n;
2190
+ };
2191
+ const copyOptions = (o) => {
2192
+ const copy = {};
2193
+ for (const k in o) copy[k] = o[k];
2194
+ return copy;
2195
+ };
2196
+ const cachedMinimatch = (pattern, options) => {
2197
+ const key = options ? optionsKey(options) : 0;
2198
+ let mm = cache.get(key)?.get(pattern);
2199
+ if (mm) return mm;
2200
+ mm = oldCache.get(key)?.get(pattern) ?? new Minimatch(pattern, copyOptions(options));
2201
+ const weight = cacheWeight(mm);
2202
+ if (weight > cacheMaxEntryWeight) return mm;
2203
+ if (cacheSize >= cacheMax || cacheTotalWeight + weight > cacheMaxWeight) {
2204
+ oldCache = cache;
2205
+ cache = /* @__PURE__ */ new Map();
2206
+ cacheSize = 0;
2207
+ cacheTotalWeight = 0;
2208
+ }
2209
+ let byPattern = cache.get(key);
2210
+ if (!byPattern) cache.set(key, byPattern = /* @__PURE__ */ new Map());
2211
+ byPattern.set(pattern, mm);
2212
+ cacheSize++;
2213
+ cacheTotalWeight += weight;
2214
+ return mm;
2215
+ };
2216
+ /* c8 ignore start */
2217
+ const defaultPlatform = typeof process === "object" && process ? process.env?.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
2218
+ const path = {
2219
+ win32: { sep: "\\" },
2220
+ posix: { sep: "/" }
2221
+ };
2222
+ minimatch.sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
2223
+ const GLOBSTAR = Symbol("globstar **");
2224
+ minimatch.GLOBSTAR = GLOBSTAR;
2225
+ const filter = (pattern, options) => {
2226
+ let mm;
2227
+ return (p) => (mm ??= cachedMinimatch(pattern, options)).match(p);
2228
+ };
2229
+ minimatch.filter = filter;
2230
+ const ext = (a, b = {}) => Object.assign({}, a, b);
2231
+ const defaults = (def) => {
2232
+ if (!def || typeof def !== "object" || !Object.keys(def).length) return minimatch;
2233
+ const orig = minimatch;
2234
+ const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
2235
+ return Object.assign(m, {
2236
+ Minimatch: class Minimatch extends orig.Minimatch {
2237
+ constructor(pattern, options = {}) {
2238
+ super(pattern, ext(def, options));
2239
+ }
2240
+ static defaults(options) {
2241
+ return orig.defaults(ext(def, options)).Minimatch;
2242
+ }
2243
+ },
2244
+ unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
2245
+ escape: (s, options = {}) => orig.escape(s, ext(def, options)),
2246
+ filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
2247
+ defaults: (options) => orig.defaults(ext(def, options)),
2248
+ braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
2249
+ match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
2250
+ sep: orig.sep,
2251
+ GLOBSTAR
2252
+ });
2253
+ };
2254
+ minimatch.defaults = defaults;
2255
+ const braceExpand = (pattern, options = {}) => {
2256
+ assertValidPattern(pattern);
2257
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) return [pattern];
2258
+ let p = pattern.replace(/\\\\/g, "\\\\\\\\");
2259
+ if (options.windowsPathsNoEscape || options[AWE_KEY] === false) p = p.replace(/\[([{}])\]/g, "[\\$1]");
2260
+ return expand(p, { max: options.braceExpandMax });
2261
+ };
2262
+ minimatch.braceExpand = braceExpand;
2263
+ const RANGE_MIN = 100;
2264
+ const rangeRe = /(?<![\\$])\{(-?\d+)\.\.(-?\d+)\}/g;
2265
+ const inRepeatOrNegExt = (portion, mark) => {
2266
+ const stack = [];
2267
+ for (let i = 0; i < portion.length; i++) {
2268
+ const c = portion.charAt(i);
2269
+ if (c === "\\") i++;
2270
+ else if (c === mark) {
2271
+ if (stack.some((t) => t !== "@" && t !== "?")) return true;
2272
+ } else if (portion.charAt(i + 1) === "(" && "!?+*@".includes(c)) {
2273
+ stack.push(c);
2274
+ i++;
2275
+ } else if (c === ")") stack.pop();
2276
+ }
2277
+ return false;
2278
+ };
2279
+ const match = (list, pattern, options = {}) => {
2280
+ const mm = new Minimatch(pattern, options);
2281
+ list = list.filter((f) => mm.match(f));
2282
+ if (mm.options.nonull && !list.length) list.push(pattern);
2283
+ return list;
2284
+ };
2285
+ minimatch.match = match;
2286
+ const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
2287
+ const classEnd = (pattern, start) => {
2288
+ let i = start + 1;
2289
+ if (pattern.charAt(i) === "!" || pattern.charAt(i) === "^") i++;
2290
+ let sawStart = false;
2291
+ for (; i < pattern.length; i++) {
2292
+ const c = pattern.charAt(i);
2293
+ if (c === "]" && sawStart) return i;
2294
+ sawStart = true;
2295
+ if (c === "\\") i++;
2296
+ }
2297
+ return -1;
2298
+ };
2299
+ const literal = (pattern, noext) => {
2300
+ if (!noext && (pattern === "+()" || pattern === "@()")) return pattern;
2301
+ let lit = "";
2302
+ for (let i = 0; i < pattern.length; i++) {
2303
+ const c = pattern.charAt(i);
2304
+ if (c === "\\") lit += pattern.charAt(++i) || c;
2305
+ else if (c === "*" || c === "?") return;
2306
+ else if (c === "[") {
2307
+ const close = classEnd(pattern, i);
2308
+ if (close === -1) {
2309
+ lit += c;
2310
+ continue;
2311
+ }
2312
+ let body = pattern.slice(i + 1, close);
2313
+ if (body.startsWith("\\")) body = body.slice(1);
2314
+ if ([...body].length !== 1 || "!^".includes(pattern.charAt(i + 1))) return;
2315
+ lit += body;
2316
+ i = close;
2317
+ } else if (!noext && "+@!".includes(c) && pattern.charAt(i + 1) === "(" && pattern.includes(")", i + 2)) return;
2318
+ else lit += c;
2319
+ }
2320
+ return lit;
2321
+ };
2322
+ const MAX_EXTGLOBS = 256;
2323
+ const extglobCount = (pattern) => {
2324
+ let n = 0;
2325
+ for (let i = 0; i < pattern.length - 1; i++) {
2326
+ const c = pattern.charAt(i);
2327
+ if (c === "\\") i++;
2328
+ else if ("+@!?*".includes(c) && pattern.charAt(i + 1) === "(") {
2329
+ n++;
2330
+ i++;
2331
+ }
2332
+ }
2333
+ return n;
2334
+ };
2335
+ const assertValidExtglobs = (pattern) => {
2336
+ if (extglobCount(pattern) > MAX_EXTGLOBS) throw new TypeError("pattern has too many extglobs");
2337
+ };
2338
+ const extSafe = (pattern) => {
2339
+ if (/^[?*+@]\(\)$/.test(pattern) || pattern.includes("[:")) return false;
2340
+ let depth = 0;
2341
+ for (let i = 0; i < pattern.length; i++) {
2342
+ const c = pattern.charAt(i);
2343
+ if (c === "\\") {
2344
+ if (++i === pattern.length) return false;
2345
+ } else if (c === "[") {
2346
+ const close = classEnd(pattern, i);
2347
+ if (close !== -1) i = close;
2348
+ } else if ("+@!?*".includes(c) && pattern.charAt(i + 1) === "(") {
2349
+ depth++;
2350
+ i++;
2351
+ } else if (c === ")") {
2352
+ if (!depth--) return false;
2353
+ } else if (c === "|" && !depth) return false;
2354
+ }
2355
+ return !depth;
2356
+ };
2357
+ let lastSplit;
2358
+ let lastChecked;
2359
+ const portionMatch = (p, f) => typeof p === "string" ? f === p : f !== "" && p.testUnchecked(f);
2360
+ const endIndex = (p, last, lastStart, prev, prevStart) => portionMatch(p, last) ? lastStart : prev !== void 0 && portionMatch(p, prev) ? prevStart : -1;
2361
+ const isDots = (p) => p === "." || p === "..";
2362
+ const isDrive = (p) => typeof p === "string" && /^[a-z]:$/i.test(p);
2363
+ const isLongUNC = (p) => typeof p === "string" && /^unc$/i.test(p);
2364
+ const uncHost = (p) => {
2365
+ if (p[0] !== "" || p[1] !== "") return -1;
2366
+ const h = p[2] !== "?" ? 2 : isLongUNC(p[3]) ? 4 : -1;
2367
+ const host = p[h];
2368
+ const share = p[h + 1];
2369
+ return h !== -1 && host !== void 0 && host !== "" && host !== GLOBSTAR && share !== void 0 && share !== "" && share !== GLOBSTAR ? h : -1;
2370
+ };
2371
+ const walkable = (p, dot) => !isDots(p) && (dot || !p.startsWith("."));
2372
+ const dotPortion = (f, start, end, dot, sep) => {
2373
+ for (let k = start; k < end;) {
2374
+ if (f.charCodeAt(k) === 46) {
2375
+ if (!dot) return true;
2376
+ const n = f.charCodeAt(k + 1) === 46 ? k + 2 : k + 1;
2377
+ if (n >= end || isSep(f.charCodeAt(n), sep)) return true;
2378
+ }
2379
+ const s = nextSep(f, k, sep);
2380
+ if (s === -1) return false;
2381
+ k = s + 1;
2382
+ while (k < end && isSep(f.charCodeAt(k), sep)) k++;
2383
+ }
2384
+ return false;
2385
+ };
2386
+ const isSep = (c, sep) => sep === "/" ? c === 47 : sep === "\\" ? c === 92 : c === 47 || c === 92;
2387
+ const nextSep = (f, from, sep) => {
2388
+ if (sep !== "both") return f.indexOf(sep, from);
2389
+ const s = f.indexOf("/", from);
2390
+ const b = f.indexOf("\\", from);
2391
+ return s === -1 ? b : b === -1 ? s : Math.min(s, b);
2392
+ };
2393
+ const lastSep = (f, from, sep) => sep !== "both" ? f.lastIndexOf(sep, from) : Math.max(f.lastIndexOf("/", from), f.lastIndexOf("\\", from));
2394
+ const PENDING = {};
2395
+ var Minimatch = class {
2396
+ options;
2397
+ set;
2398
+ pattern;
2399
+ windowsPathsNoEscape;
2400
+ nonegate;
2401
+ negate;
2402
+ comment;
2403
+ empty;
2404
+ preserveMultipleSlashes;
2405
+ partial;
2406
+ globSet;
2407
+ globParts;
2408
+ nocase;
2409
+ isWindows;
2410
+ platform;
2411
+ windowsNoMagicRoot;
2412
+ maxGlobstarRecursion;
2413
+ #endCheck;
2414
+ #literalCheck;
2415
+ #level2;
2416
+ #form;
2417
+ #literals = [];
2418
+ #shapes = [];
2419
+ #endRows = [];
2420
+ #matchers = /* @__PURE__ */ new Map();
2421
+ #pending = false;
2422
+ #rangeMark;
2423
+ #globstarParts = /* @__PURE__ */ new WeakMap();
2424
+ constructor(pattern, options = {}) {
2425
+ assertValidPattern(pattern);
2426
+ options = options || {};
2427
+ this.options = options;
2428
+ this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? DEFAULT_GLOB_STAR_RECURSION_MAX;
2429
+ this.pattern = pattern;
2430
+ this.platform = options.platform || defaultPlatform;
2431
+ this.isWindows = this.platform === "win32";
2432
+ this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options[AWE_KEY] === false;
2433
+ if (this.windowsPathsNoEscape) this.pattern = this.pattern.replace(/\\/g, "/");
2434
+ this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
2435
+ this.negate = false;
2436
+ this.nonegate = !!options.nonegate;
2437
+ this.comment = false;
2438
+ this.empty = false;
2439
+ this.partial = !!options.partial;
2440
+ this.nocase = !!this.options.nocase;
2441
+ this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
2442
+ this.globSet = [];
2443
+ this.globParts = [];
2444
+ this.set = [];
2445
+ this.#endCheck = !this.preserveMultipleSlashes;
2446
+ this.#level2 = (options.optimizationLevel ?? 1) >= 2;
2447
+ const n = options.normalize;
2448
+ this.#form = n === true ? "NFC" : n || void 0;
2449
+ this.make();
2450
+ const drives = this.set.map((row) => this.#rootIndex(row));
2451
+ this.#endRows = this.set.map((row, r) => this.#endCheck && row.length - 1 > drives[r]);
2452
+ this.#literals = this.set.map((row, r) => {
2453
+ const end = this.#endRows[r] ? row.length - 1 : row.length;
2454
+ const lits = row.slice(drives[r] + 1, end).filter((p) => typeof p === "string" && !!p);
2455
+ return [...new Set(lits)];
2456
+ });
2457
+ this.#literalCheck = this.#literals.some((l) => l.length);
2458
+ this.#shapes = this.set.map((row, r) => {
2459
+ const [p0, p1, p2] = row;
2460
+ if (this.#endRows[r] && row.length === 2) {
2461
+ if (p0 === GLOBSTAR && p1 !== GLOBSTAR) return "tail";
2462
+ }
2463
+ if (this.#endRows[r] && options.matchBase && row.length === 1 && p0 !== GLOBSTAR && p0 !== "") return "base";
2464
+ if (!this.#endCheck || drives[r] !== -1) return void 0;
2465
+ if (row.length === 3 && p0 === GLOBSTAR && p2 === GLOBSTAR && p1 !== GLOBSTAR && p1 !== "" && this.maxGlobstarRecursion > 0) return "mid";
2466
+ if (row.length === 2 && p1 === GLOBSTAR && p0 !== GLOBSTAR && p0 !== "") return "head";
2467
+ });
2468
+ }
2469
+ #norm(p) {
2470
+ return this.#form ? p.normalize(this.#form) : p;
2471
+ }
2472
+ #rootIndex(row) {
2473
+ if (!this.isWindows) return -1;
2474
+ if (isDrive(row[0])) return 0;
2475
+ if (row[0] === "" && row[1] === "" && row[2] === "?" && isDrive(row[3])) return 3;
2476
+ const h = uncHost(row);
2477
+ return h === -1 ? -1 : h + 1;
2478
+ }
2479
+ hasMagic() {
2480
+ if (this.options.magicalBraces && this.set.length > 1) return true;
2481
+ for (const pattern of this.set) for (const part of pattern) if (typeof part !== "string") return true;
2482
+ return false;
2483
+ }
2484
+ make() {
2485
+ const pattern = this.pattern;
2486
+ const options = this.options;
2487
+ if (!options.nocomment && pattern.charAt(0) === "#") {
2488
+ this.comment = true;
2489
+ return;
2490
+ }
2491
+ if (!pattern) {
2492
+ this.empty = true;
2493
+ return;
2494
+ }
2495
+ this.parseNegate();
2496
+ this.globSet = [...new Set(this.#expandBraces())];
2497
+ const rawGlobParts = this.globSet.map((s) => this.#slashSplit(s));
2498
+ this.globParts = this.preprocess(rawGlobParts);
2499
+ this.#pending = true;
2500
+ let set = this.globParts.map((s, _, __) => {
2501
+ if (this.isWindows && this.windowsNoMagicRoot) {
2502
+ const n = s[2] === "?" && isLongUNC(s[3]) ? 6 : 4;
2503
+ const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && s.slice(3, n).every((p) => !globMagic.test(p));
2504
+ const isDrive = /^[a-z]:/i.test(s[0]);
2505
+ if (isUNC) return [...s.slice(0, n).map((p) => this.#norm(p)), ...s.slice(n).map((ss) => this.parse(ss))];
2506
+ else if (isDrive) return [this.#norm(s[0]), ...s.slice(1).map((ss) => this.parse(ss))];
2507
+ }
2508
+ return s.map((ss) => this.parse(ss));
2509
+ });
2510
+ this.set = set.filter((s) => s.indexOf(false) === -1);
2511
+ if (this.isWindows) for (let i = 0; i < this.set.length; i++) {
2512
+ const p = this.set[i];
2513
+ if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && (isDrive(p[3]) || isLongUNC(this.globParts[i][3]))) {
2514
+ if (isLongUNC(this.globParts[i][3])) p[3] = "UNC";
2515
+ p[2] = "?";
2516
+ }
2517
+ }
2518
+ if (!options.noext) this.mergeRows();
2519
+ this.#pending = false;
2520
+ this.set.forEach((row, i) => {
2521
+ for (let k = 0; k < row.length; k++) if (row[k] === PENDING) row[k] = this.parse(this.globParts[i][k]);
2522
+ });
2523
+ }
2524
+ mergeRows() {
2525
+ let merged = true;
2526
+ while (merged) {
2527
+ merged = false;
2528
+ if (this.set.length < 2) return;
2529
+ let keys = this.#mergeKeys();
2530
+ const len = Math.max(0, ...this.set.map((r) => r.length));
2531
+ for (let k = 0; k < len; k++) {
2532
+ const groups = /* @__PURE__ */ new Map();
2533
+ const R = this.set.length + 1;
2534
+ this.set.forEach((row, i) => {
2535
+ if (!(row[k] instanceof Matcher || row[k] === PENDING) || !extSafe(this.globParts[i][k])) return;
2536
+ const { pre, suf } = keys[i];
2537
+ const key = pre[k] * R + suf[k + 1];
2538
+ const g = groups.get(key);
2539
+ if (g) g.push(i);
2540
+ else groups.set(key, [i]);
2541
+ });
2542
+ const drop = /* @__PURE__ */ new Set();
2543
+ for (const g of groups.values()) {
2544
+ if (g.length < 2) continue;
2545
+ const [first, ...rest] = g;
2546
+ const glob = `@(${g.map((i) => this.globParts[i][k]).join("|")})`;
2547
+ if (extglobCount(glob) > MAX_EXTGLOBS) continue;
2548
+ this.globParts[first][k] = glob;
2549
+ this.set[first][k] = this.parse(glob);
2550
+ for (const i of rest) drop.add(i);
2551
+ }
2552
+ if (drop.size) {
2553
+ merged = true;
2554
+ this.set = this.set.filter((_, i) => !drop.has(i));
2555
+ this.globParts = this.globParts.filter((_, i) => !drop.has(i));
2556
+ if (this.set.length < 2) return;
2557
+ keys = this.#mergeKeys();
2558
+ }
2559
+ }
2560
+ }
2561
+ }
2562
+ #mergeKeys() {
2563
+ const partIds = /* @__PURE__ */ new Map();
2564
+ const ids = this.globParts.map((parts) => parts.map((s) => {
2565
+ let id = partIds.get(s);
2566
+ if (id === void 0) partIds.set(s, id = partIds.size);
2567
+ return id;
2568
+ }));
2569
+ const P = partIds.size;
2570
+ const len = Math.max(0, ...ids.map((r) => r.length));
2571
+ const keys = ids.map((r) => ({
2572
+ pre: [0],
2573
+ suf: new Array(r.length + 1).fill(0)
2574
+ }));
2575
+ for (let k = 0; k < len; k++) {
2576
+ const m = /* @__PURE__ */ new Map();
2577
+ ids.forEach((r, i) => {
2578
+ if (k >= r.length) return;
2579
+ const { pre } = keys[i];
2580
+ const key = pre[k] * P + r[k];
2581
+ let id = m.get(key);
2582
+ if (id === void 0) m.set(key, id = m.size + 1);
2583
+ pre.push(id);
2584
+ });
2585
+ }
2586
+ for (let k = len - 1; k >= 0; k--) {
2587
+ const m = /* @__PURE__ */ new Map();
2588
+ ids.forEach((r, i) => {
2589
+ if (k >= r.length) return;
2590
+ const { suf } = keys[i];
2591
+ const key = suf[k + 1] * P + r[k];
2592
+ let id = m.get(key);
2593
+ if (id === void 0) m.set(key, id = m.size + 1);
2594
+ suf[k] = id;
2595
+ });
2596
+ }
2597
+ return keys;
2598
+ }
2599
+ preprocess(globParts) {
2600
+ if (this.options.noglobstar) {
2601
+ for (const partset of globParts) for (let j = 0; j < partset.length; j++) if (partset[j] === "**") partset[j] = "*";
2602
+ }
2603
+ const { optimizationLevel = 1 } = this.options;
2604
+ if (optimizationLevel >= 2) {
2605
+ globParts = this.firstPhasePreProcess(globParts);
2606
+ globParts = this.secondPhasePreProcess(globParts);
2607
+ } else if (optimizationLevel >= 1) globParts = this.levelOneOptimize(globParts);
2608
+ else globParts = this.adjascentGlobstarOptimize(globParts);
2609
+ return globParts;
2610
+ }
2611
+ adjascentGlobstarOptimize(globParts) {
2612
+ return globParts.map((parts) => {
2613
+ let gs = -1;
2614
+ while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
2615
+ let i = gs;
2616
+ while (parts[i + 1] === "**") i++;
2617
+ if (i !== gs) parts.splice(gs, i - gs);
2618
+ }
2619
+ return parts;
2620
+ });
2621
+ }
2622
+ levelOneOptimize(globParts) {
2623
+ return globParts.map((parts) => {
2624
+ const root = this.#rootIndex(parts) + 1;
2625
+ parts = parts.reduce((set, part) => {
2626
+ const prev = set[set.length - 1];
2627
+ if (part === "**" && prev === "**") return set;
2628
+ if (part === "..") {
2629
+ if (set.length > root && prev && prev !== ".." && prev !== "." && prev !== "**") {
2630
+ set.pop();
2631
+ return set;
2632
+ }
2633
+ }
2634
+ set.push(part);
2635
+ return set;
2636
+ }, []);
2637
+ return parts.length === 0 ? [""] : parts;
2638
+ });
2639
+ }
2640
+ #canMatch(f) {
2641
+ const sep = !this.isWindows || !f.includes("\\") ? "/" : f.includes("/") ? "both" : "\\";
2642
+ let ends = this.#endCheck ? 0 : -1;
2643
+ let last = "";
2644
+ let lastStart = 0;
2645
+ let prev;
2646
+ let prevStart = 0;
2647
+ const dot = !!this.options.dot;
2648
+ ROWS: for (let r = 0; r < this.set.length; r++) {
2649
+ const row = this.set[r];
2650
+ const p = row[row.length - 1];
2651
+ let end = ends !== -1 && this.#endRows[r] && p !== GLOBSTAR;
2652
+ if (end && ends === 0) {
2653
+ const i = lastSep(f, f.length, sep);
2654
+ lastStart = i + 1;
2655
+ last = f.slice(lastStart);
2656
+ if (last === "" && i >= 0) {
2657
+ let j = i;
2658
+ while (j > 0 && isSep(f.charCodeAt(j - 1), sep)) j--;
2659
+ prevStart = j === 0 ? 0 : lastSep(f, j - 1, sep) + 1;
2660
+ prev = f.slice(prevStart, j);
2661
+ }
2662
+ const resolves = this.#level2 && (isDots(last) || last === "" && prev !== void 0 && isDots(prev));
2663
+ ends = resolves ? -1 : 1;
2664
+ end = !resolves;
2665
+ }
2666
+ let tailStart = -1;
2667
+ if (end && typeof p === "string") {
2668
+ tailStart = endIndex(p, last, lastStart, prev, prevStart);
2669
+ if (tailStart === -1) continue;
2670
+ }
2671
+ if (this.#literalCheck) {
2672
+ for (const l of this.#literals[r]) if (!f.includes(l)) continue ROWS;
2673
+ }
2674
+ if (end && typeof p === "object") {
2675
+ tailStart = endIndex(p, last, lastStart, prev, prevStart);
2676
+ if (tailStart === -1) continue;
2677
+ }
2678
+ const shape = this.#shapes[r];
2679
+ if (shape === "base" && end) return "yes";
2680
+ if (shape === "tail" && end) {
2681
+ if (this.#level2 && dotPortion(f, 0, tailStart, true, sep)) return "maybe";
2682
+ if (!dotPortion(f, 0, tailStart, dot, sep)) return "yes";
2683
+ continue;
2684
+ }
2685
+ if (shape === "mid" || shape === "head") {
2686
+ const m = this.#walk(f, row, shape === "head", dot, sep);
2687
+ if (m !== "no") return m;
2688
+ continue;
2689
+ }
2690
+ return "maybe";
2691
+ }
2692
+ return "no";
2693
+ }
2694
+ #matchShape(file, row, shape) {
2695
+ const dot = !!this.options.dot;
2696
+ const n = file.length;
2697
+ if (shape === "head") {
2698
+ if (n < 2 || !portionMatch(row[0], file[0])) return false;
2699
+ for (let i = 1; i < n; i++) if (!walkable(file[i], dot)) return false;
2700
+ return true;
2701
+ }
2702
+ const x = row[1];
2703
+ if (shape === "tail") {
2704
+ let t = n - 1;
2705
+ if (!portionMatch(x, file[t])) {
2706
+ if (file[t] !== "" || n === 1 || !portionMatch(x, file[--t])) return false;
2707
+ }
2708
+ for (let i = 0; i < t; i++) if (!walkable(file[i], dot)) return false;
2709
+ return true;
2710
+ }
2711
+ for (let k = 0; k < n; k++) {
2712
+ if (portionMatch(x, file[k]) && k + 1 < n) {
2713
+ let i = k + 1;
2714
+ while (i < n && walkable(file[i], dot)) i++;
2715
+ if (i === n) return true;
2716
+ }
2717
+ if (!walkable(file[k], dot)) return false;
2718
+ }
2719
+ return false;
2720
+ }
2721
+ #walk(f, row, head, dot, sep) {
2722
+ if (this.#level2 && dotPortion(f, 0, f.length, true, sep)) return "maybe";
2723
+ const x = row[head ? 0 : 1];
2724
+ let s = 0;
2725
+ for (let e = nextSep(f, s, sep); e !== -1; e = nextSep(f, s, sep)) {
2726
+ let next = e + 1;
2727
+ while (next < f.length && isSep(f.charCodeAt(next), sep)) next++;
2728
+ if ((typeof x === "string" ? e - s === x.length && f.startsWith(x, s) : e > s && x.testUnchecked(f.slice(s, e))) && !dotPortion(f, next, f.length, dot, sep)) return "yes";
2729
+ if (head || dotPortion(f, s, next, dot, sep)) return "no";
2730
+ s = next;
2731
+ }
2732
+ return "no";
2733
+ }
2734
+ #cachedSplit(f) {
2735
+ const last = lastSplit;
2736
+ return last?.f === f && last.isWindows === this.isWindows && last.preserveMultipleSlashes === this.preserveMultipleSlashes && last.normalize === this.#form ? last : void 0;
2737
+ }
2738
+ #split(f) {
2739
+ const { isWindows, preserveMultipleSlashes } = this;
2740
+ let parts = this.#slashSplit(isWindows ? f.split("\\").join("/") : f);
2741
+ const normalize = this.#form;
2742
+ if (normalize) parts = parts.map((p) => p.normalize(normalize));
2743
+ lastSplit = {
2744
+ f,
2745
+ isWindows,
2746
+ preserveMultipleSlashes,
2747
+ normalize,
2748
+ parts
2749
+ };
2750
+ return lastSplit;
2751
+ }
2752
+ #levelTwoFileOptimize(file) {
2753
+ const parts = [...file];
2754
+ let didSomething = false;
2755
+ do {
2756
+ didSomething = false;
2757
+ if (!this.preserveMultipleSlashes) {
2758
+ for (let i = 1; i < parts.length - 1; i++) {
2759
+ const p = parts[i];
2760
+ if (i === 1 && p === "" && parts[0] === "") continue;
2761
+ if (p === "." || p === "") {
2762
+ didSomething = true;
2763
+ parts.splice(i, 1);
2764
+ i--;
2765
+ }
2766
+ }
2767
+ if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
2768
+ didSomething = true;
2769
+ parts.pop();
2770
+ }
2771
+ }
2772
+ const root = this.#rootIndex(parts) + 1;
2773
+ let dd = root;
2774
+ while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
2775
+ const p = parts[dd - 1];
2776
+ if (p && p !== "." && p !== ".." && p !== "**") {
2777
+ didSomething = true;
2778
+ parts.splice(dd - 1, 2);
2779
+ dd = Math.max(dd - 2, root);
2780
+ }
2781
+ }
2782
+ } while (didSomething);
2783
+ return parts.length === 0 ? [""] : parts;
2784
+ }
2785
+ firstPhasePreProcess(globParts) {
2786
+ const { braceExpandMax = DEFAULT_BRACE_EXPAND_MAX } = this.options;
2787
+ let splitCells = 0;
2788
+ const maxSplitCells = 1e6;
2789
+ let didSomething = false;
2790
+ do {
2791
+ didSomething = false;
2792
+ for (let parts of globParts) {
2793
+ let gs = -1;
2794
+ while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
2795
+ let gss = gs;
2796
+ while (parts[gss + 1] === "**") gss++;
2797
+ if (gss > gs) parts.splice(gs + 1, gss - gs);
2798
+ let next = parts[gs + 1];
2799
+ const p = parts[gs + 2];
2800
+ const p2 = parts[gs + 3];
2801
+ if (next !== "..") continue;
2802
+ if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") continue;
2803
+ const addedCells = parts.length - 1;
2804
+ if (globParts.length >= braceExpandMax || splitCells + addedCells > maxSplitCells) throw new RangeError(`optimizationLevel 2: too many patterns from '**/..'`);
2805
+ didSomething = true;
2806
+ parts.splice(gs, 1);
2807
+ const other = parts.slice(0);
2808
+ other[gs] = "**";
2809
+ splitCells += addedCells;
2810
+ globParts.push(other);
2811
+ gs--;
2812
+ }
2813
+ if (!this.preserveMultipleSlashes) {
2814
+ for (let i = 1; i < parts.length - 1; i++) {
2815
+ const p = parts[i];
2816
+ if (i === 1 && p === "" && parts[0] === "") continue;
2817
+ if (p === "." || p === "") {
2818
+ didSomething = true;
2819
+ parts.splice(i, 1);
2820
+ i--;
2821
+ }
2822
+ }
2823
+ if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
2824
+ didSomething = true;
2825
+ parts.pop();
2826
+ }
2827
+ }
2828
+ const root = this.#rootIndex(parts) + 1;
2829
+ let dd = root;
2830
+ while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
2831
+ const p = parts[dd - 1];
2832
+ if (p && p !== "." && p !== ".." && p !== "**") {
2833
+ didSomething = true;
2834
+ const splin = dd === 1 && parts[dd + 1] === "**" ? ["."] : [];
2835
+ parts.splice(dd - 1, 2, ...splin);
2836
+ if (parts.length === 0) parts.push("");
2837
+ dd = Math.max(dd - 2, root);
2838
+ }
2839
+ }
2840
+ }
2841
+ } while (didSomething);
2842
+ return globParts;
2843
+ }
2844
+ secondPhasePreProcess(globParts) {
2845
+ const keys = /* @__PURE__ */ new Set();
2846
+ const rows = globParts.filter((parts) => {
2847
+ const key = parts.join("/");
2848
+ if (keys.has(key)) return false;
2849
+ keys.add(key);
2850
+ return true;
2851
+ });
2852
+ const stars = /* @__PURE__ */ new Map();
2853
+ for (const parts of rows) {
2854
+ const s = [];
2855
+ for (let i = 0; i < parts.length; i++) if (parts[i] === "*") s.push(i);
2856
+ if (s.length) stars.set(s.join(","), s);
2857
+ }
2858
+ if (!stars.size || rows.length * stars.size > 1e5) return rows;
2859
+ const { dot } = this.options;
2860
+ return rows.filter((parts) => {
2861
+ for (const s of stars.values()) {
2862
+ if (s[s.length - 1] >= parts.length) continue;
2863
+ const c = [...parts];
2864
+ let ok = true;
2865
+ let changed = false;
2866
+ for (const i of s) {
2867
+ const p = parts[i];
2868
+ if (p === "*") continue;
2869
+ if (!p || p === "**" || !dot && p.startsWith(".")) {
2870
+ ok = false;
2871
+ break;
2872
+ }
2873
+ c[i] = "*";
2874
+ changed = true;
2875
+ }
2876
+ if (ok && changed && keys.has(c.join("/"))) return false;
2877
+ }
2878
+ return true;
2879
+ });
2880
+ }
2881
+ parseNegate() {
2882
+ if (this.nonegate) return;
2883
+ const pattern = this.pattern;
2884
+ let negate = false;
2885
+ let negateOffset = 0;
2886
+ for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
2887
+ negate = !negate;
2888
+ negateOffset++;
2889
+ }
2890
+ if (negateOffset) this.pattern = pattern.slice(negateOffset);
2891
+ this.negate = negate;
2892
+ }
2893
+ #matchRow(file, resolved, pattern, partial) {
2894
+ let fileStartIndex = 0;
2895
+ let patternStartIndex = 0;
2896
+ const fh = this.isWindows ? uncHost(resolved) : -1;
2897
+ const ph = fh === -1 ? -1 : uncHost(pattern);
2898
+ if (ph !== -1) {
2899
+ const host = pattern[ph];
2900
+ const share = pattern[ph + 1];
2901
+ if (typeof host !== "string" || typeof share !== "string") {
2902
+ fileStartIndex = fh;
2903
+ patternStartIndex = ph;
2904
+ } else if (resolved[fh].toLowerCase() === host.toLowerCase() && resolved[fh + 1].toLowerCase() === share.toLowerCase()) {
2905
+ fileStartIndex = fh + 2;
2906
+ patternStartIndex = ph + 2;
2907
+ }
2908
+ } else if (this.isWindows) {
2909
+ const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
2910
+ const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
2911
+ const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);
2912
+ const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
2913
+ const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;
2914
+ const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;
2915
+ if (typeof fdi === "number" && typeof pdi === "number") {
2916
+ const [fd, pd] = [file[fdi], pattern[pdi]];
2917
+ if (fd.toLowerCase() === pd.toLowerCase()) {
2918
+ patternStartIndex = pdi + 1;
2919
+ fileStartIndex = fdi + 1;
2920
+ }
2921
+ }
2922
+ }
2923
+ file = resolved;
2924
+ if (pattern.includes(GLOBSTAR)) return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
2925
+ return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
2926
+ }
2927
+ #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
2928
+ const { head, body, tail, segments } = this.#getGlobstarParts(pattern, partial, patternIndex);
2929
+ if (head.length) {
2930
+ const headEnd = fileIndex + head.length;
2931
+ if (!this.#matchOne(file, head, partial, fileIndex, 0, headEnd)) return false;
2932
+ fileIndex += head.length;
2933
+ patternIndex += head.length;
2934
+ }
2935
+ let fileTailMatch = 0;
2936
+ if (tail.length) {
2937
+ if (tail.length + fileIndex > file.length) return false;
2938
+ let tailStart = file.length - tail.length;
2939
+ if (this.#matchOne(file, tail, partial, tailStart, 0)) fileTailMatch = tail.length;
2940
+ else {
2941
+ if (file[file.length - 1] !== "" || fileIndex + tail.length === file.length) return false;
2942
+ tailStart--;
2943
+ if (!this.#matchOne(file, tail, partial, tailStart, 0)) return false;
2944
+ fileTailMatch = tail.length + 1;
2945
+ }
2946
+ }
2947
+ if (!body.length) {
2948
+ let sawSome = !!fileTailMatch;
2949
+ for (let i = fileIndex; i < file.length - fileTailMatch; i++) {
2950
+ const f = String(file[i]);
2951
+ sawSome = true;
2952
+ if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) return false;
2953
+ }
2954
+ return partial || sawSome;
2955
+ }
2956
+ return !!this.#matchGlobStarBodySections(file, segments, file.length - fileTailMatch, fileIndex, 0, partial, 0, !!fileTailMatch, /* @__PURE__ */ new Set());
2957
+ }
2958
+ #getGlobstarParts(pattern, partial, patternIndex) {
2959
+ let byStart = this.#globstarParts.get(pattern);
2960
+ if (!byStart) {
2961
+ byStart = [];
2962
+ this.#globstarParts.set(pattern, byStart);
2963
+ }
2964
+ const key = patternIndex * 2 + (partial ? 1 : 0);
2965
+ const found = byStart[key];
2966
+ if (found) return found;
2967
+ const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
2968
+ const lastgs = pattern.lastIndexOf(GLOBSTAR);
2969
+ const head = pattern.slice(patternIndex, firstgs);
2970
+ const body = pattern.slice(firstgs + 1, partial ? void 0 : lastgs);
2971
+ const tail = partial ? [] : pattern.slice(lastgs + 1);
2972
+ const segments = [[[], 0]];
2973
+ let current = segments[0];
2974
+ let nonGsParts = 0;
2975
+ const nonGsPartsSums = [0];
2976
+ for (const b of body) if (b === GLOBSTAR) {
2977
+ nonGsPartsSums.push(nonGsParts);
2978
+ current = [[], 0];
2979
+ segments.push(current);
2980
+ } else {
2981
+ current[0].push(b);
2982
+ nonGsParts++;
2983
+ }
2984
+ segments.forEach((b, i) => {
2985
+ b[1] = nonGsParts - nonGsPartsSums[i];
2986
+ });
2987
+ const parts = {
2988
+ head,
2989
+ body,
2990
+ tail,
2991
+ segments
2992
+ };
2993
+ byStart[key] = parts;
2994
+ return parts;
2995
+ }
2996
+ #matchGlobStarBodySections(file, bodySegments, fileLength, fileIndex, bodyIndex, partial, globStarDepth, sawTail, tried) {
2997
+ const bs = bodySegments[bodyIndex];
2998
+ if (!bs) {
2999
+ if (partial) return fileIndex >= fileLength || fileIndex === fileLength - 1 && file[fileIndex] === "";
3000
+ for (let i = fileIndex; i < fileLength; i++) {
3001
+ sawTail = true;
3002
+ const f = file[i];
3003
+ if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) return false;
3004
+ }
3005
+ return sawTail;
3006
+ }
3007
+ const [body, need] = bs;
3008
+ const after = partial ? fileLength : fileLength - need;
3009
+ while (fileIndex <= after) {
3010
+ const key = bodyIndex * (file.length + 1) + fileIndex;
3011
+ if (tried.has(key)) return false;
3012
+ tried.add(key);
3013
+ if (this.#matchOne(file, body, partial, fileIndex, 0, fileIndex + body.length) && globStarDepth < this.maxGlobstarRecursion) {
3014
+ const sub = this.#matchGlobStarBodySections(file, bodySegments, fileLength, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail, tried);
3015
+ if (sub !== false) return sub;
3016
+ }
3017
+ if (fileIndex === after) break;
3018
+ const f = file[fileIndex];
3019
+ if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) return false;
3020
+ fileIndex++;
3021
+ }
3022
+ return partial || null;
3023
+ }
3024
+ #matchOne(file, pattern, partial, fileIndex, patternIndex, fileEnd = file.length) {
3025
+ let fi;
3026
+ let pi;
3027
+ let pl;
3028
+ let fl;
3029
+ for (fi = fileIndex, pi = patternIndex, fl = Math.min(fileEnd, file.length), pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
3030
+ let p = pattern[pi];
3031
+ let f = file[fi];
3032
+ /* c8 ignore start */
3033
+ if (p === false || p === GLOBSTAR) return false;
3034
+ /* c8 ignore stop */
3035
+ if (!portionMatch(p, f)) return false;
3036
+ }
3037
+ if (fi === fl && pi === pl) return true;
3038
+ else if (fi === fl) return partial;
3039
+ else if (pi === pl) return fi === fl - 1 && file[fi] === "";
3040
+ else throw new Error("wtf?");
3041
+ /* c8 ignore stop */
3042
+ }
3043
+ braceExpand() {
3044
+ return braceExpand(this.pattern, this.options);
3045
+ }
3046
+ #expandBraces() {
3047
+ const { pattern } = this;
3048
+ if (this.options.nobrace) return this.braceExpand();
3049
+ let code = 57344;
3050
+ while (pattern.includes(String.fromCharCode(code))) if (++code > 63743) return this.braceExpand();
3051
+ const mark = String.fromCharCode(code);
3052
+ let found = false;
3053
+ const marked = pattern.replace(rangeRe, (m, lo, hi) => {
3054
+ const a = Number(lo);
3055
+ const b = Number(hi);
3056
+ if (!Number.isSafeInteger(a) || !Number.isSafeInteger(b) || Math.abs(a - b) + 1 < RANGE_MIN) return m;
3057
+ found = true;
3058
+ return `${mark}${lo}..${hi}${mark}`;
3059
+ });
3060
+ if (!found) return this.braceExpand();
3061
+ const set = braceExpand(marked, this.options);
3062
+ for (const p of set) for (const portion of p.split("/")) {
3063
+ const c = portion.indexOf("[");
3064
+ if (c !== -1 && c < portion.lastIndexOf(mark)) return this.braceExpand();
3065
+ if (!this.options.noext && inRepeatOrNegExt(portion, mark)) return this.braceExpand();
3066
+ }
3067
+ this.#rangeMark = mark;
3068
+ return set;
3069
+ }
3070
+ parse(pattern) {
3071
+ assertValidPattern(pattern);
3072
+ const options = this.options;
3073
+ if (pattern === "**") return GLOBSTAR;
3074
+ if (pattern === "") return "";
3075
+ const { nocase, nocaseMagicOnly, noext = false, dot, normalize } = options;
3076
+ const rangeMark = this.#rangeMark;
3077
+ const lit = rangeMark && pattern.includes(rangeMark) ? void 0 : literal(pattern, noext);
3078
+ if (lit !== void 0 && !(nocase && !nocaseMagicOnly && pattern.toUpperCase() !== pattern.toLowerCase())) return this.#norm(lit);
3079
+ if (this.#pending) return PENDING;
3080
+ let m = this.#matchers.get(pattern);
3081
+ if (!m) {
3082
+ if (!noext) assertValidExtglobs(pattern);
3083
+ m = new Matcher(pattern, {
3084
+ nocase,
3085
+ noext,
3086
+ dot,
3087
+ normalize,
3088
+ ...rangeMark && { rangeMark }
3089
+ });
3090
+ this.#matchers.set(pattern, m);
3091
+ }
3092
+ return m;
3093
+ }
3094
+ #slashSplit(p) {
3095
+ if (this.preserveMultipleSlashes) return p.split("/");
3096
+ else if (this.isWindows && /^\/\/[^/]+/.test(p)) return ["", ...p.split(/\/+/)];
3097
+ else return p.split(/\/+/);
3098
+ }
3099
+ match(f, partial = this.partial) {
3100
+ if (this.comment) return false;
3101
+ if (this.empty) return f === "";
3102
+ if (f === "/" && partial) return true;
3103
+ const options = this.options;
3104
+ let split = this.#cachedSplit(f);
3105
+ if (!split) {
3106
+ if (!partial && !this.#form && (this.#endCheck || this.#literalCheck) && lastChecked !== f) {
3107
+ lastChecked = f;
3108
+ const can = this.#canMatch(f);
3109
+ if (can === "no") return options.flipNegate ? false : this.negate;
3110
+ if (can === "yes") return options.flipNegate ? true : !this.negate;
3111
+ }
3112
+ split = this.#split(f);
3113
+ }
3114
+ const ff = split.parts;
3115
+ const resolved = this.#level2 ? split.resolved ??= this.#levelTwoFileOptimize(ff) : ff;
3116
+ const set = this.set;
3117
+ let filename = ff[ff.length - 1];
3118
+ if (!filename) for (let i = ff.length - 2; !filename && i >= 0; i--) filename = ff[i];
3119
+ for (let r = 0; r < set.length; r++) {
3120
+ const pattern = set[r];
3121
+ const shape = partial ? void 0 : this.#shapes[r];
3122
+ if (shape === "base" ? portionMatch(pattern[0], filename) : shape ? this.#matchShape(resolved, pattern, shape) : options.matchBase && pattern.length === 1 ? this.#matchRow([filename], [filename], pattern, partial) : this.#matchRow(ff, resolved, pattern, partial)) {
3123
+ if (options.flipNegate) return true;
3124
+ return !this.negate;
3125
+ }
3126
+ }
3127
+ if (options.flipNegate) return false;
3128
+ return this.negate;
3129
+ }
3130
+ static defaults(def) {
3131
+ return minimatch.defaults(def).Minimatch;
3132
+ }
3133
+ };
3134
+ /* c8 ignore stop */
3135
+ minimatch.Minimatch = Minimatch;
3136
+ minimatch.escape = escape;
3137
+ minimatch.unescape = unescape;
3138
+ // ../internal/src/build/runtime-package-files.ts
3139
+ const alwaysPublishedFile = /^(?:package\.json|(?:readme|copying|licen[cs]e)(?:\..*[^~$])?)$/i;
3140
+ const rootExcluded = /* @__PURE__ */ new Set([
3141
+ "package-lock.json",
3142
+ "yarn.lock",
3143
+ "pnpm-lock.yaml",
3144
+ "bun.lockb",
3145
+ ".lock-wscript",
3146
+ "build/config.gypi"
3147
+ ]);
3148
+ const excludedEntry = /^(?:node_modules|\.git|\.hg|\.svn|CVS|\.npmrc|\.npmignore|\.gitignore|\.DS_Store|npm-debug\.log|\._.*|.*\.orig|\..*\.swp)$/i;
3149
+ function hasNodeModulesSegment$1(path) {
3150
+ return path.split(/[\\/]/).includes("node_modules");
3151
+ }
3152
+ function isNestedPath(path) {
3153
+ return Boolean(path) && path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path);
3154
+ }
3155
+ /** Runs a filesystem read, and returns `undefined` when the path is gone. */
3156
+ async function unlessGone(read) {
3157
+ try {
3158
+ return await read();
3159
+ } catch (error) {
3160
+ const { code } = error;
3161
+ if (code === "ENOENT" || code === "ENOTDIR") return void 0;
3162
+ throw error;
3163
+ }
3164
+ }
3165
+ function readIfPresent(read) {
3166
+ try {
3167
+ return read();
3168
+ } catch (error) {
3169
+ if (error.code === "ENOENT") return void 0;
3170
+ throw error;
3171
+ }
3172
+ }
3173
+ function packageRule(entry) {
3174
+ const include = !entry.startsWith("!");
3175
+ const matcher = new Minimatch((include ? entry : entry.slice(1)).replace(/^\.\//, "/").replace(/\/$/, "") || "**", {
3176
+ dot: true,
3177
+ matchBase: true,
3178
+ nocase: true,
3179
+ nocomment: true,
3180
+ nonegate: true
3181
+ });
3182
+ return {
3183
+ include,
3184
+ matches: (path, partial = false) => matcher.match(path, partial) || matcher.match(`/${path}`, partial)
3185
+ };
3186
+ }
3187
+ /** Files selected for a linked package's publish list; `undefined` keeps the whole package. */
3188
+ function publishedPackagePaths(packageDir) {
3189
+ let manifest;
3190
+ const contents = readIfPresent(() => readFileSync(join(packageDir, "package.json"), "utf8"));
3191
+ if (contents === void 0) return void 0;
3192
+ try {
3193
+ manifest = JSON.parse(contents);
3194
+ } catch {
3195
+ return;
3196
+ }
3197
+ if (!manifest || typeof manifest !== "object" || !("files" in manifest) || !Array.isArray(manifest.files)) return void 0;
3198
+ const rules = [];
3199
+ const required = /* @__PURE__ */ new Set();
3200
+ const requiredAncestors = /* @__PURE__ */ new Set();
3201
+ const requirePath = (entry) => {
3202
+ const path = relative(packageDir, join(packageDir, entry));
3203
+ if (!isNestedPath(path)) return;
3204
+ required.add(path);
3205
+ for (let parent = dirname(path); parent !== "."; parent = dirname(parent)) requiredAncestors.add(parent);
3206
+ };
3207
+ for (const entry of manifest.files) {
3208
+ if (typeof entry !== "string" || !entry) continue;
3209
+ const candidate = join(packageDir, entry);
3210
+ if (!entry.startsWith("!") && isNestedPath(relative(packageDir, candidate)) && readIfPresent(() => lstatSync(candidate))?.isFile()) requirePath(entry);
3211
+ else rules.push(packageRule(entry.endsWith("/*") ? `${entry}*` : entry));
3212
+ }
3213
+ if ("main" in manifest && typeof manifest.main === "string") requirePath(manifest.main);
3214
+ if ("browser" in manifest && typeof manifest.browser === "string") requirePath(manifest.browser);
3215
+ if ("bin" in manifest) {
3216
+ const bin = manifest.bin;
3217
+ if (typeof bin === "string") requirePath(bin);
3218
+ else if (bin && typeof bin === "object") {
3219
+ for (const file of Object.values(bin)) if (typeof file === "string") requirePath(file);
3220
+ }
3221
+ }
3222
+ const files = /* @__PURE__ */ new Set();
3223
+ const entries = /* @__PURE__ */ new Set([""]);
3224
+ const visit = (directory, ancestors, inheritedIgnores) => {
3225
+ const children = readIfPresent(() => readdirSync(join(packageDir, directory)));
3226
+ if (!children) return;
3227
+ let ignores = inheritedIgnores;
3228
+ if (directory) {
3229
+ const ignore = readIfPresent(() => readFileSync(join(packageDir, directory, ".npmignore"), "utf8")) ?? readIfPresent(() => readFileSync(join(packageDir, directory, ".gitignore"), "utf8"));
3230
+ if (ignore) {
3231
+ const localRules = ignore.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith("#")).map(packageRule);
3232
+ ignores = [...ignores, (paths, included) => {
3233
+ for (const rule of localRules) if (paths.slice(ancestors.length).some((path) => rule.matches(path.slice(directory.length + 1)))) included = !rule.include;
3234
+ return included;
3235
+ }];
3236
+ }
3237
+ }
3238
+ for (const child of children) {
3239
+ const path = join(directory, child);
3240
+ const portablePath = path.replaceAll(sep, "/");
3241
+ if (excludedEntry.test(child) || rootExcluded.has(portablePath) || child.includes("*")) continue;
3242
+ const prefixes = [...ancestors, portablePath];
3243
+ let included = false;
3244
+ for (const rule of rules) if (prefixes.some((prefix) => rule.matches(prefix))) included = rule.include;
3245
+ const includeFile = included && ignores.every((ignore) => ignore(prefixes, true)) || required.has(path) || !directory && alwaysPublishedFile.test(child);
3246
+ const includeDirectory = included || requiredAncestors.has(path) || rules.some((rule) => rule.include && rule.matches(portablePath, true));
3247
+ if (!includeFile && !includeDirectory) continue;
3248
+ const info = readIfPresent(() => lstatSync(join(packageDir, path)));
3249
+ if (info?.isDirectory() && includeDirectory) visit(path, prefixes, ignores);
3250
+ else if (info?.isFile() && includeFile) {
3251
+ files.add(path);
3252
+ for (let entry = path; entry !== "." && !entries.has(entry); entry = dirname(entry)) entries.add(entry);
910
3253
  }
911
3254
  }
912
3255
  };
3256
+ visit("", [], []);
3257
+ return {
3258
+ files,
3259
+ entries
3260
+ };
913
3261
  }
914
- /** Matches import paths as esbuild's `external` does: `*` is a wildcard, and a package name also matches its subpaths. */
915
- function createExternalMatcher(patterns) {
916
- if (!patterns?.length) return;
917
- const matchers = patterns.map((pattern) => {
918
- if (pattern.includes("*")) {
919
- const expression = new RegExp(`^${pattern.split("*").map(escapeRegExp$1).join(".*")}$`);
920
- return (id) => expression.test(id);
3262
+ /** A published file or a directory that contains one. */
3263
+ function isPublishedPackagePath(packageDir, publishedPaths, path) {
3264
+ return !publishedPaths || publishedPaths.entries.has(relative(packageDir, path));
3265
+ }
3266
+ /** Copies a filtered source tree, preserving symlinks, while tolerating disappearance entry by entry. */
3267
+ async function copyRetainedSourceTree(source, target, filter) {
3268
+ async function copyEntry(source, target, freshParent) {
3269
+ if (!filter(source)) return;
3270
+ const info = await unlessGone(() => lstat(source));
3271
+ if (!info) return;
3272
+ if (info.isFile() && freshParent) {
3273
+ await unlessGone(() => copyFile(source, target));
3274
+ return;
921
3275
  }
922
- return isBareSpecifier(pattern) ? (id) => id === pattern || id.startsWith(`${pattern}/`) : (id) => id === pattern;
923
- });
924
- return (id) => matchers.some((matches) => matches(id));
3276
+ if (!info.isDirectory()) {
3277
+ await unlessGone(() => cp(source, target));
3278
+ return;
3279
+ }
3280
+ const entries = await unlessGone(() => readdir(source));
3281
+ if (!entries) return;
3282
+ const created = await mkdir(target, { recursive: true });
3283
+ for (const entry of entries) await copyEntry(join(source, entry), join(target, entry), created !== void 0);
3284
+ if (created) await chmod(target, info.mode);
3285
+ }
3286
+ await copyEntry(source, target, false);
3287
+ }
3288
+ /** Copies a file or folder and follows links. `node_modules` folders and paths that disappear during the copy are skipped. */
3289
+ async function copyTree(source, target) {
3290
+ const info = await unlessGone(() => stat(source));
3291
+ if (!info) return;
3292
+ if (!info.isDirectory()) {
3293
+ await unlessGone(() => copyFile(source, target));
3294
+ return;
3295
+ }
3296
+ const entries = await unlessGone(() => readdir(source));
3297
+ if (!entries) return;
3298
+ await mkdir(target, { recursive: true });
3299
+ for (const entry of entries) if (entry !== "node_modules") await copyTree(join(source, entry), join(target, entry));
925
3300
  }
926
- async function bundleEsmEntry(entryFile, outfile, options = {}) {
927
- const { rolldown } = await importRolldown();
928
- options.signal?.throwIfAborted();
929
- const format = options.format || "esm";
930
- const platform = options.platform || "neutral";
931
- const workingDir = options.workingDir ?? process.cwd();
932
- const frameworkRuntime = (Array.isArray(options.alias) ? options.alias.flatMap((alias) => typeof alias.find === "string" ? [alias.find] : []) : Object.keys(options.alias || {})).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
933
- const plugins = [];
934
- plugins.push(createWasmModulePlugin(dirname(outfile), workingDir, platform !== "node"));
935
- const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), workingDir, options.resolveEntryPackageAliases);
936
- if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
937
- plugins.push(...options.plugins ?? [], createFileUrlPlugin());
938
- const viteAliasPlugin = createViteAliasPlugin(options.alias, workingDir);
939
- if (viteAliasPlugin) plugins.push(viteAliasPlugin);
940
- plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime, workingDir));
941
- if (options.packages === "external") plugins.push(createExternalPackagesPlugin());
942
- plugins.push(createOptionalImportPlugin());
943
- const isExternal = createExternalMatcher(options.external);
944
- const minify = options.minifyIdentifiers || options.minifySyntax || options.minifyWhitespace ? {
945
- compress: options.minifySyntax ?? false,
946
- mangle: options.minifyIdentifiers ? { toplevel: true } : false,
947
- codegen: { removeWhitespace: options.minifyWhitespace ?? false }
948
- } : false;
949
- const banner = [options.banner, ...format === "esm" && platform === "node" ? [
950
- "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
951
- " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
952
- " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
953
- " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
954
- "}"
955
- ] : []].filter(Boolean).join("\n");
956
- const bundle = await rolldown({
957
- cwd: workingDir,
958
- external: isExternal ? (id) => isExternal(id) : void 0,
959
- input: entryFile,
960
- onLog(level, log) {
961
- if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
962
- },
963
- moduleTypes: platform === "node" ? { ".wasm": "binary" } : void 0,
964
- platform,
965
- plugins,
966
- resolve: {
967
- conditionNames: options.conditions ?? (platform === "node" ? ["node"] : void 0),
968
- extensions: options.extensions,
969
- mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
970
- symlinks: !options.preserveSymlinks
971
- },
972
- transform: {
973
- define: options.define,
974
- target: "es2022"
975
- },
976
- tsconfig: options.tsconfig ?? true
977
- });
978
- let output;
979
- try {
980
- output = (await bundle.generate({
981
- banner: banner || void 0,
982
- codeSplitting: false,
983
- format,
984
- keepNames: options.keepNames ?? Boolean(options.minifySyntax || options.minifyIdentifiers),
985
- minify,
986
- polyfillRequire: !(format === "esm" && platform === "node"),
987
- sourcemap: false
988
- })).output;
989
- } finally {
990
- await bundle.close();
3301
+ /**
3302
+ * Copies one runtime package into deployment output, without its `node_modules`.
3303
+ *
3304
+ * An installed package only holds its published files. A linked workspace package, such as a `link:` or `workspace:`
3305
+ * dependency, is a whole source folder with tests and fixtures, so only the files that `npm publish` would ship are
3306
+ * copied. A path that disappears during the copy, such as a temporary test folder that another process removes, is
3307
+ * skipped instead of failing the build.
3308
+ */
3309
+ async function copyRuntimePackageFiles(packageDir, targetDir) {
3310
+ const paths = hasNodeModulesSegment$1(packageDir) ? void 0 : publishedPackagePaths(packageDir);
3311
+ if (!paths) {
3312
+ await copyTree(packageDir, targetDir);
3313
+ return;
3314
+ }
3315
+ await mkdir(targetDir, { recursive: true });
3316
+ for (const path of paths.files) {
3317
+ const target = join(targetDir, path);
3318
+ await mkdir(dirname(target), { recursive: true });
3319
+ await unlessGone(() => copyFile(join(packageDir, path), target));
991
3320
  }
992
- options.signal?.throwIfAborted();
993
- const chunk = output.find((file) => file.type === "chunk");
994
- await mkdir(dirname(outfile), { recursive: true });
995
- await writeFile(outfile, chunk.code, { signal: options.signal });
996
- options.signal?.throwIfAborted();
997
3321
  }
998
- //#endregion
999
- //#region ../internal/src/build/scan-module.ts
3322
+ // ../internal/src/build/scan-module.ts
1000
3323
  /**
1001
3324
  * Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
1002
3325
  * the oxc parser that Vite ships through Rolldown, and never runs it. Values that are not static literals read as
@@ -1208,8 +3531,7 @@ function maskLiterals(module) {
1208
3531
  for (const span of literalSpans(module)) for (let index = span.start; index < span.end; index++) if (!isLineTerminator(output[index] ?? "")) output[index] = " ";
1209
3532
  return output.join("");
1210
3533
  }
1211
- //#endregion
1212
- //#region ../internal/src/build/provider-output-sources.ts
3534
+ // ../internal/src/build/provider-output-sources.ts
1213
3535
  function escapeRegExp(value) {
1214
3536
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1215
3537
  }
@@ -1468,18 +3790,21 @@ function dependencyRoots(root) {
1468
3790
  return [...new Set(roots)];
1469
3791
  }
1470
3792
  async function linkDependencies(source, target, resolveLinkTarget = (source) => source) {
3793
+ const entries = await unlessGone(() => readdir(source));
3794
+ if (!entries) return;
1471
3795
  await mkdir(target, { recursive: true });
1472
- for (const entry of await readdir(source, { withFileTypes: true })) {
1473
- if (entry.name === ".bin" || entry.name === ".pnpm") continue;
1474
- const sourceEntry = resolve(source, entry.name);
1475
- const targetEntry = resolve(target, entry.name);
1476
- if (!existsSync(sourceEntry)) continue;
1477
- const resolvedSourceEntry = realpathSync(sourceEntry);
1478
- if (!statSync(resolvedSourceEntry).isDirectory()) continue;
1479
- if (entry.name.startsWith("@") && entry.isDirectory() && !entry.isSymbolicLink()) {
3796
+ for (const entry of entries) {
3797
+ if (entry === ".bin" || entry === ".pnpm") continue;
3798
+ const sourceEntry = resolve(source, entry);
3799
+ const targetEntry = resolve(target, entry);
3800
+ const sourceType = await unlessGone(() => lstat(sourceEntry));
3801
+ if (!sourceType) continue;
3802
+ if (entry.startsWith("@") && sourceType.isDirectory()) {
1480
3803
  await linkDependencies(sourceEntry, targetEntry, resolveLinkTarget);
1481
3804
  continue;
1482
3805
  }
3806
+ const resolvedSourceEntry = await unlessGone(() => realpath(sourceEntry));
3807
+ if (!resolvedSourceEntry || !(await unlessGone(() => stat(resolvedSourceEntry)))?.isDirectory()) continue;
1483
3808
  if (existsSync(targetEntry)) continue;
1484
3809
  await symlink(resolveLinkTarget(resolvedSourceEntry), targetEntry, process.platform === "win32" ? "junction" : "dir");
1485
3810
  }
@@ -2142,15 +4467,18 @@ async function retainProviderOutputSources(options) {
2142
4467
  referencedAncestors.add(directory);
2143
4468
  if (directory === root) break;
2144
4469
  }
4470
+ const referencedSourceSet = new Set(referencedSources);
4471
+ const publishedPaths = new Map([...referencedPackages].map((sourcePackage) => [sourcePackage, publishedPackagePaths(sourcePackage)]));
2145
4472
  const isReferencedSource = (path) => {
2146
4473
  if (referencedAncestors.has(path)) return true;
2147
4474
  for (let directory = path; pathContains$1(root, directory); directory = dirname(directory)) {
2148
- if (referencedTrees.has(directory)) return true;
4475
+ if (referencedSourceSet.has(directory)) return true;
4476
+ if (publishedPaths.has(directory)) return isPublishedPackagePath(directory, publishedPaths.get(directory), path);
2149
4477
  if (directory === root) break;
2150
4478
  }
2151
4479
  return false;
2152
4480
  };
2153
- const nestedDependencyRoots = /* @__PURE__ */ new Map();
4481
+ const nestedDependencyRoots = new Map([...referencedPackages].map((sourcePackage) => [resolve(retainedRoot, relative(root, sourcePackage), "node_modules"), resolve(sourcePackage, "node_modules")]));
2154
4482
  const temporaryRoot = await mkdtemp(resolve(tmpdir(), "vitehub-provider-sources-"));
2155
4483
  const stagedContainer = resolve(temporaryRoot, "source");
2156
4484
  const stagedRoot = resolve(stagedContainer, relative(captureRoot, root));
@@ -2178,33 +4506,26 @@ async function retainProviderOutputSources(options) {
2178
4506
  if (nestedGeneratedOutput || ignoredIndex !== -1 && !packageOutput) return requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || [...importedSources].some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || requestedOutputRoots.some((outputRoot) => pathContains$1(outputRoot, resolvedSource)) || configuredOutputClosures.some((outputRoot) => pathContains$1(outputRoot, resolvedSource) && !relative(outputRoot, resolvedSource).split(sep).some((segment) => ignoredSourceDirectories.has(segment))) && !nestedConfiguredRoots.some((configuredRoot) => pathContains$1(configuredRoot, resolvedSource)) || nestedConfiguredRoots.some((configuredRoot) => pathContains$1(resolvedSource, configuredRoot));
2179
4507
  return true;
2180
4508
  };
2181
- await cp(root, stagedRoot, {
2182
- recursive: true,
2183
- filter: (source) => shouldCopySource(resolve(source))
2184
- });
2185
- const escapedMaterializedSources = materializedSources.filter((source) => !pathContains$1(root, source)).filter((source, _, sources) => !sources.some((parent) => parent !== source && statSync(parent).isDirectory() && pathContains$1(parent, source)));
4509
+ await copyRetainedSourceTree(root, stagedRoot, (source) => shouldCopySource(resolve(source)));
4510
+ const escapedMaterializedSources = materializedSources.filter((source) => !pathContains$1(root, source)).filter((source, _, sources) => !sources.some((parent) => parent !== source && pathContains$1(parent, source) && statSync(parent, { throwIfNoEntry: false })?.isDirectory()));
2186
4511
  for (const source of escapedMaterializedSources) {
2187
4512
  const retainedSource = resolve(stagedContainer, relative(captureRoot, source));
2188
4513
  await mkdir(dirname(retainedSource), { recursive: true });
2189
- await cp(realpathSync(source), retainedSource, {
2190
- filter: (path) => !isLocalSecretFile(path),
2191
- recursive: statSync(source).isDirectory()
2192
- });
4514
+ const sourceTarget = await unlessGone(() => realpath(source));
4515
+ if (sourceTarget) await copyRetainedSourceTree(sourceTarget, retainedSource, (path) => !isLocalSecretFile(path));
2193
4516
  }
2194
4517
  for (const source of requestedSymlinks) {
2195
4518
  const retainedSource = resolve(stagedRoot, relative(root, source));
2196
- const sourceTarget = realpathSync(source);
4519
+ const sourceTarget = await unlessGone(() => realpath(source));
4520
+ if (!sourceTarget) continue;
2197
4521
  await rm(retainedSource, {
2198
4522
  force: true,
2199
4523
  recursive: true
2200
4524
  });
2201
- await cp(sourceTarget, retainedSource, {
2202
- recursive: statSync(source).isDirectory(),
2203
- filter(candidate) {
2204
- const physicalCandidate = resolve(candidate);
2205
- const logicalCandidate = resolve(source, relative(sourceTarget, physicalCandidate));
2206
- return materializedSources.some((path) => pathContains$1(logicalCandidate, path) || pathContains$1(path, logicalCandidate) || pathContains$1(physicalCandidate, path) || pathContains$1(path, physicalCandidate)) && shouldCopySource(logicalCandidate);
2207
- }
4525
+ await copyRetainedSourceTree(sourceTarget, retainedSource, (candidate) => {
4526
+ const physicalCandidate = resolve(candidate);
4527
+ const logicalCandidate = resolve(source, relative(sourceTarget, physicalCandidate));
4528
+ return materializedSources.some((path) => pathContains$1(logicalCandidate, path) || pathContains$1(path, logicalCandidate) || pathContains$1(physicalCandidate, path) || pathContains$1(path, physicalCandidate)) && shouldCopySource(logicalCandidate);
2208
4529
  });
2209
4530
  }
2210
4531
  await rebaseCapturedAbsoluteSourceLinks(stagedContainer, captureRoot, retainedContainer);
@@ -2292,8 +4613,10 @@ async function retainProviderOutputSources(options) {
2292
4613
  return root ? resolve(retainedRoots.get(root), relative(root, resolvedPath)) : path;
2293
4614
  } };
2294
4615
  }
2295
- //#endregion
2296
- //#region ../internal/src/build/vercel-config.ts
4616
+ // ../internal/src/build/vercel-config.ts
4617
+ function createDefaultVercelOutputRoot(rootDir) {
4618
+ return resolve(rootDir, ".vercel", "output");
4619
+ }
2297
4620
  function createVercelConfigJson() {
2298
4621
  return {
2299
4622
  routes: [{ handle: "filesystem" }, {
@@ -2313,8 +4636,309 @@ function createNodeFunctionConfig(extra = {}) {
2313
4636
  ...extra
2314
4637
  };
2315
4638
  }
2316
- //#endregion
2317
- //#region ../internal/src/build/provider-output-catalog.ts
4639
+ // ../internal/src/build/runtime-package-resolution.ts
4640
+ /** Locates package metadata through exports, an entry's ancestors, or the project's dependency roots. */
4641
+ function createRuntimePackageResolver(readPackageName) {
4642
+ return async (name, resolver, fromDir) => {
4643
+ try {
4644
+ return resolver.resolve(`${name}/package.json`);
4645
+ } catch (error) {
4646
+ if (!isPackageResolutionMiss(error)) throw error;
4647
+ }
4648
+ try {
4649
+ let current = dirname(resolver.resolve(name));
4650
+ while (current !== dirname(current)) {
4651
+ const candidate = join(current, "package.json");
4652
+ try {
4653
+ await access(candidate);
4654
+ if (readPackageName(await readFile(candidate, "utf8"), candidate) === name) return candidate;
4655
+ } catch (error) {
4656
+ if (error.code !== "ENOENT") throw error;
4657
+ }
4658
+ current = dirname(current);
4659
+ }
4660
+ } catch (error) {
4661
+ if (!isPackageResolutionMiss(error)) throw error;
4662
+ }
4663
+ let current = fromDir;
4664
+ while (current !== dirname(current)) {
4665
+ const candidate = join(current, "node_modules", ...name.split("/"), "package.json");
4666
+ try {
4667
+ await access(candidate);
4668
+ return candidate;
4669
+ } catch (error) {
4670
+ if (error.code !== "ENOENT") throw error;
4671
+ }
4672
+ current = dirname(current);
4673
+ }
4674
+ };
4675
+ }
4676
+ function isPackageResolutionMiss(error) {
4677
+ const code = error?.code;
4678
+ return code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED";
4679
+ }
4680
+ // ../internal/src/build/runtime-package-directory.ts
4681
+ /** Update a staged copy, then publish it with rollback on failure or cancellation. */
4682
+ async function updateRuntimePackageDirectory(options) {
4683
+ const stagingRoot = await mkdtemp(join(dirname(options.directory), ".vitehub-runtime-packages-"));
4684
+ const stagedDirectory = join(stagingRoot, "node_modules");
4685
+ const previousDirectory = join(stagingRoot, "previous-node_modules");
4686
+ let movedPreviousOutput = false;
4687
+ let installedReplacement = false;
4688
+ let cleanupStagingRoot = true;
4689
+ try {
4690
+ try {
4691
+ await cp(options.directory, stagedDirectory, { recursive: true });
4692
+ } catch (error) {
4693
+ if (error.code !== "ENOENT") throw error;
4694
+ }
4695
+ await mkdir(stagedDirectory, { recursive: true });
4696
+ await options.update(stagedDirectory);
4697
+ options.signal?.throwIfAborted();
4698
+ try {
4699
+ await rename(options.directory, previousDirectory);
4700
+ movedPreviousOutput = true;
4701
+ cleanupStagingRoot = false;
4702
+ } catch (error) {
4703
+ if (error.code !== "ENOENT") throw error;
4704
+ }
4705
+ try {
4706
+ options.signal?.throwIfAborted();
4707
+ await rename(stagedDirectory, options.directory);
4708
+ installedReplacement = true;
4709
+ options.signal?.throwIfAborted();
4710
+ cleanupStagingRoot = true;
4711
+ } catch (error) {
4712
+ if (installedReplacement) await rm(options.directory, {
4713
+ force: true,
4714
+ recursive: true
4715
+ });
4716
+ if (movedPreviousOutput) await rename(previousDirectory, options.directory);
4717
+ cleanupStagingRoot = true;
4718
+ throw error;
4719
+ }
4720
+ } finally {
4721
+ if (cleanupStagingRoot) await rm(stagingRoot, {
4722
+ force: true,
4723
+ recursive: true
4724
+ });
4725
+ }
4726
+ }
4727
+ // ../internal/src/build/vercel-runtime-packages.ts
4728
+ const runtimeExportConditions = /* @__PURE__ */ new Set([
4729
+ "default",
4730
+ "import",
4731
+ "module",
4732
+ "node",
4733
+ "node-addons",
4734
+ "require"
4735
+ ]);
4736
+ const resolvePackageJson = createRuntimePackageResolver((source, path) => parsePackageJson(JSON.parse(source), path).name);
4737
+ let nodeFileTracePromise;
4738
+ /** Collects the runtime packages that features add to Vercel functions, then traces and copies them once per function. */
4739
+ function createVercelFunctionRuntimePackagesPass(beforeWrite) {
4740
+ const requests = [];
4741
+ return {
4742
+ add(request) {
4743
+ requests.push(request);
4744
+ },
4745
+ async copy(signal) {
4746
+ const functions = /* @__PURE__ */ new Map();
4747
+ for (const request of requests.splice(0)) {
4748
+ const outputRoot = request.outputRoot ?? createDefaultVercelOutputRoot(request.rootDir);
4749
+ const serverDir = resolve(outputRoot, "functions", request.serverFunctionName ?? "__server.func");
4750
+ const entry = functions.get(serverDir) ?? {
4751
+ requests: [],
4752
+ rootDir: request.rootDir
4753
+ };
4754
+ entry.requests.push(request);
4755
+ functions.set(serverDir, entry);
4756
+ }
4757
+ for (const [serverDir, entry] of functions) await copyFunctionRuntimePackages(serverDir, entry.rootDir, entry.requests, signal, beforeWrite);
4758
+ }
4759
+ };
4760
+ }
4761
+ async function copyFunctionRuntimePackages(serverDir, rootDir, requests, signal, beforeWrite) {
4762
+ try {
4763
+ await access(serverDir);
4764
+ } catch (error) {
4765
+ if (error.code === "ENOENT") return;
4766
+ throw error;
4767
+ }
4768
+ const groups = [];
4769
+ for (const request of requests) {
4770
+ const requested = Array.isArray(request.packages) ? request.packages : await request.packages();
4771
+ if (requested.length) groups.push(requested.map((runtimePackage) => ({
4772
+ ...runtimePackage,
4773
+ resolveFrom: runtimePackage.resolveFrom ?? join(request.rootDir, "package.json")
4774
+ })));
4775
+ }
4776
+ if (!groups.length) return;
4777
+ const directory = resolve(serverDir, "node_modules");
4778
+ await beforeWrite?.(directory);
4779
+ await updateRuntimePackageDirectory({
4780
+ directory,
4781
+ signal,
4782
+ update: (outputNodeModules) => copyNodeRuntimePackageGroups(outputNodeModules, rootDir, groups)
4783
+ });
4784
+ }
4785
+ async function copyNodeRuntimePackageGroups(outputNodeModules, rootDir, groups) {
4786
+ const selected = /* @__PURE__ */ new Map();
4787
+ const requested = /* @__PURE__ */ new Map();
4788
+ for (const packages of groups) {
4789
+ const visited = /* @__PURE__ */ new Set();
4790
+ const expanded = /* @__PURE__ */ new Set();
4791
+ for (const runtimePackage of packages) {
4792
+ const resolveFrom = runtimePackage.resolveFrom ?? join(rootDir, "package.json");
4793
+ const resolver = createRequire(resolveFrom);
4794
+ const packageJsonPath = await selectRuntimePackage(runtimePackage.name, resolver, dirname(resolveFrom), selected, visited, expanded, runtimePackage);
4795
+ if (!packageJsonPath) continue;
4796
+ const previous = requested.get(runtimePackage.name);
4797
+ if (previous && previous !== packageJsonPath) throw internalErrorDiagnostics.INTERNAL_RUNTIME_PACKAGE_VERSION_CONFLICT({
4798
+ first: dirname(previous),
4799
+ name: runtimePackage.name,
4800
+ second: dirname(packageJsonPath)
4801
+ });
4802
+ requested.set(runtimePackage.name, packageJsonPath);
4803
+ }
4804
+ }
4805
+ for (const [name, { packageJson, packageJsonPath, resolver }] of selected) {
4806
+ const packageDir = dirname(packageJsonPath);
4807
+ const targetDir = join(outputNodeModules, ...name.split("/"));
4808
+ await rm(targetDir, {
4809
+ force: true,
4810
+ recursive: true
4811
+ });
4812
+ if (!await copyTracedPackageFiles(name, resolver, packageDir, packageJsonPath, packageJson, targetDir)) await copyRuntimePackageFiles(packageDir, targetDir);
4813
+ }
4814
+ }
4815
+ async function selectRuntimePackage(name, resolver, fromDir, selected, visited, expanded, options = { name }) {
4816
+ const packageJsonPath = await resolvePackageJson(name, resolver, fromDir);
4817
+ if (!packageJsonPath) {
4818
+ if (options.optional) return void 0;
4819
+ throw internalErrorDiagnostics.INTERNAL_B0046({ message: `Could not resolve package.json for ${name}.` });
4820
+ }
4821
+ const resolvedPackageJsonPath = await realpath(packageJsonPath);
4822
+ const packageDir = dirname(resolvedPackageJsonPath);
4823
+ const packageJson = parsePackageJson(JSON.parse(await readFile(resolvedPackageJsonPath, "utf8")), resolvedPackageJsonPath);
4824
+ const packageKey = `${name}\0${resolvedPackageJsonPath}`;
4825
+ if (!visited.has(packageKey)) {
4826
+ visited.add(packageKey);
4827
+ selected.set(name, {
4828
+ packageJson,
4829
+ packageJsonPath: resolvedPackageJsonPath,
4830
+ resolver
4831
+ });
4832
+ }
4833
+ const expansionKey = `${packageKey}\0${options.includePeerDependencies ? "peers" : "dependencies"}`;
4834
+ if (expanded.has(expansionKey)) return resolvedPackageJsonPath;
4835
+ expanded.add(expansionKey);
4836
+ const packageRequire = createRequire(resolvedPackageJsonPath);
4837
+ const dependencyNames = new Set(Object.keys(packageJson.dependencies || {}));
4838
+ const optionalDependencyNames = new Set(Object.keys(packageJson.optionalDependencies || {}));
4839
+ for (const dependencyName of optionalDependencyNames) dependencyNames.add(dependencyName);
4840
+ const requiredPeerDependencyNames = /* @__PURE__ */ new Set();
4841
+ if (options.includePeerDependencies) {
4842
+ for (const dependencyName of Object.keys(packageJson.peerDependencies || {})) if (!packageJson.peerDependenciesMeta?.[dependencyName]?.optional) {
4843
+ dependencyNames.add(dependencyName);
4844
+ requiredPeerDependencyNames.add(dependencyName);
4845
+ }
4846
+ }
4847
+ for (const dependencyName of dependencyNames) await selectRuntimePackage(dependencyName, packageRequire, packageDir, selected, visited, expanded, {
4848
+ includePeerDependencies: options.includePeerDependencies,
4849
+ name: dependencyName,
4850
+ optional: optionalDependencyNames.has(dependencyName) && !requiredPeerDependencyNames.has(dependencyName)
4851
+ });
4852
+ return resolvedPackageJsonPath;
4853
+ }
4854
+ async function copyTracedPackageFiles(name, resolver, packageDir, packageJsonPath, packageJson, targetDir) {
4855
+ const entries = await resolvePackageTraceEntries(name, resolver, packageDir, packageJson);
4856
+ if (!entries) return false;
4857
+ const { fileList } = await (await loadNodeFileTrace())([...entries], {
4858
+ base: packageDir,
4859
+ conditions: ["node"],
4860
+ exportsOnly: true,
4861
+ processCwd: packageDir
4862
+ });
4863
+ fileList.add(relative(packageDir, packageJsonPath));
4864
+ for (const file of fileList) {
4865
+ const source = resolve(packageDir, file);
4866
+ if (!isInsideDirectory(packageDir, source) || hasNodeModulesSegment(file)) continue;
4867
+ if (!(await stat(source)).isFile()) continue;
4868
+ const target = resolve(targetDir, file);
4869
+ await mkdir(dirname(target), { recursive: true });
4870
+ await copyFile(source, target);
4871
+ }
4872
+ return true;
4873
+ }
4874
+ async function loadNodeFileTrace() {
4875
+ nodeFileTracePromise ??= import("./out-By90R-Bo.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1)).then(({ nodeFileTrace }) => nodeFileTrace);
4876
+ return nodeFileTracePromise;
4877
+ }
4878
+ async function resolvePackageTraceEntries(name, resolver, packageDir, packageJson) {
4879
+ const entryCandidates = /* @__PURE__ */ new Set();
4880
+ if (packageJson.exports) {
4881
+ const exportedTargets = collectRuntimeExportTargets(packageJson.exports);
4882
+ if (!exportedTargets) return void 0;
4883
+ for (const target of exportedTargets) entryCandidates.add(resolve(packageDir, target));
4884
+ } else {
4885
+ try {
4886
+ entryCandidates.add(resolver.resolve(name));
4887
+ } catch (error) {
4888
+ if (!isPackageResolutionMiss(error)) throw error;
4889
+ }
4890
+ if (packageJson.main) entryCandidates.add(resolve(packageDir, packageJson.main));
4891
+ if (packageJson.module) entryCandidates.add(resolve(packageDir, packageJson.module));
4892
+ entryCandidates.add(resolve(packageDir, "index.js"));
4893
+ }
4894
+ const entries = [];
4895
+ for (const candidate of entryCandidates) try {
4896
+ const candidateStat = await stat(candidate);
4897
+ if (candidateStat.isFile()) entries.push(candidate);
4898
+ else if (candidateStat.isDirectory()) return void 0;
4899
+ } catch (error) {
4900
+ if (error.code !== "ENOENT") throw error;
4901
+ }
4902
+ return entries.length ? entries : void 0;
4903
+ }
4904
+ function collectRuntimeExportTargets(exportsValue, condition) {
4905
+ if (typeof exportsValue === "string") {
4906
+ if (condition === "types") return /* @__PURE__ */ new Set();
4907
+ if (exportsValue.includes("*")) return void 0;
4908
+ return exportsValue.startsWith("./") ? /* @__PURE__ */ new Set([exportsValue]) : /* @__PURE__ */ new Set();
4909
+ }
4910
+ if (Array.isArray(exportsValue)) {
4911
+ const targets = /* @__PURE__ */ new Set();
4912
+ for (const entry of exportsValue) {
4913
+ const entryTargets = collectRuntimeExportTargets(entry, condition);
4914
+ if (!entryTargets) return void 0;
4915
+ for (const target of entryTargets) targets.add(target);
4916
+ }
4917
+ return targets;
4918
+ }
4919
+ if (typeof exportsValue !== "object" || exportsValue === null) return /* @__PURE__ */ new Set();
4920
+ const targets = /* @__PURE__ */ new Set();
4921
+ for (const [key, value] of Object.entries(exportsValue)) {
4922
+ if (key === "types") continue;
4923
+ if (!key.startsWith(".") && !runtimeExportConditions.has(key)) continue;
4924
+ const entryTargets = collectRuntimeExportTargets(value, key);
4925
+ if (!entryTargets) return void 0;
4926
+ for (const target of entryTargets) targets.add(target);
4927
+ }
4928
+ return targets;
4929
+ }
4930
+ function hasNodeModulesSegment(path) {
4931
+ return path.split(/[\\/]/).includes("node_modules");
4932
+ }
4933
+ function isInsideDirectory(parent, child) {
4934
+ const childRelativePath = relative(parent, child);
4935
+ return childRelativePath === "" || !childRelativePath.startsWith(`..${sep}`) && childRelativePath !== ".." && !isAbsolute(childRelativePath);
4936
+ }
4937
+ function parsePackageJson(value, path) {
4938
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw internalErrorDiagnostics.INTERNAL_B0047({ message: `Expected ${path} to contain a JSON object.` });
4939
+ return value;
4940
+ }
4941
+ // ../internal/src/build/provider-output-catalog.ts
2318
4942
  var ProviderOutputCatalog = class {
2319
4943
  bundleDefines = {};
2320
4944
  #appliedCloudflareContributions = /* @__PURE__ */ new Map();
@@ -2542,8 +5166,7 @@ function useProviderOutputCatalog(config) {
2542
5166
  providerOutputCatalogs.set(config, catalog);
2543
5167
  return catalog;
2544
5168
  }
2545
- //#endregion
2546
- //#region ../internal/src/build/deployment-output.ts
5169
+ // ../internal/src/build/deployment-output.ts
2547
5170
  const providerDeploymentOutputRegistry = globalThis;
2548
5171
  const providerDeploymentOutputWrites = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputWrites ??= /* @__PURE__ */ new Map();
2549
5172
  const providerDeploymentOutputFinalizations = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputFinalizations ??= /* @__PURE__ */ new WeakMap();
@@ -2634,9 +5257,6 @@ async function writeProviderOutputOwnershipFiles(outputRoot, ownership, files) {
2634
5257
  await writeFile(file, `${JSON.stringify(values, null, 2)}\n`, "utf8");
2635
5258
  }));
2636
5259
  }
2637
- function createDefaultVercelOutputRoot(rootDir) {
2638
- return resolve(rootDir, ".vercel", "output");
2639
- }
2640
5260
  function createDefaultNetlifyOutputRoot(rootDir) {
2641
5261
  return resolve(rootDir, ".netlify", "v1");
2642
5262
  }
@@ -3477,9 +6097,11 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
3477
6097
  const write = withProviderDeploymentOutputRootLock(rootDir, async () => {
3478
6098
  await withProviderDeploymentOutputRootTransaction(rootDir, async (transaction) => {
3479
6099
  try {
6100
+ const vercelRuntimePackages = createVercelFunctionRuntimePackagesPass((nodeModules) => transaction.snapshot([nodeModules]));
3480
6101
  for (const contribution of rootContributions) {
3481
6102
  throwIfProviderOutputAborted(controller.signal);
3482
6103
  await contribution.write({
6104
+ addVercelRuntimePackages: (request) => vercelRuntimePackages.add(request),
3483
6105
  readCloudflareState: async (options) => await readCloudflareProviderDeploymentOutputState(rootDir, options),
3484
6106
  signal: controller.signal,
3485
6107
  write: async (writeOptions) => {
@@ -3495,6 +6117,8 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
3495
6117
  });
3496
6118
  throwIfProviderOutputAborted(controller.signal);
3497
6119
  }
6120
+ await vercelRuntimePackages.copy(controller.signal);
6121
+ throwIfProviderOutputAborted(controller.signal);
3498
6122
  ready();
3499
6123
  const rollback = await rootDecision;
3500
6124
  if (rollback !== void 0) throw rollback;
@@ -3554,14 +6178,12 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
3554
6178
  if (providerDeploymentOutputFinalizations.get(catalog) === active) providerDeploymentOutputFinalizations.delete(catalog);
3555
6179
  }
3556
6180
  }
3557
- //#endregion
3558
- //#region ../internal/src/durability.ts
6181
+ // ../internal/src/durability.ts
3559
6182
  /** The `durability` module next to the Vite plugin module at `importMetaUrl`, in source and in `dist`. */
3560
6183
  function durabilityModuleFile(importMetaUrl) {
3561
6184
  return fileURLToPath(new URL(importMetaUrl.endsWith(".ts") ? "./durability.ts" : "./durability.js", importMetaUrl));
3562
6185
  }
3563
- //#endregion
3564
- //#region ../internal/src/definition-catalog.ts
6186
+ // ../internal/src/definition-catalog.ts
3565
6187
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
3566
6188
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
3567
6189
  const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
@@ -3720,8 +6342,7 @@ async function writeFileIfChanged(file, contents) {
3720
6342
  await mkdir(resolve$1(file, ".."), { recursive: true });
3721
6343
  await writeFile(file, contents, "utf8");
3722
6344
  }
3723
- //#endregion
3724
- //#region ../internal/src/hints.ts
6345
+ // ../internal/src/hints.ts
3725
6346
  /**
3726
6347
  * The file that lists the hints of the last build or dev server, relative to the project root. A hint is a warning
3727
6348
  * about something that works now and fails later, such as counts that stay in one server's memory. Agents and CI read
@@ -3809,8 +6430,7 @@ function hostFromNitroPreset(value) {
3809
6430
  if (normalized === "node" || normalized.startsWith("node-")) return "node";
3810
6431
  if (normalized.startsWith("vercel")) return "vercel";
3811
6432
  }
3812
- //#endregion
3813
- //#region ../internal/src/hosting.ts
6433
+ // ../internal/src/hosting.ts
3814
6434
  /**
3815
6435
  * Returns the Nitro preset name that this build targets, as the developer wrote it.
3816
6436
  * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOST`.
@@ -3831,8 +6451,8 @@ function resolveHostPreset(input = {}) {
3831
6451
  function resolveHost(input = {}) {
3832
6452
  return hostFromNitroPreset(resolveHostPreset(input));
3833
6453
  }
3834
- //#endregion
3835
- //#region ../internal/src/nitro-kit.ts
6454
+ Object.freeze({ vitehubAuthAccess: "handler" });
6455
+ Object.freeze({ vitehubOwnAccess: true });
3836
6456
  function cloneArray(value) {
3837
6457
  return Array.isArray(value) ? [...value] : [];
3838
6458
  }
@@ -3860,8 +6480,7 @@ function createNitroServerKit(value = {}) {
3860
6480
  }
3861
6481
  };
3862
6482
  }
3863
- //#endregion
3864
- //#region src/deployment-env.ts
6483
+ // src/deployment-env.ts
3865
6484
  /**
3866
6485
  * The variables that Schedules read on the deployed host. The Vercel cron handler refuses every request until
3867
6486
  * `CRON_SECRET` is set, so it is required. Cloudflare cron triggers and the Process Runtime read none.
@@ -3876,8 +6495,7 @@ function scheduleDeploymentEnv(definitions, context) {
3876
6495
  owners: ["schedule"]
3877
6496
  }];
3878
6497
  }
3879
- //#endregion
3880
- //#region ../internal/src/contributions.ts
6498
+ // ../internal/src/contributions.ts
3881
6499
  const unnamedPlugin = "unnamed plugin";
3882
6500
  function isNonEmptyString(value) {
3883
6501
  return String(value) === value && value.length > 0;
@@ -3915,6 +6533,10 @@ async function collectContributions(plugins, options) {
3915
6533
  const candidates = [];
3916
6534
  await flattenPlugins(plugins ?? [], candidates, /* @__PURE__ */ new Set());
3917
6535
  const collected = /* @__PURE__ */ new Map();
6536
+ const context = {
6537
+ ...options.context,
6538
+ plugins: candidates
6539
+ };
3918
6540
  for (const plugin of candidates) {
3919
6541
  if (!Object.hasOwn(plugin, "vitehub")) continue;
3920
6542
  const metadata = Reflect.get(plugin, "vitehub");
@@ -3926,7 +6548,7 @@ async function collectContributions(plugins, options) {
3926
6548
  throw options.invalid(`[vitehub] Plugin ${JSON.stringify(contributor)} contributed an invalid ${options.kind}: ${reason}`);
3927
6549
  };
3928
6550
  const callable = typeof source === "function";
3929
- const entries = callable ? await Reflect.apply(source, void 0, [options.context]) : source;
6551
+ const entries = callable ? await Reflect.apply(source, void 0, [context]) : source;
3930
6552
  if (entries === void 0 && callable) continue;
3931
6553
  if (!Array.isArray(entries)) fail(`\`vitehub.${options.key}\` must be an array or a function that returns one.`);
3932
6554
  const list = entries;
@@ -3978,8 +6600,7 @@ function readContribution(entry, plugin, options, fail) {
3978
6600
  ...base
3979
6601
  };
3980
6602
  }
3981
- //#endregion
3982
- //#region src/contributions.ts
6603
+ // src/contributions.ts
3983
6604
  const scheduleNamePattern = /^[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)*$/i;
3984
6605
  /** Error for a Schedule name with two definitions. Both sources are named so the user knows which to rename. */
3985
6606
  function duplicateScheduleError(name, first, second) {
@@ -4008,8 +6629,7 @@ async function collectScheduleContributions(plugins, context) {
4008
6629
  }
4009
6630
  return contributions;
4010
6631
  }
4011
- //#endregion
4012
- //#region src/discovery.ts
6632
+ // src/discovery.ts
4013
6633
  /** Discovery source of Schedule Definitions that Vite plugins contribute through `vitehub.schedules`. */
4014
6634
  const contributedScheduleSource = "vite-plugin-contribution";
4015
6635
  /**
@@ -4136,11 +6756,6 @@ function startedTickSource() {
4136
6756
  ""
4137
6757
  ].join("\n");
4138
6758
  }
4139
- /**
4140
- * The Schedule that wakes started Schedules. It is a plain Schedule with `* * * * *`, so each host wakes it the way it
4141
- * wakes any Schedule: a Cron Trigger on Cloudflare, the Process Runtime on Node. The build reads its cron from source, so
4142
- * the module is a file in the project.
4143
- */
4144
6759
  function startedTickDefinition(rootDir) {
4145
6760
  const file = resolve(rootDir, startedTickFile);
4146
6761
  const source = startedTickSource();
@@ -4178,13 +6793,11 @@ function discoverScheduleDefinitions(options) {
4178
6793
  function discoverStartableScheduleDefinitions(options) {
4179
6794
  return discoverAllScheduleDefinitions(options).filter((definition) => definition.startable);
4180
6795
  }
4181
- //#endregion
4182
- //#region src/integrations/vercel.ts
6796
+ // src/integrations/vercel.ts
4183
6797
  function getVercelSchedulePath(name) {
4184
6798
  return `/api/vitehub/schedules/vercel/${name.replace(/[^a-z0-9/_-]+/gi, "_")}`;
4185
6799
  }
4186
- //#endregion
4187
- //#region src/internal/time-zone-cron.ts
6800
+ // src/internal/time-zone-cron.ts
4188
6801
  const dayMs = 864e5;
4189
6802
  const dayMinutes = 1440;
4190
6803
  const sampledDays = 732;
@@ -4245,8 +6858,7 @@ function expandCron(cron, offsets) {
4245
6858
  })}`;
4246
6859
  return `${time} * * *`;
4247
6860
  }
4248
- //#endregion
4249
- //#region src/internal/provider-output.ts
6861
+ // src/internal/provider-output.ts
4250
6862
  const schedulePackageName = "@vite-hub/schedule";
4251
6863
  const scheduleStaticRuntimeImport = "@vite-hub/schedule/runtime/static";
4252
6864
  const productName = "schedule";
@@ -4340,14 +6952,22 @@ async function removeEmptyDirectories(directory, rootDir) {
4340
6952
  }
4341
6953
  }
4342
6954
  const cronFieldPattern = /^[*,/\-0-9]+$/;
4343
- function validateProviderCron(cron, scheduleName) {
6955
+ /** Whether host wake output accepts `cron`: five numeric UTC fields that Cloudflare, Vercel, and Netlify all read. */
6956
+ function isProviderCron(cron) {
4344
6957
  const fields = cron.trim().split(/\s+/);
4345
6958
  const hasVercelDayConflict = fields[2] !== "*" && fields[4] !== "*";
4346
- if (fields.length !== 5 || !fields.every((field) => cronFieldPattern.test(field)) || hasVercelDayConflict) throw scheduleErrorDiagnostics.SCHEDULE_R0003({ message: `Schedule "${scheduleName}" uses cron "${cron}", but provider wake output only supports five-field UTC cron syntax compatible with Cloudflare, Vercel, and Netlify.` });
6959
+ return fields.length === 5 && fields.every((field) => cronFieldPattern.test(field)) && !hasVercelDayConflict;
4347
6960
  }
4348
- function readStaticScheduleCron(file, scheduleName) {
6961
+ function validateProviderCron(cron, scheduleName) {
6962
+ if (!isProviderCron(cron)) throw scheduleErrorDiagnostics.SCHEDULE_R0003({ message: `Schedule "${scheduleName}" uses cron "${cron}", but provider wake output only supports five-field UTC cron syntax compatible with Cloudflare, Vercel, and Netlify.` });
6963
+ }
6964
+ /** Reads the `cron` option of a `defineSchedule()` call. Returns `undefined` when it is missing or not a static string. */
6965
+ function readStaticScheduleCronOption(file) {
4349
6966
  const definition = findDefaultExportCall(scanModule(readFileSync(file, "utf8"), file), ["defineSchedule"]);
4350
- const cron = definition?.options && staticString(findProperty(definition.options, "cron")?.value);
6967
+ return definition?.options && staticString(findProperty(definition.options, "cron")?.value) || void 0;
6968
+ }
6969
+ function readStaticScheduleCron(file, scheduleName) {
6970
+ const cron = readStaticScheduleCronOption(file);
4351
6971
  if (!cron) throw scheduleErrorDiagnostics.SCHEDULE_R0004({ message: `Schedule "${scheduleName}" must declare a static cron string for provider wake output.` });
4352
6972
  return cron;
4353
6973
  }
@@ -4403,7 +7023,7 @@ function renderProviderEntry(file, registryFile, provider, scheduleName, workflo
4403
7023
  const workflowRuntime = provider === "vercel" ? workflow : void 0;
4404
7024
  return [
4405
7025
  `import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
4406
- `import { executeStaticSchedule, ${provider === "vercel" ? "isScheduleCronAuthorized, " : ""}isTimeZoneWakeDue, missingScheduleDefinitionError, normalizeCron, ${provider === "vercel" ? "scheduledWakeTime, " : ""}unwrapScheduleDefinition } from ${JSON.stringify(runtimeImport)}`,
7026
+ `import { ${provider === "cloudflare" ? "cronWithWeekdayNames, " : ""}executeStaticSchedule, ${provider === "vercel" ? "isScheduleCronAuthorized, " : ""}isTimeZoneWakeDue, missingScheduleDefinitionError, normalizeCron, ${provider === "vercel" ? "scheduledWakeTime, " : ""}unwrapScheduleDefinition } from ${JSON.stringify(runtimeImport)}`,
4407
7027
  ...workflowRuntime ? [
4408
7028
  `import workflowRegistry from ${JSON.stringify(createImportPath(file, workflowRuntime.registryFile))}`,
4409
7029
  `import { setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from ${JSON.stringify(workflowRuntime.runtimeModules.state)}`,
@@ -4452,12 +7072,16 @@ function renderProviderEntry(file, registryFile, provider, scheduleName, workflo
4452
7072
  " },",
4453
7073
  " async scheduled(event, env, ctx) {",
4454
7074
  " if (typeof event.cron !== 'string' || !event.cron.trim()) return",
7075
+ " const trigger = normalizeCron(event.cron)",
4455
7076
  " const tasks = Object.entries(scheduleRegistry).map(async ([name]) => {",
4456
7077
  " const definition = await loadScheduleDefinition(name)",
4457
- " if (!definition || normalizeCron(scheduleCron(name, definition)) !== normalizeCron(event.cron)) return",
7078
+ " if (!definition) return",
7079
+ " const cron = normalizeCron(scheduleCron(name, definition))",
7080
+ " // wrangler.json has the cron with weekday names, so Cloudflare reads each weekday as declared.",
7081
+ " if (cronWithWeekdayNames(cron) !== trigger) return",
4458
7082
  " const scheduledAt = new Date(event.scheduledTime)",
4459
7083
  " if (!isWakeDue(name, definition, scheduledAt)) return",
4460
- " await executeStaticSchedule({ cron: event.cron, definition, name, scheduledAt, waitUntil: (promise) => ctx.waitUntil(promise) })",
7084
+ " await executeStaticSchedule({ cron, definition, name, scheduledAt, waitUntil: (promise) => ctx.waitUntil(promise) })",
4461
7085
  " })",
4462
7086
  " await Promise.all(tasks)",
4463
7087
  " },",
@@ -4535,28 +7159,24 @@ function netlifyScheduleFunctionNames(definitions) {
4535
7159
  }
4536
7160
  return names;
4537
7161
  }
4538
- function renderDenoCronEntry(file, registryFile, crons, runtimeImport = scheduleStaticRuntimeImport, timeZoneCrons = {}) {
4539
- const scheduleCrons = [...crons.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([name, cron], index) => {
4540
- const cronId = index.toString(36);
7162
+ const englishBuildHostOrder = new Intl.Collator("en-US");
7163
+ const denoCronNameLength = 64;
7164
+ function denoCronNames(scheduleNames) {
7165
+ const sorted = [...scheduleNames].sort((left, right) => englishBuildHostOrder.compare(left, right) || (left < right ? -1 : left > right ? 1 : 0));
7166
+ return new Map(sorted.map((name, index) => {
7167
+ const indexedName = `vitehub-${index.toString(36)}-${name}`;
7168
+ if (/^[a-z0-9 _-]*$/i.test(name) && indexedName.length <= denoCronNameLength) return [name, indexedName];
4541
7169
  const safeName = [...name].map((character) => /^[a-z0-9 _-]$/i.test(character) ? character : "_").join("");
4542
- const cronNamePrefix = `vitehub-${cronId}-`;
4543
- const fields = cron.trim().split(/\s+/);
4544
- if (fields[4] !== "*") {
4545
- const weekdays = [
4546
- "SUN",
4547
- "MON",
4548
- "TUE",
4549
- "WED",
4550
- "THU",
4551
- "FRI",
4552
- "SAT"
4553
- ];
4554
- fields[4] = parseCronExpression(cron).weekdays.map((day) => weekdays[day]).join(",");
4555
- }
7170
+ return [name, `${`vitehub_${createHash("sha256").update(name).digest("hex").slice(0, 12)}-`}${safeName}`.slice(0, denoCronNameLength)];
7171
+ }));
7172
+ }
7173
+ function renderDenoCronEntry(file, registryFile, crons, runtimeImport = scheduleStaticRuntimeImport, timeZoneCrons = {}) {
7174
+ const scheduleCrons = [...denoCronNames(crons.keys())].map(([name, cronName]) => {
7175
+ const cron = crons.get(name);
4556
7176
  return {
4557
7177
  cron,
4558
- cronName: `${cronNamePrefix}${safeName.slice(0, 64 - cronNamePrefix.length)}`,
4559
- denoCron: fields.join(" "),
7178
+ cronName,
7179
+ denoCron: cronWithWeekdayNames(cron),
4560
7180
  inTimeZone: Object.hasOwn(timeZoneCrons, name),
4561
7181
  name
4562
7182
  };
@@ -5105,7 +7725,7 @@ async function generateProviderOutputsWithinLock(options) {
5105
7725
  bundleAlias: options.bundleAlias,
5106
7726
  bundleDefines: options.bundleDefines,
5107
7727
  bundleEntry: artifacts.cloudflareWorkerFile,
5108
- crons: [...new Set(crons.values())],
7728
+ crons: [...new Set([...crons.values()].map(cronWithWeekdayNames))],
5109
7729
  rootDir: options.rootDir,
5110
7730
  previousStateFile: previousCloudflareStateFile,
5111
7731
  sourceRootDir: options.sourceRootDir,
@@ -5163,22 +7783,17 @@ async function generateProviderOutputsWithinLock(options) {
5163
7783
  throw error;
5164
7784
  }
5165
7785
  }
5166
- //#endregion
5167
- //#region src/inspect.ts
7786
+ // src/inspect.ts
5168
7787
  function inspectTimeZone(timeZone) {
5169
7788
  return timeZone === null ? "Not a static string" : timeZone ?? "UTC";
5170
7789
  }
5171
- /** The UTC cron that Cloudflare, Vercel, Netlify, and Deno run for a Schedule with a static `timeZone`. */
5172
7790
  function inspectHostCron(cron, timeZone) {
5173
- try {
5174
- const utcCron = utcCronForTimeZone(cron, timeZone);
5175
- return utcCron ? [{
5176
- label: "Host cron (UTC)",
5177
- value: utcCron
5178
- }] : [];
5179
- } catch {
5180
- return [];
5181
- }
7791
+ if (!isIanaTimeZone(timeZone) || !isProviderCron(cron) || !parseCronFields(cron)) return [];
7792
+ const utcCron = utcCronForTimeZone(cron, timeZone);
7793
+ return utcCron ? [{
7794
+ label: "Host cron (UTC)",
7795
+ value: utcCron
7796
+ }] : [];
5182
7797
  }
5183
7798
  function summarizeScheduleDefinition(projectRoot, definition, crons, overrides = {}) {
5184
7799
  const declaredCron = crons.get(definition.name);
@@ -5242,9 +7857,8 @@ async function inspectScheduleDefinitions(options) {
5242
7857
  const crons = /* @__PURE__ */ new Map();
5243
7858
  for (const definition of definitions) {
5244
7859
  if (definition.startable) continue;
5245
- try {
5246
- for (const [name, cron] of await readRuntimeDefinitionCrons([definition])) crons.set(name, cron);
5247
- } catch {}
7860
+ const cron = readStaticScheduleCronOption(definition.handler);
7861
+ if (cron) crons.set(definition.name, cron);
5248
7862
  }
5249
7863
  return definitions.map((definition) => summarizeScheduleDefinition(options.projectRoot, definition, crons, options.cron));
5250
7864
  }
@@ -5271,10 +7885,10 @@ function definitionRecord(summary) {
5271
7885
  },
5272
7886
  startable ? {
5273
7887
  label: "Runs",
5274
- value: `Use \`vitehub schedule list ${summary.name}\` to list the Schedules that code started, and \`vitehub schedule runs <id>\` for the runs of one.`
7888
+ value: `Use \`vitehub schedule list ${summary.name}\` to list the Schedules that code started, and \`vitehub schedule runs list <id>\` for the runs of one.`
5275
7889
  } : {
5276
7890
  label: "Runs",
5277
- value: `Use \`vitehub schedule runs ${summary.name}\` to list runs that this runtime recorded.`
7891
+ value: `Use \`vitehub schedule runs list ${summary.name}\` to list runs that this runtime recorded.`
5278
7892
  }
5279
7893
  ],
5280
7894
  id: `definition:${summary.name}`,
@@ -5288,7 +7902,7 @@ async function inspectScheduleConsoleRecords(options) {
5288
7902
  /**
5289
7903
  * Console section for Schedules. Records list discovered Schedule Definitions. When the server runs the Process Runtime,
5290
7904
  * the cron and time zone come from the loaded Definitions, so any expression shows its real value.
5291
- * `vitehub inspect definitions` reads the same Definitions from source, and `vitehub schedule runs <name>` lists the runs
7905
+ * `vitehub inspect definitions` reads the same Definitions from source, and `vitehub schedule runs list <name>` lists the runs
5292
7906
  * that a runtime recorded.
5293
7907
  */
5294
7908
  const scheduleConsoleSection = {
@@ -5320,8 +7934,7 @@ const scheduleConsoleSection = {
5320
7934
  notice: "The host runs each Schedule on its cron, in its time zone (UTC by default). A Definition without cron runs when code starts it with `startSchedule()`; each started Schedule has its own row. Static Definitions with `manual: true` can also run from the Console or `vitehub schedule run`."
5321
7935
  }
5322
7936
  };
5323
- //#endregion
5324
- //#region src/internal/registry-module.ts
7937
+ // src/internal/registry-module.ts
5325
7938
  /**
5326
7939
  * Renders the `#vitehub/schedule/registry` virtual module. A virtual module has no directory, so a relative import would
5327
7940
  * resolve against the Vite root, which is the app directory under Nuxt. Each definition is imported by its absolute
@@ -5338,8 +7951,7 @@ function renderScheduleRegistryModule(definitions) {
5338
7951
  ""
5339
7952
  ].join("\n");
5340
7953
  }
5341
- //#endregion
5342
- //#region src/vite.ts
7954
+ // src/vite.ts
5343
7955
  async function readScheduleDefinitionCrons(definitions) {
5344
7956
  return await readRuntimeDefinitionCrons(definitions);
5345
7957
  }
@@ -5396,10 +8008,6 @@ const databaseVitePluginName = "@vite-hub/database/vite";
5396
8008
  function hasVitePlugin(plugins, name) {
5397
8009
  return (plugins ?? []).some((plugin) => Array.isArray(plugin) ? hasVitePlugin(plugin, name) : isRecord(plugin) && plugin.name === name);
5398
8010
  }
5399
- /**
5400
- * Checks the build's `cron` map. `definitions` is the final Schedule set, or `undefined` while plugins can still
5401
- * contribute Schedules. The Process Runtime owns Static Schedule wakes unless `providerOutput` is `nitro` or `standalone`.
5402
- */
5403
8011
  function resolveCronOverrides(value, definitions, options) {
5404
8012
  if (value === void 0) return;
5405
8013
  if (!isRecord(value) || Array.isArray(value)) throw scheduleErrorDiagnostics.SCHEDULE_B0008({ message: "Schedule `cron` must map Schedule names to cron strings, such as `{ cleanup: \"0 0 * * *\" }`." });
@@ -5502,7 +8110,7 @@ function renderNitroSchedulePlugin(options) {
5502
8110
  ...options.inventoryRegistryFile ? [`import inventoryRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.inventoryRegistryFile))}`] : [],
5503
8111
  ...providerWake ? [`import scheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.providerRegistryFile))}`, `import { executeCloudflareStaticSchedules } from ${JSON.stringify(options.runtimeImport ?? scheduleStaticRuntimeModule)}`] : [],
5504
8112
  ...processRuntime ? [
5505
- `import { normalizeScheduleRuntimeError } from ${JSON.stringify(options.runtimeImport ?? scheduleStaticRuntimeModule)}`,
8113
+ `import { logScheduleRuntimeError, normalizeScheduleRuntimeError } from ${JSON.stringify(options.runtimeImport ?? scheduleStaticRuntimeModule)}`,
5506
8114
  `import { ${runStoreFactory} } from ${JSON.stringify(scheduleRuntimeModule)}`,
5507
8115
  `import { installProcessScheduleRuntime, onShutdown } from ${JSON.stringify(scheduleProcessRuntimeModule)}`,
5508
8116
  ...leaseDatabaseImport ? [`import { useLeases } from ${JSON.stringify(leaseDatabaseImport)}`] : [],
@@ -5530,7 +8138,8 @@ function renderNitroSchedulePlugin(options) {
5530
8138
  ` await executeCloudflareStaticSchedules(event, { ${[
5531
8139
  Object.keys(options.cronOverrides).length ? `cronOverrides: ${JSON.stringify(options.cronOverrides)}, ` : "",
5532
8140
  "registry: scheduleRegistry",
5533
- Object.keys(options.timeZoneCrons).length ? `, timeZoneCrons: ${JSON.stringify(options.timeZoneCrons)}` : ""
8141
+ Object.keys(options.timeZoneCrons).length ? `, timeZoneCrons: ${JSON.stringify(options.timeZoneCrons)}` : "",
8142
+ Object.keys(options.triggerCrons).length ? `, triggerCrons: ${JSON.stringify(options.triggerCrons)}` : ""
5534
8143
  ].join("")} })`,
5535
8144
  " })"
5536
8145
  ] : [],
@@ -5544,7 +8153,7 @@ function renderNitroSchedulePlugin(options) {
5544
8153
  " return",
5545
8154
  " }",
5546
8155
  " try {",
5547
- " console.error('[vitehub:schedule]', runtimeError)",
8156
+ " logScheduleRuntimeError(error, runtimeError)",
5548
8157
  " }",
5549
8158
  " catch {}",
5550
8159
  " try {",
@@ -5589,10 +8198,6 @@ function renderNitroSchedulePlugin(options) {
5589
8198
  ""
5590
8199
  ].join("\n");
5591
8200
  }
5592
- /**
5593
- * On Cloudflare, adds the cron triggers. On Netlify, Nitro has no cron, so each Schedule gets a scheduled function
5594
- * that runs it in Nitro's own server bundle: the plugins, aliases, and bindings of the app are the same as for requests.
5595
- */
5596
8201
  function renderNitroScheduleModule(options) {
5597
8202
  const { netlify } = options;
5598
8203
  let netlifyFunctionNames = /* @__PURE__ */ new Map();
@@ -5615,6 +8220,7 @@ function renderNitroScheduleModule(options) {
5615
8220
  const crons = Object.fromEntries(netlify.schedules.map((schedule) => [schedule.name, schedule.cron]));
5616
8221
  const timeZoneNames = netlify.schedules.filter((schedule) => schedule.inTimeZone).map((schedule) => schedule.name);
5617
8222
  const netlifyEntryRuntime = [
8223
+ "import { useNitroApp } from \"nitro/app\"",
5618
8224
  `import scheduleRegistry from ${JSON.stringify(netlify.registryFile)}`,
5619
8225
  `import { executeStaticSchedule, isTimeZoneWakeDue, missingScheduleDefinitionError, scheduledWakeTime, unwrapScheduleDefinition } from ${JSON.stringify(netlify.runtimeImport)}`,
5620
8226
  "",
@@ -5622,10 +8228,11 @@ function renderNitroScheduleModule(options) {
5622
8228
  `const timeZoneNames = new Set(${JSON.stringify(timeZoneNames)})`,
5623
8229
  "",
5624
8230
  "export async function runViteHubNetlifySchedule(name) {",
8231
+ " const scheduledAt = scheduledWakeTime(crons[name])",
8232
+ " await useNitroApp().ready",
5625
8233
  " const loader = scheduleRegistry[name]",
5626
8234
  " const definition = loader ? unwrapScheduleDefinition(await loader()) : undefined",
5627
8235
  " if (!definition) throw missingScheduleDefinitionError(name)",
5628
- " const scheduledAt = scheduledWakeTime(crons[name])",
5629
8236
  " if (timeZoneNames.has(name) && !isTimeZoneWakeDue(definition, name, scheduledAt)) return",
5630
8237
  " await executeStaticSchedule({ cron: crons[name], definition, name, scheduledAt })",
5631
8238
  "}",
@@ -5709,6 +8316,7 @@ async function writeNitroSchedulePlugin(root, options) {
5709
8316
  const inventoryRegistryFile = options.inventoryDefinitions.length ? resolve(root, generatedNitroInventoryRegistry) : void 0;
5710
8317
  const writes = [writeFileIfChanged(pluginFile, renderNitroSchedulePlugin({
5711
8318
  cronOverrides: options.cronOverrides,
8319
+ triggerCrons: options.triggerCrons,
5712
8320
  hostTimings: options.hostTimings,
5713
8321
  inventoryRegistryFile,
5714
8322
  timeZoneCrons: options.timeZoneCrons,
@@ -5762,6 +8370,24 @@ function selectNitroScheduleDefinitions(definitions, options) {
5762
8370
  if (options.providerOutput === "nitro") return definitions;
5763
8371
  return definitions.filter(isServerScheduleDefinition);
5764
8372
  }
8373
+ function selectHostCronDefinitions(definitions, options) {
8374
+ return resolveProcessRuntimeOptions(options.runtime) && options.providerOutput !== "nitro" ? [] : selectNitroScheduleDefinitions(definitions, options);
8375
+ }
8376
+ async function inspectScheduleResources(definitions, options, output) {
8377
+ const overrides = resolveCronOverrides(options.cron, definitions, options);
8378
+ const nitro = await readDefinitionCrons(output.nitro ? selectHostCronDefinitions(definitions, options) : [], overrides);
8379
+ const standalone = await readDefinitionCrons(output.standalone.filter((definition) => !nitro.has(definition.name)), overrides);
8380
+ const resource = (definition, cron, inStandalone) => ({
8381
+ definition,
8382
+ host: "cloudflare",
8383
+ kind: "cloudflare-cron",
8384
+ name: cronWithWeekdayNames(cron),
8385
+ note: inStandalone ? "Cloudflare runs the Schedule from `triggers.crons` in the Wrangler config of the standalone Schedule Worker." : "Cloudflare runs the Schedule from `triggers.crons` in the Wrangler config.",
8386
+ owner: "schedule",
8387
+ ...inStandalone ? { standalone: true } : {}
8388
+ });
8389
+ return [...[...nitro].map(([definition, cron]) => resource(definition, cron, false)), ...[...standalone].map(([definition, cron]) => resource(definition, cron, true))];
8390
+ }
5765
8391
  function selectStandaloneProviderSource(definitions, options) {
5766
8392
  if (options.providerOutput === "auto" || options.providerOutput === void 0) return hasServerScheduleDefinitions(definitions) ? "vite-suffix" : void 0;
5767
8393
  }
@@ -5810,10 +8436,11 @@ async function createScheduleNitroConfig(options = {}) {
5810
8436
  if (vercelDefinitions.length) nitro = mergeNitroVercelCrons(nitro, vercelDefinitions, await readDefinitionCrons(vercelDefinitions, cronOverrides));
5811
8437
  if (!installNitroPlugin) return nitro;
5812
8438
  if (processRuntime && options.command === "build" && !internal.preliminary && !internal.leaseDatabaseImport) reportViteHubHint(hints, scheduleErrorDiagnostics.SCHEDULE_PROCESS_CLAIMS_IN_MEMORY());
5813
- const nitroDefinitions = processRuntime && options.providerOutput !== "nitro" ? [] : selectNitroScheduleDefinitions(definitions, options);
8439
+ const nitroDefinitions = selectHostCronDefinitions(definitions, options);
5814
8440
  const nitroCrons = options.command === "build" ? await readDefinitionCrons(nitroDefinitions, cronOverrides) : /* @__PURE__ */ new Map();
5815
8441
  const timeZoneCrons = options.command === "build" ? readTimeZoneCrons(nitroDefinitions, cronOverrides) : {};
5816
- const crons = [...new Set(nitroCrons.values())];
8442
+ const triggerCrons = Object.fromEntries([...nitroCrons].map(([name, cron]) => [name, cronWithWeekdayNames(cron)]));
8443
+ const crons = [...new Set(Object.values(triggerCrons))];
5817
8444
  const netlifySchedules = [...nitroCrons].map(([name, cron]) => ({
5818
8445
  cron,
5819
8446
  ...Object.hasOwn(timeZoneCrons, name) ? { inTimeZone: true } : {},
@@ -5840,6 +8467,7 @@ async function createScheduleNitroConfig(options = {}) {
5840
8467
  });
5841
8468
  const plugin = await writeNitroSchedulePlugin(roots.projectRoot, {
5842
8469
  cronOverrides: Object.fromEntries(Object.entries(cronOverrides ?? {}).filter(([name]) => nitroDefinitionNames.has(name))),
8470
+ triggerCrons,
5843
8471
  hostTimings: Object.fromEntries(hostTimings),
5844
8472
  inventoryDefinitions,
5845
8473
  crons,
@@ -5876,10 +8504,14 @@ function hubSchedule(options = {}) {
5876
8504
  let viteRoot;
5877
8505
  let contributions = [];
5878
8506
  let command;
5879
- const processStorageOptions = (plugins) => ({
5880
- ...hasVitePlugin(plugins, databaseVitePluginName) ? { leaseDatabaseImport: internalOptions.databaseImport ?? "@vite-hub/database" } : {},
5881
- memoryProcessStores: internalOptions.requireKVPluginForProcessStores && !hasVitePlugin(plugins, "@vite-hub/kv/vite")
5882
- });
8507
+ let leaseDatabase = false;
8508
+ const processStorageOptions = (hasPlugin) => {
8509
+ leaseDatabase = hasPlugin(databaseVitePluginName);
8510
+ return {
8511
+ ...leaseDatabase ? { leaseDatabaseImport: internalOptions.databaseImport ?? "@vite-hub/database" } : {},
8512
+ memoryProcessStores: internalOptions.requireKVPluginForProcessStores && !hasPlugin("@vite-hub/kv/vite")
8513
+ };
8514
+ };
5883
8515
  async function collectPluginScheduleContributions(plugins, roots) {
5884
8516
  return await collectScheduleContributions(plugins, {
5885
8517
  projectRoot: roots.projectRoot,
@@ -5921,7 +8553,7 @@ function hubSchedule(options = {}) {
5921
8553
  contributions,
5922
8554
  nitroOwnsPaths: hasNitroConfigContext(config),
5923
8555
  nitro: config.nitro,
5924
- ...processStorageOptions(config.plugins),
8556
+ ...processStorageOptions(typeof Reflect.get(config, "__vitehubNuxtHints") === "function" ? (name) => hasVitePlugin(config.plugins, name) : (name) => hasViteConfigPlugin(env, name)),
5925
8557
  preliminary: true,
5926
8558
  root: config.root || process.cwd(),
5927
8559
  serverDirs
@@ -5940,7 +8572,7 @@ function hubSchedule(options = {}) {
5940
8572
  const definitions = discoverRegistrySchedules();
5941
8573
  emitStandaloneProviderOutput = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options);
5942
8574
  standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
5943
- const storage = processStorageOptions(config.plugins);
8575
+ const storage = processStorageOptions((name) => hasVitePlugin(config.plugins, name));
5944
8576
  if (config.command) {
5945
8577
  const nitro = await createScheduleNitroConfig({
5946
8578
  ...options,
@@ -6097,7 +8729,10 @@ function hubSchedule(options = {}) {
6097
8729
  inspectable.vitehub = {
6098
8730
  durability: () => options.runtime?.driver === "process" ? [{
6099
8731
  export: "scheduleDurability",
6100
- input: { driver: "process" },
8732
+ input: {
8733
+ driver: "process",
8734
+ leases: leaseDatabase
8735
+ },
6101
8736
  module: durabilityModuleFile(import.meta.url),
6102
8737
  primitive: "schedule"
6103
8738
  }] : [],
@@ -6106,23 +8741,34 @@ function hubSchedule(options = {}) {
6106
8741
  load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).scheduleOperations,
6107
8742
  module: ownModule(import.meta.url, "operations")
6108
8743
  }],
6109
- inspect: () => ({ definitions: [{
6110
- kind: "schedule",
6111
- label: "Schedules",
6112
- list: () => {
6113
- const roots = resolveSchedulePluginRoots(viteRoot ?? process.cwd(), options);
6114
- return inspectScheduleDefinitions({
6115
- cron: options.cron,
6116
- plugins: resolved?.plugins,
6117
- projectRoot: roots.projectRoot,
6118
- rootDir: roots.viteRoot,
6119
- serverDirs,
6120
- serverRootDir: roots.projectRoot
8744
+ inspect: () => ({
8745
+ definitions: [{
8746
+ kind: "schedule",
8747
+ label: "Schedules",
8748
+ list: () => {
8749
+ const roots = resolveSchedulePluginRoots(viteRoot ?? process.cwd(), options);
8750
+ return inspectScheduleDefinitions({
8751
+ cron: options.cron,
8752
+ plugins: resolved?.plugins,
8753
+ projectRoot: roots.projectRoot,
8754
+ rootDir: roots.viteRoot,
8755
+ serverDirs,
8756
+ serverRootDir: roots.projectRoot
8757
+ });
8758
+ }
8759
+ }],
8760
+ resources: async () => {
8761
+ const host = nitroPreset ? resolveHost({ nitro: { preset: nitroPreset } }) : (resolved && getDeploymentHost(resolved)) ?? resolveHost({ nitro: Reflect.get(resolved ?? {}, "nitro") });
8762
+ const definitions = discoverRegistrySchedules();
8763
+ const standaloneHost = resolveHost({ nitro: nitroPreset ? { preset: nitroPreset } : Reflect.get(resolved ?? {}, "nitro") });
8764
+ const standalone = emitStandaloneProviderOutput && (standaloneHost === void 0 || standaloneHost === "cloudflare") ? definitions.filter((definition) => !standaloneProviderSource || definition.source === standaloneProviderSource) : [];
8765
+ return await inspectScheduleResources(definitions, options, {
8766
+ nitro: host === "cloudflare",
8767
+ standalone
6121
8768
  });
6122
8769
  }
6123
- }] })
8770
+ })
6124
8771
  };
6125
8772
  return inspectable;
6126
8773
  }
6127
- //#endregion
6128
8774
  export { collectScheduleContributions, contributedScheduleSource, createScheduleNitroConfig, discoverScheduleDefinitions, discoverStartableScheduleDefinitions, hubSchedule, inspectScheduleDefinitions, readScheduleDefinitionCrons, scheduleConsoleSection };