@farm.js/create-app 0.1.0-beta.23 → 0.1.0-beta.26

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.
package/dist/index.mjs CHANGED
@@ -3,24 +3,2658 @@ import prompts from "prompts";
3
3
  import path from "path";
4
4
  import fs from "fs/promises";
5
5
  import { spawn } from "node:child_process";
6
+ import { existsSync } from "node:fs";
7
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
8
+ import path$1 from "node:path";
9
+ //#region ../farm-cli/src/ui-feature-registry.ts
10
+ async function installUIFeature(input) {
11
+ const feature = input.definition.ui;
12
+ if (!feature) {
13
+ input.result.notes.push(`No --ui feature pack is available for ${input.definition.provider} yet.`);
14
+ return;
15
+ }
16
+ input.result.ui = {
17
+ feature: feature.name,
18
+ components: [...feature.components],
19
+ files: []
20
+ };
21
+ input.result.notes.push(`Installed ${feature.description} with shadcn-style local source components.`, ...feature.notes || []);
22
+ await ensureComponentsJson({
23
+ root: input.root,
24
+ dryRun: input.dryRun,
25
+ result: input.result
26
+ });
27
+ await ensureShadcnGlobals({
28
+ root: input.root,
29
+ dryRun: input.dryRun,
30
+ result: input.result
31
+ });
32
+ await ensureTsconfigAlias({
33
+ root: input.root,
34
+ dryRun: input.dryRun,
35
+ result: input.result
36
+ });
37
+ if (!input.skipPackageJson) await updateUIPackageJson({
38
+ root: input.root,
39
+ dryRun: input.dryRun,
40
+ result: input.result
41
+ });
42
+ await writeGeneratedFile({
43
+ root: input.root,
44
+ relativePath: path$1.join("src", "lib", "utils.ts"),
45
+ source: shadcnUtilsTemplate(),
46
+ dryRun: input.dryRun,
47
+ force: input.force,
48
+ result: input.result
49
+ });
50
+ for (const component of feature.components) await writeGeneratedFile({
51
+ root: input.root,
52
+ relativePath: path$1.join("src", "components", "ui", `${component}.tsx`),
53
+ source: shadcnComponentTemplate(component),
54
+ dryRun: input.dryRun,
55
+ force: input.force,
56
+ result: input.result
57
+ });
58
+ if (feature.needsApiClient !== false) await writeGeneratedFile({
59
+ root: input.root,
60
+ relativePath: path$1.join("src", "lib", "api.ts"),
61
+ source: apiClientTemplate(),
62
+ dryRun: input.dryRun,
63
+ force: input.force,
64
+ result: input.result
65
+ });
66
+ for (const file of feature.files({
67
+ key: input.key,
68
+ provider: input.definition.provider
69
+ })) await writeGeneratedFile({
70
+ root: input.root,
71
+ relativePath: file.path,
72
+ source: file.source,
73
+ dryRun: input.dryRun,
74
+ force: input.force,
75
+ result: input.result
76
+ });
77
+ }
78
+ function stripeBillingUIFeature() {
79
+ return billingUIFeature({
80
+ provider: "stripe",
81
+ label: "Stripe"
82
+ });
83
+ }
84
+ function polarBillingUIFeature() {
85
+ return billingUIFeature({
86
+ provider: "polar",
87
+ label: "Polar"
88
+ });
89
+ }
90
+ function autumnBillingUIFeature() {
91
+ return billingUIFeature({
92
+ provider: "autumn",
93
+ label: "Autumn"
94
+ });
95
+ }
96
+ function aiChatUIFeature() {
97
+ return {
98
+ name: "ai-chat",
99
+ description: "AI chat UI",
100
+ components: [
101
+ "badge",
102
+ "button",
103
+ "card",
104
+ "input"
105
+ ],
106
+ needsApiClient: false,
107
+ notes: ["Open \"/integrations/ai\" to try the generated chat UI."],
108
+ files: () => [componentFile("ai-chat.tsx", aiChatTemplate()), integrationPageFile("ai", "AIChat", "ai-chat")]
109
+ };
110
+ }
111
+ function supabaseAuthUIFeature() {
112
+ return {
113
+ name: "supabase-auth",
114
+ description: "Supabase auth UI",
115
+ components: [
116
+ "badge",
117
+ "button",
118
+ "card",
119
+ "input",
120
+ "label"
121
+ ],
122
+ notes: ["Open \"/integrations/supabase\" to try the generated auth UI."],
123
+ files: (input) => [componentFile("supabase-auth-panel.tsx", supabaseAuthTemplate(input.key)), integrationPageFile("supabase", "SupabaseAuthPanel")]
124
+ };
125
+ }
126
+ function workosAuthUIFeature() {
127
+ return {
128
+ name: "workos-auth",
129
+ description: "WorkOS auth UI",
130
+ components: [
131
+ "badge",
132
+ "button",
133
+ "card"
134
+ ],
135
+ notes: ["Open \"/integrations/workos\" to try the generated auth UI."],
136
+ files: (input) => [componentFile("workos-auth-panel.tsx", hostedAuthTemplate({
137
+ key: input.key,
138
+ provider: "WorkOS",
139
+ componentName: "WorkOSAuthPanel",
140
+ statusCall: "session",
141
+ statusMethod: "get",
142
+ logoutCall: "logout",
143
+ logoutMethod: "post",
144
+ loginHref: "/login?returnTo=/dashboard",
145
+ signupHref: "/signup?returnTo=/dashboard",
146
+ statusLabel: "Session"
147
+ })), integrationPageFile("workos", "WorkOSAuthPanel", "workos-auth-panel")]
148
+ };
149
+ }
150
+ function auth0AuthUIFeature() {
151
+ return authRouteShellUIFeature({
152
+ provider: "auth0",
153
+ label: "Auth0",
154
+ componentName: "Auth0AuthPanel",
155
+ signInHref: "/auth/login?returnTo=/dashboard",
156
+ signUpHref: "/auth/signup?returnTo=/dashboard",
157
+ sessionHref: "/auth/profile"
158
+ });
159
+ }
160
+ function clerkAuthUIFeature() {
161
+ return authRouteShellUIFeature({
162
+ provider: "clerk",
163
+ label: "Clerk",
164
+ componentName: "ClerkAuthPanel",
165
+ signInHref: "/sign-in",
166
+ signUpHref: "/sign-up",
167
+ sessionHref: "/dashboard"
168
+ });
169
+ }
170
+ function betterAuthUIFeature() {
171
+ return {
172
+ name: "better-auth-auth",
173
+ description: "Better Auth email and password UI",
174
+ components: [
175
+ "badge",
176
+ "button",
177
+ "card",
178
+ "input",
179
+ "label"
180
+ ],
181
+ needsApiClient: false,
182
+ notes: ["Open \"/integrations/better-auth\" to try the generated auth UI."],
183
+ files: () => [
184
+ {
185
+ path: path$1.join("src", "lib", "auth-client.ts"),
186
+ source: betterAuthClientTemplate()
187
+ },
188
+ componentFile("better-auth-panel.tsx", betterAuthPanelTemplate()),
189
+ integrationPageFile("better-auth", "BetterAuthPanel")
190
+ ]
191
+ };
192
+ }
193
+ function authjsUIFeature() {
194
+ return authRouteShellUIFeature({
195
+ provider: "authjs",
196
+ label: "Auth.js",
197
+ componentName: "AuthJsPanel",
198
+ signInHref: "/api/auth/signin",
199
+ signUpHref: "/api/auth/signin",
200
+ sessionHref: "/api/auth/session"
201
+ });
202
+ }
203
+ function resendEmailUIFeature() {
204
+ return {
205
+ name: "resend-email",
206
+ description: "Resend email console UI",
207
+ components: [
208
+ "badge",
209
+ "button",
210
+ "card",
211
+ "input",
212
+ "label"
213
+ ],
214
+ notes: ["Open \"/integrations/resend\" to try the generated email UI."],
215
+ files: (input) => [componentFile("resend-email-console.tsx", resendEmailTemplate(input.key)), integrationPageFile("resend", "ResendEmailConsole")]
216
+ };
217
+ }
218
+ function jobsUIFeature(provider) {
219
+ const label = provider === "inngest" ? "Inngest" : "Trigger.dev";
220
+ return {
221
+ name: `${provider}-jobs`,
222
+ description: `${label} jobs console UI`,
223
+ components: [
224
+ "badge",
225
+ "button",
226
+ "card",
227
+ "input",
228
+ "label"
229
+ ],
230
+ notes: [`Open "/integrations/jobs-${provider}" to try the generated jobs UI.`],
231
+ files: (input) => [componentFile(`${provider}-jobs-console.tsx`, jobsConsoleTemplate(input.key, label, provider)), integrationPageFile(`jobs-${provider}`, `${pascalCase(provider)}JobsConsole`)]
232
+ };
233
+ }
234
+ function unkeyApiKeysUIFeature() {
235
+ return {
236
+ name: "unkey-api-keys",
237
+ description: "Unkey protected route UI",
238
+ components: ["badge", "card"],
239
+ needsApiClient: false,
240
+ notes: ["Open \"/integrations/unkey\" to test the generated protected API route."],
241
+ files: () => [
242
+ componentFile("unkey-api-keys-console.tsx", unkeyApiKeysTemplate()),
243
+ integrationPageFile("unkey", "UnkeyApiKeysConsole"),
244
+ {
245
+ path: path$1.join("src", "app", "api", "protected", "route.ts"),
246
+ source: unkeyProtectedRouteTemplate()
247
+ }
248
+ ]
249
+ };
250
+ }
251
+ function billingUIFeature(input) {
252
+ return {
253
+ name: `${input.provider}-billing`,
254
+ description: `${input.label} pricing and checkout UI`,
255
+ components: [
256
+ "badge",
257
+ "button",
258
+ "card"
259
+ ],
260
+ notes: [`Open "/integrations/${input.provider}" to try the generated ${input.label} billing UI.`],
261
+ files: (templateInput) => [componentFile(`${input.provider}-billing.tsx`, billingPricingTemplate({
262
+ key: templateInput.key,
263
+ provider: input.provider,
264
+ label: input.label,
265
+ componentName: `${pascalCase(input.provider)}Billing`
266
+ })), integrationPageFile(input.provider, `${pascalCase(input.provider)}Billing`)]
267
+ };
268
+ }
269
+ function authRouteShellUIFeature(input) {
270
+ return {
271
+ name: `${input.provider}-auth`,
272
+ description: `${input.label} auth UI`,
273
+ components: [
274
+ "badge",
275
+ "button",
276
+ "card"
277
+ ],
278
+ needsApiClient: false,
279
+ notes: [`Open "/integrations/${input.provider}" to try the generated auth UI.`],
280
+ files: () => [componentFile(`${input.provider}-auth-panel.tsx`, authRouteShellTemplate({
281
+ provider: input.label,
282
+ componentName: input.componentName,
283
+ signInHref: input.signInHref,
284
+ signUpHref: input.signUpHref,
285
+ sessionHref: input.sessionHref
286
+ })), integrationPageFile(input.provider, input.componentName, input.provider === "authjs" ? "authjs-auth-panel" : void 0)]
287
+ };
288
+ }
289
+ function componentFile(fileName, source) {
290
+ return {
291
+ path: path$1.join("src", "components", "farm", fileName),
292
+ source
293
+ };
294
+ }
295
+ function integrationPageFile(provider, componentName, sourceFileName = kebabCase(componentName)) {
296
+ return {
297
+ path: path$1.join("src", "app", "integrations", provider, "page.tsx"),
298
+ source: `import { ${componentName} } from "@/components/farm/${sourceFileName}";
299
+
300
+ export default function ${componentName}Page() {
301
+ return <${componentName} />;
302
+ }
303
+ `
304
+ };
305
+ }
306
+ async function writeGeneratedFile(input) {
307
+ const absolutePath = path$1.join(input.root, input.relativePath);
308
+ const exists = existsSync(absolutePath);
309
+ const source = resolveGeneratedAliases(input.source, input.relativePath);
310
+ input.result.ui?.files.push(absolutePath);
311
+ if (exists && !input.force) {
312
+ pushResultPath(input.result.skipped, absolutePath);
313
+ return;
314
+ }
315
+ if (!input.dryRun) {
316
+ await mkdir(path$1.dirname(absolutePath), { recursive: true });
317
+ await writeFile(absolutePath, source, "utf8");
318
+ }
319
+ pushResultPath(exists ? input.result.updated : input.result.created, absolutePath);
320
+ }
321
+ function resolveGeneratedAliases(source, relativePath) {
322
+ const sourceDirectory = path$1.dirname(relativePath);
323
+ return source.replace(/(["'])@\/([^"']+)\1/g, (_match, quote, target) => {
324
+ const relativeTarget = path$1.relative(sourceDirectory, path$1.join("src", target)).split(path$1.sep).join("/");
325
+ return `${quote}${relativeTarget.startsWith(".") ? relativeTarget : `./${relativeTarget}`}${quote}`;
326
+ });
327
+ }
328
+ async function ensureComponentsJson(input) {
329
+ const componentsJsonPath = path$1.join(input.root, "components.json");
330
+ input.result.ui?.files.push(componentsJsonPath);
331
+ const defaults = createComponentsJson();
332
+ if (!existsSync(componentsJsonPath)) {
333
+ if (!input.dryRun) await writeFile(componentsJsonPath, `${JSON.stringify(defaults, null, 2)}\n`, "utf8");
334
+ pushResultPath(input.result.created, componentsJsonPath);
335
+ return;
336
+ }
337
+ let current;
338
+ try {
339
+ current = JSON.parse(await readFile(componentsJsonPath, "utf8"));
340
+ } catch {
341
+ pushResultPath(input.result.skipped, componentsJsonPath);
342
+ input.result.notes.push("components.json could not be parsed. Keep shadcn aliases pointed at src/components and src/lib/utils.");
343
+ return;
344
+ }
345
+ const next = mergeComponentsJson(current, defaults);
346
+ if (JSON.stringify(current) === JSON.stringify(next)) {
347
+ pushResultPath(input.result.skipped, componentsJsonPath);
348
+ return;
349
+ }
350
+ if (!input.dryRun) await writeFile(componentsJsonPath, `${JSON.stringify(next, null, 2)}\n`, "utf8");
351
+ pushResultPath(input.result.updated, componentsJsonPath);
352
+ }
353
+ async function ensureShadcnGlobals(input) {
354
+ const globalsPath = path$1.join(input.root, "src", "app", "globals.css");
355
+ input.result.ui?.files.push(globalsPath);
356
+ if (!existsSync(globalsPath)) {
357
+ const source = `@import "tailwindcss";
358
+
359
+ ${SHADCN_THEME_CSS}
360
+ `;
361
+ if (!input.dryRun) {
362
+ await mkdir(path$1.dirname(globalsPath), { recursive: true });
363
+ await writeFile(globalsPath, source, "utf8");
364
+ }
365
+ pushResultPath(input.result.created, globalsPath);
366
+ return;
367
+ }
368
+ const source = await readFile(globalsPath, "utf8");
369
+ const hasTailwindImport = source.includes("@import \"tailwindcss\"");
370
+ const hasTheme = source.includes("--color-background") || source.includes("--background:");
371
+ if (hasTailwindImport && hasTheme) {
372
+ pushResultPath(input.result.skipped, globalsPath);
373
+ return;
374
+ }
375
+ const nextSource = `${hasTailwindImport ? "" : "@import \"tailwindcss\";\n\n"}${source.trimEnd()}${hasTheme ? "\n" : `
376
+
377
+ ${SHADCN_THEME_CSS}
378
+ `}`;
379
+ if (!input.dryRun) await writeFile(globalsPath, nextSource, "utf8");
380
+ pushResultPath(input.result.updated, globalsPath);
381
+ }
382
+ async function ensureTsconfigAlias(input) {
383
+ const tsconfigPath = path$1.join(input.root, "tsconfig.json");
384
+ input.result.ui?.files.push(tsconfigPath);
385
+ const defaults = { compilerOptions: {
386
+ baseUrl: ".",
387
+ paths: { "@/*": ["./src/*"] }
388
+ } };
389
+ if (!existsSync(tsconfigPath)) {
390
+ if (!input.dryRun) await writeFile(tsconfigPath, `${JSON.stringify(defaults, null, 2)}\n`, "utf8");
391
+ pushResultPath(input.result.created, tsconfigPath);
392
+ return;
393
+ }
394
+ let tsconfig;
395
+ try {
396
+ tsconfig = JSON.parse(await readFile(tsconfigPath, "utf8"));
397
+ } catch {
398
+ pushResultPath(input.result.skipped, tsconfigPath);
399
+ input.result.notes.push("tsconfig.json could not be parsed. Add paths: { \"@/*\": [\"./src/*\"] } manually.");
400
+ return;
401
+ }
402
+ const compilerOptions = readObject(tsconfig.compilerOptions);
403
+ const paths = readObject(compilerOptions.paths);
404
+ const nextCompilerOptions = {
405
+ ...compilerOptions,
406
+ baseUrl: typeof compilerOptions.baseUrl === "string" ? compilerOptions.baseUrl : ".",
407
+ paths: {
408
+ ...paths,
409
+ "@/*": ["./src/*"]
410
+ }
411
+ };
412
+ const nextTsconfig = {
413
+ ...tsconfig,
414
+ compilerOptions: nextCompilerOptions
415
+ };
416
+ if (JSON.stringify(tsconfig) === JSON.stringify(nextTsconfig)) {
417
+ pushResultPath(input.result.skipped, tsconfigPath);
418
+ return;
419
+ }
420
+ if (!input.dryRun) await writeFile(tsconfigPath, `${JSON.stringify(nextTsconfig, null, 2)}\n`, "utf8");
421
+ pushResultPath(input.result.updated, tsconfigPath);
422
+ }
423
+ async function updateUIPackageJson(input) {
424
+ const packageJsonPath = path$1.join(input.root, "package.json");
425
+ input.result.ui?.files.push(packageJsonPath);
426
+ if (!existsSync(packageJsonPath)) {
427
+ pushResultPath(input.result.skipped, packageJsonPath);
428
+ return;
429
+ }
430
+ const source = await readFile(packageJsonPath, "utf8");
431
+ const manifest = JSON.parse(source);
432
+ let changed = false;
433
+ for (const [dependency, version] of Object.entries(UI_DEPENDENCIES)) {
434
+ if (hasPackageDependency$1(manifest, dependency)) continue;
435
+ manifest.dependencies = {
436
+ ...manifest.dependencies,
437
+ [dependency]: version
438
+ };
439
+ changed = true;
440
+ }
441
+ if (!changed) {
442
+ pushResultPath(input.result.skipped, packageJsonPath);
443
+ return;
444
+ }
445
+ if (!input.dryRun) await writeFile(packageJsonPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
446
+ input.result.packageJson = packageJsonPath;
447
+ pushResultPath(input.result.updated, packageJsonPath);
448
+ }
449
+ const UI_DEPENDENCIES = {
450
+ "class-variance-authority": "^0.7.1",
451
+ clsx: "^2.1.1",
452
+ "tailwind-merge": "^3.3.1",
453
+ tailwindcss: "^4.1.18"
454
+ };
455
+ const SHADCN_THEME_CSS = `@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));
456
+
457
+ @theme inline {
458
+ --color-background: var(--background);
459
+ --color-foreground: var(--foreground);
460
+ --color-card: var(--card);
461
+ --color-card-foreground: var(--card-foreground);
462
+ --color-popover: var(--popover);
463
+ --color-popover-foreground: var(--popover-foreground);
464
+ --color-primary: var(--primary);
465
+ --color-primary-foreground: var(--primary-foreground);
466
+ --color-secondary: var(--secondary);
467
+ --color-secondary-foreground: var(--secondary-foreground);
468
+ --color-muted: var(--muted);
469
+ --color-muted-foreground: var(--muted-foreground);
470
+ --color-accent: var(--accent);
471
+ --color-accent-foreground: var(--accent-foreground);
472
+ --color-destructive: var(--destructive);
473
+ --color-border: var(--border);
474
+ --color-input: var(--input);
475
+ --color-ring: var(--ring);
476
+ --radius-sm: calc(var(--radius) - 4px);
477
+ --radius-md: calc(var(--radius) - 2px);
478
+ --radius-lg: var(--radius);
479
+ }
480
+
481
+ :root,
482
+ [data-theme="light"] {
483
+ --radius: 0.5rem;
484
+ --background: oklch(1 0 0);
485
+ --foreground: oklch(0.145 0 0);
486
+ --card: oklch(1 0 0);
487
+ --card-foreground: oklch(0.145 0 0);
488
+ --popover: oklch(1 0 0);
489
+ --popover-foreground: oklch(0.145 0 0);
490
+ --primary: oklch(0.205 0 0);
491
+ --primary-foreground: oklch(0.985 0 0);
492
+ --secondary: oklch(0.97 0 0);
493
+ --secondary-foreground: oklch(0.205 0 0);
494
+ --muted: oklch(0.97 0 0);
495
+ --muted-foreground: oklch(0.556 0 0);
496
+ --accent: oklch(0.97 0 0);
497
+ --accent-foreground: oklch(0.205 0 0);
498
+ --destructive: oklch(0.577 0.245 27.325);
499
+ --border: oklch(0.922 0 0);
500
+ --input: oklch(0.922 0 0);
501
+ --ring: oklch(0.708 0 0);
502
+ }
503
+
504
+ [data-theme="dark"] {
505
+ --background: oklch(0.145 0 0);
506
+ --foreground: oklch(0.985 0 0);
507
+ --card: oklch(0.205 0 0);
508
+ --card-foreground: oklch(0.985 0 0);
509
+ --popover: oklch(0.205 0 0);
510
+ --popover-foreground: oklch(0.985 0 0);
511
+ --primary: oklch(0.922 0 0);
512
+ --primary-foreground: oklch(0.205 0 0);
513
+ --secondary: oklch(0.269 0 0);
514
+ --secondary-foreground: oklch(0.985 0 0);
515
+ --muted: oklch(0.269 0 0);
516
+ --muted-foreground: oklch(0.708 0 0);
517
+ --accent: oklch(0.269 0 0);
518
+ --accent-foreground: oklch(0.985 0 0);
519
+ --destructive: oklch(0.704 0.191 22.216);
520
+ --border: oklch(1 0 0 / 10%);
521
+ --input: oklch(1 0 0 / 15%);
522
+ --ring: oklch(0.556 0 0);
523
+ }
524
+
525
+ @layer base {
526
+ * {
527
+ @apply border-border outline-ring/50;
528
+ }
529
+
530
+ body {
531
+ @apply bg-background text-foreground;
532
+ }
533
+ }`;
534
+ function createComponentsJson() {
535
+ return {
536
+ $schema: "https://ui.shadcn.com/schema.json",
537
+ style: "new-york",
538
+ rsc: true,
539
+ tsx: true,
540
+ tailwind: {
541
+ config: "",
542
+ css: "src/app/globals.css",
543
+ baseColor: "zinc",
544
+ cssVariables: true
545
+ },
546
+ aliases: {
547
+ components: "@/components",
548
+ utils: "@/lib/utils",
549
+ ui: "@/components/ui",
550
+ lib: "@/lib",
551
+ hooks: "@/hooks"
552
+ },
553
+ registries: { farm: { url: "https://farmjs.dev/r/{name}.json" } }
554
+ };
555
+ }
556
+ function mergeComponentsJson(current, defaults) {
557
+ const aliases = readObject(current.aliases);
558
+ const tailwind = readObject(current.tailwind);
559
+ const registries = readObject(current.registries);
560
+ return {
561
+ ...current,
562
+ $schema: typeof current.$schema === "string" ? current.$schema : defaults.$schema,
563
+ style: typeof current.style === "string" ? current.style : defaults.style,
564
+ rsc: typeof current.rsc === "boolean" ? current.rsc : defaults.rsc,
565
+ tsx: typeof current.tsx === "boolean" ? current.tsx : defaults.tsx,
566
+ tailwind: {
567
+ ...defaults.tailwind,
568
+ ...tailwind
569
+ },
570
+ aliases: {
571
+ ...defaults.aliases,
572
+ ...aliases
573
+ },
574
+ registries: {
575
+ ...registries,
576
+ farm: readObject(registries.farm).url ? registries.farm : defaults.registries.farm
577
+ }
578
+ };
579
+ }
580
+ function shadcnUtilsTemplate() {
581
+ return `import { clsx, type ClassValue } from "clsx";
582
+ import { twMerge } from "tailwind-merge";
583
+
584
+ export function cn(...inputs: ClassValue[]) {
585
+ return twMerge(clsx(inputs));
586
+ }
587
+ `;
588
+ }
589
+ function apiClientTemplate() {
590
+ return `import { createIntegrations } from "@farm.js/core/client";
591
+ import type { AppIntegrations } from "./integrations";
592
+
593
+ export const { api, apiClient } = createIntegrations<AppIntegrations>();
594
+ `;
595
+ }
596
+ function shadcnComponentTemplate(component) {
597
+ switch (component) {
598
+ case "badge": return `import * as React from "react";
599
+ import { cva, type VariantProps } from "class-variance-authority";
600
+ import { cn } from "@/lib/utils";
601
+
602
+ const badgeVariants = cva(
603
+ "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
604
+ {
605
+ variants: {
606
+ variant: {
607
+ default: "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
608
+ secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
609
+ outline: "text-foreground",
610
+ },
611
+ },
612
+ defaultVariants: {
613
+ variant: "default",
614
+ },
615
+ },
616
+ );
617
+
618
+ export interface BadgeProps
619
+ extends React.HTMLAttributes<HTMLDivElement>,
620
+ VariantProps<typeof badgeVariants> {}
621
+
622
+ export function Badge({ className, variant, ...props }: BadgeProps) {
623
+ return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
624
+ }
625
+
626
+ export { badgeVariants };
627
+ `;
628
+ case "button": return `import * as React from "react";
629
+ import { cva, type VariantProps } from "class-variance-authority";
630
+ import { cn } from "@/lib/utils";
631
+
632
+ const buttonVariants = cva(
633
+ "inline-flex h-9 items-center justify-center whitespace-nowrap rounded-md px-4 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
634
+ {
635
+ variants: {
636
+ variant: {
637
+ default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
638
+ secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
639
+ outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
640
+ ghost: "hover:bg-accent hover:text-accent-foreground",
641
+ },
642
+ size: {
643
+ default: "h-9 px-4 py-2",
644
+ sm: "h-8 rounded-md px-3 text-xs",
645
+ lg: "h-10 rounded-md px-8",
646
+ },
647
+ },
648
+ defaultVariants: {
649
+ variant: "default",
650
+ size: "default",
651
+ },
652
+ },
653
+ );
654
+
655
+ export interface ButtonProps
656
+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,
657
+ VariantProps<typeof buttonVariants> {}
658
+
659
+ export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
660
+ ({ className, variant, size, ...props }, ref) => {
661
+ return (
662
+ <button
663
+ className={cn(buttonVariants({ variant, size, className }))}
664
+ ref={ref}
665
+ {...props}
666
+ />
667
+ );
668
+ },
669
+ );
670
+ Button.displayName = "Button";
671
+
672
+ export { buttonVariants };
673
+ `;
674
+ case "card": return `import * as React from "react";
675
+ import { cn } from "@/lib/utils";
676
+
677
+ export const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
678
+ ({ className, ...props }, ref) => (
679
+ <div
680
+ ref={ref}
681
+ className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)}
682
+ {...props}
683
+ />
684
+ ),
685
+ );
686
+ Card.displayName = "Card";
687
+
688
+ export const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
689
+ ({ className, ...props }, ref) => (
690
+ <div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
691
+ ),
692
+ );
693
+ CardHeader.displayName = "CardHeader";
694
+
695
+ export const CardTitle = React.forwardRef<HTMLHeadingElement, React.HTMLAttributes<HTMLHeadingElement>>(
696
+ ({ className, ...props }, ref) => (
697
+ <h3 ref={ref} className={cn("text-2xl font-semibold leading-none tracking-normal", className)} {...props} />
698
+ ),
699
+ );
700
+ CardTitle.displayName = "CardTitle";
701
+
702
+ export const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
703
+ ({ className, ...props }, ref) => (
704
+ <p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
705
+ ),
706
+ );
707
+ CardDescription.displayName = "CardDescription";
708
+
709
+ export const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
710
+ ({ className, ...props }, ref) => (
711
+ <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
712
+ ),
713
+ );
714
+ CardContent.displayName = "CardContent";
715
+
716
+ export const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
717
+ ({ className, ...props }, ref) => (
718
+ <div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
719
+ ),
720
+ );
721
+ CardFooter.displayName = "CardFooter";
722
+ `;
723
+ case "input": return `import * as React from "react";
724
+ import { cn } from "@/lib/utils";
725
+
726
+ export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
727
+
728
+ export const Input = React.forwardRef<HTMLInputElement, InputProps>(
729
+ ({ className, type, ...props }, ref) => (
730
+ <input
731
+ type={type}
732
+ className={cn(
733
+ "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
734
+ className,
735
+ )}
736
+ ref={ref}
737
+ {...props}
738
+ />
739
+ ),
740
+ );
741
+ Input.displayName = "Input";
742
+ `;
743
+ case "label": return `import * as React from "react";
744
+ import { cn } from "@/lib/utils";
745
+
746
+ export const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLLabelElement>>(
747
+ ({ className, ...props }, ref) => (
748
+ <label
749
+ ref={ref}
750
+ className={cn("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70", className)}
751
+ {...props}
752
+ />
753
+ ),
754
+ );
755
+ Label.displayName = "Label";
756
+ `;
757
+ }
758
+ }
759
+ function billingPricingTemplate(input) {
760
+ return `"use client";
761
+
762
+ import * as React from "react";
763
+ import { Badge } from "@/components/ui/badge";
764
+ import { Button } from "@/components/ui/button";
765
+ import {
766
+ Card,
767
+ CardContent,
768
+ CardDescription,
769
+ CardFooter,
770
+ CardHeader,
771
+ CardTitle,
772
+ } from "@/components/ui/card";
773
+ import { apiClient } from "@/lib/api";
774
+
775
+ type BillingProduct = NonNullable<Awaited<ReturnType<typeof apiClient.${input.key}.products>>["data"]>[number];
776
+
777
+ export function ${input.componentName}() {
778
+ const [products, setProducts] = React.useState<BillingProduct[]>([]);
779
+ const [loading, setLoading] = React.useState(true);
780
+ const [checkingOut, setCheckingOut] = React.useState<string | null>(null);
781
+ const [error, setError] = React.useState<string | null>(null);
782
+
783
+ React.useEffect(() => {
784
+ let active = true;
785
+
786
+ async function loadProducts() {
787
+ setLoading(true);
788
+ setError(null);
789
+
790
+ try {
791
+ const response = await apiClient.${input.key}.products();
792
+ if (response.error) {
793
+ throw new Error(readErrorMessage(response.error, "${input.label} request failed."));
794
+ }
795
+
796
+ if (active) {
797
+ setProducts(Array.from(response.data ?? []));
798
+ }
799
+ } catch (cause) {
800
+ if (active) {
801
+ setError(cause instanceof Error ? cause.message : "Could not load ${input.label} products.");
802
+ }
803
+ } finally {
804
+ if (active) {
805
+ setLoading(false);
806
+ }
807
+ }
808
+ }
809
+
810
+ void loadProducts();
811
+
812
+ return () => {
813
+ active = false;
814
+ };
815
+ }, []);
816
+
817
+ async function startCheckout(product: BillingProduct) {
818
+ const productId = String(readProductField(product, "id") ?? "");
819
+ if (!productId) {
820
+ setError("This Stripe product is missing an id.");
821
+ return;
822
+ }
823
+
824
+ setCheckingOut(productId);
825
+ setError(null);
826
+
827
+ try {
828
+ const response = await apiClient.${input.key}.checkout({
829
+ body: {
830
+ productId,
831
+ successPath: "/billing/success",
832
+ cancelPath: "/integrations/${input.provider}",
833
+ },
834
+ });
835
+ if (response.error) {
836
+ throw new Error(readErrorMessage(response.error, "${input.label} checkout failed."));
837
+ }
838
+
839
+ const redirectTo = response.data?.redirectTo;
840
+ if (!redirectTo) {
841
+ throw new Error("${input.label} checkout did not return a redirect URL.");
842
+ }
843
+
844
+ window.location.assign(redirectTo);
845
+ } catch (cause) {
846
+ setError(cause instanceof Error ? cause.message : "Could not start ${input.label} checkout.");
847
+ setCheckingOut(null);
848
+ }
849
+ }
850
+
851
+ return (
852
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
853
+ <section className="mx-auto flex w-full max-w-5xl flex-col gap-8">
854
+ <div className="max-w-2xl space-y-3">
855
+ <Badge variant="secondary">${input.label}</Badge>
856
+ <h1 className="text-3xl font-semibold tracking-normal">${input.label} billing</h1>
857
+ <p className="text-sm leading-6 text-muted-foreground">
858
+ Plans, checkout, and customer billing actions in one place.
859
+ </p>
860
+ </div>
861
+
862
+ {error ? (
863
+ <div className="rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
864
+ {error}
865
+ </div>
866
+ ) : null}
867
+
868
+ {loading ? (
869
+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
870
+ {Array.from({ length: 3 }).map((_, index) => (
871
+ <Card key={index} className="min-h-[220px] animate-pulse" />
872
+ ))}
873
+ </div>
874
+ ) : products.length ? (
875
+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
876
+ {products.map((product) => {
877
+ const productId = String(readProductField(product, "id") ?? "");
878
+ const fallbackName = productId || "Product";
879
+ const name = String(readProductField(product, "name") ?? fallbackName);
880
+ const description =
881
+ readProductField(product, "description") ?? "Connected to your Stripe catalog.";
882
+
883
+ return (
884
+ <Card key={productId || name} className="flex min-h-[260px] flex-col">
885
+ <CardHeader>
886
+ <CardTitle className="text-xl">{name}</CardTitle>
887
+ <CardDescription>{String(description)}</CardDescription>
888
+ </CardHeader>
889
+ <CardContent className="flex-1">
890
+ <div className="text-3xl font-semibold">{formatProductPrice(product)}</div>
891
+ </CardContent>
892
+ <CardFooter>
893
+ <Button
894
+ className="w-full"
895
+ disabled={!productId || checkingOut === productId}
896
+ onClick={() => void startCheckout(product)}
897
+ >
898
+ {checkingOut === productId ? "Starting checkout..." : "Checkout"}
899
+ </Button>
900
+ </CardFooter>
901
+ </Card>
902
+ );
903
+ })}
904
+ </div>
905
+ ) : (
906
+ <Card>
907
+ <CardHeader>
908
+ <CardTitle>No products yet</CardTitle>
909
+ <CardDescription>
910
+ Add products to the generated ${input.label} integration template or provider dashboard.
911
+ </CardDescription>
912
+ </CardHeader>
913
+ </Card>
914
+ )}
915
+ </section>
916
+ </main>
917
+ );
918
+ }
919
+
920
+ function readProductField(product: BillingProduct, field: string) {
921
+ return (product as Record<string, unknown>)[field];
922
+ }
923
+
924
+ function formatProductPrice(product: BillingProduct) {
925
+ const amount = readProductField(product, "amount") ?? readProductField(product, "unitAmount");
926
+ const currency = String(readProductField(product, "currency") ?? "USD").toUpperCase();
927
+ const interval = readProductField(product, "interval");
928
+
929
+ if (typeof amount === "number" && Number.isFinite(amount)) {
930
+ const formatted = new Intl.NumberFormat("en", {
931
+ style: "currency",
932
+ currency,
933
+ }).format(amount / 100);
934
+
935
+ return interval ? \`\${formatted}/\${String(interval)}\` : formatted;
936
+ }
937
+
938
+ return "Custom";
939
+ }
940
+
941
+ function readErrorMessage(error: unknown, fallback: string) {
942
+ if (error && typeof error === "object" && "message" in error) {
943
+ return String((error as { message?: unknown }).message);
944
+ }
945
+
946
+ return fallback;
947
+ }
948
+ `;
949
+ }
950
+ function aiChatTemplate() {
951
+ return `"use client";
952
+
953
+ import * as React from "react";
954
+ import { Badge } from "@/components/ui/badge";
955
+ import { Button } from "@/components/ui/button";
956
+ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
957
+ import { Input } from "@/components/ui/input";
958
+
959
+ type ChatMessage = {
960
+ role: "user" | "assistant";
961
+ content: string;
962
+ };
963
+
964
+ export function AIChat() {
965
+ const [messages, setMessages] = React.useState<ChatMessage[]>([]);
966
+ const [input, setInput] = React.useState("");
967
+ const [pending, setPending] = React.useState(false);
968
+ const [error, setError] = React.useState<string | null>(null);
969
+
970
+ async function sendMessage(event: React.FormEvent<HTMLFormElement>) {
971
+ event.preventDefault();
972
+ const nextInput = input.trim();
973
+ if (!nextInput) {
974
+ return;
975
+ }
976
+
977
+ const nextMessages: ChatMessage[] = [...messages, { role: "user", content: nextInput }];
978
+ setMessages(nextMessages);
979
+ setInput("");
980
+ setPending(true);
981
+ setError(null);
982
+
983
+ try {
984
+ const response = await fetch("/api/chat", {
985
+ method: "POST",
986
+ headers: {
987
+ "content-type": "application/json",
988
+ },
989
+ body: JSON.stringify({
990
+ messages: nextMessages.map((message) => ({
991
+ role: message.role,
992
+ parts: [{ type: "text", text: message.content }],
993
+ })),
994
+ }),
995
+ });
996
+
997
+ const text = await response.text();
998
+ if (!response.ok) {
999
+ throw new Error(text || "AI request failed.");
1000
+ }
1001
+
1002
+ setMessages([...nextMessages, { role: "assistant", content: text || "Done." }]);
1003
+ } catch (cause) {
1004
+ setError(cause instanceof Error ? cause.message : "AI request failed.");
1005
+ } finally {
1006
+ setPending(false);
1007
+ }
1008
+ }
1009
+
1010
+ return (
1011
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1012
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1013
+ <div className="space-y-3">
1014
+ <Badge variant="secondary">AI</Badge>
1015
+ <h1 className="text-3xl font-semibold tracking-normal">Chat</h1>
1016
+ </div>
1017
+
1018
+ <Card>
1019
+ <CardHeader>
1020
+ <CardTitle className="text-xl">Conversation</CardTitle>
1021
+ </CardHeader>
1022
+ <CardContent className="space-y-4">
1023
+ <div className="min-h-[320px] space-y-3 rounded-md border bg-muted/30 p-4">
1024
+ {messages.length ? (
1025
+ messages.map((message, index) => (
1026
+ <div
1027
+ key={index}
1028
+ className={message.role === "user" ? "ml-auto max-w-[85%] rounded-md bg-primary px-3 py-2 text-sm text-primary-foreground" : "max-w-[85%] rounded-md bg-background px-3 py-2 text-sm"}
1029
+ >
1030
+ {message.content}
1031
+ </div>
1032
+ ))
1033
+ ) : (
1034
+ <p className="text-sm text-muted-foreground">Start a conversation.</p>
1035
+ )}
1036
+ </div>
1037
+
1038
+ {error ? <p className="text-sm text-destructive">{error}</p> : null}
1039
+
1040
+ <form className="flex gap-2" onSubmit={sendMessage}>
1041
+ <Input
1042
+ value={input}
1043
+ onChange={(event) => setInput(event.target.value)}
1044
+ placeholder="Ask something..."
1045
+ />
1046
+ <Button disabled={pending} type="submit">
1047
+ {pending ? "Sending..." : "Send"}
1048
+ </Button>
1049
+ </form>
1050
+ </CardContent>
1051
+ </Card>
1052
+ </section>
1053
+ </main>
1054
+ );
1055
+ }
1056
+ `;
1057
+ }
1058
+ function supabaseAuthTemplate(key) {
1059
+ return `"use client";
1060
+
1061
+ import * as React from "react";
1062
+ import { Badge } from "@/components/ui/badge";
1063
+ import { Button } from "@/components/ui/button";
1064
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1065
+ import { Input } from "@/components/ui/input";
1066
+ import { Label } from "@/components/ui/label";
1067
+ import { apiClient } from "@/lib/api";
1068
+
1069
+ export function SupabaseAuthPanel() {
1070
+ const [email, setEmail] = React.useState("");
1071
+ const [password, setPassword] = React.useState("");
1072
+ const [mode, setMode] = React.useState<"login" | "signup">("login");
1073
+ const [pending, setPending] = React.useState(false);
1074
+ const [status, setStatus] = React.useState<string | null>(null);
1075
+
1076
+ async function submit(event: React.FormEvent<HTMLFormElement>) {
1077
+ event.preventDefault();
1078
+ setPending(true);
1079
+ setStatus(null);
1080
+
1081
+ const response =
1082
+ mode === "login"
1083
+ ? await apiClient.${key}.login.post({ body: { email, password, returnTo: "/dashboard" } })
1084
+ : await apiClient.${key}.signup.post({ body: { email, password, returnTo: "/dashboard" } });
1085
+
1086
+ if (response.error) {
1087
+ setStatus(response.error.message);
1088
+ setPending(false);
1089
+ return;
1090
+ }
1091
+
1092
+ if (response.data?.redirectTo) {
1093
+ window.location.assign(response.data.redirectTo);
1094
+ return;
1095
+ }
1096
+
1097
+ setStatus(response.data?.message ?? "Check your email to continue.");
1098
+ setPending(false);
1099
+ }
1100
+
1101
+ async function loadSession() {
1102
+ const response = await apiClient.${key}.session.get();
1103
+ setStatus(response.error ? response.error.message : response.data?.authenticated ? "Authenticated" : "No active session");
1104
+ }
1105
+
1106
+ async function logout() {
1107
+ const response = await fetch("/auth/logout", {
1108
+ method: "POST",
1109
+ headers: { "content-type": "application/json" },
1110
+ body: JSON.stringify({ returnTo: "/" }),
1111
+ });
1112
+ const data = (await response.json()) as { redirectTo?: string; error?: string };
1113
+ if (data.redirectTo) {
1114
+ window.location.assign(data.redirectTo);
1115
+ return;
1116
+ }
1117
+ setStatus(data.error ?? "Signed out");
1118
+ }
1119
+
1120
+ return (
1121
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1122
+ <section className="mx-auto flex w-full max-w-xl flex-col gap-6">
1123
+ <div className="space-y-3">
1124
+ <Badge variant="secondary">Supabase</Badge>
1125
+ <h1 className="text-3xl font-semibold tracking-normal">Auth</h1>
1126
+ </div>
1127
+
1128
+ <Card>
1129
+ <CardHeader>
1130
+ <CardTitle className="text-xl">{mode === "login" ? "Sign in" : "Create account"}</CardTitle>
1131
+ <CardDescription>Email and password access for this app.</CardDescription>
1132
+ </CardHeader>
1133
+ <CardContent>
1134
+ <form className="space-y-4" onSubmit={submit}>
1135
+ <div className="space-y-2">
1136
+ <Label htmlFor="email">Email</Label>
1137
+ <Input id="email" value={email} onChange={(event) => setEmail(event.target.value)} type="email" />
1138
+ </div>
1139
+ <div className="space-y-2">
1140
+ <Label htmlFor="password">Password</Label>
1141
+ <Input id="password" value={password} onChange={(event) => setPassword(event.target.value)} type="password" />
1142
+ </div>
1143
+ {status ? <p className="text-sm text-muted-foreground">{status}</p> : null}
1144
+ <div className="flex flex-wrap gap-2">
1145
+ <Button disabled={pending} type="submit">{pending ? "Working..." : mode === "login" ? "Sign in" : "Sign up"}</Button>
1146
+ <Button type="button" variant="outline" onClick={() => setMode(mode === "login" ? "signup" : "login")}>
1147
+ {mode === "login" ? "Use sign up" : "Use sign in"}
1148
+ </Button>
1149
+ <Button type="button" variant="ghost" onClick={() => void loadSession()}>Session</Button>
1150
+ <Button type="button" variant="ghost" onClick={() => void logout()}>Logout</Button>
1151
+ </div>
1152
+ </form>
1153
+ </CardContent>
1154
+ </Card>
1155
+ </section>
1156
+ </main>
1157
+ );
1158
+ }
1159
+ `;
1160
+ }
1161
+ function hostedAuthTemplate(input) {
1162
+ return `"use client";
1163
+
1164
+ import * as React from "react";
1165
+ import { Badge } from "@/components/ui/badge";
1166
+ import { Button } from "@/components/ui/button";
1167
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1168
+ import { apiClient } from "@/lib/api";
1169
+
1170
+ export function ${input.componentName}() {
1171
+ const [status, setStatus] = React.useState<string>("Idle");
1172
+ const [pending, setPending] = React.useState(false);
1173
+
1174
+ async function refreshStatus() {
1175
+ setPending(true);
1176
+ const response = await apiClient.${input.key}.${input.statusCall}.${input.statusMethod}();
1177
+ if (response.error) {
1178
+ setStatus(response.error.message);
1179
+ } else {
1180
+ setStatus(response.data?.authenticated ? "Authenticated" : "No active session");
1181
+ }
1182
+ setPending(false);
1183
+ }
1184
+
1185
+ async function logout() {
1186
+ setPending(true);
1187
+ const response = await apiClient.${input.key}.${input.logoutCall}.${input.logoutMethod}();
1188
+ if (response.data?.redirectTo) {
1189
+ window.location.assign(response.data.redirectTo);
1190
+ return;
1191
+ }
1192
+ setStatus(response.error?.message ?? "Signed out");
1193
+ setPending(false);
1194
+ }
1195
+
1196
+ return (
1197
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1198
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1199
+ <div className="space-y-3">
1200
+ <Badge variant="secondary">${input.provider}</Badge>
1201
+ <h1 className="text-3xl font-semibold tracking-normal">Auth</h1>
1202
+ </div>
1203
+
1204
+ <Card>
1205
+ <CardHeader>
1206
+ <CardTitle className="text-xl">${input.provider} session</CardTitle>
1207
+ <CardDescription>Hosted auth, account session, and sign-out controls.</CardDescription>
1208
+ </CardHeader>
1209
+ <CardContent className="space-y-4">
1210
+ <p className="rounded-md border bg-muted/30 px-3 py-2 text-sm">{status}</p>
1211
+ <div className="flex flex-wrap gap-2">
1212
+ <Button type="button" onClick={() => window.location.assign("${input.loginHref}")}>Sign in</Button>
1213
+ <Button type="button" variant="outline" onClick={() => window.location.assign("${input.signupHref}")}>Sign up</Button>
1214
+ <Button type="button" variant="ghost" disabled={pending} onClick={() => void refreshStatus()}>Refresh</Button>
1215
+ <Button type="button" variant="ghost" disabled={pending} onClick={() => void logout()}>Logout</Button>
1216
+ </div>
1217
+ </CardContent>
1218
+ </Card>
1219
+ </section>
1220
+ </main>
1221
+ );
1222
+ }
1223
+ `;
1224
+ }
1225
+ function authRouteShellTemplate(input) {
1226
+ return `"use client";
1227
+
1228
+ import { Badge } from "@/components/ui/badge";
1229
+ import { Button } from "@/components/ui/button";
1230
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1231
+
1232
+ export function ${input.componentName}() {
1233
+ return (
1234
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1235
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1236
+ <div className="space-y-3">
1237
+ <Badge variant="secondary">${input.provider}</Badge>
1238
+ <h1 className="text-3xl font-semibold tracking-normal">Auth</h1>
1239
+ </div>
1240
+
1241
+ <Card>
1242
+ <CardHeader>
1243
+ <CardTitle className="text-xl">${input.provider} routes</CardTitle>
1244
+ <CardDescription>Account entry points and session route.</CardDescription>
1245
+ </CardHeader>
1246
+ <CardContent className="flex flex-wrap gap-2">
1247
+ <Button type="button" onClick={() => window.location.assign("${input.signInHref}")}>Sign in</Button>
1248
+ <Button type="button" variant="outline" onClick={() => window.location.assign("${input.signUpHref}")}>Sign up</Button>
1249
+ <Button type="button" variant="ghost" onClick={() => window.location.assign("${input.sessionHref}")}>Session</Button>
1250
+ </CardContent>
1251
+ </Card>
1252
+ </section>
1253
+ </main>
1254
+ );
1255
+ }
1256
+ `;
1257
+ }
1258
+ function betterAuthClientTemplate() {
1259
+ return `import { createAuthClient } from "better-auth/react";
1260
+
1261
+ export const authClient = createAuthClient({
1262
+ baseURL: "",
1263
+ });
1264
+ `;
1265
+ }
1266
+ function betterAuthPanelTemplate() {
1267
+ return `"use client";
1268
+
1269
+ import * as React from "react";
1270
+ import { Badge } from "@/components/ui/badge";
1271
+ import { Button } from "@/components/ui/button";
1272
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1273
+ import { Input } from "@/components/ui/input";
1274
+ import { Label } from "@/components/ui/label";
1275
+ import { authClient } from "@/lib/auth-client";
1276
+
1277
+ type Mode = "sign-in" | "sign-up";
1278
+
1279
+ export function BetterAuthPanel() {
1280
+ const [mode, setMode] = React.useState<Mode>("sign-in");
1281
+ const [pending, setPending] = React.useState(false);
1282
+ const [message, setMessage] = React.useState("Ready");
1283
+ const [sessionEmail, setSessionEmail] = React.useState<string | null>(null);
1284
+
1285
+ async function submit(event: React.FormEvent<HTMLFormElement>) {
1286
+ event.preventDefault();
1287
+ setPending(true);
1288
+ setMessage(mode === "sign-in" ? "Signing in…" : "Creating account…");
1289
+
1290
+ const form = new FormData(event.currentTarget);
1291
+ const email = String(form.get("email") || "");
1292
+ const password = String(form.get("password") || "");
1293
+ const name = String(form.get("name") || "");
1294
+ try {
1295
+ const response =
1296
+ mode === "sign-in"
1297
+ ? await authClient.signIn.email({ email, password })
1298
+ : await authClient.signUp.email({ email, password, name });
1299
+
1300
+ if (response.error) {
1301
+ setMessage(response.error.message || "Authentication failed.");
1302
+ return;
1303
+ }
1304
+
1305
+ setSessionEmail(email);
1306
+ setMessage(mode === "sign-in" ? "Signed in." : "Account created.");
1307
+ } catch (cause) {
1308
+ setMessage(cause instanceof Error ? cause.message : "Could not reach the auth server.");
1309
+ } finally {
1310
+ setPending(false);
1311
+ }
1312
+ }
1313
+
1314
+ async function refreshSession() {
1315
+ setPending(true);
1316
+ try {
1317
+ const response = await authClient.getSession();
1318
+ setSessionEmail(response.data?.user.email || null);
1319
+ setMessage(response.error?.message || (response.data ? "Session active." : "No active session."));
1320
+ } catch (cause) {
1321
+ setMessage(cause instanceof Error ? cause.message : "Could not read the session.");
1322
+ } finally {
1323
+ setPending(false);
1324
+ }
1325
+ }
1326
+
1327
+ async function signOut() {
1328
+ setPending(true);
1329
+ try {
1330
+ const response = await authClient.signOut();
1331
+ if (response.error) {
1332
+ setMessage(response.error.message || "Could not sign out.");
1333
+ return;
1334
+ }
1335
+ setSessionEmail(null);
1336
+ setMessage("Signed out.");
1337
+ } catch (cause) {
1338
+ setMessage(cause instanceof Error ? cause.message : "Could not reach the auth server.");
1339
+ } finally {
1340
+ setPending(false);
1341
+ }
1342
+ }
1343
+
1344
+ return (
1345
+ <main className="min-h-screen bg-background px-5 py-12 text-foreground sm:px-8">
1346
+ <section className="mx-auto grid w-full max-w-5xl gap-8 lg:grid-cols-[1fr_420px] lg:items-start">
1347
+ <div className="space-y-5 py-4">
1348
+ <Badge variant="secondary">Better Auth × Farm.js</Badge>
1349
+ <div className="space-y-3">
1350
+ <h1 className="max-w-xl text-4xl font-semibold tracking-tight sm:text-5xl">
1351
+ Authentication that starts ready.
1352
+ </h1>
1353
+ <p className="max-w-xl text-base leading-7 text-muted-foreground">
1354
+ Test account creation, email sign-in, session reads, and sign-out through Farm’s
1355
+ generated Better Auth integration.
1356
+ </p>
1357
+ </div>
1358
+ <div aria-live="polite" className="border-l-2 border-primary pl-4 text-sm">
1359
+ <p className="font-medium">{message}</p>
1360
+ <p className="mt-1 text-muted-foreground">
1361
+ {sessionEmail ? \`Signed in as \${sessionEmail}\` : "No authenticated user"}
1362
+ </p>
1363
+ </div>
1364
+ </div>
1365
+
1366
+ <Card>
1367
+ <CardHeader>
1368
+ <CardTitle>{mode === "sign-in" ? "Welcome back" : "Create an account"}</CardTitle>
1369
+ <CardDescription>
1370
+ {mode === "sign-in"
1371
+ ? "Enter your credentials to start a secure session."
1372
+ : "Use an email and password to create your local account."}
1373
+ </CardDescription>
1374
+ </CardHeader>
1375
+ <CardContent>
1376
+ <form className="space-y-4" onSubmit={submit}>
1377
+ {mode === "sign-up" ? (
1378
+ <div className="space-y-2">
1379
+ <Label htmlFor="name">Name</Label>
1380
+ <Input autoComplete="name" id="name" name="name" required />
1381
+ </div>
1382
+ ) : null}
1383
+ <div className="space-y-2">
1384
+ <Label htmlFor="email">Email</Label>
1385
+ <Input autoComplete="email" id="email" name="email" required type="email" />
1386
+ </div>
1387
+ <div className="space-y-2">
1388
+ <Label htmlFor="password">Password</Label>
1389
+ <Input
1390
+ autoComplete={mode === "sign-in" ? "current-password" : "new-password"}
1391
+ id="password"
1392
+ minLength={8}
1393
+ name="password"
1394
+ required
1395
+ type="password"
1396
+ />
1397
+ </div>
1398
+ <Button className="w-full" disabled={pending} type="submit">
1399
+ {pending ? "Working…" : mode === "sign-in" ? "Sign in" : "Create account"}
1400
+ </Button>
1401
+ </form>
1402
+
1403
+ <div className="mt-4 grid gap-2 sm:grid-cols-2">
1404
+ <Button
1405
+ disabled={pending}
1406
+ type="button"
1407
+ variant="outline"
1408
+ onClick={() => {
1409
+ setMode(mode === "sign-in" ? "sign-up" : "sign-in");
1410
+ setMessage("Ready");
1411
+ }}
1412
+ >
1413
+ {mode === "sign-in" ? "Create account" : "Use sign in"}
1414
+ </Button>
1415
+ <Button disabled={pending} type="button" variant="outline" onClick={() => void refreshSession()}>
1416
+ Check session
1417
+ </Button>
1418
+ </div>
1419
+ <Button
1420
+ className="mt-2 w-full"
1421
+ disabled={pending || !sessionEmail}
1422
+ type="button"
1423
+ variant="ghost"
1424
+ onClick={() => void signOut()}
1425
+ >
1426
+ Sign out
1427
+ </Button>
1428
+ </CardContent>
1429
+ </Card>
1430
+ </section>
1431
+ </main>
1432
+ );
1433
+ }
1434
+ `;
1435
+ }
1436
+ function resendEmailTemplate(key) {
1437
+ return `"use client";
1438
+
1439
+ import * as React from "react";
1440
+ import { Badge } from "@/components/ui/badge";
1441
+ import { Button } from "@/components/ui/button";
1442
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1443
+ import { Input } from "@/components/ui/input";
1444
+ import { Label } from "@/components/ui/label";
1445
+ import { apiClient } from "@/lib/api";
1446
+
1447
+ export function ResendEmailConsole() {
1448
+ const [to, setTo] = React.useState("");
1449
+ const [name, setName] = React.useState("Ada");
1450
+ const templateId = "welcome" as const;
1451
+ const [status, setStatus] = React.useState("Idle");
1452
+ const [previewHtml, setPreviewHtml] = React.useState("");
1453
+
1454
+ async function loadTemplates() {
1455
+ const response = await apiClient.${key}.templates();
1456
+ const templates = Array.isArray(response.data)
1457
+ ? (response.data as Array<{ id: string }>)
1458
+ : [];
1459
+ setStatus(response.error ? response.error.message : "Templates: " + templates.map((item) => item.id).join(", "));
1460
+ }
1461
+
1462
+ async function preview() {
1463
+ const response = await apiClient.${key}.preview({
1464
+ body: {
1465
+ templateId,
1466
+ data: { name },
1467
+ },
1468
+ });
1469
+ if (response.error) {
1470
+ setStatus(response.error.message);
1471
+ return;
1472
+ }
1473
+ setPreviewHtml(response.data?.html ?? "");
1474
+ setStatus(response.data?.subject ?? "Preview loaded");
1475
+ }
1476
+
1477
+ async function send() {
1478
+ const response = await apiClient.${key}.send({
1479
+ body: {
1480
+ templateId,
1481
+ to,
1482
+ data: { name },
1483
+ },
1484
+ });
1485
+ setStatus(response.error ? response.error.message : "Sent " + (response.data?.id ?? "email"));
1486
+ }
1487
+
1488
+ return (
1489
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1490
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1491
+ <div className="space-y-3">
1492
+ <Badge variant="secondary">Resend</Badge>
1493
+ <h1 className="text-3xl font-semibold tracking-normal">Email console</h1>
1494
+ </div>
1495
+ <Card>
1496
+ <CardHeader>
1497
+ <CardTitle className="text-xl">Send template</CardTitle>
1498
+ <CardDescription>Template previews and delivery controls.</CardDescription>
1499
+ </CardHeader>
1500
+ <CardContent className="space-y-4">
1501
+ <div className="grid gap-4 sm:grid-cols-2">
1502
+ <div className="space-y-2">
1503
+ <Label htmlFor="to">To</Label>
1504
+ <Input id="to" value={to} onChange={(event) => setTo(event.target.value)} />
1505
+ </div>
1506
+ <div className="space-y-2">
1507
+ <Label htmlFor="name">Name</Label>
1508
+ <Input id="name" value={name} onChange={(event) => setName(event.target.value)} />
1509
+ </div>
1510
+ </div>
1511
+ <p className="rounded-md border bg-muted/30 px-3 py-2 text-sm">{status}</p>
1512
+ {previewHtml ? <div className="max-h-64 overflow-auto rounded-md border p-3 text-sm" dangerouslySetInnerHTML={{ __html: previewHtml }} /> : null}
1513
+ <div className="flex flex-wrap gap-2">
1514
+ <Button type="button" variant="outline" onClick={() => void loadTemplates()}>Templates</Button>
1515
+ <Button type="button" variant="outline" onClick={() => void preview()}>Preview</Button>
1516
+ <Button type="button" onClick={() => void send()}>Send</Button>
1517
+ </div>
1518
+ </CardContent>
1519
+ </Card>
1520
+ </section>
1521
+ </main>
1522
+ );
1523
+ }
1524
+ `;
1525
+ }
1526
+ function jobsConsoleTemplate(key, label, provider) {
1527
+ return `"use client";
1528
+
1529
+ import * as React from "react";
1530
+ import { Badge } from "@/components/ui/badge";
1531
+ import { Button } from "@/components/ui/button";
1532
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1533
+ import { Input } from "@/components/ui/input";
1534
+ import { Label } from "@/components/ui/label";
1535
+ import { apiClient } from "@/lib/api";
1536
+
1537
+ type JobTask = {
1538
+ key: string;
1539
+ description?: string | null;
1540
+ };
1541
+
1542
+ export function ${`${pascalCase(provider)}JobsConsole`}() {
1543
+ const [tasks, setTasks] = React.useState<JobTask[]>([]);
1544
+ const [taskKey, setTaskKey] = React.useState("");
1545
+ const [runId, setRunId] = React.useState("");
1546
+ const [status, setStatus] = React.useState("Idle");
1547
+
1548
+ async function loadTasks() {
1549
+ const response = await apiClient.${key}.tasks.list();
1550
+ if (response.error) {
1551
+ setStatus(response.error.message);
1552
+ return;
1553
+ }
1554
+ const nextTasks = Array.from(response.data ?? []);
1555
+ setTasks(nextTasks);
1556
+ setTaskKey(nextTasks[0]?.key ?? "");
1557
+ setStatus(nextTasks.length ? "Tasks loaded" : "No tasks registered yet");
1558
+ }
1559
+
1560
+ async function triggerTask() {
1561
+ const task = (apiClient.${key} as Record<string, any>)[taskKey];
1562
+ if (!task?.trigger) {
1563
+ setStatus("Select a task first.");
1564
+ return;
1565
+ }
1566
+ const response = await task.trigger({ body: { input: {} } });
1567
+ setStatus(response.error ? response.error.message : "Triggered " + (response.data?.runId ?? response.data?.id ?? taskKey));
1568
+ }
1569
+
1570
+ async function checkStatus() {
1571
+ const task = (apiClient.${key} as Record<string, any>)[taskKey];
1572
+ if (!task?.status || !runId) {
1573
+ setStatus("Enter a task and run id.");
1574
+ return;
1575
+ }
1576
+ const response = await task.status({ query: { runId } });
1577
+ setStatus(response.error ? response.error.message : JSON.stringify(response.data));
1578
+ }
1579
+
1580
+ return (
1581
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1582
+ <section className="mx-auto flex w-full max-w-4xl flex-col gap-6">
1583
+ <div className="space-y-3">
1584
+ <Badge variant="secondary">${label}</Badge>
1585
+ <h1 className="text-3xl font-semibold tracking-normal">Jobs console</h1>
1586
+ </div>
1587
+ <Card>
1588
+ <CardHeader>
1589
+ <CardTitle className="text-xl">Tasks</CardTitle>
1590
+ <CardDescription>Task runs and status checks.</CardDescription>
1591
+ </CardHeader>
1592
+ <CardContent className="space-y-4">
1593
+ <div className="grid gap-4 sm:grid-cols-2">
1594
+ <div className="space-y-2">
1595
+ <Label htmlFor="taskKey">Task key</Label>
1596
+ <Input id="taskKey" value={taskKey} onChange={(event) => setTaskKey(event.target.value)} />
1597
+ </div>
1598
+ <div className="space-y-2">
1599
+ <Label htmlFor="runId">Run id</Label>
1600
+ <Input id="runId" value={runId} onChange={(event) => setRunId(event.target.value)} />
1601
+ </div>
1602
+ </div>
1603
+ <p className="rounded-md border bg-muted/30 px-3 py-2 text-sm">{status}</p>
1604
+ <div className="flex flex-wrap gap-2">
1605
+ <Button type="button" variant="outline" onClick={() => void loadTasks()}>Load tasks</Button>
1606
+ <Button type="button" onClick={() => void triggerTask()}>Trigger</Button>
1607
+ <Button type="button" variant="ghost" onClick={() => void checkStatus()}>Status</Button>
1608
+ </div>
1609
+ {tasks.length ? (
1610
+ <div className="grid gap-2">
1611
+ {tasks.map((task) => (
1612
+ <button key={task.key} className="rounded-md border px-3 py-2 text-left text-sm" onClick={() => setTaskKey(task.key)} type="button">
1613
+ {task.key}
1614
+ </button>
1615
+ ))}
1616
+ </div>
1617
+ ) : null}
1618
+ </CardContent>
1619
+ </Card>
1620
+ </section>
1621
+ </main>
1622
+ );
1623
+ }
1624
+ `;
1625
+ }
1626
+ function unkeyApiKeysTemplate() {
1627
+ return `import { Badge } from "@/components/ui/badge";
1628
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1629
+
1630
+ export function UnkeyApiKeysConsole() {
1631
+ return (
1632
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1633
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1634
+ <div className="space-y-3">
1635
+ <Badge variant="secondary">Unkey</Badge>
1636
+ <h1 className="text-3xl font-semibold tracking-normal">API keys</h1>
1637
+ </div>
1638
+ <Card>
1639
+ <CardHeader>
1640
+ <CardTitle className="text-xl">Protected API</CardTitle>
1641
+ <CardDescription>Requests are verified by Unkey before the route runs.</CardDescription>
1642
+ </CardHeader>
1643
+ <CardContent className="space-y-3">
1644
+ <code className="block overflow-x-auto rounded-md border bg-muted/30 p-3 text-xs">
1645
+ curl http://localhost:3000/api/protected -H &quot;Authorization: Bearer YOUR_KEY&quot;
1646
+ </code>
1647
+ <p className="text-sm text-muted-foreground">
1648
+ Create and rotate keys from trusted server code or the Unkey dashboard.
1649
+ </p>
1650
+ </CardContent>
1651
+ </Card>
1652
+ </section>
1653
+ </main>
1654
+ );
1655
+ }
1656
+ `;
1657
+ }
1658
+ function unkeyProtectedRouteTemplate() {
1659
+ return `export function GET() {
1660
+ return Response.json({
1661
+ ok: true,
1662
+ message: "Valid Unkey API key.",
1663
+ });
1664
+ }
1665
+ `;
1666
+ }
1667
+ function pascalCase(input) {
1668
+ return input.split(/[^A-Za-z0-9]+/g).filter(Boolean).map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`).join("");
1669
+ }
1670
+ function kebabCase(input) {
1671
+ return input.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[^A-Za-z0-9]+/g, "-").replace(/^-+|-+$/g, "").toLowerCase();
1672
+ }
1673
+ function hasPackageDependency$1(manifest, dependency) {
1674
+ return dependency in (manifest.dependencies || {}) || dependency in (manifest.devDependencies || {}) || dependency in (manifest.peerDependencies || {}) || dependency in (manifest.optionalDependencies || {});
1675
+ }
1676
+ function readObject(value) {
1677
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1678
+ }
1679
+ function pushResultPath(list, filePath) {
1680
+ if (!list.includes(filePath)) list.push(filePath);
1681
+ }
1682
+ //#endregion
1683
+ //#region ../farm-cli/src/add-integration.ts
1684
+ const PROVIDERS = [
1685
+ {
1686
+ provider: "ai",
1687
+ aliases: [
1688
+ "ai-sdk",
1689
+ "vercel-ai",
1690
+ "vercel-ai-sdk",
1691
+ "chat"
1692
+ ],
1693
+ defaultKey: "chat",
1694
+ packageName: "@farm.js/ai",
1695
+ fileName: "chat",
1696
+ exportName: "POST",
1697
+ description: "Vercel AI SDK chat route",
1698
+ env: ["AI_GATEWAY_API_KEY"],
1699
+ notes: [
1700
+ "Use @ai-sdk/react useChat with api: \"/api/chat\" on the client.",
1701
+ "Replace model with any AI SDK provider model or Vercel AI Gateway model id.",
1702
+ "No farm.config integration wiring is required for this route."
1703
+ ],
1704
+ ui: aiChatUIFeature(),
1705
+ template: () => `import { aiChatRoute } from "@farm.js/ai";
1706
+
1707
+ export const POST = aiChatRoute({
1708
+ model: "openai/gpt-4o-mini",
1709
+ system: "You are a helpful assistant.",
1710
+ });
1711
+ `
1712
+ },
1713
+ {
1714
+ provider: "stripe",
1715
+ aliases: [
1716
+ "billing-stripe",
1717
+ "payments",
1718
+ "stripe-billing"
1719
+ ],
1720
+ defaultKey: "billing",
1721
+ packageName: "@farm.js/stripe",
1722
+ fileName: "stripe",
1723
+ exportName: "stripeIntegration",
1724
+ description: "Stripe billing and checkout routes",
1725
+ env: ["STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET"],
1726
+ template: () => `import type { FarmIntegrationLogEvent } from "@farm.js/core";
1727
+ import { stripe } from "@farm.js/stripe";
1728
+
1729
+ export const stripeIntegration = stripe({
1730
+ secretKey: process.env.STRIPE_SECRET_KEY,
1731
+ webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
1732
+ products: [],
1733
+ log(event: FarmIntegrationLogEvent) {
1734
+ console.log("[stripe]", event.phase, event.route?.path || "none");
1735
+ },
1736
+ });
1737
+ `,
1738
+ ui: stripeBillingUIFeature()
1739
+ },
1740
+ {
1741
+ provider: "supabase",
1742
+ aliases: ["auth-supabase", "supabase-auth"],
1743
+ defaultKey: "auth",
1744
+ packageName: "@farm.js/supabase",
1745
+ fileName: "supabase",
1746
+ exportName: "supabaseIntegration",
1747
+ description: "Supabase auth routes and middleware",
1748
+ env: [
1749
+ "SUPABASE_URL",
1750
+ "SUPABASE_ANON_KEY",
1751
+ "APP_BASE_URL"
1752
+ ],
1753
+ ui: supabaseAuthUIFeature(),
1754
+ template: () => `import { supabase } from "@farm.js/supabase";
1755
+
1756
+ export const supabaseIntegration = supabase({
1757
+ callbackUrl: \`\${process.env.APP_BASE_URL || "http://localhost:3000"}/auth/callback\`,
1758
+ protectedRoutes: ["/dashboard(.*)"],
1759
+ pages: {
1760
+ signIn: "/sign-in",
1761
+ signUp: "/sign-up",
1762
+ },
1763
+ log(event) {
1764
+ console.log("[supabase]", event.phase, event.route?.path || "none");
1765
+ },
1766
+ });
1767
+ `
1768
+ },
1769
+ {
1770
+ provider: "workos",
1771
+ aliases: ["auth-workos", "workos-auth"],
1772
+ defaultKey: "auth",
1773
+ packageName: "@farm.js/workos",
1774
+ fileName: "workos",
1775
+ exportName: "workosIntegration",
1776
+ description: "WorkOS auth routes and protected route middleware",
1777
+ env: [
1778
+ "WORKOS_CLIENT_ID",
1779
+ "WORKOS_API_KEY",
1780
+ "WORKOS_COOKIE_PASSWORD"
1781
+ ],
1782
+ ui: workosAuthUIFeature(),
1783
+ template: () => `import { workos } from "@farm.js/workos";
1784
+
1785
+ export const workosIntegration = workos({
1786
+ protectedRoutes: ["/dashboard(.*)"],
1787
+ log(event) {
1788
+ console.log("[workos]", event.phase, event.route?.path || "none");
1789
+ },
1790
+ });
1791
+ `
1792
+ },
1793
+ {
1794
+ provider: "auth0",
1795
+ aliases: ["auth-auth0", "auth0-auth"],
1796
+ defaultKey: "auth",
1797
+ packageName: "@farm.js/auth0",
1798
+ fileName: "auth0",
1799
+ exportName: "auth0Integration",
1800
+ description: "Auth0 login, callback, logout, and profile routes",
1801
+ env: [
1802
+ "AUTH0_DOMAIN",
1803
+ "AUTH0_CLIENT_ID",
1804
+ "AUTH0_CLIENT_SECRET",
1805
+ "AUTH0_SECRET"
1806
+ ],
1807
+ ui: auth0AuthUIFeature(),
1808
+ template: () => `import { auth0 } from "@farm.js/auth0";
1809
+
1810
+ export const auth0Integration = auth0({
1811
+ callbackUrl: \`\${process.env.APP_BASE_URL || "http://localhost:3000"}/auth/callback\`,
1812
+ protectedRoutes: ["/dashboard(.*)"],
1813
+ log(event) {
1814
+ console.log("[auth0]", event.phase, event.route?.path || "none");
1815
+ },
1816
+ });
1817
+ `
1818
+ },
1819
+ {
1820
+ provider: "clerk",
1821
+ aliases: ["auth-clerk", "clerk-auth"],
1822
+ defaultKey: "auth",
1823
+ packageName: "@farm.js/clerk",
1824
+ fileName: "clerk",
1825
+ exportName: "clerkIntegration",
1826
+ description: "Clerk auth provider and protected route middleware",
1827
+ env: ["NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY", "CLERK_SECRET_KEY"],
1828
+ dependencies: { "@clerk/react": "^6.1.0" },
1829
+ ui: clerkAuthUIFeature(),
1830
+ template: () => `import { clerk } from "@farm.js/clerk";
1831
+
1832
+ export const clerkIntegration = clerk({
1833
+ signInUrl: "/sign-in",
1834
+ signUpUrl: "/sign-up",
1835
+ protectedRoutes: ["/dashboard(.*)"],
1836
+ log(event) {
1837
+ console.log("[clerk]", event.phase, event.route?.path || "none");
1838
+ },
1839
+ });
1840
+ `
1841
+ },
1842
+ {
1843
+ provider: "resend",
1844
+ aliases: ["email", "resend-email"],
1845
+ defaultKey: "email",
1846
+ packageName: "@farm.js/email",
1847
+ fileName: "resend",
1848
+ exportName: "resendIntegration",
1849
+ description: "Resend email send, preview, schedule, and webhook routes",
1850
+ env: [
1851
+ "RESEND_API_KEY",
1852
+ "RESEND_FROM_EMAIL",
1853
+ "RESEND_WEBHOOK_SECRET"
1854
+ ],
1855
+ ui: resendEmailUIFeature(),
1856
+ template: () => `import { createElement } from "react";
1857
+ import { resend, template } from "@farm.js/email";
1858
+
1859
+ function WelcomeEmail(props: { name: string }) {
1860
+ return createElement("div", null, \`Welcome \${props.name}\`);
1861
+ }
1862
+
1863
+ WelcomeEmail.PreviewProps = {
1864
+ name: "Ada",
1865
+ };
1866
+
1867
+ export const emailTemplates = {
1868
+ welcome: template(WelcomeEmail, {
1869
+ subject: ({ name }) => \`Welcome, \${name}\`,
1870
+ previewText: () => "Welcome to the app",
1871
+ }),
1872
+ } as const;
1873
+
1874
+ export const resendIntegration = resend({
1875
+ apiKey: process.env.RESEND_API_KEY,
1876
+ defaults: {
1877
+ from: process.env.RESEND_FROM_EMAIL,
1878
+ replyTo: process.env.RESEND_REPLY_TO_EMAIL ?? process.env.RESEND_FROM_EMAIL,
1879
+ },
1880
+ templates: emailTemplates,
1881
+ webhooks: process.env.RESEND_WEBHOOK_SECRET
1882
+ ? {
1883
+ secret: process.env.RESEND_WEBHOOK_SECRET,
1884
+ }
1885
+ : undefined,
1886
+ log(event) {
1887
+ console.log("[resend]", event.phase, event.route?.path || "none");
1888
+ },
1889
+ });
1890
+ `
1891
+ },
1892
+ {
1893
+ provider: "jobs-inngest",
1894
+ aliases: ["inngest", "jobs"],
1895
+ defaultKey: "jobs",
1896
+ packageName: "@farm.js/jobs",
1897
+ fileName: "jobs-inngest",
1898
+ exportName: "jobsIntegration",
1899
+ description: "Jobs integration backed by Inngest",
1900
+ env: [
1901
+ "INNGEST_APP_ID",
1902
+ "INNGEST_EVENT_KEY",
1903
+ "INNGEST_SIGNING_KEY"
1904
+ ],
1905
+ notes: ["Add tasks to jobTasks before using the generated jobs API."],
1906
+ ui: jobsUIFeature("inngest"),
1907
+ template: () => `import { defineTasks, inngest, jobs } from "@farm.js/jobs";
1908
+
1909
+ export const jobTasks = defineTasks({});
1910
+
1911
+ export const jobsIntegration = jobs({
1912
+ runtime: inngest({
1913
+ appId: process.env.INNGEST_APP_ID,
1914
+ eventKey: process.env.INNGEST_EVENT_KEY,
1915
+ signingKey: process.env.INNGEST_SIGNING_KEY,
1916
+ }),
1917
+ tasks: jobTasks,
1918
+ log(event) {
1919
+ console.log("[jobs:inngest]", event.phase, event.route?.path || "none");
1920
+ },
1921
+ });
1922
+ `
1923
+ },
1924
+ {
1925
+ provider: "jobs-trigger",
1926
+ aliases: [
1927
+ "trigger",
1928
+ "trigger-dev",
1929
+ "jobs-triggerdev"
1930
+ ],
1931
+ defaultKey: "jobs",
1932
+ packageName: "@farm.js/jobs",
1933
+ fileName: "jobs-trigger",
1934
+ exportName: "jobsIntegration",
1935
+ description: "Jobs integration backed by Trigger.dev",
1936
+ env: [
1937
+ "TRIGGER_PROJECT_REF",
1938
+ "TRIGGER_SECRET_KEY",
1939
+ "TRIGGER_WEBHOOK_SECRET"
1940
+ ],
1941
+ notes: ["Add tasks to jobTasks before using the generated jobs API."],
1942
+ ui: jobsUIFeature("trigger"),
1943
+ template: () => `import { defineTasks, jobs, trigger } from "@farm.js/jobs";
1944
+
1945
+ export const jobTasks = defineTasks({});
1946
+
1947
+ export const jobsIntegration = jobs({
1948
+ runtime: trigger({
1949
+ projectRef: process.env.TRIGGER_PROJECT_REF,
1950
+ apiKey: process.env.TRIGGER_SECRET_KEY,
1951
+ webhookSecret: process.env.TRIGGER_WEBHOOK_SECRET,
1952
+ }),
1953
+ tasks: jobTasks,
1954
+ log(event) {
1955
+ console.log("[jobs:trigger]", event.phase, event.route?.path || "none");
1956
+ },
1957
+ });
1958
+ `
1959
+ },
1960
+ {
1961
+ provider: "polar",
1962
+ aliases: ["polar-billing", "billing-polar"],
1963
+ defaultKey: "billing",
1964
+ packageName: "@farm.js/polar",
1965
+ fileName: "polar",
1966
+ exportName: "polarIntegration",
1967
+ description: "Polar billing and checkout routes",
1968
+ env: [
1969
+ "POLAR_ACCESS_TOKEN",
1970
+ "POLAR_WEBHOOK_SECRET",
1971
+ "APP_BASE_URL"
1972
+ ],
1973
+ notes: ["Replace resolveBillingOwner with your app user or organization lookup."],
1974
+ ui: polarBillingUIFeature(),
1975
+ template: () => `import type { FarmIntegrationHandlerContext } from "@farm.js/core";
1976
+ import { polar } from "@farm.js/polar";
1977
+
1978
+ function resolveBillingOwner(_context: FarmIntegrationHandlerContext): never {
1979
+ throw new Error("Configure Polar billing owner resolution for your app.");
1980
+ }
1981
+
1982
+ export const polarIntegration = polar({
1983
+ accessToken: process.env.POLAR_ACCESS_TOKEN,
1984
+ server: (process.env.POLAR_SERVER as "sandbox" | "production" | undefined) ?? "sandbox",
1985
+ appBaseUrl: process.env.APP_BASE_URL,
1986
+ webhooks: process.env.POLAR_WEBHOOK_SECRET
1987
+ ? {
1988
+ secret: process.env.POLAR_WEBHOOK_SECRET,
1989
+ }
1990
+ : undefined,
1991
+ billing: {
1992
+ resolveOwner: resolveBillingOwner,
1993
+ plans: {},
1994
+ products: {},
1995
+ },
1996
+ log(event) {
1997
+ console.log("[polar]", event.phase, event.route?.path || "none");
1998
+ },
1999
+ });
2000
+ `
2001
+ },
2002
+ {
2003
+ provider: "autumn",
2004
+ aliases: ["autumn-billing", "billing-autumn"],
2005
+ defaultKey: "billing",
2006
+ packageName: "@farm.js/autumn",
2007
+ fileName: "autumn",
2008
+ exportName: "autumnIntegration",
2009
+ description: "Autumn billing and checkout routes",
2010
+ env: [
2011
+ "AUTUMN_SECRET_KEY",
2012
+ "AUTUMN_WEBHOOK_SECRET",
2013
+ "APP_BASE_URL"
2014
+ ],
2015
+ notes: ["Replace resolveBillingOwner with your app user or organization lookup."],
2016
+ ui: autumnBillingUIFeature(),
2017
+ template: () => `import type { FarmIntegrationHandlerContext } from "@farm.js/core";
2018
+ import { autumn } from "@farm.js/autumn";
2019
+
2020
+ function resolveBillingOwner(_context: FarmIntegrationHandlerContext): never {
2021
+ throw new Error("Configure Autumn billing owner resolution for your app.");
2022
+ }
2023
+
2024
+ export const autumnIntegration = autumn({
2025
+ secretKey: process.env.AUTUMN_SECRET_KEY,
2026
+ appBaseUrl: process.env.APP_BASE_URL,
2027
+ webhooks: process.env.AUTUMN_WEBHOOK_SECRET
2028
+ ? {
2029
+ secret: process.env.AUTUMN_WEBHOOK_SECRET,
2030
+ }
2031
+ : undefined,
2032
+ billing: {
2033
+ resolveOwner: resolveBillingOwner,
2034
+ plans: {},
2035
+ products: {},
2036
+ },
2037
+ log(event) {
2038
+ console.log("[autumn]", event.phase, event.route?.path || "none");
2039
+ },
2040
+ });
2041
+ `
2042
+ },
2043
+ {
2044
+ provider: "better-auth",
2045
+ aliases: ["betterauth", "auth-better-auth"],
2046
+ defaultKey: "auth",
2047
+ packageName: "@farm.js/better-auth",
2048
+ fileName: "better-auth",
2049
+ exportName: "betterAuthIntegration",
2050
+ description: "Better Auth route adapter",
2051
+ env: [
2052
+ "BETTER_AUTH_SECRET",
2053
+ "BETTER_AUTH_URL",
2054
+ "BETTER_AUTH_DATABASE_PATH"
2055
+ ],
2056
+ dependencies: {
2057
+ "better-auth": "^1.5.5",
2058
+ "better-sqlite3": "^12.6.2"
2059
+ },
2060
+ devDependencies: { "@types/better-sqlite3": "^7.6.13" },
2061
+ notes: ["The generated SQLite database is intended for local development. Configure a persistent production database before deploying.", "Set BETTER_AUTH_SECRET to a high-entropy value of at least 32 characters."],
2062
+ setupFiles: [
2063
+ {
2064
+ path: "src/lib/auth.ts",
2065
+ source: () => `import Database from "better-sqlite3";
2066
+ import { betterAuth as createBetterAuth } from "better-auth";
2067
+ import { getMigrations } from "better-auth/db/migration";
2068
+
2069
+ const baseURL = process.env.BETTER_AUTH_URL || "http://localhost:3000";
2070
+ export const auth = createBetterAuth({
2071
+ database: new Database(process.env.BETTER_AUTH_DATABASE_PATH || "better-auth.sqlite"),
2072
+ secret: process.env.BETTER_AUTH_SECRET,
2073
+ baseURL,
2074
+ trustedOrigins: [baseURL],
2075
+ emailAndPassword: {
2076
+ enabled: true,
2077
+ },
2078
+ });
2079
+
2080
+ const migrations = await getMigrations(auth.options);
2081
+ await migrations.runMigrations();
2082
+ `
2083
+ },
2084
+ {
2085
+ path: ".env.example",
2086
+ merge: "lines",
2087
+ source: () => `BETTER_AUTH_SECRET=replace-with-at-least-32-random-characters
2088
+ BETTER_AUTH_URL=http://localhost:3000
2089
+ BETTER_AUTH_DATABASE_PATH=better-auth.sqlite
2090
+ `
2091
+ },
2092
+ {
2093
+ path: ".gitignore",
2094
+ merge: "lines",
2095
+ source: () => `better-auth.sqlite
2096
+ better-auth.sqlite-shm
2097
+ better-auth.sqlite-wal
2098
+ `
2099
+ }
2100
+ ],
2101
+ ui: betterAuthUIFeature(),
2102
+ template: () => `import { betterAuth } from "@farm.js/better-auth";
2103
+ import { auth } from "../auth.ts";
2104
+
2105
+ export const betterAuthIntegration = betterAuth({
2106
+ instance: auth,
2107
+ log(event) {
2108
+ console.log("[better-auth]", event.phase, event.route?.path || "none");
2109
+ },
2110
+ });
2111
+ `
2112
+ },
2113
+ {
2114
+ provider: "authjs",
2115
+ aliases: [
2116
+ "auth-js",
2117
+ "nextauth",
2118
+ "next-auth"
2119
+ ],
2120
+ defaultKey: "auth",
2121
+ packageName: "@farm.js/authjs",
2122
+ fileName: "authjs",
2123
+ exportName: "authjsIntegration",
2124
+ description: "Auth.js route adapter",
2125
+ env: [
2126
+ "AUTH_SECRET",
2127
+ "AUTH_GITHUB_ID",
2128
+ "AUTH_GITHUB_SECRET"
2129
+ ],
2130
+ dependencies: { "@auth/core": "0.34.3" },
2131
+ setupFiles: [{
2132
+ path: "src/lib/auth.ts",
2133
+ source: () => `import { Auth } from "@auth/core";
2134
+ import GitHub from "@auth/core/providers/github";
2135
+
2136
+ const config = {
2137
+ providers: [
2138
+ GitHub({
2139
+ clientId: process.env.AUTH_GITHUB_ID!,
2140
+ clientSecret: process.env.AUTH_GITHUB_SECRET!,
2141
+ }),
2142
+ ],
2143
+ secret: process.env.AUTH_SECRET,
2144
+ trustHost: true,
2145
+ };
2146
+
2147
+ const handler = (request: Request) => Auth(request, config);
2148
+
2149
+ export const auth = {
2150
+ handlers: {
2151
+ GET: handler,
2152
+ POST: handler,
2153
+ },
2154
+ };
2155
+ `
2156
+ }],
2157
+ notes: ["The generated Auth.js instance uses GitHub OAuth through @auth/core; add or replace providers in src/lib/auth.ts."],
2158
+ ui: authjsUIFeature(),
2159
+ template: () => `import { authjs } from "@farm.js/authjs";
2160
+ import { auth } from "../auth.ts";
2161
+
2162
+ export const authjsIntegration = authjs({
2163
+ instance: auth,
2164
+ log(event) {
2165
+ console.log("[authjs]", event.phase, event.route?.path || "none");
2166
+ },
2167
+ });
2168
+ `
2169
+ },
2170
+ {
2171
+ provider: "unkey",
2172
+ aliases: [
2173
+ "api-keys",
2174
+ "apikeys",
2175
+ "keys",
2176
+ "unkey-api-keys"
2177
+ ],
2178
+ defaultKey: "apiKeys",
2179
+ packageName: "@farm.js/unkey",
2180
+ fileName: "unkey",
2181
+ exportName: "unkeyIntegration",
2182
+ description: "Unkey API key creation, verification, and route protection",
2183
+ env: [
2184
+ "UNKEY_ROOT_KEY",
2185
+ "UNKEY_API_ID",
2186
+ "UNKEY_BASE_URL"
2187
+ ],
2188
+ ui: unkeyApiKeysUIFeature(),
2189
+ template: () => `import { unkey } from "@farm.js/unkey";
2190
+
2191
+ export const unkeyIntegration = unkey({
2192
+ rootKey: process.env.UNKEY_ROOT_KEY,
2193
+ apiId: process.env.UNKEY_API_ID,
2194
+ baseUrl: process.env.UNKEY_BASE_URL,
2195
+ protectedRoutes: ["/api/protected(.*)"],
2196
+ log(event) {
2197
+ console.log("[unkey]", event.phase, event.route?.path || "none");
2198
+ },
2199
+ });
2200
+ `
2201
+ }
2202
+ ];
2203
+ async function addFarmIntegration(options) {
2204
+ const root = path$1.resolve(options.root || process.cwd());
2205
+ const definition = resolveProvider(options.provider);
2206
+ if (definition.provider === "ai") return addAIRouteIntegration({
2207
+ root,
2208
+ definition,
2209
+ routeFile: options.routeFile,
2210
+ ui: options.ui,
2211
+ skipPackageJson: options.skipPackageJson,
2212
+ dryRun: options.dryRun,
2213
+ force: options.force
2214
+ });
2215
+ const key = options.key || definition.defaultKey;
2216
+ assertValidIntegrationKey(key);
2217
+ const registryFile = path$1.resolve(root, options.integrationsFile || path$1.join("src", "lib", "integrations.ts"));
2218
+ const integrationFile = path$1.join(path$1.dirname(registryFile), "integrations", `${definition.fileName}.ts`);
2219
+ const result = {
2220
+ provider: definition.provider,
2221
+ key,
2222
+ mode: "integration",
2223
+ integrationFile,
2224
+ registryFile,
2225
+ created: [],
2226
+ updated: [],
2227
+ skipped: [],
2228
+ env: [...definition.env],
2229
+ notes: [...definition.notes || []]
2230
+ };
2231
+ await writeIntegrationComponent({
2232
+ path: integrationFile,
2233
+ definition,
2234
+ force: options.force,
2235
+ dryRun: options.dryRun,
2236
+ result
2237
+ });
2238
+ await writeIntegrationSetupFiles({
2239
+ root,
2240
+ definition,
2241
+ force: options.force,
2242
+ dryRun: options.dryRun,
2243
+ result
2244
+ });
2245
+ await writeIntegrationRegistry({
2246
+ path: registryFile,
2247
+ integrationFile,
2248
+ definition,
2249
+ key,
2250
+ dryRun: options.dryRun,
2251
+ result
2252
+ });
2253
+ if (!options.skipPackageJson) await updatePackageJson$1({
2254
+ root,
2255
+ definition,
2256
+ dryRun: options.dryRun,
2257
+ result
2258
+ });
2259
+ if (!options.skipConfig) await updateFarmConfig({
2260
+ root,
2261
+ registryFile,
2262
+ dryRun: options.dryRun,
2263
+ result
2264
+ });
2265
+ if (options.ui) await installUIFeature({
2266
+ root,
2267
+ definition,
2268
+ key,
2269
+ dryRun: options.dryRun,
2270
+ force: options.force,
2271
+ skipPackageJson: options.skipPackageJson,
2272
+ result
2273
+ });
2274
+ return result;
2275
+ }
2276
+ async function addAIRouteIntegration(input) {
2277
+ const routeFile = path$1.resolve(input.root, input.routeFile || path$1.join("src", "app", "api", "chat", "route.ts"));
2278
+ const result = {
2279
+ provider: "ai",
2280
+ key: input.definition.defaultKey,
2281
+ mode: "route",
2282
+ integrationFile: routeFile,
2283
+ registryFile: "",
2284
+ routeFile,
2285
+ routePath: "/api/chat",
2286
+ created: [],
2287
+ updated: [],
2288
+ skipped: [],
2289
+ env: [...input.definition.env],
2290
+ notes: [...input.definition.notes || []]
2291
+ };
2292
+ await writeIntegrationComponent({
2293
+ path: routeFile,
2294
+ definition: input.definition,
2295
+ force: input.force,
2296
+ dryRun: input.dryRun,
2297
+ result
2298
+ });
2299
+ if (!input.skipPackageJson) await updatePackageJson$1({
2300
+ root: input.root,
2301
+ definition: input.definition,
2302
+ dryRun: input.dryRun,
2303
+ result
2304
+ });
2305
+ if (input.ui) await installUIFeature({
2306
+ root: input.root,
2307
+ definition: input.definition,
2308
+ key: input.definition.defaultKey,
2309
+ dryRun: input.dryRun,
2310
+ force: input.force,
2311
+ skipPackageJson: input.skipPackageJson,
2312
+ result
2313
+ });
2314
+ return result;
2315
+ }
2316
+ function resolveProvider(input) {
2317
+ const normalized = input.trim().toLowerCase();
2318
+ const match = PROVIDERS.find((provider) => provider.provider === normalized || provider.aliases.includes(normalized));
2319
+ if (!match) {
2320
+ const supported = PROVIDERS.map((provider) => provider.provider).join(", ");
2321
+ throw new Error(`Unknown integration "${input}". Supported integrations: ${supported}.`);
2322
+ }
2323
+ return match;
2324
+ }
2325
+ function assertValidIntegrationKey(key) {
2326
+ if (!/^[A-Za-z_$][\w$]*$/.test(key)) throw new Error(`Integration key "${key}" must be a valid JavaScript object property name.`);
2327
+ }
2328
+ async function writeIntegrationComponent(input) {
2329
+ const exists = existsSync(input.path);
2330
+ if (exists && !input.force) {
2331
+ input.result.skipped.push(input.path);
2332
+ return;
2333
+ }
2334
+ if (!input.dryRun) {
2335
+ await mkdir(path$1.dirname(input.path), { recursive: true });
2336
+ await writeFile(input.path, input.definition.template(), "utf8");
2337
+ }
2338
+ if (exists) input.result.updated.push(input.path);
2339
+ else input.result.created.push(input.path);
2340
+ }
2341
+ async function writeIntegrationRegistry(input) {
2342
+ const importPath = toImportPath(path$1.relative(path$1.dirname(input.path), input.integrationFile));
2343
+ const importLine = `import { ${input.definition.exportName} } from "${importPath}";`;
2344
+ const propertyLine = ` ${input.key}: ${input.definition.exportName},`;
2345
+ let nextSource;
2346
+ const exists = existsSync(input.path);
2347
+ if (exists) nextSource = ensureRegistryEntry(await readFile(input.path, "utf8"), {
2348
+ importLine,
2349
+ propertyLine,
2350
+ key: input.key,
2351
+ exportName: input.definition.exportName
2352
+ });
2353
+ else nextSource = `${importLine}
2354
+
2355
+ export const appIntegrations = {
2356
+ ${propertyLine}
2357
+ } as const;
2358
+
2359
+ export type AppIntegrations = typeof appIntegrations;
2360
+ `;
2361
+ if (!input.dryRun) {
2362
+ await mkdir(path$1.dirname(input.path), { recursive: true });
2363
+ await writeFile(input.path, nextSource, "utf8");
2364
+ }
2365
+ input.result[exists ? "updated" : "created"].push(input.path);
2366
+ }
2367
+ function ensureRegistryEntry(source, input) {
2368
+ if (new RegExp(`(^|\\n)\\s*${escapeRegExp(input.key)}\\s*:`, "m").test(source)) {
2369
+ if (source.includes(`${input.key}: ${input.exportName}`)) return source.includes(input.importLine) ? source : `${input.importLine}\n${source}`;
2370
+ throw new Error(`Integration key "${input.key}" already exists in the app integrations registry. Pass --key to use a different key.`);
2371
+ }
2372
+ const sourceWithImport = source.includes(input.importLine) ? source : `${input.importLine}\n${source}`;
2373
+ const appIntegrationsPattern = /export\s+const\s+appIntegrations\s*=\s*\{([\s\S]*?)\}\s*as\s+const;/m;
2374
+ const match = sourceWithImport.match(appIntegrationsPattern);
2375
+ if (!match) return `${sourceWithImport.trimEnd()}
2376
+
2377
+ export const appIntegrations = {
2378
+ ${input.propertyLine}
2379
+ } as const;
2380
+
2381
+ export type AppIntegrations = typeof appIntegrations;
2382
+ `;
2383
+ const body = match[1] || "";
2384
+ const nextBody = body.trim().length ? `${body.trimEnd()}\n${input.propertyLine}\n` : `\n${input.propertyLine}\n`;
2385
+ return sourceWithImport.replace(appIntegrationsPattern, () => {
2386
+ return `export const appIntegrations = {${nextBody}} as const;`;
2387
+ });
2388
+ }
2389
+ async function writeIntegrationSetupFiles(input) {
2390
+ for (const file of input.definition.setupFiles || []) {
2391
+ const absolutePath = path$1.join(input.root, file.path);
2392
+ const exists = existsSync(absolutePath);
2393
+ if (exists && !input.force) {
2394
+ if (file.merge === "lines") {
2395
+ const source = await readFile(absolutePath, "utf8");
2396
+ const additions = file.source().split(/\r?\n/).filter((line) => line && !source.split(/\r?\n/).includes(line));
2397
+ if (!additions.length) {
2398
+ input.result.skipped.push(absolutePath);
2399
+ continue;
2400
+ }
2401
+ if (!input.dryRun) await writeFile(absolutePath, `${source.trimEnd()}\n${additions.join("\n")}\n`, "utf8");
2402
+ input.result.updated.push(absolutePath);
2403
+ continue;
2404
+ }
2405
+ input.result.skipped.push(absolutePath);
2406
+ continue;
2407
+ }
2408
+ if (!input.dryRun) {
2409
+ await mkdir(path$1.dirname(absolutePath), { recursive: true });
2410
+ await writeFile(absolutePath, file.source(), "utf8");
2411
+ }
2412
+ input.result[exists ? "updated" : "created"].push(absolutePath);
2413
+ }
2414
+ }
2415
+ async function updatePackageJson$1(input) {
2416
+ const packageJsonPath = path$1.join(input.root, "package.json");
2417
+ if (!existsSync(packageJsonPath)) {
2418
+ input.result.skipped.push(packageJsonPath);
2419
+ return;
2420
+ }
2421
+ const source = await readFile(packageJsonPath, "utf8");
2422
+ const manifest = JSON.parse(source);
2423
+ const dependencies = missingDependencies(manifest, input.definition.dependencies);
2424
+ const devDependencies = missingDependencies(manifest, input.definition.devDependencies);
2425
+ manifest.dependencies = {
2426
+ ...manifest.dependencies,
2427
+ ...hasPackageDependency(manifest, input.definition.packageName) ? {} : { [input.definition.packageName]: getFarmIntegrationVersion(manifest) },
2428
+ ...dependencies
2429
+ };
2430
+ if (Object.keys(devDependencies).length) manifest.devDependencies = {
2431
+ ...manifest.devDependencies,
2432
+ ...devDependencies
2433
+ };
2434
+ const nextSource = `${JSON.stringify(manifest, null, 2)}\n`;
2435
+ if (source === nextSource) {
2436
+ input.result.packageJson = packageJsonPath;
2437
+ input.result.skipped.push(packageJsonPath);
2438
+ return;
2439
+ }
2440
+ if (!input.dryRun) await writeFile(packageJsonPath, nextSource, "utf8");
2441
+ input.result.packageJson = packageJsonPath;
2442
+ input.result.updated.push(packageJsonPath);
2443
+ }
2444
+ function missingDependencies(manifest, dependencies) {
2445
+ return Object.fromEntries(Object.entries(dependencies || {}).filter(([name]) => !hasPackageDependency(manifest, name)));
2446
+ }
2447
+ async function updateFarmConfig(input) {
2448
+ const configFile = findFarmConfig(input.root);
2449
+ if (!configFile) {
2450
+ const newConfigFile = path$1.join(input.root, "farm.config.ts");
2451
+ const source = `import { defineConfig } from "@farm.js/core";
2452
+ import { appIntegrations } from "${toImportPath(path$1.relative(input.root, input.registryFile))}";
2453
+
2454
+ export default defineConfig({
2455
+ integrations: appIntegrations,
2456
+ });
2457
+ `;
2458
+ if (!input.dryRun) await writeFile(newConfigFile, source, "utf8");
2459
+ input.result.configFile = newConfigFile;
2460
+ input.result.created.push(newConfigFile);
2461
+ return;
2462
+ }
2463
+ input.result.configFile = configFile;
2464
+ const source = await readFile(configFile, "utf8");
2465
+ if (/\bintegrations\s*:/.test(source)) {
2466
+ input.result.skipped.push(configFile);
2467
+ input.result.notes.push(`farm.config already has an integrations field. Confirm it includes appIntegrations from ${path$1.relative(input.root, input.registryFile)}.`);
2468
+ return;
2469
+ }
2470
+ const importLine = `import { appIntegrations } from "${toImportPath(path$1.relative(path$1.dirname(configFile), input.registryFile))}";`;
2471
+ const sourceWithImport = source.includes(importLine) ? source : `${importLine}\n${source}`;
2472
+ const nextSource = insertIntegrationsConfig(sourceWithImport);
2473
+ if (nextSource === sourceWithImport) {
2474
+ input.result.skipped.push(configFile);
2475
+ input.result.notes.push(`Could not safely update ${path$1.relative(input.root, configFile)}. Add integrations: appIntegrations manually.`);
2476
+ return;
2477
+ }
2478
+ if (!input.dryRun) await writeFile(configFile, nextSource, "utf8");
2479
+ input.result.updated.push(configFile);
2480
+ }
2481
+ function insertIntegrationsConfig(source) {
2482
+ const defineConfigCall = /\bdefine(?:Farm)?Config\s*\(\s*\{/;
2483
+ if (defineConfigCall.test(source)) return source.replace(defineConfigCall, (match) => {
2484
+ return `${match}\n integrations: appIntegrations,`;
2485
+ });
2486
+ if (/export\s+default\s+\{/.test(source)) return source.replace(/export\s+default\s+\{/, (match) => {
2487
+ return `${match}\n integrations: appIntegrations,`;
2488
+ });
2489
+ return source;
2490
+ }
2491
+ function findFarmConfig(root) {
2492
+ for (const candidate of [
2493
+ "farm.config.ts",
2494
+ "farm.config.mts",
2495
+ "farm.config.js",
2496
+ "farm.config.mjs",
2497
+ "config.ts",
2498
+ "config.mts",
2499
+ "config.js",
2500
+ "config.mjs"
2501
+ ]) {
2502
+ const absolutePath = path$1.join(root, candidate);
2503
+ if (existsSync(absolutePath)) return absolutePath;
2504
+ }
2505
+ return null;
2506
+ }
2507
+ function hasPackageDependency(manifest, dependency) {
2508
+ return dependency in (manifest.dependencies || {}) || dependency in (manifest.devDependencies || {}) || dependency in (manifest.peerDependencies || {}) || dependency in (manifest.optionalDependencies || {});
2509
+ }
2510
+ function getFarmIntegrationVersion(manifest) {
2511
+ const farmCoreVersion = manifest.dependencies?.["@farm.js/core"] ?? manifest.devDependencies?.["@farm.js/core"] ?? manifest.peerDependencies?.["@farm.js/core"] ?? manifest.optionalDependencies?.["@farm.js/core"];
2512
+ if (!farmCoreVersion) return "latest";
2513
+ return farmCoreVersion.startsWith("workspace:") ? "workspace:*" : farmCoreVersion;
2514
+ }
2515
+ function toImportPath(relativePath) {
2516
+ const normalized = relativePath.split(path$1.sep).join("/");
2517
+ return (normalized.startsWith(".") ? normalized : `./${normalized}`).replace(/\.tsx?$/, ".ts");
2518
+ }
2519
+ function escapeRegExp(input) {
2520
+ return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2521
+ }
2522
+ //#endregion
6
2523
  //#region src/index.ts
7
2524
  const templateDetails = {
8
2525
  basic: {
9
- title: "Farm.js Basic",
2526
+ title: "Basic starter",
10
2527
  description: "A minimal Farm.js app with built-in Tailwind support",
11
2528
  instructions: ["Tailwind is enabled by default. You only need postcss config for custom plugins."]
12
2529
  },
13
2530
  auth: {
14
- title: "Farm.js Auth",
2531
+ title: "Auth starter",
15
2532
  description: "Farm.js-native auth with local SQLite, secure sessions, and protected routes",
16
2533
  instructions: ["FARMJS Auth uses local SQLite automatically; no auth environment variables are needed locally.", "For production, set FARM_AUTH_URL, FARM_AUTH_SECRET, and DATABASE_URL, then run the auth:migrate script."]
17
2534
  },
18
2535
  "better-auth": {
19
- title: "Farm.js Better Auth",
2536
+ title: "Better Auth starter",
20
2537
  description: "Better Auth with Postgres, secure sessions, and protected routes",
21
2538
  instructions: ["Before starting, copy .env.example to .env.local and set DATABASE_URL and BETTER_AUTH_SECRET.", "Better Auth migrations run automatically when the auth instance starts."]
22
- }
2539
+ },
2540
+ ai: integrationTemplate({
2541
+ title: "AI starter",
2542
+ description: "AI SDK chat route with a ready-to-use chat interface",
2543
+ provider: "ai",
2544
+ label: "AI",
2545
+ route: "/integrations/ai",
2546
+ docsPath: "/docs/integrations"
2547
+ }),
2548
+ auth0: integrationTemplate({
2549
+ title: "Auth0 starter",
2550
+ description: "Auth0 login, sessions, protected routes, and account controls",
2551
+ provider: "auth0",
2552
+ label: "Auth0",
2553
+ route: "/integrations/auth0",
2554
+ docsPath: "/docs/integrations/auth/auth0"
2555
+ }),
2556
+ authjs: integrationTemplate({
2557
+ title: "Auth.js starter",
2558
+ description: "Auth.js with GitHub OAuth and Farm-owned route mounting",
2559
+ provider: "authjs",
2560
+ label: "Auth.js",
2561
+ route: "/integrations/authjs",
2562
+ docsPath: "/docs/integrations/auth/authjs"
2563
+ }),
2564
+ autumn: integrationTemplate({
2565
+ title: "Autumn starter",
2566
+ description: "Autumn products, checkout, billing state, and customer portal",
2567
+ provider: "autumn",
2568
+ label: "Autumn",
2569
+ route: "/integrations/autumn",
2570
+ docsPath: "/docs/integrations/autumn"
2571
+ }),
2572
+ clerk: integrationTemplate({
2573
+ title: "Clerk starter",
2574
+ description: "Clerk authentication, account entry points, and protected routes",
2575
+ provider: "clerk",
2576
+ label: "Clerk",
2577
+ route: "/integrations/clerk",
2578
+ docsPath: "/docs/integrations/auth/clerk"
2579
+ }),
2580
+ "jobs-inngest": integrationTemplate({
2581
+ title: "Inngest starter",
2582
+ description: "Typed background jobs backed by Inngest",
2583
+ provider: "jobs-inngest",
2584
+ label: "Inngest",
2585
+ route: "/integrations/jobs-inngest",
2586
+ docsPath: "/docs/integrations/inngest"
2587
+ }),
2588
+ "jobs-trigger": integrationTemplate({
2589
+ title: "Trigger.dev starter",
2590
+ description: "Typed background jobs backed by Trigger.dev",
2591
+ provider: "jobs-trigger",
2592
+ label: "Trigger.dev",
2593
+ route: "/integrations/jobs-trigger",
2594
+ docsPath: "/docs/integrations/trigger"
2595
+ }),
2596
+ polar: integrationTemplate({
2597
+ title: "Polar starter",
2598
+ description: "Polar products, checkout, billing state, and customer portal",
2599
+ provider: "polar",
2600
+ label: "Polar",
2601
+ route: "/integrations/polar",
2602
+ docsPath: "/docs/integrations/polar"
2603
+ }),
2604
+ resend: integrationTemplate({
2605
+ title: "Resend starter",
2606
+ description: "Resend templates, delivery, scheduling, and webhooks",
2607
+ provider: "resend",
2608
+ label: "Resend",
2609
+ route: "/integrations/resend",
2610
+ docsPath: "/docs/integrations/email"
2611
+ }),
2612
+ stripe: integrationTemplate({
2613
+ title: "Stripe starter",
2614
+ description: "Stripe products, checkout, billing portal, and webhooks",
2615
+ provider: "stripe",
2616
+ label: "Stripe",
2617
+ route: "/integrations/stripe",
2618
+ docsPath: "/docs/integrations/stripe"
2619
+ }),
2620
+ supabase: integrationTemplate({
2621
+ title: "Supabase starter",
2622
+ description: "Supabase authentication, sessions, OAuth, and protected routes",
2623
+ provider: "supabase",
2624
+ label: "Supabase",
2625
+ route: "/integrations/supabase",
2626
+ docsPath: "/docs/integrations/auth/supabase"
2627
+ }),
2628
+ unkey: integrationTemplate({
2629
+ title: "Unkey starter",
2630
+ description: "Unkey API key creation, verification, and route protection",
2631
+ provider: "unkey",
2632
+ label: "Unkey",
2633
+ route: "/integrations/unkey",
2634
+ docsPath: "/docs/integrations/unkey"
2635
+ }),
2636
+ workos: integrationTemplate({
2637
+ title: "WorkOS starter",
2638
+ description: "WorkOS AuthKit, organization sessions, and protected routes",
2639
+ provider: "workos",
2640
+ label: "WorkOS",
2641
+ route: "/integrations/workos",
2642
+ docsPath: "/docs/integrations/auth/workos"
2643
+ })
23
2644
  };
2645
+ function integrationTemplate(input) {
2646
+ return {
2647
+ title: input.title,
2648
+ description: input.description,
2649
+ instructions: [],
2650
+ integration: {
2651
+ provider: input.provider,
2652
+ label: input.label,
2653
+ route: input.route,
2654
+ docsPath: input.docsPath
2655
+ }
2656
+ };
2657
+ }
24
2658
  async function createApp(projectName, options = {}) {
25
2659
  showBanner();
26
2660
  const templates = await getAvailableTemplates();
@@ -28,6 +2662,14 @@ async function createApp(projectName, options = {}) {
28
2662
  logger.error("No templates are available in this package.");
29
2663
  process.exit(1);
30
2664
  }
2665
+ if (options.listTemplates) {
2666
+ logger.info("Available templates");
2667
+ for (const template of templates) {
2668
+ const details = templateDetails[template];
2669
+ logger.info(` ${template.padEnd(14)} ${details?.description ?? ""}`.trimEnd());
2670
+ }
2671
+ return;
2672
+ }
31
2673
  if (!projectName) {
32
2674
  const response = await prompts({
33
2675
  type: "text",
@@ -102,7 +2744,7 @@ async function createApp(projectName, options = {}) {
102
2744
  }
103
2745
  logger.info(`Creating FARMJS app in ${projectPath}`);
104
2746
  await fs.mkdir(projectPath, { recursive: true });
105
- await copyTemplate(template, projectPath, useTypeScript);
2747
+ const integrationResult = await copyTemplate(template, projectPath, useTypeScript);
106
2748
  await updatePackageJson(projectPath, projectName, packageManager);
107
2749
  logger.success(`🚜 Created ${projectName}`);
108
2750
  if (!options.skipInstall) {
@@ -117,13 +2759,103 @@ async function createApp(projectName, options = {}) {
117
2759
  logger.info(` ${getDevCommand(packageManager.name)}`);
118
2760
  logger.info("");
119
2761
  for (const instruction of templateDetails[template]?.instructions ?? []) logger.info(instruction);
2762
+ if (integrationResult) {
2763
+ const details = templateDetails[template].integration;
2764
+ logger.info(`Open ${details.route} for the ${details.label} starter.`);
2765
+ if (integrationResult.env.length) logger.info("Copy .env.example to .env.local and add your provider credentials.");
2766
+ for (const note of integrationResult.notes) logger.info(note);
2767
+ }
120
2768
  }
121
2769
  async function copyTemplate(template, projectPath, useTypeScript) {
122
- await copyDir(path.join(__dirname, "..", "templates", template), projectPath);
2770
+ const details = templateDetails[template];
2771
+ await copyDir(path.join(__dirname, "..", "templates", details?.integration ? "basic" : template), projectPath);
123
2772
  if (useTypeScript) {
124
2773
  const tsTemplatePath = path.join(__dirname, "..", "templates", "_typescript");
125
2774
  if (await dirExists(tsTemplatePath)) await copyDir(tsTemplatePath, projectPath);
126
2775
  }
2776
+ if (!details?.integration) return;
2777
+ const result = await addFarmIntegration({
2778
+ root: projectPath,
2779
+ provider: details.integration.provider,
2780
+ ui: true
2781
+ });
2782
+ await writeEnvironmentExample(projectPath, result.env);
2783
+ await writeIntegrationHomePage(projectPath, details.integration, result.env.length > 0);
2784
+ await writeIntegrationReadme(projectPath, details.integration, result.env);
2785
+ return result;
2786
+ }
2787
+ async function writeEnvironmentExample(projectPath, keys) {
2788
+ if (keys.length === 0) return;
2789
+ const envPath = path.join(projectPath, ".env.example");
2790
+ let current = "";
2791
+ try {
2792
+ current = await fs.readFile(envPath, "utf8");
2793
+ } catch {}
2794
+ const existingKeys = new Set(current.split(/\r?\n/).map((line) => line.match(/^([A-Z][A-Z0-9_]*)=/)?.[1]).filter((key) => Boolean(key)));
2795
+ const additions = keys.filter((key) => !existingKeys.has(key)).map((key) => `${key}=${environmentExampleValue(key)}`);
2796
+ if (additions.length > 0) await fs.writeFile(envPath, `${current.trimEnd()}${current.trim() ? "\n" : ""}${additions.join("\n")}\n`, "utf8");
2797
+ }
2798
+ function environmentExampleValue(key) {
2799
+ if (key === "APP_BASE_URL") return "http://localhost:3000";
2800
+ if (key === "AUTH_SECRET") return "replace-with-at-least-32-random-characters";
2801
+ if (key === "UNKEY_BASE_URL") return "https://api.unkey.com";
2802
+ return "";
2803
+ }
2804
+ async function writeIntegrationHomePage(projectPath, integration, hasEnvironment) {
2805
+ const commandRows = [...hasEnvironment ? ["cp .env.example .env.local"] : [], "pnpm dev"].map((command, index) => ` <div className="command-row">
2806
+ <span>${String(index + 1).padStart(2, "0")}</span>
2807
+ <code>${command}</code>
2808
+ </div>`).join("\n");
2809
+ const source = `import { ResourceLinks } from "../components/resource-links";
2810
+
2811
+ export default function HomePage() {
2812
+ return (
2813
+ <main className="landing-main">
2814
+ <section className="hero-section">
2815
+ <div className="hero-copy">
2816
+ <div className="eyebrow-row">
2817
+ <span>00</span>
2818
+ <span>FARMJS / ${integration.label} starter</span>
2819
+ </div>
2820
+
2821
+ <h1>
2822
+ Start at <code>${integration.route}</code>.
2823
+ </h1>
2824
+
2825
+ <div className="command-list" aria-label="Getting started commands">
2826
+ ${commandRows}
2827
+ </div>
2828
+
2829
+ <ResourceLinks
2830
+ className="resource-links"
2831
+ primary={{ href: "${integration.route}", label: "Get started" }}
2832
+ />
2833
+ </div>
2834
+ </section>
2835
+ </main>
2836
+ );
2837
+ }
2838
+ `;
2839
+ await fs.writeFile(path.join(projectPath, "src", "app", "page.tsx"), source, "utf8");
2840
+ }
2841
+ async function writeIntegrationReadme(projectPath, integration, env) {
2842
+ const environmentSetup = env.length ? `cp .env.example .env.local\n# Add values for: ${env.join(", ")}\n` : "";
2843
+ const wiring = integration.provider === "ai" ? "The AI route lives in `src/app/api/chat/route.ts` and its local UI lives under `src/components/farm`." : "The provider wiring lives in `src/lib/integrations` and is registered from `farm.config.ts`.";
2844
+ const source = `# FARMJS ${integration.label} Starter
2845
+
2846
+ ## Getting started
2847
+
2848
+ \`\`\`bash
2849
+ pnpm install
2850
+ ${environmentSetup}pnpm dev
2851
+ \`\`\`
2852
+
2853
+ Open [${integration.route}](http://localhost:3000${integration.route}) for the integration UI.
2854
+
2855
+ ${wiring}
2856
+ See the [${integration.label} integration guide](https://farm.js.dev${integration.docsPath}) for provider setup and production guidance.
2857
+ `;
2858
+ await fs.writeFile(path.join(projectPath, "README.md"), source, "utf8");
127
2859
  }
128
2860
  async function copyDir(src, dest) {
129
2861
  await fs.mkdir(dest, { recursive: true });
@@ -169,7 +2901,9 @@ async function getAvailableTemplates() {
169
2901
  const templatesRoot = path.join(__dirname, "..", "templates");
170
2902
  const entries = await fs.readdir(templatesRoot, { withFileTypes: true });
171
2903
  const templateOrder = Object.keys(templateDetails);
172
- return entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith("_")).map((entry) => entry.name).sort((left, right) => {
2904
+ const directoryTemplates = entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith("_")).map((entry) => entry.name);
2905
+ const generatedTemplates = Object.entries(templateDetails).filter(([, details]) => Boolean(details.integration)).map(([name]) => name);
2906
+ return [.../* @__PURE__ */ new Set([...directoryTemplates, ...generatedTemplates])].sort((left, right) => {
173
2907
  const leftIndex = templateOrder.indexOf(left);
174
2908
  const rightIndex = templateOrder.indexOf(right);
175
2909
  return (leftIndex === -1 ? Number.MAX_SAFE_INTEGER : leftIndex) - (rightIndex === -1 ? Number.MAX_SAFE_INTEGER : rightIndex) || left.localeCompare(right);