usebecky 0.0.0-stage → 0.2.0

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 (135) hide show
  1. package/README.md +701 -2
  2. package/dist/analytics/client.d.ts +219 -0
  3. package/dist/analytics/client.js +923 -0
  4. package/dist/analytics/cmp.d.ts +20 -0
  5. package/dist/analytics/cmp.js +166 -0
  6. package/dist/analytics/context.d.ts +29 -0
  7. package/dist/analytics/context.js +97 -0
  8. package/dist/auth/client.d.ts +401 -0
  9. package/dist/auth/client.js +1081 -0
  10. package/dist/auth/webauthn.d.ts +18 -0
  11. package/dist/auth/webauthn.js +138 -0
  12. package/dist/cli/ai.d.ts +54 -0
  13. package/dist/cli/ai.js +202 -0
  14. package/dist/cli/analytics.d.ts +53 -0
  15. package/dist/cli/analytics.js +357 -0
  16. package/dist/cli/config.d.ts +75 -0
  17. package/dist/cli/config.js +718 -0
  18. package/dist/cli/db.d.ts +48 -0
  19. package/dist/cli/db.js +215 -0
  20. package/dist/cli/deploy-api.d.ts +168 -0
  21. package/dist/cli/deploy-api.js +177 -0
  22. package/dist/cli/deploy-ci.d.ts +15 -0
  23. package/dist/cli/deploy-ci.js +54 -0
  24. package/dist/cli/deploy-detect.d.ts +64 -0
  25. package/dist/cli/deploy-detect.js +249 -0
  26. package/dist/cli/deploy-files.d.ts +112 -0
  27. package/dist/cli/deploy-files.js +778 -0
  28. package/dist/cli/deploy.d.ts +10 -0
  29. package/dist/cli/deploy.js +430 -0
  30. package/dist/cli/emails.d.ts +29 -0
  31. package/dist/cli/emails.js +122 -0
  32. package/dist/cli/framework.d.ts +135 -0
  33. package/dist/cli/framework.js +459 -0
  34. package/dist/cli/functions.d.ts +59 -0
  35. package/dist/cli/functions.js +426 -0
  36. package/dist/cli/hosting.d.ts +4 -0
  37. package/dist/cli/hosting.js +532 -0
  38. package/dist/cli/index.d.ts +2 -0
  39. package/dist/cli/index.js +9 -0
  40. package/dist/cli/payments.d.ts +35 -0
  41. package/dist/cli/payments.js +176 -0
  42. package/dist/cli/push.d.ts +36 -0
  43. package/dist/cli/push.js +172 -0
  44. package/dist/cli/run.d.ts +65 -0
  45. package/dist/cli/run.js +850 -0
  46. package/dist/cli/social.d.ts +52 -0
  47. package/dist/cli/social.js +532 -0
  48. package/dist/cli/tokens.d.ts +28 -0
  49. package/dist/cli/tokens.js +114 -0
  50. package/dist/cli/ui.d.ts +38 -0
  51. package/dist/cli/ui.js +140 -0
  52. package/dist/client.d.ts +94 -0
  53. package/dist/client.js +156 -0
  54. package/dist/db/query.d.ts +162 -0
  55. package/dist/db/query.js +336 -0
  56. package/dist/db/types.d.ts +93 -0
  57. package/dist/db/types.js +4 -0
  58. package/dist/forms/client.d.ts +65 -0
  59. package/dist/forms/client.js +106 -0
  60. package/dist/functions/client.d.ts +37 -0
  61. package/dist/functions/client.js +76 -0
  62. package/dist/index.d.ts +17 -0
  63. package/dist/index.js +16 -0
  64. package/dist/lib/dashboard-paths.d.ts +4 -0
  65. package/dist/lib/dashboard-paths.js +8 -0
  66. package/dist/lib/env.d.ts +9 -0
  67. package/dist/lib/env.js +55 -0
  68. package/dist/lib/errors.d.ts +22 -0
  69. package/dist/lib/errors.js +90 -0
  70. package/dist/lib/hosted.d.ts +2 -0
  71. package/dist/lib/hosted.js +7 -0
  72. package/dist/lib/http.d.ts +59 -0
  73. package/dist/lib/http.js +172 -0
  74. package/dist/lib/jwt.d.ts +1 -0
  75. package/dist/lib/jwt.js +31 -0
  76. package/dist/lib/locale.d.ts +12 -0
  77. package/dist/lib/locale.js +51 -0
  78. package/dist/lib/pkce.d.ts +20 -0
  79. package/dist/lib/pkce.js +124 -0
  80. package/dist/lib/storage-adapter.d.ts +15 -0
  81. package/dist/lib/storage-adapter.js +91 -0
  82. package/dist/lib/types.d.ts +339 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/newsletter/client.d.ts +140 -0
  85. package/dist/newsletter/client.js +85 -0
  86. package/dist/payments/client.d.ts +352 -0
  87. package/dist/payments/client.js +323 -0
  88. package/dist/push/client.d.ts +110 -0
  89. package/dist/push/client.js +179 -0
  90. package/dist/realtime/client.d.ts +131 -0
  91. package/dist/realtime/client.js +513 -0
  92. package/dist/server/analytics.d.ts +176 -0
  93. package/dist/server/analytics.js +49 -0
  94. package/dist/server/cache.d.ts +74 -0
  95. package/dist/server/cache.js +154 -0
  96. package/dist/server/emails.d.ts +142 -0
  97. package/dist/server/emails.js +123 -0
  98. package/dist/server/events.d.ts +357 -0
  99. package/dist/server/events.js +219 -0
  100. package/dist/server/functions.d.ts +40 -0
  101. package/dist/server/functions.js +1 -0
  102. package/dist/server/http-utils.d.ts +10 -0
  103. package/dist/server/http-utils.js +115 -0
  104. package/dist/server/index.d.ts +195 -0
  105. package/dist/server/index.js +314 -0
  106. package/dist/server/payments.d.ts +218 -0
  107. package/dist/server/payments.js +150 -0
  108. package/dist/server/push.d.ts +85 -0
  109. package/dist/server/push.js +37 -0
  110. package/dist/server/usage.d.ts +43 -0
  111. package/dist/server/usage.js +8 -0
  112. package/dist/storage/client.d.ts +143 -0
  113. package/dist/storage/client.js +224 -0
  114. package/package.json +52 -4
  115. package/skill/usebecky/SKILL.md +339 -0
  116. package/skill/usebecky/references/access-rules.md +307 -0
  117. package/skill/usebecky/references/addons.md +68 -0
  118. package/skill/usebecky/references/analytics.md +166 -0
  119. package/skill/usebecky/references/android.md +434 -0
  120. package/skill/usebecky/references/auth.md +379 -0
  121. package/skill/usebecky/references/cache.md +51 -0
  122. package/skill/usebecky/references/components.md +127 -0
  123. package/skill/usebecky/references/emails.md +105 -0
  124. package/skill/usebecky/references/expo.md +147 -0
  125. package/skill/usebecky/references/functions.md +99 -0
  126. package/skill/usebecky/references/hosting.md +119 -0
  127. package/skill/usebecky/references/http-api.md +233 -0
  128. package/skill/usebecky/references/ios.md +355 -0
  129. package/skill/usebecky/references/payments.md +493 -0
  130. package/skill/usebecky/references/realtime.md +143 -0
  131. package/skill/usebecky/references/scheduled-jobs.md +82 -0
  132. package/skill/usebecky/references/sdk.md +838 -0
  133. package/skill/usebecky/references/storage.md +210 -0
  134. package/skill/usebecky/references/templates.md +191 -0
  135. package/skill/usebecky/references/wordpress.md +87 -0
@@ -0,0 +1,850 @@
1
+ // `npx usebecky <command>`: login, init, projects, types, open, status, ai, analytics, db, config, functions, deploy,
2
+ // hosting, payments, emails (and `social`, which the help leaves out while Social is not open to everyone).
3
+ import { spawn } from 'node:child_process';
4
+ import crypto from 'node:crypto';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { DASHBOARD_API_KEYS } from "../lib/dashboard-paths.js";
10
+ import { HOSTED_API_URL } from "../lib/hosted.js";
11
+ import { VERSION } from "../lib/http.js";
12
+ import { SKILL_TARGET, agentsPlatformFor, examplePromptsFor, findSkillSource, installSkill, writeAgentsFile } from "./ai.js";
13
+ import { analyticsCommand } from "./analytics.js";
14
+ import { configCommand } from "./config.js";
15
+ import { dbCommand } from "./db.js";
16
+ import { emailsCommand } from "./emails.js";
17
+ import { deployCommand } from "./deploy.js";
18
+ import { functionsCommand } from "./functions.js";
19
+ import { hostingCommand } from "./hosting.js";
20
+ import { paymentsCommand } from "./payments.js";
21
+ import { pushCommand } from "./push.js";
22
+ import { tokensCommand } from "./tokens.js";
23
+ import { socialCommand } from "./social.js";
24
+ import { DOCS_URL, LOOKED_FOR, NATIVE_LABELS, detectFramework, detectProject, ensureGitignore, envPlanFor, libFileFor, nativeSetup, nextSteps, relativeImport, parseEnv, writeEnvFile, writeLibFile, } from "./framework.js";
25
+ import { c, createUi } from "./ui.js";
26
+ /** The platform API every command talks to unless --api-url / USEBECKY_API_URL / a saved login says otherwise. */
27
+ export const DEFAULT_API = HOSTED_API_URL;
28
+ /** What to try when the platform API can't be reached. */
29
+ export function unreachableHint(apiUrl) {
30
+ return apiUrl === HOSTED_API_URL ? 'Check your internet connection and try again.' : `Check the address (${apiUrl}, from --api-url, USEBECKY_API_URL or your last login) and try again.`;
31
+ }
32
+ /** `init`'s last line when no secret key was saved (browser apps, Expo). */
33
+ export const PUBLISHABLE_ONLY = "Only your publishable key was saved. It's safe in browser code.";
34
+ /** `init`'s last line for web apps. */
35
+ export const ANALYTICS_HINT = `See who visits your website: ${c.cyan('npx usebecky analytics')} adds visitor analytics in one step.`;
36
+ export function parseArgs(argv) {
37
+ const flags = { _: [], yes: false, help: false, version: false };
38
+ for (let i = 0; i < argv.length; i++) {
39
+ const a = argv[i];
40
+ const [name, inline] = a.startsWith('--') && a.includes('=') ? [a.slice(0, a.indexOf('=')), a.slice(a.indexOf('=') + 1)] : [a, undefined];
41
+ const value = () => inline ?? argv[++i];
42
+ if (name === '--api-url')
43
+ flags.apiUrl = value();
44
+ else if (name === '--project' || name === '-p')
45
+ flags.project = value();
46
+ else if (name === '--out' || name === '-o')
47
+ flags.out = value();
48
+ else if (name === '--yes' || name === '-y')
49
+ flags.yes = true;
50
+ else if (name === '--help' || name === '-h')
51
+ flags.help = true;
52
+ else if (name === '--version' || name === '-v')
53
+ flags.version = true;
54
+ else if (name === '--force' || name === '-f')
55
+ flags.force = true;
56
+ else if (name === '--key')
57
+ flags.key = value();
58
+ else if (name === '--dry-run')
59
+ flags.dryRun = true;
60
+ else if (name === '--email')
61
+ flags.email = true;
62
+ else if (name === '--no-browser')
63
+ flags.noBrowser = true;
64
+ else
65
+ flags._.push(a);
66
+ }
67
+ return flags;
68
+ }
69
+ const HELP = `
70
+ ${c.bold('usebecky')} ${c.dim(`v${VERSION}`)}: your whole backend in one package.
71
+
72
+ ${c.bold('Usage:')} npx usebecky <command> [options]
73
+
74
+ ${c.bold('Commands:')}
75
+ ${c.cyan('create')} Make a new app from a starter, connected to a project (same as npm create usebecky@latest)
76
+ ${c.cyan('init')} Pick a project and connect this app: web/Node writes .env + lib/usebecky.ts, iOS/Android prints the Swift/Kotlin client code
77
+ ${c.cyan('login')} Sign in to your usebecky account in the browser (--email: with email and password here)
78
+ ${c.cyan('logout')} Sign out on this computer
79
+ ${c.cyan('projects')} List your projects
80
+ ${c.cyan('types')} Generate usebecky.types.ts from your database (for autocomplete)
81
+ ${c.cyan('open')} Open the dashboard for the linked project
82
+ ${c.cyan('status')} Show the linked project and whether the API is reachable
83
+ ${c.cyan('ai')} Teach your AI assistant (Claude Code, Cursor, Codex, Copilot...) to use usebecky (alias: skill)
84
+ ${c.cyan('analytics')} Add visitor analytics to your website: puts the script tag in the right file
85
+ ${c.cyan('push')} Release everything in one step: db push, config push, functions deploy, deploy --prod (--dry-run)
86
+ ${c.cyan('db')} Database migrations as SQL files: db new <name>, db pull, db push, db diff
87
+ ${c.cyan('config')} The project's settings as one file (usebecky/config.json): config pull, config push [--dry-run]
88
+ (sign-in providers, redirect URLs, buckets and their access, realtime, analytics, products and prices)
89
+ ${c.cyan('tokens')} Project tokens for CI instead of a login: tokens create <name> --scope db,config, tokens list
90
+ ${c.cyan('payments')} Stripe: payments connect (sign in at Stripe), payments mode [live|test], payments products
91
+ ${c.cyan('emails')} Send from your own domain: emails domains list | add <domain> | check <domain> | remove <domain>
92
+ ${c.cyan('functions')} Your own code on usebecky: functions new <name>, deploy, list, logs, secrets set NAME=value
93
+ ${c.cyan('deploy')} Put your website or Node.js app online (Hosting, Business plan): builds, uploads, prints the address
94
+ ${c.cyan('hosting')} Your sites: hosting list, deploys, rollback, promote, env, domains, logs, github
95
+
96
+ ${c.bold('Options:')}
97
+ --api-url <url> usebecky API (env USEBECKY_API_URL, default ${DEFAULT_API})
98
+ --project <ref> Use this project instead of the linked one
99
+ --out <file> Output file for \`types\` (default usebecky.types.ts)
100
+ -f, --force \`ai\`: replace skill files you changed with this version (use it after updating);
101
+ \`db push\`: push even with dashboard changes that aren't in a migration yet;
102
+ \`config pull\`: replace a usebecky/config.json that differs;
103
+ \`functions new\`: replace an existing file
104
+ --key <ub_pk_...> \`analytics\`: the publishable key (default: from the env file \`init\` wrote)
105
+ --dry-run \`analytics\`, \`db push\`, \`config push\`: show what would change, change nothing
106
+ --site <name> \`deploy\`, \`hosting\`: which site; --prod: put the deploy live; --no-build: skip the build
107
+ --no-browser \`login\`: only print the sign-in link (open it on any device)
108
+ --email \`login\`: email and password in the terminal instead of the browser
109
+ -y, --yes Don't ask questions (keeps existing values)
110
+
111
+ ${c.bold('Environment:')} USEBECKY_ACCESS_TOKEN (instead of login: your session or a project token ubpt_…), USEBECKY_DEPLOY_TOKEN (\`deploy\` in CI), USEBECKY_API_URL
112
+ `;
113
+ /** Commands whose `help` subcommand prints their own help. */
114
+ const OWN_HELP = ['push', 'db', 'config', 'tokens', 'payments', 'emails', 'functions', 'fn', 'deploy', 'hosting', 'social'];
115
+ export async function run(argv, ctx = {}) {
116
+ const flags = parseArgs(argv);
117
+ const env = ctx.env ?? process.env;
118
+ const cwd = ctx.cwd ?? process.cwd();
119
+ const io = { input: ctx.io?.input ?? process.stdin, output: ctx.io?.output ?? process.stdout, yes: flags.yes || !!ctx.io?.yes };
120
+ const ui = createUi(io);
121
+ const configDir = defaultConfigDir(ctx.configDir ?? env.USEBECKY_CONFIG_DIR);
122
+ const configFile = path.join(configDir, 'config.json');
123
+ const fetchImpl = ctx.fetch ?? fetch;
124
+ const config = readJson(configFile) ?? {};
125
+ const linked = readLinked(cwd);
126
+ const apiUrl = (flags.apiUrl ?? env.USEBECKY_API_URL ?? config.apiUrl ?? DEFAULT_API).replace(/\/+$/, '');
127
+ const token = env.USEBECKY_ACCESS_TOKEN ?? (config.apiUrl && config.apiUrl.replace(/\/+$/, '') !== apiUrl ? undefined : config.token);
128
+ const saveConfig = (next) => {
129
+ fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
130
+ fs.writeFileSync(configFile, JSON.stringify(next, null, 2) + '\n', { mode: 0o600 });
131
+ };
132
+ async function api(method, p, body, auth = token, extra = {}) {
133
+ let res;
134
+ try {
135
+ res = await fetchImpl(`${apiUrl}/platform/v1${p}`, {
136
+ method,
137
+ headers: { 'content-type': extra.raw ? 'application/octet-stream' : 'application/json', 'x-client-info': `usebecky-cli/${VERSION}`, 'user-agent': CLI_USER_AGENT, ...(auth ? { authorization: `Bearer ${auth}` } : {}), ...extra.headers },
138
+ body: extra.raw ?? (body === undefined ? undefined : JSON.stringify(body)),
139
+ });
140
+ }
141
+ catch {
142
+ return { data: null, error: { code: 'network_error', message: `Could not reach usebecky at ${apiUrl}.`, hint: unreachableHint(apiUrl), status: 0 } };
143
+ }
144
+ const text = await res.text();
145
+ let json = null;
146
+ try {
147
+ json = text ? JSON.parse(text) : null;
148
+ }
149
+ catch {
150
+ json = text;
151
+ }
152
+ if (!res.ok) {
153
+ const e = json?.error ?? {};
154
+ return { data: null, error: { code: e.code ?? `http_${res.status}`, message: e.message ?? `Request failed (${res.status}).`, hint: e.hint, status: res.status, details: e.details } };
155
+ }
156
+ return { data: json, error: null };
157
+ }
158
+ function printError(e) {
159
+ ui.error(e.message);
160
+ if (e.hint)
161
+ ui.write(` ${c.dim(e.hint)}`);
162
+ }
163
+ // This computer's id, sent with every sign-in: a computer the account never used gets the "new sign-in" email.
164
+ const deviceId = config.deviceId && /^[A-Za-z0-9_-]{16,100}$/.test(config.deviceId) ? config.deviceId : crypto.randomBytes(18).toString('base64url');
165
+ /** Sign-in in the browser by default (every account: GitHub / Google without a password, passkeys, two-factor);
166
+ * `--email` asks for email and password here instead. Used by `login` and by every command that needs a login. */
167
+ async function login() {
168
+ ui.write(`${c.bold('Sign in to usebecky')} ${c.dim(`(${apiUrl})`)}`);
169
+ if (io.yes) {
170
+ ui.error('Not signed in. Run `npx usebecky login` first (or set USEBECKY_ACCESS_TOKEN).');
171
+ return null;
172
+ }
173
+ return flags.email ? loginWithPassword() : loginInBrowser();
174
+ }
175
+ function signedIn(token, account, fallbackEmail) {
176
+ const email = account?.email ?? fallbackEmail;
177
+ saveConfig({ ...config, apiUrl, token, email, deviceId });
178
+ ui.success(`Signed in as ${c.bold(email ?? 'your account')}`);
179
+ // Not confirmed yet: building works; upgrading, invites and newsletters wait for the click.
180
+ if (account?.email_verified === false)
181
+ ui.write(c.dim(' Confirm your email address: click the link we sent you.'));
182
+ return token;
183
+ }
184
+ /** The browser signs in (platform/cli-login.ts on the server): show the code and the link, open it, wait for Allow. */
185
+ async function loginInBrowser() {
186
+ const started = await api('POST', '/auth/cli/sessions', { device_id: deviceId }, null);
187
+ if (started.error || !started.data?.id) {
188
+ printError(started.error ?? { message: 'Could not start the sign-in.' });
189
+ if (started.error?.status === 404)
190
+ ui.write(` ${c.dim('This server signs in with email and password only: run `npx usebecky login --email`.')}`);
191
+ return null;
192
+ }
193
+ const s = started.data;
194
+ // A terminal of its own opens the browser; --no-browser, a pipe or CI only print the link (open it on any device).
195
+ const open = !flags.noBrowser && !ctx.noOpen && !!io.output.isTTY;
196
+ ui.write('');
197
+ ui.write(` Code: ${c.bold(s.user_code)}`);
198
+ ui.write(` ${open ? 'Opening' : 'Open'} ${c.cyan(s.verification_url)}`);
199
+ ui.write('');
200
+ if (open)
201
+ (ctx.openUrl ?? openBrowser)(s.verification_url);
202
+ ui.write(c.dim(' Waiting for you to click Allow… (Ctrl+C to stop)'));
203
+ const sleep = ctx.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
204
+ const deadline = Date.now() + Math.max(60, s.expires_in || 600) * 1000;
205
+ const interval = Math.max(1, s.interval || 2) * 1000;
206
+ let wait = interval;
207
+ let failures = 0;
208
+ while (Date.now() < deadline) {
209
+ await sleep(wait);
210
+ const r = await api('POST', '/auth/cli/sessions/token', { id: s.id }, null);
211
+ if (r.data?.token)
212
+ return signedIn(r.data.token, r.data.account);
213
+ const e = r.error ?? { code: 'unknown', message: 'Sign-in failed.', status: 0 };
214
+ if (e.code === 'authorization_pending') {
215
+ failures = 0;
216
+ wait = interval;
217
+ continue;
218
+ }
219
+ if (e.code === 'access_denied') {
220
+ ui.error('Cancelled in the browser.');
221
+ return null;
222
+ }
223
+ if (e.code === 'expired_token')
224
+ break;
225
+ // Offline for a moment, too many checks, the server restarting: wait longer and keep waiting.
226
+ if ((e.code === 'network_error' || e.code === 'rate_limited' || e.status >= 500) && ++failures < 30) {
227
+ wait = Math.min(wait * 2, 15_000);
228
+ continue;
229
+ }
230
+ printError(e);
231
+ return null;
232
+ }
233
+ ui.error('The sign-in expired. Run `npx usebecky login` again.');
234
+ return null;
235
+ }
236
+ /** `npx usebecky login --email`: email and password here (offers to make an account), then the two-factor step. */
237
+ async function loginWithPassword() {
238
+ const email = await ui.ask('Email:');
239
+ if (!email)
240
+ return null;
241
+ const password = await ui.askHidden('Password:');
242
+ let r = await api('POST', '/auth/login', { email, password, device_id: deviceId }, null);
243
+ // Made with GitHub / Google: no password to type (the server's hint names the provider). The browser can sign it in.
244
+ if (r.error?.code === 'invalid_credentials' && /signs in with/i.test(r.error.hint ?? '')) {
245
+ ui.error(r.error.message);
246
+ ui.write(` ${c.dim(`${r.error.hint.replace(/:.*$/, '')}. Run \`npx usebecky login\` without --email to sign in in the browser.`)}`);
247
+ return null;
248
+ }
249
+ if (r.error?.code === 'invalid_credentials' && (await ui.confirm(`No account matched. Create a new account for ${email}?`, false))) {
250
+ r = await api('POST', '/auth/signup', { email, password, device_id: deviceId }, null);
251
+ }
252
+ // Two-factor sign-in on (Account → Security in the dashboard): ask for the second step.
253
+ const step = r.data;
254
+ if (!r.error && step?.mfa_required && step.mfa_token) {
255
+ const app = step.methods?.includes('totp');
256
+ if (!app)
257
+ ui.write(c.dim(' Passkeys only work in the browser: run `npx usebecky login` without --email, or use a recovery code.'));
258
+ const code = await ui.ask(app ? 'Code from your authenticator app (or a recovery code):' : 'Recovery code:');
259
+ if (!code)
260
+ return null;
261
+ r = await api('POST', '/auth/mfa/verify', { mfa_token: step.mfa_token, code, device_id: deviceId }, null);
262
+ }
263
+ if (r.error || !r.data?.token) {
264
+ printError(r.error ?? { message: 'Sign-in failed.' });
265
+ return null;
266
+ }
267
+ return signedIn(r.data.token, r.data.account, email);
268
+ }
269
+ async function requireToken() {
270
+ if (token)
271
+ return token;
272
+ return login();
273
+ }
274
+ try {
275
+ if (flags.version) {
276
+ ui.write(VERSION);
277
+ return 0;
278
+ }
279
+ // `help hosting` is `hosting help` (like `git help <command>`).
280
+ if (flags._[0] === 'help' && OWN_HELP.includes(flags._[1]))
281
+ flags._ = [flags._[1], 'help'];
282
+ const command = flags._[0] ?? 'help';
283
+ // `create` is create-usebecky (npm create usebecky@latest): pass every argument through, --help included.
284
+ if (command === 'create')
285
+ return await createApp(argv.filter((_, i) => i !== argv.indexOf('create')));
286
+ // Commands with a help of their own show it for `<command> [sub…] --help` (e.g. `hosting domains --help`), not the
287
+ // general one. `social` reads --help itself (the general help does not name it).
288
+ if (flags.help && OWN_HELP.includes(command) && command !== 'social')
289
+ flags._ = [command, 'help'];
290
+ else if ((flags.help && command !== 'social') || command === 'help') {
291
+ ui.write(HELP);
292
+ return 0;
293
+ }
294
+ switch (command) {
295
+ case 'login': {
296
+ return (await login()) ? 0 : 1;
297
+ }
298
+ case 'logout': {
299
+ if (config.token)
300
+ await api('POST', '/auth/logout', {}, config.token);
301
+ saveConfig({ ...config, token: undefined });
302
+ ui.success('Signed out.');
303
+ return 0;
304
+ }
305
+ case 'projects': {
306
+ const t = await requireToken();
307
+ if (!t)
308
+ return 1;
309
+ const r = await api('GET', '/projects', undefined, t);
310
+ if (r.error)
311
+ return handleAuthError(r.error);
312
+ if (!r.data?.length) {
313
+ ui.info('You have no projects yet. Run `npx usebecky init` to create one.');
314
+ return 0;
315
+ }
316
+ ui.write(c.bold('Your projects:'));
317
+ for (const p of r.data) {
318
+ const mark = p.ref === (flags.project ?? linked.ref) ? c.green(' ← linked') : '';
319
+ ui.write(` ${c.bold(p.name)} ${c.dim(p.ref)} ${statusColor(p.status)} ${c.dim(p.plan)}${mark}`);
320
+ }
321
+ return 0;
322
+ }
323
+ case 'init':
324
+ return await init();
325
+ case 'types': {
326
+ const ref = flags.project ?? linked.ref;
327
+ if (!ref)
328
+ return noProject();
329
+ const t = await requireToken();
330
+ if (!t)
331
+ return 1;
332
+ let res;
333
+ try {
334
+ res = await fetchImpl(`${apiUrl}/platform/v1/projects/${ref}/database/types/typescript`, { headers: { authorization: `Bearer ${t}` } });
335
+ }
336
+ catch {
337
+ printError({ message: `Could not reach usebecky at ${apiUrl}.`, hint: unreachableHint(apiUrl) });
338
+ return 1;
339
+ }
340
+ const text = await res.text();
341
+ if (!res.ok) {
342
+ let e = {};
343
+ try {
344
+ e = JSON.parse(text).error ?? {};
345
+ }
346
+ catch { }
347
+ return handleAuthError({ code: e.code ?? `http_${res.status}`, message: e.message ?? `Could not generate types (${res.status}).`, hint: e.hint, status: res.status });
348
+ }
349
+ const out = path.resolve(cwd, flags.out ?? 'usebecky.types.ts');
350
+ fs.mkdirSync(path.dirname(out), { recursive: true });
351
+ fs.writeFileSync(out, text);
352
+ ui.success(`Wrote ${c.bold(path.relative(cwd, out) || out)}`);
353
+ // Show the import from the client file (lib/usebecky.ts) when there is one, else from the project folder.
354
+ const client = libFileFor(detectFramework(cwd)).path;
355
+ const inClient = /\.ts$/.test(client) && fs.existsSync(path.join(cwd, client));
356
+ const typesFile = path.relative(cwd, out).replace(/\\/g, '/').replace(/\.ts$/, '');
357
+ const typesPath = relativeImport(inClient ? client : 'file-in-project-folder.ts', typesFile);
358
+ ui.write(`\n Use it for autocomplete${inClient ? `, in ${c.bold(client)}` : ' (path from a file in the project folder)'}:\n ${c.cyan(`import type { Database } from '${typesPath}'`)}\n ${c.cyan('createClient<Database>(...) // add <Database> where the client is created')}\n`);
359
+ return 0;
360
+ }
361
+ case 'open': {
362
+ const ref = flags.project ?? linked.ref;
363
+ const cfg = await api('GET', '/config', undefined, null);
364
+ const dashboard = (cfg.data?.dashboard_url ?? apiUrl).replace(/\/+$/, '');
365
+ const url = ref ? `${dashboard}/project/${ref}` : dashboard;
366
+ ui.info(`Opening ${c.cyan(url)}`);
367
+ if (!ctx.noOpen)
368
+ (ctx.openUrl ?? openBrowser)(url);
369
+ return 0;
370
+ }
371
+ case 'status': {
372
+ ui.write(c.bold('usebecky status'));
373
+ ui.write(` API: ${apiUrl}`);
374
+ ui.write(` Account: ${token ? (config.email ?? 'signed in') : c.yellow('not signed in (npx usebecky login)')}`);
375
+ const ref = flags.project ?? linked.ref;
376
+ ui.write(` Project: ${ref ? `${ref}${linked.file && !flags.project ? c.dim(` (from ${linked.file})`) : ''}` : c.yellow('not linked (npx usebecky init)')}`);
377
+ let ok = false;
378
+ try {
379
+ const h = await fetchImpl(`${apiUrl}/healthz`);
380
+ ok = h.ok;
381
+ }
382
+ catch { }
383
+ ui.write(` Reachable: ${ok ? c.green('yes') : c.red('no')}`);
384
+ if (ok && ref && token) {
385
+ const p = await api('GET', `/projects/${ref}`);
386
+ if (p.data)
387
+ ui.write(` Name: ${p.data.name} (${statusColor(p.data.status)}, ${p.data.plan} plan)`);
388
+ else if (p.error)
389
+ ui.write(` ${c.yellow(p.error.message)}`);
390
+ }
391
+ if (ok && linked.key) {
392
+ const url = (linked.url ?? apiUrl).replace(/\/+$/, '');
393
+ try {
394
+ const r = await fetchImpl(`${url}/auth/v1/settings`, { headers: { apikey: linked.key } });
395
+ ui.write(` API key: ${r.ok ? c.green('valid') : c.red(`rejected (${r.status}): copy it again from ${DASHBOARD_API_KEYS}`)}`);
396
+ }
397
+ catch {
398
+ ui.write(` API key: ${c.red(`could not reach ${url}`)}`);
399
+ }
400
+ }
401
+ return ok ? 0 : 1;
402
+ }
403
+ case 'ai':
404
+ case 'skill':
405
+ return ai();
406
+ case 'db': {
407
+ const ref = flags.project ?? linked.ref;
408
+ let auth = token ?? null;
409
+ return await dbCommand({
410
+ cwd,
411
+ ui,
412
+ args: flags._.slice(1),
413
+ ref,
414
+ yes: io.yes,
415
+ dryRun: !!flags.dryRun,
416
+ force: !!flags.force,
417
+ signIn: async () => !!(auth = await requireToken()),
418
+ api: (method, p, body) => api(method, `/projects/${ref}${p}`, body, auth),
419
+ printError: (e) => handleAuthError({ code: 'error', status: 0, ...e }),
420
+ noProject,
421
+ });
422
+ }
423
+ case 'push': {
424
+ const ref = flags.project ?? linked.ref ?? null;
425
+ // Every step runs as its own command, with the same project, API address and answers.
426
+ const common = [...(ref ? ['--project', ref] : []), '--api-url', apiUrl, ...(io.yes ? ['-y'] : [])];
427
+ return await pushCommand({
428
+ cwd,
429
+ ui,
430
+ args: flags._.slice(1),
431
+ ref,
432
+ dryRun: !!flags.dryRun,
433
+ force: !!flags.force,
434
+ common,
435
+ run: (stepArgv) => run(stepArgv, { ...ctx, io: { input: io.input, output: io.output, yes: io.yes } }),
436
+ noProject,
437
+ });
438
+ }
439
+ case 'config': {
440
+ const ref = flags.project ?? linked.ref;
441
+ let auth = token ?? null;
442
+ return await configCommand({
443
+ cwd,
444
+ ui,
445
+ args: flags._.slice(1),
446
+ ref,
447
+ yes: io.yes,
448
+ dryRun: !!flags.dryRun,
449
+ force: !!flags.force,
450
+ env,
451
+ signIn: async () => !!(auth = await requireToken()),
452
+ api: (method, p, body) => api(method, `/projects/${ref}${p}`, body, auth),
453
+ printError: (e) => handleAuthError({ code: 'error', status: 0, ...e }),
454
+ noProject,
455
+ });
456
+ }
457
+ case 'payments':
458
+ case 'emails':
459
+ case 'tokens': {
460
+ const ref = flags.project ?? linked.ref;
461
+ let auth = token ?? null;
462
+ const shared = {
463
+ ui,
464
+ args: flags._.slice(1),
465
+ ref,
466
+ yes: io.yes,
467
+ signIn: async () => !!(auth = await requireToken()),
468
+ api: (method, p, body) => api(method, `/projects/${ref}${p}`, body, auth),
469
+ printError: (e) => handleAuthError({ code: 'error', status: 0, ...e }),
470
+ noProject,
471
+ env,
472
+ };
473
+ if (command === 'emails')
474
+ return await emailsCommand(shared);
475
+ if (command === 'tokens')
476
+ return await tokensCommand(shared);
477
+ return await paymentsCommand({
478
+ ...shared,
479
+ dashboardUrl: async () => (await api('GET', '/config', undefined, null)).data?.dashboard_url ?? null,
480
+ // Like login: a terminal of its own opens the browser; --no-browser, a pipe or CI only print the link.
481
+ openUrl: !flags.noBrowser && !ctx.noOpen && !!io.output.isTTY ? (ctx.openUrl ?? openBrowser) : null,
482
+ sleep: ctx.sleep,
483
+ });
484
+ }
485
+ case 'functions':
486
+ case 'fn': {
487
+ const ref = flags.project ?? linked.ref;
488
+ let auth = token ?? null;
489
+ return await functionsCommand({
490
+ cwd,
491
+ ui,
492
+ args: flags._.slice(1),
493
+ ref,
494
+ yes: io.yes,
495
+ force: !!flags.force,
496
+ signIn: async () => !!(auth = await requireToken()),
497
+ api: (method, p, body) => api(method, `/projects/${ref}${p}`, body, auth),
498
+ printError: (e) => handleAuthError({ code: 'error', status: 0, ...e }),
499
+ noProject,
500
+ loadEsbuild: ctx.loadEsbuild,
501
+ });
502
+ }
503
+ case 'social': {
504
+ const ref = flags.project ?? linked.ref;
505
+ let auth = token ?? null;
506
+ return await socialCommand({
507
+ cwd,
508
+ ui,
509
+ args: flags._.slice(1),
510
+ help: flags.help,
511
+ ref,
512
+ signedIn: !!auth,
513
+ signIn: async () => !!(auth = await requireToken()),
514
+ api: (method, p, body, extra) => api(method, `/projects/${ref}/social${p}`, body, auth, extra),
515
+ noProject,
516
+ ...ctx.social,
517
+ });
518
+ }
519
+ case 'deploy':
520
+ case 'hosting': {
521
+ let session = token ?? null;
522
+ const hostingCtx = {
523
+ cwd,
524
+ ui,
525
+ output: io.output,
526
+ args: flags._.slice(1),
527
+ project: flags.project,
528
+ linkedRef: linked.ref,
529
+ refOfFolder: (dir) => readLinked(dir).ref,
530
+ yes: io.yes,
531
+ force: !!flags.force,
532
+ sessionToken: session,
533
+ deployToken: env.USEBECKY_DEPLOY_TOKEN?.trim() || null,
534
+ signIn: async () => (session = await requireToken()),
535
+ api: (method, p, body, auth) => api(method, p, body, auth),
536
+ apiUrl,
537
+ fetch: fetchImpl,
538
+ dashboardUrl: async () => (await api('GET', '/config', undefined, null)).data?.dashboard_url ?? null,
539
+ env,
540
+ ...ctx.hosting,
541
+ };
542
+ return command === 'deploy' ? await deployCommand(hostingCtx) : await hostingCommand(hostingCtx);
543
+ }
544
+ case 'analytics':
545
+ return await analyticsCommand({
546
+ cwd,
547
+ ui,
548
+ interactive: !io.yes,
549
+ // --api-url here is the API URL in the tag (the Project URL), like the one in the env file.
550
+ flags: { key: flags.key, apiUrl: flags.apiUrl, dryRun: flags.dryRun },
551
+ defaultApiUrl: apiUrl,
552
+ linked,
553
+ dashboard: dashboardLink,
554
+ });
555
+ default:
556
+ ui.error(`Unknown command "${command}".`);
557
+ ui.write(HELP);
558
+ return 1;
559
+ }
560
+ }
561
+ finally {
562
+ ui.close();
563
+ }
564
+ /** Run create-usebecky: the copy next to this package in the usebecky repo, otherwise the latest from npm. */
565
+ async function createApp(args) {
566
+ ui.close(); // create-usebecky asks its own questions on this terminal
567
+ const local = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../create-usebecky/src/index.ts');
568
+ const [command, commandArgs] = fs.existsSync(local) ? [process.execPath, [local, ...args]] : ['npx', ['--yes', 'create-usebecky@latest', ...args]];
569
+ const runAttached = ctx.runAttached ??
570
+ ((cmd, cmdArgs) => new Promise((resolve) => {
571
+ const child = spawn(cmd, cmdArgs, { cwd, stdio: 'inherit', shell: process.platform === 'win32' });
572
+ child.on('error', () => {
573
+ ui.error('Could not start create-usebecky. Try: npm create usebecky@latest');
574
+ resolve(1);
575
+ });
576
+ child.on('close', (code) => resolve(code ?? 1));
577
+ }));
578
+ return runAttached(command, commandArgs);
579
+ }
580
+ function noProject() {
581
+ ui.error('No linked project found.');
582
+ ui.write(` ${c.dim('Run `npx usebecky init` in your app folder, or pass --project <ref>.')}`);
583
+ return 1;
584
+ }
585
+ function handleAuthError(e) {
586
+ printError(e);
587
+ if (e.status === 401)
588
+ ui.write(` ${c.dim('Your login expired. Run `npx usebecky login` again.')}`);
589
+ return 1;
590
+ }
591
+ /** Nothing in the folder looks like an app: say what was looked for and how to go on. Never guess Node.js. */
592
+ function noApp() {
593
+ ui.error('No app found in this folder.');
594
+ ui.write(` ${c.dim(`Looked for ${LOOKED_FOR}.`)}`);
595
+ ui.write(` - Run ${c.cyan('npx usebecky init')} in your app's folder: the one that contains one of these.`);
596
+ ui.write(` - No app yet? ${c.cyan('npx usebecky create')} makes a web or Expo app. For Swift or Kotlin, follow ${c.cyan(`${DOCS_URL}/frameworks/ios`)} or ${c.cyan(`${DOCS_URL}/frameworks/android`)}.`);
597
+ ui.write(` - Starting a Node.js server here? Run ${c.cyan('npm init -y')} first, then ${c.cyan('npx usebecky init')} again.`);
598
+ return 1;
599
+ }
600
+ async function dashboardLink(ref) {
601
+ const cfg = await api('GET', '/config', undefined, null);
602
+ return cfg.data?.dashboard_url ? `${cfg.data.dashboard_url.replace(/\/+$/, '')}/project/${ref}` : null;
603
+ }
604
+ /**
605
+ * iOS / Android: print the client code with the Project URL and publishable key. Nothing is written to
606
+ * the folder (the publishable key is safe to keep in the app's code, so no config file is needed) and the
607
+ * secret key is never shown: anyone can read every value inside an app.
608
+ */
609
+ async function initNative(native, keys, ref) {
610
+ ui.write(`\nYour app needs two values: the ${c.bold('Project URL')} and the ${c.bold('publishable key')} (safe inside an app).`);
611
+ ui.write(`${c.dim('Nothing was written to this folder: the values go straight into your code. The secret key (ub_sk_...) must never be in an app, so it is not shown.')}`);
612
+ for (const platform of native.platforms) {
613
+ const setup = nativeSetup(platform, keys, cwd);
614
+ ui.write(`\n${c.bold(`${setup.title}: put this in ${setup.file}`)}\n`);
615
+ for (const line of setup.code.split('\n'))
616
+ ui.write(line ? ` ${c.cyan(line)}` : '');
617
+ ui.write('');
618
+ for (const note of setup.notes)
619
+ ui.warn(note);
620
+ ui.write(`\n${c.bold('Next steps:')}`);
621
+ let n = 0;
622
+ for (const step of setup.steps)
623
+ ui.write(step.startsWith(' ') ? ` ${step}` : ` ${c.cyan(`${++n}.`)} ${step}`);
624
+ }
625
+ const dashboard = await dashboardLink(ref);
626
+ if (dashboard)
627
+ ui.write(`\n Dashboard: ${c.cyan(dashboard)} ${c.dim(`(the same values are under ${DASHBOARD_API_KEYS})`)}`);
628
+ ui.write('');
629
+ return 0;
630
+ }
631
+ async function init() {
632
+ const app = detectProject(cwd);
633
+ const detected = app.detected;
634
+ ui.write(`\n${c.bold(c.magenta('usebecky'))} ${c.dim('init')}\n`);
635
+ if (app.kind === 'none')
636
+ return noApp();
637
+ if (app.kind === 'native')
638
+ ui.info(`Detected ${c.bold(app.native.platforms.map((p) => NATIVE_LABELS[p]).join(' and '))}: ${c.dim(app.native.markers.join(', '))}`);
639
+ else
640
+ ui.info(`Detected ${c.bold(detected.label)}${detected.typescript ? ' with TypeScript' : ''}`);
641
+ const t = await requireToken();
642
+ if (!t)
643
+ return 1;
644
+ // 1. Pick or create a project
645
+ let ref = flags.project;
646
+ if (!ref) {
647
+ const r = await api('GET', '/projects', undefined, t);
648
+ if (r.error)
649
+ return handleAuthError(r.error);
650
+ const projects = r.data ?? [];
651
+ const NEW = '__new__';
652
+ const choice = projects.length === 0
653
+ ? NEW
654
+ : await ui.choose('Which project should this app use?', [...projects.map((p) => ({ label: `${p.name} ${c.dim(p.ref)}`, value: p.ref })), { label: c.green('+ Create a new project'), value: NEW }], Math.max(0, projects.findIndex((p) => p.ref === linked.ref)));
655
+ if (choice === NEW) {
656
+ const name = await ui.ask('Project name:', path.basename(cwd) || 'my-app');
657
+ ui.info('Creating your project (takes a few seconds)...');
658
+ const created = await api('POST', '/projects', { name }, t);
659
+ if (created.error || !created.data)
660
+ return handleAuthError(created.error ?? { code: 'unknown', message: 'Could not create the project.', status: 500 });
661
+ ref = created.data.ref;
662
+ ui.success(`Created ${c.bold(created.data.name)} ${c.dim(ref)}`);
663
+ }
664
+ else
665
+ ref = choice;
666
+ }
667
+ // 2. Keys
668
+ const k = await api('GET', `/projects/${ref}/keys`, undefined, t);
669
+ if (k.error || !k.data)
670
+ return handleAuthError(k.error ?? { code: 'unknown', message: 'Could not load the API keys.', status: 500 });
671
+ // Native apps only ever get the URL and the publishable key.
672
+ if (app.kind === 'native')
673
+ return initNative(app.native, { url: k.data.url, publishableKey: k.data.publishable_key }, ref);
674
+ const keys = { url: k.data.url, publishableKey: k.data.publishable_key, secretKey: k.data.secret_key };
675
+ // 3. Env file
676
+ const plan = envPlanFor(detected.framework, keys);
677
+ const envPath = path.join(cwd, plan.file);
678
+ const written = await writeEnvFile(envPath, plan.vars, (name, oldValue) => ui.confirm(`${plan.file} already has ${c.bold(name)}=${c.dim(mask(oldValue))}. Replace it?`, false));
679
+ if (written.added.length || written.updated.length)
680
+ ui.success(`${written.created ? 'Created' : 'Updated'} ${c.bold(plan.file)} ${c.dim(`(${[...written.added, ...written.updated].join(', ')})`)}`);
681
+ else
682
+ ui.info(`${plan.file} already up to date`);
683
+ if (written.kept.length)
684
+ ui.warn(`Kept your existing ${written.kept.join(', ')} in ${plan.file}`);
685
+ // 4. Keep env files out of git
686
+ const gi = ensureGitignore(cwd, ['.env', '.env.local']);
687
+ if (gi.added.length)
688
+ ui.success(`${gi.created ? 'Created' : 'Updated'} ${c.bold('.gitignore')} ${c.dim(`(ignores ${gi.added.join(', ')})`)}`);
689
+ // 5. Client file
690
+ const lib = libFileFor(detected);
691
+ const libResult = writeLibFile(cwd, lib);
692
+ if (libResult.created)
693
+ ui.success(`Created ${c.bold(lib.path)}`);
694
+ else
695
+ ui.info(`${lib.path} already exists, left it alone`);
696
+ // 6. Next steps
697
+ const needsInstall = !Object.prototype.hasOwnProperty.call(detected.dependencies, 'usebecky');
698
+ ui.write(`\n${c.bold('Next steps:')}`);
699
+ nextSteps(detected, lib, needsInstall).forEach((s, i) => ui.write(` ${c.cyan(`${i + 1}.`)} ${s}`));
700
+ const dashboard = await dashboardLink(ref);
701
+ if (dashboard)
702
+ ui.write(`\n Dashboard: ${c.cyan(dashboard)} ${c.dim('(or run `npx usebecky open`)')}`);
703
+ // Warn about the secret key only when the env file now holds one (written now, or already there).
704
+ const hasSecret = [...written.added, ...written.updated, ...written.unchanged, ...written.kept].includes('USEBECKY_SECRET_KEY');
705
+ ui.write(` ${c.dim(hasSecret ? `Your secret key is in ${plan.file} for server code only. Never commit it or use it in browser or app code.` : PUBLISHABLE_ONLY)}`);
706
+ if (detected.framework !== 'expo')
707
+ ui.write(` ${ANALYTICS_HINT}`);
708
+ ui.write('');
709
+ return 0;
710
+ }
711
+ /** `npx usebecky ai`: install the skill + AGENTS.md section. Local only: no login, no network. */
712
+ function ai() {
713
+ const source = ctx.skillDir ?? findSkillSource();
714
+ if (!source || !fs.existsSync(path.join(source, 'SKILL.md'))) {
715
+ ui.error('Could not find the usebecky skill files in this installation.');
716
+ ui.write(` ${c.dim('Run `npx usebecky@latest ai` to use a fresh copy.')}`);
717
+ return 1;
718
+ }
719
+ const force = !!flags.force;
720
+ const app = detectProject(cwd);
721
+ const platform = agentsPlatformFor(app);
722
+ ui.write(`\n${c.bold(c.magenta('usebecky'))} ${c.dim('ai')}\n`);
723
+ if (app.kind === 'native')
724
+ ui.info(`Detected ${c.bold(app.native.platforms.map((p) => NATIVE_LABELS[p]).join(' and '))}: ${c.dim(app.native.markers.join(', '))}`);
725
+ const files = installSkill(source, cwd, force);
726
+ const count = (s) => files.filter((f) => f.status === s).length;
727
+ for (const f of files) {
728
+ if (f.status === 'created')
729
+ ui.success(`Created ${c.bold(f.path)}`);
730
+ else if (f.status === 'updated')
731
+ ui.success(`Updated ${c.bold(f.path)}`);
732
+ }
733
+ const kept = files.filter((f) => f.status === 'kept');
734
+ if (count('unchanged') === files.length)
735
+ ui.info(`${SKILL_TARGET}/ is already up to date (${files.length} files)`);
736
+ else if (count('unchanged'))
737
+ ui.info(`${count('unchanged')} other skill file${count('unchanged') === 1 ? ' is' : 's are'} already up to date`);
738
+ if (kept.length) {
739
+ const one = kept.length === 1;
740
+ ui.warn(`Kept ${kept.length} skill file${one ? ' that differs' : 's that differ'} from this version (edited, or from another usebecky version):`);
741
+ for (const f of kept)
742
+ ui.write(` ${f.path}`);
743
+ ui.write(` ${c.dim(`Run \`npx usebecky ai --force\` to replace ${one ? 'it' : 'them'}.`)}`);
744
+ }
745
+ const agents = writeAgentsFile(cwd, force, platform);
746
+ if (agents.status === 'created')
747
+ ui.success(`Created ${c.bold(agents.path)} ${c.dim('(usebecky section for Cursor, Codex, Copilot, Windsurf and other agents)')}`);
748
+ else if (agents.status === 'appended')
749
+ ui.success(`Added the usebecky section to ${c.bold(agents.path)}`);
750
+ else if (agents.status === 'updated')
751
+ ui.success(`Updated the usebecky section in ${c.bold(agents.path)}`);
752
+ else if (agents.status === 'unchanged')
753
+ ui.info(`${agents.path} already up to date`);
754
+ else {
755
+ ui.warn(`${agents.path} has <!-- usebecky:start --> but no <!-- usebecky:end -->, so it was left alone.`);
756
+ ui.write(` ${c.dim('Fix or remove the marker, or run `npx usebecky ai --force` to replace everything from the start marker on.')}`);
757
+ }
758
+ ui.write(`\n${c.bold('Your AI assistant now knows usebecky.')}`);
759
+ ui.write(` Claude Code loads ${c.cyan(SKILL_TARGET)} automatically.`);
760
+ ui.write(` Cursor, Codex, Copilot, Windsurf and other agents read ${c.cyan(agents.path)}, which points them to the skill.`);
761
+ ui.write(` ${c.dim('Commit both so everyone on your team gets the same help.')}`);
762
+ if (platform === 'ios' || platform === 'android') {
763
+ const ios = platform === 'ios';
764
+ ui.write(` The rules in ${agents.path} are for ${ios ? 'Swift' : 'Kotlin'}; the assistant reads ${c.cyan(`references/${platform}.md`)} for the ${ios ? 'Swift' : 'Kotlin'} API.`);
765
+ ui.write(` ${c.yellow('!')} Connect the app with your ${c.bold('Project URL')} and ${c.bold('publishable key')} (${DASHBOARD_API_KEYS}) in ${ios ? 'Baas.swift' : 'Backend.kt'}, as the ${ios ? 'iOS' : 'Android'} guide shows: ${c.cyan(`${DOCS_URL}/frameworks/${platform}`)}. Never put the secret key in an app.`);
766
+ }
767
+ else if (app.kind === 'native') {
768
+ ui.write(` Found both an iOS and an Android project, so ${agents.path} covers Swift and Kotlin (references/ios.md, references/android.md).`);
769
+ ui.write(` ${c.yellow('!')} Connect each app with your Project URL and publishable key: ${c.cyan(`${DOCS_URL}/frameworks/ios`)}, ${c.cyan(`${DOCS_URL}/frameworks/android`)}. Never put the secret key in an app.`);
770
+ }
771
+ else if (app.kind === 'none' && !linked.ref) {
772
+ ui.write(` ${c.yellow('!')} No app found in this folder (no package.json, Xcode project or Gradle build), so ${agents.path} covers JavaScript, Swift and Kotlin.`);
773
+ ui.write(` ${c.dim('If your app lives in another folder, run `npx usebecky ai` there.')}`);
774
+ }
775
+ else if (!linked.ref)
776
+ ui.write(` ${c.yellow('!')} This folder is not connected to a project yet. Run ${c.cyan('npx usebecky init')} first.`);
777
+ ui.write(`\n${c.bold('Next, ask your assistant:')}`);
778
+ for (const p of examplePromptsFor(platform))
779
+ ui.write(` ${c.cyan(`"${p}"`)}`);
780
+ ui.write('');
781
+ return agents.status === 'broken' ? 1 : 0;
782
+ }
783
+ }
784
+ function statusColor(s) {
785
+ return s === 'active' ? c.green(s) : s === 'failed' ? c.red(s) : c.yellow(s);
786
+ }
787
+ function mask(v) {
788
+ return v.length > 16 ? `${v.slice(0, 10)}…${v.slice(-4)}` : v;
789
+ }
790
+ function readJson(file) {
791
+ try {
792
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
793
+ }
794
+ catch {
795
+ return null;
796
+ }
797
+ }
798
+ /** The linked project comes from the publishable key in your env file (`ub_pk_<ref>_...`). */
799
+ export function readLinked(cwd) {
800
+ for (const file of ['.env.local', '.env', '.env.development.local', '.env.development']) {
801
+ let content;
802
+ try {
803
+ content = fs.readFileSync(path.join(cwd, file), 'utf8');
804
+ }
805
+ catch {
806
+ continue;
807
+ }
808
+ const vars = parseEnv(content);
809
+ const keyName = Object.keys(vars).find((n) => n.endsWith('USEBECKY_PUBLISHABLE_KEY') && vars[n]);
810
+ if (!keyName)
811
+ continue;
812
+ const key = vars[keyName];
813
+ const m = /^[uy]b_pk_([a-z0-9]+)_/.exec(key); // yb_pk_: keys from before the rename to usebecky
814
+ const urlName = Object.keys(vars).find((n) => n.endsWith('USEBECKY_URL') && vars[n]);
815
+ return { ref: m ? m[1] : null, url: urlName ? vars[urlName] : null, key, file };
816
+ }
817
+ return { ref: null, url: null, key: null, file: null };
818
+ }
819
+ /** "usebecky-cli/1.4.0 (macOS; Node.js 22.11.0)": the server lists the CLI's sessions as "usebecky CLI on macOS". */
820
+ const CLI_USER_AGENT = `usebecky-cli/${VERSION} (${process.platform === 'darwin' ? 'macOS' : process.platform === 'win32' ? 'Windows' : process.platform === 'linux' ? 'Linux' : process.platform}; Node.js ${process.versions.node})`;
821
+ /** Opens the default browser (macOS open, Linux xdg-open, Windows start). Never fails: the link is printed anyway. */
822
+ function openBrowser(url) {
823
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
824
+ const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
825
+ try {
826
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
827
+ child.on('error', () => { });
828
+ child.unref();
829
+ }
830
+ catch { }
831
+ }
832
+ /**
833
+ * ~/.usebecky (or USEBECKY_CONFIG_DIR / an explicit dir). A login saved before the rename to usebecky
834
+ * lives in ~/.yourbaas/config.json: copy it over once so nobody has to sign in again.
835
+ */
836
+ function defaultConfigDir(explicit) {
837
+ if (explicit)
838
+ return explicit;
839
+ const dir = path.join(os.homedir(), '.usebecky');
840
+ const legacy = path.join(os.homedir(), '.yourbaas', 'config.json');
841
+ try {
842
+ if (!fs.existsSync(path.join(dir, 'config.json')) && fs.existsSync(legacy)) {
843
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
844
+ fs.copyFileSync(legacy, path.join(dir, 'config.json'));
845
+ fs.chmodSync(path.join(dir, 'config.json'), 0o600);
846
+ }
847
+ }
848
+ catch { }
849
+ return dir;
850
+ }