@vite-hub/kv 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 (50) hide show
  1. package/README.md +19 -13
  2. package/dist/{cli-DpPhz_Ek.d.ts → cli-CLomw9ml.d.ts} +1 -0
  3. package/dist/cli.d.ts +1 -1
  4. package/dist/cli.js +24 -12
  5. package/dist/{cloudflare-env-lOtHHsgP.js → cloudflare-env-Dl349h_9.js} +2 -1
  6. package/dist/{cloudflare-kv-BIEUFzRT.js → cloudflare-kv-DQJhmGof.js} +22 -10
  7. package/dist/{cloudflare-kv-local-BBw3ZT1K.js → cloudflare-kv-local-COjgHweC.js} +3 -7
  8. package/dist/{config-BXEVoZE3.js → config-pfyPiPrI.js} +65 -28
  9. package/dist/{create-storage-BGsrQKw3.js → create-storage-DQ1BbFqH.js} +5 -5
  10. package/dist/{cursor-history-BqIQePNP.js → cursor-history-CAT4mpP1.js} +7 -3
  11. package/dist/{deno-kv-BM9mYdUp.js → deno-kv-Cf0ZveeN.js} +43 -7
  12. package/dist/driver-Du6Eh9p2.d.ts +47 -0
  13. package/dist/{error-diagnostics-BxqvtEIb.js → error-diagnostics-C4VTHInS.js} +16 -4
  14. package/dist/errors-BpiM-Vmh.js +125 -0
  15. package/dist/errors.d.ts +13 -1
  16. package/dist/errors.js +2 -2
  17. package/dist/{fs-lite-BLZId9_P.js → fs-lite-BTcBUP6B.js} +1 -1
  18. package/dist/fs-lite-C8yXCVDM.js +2 -0
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.js +39 -52
  21. package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-CI2PJGqu.d.ts} +13 -2
  22. package/dist/{operations-Ch-gKaey.js → operations-CqKs7Ykc.js} +24 -45
  23. package/dist/{operations-B-WZ7P1h.js → operations-nAaONxzh.js} +273 -231
  24. package/dist/operations.d.ts +2 -2
  25. package/dist/operations.js +4 -3
  26. package/dist/out-BbXG-yVX.js +21755 -0
  27. package/dist/{redis-shared-E5mahECF.js → redis-shared-1M0IaguQ.js} +1 -1
  28. package/dist/request-log-Dj9Vw7qG.js +105 -0
  29. package/dist/{results-p7nPCnaJ.js → results-D6jfPtCk.js} +0 -1
  30. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  31. package/dist/runtime/cloudflare-kv.js +1 -1
  32. package/dist/runtime/cloudflare-request-env.js +1 -1
  33. package/dist/runtime/database.d.ts +2 -0
  34. package/dist/{database-72Jk3VVk.js → runtime/database.js} +68 -37
  35. package/dist/runtime/nitro-plugin.js +12 -5
  36. package/dist/runtime/redis-driver.d.ts +2 -2
  37. package/dist/runtime/redis-driver.js +2 -5
  38. package/dist/runtime/unstorage-driver.js +6 -2
  39. package/dist/runtime/upstash-driver.d.ts +2 -2
  40. package/dist/runtime/upstash-driver.js +2 -6
  41. package/dist/{types-DEiKew_3.d.ts → types-Cp6IBhSN.d.ts} +36 -37
  42. package/dist/{upstash-DDlqTttY.js → upstash-5sTbIR35.js} +2 -2
  43. package/dist/virtual-module.d.ts +1 -0
  44. package/dist/vite.d.ts +21 -6
  45. package/dist/vite.js +2738 -415
  46. package/package.json +10 -5
  47. package/dist/driver-BwxgaQ-f.d.ts +0 -15
  48. package/dist/errors-DbwufFZp.js +0 -60
  49. package/dist/fs-lite-RAoxu8L0.js +0 -2
  50. package/dist/main-F3Y22_uV.js +0 -2353
package/dist/vite.js CHANGED
@@ -1,18 +1,19 @@
1
1
  import { r as __toESM } from "./rolldown-runtime-CMFfr-1z.js";
2
2
  import { a as resolve$1, i as relative$1, n as relativeDefinitionFile, r as dirname$1 } from "./inspect-BIKQsqX4.js";
3
+ import { C as resolveViteHubProjectRoot, N as writeViteHubDevServerFile, P as internalErrorDiagnostics, S as markViteConfigPlugin, b as hasNitroConfigContext, j as removeViteHubDevServerFile, k as readViteHubDevServerFile, p as operationRpcPath, r as collectOperationContributions, v as VITEHUB_PROJECT_ROOT, w as shouldSkipViteProviderBuild, x as isServerEnvironment, y as createNoExternalAddition } from "./operations-nAaONxzh.js";
3
4
  import { n as isRecordOrFunction, t as isRecord } from "./object-Da1zyPCR.js";
4
- import { A as writeViteHubDevServerFile, E as readViteHubDevServerFile, O as removeViteHubDevServerFile, _ as createNoExternalAddition, b as resolveViteHubProjectRoot, g as internalErrorDiagnostics, p as operationRpcPath, r as collectOperationContributions, v as hasNitroConfigContext, x as shouldSkipViteProviderBuild, y as isServerEnvironment } from "./operations-B-WZ7P1h.js";
5
5
  import { n as invariantError, t as invariant } from "./invariant-DolT9EEx.js";
6
- import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
7
- import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, n as kvRedisEnvWarning, o as resolveHostPreset, r as normalizeKVOptions } from "./config-BXEVoZE3.js";
8
- import { n as resolveUpstashRuntimeValues } from "./upstash-DDlqTttY.js";
6
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C4VTHInS.js";
7
+ import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, n as kvRedisEnvHint, o as resolveHostPreset, r as normalizeKVOptions } from "./config-pfyPiPrI.js";
8
+ import { n as resolveUpstashRuntimeValues } from "./upstash-5sTbIR35.js";
9
9
  import { t as addViteHubDevPeerDevHandler } from "./dev-peer-CHafxbtj.js";
10
- import "node:module";
11
- import { copyFile, cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
10
+ import { createRequire, isBuiltin } from "node:module";
11
+ import { access, copyFile, cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
12
12
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
13
- import { existsSync, readFileSync, renameSync, rmSync } from "node:fs";
13
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
14
+ import { formatDiagnostic } from "nostics";
14
15
  import { tmpdir } from "node:os";
15
- import { fileURLToPath } from "node:url";
16
+ import { fileURLToPath, pathToFileURL } from "node:url";
16
17
  import { createHash } from "node:crypto";
17
18
  //#region ../internal/src/build/paths.ts
18
19
  function resolveRuntimeModule(packageDir, modulePath) {
@@ -49,8 +50,15 @@ async function writeFileIfChanged(file, contents) {
49
50
  await mkdir(resolve$1(file, ".."), { recursive: true });
50
51
  await writeFile(file, contents, "utf8");
51
52
  }
52
- //#endregion
53
- //#region ../internal/src/nitro-kit.ts
53
+ Object.freeze({ vitehubAuthAccess: "handler" });
54
+ /**
55
+ * The route meta of a generated handler that checks access on every request, even when the app adds no rule: a required
56
+ * `authorize` policy, an explicit `access` rule, a required access token, or a signature. Auth access routes still apply
57
+ * to it, so an app rule stays in force. `checksOwnAccess(event)` of `vite-hub/auth` reads it, so app middleware can skip
58
+ * the route. A route that can run without a check, such as a browser error sink, an optional `authorize`, or a webhook
59
+ * with `secret: false`, must not use it.
60
+ */
61
+ const ownAccessRouteMeta = Object.freeze({ vitehubOwnAccess: true });
54
62
  function cloneArray(value) {
55
63
  return Array.isArray(value) ? [...value] : [];
56
64
  }
@@ -166,6 +174,7 @@ async function installStandaloneOperationRpc(config, command, module) {
166
174
  const kit = createNitroServerKit(Reflect.get(config, "nitro"));
167
175
  kit.addHandler({
168
176
  handler,
177
+ meta: { ...ownAccessRouteMeta },
169
178
  route: operationRpcPath
170
179
  });
171
180
  const devHandlers = kit.config.devHandlers;
@@ -193,10 +202,9 @@ function resolveKVViteConfig(kv, input = {}) {
193
202
  return {
194
203
  hosting,
195
204
  kv: normalizeKVOptions(kv, {
196
- dev: input.dev,
205
+ ...input,
197
206
  env,
198
- hosting,
199
- postgresDatabase: input.postgresDatabase
207
+ hosting
200
208
  }) ?? false
201
209
  };
202
210
  }
@@ -414,20 +422,76 @@ function resolveViteHubBundleDefines(config) {
414
422
  return defines;
415
423
  }
416
424
  //#endregion
417
- //#region ../internal/src/build/esbuild.ts
418
- const viteRawNamespace = "vitehub-vite-raw";
419
- 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:";
420
452
  const markdownTemplateFileSuffix = ".template.md";
421
453
  const markdownTemplateModuleQuery = "markdown-template";
422
454
  const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
423
455
  const skipResolvedAlias = "vitehubSkipResolvedAlias";
456
+ const resolvingViteAlias = "vitehubResolvingAlias";
424
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
+ }
425
472
  function normalizePathSeparators(path) {
426
473
  return path.replaceAll("\\", "/");
427
474
  }
428
475
  function escapeRegExp(value) {
429
476
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
430
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
+ }
431
495
  function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
432
496
  if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
433
497
  if (!Array.isArray(exportsValue) && !isRecord(exportsValue)) return [];
@@ -454,7 +518,23 @@ function collectPackageExportCandidates(packageName, exportsValue, packageRelati
454
518
  }
455
519
  return candidates;
456
520
  }
457
- 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) {
458
538
  const entries = Object.entries(aliases || {});
459
539
  if (!entries.length) return;
460
540
  const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
@@ -474,391 +554,2204 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackage
474
554
  specifier: `${resolvedSpecifier}${prefix && !resolvedSpecifier.endsWith("/") ? "/" : ""}`
475
555
  };
476
556
  }));
557
+ const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
477
558
  return {
478
559
  name: "vitehub-resolved-alias",
479
- setup(build) {
480
- const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
481
- build.onResolve({ filter: /.*/ }, async (args) => {
482
- if (args.pluginData?.[skipResolvedAlias]) return;
483
- const resolveWithContext = (specifier) => build.resolve(specifier, {
484
- importer: args.importer,
485
- kind: args.kind,
486
- namespace: args.namespace,
487
- pluginData: {
488
- ...args.pluginData,
489
- [skipResolvedAlias]: true
490
- },
491
- resolveDir: args.resolveDir,
492
- with: args.with
493
- });
494
- const aliases = await resolvedEntries;
495
- let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
496
- let matchedAlias = match?.specifier;
497
- let matchedSpecifier = match ? args.path : void 0;
498
- let specifier = args.resolveDir && /^\.\.?[\\/]/.test(args.path) ? resolve(args.resolveDir, args.path) : args.path;
499
- let normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
500
- let canonicalSpecifier = normalizedSpecifier;
501
- const canonicalizeSpecifier = async () => {
502
- canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
503
- return canonicalSpecifier;
504
- };
505
- match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
506
- if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
507
- await canonicalizeSpecifier();
508
- match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
509
- }
510
- if (!match && (resolveEntryPackageAliases || args.kind !== "entry-point") && isAbsolute(args.path)) {
511
- const candidates = [];
512
- for (const alias of aliases) {
513
- if (isAbsolute(alias.specifier)) continue;
514
- const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
515
- const aliasSegments = packageAlias.split("/");
516
- if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
517
- let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
518
- if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
519
- const scopeMarker = `/node_modules/${packageAlias}/`;
520
- const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
521
- const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
522
- if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
523
- }
524
- const packageMarker = `/node_modules/${packageName}/`;
525
- const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
526
- const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
527
- const cacheKey = [
528
- alias.specifier,
529
- alias.prefix,
530
- resolutionScope,
531
- normalizedSpecifier,
532
- args.importer,
533
- args.resolveDir,
534
- args.kind,
535
- args.namespace,
536
- JSON.stringify(args.with)
537
- ].join("\0");
538
- let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
539
- if (!resolution) {
540
- resolution = (async () => {
541
- let resolvedAliasPath;
542
- if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
543
- else if (resolutionScope) {
544
- const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
545
- const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
546
- if (!isRecord(parsedPackageJson)) return;
547
- const packageJson = parsedPackageJson;
548
- if (packageJson.exports === void 0 && !alias.prefix) {
549
- const resolvedCandidate = await resolveWithContext(alias.specifier);
550
- if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
551
- canonical: alias.specifier,
552
- normalized: alias.specifier,
553
- publicSpecifier: alias.specifier
554
- };
555
- return;
556
- }
557
- const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
558
- for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
559
- const resolvedCandidate = await resolveWithContext(publicSpecifier);
560
- if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
561
- if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
562
- matchingPublicSpecifiers.add(publicSpecifier);
563
- }
564
- if (matchingPublicSpecifiers.size === 1) {
565
- const publicSpecifier = [...matchingPublicSpecifiers][0];
566
- if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
567
- canonical: publicSpecifier,
568
- normalized: publicSpecifier,
569
- publicSpecifier
570
- };
571
- }
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(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
+ };
572
631
  return;
573
- } else {
574
- const resolvedAlias = await resolveWithContext(alias.specifier);
575
- if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
576
- resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
577
632
  }
578
- const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
579
- return {
580
- canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
581
- normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
582
- };
583
- })();
584
- if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
585
- }
586
- candidates.push({
587
- alias,
588
- resolution
589
- });
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);
590
661
  }
591
- await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
592
- for (const { alias, resolution } of candidates) {
593
- const paths = await resolution;
594
- if (!paths) continue;
595
- if (paths.publicSpecifier) {
596
- match = alias;
597
- matchedAlias = alias.specifier;
598
- matchedSpecifier = paths.publicSpecifier;
599
- break;
600
- }
601
- const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
602
- let canonicalMatch = false;
603
- if (!normalizedMatch && paths.canonical !== paths.normalized) {
604
- await canonicalizeSpecifier();
605
- canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
606
- }
607
- if (normalizedMatch || canonicalMatch) {
608
- match = alias;
609
- matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
610
- matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
611
- break;
612
- }
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;
613
688
  }
614
689
  }
615
- matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
616
- matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
617
- if (!match) return;
618
- const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
619
- if (!target) return;
620
- return resolveWithContext(/^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target);
621
- });
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;
622
700
  }
623
701
  };
624
702
  }
625
- function createViteAliasPlugin(aliases) {
703
+ function createViteAliasPlugin(aliases, workingDir) {
626
704
  if (!Array.isArray(aliases)) return;
627
- const resolvingAlias = "vitehubResolvingAlias";
628
705
  return {
629
706
  name: "vitehub-vite-alias",
630
- setup(build) {
631
- build.onResolve({ filter: /.*/ }, async (args) => {
632
- if (args.pluginData?.[resolvingAlias]) return;
633
- const alias = aliases.find(({ find }) => {
634
- if (typeof find === "string") return args.path === find || args.path.startsWith(`${find}/`);
635
- find.lastIndex = 0;
636
- return find.test(args.path);
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);
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;
726
+ }
727
+ };
728
+ }
729
+ function parseMarkdownTemplateRequest(id) {
730
+ if (id.includes("#")) return;
731
+ const queryIndex = id.indexOf("?");
732
+ const path = id.split("?", 1)[0];
733
+ if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
734
+ if (id.slice(queryIndex + 1) !== markdownTemplateModuleQuery) return;
735
+ return { path };
736
+ }
737
+ function renderMarkdownTemplateModule(template) {
738
+ return [
739
+ `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
740
+ `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
741
+ "export default function render(data = {}) {",
742
+ " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data })",
743
+ "}",
744
+ ""
745
+ ].join("\n");
746
+ }
747
+ function hasViteRawQuery(path) {
748
+ const queryIndex = path.indexOf("?");
749
+ return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
750
+ }
751
+ async function resolveViteRawSpecifier(path, rootDir) {
752
+ if (path.startsWith("/@fs/")) return path.slice(5);
753
+ if (!rootDir || !path.startsWith("/")) return path;
754
+ const rootRelativePath = path.slice(1);
755
+ const publicPath = resolve(rootDir, "public", rootRelativePath);
756
+ try {
757
+ await stat(publicPath);
758
+ return publicPath;
759
+ } catch (error) {
760
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
761
+ return resolve(rootDir, rootRelativePath);
762
+ }
763
+ }
764
+ function createViteRawPlugin(rootDir, frameworkRuntime, workingDir) {
765
+ return {
766
+ name: "vitehub-vite-raw",
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
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
828
+ });
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"
637
909
  });
638
- if (!alias) return;
639
- if (alias.customResolver) return { errors: [{ text: `[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(args.path)} because it uses customResolver.` }] };
640
- if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
641
- const replacement = typeof alias.find === "string" ? `${alias.replacement}${args.path.slice(alias.find.length)}` : args.path.replace(alias.find, alias.replacement);
642
- const result = await build.resolve(replacement, {
643
- importer: args.importer,
644
- kind: args.kind,
645
- namespace: args.namespace,
646
- pluginData: Object.assign({}, args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {}, { [resolvingAlias]: true }),
647
- resolveDir: args.resolveDir,
648
- with: args.with
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
+ });
649
921
  });
650
- const pluginData = Object.assign({}, result.pluginData);
651
- Reflect.deleteProperty(pluginData, resolvingAlias);
652
- return {
653
- ...result,
654
- pluginData
655
- };
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).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;
656
2526
  });
2527
+ pp.forEach((p, i) => {
2528
+ const next = pp[i + 1];
2529
+ const prev = pp[i - 1];
2530
+ if (p !== GLOBSTAR || prev === GLOBSTAR) return;
2531
+ if (prev === void 0) {
2532
+ if (next !== void 0 && next !== GLOBSTAR) pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
2533
+ else pp[i] = twoStar;
2534
+ } else if (next === void 0) pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + ")?";
2535
+ else if (next !== GLOBSTAR) {
2536
+ pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
2537
+ pp[i + 1] = GLOBSTAR;
2538
+ }
2539
+ });
2540
+ const filtered = pp.filter((p) => p !== GLOBSTAR);
2541
+ if (this.partial && filtered.length >= 1) {
2542
+ const prefixes = [];
2543
+ for (let i = 1; i <= filtered.length; i++) prefixes.push(filtered.slice(0, i).join("/"));
2544
+ return "(?:" + prefixes.join("|") + ")";
2545
+ }
2546
+ return filtered.join("/");
2547
+ }).join("|");
2548
+ const [open, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];
2549
+ re = "^" + open + re + close + "$";
2550
+ if (this.partial) re = "^(?:\\/|" + open + re.slice(1, -1) + close + ")$";
2551
+ if (this.negate) re = "^(?!" + re + ").+$";
2552
+ try {
2553
+ this.regexp = new RegExp(re, [...flags].join(""));
2554
+ } catch {
2555
+ this.regexp = false;
657
2556
  }
658
- };
659
- }
660
- function parseMarkdownTemplateRequest(id) {
661
- if (id.includes("#")) return;
662
- const queryIndex = id.indexOf("?");
663
- const path = id.split("?", 1)[0];
664
- if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
665
- if (id.slice(queryIndex + 1) !== markdownTemplateModuleQuery) return;
666
- return { path };
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");
667
2612
  }
668
- function renderMarkdownTemplateModule(template) {
669
- return [
670
- `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
671
- `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
672
- "export default function render(data = {}) {",
673
- " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data })",
674
- "}",
675
- ""
676
- ].join("\n");
2613
+ function isNestedPath(path) {
2614
+ return Boolean(path) && path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path);
677
2615
  }
678
- function hasViteRawQuery(path) {
679
- const queryIndex = path.indexOf("?");
680
- return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
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
+ }
681
2625
  }
682
- async function resolveViteRawSpecifier(path, rootDir) {
683
- if (path.startsWith("/@fs/")) return path.slice(5);
684
- if (!rootDir || !path.startsWith("/")) return path;
685
- const rootRelativePath = path.slice(1);
686
- const publicPath = resolve(rootDir, "public", rootRelativePath);
2626
+ function readIfPresent(read) {
687
2627
  try {
688
- await stat(publicPath);
689
- return publicPath;
2628
+ return read();
690
2629
  } catch (error) {
691
- if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
692
- return resolve(rootDir, rootRelativePath);
2630
+ if (error.code === "ENOENT") return void 0;
2631
+ throw error;
693
2632
  }
694
2633
  }
695
- function createViteRawPlugin(rootDir, frameworkRuntime) {
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
+ });
696
2643
  return {
697
- name: "vitehub-vite-raw",
698
- setup(build) {
699
- build.onResolve({
700
- filter: /^@vite-hub\/markdown-template$/,
701
- namespace: viteMarkdownTemplateNamespace
702
- }, async (args) => {
703
- if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
704
- return build.resolve("vite-hub/markdown-template", {
705
- importer: args.importer,
706
- kind: args.kind,
707
- resolveDir: args.resolveDir
708
- });
709
- });
710
- build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
711
- if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
712
- const markdownTemplate = parseMarkdownTemplateRequest(args.path);
713
- const raw = hasViteRawQuery(args.path);
714
- if (!markdownTemplate && !raw) return;
715
- const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
716
- let pluginData = args.pluginData;
717
- if (markdownTemplate) pluginData = {
718
- ...args.pluginData,
719
- [skipMarkdownTemplateResolve]: true
720
- };
721
- const resolved = await build.resolve(specifier, {
722
- importer: args.importer,
723
- kind: args.kind,
724
- namespace: args.namespace,
725
- pluginData,
726
- resolveDir: args.resolveDir,
727
- with: args.with
728
- });
729
- if (resolved.errors.length) return {
730
- errors: resolved.errors,
731
- warnings: resolved.warnings
732
- };
733
- if (resolved.external) return {
734
- external: true,
735
- namespace: resolved.namespace,
736
- path: resolved.path,
737
- pluginData: resolved.pluginData,
738
- sideEffects: resolved.sideEffects,
739
- suffix: resolved.suffix,
740
- warnings: resolved.warnings
741
- };
742
- if (resolved.namespace !== "file") return {
743
- 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.` }],
744
- warnings: resolved.warnings
745
- };
746
- return {
747
- namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
748
- path: resolved.path,
749
- pluginData: resolved.pluginData,
750
- sideEffects: resolved.sideEffects,
751
- suffix: resolved.suffix,
752
- warnings: resolved.warnings
753
- };
754
- });
755
- build.onLoad({
756
- filter: /.*/,
757
- namespace: viteRawNamespace
758
- }, async (args) => ({
759
- contents: await readFile(args.path),
760
- loader: "text"
761
- }));
762
- build.onLoad({
763
- filter: /.*/,
764
- namespace: viteMarkdownTemplateNamespace
765
- }, async (args) => ({
766
- contents: renderMarkdownTemplateModule(await readFile(args.path, "utf8")),
767
- loader: "js",
768
- resolveDir: dirname(args.path)
769
- }));
770
- }
2644
+ include,
2645
+ matches: (path, partial = false) => matcher.match(path, partial) || matcher.match(`/${path}`, partial)
771
2646
  };
772
2647
  }
773
- function createFileUrlPlugin() {
774
- return {
775
- name: "vitehub-file-url",
776
- setup(build) {
777
- build.onResolve({ filter: /^file:/ }, (args) => ({ path: fileURLToPath(args.path) }));
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
+ }
778
2715
  }
779
2716
  };
780
- }
781
- /**
782
- * Copies a `.wasm?module` import next to the bundle and keeps it as a relative `.wasm` import. Wrangler and Nitro load
783
- * such an import as a compiled WebAssembly module, which Workers need because they can't compile WebAssembly bytes.
784
- */
785
- function createWasmModulePlugin(outdir) {
2717
+ visit("", [], []);
786
2718
  return {
787
- name: "vitehub-wasm-module",
788
- setup(build) {
789
- build.onResolve({ filter: /\.wasm\?module$/ }, async (args) => {
790
- const resolved = await build.resolve(args.path.slice(0, -7), {
791
- importer: args.importer,
792
- kind: args.kind,
793
- resolveDir: args.resolveDir
794
- });
795
- if (resolved.errors.length) return { errors: resolved.errors };
796
- const bytes = await readFile(resolved.path);
797
- const name = `${basename(resolved.path, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
798
- await mkdir(outdir, { recursive: true });
799
- await copyFile(resolved.path, join(outdir, name));
800
- return {
801
- external: true,
802
- path: `./${name}`
803
- };
804
- });
805
- }
2719
+ files,
2720
+ entries
806
2721
  };
807
2722
  }
808
- async function bundleEsmEntry(entryFile, outfile, options = {}) {
809
- const { build: bundle } = await import("./main-F3Y22_uV.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1));
810
- options.signal?.throwIfAborted();
811
- const format = options.format || "esm";
812
- const platform = options.platform || "neutral";
813
- const viteAliasPlugin = createViteAliasPlugin(options.alias);
814
- 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/"));
815
- const plugins = [];
816
- const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), options.resolveEntryPackageAliases);
817
- if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
818
- plugins.push(...options.plugins ?? [], createFileUrlPlugin());
819
- if (viteAliasPlugin) plugins.push(viteAliasPlugin);
820
- plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
821
- if (platform !== "node") plugins.unshift(createWasmModulePlugin(dirname(outfile)));
822
- const result = await bundle({
823
- absWorkingDir: options.workingDir,
824
- banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
825
- "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
826
- " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
827
- " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
828
- " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
829
- "}"
830
- ] : []].filter(Boolean).join("\n") } : void 0,
831
- bundle: true,
832
- conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
833
- define: options.define,
834
- entryPoints: [entryFile],
835
- external: options.external,
836
- format,
837
- keepNames: options.minifySyntax || options.minifyIdentifiers,
838
- loader: platform === "node" ? { ".wasm": "binary" } : void 0,
839
- logLevel: "silent",
840
- mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
841
- resolveExtensions: options.extensions,
842
- minifyIdentifiers: options.minifyIdentifiers,
843
- minifySyntax: options.minifySyntax,
844
- minifyWhitespace: options.minifyWhitespace,
845
- outfile,
846
- packages: options.packages,
847
- platform,
848
- preserveSymlinks: options.preserveSymlinks,
849
- plugins,
850
- sourcemap: false,
851
- target: "es2022",
852
- write: options.signal ? false : true
853
- });
854
- options.signal?.throwIfAborted();
855
- if (options.signal) {
856
- await Promise.all((result.outputFiles ?? []).map(async (output) => {
857
- await mkdir(dirname(output.path), { recursive: true });
858
- options.signal.throwIfAborted();
859
- await writeFile(output.path, output.contents, { signal: options.signal });
860
- }));
861
- options.signal.throwIfAborted();
2723
+ /** Copies a file or folder and follows links. `node_modules` folders and paths that disappear during the copy are skipped. */
2724
+ async function copyTree(source, target) {
2725
+ const info = await unlessGone(() => stat(source));
2726
+ if (!info) return;
2727
+ if (!info.isDirectory()) {
2728
+ await unlessGone(() => copyFile(source, target));
2729
+ return;
2730
+ }
2731
+ const entries = await unlessGone(() => readdir(source));
2732
+ if (!entries) return;
2733
+ await mkdir(target, { recursive: true });
2734
+ for (const entry of entries) if (entry !== "node_modules") await copyTree(join(source, entry), join(target, entry));
2735
+ }
2736
+ /**
2737
+ * Copies one runtime package into deployment output, without its `node_modules`.
2738
+ *
2739
+ * An installed package only holds its published files. A linked workspace package, such as a `link:` or `workspace:`
2740
+ * dependency, is a whole source folder with tests and fixtures, so only the files that `npm publish` would ship are
2741
+ * copied. A path that disappears during the copy, such as a temporary test folder that another process removes, is
2742
+ * skipped instead of failing the build.
2743
+ */
2744
+ async function copyRuntimePackageFiles(packageDir, targetDir) {
2745
+ const paths = hasNodeModulesSegment$1(packageDir) ? void 0 : publishedPackagePaths(packageDir);
2746
+ if (!paths) {
2747
+ await copyTree(packageDir, targetDir);
2748
+ return;
2749
+ }
2750
+ await mkdir(targetDir, { recursive: true });
2751
+ for (const path of paths.files) {
2752
+ const target = join(targetDir, path);
2753
+ await mkdir(dirname(target), { recursive: true });
2754
+ await unlessGone(() => copyFile(join(packageDir, path), target));
862
2755
  }
863
2756
  }
864
2757
  //#endregion
@@ -874,6 +2767,9 @@ async function removeProviderOutputArtifactDir(path) {
874
2767
  }
875
2768
  //#endregion
876
2769
  //#region ../internal/src/build/vercel-config.ts
2770
+ function createDefaultVercelOutputRoot(rootDir) {
2771
+ return resolve(rootDir, ".vercel", "output");
2772
+ }
877
2773
  function createVercelConfigJson() {
878
2774
  return {
879
2775
  routes: [{ handle: "filesystem" }, {
@@ -887,13 +2783,318 @@ function createNodeFunctionConfig(extra = {}) {
887
2783
  return {
888
2784
  handler: "index.mjs",
889
2785
  launcherType: "Nodejs",
890
- runtime: "nodejs22.x",
2786
+ runtime: "nodejs24.x",
891
2787
  shouldAddHelpers: false,
892
2788
  supportsResponseStreaming: true,
893
2789
  ...extra
894
2790
  };
895
2791
  }
896
2792
  //#endregion
2793
+ //#region ../internal/src/build/runtime-package-resolution.ts
2794
+ /** Locates package metadata through exports, an entry's ancestors, or the project's dependency roots. */
2795
+ function createRuntimePackageResolver(readPackageName) {
2796
+ return async (name, resolver, fromDir) => {
2797
+ try {
2798
+ return resolver.resolve(`${name}/package.json`);
2799
+ } catch (error) {
2800
+ if (!isPackageResolutionMiss(error)) throw error;
2801
+ }
2802
+ try {
2803
+ let current = dirname(resolver.resolve(name));
2804
+ while (current !== dirname(current)) {
2805
+ const candidate = join(current, "package.json");
2806
+ try {
2807
+ await access(candidate);
2808
+ if (readPackageName(await readFile(candidate, "utf8"), candidate) === name) return candidate;
2809
+ } catch (error) {
2810
+ if (error.code !== "ENOENT") throw error;
2811
+ }
2812
+ current = dirname(current);
2813
+ }
2814
+ } catch (error) {
2815
+ if (!isPackageResolutionMiss(error)) throw error;
2816
+ }
2817
+ let current = fromDir;
2818
+ while (current !== dirname(current)) {
2819
+ const candidate = join(current, "node_modules", ...name.split("/"), "package.json");
2820
+ try {
2821
+ await access(candidate);
2822
+ return candidate;
2823
+ } catch (error) {
2824
+ if (error.code !== "ENOENT") throw error;
2825
+ }
2826
+ current = dirname(current);
2827
+ }
2828
+ };
2829
+ }
2830
+ function isPackageResolutionMiss(error) {
2831
+ const code = error?.code;
2832
+ return code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED";
2833
+ }
2834
+ //#endregion
2835
+ //#region ../internal/src/build/runtime-package-directory.ts
2836
+ /** Update a staged copy, then publish it with rollback on failure or cancellation. */
2837
+ async function updateRuntimePackageDirectory(options) {
2838
+ const stagingRoot = await mkdtemp(join(dirname(options.directory), ".vitehub-runtime-packages-"));
2839
+ const stagedDirectory = join(stagingRoot, "node_modules");
2840
+ const previousDirectory = join(stagingRoot, "previous-node_modules");
2841
+ let movedPreviousOutput = false;
2842
+ let installedReplacement = false;
2843
+ let cleanupStagingRoot = true;
2844
+ try {
2845
+ try {
2846
+ await cp(options.directory, stagedDirectory, { recursive: true });
2847
+ } catch (error) {
2848
+ if (error.code !== "ENOENT") throw error;
2849
+ }
2850
+ await mkdir(stagedDirectory, { recursive: true });
2851
+ await options.update(stagedDirectory);
2852
+ options.signal?.throwIfAborted();
2853
+ try {
2854
+ await rename(options.directory, previousDirectory);
2855
+ movedPreviousOutput = true;
2856
+ cleanupStagingRoot = false;
2857
+ } catch (error) {
2858
+ if (error.code !== "ENOENT") throw error;
2859
+ }
2860
+ try {
2861
+ options.signal?.throwIfAborted();
2862
+ await rename(stagedDirectory, options.directory);
2863
+ installedReplacement = true;
2864
+ options.signal?.throwIfAborted();
2865
+ cleanupStagingRoot = true;
2866
+ } catch (error) {
2867
+ if (installedReplacement) await rm(options.directory, {
2868
+ force: true,
2869
+ recursive: true
2870
+ });
2871
+ if (movedPreviousOutput) await rename(previousDirectory, options.directory);
2872
+ cleanupStagingRoot = true;
2873
+ throw error;
2874
+ }
2875
+ } finally {
2876
+ if (cleanupStagingRoot) await rm(stagingRoot, {
2877
+ force: true,
2878
+ recursive: true
2879
+ });
2880
+ }
2881
+ }
2882
+ //#endregion
2883
+ //#region ../internal/src/build/vercel-runtime-packages.ts
2884
+ const runtimeExportConditions = /* @__PURE__ */ new Set([
2885
+ "default",
2886
+ "import",
2887
+ "module",
2888
+ "node",
2889
+ "node-addons",
2890
+ "require"
2891
+ ]);
2892
+ const resolvePackageJson = createRuntimePackageResolver((source, path) => parsePackageJson(JSON.parse(source), path).name);
2893
+ let nodeFileTracePromise;
2894
+ /** Collects the runtime packages that features add to Vercel functions, then traces and copies them once per function. */
2895
+ function createVercelFunctionRuntimePackagesPass(beforeWrite) {
2896
+ const requests = [];
2897
+ return {
2898
+ add(request) {
2899
+ requests.push(request);
2900
+ },
2901
+ async copy(signal) {
2902
+ const functions = /* @__PURE__ */ new Map();
2903
+ for (const request of requests.splice(0)) {
2904
+ const outputRoot = request.outputRoot ?? createDefaultVercelOutputRoot(request.rootDir);
2905
+ const serverDir = resolve(outputRoot, "functions", request.serverFunctionName ?? "__server.func");
2906
+ const entry = functions.get(serverDir) ?? {
2907
+ requests: [],
2908
+ rootDir: request.rootDir
2909
+ };
2910
+ entry.requests.push(request);
2911
+ functions.set(serverDir, entry);
2912
+ }
2913
+ for (const [serverDir, entry] of functions) await copyFunctionRuntimePackages(serverDir, entry.rootDir, entry.requests, signal, beforeWrite);
2914
+ }
2915
+ };
2916
+ }
2917
+ async function copyFunctionRuntimePackages(serverDir, rootDir, requests, signal, beforeWrite) {
2918
+ try {
2919
+ await access(serverDir);
2920
+ } catch (error) {
2921
+ if (error.code === "ENOENT") return;
2922
+ throw error;
2923
+ }
2924
+ const groups = [];
2925
+ for (const request of requests) {
2926
+ const requested = Array.isArray(request.packages) ? request.packages : await request.packages();
2927
+ if (requested.length) groups.push(requested.map((runtimePackage) => ({
2928
+ ...runtimePackage,
2929
+ resolveFrom: runtimePackage.resolveFrom ?? join(request.rootDir, "package.json")
2930
+ })));
2931
+ }
2932
+ if (!groups.length) return;
2933
+ const directory = resolve(serverDir, "node_modules");
2934
+ await beforeWrite?.(directory);
2935
+ await updateRuntimePackageDirectory({
2936
+ directory,
2937
+ signal,
2938
+ update: (outputNodeModules) => copyNodeRuntimePackageGroups(outputNodeModules, rootDir, groups)
2939
+ });
2940
+ }
2941
+ async function copyNodeRuntimePackageGroups(outputNodeModules, rootDir, groups) {
2942
+ const selected = /* @__PURE__ */ new Map();
2943
+ const requested = /* @__PURE__ */ new Map();
2944
+ for (const packages of groups) {
2945
+ const visited = /* @__PURE__ */ new Set();
2946
+ const expanded = /* @__PURE__ */ new Set();
2947
+ for (const runtimePackage of packages) {
2948
+ const resolveFrom = runtimePackage.resolveFrom ?? join(rootDir, "package.json");
2949
+ const resolver = createRequire(resolveFrom);
2950
+ const packageJsonPath = await selectRuntimePackage(runtimePackage.name, resolver, dirname(resolveFrom), selected, visited, expanded, runtimePackage);
2951
+ if (!packageJsonPath) continue;
2952
+ const previous = requested.get(runtimePackage.name);
2953
+ if (previous && previous !== packageJsonPath) throw internalErrorDiagnostics.INTERNAL_RUNTIME_PACKAGE_VERSION_CONFLICT({
2954
+ first: dirname(previous),
2955
+ name: runtimePackage.name,
2956
+ second: dirname(packageJsonPath)
2957
+ });
2958
+ requested.set(runtimePackage.name, packageJsonPath);
2959
+ }
2960
+ }
2961
+ for (const [name, { packageJson, packageJsonPath, resolver }] of selected) {
2962
+ const packageDir = dirname(packageJsonPath);
2963
+ const targetDir = join(outputNodeModules, ...name.split("/"));
2964
+ await rm(targetDir, {
2965
+ force: true,
2966
+ recursive: true
2967
+ });
2968
+ if (!await copyTracedPackageFiles(name, resolver, packageDir, packageJsonPath, packageJson, targetDir)) await copyRuntimePackageFiles(packageDir, targetDir);
2969
+ }
2970
+ }
2971
+ async function selectRuntimePackage(name, resolver, fromDir, selected, visited, expanded, options = { name }) {
2972
+ const packageJsonPath = await resolvePackageJson(name, resolver, fromDir);
2973
+ if (!packageJsonPath) {
2974
+ if (options.optional) return void 0;
2975
+ throw internalErrorDiagnostics.INTERNAL_B0046({ message: `Could not resolve package.json for ${name}.` });
2976
+ }
2977
+ const resolvedPackageJsonPath = await realpath(packageJsonPath);
2978
+ const packageDir = dirname(resolvedPackageJsonPath);
2979
+ const packageJson = parsePackageJson(JSON.parse(await readFile(resolvedPackageJsonPath, "utf8")), resolvedPackageJsonPath);
2980
+ const packageKey = `${name}\0${resolvedPackageJsonPath}`;
2981
+ if (!visited.has(packageKey)) {
2982
+ visited.add(packageKey);
2983
+ selected.set(name, {
2984
+ packageJson,
2985
+ packageJsonPath: resolvedPackageJsonPath,
2986
+ resolver
2987
+ });
2988
+ }
2989
+ const expansionKey = `${packageKey}\0${options.includePeerDependencies ? "peers" : "dependencies"}`;
2990
+ if (expanded.has(expansionKey)) return resolvedPackageJsonPath;
2991
+ expanded.add(expansionKey);
2992
+ const packageRequire = createRequire(resolvedPackageJsonPath);
2993
+ const dependencyNames = new Set(Object.keys(packageJson.dependencies || {}));
2994
+ const optionalDependencyNames = new Set(Object.keys(packageJson.optionalDependencies || {}));
2995
+ for (const dependencyName of optionalDependencyNames) dependencyNames.add(dependencyName);
2996
+ const requiredPeerDependencyNames = /* @__PURE__ */ new Set();
2997
+ if (options.includePeerDependencies) {
2998
+ for (const dependencyName of Object.keys(packageJson.peerDependencies || {})) if (!packageJson.peerDependenciesMeta?.[dependencyName]?.optional) {
2999
+ dependencyNames.add(dependencyName);
3000
+ requiredPeerDependencyNames.add(dependencyName);
3001
+ }
3002
+ }
3003
+ for (const dependencyName of dependencyNames) await selectRuntimePackage(dependencyName, packageRequire, packageDir, selected, visited, expanded, {
3004
+ includePeerDependencies: options.includePeerDependencies,
3005
+ name: dependencyName,
3006
+ optional: optionalDependencyNames.has(dependencyName) && !requiredPeerDependencyNames.has(dependencyName)
3007
+ });
3008
+ return resolvedPackageJsonPath;
3009
+ }
3010
+ async function copyTracedPackageFiles(name, resolver, packageDir, packageJsonPath, packageJson, targetDir) {
3011
+ const entries = await resolvePackageTraceEntries(name, resolver, packageDir, packageJson);
3012
+ if (!entries) return false;
3013
+ const { fileList } = await (await loadNodeFileTrace())([...entries], {
3014
+ base: packageDir,
3015
+ conditions: ["node"],
3016
+ exportsOnly: true,
3017
+ processCwd: packageDir
3018
+ });
3019
+ fileList.add(relative(packageDir, packageJsonPath));
3020
+ for (const file of fileList) {
3021
+ const source = resolve(packageDir, file);
3022
+ if (!isInsideDirectory(packageDir, source) || hasNodeModulesSegment(file)) continue;
3023
+ if (!(await stat(source)).isFile()) continue;
3024
+ const target = resolve(targetDir, file);
3025
+ await mkdir(dirname(target), { recursive: true });
3026
+ await copyFile(source, target);
3027
+ }
3028
+ return true;
3029
+ }
3030
+ async function loadNodeFileTrace() {
3031
+ nodeFileTracePromise ??= import("./out-BbXG-yVX.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1)).then(({ nodeFileTrace }) => nodeFileTrace);
3032
+ return nodeFileTracePromise;
3033
+ }
3034
+ async function resolvePackageTraceEntries(name, resolver, packageDir, packageJson) {
3035
+ const entryCandidates = /* @__PURE__ */ new Set();
3036
+ if (packageJson.exports) {
3037
+ const exportedTargets = collectRuntimeExportTargets(packageJson.exports);
3038
+ if (!exportedTargets) return void 0;
3039
+ for (const target of exportedTargets) entryCandidates.add(resolve(packageDir, target));
3040
+ } else {
3041
+ try {
3042
+ entryCandidates.add(resolver.resolve(name));
3043
+ } catch (error) {
3044
+ if (!isPackageResolutionMiss(error)) throw error;
3045
+ }
3046
+ if (packageJson.main) entryCandidates.add(resolve(packageDir, packageJson.main));
3047
+ if (packageJson.module) entryCandidates.add(resolve(packageDir, packageJson.module));
3048
+ entryCandidates.add(resolve(packageDir, "index.js"));
3049
+ }
3050
+ const entries = [];
3051
+ for (const candidate of entryCandidates) try {
3052
+ const candidateStat = await stat(candidate);
3053
+ if (candidateStat.isFile()) entries.push(candidate);
3054
+ else if (candidateStat.isDirectory()) return void 0;
3055
+ } catch (error) {
3056
+ if (error.code !== "ENOENT") throw error;
3057
+ }
3058
+ return entries.length ? entries : void 0;
3059
+ }
3060
+ function collectRuntimeExportTargets(exportsValue, condition) {
3061
+ if (typeof exportsValue === "string") {
3062
+ if (condition === "types") return /* @__PURE__ */ new Set();
3063
+ if (exportsValue.includes("*")) return void 0;
3064
+ return exportsValue.startsWith("./") ? /* @__PURE__ */ new Set([exportsValue]) : /* @__PURE__ */ new Set();
3065
+ }
3066
+ if (Array.isArray(exportsValue)) {
3067
+ const targets = /* @__PURE__ */ new Set();
3068
+ for (const entry of exportsValue) {
3069
+ const entryTargets = collectRuntimeExportTargets(entry, condition);
3070
+ if (!entryTargets) return void 0;
3071
+ for (const target of entryTargets) targets.add(target);
3072
+ }
3073
+ return targets;
3074
+ }
3075
+ if (typeof exportsValue !== "object" || exportsValue === null) return /* @__PURE__ */ new Set();
3076
+ const targets = /* @__PURE__ */ new Set();
3077
+ for (const [key, value] of Object.entries(exportsValue)) {
3078
+ if (key === "types") continue;
3079
+ if (!key.startsWith(".") && !runtimeExportConditions.has(key)) continue;
3080
+ const entryTargets = collectRuntimeExportTargets(value, key);
3081
+ if (!entryTargets) return void 0;
3082
+ for (const target of entryTargets) targets.add(target);
3083
+ }
3084
+ return targets;
3085
+ }
3086
+ function hasNodeModulesSegment(path) {
3087
+ return path.split(/[\\/]/).includes("node_modules");
3088
+ }
3089
+ function isInsideDirectory(parent, child) {
3090
+ const childRelativePath = relative(parent, child);
3091
+ return childRelativePath === "" || !childRelativePath.startsWith(`..${sep}`) && childRelativePath !== ".." && !isAbsolute(childRelativePath);
3092
+ }
3093
+ function parsePackageJson(value, path) {
3094
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw internalErrorDiagnostics.INTERNAL_B0047({ message: `Expected ${path} to contain a JSON object.` });
3095
+ return value;
3096
+ }
3097
+ //#endregion
897
3098
  //#region ../internal/src/build/provider-output-catalog.ts
898
3099
  var ProviderOutputCatalog = class {
899
3100
  bundleDefines = {};
@@ -1214,9 +3415,6 @@ async function writeProviderOutputOwnershipFiles(outputRoot, ownership, files) {
1214
3415
  await writeFile(file, `${JSON.stringify(values, null, 2)}\n`, "utf8");
1215
3416
  }));
1216
3417
  }
1217
- function createDefaultVercelOutputRoot(rootDir) {
1218
- return resolve(rootDir, ".vercel", "output");
1219
- }
1220
3418
  function createDefaultNetlifyOutputRoot(rootDir) {
1221
3419
  return resolve(rootDir, ".netlify", "v1");
1222
3420
  }
@@ -1233,10 +3431,26 @@ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
1233
3431
  assertNetlifyFunctionName(functionName);
1234
3432
  return resolve(functionsRoot, `${functionName}.mjs`);
1235
3433
  }
3434
+ async function declaresTopLevelBinding(code, name) {
3435
+ const { parseSync } = await import("vite");
3436
+ return parseSync("bundle.mjs", code).program.body.some((statement) => {
3437
+ const node = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
3438
+ if (node?.type === "FunctionDeclaration" || node?.type === "ClassDeclaration") return node.id?.name === name;
3439
+ return node?.type === "VariableDeclaration" && node.declarations.some((declaration) => declaration.id.type === "Identifier" && declaration.id.name === name);
3440
+ });
3441
+ }
1236
3442
  async function appendNetlifyFunctionConfig(outfile, config) {
1237
3443
  if (!config) return;
1238
3444
  const bundled = await readFile(outfile, "utf8");
1239
- await writeFile(outfile, `${bundled.trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
3445
+ const literal = stringifyProviderOutputConfig(config);
3446
+ let exported = `export const config = ${literal}`;
3447
+ if (await declaresTopLevelBinding(bundled, "config")) {
3448
+ const baseName = "vitehubNetlifyFunctionConfig";
3449
+ let name = baseName;
3450
+ for (let suffix = 2; bundled.includes(name); suffix++) name = `${baseName}${suffix}`;
3451
+ exported = `const ${name} = ${literal}\nexport { ${name} as config }`;
3452
+ }
3453
+ await writeFile(outfile, `${bundled.trimEnd()}\n\n${exported}\n`, "utf8");
1240
3454
  }
1241
3455
  async function writeCloudflareDeploymentOutput(options, signal) {
1242
3456
  signal?.throwIfAborted();
@@ -2041,9 +4255,11 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
2041
4255
  const write = withProviderDeploymentOutputRootLock(rootDir, async () => {
2042
4256
  await withProviderDeploymentOutputRootTransaction(rootDir, async (transaction) => {
2043
4257
  try {
4258
+ const vercelRuntimePackages = createVercelFunctionRuntimePackagesPass((nodeModules) => transaction.snapshot([nodeModules]));
2044
4259
  for (const contribution of rootContributions) {
2045
4260
  throwIfProviderOutputAborted(controller.signal);
2046
4261
  await contribution.write({
4262
+ addVercelRuntimePackages: (request) => vercelRuntimePackages.add(request),
2047
4263
  readCloudflareState: async (options) => await readCloudflareProviderDeploymentOutputState(rootDir, options),
2048
4264
  signal: controller.signal,
2049
4265
  write: async (writeOptions) => {
@@ -2059,6 +4275,8 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
2059
4275
  });
2060
4276
  throwIfProviderOutputAborted(controller.signal);
2061
4277
  }
4278
+ await vercelRuntimePackages.copy(controller.signal);
4279
+ throwIfProviderOutputAborted(controller.signal);
2062
4280
  ready();
2063
4281
  const rollback = await rootDecision;
2064
4282
  if (rollback !== void 0) throw rollback;
@@ -2119,6 +4337,85 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
2119
4337
  }
2120
4338
  }
2121
4339
  //#endregion
4340
+ //#region ../internal/src/hints.ts
4341
+ /**
4342
+ * The file that lists the hints of the last build or dev server, relative to the project root. A hint is a warning
4343
+ * about something that works now and fails later, such as counts that stay in one server's memory. Agents and CI read
4344
+ * the file instead of the terminal.
4345
+ */
4346
+ const viteHubHintsFile = ".vitehub/hints.json";
4347
+ const VITEHUB_NUXT_HINTS = "__vitehubNuxtHints";
4348
+ const runsKey = Symbol.for("vitehub.hints.runs");
4349
+ const shared = globalThis;
4350
+ const runs = shared[runsKey] ??= /* @__PURE__ */ new Map();
4351
+ const startedKey = Symbol.for("vitehub.hints.started");
4352
+ const startedShared = globalThis;
4353
+ const started = startedShared[startedKey] ??= /* @__PURE__ */ new WeakSet();
4354
+ /**
4355
+ * The report of the ViteHub project root, where the other generated files go. A Nuxt app with `srcDir: "app"` has its
4356
+ * Vite root in `app/`, one folder below.
4357
+ */
4358
+ function hintsFile(config) {
4359
+ const projectRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
4360
+ return resolve(typeof projectRoot === "string" ? projectRoot : resolveViteHubProjectRoot(config.root), viteHubHintsFile);
4361
+ }
4362
+ function startRun(config) {
4363
+ const file = hintsFile(config);
4364
+ const run = {
4365
+ file,
4366
+ report: {
4367
+ version: 1,
4368
+ command: config.command,
4369
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
4370
+ hints: []
4371
+ },
4372
+ keys: /* @__PURE__ */ new Set()
4373
+ };
4374
+ runs.set(file, run);
4375
+ return run;
4376
+ }
4377
+ function write(run) {
4378
+ mkdirSync(dirname(run.file), { recursive: true });
4379
+ writeFileSync(run.file, `${JSON.stringify(run.report, null, 2)}\n`);
4380
+ }
4381
+ /**
4382
+ * 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
4383
+ * {@link viteHubHintsFile}. Build the diagnostic from the package's nostics catalog, so its code has a docs page.
4384
+ */
4385
+ function reportViteHubHint(config, diagnostic) {
4386
+ if (skipHints(config)) return;
4387
+ const nuxt = config[VITEHUB_NUXT_HINTS];
4388
+ if (typeof nuxt === "function") return nuxt(diagnostic);
4389
+ const run = runs.get(hintsFile(config)) ?? startRun(config);
4390
+ const hint = {
4391
+ code: diagnostic.code,
4392
+ why: diagnostic.why,
4393
+ ...diagnostic.fix ? { fix: diagnostic.fix } : {},
4394
+ ...diagnostic.docs ? { docs: diagnostic.docs } : {},
4395
+ ...diagnostic.sources?.length ? { sources: diagnostic.sources } : {}
4396
+ };
4397
+ const key = JSON.stringify([hint.code, hint.sources ?? []]);
4398
+ if (run.keys.has(key)) return;
4399
+ run.keys.add(key);
4400
+ run.report.hints.push(hint);
4401
+ write(run);
4402
+ (config.logger ?? console).warn(formatDiagnostic(diagnostic));
4403
+ }
4404
+ function skipHints(config) {
4405
+ return !config.command || Reflect.get(config, "__vitehubPrepare") === true || Reflect.get(config, "vitehubCliDiscovery") === true;
4406
+ }
4407
+ /**
4408
+ * Starts the hints of a build or dev server: writes an empty {@link viteHubHintsFile}, so a run without hints does not
4409
+ * leave the hints of an earlier run in place. Every plugin that reports hints calls it from `configResolved`, so a
4410
+ * package used without `vitehub()` starts its own run. Nuxt uses the app instance as owner so its Vite builds and
4411
+ * separate Nitro build share one report; replay, prepare and discovery never reset it.
4412
+ */
4413
+ function startViteHubHints(config, owner = config) {
4414
+ if (skipHints(config) || config["__vitehubNuxtHints"] || started.has(owner)) return;
4415
+ started.add(owner);
4416
+ write(startRun(config));
4417
+ }
4418
+ //#endregion
2122
4419
  //#region ../internal/src/provision-state.ts
2123
4420
  const PROVISION_STATE_FILE = ".vitehub/provision.json";
2124
4421
  function getProvisionStatePath(rootDir) {
@@ -2239,21 +4536,24 @@ function inspectKVStores(build, dev, file) {
2239
4536
  };
2240
4537
  });
2241
4538
  }
2242
- function cloudflareStores(options, env) {
4539
+ function cloudflareStores(options, env, hosting) {
2243
4540
  const stores = /* @__PURE__ */ new Map();
2244
- const kv = resolveKVViteConfig(options, { env }).kv;
4541
+ const kv = resolveKVViteConfig(options, {
4542
+ env,
4543
+ hosting
4544
+ }).kv;
2245
4545
  if (!kv) return stores;
2246
4546
  for (const [name, store] of Object.entries(kv.stores || { default: kv.store })) if (store.driver === "cloudflare") stores.set(name, store);
2247
4547
  return stores;
2248
4548
  }
2249
4549
  /** Lists the Workers KV namespaces that KV Stores bind, with where each id comes from. Reads local config and Provision State only. */
2250
- function inspectKVResources(options, provisionRoot, env = process.env) {
2251
- const stores = cloudflareStores(options, env);
4550
+ function inspectKVResources(options, provisionRoot, env = process.env, hosting) {
4551
+ const stores = cloudflareStores(options, env, hosting);
2252
4552
  if (!stores.size) return [];
2253
4553
  const configured = cloudflareStores(options, {
2254
4554
  ...env,
2255
4555
  KV_NAMESPACE_ID: void 0
2256
- });
4556
+ }, hosting);
2257
4557
  const provisionState = readProvisionStateSync(provisionRoot);
2258
4558
  return [...stores].map(([storeName, store]) => {
2259
4559
  const configuredId = configured.get(storeName)?.namespaceId;
@@ -2702,7 +5002,6 @@ function hubKVOptionalPeerResolver() {
2702
5002
  function kvStores(kv) {
2703
5003
  return kv ? Object.values(kv.stores || { default: kv.store }) : [];
2704
5004
  }
2705
- /** Redis is selected explicitly at build time. */
2706
5005
  function hasRedisStore(kv) {
2707
5006
  return kvStores(kv).some((store) => store.driver === "redis");
2708
5007
  }
@@ -2712,7 +5011,7 @@ function hasDatabaseStore(kv) {
2712
5011
  function findDatabasePlugin(plugins) {
2713
5012
  return plugins?.find((plugin) => plugin.name === DATABASE_VITE_PLUGIN_NAME);
2714
5013
  }
2715
- function serializeVirtualConfig(config, databaseImport, env) {
5014
+ function serializeVirtualConfig(config, databaseImport, durabilityReportsStores, env) {
2716
5015
  const resolveStore = (store) => env && store.driver === "upstash" ? resolveUpstashRuntimeValues(store, env) : store;
2717
5016
  const kv = config.kv && env ? {
2718
5017
  ...config.kv,
@@ -2722,6 +5021,7 @@ function serializeVirtualConfig(config, databaseImport, env) {
2722
5021
  return [
2723
5022
  `export const hosting = ${JSON.stringify(config.hosting)};`,
2724
5023
  `export const kv = ${JSON.stringify(kv)};`,
5024
+ `export const durabilityReportsStores = ${durabilityReportsStores};`,
2725
5025
  hasDatabaseStore(config.kv) ? `export const loadDatabases = () => import(${JSON.stringify(databaseImport)}).then(module => module.databases);` : "export const loadDatabases = undefined;",
2726
5026
  "export default { hosting, kv };"
2727
5027
  ].join("\n");
@@ -2734,27 +5034,20 @@ function hasCloudflareKVStore(kv) {
2734
5034
  if (!kv) return false;
2735
5035
  return Object.values(kv.stores || { default: kv.store }).some((store) => store.driver === "cloudflare");
2736
5036
  }
2737
- /**
2738
- * Registers the KV Nitro plugin for Redis connections and inferred-store boot notices. It prints the driver of each inferred store at boot, and
2739
- * disposes the stores when the server closes. Without it, the open connection keeps a Node process alive after a stop
2740
- * signal.
2741
- */
2742
5037
  function configureNitroPlugin(nitro, kv) {
2743
5038
  const plugins = (nitro.plugins ?? []).filter((plugin) => plugin !== KV_NITRO_PLUGIN);
2744
5039
  if (hasRedisStore(kv) || kvStores(kv).some((store) => "inferred" in store && store.inferred)) plugins.push(KV_NITRO_PLUGIN);
2745
5040
  if (plugins.length || nitro.plugins) nitro.plugins = plugins;
2746
5041
  }
2747
- /** The Nitro storage mount of a store: `kv` for the default store, `kv-<name>` for a named store. */
2748
5042
  function kvStorageMountName(store) {
2749
5043
  const segment = store.replace(/[%:/\\?]/g, (character) => encodeURIComponent(character)) || "%";
2750
5044
  return store === "default" ? "kv" : `kv-${segment}`;
2751
5045
  }
2752
- /**
2753
- * Mounts each KV store in Nitro storage, so `useStorage("kv")` and modules that take a mount name use the store.
2754
- * A mount that the app set in `kv` or the deprecated `storage` option wins.
2755
- */
2756
5046
  function configureNitroStorage(nitro, kv) {
2757
5047
  if (!kv) return;
5048
+ const deps = nitro.deps ??= {};
5049
+ const paths = deps.paths ??= {};
5050
+ paths.unstorage ??= import.meta.resolve("unstorage");
2758
5051
  const names = Object.keys({
2759
5052
  default: kv.store,
2760
5053
  ...kv.stores
@@ -2771,7 +5064,6 @@ function configureNitroStorage(nitro, kv) {
2771
5064
  }
2772
5065
  if (Object.keys(mounts).length || nitro.kv) nitro.kv = mounts;
2773
5066
  }
2774
- /** Registers the middleware that installs the request's Cloudflare env, or removes it when no store uses a binding. */
2775
5067
  function configureNitroCloudflareRequestEnv(nitro, kv) {
2776
5068
  const handlers = Array.isArray(nitro.handlers) ? nitro.handlers.filter((handler) => !(isRecord(handler) && handler.handler === KV_CLOUDFLARE_REQUEST_ENV_MIDDLEWARE)) : [];
2777
5069
  if (hasCloudflareKVStore(kv)) handlers.unshift({
@@ -2783,7 +5075,6 @@ function configureNitroCloudflareRequestEnv(nitro, kv) {
2783
5075
  function hasUpstashStore(kv) {
2784
5076
  return kvStores(kv).some((store) => store.driver === "upstash");
2785
5077
  }
2786
- /** The import of a provider driver from the KV runtime. A build without a store on that provider keeps it external. */
2787
5078
  function isKVOptionalDriverImport(driver, id, importer) {
2788
5079
  if (id !== driver || !importer) return false;
2789
5080
  const normalizedImporter = importer.replace(/\\/g, "/").split("?", 1)[0];
@@ -2802,7 +5093,7 @@ function createCloudflareKVWranglerConfig(kv, provisionState) {
2802
5093
  function serializeCloudflareRuntime(config) {
2803
5094
  return [
2804
5095
  `import { createCloudflareKVStorage } from ${JSON.stringify(CLOUDFLARE_KV_RUNTIME_IMPORT_ID)};`,
2805
- `import { kvInvalidLimitError, kvKeyLimitCodes, kvResult, kvStoreNotFoundError, kvStoreWithMode, kvUnsupportedOperationError, kvWriteLimitCodes } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
5096
+ `import { kvClearOptionsError, kvInvalidLimitError, kvKeyLimitCodes, kvListLimitInvalid, kvResult, kvSetCodes, kvSetTTL, kvStoreNotFoundError, kvStoreWithMode, kvUnsupportedOperationError, listKVKeys } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
2806
5097
  "",
2807
5098
  `const kvConfig = ${JSON.stringify(config, null, 2)}`,
2808
5099
  "const storages = new Map();",
@@ -2836,7 +5127,11 @@ function serializeCloudflareRuntime(config) {
2836
5127
  "// kvResult throws config errors, for example an unknown store, and returns the other errors.",
2837
5128
  "function createKVStorage(name = \"default\") {",
2838
5129
  " return {",
2839
- " async clear(base, options) { return kvResult(\"clear\", name, async () => { await resolveStorage(name).clear(base, options); }); },",
5130
+ " async clear(options) {",
5131
+ " const error = kvClearOptionsError(options);",
5132
+ " if (error) return [error, undefined];",
5133
+ " return kvResult(\"clear\", name, async () => { await resolveStorage(name).clear(options?.prefix); });",
5134
+ " },",
2840
5135
  " async delete(key, options) { return kvResult(\"delete\", name, async () => { await resolveStorage(name).removeItem(key, options); }, kvKeyLimitCodes); },",
2841
5136
  " async deleteIfEquals() { return unsupported(\"deleteIfEquals\", name); },",
2842
5137
  " async get(key, options) { return kvResult(\"get\", name, () => resolveStorage(name).getItem(key, options), kvKeyLimitCodes); },",
@@ -2844,11 +5139,10 @@ function serializeCloudflareRuntime(config) {
2844
5139
  " async getMany(keys, options) { return kvResult(\"getMany\", name, () => resolveStorage(name).getMany(keys, options), kvKeyLimitCodes); },",
2845
5140
  " async has(key, options) { return kvResult(\"has\", name, () => resolveStorage(name).hasItem(key, options), kvKeyLimitCodes); },",
2846
5141
  " async increment() { return unsupported(\"increment\", name); },",
2847
- " async keys(base, options) { return kvResult(\"keys\", name, () => resolveStorage(name).getKeys(base, options)); },",
2848
5142
  " lock() { return { async acquire() { return unsupported(\"lock\", name); }, async run() { return unsupported(\"lock\", name); } }; },",
2849
- " async list(options) { if (!Number.isInteger(options.limit) || options.limit <= 0) return [kvInvalidLimitError(), undefined]; return kvResult(\"list\", name, () => resolveStorage(name).listKeys(options), [\"KV_INVALID_CURSOR\"]); },",
2850
- " async set(key, value, options) { return kvResult(\"set\", name, async () => { await resolveStorage(name).setItem(key, value, options); }, kvWriteLimitCodes); },",
2851
- " async setMany(entries, options) { return kvResult(\"setMany\", name, async () => { await resolveStorage(name).setMany(entries, options); }, kvWriteLimitCodes); },",
5143
+ " async list(options = {}) { if (kvListLimitInvalid(options)) return [kvInvalidLimitError(), undefined]; return kvResult(\"list\", name, () => listKVKeys(page => resolveStorage(name).listKeys(page), options), [\"KV_INVALID_CURSOR\"]); },",
5144
+ " async set(key, value, options) { return kvResult(\"set\", name, async () => { const storage = resolveStorage(name); const ttl = kvSetTTL(\"set\", options); await storage.setItem(key, value, ttl === undefined ? undefined : { ttl }); }, kvSetCodes); },",
5145
+ " async setMany(entries, options) { return kvResult(\"setMany\", name, async () => { const storage = resolveStorage(name); const ttl = kvSetTTL(\"setMany\", options); await storage.setMany(entries, ttl === undefined ? undefined : { ttl }); }, kvSetCodes); },",
2852
5146
  " async setIfAbsent() { return unsupported(\"setIfAbsent\", name); },",
2853
5147
  " store(storeName, options) { return kvStoreWithMode(createKVStorage(storeName), options); },",
2854
5148
  " };",
@@ -2911,7 +5205,7 @@ function configureNitroCloudflareKV(config, options, input, ownedNamespaces, pro
2911
5205
  const kv = resolveKVViteConfig(options, input).kv;
2912
5206
  configureNitroCloudflareRequestEnv(target, kv);
2913
5207
  configureNitroPlugin(target, kv);
2914
- configureNitroStorage(target, kv);
5208
+ if (Reflect.get(config, "__vitehubNitroConfigContext") === true) configureNitroStorage(target, kv);
2915
5209
  if (kv) {
2916
5210
  const existingNamespaces = new Set(target.cloudflare?.wrangler?.kv_namespaces);
2917
5211
  configureCloudflareKV(target, kv, provisionState);
@@ -2934,7 +5228,6 @@ function hubKV(options, input = {}) {
2934
5228
  postgresDatabase: postgresDatabase()
2935
5229
  });
2936
5230
  let nitroOwned = false;
2937
- let redisEnvWarned = false;
2938
5231
  let nitroOptions;
2939
5232
  const ownedNitroNamespaces = /* @__PURE__ */ new Set();
2940
5233
  let resolved;
@@ -2943,11 +5236,26 @@ function hubKV(options, input = {}) {
2943
5236
  let projectRoot = process.cwd();
2944
5237
  const getConfig = () => runtimeConfig ??= resolveKVViteConfig(options, resolutionInput());
2945
5238
  const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
5239
+ function reportRedisEnvHint(config) {
5240
+ const hint = kvRedisEnvHint(options, {
5241
+ ...resolutionInput(),
5242
+ env: {
5243
+ ...viteEnv,
5244
+ ...process.env
5245
+ },
5246
+ hosting: getConfig().hosting
5247
+ });
5248
+ if (hint) reportViteHubHint(config, hint);
5249
+ }
2946
5250
  return {
2947
5251
  name: KV_VITE_PLUGIN_NAME,
2948
5252
  enforce: "post",
2949
5253
  api: {
2950
5254
  deploymentEnv: () => kvDeploymentEnv(getConfig().kv),
5255
+ getBuildConfig: () => resolveKVViteConfig(options, {
5256
+ hosting: input.hosting,
5257
+ postgresDatabase: postgresDatabase()
5258
+ }),
2951
5259
  getConfig
2952
5260
  },
2953
5261
  nitro: {
@@ -2955,6 +5263,21 @@ function hubKV(options, input = {}) {
2955
5263
  setup(nitro) {
2956
5264
  nitroOptions = nitro.options;
2957
5265
  if (runtimeConfig) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, readProvisionStateSync(projectRoot));
5266
+ else configureNitroStorage(nitroOptions, resolveKVViteConfig(options, resolutionInput()).kv);
5267
+ nitro.hooks?.hook("prerender:config", (config) => {
5268
+ const prerender = resolveKVViteConfig(options, {
5269
+ hosting: input.hosting,
5270
+ prerender: true
5271
+ });
5272
+ if (prerender.kv && Object.values({
5273
+ ...prerender.kv.stores,
5274
+ default: prerender.kv.store
5275
+ }).some((store) => store.driver === "deno-kv")) return;
5276
+ config.virtual = {
5277
+ ...config.virtual,
5278
+ [KV_VIRTUAL_CONFIG_ID]: () => serializeVirtualConfig(prerender, databaseImport, true)
5279
+ };
5280
+ });
2958
5281
  }
2959
5282
  },
2960
5283
  vitehub: {
@@ -2996,7 +5319,7 @@ function hubKV(options, input = {}) {
2996
5319
  label: "KV stores",
2997
5320
  list: () => inspectKVStores(build, dev, file)
2998
5321
  }],
2999
- resources: () => inspectKVResources(options, projectRoot)
5322
+ resources: () => inspectKVResources(options, projectRoot, process.env, input.hosting)
3000
5323
  };
3001
5324
  },
3002
5325
  operations: [{
@@ -3018,6 +5341,7 @@ function hubKV(options, input = {}) {
3018
5341
  config: {
3019
5342
  order: "pre",
3020
5343
  async handler(config, env) {
5344
+ if (env) markViteConfigPlugin(env, KV_VITE_PLUGIN_NAME);
3021
5345
  command = env?.command ?? "build";
3022
5346
  mode = env?.mode ?? config.mode ?? (command === "serve" ? "development" : "production");
3023
5347
  runtimeConfig = void 0;
@@ -3031,6 +5355,7 @@ function hubKV(options, input = {}) {
3031
5355
  order: "pre",
3032
5356
  async handler(config) {
3033
5357
  resolved = config;
5358
+ startViteHubHints(config);
3034
5359
  if (config.command) command = config.command;
3035
5360
  mode = config.mode ?? mode;
3036
5361
  projectRoot = resolveViteHubProjectRoot(config.root || process.cwd());
@@ -3041,6 +5366,10 @@ function hubKV(options, input = {}) {
3041
5366
  const provisionState = readProvisionStateSync(projectRoot);
3042
5367
  if (nitroOptions) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, provisionState);
3043
5368
  if (hasNitroConfigContext(config) || isRecord(getResolvedNitroConfig(config))) nitroOwned = configureNitroCloudflareKV(config, options, resolutionInput(), ownedNitroNamespaces, provisionState);
5369
+ if (!config.command && command === "build" && Reflect.get(config, "__vitehubNuxtHints")) reportRedisEnvHint({
5370
+ ...config,
5371
+ command
5372
+ });
3044
5373
  }
3045
5374
  },
3046
5375
  configureServer(server) {
@@ -3081,7 +5410,10 @@ function hubKV(options, input = {}) {
3081
5410
  const kv = getConfig().kv;
3082
5411
  if (command === "build" && isCloudflareKVConfig(kv)) return serializeCloudflareRuntime(kv);
3083
5412
  }
3084
- if (id === RESOLVED_KV_VIRTUAL_CONFIG_ID) return serializeVirtualConfig(getConfig(), databaseImport, command === "serve" && options?.ssr ? viteEnv : void 0);
5413
+ if (id === RESOLVED_KV_VIRTUAL_CONFIG_ID) {
5414
+ const durabilityReportsStores = command === "build" && (resolved?.plugins?.some((plugin) => plugin.name === "vite-hub/durability/nitro") ?? false);
5415
+ return serializeVirtualConfig(getConfig(), databaseImport, durabilityReportsStores, command === "serve" && options?.ssr ? viteEnv : void 0);
5416
+ }
3085
5417
  }
3086
5418
  },
3087
5419
  buildStart: {
@@ -3089,17 +5421,8 @@ function hubKV(options, input = {}) {
3089
5421
  handler() {
3090
5422
  runtimeConfig = void 0;
3091
5423
  providerOutputGenerations.capture(this, providerOutput);
3092
- if (command !== "build" || redisEnvWarned) return;
3093
- redisEnvWarned = true;
3094
- const warning = kvRedisEnvWarning(options, {
3095
- ...resolutionInput(),
3096
- env: {
3097
- ...viteEnv,
3098
- ...process.env
3099
- },
3100
- hosting: getConfig().hosting
3101
- });
3102
- if (warning) console.warn(warning);
5424
+ if (command !== "build" || !resolved) return;
5425
+ reportRedisEnvHint(resolved);
3103
5426
  }
3104
5427
  },
3105
5428
  buildEnd: {