@vite-hub/schedule 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +14 -14
  2. package/dist/definition.js +1 -1
  3. package/dist/{due-BVMRQ93v.js → due-sOJvF_6Z.js} +1 -1
  4. package/dist/{error-diagnostics-Mpeks7J0.js → error-diagnostics-BBtYYl8j.js} +4 -0
  5. package/dist/{error-diagnostics-DSkCJC_L.js → error-diagnostics-CQ4BUqRe.js} +5 -1
  6. package/dist/index.d.ts +19 -5
  7. package/dist/index.js +34 -5
  8. package/dist/{kv-storage-iJChCS5A.js → kv-storage-2kZtP2CC.js} +2 -2
  9. package/dist/{kv-storage-C0KZZB6v.d.ts → kv-storage-Bm9aYLfZ.d.ts} +5 -1
  10. package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-nmRu_O3V.d.ts} +5 -0
  11. package/dist/{operations-DwZWFIUX.js → operations-DqwmJ8MN.js} +29 -6
  12. package/dist/operations.d.ts +10 -1
  13. package/dist/operations.js +10 -7
  14. package/dist/os.js +1 -1
  15. package/dist/runtime/console.js +1 -1
  16. package/dist/runtime/kv.d.ts +1 -1
  17. package/dist/runtime/kv.js +1 -1
  18. package/dist/runtime/process.js +5 -5
  19. package/dist/runtime/state.d.ts +2 -2
  20. package/dist/runtime/state.js +2 -2
  21. package/dist/runtime/static.js +1 -1
  22. package/dist/runtime.d.ts +3 -3
  23. package/dist/runtime.js +5 -5
  24. package/dist/{started-Bx7MDbrl.js → started-B0pc3JY0.js} +2 -2
  25. package/dist/{started-BuGmnus4.js → started-Bk2Icknk.js} +3 -3
  26. package/dist/{started-errors-p7cu_rI7.js → started-errors-DEmYH-vp.js} +30 -23
  27. package/dist/{inspect-DTfAo5gS.js → started-name-ruCM1EtQ.js} +5 -1
  28. package/dist/{state-Do2wV4Tx.d.ts → state-CPd10SXq.d.ts} +10 -1
  29. package/dist/{state-B-Fuyfb4.js → state-D4SZH6zk.js} +10 -2
  30. package/dist/{static-DQwzzvPg.js → static-7JCga3Iu.js} +21 -6
  31. package/dist/{store-Df0-fzCl.d.ts → store-DeMojnXM.d.ts} +1 -1
  32. package/dist/vite.d.ts +1 -1
  33. package/dist/vite.js +714 -462
  34. package/package.json +6 -6
package/dist/vite.js CHANGED
@@ -1,12 +1,13 @@
1
1
  import { t as isIanaTimeZone } from "./time-zone-SBldrUgt.js";
2
2
  import { n as isRecordOrFunction, t as isRecord$1 } from "./object-Da1zyPCR.js";
3
- import { t as scheduleErrorDiagnostics } from "./error-diagnostics-Mpeks7J0.js";
4
- import { a as relative$1, i as isAbsolute$1, n as relativeDefinitionFile, o as resolve$1, r as dirname$1 } from "./inspect-DTfAo5gS.js";
5
- import { t as internalErrorDiagnostics } from "./error-diagnostics-DSkCJC_L.js";
3
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-BBtYYl8j.js";
4
+ import { a as isAbsolute$1, i as dirname$1, o as relative$1, r as relativeDefinitionFile, s as resolve$1, t as startedSchedulesTickName } from "./started-name-ruCM1EtQ.js";
5
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-CQ4BUqRe.js";
6
6
  import { n as invariantError, t as invariant } from "./invariant-DolT9EEx.js";
7
- import { r as timeZoneOffsetMinutes } from "./due-BVMRQ93v.js";
7
+ import { r as timeZoneOffsetMinutes } from "./due-sOJvF_6Z.js";
8
8
  import { scheduleConsoleTiming } from "./runtime/console.js";
9
- import { builtinModules, createRequire } from "node:module";
9
+ import { builtinModules, createRequire, isBuiltin } from "node:module";
10
+ import { formatDiagnostic } from "nostics";
10
11
  import { parseCronExpression } from "cron-schedule";
11
12
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
12
13
  import { tmpdir } from "node:os";
@@ -74,6 +75,7 @@ function createProviderOutputEnvironmentOwner(name) {
74
75
  }
75
76
  };
76
77
  }
78
+ const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
77
79
  function includesNitroVitePlugin(value) {
78
80
  if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
79
81
  if (!value || typeof value !== "object") return false;
@@ -404,20 +406,76 @@ function resolveViteHubBundleDefines(config) {
404
406
  return defines;
405
407
  }
406
408
  //#endregion
407
- //#region ../internal/src/build/esbuild.ts
408
- const viteRawNamespace = "vitehub-vite-raw";
409
- const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
409
+ //#region ../internal/src/build/ast-walk.ts
410
+ /** The oxc parser grammar for a file, from its extension. Defaults to TypeScript. */
411
+ function moduleLanguage(file) {
412
+ if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
413
+ if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
414
+ if (/\.(?:c|m)?js$/i.test(file)) return "js";
415
+ return "ts";
416
+ }
417
+ function isNode(value) {
418
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
419
+ }
420
+ /** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
421
+ function walk(node, visit, parent) {
422
+ if (visit(node, parent) === false) return;
423
+ const fields = node;
424
+ for (const key in fields) {
425
+ const child = fields[key];
426
+ if (typeof child !== "object" || child === null || key === "parent") continue;
427
+ if (Array.isArray(child)) {
428
+ for (const item of child) if (isNode(item)) walk(item, visit, node);
429
+ } else if (isNode(child)) walk(child, visit, node);
430
+ }
431
+ }
432
+ //#endregion
433
+ //#region ../internal/src/build/rolldown.ts
434
+ const viteRawPrefix = "\0vitehub-vite-raw:";
435
+ const markdownTemplatePrefix = "\0vitehub-markdown-template:";
410
436
  const markdownTemplateFileSuffix = ".template.md";
411
437
  const markdownTemplateModuleQuery = "markdown-template";
412
438
  const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
413
439
  const skipResolvedAlias = "vitehubSkipResolvedAlias";
440
+ const resolvingViteAlias = "vitehubResolvingAlias";
414
441
  const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
442
+ /**
443
+ * Vite 8 bundles with Rolldown, so the app already has it. Load the copy next to `vite`, or `vite/rolldown` with
444
+ * Vite+, instead of installing a second bundler.
445
+ */
446
+ async function importRolldown() {
447
+ let entry;
448
+ try {
449
+ entry = createRequire(import.meta.resolve("vite")).resolve("rolldown");
450
+ } catch (error) {
451
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "MODULE_NOT_FOUND") throw error;
452
+ entry = createRequire(import.meta.url).resolve("vite/rolldown");
453
+ }
454
+ return await import(pathToFileURL(entry).href);
455
+ }
415
456
  function normalizePathSeparators(path) {
416
457
  return path.replaceAll("\\", "/");
417
458
  }
418
459
  function escapeRegExp$1(value) {
419
460
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
420
461
  }
462
+ function isRelativeSpecifier(path) {
463
+ return /^\.\.?[\\/]/.test(path);
464
+ }
465
+ function isBareSpecifier(id) {
466
+ return !/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/]|\0|#|[a-z][a-z0-9+.-]*:)/i.test(id);
467
+ }
468
+ /** The folder that a relative import of `importer` resolves from, as esbuild's `resolveDir`. */
469
+ function importerDir(importer, workingDir) {
470
+ return importer && isAbsolute(importer) ? dirname(importer) : workingDir;
471
+ }
472
+ /** Rolldown resolves a specifier from an importer file. A bundle entry has none, so use a file in the working folder. */
473
+ function importerFor(importer, workingDir) {
474
+ return importer ?? join(workingDir, "__vitehub_entry__.js");
475
+ }
476
+ function isFileResolution(resolved) {
477
+ return Boolean(resolved && !resolved.external && isAbsolute(resolved.id) && !resolved.id.startsWith("\0"));
478
+ }
421
479
  function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
422
480
  if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
423
481
  if (!Array.isArray(exportsValue) && !isRecord$1(exportsValue)) return [];
@@ -444,7 +502,23 @@ function collectPackageExportCandidates(packageName, exportsValue, packageRelati
444
502
  }
445
503
  return candidates;
446
504
  }
447
- function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackageAliases = true) {
505
+ /**
506
+ * Resolves `specifier` from a resolveId hook without running that hook again. `flag` in `custom` also skips the hook in
507
+ * resolutions that other plugins start from this one. `skipSelf` is still needed: when two equal resolutions run at the
508
+ * same time, Rolldown 1.2 can give one of them no `custom`, and the hook would then wait on its own resolution.
509
+ */
510
+ function resolveFrom(context, specifier, request, workingDir, flag) {
511
+ return context.resolve(specifier, importerFor(request.importer, workingDir), {
512
+ custom: {
513
+ ...request.custom,
514
+ [flag]: true
515
+ },
516
+ isEntry: request.isEntry,
517
+ kind: request.kind,
518
+ skipSelf: true
519
+ });
520
+ }
521
+ function createResolvedAliasPlugin(aliases, aliasResolveDir, workingDir, resolveEntryPackageAliases = true) {
448
522
  const entries = Object.entries(aliases || {});
449
523
  if (!entries.length) return;
450
524
  const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
@@ -464,186 +538,175 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackage
464
538
  specifier: `${resolvedSpecifier}${prefix && !resolvedSpecifier.endsWith("/") ? "/" : ""}`
465
539
  };
466
540
  }));
541
+ const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
467
542
  return {
468
543
  name: "vitehub-resolved-alias",
469
- setup(build) {
470
- const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
471
- build.onResolve({ filter: /.*/ }, async (args) => {
472
- if (args.pluginData?.[skipResolvedAlias]) return;
473
- const resolveWithContext = (specifier) => build.resolve(specifier, {
474
- importer: args.importer,
475
- kind: args.kind,
476
- namespace: args.namespace,
477
- pluginData: {
478
- ...args.pluginData,
479
- [skipResolvedAlias]: true
480
- },
481
- resolveDir: args.resolveDir,
482
- with: args.with
483
- });
484
- const aliases = await resolvedEntries;
485
- let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
486
- let matchedAlias = match?.specifier;
487
- let matchedSpecifier = match ? args.path : void 0;
488
- let specifier = args.resolveDir && /^\.\.?[\\/]/.test(args.path) ? resolve(args.resolveDir, args.path) : args.path;
489
- let normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
490
- let canonicalSpecifier = normalizedSpecifier;
491
- const canonicalizeSpecifier = async () => {
492
- canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
493
- return canonicalSpecifier;
494
- };
495
- match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
496
- if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
497
- await canonicalizeSpecifier();
498
- match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
499
- }
500
- if (!match && (resolveEntryPackageAliases || args.kind !== "entry-point") && isAbsolute(args.path)) {
501
- const candidates = [];
502
- for (const alias of aliases) {
503
- if (isAbsolute(alias.specifier)) continue;
504
- const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
505
- const aliasSegments = packageAlias.split("/");
506
- if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
507
- let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
508
- if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
509
- const scopeMarker = `/node_modules/${packageAlias}/`;
510
- const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
511
- const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
512
- if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
513
- }
514
- const packageMarker = `/node_modules/${packageName}/`;
515
- const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
516
- const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
517
- const cacheKey = [
518
- alias.specifier,
519
- alias.prefix,
520
- resolutionScope,
521
- normalizedSpecifier,
522
- args.importer,
523
- args.resolveDir,
524
- args.kind,
525
- args.namespace,
526
- JSON.stringify(args.with)
527
- ].join("\0");
528
- let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
529
- if (!resolution) {
530
- resolution = (async () => {
531
- let resolvedAliasPath;
532
- if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
533
- else if (resolutionScope) {
534
- const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
535
- const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
536
- if (!isRecord$1(parsedPackageJson)) return;
537
- const packageJson = parsedPackageJson;
538
- if (packageJson.exports === void 0 && !alias.prefix) {
539
- const resolvedCandidate = await resolveWithContext(alias.specifier);
540
- if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
541
- canonical: alias.specifier,
542
- normalized: alias.specifier,
543
- publicSpecifier: alias.specifier
544
- };
545
- return;
546
- }
547
- const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
548
- for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
549
- const resolvedCandidate = await resolveWithContext(publicSpecifier);
550
- if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
551
- if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
552
- matchingPublicSpecifiers.add(publicSpecifier);
553
- }
554
- if (matchingPublicSpecifiers.size === 1) {
555
- const publicSpecifier = [...matchingPublicSpecifiers][0];
556
- if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
557
- canonical: publicSpecifier,
558
- normalized: publicSpecifier,
559
- publicSpecifier
560
- };
561
- }
544
+ async resolveId(source, importer, extra) {
545
+ if (extra.custom?.[skipResolvedAlias]) return;
546
+ const request = {
547
+ custom: extra.custom,
548
+ importer,
549
+ isEntry: extra.isEntry,
550
+ kind: extra.kind
551
+ };
552
+ const resolveWithContext = (specifier) => resolveFrom(this, specifier, request, workingDir, skipResolvedAlias);
553
+ const resolveDir = importerDir(importer, workingDir);
554
+ const aliases = await resolvedEntries;
555
+ let match = aliases.find(({ prefix, specifier }) => isRelativeSpecifier(specifier) && (prefix ? source.startsWith(specifier) : source === specifier));
556
+ let matchedAlias = match?.specifier;
557
+ let matchedSpecifier = match ? source : void 0;
558
+ const specifier = isRelativeSpecifier(source) ? resolve(resolveDir, source) : source;
559
+ const normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
560
+ let canonicalSpecifier = normalizedSpecifier;
561
+ const canonicalizeSpecifier = async () => {
562
+ canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
563
+ return canonicalSpecifier;
564
+ };
565
+ match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
566
+ if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
567
+ await canonicalizeSpecifier();
568
+ match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
569
+ }
570
+ if (!match && (resolveEntryPackageAliases || !extra.isEntry) && isAbsolute(source)) {
571
+ const candidates = [];
572
+ for (const alias of aliases) {
573
+ if (isAbsolute(alias.specifier) || alias.prefix && alias.specifier.startsWith("#")) continue;
574
+ const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
575
+ const aliasSegments = packageAlias.split("/");
576
+ if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
577
+ let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
578
+ if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
579
+ const scopeMarker = `/node_modules/${packageAlias}/`;
580
+ const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
581
+ const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
582
+ if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
583
+ }
584
+ const packageMarker = `/node_modules/${packageName}/`;
585
+ const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
586
+ if (alias.prefix && packageMarkerIndex === -1 && !isRelativeSpecifier(alias.specifier)) continue;
587
+ const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
588
+ const cacheKey = [
589
+ alias.specifier,
590
+ alias.prefix,
591
+ resolutionScope,
592
+ normalizedSpecifier,
593
+ importer,
594
+ extra.kind,
595
+ extra.isEntry
596
+ ].join("\0");
597
+ const cacheable = !extra.custom || !Object.keys(extra.custom).length;
598
+ let resolution = cacheable ? resolvedBareAliasPaths.get(cacheKey) : void 0;
599
+ if (!resolution) {
600
+ resolution = (async () => {
601
+ let resolvedAliasPath;
602
+ if (alias.prefix && isRelativeSpecifier(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
603
+ else if (resolutionScope) {
604
+ const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
605
+ const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
606
+ if (!isRecord$1(parsedPackageJson)) return;
607
+ const packageJson = parsedPackageJson;
608
+ if (packageJson.exports === void 0 && !alias.prefix) {
609
+ const resolvedCandidate = await resolveWithContext(alias.specifier);
610
+ if (isFileResolution(resolvedCandidate) && normalizePathSeparators(resolve(resolvedCandidate.id)) === normalizedSpecifier) return {
611
+ canonical: alias.specifier,
612
+ normalized: alias.specifier,
613
+ publicSpecifier: alias.specifier
614
+ };
562
615
  return;
563
- } else {
564
- const resolvedAlias = await resolveWithContext(alias.specifier);
565
- if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
566
- resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
567
616
  }
568
- const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
569
- return {
570
- canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
571
- normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
572
- };
573
- })();
574
- if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
575
- }
576
- candidates.push({
577
- alias,
578
- resolution
579
- });
617
+ const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
618
+ for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
619
+ const resolvedCandidate = await resolveWithContext(publicSpecifier);
620
+ if (!isFileResolution(resolvedCandidate)) continue;
621
+ if (normalizePathSeparators(resolve(resolvedCandidate.id)) !== normalizedSpecifier) continue;
622
+ matchingPublicSpecifiers.add(publicSpecifier);
623
+ }
624
+ if (matchingPublicSpecifiers.size === 1) {
625
+ const publicSpecifier = [...matchingPublicSpecifiers][0];
626
+ if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
627
+ canonical: publicSpecifier,
628
+ normalized: publicSpecifier,
629
+ publicSpecifier
630
+ };
631
+ }
632
+ return;
633
+ } else {
634
+ const resolvedAlias = await resolveWithContext(alias.specifier);
635
+ if (!isFileResolution(resolvedAlias)) return;
636
+ resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.id));
637
+ }
638
+ const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
639
+ return {
640
+ canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
641
+ normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
642
+ };
643
+ })();
644
+ if (cacheable) resolvedBareAliasPaths.set(cacheKey, resolution);
580
645
  }
581
- await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
582
- for (const { alias, resolution } of candidates) {
583
- const paths = await resolution;
584
- if (!paths) continue;
585
- if (paths.publicSpecifier) {
586
- match = alias;
587
- matchedAlias = alias.specifier;
588
- matchedSpecifier = paths.publicSpecifier;
589
- break;
590
- }
591
- const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
592
- let canonicalMatch = false;
593
- if (!normalizedMatch && paths.canonical !== paths.normalized) {
594
- await canonicalizeSpecifier();
595
- canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
596
- }
597
- if (normalizedMatch || canonicalMatch) {
598
- match = alias;
599
- matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
600
- matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
601
- break;
602
- }
646
+ candidates.push({
647
+ alias,
648
+ resolution
649
+ });
650
+ }
651
+ await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
652
+ for (const { alias, resolution } of candidates) {
653
+ const paths = await resolution;
654
+ if (!paths) continue;
655
+ if (paths.publicSpecifier) {
656
+ match = alias;
657
+ matchedAlias = alias.specifier;
658
+ matchedSpecifier = paths.publicSpecifier;
659
+ break;
660
+ }
661
+ const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
662
+ let canonicalMatch = false;
663
+ if (!normalizedMatch && paths.canonical !== paths.normalized) {
664
+ await canonicalizeSpecifier();
665
+ canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
666
+ }
667
+ if (normalizedMatch || canonicalMatch) {
668
+ match = alias;
669
+ matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
670
+ matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
671
+ break;
603
672
  }
604
673
  }
605
- matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
606
- matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
607
- if (!match) return;
608
- const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
609
- if (!target) return;
610
- return resolveWithContext(/^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target);
611
- });
674
+ }
675
+ matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
676
+ matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
677
+ if (!match) return;
678
+ const target = match.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match.replacement);
679
+ if (!target) return;
680
+ const resolvedTarget = isRelativeSpecifier(target) ? resolve(aliasResolveDir, target) : target;
681
+ const resolved = await resolveWithContext(resolvedTarget);
682
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(resolvedTarget)}, the alias of ${JSON.stringify(source)}.`);
683
+ return resolved;
612
684
  }
613
685
  };
614
686
  }
615
- function createViteAliasPlugin(aliases) {
687
+ function createViteAliasPlugin(aliases, workingDir) {
616
688
  if (!Array.isArray(aliases)) return;
617
- const resolvingAlias = "vitehubResolvingAlias";
618
689
  return {
619
690
  name: "vitehub-vite-alias",
620
- setup(build) {
621
- build.onResolve({ filter: /.*/ }, async (args) => {
622
- if (args.pluginData?.[resolvingAlias]) return;
623
- const alias = aliases.find(({ find }) => {
624
- if (typeof find === "string") return args.path === find || args.path.startsWith(`${find}/`);
625
- find.lastIndex = 0;
626
- return find.test(args.path);
627
- });
628
- if (!alias) return;
629
- if (alias.customResolver) return { errors: [{ text: `[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(args.path)} because it uses customResolver.` }] };
630
- if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
631
- const replacement = typeof alias.find === "string" ? `${alias.replacement}${args.path.slice(alias.find.length)}` : args.path.replace(alias.find, alias.replacement);
632
- const result = await build.resolve(replacement, {
633
- importer: args.importer,
634
- kind: args.kind,
635
- namespace: args.namespace,
636
- pluginData: Object.assign({}, args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {}, { [resolvingAlias]: true }),
637
- resolveDir: args.resolveDir,
638
- with: args.with
639
- });
640
- const pluginData = Object.assign({}, result.pluginData);
641
- Reflect.deleteProperty(pluginData, resolvingAlias);
642
- return {
643
- ...result,
644
- pluginData
645
- };
691
+ async resolveId(source, importer, extra) {
692
+ if (extra.custom?.[resolvingViteAlias]) return;
693
+ const alias = aliases.find(({ find }) => {
694
+ if (typeof find === "string") return source === find || source.startsWith(`${find}/`);
695
+ find.lastIndex = 0;
696
+ return find.test(source);
646
697
  });
698
+ if (!alias) return;
699
+ if (alias.customResolver) this.error(`[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(source)} because it uses customResolver.`);
700
+ if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
701
+ const replacement = typeof alias.find === "string" ? `${alias.replacement}${source.slice(alias.find.length)}` : source.replace(alias.find, alias.replacement);
702
+ const resolved = await resolveFrom(this, replacement, {
703
+ custom: extra.custom,
704
+ importer,
705
+ isEntry: extra.isEntry,
706
+ kind: extra.kind
707
+ }, workingDir, resolvingViteAlias);
708
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(replacement)}, the alias of ${JSON.stringify(source)}.`);
709
+ return resolved;
647
710
  }
648
711
  };
649
712
  }
@@ -682,174 +745,255 @@ async function resolveViteRawSpecifier(path, rootDir) {
682
745
  return resolve(rootDir, rootRelativePath);
683
746
  }
684
747
  }
685
- function createViteRawPlugin(rootDir, frameworkRuntime) {
748
+ function createViteRawPlugin(rootDir, frameworkRuntime, workingDir) {
686
749
  return {
687
750
  name: "vitehub-vite-raw",
688
- setup(build) {
689
- build.onResolve({
690
- filter: /^@vite-hub\/markdown-template$/,
691
- namespace: viteMarkdownTemplateNamespace
692
- }, async (args) => {
693
- if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
694
- return build.resolve("vite-hub/markdown-template", {
695
- importer: args.importer,
696
- kind: args.kind,
697
- resolveDir: args.resolveDir
698
- });
699
- });
700
- build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
701
- if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
702
- const markdownTemplate = parseMarkdownTemplateRequest(args.path);
703
- const raw = hasViteRawQuery(args.path);
704
- if (!markdownTemplate && !raw) return;
705
- const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
706
- let pluginData = args.pluginData;
707
- if (markdownTemplate) pluginData = {
708
- ...args.pluginData,
709
- [skipMarkdownTemplateResolve]: true
710
- };
711
- const resolved = await build.resolve(specifier, {
712
- importer: args.importer,
713
- kind: args.kind,
714
- namespace: args.namespace,
715
- pluginData,
716
- resolveDir: args.resolveDir,
717
- with: args.with
751
+ async resolveId(source, importer, extra) {
752
+ if (source === markdownTemplateRuntimeSpecifier && importer?.startsWith(markdownTemplatePrefix)) {
753
+ if (!frameworkRuntime) return fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier));
754
+ return await this.resolve("vite-hub/markdown-template", importer.slice(27), {
755
+ custom: extra.custom,
756
+ kind: extra.kind
718
757
  });
719
- if (resolved.errors.length) return {
720
- errors: resolved.errors,
721
- warnings: resolved.warnings
722
- };
723
- if (resolved.external) return {
724
- external: true,
725
- namespace: resolved.namespace,
726
- path: resolved.path,
727
- pluginData: resolved.pluginData,
728
- sideEffects: resolved.sideEffects,
729
- suffix: resolved.suffix,
730
- warnings: resolved.warnings
731
- };
732
- if (resolved.namespace !== "file") return {
733
- errors: [{ text: markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this raw import in a caller plugin.` }],
734
- warnings: resolved.warnings
735
- };
736
- return {
737
- namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
738
- path: resolved.path,
739
- pluginData: resolved.pluginData,
740
- sideEffects: resolved.sideEffects,
741
- suffix: resolved.suffix,
742
- warnings: resolved.warnings
743
- };
744
- });
745
- build.onLoad({
746
- filter: /.*/,
747
- namespace: viteRawNamespace
748
- }, async (args) => ({
749
- contents: await readFile(args.path),
750
- loader: "text"
751
- }));
752
- build.onLoad({
753
- filter: /.*/,
754
- namespace: viteMarkdownTemplateNamespace
755
- }, async (args) => ({
756
- contents: renderMarkdownTemplateModule(await readFile(args.path, "utf8")),
757
- loader: "js",
758
- resolveDir: dirname(args.path)
759
- }));
758
+ }
759
+ if (extra.custom?.[skipMarkdownTemplateResolve]) return;
760
+ const markdownTemplate = parseMarkdownTemplateRequest(source);
761
+ const raw = hasViteRawQuery(source);
762
+ if (!markdownTemplate && !raw) return;
763
+ const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? source.slice(0, source.indexOf("?")), rootDir);
764
+ const resolved = await resolveFrom(this, specifier, {
765
+ custom: extra.custom,
766
+ importer,
767
+ isEntry: extra.isEntry,
768
+ kind: extra.kind
769
+ }, workingDir, skipMarkdownTemplateResolve);
770
+ if (!resolved) this.error(`[vitehub] Could not resolve ${JSON.stringify(specifier)}, imported as ${JSON.stringify(source)}.`);
771
+ if (resolved.external) return {
772
+ id: resolved.id,
773
+ external: resolved.external
774
+ };
775
+ const resolvedId = resolved.id;
776
+ 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.`);
777
+ return `${markdownTemplate ? markdownTemplatePrefix : viteRawPrefix}${resolvedId}`;
778
+ },
779
+ async load(id) {
780
+ if (id.startsWith(viteRawPrefix)) return {
781
+ code: await readFile(id.slice(18), "utf8"),
782
+ moduleType: "text"
783
+ };
784
+ if (id.startsWith(markdownTemplatePrefix)) return {
785
+ code: renderMarkdownTemplateModule(await readFile(id.slice(27), "utf8")),
786
+ moduleType: "js"
787
+ };
760
788
  }
761
789
  };
762
790
  }
763
791
  function createFileUrlPlugin() {
764
792
  return {
765
793
  name: "vitehub-file-url",
766
- setup(build) {
767
- build.onResolve({ filter: /^file:/ }, (args) => ({ path: fileURLToPath(args.path) }));
794
+ resolveId(source) {
795
+ if (source.startsWith("file:")) return fileURLToPath(source);
768
796
  }
769
797
  };
770
798
  }
771
799
  /**
772
800
  * Copies a `.wasm?module` import next to the bundle and keeps it as a relative `.wasm` import. Wrangler and Nitro load
773
801
  * such an import as a compiled WebAssembly module, which Workers need because they can't compile WebAssembly bytes.
802
+ * Node.js compiles WebAssembly bytes, so there the import becomes the bytes of the file.
774
803
  */
775
- function createWasmModulePlugin(outdir) {
804
+ function createWasmModulePlugin(outdir, workingDir, copy) {
776
805
  return {
777
806
  name: "vitehub-wasm-module",
778
- setup(build) {
779
- build.onResolve({ filter: /\.wasm\?module$/ }, async (args) => {
780
- const resolved = await build.resolve(args.path.slice(0, -7), {
781
- importer: args.importer,
782
- kind: args.kind,
783
- resolveDir: args.resolveDir
784
- });
785
- if (resolved.errors.length) return { errors: resolved.errors };
786
- const bytes = await readFile(resolved.path);
787
- const name = `${basename(resolved.path, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
788
- await mkdir(outdir, { recursive: true });
789
- await copyFile(resolved.path, join(outdir, name));
790
- return {
791
- external: true,
792
- path: `./${name}`
793
- };
807
+ async resolveId(source, importer, extra) {
808
+ if (!source.endsWith(".wasm?module")) return;
809
+ const resolved = await this.resolve(source.slice(0, -7), importerFor(importer, workingDir), {
810
+ custom: extra.custom,
811
+ kind: extra.kind
794
812
  });
813
+ if (!isFileResolution(resolved)) this.error(`[vitehub] Could not resolve ${JSON.stringify(source)}.`);
814
+ if (!copy) return resolved.id;
815
+ const bytes = await readFile(resolved.id);
816
+ const name = `${basename(resolved.id, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
817
+ await mkdir(outdir, { recursive: true });
818
+ await copyFile(resolved.id, join(outdir, name));
819
+ return {
820
+ id: `./${name}`,
821
+ external: true
822
+ };
823
+ }
824
+ };
825
+ }
826
+ /**
827
+ * Leaves package imports external. Resolve package.json import mappings first, and preserve unmapped host imports.
828
+ */
829
+ function createExternalPackagesPlugin() {
830
+ return {
831
+ name: "vitehub-external-packages",
832
+ async resolveId(source, importer, extra) {
833
+ if (source.startsWith("npm:") || source.startsWith("jsr:")) return {
834
+ id: source,
835
+ external: true
836
+ };
837
+ if (source.startsWith("#")) return await this.resolve(source, importer, {
838
+ custom: extra.custom,
839
+ kind: extra.kind
840
+ }) ?? {
841
+ id: source,
842
+ external: true
843
+ };
844
+ if (isBareSpecifier(source) && !isBuiltin(source)) return {
845
+ id: source,
846
+ external: true
847
+ };
848
+ }
849
+ };
850
+ }
851
+ function hasImportRejectionHandler(importNode, parents) {
852
+ let expression = importNode;
853
+ let parent = parents.get(expression);
854
+ while (parent?.type === "MemberExpression" && parent.object === expression) {
855
+ const call = parents.get(parent);
856
+ if (call?.type !== "CallExpression" || call.callee !== parent) break;
857
+ const method = parent.property.type === "Identifier" && !parent.computed ? parent.property.name : parent.property.type === "Literal" ? parent.property.value : void 0;
858
+ const handler = call.arguments[method === "then" ? 1 : 0];
859
+ if ((method === "then" || method === "catch") && handler && handler.type !== "SpreadElement") {
860
+ if (handler.type !== "Literal" && !(handler.type === "Identifier" && handler.name === "undefined")) return true;
861
+ }
862
+ if (method !== "then" && method !== "finally") break;
863
+ expression = call;
864
+ parent = parents.get(expression);
865
+ }
866
+ if (parent?.type !== "AwaitExpression") return false;
867
+ for (let child = parent, ancestor = parents.get(child); ancestor; ancestor = parents.get(child)) {
868
+ if (ancestor.type === "TryStatement" && ancestor.block === child && ancestor.handler) return true;
869
+ if (ancestor.type === "ArrowFunctionExpression" || ancestor.type === "FunctionExpression" || ancestor.type === "FunctionDeclaration") break;
870
+ child = ancestor;
871
+ }
872
+ return false;
873
+ }
874
+ function createOptionalImportPlugin() {
875
+ const prefix = "\0vitehub-optional-import:";
876
+ return {
877
+ name: "vitehub-optional-import",
878
+ resolveId(source) {
879
+ if (source.startsWith(prefix)) return {
880
+ id: source.slice(25),
881
+ external: "absolute"
882
+ };
883
+ },
884
+ transform: {
885
+ order: "post",
886
+ filter: { code: /\bimport\s*(?:\(|\/)/ },
887
+ async handler(code, id) {
888
+ const { parseSync } = await import("vite");
889
+ const module = parseSync(id, code, {
890
+ lang: moduleLanguage(id),
891
+ preserveParens: false,
892
+ sourceType: "module"
893
+ });
894
+ if (module.errors.length) return;
895
+ const parents = /* @__PURE__ */ new WeakMap();
896
+ const handled = [];
897
+ walk(module.program, (node, parent) => {
898
+ if (parent) parents.set(node, parent);
899
+ if (node.type !== "ImportExpression" || node.source.type !== "Literal" || typeof node.source.value !== "string") return;
900
+ if (hasImportRejectionHandler(node, parents)) handled.push({
901
+ source: node.source.value,
902
+ start: node.source.start,
903
+ end: node.source.end
904
+ });
905
+ });
906
+ if (!handled.length) return;
907
+ const resolved = await Promise.all(handled.map(({ source }) => this.resolve(source, id, { kind: "dynamic-import" })));
908
+ for (const [index, { source, start, end }] of [...handled.entries()].reverse()) if (!resolved[index]) code = code.slice(0, start) + JSON.stringify(prefix + source) + code.slice(end);
909
+ return code;
910
+ }
795
911
  }
796
912
  };
797
913
  }
914
+ /** Matches import paths as esbuild's `external` does: `*` is a wildcard, and a package name also matches its subpaths. */
915
+ function createExternalMatcher(patterns) {
916
+ if (!patterns?.length) return;
917
+ const matchers = patterns.map((pattern) => {
918
+ if (pattern.includes("*")) {
919
+ const expression = new RegExp(`^${pattern.split("*").map(escapeRegExp$1).join(".*")}$`);
920
+ return (id) => expression.test(id);
921
+ }
922
+ return isBareSpecifier(pattern) ? (id) => id === pattern || id.startsWith(`${pattern}/`) : (id) => id === pattern;
923
+ });
924
+ return (id) => matchers.some((matches) => matches(id));
925
+ }
798
926
  async function bundleEsmEntry(entryFile, outfile, options = {}) {
799
- const { build: bundle } = await import("esbuild");
927
+ const { rolldown } = await importRolldown();
800
928
  options.signal?.throwIfAborted();
801
929
  const format = options.format || "esm";
802
930
  const platform = options.platform || "neutral";
803
- const viteAliasPlugin = createViteAliasPlugin(options.alias);
931
+ const workingDir = options.workingDir ?? process.cwd();
804
932
  const frameworkRuntime = (Array.isArray(options.alias) ? options.alias.flatMap((alias) => typeof alias.find === "string" ? [alias.find] : []) : Object.keys(options.alias || {})).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
805
933
  const plugins = [];
806
- const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), options.resolveEntryPackageAliases);
934
+ plugins.push(createWasmModulePlugin(dirname(outfile), workingDir, platform !== "node"));
935
+ const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), workingDir, options.resolveEntryPackageAliases);
807
936
  if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
808
937
  plugins.push(...options.plugins ?? [], createFileUrlPlugin());
938
+ const viteAliasPlugin = createViteAliasPlugin(options.alias, workingDir);
809
939
  if (viteAliasPlugin) plugins.push(viteAliasPlugin);
810
- plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
811
- if (platform !== "node") plugins.unshift(createWasmModulePlugin(dirname(outfile)));
812
- const result = await bundle({
813
- absWorkingDir: options.workingDir,
814
- banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
815
- "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
816
- " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
817
- " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
818
- " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
819
- "}"
820
- ] : []].filter(Boolean).join("\n") } : void 0,
821
- bundle: true,
822
- conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
823
- define: options.define,
824
- entryPoints: [entryFile],
825
- external: options.external,
826
- format,
827
- keepNames: options.minifySyntax || options.minifyIdentifiers,
828
- loader: platform === "node" ? { ".wasm": "binary" } : void 0,
829
- logLevel: "silent",
830
- mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
831
- resolveExtensions: options.extensions,
832
- minifyIdentifiers: options.minifyIdentifiers,
833
- minifySyntax: options.minifySyntax,
834
- minifyWhitespace: options.minifyWhitespace,
835
- outfile,
836
- packages: options.packages,
940
+ plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime, workingDir));
941
+ if (options.packages === "external") plugins.push(createExternalPackagesPlugin());
942
+ plugins.push(createOptionalImportPlugin());
943
+ const isExternal = createExternalMatcher(options.external);
944
+ const minify = options.minifyIdentifiers || options.minifySyntax || options.minifyWhitespace ? {
945
+ compress: options.minifySyntax ?? false,
946
+ mangle: options.minifyIdentifiers ? { toplevel: true } : false,
947
+ codegen: { removeWhitespace: options.minifyWhitespace ?? false }
948
+ } : false;
949
+ const banner = [options.banner, ...format === "esm" && platform === "node" ? [
950
+ "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
951
+ " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
952
+ " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
953
+ " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
954
+ "}"
955
+ ] : []].filter(Boolean).join("\n");
956
+ const bundle = await rolldown({
957
+ cwd: workingDir,
958
+ external: isExternal ? (id) => isExternal(id) : void 0,
959
+ input: entryFile,
960
+ onLog(level, log) {
961
+ if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
962
+ },
963
+ moduleTypes: platform === "node" ? { ".wasm": "binary" } : void 0,
837
964
  platform,
838
- preserveSymlinks: options.preserveSymlinks,
839
965
  plugins,
840
- sourcemap: false,
841
- target: "es2022",
842
- write: options.signal ? false : true
966
+ resolve: {
967
+ conditionNames: options.conditions ?? (platform === "node" ? ["node"] : void 0),
968
+ extensions: options.extensions,
969
+ mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
970
+ symlinks: !options.preserveSymlinks
971
+ },
972
+ transform: {
973
+ define: options.define,
974
+ target: "es2022"
975
+ },
976
+ tsconfig: options.tsconfig ?? true
843
977
  });
844
- options.signal?.throwIfAborted();
845
- if (options.signal) {
846
- await Promise.all((result.outputFiles ?? []).map(async (output) => {
847
- await mkdir(dirname(output.path), { recursive: true });
848
- options.signal.throwIfAborted();
849
- await writeFile(output.path, output.contents, { signal: options.signal });
850
- }));
851
- options.signal.throwIfAborted();
978
+ let output;
979
+ try {
980
+ output = (await bundle.generate({
981
+ banner: banner || void 0,
982
+ codeSplitting: false,
983
+ format,
984
+ keepNames: options.keepNames ?? Boolean(options.minifySyntax || options.minifyIdentifiers),
985
+ minify,
986
+ polyfillRequire: !(format === "esm" && platform === "node"),
987
+ sourcemap: false
988
+ })).output;
989
+ } finally {
990
+ await bundle.close();
852
991
  }
992
+ options.signal?.throwIfAborted();
993
+ const chunk = output.find((file) => file.type === "chunk");
994
+ await mkdir(dirname(outfile), { recursive: true });
995
+ await writeFile(outfile, chunk.code, { signal: options.signal });
996
+ options.signal?.throwIfAborted();
853
997
  }
854
998
  //#endregion
855
999
  //#region ../internal/src/build/scan-module.ts
@@ -860,16 +1004,10 @@ async function bundleEsmEntry(entryFile, outfile, options = {}) {
860
1004
  */
861
1005
  /** The value of an expression that the scanner cannot read without running the module. */
862
1006
  const dynamic = Symbol("dynamic");
863
- function languageOf(file) {
864
- if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
865
- if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
866
- if (/\.(?:c|m)?js$/i.test(file)) return "js";
867
- return "ts";
868
- }
869
1007
  /** Parses a module once. `file` selects the grammar from its extension and defaults to TypeScript. */
870
1008
  function scanModule(source, file = "module.ts") {
871
1009
  const result = parseSync(file, source, {
872
- lang: languageOf(file),
1010
+ lang: moduleLanguage(file),
873
1011
  preserveParens: false,
874
1012
  sourceType: "module"
875
1013
  });
@@ -881,21 +1019,6 @@ function scanModule(source, file = "module.ts") {
881
1019
  source
882
1020
  };
883
1021
  }
884
- function isNode(value) {
885
- return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
886
- }
887
- /** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
888
- function walk(node, visit, parent) {
889
- if (visit(node, parent) === false) return;
890
- const fields = node;
891
- for (const key in fields) {
892
- const child = fields[key];
893
- if (typeof child !== "object" || child === null || key === "parent") continue;
894
- if (Array.isArray(child)) {
895
- for (const item of child) if (isNode(item)) walk(item, visit, node);
896
- } else if (isNode(child)) walk(child, visit, node);
897
- }
898
- }
899
1022
  /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
900
1023
  function unwrapExpression(node) {
901
1024
  while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
@@ -1622,7 +1745,8 @@ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
1622
1745
  async function traceImportedSources(paths, root, configuredRoots) {
1623
1746
  const entries = paths.filter((path) => traceableSourceExtensions.has(extname(path)));
1624
1747
  if (!entries.length) return /* @__PURE__ */ new Set();
1625
- const { build } = await import("esbuild");
1748
+ const { rolldown } = await importRolldown();
1749
+ const resolvingTraceHint = "vitehubResolvingTraceHint";
1626
1750
  const physicalRoot = realpathSync(root);
1627
1751
  const traceBuildVariants = [
1628
1752
  { platform: "node" },
@@ -1680,113 +1804,99 @@ async function traceImportedSources(paths, root, configuredRoots) {
1680
1804
  const queriedResourceSources = /* @__PURE__ */ new Set();
1681
1805
  const importedSourceHints = /* @__PURE__ */ new Set();
1682
1806
  const results = [];
1807
+ const toRootSource = (path) => pathContains$1(root, path) ? path : pathContains$1(physicalRoot, path) ? resolve(root, relative(physicalRoot, path)) : void 0;
1808
+ const isProjectSource = (path) => Boolean(path && existsSync(path) && !relative(root, path).split(sep).includes("node_modules"));
1683
1809
  for (const variant of traceBuildVariants) {
1684
- const [result] = await Promise.allSettled([build({
1685
- absWorkingDir: root,
1686
- bundle: true,
1687
- entryPoints: tracedBatch,
1688
- format: "esm",
1689
- logLevel: "silent",
1690
- metafile: true,
1691
- outdir: resolve(root, ".vitehub-provider-trace"),
1692
- packages: "bundle",
1693
- ...variant,
1694
- plugins: [{
1695
- name: "vitehub-provider-vite-resource-query",
1696
- setup(traceBuild) {
1697
- const resolvingPackageImportHint = "vitehubResolvingPackageImportHint";
1698
- traceBuild.onResolve({ filter: /^\.\.?\// }, (request) => {
1699
- const source = request.resolveDir && resolve(request.resolveDir, request.path.split(/[?#]/, 1)[0]);
1700
- if (source && existsSync(source)) importedSourceHints.add(source);
1701
- });
1702
- traceBuild.onResolve({ filter: /^#/ }, async (request) => {
1703
- if (request.pluginData?.[resolvingPackageImportHint]) return void 0;
1704
- if (!request.importer) return void 0;
1705
- const suffixOffset = request.path.slice(1).search(/[?#]/);
1706
- const packageImport = suffixOffset === -1 ? request.path : request.path.slice(0, suffixOffset + 1);
1707
- const resolution = await traceBuild.resolve(packageImport, {
1708
- importer: request.importer,
1709
- kind: request.kind,
1710
- namespace: request.namespace,
1711
- pluginData: {
1712
- ...request.pluginData,
1713
- [resolvingPackageImportHint]: true
1714
- },
1715
- resolveDir: request.resolveDir,
1716
- with: request.with
1717
- });
1718
- if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && existsSync(resolution.path)) importedSourceHints.add(resolution.path);
1719
- });
1720
- const resolvingBarePackageHint = "vitehubResolvingBarePackageHint";
1721
- traceBuild.onResolve({ filter: /^[^./#]/ }, async (request) => {
1722
- if (request.pluginData?.[resolvingBarePackageHint]) return void 0;
1723
- if (!request.importer) return void 0;
1724
- const suffixOffset = request.path.search(/[?#]/);
1725
- const packageImport = suffixOffset === -1 ? request.path : request.path.slice(0, suffixOffset);
1726
- const resolution = await traceBuild.resolve(packageImport, {
1727
- importer: request.importer,
1728
- kind: request.kind,
1729
- namespace: request.namespace,
1730
- pluginData: {
1731
- ...request.pluginData,
1732
- [resolvingBarePackageHint]: true
1733
- },
1734
- resolveDir: request.resolveDir,
1735
- with: request.with
1736
- });
1737
- const source = pathContains$1(root, resolution.path) ? resolution.path : pathContains$1(physicalRoot, resolution.path) ? resolve(root, relative(physicalRoot, resolution.path)) : void 0;
1738
- if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && source && existsSync(source) && !relative(root, source).split(sep).includes("node_modules")) importedSourceHints.add(source);
1739
- return {
1740
- external: true,
1741
- path: request.path
1742
- };
1743
- });
1744
- traceBuild.onResolve({ filter: /[?#]/ }, (request) => {
1745
- if (request.pluginData?.[resolvingPackageImportHint]) return void 0;
1746
- const resourcePath = request.path.split(/[?#]/, 1)[0];
1747
- let resourceSource;
1748
- if (request.resolveDir && (resourcePath.startsWith("./") || resourcePath.startsWith("../"))) resourceSource = resolve(request.resolveDir, resourcePath);
1749
- else if (request.resolveDir && resourcePath.startsWith("/")) {
1750
- const projectRoot = configuredRoots.filter((configuredRoot) => pathContains$1(configuredRoot, request.resolveDir)).sort((left, right) => right.length - left.length)[0] ?? root;
1751
- const rootRelativePath = resourcePath.slice(1);
1752
- const publicSource = resolve(projectRoot, "public", rootRelativePath);
1753
- resourceSource = existsSync(publicSource) ? publicSource : resolve(projectRoot, rootRelativePath);
1754
- }
1755
- if (resourceSource && existsSync(resourceSource)) queriedResourceSources.add(resourceSource);
1756
- return {
1757
- external: true,
1758
- path: request.path
1759
- };
1760
- });
1761
- traceBuild.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (request) => {
1762
- const sourcePath = pathContains$1(root, request.path) ? request.path : pathContains$1(physicalRoot, request.path) ? resolve(root, relative(physicalRoot, request.path)) : void 0;
1763
- if (!sourcePath || relative(root, sourcePath).split(sep).includes("node_modules")) return void 0;
1764
- const source = await readFile(request.path, "utf8").catch(() => void 0);
1765
- if (!source) return void 0;
1766
- const runtimeRequests = /* @__PURE__ */ new Map();
1767
- for (const runtimeRequest of traceComputedModuleSourcesOnce(request.path, source).requests) runtimeRequests.set(`${runtimeRequest.kind}\0${runtimeRequest.resolveFrom}\0${runtimeRequest.specifier}`, runtimeRequest);
1768
- await Promise.all([...runtimeRequests.values()].map(async (runtimeRequest) => {
1769
- const resolveFrom = runtimeRequest.resolveFrom ?? request.path;
1770
- const resolution = await traceBuild.resolve(runtimeRequest.specifier, {
1771
- importer: resolveFrom,
1772
- kind: runtimeRequest.kind,
1773
- namespace: request.namespace,
1774
- resolveDir: dirname(resolveFrom)
1775
- });
1776
- const resolvedSource = pathContains$1(root, resolution.path) ? resolution.path : pathContains$1(physicalRoot, resolution.path) ? resolve(root, relative(physicalRoot, resolution.path)) : void 0;
1777
- if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && resolvedSource && existsSync(resolvedSource) && !relative(root, resolvedSource).split(sep).includes("node_modules")) importedSourceHints.add(resolvedSource);
1778
- }));
1779
- });
1810
+ const inputs = /* @__PURE__ */ new Set();
1811
+ const tracePlugin = {
1812
+ name: "vitehub-provider-vite-resource-query",
1813
+ async resolveId(source, importer, extra) {
1814
+ if (!importer || extra.custom?.[resolvingTraceHint]) return;
1815
+ const resolveDir = isAbsolute(importer) ? dirname(importer) : root;
1816
+ const hintOptions = {
1817
+ custom: {
1818
+ ...extra.custom,
1819
+ [resolvingTraceHint]: true
1820
+ },
1821
+ kind: extra.kind
1822
+ };
1823
+ if (/^\.\.?\//.test(source)) {
1824
+ const relativeSource = resolve(resolveDir, source.split(/[?#]/, 1)[0]);
1825
+ if (existsSync(relativeSource)) importedSourceHints.add(relativeSource);
1826
+ } else if (source.startsWith("#")) {
1827
+ const suffixOffset = source.slice(1).search(/[?#]/);
1828
+ const packageImport = suffixOffset === -1 ? source : source.slice(0, suffixOffset + 1);
1829
+ const resolution = await this.resolve(packageImport, importer, hintOptions);
1830
+ if (resolution && !resolution.external && isAbsolute(resolution.id) && existsSync(resolution.id)) importedSourceHints.add(resolution.id);
1831
+ } else if (/^[^./#]/.test(source)) {
1832
+ const suffixOffset = source.search(/[?#]/);
1833
+ const packageImport = suffixOffset === -1 ? source : source.slice(0, suffixOffset);
1834
+ const resolution = await this.resolve(packageImport, importer, hintOptions);
1835
+ const resolvedSource = resolution && !resolution.external && isAbsolute(resolution.id) ? toRootSource(resolution.id) : void 0;
1836
+ if (isProjectSource(resolvedSource)) importedSourceHints.add(resolvedSource);
1837
+ return {
1838
+ id: source,
1839
+ external: true
1840
+ };
1780
1841
  }
1781
- }],
1782
- write: false
1783
- })]);
1784
- if (result?.status === "fulfilled") results.push(result.value);
1842
+ if (!/[?#]/.test(source)) return;
1843
+ const resourcePath = source.split(/[?#]/, 1)[0];
1844
+ let resourceSource;
1845
+ if (resourcePath.startsWith("./") || resourcePath.startsWith("../")) resourceSource = resolve(resolveDir, resourcePath);
1846
+ else if (resourcePath.startsWith("/")) {
1847
+ const projectRoot = configuredRoots.filter((configuredRoot) => pathContains$1(configuredRoot, resolveDir)).sort((left, right) => right.length - left.length)[0] ?? root;
1848
+ const rootRelativePath = resourcePath.slice(1);
1849
+ const publicSource = resolve(projectRoot, "public", rootRelativePath);
1850
+ resourceSource = existsSync(publicSource) ? publicSource : resolve(projectRoot, rootRelativePath);
1851
+ }
1852
+ if (resourceSource && existsSync(resourceSource)) queriedResourceSources.add(resourceSource);
1853
+ return {
1854
+ id: source,
1855
+ external: true
1856
+ };
1857
+ },
1858
+ async load(id) {
1859
+ if (!isAbsolute(id)) return;
1860
+ inputs.add(id);
1861
+ if (!/\.[cm]?[jt]sx?$/.test(id)) return;
1862
+ const sourcePath = toRootSource(id);
1863
+ if (!sourcePath || relative(root, sourcePath).split(sep).includes("node_modules")) return;
1864
+ const source = await readFile(id, "utf8").catch(() => void 0);
1865
+ if (!source) return;
1866
+ const runtimeRequests = /* @__PURE__ */ new Map();
1867
+ for (const runtimeRequest of traceComputedModuleSourcesOnce(id, source).requests) runtimeRequests.set(`${runtimeRequest.kind}\0${runtimeRequest.resolveFrom}\0${runtimeRequest.specifier}`, runtimeRequest);
1868
+ await Promise.all([...runtimeRequests.values()].map(async (runtimeRequest) => {
1869
+ const resolution = await this.resolve(runtimeRequest.specifier, runtimeRequest.resolveFrom ?? id, {
1870
+ kind: runtimeRequest.kind === "dynamic-import" ? "dynamic-import" : "require-call",
1871
+ skipSelf: false
1872
+ });
1873
+ const resolvedSource = resolution && !resolution.external && isAbsolute(resolution.id) ? toRootSource(resolution.id) : void 0;
1874
+ if (isProjectSource(resolvedSource)) importedSourceHints.add(resolvedSource);
1875
+ }));
1876
+ }
1877
+ };
1878
+ try {
1879
+ const bundle = await rolldown({
1880
+ cwd: root,
1881
+ input: tracedBatch,
1882
+ onLog(_level, log) {
1883
+ if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
1884
+ },
1885
+ platform: variant.platform,
1886
+ plugins: [tracePlugin],
1887
+ resolve: { conditionNames: variant.conditions }
1888
+ });
1889
+ try {
1890
+ await bundle.generate({ format: "esm" });
1891
+ } finally {
1892
+ await bundle.close();
1893
+ }
1894
+ results.push(inputs);
1895
+ } catch {}
1785
1896
  }
1786
- for (const result of results) for (const path of Object.keys(result.metafile.inputs)) {
1787
- const source = resolve(root, path);
1897
+ for (const inputs of results) for (const source of inputs) {
1788
1898
  importedSources.add(source);
1789
- if (results.length === traceBuildVariants.length && results.every((variant) => Object.hasOwn(variant.metafile.inputs, path))) tracedEntries.add(source);
1899
+ if (results.length === traceBuildVariants.length && results.every((variant) => variant.has(source))) tracedEntries.add(source);
1790
1900
  }
1791
1901
  for (const path of importedSourceHints) {
1792
1902
  importedSources.add(path);
@@ -2000,6 +2110,12 @@ async function retainProviderOutputSources(options) {
2000
2110
  ])];
2001
2111
  for (const source of materializedSources.filter((source) => !pathContains$1(root, source))) retainedPaths.set(source, resolve(retainedContainer, relative(captureRoot, source)));
2002
2112
  const requestedSymlinks = [...new Set([root, ...materializedSources].flatMap((path) => symlinkSourcesForRequestedPath(root, path)))].sort((left, right) => relative(root, left).split(sep).length - relative(root, right).split(sep).length);
2113
+ const physicalRoot = realpathSync(root);
2114
+ materializedSources.push(...requestedSymlinks.flatMap((link) => {
2115
+ const physicalTarget = realpathSync(link);
2116
+ const target = pathContains$1(physicalRoot, physicalTarget) ? resolve(root, relative(physicalRoot, physicalTarget)) : physicalTarget;
2117
+ return materializedSources.filter((source) => source !== target && pathContains$1(target, source)).map((source) => resolve(link, relative(target, source)));
2118
+ }));
2003
2119
  const configuredOutputClosures = nestedConfiguredRoots.flatMap((configuredRoot) => {
2004
2120
  const segments = relative(root, configuredRoot).split(sep);
2005
2121
  const ignoredIndex = segments.findIndex((segment) => ignoredGeneratedDirectories.has(segment));
@@ -2191,7 +2307,7 @@ function createNodeFunctionConfig(extra = {}) {
2191
2307
  return {
2192
2308
  handler: "index.mjs",
2193
2309
  launcherType: "Nodejs",
2194
- runtime: "nodejs22.x",
2310
+ runtime: "nodejs24.x",
2195
2311
  shouldAddHelpers: false,
2196
2312
  supportsResponseStreaming: true,
2197
2313
  ...extra
@@ -2537,10 +2653,26 @@ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
2537
2653
  assertNetlifyFunctionName(functionName);
2538
2654
  return resolve(functionsRoot, `${functionName}.mjs`);
2539
2655
  }
2656
+ async function declaresTopLevelBinding(code, name) {
2657
+ const { parseSync } = await import("vite");
2658
+ return parseSync("bundle.mjs", code).program.body.some((statement) => {
2659
+ const node = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
2660
+ if (node?.type === "FunctionDeclaration" || node?.type === "ClassDeclaration") return node.id?.name === name;
2661
+ return node?.type === "VariableDeclaration" && node.declarations.some((declaration) => declaration.id.type === "Identifier" && declaration.id.name === name);
2662
+ });
2663
+ }
2540
2664
  async function appendNetlifyFunctionConfig(outfile, config) {
2541
2665
  if (!config) return;
2542
2666
  const bundled = await readFile(outfile, "utf8");
2543
- await writeFile(outfile, `${bundled.trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
2667
+ const literal = stringifyProviderOutputConfig(config);
2668
+ let exported = `export const config = ${literal}`;
2669
+ if (await declaresTopLevelBinding(bundled, "config")) {
2670
+ const baseName = "vitehubNetlifyFunctionConfig";
2671
+ let name = baseName;
2672
+ for (let suffix = 2; bundled.includes(name); suffix++) name = `${baseName}${suffix}`;
2673
+ exported = `const ${name} = ${literal}\nexport { ${name} as config }`;
2674
+ }
2675
+ await writeFile(outfile, `${bundled.trimEnd()}\n\n${exported}\n`, "utf8");
2544
2676
  }
2545
2677
  async function writeCloudflareDeploymentOutput(options, signal) {
2546
2678
  signal?.throwIfAborted();
@@ -3588,6 +3720,85 @@ async function writeFileIfChanged(file, contents) {
3588
3720
  await mkdir(resolve$1(file, ".."), { recursive: true });
3589
3721
  await writeFile(file, contents, "utf8");
3590
3722
  }
3723
+ //#endregion
3724
+ //#region ../internal/src/hints.ts
3725
+ /**
3726
+ * The file that lists the hints of the last build or dev server, relative to the project root. A hint is a warning
3727
+ * about something that works now and fails later, such as counts that stay in one server's memory. Agents and CI read
3728
+ * the file instead of the terminal.
3729
+ */
3730
+ const viteHubHintsFile = ".vitehub/hints.json";
3731
+ const VITEHUB_NUXT_HINTS = "__vitehubNuxtHints";
3732
+ const runsKey = Symbol.for("vitehub.hints.runs");
3733
+ const shared = globalThis;
3734
+ const runs = shared[runsKey] ??= /* @__PURE__ */ new Map();
3735
+ const startedKey = Symbol.for("vitehub.hints.started");
3736
+ const startedShared = globalThis;
3737
+ const started = startedShared[startedKey] ??= /* @__PURE__ */ new WeakSet();
3738
+ /**
3739
+ * The report of the ViteHub project root, where the other generated files go. A Nuxt app with `srcDir: "app"` has its
3740
+ * Vite root in `app/`, one folder below.
3741
+ */
3742
+ function hintsFile(config) {
3743
+ const projectRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
3744
+ return resolve(typeof projectRoot === "string" ? projectRoot : resolveViteHubProjectRoot(config.root), viteHubHintsFile);
3745
+ }
3746
+ function startRun(config) {
3747
+ const file = hintsFile(config);
3748
+ const run = {
3749
+ file,
3750
+ report: {
3751
+ version: 1,
3752
+ command: config.command,
3753
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
3754
+ hints: []
3755
+ },
3756
+ keys: /* @__PURE__ */ new Set()
3757
+ };
3758
+ runs.set(file, run);
3759
+ return run;
3760
+ }
3761
+ function write(run) {
3762
+ mkdirSync(dirname(run.file), { recursive: true });
3763
+ writeFileSync(run.file, `${JSON.stringify(run.report, null, 2)}\n`);
3764
+ }
3765
+ /**
3766
+ * 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
3767
+ * {@link viteHubHintsFile}. Build the diagnostic from the package's nostics catalog, so its code has a docs page.
3768
+ */
3769
+ function reportViteHubHint(config, diagnostic) {
3770
+ if (skipHints(config)) return;
3771
+ const nuxt = config[VITEHUB_NUXT_HINTS];
3772
+ if (typeof nuxt === "function") return nuxt(diagnostic);
3773
+ const run = runs.get(hintsFile(config)) ?? startRun(config);
3774
+ const hint = {
3775
+ code: diagnostic.code,
3776
+ why: diagnostic.why,
3777
+ ...diagnostic.fix ? { fix: diagnostic.fix } : {},
3778
+ ...diagnostic.docs ? { docs: diagnostic.docs } : {},
3779
+ ...diagnostic.sources?.length ? { sources: diagnostic.sources } : {}
3780
+ };
3781
+ const key = JSON.stringify([hint.code, hint.sources ?? []]);
3782
+ if (run.keys.has(key)) return;
3783
+ run.keys.add(key);
3784
+ run.report.hints.push(hint);
3785
+ write(run);
3786
+ (config.logger ?? console).warn(formatDiagnostic(diagnostic));
3787
+ }
3788
+ function skipHints(config) {
3789
+ return !config.command || Reflect.get(config, "__vitehubPrepare") === true || Reflect.get(config, "vitehubCliDiscovery") === true;
3790
+ }
3791
+ /**
3792
+ * Starts the hints of a build or dev server: writes an empty {@link viteHubHintsFile}, so a run without hints does not
3793
+ * leave the hints of an earlier run in place. Every plugin that reports hints calls it from `configResolved`, so a
3794
+ * package used without `vitehub()` starts its own run. Nuxt uses the app instance as owner so its Vite builds and
3795
+ * separate Nitro build share one report; replay, prepare and discovery never reset it.
3796
+ */
3797
+ function startViteHubHints(config, owner = config) {
3798
+ if (skipHints(config) || config["__vitehubNuxtHints"] || started.has(owner)) return;
3799
+ started.add(owner);
3800
+ write(startRun(config));
3801
+ }
3591
3802
  /** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
3592
3803
  function hostFromNitroPreset(value) {
3593
3804
  const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
@@ -3798,10 +4009,6 @@ async function collectScheduleContributions(plugins, context) {
3798
4009
  return contributions;
3799
4010
  }
3800
4011
  //#endregion
3801
- //#region src/runtime/started-name.ts
3802
- /** Name of the Schedule that runs due started Schedules each minute. Discovery adds it when a Definition has no `cron`. */
3803
- const startedSchedulesTickName = "vitehub/started-schedules";
3804
- //#endregion
3805
4012
  //#region src/discovery.ts
3806
4013
  /** Discovery source of Schedule Definitions that Vite plugins contribute through `vitehub.schedules`. */
3807
4014
  const contributedScheduleSource = "vite-plugin-contribution";
@@ -4387,8 +4594,8 @@ function renderDenoCronEntry(file, registryFile, crons, runtimeImport = schedule
4387
4594
  function createSchedulePublicAliasPlugin() {
4388
4595
  return {
4389
4596
  name: "vitehub-schedule-public-alias",
4390
- setup(build) {
4391
- build.onResolve({ filter: /^(?:@vite-hub|vite-hub)\/schedule$/ }, () => ({ path: schedulePublicEntry }));
4597
+ resolveId(source) {
4598
+ if (source === "@vite-hub/schedule" || source === "vite-hub/schedule") return schedulePublicEntry;
4392
4599
  }
4393
4600
  };
4394
4601
  }
@@ -4459,7 +4666,7 @@ async function writeVercelScheduleFunctions(options, crons) {
4459
4666
  await bundleEsmEntry(wrapperFile, functionFile, {
4460
4667
  alias: options.bundleAlias,
4461
4668
  define: options.bundleDefines,
4462
- external: options.bundleExternal,
4669
+ external: [cloudflareRuntimeExternal, ...options.bundleExternal ?? []],
4463
4670
  format: "esm",
4464
4671
  platform: "node",
4465
4672
  plugins: [createSchedulePublicAliasPlugin(), ...options.workflow?.bundlePlugins ?? []],
@@ -4659,7 +4866,7 @@ async function writeNetlifyScheduleFunctions(options) {
4659
4866
  await bundleEsmEntry(wrapperFile, output.file, {
4660
4867
  alias: options.bundleAlias,
4661
4868
  define: options.bundleDefines,
4662
- external: options.bundleExternal,
4869
+ external: [cloudflareRuntimeExternal, ...options.bundleExternal ?? []],
4663
4870
  format: "esm",
4664
4871
  platform: "node",
4665
4872
  plugins: [createSchedulePublicAliasPlugin()],
@@ -5143,6 +5350,7 @@ const generatedNitroSchedulePlugin = ".vitehub/nitro/schedule/plugin.ts";
5143
5350
  const generatedNitroProviderRegistry = ".vitehub/nitro/schedule/provider-registry.js";
5144
5351
  const generatedNitroStaticRegistry = ".vitehub/nitro/schedule/static-registry.js";
5145
5352
  const generatedNitroStartedRegistry = ".vitehub/nitro/schedule/started-registry.js";
5353
+ const generatedNitroInventoryRegistry = ".vitehub/nitro/schedule/inventory-registry.js";
5146
5354
  const defaultCatchUpMs = 36e5;
5147
5355
  const generatedNitroScheduleModule = "./.vitehub/nitro/schedule/module.mjs";
5148
5356
  const generatedNitroNetlifyEntry = ".vitehub/nitro/schedule/netlify-entry.mjs";
@@ -5270,8 +5478,10 @@ const scheduleRuntimeModule = ownModule(import.meta.url, "runtime");
5270
5478
  const scheduleKVRuntimeModule = ownModule(import.meta.url, "runtime/kv");
5271
5479
  const scheduleProcessRuntimeModule = ownModule(import.meta.url, "runtime/process");
5272
5480
  const scheduleStaticRuntimeModule = ownModule(import.meta.url, "runtime/static");
5481
+ const scheduleStateModule = ownModule(import.meta.url, "runtime/state");
5273
5482
  function renderNitroSchedulePlugin(options) {
5274
5483
  const providerWake = options.providerDefinitions.length > 0;
5484
+ const installInventory = options.inventoryRegistryFile !== void 0 || Object.keys(options.hostTimings).length > 0;
5275
5485
  const processRuntime = options.processRuntime;
5276
5486
  const processRuntimeOptions = processRuntime ? {
5277
5487
  ...processRuntime.catchUpMs !== void 0 ? { catchUpMs: processRuntime.catchUpMs } : {},
@@ -5283,34 +5493,36 @@ function renderNitroSchedulePlugin(options) {
5283
5493
  } : void 0;
5284
5494
  const leaseDatabaseImport = processRuntime ? options.leaseDatabaseImport : void 0;
5285
5495
  const scheduleStoreOptions = processRuntime?.prefix !== void 0 ? { prefix: processRuntime.prefix } : {};
5496
+ const memoryStores = processRuntime && options.memoryProcessStores;
5497
+ const runStoreFactory = memoryStores ? "createMemoryScheduleRunStore" : "createKVScheduleRunStore";
5498
+ const startedStoreFactory = memoryStores ? "createMemoryStartedScheduleStore" : "createKVStartedScheduleStore";
5286
5499
  return [
5287
5500
  "import { definePlugin } from 'nitro'",
5501
+ ...installInventory ? [`import { setHostScheduleInventory } from ${JSON.stringify(scheduleStateModule)}`] : [],
5502
+ ...options.inventoryRegistryFile ? [`import inventoryRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.inventoryRegistryFile))}`] : [],
5288
5503
  ...providerWake ? [`import scheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.providerRegistryFile))}`, `import { executeCloudflareStaticSchedules } from ${JSON.stringify(options.runtimeImport ?? scheduleStaticRuntimeModule)}`] : [],
5289
5504
  ...processRuntime ? [
5290
5505
  `import { normalizeScheduleRuntimeError } from ${JSON.stringify(options.runtimeImport ?? scheduleStaticRuntimeModule)}`,
5291
- `import { createKVScheduleRunStore } from ${JSON.stringify(scheduleRuntimeModule)}`,
5292
- `import { scheduleKVStorage } from ${JSON.stringify(scheduleKVRuntimeModule)}`,
5506
+ `import { ${runStoreFactory} } from ${JSON.stringify(scheduleRuntimeModule)}`,
5293
5507
  `import { installProcessScheduleRuntime, onShutdown } from ${JSON.stringify(scheduleProcessRuntimeModule)}`,
5294
5508
  ...leaseDatabaseImport ? [`import { useLeases } from ${JSON.stringify(leaseDatabaseImport)}`] : [],
5295
5509
  `import staticScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.staticRegistryFile))}`
5296
5510
  ] : [],
5297
- ...options.startedRegistryFile ? [
5298
- `import { createKVStartedScheduleStore, installStartedSchedules } from ${JSON.stringify(scheduleRuntimeModule)}`,
5299
- ...processRuntime ? [] : [`import { scheduleKVStorage } from ${JSON.stringify(scheduleKVRuntimeModule)}`],
5300
- `import startedScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.startedRegistryFile))}`
5301
- ] : [],
5511
+ ...!memoryStores && (processRuntime || options.startedRegistryFile) ? [`import { scheduleKVStorage } from ${JSON.stringify(scheduleKVRuntimeModule)}`] : [],
5512
+ ...options.startedRegistryFile ? [`import { ${startedStoreFactory}, installStartedSchedules } from ${JSON.stringify(scheduleRuntimeModule)}`, `import startedScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.startedRegistryFile))}`] : [],
5302
5513
  "",
5303
5514
  ...processRuntime ? [
5304
5515
  `const processRuntimeOptions = ${JSON.stringify(processRuntimeOptions, null, 2)}`,
5305
- `const scheduleStoreOptions = { ...${JSON.stringify(scheduleStoreOptions, null, 2)}, kvStore: scheduleKVStorage }`,
5516
+ ...memoryStores ? [] : [`const scheduleStoreOptions = { ...${JSON.stringify(scheduleStoreOptions, null, 2)}, kvStore: scheduleKVStorage }`],
5306
5517
  ""
5307
5518
  ] : [],
5308
5519
  "export default definePlugin((nitroApp) => {",
5520
+ ...installInventory ? [` setHostScheduleInventory({ timings: ${JSON.stringify(options.hostTimings)}${options.inventoryRegistryFile ? ", registry: inventoryRegistry" : ""} })`] : [],
5309
5521
  ...options.startedRegistryFile ? [
5310
5522
  " installStartedSchedules({",
5311
5523
  ` catchUpMs: ${processRuntime ? processRuntime.catchUpMs ?? defaultCatchUpMs : 0},`,
5312
5524
  " registry: startedScheduleRegistry,",
5313
- ` store: createKVStartedScheduleStore({ ...${JSON.stringify(scheduleStoreOptions)}, kvStore: scheduleKVStorage }),`,
5525
+ ` store: ${startedStoreFactory}(${memoryStores ? "" : `{ ...${JSON.stringify(scheduleStoreOptions)}, kvStore: scheduleKVStorage }`}),`,
5314
5526
  " })"
5315
5527
  ] : [],
5316
5528
  ...providerWake ? [
@@ -5354,7 +5566,7 @@ function renderNitroSchedulePlugin(options) {
5354
5566
  ...leaseDatabaseImport ? [" ...(leases ? { leases } : {}),"] : [],
5355
5567
  " onError: captureRuntimeError,",
5356
5568
  " registry: staticScheduleRegistry,",
5357
- " scheduleRunStore: createKVScheduleRunStore(scheduleStoreOptions),",
5569
+ ` scheduleRunStore: ${runStoreFactory}(${memoryStores ? "" : "scheduleStoreOptions"}),`,
5358
5570
  " }).then(",
5359
5571
  " controller => ({ controller }),",
5360
5572
  " error => {",
@@ -5494,10 +5706,14 @@ async function writeNitroSchedulePlugin(root, options) {
5494
5706
  const providerRegistryFile = resolve(root, generatedNitroProviderRegistry);
5495
5707
  const staticRegistryFile = resolve(root, generatedNitroStaticRegistry);
5496
5708
  const startedRegistryFile = options.startableDefinitions.length ? resolve(root, generatedNitroStartedRegistry) : void 0;
5709
+ const inventoryRegistryFile = options.inventoryDefinitions.length ? resolve(root, generatedNitroInventoryRegistry) : void 0;
5497
5710
  const writes = [writeFileIfChanged(pluginFile, renderNitroSchedulePlugin({
5498
5711
  cronOverrides: options.cronOverrides,
5712
+ hostTimings: options.hostTimings,
5713
+ inventoryRegistryFile,
5499
5714
  timeZoneCrons: options.timeZoneCrons,
5500
5715
  leaseDatabaseImport: options.leaseDatabaseImport,
5716
+ memoryProcessStores: options.memoryProcessStores,
5501
5717
  pluginFile,
5502
5718
  startedRegistryFile,
5503
5719
  processRuntime: options.processRuntime,
@@ -5507,6 +5723,10 @@ async function writeNitroSchedulePlugin(root, options) {
5507
5723
  staticRegistryFile,
5508
5724
  runtimeImport: options.runtimeImport
5509
5725
  }))];
5726
+ if (inventoryRegistryFile) {
5727
+ writes.push(writeFileIfChanged(inventoryRegistryFile, createRuntimeRegistryContents(inventoryRegistryFile, options.inventoryDefinitions)));
5728
+ writes.push(writeFileIfChanged(inventoryRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase)));
5729
+ }
5510
5730
  if (startedRegistryFile) {
5511
5731
  writes.push(writeFileIfChanged(startedRegistryFile, createRuntimeRegistryContents(startedRegistryFile, options.startableDefinitions)));
5512
5732
  writes.push(writeFileIfChanged(startedRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase)));
@@ -5546,7 +5766,7 @@ function selectStandaloneProviderSource(definitions, options) {
5546
5766
  if (options.providerOutput === "auto" || options.providerOutput === void 0) return hasServerScheduleDefinitions(definitions) ? "vite-suffix" : void 0;
5547
5767
  }
5548
5768
  function shouldInstallNitroSchedulePlugin(definitions, options, startable) {
5549
- return selectNitroScheduleDefinitions(definitions, options).length > 0 || options.runtime !== void 0 || startable > 0;
5769
+ return selectNitroScheduleDefinitions(definitions, options).length > 0 || options.runtime !== void 0 || startable > 0 || options.nitroOwnsPaths === true && definitions.length > 0;
5550
5770
  }
5551
5771
  function shouldEmitStandaloneProviderOutput(definitions, options) {
5552
5772
  if (options.providerOutput === false || options.providerOutput === "nitro") return false;
@@ -5557,6 +5777,12 @@ function shouldEmitStandaloneProviderOutput(definitions, options) {
5557
5777
  async function createScheduleNitroConfig(options = {}) {
5558
5778
  const processRuntime = resolveProcessRuntimeOptions(options.runtime);
5559
5779
  const roots = resolveSchedulePluginRoots(options.root || process.cwd(), options);
5780
+ const internal = options;
5781
+ const hints = internal.hints ?? {
5782
+ root: options.root ?? roots.projectRoot,
5783
+ command: "build"
5784
+ };
5785
+ if (options.command === "build" && !internal.preliminary && !internal.hints) startViteHubHints(hints);
5560
5786
  const contributions = options.contributions ?? await collectScheduleContributions(options.plugins, {
5561
5787
  projectRoot: roots.projectRoot,
5562
5788
  root: roots.viteRoot,
@@ -5583,8 +5809,7 @@ async function createScheduleNitroConfig(options = {}) {
5583
5809
  let nitro = options.nitro;
5584
5810
  if (vercelDefinitions.length) nitro = mergeNitroVercelCrons(nitro, vercelDefinitions, await readDefinitionCrons(vercelDefinitions, cronOverrides));
5585
5811
  if (!installNitroPlugin) return nitro;
5586
- const internal = options;
5587
- if (processRuntime && options.command === "build" && !internal.preliminary && !internal.leaseDatabaseImport) console.warn("[vitehub:schedule] The Process Runtime claims each Schedule occurrence in memory, because the app has no Database. Run one server only, or add a Postgres Database so that more than one server runs each occurrence once.");
5812
+ if (processRuntime && options.command === "build" && !internal.preliminary && !internal.leaseDatabaseImport) reportViteHubHint(hints, scheduleErrorDiagnostics.SCHEDULE_PROCESS_CLAIMS_IN_MEMORY());
5588
5813
  const nitroDefinitions = processRuntime && options.providerOutput !== "nitro" ? [] : selectNitroScheduleDefinitions(definitions, options);
5589
5814
  const nitroCrons = options.command === "build" ? await readDefinitionCrons(nitroDefinitions, cronOverrides) : /* @__PURE__ */ new Map();
5590
5815
  const timeZoneCrons = options.command === "build" ? readTimeZoneCrons(nitroDefinitions, cronOverrides) : {};
@@ -5600,11 +5825,27 @@ async function createScheduleNitroConfig(options = {}) {
5600
5825
  const timing = readStaticScheduleTiming(definition.handler);
5601
5826
  return timing ? [[definition.name, timing]] : [];
5602
5827
  })) : void 0;
5828
+ const processNames = new Set(processRuntime ? staticDefinitions.map((definition) => definition.name) : []);
5829
+ const hostTimings = /* @__PURE__ */ new Map();
5830
+ const inventoryDefinitions = definitions.filter(({ name, handler }) => {
5831
+ if (processNames.has(name)) return false;
5832
+ const override = options.providerOutput !== false && cronOverrides && Object.hasOwn(cronOverrides, name) ? cronOverrides[name] : void 0;
5833
+ const timing = override ? {
5834
+ cron: override,
5835
+ timeZone: "UTC"
5836
+ } : options.command === "build" ? readStaticScheduleTiming(handler) : void 0;
5837
+ if (!timing) return true;
5838
+ hostTimings.set(name, timing);
5839
+ return false;
5840
+ });
5603
5841
  const plugin = await writeNitroSchedulePlugin(roots.projectRoot, {
5604
5842
  cronOverrides: Object.fromEntries(Object.entries(cronOverrides ?? {}).filter(([name]) => nitroDefinitionNames.has(name))),
5843
+ hostTimings: Object.fromEntries(hostTimings),
5844
+ inventoryDefinitions,
5605
5845
  crons,
5606
5846
  importBase: options.importBase,
5607
- leaseDatabaseImport: options.leaseDatabaseImport,
5847
+ leaseDatabaseImport: internal.leaseDatabaseImport,
5848
+ memoryProcessStores: internal.memoryProcessStores,
5608
5849
  netlifySchedules,
5609
5850
  timeZoneCrons,
5610
5851
  processRuntime,
@@ -5634,7 +5875,11 @@ function hubSchedule(options = {}) {
5634
5875
  let serverDirs;
5635
5876
  let viteRoot;
5636
5877
  let contributions = [];
5637
- const leaseDatabaseImport = (plugins) => hasVitePlugin(plugins, databaseVitePluginName) ? { leaseDatabaseImport: internalOptions.databaseImport ?? "@vite-hub/database" } : {};
5878
+ let command;
5879
+ const processStorageOptions = (plugins) => ({
5880
+ ...hasVitePlugin(plugins, databaseVitePluginName) ? { leaseDatabaseImport: internalOptions.databaseImport ?? "@vite-hub/database" } : {},
5881
+ memoryProcessStores: internalOptions.requireKVPluginForProcessStores && !hasVitePlugin(plugins, "@vite-hub/kv/vite")
5882
+ });
5638
5883
  async function collectPluginScheduleContributions(plugins, roots) {
5639
5884
  return await collectScheduleContributions(plugins, {
5640
5885
  projectRoot: roots.projectRoot,
@@ -5658,6 +5903,7 @@ function hubSchedule(options = {}) {
5658
5903
  name: SCHEDULE_VITE_PLUGIN_NAME,
5659
5904
  enforce: "pre",
5660
5905
  async config(config, env) {
5906
+ command = env.command;
5661
5907
  serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
5662
5908
  const roots = resolveSchedulePluginRoots(config.root || process.cwd(), options);
5663
5909
  contributions = await collectPluginScheduleContributions(config.plugins, roots);
@@ -5675,7 +5921,7 @@ function hubSchedule(options = {}) {
5675
5921
  contributions,
5676
5922
  nitroOwnsPaths: hasNitroConfigContext(config),
5677
5923
  nitro: config.nitro,
5678
- ...leaseDatabaseImport(config.plugins),
5924
+ ...processStorageOptions(config.plugins),
5679
5925
  preliminary: true,
5680
5926
  root: config.root || process.cwd(),
5681
5927
  serverDirs
@@ -5684,6 +5930,7 @@ function hubSchedule(options = {}) {
5684
5930
  config.nitro = nitro;
5685
5931
  },
5686
5932
  async configResolved(config) {
5933
+ startViteHubHints(config);
5687
5934
  resolved = config;
5688
5935
  providerOutput = useProviderOutputCatalog(config);
5689
5936
  const roots = resolveSchedulePluginRoots(config.root, options);
@@ -5693,6 +5940,7 @@ function hubSchedule(options = {}) {
5693
5940
  const definitions = discoverRegistrySchedules();
5694
5941
  emitStandaloneProviderOutput = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options);
5695
5942
  standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
5943
+ const storage = processStorageOptions(config.plugins);
5696
5944
  if (config.command) {
5697
5945
  const nitro = await createScheduleNitroConfig({
5698
5946
  ...options,
@@ -5700,7 +5948,8 @@ function hubSchedule(options = {}) {
5700
5948
  contributions,
5701
5949
  nitro: config.nitro,
5702
5950
  nitroOwnsPaths: hasNitroConfigContext(config),
5703
- ...leaseDatabaseImport(config.plugins),
5951
+ ...storage,
5952
+ hints: config,
5704
5953
  root: config.root,
5705
5954
  serverDirs
5706
5955
  });
@@ -5708,7 +5957,10 @@ function hubSchedule(options = {}) {
5708
5957
  const configWithNitro = config;
5709
5958
  configWithNitro.nitro = nitro;
5710
5959
  }
5711
- }
5960
+ } else if (command === "build" && typeof Reflect.get(config, "__vitehubNuxtHints") === "function" && options.runtime && !storage.leaseDatabaseImport) reportViteHubHint({
5961
+ ...config,
5962
+ command
5963
+ }, scheduleErrorDiagnostics.SCHEDULE_PROCESS_CLAIMS_IN_MEMORY());
5712
5964
  },
5713
5965
  configEnvironment(name, config) {
5714
5966
  if (!isServerEnvironment(name, config)) return;