@farming-labs/docs 0.1.1-beta.1 → 0.1.1-beta.4

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