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