@farm.js/create-app 0.1.0-beta.1 → 0.1.0-beta.100

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