@vite-hub/docs 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +164 -6
  2. package/dist/{assistant-pages-BN7hNsSZ.js → assistant-pages-CqNlHsx-.js} +1 -1
  3. package/dist/{assistant-shared-WzButktj.js → assistant-shared-DhiLHKSl.js} +2 -2
  4. package/dist/assistant-worker.js +1 -1
  5. package/dist/assistant.js +1 -1
  6. package/dist/{content-CPZGnn3S.js → content-BQVlMshL.js} +55 -15
  7. package/dist/{draft-BjWmaiLn.js → draft-CSsTYSeb.js} +2 -2
  8. package/dist/{error-diagnostics-B_ZOy7kF.js → error-diagnostics-CmgtG9xa.js} +64 -0
  9. package/dist/index.d.ts +7 -6
  10. package/dist/index.js +4 -4
  11. package/dist/link-checker-redirects.js +1 -1
  12. package/dist/{manifest-CMoxcwPm.d.ts → manifest-Drbdw1us.d.ts} +1 -1
  13. package/dist/{manifest-ZdxLrcvt.js → manifest-DvECmwX-.js} +62 -26
  14. package/dist/{markdown-DUWnEMPp.js → markdown-1M1FbjCw.js} +1 -1
  15. package/dist/{page-Dx2JD3y1.d.ts → markdown-BiKrT08O.d.ts} +2 -25
  16. package/dist/navigation.d.ts +9 -3
  17. package/dist/navigation.js +22 -8
  18. package/dist/{nuxt-CAGpKl_-.d.ts → nuxt-8O2OB_hI.d.ts} +80 -4
  19. package/dist/nuxt.d.ts +2 -2
  20. package/dist/nuxt.js +1269 -58
  21. package/dist/{page-GPt09oex.js → page-Bb0TfRKi.js} +19 -3
  22. package/dist/page-BryUCmYf.d.ts +26 -0
  23. package/dist/primitive-rail.d.ts +1 -4
  24. package/dist/primitive-rail.js +1 -4
  25. package/dist/{redirects-CmR1yu5A.js → redirects-BJj58IsY.js} +34 -21
  26. package/dist/runnable.d.ts +37 -0
  27. package/dist/runnable.js +105 -0
  28. package/dist/runtime/app/components/DocsAsideLeftBody.vue +2 -8
  29. package/dist/runtime/app/components/DocsLearn.vue +215 -0
  30. package/dist/runtime/app/components/DocsLearnCodePre.vue +98 -0
  31. package/dist/runtime/app/components/DocsLearnFile.vue +21 -0
  32. package/dist/runtime/app/components/DocsPage.vue +11 -5
  33. package/dist/runtime/app/components/DocsPlayground.vue +117 -0
  34. package/dist/runtime/app/components/content/Example.vue +18 -49
  35. package/dist/runtime/app/components/content/PageList.vue +1 -5
  36. package/dist/runtime/app/layouts/docs.vue +36 -8
  37. package/dist/runtime/app/middleware/docs-layout.ts +2 -2
  38. package/dist/runtime/app/utils/docs-learn.ts +31 -0
  39. package/dist/runtime/app/utils/docs-playground.ts +3 -0
  40. package/dist/runtime/server/llms.js +1 -1
  41. package/dist/runtime/server/markdown.d.ts +0 -5
  42. package/dist/runtime/server/markdown.js +10 -1
  43. package/dist/runtime/server/mcp.js +1 -1
  44. package/dist/runtime/server/page.d.ts +1 -1
  45. package/dist/runtime/server/page.js +3 -3
  46. package/dist/runtime/server/raw.js +2 -9
  47. package/dist/runtime/server/search.d.ts +1 -1
  48. package/dist/runtime/server/search.js +3 -2
  49. package/dist/runtime/server/sitemap.js +1 -1
  50. package/dist/{schema-DwpXW0VZ.js → schema-DcWZ3Q3M.js} +97 -5
  51. package/dist/server.d.ts +3 -2
  52. package/dist/server.js +3 -3
  53. package/dist/snapshot-worker.mjs +40 -0
  54. package/dist/steps-DBlkJwtD.d.ts +105 -0
  55. package/dist/steps-DF-11dJn.js +32 -0
  56. package/dist/{types-BhG6vGfG.d.ts → types-CHU_fy9l.d.ts} +69 -4
  57. package/package.json +17 -10
package/dist/nuxt.js CHANGED
@@ -1,8 +1,9 @@
1
- import { docsAppPath, docsIndexedPages, docsManifestPages, docsPageIcon, docsPageIndexed, docsRailIcon, docsRawPath, docsSectionIcon, isDocsPath, normalizeDocsBase, normalizeDocsPath } from "./navigation.js";
2
- import { a as replacesDocsPage, o as routePaths, t as docsMount } from "./page-GPt09oex.js";
3
- import { t as docsErrorDiagnostics } from "./error-diagnostics-B_ZOy7kF.js";
4
- import { i as docsServerRoutes, n as docsRedirectProblems, r as docsRedirects, t as docsRedirectError } from "./redirects-CmR1yu5A.js";
5
- 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-ZdxLrcvt.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";
6
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";
@@ -10,19 +11,155 @@ import { addComponent, addComponentsDir, addImportsDir, addPlugin, addRouteMiddl
10
11
  import { addRoute, createRouter, findAllRoutes, routeToRegExp } from "rou3";
11
12
  import { defineDiagnostics, formatDiagnostic } from "nostics";
12
13
  import { createHash } from "node:crypto";
13
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
14
- import { readFile, readdir } from "node:fs/promises";
15
- import { basename, dirname, join, parse, posix, 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";
16
16
  import { fileURLToPath, pathToFileURL } from "node:url";
17
+ import { basename, dirname, isAbsolute, join, matchesGlob, parse, posix, relative, resolve, sep } from "node:path";
17
18
  import { tmpdir } from "node:os";
18
19
  import { findContentEntry } from "@vite-hub/source/vite";
19
20
  import { vitehubTheme } from "@vite-hub/ui/theme";
20
21
  import { sizeOf } from "comark-zoom/size";
21
22
  import { defu } from "defu";
22
- import { ELEMENT_NODE, parse as parse$1, 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";
23
27
  import { gzipSync } from "node:zlib";
24
28
  import postcss from "postcss";
25
- //#region ../internal/dist/build/vite.js
29
+ //#region ../internal/dist/invariant.js
30
+ const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
31
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
32
+ codes: { INTERNAL_INVARIANT_FAILED: {
33
+ why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
34
+ fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
35
+ } }
36
+ });
37
+ /**
38
+ * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
39
+ * Use a code from the package catalog when a developer can cause the error or fix it.
40
+ */
41
+ function invariantError(what) {
42
+ return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
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
26
163
  const projectRootDirectoryMarkers = [
27
164
  ["server", "agents"],
28
165
  ["server", "channels"],
@@ -67,7 +204,7 @@ function hasProjectRootDirectoryMarker(root) {
67
204
  for (const marker of projectRootDirectoryMarkers) try {
68
205
  if (statSync(resolve(root, ...marker)).isDirectory()) return true;
69
206
  } catch (error) {
70
- if (error.code !== "ENOENT") throw error;
207
+ if (!isMissingProjectMarker(error)) throw error;
71
208
  }
72
209
  return false;
73
210
  }
@@ -81,11 +218,15 @@ function hasProjectRootFileMarker(root, markers) {
81
218
  try {
82
219
  if (statSync(resolve(root, ...path)).isFile()) return true;
83
220
  } catch (error) {
84
- if (error.code !== "ENOENT") throw error;
221
+ if (!isMissingProjectMarker(error)) throw error;
85
222
  }
86
223
  }
87
224
  return false;
88
225
  }
226
+ function isMissingProjectMarker(error) {
227
+ const code = error.code;
228
+ return code === "ENOENT" || code === "ENOTDIR";
229
+ }
89
230
  //#endregion
90
231
  //#region ../internal/dist/hints.js
91
232
  /**
@@ -166,22 +307,6 @@ function startViteHubHints(config, owner = config) {
166
307
  write(startRun(config));
167
308
  }
168
309
  //#endregion
169
- //#region ../internal/dist/invariant.js
170
- const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
171
- docsBase: "https://vitehub.dev/docs/development/diagnostics",
172
- codes: { INTERNAL_INVARIANT_FAILED: {
173
- why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
174
- fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
175
- } }
176
- });
177
- /**
178
- * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
179
- * Use a code from the package catalog when a developer can cause the error or fix it.
180
- */
181
- function invariantError(what) {
182
- return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
183
- }
184
- //#endregion
185
310
  //#region src/module-options.ts
186
311
  /** The module name: a string entry, or the `getMeta()` name of an imported module function. */
187
312
  async function moduleName(module) {
@@ -292,10 +417,11 @@ function installed(name, rootDir) {
292
417
  /**
293
418
  * The module dependency that turns Comments on in `vite-hub/nuxt`. Comments keeps threads in a ViteHub Database, so a
294
419
  * site without `vite-hub/nuxt` has none unless it asks for them, which fails the build. `false` sets `comments: false`.
295
- * 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.
296
421
  */
297
422
  async function docsCommentsDependencies(nuxt, comments) {
298
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()));
299
425
  if (comments === false) return vitehub ? { "vite-hub/nuxt": {
300
426
  optional: true,
301
427
  defaults: { comments: false }
@@ -313,6 +439,1035 @@ async function docsCommentsDependencies(nuxt, comments) {
313
439
  } };
314
440
  }
315
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
316
1471
  //#region src/content-check.ts
317
1472
  /**
318
1473
  * `content.check()` over the docs pages, as `vitehub content check` runs it: links to missing pages, and the title and
@@ -482,7 +1637,7 @@ function readDocsSeoPage(path, html, origin) {
482
1637
  if (property && attribute(tag, "content")?.trim()) openGraph.add(property.toLowerCase());
483
1638
  }
484
1639
  const levels = [];
485
- walkSync(parse$1(body), (node, parent) => {
1640
+ walkSync(parse$2(body), (node, parent) => {
486
1641
  if (node.type !== ELEMENT_NODE || !/^h[1-6]$/i.test(node.name)) return;
487
1642
  for (let ancestor = parent; ancestor; ancestor = ancestor.parent) if (ancestor.type === ELEMENT_NODE && ancestor.attributes.class?.split(/\s+/).includes("docs-example-preview")) return;
488
1643
  levels.push(Number(node.name[1]));
@@ -680,6 +1835,25 @@ function docsThemeCss(file) {
680
1835
  }
681
1836
  //#endregion
682
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
+ }
683
1857
  const docsNuxtModule = defineNuxtModule({
684
1858
  meta: {
685
1859
  configKey: "docs",
@@ -696,8 +1870,18 @@ const docsNuxtModule = defineNuxtModule({
696
1870
  const uiFontsPath = createRequire(dependency("@nuxt/ui")).resolve("@nuxt/fonts");
697
1871
  nuxt.options.alias["@nuxt/fonts"] = fontsPath;
698
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
+ };
699
1880
  return {
700
- ...await docsCommentsDependencies(nuxt, docs.comments),
1881
+ ...Object.keys(vitehubDefaults).length > 0 ? { "vite-hub/nuxt": {
1882
+ optional: true,
1883
+ defaults: vitehubDefaults
1884
+ } } : {},
701
1885
  "@nuxt/fonts": {},
702
1886
  "@nuxt/ui": { defaults: {
703
1887
  prose: true,
@@ -744,22 +1928,12 @@ const docsNuxtModule = defineNuxtModule({
744
1928
  const transform = nuxt.options.imports.transform ??= {};
745
1929
  transform.include ??= [];
746
1930
  transform.include.push(new RegExp(`^${packageRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`));
747
- const contentDir = resolve(nuxt.options.rootDir, options.dir ?? "content");
748
- const sources = options.sources && resolveDocsSources(options.sources, nuxt.options.rootDir);
1931
+ const { contentDir, sources, resolveBase, base, manifestOptions } = docsContentOf(options, nuxt.options.rootDir);
749
1932
  const sourcesDir = join(nuxt.options.buildDir, "docs/sources");
750
1933
  /** The folder that the server reads each source's pages from, by page `source` name. */
751
1934
  const sourceDirs = sources?.map((source, index) => source.dir ?? join(sourcesDir, `docs-${index}`));
752
1935
  const contentDirsToWatch = sources ? sources.flatMap((source) => source.dir ?? []) : [contentDir];
753
1936
  const agentDir = join(nuxt.options.buildDir, "docs/agent");
754
- const resolveBase = () => normalizeDocsBase(options.base ?? (sources || existsSync(join(contentDir, "docs")) ? "/docs" : "/"));
755
- const base = resolveBase();
756
- const manifestOptions = {
757
- dir: contentDir,
758
- base,
759
- sources: options.sources,
760
- rootDir: nuxt.options.rootDir,
761
- sections: options.sections
762
- };
763
1937
  const config = publicConfig(options, base, nuxt.options.app.baseURL);
764
1938
  const ownsApp = !hasAppComponent(nuxt.options._layers.map((layer) => layer.config.srcDir), nuxt.options.extensions);
765
1939
  nuxt.hook("prepare:types", ({ tsConfig, sharedTsConfig, serverTsConfig }) => {
@@ -811,6 +1985,14 @@ const docsNuxtModule = defineNuxtModule({
811
1985
  const moduleOptions = nuxt.options;
812
1986
  let read = await readDocsContent(manifestOptions);
813
1987
  let manifest = read.manifest;
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
+ }
814
1996
  /**
815
1997
  * Resolves when development has read the content after a change. Nuxt generates the app again when a file is added
816
1998
  * or removed, and the manifest templates wait for this read, so that run does not write the old pages.
@@ -827,8 +2009,9 @@ const docsNuxtModule = defineNuxtModule({
827
2009
  contentReadDone = void 0;
828
2010
  };
829
2011
  const afterContentRead = (source) => contentReadDone ? contentRead.then(source) : source();
830
- /** Copies the pages of each Content Source into the build, where the server and the agent copies read them. */
2012
+ let sourcePages = /* @__PURE__ */ new Map();
831
2013
  function writeSources(files) {
2014
+ sourcePages = new Map(files.map((file) => [`${file.source}/${file.file}`, file.markdown]));
832
2015
  rmSync(sourcesDir, {
833
2016
  force: true,
834
2017
  recursive: true
@@ -842,7 +2025,27 @@ const docsNuxtModule = defineNuxtModule({
842
2025
  writeSources(read.files);
843
2026
  /** The Markdown of a page, from the content folder or from the copy of its Content Source. */
844
2027
  const pageFile = (page) => join(page.source ? sourceDirs[Number(page.source.slice(5))] : contentDir, page.file);
845
- const readPage = (page) => readFileSync(pageFile(page), "utf8");
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
+ });
846
2049
  /**
847
2050
  * Content renders the agent copy of each page on request. `rawMarkdown` is a function of the app's build, so it runs
848
2051
  * here, and the server reads each page that it changed from `docs/agent/<source>/<file>`. `nuxi build` empties the
@@ -986,11 +2189,20 @@ const docsNuxtModule = defineNuxtModule({
986
2189
  if (!ownDiscoveryRoutes) agentDiscoveryOptions.routes = discoveryRoutes(manifest);
987
2190
  moduleOptions.agentDiscovery = agentDiscoveryOptions;
988
2191
  /**
989
- * What the module reads from the manifest only when Nuxt starts: the mount of the docs page route, and the routes
990
- * that negotiate Markdown. A content change that moves them needs a restart. Any other change reloads the pages.
991
- * `<base>/**` already covers a new page below the base.
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.
992
2196
  */
993
- const startupShape = (pages) => JSON.stringify([docsMount(pages), ownDiscoveryRoutes ? null : discoveryRoutes(pages).filter((route) => typeof route !== "string" || route.endsWith("/**") || !isDocsPath(route, config.base))]);
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
+ ]);
994
2206
  const agentFile = addTemplate({
995
2207
  filename: "docs/agent.mjs",
996
2208
  write: true,
@@ -1010,20 +2222,18 @@ const docsNuxtModule = defineNuxtModule({
1010
2222
  getContents: () => `import type { DocsManifest } from "@vite-hub/docs"\ndeclare const manifest: DocsManifest\nexport default manifest\n`,
1011
2223
  write: true
1012
2224
  });
1013
- 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;
1014
2227
  nuxt.options.alias["#docs/manifest"] = addTemplate({
1015
2228
  filename: "docs/app-manifest.mjs",
1016
- getContents: () => afterContentRead(() => docsAppManifestSource(app().manifest)),
2229
+ getContents: () => afterContentRead(() => docsAppManifestSource(appManifest())),
1017
2230
  write: true
1018
2231
  }).dst;
1019
- const panelFiles = app().panels.map((panel, index) => ({
2232
+ const panelFiles = (builtApp?.panels ?? []).map((panel, index) => ({
1020
2233
  path: panel.path,
1021
2234
  file: addTemplate({
1022
2235
  filename: `docs/panels/${index}.mjs`,
1023
- getContents: () => docsAppPanelSource(app().panels.find((candidate) => candidate.path === panel.path) ?? {
1024
- ...panel,
1025
- pages: []
1026
- }),
2236
+ getContents: () => docsAppPanelSource(panel),
1027
2237
  write: true
1028
2238
  }).dst
1029
2239
  }));
@@ -1032,9 +2242,6 @@ const docsNuxtModule = defineNuxtModule({
1032
2242
  write: true,
1033
2243
  getContents: () => `export default {\n${panelFiles.map(({ path, file }) => ` ${JSON.stringify(path)}: () => import(${JSON.stringify(file)}),\n`).join("")}}\n`
1034
2244
  }).dst;
1035
- nuxt.hook("build:manifest", (chunks) => {
1036
- for (const [key, chunk] of Object.entries(chunks)) if (/docs[/\\]panels[/\\]\d+\.mjs$/.test(decodeURIComponent(key))) chunk.prefetch = false;
1037
- });
1038
2245
  addTemplate({
1039
2246
  filename: "docs/panels.d.mts",
1040
2247
  write: true,
@@ -1046,6 +2253,7 @@ const docsNuxtModule = defineNuxtModule({
1046
2253
  write: true
1047
2254
  });
1048
2255
  nuxt.options.alias["#docs/navigation"] = resolver.resolve("./navigation.js");
2256
+ nuxt.options.alias["#docs/runnable"] = resolver.resolve("./runnable.js");
1049
2257
  nuxt.options.alias["#docs/primitive-rail"] = resolver.resolve("./primitive-rail.js");
1050
2258
  nuxt.options.alias["#docs/comark-css"] = addTemplate({
1051
2259
  filename: "docs/comark-css.mjs",
@@ -1347,6 +2555,9 @@ const docsNuxtModule = defineNuxtModule({
1347
2555
  visibility: false,
1348
2556
  interaction: true
1349
2557
  };
2558
+ nuxt.hook("build:manifest", (chunks) => {
2559
+ for (const chunk of Object.values(chunks)) chunk.prefetch = false;
2560
+ });
1350
2561
  addPlugin({
1351
2562
  src: join(runtime, "app/plugins/theme-color.ts"),
1352
2563
  mode: "all"