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,176 @@
1
+ // `npx usebecky payments <mode|products>`: Stripe test mode and live mode, and the catalog at a glance.
2
+ //
3
+ // payments mode which mode the app's payments run in, and what live still needs
4
+ // payments mode live | test switch (owners and admins; live needs the live Stripe account connected first)
5
+ // payments products the products and their prices
6
+ //
7
+ // Products and prices themselves are written in usebecky/config.json (`config push`, config.ts). Connecting Stripe stays
8
+ // in the dashboard: it is a sign-in at Stripe. Server side: modules/payments/admin.ts, go-live.ts.
9
+ import { c } from "./ui.js";
10
+ const HELP = `
11
+ ${c.bold('npx usebecky payments')}: Stripe test mode and live mode
12
+
13
+ ${c.cyan('payments mode')} Which mode payments run in, and what live mode still needs
14
+ ${c.cyan('payments mode live')} Take real payments (owners and admins; the live Stripe account must be connected)
15
+ ${c.cyan('payments mode test')} Back to test mode (test cards, nothing is charged)
16
+ ${c.cyan('payments products')} The products and their prices
17
+ ${c.cyan('payments connect')} Connect your Stripe account: opens Stripe's sign-in and waits (test or live: default live
18
+ when this server takes live payments)
19
+
20
+ Products and prices: write them in usebecky/config.json and run ${c.cyan('npx usebecky config push')}.
21
+ Options: --project <ref>, -y (don't ask)
22
+ `;
23
+ const money = (p) => `${(p.amount / 100).toFixed(2)} ${p.currency.toUpperCase()}${p.interval ? ` / ${p.interval}` : ' once'}`;
24
+ export async function paymentsCommand(ctx) {
25
+ const { ui } = ctx;
26
+ const [sub, arg] = ctx.args;
27
+ if (!sub || sub === 'help') {
28
+ ui.write(HELP);
29
+ return sub ? 0 : 1;
30
+ }
31
+ if (sub !== 'mode' && sub !== 'products' && sub !== 'connect') {
32
+ ui.error(`Unknown command "payments ${sub}".`);
33
+ ui.write(HELP);
34
+ return 1;
35
+ }
36
+ if ((sub === 'mode' || sub === 'connect') && arg !== undefined && arg !== 'live' && arg !== 'test') {
37
+ ui.error(`Unknown mode "${arg}". Use live or test.`);
38
+ return 1;
39
+ }
40
+ if (!ctx.ref)
41
+ return ctx.noProject();
42
+ if (!(await ctx.signIn()))
43
+ return 1;
44
+ if (sub === 'products')
45
+ return products(ctx);
46
+ if (sub === 'connect')
47
+ return connect(ctx, arg);
48
+ return arg ? switchMode(ctx, arg) : showMode(ctx);
49
+ }
50
+ /**
51
+ * Stripe's own sign-in (Stripe Connect needs it; there is no way around a person allowing it at Stripe): open the link,
52
+ * then check every few seconds until the account is connected. Live by default when this server takes live payments:
53
+ * one sign-in then connects the same account for testing too, when Stripe allows it (the dashboard's "Connect with
54
+ * Stripe" does the same).
55
+ */
56
+ async function connect(ctx, wanted) {
57
+ const { ui } = ctx;
58
+ const status = await ctx.api('GET', '/payments/status');
59
+ if (status.error || !status.data)
60
+ return ctx.printError(status.error ?? { message: 'Could not read the payments status.' });
61
+ const mode = wanted ?? (status.data.modes.live?.connect_configured ? 'live' : 'test');
62
+ const before = status.data.modes[mode];
63
+ if (!before?.connect_configured) {
64
+ ui.error(`Connecting a Stripe account ${mode === 'live' ? 'for live payments ' : ''}isn't set up on this server yet.`);
65
+ return 1;
66
+ }
67
+ if (before.account) {
68
+ ui.success(`Already connected (${mode}): ${before.account.name ?? before.account.email ?? before.account.id}.`);
69
+ return 0;
70
+ }
71
+ const dashboard = (await ctx.dashboardUrl())?.replace(/\/+$/, '') ?? null;
72
+ const r = await ctx.api('POST', '/payments/connect', { mode, return_path: `/project/${ctx.ref}/payments` });
73
+ if (r.error || !r.data?.url)
74
+ return ctx.printError(r.error ?? { message: 'Could not start connecting Stripe.' });
75
+ ui.write(` ${ctx.openUrl ? 'Opening' : 'Open'} ${c.cyan(r.data.url)}`);
76
+ ui.write(c.dim(` Sign in at Stripe and click Connect. You come back to ${dashboard ? 'the dashboard' : 'usebecky'}; this waits. (Ctrl+C to stop)`));
77
+ ctx.openUrl?.(r.data.url);
78
+ const sleep = ctx.sleep ?? ((ms) => new Promise((res) => setTimeout(res, ms)));
79
+ const polls = ctx.maxPolls ?? 200;
80
+ for (let i = 0; i < polls; i++) {
81
+ await sleep(3000);
82
+ const s = await ctx.api('GET', '/payments/status');
83
+ const account = s.data?.modes[mode]?.account;
84
+ if (account) {
85
+ ui.success(`Connected ${c.bold(account.name ?? account.email ?? account.id)} (${mode}).`);
86
+ if (mode === 'live' && s.data?.modes.test?.account)
87
+ ui.write(c.dim(' The same account is your test connection too.'));
88
+ if (!account.charges_enabled)
89
+ ui.warn('Stripe still needs some details before this account can take payments: finish them at Stripe.');
90
+ return 0;
91
+ }
92
+ }
93
+ ui.error('Stripe isn’t connected yet. Run the command again, or connect in the dashboard (Payments).');
94
+ return 1;
95
+ }
96
+ async function products(ctx) {
97
+ const r = await ctx.api('GET', '/payments/products');
98
+ if (r.error)
99
+ return ctx.printError(r.error);
100
+ const list = (r.data ?? []).filter((p) => p.active);
101
+ if (!list.length) {
102
+ ctx.ui.info('No products yet. Add them under "payments" in usebecky/config.json, then: npx usebecky config push');
103
+ return 0;
104
+ }
105
+ for (const p of list) {
106
+ ctx.ui.write(`${c.bold(p.key)} ${p.name} ${c.dim(p.type === 'one_time' ? 'one-time' : 'subscription')}${p.features.length ? c.dim(` unlocks ${p.features.join(', ')}`) : ''}${p.synced ? '' : c.yellow(' not in Stripe yet')}`);
107
+ for (const x of p.prices.filter((x) => x.active))
108
+ ctx.ui.write(` ${x.key} ${money(x)}`);
109
+ }
110
+ return 0;
111
+ }
112
+ /** The go-live steps that aren't done, as short lines. */
113
+ function missingSteps(g) {
114
+ const out = [];
115
+ if (!g.steps.live_plan.done)
116
+ out.push(`a plan that allows live payments (${g.steps.live_plan.required_plan ?? 'a paid plan'})`);
117
+ if (!g.steps.live_keys.done)
118
+ out.push('live payments are not set up on this server yet');
119
+ if (!g.steps.live_account.done)
120
+ out.push(g.steps.live_account.connected ? 'your live Stripe account can’t take charges yet (finish it at Stripe)' : 'your live Stripe account (Dashboard → Payments → Go live → Connect)');
121
+ if (!g.steps.live_webhooks.done)
122
+ out.push('Stripe’s live events have not arrived yet');
123
+ if (!g.steps.test_purchase.done)
124
+ out.push('one test purchase (recommended, not required)');
125
+ return out;
126
+ }
127
+ async function showMode(ctx) {
128
+ const r = await ctx.api('GET', '/payments/go-live');
129
+ if (r.error || !r.data)
130
+ return ctx.printError(r.error ?? { message: 'Could not read the payments mode.' });
131
+ const g = r.data;
132
+ ctx.ui.write(`Payments run in ${g.mode === 'live' ? c.green('live mode') : c.yellow('test mode')} ${c.dim(g.mode === 'live' ? '(real cards, real money)' : '(test cards, nothing is charged)')}.`);
133
+ if (g.mode === 'test') {
134
+ const left = missingSteps(g);
135
+ if (left.length)
136
+ for (const s of left)
137
+ ctx.ui.write(` ${c.dim('·')} ${s}`);
138
+ ctx.ui.write(c.dim(g.can_switch ? ' Switch: npx usebecky payments mode live' : ' Live mode needs the steps above first.'));
139
+ }
140
+ return 0;
141
+ }
142
+ async function switchMode(ctx, mode) {
143
+ const { ui } = ctx;
144
+ const g = await ctx.api('GET', '/payments/go-live');
145
+ if (g.error || !g.data)
146
+ return ctx.printError(g.error ?? { message: 'Could not read the payments mode.' });
147
+ if (g.data.mode === mode) {
148
+ ui.success(`Payments already run in ${mode} mode.`);
149
+ return 0;
150
+ }
151
+ if (mode === 'live') {
152
+ if (!g.data.can_switch) {
153
+ ui.error('Live mode isn’t possible yet. Still needed:');
154
+ for (const s of missingSteps(g.data))
155
+ ui.write(` ${c.dim('·')} ${s}`);
156
+ const dashboard = await ctx.dashboardUrl();
157
+ if (dashboard)
158
+ ui.write(` ${c.dim(`Connect the live account here: ${dashboard.replace(/\/+$/, '')}/project/${ctx.ref}/payments`)}`);
159
+ return 1;
160
+ }
161
+ const left = missingSteps(g.data);
162
+ if (left.length)
163
+ for (const s of left)
164
+ ui.warn(`Not done yet: ${s}`);
165
+ }
166
+ const question = mode === 'live' ? `Switch project ${ctx.ref} to live mode? Customers then pay with real cards.` : `Switch project ${ctx.ref} back to test mode? Checkout then takes test cards only.`;
167
+ if (!ctx.yes && !(await ui.confirm(question, false)))
168
+ return 1;
169
+ const r = await ctx.api('POST', '/payments/mode', { mode });
170
+ if (r.error)
171
+ return ctx.printError(r.error);
172
+ ui.success(`Payments now run in ${mode} mode.`);
173
+ if (r.data?.catalog)
174
+ ui.write(c.dim(` ${r.data.catalog.synced} product${r.data.catalog.synced === 1 ? '' : 's'} sent to the ${mode} Stripe account${r.data.catalog.errors?.length ? `, ${r.data.catalog.errors.length} failed (see Dashboard → Payments)` : ''}.`));
175
+ return 0;
176
+ }
@@ -0,0 +1,36 @@
1
+ import type { PackageManager } from './deploy-ci.ts';
2
+ import { type Ui } from './ui.ts';
3
+ export declare const PUSH_WORKFLOW_PATH = ".github/workflows/usebecky-push.yml";
4
+ export declare const ACCESS_TOKEN_SECRET = "USEBECKY_ACCESS_TOKEN";
5
+ export interface PushContext {
6
+ cwd: string;
7
+ ui: Ui;
8
+ args: string[];
9
+ ref: string | null;
10
+ dryRun: boolean;
11
+ force: boolean;
12
+ /** Options every step gets: --project, --api-url, -y. */
13
+ common: string[];
14
+ /** Runs one CLI command (run.ts) and returns its exit code. */
15
+ run: (argv: string[]) => Promise<number>;
16
+ noProject: () => number;
17
+ }
18
+ interface Step {
19
+ name: string;
20
+ /** The project token scope this step needs. */
21
+ scope: 'db' | 'config' | 'functions' | 'deploy';
22
+ argv: string[] | null;
23
+ /** --dry-run without a check of its own: what would happen. */
24
+ preview?: string;
25
+ }
26
+ /** The steps this folder has, in release order. */
27
+ export declare function pushSteps(cwd: string, dryRun: boolean): Step[];
28
+ export declare function pushCommand(ctx: PushContext): Promise<number>;
29
+ /** The workflow: `push -y` on every push to the branch, `push --dry-run` on pull requests (a check, nothing changes). */
30
+ export declare function pushWorkflow(opts: {
31
+ project: string;
32
+ packageManager: PackageManager | null;
33
+ branch?: string;
34
+ needsInstall: boolean;
35
+ }): string;
36
+ export {};
@@ -0,0 +1,172 @@
1
+ // `npx usebecky push [--dry-run] [-y]`: one release command. Runs, in this order and only what the folder has:
2
+ //
3
+ // db push usebecky/migrations/*.sql
4
+ // config push usebecky/config.json
5
+ // functions deploy usebecky/functions/
6
+ // deploy --prod usebecky/hosting.json (the site this folder deploys to)
7
+ //
8
+ // It stops at the first step that fails. --dry-run checks the migrations and the settings against the project and lists
9
+ // the functions and the site, changing nothing. `push --github` writes a GitHub Actions workflow that runs it on every
10
+ // push to main (pull requests: --dry-run) with a project token. Each step is the command itself (run.ts), so its output,
11
+ // questions (-y skips them) and errors are the same as when it runs alone.
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { CONFIG_FILE } from "./config.js";
15
+ import { readMigrations } from "./db.js";
16
+ import { readLink } from "./deploy-api.js";
17
+ import { detectPackageManager } from "./deploy-detect.js";
18
+ import { listLocalFunctions } from "./functions.js";
19
+ import { c } from "./ui.js";
20
+ export const PUSH_WORKFLOW_PATH = '.github/workflows/usebecky-push.yml';
21
+ export const ACCESS_TOKEN_SECRET = 'USEBECKY_ACCESS_TOKEN';
22
+ const HELP = `
23
+ ${c.bold('npx usebecky push')}: release everything in this folder to the project, in one command
24
+
25
+ Runs, in this order, what the folder has: ${c.cyan('db push')} (usebecky/migrations), ${c.cyan('config push')} (usebecky/config.json),
26
+ ${c.cyan('functions deploy')} (usebecky/functions), ${c.cyan('deploy --prod')} (usebecky/hosting.json). Stops at the first error.
27
+
28
+ ${c.cyan('push --dry-run')} Check the migrations and settings against the project, list the rest; change nothing
29
+ ${c.cyan('push -y')} Don't ask (CI)
30
+ ${c.cyan('push --github')} Write a GitHub Actions workflow that runs it on every push to main
31
+
32
+ In CI: a project token in USEBECKY_ACCESS_TOKEN (npx usebecky tokens create "GitHub Actions" --scope …).
33
+ Options: --project <ref>, --api-url <url>
34
+ `;
35
+ /** The steps this folder has, in release order. */
36
+ export function pushSteps(cwd, dryRun) {
37
+ const dry = dryRun ? ['--dry-run'] : [];
38
+ const steps = [];
39
+ if (readMigrations(cwd).length)
40
+ steps.push({ name: 'db push', scope: 'db', argv: ['db', 'push', ...dry] });
41
+ if (fs.existsSync(path.join(cwd, CONFIG_FILE)))
42
+ steps.push({ name: 'config push', scope: 'config', argv: ['config', 'push', ...dry] });
43
+ const functions = listLocalFunctions(cwd);
44
+ if (functions.length) {
45
+ steps.push({ name: 'functions deploy', scope: 'functions', argv: dryRun ? null : ['functions', 'deploy'], preview: `would deploy ${functions.length} function${functions.length === 1 ? '' : 's'}: ${functions.join(', ')}` });
46
+ }
47
+ const link = readLink(cwd);
48
+ if (link?.site)
49
+ steps.push({ name: 'deploy --prod', scope: 'deploy', argv: dryRun ? null : ['deploy', '--prod'], preview: `would build this folder and put it live on the site ${link.site}` });
50
+ return steps;
51
+ }
52
+ export async function pushCommand(ctx) {
53
+ const { ui } = ctx;
54
+ const words = ctx.args.filter((a) => !a.startsWith('-'));
55
+ if (words[0] === 'help') {
56
+ ui.write(HELP);
57
+ return 0;
58
+ }
59
+ if (words.length) {
60
+ ui.error(`Unknown command "push ${words.join(' ')}".`);
61
+ ui.write(HELP);
62
+ return 1;
63
+ }
64
+ if (ctx.args.includes('--github'))
65
+ return github(ctx);
66
+ const steps = pushSteps(ctx.cwd, ctx.dryRun);
67
+ if (!steps.length) {
68
+ ui.error('Nothing to release in this folder.');
69
+ ui.write(` ${c.dim('push looks for usebecky/migrations/, usebecky/config.json, usebecky/functions/ and usebecky/hosting.json.')}`);
70
+ return 1;
71
+ }
72
+ if (!ctx.ref)
73
+ return ctx.noProject();
74
+ ui.write(`\n${c.bold(c.magenta('usebecky'))} ${c.dim(`push${ctx.dryRun ? ' --dry-run' : ''}`)} ${c.dim(`(project ${ctx.ref}): ${steps.map((s) => s.name).join(', ')}`)}`);
75
+ const done = [];
76
+ for (const [i, s] of steps.entries()) {
77
+ ui.write(`\n${c.cyan(`${i + 1}/${steps.length}`)} ${c.bold(s.name)}`);
78
+ if (!s.argv) {
79
+ ui.write(` ${s.preview}`);
80
+ done.push(s.name);
81
+ continue;
82
+ }
83
+ const code = await ctx.run([...s.argv, ...ctx.common]);
84
+ if (code !== 0) {
85
+ const left = steps.slice(i + 1).map((x) => x.name);
86
+ ui.error(`${s.name} failed${left.length ? `; not run: ${left.join(', ')}` : ''}.`);
87
+ if (done.length)
88
+ ui.write(c.dim(` Done before it: ${done.join(', ')}.`));
89
+ return code;
90
+ }
91
+ done.push(s.name);
92
+ }
93
+ ui.write('');
94
+ ui.success(ctx.dryRun ? `Checked: ${done.join(', ')}. Nothing was changed (--dry-run).` : `Released to project ${ctx.ref}: ${done.join(', ')}.`);
95
+ return 0;
96
+ }
97
+ /** The workflow: `push -y` on every push to the branch, `push --dry-run` on pull requests (a check, nothing changes). */
98
+ export function pushWorkflow(opts) {
99
+ const branch = opts.branch ?? 'main';
100
+ const pm = opts.packageManager;
101
+ const install = { npm: 'npm ci', pnpm: 'pnpm install --frozen-lockfile', yarn: 'yarn install --frozen-lockfile', bun: 'bun install --frozen-lockfile' };
102
+ return [
103
+ `# ${PUSH_WORKFLOW_PATH}`,
104
+ `# Releases to usebecky on every push to ${branch} (npx usebecky push); pull requests only check (--dry-run).`,
105
+ `# Needs the repository secret ${ACCESS_TOKEN_SECRET}: a project token (npx usebecky tokens create).`,
106
+ 'name: Release to usebecky',
107
+ '',
108
+ 'on:',
109
+ ' push:',
110
+ ` branches: [${branch}]`,
111
+ ' pull_request:',
112
+ '',
113
+ '# One run at a time per branch and kind: a release never waits behind (or is replaced by) a pull request check.',
114
+ '# A newer push to main replaces one that still waits: it releases the same changes and more.',
115
+ 'concurrency:',
116
+ ' group: usebecky-push-${{ github.event_name }}-${{ github.ref }}',
117
+ ' cancel-in-progress: false',
118
+ '',
119
+ 'jobs:',
120
+ ' push:',
121
+ " # Pull requests from forks can't read your secrets, so they are skipped.",
122
+ " if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository",
123
+ ' runs-on: ubuntu-latest',
124
+ ' steps:',
125
+ ' - uses: actions/checkout@v4',
126
+ ...(pm === 'pnpm' ? [' - uses: pnpm/action-setup@v4'] : []),
127
+ ' - uses: actions/setup-node@v4',
128
+ ' with:',
129
+ ' node-version: 24',
130
+ ...(pm === 'bun' ? [' - uses: oven-sh/setup-bun@v2'] : []),
131
+ ...(pm && opts.needsInstall ? [` - run: ${install[pm]}`] : []),
132
+ ` - run: npx --yes usebecky push --project ${opts.project} \${{ github.event_name == 'push' && '-y' || '--dry-run' }}`,
133
+ ' env:',
134
+ ` ${ACCESS_TOKEN_SECRET}: \${{ secrets.${ACCESS_TOKEN_SECRET} }}`,
135
+ '',
136
+ ].join('\n');
137
+ }
138
+ async function github(ctx) {
139
+ const { ui } = ctx;
140
+ if (!ctx.ref)
141
+ return ctx.noProject();
142
+ const steps = pushSteps(ctx.cwd, false);
143
+ const hasPkg = fs.existsSync(path.join(ctx.cwd, 'package.json'));
144
+ // Functions are bundled with the app's esbuild and sites are built: both need the app's packages installed.
145
+ const needsInstall = hasPkg && steps.some((s) => s.scope === 'functions' || s.scope === 'deploy');
146
+ const text = pushWorkflow({ project: ctx.ref, packageManager: hasPkg ? detectPackageManager(ctx.cwd) : null, needsInstall });
147
+ const file = path.join(ctx.cwd, PUSH_WORKFLOW_PATH);
148
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
149
+ if (existing === text)
150
+ ui.info(`${PUSH_WORKFLOW_PATH} is already up to date.`);
151
+ else if (existing !== null && !ctx.force) {
152
+ ui.error(`${PUSH_WORKFLOW_PATH} already exists and is different.`);
153
+ ui.write(` ${c.dim('Add --force to replace it.')}`);
154
+ return 1;
155
+ }
156
+ else {
157
+ fs.mkdirSync(path.dirname(file), { recursive: true });
158
+ fs.writeFileSync(file, text);
159
+ ui.success(`${existing === null ? 'Created' : 'Replaced'} ${c.bold(PUSH_WORKFLOW_PATH)}: pushes to main release, pull requests are checked.`);
160
+ }
161
+ const scopes = [...new Set(steps.map((s) => s.scope))];
162
+ ui.write(`\n${c.bold('Two more steps:')}`);
163
+ ui.write(` ${c.cyan('1.')} Make a project token: ${c.cyan(`npx usebecky tokens create "GitHub Actions" --scope ${scopes.length ? scopes.join(',') : 'db,config'}`)}`);
164
+ ui.write(` ${c.cyan('2.')} On GitHub: your repository → Settings → Secrets and variables → Actions → New repository secret.`);
165
+ ui.write(` Name: ${c.bold(ACCESS_TOKEN_SECRET)}, value: the token. ${c.yellow('Never commit the token itself.')}`);
166
+ ui.write(` Then commit ${PUSH_WORKFLOW_PATH} and push.`);
167
+ if (fs.existsSync(path.join(ctx.cwd, '.github/workflows/usebecky-deploy.yml')) && steps.some((s) => s.scope === 'deploy')) {
168
+ ui.write(`\n ${c.yellow('!')} .github/workflows/usebecky-deploy.yml deploys too. Delete it, or every push deploys twice.`);
169
+ }
170
+ ui.write('');
171
+ return 0;
172
+ }
@@ -0,0 +1,65 @@
1
+ import type { HostingContext } from './deploy-api.ts';
2
+ import { type EsbuildLike } from './functions.ts';
3
+ import { type SocialContext } from './social.ts';
4
+ import { type Io } from './ui.ts';
5
+ export interface RunContext {
6
+ cwd?: string;
7
+ env?: Record<string, string | undefined>;
8
+ io?: Partial<Io>;
9
+ /** Directory for config.json (default ~/.usebecky). */
10
+ configDir?: string;
11
+ fetch?: typeof fetch;
12
+ /** Don't actually open a browser (tests). */
13
+ noOpen?: boolean;
14
+ /** Opens a link in the browser (default: open / xdg-open / start; tests pass a recorder). */
15
+ openUrl?: (url: string) => void;
16
+ /** Waits between checks while `login` waits for the browser (tests pass one that returns at once). */
17
+ sleep?: (ms: number) => Promise<void>;
18
+ /** Where the bundled AI skill lives (default: found next to the installed package). */
19
+ skillDir?: string;
20
+ /** Runs a command attached to this terminal and resolves with its exit code (`create`; tests pass a fake). */
21
+ runAttached?: (command: string, args: string[]) => Promise<number>;
22
+ /** esbuild for `functions deploy` (default: the one installed in the app; tests pass a fake). */
23
+ loadEsbuild?: () => Promise<EsbuildLike | null>;
24
+ /** `deploy` / `hosting`: the build runner, production package lister, sleep and poll limit (tests pass fakes). */
25
+ hosting?: Pick<HostingContext, 'runBuild' | 'listPackages' | 'sleep' | 'maxPolls'>;
26
+ /** `social`: sleep and poll limit while a video is checked (tests pass fakes). */
27
+ social?: Pick<SocialContext, 'sleep' | 'maxPolls'>;
28
+ }
29
+ interface Flags {
30
+ _: string[];
31
+ apiUrl?: string;
32
+ project?: string;
33
+ out?: string;
34
+ yes: boolean;
35
+ help: boolean;
36
+ version: boolean;
37
+ /** `ai`: overwrite skill files that differ from this version. */
38
+ force?: boolean;
39
+ /** `analytics`: the publishable key for the script tag. */
40
+ key?: string;
41
+ /** `analytics`: show what would change without changing anything. */
42
+ dryRun?: boolean;
43
+ /** `login`: email and password in the terminal instead of the browser. */
44
+ email?: boolean;
45
+ /** `login`: print the sign-in link, don't open a browser. */
46
+ noBrowser?: boolean;
47
+ }
48
+ /** The platform API every command talks to unless --api-url / USEBECKY_API_URL / a saved login says otherwise. */
49
+ export declare const DEFAULT_API = "https://api.usebecky.com";
50
+ /** What to try when the platform API can't be reached. */
51
+ export declare function unreachableHint(apiUrl: string): string;
52
+ /** `init`'s last line when no secret key was saved (browser apps, Expo). */
53
+ export declare const PUBLISHABLE_ONLY = "Only your publishable key was saved. It's safe in browser code.";
54
+ /** `init`'s last line for web apps. */
55
+ export declare const ANALYTICS_HINT: string;
56
+ export declare function parseArgs(argv: string[]): Flags;
57
+ export declare function run(argv: string[], ctx?: RunContext): Promise<number>;
58
+ /** The linked project comes from the publishable key in your env file (`ub_pk_<ref>_...`). */
59
+ export declare function readLinked(cwd: string): {
60
+ ref: string | null;
61
+ url: string | null;
62
+ key: string | null;
63
+ file: string | null;
64
+ };
65
+ export {};