@vite-hub/schedule 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +12 -7
  2. package/dist/{console-wEhr0LWn.d.ts → console-DueeEBcM.d.ts} +2 -0
  3. package/dist/cron-C1l3TquN.js +70 -0
  4. package/dist/definition.js +1 -2
  5. package/dist/{due-sOJvF_6Z.js → due-n120-_nz.js} +22 -7
  6. package/dist/durability.d.ts +2 -2
  7. package/dist/durability.js +5 -5
  8. package/dist/{error-diagnostics-CQ4BUqRe.js → error-diagnostics-C0KyI408.js} +5 -1
  9. package/dist/{error-diagnostics-BBtYYl8j.js → error-diagnostics-DTmP6baC.js} +1 -5
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.js +3 -4
  12. package/dist/{started-name-ruCM1EtQ.js → inspect-DTfAo5gS.js} +1 -5
  13. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CI2PJGqu.d.ts} +8 -2
  14. package/dist/{operations-DqwmJ8MN.js → operations-DlrK9mlH.js} +6 -9
  15. package/dist/operations.d.ts +1 -1
  16. package/dist/operations.js +5 -5
  17. package/dist/os.d.ts +0 -1
  18. package/dist/os.js +12 -84
  19. package/dist/out-BbXG-yVX.js +21755 -0
  20. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  21. package/dist/runtime/console.d.ts +1 -1
  22. package/dist/runtime/console.js +2 -2
  23. package/dist/runtime/process.js +24 -45
  24. package/dist/runtime/state.d.ts +1 -1
  25. package/dist/runtime/state.js +1 -1
  26. package/dist/runtime/static.d.ts +2 -73
  27. package/dist/runtime/static.js +3 -2
  28. package/dist/runtime.d.ts +3 -3
  29. package/dist/runtime.js +4 -4
  30. package/dist/{started-B0pc3JY0.js → started-BWWr7Ufw.js} +3 -4
  31. package/dist/{started-Bk2Icknk.js → started-BXdWMdji.js} +24 -6
  32. package/dist/{started-errors-DEmYH-vp.js → started-errors-BMg04lL3.js} +45 -5
  33. package/dist/started-name-DudQ0fsR.js +5 -0
  34. package/dist/{state-D4SZH6zk.js → state-BjWnxyhv.js} +70 -117
  35. package/dist/{state-CPd10SXq.d.ts → state-CJKAhskJ.d.ts} +2 -1
  36. package/dist/static-BgoOCoe5.js +610 -0
  37. package/dist/static-CcBWx1kU.d.ts +96 -0
  38. package/dist/{store-DeMojnXM.d.ts → store-CZHZfttA.d.ts} +2 -6
  39. package/dist/vite.d.ts +5 -3
  40. package/dist/vite.js +2251 -130
  41. package/package.json +4 -4
  42. package/dist/invariant-DolT9EEx.js +0 -22
  43. package/dist/static-7JCga3Iu.js +0 -281
  44. package/dist/wait-until-Dy4Bn3ZN.js +0 -112
package/dist/vite.js CHANGED
@@ -1,10 +1,12 @@
1
+ import { r as __toESM } from "./rolldown-runtime-CMFfr-1z.js";
1
2
  import { t as isIanaTimeZone } from "./time-zone-SBldrUgt.js";
2
3
  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";
4
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-DTmP6baC.js";
5
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-C0KyI408.js";
6
+ import { i as timeZoneOffsetMinutes, t as cronWithWeekdayNames } from "./due-n120-_nz.js";
7
+ import { t as startedSchedulesTickName } from "./started-name-DudQ0fsR.js";
8
+ import { a as relative$1, i as isAbsolute$1, n as relativeDefinitionFile, o as resolve$1, r as dirname$1 } from "./inspect-DTfAo5gS.js";
9
+ import { a as parseCronFields, l as invariant, u as invariantError } from "./cron-C1l3TquN.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,7 +15,7 @@ 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";
@@ -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,11 +140,15 @@ 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
  }
148
+ function isMissingProjectMarker(error) {
149
+ const code = error.code;
150
+ return code === "ENOENT" || code === "ENOTDIR";
151
+ }
136
152
  //#endregion
137
153
  //#region ../internal/src/build/paths.ts
138
154
  function generatedDirSegments(productName) {
@@ -923,6 +939,24 @@ function createExternalMatcher(patterns) {
923
939
  });
924
940
  return (id) => matchers.some((matches) => matches(id));
925
941
  }
942
+ /** Returns the modules of the chunks that no chunk loaded from the entry chunk imports. */
943
+ function findUnusedChunkModules(chunks) {
944
+ const used = new Set(chunks.filter((chunk) => chunk.isEntry));
945
+ for (const chunk of used) for (const other of chunks) if (!used.has(other) && chunk.code.includes(other.fileName)) used.add(other);
946
+ return new Set(chunks.filter((chunk) => !used.has(chunk)).flatMap((chunk) => chunk.moduleIds));
947
+ }
948
+ function createEmptyModulesPlugin(ids) {
949
+ return {
950
+ name: "vitehub-empty-unused-chunks",
951
+ load(id) {
952
+ if (ids.has(id)) return {
953
+ code: "",
954
+ moduleSideEffects: false,
955
+ moduleType: "js"
956
+ };
957
+ }
958
+ };
959
+ }
926
960
  async function bundleEsmEntry(entryFile, outfile, options = {}) {
927
961
  const { rolldown } = await importRolldown();
928
962
  options.signal?.throwIfAborted();
@@ -953,7 +987,7 @@ async function bundleEsmEntry(entryFile, outfile, options = {}) {
953
987
  " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
954
988
  "}"
955
989
  ] : []].filter(Boolean).join("\n");
956
- const bundle = await rolldown({
990
+ const build = (extraPlugins = [], shimMissingExports = false) => rolldown({
957
991
  cwd: workingDir,
958
992
  external: isExternal ? (id) => isExternal(id) : void 0,
959
993
  input: entryFile,
@@ -962,40 +996,1791 @@ async function bundleEsmEntry(entryFile, outfile, options = {}) {
962
996
  },
963
997
  moduleTypes: platform === "node" ? { ".wasm": "binary" } : void 0,
964
998
  platform,
965
- plugins,
999
+ plugins: [...extraPlugins, ...plugins],
966
1000
  resolve: {
967
1001
  conditionNames: options.conditions ?? (platform === "node" ? ["node"] : void 0),
968
1002
  extensions: options.extensions,
969
1003
  mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
970
1004
  symlinks: !options.preserveSymlinks
971
1005
  },
1006
+ shimMissingExports,
972
1007
  transform: {
973
1008
  define: options.define,
974
1009
  target: "es2022"
975
1010
  },
976
1011
  tsconfig: options.tsconfig ?? true
977
1012
  });
1013
+ const generate = async (bundle, codeSplitting) => (await bundle.generate({
1014
+ banner: banner || void 0,
1015
+ chunkFileNames: codeSplitting ? "chunk-[hash].js" : void 0,
1016
+ codeSplitting,
1017
+ format,
1018
+ keepNames: options.keepNames ?? Boolean(options.minifySyntax || options.minifyIdentifiers),
1019
+ minify,
1020
+ polyfillRequire: !(format === "esm" && platform === "node"),
1021
+ sourcemap: false
1022
+ })).output;
1023
+ let bundle = await build();
978
1024
  let output;
979
1025
  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;
1026
+ output = await generate(bundle, true);
1027
+ const chunks = output.filter((file) => file.type === "chunk");
1028
+ if (chunks.length > 1 || chunks.some((chunk) => chunk.dynamicImports.includes(chunk.fileName))) {
1029
+ options.signal?.throwIfAborted();
1030
+ const unusedModules = findUnusedChunkModules(chunks);
1031
+ if (unusedModules.size) {
1032
+ await bundle.close();
1033
+ bundle = await build([createEmptyModulesPlugin(unusedModules)], true);
1034
+ }
1035
+ output = await generate(bundle, false);
1036
+ }
989
1037
  } finally {
990
1038
  await bundle.close();
991
1039
  }
992
1040
  options.signal?.throwIfAborted();
993
- const chunk = output.find((file) => file.type === "chunk");
1041
+ const chunk = output.find((file) => file.type === "chunk" && file.isEntry);
994
1042
  await mkdir(dirname(outfile), { recursive: true });
995
1043
  await writeFile(outfile, chunk.code, { signal: options.signal });
996
1044
  options.signal?.throwIfAborted();
997
1045
  }
998
1046
  //#endregion
1047
+ //#region ../../node_modules/.pnpm/balanced-match@4.0.4/node_modules/balanced-match/dist/esm/index.js
1048
+ const balanced = (a, b, str) => {
1049
+ const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
1050
+ const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
1051
+ const r = ma !== null && mb != null && range(ma, mb, str);
1052
+ return r && {
1053
+ start: r[0],
1054
+ end: r[1],
1055
+ pre: str.slice(0, r[0]),
1056
+ body: str.slice(r[0] + ma.length, r[1]),
1057
+ post: str.slice(r[1] + mb.length)
1058
+ };
1059
+ };
1060
+ const maybeMatch = (reg, str) => {
1061
+ const m = str.match(reg);
1062
+ return m ? m[0] : null;
1063
+ };
1064
+ const range = (a, b, str) => {
1065
+ let begs, beg, left, right = void 0, result;
1066
+ let ai = str.indexOf(a);
1067
+ let bi = str.indexOf(b, ai + 1);
1068
+ let i = ai;
1069
+ if (ai >= 0 && bi > 0) {
1070
+ if (a === b) return [ai, bi];
1071
+ begs = [];
1072
+ left = str.length;
1073
+ while (i >= 0 && !result) {
1074
+ if (i === ai) {
1075
+ begs.push(i);
1076
+ ai = str.indexOf(a, i + 1);
1077
+ } else if (begs.length === 1) {
1078
+ const r = begs.pop();
1079
+ if (r !== void 0) result = [r, bi];
1080
+ } else {
1081
+ beg = begs.pop();
1082
+ if (beg !== void 0 && beg < left) {
1083
+ left = beg;
1084
+ right = bi;
1085
+ }
1086
+ bi = str.indexOf(b, i + 1);
1087
+ }
1088
+ i = ai < bi && ai >= 0 ? ai : bi;
1089
+ }
1090
+ if (begs.length && right !== void 0) result = [left, right];
1091
+ }
1092
+ return result;
1093
+ };
1094
+ //#endregion
1095
+ //#region ../../node_modules/.pnpm/brace-expansion@5.0.12/node_modules/brace-expansion/dist/esm/index.js
1096
+ const escSlash = "\0SLASH" + Math.random() + "\0";
1097
+ const escOpen = "\0OPEN" + Math.random() + "\0";
1098
+ const escClose = "\0CLOSE" + Math.random() + "\0";
1099
+ const escComma = "\0COMMA" + Math.random() + "\0";
1100
+ const escPeriod = "\0PERIOD" + Math.random() + "\0";
1101
+ const escSlashPattern = new RegExp(escSlash, "g");
1102
+ const escOpenPattern = new RegExp(escOpen, "g");
1103
+ const escClosePattern = new RegExp(escClose, "g");
1104
+ const escCommaPattern = new RegExp(escComma, "g");
1105
+ const escPeriodPattern = new RegExp(escPeriod, "g");
1106
+ const slashPattern = /\\\\/g;
1107
+ const openPattern = /\\{/g;
1108
+ const closePattern = /\\}/g;
1109
+ const commaPattern = /\\,/g;
1110
+ const periodPattern = /\\\./g;
1111
+ const EXPANSION_MAX = 1e5;
1112
+ const EXPANSION_MAX_LENGTH = 4e6;
1113
+ const EXPANSION_MAX_DEPTH = 1e3;
1114
+ const EXPANSION_MAX_REWRITES = 1e3;
1115
+ function numeric(str) {
1116
+ return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
1117
+ }
1118
+ function escapeBraces(str) {
1119
+ return str.replace(slashPattern, escSlash).replace(openPattern, escOpen).replace(closePattern, escClose).replace(commaPattern, escComma).replace(periodPattern, escPeriod);
1120
+ }
1121
+ function unescapeBraces(str) {
1122
+ return str.replace(escSlashPattern, "\\").replace(escOpenPattern, "{").replace(escClosePattern, "}").replace(escCommaPattern, ",").replace(escPeriodPattern, ".");
1123
+ }
1124
+ function pushAll(target, items) {
1125
+ for (let i = 0; i < items.length; i++) target.push(items[i]);
1126
+ }
1127
+ /**
1128
+ * Basically just str.split(","), but handling cases
1129
+ * where we have nested braced sections, which should be
1130
+ * treated as individual members, like {a,{b,c},d}
1131
+ */
1132
+ function parseCommaParts(str) {
1133
+ const parts = [];
1134
+ let carry = "";
1135
+ for (;;) {
1136
+ const m = balanced("{", "}", str);
1137
+ if (!m) {
1138
+ const tail = str.split(",");
1139
+ tail[0] = carry + tail[0];
1140
+ pushAll(parts, tail);
1141
+ return parts;
1142
+ }
1143
+ const { pre, body, post } = m;
1144
+ const p = pre.split(",");
1145
+ p[0] = carry + p[0];
1146
+ p[p.length - 1] += "{" + body + "}";
1147
+ if (!post.length) {
1148
+ pushAll(parts, p);
1149
+ return parts;
1150
+ }
1151
+ carry = p.pop();
1152
+ pushAll(parts, p);
1153
+ str = post;
1154
+ }
1155
+ }
1156
+ function expand(str, options = {}) {
1157
+ if (!str) return [];
1158
+ const { max = EXPANSION_MAX, maxLength = EXPANSION_MAX_LENGTH, maxDepth = EXPANSION_MAX_DEPTH, maxRewrites = EXPANSION_MAX_REWRITES } = options;
1159
+ if (str.slice(0, 2) === "{}") str = "\\{\\}" + str.slice(2);
1160
+ return expand_(escapeBraces(str), max, maxLength, maxDepth, 0, maxRewrites, true).map(unescapeBraces);
1161
+ }
1162
+ function embrace(str) {
1163
+ return "{" + str + "}";
1164
+ }
1165
+ function isPadded(el) {
1166
+ return /^-?0\d/.test(el);
1167
+ }
1168
+ function lte(i, y) {
1169
+ return i <= y;
1170
+ }
1171
+ function gte(i, y) {
1172
+ return i >= y;
1173
+ }
1174
+ function combine(acc, pre, values, max, maxLength, dropEmpties) {
1175
+ const out = [];
1176
+ let length = 0;
1177
+ for (let a = 0; a < acc.length; a++) for (let v = 0; v < values.length; v++) {
1178
+ if (out.length >= max) return out;
1179
+ const expansion = acc[a] + pre + values[v];
1180
+ if (dropEmpties && !expansion) continue;
1181
+ if (length + expansion.length > maxLength) return out;
1182
+ out.push(expansion);
1183
+ length += expansion.length;
1184
+ }
1185
+ return out;
1186
+ }
1187
+ function expandSequence(body, isAlphaSequence, max, maxLength) {
1188
+ const n = body.split(/\.\./);
1189
+ const N = [];
1190
+ /* c8 ignore start */
1191
+ if (n[0] === void 0 || n[1] === void 0) return N;
1192
+ /* c8 ignore stop */
1193
+ const x = numeric(n[0]);
1194
+ const y = numeric(n[1]);
1195
+ const width = Math.max(n[0].length, n[1].length);
1196
+ let incr = n.length === 3 && n[2] !== void 0 ? Math.max(Math.abs(numeric(n[2])), 1) : 1;
1197
+ let test = lte;
1198
+ if (y < x) {
1199
+ incr *= -1;
1200
+ test = gte;
1201
+ }
1202
+ const pad = n.some(isPadded);
1203
+ let length = 0;
1204
+ for (let i = x; test(i, y) && N.length < max; i += incr) {
1205
+ let c;
1206
+ if (isAlphaSequence) {
1207
+ c = String.fromCharCode(i);
1208
+ if (c === "\\") c = "";
1209
+ } else {
1210
+ c = String(i);
1211
+ if (pad) {
1212
+ const need = width - c.length;
1213
+ if (need > 0) {
1214
+ const z = new Array(need + 1).join("0");
1215
+ if (i < 0) c = "-" + z + c.slice(1);
1216
+ else c = z + c;
1217
+ }
1218
+ }
1219
+ }
1220
+ if (length + c.length > maxLength) break;
1221
+ N.push(c);
1222
+ length += c.length;
1223
+ }
1224
+ return N;
1225
+ }
1226
+ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) {
1227
+ if (depth > maxDepth) return [str];
1228
+ let acc = [""];
1229
+ let rewrites = 0;
1230
+ let dropEmpties = false;
1231
+ let firstGroup = true;
1232
+ for (;;) {
1233
+ const m = balanced("{", "}", str);
1234
+ if (!m) return combine(acc, str, [""], max, maxLength, dropEmpties);
1235
+ const pre = m.pre;
1236
+ if (/\$$/.test(pre)) {
1237
+ acc = combine(acc, pre + "{" + m.body + "}", [""], max, maxLength, dropEmpties && !m.post.length);
1238
+ firstGroup = false;
1239
+ if (!m.post.length) break;
1240
+ str = m.post;
1241
+ continue;
1242
+ }
1243
+ const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
1244
+ const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
1245
+ const isSequence = isNumericSequence || isAlphaSequence;
1246
+ const isOptions = m.body.indexOf(",") >= 0;
1247
+ if (!isSequence && !isOptions) {
1248
+ if (rewrites < maxRewrites && m.post.match(/,(?!,).*\}/)) {
1249
+ rewrites++;
1250
+ str = m.pre + "{" + m.body + escClose + m.post;
1251
+ isTop = true;
1252
+ continue;
1253
+ }
1254
+ return combine(acc, pre + "{" + m.body + "}" + m.post, [""], max, maxLength, dropEmpties);
1255
+ }
1256
+ if (firstGroup) {
1257
+ dropEmpties = isTop && !isSequence;
1258
+ firstGroup = false;
1259
+ }
1260
+ let values;
1261
+ if (isSequence) values = expandSequence(m.body, isAlphaSequence, max, maxLength);
1262
+ else {
1263
+ let n = parseCommaParts(m.body);
1264
+ if (n.length === 1 && n[0] !== void 0) {
1265
+ n = expand_(n[0], max, maxLength, maxDepth, depth + 1, maxRewrites, false).map(embrace);
1266
+ /* c8 ignore start */
1267
+ if (n.length === 1) {
1268
+ acc = combine(acc, pre + n[0], [""], max, maxLength, dropEmpties && !m.post.length);
1269
+ if (!m.post.length) break;
1270
+ str = m.post;
1271
+ continue;
1272
+ }
1273
+ }
1274
+ let dropsEmpties = dropEmpties && !m.post.length && !pre;
1275
+ for (let d = 0; dropsEmpties && d < acc.length; d++) if (acc[d]) dropsEmpties = false;
1276
+ values = [];
1277
+ let valuesLength = 0;
1278
+ outer: for (let j = 0; j < n.length; j++) {
1279
+ const expanded = expand_(n[j], max, maxLength, maxDepth, depth + 1, maxRewrites, false);
1280
+ for (let k = 0; k < expanded.length; k++) {
1281
+ const v = expanded[k];
1282
+ if (dropsEmpties && !v) continue;
1283
+ if (values.length >= max || valuesLength + v.length > maxLength) break outer;
1284
+ values.push(v);
1285
+ valuesLength += v.length;
1286
+ }
1287
+ }
1288
+ }
1289
+ acc = combine(acc, pre, values, max, maxLength, dropEmpties && !m.post.length);
1290
+ if (!m.post.length) break;
1291
+ str = m.post;
1292
+ }
1293
+ return acc;
1294
+ }
1295
+ //#endregion
1296
+ //#region ../../node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/assert-valid-pattern.js
1297
+ const MAX_PATTERN_LENGTH = 65536;
1298
+ const assertValidPattern = (pattern) => {
1299
+ if (typeof pattern !== "string") throw new TypeError("invalid pattern");
1300
+ if (pattern.length > MAX_PATTERN_LENGTH) throw new TypeError("pattern is too long");
1301
+ };
1302
+ //#endregion
1303
+ //#region ../../node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/brace-expressions.js
1304
+ const posixClasses = {
1305
+ "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
1306
+ "[:alpha:]": ["\\p{L}\\p{Nl}", true],
1307
+ "[:ascii:]": ["\\x00-\\x7f", false],
1308
+ "[:blank:]": ["\\p{Zs}\\t", true],
1309
+ "[:cntrl:]": ["\\p{Cc}", true],
1310
+ "[:digit:]": ["\\p{Nd}", true],
1311
+ "[:graph:]": [
1312
+ "\\p{Z}\\p{C}",
1313
+ true,
1314
+ true
1315
+ ],
1316
+ "[:lower:]": ["\\p{Ll}", true],
1317
+ "[:print:]": ["\\p{C}", true],
1318
+ "[:punct:]": ["\\p{P}", true],
1319
+ "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
1320
+ "[:upper:]": ["\\p{Lu}", true],
1321
+ "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
1322
+ "[:xdigit:]": ["A-Fa-f0-9", false]
1323
+ };
1324
+ const braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&");
1325
+ const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
1326
+ const rangesToString = (ranges) => ranges.join("");
1327
+ const parseClass = (glob, position) => {
1328
+ const pos = position;
1329
+ /* c8 ignore start */
1330
+ if (glob.charAt(pos) !== "[") throw new Error("not in a brace expression");
1331
+ /* c8 ignore stop */
1332
+ const ranges = [];
1333
+ const negs = [];
1334
+ let i = pos + 1;
1335
+ let sawStart = false;
1336
+ let uflag = false;
1337
+ let escaping = false;
1338
+ let negate = false;
1339
+ let endPos = pos;
1340
+ let rangeStart = "";
1341
+ WHILE: while (i < glob.length) {
1342
+ const c = glob.charAt(i);
1343
+ if ((c === "!" || c === "^") && i === pos + 1) {
1344
+ negate = true;
1345
+ i++;
1346
+ continue;
1347
+ }
1348
+ if (c === "]" && sawStart && !escaping) {
1349
+ endPos = i + 1;
1350
+ break;
1351
+ }
1352
+ sawStart = true;
1353
+ if (c === "\\") {
1354
+ if (!escaping) {
1355
+ escaping = true;
1356
+ i++;
1357
+ continue;
1358
+ }
1359
+ }
1360
+ if (c === "[" && !escaping) {
1361
+ for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) if (glob.startsWith(cls, i)) {
1362
+ if (rangeStart) return [
1363
+ "$.",
1364
+ false,
1365
+ glob.length - pos,
1366
+ true
1367
+ ];
1368
+ i += cls.length;
1369
+ if (neg) negs.push(unip);
1370
+ else ranges.push(unip);
1371
+ uflag = uflag || u;
1372
+ continue WHILE;
1373
+ }
1374
+ }
1375
+ escaping = false;
1376
+ if (rangeStart) {
1377
+ if (c > rangeStart) ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));
1378
+ else if (c === rangeStart) ranges.push(braceEscape(c));
1379
+ rangeStart = "";
1380
+ i++;
1381
+ continue;
1382
+ }
1383
+ if (glob.startsWith("-]", i + 1)) {
1384
+ ranges.push(braceEscape(c + "-"));
1385
+ i += 2;
1386
+ continue;
1387
+ }
1388
+ if (glob.startsWith("-", i + 1)) {
1389
+ rangeStart = c;
1390
+ i += 2;
1391
+ continue;
1392
+ }
1393
+ ranges.push(braceEscape(c));
1394
+ i++;
1395
+ }
1396
+ if (endPos < i) return [
1397
+ "",
1398
+ false,
1399
+ 0,
1400
+ false
1401
+ ];
1402
+ if (!ranges.length && !negs.length) return [
1403
+ "$.",
1404
+ false,
1405
+ glob.length - pos,
1406
+ true
1407
+ ];
1408
+ if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
1409
+ const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
1410
+ return [
1411
+ regexpEscape(r),
1412
+ false,
1413
+ endPos - pos,
1414
+ false
1415
+ ];
1416
+ }
1417
+ const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
1418
+ const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
1419
+ return [
1420
+ ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs,
1421
+ uflag,
1422
+ endPos - pos,
1423
+ true
1424
+ ];
1425
+ };
1426
+ //#endregion
1427
+ //#region ../../node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/unescape.js
1428
+ /**
1429
+ * Un-escape a string that has been escaped with {@link escape}.
1430
+ *
1431
+ * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
1432
+ * square-bracket escapes are removed, but not backslash escapes.
1433
+ *
1434
+ * For example, it will turn the string `'[*]'` into `*`, but it will not
1435
+ * turn `'\\*'` into `'*'`, because `\` is a path separator in
1436
+ * `windowsPathsNoEscape` mode.
1437
+ *
1438
+ * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
1439
+ * backslash escapes are removed.
1440
+ *
1441
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
1442
+ * or unescaped.
1443
+ *
1444
+ * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
1445
+ * unescaped.
1446
+ */
1447
+ const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true } = {}) => {
1448
+ if (magicalBraces) return windowsPathsNoEscape ? s.replace(/\[([^/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^/\\])\]/g, "$1$2").replace(/\\([^/])/g, "$1");
1449
+ return windowsPathsNoEscape ? s.replace(/\[([^/\\{}])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^/\\{}])\]/g, "$1$2").replace(/\\([^/{}])/g, "$1");
1450
+ };
1451
+ //#endregion
1452
+ //#region ../../node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/ast.js
1453
+ var _a;
1454
+ const types = /* @__PURE__ */ new Set([
1455
+ "!",
1456
+ "?",
1457
+ "+",
1458
+ "*",
1459
+ "@"
1460
+ ]);
1461
+ const isExtglobType = (c) => types.has(c);
1462
+ const isExtglobAST = (c) => isExtglobType(c.type);
1463
+ const adoptionMap = /* @__PURE__ */ new Map([
1464
+ ["!", ["@"]],
1465
+ ["?", ["?", "@"]],
1466
+ ["@", ["@"]],
1467
+ ["*", [
1468
+ "*",
1469
+ "+",
1470
+ "?",
1471
+ "@"
1472
+ ]],
1473
+ ["+", ["+", "@"]]
1474
+ ]);
1475
+ const adoptionWithSpaceMap = /* @__PURE__ */ new Map([
1476
+ ["!", ["?"]],
1477
+ ["@", ["?"]],
1478
+ ["+", ["?", "*"]]
1479
+ ]);
1480
+ const adoptionAnyMap = /* @__PURE__ */ new Map([
1481
+ ["!", ["?", "@"]],
1482
+ ["?", ["?", "@"]],
1483
+ ["@", ["?", "@"]],
1484
+ ["*", [
1485
+ "*",
1486
+ "+",
1487
+ "?",
1488
+ "@"
1489
+ ]],
1490
+ ["+", [
1491
+ "+",
1492
+ "@",
1493
+ "?",
1494
+ "*"
1495
+ ]]
1496
+ ]);
1497
+ const usurpMap = /* @__PURE__ */ new Map([
1498
+ ["!", /* @__PURE__ */ new Map([["!", "@"]])],
1499
+ ["?", /* @__PURE__ */ new Map([["*", "*"], ["+", "*"]])],
1500
+ ["@", /* @__PURE__ */ new Map([
1501
+ ["!", "!"],
1502
+ ["?", "?"],
1503
+ ["@", "@"],
1504
+ ["*", "*"],
1505
+ ["+", "+"]
1506
+ ])],
1507
+ ["+", /* @__PURE__ */ new Map([["?", "*"], ["*", "*"]])]
1508
+ ]);
1509
+ const startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
1510
+ const startNoDot = "(?!\\.)";
1511
+ const addPatternStart = /* @__PURE__ */ new Set(["[", "."]);
1512
+ const justDots = /* @__PURE__ */ new Set(["..", "."]);
1513
+ const reSpecials = /* @__PURE__ */ new Set("().*{}+?[]^$\\!");
1514
+ const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
1515
+ const qmark = "[^/]";
1516
+ const star$1 = "[^/]*?";
1517
+ const starNoEmpty = "[^/]+?";
1518
+ let ID = 0;
1519
+ var AST = class {
1520
+ type;
1521
+ #root;
1522
+ #hasMagic;
1523
+ #uflag = false;
1524
+ #parts = [];
1525
+ #parent;
1526
+ #parentIndex;
1527
+ #negs;
1528
+ #filledNegs = false;
1529
+ #options;
1530
+ #toString;
1531
+ #emptyExt = false;
1532
+ id = ++ID;
1533
+ get depth() {
1534
+ return (this.#parent?.depth ?? -1) + 1;
1535
+ }
1536
+ [Symbol.for("nodejs.util.inspect.custom")]() {
1537
+ return {
1538
+ "@@type": "AST",
1539
+ id: this.id,
1540
+ type: this.type,
1541
+ root: this.#root.id,
1542
+ parent: this.#parent?.id,
1543
+ depth: this.depth,
1544
+ partsLength: this.#parts.length,
1545
+ parts: this.#parts
1546
+ };
1547
+ }
1548
+ constructor(type, parent, options = {}) {
1549
+ this.type = type;
1550
+ if (type) this.#hasMagic = true;
1551
+ this.#parent = parent;
1552
+ this.#root = this.#parent ? this.#parent.#root : this;
1553
+ this.#options = this.#root === this ? options : this.#root.#options;
1554
+ this.#negs = this.#root === this ? [] : this.#root.#negs;
1555
+ if (type === "!" && !this.#root.#filledNegs) this.#negs.push(this);
1556
+ this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
1557
+ }
1558
+ get hasMagic() {
1559
+ /* c8 ignore start */
1560
+ if (this.#hasMagic !== void 0) return this.#hasMagic;
1561
+ /* c8 ignore stop */
1562
+ for (const p of this.#parts) {
1563
+ if (typeof p === "string") continue;
1564
+ if (p.type || p.hasMagic) return this.#hasMagic = true;
1565
+ }
1566
+ return this.#hasMagic;
1567
+ }
1568
+ toString() {
1569
+ return this.#toString !== void 0 ? this.#toString : !this.type ? this.#toString = this.#parts.map((p) => String(p)).join("") : this.#toString = this.type + "(" + this.#parts.map((p) => String(p)).join("|") + ")";
1570
+ }
1571
+ #fillNegs() {
1572
+ /* c8 ignore start */
1573
+ if (this !== this.#root) throw new Error("should only call on root");
1574
+ if (this.#filledNegs) return this;
1575
+ /* c8 ignore stop */
1576
+ this.toString();
1577
+ this.#filledNegs = true;
1578
+ let n;
1579
+ while (n = this.#negs.pop()) {
1580
+ if (n.type !== "!") continue;
1581
+ let p = n;
1582
+ let pp = p.#parent;
1583
+ while (pp) {
1584
+ for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) for (const part of n.#parts) {
1585
+ /* c8 ignore start */
1586
+ if (typeof part === "string") throw new Error("string part in extglob AST??");
1587
+ /* c8 ignore stop */
1588
+ part.copyIn(pp.#parts[i]);
1589
+ }
1590
+ p = pp;
1591
+ pp = p.#parent;
1592
+ }
1593
+ }
1594
+ return this;
1595
+ }
1596
+ push(...parts) {
1597
+ for (const p of parts) {
1598
+ if (p === "") continue;
1599
+ /* c8 ignore start */
1600
+ if (typeof p !== "string" && !(p instanceof _a && p.#parent === this)) throw new Error("invalid part: " + p);
1601
+ /* c8 ignore stop */
1602
+ this.#parts.push(p);
1603
+ }
1604
+ }
1605
+ toJSON() {
1606
+ const ret = this.type === null ? this.#parts.slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...this.#parts.map((p) => p.toJSON())];
1607
+ if (this.isStart() && !this.type) ret.unshift([]);
1608
+ if (this.isEnd() && (this === this.#root || this.#root.#filledNegs && this.#parent?.type === "!")) ret.push({});
1609
+ return ret;
1610
+ }
1611
+ isStart() {
1612
+ if (this.#root === this) return true;
1613
+ if (!this.#parent?.isStart()) return false;
1614
+ if (this.#parentIndex === 0) return true;
1615
+ const p = this.#parent;
1616
+ for (let i = 0; i < this.#parentIndex; i++) {
1617
+ const pp = p.#parts[i];
1618
+ if (!(pp instanceof _a && pp.type === "!")) return false;
1619
+ }
1620
+ return true;
1621
+ }
1622
+ isEnd() {
1623
+ if (this.#root === this) return true;
1624
+ if (this.#parent?.type === "!") return true;
1625
+ if (!this.#parent?.isEnd()) return false;
1626
+ if (!this.type) return this.#parent?.isEnd();
1627
+ /* c8 ignore start */
1628
+ const pl = this.#parent ? this.#parent.#parts.length : 0;
1629
+ /* c8 ignore stop */
1630
+ return this.#parentIndex === pl - 1;
1631
+ }
1632
+ copyIn(part) {
1633
+ if (typeof part === "string") this.push(part);
1634
+ else this.push(part.clone(this));
1635
+ }
1636
+ clone(parent) {
1637
+ const c = new _a(this.type, parent);
1638
+ for (const p of this.#parts) c.copyIn(p);
1639
+ return c;
1640
+ }
1641
+ static #parseAST(str, ast, pos, opt, extDepth) {
1642
+ const maxDepth = opt.maxExtglobRecursion ?? 2;
1643
+ let escaping = false;
1644
+ let inBrace = false;
1645
+ let braceStart = -1;
1646
+ let braceNeg = false;
1647
+ if (ast.type === null) {
1648
+ let i = pos;
1649
+ let acc = "";
1650
+ while (i < str.length) {
1651
+ const c = str.charAt(i++);
1652
+ if (escaping || c === "\\") {
1653
+ escaping = !escaping;
1654
+ acc += c;
1655
+ continue;
1656
+ }
1657
+ if (inBrace) {
1658
+ if (i === braceStart + 1) {
1659
+ if (c === "^" || c === "!") braceNeg = true;
1660
+ } else if (c === "]" && !(i === braceStart + 2 && braceNeg)) inBrace = false;
1661
+ acc += c;
1662
+ continue;
1663
+ } else if (c === "[") {
1664
+ inBrace = true;
1665
+ braceStart = i;
1666
+ braceNeg = false;
1667
+ acc += c;
1668
+ continue;
1669
+ }
1670
+ if (!opt.noext && isExtglobType(c) && str.charAt(i) === "(" && extDepth <= maxDepth) {
1671
+ ast.push(acc);
1672
+ acc = "";
1673
+ const ext = new _a(c, ast);
1674
+ i = _a.#parseAST(str, ext, i, opt, extDepth + 1);
1675
+ ast.push(ext);
1676
+ continue;
1677
+ }
1678
+ acc += c;
1679
+ }
1680
+ ast.push(acc);
1681
+ return i;
1682
+ }
1683
+ let i = pos + 1;
1684
+ let part = new _a(null, ast);
1685
+ const parts = [];
1686
+ let acc = "";
1687
+ while (i < str.length) {
1688
+ const c = str.charAt(i++);
1689
+ if (escaping || c === "\\") {
1690
+ escaping = !escaping;
1691
+ acc += c;
1692
+ continue;
1693
+ }
1694
+ if (inBrace) {
1695
+ if (i === braceStart + 1) {
1696
+ if (c === "^" || c === "!") braceNeg = true;
1697
+ } else if (c === "]" && !(i === braceStart + 2 && braceNeg)) inBrace = false;
1698
+ acc += c;
1699
+ continue;
1700
+ } else if (c === "[") {
1701
+ inBrace = true;
1702
+ braceStart = i;
1703
+ braceNeg = false;
1704
+ acc += c;
1705
+ continue;
1706
+ }
1707
+ /* c8 ignore stop */
1708
+ if (!opt.noext && isExtglobType(c) && str.charAt(i) === "(" && (extDepth <= maxDepth || ast && ast.#canAdoptType(c))) {
1709
+ const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
1710
+ part.push(acc);
1711
+ acc = "";
1712
+ const ext = new _a(c, part);
1713
+ part.push(ext);
1714
+ i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
1715
+ continue;
1716
+ }
1717
+ if (c === "|") {
1718
+ part.push(acc);
1719
+ acc = "";
1720
+ parts.push(part);
1721
+ part = new _a(null, ast);
1722
+ continue;
1723
+ }
1724
+ if (c === ")") {
1725
+ if (acc === "" && ast.#parts.length === 0) ast.#emptyExt = true;
1726
+ part.push(acc);
1727
+ acc = "";
1728
+ ast.push(...parts, part);
1729
+ return i;
1730
+ }
1731
+ acc += c;
1732
+ }
1733
+ ast.type = null;
1734
+ ast.#hasMagic = void 0;
1735
+ ast.#parts = [str.substring(pos - 1)];
1736
+ return i;
1737
+ }
1738
+ #canAdoptWithSpace(child) {
1739
+ return this.#canAdopt(child, adoptionWithSpaceMap);
1740
+ }
1741
+ #canAdopt(child, map = adoptionMap) {
1742
+ if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null) return false;
1743
+ const gc = child.#parts[0];
1744
+ if (!gc || typeof gc !== "object" || gc.type === null) return false;
1745
+ return this.#canAdoptType(gc.type, map);
1746
+ }
1747
+ #canAdoptType(c, map = adoptionAnyMap) {
1748
+ return !!map.get(this.type)?.includes(c);
1749
+ }
1750
+ #adoptWithSpace(child, index) {
1751
+ const gc = child.#parts[0];
1752
+ const blank = new _a(null, gc, this.options);
1753
+ blank.#parts.push("");
1754
+ gc.push(blank);
1755
+ this.#adopt(child, index);
1756
+ }
1757
+ #adopt(child, index) {
1758
+ const gc = child.#parts[0];
1759
+ this.#parts.splice(index, 1, ...gc.#parts);
1760
+ for (const p of gc.#parts) if (typeof p === "object") p.#parent = this;
1761
+ this.#toString = void 0;
1762
+ }
1763
+ #canUsurpType(c) {
1764
+ return !!usurpMap.get(this.type)?.has(c);
1765
+ }
1766
+ #canUsurp(child) {
1767
+ if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null || this.#parts.length !== 1) return false;
1768
+ const gc = child.#parts[0];
1769
+ if (!gc || typeof gc !== "object" || gc.type === null) return false;
1770
+ return this.#canUsurpType(gc.type);
1771
+ }
1772
+ #usurp(child) {
1773
+ const m = usurpMap.get(this.type);
1774
+ const gc = child.#parts[0];
1775
+ const nt = m?.get(gc.type);
1776
+ /* c8 ignore start - impossible */
1777
+ if (!nt) return false;
1778
+ /* c8 ignore stop */
1779
+ this.#parts = gc.#parts;
1780
+ for (const p of this.#parts) if (typeof p === "object") p.#parent = this;
1781
+ this.type = nt;
1782
+ this.#toString = void 0;
1783
+ this.#emptyExt = false;
1784
+ }
1785
+ static fromGlob(pattern, options = {}) {
1786
+ const ast = new _a(null, void 0, options);
1787
+ _a.#parseAST(pattern, ast, 0, options, 0);
1788
+ return ast;
1789
+ }
1790
+ toMMPattern() {
1791
+ /* c8 ignore start */
1792
+ if (this !== this.#root) return this.#root.toMMPattern();
1793
+ /* c8 ignore stop */
1794
+ const glob = this.toString();
1795
+ const [re, body, hasMagic, uflag] = this.toRegExpSource();
1796
+ if (!(hasMagic || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob.toUpperCase() !== glob.toLowerCase())) return body;
1797
+ const flags = (this.#options.nocase ? "i" : "") + (uflag ? "u" : "");
1798
+ return Object.assign(new RegExp(`^${re}$`, flags), {
1799
+ _src: re,
1800
+ _glob: glob
1801
+ });
1802
+ }
1803
+ get options() {
1804
+ return this.#options;
1805
+ }
1806
+ toRegExpSource(allowDot) {
1807
+ const dot = allowDot ?? !!this.#options.dot;
1808
+ if (this.#root === this) {
1809
+ this.#flatten();
1810
+ this.#fillNegs();
1811
+ }
1812
+ if (!isExtglobAST(this)) {
1813
+ const noEmpty = this.isStart() && this.isEnd() && !this.#parts.some((s) => typeof s !== "string");
1814
+ const src = this.#parts.map((p) => {
1815
+ const [re, _, hasMagic, uflag] = typeof p === "string" ? _a.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot);
1816
+ this.#hasMagic = this.#hasMagic || hasMagic;
1817
+ this.#uflag = this.#uflag || uflag;
1818
+ return re;
1819
+ }).join("");
1820
+ let start = "";
1821
+ if (this.isStart()) {
1822
+ if (typeof this.#parts[0] === "string") {
1823
+ if (!(this.#parts.length === 1 && justDots.has(this.#parts[0]))) {
1824
+ const aps = addPatternStart;
1825
+ const needNoTrav = dot && aps.has(src.charAt(0)) || src.startsWith("\\.") && aps.has(src.charAt(2)) || src.startsWith("\\.\\.") && aps.has(src.charAt(4));
1826
+ const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
1827
+ start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";
1828
+ }
1829
+ }
1830
+ }
1831
+ let end = "";
1832
+ if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === "!") end = "(?:$|\\/)";
1833
+ return [
1834
+ start + src + end,
1835
+ unescape(src),
1836
+ this.#hasMagic = !!this.#hasMagic,
1837
+ this.#uflag
1838
+ ];
1839
+ }
1840
+ const repeated = this.type === "*" || this.type === "+";
1841
+ const start = this.type === "!" ? "(?:(?!(?:" : "(?:";
1842
+ let body = this.#partsToRegExp(dot);
1843
+ if (this.isStart() && this.isEnd() && !body && this.type !== "!") {
1844
+ const s = this.toString();
1845
+ const me = this;
1846
+ me.#parts = [s];
1847
+ me.type = null;
1848
+ me.#hasMagic = void 0;
1849
+ return [
1850
+ s,
1851
+ unescape(this.toString()),
1852
+ false,
1853
+ false
1854
+ ];
1855
+ }
1856
+ let bodyDotAllowed = !repeated || allowDot || dot || false ? "" : this.#partsToRegExp(true);
1857
+ if (bodyDotAllowed === body) bodyDotAllowed = "";
1858
+ if (bodyDotAllowed) body = `(?:${body})(?:${bodyDotAllowed})*?`;
1859
+ let final = "";
1860
+ if (this.type === "!" && this.#emptyExt) final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty;
1861
+ else {
1862
+ const close = this.type === "!" ? "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + "[^/]*?)" : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`;
1863
+ final = start + body + close;
1864
+ }
1865
+ return [
1866
+ final,
1867
+ unescape(body),
1868
+ this.#hasMagic = !!this.#hasMagic,
1869
+ this.#uflag
1870
+ ];
1871
+ }
1872
+ #flatten() {
1873
+ if (!isExtglobAST(this)) {
1874
+ for (const p of this.#parts) if (typeof p === "object") p.#flatten();
1875
+ } else {
1876
+ let iterations = 0;
1877
+ let done = false;
1878
+ do {
1879
+ done = true;
1880
+ for (let i = 0; i < this.#parts.length; i++) {
1881
+ const c = this.#parts[i];
1882
+ if (typeof c === "object") {
1883
+ c.#flatten();
1884
+ if (this.#canAdopt(c)) {
1885
+ done = false;
1886
+ this.#adopt(c, i);
1887
+ } else if (this.#canAdoptWithSpace(c)) {
1888
+ done = false;
1889
+ this.#adoptWithSpace(c, i);
1890
+ } else if (this.#canUsurp(c)) {
1891
+ done = false;
1892
+ this.#usurp(c);
1893
+ }
1894
+ }
1895
+ }
1896
+ } while (!done && ++iterations < 10);
1897
+ }
1898
+ this.#toString = void 0;
1899
+ }
1900
+ #partsToRegExp(dot) {
1901
+ return this.#parts.map((p) => {
1902
+ /* c8 ignore start */
1903
+ if (typeof p === "string") throw new Error("string type in extglob ast??");
1904
+ /* c8 ignore stop */
1905
+ const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
1906
+ this.#uflag = this.#uflag || uflag;
1907
+ return re;
1908
+ }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");
1909
+ }
1910
+ static #parseGlob(glob, hasMagic, noEmpty = false) {
1911
+ let escaping = false;
1912
+ let re = "";
1913
+ let uflag = false;
1914
+ let inStar = false;
1915
+ for (let i = 0; i < glob.length; i++) {
1916
+ const c = glob.charAt(i);
1917
+ if (escaping) {
1918
+ escaping = false;
1919
+ re += (reSpecials.has(c) ? "\\" : "") + c;
1920
+ continue;
1921
+ }
1922
+ if (c === "*") {
1923
+ if (inStar) continue;
1924
+ inStar = true;
1925
+ re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star$1;
1926
+ hasMagic = true;
1927
+ continue;
1928
+ } else inStar = false;
1929
+ if (c === "\\") {
1930
+ if (i === glob.length - 1) re += "\\\\";
1931
+ else escaping = true;
1932
+ continue;
1933
+ }
1934
+ if (c === "[") {
1935
+ const [src, needUflag, consumed, magic] = parseClass(glob, i);
1936
+ if (consumed) {
1937
+ re += src;
1938
+ uflag = uflag || needUflag;
1939
+ i += consumed - 1;
1940
+ hasMagic = hasMagic || magic;
1941
+ continue;
1942
+ }
1943
+ }
1944
+ if (c === "?") {
1945
+ re += qmark;
1946
+ hasMagic = true;
1947
+ continue;
1948
+ }
1949
+ re += regExpEscape$1(c);
1950
+ }
1951
+ return [
1952
+ re,
1953
+ unescape(glob),
1954
+ !!hasMagic,
1955
+ uflag
1956
+ ];
1957
+ }
1958
+ };
1959
+ _a = AST;
1960
+ //#endregion
1961
+ //#region ../../node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/escape.js
1962
+ /**
1963
+ * Escape all magic characters in a glob pattern.
1964
+ *
1965
+ * If the {@link MinimatchOptions.windowsPathsNoEscape}
1966
+ * option is used, then characters are escaped by wrapping in `[]`, because
1967
+ * a magic character wrapped in a character class can only be satisfied by
1968
+ * that exact character. In this mode, `\` is _not_ escaped, because it is
1969
+ * not interpreted as a magic character, but instead as a path separator.
1970
+ *
1971
+ * If the {@link MinimatchOptions.magicalBraces} option is used,
1972
+ * then braces (`{` and `}`) will be escaped.
1973
+ */
1974
+ const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false } = {}) => {
1975
+ if (magicalBraces) return windowsPathsNoEscape ? s.replace(/[?*()[\]{}]/g, "[$&]") : s.replace(/[?*()[\]\\{}]/g, "\\$&");
1976
+ return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
1977
+ };
1978
+ //#endregion
1979
+ //#region ../../node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/index.js
1980
+ const minimatch = (p, pattern, options = {}) => {
1981
+ assertValidPattern(pattern);
1982
+ if (!options.nocomment && pattern.charAt(0) === "#") return false;
1983
+ return new Minimatch(pattern, options).match(p);
1984
+ };
1985
+ const starDotExtRE = /^\*+([^+@!?*[(]*)$/;
1986
+ const starDotExtTest = (ext) => (f) => !f.startsWith(".") && f.endsWith(ext);
1987
+ const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
1988
+ const starDotExtTestNocase = (ext) => {
1989
+ ext = ext.toLowerCase();
1990
+ return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext);
1991
+ };
1992
+ const starDotExtTestNocaseDot = (ext) => {
1993
+ ext = ext.toLowerCase();
1994
+ return (f) => f.toLowerCase().endsWith(ext);
1995
+ };
1996
+ const starDotStarRE = /^\*+\.\*+$/;
1997
+ const starDotStarTest = (f) => !f.startsWith(".") && f.includes(".");
1998
+ const starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes(".");
1999
+ const dotStarRE = /^\.\*+$/;
2000
+ const dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith(".");
2001
+ const starRE = /^\*+$/;
2002
+ const starTest = (f) => f.length !== 0 && !f.startsWith(".");
2003
+ const starTestDot = (f) => f.length !== 0 && f !== "." && f !== "..";
2004
+ const qmarksRE = /^\?+([^+@!?*[(]*)?$/;
2005
+ const qmarksTestNocase = ([$0, ext = ""]) => {
2006
+ const noext = qmarksTestNoExt([$0]);
2007
+ if (!ext) return noext;
2008
+ ext = ext.toLowerCase();
2009
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext);
2010
+ };
2011
+ const qmarksTestNocaseDot = ([$0, ext = ""]) => {
2012
+ const noext = qmarksTestNoExtDot([$0]);
2013
+ if (!ext) return noext;
2014
+ ext = ext.toLowerCase();
2015
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext);
2016
+ };
2017
+ const qmarksTestDot = ([$0, ext = ""]) => {
2018
+ const noext = qmarksTestNoExtDot([$0]);
2019
+ return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
2020
+ };
2021
+ const qmarksTest = ([$0, ext = ""]) => {
2022
+ const noext = qmarksTestNoExt([$0]);
2023
+ return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
2024
+ };
2025
+ const qmarksTestNoExt = ([$0]) => {
2026
+ const len = $0.length;
2027
+ return (f) => f.length === len && !f.startsWith(".");
2028
+ };
2029
+ const qmarksTestNoExtDot = ([$0]) => {
2030
+ const len = $0.length;
2031
+ return (f) => f.length === len && f !== "." && f !== "..";
2032
+ };
2033
+ /* c8 ignore start */
2034
+ const defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
2035
+ const path = {
2036
+ win32: { sep: "\\" },
2037
+ posix: { sep: "/" }
2038
+ };
2039
+ minimatch.sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
2040
+ const GLOBSTAR = Symbol("globstar **");
2041
+ minimatch.GLOBSTAR = GLOBSTAR;
2042
+ const star = "[^/]*?";
2043
+ const twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
2044
+ const twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
2045
+ const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
2046
+ minimatch.filter = filter;
2047
+ const ext = (a, b = {}) => Object.assign({}, a, b);
2048
+ const defaults = (def) => {
2049
+ if (!def || typeof def !== "object" || !Object.keys(def).length) return minimatch;
2050
+ const orig = minimatch;
2051
+ const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
2052
+ return Object.assign(m, {
2053
+ Minimatch: class Minimatch extends orig.Minimatch {
2054
+ constructor(pattern, options = {}) {
2055
+ super(pattern, ext(def, options));
2056
+ }
2057
+ static defaults(options) {
2058
+ return orig.defaults(ext(def, options)).Minimatch;
2059
+ }
2060
+ },
2061
+ AST: class AST extends orig.AST {
2062
+ /* c8 ignore start */
2063
+ constructor(type, parent, options = {}) {
2064
+ super(type, parent, ext(def, options));
2065
+ }
2066
+ /* c8 ignore stop */
2067
+ static fromGlob(pattern, options = {}) {
2068
+ return orig.AST.fromGlob(pattern, ext(def, options));
2069
+ }
2070
+ },
2071
+ unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
2072
+ escape: (s, options = {}) => orig.escape(s, ext(def, options)),
2073
+ filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
2074
+ defaults: (options) => orig.defaults(ext(def, options)),
2075
+ makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
2076
+ braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
2077
+ match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
2078
+ sep: orig.sep,
2079
+ GLOBSTAR
2080
+ });
2081
+ };
2082
+ minimatch.defaults = defaults;
2083
+ const braceExpand = (pattern, options = {}) => {
2084
+ assertValidPattern(pattern);
2085
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) return [pattern];
2086
+ return expand(pattern, { max: options.braceExpandMax });
2087
+ };
2088
+ minimatch.braceExpand = braceExpand;
2089
+ const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
2090
+ minimatch.makeRe = makeRe;
2091
+ const match = (list, pattern, options = {}) => {
2092
+ const mm = new Minimatch(pattern, options);
2093
+ list = list.filter((f) => mm.match(f));
2094
+ if (mm.options.nonull && !list.length) list.push(pattern);
2095
+ return list;
2096
+ };
2097
+ minimatch.match = match;
2098
+ const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
2099
+ const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
2100
+ var Minimatch = class {
2101
+ options;
2102
+ set;
2103
+ pattern;
2104
+ windowsPathsNoEscape;
2105
+ nonegate;
2106
+ negate;
2107
+ comment;
2108
+ empty;
2109
+ preserveMultipleSlashes;
2110
+ partial;
2111
+ globSet;
2112
+ globParts;
2113
+ nocase;
2114
+ isWindows;
2115
+ platform;
2116
+ windowsNoMagicRoot;
2117
+ maxGlobstarRecursion;
2118
+ regexp;
2119
+ constructor(pattern, options = {}) {
2120
+ assertValidPattern(pattern);
2121
+ options = options || {};
2122
+ this.options = options;
2123
+ this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;
2124
+ this.pattern = pattern;
2125
+ this.platform = options.platform || defaultPlatform;
2126
+ this.isWindows = this.platform === "win32";
2127
+ const awe = "allowWindowsEscape";
2128
+ this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options[awe] === false;
2129
+ if (this.windowsPathsNoEscape) this.pattern = this.pattern.replace(/\\/g, "/");
2130
+ this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
2131
+ this.regexp = null;
2132
+ this.negate = false;
2133
+ this.nonegate = !!options.nonegate;
2134
+ this.comment = false;
2135
+ this.empty = false;
2136
+ this.partial = !!options.partial;
2137
+ this.nocase = !!this.options.nocase;
2138
+ this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
2139
+ this.globSet = [];
2140
+ this.globParts = [];
2141
+ this.set = [];
2142
+ this.make();
2143
+ }
2144
+ hasMagic() {
2145
+ if (this.options.magicalBraces && this.set.length > 1) return true;
2146
+ for (const pattern of this.set) for (const part of pattern) if (typeof part !== "string") return true;
2147
+ return false;
2148
+ }
2149
+ debug(..._) {}
2150
+ make() {
2151
+ const pattern = this.pattern;
2152
+ const options = this.options;
2153
+ if (!options.nocomment && pattern.charAt(0) === "#") {
2154
+ this.comment = true;
2155
+ return;
2156
+ }
2157
+ if (!pattern) {
2158
+ this.empty = true;
2159
+ return;
2160
+ }
2161
+ this.parseNegate();
2162
+ this.globSet = [...new Set(this.braceExpand())];
2163
+ if (options.debug) this.debug = (...args) => console.error(...args);
2164
+ this.debug(this.pattern, this.globSet);
2165
+ const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));
2166
+ this.globParts = this.preprocess(rawGlobParts);
2167
+ this.debug(this.pattern, this.globParts);
2168
+ let set = this.globParts.map((s, _, __) => {
2169
+ if (this.isWindows && this.windowsNoMagicRoot) {
2170
+ const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);
2171
+ const isDrive = /^[a-z]:/i.test(s[0]);
2172
+ if (isUNC) return [...s.slice(0, 4), ...s.slice(4).map((ss) => this.parse(ss))];
2173
+ else if (isDrive) return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];
2174
+ }
2175
+ return s.map((ss) => this.parse(ss));
2176
+ });
2177
+ this.debug(this.pattern, set);
2178
+ this.set = set.filter((s) => s.indexOf(false) === -1);
2179
+ if (this.isWindows) for (let i = 0; i < this.set.length; i++) {
2180
+ const p = this.set[i];
2181
+ if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) p[2] = "?";
2182
+ }
2183
+ this.debug(this.pattern, this.set);
2184
+ }
2185
+ preprocess(globParts) {
2186
+ if (this.options.noglobstar) {
2187
+ for (const partset of globParts) for (let j = 0; j < partset.length; j++) if (partset[j] === "**") partset[j] = "*";
2188
+ }
2189
+ const { optimizationLevel = 1 } = this.options;
2190
+ if (optimizationLevel >= 2) {
2191
+ globParts = this.firstPhasePreProcess(globParts);
2192
+ globParts = this.secondPhasePreProcess(globParts);
2193
+ } else if (optimizationLevel >= 1) globParts = this.levelOneOptimize(globParts);
2194
+ else globParts = this.adjascentGlobstarOptimize(globParts);
2195
+ return globParts;
2196
+ }
2197
+ adjascentGlobstarOptimize(globParts) {
2198
+ return globParts.map((parts) => {
2199
+ let gs = -1;
2200
+ while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
2201
+ let i = gs;
2202
+ while (parts[i + 1] === "**") i++;
2203
+ if (i !== gs) parts.splice(gs, i - gs);
2204
+ }
2205
+ return parts;
2206
+ });
2207
+ }
2208
+ levelOneOptimize(globParts) {
2209
+ return globParts.map((parts) => {
2210
+ parts = parts.reduce((set, part) => {
2211
+ const prev = set[set.length - 1];
2212
+ if (part === "**" && prev === "**") return set;
2213
+ if (part === "..") {
2214
+ if (prev && prev !== ".." && prev !== "." && prev !== "**") {
2215
+ set.pop();
2216
+ return set;
2217
+ }
2218
+ }
2219
+ set.push(part);
2220
+ return set;
2221
+ }, []);
2222
+ return parts.length === 0 ? [""] : parts;
2223
+ });
2224
+ }
2225
+ levelTwoFileOptimize(parts) {
2226
+ if (!Array.isArray(parts)) parts = this.slashSplit(parts);
2227
+ let didSomething = false;
2228
+ do {
2229
+ didSomething = false;
2230
+ if (!this.preserveMultipleSlashes) {
2231
+ for (let i = 1; i < parts.length - 1; i++) {
2232
+ const p = parts[i];
2233
+ if (i === 1 && p === "" && parts[0] === "") continue;
2234
+ if (p === "." || p === "") {
2235
+ didSomething = true;
2236
+ parts.splice(i, 1);
2237
+ i--;
2238
+ }
2239
+ }
2240
+ if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
2241
+ didSomething = true;
2242
+ parts.pop();
2243
+ }
2244
+ }
2245
+ let dd = 0;
2246
+ while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
2247
+ const p = parts[dd - 1];
2248
+ if (p && p !== "." && p !== ".." && p !== "**" && !(this.isWindows && /^[a-z]:$/i.test(p))) {
2249
+ didSomething = true;
2250
+ parts.splice(dd - 1, 2);
2251
+ dd -= 2;
2252
+ }
2253
+ }
2254
+ } while (didSomething);
2255
+ return parts.length === 0 ? [""] : parts;
2256
+ }
2257
+ firstPhasePreProcess(globParts) {
2258
+ let didSomething = false;
2259
+ do {
2260
+ didSomething = false;
2261
+ for (let parts of globParts) {
2262
+ let gs = -1;
2263
+ while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
2264
+ let gss = gs;
2265
+ while (parts[gss + 1] === "**") gss++;
2266
+ if (gss > gs) parts.splice(gs + 1, gss - gs);
2267
+ let next = parts[gs + 1];
2268
+ const p = parts[gs + 2];
2269
+ const p2 = parts[gs + 3];
2270
+ if (next !== "..") continue;
2271
+ if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") continue;
2272
+ didSomething = true;
2273
+ parts.splice(gs, 1);
2274
+ const other = parts.slice(0);
2275
+ other[gs] = "**";
2276
+ globParts.push(other);
2277
+ gs--;
2278
+ }
2279
+ if (!this.preserveMultipleSlashes) {
2280
+ for (let i = 1; i < parts.length - 1; i++) {
2281
+ const p = parts[i];
2282
+ if (i === 1 && p === "" && parts[0] === "") continue;
2283
+ if (p === "." || p === "") {
2284
+ didSomething = true;
2285
+ parts.splice(i, 1);
2286
+ i--;
2287
+ }
2288
+ }
2289
+ if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
2290
+ didSomething = true;
2291
+ parts.pop();
2292
+ }
2293
+ }
2294
+ let dd = 0;
2295
+ while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
2296
+ const p = parts[dd - 1];
2297
+ if (p && p !== "." && p !== ".." && p !== "**") {
2298
+ didSomething = true;
2299
+ const splin = dd === 1 && parts[dd + 1] === "**" ? ["."] : [];
2300
+ parts.splice(dd - 1, 2, ...splin);
2301
+ if (parts.length === 0) parts.push("");
2302
+ dd -= 2;
2303
+ }
2304
+ }
2305
+ }
2306
+ } while (didSomething);
2307
+ return globParts;
2308
+ }
2309
+ secondPhasePreProcess(globParts) {
2310
+ for (let i = 0; i < globParts.length - 1; i++) for (let j = i + 1; j < globParts.length; j++) {
2311
+ const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
2312
+ if (matched) {
2313
+ globParts[i] = [];
2314
+ globParts[j] = matched;
2315
+ break;
2316
+ }
2317
+ }
2318
+ return globParts.filter((gs) => gs.length);
2319
+ }
2320
+ partsMatch(a, b, emptyGSMatch = false) {
2321
+ let ai = 0;
2322
+ let bi = 0;
2323
+ let result = [];
2324
+ let which = "";
2325
+ while (ai < a.length && bi < b.length) if (a[ai] === b[bi]) {
2326
+ result.push(which === "b" ? b[bi] : a[ai]);
2327
+ ai++;
2328
+ bi++;
2329
+ } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
2330
+ result.push(a[ai]);
2331
+ ai++;
2332
+ } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
2333
+ result.push(b[bi]);
2334
+ bi++;
2335
+ } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
2336
+ if (which === "b") return false;
2337
+ which = "a";
2338
+ result.push(a[ai]);
2339
+ ai++;
2340
+ bi++;
2341
+ } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
2342
+ if (which === "a") return false;
2343
+ which = "b";
2344
+ result.push(b[bi]);
2345
+ ai++;
2346
+ bi++;
2347
+ } else return false;
2348
+ return a.length === b.length && result;
2349
+ }
2350
+ parseNegate() {
2351
+ if (this.nonegate) return;
2352
+ const pattern = this.pattern;
2353
+ let negate = false;
2354
+ let negateOffset = 0;
2355
+ for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
2356
+ negate = !negate;
2357
+ negateOffset++;
2358
+ }
2359
+ if (negateOffset) this.pattern = pattern.slice(negateOffset);
2360
+ this.negate = negate;
2361
+ }
2362
+ matchOne(file, pattern, partial = false) {
2363
+ let fileStartIndex = 0;
2364
+ let patternStartIndex = 0;
2365
+ if (this.isWindows) {
2366
+ const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
2367
+ const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
2368
+ const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);
2369
+ const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
2370
+ const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;
2371
+ const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;
2372
+ if (typeof fdi === "number" && typeof pdi === "number") {
2373
+ const [fd, pd] = [file[fdi], pattern[pdi]];
2374
+ if (fd.toLowerCase() === pd.toLowerCase()) {
2375
+ pattern[pdi] = fd;
2376
+ patternStartIndex = pdi;
2377
+ fileStartIndex = fdi;
2378
+ }
2379
+ }
2380
+ }
2381
+ const { optimizationLevel = 1 } = this.options;
2382
+ if (optimizationLevel >= 2) file = this.levelTwoFileOptimize(file);
2383
+ if (pattern.includes(GLOBSTAR)) return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
2384
+ return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
2385
+ }
2386
+ #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
2387
+ const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
2388
+ const lastgs = pattern.lastIndexOf(GLOBSTAR);
2389
+ const [head, body, tail] = partial ? [
2390
+ pattern.slice(patternIndex, firstgs),
2391
+ pattern.slice(firstgs + 1),
2392
+ []
2393
+ ] : [
2394
+ pattern.slice(patternIndex, firstgs),
2395
+ pattern.slice(firstgs + 1, lastgs),
2396
+ pattern.slice(lastgs + 1)
2397
+ ];
2398
+ if (head.length) {
2399
+ const fileHead = file.slice(fileIndex, fileIndex + head.length);
2400
+ if (!this.#matchOne(fileHead, head, partial, 0, 0)) return false;
2401
+ fileIndex += head.length;
2402
+ patternIndex += head.length;
2403
+ }
2404
+ let fileTailMatch = 0;
2405
+ if (tail.length) {
2406
+ if (tail.length + fileIndex > file.length) return false;
2407
+ let tailStart = file.length - tail.length;
2408
+ if (this.#matchOne(file, tail, partial, tailStart, 0)) fileTailMatch = tail.length;
2409
+ else {
2410
+ if (file[file.length - 1] !== "" || fileIndex + tail.length === file.length) return false;
2411
+ tailStart--;
2412
+ if (!this.#matchOne(file, tail, partial, tailStart, 0)) return false;
2413
+ fileTailMatch = tail.length + 1;
2414
+ }
2415
+ }
2416
+ if (!body.length) {
2417
+ let sawSome = !!fileTailMatch;
2418
+ for (let i = fileIndex; i < file.length - fileTailMatch; i++) {
2419
+ const f = String(file[i]);
2420
+ sawSome = true;
2421
+ if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) return false;
2422
+ }
2423
+ return partial || sawSome;
2424
+ }
2425
+ const bodySegments = [[[], 0]];
2426
+ let currentBody = bodySegments[0];
2427
+ let nonGsParts = 0;
2428
+ const nonGsPartsSums = [0];
2429
+ for (const b of body) if (b === GLOBSTAR) {
2430
+ nonGsPartsSums.push(nonGsParts);
2431
+ currentBody = [[], 0];
2432
+ bodySegments.push(currentBody);
2433
+ } else {
2434
+ currentBody[0].push(b);
2435
+ nonGsParts++;
2436
+ }
2437
+ let i = bodySegments.length - 1;
2438
+ const fileLength = file.length - fileTailMatch;
2439
+ for (const b of bodySegments) b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);
2440
+ return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
2441
+ }
2442
+ #matchGlobStarBodySections(file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
2443
+ const bs = bodySegments[bodyIndex];
2444
+ if (!bs) {
2445
+ for (let i = fileIndex; i < file.length; i++) {
2446
+ sawTail = true;
2447
+ const f = file[i];
2448
+ if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) return false;
2449
+ }
2450
+ return sawTail;
2451
+ }
2452
+ const [body, after] = bs;
2453
+ while (fileIndex <= after) {
2454
+ if (this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0) && globStarDepth < this.maxGlobstarRecursion) {
2455
+ const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
2456
+ if (sub !== false) return sub;
2457
+ }
2458
+ const f = file[fileIndex];
2459
+ if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) return false;
2460
+ fileIndex++;
2461
+ }
2462
+ return partial || null;
2463
+ }
2464
+ #matchOne(file, pattern, partial, fileIndex, patternIndex) {
2465
+ let fi;
2466
+ let pi;
2467
+ let pl;
2468
+ let fl;
2469
+ for (fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
2470
+ this.debug("matchOne loop");
2471
+ let p = pattern[pi];
2472
+ let f = file[fi];
2473
+ this.debug(pattern, p, f);
2474
+ /* c8 ignore start */
2475
+ if (p === false || p === GLOBSTAR) return false;
2476
+ /* c8 ignore stop */
2477
+ let hit;
2478
+ if (typeof p === "string") {
2479
+ hit = f === p;
2480
+ this.debug("string match", p, f, hit);
2481
+ } else {
2482
+ hit = p.test(f);
2483
+ this.debug("pattern match", p, f, hit);
2484
+ }
2485
+ if (!hit) return false;
2486
+ }
2487
+ if (fi === fl && pi === pl) return true;
2488
+ else if (fi === fl) return partial;
2489
+ else if (pi === pl) return fi === fl - 1 && file[fi] === "";
2490
+ else throw new Error("wtf?");
2491
+ /* c8 ignore stop */
2492
+ }
2493
+ braceExpand() {
2494
+ return braceExpand(this.pattern, this.options);
2495
+ }
2496
+ parse(pattern) {
2497
+ assertValidPattern(pattern);
2498
+ const options = this.options;
2499
+ if (pattern === "**") return GLOBSTAR;
2500
+ if (pattern === "") return "";
2501
+ let m;
2502
+ let fastTest = null;
2503
+ if (m = pattern.match(starRE)) fastTest = options.dot ? starTestDot : starTest;
2504
+ else if (m = pattern.match(starDotExtRE)) fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
2505
+ else if (m = pattern.match(qmarksRE)) fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);
2506
+ else if (m = pattern.match(starDotStarRE)) fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
2507
+ else if (m = pattern.match(dotStarRE)) fastTest = dotStarTest;
2508
+ const re = AST.fromGlob(pattern, this.options).toMMPattern();
2509
+ if (fastTest && typeof re === "object") Reflect.defineProperty(re, "test", { value: fastTest });
2510
+ return re;
2511
+ }
2512
+ makeRe() {
2513
+ if (this.regexp || this.regexp === false) return this.regexp;
2514
+ const set = this.set;
2515
+ if (!set.length) {
2516
+ this.regexp = false;
2517
+ return this.regexp;
2518
+ }
2519
+ const options = this.options;
2520
+ const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
2521
+ const flags = new Set(options.nocase ? ["i"] : []);
2522
+ let re = set.map((pattern) => {
2523
+ const pp = pattern.map((p) => {
2524
+ if (p instanceof RegExp) for (const f of p.flags.split("")) flags.add(f);
2525
+ return typeof p === "string" ? regExpEscape(p) : p === GLOBSTAR ? GLOBSTAR : p._src;
2526
+ });
2527
+ pp.forEach((p, i) => {
2528
+ const next = pp[i + 1];
2529
+ const prev = pp[i - 1];
2530
+ if (p !== GLOBSTAR || prev === GLOBSTAR) return;
2531
+ if (prev === void 0) {
2532
+ if (next !== void 0 && next !== GLOBSTAR) pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
2533
+ else pp[i] = twoStar;
2534
+ } else if (next === void 0) pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + ")?";
2535
+ else if (next !== GLOBSTAR) {
2536
+ pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
2537
+ pp[i + 1] = GLOBSTAR;
2538
+ }
2539
+ });
2540
+ const filtered = pp.filter((p) => p !== GLOBSTAR);
2541
+ if (this.partial && filtered.length >= 1) {
2542
+ const prefixes = [];
2543
+ for (let i = 1; i <= filtered.length; i++) prefixes.push(filtered.slice(0, i).join("/"));
2544
+ return "(?:" + prefixes.join("|") + ")";
2545
+ }
2546
+ return filtered.join("/");
2547
+ }).join("|");
2548
+ const [open, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];
2549
+ re = "^" + open + re + close + "$";
2550
+ if (this.partial) re = "^(?:\\/|" + open + re.slice(1, -1) + close + ")$";
2551
+ if (this.negate) re = "^(?!" + re + ").+$";
2552
+ try {
2553
+ this.regexp = new RegExp(re, [...flags].join(""));
2554
+ } catch {
2555
+ this.regexp = false;
2556
+ }
2557
+ /* c8 ignore stop */
2558
+ return this.regexp;
2559
+ }
2560
+ slashSplit(p) {
2561
+ if (this.preserveMultipleSlashes) return p.split("/");
2562
+ else if (this.isWindows && /^\/\/[^/]+/.test(p)) return ["", ...p.split(/\/+/)];
2563
+ else return p.split(/\/+/);
2564
+ }
2565
+ match(f, partial = this.partial) {
2566
+ this.debug("match", f, this.pattern);
2567
+ if (this.comment) return false;
2568
+ if (this.empty) return f === "";
2569
+ if (f === "/" && partial) return true;
2570
+ const options = this.options;
2571
+ if (this.isWindows) f = f.split("\\").join("/");
2572
+ const ff = this.slashSplit(f);
2573
+ this.debug(this.pattern, "split", ff);
2574
+ const set = this.set;
2575
+ this.debug(this.pattern, "set", set);
2576
+ let filename = ff[ff.length - 1];
2577
+ if (!filename) for (let i = ff.length - 2; !filename && i >= 0; i--) filename = ff[i];
2578
+ for (const pattern of set) {
2579
+ let file = ff;
2580
+ if (options.matchBase && pattern.length === 1) file = [filename];
2581
+ if (this.matchOne(file, pattern, partial)) {
2582
+ if (options.flipNegate) return true;
2583
+ return !this.negate;
2584
+ }
2585
+ }
2586
+ if (options.flipNegate) return false;
2587
+ return this.negate;
2588
+ }
2589
+ static defaults(def) {
2590
+ return minimatch.defaults(def).Minimatch;
2591
+ }
2592
+ };
2593
+ /* c8 ignore stop */
2594
+ minimatch.AST = AST;
2595
+ minimatch.Minimatch = Minimatch;
2596
+ minimatch.escape = escape;
2597
+ minimatch.unescape = unescape;
2598
+ //#endregion
2599
+ //#region ../internal/src/build/runtime-package-files.ts
2600
+ const alwaysPublishedFile = /^(?:package\.json|(?:readme|copying|licen[cs]e)(?:\..*[^~$])?)$/i;
2601
+ const rootExcluded = /* @__PURE__ */ new Set([
2602
+ "package-lock.json",
2603
+ "yarn.lock",
2604
+ "pnpm-lock.yaml",
2605
+ "bun.lockb",
2606
+ ".lock-wscript",
2607
+ "build/config.gypi"
2608
+ ]);
2609
+ const excludedEntry = /^(?:node_modules|\.git|\.hg|\.svn|CVS|\.npmrc|\.npmignore|\.gitignore|\.DS_Store|npm-debug\.log|\._.*|.*\.orig|\..*\.swp)$/i;
2610
+ function hasNodeModulesSegment$1(path) {
2611
+ return path.split(/[\\/]/).includes("node_modules");
2612
+ }
2613
+ function isNestedPath(path) {
2614
+ return Boolean(path) && path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path);
2615
+ }
2616
+ /** Runs a filesystem read, and returns `undefined` when the path is gone. */
2617
+ async function unlessGone(read) {
2618
+ try {
2619
+ return await read();
2620
+ } catch (error) {
2621
+ const { code } = error;
2622
+ if (code === "ENOENT" || code === "ENOTDIR") return void 0;
2623
+ throw error;
2624
+ }
2625
+ }
2626
+ function readIfPresent(read) {
2627
+ try {
2628
+ return read();
2629
+ } catch (error) {
2630
+ if (error.code === "ENOENT") return void 0;
2631
+ throw error;
2632
+ }
2633
+ }
2634
+ function packageRule(entry) {
2635
+ const include = !entry.startsWith("!");
2636
+ const matcher = new Minimatch((include ? entry : entry.slice(1)).replace(/^\.\//, "/").replace(/\/$/, "") || "**", {
2637
+ dot: true,
2638
+ matchBase: true,
2639
+ nocase: true,
2640
+ nocomment: true,
2641
+ nonegate: true
2642
+ });
2643
+ return {
2644
+ include,
2645
+ matches: (path, partial = false) => matcher.match(path, partial) || matcher.match(`/${path}`, partial)
2646
+ };
2647
+ }
2648
+ /** Files selected for a linked package's publish list; `undefined` keeps the whole package. */
2649
+ function publishedPackagePaths(packageDir) {
2650
+ let manifest;
2651
+ const contents = readIfPresent(() => readFileSync(join(packageDir, "package.json"), "utf8"));
2652
+ if (contents === void 0) return void 0;
2653
+ try {
2654
+ manifest = JSON.parse(contents);
2655
+ } catch {
2656
+ return;
2657
+ }
2658
+ if (!manifest || typeof manifest !== "object" || !("files" in manifest) || !Array.isArray(manifest.files)) return void 0;
2659
+ const rules = [];
2660
+ const required = /* @__PURE__ */ new Set();
2661
+ const requiredAncestors = /* @__PURE__ */ new Set();
2662
+ const requirePath = (entry) => {
2663
+ const path = relative(packageDir, join(packageDir, entry));
2664
+ if (!isNestedPath(path)) return;
2665
+ required.add(path);
2666
+ for (let parent = dirname(path); parent !== "."; parent = dirname(parent)) requiredAncestors.add(parent);
2667
+ };
2668
+ for (const entry of manifest.files) {
2669
+ if (typeof entry !== "string" || !entry) continue;
2670
+ const candidate = join(packageDir, entry);
2671
+ if (!entry.startsWith("!") && isNestedPath(relative(packageDir, candidate)) && readIfPresent(() => lstatSync(candidate))?.isFile()) requirePath(entry);
2672
+ else rules.push(packageRule(entry.endsWith("/*") ? `${entry}*` : entry));
2673
+ }
2674
+ if ("main" in manifest && typeof manifest.main === "string") requirePath(manifest.main);
2675
+ if ("browser" in manifest && typeof manifest.browser === "string") requirePath(manifest.browser);
2676
+ if ("bin" in manifest) {
2677
+ const bin = manifest.bin;
2678
+ if (typeof bin === "string") requirePath(bin);
2679
+ else if (bin && typeof bin === "object") {
2680
+ for (const file of Object.values(bin)) if (typeof file === "string") requirePath(file);
2681
+ }
2682
+ }
2683
+ const files = /* @__PURE__ */ new Set();
2684
+ const entries = /* @__PURE__ */ new Set([""]);
2685
+ const visit = (directory, ancestors, inheritedIgnores) => {
2686
+ const children = readIfPresent(() => readdirSync(join(packageDir, directory)));
2687
+ if (!children) return;
2688
+ let ignores = inheritedIgnores;
2689
+ if (directory) {
2690
+ const ignore = readIfPresent(() => readFileSync(join(packageDir, directory, ".npmignore"), "utf8")) ?? readIfPresent(() => readFileSync(join(packageDir, directory, ".gitignore"), "utf8"));
2691
+ if (ignore) {
2692
+ const localRules = ignore.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith("#")).map(packageRule);
2693
+ ignores = [...ignores, (paths, included) => {
2694
+ for (const rule of localRules) if (paths.slice(ancestors.length).some((path) => rule.matches(path.slice(directory.length + 1)))) included = !rule.include;
2695
+ return included;
2696
+ }];
2697
+ }
2698
+ }
2699
+ for (const child of children) {
2700
+ const path = join(directory, child);
2701
+ const portablePath = path.replaceAll(sep, "/");
2702
+ if (excludedEntry.test(child) || rootExcluded.has(portablePath) || child.includes("*")) continue;
2703
+ const prefixes = [...ancestors, portablePath];
2704
+ let included = false;
2705
+ for (const rule of rules) if (prefixes.some((prefix) => rule.matches(prefix))) included = rule.include;
2706
+ const includeFile = included && ignores.every((ignore) => ignore(prefixes, true)) || required.has(path) || !directory && alwaysPublishedFile.test(child);
2707
+ const includeDirectory = included || requiredAncestors.has(path) || rules.some((rule) => rule.include && rule.matches(portablePath, true));
2708
+ if (!includeFile && !includeDirectory) continue;
2709
+ const info = readIfPresent(() => lstatSync(join(packageDir, path)));
2710
+ if (info?.isDirectory() && includeDirectory) visit(path, prefixes, ignores);
2711
+ else if (info?.isFile() && includeFile) {
2712
+ files.add(path);
2713
+ for (let entry = path; entry !== "." && !entries.has(entry); entry = dirname(entry)) entries.add(entry);
2714
+ }
2715
+ }
2716
+ };
2717
+ visit("", [], []);
2718
+ return {
2719
+ files,
2720
+ entries
2721
+ };
2722
+ }
2723
+ /** A published file or a directory that contains one. */
2724
+ function isPublishedPackagePath(packageDir, publishedPaths, path) {
2725
+ return !publishedPaths || publishedPaths.entries.has(relative(packageDir, path));
2726
+ }
2727
+ /** Copies a filtered source tree, preserving symlinks, while tolerating disappearance entry by entry. */
2728
+ async function copyRetainedSourceTree(source, target, filter) {
2729
+ async function copyEntry(source, target, freshParent) {
2730
+ if (!filter(source)) return;
2731
+ const info = await unlessGone(() => lstat(source));
2732
+ if (!info) return;
2733
+ if (info.isFile() && freshParent) {
2734
+ await unlessGone(() => copyFile(source, target));
2735
+ return;
2736
+ }
2737
+ if (!info.isDirectory()) {
2738
+ await unlessGone(() => cp(source, target));
2739
+ return;
2740
+ }
2741
+ const entries = await unlessGone(() => readdir(source));
2742
+ if (!entries) return;
2743
+ const created = await mkdir(target, { recursive: true });
2744
+ for (const entry of entries) await copyEntry(join(source, entry), join(target, entry), created !== void 0);
2745
+ if (created) await chmod(target, info.mode);
2746
+ }
2747
+ await copyEntry(source, target, false);
2748
+ }
2749
+ /** Copies a file or folder and follows links. `node_modules` folders and paths that disappear during the copy are skipped. */
2750
+ async function copyTree(source, target) {
2751
+ const info = await unlessGone(() => stat(source));
2752
+ if (!info) return;
2753
+ if (!info.isDirectory()) {
2754
+ await unlessGone(() => copyFile(source, target));
2755
+ return;
2756
+ }
2757
+ const entries = await unlessGone(() => readdir(source));
2758
+ if (!entries) return;
2759
+ await mkdir(target, { recursive: true });
2760
+ for (const entry of entries) if (entry !== "node_modules") await copyTree(join(source, entry), join(target, entry));
2761
+ }
2762
+ /**
2763
+ * Copies one runtime package into deployment output, without its `node_modules`.
2764
+ *
2765
+ * An installed package only holds its published files. A linked workspace package, such as a `link:` or `workspace:`
2766
+ * dependency, is a whole source folder with tests and fixtures, so only the files that `npm publish` would ship are
2767
+ * copied. A path that disappears during the copy, such as a temporary test folder that another process removes, is
2768
+ * skipped instead of failing the build.
2769
+ */
2770
+ async function copyRuntimePackageFiles(packageDir, targetDir) {
2771
+ const paths = hasNodeModulesSegment$1(packageDir) ? void 0 : publishedPackagePaths(packageDir);
2772
+ if (!paths) {
2773
+ await copyTree(packageDir, targetDir);
2774
+ return;
2775
+ }
2776
+ await mkdir(targetDir, { recursive: true });
2777
+ for (const path of paths.files) {
2778
+ const target = join(targetDir, path);
2779
+ await mkdir(dirname(target), { recursive: true });
2780
+ await unlessGone(() => copyFile(join(packageDir, path), target));
2781
+ }
2782
+ }
2783
+ //#endregion
999
2784
  //#region ../internal/src/build/scan-module.ts
1000
2785
  /**
1001
2786
  * Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
@@ -1468,18 +3253,21 @@ function dependencyRoots(root) {
1468
3253
  return [...new Set(roots)];
1469
3254
  }
1470
3255
  async function linkDependencies(source, target, resolveLinkTarget = (source) => source) {
3256
+ const entries = await unlessGone(() => readdir(source));
3257
+ if (!entries) return;
1471
3258
  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()) {
3259
+ for (const entry of entries) {
3260
+ if (entry === ".bin" || entry === ".pnpm") continue;
3261
+ const sourceEntry = resolve(source, entry);
3262
+ const targetEntry = resolve(target, entry);
3263
+ const sourceType = await unlessGone(() => lstat(sourceEntry));
3264
+ if (!sourceType) continue;
3265
+ if (entry.startsWith("@") && sourceType.isDirectory()) {
1480
3266
  await linkDependencies(sourceEntry, targetEntry, resolveLinkTarget);
1481
3267
  continue;
1482
3268
  }
3269
+ const resolvedSourceEntry = await unlessGone(() => realpath(sourceEntry));
3270
+ if (!resolvedSourceEntry || !(await unlessGone(() => stat(resolvedSourceEntry)))?.isDirectory()) continue;
1483
3271
  if (existsSync(targetEntry)) continue;
1484
3272
  await symlink(resolveLinkTarget(resolvedSourceEntry), targetEntry, process.platform === "win32" ? "junction" : "dir");
1485
3273
  }
@@ -2142,15 +3930,18 @@ async function retainProviderOutputSources(options) {
2142
3930
  referencedAncestors.add(directory);
2143
3931
  if (directory === root) break;
2144
3932
  }
3933
+ const referencedSourceSet = new Set(referencedSources);
3934
+ const publishedPaths = new Map([...referencedPackages].map((sourcePackage) => [sourcePackage, publishedPackagePaths(sourcePackage)]));
2145
3935
  const isReferencedSource = (path) => {
2146
3936
  if (referencedAncestors.has(path)) return true;
2147
3937
  for (let directory = path; pathContains$1(root, directory); directory = dirname(directory)) {
2148
- if (referencedTrees.has(directory)) return true;
3938
+ if (referencedSourceSet.has(directory)) return true;
3939
+ if (publishedPaths.has(directory)) return isPublishedPackagePath(directory, publishedPaths.get(directory), path);
2149
3940
  if (directory === root) break;
2150
3941
  }
2151
3942
  return false;
2152
3943
  };
2153
- const nestedDependencyRoots = /* @__PURE__ */ new Map();
3944
+ const nestedDependencyRoots = new Map([...referencedPackages].map((sourcePackage) => [resolve(retainedRoot, relative(root, sourcePackage), "node_modules"), resolve(sourcePackage, "node_modules")]));
2154
3945
  const temporaryRoot = await mkdtemp(resolve(tmpdir(), "vitehub-provider-sources-"));
2155
3946
  const stagedContainer = resolve(temporaryRoot, "source");
2156
3947
  const stagedRoot = resolve(stagedContainer, relative(captureRoot, root));
@@ -2178,33 +3969,26 @@ async function retainProviderOutputSources(options) {
2178
3969
  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
3970
  return true;
2180
3971
  };
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)));
3972
+ await copyRetainedSourceTree(root, stagedRoot, (source) => shouldCopySource(resolve(source)));
3973
+ 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
3974
  for (const source of escapedMaterializedSources) {
2187
3975
  const retainedSource = resolve(stagedContainer, relative(captureRoot, source));
2188
3976
  await mkdir(dirname(retainedSource), { recursive: true });
2189
- await cp(realpathSync(source), retainedSource, {
2190
- filter: (path) => !isLocalSecretFile(path),
2191
- recursive: statSync(source).isDirectory()
2192
- });
3977
+ const sourceTarget = await unlessGone(() => realpath(source));
3978
+ if (sourceTarget) await copyRetainedSourceTree(sourceTarget, retainedSource, (path) => !isLocalSecretFile(path));
2193
3979
  }
2194
3980
  for (const source of requestedSymlinks) {
2195
3981
  const retainedSource = resolve(stagedRoot, relative(root, source));
2196
- const sourceTarget = realpathSync(source);
3982
+ const sourceTarget = await unlessGone(() => realpath(source));
3983
+ if (!sourceTarget) continue;
2197
3984
  await rm(retainedSource, {
2198
3985
  force: true,
2199
3986
  recursive: true
2200
3987
  });
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
- }
3988
+ await copyRetainedSourceTree(sourceTarget, retainedSource, (candidate) => {
3989
+ const physicalCandidate = resolve(candidate);
3990
+ const logicalCandidate = resolve(source, relative(sourceTarget, physicalCandidate));
3991
+ return materializedSources.some((path) => pathContains$1(logicalCandidate, path) || pathContains$1(path, logicalCandidate) || pathContains$1(physicalCandidate, path) || pathContains$1(path, physicalCandidate)) && shouldCopySource(logicalCandidate);
2208
3992
  });
2209
3993
  }
2210
3994
  await rebaseCapturedAbsoluteSourceLinks(stagedContainer, captureRoot, retainedContainer);
@@ -2294,6 +4078,9 @@ async function retainProviderOutputSources(options) {
2294
4078
  }
2295
4079
  //#endregion
2296
4080
  //#region ../internal/src/build/vercel-config.ts
4081
+ function createDefaultVercelOutputRoot(rootDir) {
4082
+ return resolve(rootDir, ".vercel", "output");
4083
+ }
2297
4084
  function createVercelConfigJson() {
2298
4085
  return {
2299
4086
  routes: [{ handle: "filesystem" }, {
@@ -2314,6 +4101,311 @@ function createNodeFunctionConfig(extra = {}) {
2314
4101
  };
2315
4102
  }
2316
4103
  //#endregion
4104
+ //#region ../internal/src/build/runtime-package-resolution.ts
4105
+ /** Locates package metadata through exports, an entry's ancestors, or the project's dependency roots. */
4106
+ function createRuntimePackageResolver(readPackageName) {
4107
+ return async (name, resolver, fromDir) => {
4108
+ try {
4109
+ return resolver.resolve(`${name}/package.json`);
4110
+ } catch (error) {
4111
+ if (!isPackageResolutionMiss(error)) throw error;
4112
+ }
4113
+ try {
4114
+ let current = dirname(resolver.resolve(name));
4115
+ while (current !== dirname(current)) {
4116
+ const candidate = join(current, "package.json");
4117
+ try {
4118
+ await access(candidate);
4119
+ if (readPackageName(await readFile(candidate, "utf8"), candidate) === name) return candidate;
4120
+ } catch (error) {
4121
+ if (error.code !== "ENOENT") throw error;
4122
+ }
4123
+ current = dirname(current);
4124
+ }
4125
+ } catch (error) {
4126
+ if (!isPackageResolutionMiss(error)) throw error;
4127
+ }
4128
+ let current = fromDir;
4129
+ while (current !== dirname(current)) {
4130
+ const candidate = join(current, "node_modules", ...name.split("/"), "package.json");
4131
+ try {
4132
+ await access(candidate);
4133
+ return candidate;
4134
+ } catch (error) {
4135
+ if (error.code !== "ENOENT") throw error;
4136
+ }
4137
+ current = dirname(current);
4138
+ }
4139
+ };
4140
+ }
4141
+ function isPackageResolutionMiss(error) {
4142
+ const code = error?.code;
4143
+ return code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED";
4144
+ }
4145
+ //#endregion
4146
+ //#region ../internal/src/build/runtime-package-directory.ts
4147
+ /** Update a staged copy, then publish it with rollback on failure or cancellation. */
4148
+ async function updateRuntimePackageDirectory(options) {
4149
+ const stagingRoot = await mkdtemp(join(dirname(options.directory), ".vitehub-runtime-packages-"));
4150
+ const stagedDirectory = join(stagingRoot, "node_modules");
4151
+ const previousDirectory = join(stagingRoot, "previous-node_modules");
4152
+ let movedPreviousOutput = false;
4153
+ let installedReplacement = false;
4154
+ let cleanupStagingRoot = true;
4155
+ try {
4156
+ try {
4157
+ await cp(options.directory, stagedDirectory, { recursive: true });
4158
+ } catch (error) {
4159
+ if (error.code !== "ENOENT") throw error;
4160
+ }
4161
+ await mkdir(stagedDirectory, { recursive: true });
4162
+ await options.update(stagedDirectory);
4163
+ options.signal?.throwIfAborted();
4164
+ try {
4165
+ await rename(options.directory, previousDirectory);
4166
+ movedPreviousOutput = true;
4167
+ cleanupStagingRoot = false;
4168
+ } catch (error) {
4169
+ if (error.code !== "ENOENT") throw error;
4170
+ }
4171
+ try {
4172
+ options.signal?.throwIfAborted();
4173
+ await rename(stagedDirectory, options.directory);
4174
+ installedReplacement = true;
4175
+ options.signal?.throwIfAborted();
4176
+ cleanupStagingRoot = true;
4177
+ } catch (error) {
4178
+ if (installedReplacement) await rm(options.directory, {
4179
+ force: true,
4180
+ recursive: true
4181
+ });
4182
+ if (movedPreviousOutput) await rename(previousDirectory, options.directory);
4183
+ cleanupStagingRoot = true;
4184
+ throw error;
4185
+ }
4186
+ } finally {
4187
+ if (cleanupStagingRoot) await rm(stagingRoot, {
4188
+ force: true,
4189
+ recursive: true
4190
+ });
4191
+ }
4192
+ }
4193
+ //#endregion
4194
+ //#region ../internal/src/build/vercel-runtime-packages.ts
4195
+ const runtimeExportConditions = /* @__PURE__ */ new Set([
4196
+ "default",
4197
+ "import",
4198
+ "module",
4199
+ "node",
4200
+ "node-addons",
4201
+ "require"
4202
+ ]);
4203
+ const resolvePackageJson = createRuntimePackageResolver((source, path) => parsePackageJson(JSON.parse(source), path).name);
4204
+ let nodeFileTracePromise;
4205
+ /** Collects the runtime packages that features add to Vercel functions, then traces and copies them once per function. */
4206
+ function createVercelFunctionRuntimePackagesPass(beforeWrite) {
4207
+ const requests = [];
4208
+ return {
4209
+ add(request) {
4210
+ requests.push(request);
4211
+ },
4212
+ async copy(signal) {
4213
+ const functions = /* @__PURE__ */ new Map();
4214
+ for (const request of requests.splice(0)) {
4215
+ const outputRoot = request.outputRoot ?? createDefaultVercelOutputRoot(request.rootDir);
4216
+ const serverDir = resolve(outputRoot, "functions", request.serverFunctionName ?? "__server.func");
4217
+ const entry = functions.get(serverDir) ?? {
4218
+ requests: [],
4219
+ rootDir: request.rootDir
4220
+ };
4221
+ entry.requests.push(request);
4222
+ functions.set(serverDir, entry);
4223
+ }
4224
+ for (const [serverDir, entry] of functions) await copyFunctionRuntimePackages(serverDir, entry.rootDir, entry.requests, signal, beforeWrite);
4225
+ }
4226
+ };
4227
+ }
4228
+ async function copyFunctionRuntimePackages(serverDir, rootDir, requests, signal, beforeWrite) {
4229
+ try {
4230
+ await access(serverDir);
4231
+ } catch (error) {
4232
+ if (error.code === "ENOENT") return;
4233
+ throw error;
4234
+ }
4235
+ const groups = [];
4236
+ for (const request of requests) {
4237
+ const requested = Array.isArray(request.packages) ? request.packages : await request.packages();
4238
+ if (requested.length) groups.push(requested.map((runtimePackage) => ({
4239
+ ...runtimePackage,
4240
+ resolveFrom: runtimePackage.resolveFrom ?? join(request.rootDir, "package.json")
4241
+ })));
4242
+ }
4243
+ if (!groups.length) return;
4244
+ const directory = resolve(serverDir, "node_modules");
4245
+ await beforeWrite?.(directory);
4246
+ await updateRuntimePackageDirectory({
4247
+ directory,
4248
+ signal,
4249
+ update: (outputNodeModules) => copyNodeRuntimePackageGroups(outputNodeModules, rootDir, groups)
4250
+ });
4251
+ }
4252
+ async function copyNodeRuntimePackageGroups(outputNodeModules, rootDir, groups) {
4253
+ const selected = /* @__PURE__ */ new Map();
4254
+ const requested = /* @__PURE__ */ new Map();
4255
+ for (const packages of groups) {
4256
+ const visited = /* @__PURE__ */ new Set();
4257
+ const expanded = /* @__PURE__ */ new Set();
4258
+ for (const runtimePackage of packages) {
4259
+ const resolveFrom = runtimePackage.resolveFrom ?? join(rootDir, "package.json");
4260
+ const resolver = createRequire(resolveFrom);
4261
+ const packageJsonPath = await selectRuntimePackage(runtimePackage.name, resolver, dirname(resolveFrom), selected, visited, expanded, runtimePackage);
4262
+ if (!packageJsonPath) continue;
4263
+ const previous = requested.get(runtimePackage.name);
4264
+ if (previous && previous !== packageJsonPath) throw internalErrorDiagnostics.INTERNAL_RUNTIME_PACKAGE_VERSION_CONFLICT({
4265
+ first: dirname(previous),
4266
+ name: runtimePackage.name,
4267
+ second: dirname(packageJsonPath)
4268
+ });
4269
+ requested.set(runtimePackage.name, packageJsonPath);
4270
+ }
4271
+ }
4272
+ for (const [name, { packageJson, packageJsonPath, resolver }] of selected) {
4273
+ const packageDir = dirname(packageJsonPath);
4274
+ const targetDir = join(outputNodeModules, ...name.split("/"));
4275
+ await rm(targetDir, {
4276
+ force: true,
4277
+ recursive: true
4278
+ });
4279
+ if (!await copyTracedPackageFiles(name, resolver, packageDir, packageJsonPath, packageJson, targetDir)) await copyRuntimePackageFiles(packageDir, targetDir);
4280
+ }
4281
+ }
4282
+ async function selectRuntimePackage(name, resolver, fromDir, selected, visited, expanded, options = { name }) {
4283
+ const packageJsonPath = await resolvePackageJson(name, resolver, fromDir);
4284
+ if (!packageJsonPath) {
4285
+ if (options.optional) return void 0;
4286
+ throw internalErrorDiagnostics.INTERNAL_B0046({ message: `Could not resolve package.json for ${name}.` });
4287
+ }
4288
+ const resolvedPackageJsonPath = await realpath(packageJsonPath);
4289
+ const packageDir = dirname(resolvedPackageJsonPath);
4290
+ const packageJson = parsePackageJson(JSON.parse(await readFile(resolvedPackageJsonPath, "utf8")), resolvedPackageJsonPath);
4291
+ const packageKey = `${name}\0${resolvedPackageJsonPath}`;
4292
+ if (!visited.has(packageKey)) {
4293
+ visited.add(packageKey);
4294
+ selected.set(name, {
4295
+ packageJson,
4296
+ packageJsonPath: resolvedPackageJsonPath,
4297
+ resolver
4298
+ });
4299
+ }
4300
+ const expansionKey = `${packageKey}\0${options.includePeerDependencies ? "peers" : "dependencies"}`;
4301
+ if (expanded.has(expansionKey)) return resolvedPackageJsonPath;
4302
+ expanded.add(expansionKey);
4303
+ const packageRequire = createRequire(resolvedPackageJsonPath);
4304
+ const dependencyNames = new Set(Object.keys(packageJson.dependencies || {}));
4305
+ const optionalDependencyNames = new Set(Object.keys(packageJson.optionalDependencies || {}));
4306
+ for (const dependencyName of optionalDependencyNames) dependencyNames.add(dependencyName);
4307
+ const requiredPeerDependencyNames = /* @__PURE__ */ new Set();
4308
+ if (options.includePeerDependencies) {
4309
+ for (const dependencyName of Object.keys(packageJson.peerDependencies || {})) if (!packageJson.peerDependenciesMeta?.[dependencyName]?.optional) {
4310
+ dependencyNames.add(dependencyName);
4311
+ requiredPeerDependencyNames.add(dependencyName);
4312
+ }
4313
+ }
4314
+ for (const dependencyName of dependencyNames) await selectRuntimePackage(dependencyName, packageRequire, packageDir, selected, visited, expanded, {
4315
+ includePeerDependencies: options.includePeerDependencies,
4316
+ name: dependencyName,
4317
+ optional: optionalDependencyNames.has(dependencyName) && !requiredPeerDependencyNames.has(dependencyName)
4318
+ });
4319
+ return resolvedPackageJsonPath;
4320
+ }
4321
+ async function copyTracedPackageFiles(name, resolver, packageDir, packageJsonPath, packageJson, targetDir) {
4322
+ const entries = await resolvePackageTraceEntries(name, resolver, packageDir, packageJson);
4323
+ if (!entries) return false;
4324
+ const { fileList } = await (await loadNodeFileTrace())([...entries], {
4325
+ base: packageDir,
4326
+ conditions: ["node"],
4327
+ exportsOnly: true,
4328
+ processCwd: packageDir
4329
+ });
4330
+ fileList.add(relative(packageDir, packageJsonPath));
4331
+ for (const file of fileList) {
4332
+ const source = resolve(packageDir, file);
4333
+ if (!isInsideDirectory(packageDir, source) || hasNodeModulesSegment(file)) continue;
4334
+ if (!(await stat(source)).isFile()) continue;
4335
+ const target = resolve(targetDir, file);
4336
+ await mkdir(dirname(target), { recursive: true });
4337
+ await copyFile(source, target);
4338
+ }
4339
+ return true;
4340
+ }
4341
+ async function loadNodeFileTrace() {
4342
+ nodeFileTracePromise ??= import("./out-BbXG-yVX.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1)).then(({ nodeFileTrace }) => nodeFileTrace);
4343
+ return nodeFileTracePromise;
4344
+ }
4345
+ async function resolvePackageTraceEntries(name, resolver, packageDir, packageJson) {
4346
+ const entryCandidates = /* @__PURE__ */ new Set();
4347
+ if (packageJson.exports) {
4348
+ const exportedTargets = collectRuntimeExportTargets(packageJson.exports);
4349
+ if (!exportedTargets) return void 0;
4350
+ for (const target of exportedTargets) entryCandidates.add(resolve(packageDir, target));
4351
+ } else {
4352
+ try {
4353
+ entryCandidates.add(resolver.resolve(name));
4354
+ } catch (error) {
4355
+ if (!isPackageResolutionMiss(error)) throw error;
4356
+ }
4357
+ if (packageJson.main) entryCandidates.add(resolve(packageDir, packageJson.main));
4358
+ if (packageJson.module) entryCandidates.add(resolve(packageDir, packageJson.module));
4359
+ entryCandidates.add(resolve(packageDir, "index.js"));
4360
+ }
4361
+ const entries = [];
4362
+ for (const candidate of entryCandidates) try {
4363
+ const candidateStat = await stat(candidate);
4364
+ if (candidateStat.isFile()) entries.push(candidate);
4365
+ else if (candidateStat.isDirectory()) return void 0;
4366
+ } catch (error) {
4367
+ if (error.code !== "ENOENT") throw error;
4368
+ }
4369
+ return entries.length ? entries : void 0;
4370
+ }
4371
+ function collectRuntimeExportTargets(exportsValue, condition) {
4372
+ if (typeof exportsValue === "string") {
4373
+ if (condition === "types") return /* @__PURE__ */ new Set();
4374
+ if (exportsValue.includes("*")) return void 0;
4375
+ return exportsValue.startsWith("./") ? /* @__PURE__ */ new Set([exportsValue]) : /* @__PURE__ */ new Set();
4376
+ }
4377
+ if (Array.isArray(exportsValue)) {
4378
+ const targets = /* @__PURE__ */ new Set();
4379
+ for (const entry of exportsValue) {
4380
+ const entryTargets = collectRuntimeExportTargets(entry, condition);
4381
+ if (!entryTargets) return void 0;
4382
+ for (const target of entryTargets) targets.add(target);
4383
+ }
4384
+ return targets;
4385
+ }
4386
+ if (typeof exportsValue !== "object" || exportsValue === null) return /* @__PURE__ */ new Set();
4387
+ const targets = /* @__PURE__ */ new Set();
4388
+ for (const [key, value] of Object.entries(exportsValue)) {
4389
+ if (key === "types") continue;
4390
+ if (!key.startsWith(".") && !runtimeExportConditions.has(key)) continue;
4391
+ const entryTargets = collectRuntimeExportTargets(value, key);
4392
+ if (!entryTargets) return void 0;
4393
+ for (const target of entryTargets) targets.add(target);
4394
+ }
4395
+ return targets;
4396
+ }
4397
+ function hasNodeModulesSegment(path) {
4398
+ return path.split(/[\\/]/).includes("node_modules");
4399
+ }
4400
+ function isInsideDirectory(parent, child) {
4401
+ const childRelativePath = relative(parent, child);
4402
+ return childRelativePath === "" || !childRelativePath.startsWith(`..${sep}`) && childRelativePath !== ".." && !isAbsolute(childRelativePath);
4403
+ }
4404
+ function parsePackageJson(value, path) {
4405
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw internalErrorDiagnostics.INTERNAL_B0047({ message: `Expected ${path} to contain a JSON object.` });
4406
+ return value;
4407
+ }
4408
+ //#endregion
2317
4409
  //#region ../internal/src/build/provider-output-catalog.ts
2318
4410
  var ProviderOutputCatalog = class {
2319
4411
  bundleDefines = {};
@@ -2634,9 +4726,6 @@ async function writeProviderOutputOwnershipFiles(outputRoot, ownership, files) {
2634
4726
  await writeFile(file, `${JSON.stringify(values, null, 2)}\n`, "utf8");
2635
4727
  }));
2636
4728
  }
2637
- function createDefaultVercelOutputRoot(rootDir) {
2638
- return resolve(rootDir, ".vercel", "output");
2639
- }
2640
4729
  function createDefaultNetlifyOutputRoot(rootDir) {
2641
4730
  return resolve(rootDir, ".netlify", "v1");
2642
4731
  }
@@ -3477,9 +5566,11 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
3477
5566
  const write = withProviderDeploymentOutputRootLock(rootDir, async () => {
3478
5567
  await withProviderDeploymentOutputRootTransaction(rootDir, async (transaction) => {
3479
5568
  try {
5569
+ const vercelRuntimePackages = createVercelFunctionRuntimePackagesPass((nodeModules) => transaction.snapshot([nodeModules]));
3480
5570
  for (const contribution of rootContributions) {
3481
5571
  throwIfProviderOutputAborted(controller.signal);
3482
5572
  await contribution.write({
5573
+ addVercelRuntimePackages: (request) => vercelRuntimePackages.add(request),
3483
5574
  readCloudflareState: async (options) => await readCloudflareProviderDeploymentOutputState(rootDir, options),
3484
5575
  signal: controller.signal,
3485
5576
  write: async (writeOptions) => {
@@ -3495,6 +5586,8 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
3495
5586
  });
3496
5587
  throwIfProviderOutputAborted(controller.signal);
3497
5588
  }
5589
+ await vercelRuntimePackages.copy(controller.signal);
5590
+ throwIfProviderOutputAborted(controller.signal);
3498
5591
  ready();
3499
5592
  const rollback = await rootDecision;
3500
5593
  if (rollback !== void 0) throw rollback;
@@ -3831,8 +5924,8 @@ function resolveHostPreset(input = {}) {
3831
5924
  function resolveHost(input = {}) {
3832
5925
  return hostFromNitroPreset(resolveHostPreset(input));
3833
5926
  }
3834
- //#endregion
3835
- //#region ../internal/src/nitro-kit.ts
5927
+ Object.freeze({ vitehubAuthAccess: "handler" });
5928
+ Object.freeze({ vitehubOwnAccess: true });
3836
5929
  function cloneArray(value) {
3837
5930
  return Array.isArray(value) ? [...value] : [];
3838
5931
  }
@@ -3915,6 +6008,10 @@ async function collectContributions(plugins, options) {
3915
6008
  const candidates = [];
3916
6009
  await flattenPlugins(plugins ?? [], candidates, /* @__PURE__ */ new Set());
3917
6010
  const collected = /* @__PURE__ */ new Map();
6011
+ const context = {
6012
+ ...options.context,
6013
+ plugins: candidates
6014
+ };
3918
6015
  for (const plugin of candidates) {
3919
6016
  if (!Object.hasOwn(plugin, "vitehub")) continue;
3920
6017
  const metadata = Reflect.get(plugin, "vitehub");
@@ -3926,7 +6023,7 @@ async function collectContributions(plugins, options) {
3926
6023
  throw options.invalid(`[vitehub] Plugin ${JSON.stringify(contributor)} contributed an invalid ${options.kind}: ${reason}`);
3927
6024
  };
3928
6025
  const callable = typeof source === "function";
3929
- const entries = callable ? await Reflect.apply(source, void 0, [options.context]) : source;
6026
+ const entries = callable ? await Reflect.apply(source, void 0, [context]) : source;
3930
6027
  if (entries === void 0 && callable) continue;
3931
6028
  if (!Array.isArray(entries)) fail(`\`vitehub.${options.key}\` must be an array or a function that returns one.`);
3932
6029
  const list = entries;
@@ -4136,11 +6233,6 @@ function startedTickSource() {
4136
6233
  ""
4137
6234
  ].join("\n");
4138
6235
  }
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
6236
  function startedTickDefinition(rootDir) {
4145
6237
  const file = resolve(rootDir, startedTickFile);
4146
6238
  const source = startedTickSource();
@@ -4340,14 +6432,22 @@ async function removeEmptyDirectories(directory, rootDir) {
4340
6432
  }
4341
6433
  }
4342
6434
  const cronFieldPattern = /^[*,/\-0-9]+$/;
4343
- function validateProviderCron(cron, scheduleName) {
6435
+ /** Whether host wake output accepts `cron`: five numeric UTC fields that Cloudflare, Vercel, and Netlify all read. */
6436
+ function isProviderCron(cron) {
4344
6437
  const fields = cron.trim().split(/\s+/);
4345
6438
  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.` });
6439
+ return fields.length === 5 && fields.every((field) => cronFieldPattern.test(field)) && !hasVercelDayConflict;
4347
6440
  }
4348
- function readStaticScheduleCron(file, scheduleName) {
6441
+ function validateProviderCron(cron, scheduleName) {
6442
+ 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.` });
6443
+ }
6444
+ /** Reads the `cron` option of a `defineSchedule()` call. Returns `undefined` when it is missing or not a static string. */
6445
+ function readStaticScheduleCronOption(file) {
4349
6446
  const definition = findDefaultExportCall(scanModule(readFileSync(file, "utf8"), file), ["defineSchedule"]);
4350
- const cron = definition?.options && staticString(findProperty(definition.options, "cron")?.value);
6447
+ return definition?.options && staticString(findProperty(definition.options, "cron")?.value) || void 0;
6448
+ }
6449
+ function readStaticScheduleCron(file, scheduleName) {
6450
+ const cron = readStaticScheduleCronOption(file);
4351
6451
  if (!cron) throw scheduleErrorDiagnostics.SCHEDULE_R0004({ message: `Schedule "${scheduleName}" must declare a static cron string for provider wake output.` });
4352
6452
  return cron;
4353
6453
  }
@@ -4403,7 +6503,7 @@ function renderProviderEntry(file, registryFile, provider, scheduleName, workflo
4403
6503
  const workflowRuntime = provider === "vercel" ? workflow : void 0;
4404
6504
  return [
4405
6505
  `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)}`,
6506
+ `import { ${provider === "cloudflare" ? "cronWithWeekdayNames, " : ""}executeStaticSchedule, ${provider === "vercel" ? "isScheduleCronAuthorized, " : ""}isTimeZoneWakeDue, missingScheduleDefinitionError, normalizeCron, ${provider === "vercel" ? "scheduledWakeTime, " : ""}unwrapScheduleDefinition } from ${JSON.stringify(runtimeImport)}`,
4407
6507
  ...workflowRuntime ? [
4408
6508
  `import workflowRegistry from ${JSON.stringify(createImportPath(file, workflowRuntime.registryFile))}`,
4409
6509
  `import { setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from ${JSON.stringify(workflowRuntime.runtimeModules.state)}`,
@@ -4452,12 +6552,16 @@ function renderProviderEntry(file, registryFile, provider, scheduleName, workflo
4452
6552
  " },",
4453
6553
  " async scheduled(event, env, ctx) {",
4454
6554
  " if (typeof event.cron !== 'string' || !event.cron.trim()) return",
6555
+ " const trigger = normalizeCron(event.cron)",
4455
6556
  " const tasks = Object.entries(scheduleRegistry).map(async ([name]) => {",
4456
6557
  " const definition = await loadScheduleDefinition(name)",
4457
- " if (!definition || normalizeCron(scheduleCron(name, definition)) !== normalizeCron(event.cron)) return",
6558
+ " if (!definition) return",
6559
+ " const cron = normalizeCron(scheduleCron(name, definition))",
6560
+ " // wrangler.json has the cron with weekday names, so Cloudflare reads each weekday as declared.",
6561
+ " if (cronWithWeekdayNames(cron) !== trigger) return",
4458
6562
  " const scheduledAt = new Date(event.scheduledTime)",
4459
6563
  " if (!isWakeDue(name, definition, scheduledAt)) return",
4460
- " await executeStaticSchedule({ cron: event.cron, definition, name, scheduledAt, waitUntil: (promise) => ctx.waitUntil(promise) })",
6564
+ " await executeStaticSchedule({ cron, definition, name, scheduledAt, waitUntil: (promise) => ctx.waitUntil(promise) })",
4461
6565
  " })",
4462
6566
  " await Promise.all(tasks)",
4463
6567
  " },",
@@ -4540,23 +6644,10 @@ function renderDenoCronEntry(file, registryFile, crons, runtimeImport = schedule
4540
6644
  const cronId = index.toString(36);
4541
6645
  const safeName = [...name].map((character) => /^[a-z0-9 _-]$/i.test(character) ? character : "_").join("");
4542
6646
  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
- }
4556
6647
  return {
4557
6648
  cron,
4558
6649
  cronName: `${cronNamePrefix}${safeName.slice(0, 64 - cronNamePrefix.length)}`,
4559
- denoCron: fields.join(" "),
6650
+ denoCron: cronWithWeekdayNames(cron),
4560
6651
  inTimeZone: Object.hasOwn(timeZoneCrons, name),
4561
6652
  name
4562
6653
  };
@@ -5105,7 +7196,7 @@ async function generateProviderOutputsWithinLock(options) {
5105
7196
  bundleAlias: options.bundleAlias,
5106
7197
  bundleDefines: options.bundleDefines,
5107
7198
  bundleEntry: artifacts.cloudflareWorkerFile,
5108
- crons: [...new Set(crons.values())],
7199
+ crons: [...new Set([...crons.values()].map(cronWithWeekdayNames))],
5109
7200
  rootDir: options.rootDir,
5110
7201
  previousStateFile: previousCloudflareStateFile,
5111
7202
  sourceRootDir: options.sourceRootDir,
@@ -5168,17 +7259,13 @@ async function generateProviderOutputsWithinLock(options) {
5168
7259
  function inspectTimeZone(timeZone) {
5169
7260
  return timeZone === null ? "Not a static string" : timeZone ?? "UTC";
5170
7261
  }
5171
- /** The UTC cron that Cloudflare, Vercel, Netlify, and Deno run for a Schedule with a static `timeZone`. */
5172
7262
  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
- }
7263
+ if (!isIanaTimeZone(timeZone) || !isProviderCron(cron) || !parseCronFields(cron)) return [];
7264
+ const utcCron = utcCronForTimeZone(cron, timeZone);
7265
+ return utcCron ? [{
7266
+ label: "Host cron (UTC)",
7267
+ value: utcCron
7268
+ }] : [];
5182
7269
  }
5183
7270
  function summarizeScheduleDefinition(projectRoot, definition, crons, overrides = {}) {
5184
7271
  const declaredCron = crons.get(definition.name);
@@ -5242,9 +7329,8 @@ async function inspectScheduleDefinitions(options) {
5242
7329
  const crons = /* @__PURE__ */ new Map();
5243
7330
  for (const definition of definitions) {
5244
7331
  if (definition.startable) continue;
5245
- try {
5246
- for (const [name, cron] of await readRuntimeDefinitionCrons([definition])) crons.set(name, cron);
5247
- } catch {}
7332
+ const cron = readStaticScheduleCronOption(definition.handler);
7333
+ if (cron) crons.set(definition.name, cron);
5248
7334
  }
5249
7335
  return definitions.map((definition) => summarizeScheduleDefinition(options.projectRoot, definition, crons, options.cron));
5250
7336
  }
@@ -5271,10 +7357,10 @@ function definitionRecord(summary) {
5271
7357
  },
5272
7358
  startable ? {
5273
7359
  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.`
7360
+ 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
7361
  } : {
5276
7362
  label: "Runs",
5277
- value: `Use \`vitehub schedule runs ${summary.name}\` to list runs that this runtime recorded.`
7363
+ value: `Use \`vitehub schedule runs list ${summary.name}\` to list runs that this runtime recorded.`
5278
7364
  }
5279
7365
  ],
5280
7366
  id: `definition:${summary.name}`,
@@ -5288,7 +7374,7 @@ async function inspectScheduleConsoleRecords(options) {
5288
7374
  /**
5289
7375
  * Console section for Schedules. Records list discovered Schedule Definitions. When the server runs the Process Runtime,
5290
7376
  * 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
7377
+ * `vitehub inspect definitions` reads the same Definitions from source, and `vitehub schedule runs list <name>` lists the runs
5292
7378
  * that a runtime recorded.
5293
7379
  */
5294
7380
  const scheduleConsoleSection = {
@@ -5396,10 +7482,6 @@ const databaseVitePluginName = "@vite-hub/database/vite";
5396
7482
  function hasVitePlugin(plugins, name) {
5397
7483
  return (plugins ?? []).some((plugin) => Array.isArray(plugin) ? hasVitePlugin(plugin, name) : isRecord(plugin) && plugin.name === name);
5398
7484
  }
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
7485
  function resolveCronOverrides(value, definitions, options) {
5404
7486
  if (value === void 0) return;
5405
7487
  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 +7584,7 @@ function renderNitroSchedulePlugin(options) {
5502
7584
  ...options.inventoryRegistryFile ? [`import inventoryRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.inventoryRegistryFile))}`] : [],
5503
7585
  ...providerWake ? [`import scheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.providerRegistryFile))}`, `import { executeCloudflareStaticSchedules } from ${JSON.stringify(options.runtimeImport ?? scheduleStaticRuntimeModule)}`] : [],
5504
7586
  ...processRuntime ? [
5505
- `import { normalizeScheduleRuntimeError } from ${JSON.stringify(options.runtimeImport ?? scheduleStaticRuntimeModule)}`,
7587
+ `import { logScheduleRuntimeError, normalizeScheduleRuntimeError } from ${JSON.stringify(options.runtimeImport ?? scheduleStaticRuntimeModule)}`,
5506
7588
  `import { ${runStoreFactory} } from ${JSON.stringify(scheduleRuntimeModule)}`,
5507
7589
  `import { installProcessScheduleRuntime, onShutdown } from ${JSON.stringify(scheduleProcessRuntimeModule)}`,
5508
7590
  ...leaseDatabaseImport ? [`import { useLeases } from ${JSON.stringify(leaseDatabaseImport)}`] : [],
@@ -5530,7 +7612,8 @@ function renderNitroSchedulePlugin(options) {
5530
7612
  ` await executeCloudflareStaticSchedules(event, { ${[
5531
7613
  Object.keys(options.cronOverrides).length ? `cronOverrides: ${JSON.stringify(options.cronOverrides)}, ` : "",
5532
7614
  "registry: scheduleRegistry",
5533
- Object.keys(options.timeZoneCrons).length ? `, timeZoneCrons: ${JSON.stringify(options.timeZoneCrons)}` : ""
7615
+ Object.keys(options.timeZoneCrons).length ? `, timeZoneCrons: ${JSON.stringify(options.timeZoneCrons)}` : "",
7616
+ Object.keys(options.triggerCrons).length ? `, triggerCrons: ${JSON.stringify(options.triggerCrons)}` : ""
5534
7617
  ].join("")} })`,
5535
7618
  " })"
5536
7619
  ] : [],
@@ -5544,7 +7627,7 @@ function renderNitroSchedulePlugin(options) {
5544
7627
  " return",
5545
7628
  " }",
5546
7629
  " try {",
5547
- " console.error('[vitehub:schedule]', runtimeError)",
7630
+ " logScheduleRuntimeError(error, runtimeError)",
5548
7631
  " }",
5549
7632
  " catch {}",
5550
7633
  " try {",
@@ -5589,10 +7672,6 @@ function renderNitroSchedulePlugin(options) {
5589
7672
  ""
5590
7673
  ].join("\n");
5591
7674
  }
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
7675
  function renderNitroScheduleModule(options) {
5597
7676
  const { netlify } = options;
5598
7677
  let netlifyFunctionNames = /* @__PURE__ */ new Map();
@@ -5615,6 +7694,7 @@ function renderNitroScheduleModule(options) {
5615
7694
  const crons = Object.fromEntries(netlify.schedules.map((schedule) => [schedule.name, schedule.cron]));
5616
7695
  const timeZoneNames = netlify.schedules.filter((schedule) => schedule.inTimeZone).map((schedule) => schedule.name);
5617
7696
  const netlifyEntryRuntime = [
7697
+ "import { useNitroApp } from \"nitro/app\"",
5618
7698
  `import scheduleRegistry from ${JSON.stringify(netlify.registryFile)}`,
5619
7699
  `import { executeStaticSchedule, isTimeZoneWakeDue, missingScheduleDefinitionError, scheduledWakeTime, unwrapScheduleDefinition } from ${JSON.stringify(netlify.runtimeImport)}`,
5620
7700
  "",
@@ -5622,10 +7702,11 @@ function renderNitroScheduleModule(options) {
5622
7702
  `const timeZoneNames = new Set(${JSON.stringify(timeZoneNames)})`,
5623
7703
  "",
5624
7704
  "export async function runViteHubNetlifySchedule(name) {",
7705
+ " const scheduledAt = scheduledWakeTime(crons[name])",
7706
+ " await useNitroApp().ready",
5625
7707
  " const loader = scheduleRegistry[name]",
5626
7708
  " const definition = loader ? unwrapScheduleDefinition(await loader()) : undefined",
5627
7709
  " if (!definition) throw missingScheduleDefinitionError(name)",
5628
- " const scheduledAt = scheduledWakeTime(crons[name])",
5629
7710
  " if (timeZoneNames.has(name) && !isTimeZoneWakeDue(definition, name, scheduledAt)) return",
5630
7711
  " await executeStaticSchedule({ cron: crons[name], definition, name, scheduledAt })",
5631
7712
  "}",
@@ -5709,6 +7790,7 @@ async function writeNitroSchedulePlugin(root, options) {
5709
7790
  const inventoryRegistryFile = options.inventoryDefinitions.length ? resolve(root, generatedNitroInventoryRegistry) : void 0;
5710
7791
  const writes = [writeFileIfChanged(pluginFile, renderNitroSchedulePlugin({
5711
7792
  cronOverrides: options.cronOverrides,
7793
+ triggerCrons: options.triggerCrons,
5712
7794
  hostTimings: options.hostTimings,
5713
7795
  inventoryRegistryFile,
5714
7796
  timeZoneCrons: options.timeZoneCrons,
@@ -5762,6 +7844,24 @@ function selectNitroScheduleDefinitions(definitions, options) {
5762
7844
  if (options.providerOutput === "nitro") return definitions;
5763
7845
  return definitions.filter(isServerScheduleDefinition);
5764
7846
  }
7847
+ function selectHostCronDefinitions(definitions, options) {
7848
+ return resolveProcessRuntimeOptions(options.runtime) && options.providerOutput !== "nitro" ? [] : selectNitroScheduleDefinitions(definitions, options);
7849
+ }
7850
+ async function inspectScheduleResources(definitions, options, output) {
7851
+ const overrides = resolveCronOverrides(options.cron, definitions, options);
7852
+ const nitro = await readDefinitionCrons(output.nitro ? selectHostCronDefinitions(definitions, options) : [], overrides);
7853
+ const standalone = await readDefinitionCrons(output.standalone.filter((definition) => !nitro.has(definition.name)), overrides);
7854
+ const resource = (definition, cron, inStandalone) => ({
7855
+ definition,
7856
+ host: "cloudflare",
7857
+ kind: "cloudflare-cron",
7858
+ name: cronWithWeekdayNames(cron),
7859
+ 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.",
7860
+ owner: "schedule",
7861
+ ...inStandalone ? { standalone: true } : {}
7862
+ });
7863
+ return [...[...nitro].map(([definition, cron]) => resource(definition, cron, false)), ...[...standalone].map(([definition, cron]) => resource(definition, cron, true))];
7864
+ }
5765
7865
  function selectStandaloneProviderSource(definitions, options) {
5766
7866
  if (options.providerOutput === "auto" || options.providerOutput === void 0) return hasServerScheduleDefinitions(definitions) ? "vite-suffix" : void 0;
5767
7867
  }
@@ -5810,10 +7910,11 @@ async function createScheduleNitroConfig(options = {}) {
5810
7910
  if (vercelDefinitions.length) nitro = mergeNitroVercelCrons(nitro, vercelDefinitions, await readDefinitionCrons(vercelDefinitions, cronOverrides));
5811
7911
  if (!installNitroPlugin) return nitro;
5812
7912
  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);
7913
+ const nitroDefinitions = selectHostCronDefinitions(definitions, options);
5814
7914
  const nitroCrons = options.command === "build" ? await readDefinitionCrons(nitroDefinitions, cronOverrides) : /* @__PURE__ */ new Map();
5815
7915
  const timeZoneCrons = options.command === "build" ? readTimeZoneCrons(nitroDefinitions, cronOverrides) : {};
5816
- const crons = [...new Set(nitroCrons.values())];
7916
+ const triggerCrons = Object.fromEntries([...nitroCrons].map(([name, cron]) => [name, cronWithWeekdayNames(cron)]));
7917
+ const crons = [...new Set(Object.values(triggerCrons))];
5817
7918
  const netlifySchedules = [...nitroCrons].map(([name, cron]) => ({
5818
7919
  cron,
5819
7920
  ...Object.hasOwn(timeZoneCrons, name) ? { inTimeZone: true } : {},
@@ -5840,6 +7941,7 @@ async function createScheduleNitroConfig(options = {}) {
5840
7941
  });
5841
7942
  const plugin = await writeNitroSchedulePlugin(roots.projectRoot, {
5842
7943
  cronOverrides: Object.fromEntries(Object.entries(cronOverrides ?? {}).filter(([name]) => nitroDefinitionNames.has(name))),
7944
+ triggerCrons,
5843
7945
  hostTimings: Object.fromEntries(hostTimings),
5844
7946
  inventoryDefinitions,
5845
7947
  crons,
@@ -5876,10 +7978,14 @@ function hubSchedule(options = {}) {
5876
7978
  let viteRoot;
5877
7979
  let contributions = [];
5878
7980
  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
- });
7981
+ let leaseDatabase = false;
7982
+ const processStorageOptions = (hasPlugin) => {
7983
+ leaseDatabase = hasPlugin(databaseVitePluginName);
7984
+ return {
7985
+ ...leaseDatabase ? { leaseDatabaseImport: internalOptions.databaseImport ?? "@vite-hub/database" } : {},
7986
+ memoryProcessStores: internalOptions.requireKVPluginForProcessStores && !hasPlugin("@vite-hub/kv/vite")
7987
+ };
7988
+ };
5883
7989
  async function collectPluginScheduleContributions(plugins, roots) {
5884
7990
  return await collectScheduleContributions(plugins, {
5885
7991
  projectRoot: roots.projectRoot,
@@ -5921,7 +8027,7 @@ function hubSchedule(options = {}) {
5921
8027
  contributions,
5922
8028
  nitroOwnsPaths: hasNitroConfigContext(config),
5923
8029
  nitro: config.nitro,
5924
- ...processStorageOptions(config.plugins),
8030
+ ...processStorageOptions(typeof Reflect.get(config, "__vitehubNuxtHints") === "function" ? (name) => hasVitePlugin(config.plugins, name) : (name) => hasViteConfigPlugin(env, name)),
5925
8031
  preliminary: true,
5926
8032
  root: config.root || process.cwd(),
5927
8033
  serverDirs
@@ -5940,7 +8046,7 @@ function hubSchedule(options = {}) {
5940
8046
  const definitions = discoverRegistrySchedules();
5941
8047
  emitStandaloneProviderOutput = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options);
5942
8048
  standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
5943
- const storage = processStorageOptions(config.plugins);
8049
+ const storage = processStorageOptions((name) => hasVitePlugin(config.plugins, name));
5944
8050
  if (config.command) {
5945
8051
  const nitro = await createScheduleNitroConfig({
5946
8052
  ...options,
@@ -6097,7 +8203,10 @@ function hubSchedule(options = {}) {
6097
8203
  inspectable.vitehub = {
6098
8204
  durability: () => options.runtime?.driver === "process" ? [{
6099
8205
  export: "scheduleDurability",
6100
- input: { driver: "process" },
8206
+ input: {
8207
+ driver: "process",
8208
+ leases: leaseDatabase
8209
+ },
6101
8210
  module: durabilityModuleFile(import.meta.url),
6102
8211
  primitive: "schedule"
6103
8212
  }] : [],
@@ -6106,21 +8215,33 @@ function hubSchedule(options = {}) {
6106
8215
  load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).scheduleOperations,
6107
8216
  module: ownModule(import.meta.url, "operations")
6108
8217
  }],
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
8218
+ inspect: () => ({
8219
+ definitions: [{
8220
+ kind: "schedule",
8221
+ label: "Schedules",
8222
+ list: () => {
8223
+ const roots = resolveSchedulePluginRoots(viteRoot ?? process.cwd(), options);
8224
+ return inspectScheduleDefinitions({
8225
+ cron: options.cron,
8226
+ plugins: resolved?.plugins,
8227
+ projectRoot: roots.projectRoot,
8228
+ rootDir: roots.viteRoot,
8229
+ serverDirs,
8230
+ serverRootDir: roots.projectRoot
8231
+ });
8232
+ }
8233
+ }],
8234
+ resources: async () => {
8235
+ const host = nitroPreset ? resolveHost({ nitro: { preset: nitroPreset } }) : (resolved && getDeploymentHost(resolved)) ?? resolveHost({ nitro: Reflect.get(resolved ?? {}, "nitro") });
8236
+ const definitions = discoverRegistrySchedules();
8237
+ const standaloneHost = resolveHost({ nitro: nitroPreset ? { preset: nitroPreset } : Reflect.get(resolved ?? {}, "nitro") });
8238
+ const standalone = emitStandaloneProviderOutput && (standaloneHost === void 0 || standaloneHost === "cloudflare") ? definitions.filter((definition) => !standaloneProviderSource || definition.source === standaloneProviderSource) : [];
8239
+ return await inspectScheduleResources(definitions, options, {
8240
+ nitro: host === "cloudflare",
8241
+ standalone
6121
8242
  });
6122
8243
  }
6123
- }] })
8244
+ })
6124
8245
  };
6125
8246
  return inspectable;
6126
8247
  }