@farm.js/create-app 0.1.0-beta.4 → 0.1.0-beta.41

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