@farming-labs/docs 0.1.1 → 0.1.2

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.
@@ -1,3641 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import "../api-reference-wh4_pwG8.mjs";
3
- import { createFilesystemDocsMcpSource, resolveDocsMcpConfig, runDocsMcpStdio } from "../mcp.mjs";
4
- import "../server.mjs";
5
- import fs, { existsSync, readFileSync } from "node:fs";
6
- import path, { join, resolve } from "node:path";
7
2
  import pc from "picocolors";
8
- import * as p from "@clack/prompts";
9
- import { execSync, spawn } from "node:child_process";
10
3
 
11
- //#region src/cli/utils.ts
12
- function detectFramework(cwd) {
13
- const pkgPath = path.join(cwd, "package.json");
14
- if (!fs.existsSync(pkgPath)) return null;
15
- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
16
- const allDeps = {
17
- ...pkg.dependencies,
18
- ...pkg.devDependencies
19
- };
20
- if (allDeps["next"]) return "nextjs";
21
- if (allDeps["@tanstack/react-start"]) return "tanstack-start";
22
- if (allDeps["@sveltejs/kit"]) return "sveltekit";
23
- if (allDeps["astro"]) return "astro";
24
- if (allDeps["nuxt"]) return "nuxt";
25
- return null;
26
- }
27
- function detectPackageManagerFromLockfile(cwd) {
28
- if (fs.existsSync(path.join(cwd, "pnpm-lock.yaml"))) return "pnpm";
29
- if (fs.existsSync(path.join(cwd, "bun.lockb")) || fs.existsSync(path.join(cwd, "bun.lock"))) return "bun";
30
- if (fs.existsSync(path.join(cwd, "yarn.lock"))) return "yarn";
31
- if (fs.existsSync(path.join(cwd, "package-lock.json"))) return "npm";
32
- return null;
33
- }
34
- function installCommand(pm) {
35
- return pm === "yarn" ? "yarn add" : `${pm} add`;
36
- }
37
- function devInstallCommand(pm) {
38
- if (pm === "yarn") return "yarn add -D";
39
- if (pm === "npm") return "npm install -D";
40
- return `${pm} add -D`;
41
- }
42
- /**
43
- * Write a file, creating parent directories as needed.
44
- * Returns true if the file was written, false if it already existed and was skipped.
45
- */
46
- function writeFileSafe(filePath, content, overwrite = false) {
47
- if (fs.existsSync(filePath) && !overwrite) return false;
48
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
49
- fs.writeFileSync(filePath, content, "utf-8");
50
- return true;
51
- }
52
- /**
53
- * Check if a file exists.
54
- */
55
- function fileExists(filePath) {
56
- return fs.existsSync(filePath);
57
- }
58
- /**
59
- * Read a file, returning null if it does not exist.
60
- */
61
- function readFileSafe(filePath) {
62
- if (!fs.existsSync(filePath)) return null;
63
- return fs.readFileSync(filePath, "utf-8");
64
- }
65
- /** Common locations where global CSS files live in Next.js / SvelteKit projects. */
66
- const GLOBAL_CSS_CANDIDATES = [
67
- "app/globals.css",
68
- "app/global.css",
69
- "src/app/globals.css",
70
- "src/app/global.css",
71
- "src/app.css",
72
- "src/styles/app.css",
73
- "styles/globals.css",
74
- "styles/global.css",
75
- "src/styles/globals.css",
76
- "src/styles/global.css",
77
- "assets/css/main.css",
78
- "assets/main.css"
79
- ];
80
- /**
81
- * Find existing global CSS files in the project.
82
- * Returns relative paths that exist.
83
- */
84
- function detectGlobalCssFiles(cwd) {
85
- return GLOBAL_CSS_CANDIDATES.filter((rel) => fs.existsSync(path.join(cwd, rel)));
86
- }
87
- /**
88
- * Detect whether the Next.js project uses `app` or `src/app` for the App Router.
89
- * Returns the directory that exists; if both exist, prefers src/app; if neither, returns null.
90
- */
91
- function detectNextAppDir(cwd) {
92
- const hasSrcApp = fs.existsSync(path.join(cwd, "src", "app"));
93
- const hasApp = fs.existsSync(path.join(cwd, "app"));
94
- if (hasSrcApp) return "src/app";
95
- if (hasApp) return "app";
96
- return null;
97
- }
98
- /**
99
- * Run a shell command synchronously, inheriting stdio.
100
- */
101
- function exec(command, cwd) {
102
- execSync(command, {
103
- cwd,
104
- stdio: "inherit"
105
- });
106
- }
107
- /**
108
- * Spawn a process and wait for a specific string in stdout,
109
- * then resolve with the child process (still running).
110
- */
111
- function spawnAndWaitFor(command, args, cwd, waitFor, timeoutMs = 6e4) {
112
- return new Promise((resolve, reject) => {
113
- const child = spawn(command, args, {
114
- cwd,
115
- stdio: [
116
- "ignore",
117
- "pipe",
118
- "pipe"
119
- ],
120
- shell: true
121
- });
122
- let output = "";
123
- const timer = setTimeout(() => {
124
- child.kill();
125
- reject(/* @__PURE__ */ new Error(`Timed out waiting for "${waitFor}" after ${timeoutMs}ms`));
126
- }, timeoutMs);
127
- child.stdout?.on("data", (data) => {
128
- const text = data.toString();
129
- output += text;
130
- process.stdout.write(text);
131
- if (output.includes(waitFor)) {
132
- clearTimeout(timer);
133
- resolve(child);
134
- }
135
- });
136
- child.stderr?.on("data", (data) => {
137
- process.stderr.write(data.toString());
138
- });
139
- child.on("error", (err) => {
140
- clearTimeout(timer);
141
- reject(err);
142
- });
143
- child.on("close", (code) => {
144
- clearTimeout(timer);
145
- if (!output.includes(waitFor)) reject(/* @__PURE__ */ new Error(`Process exited with code ${code} before "${waitFor}" appeared`));
146
- });
147
- });
148
- }
149
-
150
- //#endregion
151
- //#region src/cli/templates.ts
152
- const THEME_INFO = {
153
- fumadocs: {
154
- factory: "fumadocs",
155
- nextImport: "@farming-labs/theme",
156
- svelteImport: "@farming-labs/svelte-theme",
157
- astroImport: "@farming-labs/astro-theme",
158
- nuxtImport: "@farming-labs/nuxt-theme",
159
- nextCssImport: "default",
160
- svelteCssTheme: "fumadocs",
161
- astroCssTheme: "fumadocs",
162
- nuxtCssTheme: "fumadocs"
163
- },
164
- darksharp: {
165
- factory: "darksharp",
166
- nextImport: "@farming-labs/theme/darksharp",
167
- svelteImport: "@farming-labs/svelte-theme/darksharp",
168
- astroImport: "@farming-labs/astro-theme/darksharp",
169
- nuxtImport: "@farming-labs/nuxt-theme/darksharp",
170
- nextCssImport: "darksharp",
171
- svelteCssTheme: "darksharp",
172
- astroCssTheme: "darksharp",
173
- nuxtCssTheme: "darksharp"
174
- },
175
- "pixel-border": {
176
- factory: "pixelBorder",
177
- nextImport: "@farming-labs/theme/pixel-border",
178
- svelteImport: "@farming-labs/svelte-theme/pixel-border",
179
- astroImport: "@farming-labs/astro-theme/pixel-border",
180
- nuxtImport: "@farming-labs/nuxt-theme/pixel-border",
181
- nextCssImport: "pixel-border",
182
- svelteCssTheme: "pixel-border",
183
- astroCssTheme: "pixel-border",
184
- nuxtCssTheme: "pixel-border"
185
- },
186
- colorful: {
187
- factory: "colorful",
188
- nextImport: "@farming-labs/theme/colorful",
189
- svelteImport: "@farming-labs/svelte-theme/colorful",
190
- astroImport: "@farming-labs/astro-theme/colorful",
191
- nuxtImport: "@farming-labs/nuxt-theme/colorful",
192
- nextCssImport: "colorful",
193
- svelteCssTheme: "colorful",
194
- astroCssTheme: "colorful",
195
- nuxtCssTheme: "colorful"
196
- },
197
- darkbold: {
198
- factory: "darkbold",
199
- nextImport: "@farming-labs/theme/darkbold",
200
- svelteImport: "@farming-labs/svelte-theme/darkbold",
201
- astroImport: "@farming-labs/astro-theme/darkbold",
202
- nuxtImport: "@farming-labs/nuxt-theme/darkbold",
203
- nextCssImport: "darkbold",
204
- svelteCssTheme: "darkbold",
205
- astroCssTheme: "darkbold",
206
- nuxtCssTheme: "darkbold"
207
- },
208
- shiny: {
209
- factory: "shiny",
210
- nextImport: "@farming-labs/theme/shiny",
211
- svelteImport: "@farming-labs/svelte-theme/shiny",
212
- astroImport: "@farming-labs/astro-theme/shiny",
213
- nuxtImport: "@farming-labs/nuxt-theme/shiny",
214
- nextCssImport: "shiny",
215
- svelteCssTheme: "shiny",
216
- astroCssTheme: "shiny",
217
- nuxtCssTheme: "shiny"
218
- },
219
- greentree: {
220
- factory: "greentree",
221
- nextImport: "@farming-labs/theme/greentree",
222
- svelteImport: "@farming-labs/svelte-theme/greentree",
223
- astroImport: "@farming-labs/astro-theme/greentree",
224
- nuxtImport: "@farming-labs/nuxt-theme/greentree",
225
- nextCssImport: "greentree",
226
- svelteCssTheme: "greentree",
227
- astroCssTheme: "greentree",
228
- nuxtCssTheme: "greentree"
229
- },
230
- concrete: {
231
- factory: "concrete",
232
- nextImport: "@farming-labs/theme/concrete",
233
- svelteImport: "@farming-labs/svelte-theme/concrete",
234
- astroImport: "@farming-labs/astro-theme/concrete",
235
- nuxtImport: "@farming-labs/nuxt-theme/concrete",
236
- nextCssImport: "concrete",
237
- svelteCssTheme: "concrete",
238
- astroCssTheme: "concrete",
239
- nuxtCssTheme: "concrete"
240
- },
241
- hardline: {
242
- factory: "hardline",
243
- nextImport: "@farming-labs/theme/hardline",
244
- svelteImport: "@farming-labs/svelte-theme/hardline",
245
- astroImport: "@farming-labs/astro-theme/hardline",
246
- nuxtImport: "@farming-labs/nuxt-theme/hardline",
247
- nextCssImport: "hardline",
248
- svelteCssTheme: "hardline",
249
- astroCssTheme: "hardline",
250
- nuxtCssTheme: "hardline"
251
- }
252
- };
253
- function getThemeInfo(theme) {
254
- return THEME_INFO[theme] ?? THEME_INFO.fumadocs;
255
- }
256
- function toPosixPath(value) {
257
- return value.replace(/\\/g, "/");
258
- }
259
- function stripScriptExtension(value) {
260
- return value.replace(/\.(?:[cm]?[jt]sx?)$/i, "");
261
- }
262
- function relativeImport(fromFile, toFile) {
263
- const fromPosix = toPosixPath(fromFile);
264
- const toPosix = stripScriptExtension(toPosixPath(toFile));
265
- const rel = path.posix.relative(path.posix.dirname(fromPosix), toPosix);
266
- return rel.startsWith(".") ? rel : `./${rel}`;
267
- }
268
- function relativeAssetPath(fromFile, toFile) {
269
- const fromPosix = toPosixPath(fromFile);
270
- const toPosix = toPosixPath(toFile);
271
- const rel = path.posix.relative(path.posix.dirname(fromPosix), toPosix);
272
- return rel.startsWith(".") ? rel : `./${rel}`;
273
- }
274
- function extractImportSpecifier(importLine) {
275
- const fromMatch = importLine.match(/\bfrom\s+["']([^"']+)["']/);
276
- if (fromMatch) return fromMatch[1];
277
- const bareImportMatch = importLine.match(/^\s*import\s+["']([^"']+)["']/);
278
- if (bareImportMatch) return bareImportMatch[1];
279
- return null;
280
- }
281
- function addImportLine(content, importLine) {
282
- if (content.includes(importLine)) return content;
283
- const specifier = extractImportSpecifier(importLine);
284
- if (specifier) {
285
- if (new RegExp(String.raw`\bimport(?:\s+type)?[\s\S]*?\bfrom\s+["']${specifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}["']|^\s*import\s+["']${specifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}["']`, "m").test(content)) return content;
286
- }
287
- const lines = content.split("\n");
288
- const lastImportIdx = lines.reduce((acc, line, index) => {
289
- const trimmed = line.trimStart();
290
- return trimmed.startsWith("import ") || trimmed.startsWith("import type ") ? index : acc;
291
- }, -1);
292
- if (lastImportIdx >= 0) lines.splice(lastImportIdx + 1, 0, importLine);
293
- else lines.unshift(importLine, "");
294
- return lines.join("\n");
295
- }
296
- function renderI18nConfig(cfg, indent = " ") {
297
- const i18n = cfg.i18n;
298
- if (!i18n || i18n.locales.length === 0) return "";
299
- return `${indent}i18n: {\n${indent} locales: [${i18n.locales.map((locale) => `"${locale}"`).join(", ")}],\n${indent} defaultLocale: "${i18n.defaultLocale}",\n${indent}},\n`;
300
- }
301
- function renderApiReferenceConfig(cfg, indent = " ") {
302
- const apiReference = cfg.apiReference;
303
- if (!apiReference) return "";
304
- return `${indent}apiReference: {\n${indent} enabled: true,\n${indent} path: "${apiReference.path}",\n${indent} routeRoot: "${apiReference.routeRoot}",\n${indent}},\n`;
305
- }
306
- function toLocaleImportName(locale) {
307
- return `LocalePage_${locale.replace(/[^a-zA-Z0-9_$]/g, "_")}`;
308
- }
309
- function getThemeExportName(themeName) {
310
- const base = themeName.replace(/\.ts$/i, "").trim();
311
- if (!base) return "customTheme";
312
- return base.replace(/-([a-z])/g, (_, c) => c.toUpperCase()).replace(/^./, (c) => c.toLowerCase());
313
- }
314
- function getCustomThemeCssImportPath(globalCssRelPath, themeName) {
315
- if (globalCssRelPath.startsWith("app/")) return `../themes/${themeName}.css`;
316
- if (globalCssRelPath.startsWith("src/")) return `../../themes/${themeName}.css`;
317
- return `../themes/${themeName}.css`;
318
- }
319
- /** Content for themes/{name}.ts - createTheme with the given name */
320
- function customThemeTsTemplate(themeName) {
321
- return `\
322
- import { createTheme } from "@farming-labs/docs";
323
-
324
- export const ${getThemeExportName(themeName)} = createTheme({
325
- name: "${themeName.replace(/\.ts$/i, "")}",
326
- ui: {
327
- colors: {
328
- primary: "#e11d48",
329
- background: "#09090b",
330
- foreground: "#fafafa",
331
- muted: "#71717a",
332
- border: "#27272a",
333
- },
334
- radius: "0.5rem",
335
- },
336
- });
337
- `;
338
- }
339
- function customThemeCssTemplate(themeName) {
340
- return `\
341
- /* Custom theme: ${themeName} - edit variables and selectors as needed */
342
- @import "@farming-labs/theme/presets/black";
343
-
344
- .dark {
345
- --color-fd-primary: #e11d48;
346
- --color-fd-background: #09090b;
347
- --color-fd-border: #27272a;
348
- --radius: 0.5rem;
349
- }
350
- `;
351
- }
352
- /** Config import for Next.js root layout → root docs.config */
353
- function nextRootLayoutConfigImport(useAlias, nextAppDir = "app") {
354
- if (useAlias) return "@/docs.config";
355
- return nextAppDir === "src/app" ? "../../docs.config" : "../docs.config";
356
- }
357
- /** Config import for Next.js app/{entry}/layout.tsx → root docs.config */
358
- function nextDocsLayoutConfigImport(useAlias, nextAppDir = "app") {
359
- if (useAlias) return "@/docs.config";
360
- return nextAppDir === "src/app" ? "../../../docs.config" : "../../docs.config";
361
- }
362
- function nextApiReferenceConfigImport(useAlias, nextAppDir = "app", filePath) {
363
- if (useAlias) return "@/docs.config";
364
- return relativeImport(filePath, "docs.config.ts");
365
- }
366
- /** Config import for SvelteKit src/lib/docs.server.ts → src/lib/docs.config */
367
- function svelteServerConfigImport(useAlias) {
368
- return useAlias ? "$lib/docs.config" : "./docs.config";
369
- }
370
- /** Config import for SvelteKit src/routes/{entry}/+layout.svelte → src/lib/docs.config */
371
- function svelteLayoutConfigImport(useAlias) {
372
- return useAlias ? "$lib/docs.config" : "../../lib/docs.config";
373
- }
374
- /** Config import for SvelteKit src/routes/{entry}/[...slug]/+page.svelte → src/lib/docs.config */
375
- function sveltePageConfigImport(useAlias) {
376
- return useAlias ? "$lib/docs.config" : "../../../lib/docs.config";
377
- }
378
- /** Server import for SvelteKit +layout.server.js → src/lib/docs.server */
379
- function svelteLayoutServerImport(useAlias) {
380
- return useAlias ? "$lib/docs.server" : "../../lib/docs.server";
381
- }
382
- function astroServerConfigImport(useAlias) {
383
- return useAlias ? "@/lib/docs.config" : "./docs.config";
384
- }
385
- function astroPageConfigImport(useAlias, depth) {
386
- if (useAlias) return "@/lib/docs.config";
387
- return `${"../".repeat(depth)}lib/docs.config`;
388
- }
389
- function astroPageServerImport(useAlias, depth) {
390
- if (useAlias) return "@/lib/docs.server";
391
- return `${"../".repeat(depth)}lib/docs.server`;
392
- }
393
- function docsConfigTemplate(cfg) {
394
- if (cfg.theme === "custom" && cfg.customThemeName) {
395
- const exportName = getThemeExportName(cfg.customThemeName);
396
- return `\
397
- import { defineDocs } from "@farming-labs/docs";
398
- import { ${exportName} } from "${cfg.useAlias ? "@/themes/" + cfg.customThemeName.replace(/\.ts$/i, "") : "./themes/" + cfg.customThemeName.replace(/\.ts$/i, "")}";
399
-
400
- export default defineDocs({
401
- entry: "${cfg.entry}",
402
- ${renderI18nConfig(cfg)}${renderApiReferenceConfig(cfg)} theme: ${exportName}({
403
- ui: {
404
- colors: { primary: "#6366f1" },
405
- },
406
- }),
407
-
408
- metadata: {
409
- titleTemplate: "%s – ${cfg.projectName}",
410
- description: "Documentation for ${cfg.projectName}",
411
- },
412
- });
413
- `;
414
- }
415
- const t = getThemeInfo(cfg.theme);
416
- return `\
417
- import { defineDocs } from "@farming-labs/docs";
418
- import { ${t.factory} } from "${t.nextImport}";
419
-
420
- export default defineDocs({
421
- entry: "${cfg.entry}",
422
- ${renderI18nConfig(cfg)}${renderApiReferenceConfig(cfg)} theme: ${t.factory}({
423
- ui: {
424
- colors: { primary: "#6366f1" },
425
- },
426
- }),
427
-
428
- metadata: {
429
- titleTemplate: "%s – ${cfg.projectName}",
430
- description: "Documentation for ${cfg.projectName}",
431
- },
432
- });
433
- `;
434
- }
435
- function nextConfigTemplate() {
436
- return `\
437
- import { withDocs } from "@farming-labs/next/config";
438
-
439
- export default withDocs();
440
- `;
441
- }
442
- function nextConfigMergedTemplate(existingContent) {
443
- if (existingContent.includes("withDocs")) return existingContent;
444
- const lines = existingContent.split("\n");
445
- const importLine = "import { withDocs } from \"@farming-labs/next/config\";";
446
- const exportIdx = lines.findIndex((l) => l.match(/export\s+default/));
447
- if (exportIdx === -1) return `${importLine}\n\n${existingContent}\n\nexport default withDocs();\n`;
448
- const lastImportIdx = lines.reduce((acc, l, i) => l.trimStart().startsWith("import ") ? i : acc, -1);
449
- if (lastImportIdx >= 0) lines.splice(lastImportIdx + 1, 0, importLine);
450
- else lines.unshift(importLine, "");
451
- const adjustedExportIdx = exportIdx + (lastImportIdx >= 0 ? exportIdx > lastImportIdx ? 1 : 0 : 2);
452
- const simpleMatch = lines[adjustedExportIdx].match(/^(\s*export\s+default\s+)(.*?)(;?\s*)$/);
453
- if (simpleMatch) {
454
- const [, prefix, value, suffix] = simpleMatch;
455
- lines[adjustedExportIdx] = `${prefix}withDocs(${value})${suffix}`;
456
- }
457
- return lines.join("\n");
458
- }
459
- function rootLayoutTemplate(cfg, globalCssRelPath = "app/globals.css") {
460
- let cssImport;
461
- if (globalCssRelPath.startsWith("app/")) cssImport = "./" + globalCssRelPath.slice(4);
462
- else if (globalCssRelPath.startsWith("src/app/")) cssImport = "./" + globalCssRelPath.slice(8);
463
- else cssImport = "../" + globalCssRelPath;
464
- const appDir = cfg.nextAppDir ?? "app";
465
- return `\
466
- import type { Metadata } from "next";
467
- import { RootProvider } from "@farming-labs/theme";
468
- import docsConfig from "${nextRootLayoutConfigImport(cfg.useAlias, appDir)}";
469
- import "${cssImport}";
470
-
471
- export const metadata: Metadata = {
472
- title: {
473
- default: "Docs",
474
- template: docsConfig.metadata?.titleTemplate ?? "%s",
475
- },
476
- description: docsConfig.metadata?.description,
477
- };
478
-
479
- export default function RootLayout({
480
- children,
481
- }: {
482
- children: React.ReactNode;
483
- }) {
484
- return (
485
- <html lang="en" suppressHydrationWarning>
486
- <body>
487
- <RootProvider>{children}</RootProvider>
488
- </body>
489
- </html>
490
- );
491
- }
492
- `;
493
- }
494
- /**
495
- * Injects RootProvider (import + wrapper) into an existing root layout without overwriting.
496
- * Returns the modified content, or null if RootProvider is already present or injection isn't possible.
497
- */
498
- function injectRootProviderIntoLayout(content) {
499
- if (!content || content.includes("RootProvider")) return null;
500
- let out = content;
501
- const themeImport = "import { RootProvider } from \"@farming-labs/theme\";";
502
- if (!out.includes("@farming-labs/theme")) {
503
- const lines = out.split("\n");
504
- let lastImportIdx = -1;
505
- for (let i = 0; i < lines.length; i++) {
506
- const trimmed = lines[i].trimStart();
507
- if (trimmed.startsWith("import ") || trimmed.startsWith("import type ")) lastImportIdx = i;
508
- }
509
- if (lastImportIdx >= 0) {
510
- lines.splice(lastImportIdx + 1, 0, themeImport);
511
- out = lines.join("\n");
512
- } else out = themeImport + "\n" + out;
513
- }
514
- if (!out.includes("<RootProvider>")) {
515
- const childrenPattern = /\{children\}/;
516
- if (childrenPattern.test(out)) out = out.replace(childrenPattern, "<RootProvider>{children}</RootProvider>");
517
- }
518
- return out === content ? null : out;
519
- }
520
- function globalCssTemplate(theme, customThemeName, globalCssRelPath) {
521
- if (theme === "custom" && customThemeName && globalCssRelPath) return `\
522
- @import "tailwindcss";
523
- @import "${getCustomThemeCssImportPath(globalCssRelPath, customThemeName.replace(/\.css$/i, ""))}";
524
- `;
525
- return `\
526
- @import "tailwindcss";
527
- @import "@farming-labs/theme/${getThemeInfo(theme).nextCssImport}/css";
528
- `;
529
- }
530
- function injectCssImport(existingContent, theme, customThemeName, globalCssRelPath) {
531
- const importLine = theme === "custom" && customThemeName && globalCssRelPath ? `@import "${getCustomThemeCssImportPath(globalCssRelPath, customThemeName.replace(/\.css$/i, ""))}";` : `@import "@farming-labs/theme/${getThemeInfo(theme).nextCssImport}/css";`;
532
- if (existingContent.includes(importLine)) return null;
533
- if (theme !== "custom" && existingContent.includes("@farming-labs/theme/") && existingContent.includes("/css")) return null;
534
- if (theme === "custom" && existingContent.includes("themes/") && existingContent.includes(".css")) return null;
535
- const lines = existingContent.split("\n");
536
- const lastImportIdx = lines.reduce((acc, l, i) => l.trimStart().startsWith("@import") ? i : acc, -1);
537
- if (lastImportIdx >= 0) lines.splice(lastImportIdx + 1, 0, importLine);
538
- else lines.unshift(importLine);
539
- return lines.join("\n");
540
- }
541
- function docsLayoutTemplate(cfg) {
542
- const appDir = cfg.nextAppDir ?? "app";
543
- return `\
544
- import docsConfig from "${nextDocsLayoutConfigImport(cfg.useAlias, appDir)}";
545
- import { createDocsLayout, createDocsMetadata } from "@farming-labs/theme";
546
-
547
- export const metadata = createDocsMetadata(docsConfig);
548
-
549
- const DocsLayout = createDocsLayout(docsConfig);
550
-
551
- export default function Layout({ children }: { children: React.ReactNode }) {
552
- return (
553
- <>
554
- <DocsLayout>{children}</DocsLayout>
555
- </>
556
- );
557
- }
558
- `;
559
- }
560
- function nextApiReferenceRouteTemplate(cfg, filePath) {
561
- const appDir = cfg.nextAppDir ?? "app";
562
- return `
563
- import docsConfig from "${nextApiReferenceConfigImport(cfg.useAlias, appDir, filePath)}";
564
- import { createNextApiReference } from "@farming-labs/next/api-reference";
565
-
566
- export const GET = createNextApiReference(docsConfig);
567
-
568
- export const revalidate = false;
569
- `;
570
- }
571
- function nextLocaleDocPageTemplate(defaultLocale) {
572
- return `\
573
- import type { ComponentType } from "react";
574
-
575
- type SearchParams = Promise<{ lang?: string | string[] | undefined }> | undefined;
576
-
577
- function normalizeLang(value: string | string[] | undefined) {
578
- return Array.isArray(value) ? value[0] : value;
579
- }
580
-
581
- export async function resolveLocaleDocPage<T extends ComponentType>(
582
- searchParams: SearchParams,
583
- pages: Record<string, T>,
584
- fallbackLocale = "${defaultLocale}",
585
- ) {
586
- const params = (await searchParams) ?? {};
587
- const locale = normalizeLang(params.lang) ?? fallbackLocale;
588
-
589
- return pages[locale] ?? pages[fallbackLocale];
590
- }
591
- `;
592
- }
593
- function nextLocalizedPageTemplate(options) {
594
- const importLines = options.pageImports.map(({ locale, importPath }) => `import ${toLocaleImportName(locale)} from "${importPath}";`).join("\n");
595
- const pageMap = options.pageImports.map(({ locale }) => ` ${JSON.stringify(locale)}: ${toLocaleImportName(locale)},`).join("\n");
596
- return `\
597
- ${importLines}
598
- import { resolveLocaleDocPage } from "${options.helperImport}";
599
-
600
- type PageProps = {
601
- searchParams?: Promise<{ lang?: string | string[] | undefined }>;
602
- };
603
-
604
- export default async function ${options.componentName}({ searchParams }: PageProps) {
605
- const Page = await resolveLocaleDocPage(searchParams, {
606
- ${pageMap}
607
- }, "${options.defaultLocale}");
608
-
609
- return <Page />;
610
- }
611
- `;
612
- }
613
- function postcssConfigTemplate() {
614
- return `\
615
- const config = {
616
- plugins: {
617
- "@tailwindcss/postcss": {},
618
- },
619
- };
620
-
621
- export default config;
622
- `;
623
- }
624
- /** @param useAlias - When false, paths (e.g. @/*) are omitted so no alias is added. */
625
- function tsconfigTemplate(useAlias = false) {
626
- return `\
627
- {
628
- "compilerOptions": {
629
- "target": "ES2017",
630
- "lib": ["dom", "dom.iterable", "esnext"],
631
- "allowJs": true,
632
- "skipLibCheck": true,
633
- "strict": true,
634
- "noEmit": true,
635
- "esModuleInterop": true,
636
- "module": "esnext",
637
- "moduleResolution": "bundler",
638
- "resolveJsonModule": true,
639
- "isolatedModules": true,
640
- "jsx": "react-jsx",
641
- "incremental": true,
642
- "plugins": [{ "name": "next" }]${useAlias ? ",\n \"paths\": { \"@/*\": [\"./*\"] }" : ""}
643
- },
644
- "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
645
- "exclude": ["node_modules"]
646
- }
647
- `;
648
- }
649
- function welcomePageTemplate(cfg) {
650
- const appDir = cfg.nextAppDir ?? "app";
651
- return `\
652
- ---
653
- title: "Documentation"
654
- description: "Welcome to ${cfg.projectName} documentation"
655
- ---
656
-
657
- # Welcome to ${cfg.projectName}
658
-
659
- Get started with our documentation. Browse the pages on the left to learn more.
660
-
661
- <Callout type="info">
662
- This documentation was generated by \`@farming-labs/docs\`. Edit the MDX files in \`${appDir}/${cfg.entry}/\` to customize.
663
- </Callout>
664
-
665
- ## Overview
666
-
667
- This is your documentation home page. From here you can navigate to:
668
-
669
- - [Installation](/${cfg.entry}/installation) — How to install and set up the project
670
- - [Quickstart](/${cfg.entry}/quickstart) — Get up and running in minutes
671
-
672
- ## Features
673
-
674
- - **MDX Support** — Write docs with Markdown and React components
675
- - **Syntax Highlighting** — Code blocks with automatic highlighting
676
- - **Dark Mode** — Built-in theme switching
677
- - **Search** — Full-text search across all pages
678
- - **Responsive** — Works on any screen size
679
-
680
- ---
681
-
682
- ## Next Steps
683
-
684
- Start by reading the [Installation](/${cfg.entry}/installation) guide, then follow the [Quickstart](/${cfg.entry}/quickstart) to build something.
685
- `;
686
- }
687
- function installationPageTemplate(cfg) {
688
- const t = getThemeInfo(cfg.theme);
689
- return `\
690
- ---
691
- title: "Installation"
692
- description: "How to install and set up ${cfg.projectName}"
693
- ---
694
-
695
- # Installation
696
-
697
- Follow these steps to install and configure ${cfg.projectName}.
698
-
699
- <Callout type="info">
700
- Prerequisites: Node.js 18+ and a package manager (pnpm, npm, or yarn).
701
- </Callout>
702
-
703
- ## Install Dependencies
704
-
705
- \`\`\`bash
706
- pnpm add @farming-labs/docs
707
- \`\`\`
708
-
709
- ## Configuration
710
-
711
- Your project includes a \`docs.config.ts\` at the root:
712
-
713
- \`\`\`ts
714
- import { defineDocs } from "@farming-labs/docs";
715
- import { ${t.factory} } from "${t.nextImport}";
716
-
717
- export default defineDocs({
718
- entry: "${cfg.entry}",
719
- theme: ${t.factory}({
720
- ui: { colors: { primary: "#6366f1" } },
721
- }),
722
- });
723
- \`\`\`
724
-
725
- ## Project Structure
726
-
727
- \`\`\`
728
- ${cfg.nextAppDir ?? "app"}/
729
- ${cfg.entry}/
730
- layout.tsx # Docs layout
731
- page.mdx # /${cfg.entry}
732
- installation/
733
- page.mdx # /${cfg.entry}/installation
734
- quickstart/
735
- page.mdx # /${cfg.entry}/quickstart
736
- docs.config.ts # Docs configuration
737
- next.config.ts # Next.js config with withDocs()
738
- \`\`\`
739
-
740
- ## What's Next?
741
-
742
- Head to the [Quickstart](/${cfg.entry}/quickstart) guide to start writing your first page.
743
- `;
744
- }
745
- function quickstartPageTemplate(cfg) {
746
- const t = getThemeInfo(cfg.theme);
747
- return `\
748
- ---
749
- title: "Quickstart"
750
- description: "Get up and running in minutes"
751
- ---
752
-
753
- # Quickstart
754
-
755
- This guide walks you through creating your first documentation page.
756
-
757
- ## Creating a Page
758
-
759
- Create a new folder under \`${cfg.nextAppDir ?? "app"}/${cfg.entry}/\` with a \`page.mdx\` file:
760
-
761
- \`\`\`bash
762
- mkdir -p ${cfg.nextAppDir ?? "app"}/${cfg.entry}/my-page
763
- \`\`\`
764
-
765
- Then create \`${cfg.nextAppDir ?? "app"}/${cfg.entry}/my-page/page.mdx\`:
766
-
767
- \`\`\`mdx
768
- ---
769
- title: "My Page"
770
- description: "A custom documentation page"
771
- ---
772
-
773
- # My Page
774
-
775
- Write your content here using **Markdown** and JSX components.
776
- \`\`\`
777
-
778
- Your page is now available at \`/${cfg.entry}/my-page\`.
779
-
780
- ## Using Components
781
-
782
- ### Callouts
783
-
784
- <Callout type="info">
785
- This is an informational callout. Use it for tips and notes.
786
- </Callout>
787
-
788
- <Callout type="warn">
789
- This is a warning callout. Use it for important caveats.
790
- </Callout>
791
-
792
- ### Code Blocks
793
-
794
- Code blocks are automatically syntax-highlighted:
795
-
796
- \`\`\`typescript
797
- function greet(name: string): string {
798
- return \\\`Hello, \\\${name}!\\\`;
799
- }
800
-
801
- console.log(greet("World"));
802
- \`\`\`
803
-
804
- ## Customizing the Theme
805
-
806
- Edit \`docs.config.ts\` to change colors, typography, and component defaults:
807
-
808
- \`\`\`ts
809
- theme: ${t.factory}({
810
- ui: {
811
- colors: { primary: "#22c55e" },
812
- },
813
- }),
814
- \`\`\`
815
-
816
- ## Deploying
817
-
818
- Build your docs for production:
819
-
820
- \`\`\`bash
821
- pnpm build
822
- \`\`\`
823
-
824
- Deploy to Vercel, Netlify, or any Node.js hosting platform.
825
- `;
826
- }
827
- function tanstackDocsConfigTemplate(cfg) {
828
- if (cfg.theme === "custom" && cfg.customThemeName) {
829
- const exportName = getThemeExportName(cfg.customThemeName);
830
- return `\
831
- import { defineDocs } from "@farming-labs/docs";
832
- import { ${exportName} } from "./themes/${cfg.customThemeName.replace(/\.ts$/i, "")}";
833
-
834
- export default defineDocs({
835
- entry: "${cfg.entry}",
836
- contentDir: "${cfg.entry}",
837
- ${renderApiReferenceConfig(cfg)} theme: ${exportName}({
838
- ui: {
839
- colors: { primary: "#6366f1" },
840
- },
841
- }),
842
- nav: {
843
- title: "${cfg.projectName} Docs",
844
- url: "/${cfg.entry}",
845
- },
846
- themeToggle: {
847
- enabled: true,
848
- default: "dark",
849
- },
850
- metadata: {
851
- titleTemplate: "%s – ${cfg.projectName}",
852
- description: "Documentation for ${cfg.projectName}",
853
- },
854
- });
855
- `;
856
- }
857
- const t = getThemeInfo(cfg.theme);
858
- return `\
859
- import { defineDocs } from "@farming-labs/docs";
860
- import { ${t.factory} } from "${t.nextImport}";
861
-
862
- export default defineDocs({
863
- entry: "${cfg.entry}",
864
- contentDir: "${cfg.entry}",
865
- ${renderApiReferenceConfig(cfg)} theme: ${t.factory}({
866
- ui: {
867
- colors: { primary: "#6366f1" },
868
- },
869
- }),
870
- nav: {
871
- title: "${cfg.projectName} Docs",
872
- url: "/${cfg.entry}",
873
- },
874
- themeToggle: {
875
- enabled: true,
876
- default: "dark",
877
- },
878
- metadata: {
879
- titleTemplate: "%s – ${cfg.projectName}",
880
- description: "Documentation for ${cfg.projectName}",
881
- },
882
- });
883
- `;
884
- }
885
- function tanstackDocsServerTemplate() {
886
- return `\
887
- import { createDocsServer } from "@farming-labs/tanstack-start/server";
888
- import docsConfig from "../../docs.config";
889
-
890
- export const docsServer = createDocsServer({
891
- ...docsConfig,
892
- rootDir: process.cwd(),
893
- });
894
- `;
895
- }
896
- function tanstackDocsFunctionsTemplate() {
897
- return `\
898
- import { createServerFn } from "@tanstack/react-start";
899
- import { docsServer } from "./docs.server";
900
-
901
- export const loadDocPage = createServerFn({ method: "GET" })
902
- .inputValidator((data: { pathname: string; locale?: string }) => data)
903
- .handler(async ({ data }) => docsServer.load(data));
904
- `;
905
- }
906
- function tanstackDocsFunctionsImport(opts) {
907
- if (opts.useAlias) return "@/lib/docs.functions";
908
- return relativeImport(opts.filePath, "src/lib/docs.functions.ts");
909
- }
910
- function tanstackDocsConfigImport(filePath) {
911
- return relativeImport(filePath, "docs.config.ts");
912
- }
913
- function tanstackDocsIndexRouteTemplate(opts) {
914
- const entryUrl = `/${opts.entry.replace(/^\/+|\/+$/g, "")}`;
915
- return `\
916
- import { createFileRoute } from "@tanstack/react-router";
917
- import { TanstackDocsPage } from "@farming-labs/tanstack-start/react";
918
- import { loadDocPage } from "${tanstackDocsFunctionsImport(opts)}";
919
- import docsConfig from "${tanstackDocsConfigImport(opts.filePath)}";
920
-
921
- export const Route = createFileRoute("${entryUrl}/")({
922
- loader: () => loadDocPage({ data: { pathname: "${entryUrl}" } }),
923
- head: ({ loaderData }) => ({
924
- meta: [
925
- { title: loaderData ? \`\${loaderData.title} – ${opts.projectName}\` : "${opts.projectName}" },
926
- ...(loaderData?.description
927
- ? [{ name: "description", content: loaderData.description }]
928
- : []),
929
- ],
930
- }),
931
- component: DocsIndexPage,
932
- });
933
-
934
- function DocsIndexPage() {
935
- const data = Route.useLoaderData();
936
- return <TanstackDocsPage config={docsConfig} data={data} />;
937
- }
938
- `;
939
- }
940
- function tanstackDocsCatchAllRouteTemplate(opts) {
941
- const entryUrl = `/${opts.entry.replace(/^\/+|\/+$/g, "")}`;
942
- return `\
943
- import { createFileRoute, notFound } from "@tanstack/react-router";
944
- import { TanstackDocsPage } from "@farming-labs/tanstack-start/react";
945
- import { loadDocPage } from "${tanstackDocsFunctionsImport(opts)}";
946
- import docsConfig from "${tanstackDocsConfigImport(opts.filePath)}";
947
-
948
- export const Route = createFileRoute("${entryUrl}/$")({
949
- loader: async ({ location }) => {
950
- try {
951
- return await loadDocPage({ data: { pathname: location.pathname } });
952
- } catch (error) {
953
- if (
954
- error &&
955
- typeof error === "object" &&
956
- "status" in error &&
957
- (error as { status?: unknown }).status === 404
958
- ) {
959
- throw notFound();
960
- }
961
- throw error;
962
- }
963
- },
964
- head: ({ loaderData }) => ({
965
- meta: [
966
- { title: loaderData ? \`\${loaderData.title} – ${opts.projectName}\` : "${opts.projectName}" },
967
- ...(loaderData?.description
968
- ? [{ name: "description", content: loaderData.description }]
969
- : []),
970
- ],
971
- }),
972
- component: DocsCatchAllPage,
973
- });
974
-
975
- function DocsCatchAllPage() {
976
- const data = Route.useLoaderData();
977
- return <TanstackDocsPage config={docsConfig} data={data} />;
978
- }
979
- `;
980
- }
981
- function tanstackApiDocsRouteTemplate(useAlias, filePath) {
982
- return `\
983
- import { createFileRoute } from "@tanstack/react-router";
984
- import { docsServer } from "${useAlias ? "@/lib/docs.server" : relativeImport(filePath, "src/lib/docs.server.ts")}";
985
-
986
- export const Route = createFileRoute("/api/docs")({
987
- server: {
988
- handlers: {
989
- GET: async ({ request }) => docsServer.GET({ request }),
990
- POST: async ({ request }) => docsServer.POST({ request }),
991
- },
992
- },
993
- });
994
- `;
995
- }
996
- function tanstackApiReferenceRouteTemplate(opts) {
997
- const routePath = `/${opts.apiReferencePath}${opts.catchAll ? "/$" : "/"}`;
998
- return `\
999
- import { createFileRoute } from "@tanstack/react-router";
1000
- import { createTanstackApiReference } from "@farming-labs/tanstack-start/api-reference";
1001
- import docsConfig from "${tanstackDocsConfigImport(opts.filePath)}";
1002
-
1003
- const handler = createTanstackApiReference(docsConfig);
1004
-
1005
- export const Route = createFileRoute("${routePath}")({
1006
- server: {
1007
- handlers: {
1008
- GET: handler,
1009
- },
1010
- },
1011
- });
1012
- `;
1013
- }
1014
- function tanstackRootRouteTemplate(globalCssRelPath) {
1015
- return `\
1016
- import appCss from "${relativeAssetPath("src/routes/__root.tsx", globalCssRelPath)}?url";
1017
- import { createRootRoute, HeadContent, Outlet, Scripts } from "@tanstack/react-router";
1018
- import { RootProvider } from "@farming-labs/theme/tanstack";
1019
-
1020
- export const Route = createRootRoute({
1021
- head: () => ({
1022
- links: [{ rel: "stylesheet", href: appCss }],
1023
- meta: [
1024
- { charSet: "utf-8" },
1025
- { name: "viewport", content: "width=device-width, initial-scale=1" },
1026
- { title: "Docs" },
1027
- ],
1028
- }),
1029
- component: RootComponent,
1030
- });
1031
-
1032
- function RootComponent() {
1033
- return (
1034
- <html lang="en" suppressHydrationWarning>
1035
- <head>
1036
- <HeadContent />
1037
- </head>
1038
- <body>
1039
- <RootProvider>
1040
- <Outlet />
1041
- </RootProvider>
1042
- <Scripts />
1043
- </body>
1044
- </html>
1045
- );
1046
- }
1047
- `;
1048
- }
1049
- function injectTanstackRootProviderIntoRoute(content) {
1050
- if (!content || content.includes("RootProvider")) return null;
1051
- let out = addImportLine(content, "import { RootProvider } from \"@farming-labs/theme/tanstack\";");
1052
- if (out.includes("<Outlet />")) out = out.replace("<Outlet />", "<RootProvider><Outlet /></RootProvider>");
1053
- else if (out.includes("<Outlet></Outlet>")) out = out.replace("<Outlet></Outlet>", "<RootProvider><Outlet /></RootProvider>");
1054
- else return null;
1055
- return out === content ? null : out;
1056
- }
1057
- function tanstackViteConfigTemplate(useAlias) {
1058
- return `\
1059
- import { defineConfig } from "vite";
1060
- import tailwindcss from "@tailwindcss/vite";
1061
- ${useAlias ? "import tsconfigPaths from \"vite-tsconfig-paths\";\n" : ""}import { tanstackStart } from "@tanstack/react-start/plugin/vite";
1062
- import { docsMdx } from "@farming-labs/tanstack-start/vite";
1063
-
1064
- export default defineConfig({
1065
- plugins: [tailwindcss(), docsMdx(), ${useAlias ? "tsconfigPaths({ ignoreConfigErrors: true }), " : ""}tanstackStart()],
1066
- });
1067
- `;
1068
- }
1069
- function injectTanstackVitePlugins(content, useAlias) {
1070
- if (!content) return null;
1071
- let out = content;
1072
- out = addImportLine(out, "import tailwindcss from \"@tailwindcss/vite\";");
1073
- if (useAlias) out = addImportLine(out, "import tsconfigPaths from \"vite-tsconfig-paths\";");
1074
- out = addImportLine(out, "import { docsMdx } from \"@farming-labs/tanstack-start/vite\";");
1075
- const additions = [];
1076
- if (!out.includes("tailwindcss()")) additions.push("tailwindcss()");
1077
- if (!out.includes("docsMdx()")) additions.push("docsMdx()");
1078
- if (useAlias && !out.includes("tsconfigPaths(")) additions.push("tsconfigPaths({ ignoreConfigErrors: true })");
1079
- if (additions.length === 0) return out === content ? null : out;
1080
- const pluginsMatch = out.match(/plugins\s*:\s*\[([\s\S]*?)\]/m);
1081
- if (pluginsMatch) {
1082
- const current = pluginsMatch[1].trim();
1083
- const existing = current ? `${current}${current.endsWith(",") ? "" : ","}` : "";
1084
- const replacement = `plugins: [\n ${existing}${existing ? "\n " : ""}${additions.join(",\n ")}\n ]`;
1085
- return out.replace(pluginsMatch[0], replacement);
1086
- }
1087
- const configMatch = out.match(/defineConfig\(\s*\{/);
1088
- if (configMatch) {
1089
- const insertion = `defineConfig({\n plugins: [${additions.join(", ")}],`;
1090
- return out.replace(configMatch[0], insertion);
1091
- }
1092
- return out === content ? null : out;
1093
- }
1094
- function tanstackWelcomePageTemplate(cfg) {
1095
- return `\
1096
- ---
1097
- title: "Documentation"
1098
- description: "Welcome to ${cfg.projectName} documentation"
1099
- ---
1100
-
1101
- # Welcome to ${cfg.projectName}
1102
-
1103
- This docs site is powered by \`@farming-labs/docs\` and TanStack Start.
1104
-
1105
- ## Overview
1106
-
1107
- - Content lives in \`${cfg.entry}/\`
1108
- - Routes live in \`src/routes/${cfg.entry}/\`
1109
- - Search is served from \`/api/docs\`
1110
-
1111
- ## Next Steps
1112
-
1113
- Read the [Installation](/${cfg.entry}/installation) guide, then continue to [Quickstart](/${cfg.entry}/quickstart).
1114
- `;
1115
- }
1116
- function tanstackInstallationPageTemplate(cfg) {
1117
- if (cfg.theme === "custom" && cfg.customThemeName) {
1118
- const baseName = cfg.customThemeName.replace(/\.(ts|css)$/i, "");
1119
- const exportName = getThemeExportName(baseName);
1120
- const cssImportPath = getCustomThemeCssImportPath("src/styles/app.css", baseName);
1121
- return `\
1122
- ---
1123
- title: "Installation"
1124
- description: "How to install and set up ${cfg.projectName}"
1125
- ---
1126
-
1127
- # Installation
1128
-
1129
- Add the docs packages to your TanStack Start app:
1130
-
1131
- \`\`\`bash
1132
- pnpm add @farming-labs/docs @farming-labs/theme @farming-labs/tanstack-start
1133
- \`\`\`
1134
-
1135
- The scaffold also configures MDX through \`docsMdx()\` in \`vite.config.ts\`.
1136
-
1137
- ## Theme CSS
1138
-
1139
- Keep your config theme and global CSS import aligned:
1140
-
1141
- \`\`\`ts title="docs.config.ts"
1142
- import { defineDocs } from "@farming-labs/docs";
1143
- import { ${exportName} } from "./themes/${baseName}";
1144
-
1145
- export default defineDocs({
1146
- entry: "${cfg.entry}",
1147
- contentDir: "${cfg.entry}",
1148
- theme: ${exportName}(),
1149
- });
1150
- \`\`\`
1151
-
1152
- \`\`\`css title="src/styles/app.css"
1153
- @import "tailwindcss";
1154
- @import "${cssImportPath}";
1155
- \`\`\`
1156
-
1157
- ## Generated Files
1158
-
1159
- \`\`\`
1160
- docs.config.ts
1161
- themes/${baseName}.ts
1162
- themes/${baseName}.css
1163
- ${cfg.entry}/
1164
- src/lib/docs.server.ts
1165
- src/lib/docs.functions.ts
1166
- src/routes/${cfg.entry}/index.tsx
1167
- src/routes/${cfg.entry}/$.tsx
1168
- src/routes/api/docs.ts
1169
- \`\`\`
1170
- `;
1171
- }
1172
- const t = getThemeInfo(cfg.theme);
1173
- return `\
1174
- ---
1175
- title: "Installation"
1176
- description: "How to install and set up ${cfg.projectName}"
1177
- ---
1178
-
1179
- # Installation
1180
-
1181
- Add the docs packages to your TanStack Start app:
1182
-
1183
- \`\`\`bash
1184
- pnpm add @farming-labs/docs @farming-labs/theme @farming-labs/tanstack-start
1185
- \`\`\`
1186
-
1187
- The scaffold also configures MDX through \`docsMdx()\` in \`vite.config.ts\`.
1188
-
1189
- ## Theme CSS
1190
-
1191
- Keep your config theme and global CSS import aligned:
1192
-
1193
- \`\`\`ts title="docs.config.ts"
1194
- import { defineDocs } from "@farming-labs/docs";
1195
- import { ${t.factory} } from "${t.nextImport}";
1196
-
1197
- export default defineDocs({
1198
- entry: "${cfg.entry}",
1199
- contentDir: "${cfg.entry}",
1200
- theme: ${t.factory}(),
1201
- });
1202
- \`\`\`
1203
-
1204
- \`\`\`css title="src/styles/app.css"
1205
- @import "tailwindcss";
1206
- @import "@farming-labs/theme/${t.nextCssImport}/css";
1207
- \`\`\`
1208
-
1209
- ## Generated Files
1210
-
1211
- \`\`\`
1212
- docs.config.ts
1213
- ${cfg.entry}/
1214
- src/lib/docs.server.ts
1215
- src/lib/docs.functions.ts
1216
- src/routes/${cfg.entry}/index.tsx
1217
- src/routes/${cfg.entry}/$.tsx
1218
- src/routes/api/docs.ts
1219
- \`\`\`
1220
- `;
1221
- }
1222
- function tanstackQuickstartPageTemplate(cfg) {
1223
- return `\
1224
- ---
1225
- title: "Quickstart"
1226
- description: "Get up and running in minutes"
1227
- ---
1228
-
1229
- # Quickstart
1230
-
1231
- Create a new page under \`${cfg.entry}/\`:
1232
-
1233
- \`\`\`bash
1234
- mkdir -p ${cfg.entry}/my-page
1235
- \`\`\`
1236
-
1237
- Then add \`${cfg.entry}/my-page/page.mdx\`:
1238
-
1239
- \`\`\`mdx
1240
- ---
1241
- title: "My Page"
1242
- description: "A custom documentation page"
1243
- ---
1244
-
1245
- # My Page
1246
-
1247
- Write your content here using **MDX**.
1248
- \`\`\`
1249
-
1250
- Visit [/${cfg.entry}/my-page](/${cfg.entry}/my-page) after starting the dev server.
1251
- `;
1252
- }
1253
- function svelteDocsConfigTemplate(cfg) {
1254
- if (cfg.theme === "custom" && cfg.customThemeName) {
1255
- const exportName = getThemeExportName(cfg.customThemeName);
1256
- return `\
1257
- import { defineDocs } from "@farming-labs/docs";
1258
- import { ${exportName} } from "${"../../themes/" + cfg.customThemeName.replace(/\.ts$/i, "")}";
1259
-
1260
- export default defineDocs({
1261
- entry: "${cfg.entry}",
1262
- contentDir: "${cfg.entry}",
1263
- ${renderI18nConfig(cfg)}${renderApiReferenceConfig(cfg)} theme: ${exportName}({
1264
- ui: {
1265
- colors: { primary: "#6366f1" },
1266
- },
1267
- }),
1268
-
1269
- nav: {
1270
- title: "${cfg.projectName}",
1271
- url: "/${cfg.entry}",
1272
- },
1273
-
1274
- breadcrumb: { enabled: true },
1275
-
1276
- metadata: {
1277
- titleTemplate: "%s – ${cfg.projectName}",
1278
- description: "Documentation for ${cfg.projectName}",
1279
- },
1280
- });
1281
- `;
1282
- }
1283
- const t = getThemeInfo(cfg.theme);
1284
- return `\
1285
- import { defineDocs } from "@farming-labs/docs";
1286
- import { ${t.factory} } from "${t.svelteImport}";
1287
-
1288
- export default defineDocs({
1289
- entry: "${cfg.entry}",
1290
- contentDir: "${cfg.entry}",
1291
- ${renderI18nConfig(cfg)}${renderApiReferenceConfig(cfg)} theme: ${t.factory}({
1292
- ui: {
1293
- colors: { primary: "#6366f1" },
1294
- },
1295
- }),
1296
-
1297
- nav: {
1298
- title: "${cfg.projectName}",
1299
- url: "/${cfg.entry}",
1300
- },
1301
-
1302
- breadcrumb: { enabled: true },
1303
-
1304
- metadata: {
1305
- titleTemplate: "%s – ${cfg.projectName}",
1306
- description: "Documentation for ${cfg.projectName}",
1307
- },
1308
- });
1309
- `;
1310
- }
1311
- function svelteDocsServerTemplate(cfg) {
1312
- return `\
1313
- import { createDocsServer } from "@farming-labs/svelte/server";
1314
- import config from "${svelteServerConfigImport(cfg.useAlias)}";
1315
-
1316
- // preload for production
1317
- const contentFiles = import.meta.glob("/${cfg.entry ?? "docs"}/**/*.{md,mdx,svx}", {
1318
- query: "?raw",
1319
- import: "default",
1320
- eager: true,
1321
- }) as Record<string, string>;
1322
-
1323
- export const { load, GET, POST } = createDocsServer({
1324
- ...config,
1325
- _preloadedContent: contentFiles,
1326
- });
1327
- `;
1328
- }
1329
- function svelteDocsLayoutTemplate(cfg) {
1330
- return `\
1331
- <script>
1332
- import { DocsLayout } from "@farming-labs/svelte-theme";
1333
- import config from "${svelteLayoutConfigImport(cfg.useAlias)}";
1334
-
1335
- let { data, children } = $props();
1336
- <\/script>
1337
-
1338
- <DocsLayout tree={data.tree} {config}>
1339
- {@render children()}
1340
- </DocsLayout>
1341
- `;
1342
- }
1343
- function svelteDocsLayoutServerTemplate(cfg) {
1344
- return `\
1345
- export { load } from "${svelteLayoutServerImport(cfg.useAlias)}";
1346
- `;
1347
- }
1348
- function svelteDocsPageTemplate(cfg) {
1349
- return `\
1350
- <script>
1351
- import { DocsContent } from "@farming-labs/svelte-theme";
1352
- import config from "${sveltePageConfigImport(cfg.useAlias)}";
1353
-
1354
- let { data } = $props();
1355
- <\/script>
1356
-
1357
- <DocsContent {data} {config} />
1358
- `;
1359
- }
1360
- function svelteApiReferenceRouteTemplate(filePath, useAlias) {
1361
- return `\
1362
- import { createSvelteApiReference } from "@farming-labs/svelte/api-reference";
1363
- import config from "${useAlias ? "$lib/docs.config" : relativeImport(filePath, "src/lib/docs.config.ts")}";
1364
-
1365
- export const GET = createSvelteApiReference(config);
1366
- `;
1367
- }
1368
- function svelteRootLayoutTemplate(globalCssRelPath) {
1369
- let cssImport;
1370
- if (globalCssRelPath.startsWith("src/")) cssImport = "./" + globalCssRelPath.slice(4);
1371
- else cssImport = "../" + globalCssRelPath;
1372
- return `\
1373
- <script>
1374
- import "${cssImport}";
1375
-
1376
- let { children } = $props();
1377
- <\/script>
1378
-
1379
- {@render children()}
1380
- `;
1381
- }
1382
- function svelteGlobalCssTemplate(theme, customThemeName, globalCssRelPath) {
1383
- if (theme === "custom" && customThemeName && globalCssRelPath) return `\
1384
- @import "${getCustomThemeCssImportPath(globalCssRelPath, customThemeName.replace(/\.css$/i, ""))}";
1385
- `;
1386
- return `\
1387
- @import "@farming-labs/svelte-theme/${theme}/css";
1388
- `;
1389
- }
1390
- function svelteCssImportLine(theme, customThemeName, globalCssRelPath) {
1391
- if (theme === "custom" && customThemeName && globalCssRelPath) return `@import "${getCustomThemeCssImportPath(globalCssRelPath, customThemeName.replace(/\.css$/i, ""))}";`;
1392
- return `@import "@farming-labs/svelte-theme/${theme}/css";`;
1393
- }
1394
- function injectSvelteCssImport(existingContent, theme, customThemeName, globalCssRelPath) {
1395
- const importLine = svelteCssImportLine(theme, customThemeName, globalCssRelPath);
1396
- if (existingContent.includes(importLine)) return null;
1397
- if (theme !== "custom" && existingContent.includes("@farming-labs/svelte-theme/") && existingContent.includes("/css")) return null;
1398
- if (theme === "custom" && existingContent.includes("themes/") && existingContent.includes(".css")) return null;
1399
- const lines = existingContent.split("\n");
1400
- const lastImportIdx = lines.reduce((acc, l, i) => l.trimStart().startsWith("@import") ? i : acc, -1);
1401
- if (lastImportIdx >= 0) lines.splice(lastImportIdx + 1, 0, importLine);
1402
- else lines.unshift(importLine);
1403
- return lines.join("\n");
1404
- }
1405
- function svelteWelcomePageTemplate(cfg) {
1406
- return `\
1407
- ---
1408
- title: "Documentation"
1409
- description: "Welcome to ${cfg.projectName} documentation"
1410
- ---
1411
-
1412
- # Welcome to ${cfg.projectName}
1413
-
1414
- Get started with our documentation. Browse the pages on the left to learn more.
1415
-
1416
- ## Overview
1417
-
1418
- This documentation was generated by \`@farming-labs/docs\`. Edit the markdown files in \`${cfg.entry}/\` to customize.
1419
-
1420
- ## Features
1421
-
1422
- - **Markdown Support** — Write docs with standard Markdown
1423
- - **Syntax Highlighting** — Code blocks with automatic highlighting
1424
- - **Dark Mode** — Built-in theme switching
1425
- - **Search** — Full-text search across all pages
1426
- - **Responsive** — Works on any screen size
1427
-
1428
- ---
1429
-
1430
- ## Next Steps
1431
-
1432
- Start by reading the [Installation](/${cfg.entry}/installation) guide, then follow the [Quickstart](/${cfg.entry}/quickstart) to build something.
1433
- `;
1434
- }
1435
- function svelteInstallationPageTemplate(cfg) {
1436
- const t = getThemeInfo(cfg.theme);
1437
- return `\
1438
- ---
1439
- title: "Installation"
1440
- description: "How to install and set up ${cfg.projectName}"
1441
- ---
1442
-
1443
- # Installation
1444
-
1445
- Follow these steps to install and configure ${cfg.projectName}.
1446
-
1447
- ## Prerequisites
1448
-
1449
- - Node.js 18+
1450
- - A package manager (pnpm, npm, or yarn)
1451
-
1452
- ## Install Dependencies
1453
-
1454
- \`\`\`bash
1455
- pnpm add @farming-labs/docs @farming-labs/svelte @farming-labs/svelte-theme
1456
- \`\`\`
1457
-
1458
- ## Configuration
1459
-
1460
- Your project includes a \`docs.config.ts\` in \`src/lib/\`:
1461
-
1462
- \`\`\`ts title="src/lib/docs.config.ts"
1463
- import { defineDocs } from "@farming-labs/docs";
1464
- import { ${t.factory} } from "${t.svelteImport}";
1465
-
1466
- export default defineDocs({
1467
- entry: "${cfg.entry}",
1468
- contentDir: "${cfg.entry}",
1469
- theme: ${t.factory}({
1470
- ui: { colors: { primary: "#6366f1" } },
1471
- }),
1472
- });
1473
- \`\`\`
1474
-
1475
- ## Project Structure
1476
-
1477
- \`\`\`
1478
- ${cfg.entry}/ # Markdown content
1479
- page.md # /${cfg.entry}
1480
- installation/
1481
- page.md # /${cfg.entry}/installation
1482
- quickstart/
1483
- page.md # /${cfg.entry}/quickstart
1484
- src/
1485
- lib/
1486
- docs.config.ts # Docs configuration
1487
- docs.server.ts # Server-side docs loader
1488
- routes/
1489
- ${cfg.entry}/
1490
- +layout.svelte # Docs layout
1491
- +layout.server.js # Layout data loader
1492
- [...slug]/
1493
- +page.svelte # Dynamic doc page
1494
- \`\`\`
1495
-
1496
- ## What's Next?
1497
-
1498
- Head to the [Quickstart](/${cfg.entry}/quickstart) guide to start writing your first page.
1499
- `;
1500
- }
1501
- function svelteQuickstartPageTemplate(cfg) {
1502
- const t = getThemeInfo(cfg.theme);
1503
- return `\
1504
- ---
1505
- title: "Quickstart"
1506
- description: "Get up and running in minutes"
1507
- ---
1508
-
1509
- # Quickstart
1510
-
1511
- This guide walks you through creating your first documentation page.
1512
-
1513
- ## Creating a Page
1514
-
1515
- Create a new folder under \`${cfg.entry}/\` with a \`page.md\` file:
1516
-
1517
- \`\`\`bash
1518
- mkdir -p ${cfg.entry}/my-page
1519
- \`\`\`
1520
-
1521
- Then create \`${cfg.entry}/my-page/page.md\`:
1522
-
1523
- \`\`\`md
1524
- ---
1525
- title: "My Page"
1526
- description: "A custom documentation page"
1527
- ---
1528
-
1529
- # My Page
1530
-
1531
- Write your content here using **Markdown**.
1532
- \`\`\`
1533
-
1534
- Your page is now available at \`/${cfg.entry}/my-page\`.
1535
-
1536
- ## Code Blocks
1537
-
1538
- Code blocks are automatically syntax-highlighted:
1539
-
1540
- \`\`\`typescript
1541
- function greet(name: string): string {
1542
- return \\\`Hello, \\\${name}!\\\`;
1543
- }
1544
-
1545
- console.log(greet("World"));
1546
- \`\`\`
1547
-
1548
- ## Customizing the Theme
1549
-
1550
- Edit \`src/lib/docs.config.ts\` to change colors, typography, and component defaults:
1551
-
1552
- \`\`\`ts title="src/lib/docs.config.ts"
1553
- theme: ${t.factory}({
1554
- ui: {
1555
- colors: { primary: "#22c55e" },
1556
- },
1557
- }),
1558
- \`\`\`
1559
-
1560
- ## Deploying
1561
-
1562
- Build your docs for production:
1563
-
1564
- \`\`\`bash
1565
- pnpm build
1566
- \`\`\`
1567
-
1568
- Deploy to Vercel, Netlify, or any Node.js hosting platform.
1569
- `;
1570
- }
1571
- function astroDocsConfigTemplate(cfg) {
1572
- if (cfg.theme === "custom" && cfg.customThemeName) {
1573
- const exportName = getThemeExportName(cfg.customThemeName);
1574
- return `\
1575
- import { defineDocs } from "@farming-labs/docs";
1576
- import { ${exportName} } from "${"../../themes/" + cfg.customThemeName.replace(/\.ts$/i, "")}";
1577
-
1578
- export default defineDocs({
1579
- entry: "${cfg.entry}",
1580
- contentDir: "${cfg.entry}",
1581
- ${renderI18nConfig(cfg)}${renderApiReferenceConfig(cfg)} theme: ${exportName}({
1582
- ui: {
1583
- colors: { primary: "#6366f1" },
1584
- },
1585
- }),
1586
-
1587
- nav: {
1588
- title: "${cfg.projectName}",
1589
- url: "/${cfg.entry}",
1590
- },
1591
-
1592
- breadcrumb: { enabled: true },
1593
-
1594
- metadata: {
1595
- titleTemplate: "%s – ${cfg.projectName}",
1596
- description: "Documentation for ${cfg.projectName}",
1597
- },
1598
- });
1599
- `;
1600
- }
1601
- const t = getThemeInfo(cfg.theme);
1602
- return `\
1603
- import { defineDocs } from "@farming-labs/docs";
1604
- import { ${t.factory} } from "${t.astroImport}";
1605
-
1606
- export default defineDocs({
1607
- entry: "${cfg.entry}",
1608
- contentDir: "${cfg.entry}",
1609
- ${renderI18nConfig(cfg)}${renderApiReferenceConfig(cfg)} theme: ${t.factory}({
1610
- ui: {
1611
- colors: { primary: "#6366f1" },
1612
- },
1613
- }),
1614
-
1615
- nav: {
1616
- title: "${cfg.projectName}",
1617
- url: "/${cfg.entry}",
1618
- },
1619
-
1620
- breadcrumb: { enabled: true },
1621
-
1622
- metadata: {
1623
- titleTemplate: "%s – ${cfg.projectName}",
1624
- description: "Documentation for ${cfg.projectName}",
1625
- },
1626
- });
1627
- `;
1628
- }
1629
- function astroDocsServerTemplate(cfg) {
1630
- return `\
1631
- import { createDocsServer } from "@farming-labs/astro/server";
1632
- import config from "${astroServerConfigImport(cfg.useAlias)}";
1633
-
1634
- const contentFiles = import.meta.glob("/${cfg.entry ?? "docs"}/**/*.{md,mdx}", {
1635
- query: "?raw",
1636
- import: "default",
1637
- eager: true,
1638
- }) as Record<string, string>;
1639
-
1640
- export const { load, GET, POST } = createDocsServer({
1641
- ...config,
1642
- _preloadedContent: contentFiles,
1643
- });
1644
- `;
1645
- }
1646
- const ASTRO_ADAPTER_INFO = {
1647
- vercel: {
1648
- pkg: "@astrojs/vercel",
1649
- import: "@astrojs/vercel"
1650
- },
1651
- netlify: {
1652
- pkg: "@astrojs/netlify",
1653
- import: "@astrojs/netlify"
1654
- },
1655
- node: {
1656
- pkg: "@astrojs/node",
1657
- import: "@astrojs/node"
1658
- },
1659
- cloudflare: {
1660
- pkg: "@astrojs/cloudflare",
1661
- import: "@astrojs/cloudflare"
1662
- }
1663
- };
1664
- function getAstroAdapterPkg(adapter) {
1665
- return ASTRO_ADAPTER_INFO[adapter]?.pkg ?? ASTRO_ADAPTER_INFO.vercel.pkg;
1666
- }
1667
- function astroConfigTemplate(adapter = "vercel") {
1668
- const info = ASTRO_ADAPTER_INFO[adapter] ?? ASTRO_ADAPTER_INFO.vercel;
1669
- const adapterCall = adapter === "node" ? `${adapter}({ mode: "standalone" })` : `${adapter}()`;
1670
- return `\
1671
- import { defineConfig } from "astro/config";
1672
- import ${adapter} from "${info.import}";
1673
-
1674
- export default defineConfig({
1675
- output: "server",
1676
- adapter: ${adapterCall},
1677
- });
1678
- `;
1679
- }
1680
- function astroDocsPageTemplate(cfg) {
1681
- return `\
1682
- ---
1683
- import DocsLayout from "@farming-labs/astro-theme/src/components/DocsLayout.astro";
1684
- import DocsContent from "@farming-labs/astro-theme/src/components/DocsContent.astro";
1685
- import SearchDialog from "@farming-labs/astro-theme/src/components/SearchDialog.astro";
1686
- import config from "${astroPageConfigImport(cfg.useAlias, 2)}";
1687
- import { load } from "${astroPageServerImport(cfg.useAlias, 2)}";
1688
- import "${`@farming-labs/astro-theme/${getThemeInfo(cfg.theme).astroCssTheme}/css`}";
1689
-
1690
- const data = await load(Astro.url.pathname);
1691
- ---
1692
-
1693
- <html lang="en">
1694
- <head>
1695
- <meta charset="utf-8" />
1696
- <meta name="viewport" content="width=device-width, initial-scale=1" />
1697
- <title>{data.title} – Docs</title>
1698
- </head>
1699
- <body>
1700
- <DocsLayout tree={data.tree} config={config}>
1701
- <DocsContent data={data} config={config} />
1702
- </DocsLayout>
1703
- <SearchDialog config={config} />
1704
- </body>
1705
- </html>
1706
- `;
1707
- }
1708
- function astroDocsIndexTemplate(cfg) {
1709
- return `\
1710
- ---
1711
- import DocsLayout from "@farming-labs/astro-theme/src/components/DocsLayout.astro";
1712
- import DocsContent from "@farming-labs/astro-theme/src/components/DocsContent.astro";
1713
- import SearchDialog from "@farming-labs/astro-theme/src/components/SearchDialog.astro";
1714
- import config from "${astroPageConfigImport(cfg.useAlias, 2)}";
1715
- import { load } from "${astroPageServerImport(cfg.useAlias, 2)}";
1716
- import "${`@farming-labs/astro-theme/${getThemeInfo(cfg.theme).astroCssTheme}/css`}";
1717
-
1718
- const data = await load(Astro.url.pathname);
1719
- ---
1720
-
1721
- <html lang="en">
1722
- <head>
1723
- <meta charset="utf-8" />
1724
- <meta name="viewport" content="width=device-width, initial-scale=1" />
1725
- <title>{data.title} – Docs</title>
1726
- </head>
1727
- <body>
1728
- <DocsLayout tree={data.tree} config={config}>
1729
- <DocsContent data={data} config={config} />
1730
- </DocsLayout>
1731
- <SearchDialog config={config} />
1732
- </body>
1733
- </html>
1734
- `;
1735
- }
1736
- function astroApiRouteTemplate(cfg) {
1737
- return `\
1738
- import type { APIRoute } from "astro";
1739
- import { GET as docsGET, POST as docsPOST } from "${astroPageServerImport(cfg.useAlias, 2)}";
1740
-
1741
- export const GET: APIRoute = async ({ request }) => {
1742
- return docsGET({ request });
1743
- };
1744
-
1745
- export const POST: APIRoute = async ({ request }) => {
1746
- return docsPOST({ request });
1747
- };
1748
- `;
1749
- }
1750
- function astroApiReferenceRouteTemplate(filePath) {
1751
- return `\
1752
- import { createAstroApiReference } from "@farming-labs/astro/api-reference";
1753
- import config from "${relativeImport(filePath, "src/lib/docs.config.ts")}";
1754
-
1755
- export const GET = createAstroApiReference(config);
1756
- `;
1757
- }
1758
- function astroGlobalCssTemplate(theme, customThemeName, globalCssRelPath) {
1759
- if (theme === "custom" && customThemeName && globalCssRelPath) return `\
1760
- @import "${getCustomThemeCssImportPath(globalCssRelPath, customThemeName.replace(/\.css$/i, ""))}";
1761
- `;
1762
- return `\
1763
- @import "@farming-labs/astro-theme/${theme}/css";
1764
- `;
1765
- }
1766
- function astroCssImportLine(theme, customThemeName, globalCssRelPath) {
1767
- if (theme === "custom" && customThemeName && globalCssRelPath) return `@import "${getCustomThemeCssImportPath(globalCssRelPath, customThemeName.replace(/\.css$/i, ""))}";`;
1768
- return `@import "@farming-labs/astro-theme/${theme}/css";`;
1769
- }
1770
- function injectAstroCssImport(existingContent, theme, customThemeName, globalCssRelPath) {
1771
- const importLine = astroCssImportLine(theme, customThemeName, globalCssRelPath);
1772
- if (existingContent.includes(importLine)) return null;
1773
- if (theme !== "custom" && existingContent.includes("@farming-labs/astro-theme/") && existingContent.includes("/css")) return null;
1774
- if (theme === "custom" && existingContent.includes("themes/") && existingContent.includes(".css")) return null;
1775
- const lines = existingContent.split("\n");
1776
- const lastImportIdx = lines.reduce((acc, l, i) => l.trimStart().startsWith("@import") ? i : acc, -1);
1777
- if (lastImportIdx >= 0) lines.splice(lastImportIdx + 1, 0, importLine);
1778
- else lines.unshift(importLine);
1779
- return lines.join("\n");
1780
- }
1781
- function astroWelcomePageTemplate(cfg) {
1782
- return `\
1783
- ---
1784
- title: "Documentation"
1785
- description: "Welcome to ${cfg.projectName} documentation"
1786
- ---
1787
-
1788
- # Welcome to ${cfg.projectName}
1789
-
1790
- Get started with our documentation. Browse the pages on the left to learn more.
1791
-
1792
- ## Overview
1793
-
1794
- This documentation was generated by \`@farming-labs/docs\`. Edit the markdown files in \`${cfg.entry}/\` to customize.
1795
-
1796
- ## Features
1797
-
1798
- - **Markdown Support** — Write docs with standard Markdown
1799
- - **Syntax Highlighting** — Code blocks with automatic highlighting
1800
- - **Dark Mode** — Built-in theme switching
1801
- - **Search** — Full-text search across all pages
1802
- - **Responsive** — Works on any screen size
1803
-
1804
- ---
1805
-
1806
- ## Next Steps
1807
-
1808
- Start by reading the [Installation](/${cfg.entry}/installation) guide, then follow the [Quickstart](/${cfg.entry}/quickstart) to build something.
1809
- `;
1810
- }
1811
- function astroInstallationPageTemplate(cfg) {
1812
- const t = getThemeInfo(cfg.theme);
1813
- return `\
1814
- ---
1815
- title: "Installation"
1816
- description: "How to install and set up ${cfg.projectName}"
1817
- ---
1818
-
1819
- # Installation
1820
-
1821
- Follow these steps to install and configure ${cfg.projectName}.
1822
-
1823
- ## Prerequisites
1824
-
1825
- - Node.js 18+
1826
- - A package manager (pnpm, npm, or yarn)
1827
-
1828
- ## Install Dependencies
1829
-
1830
- \\\`\\\`\\\`bash
1831
- pnpm add @farming-labs/docs @farming-labs/astro @farming-labs/astro-theme
1832
- \\\`\\\`\\\`
1833
-
1834
- ## Configuration
1835
-
1836
- Your project includes a \\\`docs.config.ts\\\` in \\\`src/lib/\\\`:
1837
-
1838
- \\\`\\\`\\\`ts title="src/lib/docs.config.ts"
1839
- import { defineDocs } from "@farming-labs/docs";
1840
- import { ${t.factory} } from "${t.astroImport}";
1841
-
1842
- export default defineDocs({
1843
- entry: "${cfg.entry}",
1844
- contentDir: "${cfg.entry}",
1845
- theme: ${t.factory}({
1846
- ui: { colors: { primary: "#6366f1" } },
1847
- }),
1848
- });
1849
- \\\`\\\`\\\`
1850
-
1851
- ## Project Structure
1852
-
1853
- \\\`\\\`\\\`
1854
- ${cfg.entry}/ # Markdown content
1855
- page.md # /${cfg.entry}
1856
- installation/
1857
- page.md # /${cfg.entry}/installation
1858
- quickstart/
1859
- page.md # /${cfg.entry}/quickstart
1860
- src/
1861
- lib/
1862
- docs.config.ts # Docs configuration
1863
- docs.server.ts # Server-side docs loader
1864
- pages/
1865
- ${cfg.entry}/
1866
- index.astro # Docs index page
1867
- [...slug].astro # Dynamic doc page
1868
- api/
1869
- ${cfg.entry}.ts # Search/AI API route
1870
- \\\`\\\`\\\`
1871
-
1872
- ## What's Next?
1873
-
1874
- Head to the [Quickstart](/${cfg.entry}/quickstart) guide to start writing your first page.
1875
- `;
1876
- }
1877
- function astroQuickstartPageTemplate(cfg) {
1878
- const t = getThemeInfo(cfg.theme);
1879
- return `\
1880
- ---
1881
- title: "Quickstart"
1882
- description: "Get up and running in minutes"
1883
- ---
1884
-
1885
- # Quickstart
1886
-
1887
- This guide walks you through creating your first documentation page.
1888
-
1889
- ## Creating a Page
1890
-
1891
- Create a new folder under \\\`${cfg.entry}/\\\` with a \\\`page.md\\\` file:
1892
-
1893
- \\\`\\\`\\\`bash
1894
- mkdir -p ${cfg.entry}/my-page
1895
- \\\`\\\`\\\`
1896
-
1897
- Then create \\\`${cfg.entry}/my-page/page.md\\\`:
1898
-
1899
- \\\`\\\`\\\`md
1900
- ---
1901
- title: "My Page"
1902
- description: "A custom documentation page"
1903
- ---
1904
-
1905
- # My Page
1906
-
1907
- Write your content here using **Markdown**.
1908
- \\\`\\\`\\\`
1909
-
1910
- Your page is now available at \\\`/${cfg.entry}/my-page\\\`.
1911
-
1912
- ## Customizing the Theme
1913
-
1914
- Edit \\\`src/lib/docs.config.ts\\\` to change colors, typography, and component defaults:
1915
-
1916
- \\\`\\\`\\\`ts title="src/lib/docs.config.ts"
1917
- theme: ${t.factory}({
1918
- ui: {
1919
- colors: { primary: "#22c55e" },
1920
- },
1921
- }),
1922
- \\\`\\\`\\\`
1923
-
1924
- ## Deploying
1925
-
1926
- Build your docs for production:
1927
-
1928
- \\\`\\\`\\\`bash
1929
- pnpm build
1930
- \\\`\\\`\\\`
1931
-
1932
- Deploy to Vercel, Netlify, or any Node.js hosting platform.
1933
- `;
1934
- }
1935
- function nuxtDocsConfigTemplate(cfg) {
1936
- if (cfg.theme === "custom" && cfg.customThemeName) {
1937
- const exportName = getThemeExportName(cfg.customThemeName);
1938
- return `\
1939
- import { defineDocs } from "@farming-labs/docs";
1940
- import { ${exportName} } from "${cfg.useAlias ? "~/themes/" + cfg.customThemeName.replace(/\.ts$/i, "") : "./themes/" + cfg.customThemeName.replace(/\.ts$/i, "")}";
1941
-
1942
- export default defineDocs({
1943
- entry: "${cfg.entry}",
1944
- contentDir: "${cfg.entry}",
1945
- ${renderI18nConfig(cfg)}${renderApiReferenceConfig(cfg)} theme: ${exportName}({
1946
- ui: {
1947
- colors: { primary: "#6366f1" },
1948
- },
1949
- }),
1950
-
1951
- nav: {
1952
- title: "${cfg.projectName}",
1953
- url: "/${cfg.entry}",
1954
- },
1955
-
1956
- breadcrumb: { enabled: true },
1957
-
1958
- metadata: {
1959
- titleTemplate: "%s – ${cfg.projectName}",
1960
- description: "Documentation for ${cfg.projectName}",
1961
- },
1962
- });
1963
- `;
1964
- }
1965
- const t = getThemeInfo(cfg.theme);
1966
- return `\
1967
- import { defineDocs } from "@farming-labs/docs";
1968
- import { ${t.factory} } from "${t.nuxtImport}";
1969
-
1970
- export default defineDocs({
1971
- entry: "${cfg.entry}",
1972
- contentDir: "${cfg.entry}",
1973
- ${renderI18nConfig(cfg)}${renderApiReferenceConfig(cfg)} theme: ${t.factory}({
1974
- ui: {
1975
- colors: { primary: "#6366f1" },
1976
- },
1977
- }),
1978
-
1979
- nav: {
1980
- title: "${cfg.projectName}",
1981
- url: "/${cfg.entry}",
1982
- },
1983
-
1984
- breadcrumb: { enabled: true },
1985
-
1986
- metadata: {
1987
- titleTemplate: "%s – ${cfg.projectName}",
1988
- description: "Documentation for ${cfg.projectName}",
1989
- },
1990
- });
1991
- `;
1992
- }
1993
- function nuxtDocsServerTemplate(cfg) {
1994
- const contentDirName = cfg.entry ?? "docs";
1995
- return `\
1996
- import { createDocsServer } from "@farming-labs/nuxt/server";
1997
- import config from "${cfg.useAlias ? "~/docs.config" : "../../docs.config"}";
1998
-
1999
- const contentFiles = import.meta.glob("/${contentDirName}/**/*.{md,mdx}", {
2000
- query: "?raw",
2001
- import: "default",
2002
- eager: true,
2003
- }) as Record<string, string>;
2004
-
2005
- export const docsServer = createDocsServer({
2006
- ...config,
2007
- _preloadedContent: contentFiles,
2008
- });
2009
- `;
2010
- }
2011
- function nuxtServerApiDocsGetTemplate() {
2012
- return `\
2013
- import { getRequestURL } from "h3";
2014
- import { docsServer } from "../utils/docs-server";
2015
-
2016
- export default defineEventHandler((event) => {
2017
- const url = getRequestURL(event);
2018
- const request = new Request(url.href, {
2019
- method: event.method,
2020
- headers: event.headers,
2021
- });
2022
- return docsServer.GET({ request });
2023
- });
2024
- `;
2025
- }
2026
- function nuxtServerApiDocsPostTemplate() {
2027
- return `\
2028
- import { getRequestURL, readRawBody } from "h3";
2029
- import { docsServer } from "../utils/docs-server";
2030
-
2031
- export default defineEventHandler(async (event) => {
2032
- const url = getRequestURL(event);
2033
- const body = await readRawBody(event);
2034
- const request = new Request(url.href, {
2035
- method: "POST",
2036
- headers: event.headers,
2037
- body: body ?? undefined,
2038
- });
2039
- return docsServer.POST({ request });
2040
- });
2041
- `;
2042
- }
2043
- function nuxtServerApiDocsLoadTemplate() {
2044
- return `\
2045
- import { getQuery } from "h3";
2046
- import { docsServer } from "../../utils/docs-server";
2047
-
2048
- export default defineEventHandler(async (event) => {
2049
- const query = getQuery(event);
2050
- const pathname = (query.pathname as string) ?? "/docs";
2051
- return docsServer.load(pathname);
2052
- });
2053
- `;
2054
- }
2055
- function nuxtServerApiReferenceRouteTemplate(filePath, useAlias) {
2056
- return `\
2057
- import { defineApiReferenceHandler } from "@farming-labs/nuxt/api-reference";
2058
- import config from "${useAlias ? "~/docs.config" : relativeImport(filePath, "docs.config.ts")}";
2059
-
2060
- export default defineApiReferenceHandler(config);
2061
- `;
2062
- }
2063
- function nuxtDocsPageTemplate(cfg) {
2064
- return `\
2065
- <script setup lang="ts">
2066
- import { DocsLayout, DocsContent } from "@farming-labs/nuxt-theme";
2067
- import config from "${cfg.useAlias ? "~/docs.config" : "../../docs.config"}";
2068
-
2069
- const route = useRoute();
2070
- const pathname = computed(() => route.path);
2071
-
2072
- const { data, error } = await useAsyncData(\`docs-\${pathname.value}\`, () =>
2073
- $fetch("/api/docs/load", {
2074
- query: { pathname: pathname.value },
2075
- })
2076
- );
2077
-
2078
- if (error.value) {
2079
- throw createError({
2080
- statusCode: 404,
2081
- statusMessage: "Page not found",
2082
- });
2083
- }
2084
- <\/script>
2085
-
2086
- <template>
2087
- <div v-if="data" class="fd-docs-wrapper">
2088
- <DocsLayout :tree="data.tree" :config="config">
2089
- <DocsContent :data="data" :config="config" />
2090
- </DocsLayout>
2091
- </div>
2092
- </template>
2093
- `;
2094
- }
2095
- function nuxtConfigTemplate(cfg) {
2096
- return `\
2097
- export default defineNuxtConfig({
2098
- compatibilityDate: "2024-11-01",
2099
-
2100
- css: ["@farming-labs/nuxt-theme/${getThemeInfo(cfg.theme).nuxtCssTheme}/css"],
2101
-
2102
- vite: {
2103
- optimizeDeps: {
2104
- include: ["@farming-labs/docs", "@farming-labs/nuxt", "@farming-labs/nuxt-theme"],
2105
- },
2106
- },
2107
-
2108
- nitro: {
2109
- moduleSideEffects: ["@farming-labs/nuxt/server"],
2110
- },
2111
- });
2112
- `;
2113
- }
2114
- function nuxtWelcomePageTemplate(cfg) {
2115
- return `\
2116
- ---
2117
- order: 1
2118
- title: Documentation
2119
- description: Welcome to ${cfg.projectName} documentation
2120
- icon: book
2121
- ---
2122
-
2123
- # Welcome to ${cfg.projectName}
2124
-
2125
- Get started with our documentation. Browse the pages on the left to learn more.
2126
-
2127
- ## Overview
2128
-
2129
- This documentation was generated by \`@farming-labs/docs\`. Edit the markdown files in \`${cfg.entry}/\` to customize.
2130
-
2131
- ## Features
2132
-
2133
- - **Markdown Support** — Write docs with standard Markdown
2134
- - **Syntax Highlighting** — Code blocks with automatic highlighting
2135
- - **Dark Mode** — Built-in theme switching
2136
- - **Search** — Full-text search across all pages (⌘ K)
2137
- - **Responsive** — Works on any screen size
2138
-
2139
- ---
2140
-
2141
- ## Next Steps
2142
-
2143
- Start by reading the [Installation](/${cfg.entry}/installation) guide, then follow the [Quickstart](/${cfg.entry}/quickstart) to build something.
2144
- `;
2145
- }
2146
- function nuxtInstallationPageTemplate(cfg) {
2147
- const t = getThemeInfo(cfg.theme);
2148
- return `\
2149
- ---
2150
- order: 3
2151
- title: Installation
2152
- description: How to install and set up ${cfg.projectName}
2153
- icon: terminal
2154
- ---
2155
-
2156
- # Installation
2157
-
2158
- Follow these steps to install and configure ${cfg.projectName}.
2159
-
2160
- ## Prerequisites
2161
-
2162
- - Node.js 18+
2163
- - A package manager (pnpm, npm, or yarn)
2164
-
2165
- ## Install Dependencies
2166
-
2167
- \`\`\`bash
2168
- pnpm add @farming-labs/docs @farming-labs/nuxt @farming-labs/nuxt-theme
2169
- \`\`\`
2170
-
2171
- ## Configuration
2172
-
2173
- Your project includes a \`docs.config.ts\` at the root:
2174
-
2175
- \`\`\`ts title="docs.config.ts"
2176
- import { defineDocs } from "@farming-labs/docs";
2177
- import { ${t.factory} } from "${t.nuxtImport}";
2178
-
2179
- export default defineDocs({
2180
- entry: "${cfg.entry}",
2181
- contentDir: "${cfg.entry}",
2182
- theme: ${t.factory}({
2183
- ui: { colors: { primary: "#6366f1" } },
2184
- }),
2185
- });
2186
- \`\`\`
2187
-
2188
- ## Project Structure
2189
-
2190
- \`\`\`
2191
- ${cfg.entry}/ # Markdown content
2192
- page.md
2193
- installation/page.md
2194
- quickstart/page.md
2195
- server/
2196
- utils/docs-server.ts # createDocsServer + preloaded content
2197
- api/docs/
2198
- load.get.ts # Page data API
2199
- docs.get.ts # Search API
2200
- docs.post.ts # AI chat API
2201
- pages/
2202
- ${cfg.entry}/[[...slug]].vue # Docs catch-all page
2203
- docs.config.ts
2204
- nuxt.config.ts
2205
- \`\`\`
2206
-
2207
- ## What's Next?
2208
-
2209
- Head to the [Quickstart](/${cfg.entry}/quickstart) guide to start writing your first page.
2210
- `;
2211
- }
2212
- function nuxtQuickstartPageTemplate(cfg) {
2213
- const t = getThemeInfo(cfg.theme);
2214
- return `\
2215
- ---
2216
- order: 2
2217
- title: Quickstart
2218
- description: Get up and running in minutes
2219
- icon: rocket
2220
- ---
2221
-
2222
- # Quickstart
2223
-
2224
- This guide walks you through creating your first documentation page.
2225
-
2226
- ## Creating a Page
2227
-
2228
- Create a new folder under \`${cfg.entry}/\` with a \`page.md\` file:
2229
-
2230
- \`\`\`bash
2231
- mkdir -p ${cfg.entry}/my-page
2232
- \`\`\`
2233
-
2234
- Then create \`${cfg.entry}/my-page/page.md\`:
2235
-
2236
- \`\`\`md
2237
- ---
2238
- title: "My Page"
2239
- description: "A custom documentation page"
2240
- ---
2241
-
2242
- # My Page
2243
-
2244
- Write your content here using **Markdown**.
2245
- \`\`\`
2246
-
2247
- Your page is now available at \`/${cfg.entry}/my-page\`.
2248
-
2249
- ## Customizing the Theme
2250
-
2251
- Edit \`docs.config.ts\` to change colors and typography:
2252
-
2253
- \`\`\`ts
2254
- theme: ${t.factory}({
2255
- ui: {
2256
- colors: { primary: "#22c55e" },
2257
- },
2258
- }),
2259
- \`\`\`
2260
-
2261
- ## Deploying
2262
-
2263
- Build your docs for production:
2264
-
2265
- \`\`\`bash
2266
- pnpm build
2267
- \`\`\`
2268
-
2269
- Deploy to Vercel, Netlify, or any Node.js hosting platform.
2270
- `;
2271
- }
2272
- function nuxtGlobalCssTemplate(theme, customThemeName, globalCssRelPath) {
2273
- if (theme === "custom" && customThemeName && globalCssRelPath) return `\
2274
- @import "${getCustomThemeCssImportPath(globalCssRelPath, customThemeName.replace(/\.css$/i, ""))}";
2275
- `;
2276
- return `\
2277
- @import "@farming-labs/nuxt-theme/${theme}/css";
2278
- `;
2279
- }
2280
- function nuxtCssImportLine(theme, customThemeName, globalCssRelPath) {
2281
- if (theme === "custom" && customThemeName && globalCssRelPath) return `@import "${getCustomThemeCssImportPath(globalCssRelPath, customThemeName.replace(/\.css$/i, ""))}";`;
2282
- return `@import "@farming-labs/nuxt-theme/${theme}/css";`;
2283
- }
2284
- function injectNuxtCssImport(existingContent, theme, customThemeName, globalCssRelPath) {
2285
- const importLine = nuxtCssImportLine(theme, customThemeName, globalCssRelPath);
2286
- if (existingContent.includes(importLine)) return null;
2287
- if (theme !== "custom" && existingContent.includes("@farming-labs/nuxt-theme/") && existingContent.includes("/css")) return null;
2288
- if (theme === "custom" && existingContent.includes("themes/") && existingContent.includes(".css")) return null;
2289
- const lines = existingContent.split("\n");
2290
- const lastImportIdx = lines.reduce((acc, l, i) => l.trimStart().startsWith("@import") ? i : acc, -1);
2291
- if (lastImportIdx >= 0) lines.splice(lastImportIdx + 1, 0, importLine);
2292
- else lines.unshift(importLine);
2293
- return lines.join("\n");
2294
- }
2295
-
2296
- //#endregion
2297
- //#region src/cli/init.ts
2298
- const EXAMPLES_REPO = "farming-labs/docs";
2299
- const VALID_TEMPLATES = [
2300
- "next",
2301
- "nuxt",
2302
- "sveltekit",
2303
- "astro",
2304
- "tanstack-start"
2305
- ];
2306
- const COMMON_LOCALE_OPTIONS = [
2307
- {
2308
- value: "en",
2309
- label: "English",
2310
- hint: "en"
2311
- },
2312
- {
2313
- value: "fr",
2314
- label: "French",
2315
- hint: "fr"
2316
- },
2317
- {
2318
- value: "es",
2319
- label: "Spanish",
2320
- hint: "es"
2321
- },
2322
- {
2323
- value: "de",
2324
- label: "German",
2325
- hint: "de"
2326
- },
2327
- {
2328
- value: "pt",
2329
- label: "Portuguese",
2330
- hint: "pt"
2331
- },
2332
- {
2333
- value: "it",
2334
- label: "Italian",
2335
- hint: "it"
2336
- },
2337
- {
2338
- value: "ja",
2339
- label: "Japanese",
2340
- hint: "ja"
2341
- },
2342
- {
2343
- value: "ko",
2344
- label: "Korean",
2345
- hint: "ko"
2346
- },
2347
- {
2348
- value: "zh",
2349
- label: "Chinese",
2350
- hint: "zh"
2351
- },
2352
- {
2353
- value: "ar",
2354
- label: "Arabic",
2355
- hint: "ar"
2356
- },
2357
- {
2358
- value: "hi",
2359
- label: "Hindi",
2360
- hint: "hi"
2361
- },
2362
- {
2363
- value: "ru",
2364
- label: "Russian",
2365
- hint: "ru"
2366
- }
2367
- ];
2368
- function normalizeLocaleCode(value) {
2369
- const trimmed = value.trim();
2370
- if (!trimmed) return "";
2371
- const [language, ...rest] = trimmed.split("-");
2372
- const normalizedLanguage = language.toLowerCase();
2373
- if (rest.length === 0) return normalizedLanguage;
2374
- return `${normalizedLanguage}-${rest.join("-").toUpperCase()}`;
2375
- }
2376
- function parseLocaleInput(input) {
2377
- return Array.from(new Set(input.split(",").map((value) => normalizeLocaleCode(value)).filter(Boolean)));
2378
- }
2379
- function normalizeEntryPath(entry) {
2380
- return entry.replace(/^\/+|\/+$/g, "");
2381
- }
2382
- function getTanstackDocsRouteDir(entry) {
2383
- return path.posix.join("src/routes", normalizeEntryPath(entry));
2384
- }
2385
- function normalizeApiRouteRoot(routeRoot) {
2386
- return routeRoot.replace(/^\/+|\/+$/g, "");
2387
- }
2388
- function detectApiRouteRoot(cwd, framework, nextAppDir = "app") {
2389
- const defaultRoot = "api";
2390
- const detectFromRecursiveRouteFiles = (baseDir, matcher) => {
2391
- if (!fs.existsSync(baseDir)) return null;
2392
- const candidates = /* @__PURE__ */ new Map();
2393
- const walk = (dir, prefix = "") => {
2394
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
2395
- const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;
2396
- const fullPath = path.join(dir, entry.name);
2397
- if (entry.isDirectory()) {
2398
- walk(fullPath, relativePath);
2399
- continue;
2400
- }
2401
- if (!matcher(entry, relativePath)) continue;
2402
- const [topLevel] = relativePath.split("/");
2403
- if (!topLevel) continue;
2404
- candidates.set(topLevel, (candidates.get(topLevel) ?? 0) + 1);
2405
- }
2406
- };
2407
- walk(baseDir);
2408
- return Array.from(candidates.entries()).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
2409
- };
2410
- if (framework === "nextjs") {
2411
- const appRoot = path.join(cwd, nextAppDir);
2412
- if (fs.existsSync(path.join(appRoot, defaultRoot))) return defaultRoot;
2413
- return detectFromRecursiveRouteFiles(appRoot, (_entry, relativePath) => /\/?route\.(?:[cm]?[jt]sx?)$/i.test(relativePath)) ?? defaultRoot;
2414
- }
2415
- if (framework === "tanstack-start") {
2416
- const routesRoot = path.join(cwd, "src/routes");
2417
- if (fs.existsSync(path.join(routesRoot, defaultRoot))) return defaultRoot;
2418
- return detectFromRecursiveRouteFiles(routesRoot, (_entry, relativePath) => /(?:^|\/)[^/]+\.(?:[cm]?[jt]sx?)$/i.test(relativePath)) ?? defaultRoot;
2419
- }
2420
- if (framework === "sveltekit") {
2421
- const routesRoot = path.join(cwd, "src/routes");
2422
- if (fs.existsSync(path.join(routesRoot, defaultRoot))) return defaultRoot;
2423
- return detectFromRecursiveRouteFiles(routesRoot, (_entry, relativePath) => /\/?\+server\.(?:[cm]?[jt]s)$/i.test(relativePath)) ?? defaultRoot;
2424
- }
2425
- if (framework === "astro") {
2426
- const pagesRoot = path.join(cwd, "src/pages");
2427
- if (fs.existsSync(path.join(pagesRoot, defaultRoot))) return defaultRoot;
2428
- return detectFromRecursiveRouteFiles(pagesRoot, (entry, relativePath) => /\.(?:[cm]?[jt]s)$/i.test(relativePath) && !relativePath.endsWith(".d.ts") && entry.isFile()) ?? defaultRoot;
2429
- }
2430
- const serverRoot = path.join(cwd, "server");
2431
- if (fs.existsSync(path.join(serverRoot, defaultRoot))) return defaultRoot;
2432
- return detectFromRecursiveRouteFiles(serverRoot, (entry, relativePath) => /\.(?:[cm]?[jt]s)$/i.test(relativePath) && !relativePath.endsWith(".d.ts") && entry.isFile()) ?? defaultRoot;
2433
- }
2434
- async function init(options = {}) {
2435
- const cwd = process.cwd();
2436
- p.intro(pc.bgCyan(pc.black(" @farming-labs/docs ")));
2437
- let projectType = "existing";
2438
- if (!options.template) {
2439
- const projectTypeAnswer = await p.select({
2440
- message: "Are you adding docs to an existing project or starting fresh?",
2441
- options: [{
2442
- value: "existing",
2443
- label: "Existing project",
2444
- hint: "Add docs to the current app in this directory"
2445
- }, {
2446
- value: "fresh",
2447
- label: "Fresh project",
2448
- hint: "Bootstrap a new app from a template (Next, Nuxt, SvelteKit, Astro, TanStack Start)"
2449
- }]
2450
- });
2451
- if (p.isCancel(projectTypeAnswer)) {
2452
- p.outro(pc.red("Init cancelled."));
2453
- process.exit(0);
2454
- }
2455
- projectType = projectTypeAnswer;
2456
- }
2457
- if (projectType === "fresh" || options.template) {
2458
- let template;
2459
- if (options.template) {
2460
- template = options.template.toLowerCase();
2461
- if (!VALID_TEMPLATES.includes(template)) {
2462
- p.log.error(`Invalid ${pc.cyan("--template")}. Use one of: ${VALID_TEMPLATES.map((t) => pc.cyan(t)).join(", ")}`);
2463
- process.exit(1);
2464
- }
2465
- } else {
2466
- const templateAnswer = await p.select({
2467
- message: "Which framework would you like to use?",
2468
- options: [
2469
- {
2470
- value: "next",
2471
- label: "Next.js",
2472
- hint: "React with App Router"
2473
- },
2474
- {
2475
- value: "nuxt",
2476
- label: "Nuxt",
2477
- hint: "Vue 3 with file-based routing"
2478
- },
2479
- {
2480
- value: "sveltekit",
2481
- label: "SvelteKit",
2482
- hint: "Svelte with file-based routing"
2483
- },
2484
- {
2485
- value: "astro",
2486
- label: "Astro",
2487
- hint: "Content-focused with islands"
2488
- },
2489
- {
2490
- value: "tanstack-start",
2491
- label: "TanStack Start",
2492
- hint: "React with TanStack Router and server functions"
2493
- }
2494
- ]
2495
- });
2496
- if (p.isCancel(templateAnswer)) {
2497
- p.outro(pc.red("Init cancelled."));
2498
- process.exit(0);
2499
- }
2500
- template = templateAnswer;
2501
- }
2502
- const defaultProjectName = "my-docs";
2503
- let projectName = options.name?.trim();
2504
- if (!projectName) {
2505
- const nameAnswer = await p.text({
2506
- message: "Project name? (we'll create this folder and bootstrap the app here)",
2507
- placeholder: defaultProjectName,
2508
- defaultValue: defaultProjectName,
2509
- validate: (value) => {
2510
- const v = (value ?? "").trim();
2511
- if (v.includes("/") || v.includes("\\")) return "Project name cannot contain path separators";
2512
- if (v.includes(" ")) return "Project name cannot contain spaces";
2513
- }
2514
- });
2515
- if (p.isCancel(nameAnswer)) {
2516
- p.outro(pc.red("Init cancelled."));
2517
- process.exit(0);
2518
- }
2519
- projectName = nameAnswer.trim() || defaultProjectName;
2520
- }
2521
- const templateLabel = template === "next" ? "Next.js" : template === "nuxt" ? "Nuxt" : template === "sveltekit" ? "SvelteKit" : template === "astro" ? "Astro" : "TanStack Start";
2522
- const targetDir = path.join(cwd, projectName);
2523
- const fs = await import("node:fs");
2524
- if (fs.existsSync(targetDir)) {
2525
- p.log.error(`Directory ${pc.cyan(projectName)} already exists. Choose a different ${pc.cyan("--name")} or remove it.`);
2526
- process.exit(1);
2527
- }
2528
- fs.mkdirSync(targetDir, { recursive: true });
2529
- p.log.step(`Bootstrapping project with ${pc.cyan(`'${projectName}'`)} (${templateLabel})...`);
2530
- try {
2531
- exec(`npx degit ${EXAMPLES_REPO}/examples/${template} . --force`, targetDir);
2532
- } catch {
2533
- p.log.error("Failed to bootstrap. Check your connection and that the repo exists.");
2534
- process.exit(1);
2535
- }
2536
- const pmAnswer = await p.select({
2537
- message: "Which package manager do you want to use in this new project?",
2538
- options: [
2539
- {
2540
- value: "pnpm",
2541
- label: "pnpm",
2542
- hint: "Fast, disk-efficient (recommended)"
2543
- },
2544
- {
2545
- value: "npm",
2546
- label: "npm",
2547
- hint: "Default Node.js package manager"
2548
- },
2549
- {
2550
- value: "yarn",
2551
- label: "yarn",
2552
- hint: "Classic yarn (script: yarn dev)"
2553
- },
2554
- {
2555
- value: "bun",
2556
- label: "bun",
2557
- hint: "Bun runtime + bun install/dev"
2558
- }
2559
- ]
2560
- });
2561
- if (p.isCancel(pmAnswer)) {
2562
- p.outro(pc.red("Init cancelled."));
2563
- process.exit(0);
2564
- }
2565
- const pmFresh = pmAnswer;
2566
- p.log.success(`Bootstrapped ${pc.cyan(`'${projectName}'`)}. Installing dependencies with ${pc.cyan(pmFresh)}...`);
2567
- const installCmd = pmFresh === "yarn" ? "yarn install" : pmFresh === "npm" ? "npm install" : pmFresh === "bun" ? "bun install" : "pnpm install";
2568
- try {
2569
- exec(installCmd, targetDir);
2570
- } catch {
2571
- p.log.warn(`${pmFresh} install failed. Run ${pc.cyan(installCmd)} manually inside the project.`);
2572
- }
2573
- const devCmd = pmFresh === "yarn" ? "yarn dev" : pmFresh === "npm" ? "npm run dev" : pmFresh === "bun" ? "bun dev" : "pnpm dev";
2574
- p.outro(pc.green(`Done! Run ${pc.cyan(`cd ${projectName} && ${devCmd}`)} to start the dev server and navigate to the /docs.`));
2575
- p.outro(pc.green("Happy documenting!"));
2576
- process.exit(0);
2577
- }
2578
- let framework = detectFramework(cwd);
2579
- if (framework) {
2580
- const frameworkName = framework === "nextjs" ? "Next.js" : framework === "tanstack-start" ? "TanStack Start" : framework === "sveltekit" ? "SvelteKit" : framework === "astro" ? "Astro" : "Nuxt";
2581
- p.log.success(`Detected framework: ${pc.cyan(frameworkName)}`);
2582
- } else {
2583
- p.log.warn("Could not auto-detect a framework from " + pc.cyan("package.json") + ".");
2584
- const picked = await p.select({
2585
- message: "Which framework are you using?",
2586
- options: [
2587
- {
2588
- value: "nextjs",
2589
- label: "Next.js",
2590
- hint: "React framework with App Router"
2591
- },
2592
- {
2593
- value: "tanstack-start",
2594
- label: "TanStack Start",
2595
- hint: "React with TanStack Router and server functions"
2596
- },
2597
- {
2598
- value: "sveltekit",
2599
- label: "SvelteKit",
2600
- hint: "Svelte framework with file-based routing"
2601
- },
2602
- {
2603
- value: "astro",
2604
- label: "Astro",
2605
- hint: "Content-focused framework with island architecture"
2606
- },
2607
- {
2608
- value: "nuxt",
2609
- label: "Nuxt",
2610
- hint: "Vue 3 framework with file-based routing and Nitro server"
2611
- }
2612
- ]
2613
- });
2614
- if (p.isCancel(picked)) {
2615
- p.outro(pc.red("Init cancelled."));
2616
- process.exit(0);
2617
- }
2618
- framework = picked;
2619
- }
2620
- let nextAppDir = "app";
2621
- if (framework === "nextjs") {
2622
- const detected = detectNextAppDir(cwd);
2623
- if (detected) {
2624
- nextAppDir = detected;
2625
- p.log.info(`Using App Router at ${pc.cyan(nextAppDir)} (detected ${detected === "src/app" ? "src directory" : "root app"})`);
2626
- } else {
2627
- const useSrcApp = await p.confirm({
2628
- message: "Do you use the src directory for the App Router? (e.g. src/app instead of app)",
2629
- initialValue: false
2630
- });
2631
- if (p.isCancel(useSrcApp)) {
2632
- p.outro(pc.red("Init cancelled."));
2633
- process.exit(0);
2634
- }
2635
- nextAppDir = useSrcApp ? "src/app" : "app";
2636
- }
2637
- }
2638
- const themeOptions = [
2639
- {
2640
- value: "fumadocs",
2641
- label: "Fumadocs (Default)",
2642
- hint: "Clean, modern docs theme with sidebar, search, and dark mode"
2643
- },
2644
- {
2645
- value: "darksharp",
2646
- label: "Darksharp",
2647
- hint: "All-black, sharp edges, zero-radius look"
2648
- },
2649
- {
2650
- value: "pixel-border",
2651
- label: "Pixel Border",
2652
- hint: "Rounded borders, pixel-perfect spacing, refined sidebar"
2653
- },
2654
- {
2655
- value: "colorful",
2656
- label: "Colorful",
2657
- hint: "Fumadocs-style neutral theme with description support"
2658
- },
2659
- {
2660
- value: "darkbold",
2661
- label: "DarkBold",
2662
- hint: "Pure monochrome, Geist typography, clean minimalism"
2663
- },
2664
- {
2665
- value: "shiny",
2666
- label: "Shiny",
2667
- hint: "Glossy, modern look with subtle shimmer effects"
2668
- },
2669
- {
2670
- value: "greentree",
2671
- label: "GreenTree",
2672
- hint: "Emerald green accent, Inter font, Mintlify-inspired"
2673
- },
2674
- {
2675
- value: "concrete",
2676
- label: "Concrete",
2677
- hint: "Brutalist poster-style theme with offset shadows and loud contrast"
2678
- },
2679
- {
2680
- value: "hardline",
2681
- label: "Hardline",
2682
- hint: "Hard-edge theme with square corners and bold borders"
2683
- },
2684
- {
2685
- value: "custom",
2686
- label: "Create your own theme",
2687
- hint: "Scaffold a new theme file + CSS in themes/ (name asked next)"
2688
- }
2689
- ];
2690
- const themeValues = new Set(themeOptions.map((option) => option.value));
2691
- let theme;
2692
- if (options.theme) {
2693
- if (!themeValues.has(options.theme)) {
2694
- p.log.error(`Invalid ${pc.cyan("--theme")}. Use one of: ${themeOptions.map((option) => pc.cyan(option.value)).join(", ")}`);
2695
- process.exit(1);
2696
- }
2697
- theme = options.theme;
2698
- } else {
2699
- const themeAnswer = await p.select({
2700
- message: "Which theme would you like to use?",
2701
- options: themeOptions
2702
- });
2703
- if (p.isCancel(themeAnswer)) {
2704
- p.outro(pc.red("Init cancelled."));
2705
- process.exit(0);
2706
- }
2707
- theme = themeAnswer;
2708
- }
2709
- const defaultThemeName = "my-theme";
2710
- let customThemeName;
2711
- if (theme === "custom") {
2712
- const nameAnswer = await p.text({
2713
- message: "Theme name? (we'll create themes/<name>.ts and themes/<name>.css)",
2714
- placeholder: defaultThemeName,
2715
- defaultValue: defaultThemeName,
2716
- validate: (value) => {
2717
- const v = (value ?? "").trim().replace(/\.(ts|css)$/i, "");
2718
- if (v.includes("/") || v.includes("\\")) return "Theme name cannot contain path separators";
2719
- if (v.includes(" ")) return "Theme name cannot contain spaces";
2720
- if (v && !/^[a-z0-9_-]+$/i.test(v)) return "Use only letters, numbers, hyphens, and underscores";
2721
- }
2722
- });
2723
- if (p.isCancel(nameAnswer)) {
2724
- p.outro(pc.red("Init cancelled."));
2725
- process.exit(0);
2726
- }
2727
- customThemeName = nameAnswer.trim().replace(/\.(ts|css)$/i, "") || defaultThemeName;
2728
- }
2729
- const aliasHint = framework === "nextjs" ? `Uses ${pc.cyan("@/")} prefix (requires tsconfig paths)` : framework === "tanstack-start" ? `Uses ${pc.cyan("@/")} prefix (requires tsconfig paths)` : framework === "sveltekit" ? `Uses ${pc.cyan("$lib/")} prefix (SvelteKit built-in)` : framework === "nuxt" ? `Uses ${pc.cyan("~/")} prefix (Nuxt built-in)` : `Uses ${pc.cyan("@/")} prefix (requires tsconfig paths)`;
2730
- const useAlias = await p.confirm({
2731
- message: `Use path aliases for imports? ${pc.dim(aliasHint)}`,
2732
- initialValue: false
2733
- });
2734
- if (p.isCancel(useAlias)) {
2735
- p.outro(pc.red("Init cancelled."));
2736
- process.exit(0);
2737
- }
2738
- let astroAdapter;
2739
- if (framework === "astro") {
2740
- const adapter = await p.select({
2741
- message: "Where will you deploy?",
2742
- options: [
2743
- {
2744
- value: "vercel",
2745
- label: "Vercel",
2746
- hint: "Recommended for most projects"
2747
- },
2748
- {
2749
- value: "netlify",
2750
- label: "Netlify"
2751
- },
2752
- {
2753
- value: "cloudflare",
2754
- label: "Cloudflare Pages"
2755
- },
2756
- {
2757
- value: "node",
2758
- label: "Node.js / Docker",
2759
- hint: "Self-hosted standalone server"
2760
- }
2761
- ]
2762
- });
2763
- if (p.isCancel(adapter)) {
2764
- p.outro(pc.red("Init cancelled."));
2765
- process.exit(0);
2766
- }
2767
- astroAdapter = adapter;
2768
- }
2769
- const defaultEntry = "docs";
2770
- let entryPath;
2771
- if (options.entry) {
2772
- const normalizedEntry = options.entry.trim();
2773
- if (normalizedEntry.startsWith("/")) {
2774
- p.log.error("Use a relative path for --entry (no leading /)");
2775
- process.exit(1);
2776
- }
2777
- if (normalizedEntry.includes(" ")) {
2778
- p.log.error("Path passed to --entry cannot contain spaces");
2779
- process.exit(1);
2780
- }
2781
- entryPath = normalizedEntry || defaultEntry;
2782
- } else {
2783
- const entry = await p.text({
2784
- message: "Where should your docs live?",
2785
- placeholder: defaultEntry,
2786
- defaultValue: defaultEntry,
2787
- validate: (value) => {
2788
- const v = (value ?? "").trim();
2789
- if (v.startsWith("/")) return "Use a relative path (no leading /)";
2790
- if (v.includes(" ")) return "Path cannot contain spaces";
2791
- }
2792
- });
2793
- if (p.isCancel(entry)) {
2794
- p.outro(pc.red("Init cancelled."));
2795
- process.exit(0);
2796
- }
2797
- entryPath = entry.trim() || defaultEntry;
2798
- }
2799
- const defaultApiRouteRoot = normalizeApiRouteRoot(options.apiRouteRoot?.trim() || detectApiRouteRoot(cwd, framework, nextAppDir));
2800
- let apiReferenceConfig;
2801
- let enableApiReference;
2802
- if (typeof options.apiReference === "boolean") enableApiReference = options.apiReference;
2803
- else if (typeof options.apiRouteRoot === "string" && options.apiRouteRoot.trim()) enableApiReference = true;
2804
- else {
2805
- const apiReferenceAnswer = await p.confirm({
2806
- message: "Do you want to scaffold API reference support?",
2807
- initialValue: false
2808
- });
2809
- if (p.isCancel(apiReferenceAnswer)) {
2810
- p.outro(pc.red("Init cancelled."));
2811
- process.exit(0);
2812
- }
2813
- enableApiReference = apiReferenceAnswer;
2814
- }
2815
- if (enableApiReference) {
2816
- let routeRoot = options.apiRouteRoot?.trim();
2817
- if (!routeRoot) {
2818
- const routeRootAnswer = await p.text({
2819
- message: "API route root to scan?",
2820
- placeholder: defaultApiRouteRoot,
2821
- defaultValue: defaultApiRouteRoot,
2822
- validate: (value) => {
2823
- const normalizedValue = normalizeApiRouteRoot((value ?? "").trim());
2824
- if (!normalizedValue) return "Route root cannot be empty";
2825
- if (normalizedValue.includes(" ")) return "Route root cannot contain spaces";
2826
- }
2827
- });
2828
- if (p.isCancel(routeRootAnswer)) {
2829
- p.outro(pc.red("Init cancelled."));
2830
- process.exit(0);
2831
- }
2832
- routeRoot = routeRootAnswer.trim() || defaultApiRouteRoot;
2833
- }
2834
- const normalizedRouteRoot = normalizeApiRouteRoot(routeRoot);
2835
- if (!normalizedRouteRoot) {
2836
- p.log.error("Route root cannot be empty");
2837
- process.exit(1);
2838
- }
2839
- if (normalizedRouteRoot.includes(" ")) {
2840
- p.log.error("Route root cannot contain spaces");
2841
- process.exit(1);
2842
- }
2843
- apiReferenceConfig = {
2844
- path: "api-reference",
2845
- routeRoot: normalizedRouteRoot
2846
- };
2847
- }
2848
- let docsI18n;
2849
- if (framework === "tanstack-start") p.log.info("Skipping i18n scaffold for TanStack Start. Configure localized routes manually if needed.");
2850
- else {
2851
- const enableI18n = await p.confirm({
2852
- message: "Do you want to scaffold internationalized docs ?",
2853
- initialValue: false
2854
- });
2855
- if (p.isCancel(enableI18n)) {
2856
- p.outro(pc.red("Init cancelled."));
2857
- process.exit(0);
2858
- }
2859
- if (!enableI18n) docsI18n = void 0;
2860
- else {
2861
- const selectedLocales = await p.multiselect({
2862
- message: "Which languages should we scaffold?",
2863
- options: COMMON_LOCALE_OPTIONS.map((option) => ({
2864
- value: option.value,
2865
- label: option.label,
2866
- hint: option.hint
2867
- }))
2868
- });
2869
- if (p.isCancel(selectedLocales)) {
2870
- p.outro(pc.red("Init cancelled."));
2871
- process.exit(0);
2872
- }
2873
- const extraLocalesAnswer = await p.text({
2874
- message: "Any additional locale codes? (comma-separated, optional)",
2875
- placeholder: "nl, sv, pt-BR",
2876
- defaultValue: "",
2877
- validate: (value) => {
2878
- return parseLocaleInput(value ?? "").every((locale) => /^[a-z]{2,3}(?:-[A-Z]{2})?$/.test(locale)) ? void 0 : "Use locale codes like en, fr, zh, or pt-BR";
2879
- }
2880
- });
2881
- if (p.isCancel(extraLocalesAnswer)) {
2882
- p.outro(pc.red("Init cancelled."));
2883
- process.exit(0);
2884
- }
2885
- const locales = Array.from(new Set([...(selectedLocales ?? []).map((locale) => normalizeLocaleCode(locale)), ...parseLocaleInput(extraLocalesAnswer ?? "")])).filter(Boolean);
2886
- if (locales.length === 0) {
2887
- p.log.error("Pick at least one locale to scaffold i18n support.");
2888
- p.outro(pc.red("Init cancelled."));
2889
- process.exit(1);
2890
- }
2891
- const defaultLocaleAnswer = await p.select({
2892
- message: "Which locale should be the default?",
2893
- options: locales.map((locale) => ({
2894
- value: locale,
2895
- label: locale,
2896
- hint: locale === "en" ? "Recommended default" : void 0
2897
- })),
2898
- initialValue: locales[0]
2899
- });
2900
- if (p.isCancel(defaultLocaleAnswer)) {
2901
- p.outro(pc.red("Init cancelled."));
2902
- process.exit(0);
2903
- }
2904
- docsI18n = {
2905
- locales,
2906
- defaultLocale: defaultLocaleAnswer
2907
- };
2908
- }
2909
- }
2910
- const detectedCssFiles = detectGlobalCssFiles(cwd);
2911
- let globalCssRelPath;
2912
- const defaultCssPath = framework === "tanstack-start" ? "src/styles/app.css" : framework === "sveltekit" ? "src/app.css" : framework === "astro" ? "src/styles/global.css" : framework === "nuxt" ? "assets/css/main.css" : framework === "nextjs" ? `${nextAppDir}/globals.css` : "app/globals.css";
2913
- if (detectedCssFiles.length === 1) {
2914
- globalCssRelPath = detectedCssFiles[0];
2915
- p.log.info(`Found global CSS at ${pc.cyan(globalCssRelPath)}`);
2916
- } else if (detectedCssFiles.length > 1) {
2917
- const picked = await p.select({
2918
- message: "Multiple global CSS files found. Which one should we use?",
2919
- options: detectedCssFiles.map((f) => ({
2920
- value: f,
2921
- label: f
2922
- }))
2923
- });
2924
- if (p.isCancel(picked)) {
2925
- p.outro(pc.red("Init cancelled."));
2926
- process.exit(0);
2927
- }
2928
- globalCssRelPath = picked;
2929
- } else {
2930
- const cssPathAnswer = await p.text({
2931
- message: "Where is your global CSS file?",
2932
- placeholder: defaultCssPath,
2933
- defaultValue: defaultCssPath,
2934
- validate: (value) => {
2935
- const v = (value ?? "").trim();
2936
- if (v && !v.endsWith(".css")) return "Path must end with .css";
2937
- }
2938
- });
2939
- if (p.isCancel(cssPathAnswer)) {
2940
- p.outro(pc.red("Init cancelled."));
2941
- process.exit(0);
2942
- }
2943
- globalCssRelPath = cssPathAnswer.trim() || defaultCssPath;
2944
- }
2945
- const pkgJsonContent = readFileSafe(path.join(cwd, "package.json"));
2946
- const pkgJson = pkgJsonContent ? JSON.parse(pkgJsonContent) : { name: "my-project" };
2947
- const projectName = pkgJson.name || "My Project";
2948
- const cfg = {
2949
- entry: entryPath,
2950
- theme,
2951
- customThemeName,
2952
- projectName,
2953
- framework,
2954
- useAlias,
2955
- astroAdapter,
2956
- i18n: docsI18n,
2957
- apiReference: apiReferenceConfig,
2958
- ...framework === "nextjs" && { nextAppDir }
2959
- };
2960
- const s = p.spinner();
2961
- s.start("Scaffolding docs files");
2962
- const written = [];
2963
- const skipped = [];
2964
- function write(rel, content, overwrite = false) {
2965
- if (writeFileSafe(path.join(cwd, rel), content, overwrite)) written.push(rel);
2966
- else skipped.push(rel);
2967
- }
2968
- if (framework === "tanstack-start") scaffoldTanstackStart(cwd, cfg, globalCssRelPath, write, skipped, written);
2969
- else if (framework === "sveltekit") scaffoldSvelteKit(cwd, cfg, globalCssRelPath, write, skipped, written);
2970
- else if (framework === "astro") scaffoldAstro(cwd, cfg, globalCssRelPath, write, skipped, written);
2971
- else if (framework === "nuxt") scaffoldNuxt(cwd, cfg, globalCssRelPath, write, skipped, written);
2972
- else scaffoldNextJs(cwd, cfg, globalCssRelPath, write, skipped, written);
2973
- s.stop("Files scaffolded");
2974
- if (written.length > 0) p.log.success(`Created ${written.length} file${written.length > 1 ? "s" : ""}:\n` + written.map((f) => ` ${pc.green("+")} ${f}`).join("\n"));
2975
- if (skipped.length > 0) p.log.info(`Skipped ${skipped.length} existing file${skipped.length > 1 ? "s" : ""}:\n` + skipped.map((f) => ` ${pc.dim("-")} ${f}`).join("\n"));
2976
- let pm = detectPackageManagerFromLockfile(cwd);
2977
- if (pm) p.log.info(`Detected ${pc.cyan(pm)}`);
2978
- const pmAnswerExisting = await p.select({
2979
- ...pm ? { initialValue: pm } : {},
2980
- message: "Which package manager do you want to use in this project?",
2981
- options: [
2982
- {
2983
- value: "pnpm",
2984
- label: "pnpm",
2985
- hint: "Fast, disk-efficient (recommended)"
2986
- },
2987
- {
2988
- value: "npm",
2989
- label: "npm",
2990
- hint: "Default Node.js package manager"
2991
- },
2992
- {
2993
- value: "yarn",
2994
- label: "yarn",
2995
- hint: "Classic yarn (script: yarn dev)"
2996
- },
2997
- {
2998
- value: "bun",
2999
- label: "bun",
3000
- hint: "Bun runtime + bun install/dev"
3001
- }
3002
- ]
3003
- });
3004
- if (p.isCancel(pmAnswerExisting)) {
3005
- p.outro(pc.red("Init cancelled."));
3006
- process.exit(0);
3007
- }
3008
- pm = pmAnswerExisting;
3009
- p.log.info(`Using ${pc.cyan(pm)} as package manager`);
3010
- const s2 = p.spinner();
3011
- s2.start("Installing dependencies");
3012
- try {
3013
- if (framework === "tanstack-start") {
3014
- exec(`${installCommand(pm)} @farming-labs/docs @farming-labs/theme @farming-labs/tanstack-start`, cwd);
3015
- const devDeps = ["@tailwindcss/vite", "tailwindcss"];
3016
- if (useAlias) devDeps.push("vite-tsconfig-paths");
3017
- const allDeps = {
3018
- ...pkgJson.dependencies,
3019
- ...pkgJson.devDependencies
3020
- };
3021
- const missingDevDeps = devDeps.filter((d) => !allDeps[d]);
3022
- if (missingDevDeps.length > 0) exec(`${devInstallCommand(pm)} ${missingDevDeps.join(" ")}`, cwd);
3023
- } else if (framework === "sveltekit") exec(`${installCommand(pm)} @farming-labs/docs @farming-labs/svelte @farming-labs/svelte-theme`, cwd);
3024
- else if (framework === "astro") {
3025
- const adapterPkg = getAstroAdapterPkg(cfg.astroAdapter ?? "vercel");
3026
- exec(`${installCommand(pm)} @farming-labs/docs @farming-labs/astro @farming-labs/astro-theme ${adapterPkg}`, cwd);
3027
- } else if (framework === "nuxt") exec(`${installCommand(pm)} @farming-labs/docs @farming-labs/nuxt @farming-labs/nuxt-theme`, cwd);
3028
- else {
3029
- exec(`${installCommand(pm)} @farming-labs/docs @farming-labs/next @farming-labs/theme`, cwd);
3030
- const devDeps = [
3031
- "@tailwindcss/postcss",
3032
- "postcss",
3033
- "tailwindcss",
3034
- "@types/mdx",
3035
- "@types/node"
3036
- ];
3037
- const allDeps = {
3038
- ...pkgJson.dependencies,
3039
- ...pkgJson.devDependencies
3040
- };
3041
- const missingDevDeps = devDeps.filter((d) => !allDeps[d]);
3042
- if (missingDevDeps.length > 0) exec(`${devInstallCommand(pm)} ${missingDevDeps.join(" ")}`, cwd);
3043
- }
3044
- } catch {
3045
- s2.stop("Failed to install dependencies");
3046
- p.log.error(`Dependency installation failed. Run the install command manually:
3047
- ${pc.cyan(`${installCommand(pm)} @farming-labs/docs`)}`);
3048
- p.outro(pc.yellow("Setup partially complete. Install deps and run dev server manually."));
3049
- process.exit(1);
3050
- }
3051
- s2.stop("Dependencies installed");
3052
- const startDev = await p.confirm({
3053
- message: "Start the dev server now?",
3054
- initialValue: true
3055
- });
3056
- if (p.isCancel(startDev) || !startDev) {
3057
- p.log.info(`You can start the dev server later with:
3058
- ${pc.cyan(`${pm === "yarn" ? "yarn" : pm + " run"} dev`)}`);
3059
- p.outro(pc.green("Done! Happy documenting."));
3060
- process.exit(0);
3061
- }
3062
- p.log.step("Starting dev server...");
3063
- const devCommand = framework === "tanstack-start" ? {
3064
- cmd: "npx",
3065
- args: ["vite", "dev"],
3066
- waitFor: "ready"
3067
- } : framework === "sveltekit" ? {
3068
- cmd: "npx",
3069
- args: ["vite", "dev"],
3070
- waitFor: "ready"
3071
- } : framework === "astro" ? {
3072
- cmd: "npx",
3073
- args: ["astro", "dev"],
3074
- waitFor: "ready"
3075
- } : framework === "nuxt" ? {
3076
- cmd: "npx",
3077
- args: ["nuxt", "dev"],
3078
- waitFor: "Local"
3079
- } : {
3080
- cmd: "npx",
3081
- args: [
3082
- "next",
3083
- "dev",
3084
- "--webpack"
3085
- ],
3086
- waitFor: "Ready"
3087
- };
3088
- const defaultPort = framework === "tanstack-start" ? "5173" : framework === "sveltekit" ? "5173" : framework === "astro" ? "4321" : framework === "nuxt" ? "3000" : "3000";
3089
- try {
3090
- const child = await spawnAndWaitFor(devCommand.cmd, devCommand.args, cwd, devCommand.waitFor, 6e4);
3091
- const url = `http://localhost:${defaultPort}/${entryPath}`;
3092
- console.log();
3093
- p.log.success(`Dev server is running! Your docs are live at:\n\n ${pc.cyan(pc.underline(url))}\n\n Press ${pc.dim("Ctrl+C")} to stop the server.`);
3094
- p.outro(pc.green("Happy documenting!"));
3095
- await new Promise((resolve) => {
3096
- child.on("close", () => resolve());
3097
- process.on("SIGINT", () => {
3098
- child.kill("SIGINT");
3099
- resolve();
3100
- });
3101
- process.on("SIGTERM", () => {
3102
- child.kill("SIGTERM");
3103
- resolve();
3104
- });
3105
- });
3106
- } catch {
3107
- const manualCmd = framework === "tanstack-start" ? "npx vite dev" : framework === "sveltekit" ? "npx vite dev" : framework === "astro" ? "npx astro dev" : framework === "nuxt" ? "npx nuxt dev" : "pnpm dev";
3108
- p.log.error(`Could not start dev server. Try running manually:
3109
- ${pc.cyan(manualCmd)}`);
3110
- p.outro(pc.yellow("Setup complete. Start the server manually."));
3111
- process.exit(1);
3112
- }
3113
- }
3114
- function getScaffoldContentRoots(cfg) {
3115
- return cfg.i18n?.locales?.length ? cfg.i18n.locales.map((locale) => `${cfg.entry}/${locale}`) : [cfg.entry];
3116
- }
3117
- function scaffoldNextJs(cwd, cfg, globalCssRelPath, write, skipped, written) {
3118
- const appDir = cfg.nextAppDir ?? "app";
3119
- if (cfg.theme === "custom" && cfg.customThemeName) {
3120
- const baseName = cfg.customThemeName.replace(/\.(ts|css)$/i, "");
3121
- write(`themes/${baseName}.ts`, customThemeTsTemplate(baseName));
3122
- write(`themes/${baseName}.css`, customThemeCssTemplate(baseName));
3123
- }
3124
- write("docs.config.ts", docsConfigTemplate(cfg));
3125
- const existingNextConfig = readFileSafe(path.join(cwd, "next.config.ts")) ?? readFileSafe(path.join(cwd, "next.config.mjs")) ?? readFileSafe(path.join(cwd, "next.config.js"));
3126
- if (existingNextConfig) {
3127
- const configFile = fileExists(path.join(cwd, "next.config.ts")) ? "next.config.ts" : fileExists(path.join(cwd, "next.config.mjs")) ? "next.config.mjs" : "next.config.js";
3128
- const merged = nextConfigMergedTemplate(existingNextConfig);
3129
- if (merged !== existingNextConfig) {
3130
- writeFileSafe(path.join(cwd, configFile), merged, true);
3131
- written.push(configFile + " (updated)");
3132
- } else skipped.push(configFile + " (already configured)");
3133
- } else write("next.config.ts", nextConfigTemplate());
3134
- const rootLayoutPath = path.join(cwd, `${appDir}/layout.tsx`);
3135
- const existingRootLayout = readFileSafe(rootLayoutPath);
3136
- if (!existingRootLayout) write(`${appDir}/layout.tsx`, rootLayoutTemplate(cfg, globalCssRelPath), true);
3137
- else if (!existingRootLayout.includes("RootProvider")) {
3138
- const injected = injectRootProviderIntoLayout(existingRootLayout);
3139
- if (injected) {
3140
- writeFileSafe(rootLayoutPath, injected, true);
3141
- written.push(`${appDir}/layout.tsx (injected RootProvider)`);
3142
- } else skipped.push(`${appDir}/layout.tsx (could not inject RootProvider)`);
3143
- } else skipped.push(`${appDir}/layout.tsx (already has RootProvider)`);
3144
- const globalCssAbsPath = path.join(cwd, globalCssRelPath);
3145
- const existingGlobalCss = readFileSafe(globalCssAbsPath);
3146
- if (existingGlobalCss) {
3147
- const injected = injectCssImport(existingGlobalCss, cfg.theme, cfg.customThemeName, globalCssRelPath);
3148
- if (injected) {
3149
- writeFileSafe(globalCssAbsPath, injected, true);
3150
- written.push(globalCssRelPath + " (updated)");
3151
- } else skipped.push(globalCssRelPath + " (already configured)");
3152
- } else write(globalCssRelPath, globalCssTemplate(cfg.theme, cfg.customThemeName, globalCssRelPath));
3153
- write(`${appDir}/${cfg.entry}/layout.tsx`, docsLayoutTemplate(cfg));
3154
- if (cfg.apiReference) {
3155
- const apiReferenceRoute = `${appDir}/${cfg.apiReference.path}/[[...slug]]/route.ts`;
3156
- write(apiReferenceRoute, nextApiReferenceRouteTemplate(cfg, apiReferenceRoute));
3157
- }
3158
- write("postcss.config.mjs", postcssConfigTemplate());
3159
- if (!fileExists(path.join(cwd, "tsconfig.json"))) write("tsconfig.json", tsconfigTemplate(cfg.useAlias));
3160
- if (cfg.i18n?.locales.length) {
3161
- write(`${appDir}/components/locale-doc-page.tsx`, nextLocaleDocPageTemplate(cfg.i18n.defaultLocale));
3162
- write(`${appDir}/${cfg.entry}/page.tsx`, nextLocalizedPageTemplate({
3163
- locales: cfg.i18n.locales,
3164
- defaultLocale: cfg.i18n.defaultLocale,
3165
- componentName: "DocsIndexPage",
3166
- helperImport: "../components/locale-doc-page",
3167
- pageImports: cfg.i18n.locales.map((locale) => ({
3168
- locale,
3169
- importPath: `./${locale}/page.mdx`
3170
- }))
3171
- }));
3172
- write(`${appDir}/${cfg.entry}/installation/page.tsx`, nextLocalizedPageTemplate({
3173
- locales: cfg.i18n.locales,
3174
- defaultLocale: cfg.i18n.defaultLocale,
3175
- componentName: "InstallationPage",
3176
- helperImport: "../../components/locale-doc-page",
3177
- pageImports: cfg.i18n.locales.map((locale) => ({
3178
- locale,
3179
- importPath: `../${locale}/installation/page.mdx`
3180
- }))
3181
- }));
3182
- write(`${appDir}/${cfg.entry}/quickstart/page.tsx`, nextLocalizedPageTemplate({
3183
- locales: cfg.i18n.locales,
3184
- defaultLocale: cfg.i18n.defaultLocale,
3185
- componentName: "QuickstartPage",
3186
- helperImport: "../../components/locale-doc-page",
3187
- pageImports: cfg.i18n.locales.map((locale) => ({
3188
- locale,
3189
- importPath: `../${locale}/quickstart/page.mdx`
3190
- }))
3191
- }));
3192
- for (const locale of cfg.i18n.locales) {
3193
- const base = `${appDir}/${cfg.entry}/${locale}`;
3194
- write(`${base}/page.mdx`, welcomePageTemplate(cfg));
3195
- write(`${base}/installation/page.mdx`, installationPageTemplate(cfg));
3196
- write(`${base}/quickstart/page.mdx`, quickstartPageTemplate(cfg));
3197
- }
3198
- return;
3199
- }
3200
- write(`${appDir}/${cfg.entry}/page.mdx`, welcomePageTemplate(cfg));
3201
- write(`${appDir}/${cfg.entry}/installation/page.mdx`, installationPageTemplate(cfg));
3202
- write(`${appDir}/${cfg.entry}/quickstart/page.mdx`, quickstartPageTemplate(cfg));
3203
- }
3204
- function scaffoldTanstackStart(cwd, cfg, globalCssRelPath, write, skipped, written) {
3205
- if (cfg.theme === "custom" && cfg.customThemeName) {
3206
- const baseName = cfg.customThemeName.replace(/\.(ts|css)$/i, "");
3207
- write(`themes/${baseName}.ts`, customThemeTsTemplate(baseName));
3208
- write(`themes/${baseName}.css`, customThemeCssTemplate(baseName));
3209
- }
3210
- write("docs.config.ts", tanstackDocsConfigTemplate(cfg));
3211
- write("src/lib/docs.server.ts", tanstackDocsServerTemplate());
3212
- write("src/lib/docs.functions.ts", tanstackDocsFunctionsTemplate());
3213
- const routeDir = getTanstackDocsRouteDir(cfg.entry);
3214
- const docsIndexRoute = `${routeDir}/index.tsx`;
3215
- const docsCatchAllRoute = `${routeDir}/$.tsx`;
3216
- const apiRoute = "src/routes/api/docs.ts";
3217
- write(docsIndexRoute, tanstackDocsIndexRouteTemplate({
3218
- entry: cfg.entry,
3219
- filePath: docsIndexRoute,
3220
- useAlias: cfg.useAlias,
3221
- projectName: cfg.projectName
3222
- }));
3223
- write(docsCatchAllRoute, tanstackDocsCatchAllRouteTemplate({
3224
- entry: cfg.entry,
3225
- filePath: docsCatchAllRoute,
3226
- useAlias: cfg.useAlias,
3227
- projectName: cfg.projectName
3228
- }));
3229
- write(apiRoute, tanstackApiDocsRouteTemplate(cfg.useAlias, apiRoute));
3230
- if (cfg.apiReference) {
3231
- const apiReferenceIndexRoute = `src/routes/${cfg.apiReference.path}.index.ts`;
3232
- const apiReferenceCatchAllRoute = `src/routes/${cfg.apiReference.path}.$.ts`;
3233
- write(apiReferenceIndexRoute, tanstackApiReferenceRouteTemplate({
3234
- filePath: apiReferenceIndexRoute,
3235
- useAlias: cfg.useAlias,
3236
- apiReferencePath: cfg.apiReference.path,
3237
- catchAll: false
3238
- }));
3239
- write(apiReferenceCatchAllRoute, tanstackApiReferenceRouteTemplate({
3240
- filePath: apiReferenceCatchAllRoute,
3241
- useAlias: cfg.useAlias,
3242
- apiReferencePath: cfg.apiReference.path,
3243
- catchAll: true
3244
- }));
3245
- }
3246
- const rootRoutePath = path.join(cwd, "src/routes/__root.tsx");
3247
- const existingRootRoute = readFileSafe(rootRoutePath);
3248
- if (!existingRootRoute) write("src/routes/__root.tsx", tanstackRootRouteTemplate(globalCssRelPath), true);
3249
- else if (!existingRootRoute.includes("RootProvider")) {
3250
- const injected = injectTanstackRootProviderIntoRoute(existingRootRoute);
3251
- if (injected) {
3252
- writeFileSafe(rootRoutePath, injected, true);
3253
- written.push("src/routes/__root.tsx (injected RootProvider)");
3254
- } else skipped.push("src/routes/__root.tsx (could not inject RootProvider)");
3255
- } else skipped.push("src/routes/__root.tsx (already has RootProvider)");
3256
- const viteConfigRel = fileExists(path.join(cwd, "vite.config.ts")) ? "vite.config.ts" : fileExists(path.join(cwd, "vite.config.mts")) ? "vite.config.mts" : fileExists(path.join(cwd, "vite.config.js")) ? "vite.config.js" : "vite.config.ts";
3257
- const viteConfigPath = path.join(cwd, viteConfigRel);
3258
- const existingViteConfig = readFileSafe(viteConfigPath);
3259
- if (!existingViteConfig) write(viteConfigRel, tanstackViteConfigTemplate(cfg.useAlias), true);
3260
- else {
3261
- const injected = injectTanstackVitePlugins(existingViteConfig, cfg.useAlias);
3262
- if (injected) {
3263
- writeFileSafe(viteConfigPath, injected, true);
3264
- written.push(`${viteConfigRel} (updated)`);
3265
- } else skipped.push(`${viteConfigRel} (already configured)`);
3266
- }
3267
- const globalCssAbsPath = path.join(cwd, globalCssRelPath);
3268
- const existingGlobalCss = readFileSafe(globalCssAbsPath);
3269
- if (existingGlobalCss) {
3270
- const injected = injectCssImport(existingGlobalCss, cfg.theme, cfg.customThemeName, globalCssRelPath);
3271
- if (injected) {
3272
- writeFileSafe(globalCssAbsPath, injected, true);
3273
- written.push(globalCssRelPath + " (updated)");
3274
- } else skipped.push(globalCssRelPath + " (already configured)");
3275
- } else write(globalCssRelPath, globalCssTemplate(cfg.theme, cfg.customThemeName, globalCssRelPath));
3276
- for (const base of getScaffoldContentRoots(cfg)) {
3277
- write(`${base}/page.mdx`, tanstackWelcomePageTemplate(cfg));
3278
- write(`${base}/installation/page.mdx`, tanstackInstallationPageTemplate(cfg));
3279
- write(`${base}/quickstart/page.mdx`, tanstackQuickstartPageTemplate(cfg));
3280
- }
3281
- }
3282
- function scaffoldSvelteKit(cwd, cfg, globalCssRelPath, write, skipped, written) {
3283
- if (cfg.theme === "custom" && cfg.customThemeName) {
3284
- const baseName = cfg.customThemeName.replace(/\.(ts|css)$/i, "");
3285
- write(`themes/${baseName}.ts`, customThemeTsTemplate(baseName));
3286
- write(`themes/${baseName}.css`, customThemeCssTemplate(baseName));
3287
- }
3288
- write("src/lib/docs.config.ts", svelteDocsConfigTemplate(cfg));
3289
- write("src/lib/docs.server.ts", svelteDocsServerTemplate(cfg));
3290
- write(`src/routes/${cfg.entry}/+layout.svelte`, svelteDocsLayoutTemplate(cfg));
3291
- write(`src/routes/${cfg.entry}/+layout.server.js`, svelteDocsLayoutServerTemplate(cfg));
3292
- write(`src/routes/${cfg.entry}/[...slug]/+page.svelte`, svelteDocsPageTemplate(cfg));
3293
- if (cfg.i18n?.locales.length) write(`src/routes/${cfg.entry}/+page.svelte`, svelteDocsPageTemplate(cfg));
3294
- if (cfg.apiReference) {
3295
- const apiReferenceIndexRoute = `src/routes/${cfg.apiReference.path}/+server.ts`;
3296
- const apiReferenceCatchAllRoute = `src/routes/${cfg.apiReference.path}/[...slug]/+server.ts`;
3297
- write(apiReferenceIndexRoute, svelteApiReferenceRouteTemplate(apiReferenceIndexRoute, cfg.useAlias));
3298
- write(apiReferenceCatchAllRoute, svelteApiReferenceRouteTemplate(apiReferenceCatchAllRoute, cfg.useAlias));
3299
- }
3300
- if (!readFileSafe(path.join(cwd, "src/routes/+layout.svelte"))) write("src/routes/+layout.svelte", svelteRootLayoutTemplate(globalCssRelPath));
3301
- const globalCssAbsPath = path.join(cwd, globalCssRelPath);
3302
- const existingGlobalCss = readFileSafe(globalCssAbsPath);
3303
- const cssTheme = {
3304
- fumadocs: "fumadocs",
3305
- darksharp: "darksharp",
3306
- "pixel-border": "pixel-border",
3307
- colorful: "colorful",
3308
- darkbold: "darkbold",
3309
- shiny: "shiny",
3310
- greentree: "greentree",
3311
- concrete: "concrete",
3312
- hardline: "hardline",
3313
- default: "fumadocs"
3314
- }[cfg.theme] || "fumadocs";
3315
- if (existingGlobalCss) {
3316
- const injected = cfg.theme === "custom" && cfg.customThemeName ? injectSvelteCssImport(existingGlobalCss, "custom", cfg.customThemeName, globalCssRelPath) : injectSvelteCssImport(existingGlobalCss, cssTheme);
3317
- if (injected) {
3318
- writeFileSafe(globalCssAbsPath, injected, true);
3319
- written.push(globalCssRelPath + " (updated)");
3320
- } else skipped.push(globalCssRelPath + " (already configured)");
3321
- } else write(globalCssRelPath, cfg.theme === "custom" && cfg.customThemeName ? svelteGlobalCssTemplate("custom", cfg.customThemeName, globalCssRelPath) : svelteGlobalCssTemplate(cssTheme));
3322
- for (const base of getScaffoldContentRoots(cfg)) {
3323
- write(`${base}/page.md`, svelteWelcomePageTemplate(cfg));
3324
- write(`${base}/installation/page.md`, svelteInstallationPageTemplate(cfg));
3325
- write(`${base}/quickstart/page.md`, svelteQuickstartPageTemplate(cfg));
3326
- }
3327
- }
3328
- function scaffoldAstro(cwd, cfg, globalCssRelPath, write, skipped, written) {
3329
- if (cfg.theme === "custom" && cfg.customThemeName) {
3330
- const baseName = cfg.customThemeName.replace(/\.(ts|css)$/i, "");
3331
- write(`themes/${baseName}.ts`, customThemeTsTemplate(baseName));
3332
- write(`themes/${baseName}.css`, customThemeCssTemplate(baseName));
3333
- }
3334
- write("src/lib/docs.config.ts", astroDocsConfigTemplate(cfg));
3335
- write("src/lib/docs.server.ts", astroDocsServerTemplate(cfg));
3336
- if (!fileExists(path.join(cwd, "astro.config.mjs")) && !fileExists(path.join(cwd, "astro.config.ts"))) write("astro.config.mjs", astroConfigTemplate(cfg.astroAdapter ?? "vercel"));
3337
- write(`src/pages/${cfg.entry}/index.astro`, astroDocsIndexTemplate(cfg));
3338
- write(`src/pages/${cfg.entry}/[...slug].astro`, astroDocsPageTemplate(cfg));
3339
- write(`src/pages/api/${cfg.entry}.ts`, astroApiRouteTemplate(cfg));
3340
- if (cfg.apiReference) {
3341
- const apiReferenceIndexRoute = `src/pages/${cfg.apiReference.path}/index.ts`;
3342
- const apiReferenceCatchAllRoute = `src/pages/${cfg.apiReference.path}/[...slug].ts`;
3343
- write(apiReferenceIndexRoute, astroApiReferenceRouteTemplate(apiReferenceIndexRoute));
3344
- write(apiReferenceCatchAllRoute, astroApiReferenceRouteTemplate(apiReferenceCatchAllRoute));
3345
- }
3346
- const globalCssAbsPath = path.join(cwd, globalCssRelPath);
3347
- const existingGlobalCss = readFileSafe(globalCssAbsPath);
3348
- const cssTheme = {
3349
- fumadocs: "fumadocs",
3350
- darksharp: "darksharp",
3351
- "pixel-border": "pixel-border",
3352
- colorful: "colorful",
3353
- darkbold: "darkbold",
3354
- shiny: "shiny",
3355
- greentree: "greentree",
3356
- concrete: "concrete",
3357
- hardline: "hardline",
3358
- default: "fumadocs"
3359
- }[cfg.theme] || "fumadocs";
3360
- if (existingGlobalCss) {
3361
- const injected = cfg.theme === "custom" && cfg.customThemeName ? injectAstroCssImport(existingGlobalCss, "custom", cfg.customThemeName, globalCssRelPath) : injectAstroCssImport(existingGlobalCss, cssTheme);
3362
- if (injected) {
3363
- writeFileSafe(globalCssAbsPath, injected, true);
3364
- written.push(globalCssRelPath + " (updated)");
3365
- } else skipped.push(globalCssRelPath + " (already configured)");
3366
- } else write(globalCssRelPath, cfg.theme === "custom" && cfg.customThemeName ? astroGlobalCssTemplate("custom", cfg.customThemeName, globalCssRelPath) : astroGlobalCssTemplate(cssTheme));
3367
- for (const base of getScaffoldContentRoots(cfg)) {
3368
- write(`${base}/page.md`, astroWelcomePageTemplate(cfg));
3369
- write(`${base}/installation/page.md`, astroInstallationPageTemplate(cfg));
3370
- write(`${base}/quickstart/page.md`, astroQuickstartPageTemplate(cfg));
3371
- }
3372
- }
3373
- function scaffoldNuxt(cwd, cfg, globalCssRelPath, write, skipped, written) {
3374
- if (cfg.theme === "custom" && cfg.customThemeName) {
3375
- const baseName = cfg.customThemeName.replace(/\.(ts|css)$/i, "");
3376
- write(`themes/${baseName}.ts`, customThemeTsTemplate(baseName));
3377
- write(`themes/${baseName}.css`, customThemeCssTemplate(baseName));
3378
- }
3379
- write("docs.config.ts", nuxtDocsConfigTemplate(cfg));
3380
- write("server/utils/docs-server.ts", nuxtDocsServerTemplate(cfg));
3381
- write("server/api/docs.get.ts", nuxtServerApiDocsGetTemplate());
3382
- write("server/api/docs.post.ts", nuxtServerApiDocsPostTemplate());
3383
- write("server/api/docs/load.get.ts", nuxtServerApiDocsLoadTemplate());
3384
- write(`pages/${cfg.entry}/[[...slug]].vue`, nuxtDocsPageTemplate(cfg));
3385
- if (cfg.apiReference) {
3386
- const apiReferenceIndexRoute = `server/routes/${cfg.apiReference.path}/index.ts`;
3387
- const apiReferenceCatchAllRoute = `server/routes/${cfg.apiReference.path}/[...slug].ts`;
3388
- write(apiReferenceIndexRoute, nuxtServerApiReferenceRouteTemplate(apiReferenceIndexRoute, cfg.useAlias));
3389
- write(apiReferenceCatchAllRoute, nuxtServerApiReferenceRouteTemplate(apiReferenceCatchAllRoute, cfg.useAlias));
3390
- }
3391
- if (!fileExists(path.join(cwd, "nuxt.config.ts")) && !fileExists(path.join(cwd, "nuxt.config.js"))) write("nuxt.config.ts", nuxtConfigTemplate(cfg));
3392
- const cssTheme = {
3393
- fumadocs: "fumadocs",
3394
- darksharp: "darksharp",
3395
- "pixel-border": "pixel-border",
3396
- colorful: "colorful",
3397
- darkbold: "darkbold",
3398
- shiny: "shiny",
3399
- greentree: "greentree",
3400
- concrete: "concrete",
3401
- hardline: "hardline",
3402
- default: "fumadocs"
3403
- }[cfg.theme] || "fumadocs";
3404
- const globalCssAbsPath = path.join(cwd, globalCssRelPath);
3405
- const existingGlobalCss = readFileSafe(globalCssAbsPath);
3406
- if (existingGlobalCss) {
3407
- const injected = cfg.theme === "custom" && cfg.customThemeName ? injectNuxtCssImport(existingGlobalCss, "custom", cfg.customThemeName, globalCssRelPath) : injectNuxtCssImport(existingGlobalCss, cssTheme);
3408
- if (injected) {
3409
- writeFileSafe(globalCssAbsPath, injected, true);
3410
- written.push(globalCssRelPath + " (updated)");
3411
- } else skipped.push(globalCssRelPath + " (already configured)");
3412
- } else write(globalCssRelPath, cfg.theme === "custom" && cfg.customThemeName ? nuxtGlobalCssTemplate("custom", cfg.customThemeName, globalCssRelPath) : nuxtGlobalCssTemplate(cssTheme));
3413
- for (const base of getScaffoldContentRoots(cfg)) {
3414
- write(`${base}/page.md`, nuxtWelcomePageTemplate(cfg));
3415
- write(`${base}/installation/page.md`, nuxtInstallationPageTemplate(cfg));
3416
- write(`${base}/quickstart/page.md`, nuxtQuickstartPageTemplate(cfg));
3417
- }
3418
- }
3419
-
3420
- //#endregion
3421
- //#region src/cli/mcp.ts
3422
- const FILE_EXTS = [
3423
- "tsx",
3424
- "ts",
3425
- "jsx",
3426
- "js"
3427
- ];
3428
- async function runMcp(options = {}) {
3429
- const rootDir = process.cwd();
3430
- const content = readFileSync(resolveDocsConfigPath(rootDir, options.configPath), "utf-8");
3431
- const entry = readStringProperty(content, "entry") ?? "docs";
3432
- const contentDir = readStringProperty(content, "contentDir") ?? entry;
3433
- const navTitle = readNavTitle(content);
3434
- const mcp = readMcpConfig(content);
3435
- await runDocsMcpStdio({
3436
- source: createFilesystemDocsMcpSource({
3437
- rootDir,
3438
- entry,
3439
- contentDir,
3440
- siteTitle: navTitle ?? "Documentation"
3441
- }),
3442
- mcp: resolveDocsMcpConfig(mcp ?? true, { defaultName: navTitle ?? "@farming-labs/docs" }),
3443
- defaultName: navTitle ?? "@farming-labs/docs"
3444
- });
3445
- }
3446
- function resolveDocsConfigPath(rootDir, explicitPath) {
3447
- if (explicitPath) {
3448
- const resolvedPath = resolve(rootDir, explicitPath);
3449
- if (!existsSync(resolvedPath)) throw new Error(`Could not find docs config at ${explicitPath}.`);
3450
- return resolvedPath;
3451
- }
3452
- for (const ext of FILE_EXTS) {
3453
- const configPath = join(rootDir, `docs.config.${ext}`);
3454
- if (existsSync(configPath)) return configPath;
3455
- }
3456
- throw new Error("Could not find docs.config.ts or docs.config.tsx in the current project. Use --config to point at a custom path.");
3457
- }
3458
- function readStringProperty(content, key) {
3459
- return content.match(new RegExp(`${key}\\s*:\\s*["']([^"']+)["']`))?.[1];
3460
- }
3461
- function readNavTitle(content) {
3462
- const block = extractObjectLiteral(content, "nav");
3463
- if (!block) return void 0;
3464
- return readStringProperty(block, "title");
3465
- }
3466
- function readMcpConfig(content) {
3467
- if (content.match(/mcp\s*:\s*false/)) return false;
3468
- if (content.match(/mcp\s*:\s*true/)) return true;
3469
- const block = extractObjectLiteral(content, "mcp");
3470
- if (!block) return void 0;
3471
- return {
3472
- enabled: readBooleanProperty(block, "enabled"),
3473
- route: readStringProperty(block, "route"),
3474
- name: readStringProperty(block, "name"),
3475
- version: readStringProperty(block, "version"),
3476
- tools: {
3477
- listPages: readBooleanProperty(block, "listPages"),
3478
- readPage: readBooleanProperty(block, "readPage"),
3479
- searchDocs: readBooleanProperty(block, "searchDocs"),
3480
- getNavigation: readBooleanProperty(block, "getNavigation")
3481
- }
3482
- };
3483
- }
3484
- function readBooleanProperty(content, key) {
3485
- const match = content.match(new RegExp(`${key}\\s*:\\s*(true|false)`));
3486
- return match ? match[1] === "true" : void 0;
3487
- }
3488
- function extractObjectLiteral(content, key) {
3489
- const keyIndex = content.search(new RegExp(`${key}\\s*:\\s*\\{`));
3490
- if (keyIndex === -1) return void 0;
3491
- const braceStart = content.indexOf("{", keyIndex);
3492
- if (braceStart === -1) return void 0;
3493
- let depth = 0;
3494
- for (let index = braceStart; index < content.length; index += 1) {
3495
- const char = content[index];
3496
- if (char === "{") {
3497
- depth += 1;
3498
- continue;
3499
- }
3500
- if (char !== "}") continue;
3501
- depth -= 1;
3502
- if (depth === 0) return content.slice(braceStart + 1, index);
3503
- }
3504
- }
3505
-
3506
- //#endregion
3507
- //#region src/cli/upgrade.ts
3508
- /**
3509
- * Upgrade @farming-labs/* packages to latest.
3510
- * Detects framework from package.json by default, or use --framework (next, tanstack-start, nuxt, sveltekit, astro).
3511
- */
3512
- const PRESETS = [
3513
- "next",
3514
- "tanstack-start",
3515
- "nuxt",
3516
- "sveltekit",
3517
- "astro"
3518
- ];
3519
- const PACKAGES_BY_FRAMEWORK = {
3520
- nextjs: [
3521
- "@farming-labs/docs",
3522
- "@farming-labs/theme",
3523
- "@farming-labs/next"
3524
- ],
3525
- "tanstack-start": [
3526
- "@farming-labs/docs",
3527
- "@farming-labs/theme",
3528
- "@farming-labs/tanstack-start"
3529
- ],
3530
- nuxt: [
3531
- "@farming-labs/docs",
3532
- "@farming-labs/nuxt",
3533
- "@farming-labs/nuxt-theme"
3534
- ],
3535
- sveltekit: [
3536
- "@farming-labs/docs",
3537
- "@farming-labs/svelte",
3538
- "@farming-labs/svelte-theme"
3539
- ],
3540
- astro: [
3541
- "@farming-labs/docs",
3542
- "@farming-labs/astro",
3543
- "@farming-labs/astro-theme"
3544
- ]
3545
- };
3546
- function presetFromFramework(fw) {
3547
- return fw === "nextjs" ? "next" : fw;
3548
- }
3549
- function frameworkFromPreset(preset) {
3550
- return preset === "next" ? "nextjs" : preset;
3551
- }
3552
- /** Return package list for a framework (for testing and CLI). */
3553
- function getPackagesForFramework(framework) {
3554
- return PACKAGES_BY_FRAMEWORK[framework];
3555
- }
3556
- /** Build the install command for upgrade (for testing). */
3557
- function buildUpgradeCommand(framework, tag, pm) {
3558
- const packagesWithTag = PACKAGES_BY_FRAMEWORK[framework].map((name) => `${name}@${tag}`);
3559
- return `${installCommand(pm)} ${packagesWithTag.join(" ")}`;
3560
- }
3561
- async function upgrade(options = {}) {
3562
- const cwd = process.cwd();
3563
- const tag = options.tag ?? "latest";
3564
- p.intro(pc.bgCyan(pc.black(" @farming-labs/docs upgrade ")));
3565
- if (!fileExists(path.join(cwd, "package.json"))) {
3566
- p.log.error("No package.json found in the current directory. Run this from your project root.");
3567
- process.exit(1);
3568
- }
3569
- let framework = null;
3570
- let preset;
3571
- if (options.framework) {
3572
- const raw = options.framework.toLowerCase().trim();
3573
- const normalized = raw === "nextjs" ? "next" : raw;
3574
- if (!PRESETS.includes(normalized)) {
3575
- p.log.error(`Invalid framework ${pc.cyan(options.framework)}. Use one of: ${PRESETS.map((t) => pc.cyan(t)).join(", ")}`);
3576
- process.exit(1);
3577
- }
3578
- preset = normalized;
3579
- framework = frameworkFromPreset(preset);
3580
- } else {
3581
- const detected = detectFramework(cwd);
3582
- if (!detected) {
3583
- p.log.error("Could not detect a supported framework (Next.js, TanStack Start, Nuxt, SvelteKit, Astro). Use " + pc.cyan("--framework <next|tanstack-start|nuxt|sveltekit|astro>") + " to specify.");
3584
- process.exit(1);
3585
- }
3586
- framework = detected;
3587
- preset = presetFromFramework(framework);
3588
- }
3589
- let pm = detectPackageManagerFromLockfile(cwd);
3590
- if (pm) p.log.info(`Detected ${pc.cyan(pm)} from lockfile`);
3591
- else {
3592
- const pmAnswer = await p.select({
3593
- message: "Which package manager do you want to use for this upgrade?",
3594
- options: [
3595
- {
3596
- value: "pnpm",
3597
- label: "pnpm",
3598
- hint: "Use pnpm add"
3599
- },
3600
- {
3601
- value: "npm",
3602
- label: "npm",
3603
- hint: "Use npm add"
3604
- },
3605
- {
3606
- value: "yarn",
3607
- label: "yarn",
3608
- hint: "Use yarn add"
3609
- },
3610
- {
3611
- value: "bun",
3612
- label: "bun",
3613
- hint: "Use bun add"
3614
- }
3615
- ]
3616
- });
3617
- if (p.isCancel(pmAnswer)) {
3618
- p.outro(pc.red("Upgrade cancelled."));
3619
- process.exit(0);
3620
- }
3621
- pm = pmAnswer;
3622
- p.log.info(`Using ${pc.cyan(pm)} as package manager`);
3623
- }
3624
- const cmd = buildUpgradeCommand(framework, tag, pm);
3625
- const packages = getPackagesForFramework(framework);
3626
- p.log.step(`Upgrading ${preset} docs packages to ${tag}...`);
3627
- p.log.message(pc.dim(packages.join(", ")));
3628
- try {
3629
- exec(cmd, cwd);
3630
- p.log.success(`Packages upgraded to ${tag}.`);
3631
- p.outro(pc.green("Done. Run your dev server to confirm everything works."));
3632
- } catch {
3633
- p.log.error("Upgrade failed. Try running manually:\n " + pc.cyan(cmd));
3634
- process.exit(1);
3635
- }
3636
- }
3637
-
3638
- //#endregion
3639
4
  //#region src/cli/index.ts
3640
5
  const args = process.argv.slice(2);
3641
6
  const command = args[0];
@@ -3682,13 +47,19 @@ async function main() {
3682
47
  apiRouteRoot: typeof flags["api-route-root"] === "string" ? flags["api-route-root"] : void 0
3683
48
  };
3684
49
  const mcpOptions = { configPath: typeof flags.config === "string" ? flags.config : void 0 };
3685
- if (!parsedCommand.command || parsedCommand.command === "init") await init(initOptions);
3686
- else if (parsedCommand.command === "mcp") await runMcp(mcpOptions);
3687
- else if (parsedCommand.command === "upgrade") await upgrade({
3688
- framework: (typeof flags.framework === "string" ? flags.framework : void 0) ?? (args[1] && !args[1].startsWith("--") ? args[1] : void 0),
3689
- tag: args.includes("--beta") ? "beta" : args.includes("--latest") ? "latest" : parsedCommand.tag ?? "latest"
3690
- });
3691
- else if (parsedCommand.command === "--help" || parsedCommand.command === "-h") printHelp();
50
+ if (!parsedCommand.command || parsedCommand.command === "init") {
51
+ const { init } = await import("../init-N0bZQFRd.mjs");
52
+ await init(initOptions);
53
+ } else if (parsedCommand.command === "mcp") {
54
+ const { runMcp } = await import("../mcp-8rCBy2-U.mjs");
55
+ await runMcp(mcpOptions);
56
+ } else if (parsedCommand.command === "upgrade") {
57
+ const { upgrade } = await import("../upgrade-BbEyR_JB.mjs");
58
+ await upgrade({
59
+ framework: (typeof flags.framework === "string" ? flags.framework : void 0) ?? (args[1] && !args[1].startsWith("--") ? args[1] : void 0),
60
+ tag: args.includes("--beta") ? "beta" : args.includes("--latest") ? "latest" : parsedCommand.tag ?? "latest"
61
+ });
62
+ } else if (parsedCommand.command === "--help" || parsedCommand.command === "-h") printHelp();
3692
63
  else if (parsedCommand.command === "--version" || parsedCommand.command === "-v") printVersion();
3693
64
  else {
3694
65
  console.error(pc.red(`Unknown command: ${command}`));