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