@vite-hub/schedule 0.3.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 (47) hide show
  1. package/README.md +24 -19
  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-BVMRQ93v.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-DSkCJC_L.js → error-diagnostics-C0KyI408.js} +10 -2
  9. package/dist/{error-diagnostics-Mpeks7J0.js → error-diagnostics-DTmP6baC.js} +5 -5
  10. package/dist/index.d.ts +19 -5
  11. package/dist/index.js +34 -6
  12. package/dist/{kv-storage-iJChCS5A.js → kv-storage-2kZtP2CC.js} +2 -2
  13. package/dist/{kv-storage-C0KZZB6v.d.ts → kv-storage-Bm9aYLfZ.d.ts} +5 -1
  14. package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-CI2PJGqu.d.ts} +13 -2
  15. package/dist/{operations-DwZWFIUX.js → operations-DlrK9mlH.js} +29 -9
  16. package/dist/operations.d.ts +10 -1
  17. package/dist/operations.js +13 -10
  18. package/dist/os.d.ts +0 -1
  19. package/dist/os.js +12 -84
  20. package/dist/out-BbXG-yVX.js +21755 -0
  21. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  22. package/dist/runtime/console.d.ts +1 -1
  23. package/dist/runtime/console.js +2 -2
  24. package/dist/runtime/kv.d.ts +1 -1
  25. package/dist/runtime/kv.js +1 -1
  26. package/dist/runtime/process.js +24 -45
  27. package/dist/runtime/state.d.ts +2 -2
  28. package/dist/runtime/state.js +2 -2
  29. package/dist/runtime/static.d.ts +2 -73
  30. package/dist/runtime/static.js +3 -2
  31. package/dist/runtime.d.ts +4 -4
  32. package/dist/runtime.js +5 -5
  33. package/dist/{started-Bx7MDbrl.js → started-BWWr7Ufw.js} +3 -4
  34. package/dist/{started-BuGmnus4.js → started-BXdWMdji.js} +24 -6
  35. package/dist/{started-errors-p7cu_rI7.js → started-errors-BMg04lL3.js} +73 -26
  36. package/dist/started-name-DudQ0fsR.js +5 -0
  37. package/dist/{state-B-Fuyfb4.js → state-BjWnxyhv.js} +79 -118
  38. package/dist/{state-Do2wV4Tx.d.ts → state-CJKAhskJ.d.ts} +12 -2
  39. package/dist/static-BgoOCoe5.js +610 -0
  40. package/dist/static-CcBWx1kU.d.ts +96 -0
  41. package/dist/{store-Df0-fzCl.d.ts → store-CZHZfttA.d.ts} +3 -7
  42. package/dist/vite.d.ts +5 -3
  43. package/dist/vite.js +2963 -590
  44. package/package.json +6 -6
  45. package/dist/invariant-DolT9EEx.js +0 -22
  46. package/dist/static-DQwzzvPg.js +0 -266
  47. package/dist/wait-until-Dy4Bn3ZN.js +0 -112
package/dist/vite.js CHANGED
@@ -1,18 +1,21 @@
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-Mpeks7J0.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";
4
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";
5
- import { t as internalErrorDiagnostics } from "./error-diagnostics-DSkCJC_L.js";
6
- import { n as invariantError, t as invariant } from "./invariant-DolT9EEx.js";
7
- import { r as timeZoneOffsetMinutes } from "./due-BVMRQ93v.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
- import { builtinModules, createRequire } from "node:module";
11
+ import { builtinModules, createRequire, isBuiltin } from "node:module";
12
+ import { formatDiagnostic } from "nostics";
10
13
  import { parseCronExpression } from "cron-schedule";
11
14
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
12
15
  import { tmpdir } from "node:os";
13
16
  import { basename, dirname, extname, isAbsolute, join, normalize, parse, relative, resolve, sep } from "node:path";
14
17
  import { fileURLToPath, pathToFileURL } from "node:url";
15
- 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";
16
19
  import { createHash, randomUUID } from "node:crypto";
17
20
  import { isDeepStrictEqual } from "node:util";
18
21
  import { parseSync } from "vite";
@@ -39,6 +42,9 @@ const projectRootFileMarkers = [
39
42
  ["nuxt.config.js"],
40
43
  ["nuxt.config.mjs"]
41
44
  ];
45
+ function hasViteConfigPlugin(env, name) {
46
+ return Reflect.get(env, Symbol.for(`vitehub.config-plugin:${name}`)) === true;
47
+ }
42
48
  function createNoExternalMerger(packageName) {
43
49
  return (current) => {
44
50
  if (current === true) return true;
@@ -74,6 +80,14 @@ function createProviderOutputEnvironmentOwner(name) {
74
80
  }
75
81
  };
76
82
  }
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
+ }
77
91
  function includesNitroVitePlugin(value) {
78
92
  if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
79
93
  if (!value || typeof value !== "object") return false;
@@ -112,7 +126,7 @@ function hasProjectRootDirectoryMarker(root) {
112
126
  for (const marker of projectRootDirectoryMarkers) try {
113
127
  if (statSync(resolve(root, ...marker)).isDirectory()) return true;
114
128
  } catch (error) {
115
- if (error.code !== "ENOENT") throw error;
129
+ if (!isMissingProjectMarker(error)) throw error;
116
130
  }
117
131
  return false;
118
132
  }
@@ -126,11 +140,15 @@ function hasProjectRootFileMarker(root, markers) {
126
140
  try {
127
141
  if (statSync(resolve(root, ...path)).isFile()) return true;
128
142
  } catch (error) {
129
- if (error.code !== "ENOENT") throw error;
143
+ if (!isMissingProjectMarker(error)) throw error;
130
144
  }
131
145
  }
132
146
  return false;
133
147
  }
148
+ function isMissingProjectMarker(error) {
149
+ const code = error.code;
150
+ return code === "ENOENT" || code === "ENOTDIR";
151
+ }
134
152
  //#endregion
135
153
  //#region ../internal/src/build/paths.ts
136
154
  function generatedDirSegments(productName) {
@@ -404,20 +422,76 @@ function resolveViteHubBundleDefines(config) {
404
422
  return defines;
405
423
  }
406
424
  //#endregion
407
- //#region ../internal/src/build/esbuild.ts
408
- const viteRawNamespace = "vitehub-vite-raw";
409
- const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
425
+ //#region ../internal/src/build/ast-walk.ts
426
+ /** The oxc parser grammar for a file, from its extension. Defaults to TypeScript. */
427
+ function moduleLanguage(file) {
428
+ if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
429
+ if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
430
+ if (/\.(?:c|m)?js$/i.test(file)) return "js";
431
+ return "ts";
432
+ }
433
+ function isNode(value) {
434
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
435
+ }
436
+ /** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
437
+ function walk(node, visit, parent) {
438
+ if (visit(node, parent) === false) return;
439
+ const fields = node;
440
+ for (const key in fields) {
441
+ const child = fields[key];
442
+ if (typeof child !== "object" || child === null || key === "parent") continue;
443
+ if (Array.isArray(child)) {
444
+ for (const item of child) if (isNode(item)) walk(item, visit, node);
445
+ } else if (isNode(child)) walk(child, visit, node);
446
+ }
447
+ }
448
+ //#endregion
449
+ //#region ../internal/src/build/rolldown.ts
450
+ const viteRawPrefix = "\0vitehub-vite-raw:";
451
+ const markdownTemplatePrefix = "\0vitehub-markdown-template:";
410
452
  const markdownTemplateFileSuffix = ".template.md";
411
453
  const markdownTemplateModuleQuery = "markdown-template";
412
454
  const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
413
455
  const skipResolvedAlias = "vitehubSkipResolvedAlias";
456
+ const resolvingViteAlias = "vitehubResolvingAlias";
414
457
  const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
458
+ /**
459
+ * Vite 8 bundles with Rolldown, so the app already has it. Load the copy next to `vite`, or `vite/rolldown` with
460
+ * Vite+, instead of installing a second bundler.
461
+ */
462
+ async function importRolldown() {
463
+ let entry;
464
+ try {
465
+ entry = createRequire(import.meta.resolve("vite")).resolve("rolldown");
466
+ } catch (error) {
467
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "MODULE_NOT_FOUND") throw error;
468
+ entry = createRequire(import.meta.url).resolve("vite/rolldown");
469
+ }
470
+ return await import(pathToFileURL(entry).href);
471
+ }
415
472
  function normalizePathSeparators(path) {
416
473
  return path.replaceAll("\\", "/");
417
474
  }
418
475
  function escapeRegExp$1(value) {
419
476
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
420
477
  }
478
+ function isRelativeSpecifier(path) {
479
+ return /^\.\.?[\\/]/.test(path);
480
+ }
481
+ function isBareSpecifier(id) {
482
+ return !/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/]|\0|#|[a-z][a-z0-9+.-]*:)/i.test(id);
483
+ }
484
+ /** The folder that a relative import of `importer` resolves from, as esbuild's `resolveDir`. */
485
+ function importerDir(importer, workingDir) {
486
+ return importer && isAbsolute(importer) ? dirname(importer) : workingDir;
487
+ }
488
+ /** Rolldown resolves a specifier from an importer file. A bundle entry has none, so use a file in the working folder. */
489
+ function importerFor(importer, workingDir) {
490
+ return importer ?? join(workingDir, "__vitehub_entry__.js");
491
+ }
492
+ function isFileResolution(resolved) {
493
+ return Boolean(resolved && !resolved.external && isAbsolute(resolved.id) && !resolved.id.startsWith("\0"));
494
+ }
421
495
  function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
422
496
  if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
423
497
  if (!Array.isArray(exportsValue) && !isRecord$1(exportsValue)) return [];
@@ -444,7 +518,23 @@ function collectPackageExportCandidates(packageName, exportsValue, packageRelati
444
518
  }
445
519
  return candidates;
446
520
  }
447
- function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackageAliases = true) {
521
+ /**
522
+ * Resolves `specifier` from a resolveId hook without running that hook again. `flag` in `custom` also skips the hook in
523
+ * resolutions that other plugins start from this one. `skipSelf` is still needed: when two equal resolutions run at the
524
+ * same time, Rolldown 1.2 can give one of them no `custom`, and the hook would then wait on its own resolution.
525
+ */
526
+ function resolveFrom(context, specifier, request, workingDir, flag) {
527
+ return context.resolve(specifier, importerFor(request.importer, workingDir), {
528
+ custom: {
529
+ ...request.custom,
530
+ [flag]: true
531
+ },
532
+ isEntry: request.isEntry,
533
+ kind: request.kind,
534
+ skipSelf: true
535
+ });
536
+ }
537
+ function createResolvedAliasPlugin(aliases, aliasResolveDir, workingDir, resolveEntryPackageAliases = true) {
448
538
  const entries = Object.entries(aliases || {});
449
539
  if (!entries.length) return;
450
540
  const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
@@ -464,186 +554,175 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackage
464
554
  specifier: `${resolvedSpecifier}${prefix && !resolvedSpecifier.endsWith("/") ? "/" : ""}`
465
555
  };
466
556
  }));
557
+ const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
467
558
  return {
468
559
  name: "vitehub-resolved-alias",
469
- setup(build) {
470
- const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
471
- build.onResolve({ filter: /.*/ }, async (args) => {
472
- if (args.pluginData?.[skipResolvedAlias]) return;
473
- const resolveWithContext = (specifier) => build.resolve(specifier, {
474
- importer: args.importer,
475
- kind: args.kind,
476
- namespace: args.namespace,
477
- pluginData: {
478
- ...args.pluginData,
479
- [skipResolvedAlias]: true
480
- },
481
- resolveDir: args.resolveDir,
482
- with: args.with
483
- });
484
- const aliases = await resolvedEntries;
485
- let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
486
- let matchedAlias = match?.specifier;
487
- let matchedSpecifier = match ? args.path : void 0;
488
- let specifier = args.resolveDir && /^\.\.?[\\/]/.test(args.path) ? resolve(args.resolveDir, args.path) : args.path;
489
- let normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
490
- let canonicalSpecifier = normalizedSpecifier;
491
- const canonicalizeSpecifier = async () => {
492
- canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
493
- return canonicalSpecifier;
494
- };
495
- match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
496
- if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
497
- await canonicalizeSpecifier();
498
- match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
499
- }
500
- if (!match && (resolveEntryPackageAliases || args.kind !== "entry-point") && isAbsolute(args.path)) {
501
- const candidates = [];
502
- for (const alias of aliases) {
503
- if (isAbsolute(alias.specifier)) continue;
504
- const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
505
- const aliasSegments = packageAlias.split("/");
506
- if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
507
- let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
508
- if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
509
- const scopeMarker = `/node_modules/${packageAlias}/`;
510
- const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
511
- const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
512
- if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
513
- }
514
- const packageMarker = `/node_modules/${packageName}/`;
515
- const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
516
- const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
517
- const cacheKey = [
518
- alias.specifier,
519
- alias.prefix,
520
- resolutionScope,
521
- normalizedSpecifier,
522
- args.importer,
523
- args.resolveDir,
524
- args.kind,
525
- args.namespace,
526
- JSON.stringify(args.with)
527
- ].join("\0");
528
- let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
529
- if (!resolution) {
530
- resolution = (async () => {
531
- let resolvedAliasPath;
532
- if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
533
- else if (resolutionScope) {
534
- const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
535
- const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
536
- if (!isRecord$1(parsedPackageJson)) return;
537
- const packageJson = parsedPackageJson;
538
- if (packageJson.exports === void 0 && !alias.prefix) {
539
- const resolvedCandidate = await resolveWithContext(alias.specifier);
540
- if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
541
- canonical: alias.specifier,
542
- normalized: alias.specifier,
543
- publicSpecifier: alias.specifier
544
- };
545
- return;
546
- }
547
- const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
548
- for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
549
- const resolvedCandidate = await resolveWithContext(publicSpecifier);
550
- if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
551
- if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
552
- matchingPublicSpecifiers.add(publicSpecifier);
553
- }
554
- if (matchingPublicSpecifiers.size === 1) {
555
- const publicSpecifier = [...matchingPublicSpecifiers][0];
556
- if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
557
- canonical: publicSpecifier,
558
- normalized: publicSpecifier,
559
- publicSpecifier
560
- };
561
- }
560
+ async resolveId(source, importer, extra) {
561
+ if (extra.custom?.[skipResolvedAlias]) return;
562
+ const request = {
563
+ custom: extra.custom,
564
+ importer,
565
+ isEntry: extra.isEntry,
566
+ kind: extra.kind
567
+ };
568
+ const resolveWithContext = (specifier) => resolveFrom(this, specifier, request, workingDir, skipResolvedAlias);
569
+ const resolveDir = importerDir(importer, workingDir);
570
+ const aliases = await resolvedEntries;
571
+ let match = aliases.find(({ prefix, specifier }) => isRelativeSpecifier(specifier) && (prefix ? source.startsWith(specifier) : source === specifier));
572
+ let matchedAlias = match?.specifier;
573
+ let matchedSpecifier = match ? source : void 0;
574
+ const specifier = isRelativeSpecifier(source) ? resolve(resolveDir, source) : source;
575
+ const normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
576
+ let canonicalSpecifier = normalizedSpecifier;
577
+ const canonicalizeSpecifier = async () => {
578
+ canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
579
+ return canonicalSpecifier;
580
+ };
581
+ match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
582
+ if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
583
+ await canonicalizeSpecifier();
584
+ match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
585
+ }
586
+ if (!match && (resolveEntryPackageAliases || !extra.isEntry) && isAbsolute(source)) {
587
+ const candidates = [];
588
+ for (const alias of aliases) {
589
+ if (isAbsolute(alias.specifier) || alias.prefix && alias.specifier.startsWith("#")) continue;
590
+ const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
591
+ const aliasSegments = packageAlias.split("/");
592
+ if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
593
+ let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
594
+ if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
595
+ const scopeMarker = `/node_modules/${packageAlias}/`;
596
+ const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
597
+ const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
598
+ if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
599
+ }
600
+ const packageMarker = `/node_modules/${packageName}/`;
601
+ const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
602
+ if (alias.prefix && packageMarkerIndex === -1 && !isRelativeSpecifier(alias.specifier)) continue;
603
+ const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
604
+ const cacheKey = [
605
+ alias.specifier,
606
+ alias.prefix,
607
+ resolutionScope,
608
+ normalizedSpecifier,
609
+ importer,
610
+ extra.kind,
611
+ extra.isEntry
612
+ ].join("\0");
613
+ const cacheable = !extra.custom || !Object.keys(extra.custom).length;
614
+ let resolution = cacheable ? resolvedBareAliasPaths.get(cacheKey) : void 0;
615
+ if (!resolution) {
616
+ resolution = (async () => {
617
+ let resolvedAliasPath;
618
+ if (alias.prefix && isRelativeSpecifier(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
619
+ else if (resolutionScope) {
620
+ const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
621
+ const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
622
+ if (!isRecord$1(parsedPackageJson)) return;
623
+ const packageJson = parsedPackageJson;
624
+ if (packageJson.exports === void 0 && !alias.prefix) {
625
+ const resolvedCandidate = await resolveWithContext(alias.specifier);
626
+ if (isFileResolution(resolvedCandidate) && normalizePathSeparators(resolve(resolvedCandidate.id)) === normalizedSpecifier) return {
627
+ canonical: alias.specifier,
628
+ normalized: alias.specifier,
629
+ publicSpecifier: alias.specifier
630
+ };
562
631
  return;
563
- } else {
564
- const resolvedAlias = await resolveWithContext(alias.specifier);
565
- if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
566
- resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
567
632
  }
568
- const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
569
- return {
570
- canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
571
- normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
572
- };
573
- })();
574
- if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
575
- }
576
- candidates.push({
577
- alias,
578
- resolution
579
- });
633
+ const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
634
+ for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
635
+ const resolvedCandidate = await resolveWithContext(publicSpecifier);
636
+ if (!isFileResolution(resolvedCandidate)) continue;
637
+ if (normalizePathSeparators(resolve(resolvedCandidate.id)) !== normalizedSpecifier) continue;
638
+ matchingPublicSpecifiers.add(publicSpecifier);
639
+ }
640
+ if (matchingPublicSpecifiers.size === 1) {
641
+ const publicSpecifier = [...matchingPublicSpecifiers][0];
642
+ if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
643
+ canonical: publicSpecifier,
644
+ normalized: publicSpecifier,
645
+ publicSpecifier
646
+ };
647
+ }
648
+ return;
649
+ } else {
650
+ const resolvedAlias = await resolveWithContext(alias.specifier);
651
+ if (!isFileResolution(resolvedAlias)) return;
652
+ resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.id));
653
+ }
654
+ const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
655
+ return {
656
+ canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
657
+ normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
658
+ };
659
+ })();
660
+ if (cacheable) resolvedBareAliasPaths.set(cacheKey, resolution);
580
661
  }
581
- await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
582
- for (const { alias, resolution } of candidates) {
583
- const paths = await resolution;
584
- if (!paths) continue;
585
- if (paths.publicSpecifier) {
586
- match = alias;
587
- matchedAlias = alias.specifier;
588
- matchedSpecifier = paths.publicSpecifier;
589
- break;
590
- }
591
- const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
592
- let canonicalMatch = false;
593
- if (!normalizedMatch && paths.canonical !== paths.normalized) {
594
- await canonicalizeSpecifier();
595
- canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
596
- }
597
- if (normalizedMatch || canonicalMatch) {
598
- match = alias;
599
- matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
600
- matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
601
- break;
602
- }
662
+ candidates.push({
663
+ alias,
664
+ resolution
665
+ });
666
+ }
667
+ await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
668
+ for (const { alias, resolution } of candidates) {
669
+ const paths = await resolution;
670
+ if (!paths) continue;
671
+ if (paths.publicSpecifier) {
672
+ match = alias;
673
+ matchedAlias = alias.specifier;
674
+ matchedSpecifier = paths.publicSpecifier;
675
+ break;
676
+ }
677
+ const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
678
+ let canonicalMatch = false;
679
+ if (!normalizedMatch && paths.canonical !== paths.normalized) {
680
+ await canonicalizeSpecifier();
681
+ canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
682
+ }
683
+ if (normalizedMatch || canonicalMatch) {
684
+ match = alias;
685
+ matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
686
+ matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
687
+ break;
603
688
  }
604
689
  }
605
- matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
606
- matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
607
- if (!match) return;
608
- const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
609
- if (!target) return;
610
- return resolveWithContext(/^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target);
611
- });
690
+ }
691
+ matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
692
+ matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
693
+ if (!match) return;
694
+ const target = match.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match.replacement);
695
+ if (!target) return;
696
+ const resolvedTarget = isRelativeSpecifier(target) ? resolve(aliasResolveDir, target) : target;
697
+ const resolved = await resolveWithContext(resolvedTarget);
698
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(resolvedTarget)}, the alias of ${JSON.stringify(source)}.`);
699
+ return resolved;
612
700
  }
613
701
  };
614
702
  }
615
- function createViteAliasPlugin(aliases) {
703
+ function createViteAliasPlugin(aliases, workingDir) {
616
704
  if (!Array.isArray(aliases)) return;
617
- const resolvingAlias = "vitehubResolvingAlias";
618
705
  return {
619
706
  name: "vitehub-vite-alias",
620
- setup(build) {
621
- build.onResolve({ filter: /.*/ }, async (args) => {
622
- if (args.pluginData?.[resolvingAlias]) return;
623
- const alias = aliases.find(({ find }) => {
624
- if (typeof find === "string") return args.path === find || args.path.startsWith(`${find}/`);
625
- find.lastIndex = 0;
626
- return find.test(args.path);
627
- });
628
- if (!alias) return;
629
- if (alias.customResolver) return { errors: [{ text: `[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(args.path)} because it uses customResolver.` }] };
630
- if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
631
- const replacement = typeof alias.find === "string" ? `${alias.replacement}${args.path.slice(alias.find.length)}` : args.path.replace(alias.find, alias.replacement);
632
- const result = await build.resolve(replacement, {
633
- importer: args.importer,
634
- kind: args.kind,
635
- namespace: args.namespace,
636
- pluginData: Object.assign({}, args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {}, { [resolvingAlias]: true }),
637
- resolveDir: args.resolveDir,
638
- with: args.with
639
- });
640
- const pluginData = Object.assign({}, result.pluginData);
641
- Reflect.deleteProperty(pluginData, resolvingAlias);
642
- return {
643
- ...result,
644
- pluginData
645
- };
707
+ async resolveId(source, importer, extra) {
708
+ if (extra.custom?.[resolvingViteAlias]) return;
709
+ const alias = aliases.find(({ find }) => {
710
+ if (typeof find === "string") return source === find || source.startsWith(`${find}/`);
711
+ find.lastIndex = 0;
712
+ return find.test(source);
646
713
  });
714
+ if (!alias) return;
715
+ if (alias.customResolver) this.error(`[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(source)} because it uses customResolver.`);
716
+ if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
717
+ const replacement = typeof alias.find === "string" ? `${alias.replacement}${source.slice(alias.find.length)}` : source.replace(alias.find, alias.replacement);
718
+ const resolved = await resolveFrom(this, replacement, {
719
+ custom: extra.custom,
720
+ importer,
721
+ isEntry: extra.isEntry,
722
+ kind: extra.kind
723
+ }, workingDir, resolvingViteAlias);
724
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(replacement)}, the alias of ${JSON.stringify(source)}.`);
725
+ return resolved;
647
726
  }
648
727
  };
649
728
  }
@@ -682,173 +761,2023 @@ async function resolveViteRawSpecifier(path, rootDir) {
682
761
  return resolve(rootDir, rootRelativePath);
683
762
  }
684
763
  }
685
- function createViteRawPlugin(rootDir, frameworkRuntime) {
764
+ function createViteRawPlugin(rootDir, frameworkRuntime, workingDir) {
686
765
  return {
687
766
  name: "vitehub-vite-raw",
688
- setup(build) {
689
- build.onResolve({
690
- filter: /^@vite-hub\/markdown-template$/,
691
- namespace: viteMarkdownTemplateNamespace
692
- }, async (args) => {
693
- if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
694
- return build.resolve("vite-hub/markdown-template", {
695
- importer: args.importer,
696
- kind: args.kind,
697
- resolveDir: args.resolveDir
767
+ async resolveId(source, importer, extra) {
768
+ if (source === markdownTemplateRuntimeSpecifier && importer?.startsWith(markdownTemplatePrefix)) {
769
+ if (!frameworkRuntime) return fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier));
770
+ return await this.resolve("vite-hub/markdown-template", importer.slice(27), {
771
+ custom: extra.custom,
772
+ kind: extra.kind
698
773
  });
774
+ }
775
+ if (extra.custom?.[skipMarkdownTemplateResolve]) return;
776
+ const markdownTemplate = parseMarkdownTemplateRequest(source);
777
+ const raw = hasViteRawQuery(source);
778
+ if (!markdownTemplate && !raw) return;
779
+ const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? source.slice(0, source.indexOf("?")), rootDir);
780
+ const resolved = await resolveFrom(this, specifier, {
781
+ custom: extra.custom,
782
+ importer,
783
+ isEntry: extra.isEntry,
784
+ kind: extra.kind
785
+ }, workingDir, skipMarkdownTemplateResolve);
786
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(specifier)}, imported as ${JSON.stringify(source)}.`);
787
+ if (resolved.external) return {
788
+ id: resolved.id,
789
+ external: resolved.external
790
+ };
791
+ const resolvedId = resolved.id;
792
+ if (!isFileResolution(resolved)) this.error(markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(source)} from the virtual module ${JSON.stringify(resolvedId)}. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(source)} from the virtual module ${JSON.stringify(resolvedId)}. Handle this raw import in a caller plugin.`);
793
+ return `${markdownTemplate ? markdownTemplatePrefix : viteRawPrefix}${resolvedId}`;
794
+ },
795
+ async load(id) {
796
+ if (id.startsWith(viteRawPrefix)) return {
797
+ code: await readFile(id.slice(18), "utf8"),
798
+ moduleType: "text"
799
+ };
800
+ if (id.startsWith(markdownTemplatePrefix)) return {
801
+ code: renderMarkdownTemplateModule(await readFile(id.slice(27), "utf8")),
802
+ moduleType: "js"
803
+ };
804
+ }
805
+ };
806
+ }
807
+ function createFileUrlPlugin() {
808
+ return {
809
+ name: "vitehub-file-url",
810
+ resolveId(source) {
811
+ if (source.startsWith("file:")) return fileURLToPath(source);
812
+ }
813
+ };
814
+ }
815
+ /**
816
+ * Copies a `.wasm?module` import next to the bundle and keeps it as a relative `.wasm` import. Wrangler and Nitro load
817
+ * such an import as a compiled WebAssembly module, which Workers need because they can't compile WebAssembly bytes.
818
+ * Node.js compiles WebAssembly bytes, so there the import becomes the bytes of the file.
819
+ */
820
+ function createWasmModulePlugin(outdir, workingDir, copy) {
821
+ return {
822
+ name: "vitehub-wasm-module",
823
+ async resolveId(source, importer, extra) {
824
+ if (!source.endsWith(".wasm?module")) return;
825
+ const resolved = await this.resolve(source.slice(0, -7), importerFor(importer, workingDir), {
826
+ custom: extra.custom,
827
+ kind: extra.kind
699
828
  });
700
- build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
701
- if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
702
- const markdownTemplate = parseMarkdownTemplateRequest(args.path);
703
- const raw = hasViteRawQuery(args.path);
704
- if (!markdownTemplate && !raw) return;
705
- const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
706
- let pluginData = args.pluginData;
707
- if (markdownTemplate) pluginData = {
708
- ...args.pluginData,
709
- [skipMarkdownTemplateResolve]: true
710
- };
711
- const resolved = await build.resolve(specifier, {
712
- importer: args.importer,
713
- kind: args.kind,
714
- namespace: args.namespace,
715
- pluginData,
716
- resolveDir: args.resolveDir,
717
- with: args.with
829
+ if (!isFileResolution(resolved)) this.error(`[vitehub] Could not resolve ${JSON.stringify(source)}.`);
830
+ if (!copy) return resolved.id;
831
+ const bytes = await readFile(resolved.id);
832
+ const name = `${basename(resolved.id, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
833
+ await mkdir(outdir, { recursive: true });
834
+ await copyFile(resolved.id, join(outdir, name));
835
+ return {
836
+ id: `./${name}`,
837
+ external: true
838
+ };
839
+ }
840
+ };
841
+ }
842
+ /**
843
+ * Leaves package imports external. Resolve package.json import mappings first, and preserve unmapped host imports.
844
+ */
845
+ function createExternalPackagesPlugin() {
846
+ return {
847
+ name: "vitehub-external-packages",
848
+ async resolveId(source, importer, extra) {
849
+ if (source.startsWith("npm:") || source.startsWith("jsr:")) return {
850
+ id: source,
851
+ external: true
852
+ };
853
+ if (source.startsWith("#")) return await this.resolve(source, importer, {
854
+ custom: extra.custom,
855
+ kind: extra.kind
856
+ }) ?? {
857
+ id: source,
858
+ external: true
859
+ };
860
+ if (isBareSpecifier(source) && !isBuiltin(source)) return {
861
+ id: source,
862
+ external: true
863
+ };
864
+ }
865
+ };
866
+ }
867
+ function hasImportRejectionHandler(importNode, parents) {
868
+ let expression = importNode;
869
+ let parent = parents.get(expression);
870
+ while (parent?.type === "MemberExpression" && parent.object === expression) {
871
+ const call = parents.get(parent);
872
+ if (call?.type !== "CallExpression" || call.callee !== parent) break;
873
+ const method = parent.property.type === "Identifier" && !parent.computed ? parent.property.name : parent.property.type === "Literal" ? parent.property.value : void 0;
874
+ const handler = call.arguments[method === "then" ? 1 : 0];
875
+ if ((method === "then" || method === "catch") && handler && handler.type !== "SpreadElement") {
876
+ if (handler.type !== "Literal" && !(handler.type === "Identifier" && handler.name === "undefined")) return true;
877
+ }
878
+ if (method !== "then" && method !== "finally") break;
879
+ expression = call;
880
+ parent = parents.get(expression);
881
+ }
882
+ if (parent?.type !== "AwaitExpression") return false;
883
+ for (let child = parent, ancestor = parents.get(child); ancestor; ancestor = parents.get(child)) {
884
+ if (ancestor.type === "TryStatement" && ancestor.block === child && ancestor.handler) return true;
885
+ if (ancestor.type === "ArrowFunctionExpression" || ancestor.type === "FunctionExpression" || ancestor.type === "FunctionDeclaration") break;
886
+ child = ancestor;
887
+ }
888
+ return false;
889
+ }
890
+ function createOptionalImportPlugin() {
891
+ const prefix = "\0vitehub-optional-import:";
892
+ return {
893
+ name: "vitehub-optional-import",
894
+ resolveId(source) {
895
+ if (source.startsWith(prefix)) return {
896
+ id: source.slice(25),
897
+ external: "absolute"
898
+ };
899
+ },
900
+ transform: {
901
+ order: "post",
902
+ filter: { code: /\bimport\s*(?:\(|\/)/ },
903
+ async handler(code, id) {
904
+ const { parseSync } = await import("vite");
905
+ const module = parseSync(id, code, {
906
+ lang: moduleLanguage(id),
907
+ preserveParens: false,
908
+ sourceType: "module"
718
909
  });
719
- if (resolved.errors.length) return {
720
- errors: resolved.errors,
721
- warnings: resolved.warnings
722
- };
723
- if (resolved.external) return {
724
- external: true,
725
- namespace: resolved.namespace,
726
- path: resolved.path,
727
- pluginData: resolved.pluginData,
728
- sideEffects: resolved.sideEffects,
729
- suffix: resolved.suffix,
730
- warnings: resolved.warnings
731
- };
732
- if (resolved.namespace !== "file") return {
733
- errors: [{ text: markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this raw import in a caller plugin.` }],
734
- warnings: resolved.warnings
735
- };
736
- return {
737
- namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
738
- path: resolved.path,
739
- pluginData: resolved.pluginData,
740
- sideEffects: resolved.sideEffects,
741
- suffix: resolved.suffix,
742
- warnings: resolved.warnings
743
- };
910
+ if (module.errors.length) return;
911
+ const parents = /* @__PURE__ */ new WeakMap();
912
+ const handled = [];
913
+ walk(module.program, (node, parent) => {
914
+ if (parent) parents.set(node, parent);
915
+ if (node.type !== "ImportExpression" || node.source.type !== "Literal" || typeof node.source.value !== "string") return;
916
+ if (hasImportRejectionHandler(node, parents)) handled.push({
917
+ source: node.source.value,
918
+ start: node.source.start,
919
+ end: node.source.end
920
+ });
921
+ });
922
+ if (!handled.length) return;
923
+ const resolved = await Promise.all(handled.map(({ source }) => this.resolve(source, id, { kind: "dynamic-import" })));
924
+ for (const [index, { source, start, end }] of [...handled.entries()].reverse()) if (!resolved[index]) code = code.slice(0, start) + JSON.stringify(prefix + source) + code.slice(end);
925
+ return code;
926
+ }
927
+ }
928
+ };
929
+ }
930
+ /** Matches import paths as esbuild's `external` does: `*` is a wildcard, and a package name also matches its subpaths. */
931
+ function createExternalMatcher(patterns) {
932
+ if (!patterns?.length) return;
933
+ const matchers = patterns.map((pattern) => {
934
+ if (pattern.includes("*")) {
935
+ const expression = new RegExp(`^${pattern.split("*").map(escapeRegExp$1).join(".*")}$`);
936
+ return (id) => expression.test(id);
937
+ }
938
+ return isBareSpecifier(pattern) ? (id) => id === pattern || id.startsWith(`${pattern}/`) : (id) => id === pattern;
939
+ });
940
+ return (id) => matchers.some((matches) => matches(id));
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
+ }
960
+ async function bundleEsmEntry(entryFile, outfile, options = {}) {
961
+ const { rolldown } = await importRolldown();
962
+ options.signal?.throwIfAborted();
963
+ const format = options.format || "esm";
964
+ const platform = options.platform || "neutral";
965
+ const workingDir = options.workingDir ?? process.cwd();
966
+ const frameworkRuntime = (Array.isArray(options.alias) ? options.alias.flatMap((alias) => typeof alias.find === "string" ? [alias.find] : []) : Object.keys(options.alias || {})).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
967
+ const plugins = [];
968
+ plugins.push(createWasmModulePlugin(dirname(outfile), workingDir, platform !== "node"));
969
+ const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), workingDir, options.resolveEntryPackageAliases);
970
+ if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
971
+ plugins.push(...options.plugins ?? [], createFileUrlPlugin());
972
+ const viteAliasPlugin = createViteAliasPlugin(options.alias, workingDir);
973
+ if (viteAliasPlugin) plugins.push(viteAliasPlugin);
974
+ plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime, workingDir));
975
+ if (options.packages === "external") plugins.push(createExternalPackagesPlugin());
976
+ plugins.push(createOptionalImportPlugin());
977
+ const isExternal = createExternalMatcher(options.external);
978
+ const minify = options.minifyIdentifiers || options.minifySyntax || options.minifyWhitespace ? {
979
+ compress: options.minifySyntax ?? false,
980
+ mangle: options.minifyIdentifiers ? { toplevel: true } : false,
981
+ codegen: { removeWhitespace: options.minifyWhitespace ?? false }
982
+ } : false;
983
+ const banner = [options.banner, ...format === "esm" && platform === "node" ? [
984
+ "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
985
+ " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
986
+ " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
987
+ " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
988
+ "}"
989
+ ] : []].filter(Boolean).join("\n");
990
+ const build = (extraPlugins = [], shimMissingExports = false) => rolldown({
991
+ cwd: workingDir,
992
+ external: isExternal ? (id) => isExternal(id) : void 0,
993
+ input: entryFile,
994
+ onLog(level, log) {
995
+ if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
996
+ },
997
+ moduleTypes: platform === "node" ? { ".wasm": "binary" } : void 0,
998
+ platform,
999
+ plugins: [...extraPlugins, ...plugins],
1000
+ resolve: {
1001
+ conditionNames: options.conditions ?? (platform === "node" ? ["node"] : void 0),
1002
+ extensions: options.extensions,
1003
+ mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
1004
+ symlinks: !options.preserveSymlinks
1005
+ },
1006
+ shimMissingExports,
1007
+ transform: {
1008
+ define: options.define,
1009
+ target: "es2022"
1010
+ },
1011
+ tsconfig: options.tsconfig ?? true
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();
1024
+ let output;
1025
+ try {
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
+ }
1037
+ } finally {
1038
+ await bundle.close();
1039
+ }
1040
+ options.signal?.throwIfAborted();
1041
+ const chunk = output.find((file) => file.type === "chunk" && file.isEntry);
1042
+ await mkdir(dirname(outfile), { recursive: true });
1043
+ await writeFile(outfile, chunk.code, { signal: options.signal });
1044
+ options.signal?.throwIfAborted();
1045
+ }
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;
744
2526
  });
745
- build.onLoad({
746
- filter: /.*/,
747
- namespace: viteRawNamespace
748
- }, async (args) => ({
749
- contents: await readFile(args.path),
750
- loader: "text"
751
- }));
752
- build.onLoad({
753
- filter: /.*/,
754
- namespace: viteMarkdownTemplateNamespace
755
- }, async (args) => ({
756
- contents: renderMarkdownTemplateModule(await readFile(args.path, "utf8")),
757
- loader: "js",
758
- resolveDir: dirname(args.path)
759
- }));
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
+ }
760
2715
  }
761
2716
  };
762
- }
763
- function createFileUrlPlugin() {
2717
+ visit("", [], []);
764
2718
  return {
765
- name: "vitehub-file-url",
766
- setup(build) {
767
- build.onResolve({ filter: /^file:/ }, (args) => ({ path: fileURLToPath(args.path) }));
768
- }
2719
+ files,
2720
+ entries
769
2721
  };
770
2722
  }
771
- /**
772
- * Copies a `.wasm?module` import next to the bundle and keeps it as a relative `.wasm` import. Wrangler and Nitro load
773
- * such an import as a compiled WebAssembly module, which Workers need because they can't compile WebAssembly bytes.
774
- */
775
- function createWasmModulePlugin(outdir) {
776
- return {
777
- name: "vitehub-wasm-module",
778
- setup(build) {
779
- build.onResolve({ filter: /\.wasm\?module$/ }, async (args) => {
780
- const resolved = await build.resolve(args.path.slice(0, -7), {
781
- importer: args.importer,
782
- kind: args.kind,
783
- resolveDir: args.resolveDir
784
- });
785
- if (resolved.errors.length) return { errors: resolved.errors };
786
- const bytes = await readFile(resolved.path);
787
- const name = `${basename(resolved.path, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
788
- await mkdir(outdir, { recursive: true });
789
- await copyFile(resolved.path, join(outdir, name));
790
- return {
791
- external: true,
792
- path: `./${name}`
793
- };
794
- });
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;
795
2736
  }
796
- };
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));
797
2761
  }
798
- async function bundleEsmEntry(entryFile, outfile, options = {}) {
799
- const { build: bundle } = await import("esbuild");
800
- options.signal?.throwIfAborted();
801
- const format = options.format || "esm";
802
- const platform = options.platform || "neutral";
803
- const viteAliasPlugin = createViteAliasPlugin(options.alias);
804
- const frameworkRuntime = (Array.isArray(options.alias) ? options.alias.flatMap((alias) => typeof alias.find === "string" ? [alias.find] : []) : Object.keys(options.alias || {})).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
805
- const plugins = [];
806
- const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), options.resolveEntryPackageAliases);
807
- if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
808
- plugins.push(...options.plugins ?? [], createFileUrlPlugin());
809
- if (viteAliasPlugin) plugins.push(viteAliasPlugin);
810
- plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
811
- if (platform !== "node") plugins.unshift(createWasmModulePlugin(dirname(outfile)));
812
- const result = await bundle({
813
- absWorkingDir: options.workingDir,
814
- banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
815
- "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
816
- " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
817
- " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
818
- " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
819
- "}"
820
- ] : []].filter(Boolean).join("\n") } : void 0,
821
- bundle: true,
822
- conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
823
- define: options.define,
824
- entryPoints: [entryFile],
825
- external: options.external,
826
- format,
827
- keepNames: options.minifySyntax || options.minifyIdentifiers,
828
- loader: platform === "node" ? { ".wasm": "binary" } : void 0,
829
- logLevel: "silent",
830
- mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
831
- resolveExtensions: options.extensions,
832
- minifyIdentifiers: options.minifyIdentifiers,
833
- minifySyntax: options.minifySyntax,
834
- minifyWhitespace: options.minifyWhitespace,
835
- outfile,
836
- packages: options.packages,
837
- platform,
838
- preserveSymlinks: options.preserveSymlinks,
839
- plugins,
840
- sourcemap: false,
841
- target: "es2022",
842
- write: options.signal ? false : true
843
- });
844
- options.signal?.throwIfAborted();
845
- if (options.signal) {
846
- await Promise.all((result.outputFiles ?? []).map(async (output) => {
847
- await mkdir(dirname(output.path), { recursive: true });
848
- options.signal.throwIfAborted();
849
- await writeFile(output.path, output.contents, { signal: options.signal });
850
- }));
851
- options.signal.throwIfAborted();
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));
852
2781
  }
853
2782
  }
854
2783
  //#endregion
@@ -860,16 +2789,10 @@ async function bundleEsmEntry(entryFile, outfile, options = {}) {
860
2789
  */
861
2790
  /** The value of an expression that the scanner cannot read without running the module. */
862
2791
  const dynamic = Symbol("dynamic");
863
- function languageOf(file) {
864
- if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
865
- if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
866
- if (/\.(?:c|m)?js$/i.test(file)) return "js";
867
- return "ts";
868
- }
869
2792
  /** Parses a module once. `file` selects the grammar from its extension and defaults to TypeScript. */
870
2793
  function scanModule(source, file = "module.ts") {
871
2794
  const result = parseSync(file, source, {
872
- lang: languageOf(file),
2795
+ lang: moduleLanguage(file),
873
2796
  preserveParens: false,
874
2797
  sourceType: "module"
875
2798
  });
@@ -881,21 +2804,6 @@ function scanModule(source, file = "module.ts") {
881
2804
  source
882
2805
  };
883
2806
  }
884
- function isNode(value) {
885
- return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
886
- }
887
- /** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
888
- function walk(node, visit, parent) {
889
- if (visit(node, parent) === false) return;
890
- const fields = node;
891
- for (const key in fields) {
892
- const child = fields[key];
893
- if (typeof child !== "object" || child === null || key === "parent") continue;
894
- if (Array.isArray(child)) {
895
- for (const item of child) if (isNode(item)) walk(item, visit, node);
896
- } else if (isNode(child)) walk(child, visit, node);
897
- }
898
- }
899
2807
  /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
900
2808
  function unwrapExpression(node) {
901
2809
  while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
@@ -1345,18 +3253,21 @@ function dependencyRoots(root) {
1345
3253
  return [...new Set(roots)];
1346
3254
  }
1347
3255
  async function linkDependencies(source, target, resolveLinkTarget = (source) => source) {
3256
+ const entries = await unlessGone(() => readdir(source));
3257
+ if (!entries) return;
1348
3258
  await mkdir(target, { recursive: true });
1349
- for (const entry of await readdir(source, { withFileTypes: true })) {
1350
- if (entry.name === ".bin" || entry.name === ".pnpm") continue;
1351
- const sourceEntry = resolve(source, entry.name);
1352
- const targetEntry = resolve(target, entry.name);
1353
- if (!existsSync(sourceEntry)) continue;
1354
- const resolvedSourceEntry = realpathSync(sourceEntry);
1355
- if (!statSync(resolvedSourceEntry).isDirectory()) continue;
1356
- 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()) {
1357
3266
  await linkDependencies(sourceEntry, targetEntry, resolveLinkTarget);
1358
3267
  continue;
1359
3268
  }
3269
+ const resolvedSourceEntry = await unlessGone(() => realpath(sourceEntry));
3270
+ if (!resolvedSourceEntry || !(await unlessGone(() => stat(resolvedSourceEntry)))?.isDirectory()) continue;
1360
3271
  if (existsSync(targetEntry)) continue;
1361
3272
  await symlink(resolveLinkTarget(resolvedSourceEntry), targetEntry, process.platform === "win32" ? "junction" : "dir");
1362
3273
  }
@@ -1622,7 +3533,8 @@ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
1622
3533
  async function traceImportedSources(paths, root, configuredRoots) {
1623
3534
  const entries = paths.filter((path) => traceableSourceExtensions.has(extname(path)));
1624
3535
  if (!entries.length) return /* @__PURE__ */ new Set();
1625
- const { build } = await import("esbuild");
3536
+ const { rolldown } = await importRolldown();
3537
+ const resolvingTraceHint = "vitehubResolvingTraceHint";
1626
3538
  const physicalRoot = realpathSync(root);
1627
3539
  const traceBuildVariants = [
1628
3540
  { platform: "node" },
@@ -1680,113 +3592,99 @@ async function traceImportedSources(paths, root, configuredRoots) {
1680
3592
  const queriedResourceSources = /* @__PURE__ */ new Set();
1681
3593
  const importedSourceHints = /* @__PURE__ */ new Set();
1682
3594
  const results = [];
3595
+ const toRootSource = (path) => pathContains$1(root, path) ? path : pathContains$1(physicalRoot, path) ? resolve(root, relative(physicalRoot, path)) : void 0;
3596
+ const isProjectSource = (path) => Boolean(path && existsSync(path) && !relative(root, path).split(sep).includes("node_modules"));
1683
3597
  for (const variant of traceBuildVariants) {
1684
- const [result] = await Promise.allSettled([build({
1685
- absWorkingDir: root,
1686
- bundle: true,
1687
- entryPoints: tracedBatch,
1688
- format: "esm",
1689
- logLevel: "silent",
1690
- metafile: true,
1691
- outdir: resolve(root, ".vitehub-provider-trace"),
1692
- packages: "bundle",
1693
- ...variant,
1694
- plugins: [{
1695
- name: "vitehub-provider-vite-resource-query",
1696
- setup(traceBuild) {
1697
- const resolvingPackageImportHint = "vitehubResolvingPackageImportHint";
1698
- traceBuild.onResolve({ filter: /^\.\.?\// }, (request) => {
1699
- const source = request.resolveDir && resolve(request.resolveDir, request.path.split(/[?#]/, 1)[0]);
1700
- if (source && existsSync(source)) importedSourceHints.add(source);
1701
- });
1702
- traceBuild.onResolve({ filter: /^#/ }, async (request) => {
1703
- if (request.pluginData?.[resolvingPackageImportHint]) return void 0;
1704
- if (!request.importer) return void 0;
1705
- const suffixOffset = request.path.slice(1).search(/[?#]/);
1706
- const packageImport = suffixOffset === -1 ? request.path : request.path.slice(0, suffixOffset + 1);
1707
- const resolution = await traceBuild.resolve(packageImport, {
1708
- importer: request.importer,
1709
- kind: request.kind,
1710
- namespace: request.namespace,
1711
- pluginData: {
1712
- ...request.pluginData,
1713
- [resolvingPackageImportHint]: true
1714
- },
1715
- resolveDir: request.resolveDir,
1716
- with: request.with
1717
- });
1718
- if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && existsSync(resolution.path)) importedSourceHints.add(resolution.path);
1719
- });
1720
- const resolvingBarePackageHint = "vitehubResolvingBarePackageHint";
1721
- traceBuild.onResolve({ filter: /^[^./#]/ }, async (request) => {
1722
- if (request.pluginData?.[resolvingBarePackageHint]) return void 0;
1723
- if (!request.importer) return void 0;
1724
- const suffixOffset = request.path.search(/[?#]/);
1725
- const packageImport = suffixOffset === -1 ? request.path : request.path.slice(0, suffixOffset);
1726
- const resolution = await traceBuild.resolve(packageImport, {
1727
- importer: request.importer,
1728
- kind: request.kind,
1729
- namespace: request.namespace,
1730
- pluginData: {
1731
- ...request.pluginData,
1732
- [resolvingBarePackageHint]: true
1733
- },
1734
- resolveDir: request.resolveDir,
1735
- with: request.with
1736
- });
1737
- const source = pathContains$1(root, resolution.path) ? resolution.path : pathContains$1(physicalRoot, resolution.path) ? resolve(root, relative(physicalRoot, resolution.path)) : void 0;
1738
- if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && source && existsSync(source) && !relative(root, source).split(sep).includes("node_modules")) importedSourceHints.add(source);
1739
- return {
1740
- external: true,
1741
- path: request.path
1742
- };
1743
- });
1744
- traceBuild.onResolve({ filter: /[?#]/ }, (request) => {
1745
- if (request.pluginData?.[resolvingPackageImportHint]) return void 0;
1746
- const resourcePath = request.path.split(/[?#]/, 1)[0];
1747
- let resourceSource;
1748
- if (request.resolveDir && (resourcePath.startsWith("./") || resourcePath.startsWith("../"))) resourceSource = resolve(request.resolveDir, resourcePath);
1749
- else if (request.resolveDir && resourcePath.startsWith("/")) {
1750
- const projectRoot = configuredRoots.filter((configuredRoot) => pathContains$1(configuredRoot, request.resolveDir)).sort((left, right) => right.length - left.length)[0] ?? root;
1751
- const rootRelativePath = resourcePath.slice(1);
1752
- const publicSource = resolve(projectRoot, "public", rootRelativePath);
1753
- resourceSource = existsSync(publicSource) ? publicSource : resolve(projectRoot, rootRelativePath);
1754
- }
1755
- if (resourceSource && existsSync(resourceSource)) queriedResourceSources.add(resourceSource);
1756
- return {
1757
- external: true,
1758
- path: request.path
1759
- };
1760
- });
1761
- traceBuild.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (request) => {
1762
- const sourcePath = pathContains$1(root, request.path) ? request.path : pathContains$1(physicalRoot, request.path) ? resolve(root, relative(physicalRoot, request.path)) : void 0;
1763
- if (!sourcePath || relative(root, sourcePath).split(sep).includes("node_modules")) return void 0;
1764
- const source = await readFile(request.path, "utf8").catch(() => void 0);
1765
- if (!source) return void 0;
1766
- const runtimeRequests = /* @__PURE__ */ new Map();
1767
- for (const runtimeRequest of traceComputedModuleSourcesOnce(request.path, source).requests) runtimeRequests.set(`${runtimeRequest.kind}\0${runtimeRequest.resolveFrom}\0${runtimeRequest.specifier}`, runtimeRequest);
1768
- await Promise.all([...runtimeRequests.values()].map(async (runtimeRequest) => {
1769
- const resolveFrom = runtimeRequest.resolveFrom ?? request.path;
1770
- const resolution = await traceBuild.resolve(runtimeRequest.specifier, {
1771
- importer: resolveFrom,
1772
- kind: runtimeRequest.kind,
1773
- namespace: request.namespace,
1774
- resolveDir: dirname(resolveFrom)
1775
- });
1776
- const resolvedSource = pathContains$1(root, resolution.path) ? resolution.path : pathContains$1(physicalRoot, resolution.path) ? resolve(root, relative(physicalRoot, resolution.path)) : void 0;
1777
- if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && resolvedSource && existsSync(resolvedSource) && !relative(root, resolvedSource).split(sep).includes("node_modules")) importedSourceHints.add(resolvedSource);
1778
- }));
1779
- });
3598
+ const inputs = /* @__PURE__ */ new Set();
3599
+ const tracePlugin = {
3600
+ name: "vitehub-provider-vite-resource-query",
3601
+ async resolveId(source, importer, extra) {
3602
+ if (!importer || extra.custom?.[resolvingTraceHint]) return;
3603
+ const resolveDir = isAbsolute(importer) ? dirname(importer) : root;
3604
+ const hintOptions = {
3605
+ custom: {
3606
+ ...extra.custom,
3607
+ [resolvingTraceHint]: true
3608
+ },
3609
+ kind: extra.kind
3610
+ };
3611
+ if (/^\.\.?\//.test(source)) {
3612
+ const relativeSource = resolve(resolveDir, source.split(/[?#]/, 1)[0]);
3613
+ if (existsSync(relativeSource)) importedSourceHints.add(relativeSource);
3614
+ } else if (source.startsWith("#")) {
3615
+ const suffixOffset = source.slice(1).search(/[?#]/);
3616
+ const packageImport = suffixOffset === -1 ? source : source.slice(0, suffixOffset + 1);
3617
+ const resolution = await this.resolve(packageImport, importer, hintOptions);
3618
+ if (resolution && !resolution.external && isAbsolute(resolution.id) && existsSync(resolution.id)) importedSourceHints.add(resolution.id);
3619
+ } else if (/^[^./#]/.test(source)) {
3620
+ const suffixOffset = source.search(/[?#]/);
3621
+ const packageImport = suffixOffset === -1 ? source : source.slice(0, suffixOffset);
3622
+ const resolution = await this.resolve(packageImport, importer, hintOptions);
3623
+ const resolvedSource = resolution && !resolution.external && isAbsolute(resolution.id) ? toRootSource(resolution.id) : void 0;
3624
+ if (isProjectSource(resolvedSource)) importedSourceHints.add(resolvedSource);
3625
+ return {
3626
+ id: source,
3627
+ external: true
3628
+ };
1780
3629
  }
1781
- }],
1782
- write: false
1783
- })]);
1784
- if (result?.status === "fulfilled") results.push(result.value);
3630
+ if (!/[?#]/.test(source)) return;
3631
+ const resourcePath = source.split(/[?#]/, 1)[0];
3632
+ let resourceSource;
3633
+ if (resourcePath.startsWith("./") || resourcePath.startsWith("../")) resourceSource = resolve(resolveDir, resourcePath);
3634
+ else if (resourcePath.startsWith("/")) {
3635
+ const projectRoot = configuredRoots.filter((configuredRoot) => pathContains$1(configuredRoot, resolveDir)).sort((left, right) => right.length - left.length)[0] ?? root;
3636
+ const rootRelativePath = resourcePath.slice(1);
3637
+ const publicSource = resolve(projectRoot, "public", rootRelativePath);
3638
+ resourceSource = existsSync(publicSource) ? publicSource : resolve(projectRoot, rootRelativePath);
3639
+ }
3640
+ if (resourceSource && existsSync(resourceSource)) queriedResourceSources.add(resourceSource);
3641
+ return {
3642
+ id: source,
3643
+ external: true
3644
+ };
3645
+ },
3646
+ async load(id) {
3647
+ if (!isAbsolute(id)) return;
3648
+ inputs.add(id);
3649
+ if (!/\.[cm]?[jt]sx?$/.test(id)) return;
3650
+ const sourcePath = toRootSource(id);
3651
+ if (!sourcePath || relative(root, sourcePath).split(sep).includes("node_modules")) return;
3652
+ const source = await readFile(id, "utf8").catch(() => void 0);
3653
+ if (!source) return;
3654
+ const runtimeRequests = /* @__PURE__ */ new Map();
3655
+ for (const runtimeRequest of traceComputedModuleSourcesOnce(id, source).requests) runtimeRequests.set(`${runtimeRequest.kind}\0${runtimeRequest.resolveFrom}\0${runtimeRequest.specifier}`, runtimeRequest);
3656
+ await Promise.all([...runtimeRequests.values()].map(async (runtimeRequest) => {
3657
+ const resolution = await this.resolve(runtimeRequest.specifier, runtimeRequest.resolveFrom ?? id, {
3658
+ kind: runtimeRequest.kind === "dynamic-import" ? "dynamic-import" : "require-call",
3659
+ skipSelf: false
3660
+ });
3661
+ const resolvedSource = resolution && !resolution.external && isAbsolute(resolution.id) ? toRootSource(resolution.id) : void 0;
3662
+ if (isProjectSource(resolvedSource)) importedSourceHints.add(resolvedSource);
3663
+ }));
3664
+ }
3665
+ };
3666
+ try {
3667
+ const bundle = await rolldown({
3668
+ cwd: root,
3669
+ input: tracedBatch,
3670
+ onLog(_level, log) {
3671
+ if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
3672
+ },
3673
+ platform: variant.platform,
3674
+ plugins: [tracePlugin],
3675
+ resolve: { conditionNames: variant.conditions }
3676
+ });
3677
+ try {
3678
+ await bundle.generate({ format: "esm" });
3679
+ } finally {
3680
+ await bundle.close();
3681
+ }
3682
+ results.push(inputs);
3683
+ } catch {}
1785
3684
  }
1786
- for (const result of results) for (const path of Object.keys(result.metafile.inputs)) {
1787
- const source = resolve(root, path);
3685
+ for (const inputs of results) for (const source of inputs) {
1788
3686
  importedSources.add(source);
1789
- if (results.length === traceBuildVariants.length && results.every((variant) => Object.hasOwn(variant.metafile.inputs, path))) tracedEntries.add(source);
3687
+ if (results.length === traceBuildVariants.length && results.every((variant) => variant.has(source))) tracedEntries.add(source);
1790
3688
  }
1791
3689
  for (const path of importedSourceHints) {
1792
3690
  importedSources.add(path);
@@ -2000,6 +3898,12 @@ async function retainProviderOutputSources(options) {
2000
3898
  ])];
2001
3899
  for (const source of materializedSources.filter((source) => !pathContains$1(root, source))) retainedPaths.set(source, resolve(retainedContainer, relative(captureRoot, source)));
2002
3900
  const requestedSymlinks = [...new Set([root, ...materializedSources].flatMap((path) => symlinkSourcesForRequestedPath(root, path)))].sort((left, right) => relative(root, left).split(sep).length - relative(root, right).split(sep).length);
3901
+ const physicalRoot = realpathSync(root);
3902
+ materializedSources.push(...requestedSymlinks.flatMap((link) => {
3903
+ const physicalTarget = realpathSync(link);
3904
+ const target = pathContains$1(physicalRoot, physicalTarget) ? resolve(root, relative(physicalRoot, physicalTarget)) : physicalTarget;
3905
+ return materializedSources.filter((source) => source !== target && pathContains$1(target, source)).map((source) => resolve(link, relative(target, source)));
3906
+ }));
2003
3907
  const configuredOutputClosures = nestedConfiguredRoots.flatMap((configuredRoot) => {
2004
3908
  const segments = relative(root, configuredRoot).split(sep);
2005
3909
  const ignoredIndex = segments.findIndex((segment) => ignoredGeneratedDirectories.has(segment));
@@ -2026,15 +3930,18 @@ async function retainProviderOutputSources(options) {
2026
3930
  referencedAncestors.add(directory);
2027
3931
  if (directory === root) break;
2028
3932
  }
3933
+ const referencedSourceSet = new Set(referencedSources);
3934
+ const publishedPaths = new Map([...referencedPackages].map((sourcePackage) => [sourcePackage, publishedPackagePaths(sourcePackage)]));
2029
3935
  const isReferencedSource = (path) => {
2030
3936
  if (referencedAncestors.has(path)) return true;
2031
3937
  for (let directory = path; pathContains$1(root, directory); directory = dirname(directory)) {
2032
- 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);
2033
3940
  if (directory === root) break;
2034
3941
  }
2035
3942
  return false;
2036
3943
  };
2037
- const nestedDependencyRoots = /* @__PURE__ */ new Map();
3944
+ const nestedDependencyRoots = new Map([...referencedPackages].map((sourcePackage) => [resolve(retainedRoot, relative(root, sourcePackage), "node_modules"), resolve(sourcePackage, "node_modules")]));
2038
3945
  const temporaryRoot = await mkdtemp(resolve(tmpdir(), "vitehub-provider-sources-"));
2039
3946
  const stagedContainer = resolve(temporaryRoot, "source");
2040
3947
  const stagedRoot = resolve(stagedContainer, relative(captureRoot, root));
@@ -2062,33 +3969,26 @@ async function retainProviderOutputSources(options) {
2062
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));
2063
3970
  return true;
2064
3971
  };
2065
- await cp(root, stagedRoot, {
2066
- recursive: true,
2067
- filter: (source) => shouldCopySource(resolve(source))
2068
- });
2069
- 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()));
2070
3974
  for (const source of escapedMaterializedSources) {
2071
3975
  const retainedSource = resolve(stagedContainer, relative(captureRoot, source));
2072
3976
  await mkdir(dirname(retainedSource), { recursive: true });
2073
- await cp(realpathSync(source), retainedSource, {
2074
- filter: (path) => !isLocalSecretFile(path),
2075
- recursive: statSync(source).isDirectory()
2076
- });
3977
+ const sourceTarget = await unlessGone(() => realpath(source));
3978
+ if (sourceTarget) await copyRetainedSourceTree(sourceTarget, retainedSource, (path) => !isLocalSecretFile(path));
2077
3979
  }
2078
3980
  for (const source of requestedSymlinks) {
2079
3981
  const retainedSource = resolve(stagedRoot, relative(root, source));
2080
- const sourceTarget = realpathSync(source);
3982
+ const sourceTarget = await unlessGone(() => realpath(source));
3983
+ if (!sourceTarget) continue;
2081
3984
  await rm(retainedSource, {
2082
3985
  force: true,
2083
3986
  recursive: true
2084
3987
  });
2085
- await cp(sourceTarget, retainedSource, {
2086
- recursive: statSync(source).isDirectory(),
2087
- filter(candidate) {
2088
- const physicalCandidate = resolve(candidate);
2089
- const logicalCandidate = resolve(source, relative(sourceTarget, physicalCandidate));
2090
- return materializedSources.some((path) => pathContains$1(logicalCandidate, path) || pathContains$1(path, logicalCandidate) || pathContains$1(physicalCandidate, path) || pathContains$1(path, physicalCandidate)) && shouldCopySource(logicalCandidate);
2091
- }
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);
2092
3992
  });
2093
3993
  }
2094
3994
  await rebaseCapturedAbsoluteSourceLinks(stagedContainer, captureRoot, retainedContainer);
@@ -2178,6 +4078,9 @@ async function retainProviderOutputSources(options) {
2178
4078
  }
2179
4079
  //#endregion
2180
4080
  //#region ../internal/src/build/vercel-config.ts
4081
+ function createDefaultVercelOutputRoot(rootDir) {
4082
+ return resolve(rootDir, ".vercel", "output");
4083
+ }
2181
4084
  function createVercelConfigJson() {
2182
4085
  return {
2183
4086
  routes: [{ handle: "filesystem" }, {
@@ -2191,13 +4094,318 @@ function createNodeFunctionConfig(extra = {}) {
2191
4094
  return {
2192
4095
  handler: "index.mjs",
2193
4096
  launcherType: "Nodejs",
2194
- runtime: "nodejs22.x",
4097
+ runtime: "nodejs24.x",
2195
4098
  shouldAddHelpers: false,
2196
4099
  supportsResponseStreaming: true,
2197
4100
  ...extra
2198
4101
  };
2199
4102
  }
2200
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
2201
4409
  //#region ../internal/src/build/provider-output-catalog.ts
2202
4410
  var ProviderOutputCatalog = class {
2203
4411
  bundleDefines = {};
@@ -2518,9 +4726,6 @@ async function writeProviderOutputOwnershipFiles(outputRoot, ownership, files) {
2518
4726
  await writeFile(file, `${JSON.stringify(values, null, 2)}\n`, "utf8");
2519
4727
  }));
2520
4728
  }
2521
- function createDefaultVercelOutputRoot(rootDir) {
2522
- return resolve(rootDir, ".vercel", "output");
2523
- }
2524
4729
  function createDefaultNetlifyOutputRoot(rootDir) {
2525
4730
  return resolve(rootDir, ".netlify", "v1");
2526
4731
  }
@@ -2537,10 +4742,26 @@ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
2537
4742
  assertNetlifyFunctionName(functionName);
2538
4743
  return resolve(functionsRoot, `${functionName}.mjs`);
2539
4744
  }
4745
+ async function declaresTopLevelBinding(code, name) {
4746
+ const { parseSync } = await import("vite");
4747
+ return parseSync("bundle.mjs", code).program.body.some((statement) => {
4748
+ const node = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
4749
+ if (node?.type === "FunctionDeclaration" || node?.type === "ClassDeclaration") return node.id?.name === name;
4750
+ return node?.type === "VariableDeclaration" && node.declarations.some((declaration) => declaration.id.type === "Identifier" && declaration.id.name === name);
4751
+ });
4752
+ }
2540
4753
  async function appendNetlifyFunctionConfig(outfile, config) {
2541
4754
  if (!config) return;
2542
4755
  const bundled = await readFile(outfile, "utf8");
2543
- await writeFile(outfile, `${bundled.trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
4756
+ const literal = stringifyProviderOutputConfig(config);
4757
+ let exported = `export const config = ${literal}`;
4758
+ if (await declaresTopLevelBinding(bundled, "config")) {
4759
+ const baseName = "vitehubNetlifyFunctionConfig";
4760
+ let name = baseName;
4761
+ for (let suffix = 2; bundled.includes(name); suffix++) name = `${baseName}${suffix}`;
4762
+ exported = `const ${name} = ${literal}\nexport { ${name} as config }`;
4763
+ }
4764
+ await writeFile(outfile, `${bundled.trimEnd()}\n\n${exported}\n`, "utf8");
2544
4765
  }
2545
4766
  async function writeCloudflareDeploymentOutput(options, signal) {
2546
4767
  signal?.throwIfAborted();
@@ -3345,9 +5566,11 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
3345
5566
  const write = withProviderDeploymentOutputRootLock(rootDir, async () => {
3346
5567
  await withProviderDeploymentOutputRootTransaction(rootDir, async (transaction) => {
3347
5568
  try {
5569
+ const vercelRuntimePackages = createVercelFunctionRuntimePackagesPass((nodeModules) => transaction.snapshot([nodeModules]));
3348
5570
  for (const contribution of rootContributions) {
3349
5571
  throwIfProviderOutputAborted(controller.signal);
3350
5572
  await contribution.write({
5573
+ addVercelRuntimePackages: (request) => vercelRuntimePackages.add(request),
3351
5574
  readCloudflareState: async (options) => await readCloudflareProviderDeploymentOutputState(rootDir, options),
3352
5575
  signal: controller.signal,
3353
5576
  write: async (writeOptions) => {
@@ -3363,6 +5586,8 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
3363
5586
  });
3364
5587
  throwIfProviderOutputAborted(controller.signal);
3365
5588
  }
5589
+ await vercelRuntimePackages.copy(controller.signal);
5590
+ throwIfProviderOutputAborted(controller.signal);
3366
5591
  ready();
3367
5592
  const rollback = await rootDecision;
3368
5593
  if (rollback !== void 0) throw rollback;
@@ -3588,6 +5813,85 @@ async function writeFileIfChanged(file, contents) {
3588
5813
  await mkdir(resolve$1(file, ".."), { recursive: true });
3589
5814
  await writeFile(file, contents, "utf8");
3590
5815
  }
5816
+ //#endregion
5817
+ //#region ../internal/src/hints.ts
5818
+ /**
5819
+ * The file that lists the hints of the last build or dev server, relative to the project root. A hint is a warning
5820
+ * about something that works now and fails later, such as counts that stay in one server's memory. Agents and CI read
5821
+ * the file instead of the terminal.
5822
+ */
5823
+ const viteHubHintsFile = ".vitehub/hints.json";
5824
+ const VITEHUB_NUXT_HINTS = "__vitehubNuxtHints";
5825
+ const runsKey = Symbol.for("vitehub.hints.runs");
5826
+ const shared = globalThis;
5827
+ const runs = shared[runsKey] ??= /* @__PURE__ */ new Map();
5828
+ const startedKey = Symbol.for("vitehub.hints.started");
5829
+ const startedShared = globalThis;
5830
+ const started = startedShared[startedKey] ??= /* @__PURE__ */ new WeakSet();
5831
+ /**
5832
+ * The report of the ViteHub project root, where the other generated files go. A Nuxt app with `srcDir: "app"` has its
5833
+ * Vite root in `app/`, one folder below.
5834
+ */
5835
+ function hintsFile(config) {
5836
+ const projectRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
5837
+ return resolve(typeof projectRoot === "string" ? projectRoot : resolveViteHubProjectRoot(config.root), viteHubHintsFile);
5838
+ }
5839
+ function startRun(config) {
5840
+ const file = hintsFile(config);
5841
+ const run = {
5842
+ file,
5843
+ report: {
5844
+ version: 1,
5845
+ command: config.command,
5846
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
5847
+ hints: []
5848
+ },
5849
+ keys: /* @__PURE__ */ new Set()
5850
+ };
5851
+ runs.set(file, run);
5852
+ return run;
5853
+ }
5854
+ function write(run) {
5855
+ mkdirSync(dirname(run.file), { recursive: true });
5856
+ writeFileSync(run.file, `${JSON.stringify(run.report, null, 2)}\n`);
5857
+ }
5858
+ /**
5859
+ * Reports a hint from a Vite plugin hook, or from a Nitro or Nuxt hook of the same build: prints it once with its fix and docs link, and adds it to
5860
+ * {@link viteHubHintsFile}. Build the diagnostic from the package's nostics catalog, so its code has a docs page.
5861
+ */
5862
+ function reportViteHubHint(config, diagnostic) {
5863
+ if (skipHints(config)) return;
5864
+ const nuxt = config[VITEHUB_NUXT_HINTS];
5865
+ if (typeof nuxt === "function") return nuxt(diagnostic);
5866
+ const run = runs.get(hintsFile(config)) ?? startRun(config);
5867
+ const hint = {
5868
+ code: diagnostic.code,
5869
+ why: diagnostic.why,
5870
+ ...diagnostic.fix ? { fix: diagnostic.fix } : {},
5871
+ ...diagnostic.docs ? { docs: diagnostic.docs } : {},
5872
+ ...diagnostic.sources?.length ? { sources: diagnostic.sources } : {}
5873
+ };
5874
+ const key = JSON.stringify([hint.code, hint.sources ?? []]);
5875
+ if (run.keys.has(key)) return;
5876
+ run.keys.add(key);
5877
+ run.report.hints.push(hint);
5878
+ write(run);
5879
+ (config.logger ?? console).warn(formatDiagnostic(diagnostic));
5880
+ }
5881
+ function skipHints(config) {
5882
+ return !config.command || Reflect.get(config, "__vitehubPrepare") === true || Reflect.get(config, "vitehubCliDiscovery") === true;
5883
+ }
5884
+ /**
5885
+ * Starts the hints of a build or dev server: writes an empty {@link viteHubHintsFile}, so a run without hints does not
5886
+ * leave the hints of an earlier run in place. Every plugin that reports hints calls it from `configResolved`, so a
5887
+ * package used without `vitehub()` starts its own run. Nuxt uses the app instance as owner so its Vite builds and
5888
+ * separate Nitro build share one report; replay, prepare and discovery never reset it.
5889
+ */
5890
+ function startViteHubHints(config, owner = config) {
5891
+ if (skipHints(config) || config["__vitehubNuxtHints"] || started.has(owner)) return;
5892
+ started.add(owner);
5893
+ write(startRun(config));
5894
+ }
3591
5895
  /** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
3592
5896
  function hostFromNitroPreset(value) {
3593
5897
  const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
@@ -3620,8 +5924,8 @@ function resolveHostPreset(input = {}) {
3620
5924
  function resolveHost(input = {}) {
3621
5925
  return hostFromNitroPreset(resolveHostPreset(input));
3622
5926
  }
3623
- //#endregion
3624
- //#region ../internal/src/nitro-kit.ts
5927
+ Object.freeze({ vitehubAuthAccess: "handler" });
5928
+ Object.freeze({ vitehubOwnAccess: true });
3625
5929
  function cloneArray(value) {
3626
5930
  return Array.isArray(value) ? [...value] : [];
3627
5931
  }
@@ -3704,6 +6008,10 @@ async function collectContributions(plugins, options) {
3704
6008
  const candidates = [];
3705
6009
  await flattenPlugins(plugins ?? [], candidates, /* @__PURE__ */ new Set());
3706
6010
  const collected = /* @__PURE__ */ new Map();
6011
+ const context = {
6012
+ ...options.context,
6013
+ plugins: candidates
6014
+ };
3707
6015
  for (const plugin of candidates) {
3708
6016
  if (!Object.hasOwn(plugin, "vitehub")) continue;
3709
6017
  const metadata = Reflect.get(plugin, "vitehub");
@@ -3715,7 +6023,7 @@ async function collectContributions(plugins, options) {
3715
6023
  throw options.invalid(`[vitehub] Plugin ${JSON.stringify(contributor)} contributed an invalid ${options.kind}: ${reason}`);
3716
6024
  };
3717
6025
  const callable = typeof source === "function";
3718
- const entries = callable ? await Reflect.apply(source, void 0, [options.context]) : source;
6026
+ const entries = callable ? await Reflect.apply(source, void 0, [context]) : source;
3719
6027
  if (entries === void 0 && callable) continue;
3720
6028
  if (!Array.isArray(entries)) fail(`\`vitehub.${options.key}\` must be an array or a function that returns one.`);
3721
6029
  const list = entries;
@@ -3798,10 +6106,6 @@ async function collectScheduleContributions(plugins, context) {
3798
6106
  return contributions;
3799
6107
  }
3800
6108
  //#endregion
3801
- //#region src/runtime/started-name.ts
3802
- /** Name of the Schedule that runs due started Schedules each minute. Discovery adds it when a Definition has no `cron`. */
3803
- const startedSchedulesTickName = "vitehub/started-schedules";
3804
- //#endregion
3805
6109
  //#region src/discovery.ts
3806
6110
  /** Discovery source of Schedule Definitions that Vite plugins contribute through `vitehub.schedules`. */
3807
6111
  const contributedScheduleSource = "vite-plugin-contribution";
@@ -3929,11 +6233,6 @@ function startedTickSource() {
3929
6233
  ""
3930
6234
  ].join("\n");
3931
6235
  }
3932
- /**
3933
- * The Schedule that wakes started Schedules. It is a plain Schedule with `* * * * *`, so each host wakes it the way it
3934
- * wakes any Schedule: a Cron Trigger on Cloudflare, the Process Runtime on Node. The build reads its cron from source, so
3935
- * the module is a file in the project.
3936
- */
3937
6236
  function startedTickDefinition(rootDir) {
3938
6237
  const file = resolve(rootDir, startedTickFile);
3939
6238
  const source = startedTickSource();
@@ -4133,14 +6432,22 @@ async function removeEmptyDirectories(directory, rootDir) {
4133
6432
  }
4134
6433
  }
4135
6434
  const cronFieldPattern = /^[*,/\-0-9]+$/;
4136
- 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) {
4137
6437
  const fields = cron.trim().split(/\s+/);
4138
6438
  const hasVercelDayConflict = fields[2] !== "*" && fields[4] !== "*";
4139
- 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;
4140
6440
  }
4141
- 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) {
4142
6446
  const definition = findDefaultExportCall(scanModule(readFileSync(file, "utf8"), file), ["defineSchedule"]);
4143
- 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);
4144
6451
  if (!cron) throw scheduleErrorDiagnostics.SCHEDULE_R0004({ message: `Schedule "${scheduleName}" must declare a static cron string for provider wake output.` });
4145
6452
  return cron;
4146
6453
  }
@@ -4196,7 +6503,7 @@ function renderProviderEntry(file, registryFile, provider, scheduleName, workflo
4196
6503
  const workflowRuntime = provider === "vercel" ? workflow : void 0;
4197
6504
  return [
4198
6505
  `import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
4199
- `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)}`,
4200
6507
  ...workflowRuntime ? [
4201
6508
  `import workflowRegistry from ${JSON.stringify(createImportPath(file, workflowRuntime.registryFile))}`,
4202
6509
  `import { setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from ${JSON.stringify(workflowRuntime.runtimeModules.state)}`,
@@ -4245,12 +6552,16 @@ function renderProviderEntry(file, registryFile, provider, scheduleName, workflo
4245
6552
  " },",
4246
6553
  " async scheduled(event, env, ctx) {",
4247
6554
  " if (typeof event.cron !== 'string' || !event.cron.trim()) return",
6555
+ " const trigger = normalizeCron(event.cron)",
4248
6556
  " const tasks = Object.entries(scheduleRegistry).map(async ([name]) => {",
4249
6557
  " const definition = await loadScheduleDefinition(name)",
4250
- " 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",
4251
6562
  " const scheduledAt = new Date(event.scheduledTime)",
4252
6563
  " if (!isWakeDue(name, definition, scheduledAt)) return",
4253
- " 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) })",
4254
6565
  " })",
4255
6566
  " await Promise.all(tasks)",
4256
6567
  " },",
@@ -4333,23 +6644,10 @@ function renderDenoCronEntry(file, registryFile, crons, runtimeImport = schedule
4333
6644
  const cronId = index.toString(36);
4334
6645
  const safeName = [...name].map((character) => /^[a-z0-9 _-]$/i.test(character) ? character : "_").join("");
4335
6646
  const cronNamePrefix = `vitehub-${cronId}-`;
4336
- const fields = cron.trim().split(/\s+/);
4337
- if (fields[4] !== "*") {
4338
- const weekdays = [
4339
- "SUN",
4340
- "MON",
4341
- "TUE",
4342
- "WED",
4343
- "THU",
4344
- "FRI",
4345
- "SAT"
4346
- ];
4347
- fields[4] = parseCronExpression(cron).weekdays.map((day) => weekdays[day]).join(",");
4348
- }
4349
6647
  return {
4350
6648
  cron,
4351
6649
  cronName: `${cronNamePrefix}${safeName.slice(0, 64 - cronNamePrefix.length)}`,
4352
- denoCron: fields.join(" "),
6650
+ denoCron: cronWithWeekdayNames(cron),
4353
6651
  inTimeZone: Object.hasOwn(timeZoneCrons, name),
4354
6652
  name
4355
6653
  };
@@ -4387,8 +6685,8 @@ function renderDenoCronEntry(file, registryFile, crons, runtimeImport = schedule
4387
6685
  function createSchedulePublicAliasPlugin() {
4388
6686
  return {
4389
6687
  name: "vitehub-schedule-public-alias",
4390
- setup(build) {
4391
- build.onResolve({ filter: /^(?:@vite-hub|vite-hub)\/schedule$/ }, () => ({ path: schedulePublicEntry }));
6688
+ resolveId(source) {
6689
+ if (source === "@vite-hub/schedule" || source === "vite-hub/schedule") return schedulePublicEntry;
4392
6690
  }
4393
6691
  };
4394
6692
  }
@@ -4459,7 +6757,7 @@ async function writeVercelScheduleFunctions(options, crons) {
4459
6757
  await bundleEsmEntry(wrapperFile, functionFile, {
4460
6758
  alias: options.bundleAlias,
4461
6759
  define: options.bundleDefines,
4462
- external: options.bundleExternal,
6760
+ external: [cloudflareRuntimeExternal, ...options.bundleExternal ?? []],
4463
6761
  format: "esm",
4464
6762
  platform: "node",
4465
6763
  plugins: [createSchedulePublicAliasPlugin(), ...options.workflow?.bundlePlugins ?? []],
@@ -4659,7 +6957,7 @@ async function writeNetlifyScheduleFunctions(options) {
4659
6957
  await bundleEsmEntry(wrapperFile, output.file, {
4660
6958
  alias: options.bundleAlias,
4661
6959
  define: options.bundleDefines,
4662
- external: options.bundleExternal,
6960
+ external: [cloudflareRuntimeExternal, ...options.bundleExternal ?? []],
4663
6961
  format: "esm",
4664
6962
  platform: "node",
4665
6963
  plugins: [createSchedulePublicAliasPlugin()],
@@ -4898,7 +7196,7 @@ async function generateProviderOutputsWithinLock(options) {
4898
7196
  bundleAlias: options.bundleAlias,
4899
7197
  bundleDefines: options.bundleDefines,
4900
7198
  bundleEntry: artifacts.cloudflareWorkerFile,
4901
- crons: [...new Set(crons.values())],
7199
+ crons: [...new Set([...crons.values()].map(cronWithWeekdayNames))],
4902
7200
  rootDir: options.rootDir,
4903
7201
  previousStateFile: previousCloudflareStateFile,
4904
7202
  sourceRootDir: options.sourceRootDir,
@@ -4961,17 +7259,13 @@ async function generateProviderOutputsWithinLock(options) {
4961
7259
  function inspectTimeZone(timeZone) {
4962
7260
  return timeZone === null ? "Not a static string" : timeZone ?? "UTC";
4963
7261
  }
4964
- /** The UTC cron that Cloudflare, Vercel, Netlify, and Deno run for a Schedule with a static `timeZone`. */
4965
7262
  function inspectHostCron(cron, timeZone) {
4966
- try {
4967
- const utcCron = utcCronForTimeZone(cron, timeZone);
4968
- return utcCron ? [{
4969
- label: "Host cron (UTC)",
4970
- value: utcCron
4971
- }] : [];
4972
- } catch {
4973
- return [];
4974
- }
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
+ }] : [];
4975
7269
  }
4976
7270
  function summarizeScheduleDefinition(projectRoot, definition, crons, overrides = {}) {
4977
7271
  const declaredCron = crons.get(definition.name);
@@ -5035,9 +7329,8 @@ async function inspectScheduleDefinitions(options) {
5035
7329
  const crons = /* @__PURE__ */ new Map();
5036
7330
  for (const definition of definitions) {
5037
7331
  if (definition.startable) continue;
5038
- try {
5039
- for (const [name, cron] of await readRuntimeDefinitionCrons([definition])) crons.set(name, cron);
5040
- } catch {}
7332
+ const cron = readStaticScheduleCronOption(definition.handler);
7333
+ if (cron) crons.set(definition.name, cron);
5041
7334
  }
5042
7335
  return definitions.map((definition) => summarizeScheduleDefinition(options.projectRoot, definition, crons, options.cron));
5043
7336
  }
@@ -5064,10 +7357,10 @@ function definitionRecord(summary) {
5064
7357
  },
5065
7358
  startable ? {
5066
7359
  label: "Runs",
5067
- 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.`
5068
7361
  } : {
5069
7362
  label: "Runs",
5070
- 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.`
5071
7364
  }
5072
7365
  ],
5073
7366
  id: `definition:${summary.name}`,
@@ -5081,7 +7374,7 @@ async function inspectScheduleConsoleRecords(options) {
5081
7374
  /**
5082
7375
  * Console section for Schedules. Records list discovered Schedule Definitions. When the server runs the Process Runtime,
5083
7376
  * the cron and time zone come from the loaded Definitions, so any expression shows its real value.
5084
- * `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
5085
7378
  * that a runtime recorded.
5086
7379
  */
5087
7380
  const scheduleConsoleSection = {
@@ -5143,6 +7436,7 @@ const generatedNitroSchedulePlugin = ".vitehub/nitro/schedule/plugin.ts";
5143
7436
  const generatedNitroProviderRegistry = ".vitehub/nitro/schedule/provider-registry.js";
5144
7437
  const generatedNitroStaticRegistry = ".vitehub/nitro/schedule/static-registry.js";
5145
7438
  const generatedNitroStartedRegistry = ".vitehub/nitro/schedule/started-registry.js";
7439
+ const generatedNitroInventoryRegistry = ".vitehub/nitro/schedule/inventory-registry.js";
5146
7440
  const defaultCatchUpMs = 36e5;
5147
7441
  const generatedNitroScheduleModule = "./.vitehub/nitro/schedule/module.mjs";
5148
7442
  const generatedNitroNetlifyEntry = ".vitehub/nitro/schedule/netlify-entry.mjs";
@@ -5188,10 +7482,6 @@ const databaseVitePluginName = "@vite-hub/database/vite";
5188
7482
  function hasVitePlugin(plugins, name) {
5189
7483
  return (plugins ?? []).some((plugin) => Array.isArray(plugin) ? hasVitePlugin(plugin, name) : isRecord(plugin) && plugin.name === name);
5190
7484
  }
5191
- /**
5192
- * Checks the build's `cron` map. `definitions` is the final Schedule set, or `undefined` while plugins can still
5193
- * contribute Schedules. The Process Runtime owns Static Schedule wakes unless `providerOutput` is `nitro` or `standalone`.
5194
- */
5195
7485
  function resolveCronOverrides(value, definitions, options) {
5196
7486
  if (value === void 0) return;
5197
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 * * *\" }`." });
@@ -5270,8 +7560,10 @@ const scheduleRuntimeModule = ownModule(import.meta.url, "runtime");
5270
7560
  const scheduleKVRuntimeModule = ownModule(import.meta.url, "runtime/kv");
5271
7561
  const scheduleProcessRuntimeModule = ownModule(import.meta.url, "runtime/process");
5272
7562
  const scheduleStaticRuntimeModule = ownModule(import.meta.url, "runtime/static");
7563
+ const scheduleStateModule = ownModule(import.meta.url, "runtime/state");
5273
7564
  function renderNitroSchedulePlugin(options) {
5274
7565
  const providerWake = options.providerDefinitions.length > 0;
7566
+ const installInventory = options.inventoryRegistryFile !== void 0 || Object.keys(options.hostTimings).length > 0;
5275
7567
  const processRuntime = options.processRuntime;
5276
7568
  const processRuntimeOptions = processRuntime ? {
5277
7569
  ...processRuntime.catchUpMs !== void 0 ? { catchUpMs: processRuntime.catchUpMs } : {},
@@ -5283,34 +7575,36 @@ function renderNitroSchedulePlugin(options) {
5283
7575
  } : void 0;
5284
7576
  const leaseDatabaseImport = processRuntime ? options.leaseDatabaseImport : void 0;
5285
7577
  const scheduleStoreOptions = processRuntime?.prefix !== void 0 ? { prefix: processRuntime.prefix } : {};
7578
+ const memoryStores = processRuntime && options.memoryProcessStores;
7579
+ const runStoreFactory = memoryStores ? "createMemoryScheduleRunStore" : "createKVScheduleRunStore";
7580
+ const startedStoreFactory = memoryStores ? "createMemoryStartedScheduleStore" : "createKVStartedScheduleStore";
5286
7581
  return [
5287
7582
  "import { definePlugin } from 'nitro'",
7583
+ ...installInventory ? [`import { setHostScheduleInventory } from ${JSON.stringify(scheduleStateModule)}`] : [],
7584
+ ...options.inventoryRegistryFile ? [`import inventoryRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.inventoryRegistryFile))}`] : [],
5288
7585
  ...providerWake ? [`import scheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.providerRegistryFile))}`, `import { executeCloudflareStaticSchedules } from ${JSON.stringify(options.runtimeImport ?? scheduleStaticRuntimeModule)}`] : [],
5289
7586
  ...processRuntime ? [
5290
- `import { normalizeScheduleRuntimeError } from ${JSON.stringify(options.runtimeImport ?? scheduleStaticRuntimeModule)}`,
5291
- `import { createKVScheduleRunStore } from ${JSON.stringify(scheduleRuntimeModule)}`,
5292
- `import { scheduleKVStorage } from ${JSON.stringify(scheduleKVRuntimeModule)}`,
7587
+ `import { logScheduleRuntimeError, normalizeScheduleRuntimeError } from ${JSON.stringify(options.runtimeImport ?? scheduleStaticRuntimeModule)}`,
7588
+ `import { ${runStoreFactory} } from ${JSON.stringify(scheduleRuntimeModule)}`,
5293
7589
  `import { installProcessScheduleRuntime, onShutdown } from ${JSON.stringify(scheduleProcessRuntimeModule)}`,
5294
7590
  ...leaseDatabaseImport ? [`import { useLeases } from ${JSON.stringify(leaseDatabaseImport)}`] : [],
5295
7591
  `import staticScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.staticRegistryFile))}`
5296
7592
  ] : [],
5297
- ...options.startedRegistryFile ? [
5298
- `import { createKVStartedScheduleStore, installStartedSchedules } from ${JSON.stringify(scheduleRuntimeModule)}`,
5299
- ...processRuntime ? [] : [`import { scheduleKVStorage } from ${JSON.stringify(scheduleKVRuntimeModule)}`],
5300
- `import startedScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.startedRegistryFile))}`
5301
- ] : [],
7593
+ ...!memoryStores && (processRuntime || options.startedRegistryFile) ? [`import { scheduleKVStorage } from ${JSON.stringify(scheduleKVRuntimeModule)}`] : [],
7594
+ ...options.startedRegistryFile ? [`import { ${startedStoreFactory}, installStartedSchedules } from ${JSON.stringify(scheduleRuntimeModule)}`, `import startedScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.startedRegistryFile))}`] : [],
5302
7595
  "",
5303
7596
  ...processRuntime ? [
5304
7597
  `const processRuntimeOptions = ${JSON.stringify(processRuntimeOptions, null, 2)}`,
5305
- `const scheduleStoreOptions = { ...${JSON.stringify(scheduleStoreOptions, null, 2)}, kvStore: scheduleKVStorage }`,
7598
+ ...memoryStores ? [] : [`const scheduleStoreOptions = { ...${JSON.stringify(scheduleStoreOptions, null, 2)}, kvStore: scheduleKVStorage }`],
5306
7599
  ""
5307
7600
  ] : [],
5308
7601
  "export default definePlugin((nitroApp) => {",
7602
+ ...installInventory ? [` setHostScheduleInventory({ timings: ${JSON.stringify(options.hostTimings)}${options.inventoryRegistryFile ? ", registry: inventoryRegistry" : ""} })`] : [],
5309
7603
  ...options.startedRegistryFile ? [
5310
7604
  " installStartedSchedules({",
5311
7605
  ` catchUpMs: ${processRuntime ? processRuntime.catchUpMs ?? defaultCatchUpMs : 0},`,
5312
7606
  " registry: startedScheduleRegistry,",
5313
- ` store: createKVStartedScheduleStore({ ...${JSON.stringify(scheduleStoreOptions)}, kvStore: scheduleKVStorage }),`,
7607
+ ` store: ${startedStoreFactory}(${memoryStores ? "" : `{ ...${JSON.stringify(scheduleStoreOptions)}, kvStore: scheduleKVStorage }`}),`,
5314
7608
  " })"
5315
7609
  ] : [],
5316
7610
  ...providerWake ? [
@@ -5318,7 +7612,8 @@ function renderNitroSchedulePlugin(options) {
5318
7612
  ` await executeCloudflareStaticSchedules(event, { ${[
5319
7613
  Object.keys(options.cronOverrides).length ? `cronOverrides: ${JSON.stringify(options.cronOverrides)}, ` : "",
5320
7614
  "registry: scheduleRegistry",
5321
- 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)}` : ""
5322
7617
  ].join("")} })`,
5323
7618
  " })"
5324
7619
  ] : [],
@@ -5332,7 +7627,7 @@ function renderNitroSchedulePlugin(options) {
5332
7627
  " return",
5333
7628
  " }",
5334
7629
  " try {",
5335
- " console.error('[vitehub:schedule]', runtimeError)",
7630
+ " logScheduleRuntimeError(error, runtimeError)",
5336
7631
  " }",
5337
7632
  " catch {}",
5338
7633
  " try {",
@@ -5354,7 +7649,7 @@ function renderNitroSchedulePlugin(options) {
5354
7649
  ...leaseDatabaseImport ? [" ...(leases ? { leases } : {}),"] : [],
5355
7650
  " onError: captureRuntimeError,",
5356
7651
  " registry: staticScheduleRegistry,",
5357
- " scheduleRunStore: createKVScheduleRunStore(scheduleStoreOptions),",
7652
+ ` scheduleRunStore: ${runStoreFactory}(${memoryStores ? "" : "scheduleStoreOptions"}),`,
5358
7653
  " }).then(",
5359
7654
  " controller => ({ controller }),",
5360
7655
  " error => {",
@@ -5377,10 +7672,6 @@ function renderNitroSchedulePlugin(options) {
5377
7672
  ""
5378
7673
  ].join("\n");
5379
7674
  }
5380
- /**
5381
- * On Cloudflare, adds the cron triggers. On Netlify, Nitro has no cron, so each Schedule gets a scheduled function
5382
- * that runs it in Nitro's own server bundle: the plugins, aliases, and bindings of the app are the same as for requests.
5383
- */
5384
7675
  function renderNitroScheduleModule(options) {
5385
7676
  const { netlify } = options;
5386
7677
  let netlifyFunctionNames = /* @__PURE__ */ new Map();
@@ -5403,6 +7694,7 @@ function renderNitroScheduleModule(options) {
5403
7694
  const crons = Object.fromEntries(netlify.schedules.map((schedule) => [schedule.name, schedule.cron]));
5404
7695
  const timeZoneNames = netlify.schedules.filter((schedule) => schedule.inTimeZone).map((schedule) => schedule.name);
5405
7696
  const netlifyEntryRuntime = [
7697
+ "import { useNitroApp } from \"nitro/app\"",
5406
7698
  `import scheduleRegistry from ${JSON.stringify(netlify.registryFile)}`,
5407
7699
  `import { executeStaticSchedule, isTimeZoneWakeDue, missingScheduleDefinitionError, scheduledWakeTime, unwrapScheduleDefinition } from ${JSON.stringify(netlify.runtimeImport)}`,
5408
7700
  "",
@@ -5410,10 +7702,11 @@ function renderNitroScheduleModule(options) {
5410
7702
  `const timeZoneNames = new Set(${JSON.stringify(timeZoneNames)})`,
5411
7703
  "",
5412
7704
  "export async function runViteHubNetlifySchedule(name) {",
7705
+ " const scheduledAt = scheduledWakeTime(crons[name])",
7706
+ " await useNitroApp().ready",
5413
7707
  " const loader = scheduleRegistry[name]",
5414
7708
  " const definition = loader ? unwrapScheduleDefinition(await loader()) : undefined",
5415
7709
  " if (!definition) throw missingScheduleDefinitionError(name)",
5416
- " const scheduledAt = scheduledWakeTime(crons[name])",
5417
7710
  " if (timeZoneNames.has(name) && !isTimeZoneWakeDue(definition, name, scheduledAt)) return",
5418
7711
  " await executeStaticSchedule({ cron: crons[name], definition, name, scheduledAt })",
5419
7712
  "}",
@@ -5494,10 +7787,15 @@ async function writeNitroSchedulePlugin(root, options) {
5494
7787
  const providerRegistryFile = resolve(root, generatedNitroProviderRegistry);
5495
7788
  const staticRegistryFile = resolve(root, generatedNitroStaticRegistry);
5496
7789
  const startedRegistryFile = options.startableDefinitions.length ? resolve(root, generatedNitroStartedRegistry) : void 0;
7790
+ const inventoryRegistryFile = options.inventoryDefinitions.length ? resolve(root, generatedNitroInventoryRegistry) : void 0;
5497
7791
  const writes = [writeFileIfChanged(pluginFile, renderNitroSchedulePlugin({
5498
7792
  cronOverrides: options.cronOverrides,
7793
+ triggerCrons: options.triggerCrons,
7794
+ hostTimings: options.hostTimings,
7795
+ inventoryRegistryFile,
5499
7796
  timeZoneCrons: options.timeZoneCrons,
5500
7797
  leaseDatabaseImport: options.leaseDatabaseImport,
7798
+ memoryProcessStores: options.memoryProcessStores,
5501
7799
  pluginFile,
5502
7800
  startedRegistryFile,
5503
7801
  processRuntime: options.processRuntime,
@@ -5507,6 +7805,10 @@ async function writeNitroSchedulePlugin(root, options) {
5507
7805
  staticRegistryFile,
5508
7806
  runtimeImport: options.runtimeImport
5509
7807
  }))];
7808
+ if (inventoryRegistryFile) {
7809
+ writes.push(writeFileIfChanged(inventoryRegistryFile, createRuntimeRegistryContents(inventoryRegistryFile, options.inventoryDefinitions)));
7810
+ writes.push(writeFileIfChanged(inventoryRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase)));
7811
+ }
5510
7812
  if (startedRegistryFile) {
5511
7813
  writes.push(writeFileIfChanged(startedRegistryFile, createRuntimeRegistryContents(startedRegistryFile, options.startableDefinitions)));
5512
7814
  writes.push(writeFileIfChanged(startedRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase)));
@@ -5542,11 +7844,29 @@ function selectNitroScheduleDefinitions(definitions, options) {
5542
7844
  if (options.providerOutput === "nitro") return definitions;
5543
7845
  return definitions.filter(isServerScheduleDefinition);
5544
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
+ }
5545
7865
  function selectStandaloneProviderSource(definitions, options) {
5546
7866
  if (options.providerOutput === "auto" || options.providerOutput === void 0) return hasServerScheduleDefinitions(definitions) ? "vite-suffix" : void 0;
5547
7867
  }
5548
7868
  function shouldInstallNitroSchedulePlugin(definitions, options, startable) {
5549
- return selectNitroScheduleDefinitions(definitions, options).length > 0 || options.runtime !== void 0 || startable > 0;
7869
+ return selectNitroScheduleDefinitions(definitions, options).length > 0 || options.runtime !== void 0 || startable > 0 || options.nitroOwnsPaths === true && definitions.length > 0;
5550
7870
  }
5551
7871
  function shouldEmitStandaloneProviderOutput(definitions, options) {
5552
7872
  if (options.providerOutput === false || options.providerOutput === "nitro") return false;
@@ -5557,6 +7877,12 @@ function shouldEmitStandaloneProviderOutput(definitions, options) {
5557
7877
  async function createScheduleNitroConfig(options = {}) {
5558
7878
  const processRuntime = resolveProcessRuntimeOptions(options.runtime);
5559
7879
  const roots = resolveSchedulePluginRoots(options.root || process.cwd(), options);
7880
+ const internal = options;
7881
+ const hints = internal.hints ?? {
7882
+ root: options.root ?? roots.projectRoot,
7883
+ command: "build"
7884
+ };
7885
+ if (options.command === "build" && !internal.preliminary && !internal.hints) startViteHubHints(hints);
5560
7886
  const contributions = options.contributions ?? await collectScheduleContributions(options.plugins, {
5561
7887
  projectRoot: roots.projectRoot,
5562
7888
  root: roots.viteRoot,
@@ -5583,12 +7909,12 @@ async function createScheduleNitroConfig(options = {}) {
5583
7909
  let nitro = options.nitro;
5584
7910
  if (vercelDefinitions.length) nitro = mergeNitroVercelCrons(nitro, vercelDefinitions, await readDefinitionCrons(vercelDefinitions, cronOverrides));
5585
7911
  if (!installNitroPlugin) return nitro;
5586
- const internal = options;
5587
- if (processRuntime && options.command === "build" && !internal.preliminary && !internal.leaseDatabaseImport) console.warn("[vitehub:schedule] The Process Runtime claims each Schedule occurrence in memory, because the app has no Database. Run one server only, or add a Postgres Database so that more than one server runs each occurrence once.");
5588
- const nitroDefinitions = processRuntime && options.providerOutput !== "nitro" ? [] : selectNitroScheduleDefinitions(definitions, options);
7912
+ if (processRuntime && options.command === "build" && !internal.preliminary && !internal.leaseDatabaseImport) reportViteHubHint(hints, scheduleErrorDiagnostics.SCHEDULE_PROCESS_CLAIMS_IN_MEMORY());
7913
+ const nitroDefinitions = selectHostCronDefinitions(definitions, options);
5589
7914
  const nitroCrons = options.command === "build" ? await readDefinitionCrons(nitroDefinitions, cronOverrides) : /* @__PURE__ */ new Map();
5590
7915
  const timeZoneCrons = options.command === "build" ? readTimeZoneCrons(nitroDefinitions, cronOverrides) : {};
5591
- 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))];
5592
7918
  const netlifySchedules = [...nitroCrons].map(([name, cron]) => ({
5593
7919
  cron,
5594
7920
  ...Object.hasOwn(timeZoneCrons, name) ? { inTimeZone: true } : {},
@@ -5600,11 +7926,28 @@ async function createScheduleNitroConfig(options = {}) {
5600
7926
  const timing = readStaticScheduleTiming(definition.handler);
5601
7927
  return timing ? [[definition.name, timing]] : [];
5602
7928
  })) : void 0;
7929
+ const processNames = new Set(processRuntime ? staticDefinitions.map((definition) => definition.name) : []);
7930
+ const hostTimings = /* @__PURE__ */ new Map();
7931
+ const inventoryDefinitions = definitions.filter(({ name, handler }) => {
7932
+ if (processNames.has(name)) return false;
7933
+ const override = options.providerOutput !== false && cronOverrides && Object.hasOwn(cronOverrides, name) ? cronOverrides[name] : void 0;
7934
+ const timing = override ? {
7935
+ cron: override,
7936
+ timeZone: "UTC"
7937
+ } : options.command === "build" ? readStaticScheduleTiming(handler) : void 0;
7938
+ if (!timing) return true;
7939
+ hostTimings.set(name, timing);
7940
+ return false;
7941
+ });
5603
7942
  const plugin = await writeNitroSchedulePlugin(roots.projectRoot, {
5604
7943
  cronOverrides: Object.fromEntries(Object.entries(cronOverrides ?? {}).filter(([name]) => nitroDefinitionNames.has(name))),
7944
+ triggerCrons,
7945
+ hostTimings: Object.fromEntries(hostTimings),
7946
+ inventoryDefinitions,
5605
7947
  crons,
5606
7948
  importBase: options.importBase,
5607
- leaseDatabaseImport: options.leaseDatabaseImport,
7949
+ leaseDatabaseImport: internal.leaseDatabaseImport,
7950
+ memoryProcessStores: internal.memoryProcessStores,
5608
7951
  netlifySchedules,
5609
7952
  timeZoneCrons,
5610
7953
  processRuntime,
@@ -5634,7 +7977,15 @@ function hubSchedule(options = {}) {
5634
7977
  let serverDirs;
5635
7978
  let viteRoot;
5636
7979
  let contributions = [];
5637
- const leaseDatabaseImport = (plugins) => hasVitePlugin(plugins, databaseVitePluginName) ? { leaseDatabaseImport: internalOptions.databaseImport ?? "@vite-hub/database" } : {};
7980
+ let command;
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
+ };
5638
7989
  async function collectPluginScheduleContributions(plugins, roots) {
5639
7990
  return await collectScheduleContributions(plugins, {
5640
7991
  projectRoot: roots.projectRoot,
@@ -5658,6 +8009,7 @@ function hubSchedule(options = {}) {
5658
8009
  name: SCHEDULE_VITE_PLUGIN_NAME,
5659
8010
  enforce: "pre",
5660
8011
  async config(config, env) {
8012
+ command = env.command;
5661
8013
  serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
5662
8014
  const roots = resolveSchedulePluginRoots(config.root || process.cwd(), options);
5663
8015
  contributions = await collectPluginScheduleContributions(config.plugins, roots);
@@ -5675,7 +8027,7 @@ function hubSchedule(options = {}) {
5675
8027
  contributions,
5676
8028
  nitroOwnsPaths: hasNitroConfigContext(config),
5677
8029
  nitro: config.nitro,
5678
- ...leaseDatabaseImport(config.plugins),
8030
+ ...processStorageOptions(typeof Reflect.get(config, "__vitehubNuxtHints") === "function" ? (name) => hasVitePlugin(config.plugins, name) : (name) => hasViteConfigPlugin(env, name)),
5679
8031
  preliminary: true,
5680
8032
  root: config.root || process.cwd(),
5681
8033
  serverDirs
@@ -5684,6 +8036,7 @@ function hubSchedule(options = {}) {
5684
8036
  config.nitro = nitro;
5685
8037
  },
5686
8038
  async configResolved(config) {
8039
+ startViteHubHints(config);
5687
8040
  resolved = config;
5688
8041
  providerOutput = useProviderOutputCatalog(config);
5689
8042
  const roots = resolveSchedulePluginRoots(config.root, options);
@@ -5693,6 +8046,7 @@ function hubSchedule(options = {}) {
5693
8046
  const definitions = discoverRegistrySchedules();
5694
8047
  emitStandaloneProviderOutput = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options);
5695
8048
  standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
8049
+ const storage = processStorageOptions((name) => hasVitePlugin(config.plugins, name));
5696
8050
  if (config.command) {
5697
8051
  const nitro = await createScheduleNitroConfig({
5698
8052
  ...options,
@@ -5700,7 +8054,8 @@ function hubSchedule(options = {}) {
5700
8054
  contributions,
5701
8055
  nitro: config.nitro,
5702
8056
  nitroOwnsPaths: hasNitroConfigContext(config),
5703
- ...leaseDatabaseImport(config.plugins),
8057
+ ...storage,
8058
+ hints: config,
5704
8059
  root: config.root,
5705
8060
  serverDirs
5706
8061
  });
@@ -5708,7 +8063,10 @@ function hubSchedule(options = {}) {
5708
8063
  const configWithNitro = config;
5709
8064
  configWithNitro.nitro = nitro;
5710
8065
  }
5711
- }
8066
+ } else if (command === "build" && typeof Reflect.get(config, "__vitehubNuxtHints") === "function" && options.runtime && !storage.leaseDatabaseImport) reportViteHubHint({
8067
+ ...config,
8068
+ command
8069
+ }, scheduleErrorDiagnostics.SCHEDULE_PROCESS_CLAIMS_IN_MEMORY());
5712
8070
  },
5713
8071
  configEnvironment(name, config) {
5714
8072
  if (!isServerEnvironment(name, config)) return;
@@ -5845,7 +8203,10 @@ function hubSchedule(options = {}) {
5845
8203
  inspectable.vitehub = {
5846
8204
  durability: () => options.runtime?.driver === "process" ? [{
5847
8205
  export: "scheduleDurability",
5848
- input: { driver: "process" },
8206
+ input: {
8207
+ driver: "process",
8208
+ leases: leaseDatabase
8209
+ },
5849
8210
  module: durabilityModuleFile(import.meta.url),
5850
8211
  primitive: "schedule"
5851
8212
  }] : [],
@@ -5854,21 +8215,33 @@ function hubSchedule(options = {}) {
5854
8215
  load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).scheduleOperations,
5855
8216
  module: ownModule(import.meta.url, "operations")
5856
8217
  }],
5857
- inspect: () => ({ definitions: [{
5858
- kind: "schedule",
5859
- label: "Schedules",
5860
- list: () => {
5861
- const roots = resolveSchedulePluginRoots(viteRoot ?? process.cwd(), options);
5862
- return inspectScheduleDefinitions({
5863
- cron: options.cron,
5864
- plugins: resolved?.plugins,
5865
- projectRoot: roots.projectRoot,
5866
- rootDir: roots.viteRoot,
5867
- serverDirs,
5868
- 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
5869
8242
  });
5870
8243
  }
5871
- }] })
8244
+ })
5872
8245
  };
5873
8246
  return inspectable;
5874
8247
  }