@farming-labs/docs 0.0.33 → 0.0.34

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