@vite-hub/docs 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +167 -7
  2. package/dist/{agent-copy-xPaWye_g.js → agent-copy-CY9_RkHN.js} +2 -3
  3. package/dist/{assistant-pages-BN7hNsSZ.js → assistant-pages-BbWfd69g.js} +3 -4
  4. package/dist/{assistant-shared-CWIKRtBv.d.ts → assistant-shared-BWeRcmVS.d.ts} +0 -2
  5. package/dist/{assistant-shared-WzButktj.js → assistant-shared-JcfjK-qg.js} +3 -4
  6. package/dist/assistant-worker.d.ts +1 -3
  7. package/dist/assistant-worker.js +2 -3
  8. package/dist/assistant.d.ts +1 -3
  9. package/dist/assistant.js +2 -3
  10. package/dist/{content-CPZGnn3S.js → content-C_WXjV3y.js} +60 -28
  11. package/dist/{draft-BjWmaiLn.js → draft-rOGhtXch.js} +3 -4
  12. package/dist/{error-diagnostics-B_ZOy7kF.js → error-diagnostics-Daz9oBJS.js} +65 -2
  13. package/dist/{files-UY4h1_36.js → files-BBoAGhhM.js} +1 -2
  14. package/dist/index.d.ts +7 -8
  15. package/dist/index.js +5 -6
  16. package/dist/link-checker-redirects.d.ts +0 -2
  17. package/dist/link-checker-redirects.js +2 -3
  18. package/dist/{manifest-ZdxLrcvt.js → manifest-Bti_WxDZ.js} +64 -30
  19. package/dist/{manifest-CMoxcwPm.d.ts → manifest-DJ2DyNue.d.ts} +1 -5
  20. package/dist/{page-Dx2JD3y1.d.ts → markdown-B97RuMXs.d.ts} +2 -27
  21. package/dist/{markdown-DUWnEMPp.js → markdown-BzZkYb24.js} +2 -3
  22. package/dist/navigation.d.ts +10 -6
  23. package/dist/navigation.js +23 -10
  24. package/dist/{nuxt-CAGpKl_-.d.ts → nuxt-CYAIBEHE.d.ts} +74 -8
  25. package/dist/nuxt.d.ts +3 -3
  26. package/dist/nuxt.js +1286 -89
  27. package/dist/page-B8_70-5D.d.ts +24 -0
  28. package/dist/{page-GPt09oex.js → page-DWsretqk.js} +20 -5
  29. package/dist/primitive-rail.d.ts +1 -10
  30. package/dist/primitive-rail.js +4 -10
  31. package/dist/{raw-BChwipz_.js → raw-CQukuLuj.js} +1 -2
  32. package/dist/{redirects-CmR1yu5A.js → redirects-BEFu4KLR.js} +35 -23
  33. package/dist/runnable.d.ts +33 -0
  34. package/dist/runnable.js +104 -0
  35. package/dist/runtime/app/components/DocsAsideLeftBody.vue +2 -8
  36. package/dist/runtime/app/components/DocsLearn.vue +215 -0
  37. package/dist/runtime/app/components/DocsLearnCodePre.vue +98 -0
  38. package/dist/runtime/app/components/DocsLearnFile.vue +21 -0
  39. package/dist/runtime/app/components/DocsPage.vue +11 -5
  40. package/dist/runtime/app/components/DocsPlayground.vue +117 -0
  41. package/dist/runtime/app/components/content/Example.vue +18 -49
  42. package/dist/runtime/app/components/content/PageList.vue +1 -5
  43. package/dist/runtime/app/layouts/docs.vue +36 -8
  44. package/dist/runtime/app/middleware/docs-layout.ts +2 -2
  45. package/dist/runtime/app/utils/docs-learn.ts +31 -0
  46. package/dist/runtime/app/utils/docs-playground.ts +3 -0
  47. package/dist/runtime/server/llms.d.ts +0 -2
  48. package/dist/runtime/server/llms.js +2 -3
  49. package/dist/runtime/server/markdown.d.ts +0 -7
  50. package/dist/runtime/server/markdown.js +11 -3
  51. package/dist/runtime/server/mcp.d.ts +0 -2
  52. package/dist/runtime/server/mcp.js +2 -3
  53. package/dist/runtime/server/page.d.ts +1 -3
  54. package/dist/runtime/server/page.js +4 -5
  55. package/dist/runtime/server/raw.d.ts +0 -2
  56. package/dist/runtime/server/raw.js +3 -11
  57. package/dist/runtime/server/search.d.ts +1 -3
  58. package/dist/runtime/server/search.js +4 -4
  59. package/dist/runtime/server/sitemap.d.ts +0 -2
  60. package/dist/runtime/server/sitemap.js +3 -5
  61. package/dist/runtime/server/trailing-slash.d.ts +0 -2
  62. package/dist/runtime/server/trailing-slash.js +1 -2
  63. package/dist/schema-CmSiwC4t.js +189 -0
  64. package/dist/server.d.ts +3 -4
  65. package/dist/server.js +4 -4
  66. package/dist/snapshot-worker.mjs +40 -0
  67. package/dist/steps-C3tGwhNK.d.ts +103 -0
  68. package/dist/steps-muDP1nYT.js +31 -0
  69. package/dist/{theme-BXyu4uFL.d.ts → theme-CgJRnVdT.d.ts} +0 -4
  70. package/dist/{theme-DzC8LtMH.js → theme-CxBzPBZ9.js} +2 -4
  71. package/dist/theme.d.ts +1 -1
  72. package/dist/theme.js +1 -2
  73. package/dist/{types-BhG6vGfG.d.ts → types-B6YlHil4.d.ts} +69 -8
  74. package/package.json +40 -32
  75. package/dist/schema-DwpXW0VZ.js +0 -98
@@ -0,0 +1,24 @@
1
+ import { t as DocsDocument } from "./markdown-B97RuMXs.js";
2
+ import { n as DocsManifest, o as DocsSection, r as DocsPage } from "./types-B6YlHil4.js";
3
+ interface DocsPageLink {
4
+ path: string;
5
+ title: string;
6
+ description: string | null;
7
+ }
8
+ /** What the page route returns for one URL. The client renders it as is. */
9
+ interface DocsPageResponse {
10
+ page: DocsPage;
11
+ /** Id of the section that owns the page, or `null` for the root page and pages outside the base. */
12
+ section: string | null;
13
+ document: DocsDocument;
14
+ /** The page's `credits`, parsed like its body, or `null` without them. */
15
+ credits: DocsDocument | null;
16
+ prev: DocsPageLink | null;
17
+ next: DocsPageLink | null;
18
+ }
19
+ /** Previous and next follow the sidebar order of the page's section, or of its panel for a page inside one. */
20
+ declare function docsPageResponse(manifest: DocsManifest, found: {
21
+ page: DocsPage;
22
+ section: DocsSection | null;
23
+ }, document: DocsDocument, credits?: DocsDocument | null): DocsPageResponse;
24
+ export { DocsPageResponse as n, docsPageResponse as r, DocsPageLink as t };
@@ -1,5 +1,5 @@
1
- import { docsManifestPages, docsPanelOf, docsPanelPages, isDocsPath } from "./navigation.js";
2
- //#region src/page.ts
1
+ import { docsManifestPages, docsPanelOf, docsPanelPages, isDocsPath, isDocsWorkspaceLayout } from "./navigation.js";
2
+ // src/page.ts
3
3
  /** Previous and next follow the sidebar order of the page's section, or of its panel for a page inside one. */
4
4
  function docsPageResponse(manifest, found, document, credits = null) {
5
5
  const section = found.section;
@@ -23,6 +23,7 @@ function docsPageResponse(manifest, found, document, credits = null) {
23
23
  function docsPageOf(frontmatter, at) {
24
24
  const navigation = frontmatter.navigation === false ? void 0 : frontmatter.navigation;
25
25
  const layout = frontmatter.layout ?? "article";
26
+ const workspace = isDocsWorkspaceLayout(layout);
26
27
  return {
27
28
  id: at.id,
28
29
  path: at.path || "/",
@@ -39,8 +40,9 @@ function docsPageOf(frontmatter, at) {
39
40
  ...frontmatter.tutorial ? { tutorial: frontmatter.tutorial } : {},
40
41
  ...frontmatter.codePanel ? { codePanel: true } : {},
41
42
  ...frontmatter.seo ? { seo: frontmatter.seo } : {},
42
- sidebar: frontmatter.sidebar ?? true,
43
- toc: frontmatter.toc ?? (layout !== "landing" && layout !== "home"),
43
+ ...workspace ? { workspace: workspaceOf(frontmatter) } : {},
44
+ sidebar: frontmatter.sidebar ?? (workspace ? "collapsed" : true),
45
+ toc: frontmatter.toc ?? (layout !== "landing" && layout !== "home" && !workspace),
44
46
  kind: navigation?.kind ?? null,
45
47
  group: navigation?.group ?? null,
46
48
  navigation: frontmatter.navigation !== false,
@@ -48,6 +50,20 @@ function docsPageOf(frontmatter, at) {
48
50
  order: navigation?.order ?? Number.MAX_SAFE_INTEGER
49
51
  };
50
52
  }
53
+ function workspaceOf(frontmatter) {
54
+ const { examples, tabs, render, connect, port, fixture, guide, lesson, preview } = frontmatter;
55
+ return {
56
+ examples,
57
+ tabs,
58
+ render,
59
+ connect,
60
+ port,
61
+ fixture,
62
+ guide,
63
+ lesson,
64
+ preview
65
+ };
66
+ }
51
67
  /**
52
68
  * The URL of a page file, from its path below the content folder without `.md`: `docs/kv/index` is `/docs/kv`, `about`
53
69
  * is `/about`, and `index` is `/`.
@@ -78,5 +94,4 @@ function routePaths(routes, parent = "") {
78
94
  return [path, ...routePaths(route.children ?? [], path)];
79
95
  });
80
96
  }
81
- //#endregion
82
97
  export { replacesDocsPage as a, docsPageResponse as i, docsPageOf as n, routePaths as o, docsPagePath as r, docsMount as t };
@@ -1,19 +1,13 @@
1
1
  import { Component, PropType, SlotsType, VNode } from "vue";
2
- //#region ../icons/dist/index.d.ts
3
2
  /** Name of an icon in the ViteHub set, such as `kv` for `i-vitehub-kv`. */
4
3
  type ViteHubIconName = "agent" | "auth" | "blob" | "browser" | "bundle" | "cache" | "channels" | "choices" | "cli" | "cms" | "codemods" | "comments" | "compare" | "connections" | "console" | "content" | "database" | "development" | "device" | "docs" | "email" | "env" | "forge" | "forms" | "gateways" | "guides" | "hosts" | "i18n" | "kv" | "logs" | "markdown-template" | "mcp" | "presets" | "queue" | "rate-limit" | "realtime" | "reference" | "runtime" | "sandbox" | "schedule" | "shell" | "skills" | "source" | "start" | "sync" | "ui" | "usage" | "web-container" | "webhooks" | "workflow" | "workspace";
5
- //#endregion
6
- //#region src/components/primitive-icon.d.ts
7
4
  /** Name of an icon in the `@vite-hub/icons` set: one for each Server Primitive, Console area, and docs area. */
8
5
  type PrimitiveIconName = ViteHubIconName;
9
6
  export declare function isPrimitiveIconName(value: unknown): value is PrimitiveIconName;
10
7
  export declare const primitiveIconNames: readonly PrimitiveIconName[];
11
8
  /** Returns the set icon that an Iconify name such as `i-vitehub-kv` or `vitehub:kv` names, or a bare name such as `kv`. */
12
9
  export declare function resolvePrimitiveIconName(icon: string): PrimitiveIconName | undefined;
13
- /**
14
- * Inline SVG of a `@vite-hub/icons` icon, so the part that each icon marks with `data-motion` can move when its rail item
15
- * gets a pointer or keyboard focus. `styles.css` sets the motion of each icon. Strokes use currentColor.
16
- */
10
+ /** Inline SVG of a `@vite-hub/icons` icon. Strokes use currentColor. */
17
11
  export declare const PrimitiveIcon: import("vue").DefineComponent<import("vue").ExtractPropTypes<{
18
12
  name: {
19
13
  required: true;
@@ -27,8 +21,6 @@ export declare const PrimitiveIcon: import("vue").DefineComponent<import("vue").
27
21
  type: PropType<PrimitiveIconName>;
28
22
  };
29
23
  }>> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
30
- //#endregion
31
- //#region src/components/primitive-rail.d.ts
32
24
  /** Props of every rail slot. `expanded` is true while the rail shows its labels, for example to turn off tooltips. */
33
25
  interface PrimitiveRailSlotProps {
34
26
  expanded: boolean;
@@ -106,5 +98,4 @@ export declare const PrimitiveRailItem: import("vue").DefineComponent<import("vu
106
98
  current: boolean;
107
99
  as: string | Component;
108
100
  }, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
109
- //#endregion
110
101
  export type { PrimitiveIconName, PrimitiveRailSlotProps };
@@ -1,5 +1,5 @@
1
1
  import { computed, defineComponent, getCurrentInstance, h, onBeforeUnmount, onMounted, ref, watch } from "vue";
2
- //#region ../icons/dist/index.js
2
+ // ../icons/dist/index.js
3
3
  const icons = {
4
4
  "prefix": "vitehub",
5
5
  "info": {
@@ -74,8 +74,7 @@ const icons = {
74
74
  "width": 24,
75
75
  "height": 24
76
76
  };
77
- //#endregion
78
- //#region src/components/primitive-icon.ts
77
+ // src/components/primitive-icon.ts
79
78
  function isPrimitiveIconName(value) {
80
79
  return typeof value === "string" && Object.hasOwn(icons.icons, value);
81
80
  }
@@ -85,10 +84,7 @@ function resolvePrimitiveIconName(icon) {
85
84
  const name = icon.replace(/^(?:i-vitehub-|vitehub:)/, "");
86
85
  return isPrimitiveIconName(name) ? name : void 0;
87
86
  }
88
- /**
89
- * Inline SVG of a `@vite-hub/icons` icon, so the part that each icon marks with `data-motion` can move when its rail item
90
- * gets a pointer or keyboard focus. `styles.css` sets the motion of each icon. Strokes use currentColor.
91
- */
87
+ /** Inline SVG of a `@vite-hub/icons` icon. Strokes use currentColor. */
92
88
  const PrimitiveIcon = defineComponent({
93
89
  name: "PrimitiveIcon",
94
90
  props: { name: {
@@ -106,8 +102,7 @@ const PrimitiveIcon = defineComponent({
106
102
  });
107
103
  }
108
104
  });
109
- //#endregion
110
- //#region src/components/primitive-rail.ts
105
+ // src/components/primitive-rail.ts
111
106
  const hoverIntentDelay = 200;
112
107
  /**
113
108
  * The narrow icon rail that ViteHub docs and the Console show at the left edge.
@@ -285,5 +280,4 @@ const PrimitiveRailItem = defineComponent({
285
280
  };
286
281
  }
287
282
  });
288
- //#endregion
289
283
  export { PrimitiveIcon, PrimitiveRail, PrimitiveRailGroup, PrimitiveRailItem, isPrimitiveIconName, primitiveIconNames, resolvePrimitiveIconName };
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { parse } from "yaml";
3
- //#region src/raw.ts
3
+ // src/raw.ts
4
4
  const frontmatterBoundary = "---";
5
5
  const frontmatterSchema = z.object({ title: z.string().optional() });
6
6
  const pageCardSchema = z.object({
@@ -853,5 +853,4 @@ function toRawMarkdown(source, options = {}) {
853
853
  const startsWithH1 = /^[ \t]{0,3}#(?:[ \t]+|$)/.test(content) || /^[^\n]+\n[ \t]{0,3}=+[ \t]*(?:\n|$)/.test(content);
854
854
  return `${title && !startsWithH1 ? `# ${title}\n\n${content}` : content}\n`;
855
855
  }
856
- //#endregion
857
856
  export { toRawMarkdown as t };
@@ -1,7 +1,7 @@
1
+ import { t as docsErrorDiagnostics } from "./error-diagnostics-Daz9oBJS.js";
1
2
  import { docsManifestPages, docsRawPath, docsSectionForPath, isDocsPath, normalizeDocsPath } from "./navigation.js";
2
- import { t as docsErrorDiagnostics } from "./error-diagnostics-B_ZOy7kF.js";
3
3
  import { addRoute, createRouter, findRoute } from "rou3";
4
- //#region src/redirects.ts
4
+ // src/redirects.ts
5
5
  /**
6
6
  * The redirect route rules from an exact app path. Keep external targets so a chain can end at another site.
7
7
  * A wildcard rule, such as `/docs/old/**`, has no single target page, so it is left out.
@@ -16,7 +16,6 @@ function docsRedirects(routeRules) {
16
16
  }];
17
17
  });
18
18
  }
19
- /** A docs page or the Markdown copy of one that answers a URL path. */
20
19
  function docsPaths(manifest) {
21
20
  return new Set(docsManifestPages(manifest).flatMap((page) => [page.path, docsRawPath(page.path)]));
22
21
  }
@@ -38,37 +37,50 @@ function docsRedirectProblems(manifest, redirects, serverRoutes = []) {
38
37
  const pages = docsPaths(manifest);
39
38
  const routes = createRouter();
40
39
  for (const { route, method } of serverRoutes) addRoute(routes, method, route, true);
41
- const next = new Map(redirects.map((redirect) => [normalizeDocsPath(redirect.from), redirect.to]));
40
+ const next = new Map(redirects.filter((redirect) => !isTrailingSlashRedirect(redirect)).map((redirect) => [routeRulePath(redirect.from), redirect.to]));
42
41
  const problems = [];
43
- for (const { from, to } of redirects) {
44
- const source = normalizeDocsPath(from);
45
- const page = docsManifestPages(manifest).find((candidate) => candidate.path === source || docsRawPath(candidate.path) === source);
42
+ for (const redirect of redirects) {
43
+ const { from, to } = redirect;
44
+ const source = routeRulePath(from);
45
+ const trailingSlashRedirect = isTrailingSlashRedirect(redirect);
46
+ const page = trailingSlashRedirect ? void 0 : docsManifestPages(manifest).find((candidate) => candidate.path === source || docsRawPath(candidate.path) === source);
46
47
  if (page) problems.push(`The redirect from ${from} hides the page ${page.file}. Remove the route rule, or move the page.`);
47
- const seen = /* @__PURE__ */ new Set([source]);
48
+ const seen = new Set(trailingSlashRedirect ? [] : [source]);
48
49
  let end = to;
49
- let target = targetPath(end);
50
- while (target !== void 0 && next.has(target) && !seen.has(target)) {
51
- seen.add(target);
52
- end = next.get(target);
53
- target = targetPath(end);
50
+ let path = localTargetPath(end);
51
+ while (path !== void 0) {
52
+ const target = normalizeDocsPath(path);
53
+ const rulePath = routeRulePath(path);
54
+ const key = !next.has(rulePath) && path.endsWith("/") && pages.has(target) ? target : rulePath;
55
+ const redirectTarget = next.get(key);
56
+ if (seen.has(key)) {
57
+ problems.push(`The redirect from ${from} comes back to ${key} and never reaches a page. Point one of its route rules to a page.`);
58
+ break;
59
+ }
60
+ if (redirectTarget === void 0) {
61
+ if ((target.startsWith("/raw/") || docsSectionForPath(manifest, target) !== null || manifest.base !== "/" && isDocsPath(target, manifest.base)) && !pages.has(target) && !findRoute(routes, "GET", path)) problems.push(`The redirect from ${from} goes to ${end}, which is not a docs page. Point it to a page, or remove the route rule.`);
62
+ break;
63
+ }
64
+ seen.add(key);
65
+ end = redirectTarget;
66
+ path = localTargetPath(end);
54
67
  }
55
- if (target === void 0) continue;
56
- if (seen.has(target)) {
57
- problems.push(`The redirect from ${from} comes back to ${target} and never reaches a page. Point one of its route rules to a page.`);
58
- continue;
59
- }
60
- if ((target.startsWith("/raw/") || docsSectionForPath(manifest, target) !== null || manifest.base !== "/" && isDocsPath(target, manifest.base)) && !pages.has(target) && !findRoute(routes, "GET", end.replace(/[?#].*$/, ""))) problems.push(`The redirect from ${from} goes to ${end}, which is not a docs page. Point it to a page, or remove the route rule.`);
61
68
  }
62
69
  return problems;
63
70
  }
64
- function targetPath(to) {
71
+ function routeRulePath(path) {
72
+ return path.replace(/\/$/, "") || "/";
73
+ }
74
+ function isTrailingSlashRedirect({ from, to }) {
75
+ const target = localTargetPath(to);
76
+ return target !== void 0 && target !== from && target === routeRulePath(from);
77
+ }
78
+ function localTargetPath(to) {
65
79
  if (!to.startsWith("/") || to.startsWith("//")) return void 0;
66
- return normalizeDocsPath(to.replace(/[?#].*$/, ""));
80
+ return to.replace(/[?#].*$/, "");
67
81
  }
68
- /** Redirect route rules that break links. The build stops on them while the link checker is on. */
69
82
  /** `DOCS_REDIRECTS_BROKEN`, with the list of problems in `problems`. */
70
83
  function docsRedirectError(problems) {
71
84
  return Object.assign(docsErrorDiagnostics.DOCS_REDIRECTS_BROKEN({ problems }), { problems });
72
85
  }
73
- //#endregion
74
86
  export { docsServerRoutes as i, docsRedirectProblems as n, docsRedirects as r, docsRedirectError as t };
@@ -0,0 +1,33 @@
1
+ import { a as DocsWorkspaceData, c as RunnableTutorialData, d as dependencyKey, f as restartsDevServer, i as DocsRenderFunction, l as RunnableTutorialStep, m as tutorialWorkspaceFiles, n as DocsPlaygroundData, o as DocsWorkspaceTab, p as tutorialStepFiles, r as DocsPlaygroundExampleData, s as PlaygroundTemplate, t as DocsLearnData, u as TutorialFiles } from "./steps-C3tGwhNK.js";
2
+ import { t as DocsDocument } from "./markdown-B97RuMXs.js";
3
+ type DocsNode = DocsDocument["nodes"][number];
4
+ /**
5
+ * The nodes as a reader of one framework sees them: each `::tabs{sync="framework"}` block becomes the content of that
6
+ * framework's tab. A runnable lesson runs a Vite workspace, so its guide shows the Vite tab, whatever the reader picked.
7
+ */
8
+ export declare function frameworkNodes(nodes: readonly DocsNode[], framework: string): DocsNode[];
9
+ /** Splits a lesson page into the prose before the first step, one node per `::tutorial-step`, and the prose after the last. */
10
+ export declare function splitTutorialDocument(nodes: readonly DocsNode[]): {
11
+ intro: DocsNode[];
12
+ steps: DocsNode[];
13
+ outro: DocsNode[];
14
+ };
15
+ /** A request of a lesson command, which the workspace sends from inside the WebContainer. */
16
+ interface TutorialRequest {
17
+ method: string;
18
+ url: string;
19
+ headers: Record<string, string>;
20
+ body?: string;
21
+ }
22
+ /** Reads the `curl` command of a lesson, such as `curl -X POST http://localhost:3000/api/greet -d '{}'`. Other commands return `undefined`. */
23
+ export declare function parseCurl(command: string): TutorialRequest | undefined;
24
+ /** A Node script that sends the request from inside the workspace and prints the status and the body, like `curl`. */
25
+ export declare function requestScript(request: TutorialRequest): string;
26
+ /** What the Learn page shows about one tutorial page, read from its Markdown. */
27
+ interface LearnPageFacts {
28
+ /** The `::tutorial-step` blocks. */
29
+ steps: number;
30
+ /** About how long the tutorial takes, in minutes. */
31
+ minutes: number;
32
+ }
33
+ export { type DocsLearnData, type DocsPlaygroundData, type DocsPlaygroundExampleData, type DocsRenderFunction, type DocsWorkspaceData, type DocsWorkspaceTab, type LearnPageFacts, type PlaygroundTemplate, type RunnableTutorialData, type RunnableTutorialStep, type TutorialFiles, type TutorialRequest, dependencyKey, restartsDevServer, tutorialStepFiles, tutorialWorkspaceFiles };
@@ -0,0 +1,104 @@
1
+ import { i as tutorialWorkspaceFiles, n as restartsDevServer, r as tutorialStepFiles, t as dependencyKey } from "./steps-muDP1nYT.js";
2
+ // src/runnable/document.ts
3
+ /**
4
+ * The nodes as a reader of one framework sees them: each `::tabs{sync="framework"}` block becomes the content of that
5
+ * framework's tab. A runnable lesson runs a Vite workspace, so its guide shows the Vite tab, whatever the reader picked.
6
+ */
7
+ function frameworkNodes(nodes, framework) {
8
+ return nodes.flatMap((node) => {
9
+ if (!Array.isArray(node) || node[0] === null) return [node];
10
+ const [tag, props, ...children] = node;
11
+ if (tag === "tabs" && props?.sync === "framework") {
12
+ const item = children.find((child) => Array.isArray(child) && child[0] === "tabs-item" && child[1]?.label === framework);
13
+ if (!Array.isArray(item)) return [];
14
+ const [, , ...content] = item;
15
+ return frameworkNodes(content, framework);
16
+ }
17
+ return [[
18
+ tag,
19
+ props,
20
+ ...frameworkNodes(children, framework)
21
+ ]];
22
+ });
23
+ }
24
+ function isStep(node) {
25
+ return Array.isArray(node) && node[0] === "tutorial-step";
26
+ }
27
+ /** Splits a lesson page into the prose before the first step, one node per `::tutorial-step`, and the prose after the last. */
28
+ function splitTutorialDocument(nodes) {
29
+ const first = nodes.findIndex(isStep);
30
+ const last = nodes.findLastIndex(isStep);
31
+ if (first === -1) return {
32
+ intro: [...nodes],
33
+ steps: [],
34
+ outro: []
35
+ };
36
+ return {
37
+ intro: nodes.slice(0, first),
38
+ steps: nodes.slice(first, last + 1).filter(isStep),
39
+ outro: nodes.slice(last + 1)
40
+ };
41
+ }
42
+ function tokenize(command) {
43
+ const tokens = [];
44
+ let current = "";
45
+ let quote;
46
+ let started = false;
47
+ const source = command.replace(/\\\n/g, " ");
48
+ for (let index = 0; index < source.length; index++) {
49
+ const char = source[index];
50
+ if (quote) {
51
+ if (char === quote) quote = void 0;
52
+ else if (char === "\\" && quote === "\"" && index + 1 < source.length) current += source[++index];
53
+ else current += char;
54
+ } else if (char === "'" || char === "\"") {
55
+ quote = char;
56
+ started = true;
57
+ } else if (/\s/.test(char)) {
58
+ if (started || current) tokens.push(current);
59
+ current = "";
60
+ started = false;
61
+ } else current += char;
62
+ }
63
+ if (started || current) tokens.push(current);
64
+ return tokens;
65
+ }
66
+ /** Reads the `curl` command of a lesson, such as `curl -X POST http://localhost:3000/api/greet -d '{}'`. Other commands return `undefined`. */
67
+ function parseCurl(command) {
68
+ const tokens = tokenize(command.trim());
69
+ if (tokens[0] !== "curl") return void 0;
70
+ const request = {
71
+ method: "",
72
+ url: "",
73
+ headers: {}
74
+ };
75
+ for (let index = 1; index < tokens.length; index++) {
76
+ const token = tokens[index];
77
+ const value = () => tokens[++index] ?? "";
78
+ if (token === "-X" || token === "--request") request.method = value().toUpperCase();
79
+ else if (token === "-H" || token === "--header") {
80
+ const header = value();
81
+ const colon = header.indexOf(":");
82
+ if (colon > 0) request.headers[header.slice(0, colon).trim()] = header.slice(colon + 1).trim();
83
+ } else if (token === "-d" || token === "--data" || token === "--data-raw") request.body = value();
84
+ else if (token.startsWith("-")) return void 0;
85
+ else request.url = token;
86
+ }
87
+ if (!/^https?:\/\/localhost(?::\d+)?\//.test(request.url)) return void 0;
88
+ request.method ||= request.body === void 0 ? "GET" : "POST";
89
+ return request;
90
+ }
91
+ /** A Node script that sends the request from inside the workspace and prints the status and the body, like `curl`. */
92
+ function requestScript(request) {
93
+ const init = {
94
+ method: request.method,
95
+ headers: request.headers,
96
+ body: request.body
97
+ };
98
+ return [
99
+ `const response = await fetch(${JSON.stringify(request.url)}, ${JSON.stringify(init)})`,
100
+ `console.log(response.status + " " + response.statusText)`,
101
+ `console.log(await response.text())`
102
+ ].join("\n");
103
+ }
104
+ export { dependencyKey, frameworkNodes, parseCurl, requestScript, restartsDevServer, splitTutorialDocument, tutorialStepFiles, tutorialWorkspaceFiles };
@@ -478,7 +478,8 @@ function toggleGroup(pageGroup: DocsSidebarGroup<DocsAppPage>, event: Event) {
478
478
  cursor: pointer;
479
479
  }
480
480
 
481
- /* A folded group: the summary is its heading, and its chevron points right while the group is shut. */
481
+ /* A folded group: the summary is its heading, and its chevron points right while the group is shut. The disclosure effect
482
+ of the motion layer turns the chevron when the group opens or closes. */
482
483
  .vh-docs-sidebar-fold > summary {
483
484
  cursor: pointer;
484
485
  list-style: none;
@@ -490,7 +491,6 @@ function toggleGroup(pageGroup: DocsSidebarGroup<DocsAppPage>, event: Event) {
490
491
 
491
492
  .vh-docs-sidebar-fold-icon {
492
493
  color: var(--ui-text-dimmed);
493
- transition: transform 150ms ease;
494
494
  }
495
495
 
496
496
  .vh-docs-sidebar-fold:not([open]) .vh-docs-sidebar-fold-icon {
@@ -507,12 +507,6 @@ function toggleGroup(pageGroup: DocsSidebarGroup<DocsAppPage>, event: Event) {
507
507
  }
508
508
  }
509
509
 
510
- @media (prefers-reduced-motion: reduce) {
511
- .vh-docs-sidebar-fold-icon {
512
- transition: none;
513
- }
514
- }
515
-
516
510
  /* A section without a listed home page has a title row that opens nothing. */
517
511
  .vh-docs-sidebar-section-title {
518
512
  display: flex;
@@ -0,0 +1,215 @@
1
+ <script setup lang="ts">
2
+ import { webContainer, Workspace, type WorkspaceExample, type WorkspaceSlotProps, type WorkspaceStep } from "@vite-hub/ui/workspace"
3
+ import { fetchSnapshot } from "@vite-hub/web-container"
4
+ import { docsAppPath } from "#docs/navigation"
5
+ import { frameworkNodes, parseCurl, requestScript, restartsDevServer, splitTutorialDocument, tutorialStepFiles, tutorialWorkspaceFiles } from "#docs/runnable"
6
+ import DocsLearnCodePre from "./DocsLearnCodePre.vue"
7
+ import DocsLearnFile from "./DocsLearnFile.vue"
8
+ import { docsLearnActionsKey, docsLearnGuideNodes, docsLearnStepNodes } from "../utils/docs-learn"
9
+
10
+ import type { DocsLearnData } from "#docs/runnable"
11
+ import type { DocsLearnActions } from "../utils/docs-learn"
12
+ import type { DocsPageResponse } from "@vite-hub/docs"
13
+
14
+ type Files = Record<string, string>
15
+
16
+ const props = defineProps<{ response: DocsPageResponse, data: DocsLearnData }>()
17
+ const tutorial = props.data.tutorial
18
+ const route = useRoute()
19
+ const router = useRouter()
20
+ const { site, appBase } = useDocsConfig()
21
+
22
+ let lessonDocument = props.response.document
23
+ if (tutorial.page !== props.response.page.path) {
24
+ const { data } = await useFetch<DocsPageResponse>(docsAppPath(`/api/_docs/page${tutorial.page}.json`, appBase), { key: `docs:${tutorial.page}` })
25
+ if (!data.value) throw createError({ statusCode: 404, statusMessage: `The lesson page ${tutorial.page} was not found`, fatal: true })
26
+ lessonDocument = data.value.document
27
+ useHead({ link: [{ rel: "canonical", href: `${site.url}${docsAppPath(tutorial.page, appBase)}` }] })
28
+ }
29
+ const lesson = splitTutorialDocument(frameworkNodes(lessonDocument.nodes, "Vite"))
30
+ const steps: WorkspaceStep[] = tutorial.steps.map(item => ({ title: item.title }))
31
+ const total = steps.length
32
+
33
+ const step = computed({
34
+ get: () => {
35
+ const value = Number(route.query.step)
36
+ return Number.isInteger(value) && value >= 1 && value <= total ? value - 1 : 0
37
+ },
38
+ set: value => void router.replace({ query: { ...route.query, step: value === 0 ? undefined : String(value + 1) } }),
39
+ })
40
+
41
+ const paths = [...new Set([...Object.keys(tutorial.files), ...tutorial.steps.flatMap(item => Object.keys(item.files))])]
42
+ const guideNodes = computed(() => docsLearnGuideNodes([
43
+ ...step.value === 0 ? lesson.intro : [],
44
+ ...docsLearnStepNodes(lesson.steps[step.value]),
45
+ ...step.value === total - 1 ? lesson.outro : [],
46
+ ], new Set(paths)))
47
+
48
+ const stepFiles = (index: number, state: "start" | "solution"): Files => tutorialStepFiles(tutorial, index, state)
49
+
50
+ const prebuilt = tutorial.snapshot
51
+ const snapshot = prebuilt && (() => fetchSnapshot(prebuilt.parts, { cache: `vitehub-tutorial-${tutorial.slug}`, sha256: prebuilt.sha256 }))
52
+
53
+ const baseline = shallowRef<Files>(stepFiles(step.value, "start"))
54
+ const examples = computed<WorkspaceExample[]>(() => [
55
+ { id: tutorial.slug, label: tutorial.title, files: stepFiles(step.value, "start"), preview: props.data.preview },
56
+ ])
57
+ const resetStep = (files: Files) => tutorialWorkspaceFiles(tutorial, files, stepFiles(step.value, "start"))
58
+ const runner = webContainer({ port: props.data.port, snapshot: () => snapshot || undefined })
59
+ type Container = NonNullable<typeof runner.workspace.value>
60
+ const selected = ref(Object.keys(tutorial.steps[step.value]?.files ?? {})[0])
61
+ const open = ref(false)
62
+
63
+ const edited = computed(() => {
64
+ const files = runner.workspace.value?.files.value
65
+ if (!files) return []
66
+ const all = new Set([...Object.keys(baseline.value), ...Object.keys(files)])
67
+ return [...all].filter(path => baseline.value[path] !== files[path])
68
+ })
69
+
70
+ async function write(workspace: Container, next: Files) {
71
+ const restart = restartsDevServer(workspace.files.value, next) && ["starting", "ready"].includes(workspace.status.value)
72
+ await workspace.setFiles(next, { mode: "replace" })
73
+ if (restart) await workspace.restart()
74
+ }
75
+
76
+ async function load(target: Files) {
77
+ pendingStep.value = undefined
78
+ const workspace = runner.workspace.value
79
+ const next = workspace && tutorialWorkspaceFiles(tutorial, workspace.files.value, target)
80
+ baseline.value = target
81
+ if (workspace && next) await write(workspace, next)
82
+ }
83
+
84
+ const pendingStep = ref<number>()
85
+ watch(step, (index) => {
86
+ const first = Object.keys(tutorial.steps[index]?.files ?? {})[0]
87
+ if (first) selected.value = first
88
+ if (!runner.workspace.value || edited.value.length === 0) void load(stepFiles(index, "start"))
89
+ else pendingStep.value = index
90
+ })
91
+ function loadPending() {
92
+ if (pendingStep.value !== undefined) void load(stepFiles(pendingStep.value, "start"))
93
+ }
94
+ function keepMine() {
95
+ if (pendingStep.value === undefined) return
96
+ baseline.value = stepFiles(pendingStep.value, "start")
97
+ pendingStep.value = undefined
98
+ }
99
+ function solve(guard: WorkspaceSlotProps["guard"]) {
100
+ guard(`Replace your changes with the solution of step ${step.value + 1}?`, "Replace files", () => void load(stepFiles(step.value, "solution")))
101
+ }
102
+
103
+ const requestPath = "node_modules/.vitehub-tutorial-request.mjs"
104
+ async function run(command: string): Promise<string> {
105
+ const request = parseCurl(command)
106
+ const container = runner.workspace.value?.container.value
107
+ if (!request || !container) return "The workspace is not running."
108
+ await container.fs.mkdir("node_modules", { recursive: true })
109
+ await container.fs.writeFile(requestPath, requestScript(request))
110
+ const process = await container.run(["node", requestPath])
111
+ void process.output.cancel()
112
+ await process.exit
113
+ return (await process.text()).replace(/\u001B\[[\d;]*m/g, "").trim()
114
+ }
115
+
116
+ const actions: DocsLearnActions = {
117
+ get available() {
118
+ return !!runner.workspace.value
119
+ },
120
+ get running() {
121
+ return runner.workspace.value?.status.value === "ready" && !!runner.workspace.value.previewUrl.value
122
+ },
123
+ paths,
124
+ show(path: string) {
125
+ const workspace = runner.workspace.value
126
+ if (workspace && !(path in workspace.files.value)) void write(workspace, { ...workspace.files.value, [path]: "" })
127
+ selected.value = path
128
+ },
129
+ run,
130
+ }
131
+ provide(docsLearnActionsKey, actions)
132
+ const guideComponents = { pre: DocsLearnCodePre, DocsLearnFile }
133
+ </script>
134
+
135
+ <template>
136
+ <div class="vh-docs-workspace" :data-path="response.page.path">
137
+ <Workspace
138
+ v-model:open="open"
139
+ v-model:selected="selected"
140
+ v-model:step="step"
141
+ :steps="steps"
142
+ :guide="data.guide"
143
+ :examples="examples"
144
+ :runner="runner"
145
+ :reset="resetStep"
146
+ :share="false"
147
+ label="lesson"
148
+ >
149
+ <template #guide>
150
+ <!-- A lesson that takes its steps from a docs page links back to that page. -->
151
+ <p v-if="tutorial.page !== response.page.path" class="mb-4 text-sm text-muted">
152
+ <NuxtLink :to="tutorial.page" class="hover:text-highlighted">Read in the docs</NuxtLink>
153
+ </p>
154
+ <UPageBody prose class="docs-content docs-tutorial-content !my-0 !px-0 !pb-0">
155
+ <DocsMarkdown :key="step" :document="{ nodes: guideNodes, toc: [] }" :components="guideComponents" />
156
+ </UPageBody>
157
+ </template>
158
+
159
+ <template #bar-actions="{ guard }">
160
+ <UButton color="neutral" variant="outline" label="Solve" icon="i-lucide-wand-sparkles" @click="solve(guard)" />
161
+ </template>
162
+
163
+ <template v-if="pendingStep !== undefined" #banner>
164
+ <div class="vh-docs-learn-bar" role="status">
165
+ <span class="min-w-0 flex-1">You changed {{ edited.length === 1 ? "1 file" : `${edited.length} files` }}. Step {{ pendingStep + 1 }} has its own version.</span>
166
+ <UButton size="xs" color="neutral" variant="outline" :label="`Load step ${pendingStep + 1}`" @click="loadPending" />
167
+ <UButton size="xs" color="neutral" variant="ghost" label="Keep mine" @click="keepMine" />
168
+ </div>
169
+ </template>
170
+
171
+ <template #intro>
172
+ <h1 class="text-balance text-3xl font-semibold text-highlighted">{{ response.page.sourceTitle }}</h1>
173
+ <p v-if="response.page.description" class="mt-3 text-muted">{{ response.page.description }}</p>
174
+ </template>
175
+
176
+ <!-- Without the workspace, such as on a phone, the page is the whole lesson. -->
177
+ <template #fallback>
178
+ <UPageBody prose class="docs-content docs-tutorial-content !px-0 !pb-0">
179
+ <DocsMarkdown :document="lessonDocument" />
180
+ </UPageBody>
181
+ </template>
182
+ </Workspace>
183
+ </div>
184
+ </template>
185
+
186
+ <style scoped>
187
+ .vh-docs-workspace {
188
+ display: flex;
189
+ height: 100%;
190
+ min-height: 0;
191
+ flex-direction: column;
192
+ }
193
+
194
+ .vh-docs-workspace :deep(.vh-workspace) {
195
+ flex: 1 1 0;
196
+ min-height: 0;
197
+ }
198
+
199
+ .vh-docs-workspace :deep(.vh-workspace-gate-content) {
200
+ width: 100%;
201
+ max-width: calc(65ch + 2rem);
202
+ margin-inline: auto;
203
+ padding: 2.5rem 1rem 4rem;
204
+ }
205
+
206
+ .vh-docs-learn-bar {
207
+ display: flex;
208
+ align-items: center;
209
+ gap: 0.5rem;
210
+ border-bottom: 1px solid var(--ui-border);
211
+ background: var(--ui-bg-elevated);
212
+ padding: 0.5rem 0.75rem;
213
+ font-size: 0.8125rem;
214
+ }
215
+ </style>