@vite-hub/docs 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 (67) hide show
  1. package/README.md +179 -19
  2. package/dist/{agent-copy-BJp_Yf5d.js → agent-copy-xPaWye_g.js} +1 -1
  3. package/dist/assistant-pages-CqNlHsx-.js +37 -0
  4. package/dist/{assistant-shared-Dll_F_yy.d.ts → assistant-shared-CWIKRtBv.d.ts} +3 -2
  5. package/dist/{assistant-shared-CdtXowot.js → assistant-shared-DhiLHKSl.js} +23 -7
  6. package/dist/assistant-worker.d.ts +1 -1
  7. package/dist/assistant-worker.js +1 -1
  8. package/dist/assistant.d.ts +1 -1
  9. package/dist/assistant.js +1 -1
  10. package/dist/{content-9CINWiRf.js → content-BQVlMshL.js} +57 -47
  11. package/dist/{draft-DUBx--r9.js → draft-CSsTYSeb.js} +2 -2
  12. package/dist/error-diagnostics-CmgtG9xa.js +157 -0
  13. package/dist/files-UY4h1_36.js +38 -0
  14. package/dist/index.d.ts +7 -6
  15. package/dist/index.js +4 -4
  16. package/dist/link-checker-redirects.js +1 -1
  17. package/dist/{manifest-Dzp5-_AJ.d.ts → manifest-Drbdw1us.d.ts} +9 -3
  18. package/dist/{manifest-D66AEF8F.js → manifest-DvECmwX-.js} +101 -51
  19. package/dist/{markdown-Cn9-4oVG.js → markdown-1M1FbjCw.js} +1 -1
  20. package/dist/{page-Dx2JD3y1.d.ts → markdown-BiKrT08O.d.ts} +2 -25
  21. package/dist/navigation.d.ts +10 -5
  22. package/dist/navigation.js +23 -10
  23. package/dist/{nuxt-B5LrERKc.d.ts → nuxt-8O2OB_hI.d.ts} +84 -7
  24. package/dist/nuxt.d.ts +2 -2
  25. package/dist/nuxt.js +1699 -105
  26. package/dist/{page-BbmSfZO8.js → page-Bb0TfRKi.js} +21 -4
  27. package/dist/page-BryUCmYf.d.ts +26 -0
  28. package/dist/primitive-rail.d.ts +2 -5
  29. package/dist/primitive-rail.js +8 -6
  30. package/dist/{raw-C03EUJKw.js → raw-BChwipz_.js} +6 -0
  31. package/dist/redirects-BJj58IsY.js +87 -0
  32. package/dist/runnable.d.ts +37 -0
  33. package/dist/runnable.js +105 -0
  34. package/dist/runtime/app/components/DocsAsideLeftBody.vue +2 -8
  35. package/dist/runtime/app/components/DocsLearn.vue +215 -0
  36. package/dist/runtime/app/components/DocsLearnCodePre.vue +98 -0
  37. package/dist/runtime/app/components/DocsLearnFile.vue +21 -0
  38. package/dist/runtime/app/components/DocsPage.vue +11 -5
  39. package/dist/runtime/app/components/DocsPlayground.vue +117 -0
  40. package/dist/runtime/app/components/content/Example.vue +18 -49
  41. package/dist/runtime/app/components/content/McpClient.vue +170 -0
  42. package/dist/runtime/app/components/content/McpInstall.vue +238 -0
  43. package/dist/runtime/app/components/content/PageList.vue +1 -5
  44. package/dist/runtime/app/layouts/docs.vue +36 -8
  45. package/dist/runtime/app/middleware/docs-layout.ts +2 -2
  46. package/dist/runtime/app/utils/docs-learn.ts +31 -0
  47. package/dist/runtime/app/utils/docs-playground.ts +3 -0
  48. package/dist/runtime/server/llms.js +1 -1
  49. package/dist/runtime/server/markdown.d.ts +0 -5
  50. package/dist/runtime/server/markdown.js +10 -1
  51. package/dist/runtime/server/mcp.js +1 -1
  52. package/dist/runtime/server/page.d.ts +1 -1
  53. package/dist/runtime/server/page.js +3 -3
  54. package/dist/runtime/server/raw.js +2 -9
  55. package/dist/runtime/server/search.d.ts +1 -1
  56. package/dist/runtime/server/search.js +3 -2
  57. package/dist/runtime/server/sitemap.js +1 -1
  58. package/dist/{schema-DwpXW0VZ.js → schema-DcWZ3Q3M.js} +97 -5
  59. package/dist/server.d.ts +3 -2
  60. package/dist/server.js +4 -4
  61. package/dist/snapshot-worker.mjs +40 -0
  62. package/dist/steps-DBlkJwtD.d.ts +105 -0
  63. package/dist/steps-DF-11dJn.js +32 -0
  64. package/dist/{types-BhG6vGfG.d.ts → types-CHU_fy9l.d.ts} +69 -4
  65. package/package.json +18 -11
  66. package/dist/error-diagnostics-BoOsP6Y4.js +0 -53
  67. package/dist/redirects-BrbWFSzW.js +0 -62
package/dist/nuxt.js CHANGED
@@ -1,24 +1,29 @@
1
- import { docsAppPath, docsIndexedPages, docsManifestPages, docsPageIcon, docsPageIndexed, docsRailIcon, docsRawPath, docsSectionIcon, isDocsPath, normalizeDocsBase, normalizeDocsPath } from "./navigation.js";
2
- import { a as replacesDocsPage, t as docsMount } from "./page-BbmSfZO8.js";
3
- import { t as docsErrorDiagnostics } from "./error-diagnostics-BoOsP6Y4.js";
4
- import { n as docsRedirectProblems, r as docsRedirects, t as docsRedirectError } from "./redirects-BrbWFSzW.js";
5
- import { a as docsAppPanelSource, c as checkDocsLinks, i as docsAppManifestSource, o as readDocsContent, r as docsAppManifest, s as resolveDocsSources } from "./manifest-D66AEF8F.js";
6
- import { r as docsContentSource } from "./agent-copy-BJp_Yf5d.js";
1
+ import { docsAppPath, docsIndexedPages, docsManifestPages, docsPageIcon, docsPageIndexed, docsRailIcon, docsRawPath, docsSectionIcon, isDocsPath, isDocsWorkspaceLayout, normalizeDocsBase, normalizeDocsPath } from "./navigation.js";
2
+ import { a as replacesDocsPage, o as routePaths, t as docsMount } from "./page-Bb0TfRKi.js";
3
+ import { t as docsErrorDiagnostics } from "./error-diagnostics-CmgtG9xa.js";
4
+ import { i as docsServerRoutes, n as docsRedirectProblems, r as docsRedirects, t as docsRedirectError } from "./redirects-BJj58IsY.js";
5
+ import { t as dependencyKey } from "./steps-DF-11dJn.js";
6
+ import { a as docsAppManifestSource, c as resolveDocsSources, d as docsLinkExclusion, f as docsOutputFile, i as docsAppManifest, l as checkDocsLinks, n as createDocsContent, o as docsAppPanelSource, s as readDocsContent, t as contentName, u as docsLinkError } from "./manifest-DvECmwX-.js";
7
+ import { r as docsContentSource } from "./agent-copy-xPaWye_g.js";
7
8
  import { i as docsThemeScope, n as docsThemeAdditions, r as docsUi, t as docsAppConfigUi } from "./theme-DzC8LtMH.js";
8
9
  import { createRequire } from "node:module";
9
10
  import { addComponent, addComponentsDir, addImportsDir, addPlugin, addRouteMiddleware, addServerHandler, addTemplate, addTypeTemplate, createResolver, defineNuxtModule, extendPages, updateTemplates, useLogger } from "@nuxt/kit";
10
- import { defineDiagnostics } from "nostics";
11
+ import { addRoute, createRouter, findAllRoutes, routeToRegExp } from "rou3";
12
+ import { defineDiagnostics, formatDiagnostic } from "nostics";
11
13
  import { createHash } from "node:crypto";
12
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
13
- import { readFile, readdir } from "node:fs/promises";
14
- import { dirname, join, relative, resolve, sep } from "node:path";
14
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
15
+ import { copyFile, glob, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
15
16
  import { fileURLToPath, pathToFileURL } from "node:url";
17
+ import { basename, dirname, isAbsolute, join, matchesGlob, parse, posix, relative, resolve, sep } from "node:path";
18
+ import { tmpdir } from "node:os";
16
19
  import { findContentEntry } from "@vite-hub/source/vite";
17
20
  import { vitehubTheme } from "@vite-hub/ui/theme";
18
21
  import { sizeOf } from "comark-zoom/size";
19
22
  import { defu } from "defu";
20
- import { addRoute, createRouter, findAllRoutes, routeToRegExp } from "rou3";
21
- import { ELEMENT_NODE, parse, walkSync } from "ultrahtml";
23
+ import { Buffer as Buffer$1 } from "node:buffer";
24
+ import { parse as parse$1 } from "yaml";
25
+ import { execFileSync, spawn } from "node:child_process";
26
+ import { ELEMENT_NODE, parse as parse$2, walkSync } from "ultrahtml";
22
27
  import { gzipSync } from "node:zlib";
23
28
  import postcss from "postcss";
24
29
  //#region ../internal/dist/invariant.js
@@ -36,6 +41,271 @@ const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
36
41
  function invariantError(what) {
37
42
  return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
38
43
  }
44
+ /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
45
+ function invariant(condition, what) {
46
+ if (!condition) throw invariantError(what);
47
+ }
48
+ //#endregion
49
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
50
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
51
+ function normalizeWindowsPath(input = "") {
52
+ if (!input) return input;
53
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
54
+ }
55
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
56
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
57
+ function cwd() {
58
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
59
+ return "/";
60
+ }
61
+ const resolve$1 = function(...arguments_) {
62
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
63
+ let resolvedPath = "";
64
+ let resolvedAbsolute = false;
65
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
66
+ const path = index >= 0 ? arguments_[index] : cwd();
67
+ if (!path || path.length === 0) continue;
68
+ resolvedPath = `${path}/${resolvedPath}`;
69
+ resolvedAbsolute = isAbsolute$1(path);
70
+ }
71
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
72
+ if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
73
+ return resolvedPath.length > 0 ? resolvedPath : ".";
74
+ };
75
+ function normalizeString(path, allowAboveRoot) {
76
+ let res = "";
77
+ let lastSegmentLength = 0;
78
+ let lastSlash = -1;
79
+ let dots = 0;
80
+ let char = null;
81
+ for (let index = 0; index <= path.length; ++index) {
82
+ if (index < path.length) char = path[index];
83
+ else if (char === "/") break;
84
+ else char = "/";
85
+ if (char === "/") {
86
+ if (lastSlash === index - 1 || dots === 1);
87
+ else if (dots === 2) {
88
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
89
+ if (res.length > 2) {
90
+ const lastSlashIndex = res.lastIndexOf("/");
91
+ if (lastSlashIndex === -1) {
92
+ res = "";
93
+ lastSegmentLength = 0;
94
+ } else {
95
+ res = res.slice(0, lastSlashIndex);
96
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
97
+ }
98
+ lastSlash = index;
99
+ dots = 0;
100
+ continue;
101
+ } else if (res.length > 0) {
102
+ res = "";
103
+ lastSegmentLength = 0;
104
+ lastSlash = index;
105
+ dots = 0;
106
+ continue;
107
+ }
108
+ }
109
+ if (allowAboveRoot) {
110
+ res += res.length > 0 ? "/.." : "..";
111
+ lastSegmentLength = 2;
112
+ }
113
+ } else {
114
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
115
+ else res = path.slice(lastSlash + 1, index);
116
+ lastSegmentLength = index - lastSlash - 1;
117
+ }
118
+ lastSlash = index;
119
+ dots = 0;
120
+ } else if (char === "." && dots !== -1) ++dots;
121
+ else dots = -1;
122
+ }
123
+ return res;
124
+ }
125
+ const isAbsolute$1 = function(p) {
126
+ return _IS_ABSOLUTE_RE.test(p);
127
+ };
128
+ const dirname$1 = function(p) {
129
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
130
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
131
+ return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
132
+ };
133
+ //#endregion
134
+ //#region ../internal/dist/build/paths.js
135
+ function resolveRuntimeModule(packageDir, modulePath) {
136
+ const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
137
+ return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
138
+ }
139
+ const packageDirs = /* @__PURE__ */ new Map();
140
+ function findPackageDir(file) {
141
+ const start = dirname$1(file);
142
+ const cached = packageDirs.get(start);
143
+ if (cached) return cached;
144
+ let dir = start;
145
+ while (!existsSync(resolve$1(dir, "package.json"))) {
146
+ const parent = dirname$1(dir);
147
+ invariant(parent !== dir, `a file that a package resolver found has a package.json above it (${file})`);
148
+ dir = parent;
149
+ }
150
+ packageDirs.set(start, dir);
151
+ return dir;
152
+ }
153
+ /**
154
+ * The absolute path of a module that the calling package builds, such as `ownModule(import.meta.url, "runtime/state")`.
155
+ * Owner plugins write this path into generated code, so the module needs no package export, and an app resolves it
156
+ * only when the owner's feature is on. It is the `dist` file, or the `src` file before the package is built.
157
+ */
158
+ function ownModule(importMetaUrl, modulePath) {
159
+ return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
160
+ }
161
+ //#endregion
162
+ //#region ../internal/dist/vite-DGZFNpcx.js
163
+ const projectRootDirectoryMarkers = [
164
+ ["server", "agents"],
165
+ ["server", "channels"],
166
+ ["server", "connections"],
167
+ ["server", "browsers"],
168
+ ["server", "emails"],
169
+ ["server", "schedules"],
170
+ ["server", "workspaces"]
171
+ ];
172
+ const projectRootFileMarkers = [
173
+ ["package.json"],
174
+ ["nuxt.config.ts"],
175
+ ["nuxt.config.mts"],
176
+ ["nuxt.config.js"],
177
+ ["nuxt.config.mjs"]
178
+ ];
179
+ const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
180
+ function resolveViteHubProjectRoot(root, options = {}) {
181
+ const resolvedRoot = resolve(root);
182
+ const temporaryRoot = resolve(tmpdir());
183
+ const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
184
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
185
+ if (basename(resolvedRoot) === "app") {
186
+ const parent = dirname(resolvedRoot);
187
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
188
+ "nuxt.config.ts",
189
+ "nuxt.config.mts",
190
+ "nuxt.config.js",
191
+ "nuxt.config.mjs"
192
+ ]))) return parent;
193
+ }
194
+ let current = resolvedRoot;
195
+ while (true) {
196
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
197
+ if (hasProjectRootMarker(current)) return current;
198
+ const parent = dirname(current);
199
+ if (parent === current) return resolvedRoot;
200
+ current = parent;
201
+ }
202
+ }
203
+ function hasProjectRootDirectoryMarker(root) {
204
+ for (const marker of projectRootDirectoryMarkers) try {
205
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
206
+ } catch (error) {
207
+ if (!isMissingProjectMarker(error)) throw error;
208
+ }
209
+ return false;
210
+ }
211
+ function hasProjectRootMarker(root) {
212
+ if (hasProjectRootDirectoryMarker(root)) return true;
213
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
214
+ }
215
+ function hasProjectRootFileMarker(root, markers) {
216
+ for (const marker of markers) {
217
+ const path = Array.isArray(marker) ? marker : [marker];
218
+ try {
219
+ if (statSync(resolve(root, ...path)).isFile()) return true;
220
+ } catch (error) {
221
+ if (!isMissingProjectMarker(error)) throw error;
222
+ }
223
+ }
224
+ return false;
225
+ }
226
+ function isMissingProjectMarker(error) {
227
+ const code = error.code;
228
+ return code === "ENOENT" || code === "ENOTDIR";
229
+ }
230
+ //#endregion
231
+ //#region ../internal/dist/hints.js
232
+ /**
233
+ * The file that lists the hints of the last build or dev server, relative to the project root. A hint is a warning
234
+ * about something that works now and fails later, such as counts that stay in one server's memory. Agents and CI read
235
+ * the file instead of the terminal.
236
+ */
237
+ const viteHubHintsFile = ".vitehub/hints.json";
238
+ const VITEHUB_NUXT_HINTS = "__vitehubNuxtHints";
239
+ const runsKey = Symbol.for("vitehub.hints.runs");
240
+ const shared = globalThis;
241
+ const runs = shared[runsKey] ??= /* @__PURE__ */ new Map();
242
+ const startedKey = Symbol.for("vitehub.hints.started");
243
+ const startedShared = globalThis;
244
+ const started = startedShared[startedKey] ??= /* @__PURE__ */ new WeakSet();
245
+ /**
246
+ * The report of the ViteHub project root, where the other generated files go. A Nuxt app with `srcDir: "app"` has its
247
+ * Vite root in `app/`, one folder below.
248
+ */
249
+ function hintsFile(config) {
250
+ const projectRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
251
+ return resolve(typeof projectRoot === "string" ? projectRoot : resolveViteHubProjectRoot(config.root), viteHubHintsFile);
252
+ }
253
+ function startRun(config) {
254
+ const file = hintsFile(config);
255
+ const run = {
256
+ file,
257
+ report: {
258
+ version: 1,
259
+ command: config.command,
260
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
261
+ hints: []
262
+ },
263
+ keys: /* @__PURE__ */ new Set()
264
+ };
265
+ runs.set(file, run);
266
+ return run;
267
+ }
268
+ function write(run) {
269
+ mkdirSync(dirname(run.file), { recursive: true });
270
+ writeFileSync(run.file, `${JSON.stringify(run.report, null, 2)}\n`);
271
+ }
272
+ /**
273
+ * 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
274
+ * {@link viteHubHintsFile}. Build the diagnostic from the package's nostics catalog, so its code has a docs page.
275
+ */
276
+ function reportViteHubHint(config, diagnostic) {
277
+ if (skipHints(config)) return;
278
+ const nuxt = config[VITEHUB_NUXT_HINTS];
279
+ if (typeof nuxt === "function") return nuxt(diagnostic);
280
+ const run = runs.get(hintsFile(config)) ?? startRun(config);
281
+ const hint = {
282
+ code: diagnostic.code,
283
+ why: diagnostic.why,
284
+ ...diagnostic.fix ? { fix: diagnostic.fix } : {},
285
+ ...diagnostic.docs ? { docs: diagnostic.docs } : {},
286
+ ...diagnostic.sources?.length ? { sources: diagnostic.sources } : {}
287
+ };
288
+ const key = JSON.stringify([hint.code, hint.sources ?? []]);
289
+ if (run.keys.has(key)) return;
290
+ run.keys.add(key);
291
+ run.report.hints.push(hint);
292
+ write(run);
293
+ (config.logger ?? console).warn(formatDiagnostic(diagnostic));
294
+ }
295
+ function skipHints(config) {
296
+ return !config.command || Reflect.get(config, "__vitehubPrepare") === true || Reflect.get(config, "vitehubCliDiscovery") === true;
297
+ }
298
+ /**
299
+ * Starts the hints of a build or dev server: writes an empty {@link viteHubHintsFile}, so a run without hints does not
300
+ * leave the hints of an earlier run in place. Every plugin that reports hints calls it from `configResolved`, so a
301
+ * package used without `vitehub()` starts its own run. Nuxt uses the app instance as owner so its Vite builds and
302
+ * separate Nitro build share one report; replay, prepare and discovery never reset it.
303
+ */
304
+ function startViteHubHints(config, owner = config) {
305
+ if (skipHints(config) || config["__vitehubNuxtHints"] || started.has(owner)) return;
306
+ started.add(owner);
307
+ write(startRun(config));
308
+ }
39
309
  //#endregion
40
310
  //#region src/module-options.ts
41
311
  /** The module name: a string entry, or the `getMeta()` name of an imported module function. */
@@ -147,10 +417,11 @@ function installed(name, rootDir) {
147
417
  /**
148
418
  * The module dependency that turns Comments on in `vite-hub/nuxt`. Comments keeps threads in a ViteHub Database, so a
149
419
  * site without `vite-hub/nuxt` has none unless it asks for them, which fails the build. `false` sets `comments: false`.
150
- * The dependency only sets defaults: the app's own `vitehub.comments` wins.
420
+ * The dependency only sets defaults: the app's own `vitehub.comments` wins, so `false` with Comments on in `vitehub` warns.
151
421
  */
152
422
  async function docsCommentsDependencies(nuxt, comments) {
153
423
  const vitehub = await viteHubModuleOptions(nuxt);
424
+ if (comments === false && vitehub?.comments !== void 0 && vitehub.comments !== false) useLogger("@vite-hub/docs").warn(formatDiagnostic(docsErrorDiagnostics.DOCS_COMMENTS_OFF_IGNORED()));
154
425
  if (comments === false) return vitehub ? { "vite-hub/nuxt": {
155
426
  optional: true,
156
427
  defaults: { comments: false }
@@ -168,6 +439,1092 @@ async function docsCommentsDependencies(nuxt, comments) {
168
439
  } };
169
440
  }
170
441
  //#endregion
442
+ //#region src/runnable/build.ts
443
+ const ignoredEntries = /* @__PURE__ */ new Set([
444
+ "node_modules",
445
+ ".output",
446
+ ".vitehub",
447
+ ".nitro",
448
+ ".data",
449
+ "dist"
450
+ ]);
451
+ /**
452
+ * Local files with secrets, in any folder: `.env` and `.env.*` but not `.env.example`, `.dev.vars*`, npm and netrc
453
+ * credentials, and keys. Workspace modules ship to the browser, so they never hold these.
454
+ */
455
+ function isPrivateFile(name) {
456
+ if (name === ".env.example") return false;
457
+ return name === ".env" || name.startsWith(".env.") || name.startsWith(".dev.vars") || name === ".npmrc" || name === ".netrc" || /\.(?:pem|key|p12|pfx)$/.test(name);
458
+ }
459
+ /** Labels of code blocks that are not files of the app, such as `commands/dev` and `output/response.json`. */
460
+ function isTutorialFileLabel(label) {
461
+ return !label.startsWith("commands/") && !label.startsWith("output/");
462
+ }
463
+ function codeBlockLabels(markdown) {
464
+ return [...markdown.matchAll(/^```[^\n[]*\[([^\]]+)\]/gm)].map((match) => match[1]);
465
+ }
466
+ function frontmatterField(markdown, field) {
467
+ const frontmatter = /^---\n([\s\S]*?)\n---/.exec(markdown)?.[1] ?? "";
468
+ const value = parse$1(frontmatter)?.[field];
469
+ return typeof value === "string" ? value : "";
470
+ }
471
+ /**
472
+ * A page as a reader of one framework sees it: the content of that framework's tab stays, and the other tabs of every
473
+ * `::tabs{sync="framework"}` block go away. Runnable lessons run a Vite fixture, so they read the Vite view. A page
474
+ * without framework tabs stays as it is.
475
+ */
476
+ function frameworkView(markdown, framework) {
477
+ const lines = markdown.replaceAll("\r\n", "\n").split("\n");
478
+ const out = [];
479
+ for (let index = 0; index < lines.length; index++) {
480
+ const panel = /^(:{2,})framework\{name="([^"]+)"\}\s*$/.exec(lines[index]);
481
+ if (panel) {
482
+ for (index++; index < lines.length && lines[index].trim() !== panel[1]; index++) if (panel[2] === framework) out.push(lines[index]);
483
+ continue;
484
+ }
485
+ const tabs = /^(:{2,})tabs\{[^}]*sync="framework"[^}]*\}\s*$/.exec(lines[index]);
486
+ if (!tabs) {
487
+ out.push(lines[index]);
488
+ continue;
489
+ }
490
+ const colons = tabs[1];
491
+ let keep = false;
492
+ for (index++; index < lines.length && lines[index].trim() !== colons; index++) {
493
+ const line = lines[index];
494
+ const item = new RegExp(`^${colons}:tabs-item\\{[^}]*label="([^"]*)"`).exec(line);
495
+ if (item) keep = item[1] === framework;
496
+ else if (line.trim() === `${colons}:`) keep = false;
497
+ else if (keep) out.push(line);
498
+ }
499
+ }
500
+ return out.join("\n");
501
+ }
502
+ /** The `::tutorial-step` blocks of a page, in order, with the file labels of their code blocks. */
503
+ function parseTutorialSteps(markdown) {
504
+ const steps = [];
505
+ markdown = frameworkView(markdown, "Vite");
506
+ for (const match of markdown.matchAll(/^::tutorial-step\{([^}]*)\}\n([\s\S]*?)^::$/gm)) {
507
+ const title = /title="([^"]*)"/.exec(match[1])?.[1];
508
+ if (!title) throw docsErrorDiagnostics.DOCS_RUNNABLE_TITLE_MISSING({ block: `::tutorial-step{${match[1]}}` });
509
+ steps.push({
510
+ title,
511
+ labels: codeBlockLabels(match[2]).filter(isTutorialFileLabel)
512
+ });
513
+ }
514
+ return steps;
515
+ }
516
+ /** The code block of `label` in a page, without its fences. */
517
+ function codeBlock(markdown, label) {
518
+ markdown = frameworkView(markdown, "Vite");
519
+ const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
520
+ const match = new RegExp("^```[^\\n]*\\[" + escaped + "\\]\\n([\\s\\S]*?)\\n```", "m").exec(markdown);
521
+ return match ? `${match[1]}\n` : void 0;
522
+ }
523
+ /** Whether `entry`, a name in a fixture folder, is a generated or installed file that the workspace makes itself. */
524
+ function isIgnoredEntry(entry) {
525
+ return ignoredEntries.has(entry);
526
+ }
527
+ /**
528
+ * The text of a file, with its BOM, or `undefined` for a binary file: bytes that are not valid UTF-8, or that hold a
529
+ * NUL byte, such as WebAssembly modules and model weights.
530
+ */
531
+ function decodeText(bytes) {
532
+ if (bytes.includes(0)) return void 0;
533
+ try {
534
+ return new TextDecoder("utf-8", {
535
+ fatal: true,
536
+ ignoreBOM: true
537
+ }).decode(bytes);
538
+ } catch {
539
+ return;
540
+ }
541
+ }
542
+ /**
543
+ * The files of a fixture folder, without generated, installed or private files: the text files in `files`, and the files
544
+ * that are not valid UTF-8, such as model weights, in `assets`.
545
+ */
546
+ async function readTree(root) {
547
+ const files = {};
548
+ const assets = {};
549
+ async function walk(directory) {
550
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
551
+ if (ignoredEntries.has(entry.name) || entry.isFile() && isPrivateFile(entry.name)) continue;
552
+ const path = join(directory, entry.name);
553
+ if (entry.isDirectory()) await walk(path);
554
+ else if (entry.isFile()) {
555
+ const name = relative(root, path).replaceAll("\\", "/");
556
+ const bytes = new Uint8Array(await readFile(path));
557
+ const text = decodeText(bytes);
558
+ if (text === void 0) assets[name] = bytes;
559
+ else files[name] = text;
560
+ }
561
+ }
562
+ }
563
+ await walk(root);
564
+ return {
565
+ files,
566
+ assets
567
+ };
568
+ }
569
+ /** No pnpm workspace: `catalog:` and `workspace:` specifiers fail, and every dependency installs from npm. */
570
+ const noWorkspaceVersions = {
571
+ catalogs: {},
572
+ packages: {}
573
+ };
574
+ async function readPnpmWorkspace(root) {
575
+ const workspace = parse$1(await readFile(resolve(root, "pnpm-workspace.yaml"), "utf8"));
576
+ return workspace && typeof workspace === "object" ? workspace : {};
577
+ }
578
+ const isNodeModules = (path) => path.split(/[\\/]/).includes("node_modules");
579
+ /**
580
+ * The folders of the workspace packages, sorted, as pnpm finds them: the root and each folder with a `package.json`
581
+ * that a `packages` pattern of `pnpm-workspace.yaml` matches and no `!` pattern excludes.
582
+ */
583
+ async function workspacePackageDirs(root) {
584
+ const { packages } = await readPnpmWorkspace(root);
585
+ const patterns = Array.isArray(packages) ? packages.filter((pattern) => typeof pattern === "string").map((pattern) => pattern.replace(/\/+$/, "")) : [];
586
+ const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => pattern.slice(1));
587
+ const included = patterns.filter((pattern) => !pattern.startsWith("!")).map((pattern) => `${pattern}/package.json`);
588
+ const dirs = /* @__PURE__ */ new Set();
589
+ for await (const file of glob(["package.json", ...included], {
590
+ cwd: root,
591
+ exclude: isNodeModules
592
+ })) {
593
+ const dir = file.replaceAll("\\", "/").replace(/\/?package\.json$/, "");
594
+ if (!excluded.some((pattern) => matchesGlob(dir, pattern))) dirs.add(resolve(root, dir));
595
+ }
596
+ return [...dirs].sort();
597
+ }
598
+ /** Reads the pnpm catalogs and the versions of the workspace packages that fixtures depend on. */
599
+ async function readWorkspaceVersions(root) {
600
+ const record = await readPnpmWorkspace(root);
601
+ const catalogs = {};
602
+ if (record.catalog && typeof record.catalog === "object") catalogs.default = record.catalog;
603
+ if (record.catalogs && typeof record.catalogs === "object") Object.assign(catalogs, record.catalogs);
604
+ const packages = {};
605
+ for (const dir of await workspacePackageDirs(root)) {
606
+ const manifest = await readFile(resolve(dir, "package.json"), "utf8").then(JSON.parse, () => void 0);
607
+ if (!manifest || typeof manifest !== "object") continue;
608
+ const { name, version } = manifest;
609
+ if (typeof name === "string" && typeof version === "string") packages[name] = version;
610
+ }
611
+ return {
612
+ catalogs,
613
+ packages
614
+ };
615
+ }
616
+ const isStringRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value) && Object.values(value).every((item) => typeof item === "string");
617
+ /**
618
+ * Rewrites `catalog:` and `workspace:` specifiers to npm versions, so `npm install` works outside the pnpm workspace.
619
+ * A workspace package resolves to the published range of its current version.
620
+ */
621
+ function resolveDependencies(dependencies, versions) {
622
+ const resolved = {};
623
+ for (const [name, specifier] of Object.entries(dependencies)) if (specifier.startsWith("catalog:")) {
624
+ const catalog = specifier.slice(8) || "default";
625
+ const version = versions.catalogs[catalog]?.[name];
626
+ if (!version) throw docsErrorDiagnostics.DOCS_RUNNABLE_CATALOG_VERSION_MISSING({
627
+ catalog,
628
+ name
629
+ });
630
+ resolved[name] = version;
631
+ } else if (specifier.startsWith("workspace:")) {
632
+ const version = versions.packages[name];
633
+ if (!version) throw docsErrorDiagnostics.DOCS_RUNNABLE_WORKSPACE_PACKAGE_MISSING({ name });
634
+ resolved[name] = `^${version}`;
635
+ } else resolved[name] = specifier;
636
+ return resolved;
637
+ }
638
+ /** A `package.json` with the `dependencies` and `devDependencies` of `resolveDependencies()`. Other JSON stays as it is. */
639
+ function resolveManifest(source, versions) {
640
+ const manifest = JSON.parse(source);
641
+ if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) return source;
642
+ const resolved = { ...manifest };
643
+ for (const field of ["dependencies", "devDependencies"]) {
644
+ const dependencies = resolved[field];
645
+ if (isStringRecord(dependencies)) resolved[field] = resolveDependencies(dependencies, versions);
646
+ }
647
+ return `${JSON.stringify(resolved, null, 2)}\n`;
648
+ }
649
+ /**
650
+ * Builds the workspace files of one lesson.
651
+ *
652
+ * The fixture is the app after the last step, and every file code block in the lesson equals a fixture file. So step N
653
+ * writes the fixture version of the files that its code blocks name. Before step 1 the app is the fixture without those
654
+ * files, except where the `start` page already shows a version, such as `vite.config.ts`.
655
+ */
656
+ async function buildRunnableTutorial(input) {
657
+ const { source, fixturesDir, versions } = input;
658
+ const readPage = (page) => {
659
+ const markdown = input.readPage(page);
660
+ if (markdown === void 0) throw docsErrorDiagnostics.DOCS_RUNNABLE_PAGE_MISSING({ page });
661
+ return markdown.replaceAll("\r\n", "\n");
662
+ };
663
+ const lesson = readPage(source.page);
664
+ const start = input.start ? readPage(input.start) : "";
665
+ const { files: fixture } = await readTree(resolve(fixturesDir, source.fixture));
666
+ if (fixture["package.json"]) fixture["package.json"] = resolveManifest(fixture["package.json"], versions);
667
+ const parsed = parseTutorialSteps(lesson);
668
+ if (parsed.length === 0) throw docsErrorDiagnostics.DOCS_RUNNABLE_STEPS_MISSING({ page: source.page });
669
+ const files = { ...fixture };
670
+ const steps = parsed.map(({ title, labels }) => {
671
+ const stepFiles = {};
672
+ for (const label of labels) {
673
+ const contents = fixture[label];
674
+ if (contents === void 0) throw docsErrorDiagnostics.DOCS_RUNNABLE_FIXTURE_FILE_MISSING({
675
+ fixture: source.fixture,
676
+ label,
677
+ page: source.page
678
+ });
679
+ stepFiles[label] = contents;
680
+ }
681
+ return {
682
+ title,
683
+ files: stepFiles
684
+ };
685
+ });
686
+ for (const step of steps) for (const path of Object.keys(step.files)) {
687
+ const before = codeBlock(start, path);
688
+ if (before === void 0) delete files[path];
689
+ else files[path] = before;
690
+ }
691
+ return {
692
+ slug: source.slug,
693
+ page: source.page,
694
+ title: frontmatterField(lesson, "title"),
695
+ description: frontmatterField(lesson, "description"),
696
+ files,
697
+ steps
698
+ };
699
+ }
700
+ //#endregion
701
+ //#region src/runnable/workspaces.ts
702
+ /** The `playground` and `learn` pages of the site. */
703
+ function workspacePages(pages) {
704
+ return pages.filter((page) => (page.layout === "playground" || page.layout === "learn") && !!page.workspace);
705
+ }
706
+ /**
707
+ * The paths that must be cross-origin isolated: each `learn` page, and each `playground` page without `render`. A
708
+ * WebContainer runs only there. A `render` page runs in the page, so it stays a plain page.
709
+ */
710
+ function webContainerRoutes(pages) {
711
+ return workspacePages(pages).filter((page) => page.layout === "learn" || !page.workspace.render).map((page) => page.path);
712
+ }
713
+ /**
714
+ * The id of a page in file names, snapshot names, and zip names: `/learn/first-kv` is `learn-first-kv`. It has no
715
+ * `--`, so the ids of a page's examples, `<page id>--<example id>`, never start with the id of another page.
716
+ */
717
+ function workspacePageSlug(path) {
718
+ return path.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "index";
719
+ }
720
+ /** Fails the build when two pages get one id, such as `/docs/a/b` and `/docs/a-b`. */
721
+ function checkWorkspacePageIds(pages) {
722
+ const seen = /* @__PURE__ */ new Map();
723
+ for (const page of pages) {
724
+ const id = workspacePageSlug(page.path);
725
+ const other = seen.get(id);
726
+ if (other !== void 0) throw docsErrorDiagnostics.DOCS_WORKSPACE_ID_COLLISION({
727
+ id,
728
+ owners: [`the page ${other}`, `the page ${page.path}`]
729
+ });
730
+ seen.set(id, page.path);
731
+ }
732
+ }
733
+ /**
734
+ * Fails the build when two lessons, two examples, or two snapshots get one id, configured or from a page. A configured
735
+ * lesson `learn-first-kv` and the page `/learn/first-kv` collide, and so do the lesson of `/playground/kv` and the
736
+ * snapshot `playground-kv` of an example `kv`.
737
+ */
738
+ function checkRunnableIds(lessons, examples) {
739
+ const seen = /* @__PURE__ */ new Map();
740
+ const claim = (kind, id, owner) => {
741
+ const key = `${kind} ${id.toLowerCase()}`;
742
+ const other = seen.get(key);
743
+ if (other !== void 0) throw docsErrorDiagnostics.DOCS_WORKSPACE_ID_COLLISION({
744
+ id,
745
+ owners: [other, owner]
746
+ });
747
+ seen.set(key, owner);
748
+ };
749
+ for (const lesson of lessons) claim("snapshot", lesson.slug, `the lesson ${lesson.slug} of ${lesson.page}`);
750
+ for (const example of examples) {
751
+ claim("example", example.id, `the example ${example.id}`);
752
+ claim("snapshot", `playground-${example.id}`, `the example ${example.id}`);
753
+ }
754
+ }
755
+ /** The lesson of a `learn` page: its steps come from `lesson`, or from the page itself. */
756
+ function learnLessonSource(page) {
757
+ return {
758
+ slug: workspacePageSlug(page.path),
759
+ page: page.workspace.lesson ?? page.path,
760
+ fixture: page.workspace.fixture ?? ""
761
+ };
762
+ }
763
+ const exampleSeparator = "--";
764
+ /**
765
+ * The examples of a `playground` page that runs a WebContainer, as playground sources. They share the snapshot of a
766
+ * lesson or of another example with the same dependencies. The id names the page, so two pages can use one example id.
767
+ */
768
+ function playgroundExampleSources(page, rootDir) {
769
+ return (page.workspace.examples ?? []).map((example) => ({
770
+ id: `${workspacePageSlug(page.path)}${exampleSeparator}${example.id}`,
771
+ label: example.label,
772
+ description: example.description,
773
+ group: example.group,
774
+ fixture: resolve(rootDir, example.dir),
775
+ open: example.open,
776
+ preview: example.preview,
777
+ readonly: example.readonly
778
+ }));
779
+ }
780
+ function isTextFileOf(dir, path) {
781
+ const parts = path.split("/");
782
+ if (isAbsolute(path) || path.includes("\\") || parts.some((part) => part === "" || part === "." || part === ".." || isIgnoredEntry(part)) || isPrivateFile(parts.at(-1))) return false;
783
+ if (parts.map((_, index) => lstatSync(resolve(dir, ...parts.slice(0, index + 1)), { throwIfNoEntry: false })).some((stat, index) => !(index === parts.length - 1 ? stat?.isFile() : stat?.isDirectory()))) return false;
784
+ return decodeText(readFileSync(resolve(dir, path))) !== void 0;
785
+ }
786
+ /**
787
+ * Fails the build for a folder, a `render` module, or a tab component that a page names and that does not exist, and
788
+ * for a `readonly` path that is not a text file of its example.
789
+ */
790
+ function checkWorkspacePage(page, input) {
791
+ const { workspace } = page;
792
+ const dirs = page.layout === "learn" ? [resolve(input.fixturesDir, workspace.fixture ?? "")] : (workspace.examples ?? []).map((example) => resolve(input.rootDir, example.dir));
793
+ for (const dir of dirs) if (!existsSync(dir)) throw docsErrorDiagnostics.DOCS_WORKSPACE_DIR_MISSING({
794
+ page: page.path,
795
+ dir
796
+ });
797
+ for (const example of workspace.examples ?? []) {
798
+ const dir = resolve(input.rootDir, example.dir);
799
+ for (const path of example.readonly ?? []) if (!isTextFileOf(dir, path)) throw docsErrorDiagnostics.DOCS_WORKSPACE_READONLY_MISSING({
800
+ page: page.path,
801
+ example: example.id,
802
+ path,
803
+ dir: example.dir
804
+ });
805
+ }
806
+ if (workspace.render && !existsSync(resolve(input.rootDir, workspace.render))) throw docsErrorDiagnostics.DOCS_WORKSPACE_RENDER_MISSING({
807
+ page: page.path,
808
+ file: workspace.render
809
+ });
810
+ for (const tab of workspace.tabs ?? []) {
811
+ const file = workspaceTabComponent(input.srcDir, tab.value);
812
+ if (!existsSync(file)) throw docsErrorDiagnostics.DOCS_WORKSPACE_TAB_MISSING({
813
+ page: page.path,
814
+ tab: tab.value,
815
+ file
816
+ });
817
+ }
818
+ }
819
+ /** The component of a tab: `messages` is `<srcDir>/components/playground/PlaygroundTabMessages.vue`. */
820
+ function workspaceTabComponent(srcDir, value) {
821
+ const name = value.split(/[-_]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
822
+ return resolve(srcDir, "components/playground", `PlaygroundTab${name}.vue`);
823
+ }
824
+ /** The examples of a `render` page, with their files and binary files. They need no snapshot. */
825
+ async function renderExamples(page, rootDir) {
826
+ return Promise.all((page.workspace.examples ?? []).map(async (example) => {
827
+ const { files, assets } = await readTree(resolve(rootDir, example.dir));
828
+ const { id, label, description, group, open, preview, readonly } = example;
829
+ return {
830
+ id,
831
+ label,
832
+ description,
833
+ group,
834
+ open,
835
+ preview,
836
+ readonly,
837
+ files,
838
+ ...Object.keys(assets).length ? { assets } : {}
839
+ };
840
+ }));
841
+ }
842
+ /** The examples of a WebContainer page from the built templates, with their own ids again. */
843
+ function pageExamples(page, templates) {
844
+ const prefix = `${workspacePageSlug(page.path)}${exampleSeparator}`;
845
+ return templates.filter((template) => template.id.startsWith(prefix)).map((template) => ({
846
+ ...template,
847
+ id: template.id.slice(prefix.length)
848
+ }));
849
+ }
850
+ const decodeAssets = [
851
+ `const bytes = text => Uint8Array.from(atob(text), char => char.charCodeAt(0))`,
852
+ `for (const example of data.examples) {`,
853
+ ` const encoded = Object.hasOwn(assets, example.id) ? assets[example.id] : undefined`,
854
+ ` if (encoded) example.assets = Object.fromEntries(Object.entries(encoded).map(([path, text]) => [path, bytes(text)]))`,
855
+ `}`
856
+ ];
857
+ /**
858
+ * The JavaScript of a page module. `render` and the tab components are imports, so the page loads them with its data
859
+ * and Vite bundles them with the app. JSON has no bytes, so the binary files of the examples are base64 in the module,
860
+ * and the module decodes them when it loads.
861
+ */
862
+ function workspacePageModule(data, loaders = {}) {
863
+ if (data.layout === "learn") return pageModule(data, loaders);
864
+ const assets = {};
865
+ const examples = data.examples.map(({ assets: bytes, ...example }) => {
866
+ if (bytes) assets[example.id] = Object.fromEntries(Object.entries(bytes).map(([path, contents]) => [path, Buffer$1.from(contents).toString("base64")]));
867
+ return example;
868
+ });
869
+ return pageModule({
870
+ ...data,
871
+ examples
872
+ }, loaders, Object.keys(assets).length ? [`const assets = ${JSON.stringify(assets)}`, ...decodeAssets] : []);
873
+ }
874
+ function pageModule(data, loaders, decode = []) {
875
+ const lines = [`const data = ${JSON.stringify(data)}`, ...decode];
876
+ if (loaders.render) lines.push(`data.render = () => import(${JSON.stringify(loaders.render)})`);
877
+ if (loaders.tabs?.length) lines.push(`data.tabs = [`, ...loaders.tabs.map((tab) => ` { value: ${JSON.stringify(tab.value)}, label: ${JSON.stringify(tab.label)}, component: () => import(${JSON.stringify(tab.file)}) },`), `]`);
878
+ lines.push("export default data", "");
879
+ return lines.join("\n");
880
+ }
881
+ //#endregion
882
+ //#region src/workspace-nuxt.ts
883
+ /**
884
+ * The `webContainer` defaults of `vite-hub/nuxt` for the pages that run a WebContainer. `vite-hub/nuxt` sends the
885
+ * cross-origin isolation headers on these routes only. The defaults merge with the app's own `vitehub.webContainer.routes`,
886
+ * and they reach `vite-hub/nuxt` in either module order. Without such pages there are none.
887
+ */
888
+ async function docsWebContainerDefaults(nuxt, routes) {
889
+ if (routes.length === 0) return void 0;
890
+ if (!await viteHubModuleOptions(nuxt)) throw docsErrorDiagnostics.DOCS_WORKSPACE_VITEHUB_MISSING({ pages: routes });
891
+ return { webContainer: { routes: [...routes] } };
892
+ }
893
+ //#endregion
894
+ //#region src/runnable/learn.ts
895
+ /**
896
+ * Reading at 200 words a minute, plus 2 minutes to do each step, rounded up to 5 minutes.
897
+ * Code blocks do not count as reading, because the reader copies or opens them.
898
+ */
899
+ function tutorialMinutes(markdown) {
900
+ const words = markdown.replace(/^```[\s\S]*?^```/gm, "").replace(/^---[\s\S]*?^---/m, "").split(/\s+/).filter(Boolean).length;
901
+ const steps = tutorialSteps(markdown);
902
+ return Math.max(5, Math.ceil((words / 200 + steps * 2) / 5) * 5);
903
+ }
904
+ function tutorialSteps(markdown) {
905
+ return markdown.match(/^::tutorial-step\b/gm)?.length ?? 0;
906
+ }
907
+ /** The facts of a page with `layout: tutorial`, from its Markdown. */
908
+ function tutorialPageFacts(markdown) {
909
+ markdown = markdown.replaceAll("\r\n", "\n");
910
+ return {
911
+ steps: tutorialSteps(markdown),
912
+ minutes: tutorialMinutes(markdown)
913
+ };
914
+ }
915
+ //#endregion
916
+ //#region src/runnable/playground.ts
917
+ /**
918
+ * Reads the files of each example from its fixture.
919
+ *
920
+ * A snapshot holds the `dependencies` of a fixture. An example whose fixture has the same dependencies as the fixture
921
+ * of a lesson names that lesson in `snapshotOf`, so the playground mounts the same snapshot and the browser keeps one
922
+ * copy. Any other example names `playground-<id>` of the first example with its dependencies, and `snapshotSources`
923
+ * adds a snapshot for it.
924
+ */
925
+ async function buildPlaygroundTemplates(input) {
926
+ const manifest = (fixture) => readFile(resolve(input.fixturesDir, fixture, "package.json"), "utf8").catch(() => void 0);
927
+ const tutorialKeys = await Promise.all(input.tutorials.map(async (tutorial) => ({
928
+ slug: tutorial.slug,
929
+ key: dependencyKey(await manifest(tutorial.fixture))
930
+ })));
931
+ const read = await Promise.all(input.examples.map(async (source) => {
932
+ const { files, assets } = await readTree(resolve(input.fixturesDir, source.fixture));
933
+ if (files["package.json"]) files["package.json"] = resolveManifest(files["package.json"], input.versions);
934
+ return {
935
+ source,
936
+ files,
937
+ assets,
938
+ key: dependencyKey(await manifest(source.fixture))
939
+ };
940
+ }));
941
+ const shared = new Map(tutorialKeys.toReversed().map((tutorial) => [tutorial.key, tutorial.slug]));
942
+ return read.map(({ source, files, assets, key }) => {
943
+ const snapshotOf = shared.get(key) ?? `playground-${source.id}`;
944
+ shared.set(key, snapshotOf);
945
+ const { id, label, description, group, open, preview, readonly } = source;
946
+ return {
947
+ id,
948
+ label,
949
+ description,
950
+ group,
951
+ open,
952
+ preview,
953
+ readonly,
954
+ files,
955
+ ...Object.keys(assets).length ? { assets } : {},
956
+ snapshotOf
957
+ };
958
+ });
959
+ }
960
+ /** The lessons, and a source for each example that shares no snapshot with a lesson. */
961
+ function snapshotSources(tutorials, examples, templates) {
962
+ const own = templates.filter((template) => template.snapshotOf === `playground-${template.id}`);
963
+ return [...tutorials, ...own.map((template) => {
964
+ const example = examples.find((source) => source.id === template.id);
965
+ if (!example) throw invariantError(`a playground template comes from an example (${template.id})`);
966
+ return {
967
+ slug: template.snapshotOf,
968
+ page: "/playground",
969
+ fixture: example.fixture
970
+ };
971
+ })];
972
+ }
973
+ //#endregion
974
+ //#region src/runnable/snapshots.ts
975
+ const SNAPSHOT_CONCURRENCY = 3;
976
+ /** Runs `snapshot-worker.mjs` and returns its stdout. Its warnings, such as an updated lockfile, go to stderr. */
977
+ function runSnapshotWorker(args) {
978
+ return new Promise((resolvePromise, reject) => {
979
+ const child = spawn(process.execPath, [resolve(import.meta.dirname, "snapshot-worker.mjs"), ...args], { stdio: [
980
+ "ignore",
981
+ "pipe",
982
+ "inherit"
983
+ ] });
984
+ let stdout = "";
985
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
986
+ stdout += chunk;
987
+ });
988
+ child.once("error", reject);
989
+ child.once("close", (code) => code === 0 ? resolvePromise(stdout) : reject(/* @__PURE__ */ new Error(`snapshot-worker.mjs exited with code ${code} for ${args[2]}.`)));
990
+ });
991
+ }
992
+ /** The npm lockfile that pins the install of a fixture: `<fixture>.package-lock.json` beside the fixture folder. */
993
+ function tutorialLockfile(fixturesDir, fixture) {
994
+ return resolve(fixturesDir, `${fixture}.package-lock.json`);
995
+ }
996
+ const isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
997
+ const stringRecord = (value) => isRecord(value) ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string")) : {};
998
+ /** The fields of a `package.json` that a snapshot reads. Other values, and invalid JSON, read as empty. */
999
+ function readManifest(source) {
1000
+ let json;
1001
+ try {
1002
+ json = source === void 0 ? void 0 : JSON.parse(source);
1003
+ } catch {
1004
+ json = void 0;
1005
+ }
1006
+ const record = isRecord(json) ? json : {};
1007
+ const meta = isRecord(record.peerDependenciesMeta) ? record.peerDependenciesMeta : {};
1008
+ return {
1009
+ name: typeof record.name === "string" ? record.name : void 0,
1010
+ private: record.private === true,
1011
+ scripts: stringRecord(record.scripts),
1012
+ dependencies: stringRecord(record.dependencies),
1013
+ devDependencies: stringRecord(record.devDependencies),
1014
+ peerDependencies: stringRecord(record.peerDependencies),
1015
+ optionalPeers: new Set(Object.entries(meta).filter(([, value]) => isRecord(value) && value.optional === true).map(([name]) => name))
1016
+ };
1017
+ }
1018
+ /**
1019
+ * The package that the `dev` script of a fixture runs, when it is in `devDependencies`. A snapshot installs
1020
+ * `dependencies` only, so the workspace could not start that dev server.
1021
+ */
1022
+ function devServerInDevDependencies(manifest) {
1023
+ const command = manifest.scripts.dev?.trim().split(/\s+/)[0];
1024
+ return command && command in manifest.devDependencies && !(command in manifest.dependencies) ? command : void 0;
1025
+ }
1026
+ /** The output line of `snapshot-worker.mjs`. */
1027
+ function readWorkerResult(stdout) {
1028
+ const result = JSON.parse(stdout.trim().split("\n").at(-1) ?? "");
1029
+ if (isRecord(result) && Array.isArray(result.files) && result.files.every((file) => typeof file === "string") && typeof result.sha256 === "string" && typeof result.bytes === "number" && typeof result.compressed === "number") return {
1030
+ files: result.files,
1031
+ sha256: result.sha256,
1032
+ bytes: result.bytes,
1033
+ compressed: result.compressed
1034
+ };
1035
+ throw invariantError(`snapshot-worker.mjs prints its files, hash, and sizes as its last line (${stdout.slice(-200)})`);
1036
+ }
1037
+ const dependencyFields = [
1038
+ "dependencies",
1039
+ "devDependencies",
1040
+ "optionalDependencies",
1041
+ "peerDependencies",
1042
+ "peerDependenciesMeta"
1043
+ ];
1044
+ /**
1045
+ * `pnpm pack` writes the dependencies that had `workspace:` specifiers in a different order on each run. The installed
1046
+ * `package.json` would then change the snapshot bytes, so sort those fields and pack the tarball again.
1047
+ */
1048
+ async function sortPackedManifest(tarball, scratch) {
1049
+ await rm(scratch, {
1050
+ recursive: true,
1051
+ force: true
1052
+ });
1053
+ await mkdir(scratch, { recursive: true });
1054
+ execFileSync("tar", [
1055
+ "-xzf",
1056
+ tarball,
1057
+ "-C",
1058
+ scratch
1059
+ ]);
1060
+ const path = resolve(scratch, "package/package.json");
1061
+ const manifest = JSON.parse(await readFile(path, "utf8"));
1062
+ for (const field of dependencyFields) {
1063
+ const value = manifest[field];
1064
+ if (value && typeof value === "object") manifest[field] = Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)));
1065
+ }
1066
+ await writeFile(path, `${JSON.stringify(manifest, null, 2)}\n`);
1067
+ execFileSync("tar", [
1068
+ "-czf",
1069
+ tarball,
1070
+ "-C",
1071
+ scratch,
1072
+ "package"
1073
+ ]);
1074
+ await rm(scratch, {
1075
+ recursive: true,
1076
+ force: true
1077
+ });
1078
+ }
1079
+ /**
1080
+ * A hash of everything that decides what a snapshot installs: the fixture manifests, the npm lockfiles of the
1081
+ * fixtures, and with a pnpm workspace its catalogs, its lockfile, and the manifest of every workspace package. Source
1082
+ * code is not in it: a dev server reuses a snapshot with older package code until `TUTORIAL_SNAPSHOTS=1` rebuilds it.
1083
+ */
1084
+ async function tutorialSnapshotInputs(input) {
1085
+ const hash = createHash("sha256");
1086
+ const add = (label, contents) => hash.update(`${label}\0${contents}\0`);
1087
+ const read = (path) => readFile(path, "utf8").catch(() => "");
1088
+ add("versions", JSON.stringify(input.versions));
1089
+ for (const tutorial of input.tutorials) {
1090
+ add(`${tutorial.slug} fixture`, await read(resolve(input.fixturesDir, tutorial.fixture, "package.json")));
1091
+ add(`${tutorial.slug} lockfile`, await read(tutorialLockfile(input.fixturesDir, tutorial.fixture)));
1092
+ }
1093
+ if (input.workspaceRoot) {
1094
+ add("pnpm-lock.yaml", await read(resolve(input.workspaceRoot, "pnpm-lock.yaml")));
1095
+ for (const dir of await workspacePackageDirs(input.workspaceRoot)) add(relative(input.workspaceRoot, dir).replaceAll("\\", "/"), await read(resolve(dir, "package.json")));
1096
+ }
1097
+ return hash.digest("hex");
1098
+ }
1099
+ /**
1100
+ * Reads the snapshots of the last build when they were built from `inputs`. Removes them, and returns nothing, when
1101
+ * snapshots are disabled.
1102
+ */
1103
+ async function readTutorialSnapshots(outDir, options) {
1104
+ if (options.disabled) {
1105
+ await rm(resolve(outDir, "snapshots"), {
1106
+ recursive: true,
1107
+ force: true
1108
+ });
1109
+ await rm(resolve(outDir, "snapshots.json"), { force: true });
1110
+ return;
1111
+ }
1112
+ const file = await readFile(resolve(outDir, "snapshots.json"), "utf8").then(JSON.parse, () => void 0);
1113
+ return file?.inputs === options.inputs ? file.tutorials : void 0;
1114
+ }
1115
+ /**
1116
+ * Builds the `node_modules` snapshot of each tutorial, so its workspace skips `npm install` in the browser.
1117
+ *
1118
+ * With a pnpm workspace, this builds and packs the workspace packages that each fixture uses, so the snapshot holds
1119
+ * the code that the docs describe. It installs them with the other dependencies of the fixture through
1120
+ * `createNodeModulesSnapshot` in `snapshot-worker.mjs`, pinned by the npm lockfile beside the fixture, and writes the
1121
+ * gzip parts to `<outDir>/snapshots/` with `snapshots.json` beside them. A build that resolves new versions writes the
1122
+ * lockfile.
1123
+ */
1124
+ async function buildTutorialSnapshots(input) {
1125
+ const { workspaceRoot, outDir, workDir } = input;
1126
+ const workspace = /* @__PURE__ */ new Map();
1127
+ for (const dir of workspaceRoot ? await workspacePackageDirs(workspaceRoot) : []) {
1128
+ const manifest = readManifest(await readFile(resolve(dir, "package.json"), "utf8").catch(() => void 0));
1129
+ if (manifest.name) workspace.set(manifest.name, {
1130
+ dir,
1131
+ manifest
1132
+ });
1133
+ }
1134
+ const closure = (names) => {
1135
+ const seen = /* @__PURE__ */ new Set();
1136
+ const visit = (name) => {
1137
+ const found = workspace.get(name);
1138
+ if (!found || found.manifest.private || seen.has(name)) return;
1139
+ seen.add(name);
1140
+ for (const dependency of Object.keys(found.manifest.dependencies)) visit(dependency);
1141
+ };
1142
+ names.forEach(visit);
1143
+ return [...seen];
1144
+ };
1145
+ const run = (command, args, cwd) => execFileSync(command, args, {
1146
+ cwd,
1147
+ stdio: [
1148
+ "ignore",
1149
+ "ignore",
1150
+ "inherit"
1151
+ ]
1152
+ });
1153
+ const snapshotsDir = resolve(outDir, "snapshots");
1154
+ await rm(snapshotsDir, {
1155
+ recursive: true,
1156
+ force: true
1157
+ });
1158
+ await mkdir(snapshotsDir, { recursive: true });
1159
+ await rm(workDir, {
1160
+ recursive: true,
1161
+ force: true
1162
+ });
1163
+ const plans = (await Promise.all(input.tutorials.map(async (tutorial) => {
1164
+ const source = readManifest(await readFile(resolve(input.fixturesDir, tutorial.fixture, "package.json"), "utf8"));
1165
+ const devServer = devServerInDevDependencies(source);
1166
+ if (devServer) throw docsErrorDiagnostics.DOCS_RUNNABLE_DEV_SERVER_MISSING({
1167
+ fixture: tutorial.fixture,
1168
+ name: devServer
1169
+ });
1170
+ const local = Object.entries(source.dependencies).filter(([, specifier]) => specifier.startsWith("workspace:")).map(([name]) => name);
1171
+ return {
1172
+ tutorial,
1173
+ source,
1174
+ local,
1175
+ packages: closure(local)
1176
+ };
1177
+ }))).filter((plan) => Object.keys(plan.source.dependencies).length > 0);
1178
+ const packed = [...new Set(plans.flatMap((plan) => plan.packages))];
1179
+ if (workspaceRoot && packed.length > 0) {
1180
+ const filters = packed.flatMap((name) => ["--filter", `${name}...`]);
1181
+ const vp = resolve(workspaceRoot, "node_modules/.bin/vp");
1182
+ if (existsSync(vp)) run(vp, [
1183
+ "run",
1184
+ "--cache",
1185
+ ...filters,
1186
+ "build"
1187
+ ], workspaceRoot);
1188
+ else run("pnpm", [
1189
+ "--recursive",
1190
+ ...filters,
1191
+ "run",
1192
+ "--if-present",
1193
+ "build"
1194
+ ], workspaceRoot);
1195
+ }
1196
+ const tarballDir = resolve(workDir, "tarballs");
1197
+ await mkdir(tarballDir, { recursive: true });
1198
+ const tarballFiles = /* @__PURE__ */ new Map();
1199
+ for (const name of packed) {
1200
+ const before = new Set(await readdir(tarballDir));
1201
+ run("pnpm", [
1202
+ "pack",
1203
+ "--pack-destination",
1204
+ tarballDir
1205
+ ], workspace.get(name).dir);
1206
+ const file = (await readdir(tarballDir)).find((candidate) => !before.has(candidate));
1207
+ if (!file) throw docsErrorDiagnostics.DOCS_RUNNABLE_PACK_FAILED({ name });
1208
+ await sortPackedManifest(resolve(tarballDir, file), resolve(workDir, "unpacked"));
1209
+ tarballFiles.set(name, file);
1210
+ }
1211
+ const buildSnapshot = async ({ tutorial, source, local, packages }) => {
1212
+ const started = performance.now();
1213
+ const work = resolve(workDir, tutorial.slug);
1214
+ await mkdir(resolve(work, "tarballs"), { recursive: true });
1215
+ const tarballs = {};
1216
+ for (const name of packages) {
1217
+ const file = tarballFiles.get(name);
1218
+ await copyFile(resolve(tarballDir, file), resolve(work, "tarballs", file));
1219
+ tarballs[name] = `file:./tarballs/${file}`;
1220
+ }
1221
+ const peers = {};
1222
+ for (const name of packages) {
1223
+ const { peerDependencies, optionalPeers } = workspace.get(name).manifest;
1224
+ for (const [peer, specifier] of Object.entries(peerDependencies)) if (!optionalPeers.has(peer) && !tarballs[peer] && !peer.startsWith("@types/")) peers[peer] = specifier;
1225
+ }
1226
+ const dependencies = resolveDependencies({
1227
+ ...peers,
1228
+ ...source.dependencies
1229
+ }, input.versions);
1230
+ for (const name of local) dependencies[name] = tarballs[name];
1231
+ await writeFile(resolve(work, "package.json"), `${JSON.stringify({
1232
+ name: source.name,
1233
+ private: true,
1234
+ dependencies,
1235
+ overrides: tarballs
1236
+ }, null, 2)}\n`);
1237
+ await writeFile(resolve(work, ".npmrc"), "legacy-peer-deps=true\n");
1238
+ const lockfile = tutorialLockfile(input.fixturesDir, tutorial.fixture);
1239
+ const written = readWorkerResult(await runSnapshotWorker([
1240
+ work,
1241
+ snapshotsDir,
1242
+ tutorial.slug,
1243
+ lockfile
1244
+ ]));
1245
+ await rm(work, {
1246
+ recursive: true,
1247
+ force: true
1248
+ });
1249
+ console.info(`[docs] ${tutorial.slug}: ${(written.bytes / 2 ** 20).toFixed(1)} MiB of node_modules, ${(written.compressed / 2 ** 20).toFixed(1)} MiB in ${written.files.length} parts, sha256 ${written.sha256.slice(0, 12)}, built in ${((performance.now() - started) / 1e3).toFixed(0)} s`);
1250
+ return {
1251
+ parts: written.files,
1252
+ sha256: written.sha256
1253
+ };
1254
+ };
1255
+ const results = /* @__PURE__ */ new Map();
1256
+ const queue = [...plans];
1257
+ await Promise.all(Array.from({ length: SNAPSHOT_CONCURRENCY }, async () => {
1258
+ for (let plan = queue.shift(); plan; plan = queue.shift()) results.set(plan.tutorial.slug, await buildSnapshot(plan));
1259
+ }));
1260
+ await rm(workDir, {
1261
+ recursive: true,
1262
+ force: true
1263
+ });
1264
+ const snapshots = Object.fromEntries(plans.map((plan) => [plan.tutorial.slug, results.get(plan.tutorial.slug)]));
1265
+ const file = {
1266
+ inputs: await tutorialSnapshotInputs(input),
1267
+ tutorials: snapshots
1268
+ };
1269
+ await writeFile(resolve(outDir, "snapshots.json"), `${JSON.stringify(file, null, 2)}\n`);
1270
+ return snapshots;
1271
+ }
1272
+ //#endregion
1273
+ //#region src/runnable/nuxt.ts
1274
+ /** Where Nitro serves the snapshot parts, under the app base. */
1275
+ const baseURL = "/_tutorials";
1276
+ /**
1277
+ * Runnable lessons and playground examples.
1278
+ *
1279
+ * The pages with `layout: learn` and `layout: playground` are the lessons and the examples. Their frontmatter is the
1280
+ * only list. `lessons` and `examples` of the options add more, for app pages that render a workspace themselves. Both
1281
+ * share one snapshot build, so a lesson and an example with the same dependencies share one snapshot.
1282
+ *
1283
+ * At build time this reads each lesson and its fixture, and writes:
1284
+ * - `#build/docs/workspaces/<page>.mjs`: the workspace data of each `learn` and `playground` page. The result's
1285
+ * `workspaces` is the source of `#docs/workspaces`, which loads them by page path.
1286
+ * - `#build/runnable-tutorials.mjs`: the files before step 1 and the files that each step writes, for `lessons`.
1287
+ * - `#build/playground-templates.mjs`: the files of each example of `examples`, read from its fixture.
1288
+ * - `#build/learn-facts.mjs`: the step count and reading time of each page with `layout: tutorial` or `layout: learn`.
1289
+ * - `/_tutorials/snapshots/<slug>.<hash>.<part>.bin`: the `node_modules` of the workspace, so the browser skips
1290
+ * `npm install`. An example with the dependencies of a lesson mounts the snapshot of that lesson. `nuxt build` writes
1291
+ * them, pinned by the lockfile beside each fixture. `nuxt dev` reuses the last ones while their dependencies match
1292
+ * (`tutorialSnapshotInputs`). Set `TUTORIAL_SNAPSHOTS=1` to build them in development, or `TUTORIAL_SNAPSHOTS=0` to
1293
+ * skip them in a build. Without them the workspace installs. `nuxi prepare` never builds them.
1294
+ */
1295
+ async function setupDocsRunnable(options, input) {
1296
+ const { nuxt, content } = input;
1297
+ const rootDir = nuxt.options.rootDir;
1298
+ const fixturesDir = resolve(rootDir, options.fixtures ?? "fixtures");
1299
+ const pages = workspacePages(content.pages());
1300
+ checkWorkspacePageIds(pages);
1301
+ for (const page of pages) checkWorkspacePage(page, {
1302
+ rootDir,
1303
+ srcDir: nuxt.options.srcDir,
1304
+ fixturesDir
1305
+ });
1306
+ const learnPages = pages.filter((page) => page.layout === "learn");
1307
+ const containerPages = pages.filter((page) => page.layout === "playground" && !page.workspace.render);
1308
+ const renderPages = pages.filter((page) => page.layout === "playground" && page.workspace.render);
1309
+ const pageLessons = learnPages.map(learnLessonSource);
1310
+ const lessons = [...options.lessons ?? [], ...pageLessons];
1311
+ const examples = [...options.examples ?? [], ...containerPages.flatMap((page) => playgroundExampleSources(page, rootDir))];
1312
+ checkRunnableIds(lessons, examples);
1313
+ const workspaceRoot = options.pnpmWorkspace === void 0 ? void 0 : resolve(rootDir, options.pnpmWorkspace);
1314
+ const versions = workspaceRoot ? await readWorkspaceVersions(workspaceRoot) : noWorkspaceVersions;
1315
+ nuxt.options.routeRules = {
1316
+ ...nuxt.options.routeRules,
1317
+ [`${baseURL}/snapshots/**`]: { headers: { "cache-control": "public, max-age=31536000, immutable" } }
1318
+ };
1319
+ const build = () => Promise.all(lessons.map((source) => buildRunnableTutorial({
1320
+ source,
1321
+ readPage: content.read,
1322
+ fixturesDir,
1323
+ versions,
1324
+ start: options.start
1325
+ })));
1326
+ const buildTemplates = () => buildPlaygroundTemplates({
1327
+ fixturesDir,
1328
+ versions,
1329
+ tutorials: lessons,
1330
+ examples
1331
+ });
1332
+ const tutorials = await build();
1333
+ const templates = await buildTemplates();
1334
+ const assetsDir = resolve(rootDir, "node_modules/.cache/runnable-tutorials");
1335
+ await mkdir(assetsDir, { recursive: true });
1336
+ const sources = snapshotSources(lessons, examples, templates);
1337
+ let snapshots = await readTutorialSnapshots(assetsDir, {
1338
+ inputs: await tutorialSnapshotInputs({
1339
+ tutorials: sources,
1340
+ workspaceRoot,
1341
+ fixturesDir,
1342
+ versions
1343
+ }),
1344
+ disabled: process.env.TUTORIAL_SNAPSHOTS === "0"
1345
+ });
1346
+ if (!snapshots && sources.length > 0 && nuxt.options.dev && process.env.TUTORIAL_SNAPSHOTS !== "1" && process.env.TUTORIAL_SNAPSHOTS !== "0") console.info("[docs] No snapshots of the runnable lessons for the current dependencies, so the workspace runs npm install. Start with TUTORIAL_SNAPSHOTS=1 to build them.");
1347
+ const buildSnapshots = sources.length > 0 && !Reflect.get(nuxt.options, "_prepare") && (process.env.TUTORIAL_SNAPSHOTS ?? (nuxt.options.dev ? "0" : "1")) === "1";
1348
+ let built;
1349
+ nuxt.hook("app:templates", () => {
1350
+ if (!buildSnapshots) return;
1351
+ built ??= buildTutorialSnapshots({
1352
+ tutorials: sources,
1353
+ workspaceRoot,
1354
+ fixturesDir,
1355
+ versions,
1356
+ outDir: assetsDir,
1357
+ workDir: resolve(rootDir, "node_modules/.cache/runnable-tutorials-work")
1358
+ }).then((result) => {
1359
+ snapshots = result;
1360
+ });
1361
+ return built;
1362
+ });
1363
+ const partsBase = `${nuxt.options.app.baseURL.replace(/\/+$/, "")}${baseURL}/snapshots/`;
1364
+ const served = (snapshot) => snapshot && {
1365
+ ...snapshot,
1366
+ parts: snapshot.parts.map((part) => `${partsBase}${basename(part)}`)
1367
+ };
1368
+ const snapshotOf = (slug, all) => served(all && Object.hasOwn(all, slug) ? all[slug] : void 0);
1369
+ const currentTutorials = async () => (nuxt.options.dev ? await build() : tutorials).map((tutorial) => ({
1370
+ ...tutorial,
1371
+ snapshot: snapshotOf(tutorial.slug, snapshots)
1372
+ }));
1373
+ const currentTemplates = async () => (nuxt.options.dev ? await buildTemplates() : templates).map((template) => ({
1374
+ ...template,
1375
+ snapshot: snapshotOf(template.snapshotOf, snapshots)
1376
+ }));
1377
+ const configLessons = new Set((options.lessons ?? []).map((lesson) => lesson.slug));
1378
+ const configExamples = new Set((options.examples ?? []).map((example) => example.id));
1379
+ addTemplate({
1380
+ filename: "runnable-tutorials.mjs",
1381
+ write: true,
1382
+ getContents: async () => `export const runnableTutorials = ${JSON.stringify((await currentTutorials()).filter((tutorial) => configLessons.has(tutorial.slug)))}\n`
1383
+ });
1384
+ addTemplate({
1385
+ filename: "playground-templates.mjs",
1386
+ write: true,
1387
+ getContents: async () => `export const playgroundTemplates = ${JSON.stringify((await currentTemplates()).filter((template) => configExamples.has(template.id)).map(({ assets: _assets, ...template }) => template))}\n`
1388
+ });
1389
+ const pageModule = async (page) => {
1390
+ const port = page.workspace.port ?? 3e3;
1391
+ if (page.layout === "learn") {
1392
+ const slug = workspacePageSlug(page.path);
1393
+ const tutorial = (await currentTutorials()).find((candidate) => candidate.slug === slug);
1394
+ if (!tutorial) throw invariantError(`the lesson of ${page.path} was built`);
1395
+ return workspacePageModule({
1396
+ layout: "learn",
1397
+ tutorial,
1398
+ guide: page.workspace.guide ?? "side",
1399
+ port,
1400
+ preview: page.workspace.preview
1401
+ });
1402
+ }
1403
+ const tabs = (page.workspace.tabs ?? []).map((tab) => ({
1404
+ ...tab,
1405
+ file: workspaceTabComponent(nuxt.options.srcDir, tab.value)
1406
+ }));
1407
+ if (page.workspace.render) return workspacePageModule({
1408
+ layout: "playground",
1409
+ examples: await renderExamples(page, rootDir),
1410
+ port
1411
+ }, {
1412
+ render: resolve(rootDir, page.workspace.render),
1413
+ tabs
1414
+ });
1415
+ return workspacePageModule({
1416
+ layout: "playground",
1417
+ examples: pageExamples(page, await currentTemplates()),
1418
+ port,
1419
+ connect: page.workspace.connect
1420
+ }, { tabs });
1421
+ };
1422
+ const pageFile = (page) => `docs/workspaces/${workspacePageSlug(page.path)}.mjs`;
1423
+ for (const page of [
1424
+ ...learnPages,
1425
+ ...containerPages,
1426
+ ...renderPages
1427
+ ]) addTemplate({
1428
+ filename: pageFile(page),
1429
+ write: true,
1430
+ getContents: () => pageModule(page)
1431
+ });
1432
+ addTemplate({
1433
+ filename: "learn-facts.mjs",
1434
+ write: true,
1435
+ getContents: () => {
1436
+ const facts = Object.fromEntries(content.pages().filter((page) => page.layout === "tutorial" || page.layout === "learn").flatMap((page) => {
1437
+ const markdown = content.read(page.layout === "learn" ? page.workspace?.lesson ?? page.path : page.path);
1438
+ return markdown === void 0 ? [] : [[page.path, tutorialPageFacts(markdown)]];
1439
+ }));
1440
+ return `export const learnFacts = ${JSON.stringify(facts)}\n`;
1441
+ }
1442
+ });
1443
+ const types = JSON.stringify(ownModule(import.meta.url, "runnable"));
1444
+ addTypeTemplate({
1445
+ filename: "types/runnable-tutorials.d.ts",
1446
+ getContents: () => [
1447
+ `declare module "#build/runnable-tutorials.mjs" {`,
1448
+ ` export const runnableTutorials: import(${types}).RunnableTutorialData[]`,
1449
+ `}`,
1450
+ `declare module "#build/playground-templates.mjs" {`,
1451
+ ` export const playgroundTemplates: import(${types}).PlaygroundTemplate[]`,
1452
+ `}`,
1453
+ `declare module "#build/learn-facts.mjs" {`,
1454
+ ` export const learnFacts: Record<string, import(${types}).LearnPageFacts>`,
1455
+ `}`
1456
+ ].join("\n")
1457
+ });
1458
+ Reflect.apply(nuxt.hook, nuxt, ["nitro:config", (nitro) => {
1459
+ nitro.publicAssets = [...nitro.publicAssets ?? [], {
1460
+ baseURL,
1461
+ dir: assetsDir
1462
+ }];
1463
+ }]);
1464
+ return { workspaces: docsWorkspacesSource(pages) };
1465
+ }
1466
+ /** The source of `#docs/workspaces`: a loader of the page module of each workspace page, by page path. */
1467
+ function docsWorkspacesSource(pages) {
1468
+ return `export default {\n${pages.map((page) => ` ${JSON.stringify(page.path)}: () => import(${JSON.stringify(`./workspaces/${workspacePageSlug(page.path)}.mjs`)}),`).join("\n")}\n}\n`;
1469
+ }
1470
+ //#endregion
1471
+ //#region src/content-check.ts
1472
+ /**
1473
+ * `content.check()` over the docs pages, as `vitehub content check` runs it: links to missing pages, and the title and
1474
+ * description rules of `seoAudit`, from the Markdown and without built HTML. Each page has its URL from the manifest.
1475
+ */
1476
+ async function checkDocsContent(options, manifest, appBase, check) {
1477
+ const sources = options.sources ? resolveDocsSources(options.sources, options.rootDir) : [{ dir: options.dir }];
1478
+ const byFile = new Map(docsManifestPages(manifest).map((page) => [`${page.source ? Number(page.source.slice(5)) : 0}:${page.file}`, page.path]));
1479
+ const byId = /* @__PURE__ */ new Map();
1480
+ const content = createDocsContent(sources, options.rootDir, {
1481
+ check,
1482
+ url: (index, id) => byId.get(`${index}:${id}`) ?? null
1483
+ });
1484
+ try {
1485
+ for (const index of sources.keys()) {
1486
+ const name = contentName(index);
1487
+ for (const file of await content.list(name)) {
1488
+ const path = byFile.get(`${index}:${file.meta.key.slice(name.length + 1)}`);
1489
+ if (path) byId.set(`${index}:${file.path.replace(/^\/+/, "")}`, docsAppPath(path, appBase));
1490
+ }
1491
+ }
1492
+ return await content.check();
1493
+ } finally {
1494
+ await content.dispose();
1495
+ }
1496
+ }
1497
+ /** The findings of a check that the link checker reports: errors, such as a link to a missing page. */
1498
+ function docsContentLinkProblems(result) {
1499
+ return result.findings.filter((finding) => finding.severity === "error").map(problem);
1500
+ }
1501
+ /** Add a source location only when Content and the rendered audit found the same problem. */
1502
+ function docsContentSeoLocation(result, pages, appBase) {
1503
+ const byMessage = new Map(result.findings.filter((finding) => finding.line !== null && (finding.rule === "title" || finding.rule === "description")).map((finding) => [finding.message, finding]));
1504
+ return (page, field, message) => {
1505
+ const source = pages.get(page.path);
1506
+ if (!source) return message;
1507
+ if (field === "description" && (source.seo?.description ?? source.description) !== page.description) return message;
1508
+ const finding = byMessage.get(`${docsAppPath(page.path, appBase)}${message.slice(page.path.length)}`);
1509
+ return finding ? problem({
1510
+ ...finding,
1511
+ message
1512
+ }) : message;
1513
+ };
1514
+ }
1515
+ /** `docs/guide.md:12: <message> (CONTENT_R0062)`. */
1516
+ function problem(finding) {
1517
+ return `${finding.line === null ? finding.path : `${finding.path}:${finding.line}`}: ${finding.message} (${finding.code})`;
1518
+ }
1519
+ /**
1520
+ * The app's own pages as link patterns for `check.ignoreLinks`: `/pricing`, and `/blog/*` for `/blog/:id`. Content knows
1521
+ * only the docs pages, and these pages answer too. A catch-all page, such as `/:slug(.*)*`, would cover every link, so
1522
+ * it is left out.
1523
+ */
1524
+ function docsAppPageLinks(routes) {
1525
+ return [...new Set(routePaths(routes).filter((path) => !/\(\.\*\)\*?|\*$/.test(path)).map((path) => path.replace(/:\w+(?:\([^)]*\))?\??/g, "*") || "/"))];
1526
+ }
1527
+ //#endregion
171
1528
  //#region src/files.ts
172
1529
  /** The Markdown files of a folder, without dot files or dot folders, as Nitro's server assets list them. */
173
1530
  function markdownFiles(dir) {
@@ -218,10 +1575,11 @@ function packDocsFiles(stores, order = []) {
218
1575
  function docsDevFilesModule(stores) {
219
1576
  return [
220
1577
  `const files = {\n${stores.map((store) => ` ${JSON.stringify(store.name)}: {\n${markdownFiles(store.dir).map((file) => ` ${JSON.stringify(file)}: () => import(${JSON.stringify(`${join(store.dir, file).split(sep).join("/")}?raw`)}),`).join("\n")}\n },`).join("\n")}\n}`,
1578
+ "const has = (store, file) => Object.hasOwn(files, store) && Object.hasOwn(files[store], file)",
221
1579
  "export default {",
1580
+ " has,",
222
1581
  " async read(store, file) {",
223
- " const load = Object.hasOwn(files, store) && Object.hasOwn(files[store], file) ? files[store][file] : undefined",
224
- " return load ? (await load()).default : null",
1582
+ " return has(store, file) ? (await files[store][file]()).default : null",
225
1583
  " },",
226
1584
  "}",
227
1585
  ""
@@ -279,7 +1637,7 @@ function readDocsSeoPage(path, html, origin) {
279
1637
  if (property && attribute(tag, "content")?.trim()) openGraph.add(property.toLowerCase());
280
1638
  }
281
1639
  const levels = [];
282
- walkSync(parse(body), (node, parent) => {
1640
+ walkSync(parse$2(body), (node, parent) => {
283
1641
  if (node.type !== ELEMENT_NODE || !/^h[1-6]$/i.test(node.name)) return;
284
1642
  for (let ancestor = parent; ancestor; ancestor = ancestor.parent) if (ancestor.type === ELEMENT_NODE && ancestor.attributes.class?.split(/\s+/).includes("docs-example-preview")) return;
285
1643
  levels.push(Number(node.name[1]));
@@ -316,13 +1674,17 @@ function docsSitemapPaths(xml, origin) {
316
1674
  * search engines index needs its own title and description within the limits, one `h1`, headings in order, enough
317
1675
  * text, complete Open Graph tags, and a link from another page. A page that is a copy, through `noindex` or a canonical
318
1676
  * link to another page, is left out of those checks. Every page must stay below the size limit and must not link to a
319
- * redirect or to an endpoint. Each problem is one sentence that names the fix.
1677
+ * redirect or to an endpoint.
320
1678
  */
321
1679
  function docsSeoProblems(pages, sitemap, options = {}) {
322
1680
  const problems = [];
1681
+ const add = (code, message) => problems.push({
1682
+ code,
1683
+ message
1684
+ });
323
1685
  const byPath = new Map(pages.map((page) => [page.path, page]));
324
1686
  const megabytes = (bytes) => `${(bytes / 1e6).toFixed(1)} MB`;
325
- for (const page of pages) if (page.bytes > docsSeoLimits.bytes) problems.push(`${page.path} has ${megabytes(page.bytes)} of HTML, and Googlebot reads only the first ${megabytes(docsSeoLimits.bytes)}. Split the page, or show long lists with a component that renders less markup than a Markdown table.`);
1687
+ for (const page of pages) if (page.bytes > docsSeoLimits.bytes) add("DOCS_SEO_HTML_TOO_LARGE", `${page.path} has ${megabytes(page.bytes)} of HTML, and Googlebot reads only the first ${megabytes(docsSeoLimits.bytes)}. Split the page, or show long lists with a component that renders less markup than a Markdown table.`);
326
1688
  const redirects = new Set(pages.filter((page) => page.redirect).map((page) => page.path));
327
1689
  const endpoints = new Set(options.endpoints);
328
1690
  const linkedFrom = /* @__PURE__ */ new Map();
@@ -332,41 +1694,48 @@ function docsSeoProblems(pages, sitemap, options = {}) {
332
1694
  }
333
1695
  for (const [link, from] of linkedFrom) {
334
1696
  const where = from.length > 3 ? `${from.slice(0, 3).join(", ")} and ${from.length - 3} more pages` : from.join(", ");
335
- problems.push(redirects.has(link) ? `${where} link to ${link}, which redirects. Link to the page that it redirects to.` : `${where} link to ${link}, an endpoint that answers a browser with an error. Write the URL as code, or link to the page that explains it.`);
1697
+ add("DOCS_SEO_LINK_NOT_PAGE", redirects.has(link) ? `${where} link to ${link}, which redirects. Link to the page that it redirects to.` : `${where} link to ${link}, an endpoint that answers a browser with an error. Write the URL as code, or link to the page that explains it.`);
336
1698
  }
337
1699
  for (const path of sitemap) {
338
1700
  const page = byPath.get(path);
339
- if (!page) problems.push(`${path} is in the sitemap, but the build did not prerender it as a page. Remove it from the sitemap, or make it a page.`);
340
- else if (page.redirect) problems.push(`${path} is in the sitemap, but it redirects. List the page that it redirects to instead.`);
1701
+ if (!page) add("DOCS_SEO_SITEMAP_NOT_PAGE", `${path} is in the sitemap, but the build did not prerender it as a page. Remove it from the sitemap, or make it a page.`);
1702
+ else if (page.redirect) add("DOCS_SEO_SITEMAP_NOT_PAGE", `${path} is in the sitemap, but it redirects. List the page that it redirects to instead.`);
341
1703
  }
342
1704
  const indexed = pages.filter((page) => !page.redirect && !page.noindex && (page.canonical === null || page.canonical === page.path));
343
1705
  const { title, description, words } = docsSeoLimits;
1706
+ const withSourceLocation = options.withSourceLocation ?? ((_page, _field, message) => message);
344
1707
  for (const page of indexed) {
345
1708
  const at = page.path;
346
- if (!page.title) problems.push(`${at} has no title. Set \`title\` in its frontmatter.`);
347
- else if (page.title.length < title.min || page.title.length > title.max) problems.push(`${at} has a title of ${page.title.length} characters, "${page.title}". Keep it between ${title.min} and ${title.max}, with \`seo.title\` when the heading must stay.`);
348
- if (!page.description) problems.push(`${at} has no description. Set \`description\` in its frontmatter.`);
349
- else if (page.description.length < description.min || page.description.length > description.max) problems.push(`${at} has a description of ${page.description.length} characters. Keep it between ${description.min} and ${description.max}.`);
350
- if (page.h1 !== 1) problems.push(`${at} has ${page.h1} h1 headings. Give it one.`);
351
- if (page.headingSkip) problems.push(`${at} skips a heading level, ${page.headingSkip}. Go down one level at a time.`);
352
- if (page.words < words) problems.push(`${at} has ${page.words} words. Write at least ${words}, or merge it into another page.`);
1709
+ if (!page.title) add("DOCS_SEO_TITLE_INVALID", `${at} has no title. Set \`title\` in its frontmatter.`);
1710
+ else if (page.title.length < title.min || page.title.length > title.max) add("DOCS_SEO_TITLE_INVALID", withSourceLocation(page, "title", `${at} has a title of ${page.title.length} characters, "${page.title}". Keep it between ${title.min} and ${title.max}, with \`seo.title\` when the heading must stay.`));
1711
+ if (!page.description) add("DOCS_SEO_DESCRIPTION_INVALID", `${at} has no description. Set \`description\` in its frontmatter.`);
1712
+ else if (page.description.length < description.min || page.description.length > description.max) add("DOCS_SEO_DESCRIPTION_INVALID", withSourceLocation(page, "description", `${at} has a description of ${page.description.length} characters. Keep it between ${description.min} and ${description.max}.`));
1713
+ if (page.h1 !== 1) add("DOCS_SEO_HEADINGS_INVALID", `${at} has ${page.h1} h1 headings. Give it one.`);
1714
+ if (page.headingSkip) add("DOCS_SEO_HEADINGS_INVALID", `${at} skips a heading level, ${page.headingSkip}. Go down one level at a time.`);
1715
+ if (page.words < words) add("DOCS_SEO_PAGE_THIN", `${at} has ${page.words} words. Write at least ${words}, or merge it into another page.`);
353
1716
  const missing = page.openGraphMissing.filter((tag) => !(tag === "og:image" && page.twitterCard === "summary") && !(tag === "og:url" && options.siteUrl === false));
354
- if (missing.length) problems.push(`${at} has no ${missing.join(", ")} tag, so share previews and site audits call its Open Graph tags incomplete. Pages from \`useDocsSeo()\` set them; an app page that writes its own head needs them too.`);
1717
+ if (missing.length) add("DOCS_SEO_OPEN_GRAPH_INCOMPLETE", `${at} has no ${missing.join(", ")} tag, so share previews and site audits call its Open Graph tags incomplete. Pages from \`useDocsSeo()\` set them; an app page that writes its own head needs them too.`);
355
1718
  }
356
- for (const [field, label] of [["title", "title"], ["description", "description"]]) {
1719
+ for (const [field, code] of [["title", "DOCS_SEO_TITLE_INVALID"], ["description", "DOCS_SEO_DESCRIPTION_INVALID"]]) {
357
1720
  const groups = /* @__PURE__ */ new Map();
358
1721
  for (const page of indexed) if (page[field]) groups.set(page[field], [...groups.get(page[field]) ?? [], page.path]);
359
- for (const [value, paths] of groups) if (paths.length > 1) problems.push(`${paths.join(", ")} share the ${label} "${value}". Give each page its own.`);
1722
+ for (const [value, paths] of groups) if (paths.length > 1) add(code, `${paths.join(", ")} share the ${field} "${value}". Give each page its own.`);
360
1723
  }
361
1724
  const linked = /* @__PURE__ */ new Set();
362
1725
  for (const page of pages) for (const link of page.links) if (link !== page.path) linked.add(link);
363
- for (const page of indexed) if (page.path !== "/" && !linked.has(page.path)) problems.push(`No page links to ${page.path}. Link it from the navigation, the footer, or a related page.`);
1726
+ for (const page of indexed) if (page.path !== "/" && !linked.has(page.path)) add("DOCS_SEO_PAGE_UNLINKED", `No page links to ${page.path}. Link it from the navigation, the footer, or a related page.`);
364
1727
  return problems;
365
1728
  }
366
- /** Pages that search engines would flag. The build stops on them while the check is on. */
367
- /** `DOCS_SEO_FAILED`, with the list of problems in `problems`. */
1729
+ /** `DOCS_SEO_FAILED`, which stops the build, with the list of problems in `problems`. */
368
1730
  function docsSeoError(problems) {
369
- return Object.assign(docsErrorDiagnostics.DOCS_SEO_FAILED({ problems }), { problems });
1731
+ const messages = problems.map((problem) => problem.message);
1732
+ return Object.assign(docsErrorDiagnostics.DOCS_SEO_FAILED({ problems: messages }), { problems: messages });
1733
+ }
1734
+ /** One hint for each code of the problems, with the problems of that code, for `seoAudit: "warn"`. */
1735
+ function docsSeoHints(problems) {
1736
+ const byCode = /* @__PURE__ */ new Map();
1737
+ for (const problem of problems) byCode.set(problem.code, [...byCode.get(problem.code) ?? [], problem.message]);
1738
+ return [...byCode].map(([code, messages]) => docsErrorDiagnostics[code]({ problems: messages }));
370
1739
  }
371
1740
  function attribute(tag, name) {
372
1741
  if (!tag) return void 0;
@@ -466,6 +1835,25 @@ function docsThemeCss(file) {
466
1835
  }
467
1836
  //#endregion
468
1837
  //#region src/nuxt.ts
1838
+ function docsContentOf(options, rootDir) {
1839
+ const contentDir = resolve(rootDir, options.dir ?? "content");
1840
+ const sources = options.sources && resolveDocsSources(options.sources, rootDir);
1841
+ const resolveBase = () => normalizeDocsBase(options.base ?? (sources || existsSync(join(contentDir, "docs")) ? "/docs" : "/"));
1842
+ const base = resolveBase();
1843
+ return {
1844
+ contentDir,
1845
+ sources,
1846
+ resolveBase,
1847
+ base,
1848
+ manifestOptions: {
1849
+ dir: contentDir,
1850
+ base,
1851
+ sources: options.sources,
1852
+ rootDir,
1853
+ sections: options.sections
1854
+ }
1855
+ };
1856
+ }
469
1857
  const docsNuxtModule = defineNuxtModule({
470
1858
  meta: {
471
1859
  configKey: "docs",
@@ -482,8 +1870,18 @@ const docsNuxtModule = defineNuxtModule({
482
1870
  const uiFontsPath = createRequire(dependency("@nuxt/ui")).resolve("@nuxt/fonts");
483
1871
  nuxt.options.alias["@nuxt/fonts"] = fontsPath;
484
1872
  nuxt.options.alias[uiFontsPath] = fontsPath;
1873
+ const comments = await docsCommentsDependencies(nuxt, docs.comments);
1874
+ const { manifestOptions } = docsContentOf(docs, nuxt.options.rootDir);
1875
+ const webContainer = await docsWebContainerDefaults(nuxt, webContainerRoutes(docsManifestPages((await readDocsContent(manifestOptions)).manifest)));
1876
+ const vitehubDefaults = {
1877
+ ...comments["vite-hub/nuxt"]?.defaults,
1878
+ ...webContainer
1879
+ };
485
1880
  return {
486
- ...await docsCommentsDependencies(nuxt, docs.comments),
1881
+ ...Object.keys(vitehubDefaults).length > 0 ? { "vite-hub/nuxt": {
1882
+ optional: true,
1883
+ defaults: vitehubDefaults
1884
+ } } : {},
487
1885
  "@nuxt/fonts": {},
488
1886
  "@nuxt/ui": { defaults: {
489
1887
  prose: true,
@@ -501,6 +1899,10 @@ const docsNuxtModule = defineNuxtModule({
501
1899
  enabled: docs.ogImage !== false,
502
1900
  zeroRuntime: true,
503
1901
  runtimeCacheStorage: false,
1902
+ compatibility: {
1903
+ dev: { takumi: "node" },
1904
+ prerender: { takumi: "node" }
1905
+ },
504
1906
  defaults: {
505
1907
  width: 1200,
506
1908
  height: 630
@@ -526,21 +1928,12 @@ const docsNuxtModule = defineNuxtModule({
526
1928
  const transform = nuxt.options.imports.transform ??= {};
527
1929
  transform.include ??= [];
528
1930
  transform.include.push(new RegExp(`^${packageRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`));
529
- const contentDir = resolve(nuxt.options.rootDir, options.dir ?? "content");
530
- const sources = options.sources && resolveDocsSources(options.sources, nuxt.options.rootDir);
1931
+ const { contentDir, sources, resolveBase, base, manifestOptions } = docsContentOf(options, nuxt.options.rootDir);
531
1932
  const sourcesDir = join(nuxt.options.buildDir, "docs/sources");
532
1933
  /** The folder that the server reads each source's pages from, by page `source` name. */
533
1934
  const sourceDirs = sources?.map((source, index) => source.dir ?? join(sourcesDir, `docs-${index}`));
534
1935
  const contentDirsToWatch = sources ? sources.flatMap((source) => source.dir ?? []) : [contentDir];
535
1936
  const agentDir = join(nuxt.options.buildDir, "docs/agent");
536
- const base = normalizeDocsBase(options.base ?? (sources || existsSync(join(contentDir, "docs")) ? "/docs" : "/"));
537
- const manifestOptions = {
538
- dir: contentDir,
539
- base,
540
- sources: options.sources,
541
- rootDir: nuxt.options.rootDir,
542
- sections: options.sections
543
- };
544
1937
  const config = publicConfig(options, base, nuxt.options.app.baseURL);
545
1938
  const ownsApp = !hasAppComponent(nuxt.options._layers.map((layer) => layer.config.srcDir), nuxt.options.extensions);
546
1939
  nuxt.hook("prepare:types", ({ tsConfig, sharedTsConfig, serverTsConfig }) => {
@@ -592,8 +1985,33 @@ const docsNuxtModule = defineNuxtModule({
592
1985
  const moduleOptions = nuxt.options;
593
1986
  let read = await readDocsContent(manifestOptions);
594
1987
  let manifest = read.manifest;
595
- /** Copies the pages of each Content Source into the build, where the server and the agent copies read them. */
1988
+ if (sources && options.base === void 0) {
1989
+ const pages = docsManifestPages(manifest);
1990
+ const firstPage = pages[0];
1991
+ if (firstPage && !pages.some((page) => isDocsPath(page.path, base))) useLogger("@vite-hub/docs").warn(formatDiagnostic(docsErrorDiagnostics.DOCS_BASE_EMPTY({
1992
+ base,
1993
+ path: firstPage.path
1994
+ })));
1995
+ }
1996
+ /**
1997
+ * Resolves when development has read the content after a change. Nuxt generates the app again when a file is added
1998
+ * or removed, and the manifest templates wait for this read, so that run does not write the old pages.
1999
+ */
2000
+ let contentRead = Promise.resolve();
2001
+ let contentReadDone;
2002
+ const startContentRead = () => {
2003
+ if (!contentReadDone) contentRead = new Promise((done) => {
2004
+ contentReadDone = done;
2005
+ });
2006
+ };
2007
+ const endContentRead = () => {
2008
+ contentReadDone?.();
2009
+ contentReadDone = void 0;
2010
+ };
2011
+ const afterContentRead = (source) => contentReadDone ? contentRead.then(source) : source();
2012
+ let sourcePages = /* @__PURE__ */ new Map();
596
2013
  function writeSources(files) {
2014
+ sourcePages = new Map(files.map((file) => [`${file.source}/${file.file}`, file.markdown]));
597
2015
  rmSync(sourcesDir, {
598
2016
  force: true,
599
2017
  recursive: true
@@ -606,7 +2024,28 @@ const docsNuxtModule = defineNuxtModule({
606
2024
  }
607
2025
  writeSources(read.files);
608
2026
  /** The Markdown of a page, from the content folder or from the copy of its Content Source. */
609
- const readPage = (page) => readFileSync(join(page.source ? sourceDirs[Number(page.source.slice(5))] : contentDir, page.file), "utf8");
2027
+ const pageFile = (page) => join(page.source ? sourceDirs[Number(page.source.slice(5))] : contentDir, page.file);
2028
+ const readPage = (page) => sourcePages.get(`${page.source}/${page.file}`) ?? readFileSync(pageFile(page), "utf8");
2029
+ const runnable = options.runnable || docsManifestPages(manifest).some((page) => isDocsWorkspaceLayout(page.layout)) ? await setupDocsRunnable(options.runnable ?? {}, {
2030
+ nuxt,
2031
+ content: {
2032
+ pages: () => docsManifestPages(manifest),
2033
+ read: (path) => {
2034
+ const page = docsManifestPages(manifest).find((page) => page.path === normalizeDocsPath(path));
2035
+ return page && readPage(page);
2036
+ }
2037
+ }
2038
+ }) : void 0;
2039
+ nuxt.options.alias["#docs/workspaces"] = addTemplate({
2040
+ filename: "docs/workspaces.mjs",
2041
+ write: true,
2042
+ getContents: () => runnable?.workspaces ?? "export default {}\n"
2043
+ }).dst;
2044
+ addTemplate({
2045
+ filename: "docs/workspaces.d.mts",
2046
+ write: true,
2047
+ getContents: () => `declare const workspaces: Record<string, (() => Promise<{ default: import(${JSON.stringify(ownModule(import.meta.url, "runnable"))}).DocsWorkspaceData }>) | undefined>\nexport default workspaces\n`
2048
+ });
610
2049
  /**
611
2050
  * Content renders the agent copy of each page on request. `rawMarkdown` is a function of the app's build, so it runs
612
2051
  * here, and the server reads each page that it changed from `docs/agent/<source>/<file>`. `nuxi build` empties the
@@ -637,15 +2076,18 @@ const docsNuxtModule = defineNuxtModule({
637
2076
  nuxt.hook("build:before", async () => {
638
2077
  agentCopies = await writeAgentSources();
639
2078
  });
640
- const indexedPagePaths = new Set(docsManifestPages(manifest).filter((page) => docsPageIndexed(page)).map((page) => docsAppPath(page.path, config.appBase)));
2079
+ const indexedPagePaths = docsManifestPages(manifest).filter(docsPageIndexed).map((page) => docsAppPath(page.path, config.appBase));
2080
+ const indexedPageExclusions = new Set(indexedPagePaths);
2081
+ if (indexedPagePaths.length) indexedPageExclusions.add(new RegExp(`^(?:${indexedPagePaths.map((path) => RegExp.escape(path)).join("|")})[?#]`));
641
2082
  if (options.linkChecker !== false) {
642
2083
  const linkChecker = moduleOptions.linkChecker ??= {};
643
2084
  linkChecker.excludeLinks = [
644
2085
  ...linkChecker.excludeLinks ?? [],
645
2086
  ...options.linkChecker?.excludeLinks ?? [],
2087
+ ...config.mcp ? [/^(?:cursor:\/\/anysphere\.cursor-deeplink\/mcp\/install|vscode:mcp\/install)\?/] : [],
646
2088
  ...docsManifestPages(manifest).map((page) => docsAppPath(docsRawPath(page.path), config.appBase)),
647
2089
  ...docsManifestPages(manifest).filter((page) => !docsPageIndexed(page)).map((page) => docsAppPath(page.path, config.appBase)),
648
- ...indexedPagePaths
2090
+ ...indexedPageExclusions
649
2091
  ];
650
2092
  }
651
2093
  moduleOptions.runtimeConfig.public.mdc ??= { headings: { anchorLinks: {
@@ -731,19 +2173,36 @@ const docsNuxtModule = defineNuxtModule({
731
2173
  };
732
2174
  const agentDiscoveryOptions = defu(moduleOptions.agentDiscovery, discovery);
733
2175
  if (agentDiscoveryOptions.errors !== false) nuxt.options.experimental.inlineErrorRendering = false;
734
- if (!agentDiscoveryOptions.routes?.length) {
735
- const standalone = manifest.pages.map((page) => page.path).filter((path) => path !== "/");
736
- agentDiscoveryOptions.routes = config.appBase === "/" ? [.../* @__PURE__ */ new Set([
737
- ...manifest.root?.path === "/" || manifest.pages.some((page) => page.path === "/") ? ["/"] : [],
2176
+ const discoveryRoutes = (pages) => {
2177
+ const standalone = pages.pages.map((page) => page.path).filter((path) => path !== "/");
2178
+ return config.appBase === "/" ? [.../* @__PURE__ */ new Set([
2179
+ ...pages.root?.path === "/" || pages.pages.some((page) => page.path === "/") ? ["/"] : [],
738
2180
  config.base,
739
2181
  `${config.base.replace(/\/+$/, "")}/**`,
740
2182
  ...standalone
741
- ])] : docsManifestPages(manifest).flatMap((page) => [.../* @__PURE__ */ new Set([page.path, docsAppPath(page.path, config.appBase).replace(/(.)\/$/, "$1")])].map((path) => ({
2183
+ ])] : docsManifestPages(pages).flatMap((page) => [.../* @__PURE__ */ new Set([page.path, docsAppPath(page.path, config.appBase).replace(/(.)\/$/, "$1")])].map((path) => ({
742
2184
  path,
743
2185
  raw: docsAppPath(docsRawPath(page.path), config.appBase)
744
2186
  })));
745
- }
2187
+ };
2188
+ const ownDiscoveryRoutes = Boolean(agentDiscoveryOptions.routes?.length);
2189
+ if (!ownDiscoveryRoutes) agentDiscoveryOptions.routes = discoveryRoutes(manifest);
746
2190
  moduleOptions.agentDiscovery = agentDiscoveryOptions;
2191
+ /**
2192
+ * What the module reads from the manifest only when Nuxt starts: the mount of the docs page route, the routes
2193
+ * that negotiate Markdown, and the workspace pages, whose modules and isolated routes are set up then. A content
2194
+ * change that moves them needs a restart. Any other change reloads the pages. `<base>/**` already covers a new page
2195
+ * below the base.
2196
+ */
2197
+ const startupShape = (pages) => JSON.stringify([
2198
+ docsMount(pages),
2199
+ ownDiscoveryRoutes ? null : discoveryRoutes(pages).filter((route) => typeof route !== "string" || route.endsWith("/**") || !isDocsPath(route, config.base)),
2200
+ workspacePages(docsManifestPages(pages)).map((page) => [
2201
+ page.path,
2202
+ page.layout,
2203
+ page.workspace
2204
+ ])
2205
+ ]);
747
2206
  const agentFile = addTemplate({
748
2207
  filename: "docs/agent.mjs",
749
2208
  write: true,
@@ -755,7 +2214,7 @@ const docsNuxtModule = defineNuxtModule({
755
2214
  const manifestSource = () => `export default JSON.parse(${JSON.stringify(JSON.stringify(manifest))})\n`;
756
2215
  const manifestFile = addTemplate({
757
2216
  filename: "docs/manifest.mjs",
758
- getContents: manifestSource,
2217
+ getContents: () => afterContentRead(manifestSource),
759
2218
  write: true
760
2219
  }).dst;
761
2220
  addTemplate({
@@ -763,20 +2222,18 @@ const docsNuxtModule = defineNuxtModule({
763
2222
  getContents: () => `import type { DocsManifest } from "@vite-hub/docs"\ndeclare const manifest: DocsManifest\nexport default manifest\n`,
764
2223
  write: true
765
2224
  });
766
- const app = () => docsAppManifest(manifest, { panels: !nuxt.options.dev });
2225
+ const builtApp = nuxt.options.dev ? void 0 : docsAppManifest(manifest, { panels: true });
2226
+ const appManifest = () => builtApp?.manifest ?? docsAppManifest(manifest, { panels: false }).manifest;
767
2227
  nuxt.options.alias["#docs/manifest"] = addTemplate({
768
2228
  filename: "docs/app-manifest.mjs",
769
- getContents: () => docsAppManifestSource(app().manifest),
2229
+ getContents: () => afterContentRead(() => docsAppManifestSource(appManifest())),
770
2230
  write: true
771
2231
  }).dst;
772
- const panelFiles = app().panels.map((panel, index) => ({
2232
+ const panelFiles = (builtApp?.panels ?? []).map((panel, index) => ({
773
2233
  path: panel.path,
774
2234
  file: addTemplate({
775
2235
  filename: `docs/panels/${index}.mjs`,
776
- getContents: () => docsAppPanelSource(app().panels.find((candidate) => candidate.path === panel.path) ?? {
777
- ...panel,
778
- pages: []
779
- }),
2236
+ getContents: () => docsAppPanelSource(panel),
780
2237
  write: true
781
2238
  }).dst
782
2239
  }));
@@ -785,9 +2242,6 @@ const docsNuxtModule = defineNuxtModule({
785
2242
  write: true,
786
2243
  getContents: () => `export default {\n${panelFiles.map(({ path, file }) => ` ${JSON.stringify(path)}: () => import(${JSON.stringify(file)}),\n`).join("")}}\n`
787
2244
  }).dst;
788
- nuxt.hook("build:manifest", (chunks) => {
789
- for (const [key, chunk] of Object.entries(chunks)) if (/docs[/\\]panels[/\\]\d+\.mjs$/.test(decodeURIComponent(key))) chunk.prefetch = false;
790
- });
791
2245
  addTemplate({
792
2246
  filename: "docs/panels.d.mts",
793
2247
  write: true,
@@ -799,6 +2253,7 @@ const docsNuxtModule = defineNuxtModule({
799
2253
  write: true
800
2254
  });
801
2255
  nuxt.options.alias["#docs/navigation"] = resolver.resolve("./navigation.js");
2256
+ nuxt.options.alias["#docs/runnable"] = resolver.resolve("./runnable.js");
802
2257
  nuxt.options.alias["#docs/primitive-rail"] = resolver.resolve("./primitive-rail.js");
803
2258
  nuxt.options.alias["#docs/comark-css"] = addTemplate({
804
2259
  filename: "docs/comark-css.mjs",
@@ -879,13 +2334,105 @@ const docsNuxtModule = defineNuxtModule({
879
2334
  if (nuxt.options.dev) {
880
2335
  nuxt.options.watch = [.../* @__PURE__ */ new Set([...nuxt.options.watch ?? [], examplesDir])];
881
2336
  let timer;
2337
+ let reading = Promise.resolve();
882
2338
  let regeneration = Promise.resolve();
883
2339
  let closed = false;
884
2340
  let viteServer;
885
2341
  nuxt.hook("vite:serverCreated", (server) => {
886
2342
  viteServer = server;
887
2343
  });
2344
+ const shape = startupShape(manifest);
2345
+ const isContentFile = (file) => /(\.md|\.navigation\.yml)$/.test(file) && contentDirsToWatch.some((dir) => resolve(file).startsWith(`${dir}${sep}`));
2346
+ nuxt.hook("vite:extend", ({ config }) => {
2347
+ (config.plugins ??= []).push({
2348
+ name: "vite-hub:docs-content",
2349
+ applyToEnvironment: (environment) => environment.name === "nitro",
2350
+ hotUpdate: {
2351
+ order: "pre",
2352
+ handler: ({ file }) => isContentFile(file) ? [] : void 0
2353
+ }
2354
+ });
2355
+ });
2356
+ /**
2357
+ * Shows a content change without a restart. Content reads each page on request, so only the generated modules
2358
+ * change: the manifest of the app and the server, `#docs/files`, which lists the files, and the changed files.
2359
+ * Returns false when Nitro does not run in Vite, where the server must restart to see a new manifest.
2360
+ */
2361
+ async function reloadPages(change) {
2362
+ const nitro = viteServer?.environments?.nitro;
2363
+ if (!viteServer || !nitro) return false;
2364
+ if (change.manifest) {
2365
+ await updateTemplates({ filter: (template) => template.filename === "docs/manifest.mjs" || template.filename === "docs/app-manifest.mjs" });
2366
+ const source = manifestSource();
2367
+ if (!existsSync(manifestFile) || readFileSync(manifestFile, "utf8") !== source) writeFileSync(manifestFile, source);
2368
+ }
2369
+ const modules = [...change.files.flatMap((file) => [...nitro.moduleGraph.getModulesByFile(file) ?? []]), ...change.list ? [nitro.moduleGraph.getModuleById("#docs/files")] : []];
2370
+ for (const module of modules) if (module) nitro.moduleGraph.invalidateModule(module);
2371
+ if (change.manifest || modules.length) viteServer.watcher.emit("change", manifestFile);
2372
+ return true;
2373
+ }
888
2374
  const logError = (error) => useLogger("@vite-hub/docs").error(error);
2375
+ const restart = () => {
2376
+ Promise.resolve(nuxt.callHook("restart")).catch(logError);
2377
+ };
2378
+ /** The changed files since the last run, or null when a watcher did not name one. */
2379
+ let changed = /* @__PURE__ */ new Set();
2380
+ let contentVersion = 0;
2381
+ /** Reads the content again after a change of `file`, or of any file when the watcher did not name one. */
2382
+ function schedule(file) {
2383
+ if (file) changed?.add(file);
2384
+ else changed = null;
2385
+ const version = ++contentVersion;
2386
+ startContentRead();
2387
+ clearTimeout(timer);
2388
+ timer = setTimeout(() => {
2389
+ const files = changed;
2390
+ changed = /* @__PURE__ */ new Set();
2391
+ const result = reading.then(async () => {
2392
+ if (closed) return;
2393
+ try {
2394
+ if (resolveBase() !== base) return "restart";
2395
+ const next = await readDocsContent(manifestOptions);
2396
+ const previous = JSON.stringify(manifest);
2397
+ const copies = await writeAgentSources(next);
2398
+ const copiesChanged = copies.join("\n") !== agentCopies.join("\n");
2399
+ agentCopies = copies;
2400
+ read = next;
2401
+ manifest = next.manifest;
2402
+ const manifestChanged = JSON.stringify(manifest) !== previous;
2403
+ return {
2404
+ files: [...files ?? docsManifestPages(manifest).map(pageFile), ...copies],
2405
+ copies,
2406
+ copiesChanged,
2407
+ manifestChanged,
2408
+ shapeChanged: manifestChanged && startupShape(manifest) !== shape,
2409
+ listChanged: manifestChanged || copiesChanged || files === null
2410
+ };
2411
+ } catch (error) {
2412
+ logError(error);
2413
+ } finally {
2414
+ if (version === contentVersion) endContentRead();
2415
+ }
2416
+ });
2417
+ reading = result.then(() => {});
2418
+ regeneration = regeneration.then(async () => {
2419
+ const change = await result;
2420
+ if (closed || !change) return;
2421
+ if (change === "restart") return restart();
2422
+ if (!change.shapeChanged && await reloadPages({
2423
+ files: change.files,
2424
+ manifest: change.manifestChanged,
2425
+ list: change.listChanged
2426
+ })) return;
2427
+ for (const file of change.copies) viteServer?.watcher.emit("change", file);
2428
+ if (change.manifestChanged || change.copiesChanged) restart();
2429
+ }).catch(logError);
2430
+ }, 100);
2431
+ }
2432
+ nuxt.hook("builder:watch", (_event, path) => {
2433
+ const file = resolve(nuxt.options.srcDir, path);
2434
+ if (isContentFile(file)) schedule(file);
2435
+ });
889
2436
  const watchers = contentDirsToWatch.map((contentDir) => {
890
2437
  let watchDir = contentDir;
891
2438
  while (!existsSync(watchDir) && dirname(watchDir) !== watchDir) watchDir = dirname(watchDir);
@@ -894,32 +2441,15 @@ const docsNuxtModule = defineNuxtModule({
894
2441
  const changedPath = resolve(watchDir, file);
895
2442
  if (changedPath !== contentDir && !changedPath.startsWith(`${contentDir}${sep}`) && !contentDir.startsWith(`${changedPath}${sep}`)) return;
896
2443
  if (event === "change" && !/(\.md|\.navigation\.yml)$/.test(file)) return;
897
- }
898
- clearTimeout(timer);
899
- timer = setTimeout(() => {
900
- regeneration = regeneration.then(async () => {
901
- if (closed) return;
902
- try {
903
- const next = await readDocsContent(manifestOptions);
904
- const changed = JSON.stringify(next.manifest) !== JSON.stringify(manifest);
905
- const copies = await writeAgentSources(next);
906
- const copiesChanged = copies.join("\n") !== agentCopies.join("\n");
907
- agentCopies = copies;
908
- for (const file of copies) viteServer?.watcher.emit("change", file);
909
- read = next;
910
- manifest = next.manifest;
911
- if ((changed || copiesChanged) && !closed) Promise.resolve(nuxt.callHook("restart")).catch(logError);
912
- } catch (error) {
913
- logError(error);
914
- }
915
- });
916
- }, 100);
2444
+ schedule(changedPath);
2445
+ } else schedule(null);
917
2446
  });
918
2447
  });
919
2448
  nuxt.hook("close", async () => {
920
2449
  closed = true;
921
2450
  clearTimeout(timer);
922
2451
  for (const watcher of watchers) watcher.close();
2452
+ endContentRead();
923
2453
  await regeneration;
924
2454
  });
925
2455
  }
@@ -1025,6 +2555,9 @@ const docsNuxtModule = defineNuxtModule({
1025
2555
  visibility: false,
1026
2556
  interaction: true
1027
2557
  };
2558
+ nuxt.hook("build:manifest", (chunks) => {
2559
+ for (const chunk of Object.values(chunks)) chunk.prefetch = false;
2560
+ });
1028
2561
  addPlugin({
1029
2562
  src: join(runtime, "app/plugins/theme-color.ts"),
1030
2563
  mode: "all"
@@ -1042,9 +2575,14 @@ const docsNuxtModule = defineNuxtModule({
1042
2575
  path: join(runtime, "app/middleware/docs-layout.ts"),
1043
2576
  global: true
1044
2577
  });
2578
+ /** Link patterns of the app's own pages, which the Content check of the docs links accepts. */
2579
+ let appPageLinks = [];
2580
+ let appReplacesDocs = false;
1045
2581
  extendPages((pages) => {
2582
+ appPageLinks = docsAppPageLinks(pages);
1046
2583
  const mount = docsMount(manifest);
1047
- if (replacesDocsPage(pages, mount)) return;
2584
+ appReplacesDocs = replacesDocsPage(pages, mount);
2585
+ if (appReplacesDocs) return;
1048
2586
  pages.push({
1049
2587
  name: "docs-page",
1050
2588
  path: `${mount === "/" ? "" : mount}/:slug(.*)*`,
@@ -1110,32 +2648,73 @@ const docsNuxtModule = defineNuxtModule({
1110
2648
  "/llms-full.txt"
1111
2649
  ];
1112
2650
  }
2651
+ const buildingHints = () => !nuxt.options.dev && !Reflect.get(nuxt.options, "_prepare") && !Reflect.get(nuxt.options, "vitehubCliDiscovery");
2652
+ const hintsConfig = () => ({
2653
+ root: nuxt.options.rootDir,
2654
+ command: "build",
2655
+ logger: useLogger("@vite-hub/docs")
2656
+ });
2657
+ const startHints = () => {
2658
+ if (buildingHints()) startViteHubHints(hintsConfig(), nuxt);
2659
+ };
2660
+ nuxt.hook("build:before", startHints);
2661
+ Reflect.apply(nuxt.hook, nuxt, ["nitro:build:before", startHints]);
2662
+ let checkSourceLinks;
1113
2663
  Reflect.apply(nuxt.hook, nuxt, ["nitro:init", (nitro) => {
1114
2664
  const building = !nuxt.options.dev && !Reflect.get(nuxt.options, "_prepare");
2665
+ const seoAudit = options.seoAudit ?? "warn";
2666
+ const redirects = docsRedirects(nitro.options.routeRules ?? {});
2667
+ const settings = options.linkChecker || {};
2668
+ const runtimePath = () => docsRuntimePath(nitro.options, config.appBase, docsMount(manifest));
2669
+ const excludeLinks = [
2670
+ ...(moduleOptions.linkChecker?.excludeLinks ?? []).filter((link) => !indexedPageExclusions.has(link)),
2671
+ ...settings.excludeLinks ?? [],
2672
+ ...redirects.map((redirect) => docsAppPath(redirect.from, config.appBase)),
2673
+ ...config.mcp ? [docsAppPath("/mcp", config.appBase)] : []
2674
+ ];
2675
+ const excluded = docsLinkExclusion(excludeLinks);
2676
+ const outputFile = nitro.options.output && docsOutputFile(nitro.options.output.publicDir, config.appBase);
2677
+ const appPage = (path) => appPageLinks.some((pattern) => posix.matchesGlob(path, pattern));
2678
+ const base = config.appBase.replace(/\/+$/, "");
2679
+ let contentCheck;
2680
+ const checkContent = () => contentCheck ??= (async () => {
2681
+ const isRuntimePath = runtimePath();
2682
+ return checkDocsContent(manifestOptions, manifest, config.appBase, {
2683
+ isLinkTarget: (url, href) => {
2684
+ const path = url.pathname;
2685
+ if (base && path !== base && !path.startsWith(`${base}/`)) return true;
2686
+ return excluded(url, href) || appPage(path.slice(base.length) || "/") || isRuntimePath(path) || Boolean(outputFile?.(path));
2687
+ },
2688
+ ...config.site.url ? { site: config.site.url } : {},
2689
+ titleTemplate: `%s · ${config.site.name}`
2690
+ });
2691
+ })();
1115
2692
  if (options.linkChecker !== false && building) {
1116
- const problems = docsRedirectProblems(manifest, docsRedirects(nitro.options.routeRules ?? {}));
2693
+ const serverRoutes = docsServerRoutes(nitro.routing?.routes.routes ?? [], resolver.resolve("./runtime"));
2694
+ const problems = docsRedirectProblems(manifest, redirects, serverRoutes);
1117
2695
  if (problems.length) throw docsRedirectError(problems);
1118
- nitro.hooks?.hook("compiled", () => {
2696
+ let sourceLinks;
2697
+ const checkLinks = () => sourceLinks ??= (async () => {
2698
+ const checked = await checkContent();
2699
+ const broken = docsContentLinkProblems(checked);
2700
+ if (broken.length) throw docsLinkError(broken);
2701
+ useLogger("@vite-hub/docs").info?.(`Checked the links of ${checked.sources.reduce((pages, source) => pages + source.pages, 0)} Markdown pages with \`vitehub content check\``);
2702
+ })();
2703
+ checkSourceLinks = checkLinks;
2704
+ nitro.hooks?.hook("compiled", async () => {
1119
2705
  if (!nitro.options.output) return;
1120
- const redirects = docsRedirects(nitro.options.routeRules ?? {});
1121
- const settings = options.linkChecker || {};
2706
+ await checkLinks();
1122
2707
  const result = checkDocsLinks({
1123
2708
  dir: nitro.options.output.publicDir,
1124
2709
  siteUrl: config.site.url || "https://docs.local",
1125
2710
  appBase: config.appBase,
1126
2711
  ...settings,
1127
- isRuntimePath: docsRuntimePath(nitro.options, config.appBase, docsMount(manifest)),
1128
- excludeLinks: [
1129
- ...(moduleOptions.linkChecker?.excludeLinks ?? []).filter((link) => typeof link !== "string" || !indexedPagePaths.has(link)),
1130
- ...settings.excludeLinks ?? [],
1131
- ...redirects.map((redirect) => docsAppPath(redirect.from, config.appBase)),
1132
- ...config.mcp ? [docsAppPath("/mcp", config.appBase)] : []
1133
- ]
2712
+ isRuntimePath: runtimePath(),
2713
+ excludeLinks
1134
2714
  });
1135
2715
  useLogger("@vite-hub/docs").info?.(`Checked links and fragments of ${result.pages} pages`);
1136
2716
  });
1137
2717
  }
1138
- const seoAudit = options.seoAudit ?? "warn";
1139
2718
  if (seoAudit && building) {
1140
2719
  const origin = `${config.site.url || "http://docs.invalid"}${config.appBase.replace(/\/+$/, "")}`;
1141
2720
  const pages = [];
@@ -1145,19 +2724,32 @@ const docsNuxtModule = defineNuxtModule({
1145
2724
  if (route.route === "/sitemap.xml") sitemap = docsSitemapPaths(route.contents, origin);
1146
2725
  else if (route.fileName?.endsWith(".html") && route.contentType?.includes("text/html")) pages.push(readDocsSeoPage(route.route, route.contents, origin));
1147
2726
  });
1148
- nitro.hooks?.hook("prerender:done", () => {
2727
+ const adapted = new Set((sources ?? []).flatMap((source, index) => source.frontmatter ? [`docs-${index}`] : []));
2728
+ nitro.hooks?.hook("prerender:done", async () => {
2729
+ const rendered = new Set(pages.map((page) => page.path));
2730
+ const candidates = appReplacesDocs ? [] : docsManifestPages(manifest).filter((page) => rendered.has(page.path) && !appPage(page.path) && !(page.source && adapted.has(page.source)));
1149
2731
  const problems = docsSeoProblems(pages, sitemap, {
1150
2732
  endpoints: config.mcp ? ["/mcp"] : [],
1151
- siteUrl: Boolean(config.site.url)
2733
+ siteUrl: Boolean(config.site.url),
2734
+ withSourceLocation: candidates.length ? docsContentSeoLocation(await checkContent(), new Map(candidates.map((page) => [page.path, page])), config.appBase) : void 0
1152
2735
  });
1153
2736
  if (!problems.length) return;
1154
- const error = docsSeoError(problems);
1155
- if (seoAudit === "error" || seoAudit === true) throw error;
1156
- useLogger("@vite-hub/docs").warn(`${error.message}\nSet \`docs.seoAudit\` to "error" to stop the build on these, or to false to turn the check off.`);
2737
+ if (seoAudit === "error" || seoAudit === true) throw docsSeoError(problems);
2738
+ if (buildingHints()) for (const hint of docsSeoHints(problems)) reportViteHubHint(hintsConfig(), hint);
1157
2739
  });
1158
2740
  }
1159
2741
  }]);
1160
2742
  Reflect.apply(nuxt.hook, nuxt, ["nitro:config", (nitro) => {
2743
+ if (options.linkChecker !== false && !nuxt.options.dev && !Reflect.get(nuxt.options, "_prepare")) {
2744
+ const prerenderDone = nitro.hooks?.["prerender:done"];
2745
+ nitro.hooks = {
2746
+ ...nitro.hooks,
2747
+ "prerender:done": async (result) => {
2748
+ await checkSourceLinks?.();
2749
+ await prerenderDone?.(result);
2750
+ }
2751
+ };
2752
+ }
1161
2753
  if (config.appBase !== "/") {
1162
2754
  for (const link of [...nitro.runtimeConfig?.agentDiscovery?.links ?? [], ...nitro.runtimeConfig?.public?.agentDiscovery?.resources ?? []]) {
1163
2755
  link.href = docsAppPath(link.href, config.appBase);
@@ -1251,7 +2843,9 @@ const shellIcons = [
1251
2843
  "i-lucide-search",
1252
2844
  "i-lucide-x",
1253
2845
  "i-simple-icons-anthropic",
2846
+ "i-simple-icons-claude",
1254
2847
  "i-simple-icons-cursor",
2848
+ "i-simple-icons-windsurf",
1255
2849
  "i-simple-icons-github",
1256
2850
  "i-simple-icons-markdown",
1257
2851
  "i-simple-icons-openai",