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,48 @@
1
+ import { type Ui } from './ui.ts';
2
+ export declare const MIGRATIONS_DIR: string;
3
+ type ApiResult<T> = {
4
+ data: T | null;
5
+ error: {
6
+ code: string;
7
+ message: string;
8
+ hint?: string;
9
+ status: number;
10
+ details?: any;
11
+ } | null;
12
+ };
13
+ export interface DbContext {
14
+ cwd: string;
15
+ ui: Ui;
16
+ /** Positional arguments after `db` (subcommand first). */
17
+ args: string[];
18
+ ref: string | null;
19
+ yes: boolean;
20
+ dryRun: boolean;
21
+ force: boolean;
22
+ /** Platform API call for this project, already signed in: api('GET', '/database/migrations'). */
23
+ api: <T = any>(method: string, path: string, body?: unknown) => Promise<ApiResult<T>>;
24
+ /** Make sure we're signed in (asks to log in when needed); false = stop. */
25
+ signIn: () => Promise<boolean>;
26
+ printError: (e: {
27
+ message: string;
28
+ hint?: string;
29
+ status?: number;
30
+ }) => number;
31
+ noProject: () => number;
32
+ }
33
+ export interface MigrationFile {
34
+ version: string;
35
+ name: string;
36
+ file: string;
37
+ sql: string;
38
+ }
39
+ /** A version from the current time: 20261115093000 (UTC). */
40
+ export declare function versionNow(d?: Date): string;
41
+ /** "add_todos" from "Add todos!". */
42
+ export declare function slug(raw: string): string;
43
+ /** Same checksum as the server (sha256 of the SQL with \n line endings, trimmed). */
44
+ export declare function checksum(sql: string): string;
45
+ /** The migration files in usebecky/migrations, oldest first. Files that don't look like <version>_<name>.sql are ignored. */
46
+ export declare function readMigrations(cwd: string): MigrationFile[];
47
+ export declare function dbCommand(ctx: DbContext): Promise<number>;
48
+ export {};
package/dist/cli/db.js ADDED
@@ -0,0 +1,215 @@
1
+ // `npx usebecky db <new|pull|push|diff>`: schema migrations as SQL files in usebecky/migrations/.
2
+ //
3
+ // db new <name> creates usebecky/migrations/<version>_<name>.sql (local only)
4
+ // db pull saves changes made in the dashboard as a migration, then writes every migration the project has
5
+ // recorded that this folder doesn't have yet (a teammate's push, a staging copy, the first pull)
6
+ // db push applies the files the project doesn't have yet, in version order, all in one transaction
7
+ // (--dry-run: check them without changing anything; --force: push even with unsaved dashboard changes)
8
+ // db diff prints the SQL of the changes made in the dashboard since the last migration
9
+ //
10
+ // Server side: packages/server/src/modules/database/migrations.ts. Guide: docs/guide/guides/database.md "Migrations".
11
+ import crypto from 'node:crypto';
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { c } from "./ui.js";
15
+ export const MIGRATIONS_DIR = path.join('usebecky', 'migrations');
16
+ const FILE_RE = /^(\d{4,20})(?:_(.*))?\.sql$/;
17
+ /** A version from the current time: 20261115093000 (UTC). */
18
+ export function versionNow(d = new Date()) {
19
+ return d.toISOString().replace(/[-:T]/g, '').slice(0, 14);
20
+ }
21
+ /** "add_todos" from "Add todos!". */
22
+ export function slug(raw) {
23
+ return raw
24
+ .trim()
25
+ .toLowerCase()
26
+ .replace(/[^a-z0-9]+/g, '_')
27
+ .replace(/^_+|_+$/g, '')
28
+ .slice(0, 100);
29
+ }
30
+ /** Same checksum as the server (sha256 of the SQL with \n line endings, trimmed). */
31
+ export function checksum(sql) {
32
+ return crypto.createHash('sha256').update(sql.replace(/\r\n/g, '\n').trim()).digest('hex');
33
+ }
34
+ function compare(a, b) {
35
+ return a.length - b.length || (a < b ? -1 : a > b ? 1 : 0);
36
+ }
37
+ /** The migration files in usebecky/migrations, oldest first. Files that don't look like <version>_<name>.sql are ignored. */
38
+ export function readMigrations(cwd) {
39
+ const dir = path.join(cwd, MIGRATIONS_DIR);
40
+ if (!fs.existsSync(dir))
41
+ return [];
42
+ return fs
43
+ .readdirSync(dir)
44
+ .map((f) => ({ f, m: FILE_RE.exec(f) }))
45
+ .filter((x) => !!x.m)
46
+ .map(({ f, m }) => ({ version: m[1], name: m[2] ?? '', file: path.join(MIGRATIONS_DIR, f), sql: fs.readFileSync(path.join(dir, f), 'utf8') }))
47
+ .sort((a, b) => compare(a.version, b.version));
48
+ }
49
+ function writeMigration(cwd, version, name, sql) {
50
+ const rel = path.join(MIGRATIONS_DIR, `${version}${name ? `_${name}` : ''}.sql`);
51
+ fs.mkdirSync(path.join(cwd, MIGRATIONS_DIR), { recursive: true });
52
+ fs.writeFileSync(path.join(cwd, rel), sql.endsWith('\n') ? sql : `${sql}\n`);
53
+ return rel;
54
+ }
55
+ const DB_HELP = `
56
+ ${c.bold('npx usebecky db')}: your database structure as SQL files in ${c.cyan('usebecky/migrations/')}
57
+
58
+ ${c.cyan('db new <name>')} Create an empty migration file to write SQL in
59
+ ${c.cyan('db pull')} Save changes made in the dashboard as a migration and download the project's migrations
60
+ ${c.cyan('db push')} Apply the migrations the project doesn't have yet (all or nothing)
61
+ ${c.cyan('db diff')} Show the SQL of changes made in the dashboard that aren't in a migration yet
62
+
63
+ Options: --project <ref>, --dry-run (push: check without changing anything), --force (push despite unsaved
64
+ dashboard changes), -y (don't ask)
65
+ `;
66
+ export async function dbCommand(ctx) {
67
+ const { ui } = ctx;
68
+ const sub = ctx.args[0];
69
+ if (!sub || sub === 'help') {
70
+ ui.write(DB_HELP);
71
+ return sub ? 0 : 1;
72
+ }
73
+ if (sub === 'new')
74
+ return dbNew(ctx);
75
+ if (!['pull', 'push', 'diff'].includes(sub)) {
76
+ ui.error(`Unknown command "db ${sub}".`);
77
+ ui.write(DB_HELP);
78
+ return 1;
79
+ }
80
+ if (!ctx.ref)
81
+ return ctx.noProject();
82
+ if (!(await ctx.signIn()))
83
+ return 1;
84
+ ui.write(`\n${c.bold(c.magenta('usebecky'))} ${c.dim(`db ${sub}`)} ${c.dim(`(project ${ctx.ref})`)}\n`);
85
+ if (sub === 'pull')
86
+ return dbPull(ctx);
87
+ if (sub === 'push')
88
+ return dbPush(ctx);
89
+ return dbDiff(ctx);
90
+ }
91
+ function dbNew(ctx) {
92
+ const name = slug(ctx.args.slice(1).join(' '));
93
+ if (!name) {
94
+ ctx.ui.error('Give the migration a name.');
95
+ ctx.ui.write(` ${c.dim('Example: npx usebecky db new add_todos')}`);
96
+ return 1;
97
+ }
98
+ const existing = readMigrations(ctx.cwd);
99
+ let version = versionNow();
100
+ const last = existing.at(-1)?.version;
101
+ if (last && compare(version, last) <= 0)
102
+ version = (BigInt(last) + 1n).toString().padStart(last.length, '0');
103
+ const rel = writeMigration(ctx.cwd, version, name, `-- ${name}\n-- Write the SQL for this change here, then run: npx usebecky db push\n\n`);
104
+ ctx.ui.success(`Created ${c.bold(rel)}`);
105
+ ctx.ui.write(` ${c.dim('Write your SQL in it, then run')} ${c.cyan('npx usebecky db push')}`);
106
+ return 0;
107
+ }
108
+ async function dbPull(ctx) {
109
+ const { ui, cwd } = ctx;
110
+ const r = await ctx.api('POST', '/database/migrations/pull', { save: true });
111
+ if (r.error || !r.data)
112
+ return ctx.printError(r.error ?? { message: 'Could not pull the migrations.' });
113
+ const local = new Map(readMigrations(cwd).map((m) => [m.version, m]));
114
+ let written = 0;
115
+ for (const m of r.data.migrations) {
116
+ const mine = local.get(m.version);
117
+ if (mine) {
118
+ if (checksum(mine.sql) !== m.checksum && m.sql !== undefined && checksum(m.sql) === m.checksum)
119
+ ui.warn(`${mine.file} differs from what the project ran for ${m.version}. Left it alone.`);
120
+ continue;
121
+ }
122
+ const rel = writeMigration(cwd, m.version, m.name, m.sql ?? '');
123
+ written++;
124
+ if (r.data.created?.version === m.version)
125
+ ui.success(`Saved the changes made in the dashboard as ${c.bold(rel)}`);
126
+ else
127
+ ui.success(`Wrote ${c.bold(rel)}`);
128
+ }
129
+ if (!written)
130
+ ui.info(`${MIGRATIONS_DIR.split(path.sep).join('/')}/ is up to date (${r.data.migrations.length} migration${r.data.migrations.length === 1 ? '' : 's'}).`);
131
+ else
132
+ ui.write(`\n ${c.dim('Commit the folder so your team and your next deploy get the same database structure.')}`);
133
+ return 0;
134
+ }
135
+ async function dbPush(ctx) {
136
+ const { ui, cwd } = ctx;
137
+ const files = readMigrations(cwd);
138
+ if (!files.length) {
139
+ ui.info(`No migration files in ${MIGRATIONS_DIR.split(path.sep).join('/')}/.`);
140
+ ui.write(` ${c.dim('Create one with')} ${c.cyan('npx usebecky db new <name>')}${c.dim(', or download the current structure with')} ${c.cyan('npx usebecky db pull')}`);
141
+ return 0;
142
+ }
143
+ const h = await ctx.api('GET', '/database/migrations');
144
+ if (h.error || !h.data)
145
+ return ctx.printError(h.error ?? { message: 'Could not read the migration history.' });
146
+ const remote = new Map(h.data.migrations.map((m) => [m.version, m]));
147
+ const pending = files.filter((f) => !remote.has(f.version));
148
+ for (const f of files) {
149
+ const m = remote.get(f.version);
150
+ if (m && m.checksum && checksum(f.sql) !== m.checksum)
151
+ ui.warn(`${f.file} was changed after it was applied. The project keeps the version it ran; make a new migration for further changes.`);
152
+ }
153
+ const localVersions = new Set(files.map((f) => f.version));
154
+ const missing = h.data.migrations.filter((m) => !localVersions.has(m.version));
155
+ if (missing.length)
156
+ ui.warn(`The project has ${missing.length} migration${missing.length === 1 ? '' : 's'} this folder doesn't: run ${c.cyan('npx usebecky db pull')} to get ${missing.length === 1 ? 'it' : 'them'}.`);
157
+ if (!pending.length) {
158
+ ui.success('The database is up to date: every migration in this folder is applied.');
159
+ return 0;
160
+ }
161
+ ui.write(`${ctx.dryRun ? 'Would apply' : 'Ready to apply'} ${c.bold(String(pending.length))} migration${pending.length === 1 ? '' : 's'}:`);
162
+ for (const f of pending)
163
+ ui.write(` ${c.cyan('+')} ${f.file}`);
164
+ if (!ctx.dryRun && !ctx.yes) {
165
+ const ok = await ui.confirm(`Apply ${pending.length === 1 ? 'it' : 'them'} to project ${ctx.ref}?`, true);
166
+ if (!ok) {
167
+ ui.info('Nothing was changed.');
168
+ return 1;
169
+ }
170
+ }
171
+ const r = await ctx.api('POST', '/database/migrations/push', {
172
+ migrations: pending.map((f) => ({ version: f.version, name: f.name, sql: f.sql })),
173
+ dry_run: ctx.dryRun || undefined,
174
+ force: ctx.force || undefined,
175
+ });
176
+ if (r.error || !r.data) {
177
+ const e = r.error ?? { code: 'unknown', message: 'The push failed.', status: 500 };
178
+ ui.error(e.message);
179
+ if (e.code === 'schema_drift' && Array.isArray(e.details?.changes))
180
+ for (const s of e.details.changes)
181
+ ui.write(` ${c.dim('·')} ${s}`);
182
+ if (e.details?.line)
183
+ ui.write(` ${c.dim(`Line ${e.details.line} of the migration.`)}`);
184
+ if (e.hint)
185
+ ui.write(` ${c.dim(e.hint)}`);
186
+ if (e.code === 'schema_drift')
187
+ ui.write(` ${c.dim('Or push anyway with --force (those changes then stay out of your files).')}`);
188
+ if (e.status === 401)
189
+ ui.write(` ${c.dim('Your login expired. Run `npx usebecky login` again.')}`);
190
+ return 1;
191
+ }
192
+ if (ctx.dryRun)
193
+ ui.success(`All ${pending.length} migration${pending.length === 1 ? '' : 's'} would apply cleanly. Nothing was changed (--dry-run).`);
194
+ else
195
+ ui.success(`Applied ${r.data.applied.length} migration${r.data.applied.length === 1 ? '' : 's'}.`);
196
+ if (r.data.out_of_order?.length)
197
+ ui.warn(`Applied out of order (older than the newest applied one): ${r.data.out_of_order.join(', ')}`);
198
+ return 0;
199
+ }
200
+ async function dbDiff(ctx) {
201
+ const { ui } = ctx;
202
+ const r = await ctx.api('GET', '/database/migrations/diff');
203
+ if (r.error || !r.data)
204
+ return ctx.printError(r.error ?? { message: 'Could not compare the database.' });
205
+ if (!r.data.count) {
206
+ ui.success('No changes: everything in the database is in a migration.');
207
+ return 0;
208
+ }
209
+ ui.write(r.data.baseline ? `${c.bold(String(r.data.count))} change${r.data.count === 1 ? '' : 's'} since the last migration (made in the dashboard or the SQL editor):\n` : `The database isn't saved as migrations yet. Its whole structure:\n`);
210
+ ui.write(r.data.sql);
211
+ for (const w of r.data.warnings ?? [])
212
+ ui.warn(w);
213
+ ui.write(`${c.dim('Save this as a migration file with')} ${c.cyan('npx usebecky db pull')}`);
214
+ return 0;
215
+ }
@@ -0,0 +1,168 @@
1
+ import { type Ui } from './ui.ts';
2
+ export type ApiResult<T> = {
3
+ data: T | null;
4
+ error: ApiError | null;
5
+ };
6
+ export interface ApiError {
7
+ code: string;
8
+ message: string;
9
+ hint?: string;
10
+ status: number;
11
+ details?: any;
12
+ }
13
+ export type SiteKind = 'static' | 'node';
14
+ export interface Domain {
15
+ host: string;
16
+ status: 'pending_dns' | 'issuing' | 'active' | 'error';
17
+ records: {
18
+ type: string;
19
+ name: string;
20
+ value: string;
21
+ }[];
22
+ error?: string | null;
23
+ }
24
+ export interface Site {
25
+ id: string;
26
+ name: string;
27
+ kind: SiteKind;
28
+ url: string;
29
+ production_deploy_id: string | null;
30
+ spa_fallback: boolean;
31
+ keep_warm: boolean;
32
+ memory_mb: number;
33
+ env_names: string[];
34
+ expose_secret_key: boolean;
35
+ domains: Domain[];
36
+ disabled: boolean;
37
+ created_at: string;
38
+ }
39
+ export interface Deploy {
40
+ id: string;
41
+ short_id: string;
42
+ site_id: string;
43
+ status: 'uploading' | 'ready' | 'failed';
44
+ production: boolean;
45
+ preview_url: string;
46
+ file_count: number;
47
+ bytes: number;
48
+ created_at: string;
49
+ created_by: string | null;
50
+ /** Lines of _headers / _redirects that were skipped, each with why. */
51
+ warnings?: string[];
52
+ }
53
+ export interface HostingOverview {
54
+ available_on_plan: boolean;
55
+ required_plan?: string;
56
+ /** Settings → Usage & plan with Business picked (Free and Pro). */
57
+ upgrade_url?: string | null;
58
+ configured: boolean;
59
+ sites: Site[];
60
+ usage?: Record<string, number | null>;
61
+ limits?: Record<string, number | null>;
62
+ }
63
+ export interface HostingContext {
64
+ cwd: string;
65
+ ui: Ui;
66
+ /** For the upload progress line (a TTY gets one line that updates). */
67
+ output: NodeJS.WritableStream & {
68
+ isTTY?: boolean;
69
+ };
70
+ /** Arguments after the command (`deploy` or `hosting`), unknown --flags included. */
71
+ args: string[];
72
+ /** --project <ref>. */
73
+ project?: string;
74
+ /** The project of the publishable key in this folder's env file (`npx usebecky init`). */
75
+ linkedRef: string | null;
76
+ /** The same for another folder (`npx usebecky deploy ../web`). */
77
+ refOfFolder?: (dir: string) => string | null;
78
+ /** Non-interactive (-y, or CI): never ask. */
79
+ yes: boolean;
80
+ force: boolean;
81
+ /** The signed-in session (`npx usebecky login` or USEBECKY_ACCESS_TOKEN). */
82
+ sessionToken: string | null;
83
+ /** USEBECKY_DEPLOY_TOKEN: a project's deploy token (CI). It can deploy and list or promote deploys, nothing else. */
84
+ deployToken: string | null;
85
+ signIn: () => Promise<string | null>;
86
+ /** Platform API call: api('GET', '/projects/abc/hosting', undefined, token). */
87
+ api: <T = any>(method: string, path: string, body: unknown, auth: string | null) => Promise<ApiResult<T>>;
88
+ /** The platform API's base (for uploads to the API itself). */
89
+ apiUrl: string;
90
+ fetch: typeof fetch;
91
+ /** The dashboard's address, or null when it isn't known. */
92
+ dashboardUrl: () => Promise<string | null>;
93
+ /** The environment (CLOUDFLARE_API_TOKEN for `domains add --dns cloudflare`). */
94
+ env?: Record<string, string | undefined>;
95
+ /** Runs the build attached to this terminal and resolves with its exit code (tests pass a fake). */
96
+ runBuild?: (command: string, args: string[], cwd: string) => Promise<number>;
97
+ /** Production packages of an app (default `npm ls --omit=dev`; tests pass a fake). */
98
+ listPackages?: (dir: string) => Promise<string[] | null>;
99
+ /** Waits between log polls and upload retries (tests pass a fast one). */
100
+ sleep?: (ms: number) => Promise<void>;
101
+ /** `hosting logs --follow`: stop after this many polls (tests). */
102
+ maxPolls?: number;
103
+ }
104
+ export interface HostingArgs {
105
+ positional: string[];
106
+ site?: string;
107
+ prod: boolean;
108
+ noBuild: boolean;
109
+ follow: boolean;
110
+ /** `--dns cloudflare`: write a new domain's DNS records there (domains add). */
111
+ dns?: string;
112
+ /** Flags nobody knows (a typo): the command says so instead of guessing. */
113
+ unknown: string[];
114
+ }
115
+ export declare function parseHostingArgs(args: string[]): HostingArgs;
116
+ /** `--dns cloudflare`: the API token from the environment (never a command-line argument: those end up in shell history
117
+ * and CI logs). An error line when it is missing or the provider is unknown. */
118
+ export declare const CLOUDFLARE_TOKEN_ENV = "CLOUDFLARE_API_TOKEN";
119
+ export declare function dnsToken(dns: string | undefined, env: Record<string, string | undefined> | undefined): {
120
+ token: string | null;
121
+ problem: string | null;
122
+ };
123
+ /** What Cloudflare did (POST …/cloudflare), as lines; false when a record failed. */
124
+ export declare function reportDns(ui: Ui, r: {
125
+ added: number;
126
+ existing: number;
127
+ kept?: {
128
+ name: string;
129
+ type: string;
130
+ message: string;
131
+ }[];
132
+ failed?: {
133
+ name: string;
134
+ type: string;
135
+ message: string;
136
+ }[];
137
+ }): boolean;
138
+ export declare const LINK_FILE = "usebecky/hosting.json";
139
+ export interface SiteLink {
140
+ project?: string;
141
+ site?: string;
142
+ /** The site's kind, so a deploy token (which can't look the site up) builds frameworks that can be either the right way. */
143
+ kind?: SiteKind;
144
+ }
145
+ export declare function readLink(dir: string): SiteLink | null;
146
+ export declare function writeLink(dir: string, link: {
147
+ project: string;
148
+ site: string;
149
+ kind?: SiteKind;
150
+ }): void;
151
+ export declare const hostingPath: (ref: string, rest?: string) => string;
152
+ export declare const sitePath: (ref: string, site: string, rest?: string) => string;
153
+ export declare const KIND_LABEL: Record<SiteKind, string>;
154
+ export declare function siteStatus(s: Pick<Site, 'disabled' | 'production_deploy_id'>): string;
155
+ export declare const DOMAIN_STATUS: Record<Domain['status'], string>;
156
+ /** The production address from a preview one: https://my-app--k3x9q2m.usebecky.site → https://my-app.usebecky.site. */
157
+ export declare function productionUrlFrom(previewUrl: string | undefined, site: string): string | null;
158
+ export declare const MB: (n: number) => string;
159
+ export declare const when: (iso: string) => string;
160
+ /** A limit from GET /hosting (`hosting_deploy_bytes`, also accepted without the prefix). */
161
+ export declare function limitOf(o: HostingOverview | null | undefined, key: string): number | null;
162
+ /** Print an API error with what to do next; always returns 1 (the exit code). */
163
+ export declare function explain(ctx: HostingContext, e: ApiError, ref: string | null, site?: string): Promise<number>;
164
+ /** The project a command is about: --project, usebecky/hosting.json, then the env file's publishable key. */
165
+ export declare function projectRef(ctx: HostingContext, link: SiteLink | null): string | null;
166
+ export declare function noProject(ctx: HostingContext): number;
167
+ /** The token for a call: the session for everything; a deploy token where it's allowed (`deployOk`). Signs in when needed. */
168
+ export declare function tokenFor(ctx: HostingContext, deployOk: boolean): Promise<string | null>;
@@ -0,0 +1,177 @@
1
+ // Shared by `npx usebecky deploy` (deploy.ts) and `npx usebecky hosting …` (hosting.ts): the platform API's
2
+ // hosting shapes, flags, the folder's link to its site (usebecky/hosting.json), which project/site a command is
3
+ // about, and errors in plain words. Server: packages/server/src/modules/hosting. Guide: docs/guide/guides/hosting.md.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { c } from "./ui.js";
7
+ export function parseHostingArgs(args) {
8
+ const out = { positional: [], prod: false, noBuild: false, follow: false, unknown: [] };
9
+ for (let i = 0; i < args.length; i++) {
10
+ const a = args[i];
11
+ const eq = a.startsWith('--') ? a.indexOf('=') : -1;
12
+ const name = eq > 0 ? a.slice(0, eq) : a;
13
+ const inline = eq > 0 ? a.slice(eq + 1) : undefined;
14
+ if (name === '--site' || name === '-s')
15
+ out.site = inline ?? args[++i];
16
+ else if (name === '--prod' || name === '--production')
17
+ out.prod = true;
18
+ else if (name === '--no-build')
19
+ out.noBuild = true;
20
+ else if (name === '--build')
21
+ out.noBuild = false;
22
+ else if (name === '--follow')
23
+ out.follow = true;
24
+ else if (name === '--dns')
25
+ out.dns = (inline ?? args[++i] ?? '').trim().toLowerCase();
26
+ else if (a.startsWith('-') && a.length > 1)
27
+ out.unknown.push(a);
28
+ else
29
+ out.positional.push(a);
30
+ }
31
+ if (out.site !== undefined)
32
+ out.site = out.site.trim().toLowerCase();
33
+ return out;
34
+ }
35
+ // ---- The folder's site: usebecky/hosting.json ------------------------------------------------------------------
36
+ /** `--dns cloudflare`: the API token from the environment (never a command-line argument: those end up in shell history
37
+ * and CI logs). An error line when it is missing or the provider is unknown. */
38
+ export const CLOUDFLARE_TOKEN_ENV = 'CLOUDFLARE_API_TOKEN';
39
+ export function dnsToken(dns, env) {
40
+ if (dns === undefined)
41
+ return { token: null, problem: null };
42
+ if (dns !== 'cloudflare')
43
+ return { token: null, problem: `usebecky can write DNS records at Cloudflare only (--dns cloudflare), not "${dns || '?'}".` };
44
+ const token = env?.[CLOUDFLARE_TOKEN_ENV]?.trim();
45
+ if (!token)
46
+ return { token: null, problem: `Set ${CLOUDFLARE_TOKEN_ENV} first: Cloudflare → My Profile → API Tokens → Create Token → "Edit zone DNS" for this domain.` };
47
+ return { token, problem: null };
48
+ }
49
+ /** What Cloudflare did (POST …/cloudflare), as lines; false when a record failed. */
50
+ export function reportDns(ui, r) {
51
+ ui.success(`Cloudflare: ${r.added} record${r.added === 1 ? '' : 's'} added${r.existing ? `, ${r.existing} already there` : ''}.`);
52
+ for (const k of r.kept ?? [])
53
+ ui.warn(`Kept your ${k.type} ${k.name}: ${k.message}`);
54
+ for (const f of r.failed ?? [])
55
+ ui.error(`${f.type} ${f.name}: ${f.message}`);
56
+ return !(r.failed ?? []).length;
57
+ }
58
+ export const LINK_FILE = 'usebecky/hosting.json';
59
+ export function readLink(dir) {
60
+ try {
61
+ const j = JSON.parse(fs.readFileSync(path.join(dir, LINK_FILE), 'utf8'));
62
+ return j && typeof j === 'object' ? { project: typeof j.project === 'string' ? j.project : undefined, site: typeof j.site === 'string' ? j.site : undefined, kind: j.kind === 'static' || j.kind === 'node' ? j.kind : undefined } : null;
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ }
68
+ export function writeLink(dir, link) {
69
+ const file = path.join(dir, LINK_FILE);
70
+ fs.mkdirSync(path.dirname(file), { recursive: true });
71
+ fs.writeFileSync(file, JSON.stringify({ project: link.project, site: link.site, ...(link.kind ? { kind: link.kind } : {}) }, null, 2) + '\n');
72
+ }
73
+ // ---- Paths and words ------------------------------------------------------------------------------------------
74
+ export const hostingPath = (ref, rest = '') => `/projects/${encodeURIComponent(ref)}/hosting${rest}`;
75
+ export const sitePath = (ref, site, rest = '') => hostingPath(ref, `/sites/${encodeURIComponent(site)}${rest}`);
76
+ export const KIND_LABEL = { static: 'Static site', node: 'Node.js app' };
77
+ export function siteStatus(s) {
78
+ if (s.disabled)
79
+ return c.red('Not available');
80
+ if (!s.production_deploy_id)
81
+ return c.yellow('Waiting for the first deploy');
82
+ return c.green('Live');
83
+ }
84
+ export const DOMAIN_STATUS = {
85
+ pending_dns: 'Waiting for DNS',
86
+ issuing: 'Getting a certificate',
87
+ active: 'Live',
88
+ error: 'Needs a look',
89
+ };
90
+ /** The production address from a preview one: https://my-app--k3x9q2m.usebecky.site → https://my-app.usebecky.site. */
91
+ export function productionUrlFrom(previewUrl, site) {
92
+ if (!previewUrl)
93
+ return null;
94
+ const re = new RegExp(`^(https?://)${site.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}--[a-z0-9]+\\.`);
95
+ return re.test(previewUrl) ? previewUrl.replace(re, `$1${site}.`) : null;
96
+ }
97
+ export const MB = (n) => (n < 1024 * 1024 ? `${Math.max(1, Math.round(n / 1024))} KB` : n < 1024 ** 3 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${(n / 1024 ** 3).toFixed(2)} GB`);
98
+ export const when = (iso) => (iso ? iso.replace('T', ' ').slice(0, 16) : '');
99
+ /** A limit from GET /hosting (`hosting_deploy_bytes`, also accepted without the prefix). */
100
+ export function limitOf(o, key) {
101
+ const l = o?.limits ?? {};
102
+ const v = l[`hosting_${key}`] ?? l[key];
103
+ return typeof v === 'number' ? v : null;
104
+ }
105
+ // ---- Errors in plain words -----------------------------------------------------------------------------------
106
+ /** Print an API error with what to do next; always returns 1 (the exit code). */
107
+ export async function explain(ctx, e, ref, site) {
108
+ const { ui } = ctx;
109
+ // The API's own link (error details) first: it opens Settings → Usage & plan with the right plan picked.
110
+ const upgradeLink = async () => {
111
+ if (typeof e.details?.upgrade_url === 'string' && /^https?:\/\//.test(e.details.upgrade_url))
112
+ return e.details.upgrade_url;
113
+ const d = await ctx.dashboardUrl();
114
+ return d && ref ? `${d.replace(/\/+$/, '')}/project/${ref}/settings/usage?upgrade=hosting` : 'Dashboard → Settings → Usage & plan';
115
+ };
116
+ if (e.code === 'plan_required') {
117
+ ui.error('Hosting is part of the Business plan.');
118
+ ui.write(` Upgrade the project to put your app online with usebecky: ${c.cyan(await upgradeLink())}`);
119
+ return 1;
120
+ }
121
+ if (e.code === 'quota_exceeded' || e.code === 'limit_reached' || e.status === 429 || e.status === 402) {
122
+ ui.error(e.message);
123
+ if (e.hint)
124
+ ui.write(` ${c.dim(e.hint)}`);
125
+ if (typeof e.details?.upgrade_url === 'string' && e.details.upgrade_plan)
126
+ ui.write(` More room on a bigger plan: ${c.cyan(e.details.upgrade_url)}`);
127
+ return 1;
128
+ }
129
+ if (e.status === 401) {
130
+ ui.error(e.message);
131
+ ui.write(` ${c.dim(ctx.deployToken
132
+ ? 'The deploy token was rejected: it was revoked or belongs to another project. Create a new one in Dashboard → Hosting → Deploy tokens and save it as USEBECKY_DEPLOY_TOKEN.'
133
+ : 'Your login expired. Run `npx usebecky login` again.')}`);
134
+ return 1;
135
+ }
136
+ if (e.status === 403 && ctx.deployToken) {
137
+ ui.error(e.message);
138
+ ui.write(` ${c.dim('A deploy token can only deploy. Sign in with `npx usebecky login` (and unset USEBECKY_DEPLOY_TOKEN) for everything else.')}`);
139
+ return 1;
140
+ }
141
+ if (e.status === 404 && site && /site/.test(e.code + e.message.toLowerCase())) {
142
+ ui.error(`There's no site called “${site}” in project ${ref}.`);
143
+ ui.write(` ${c.dim(ctx.deployToken ? 'A deploy token can’t create sites. Create it in Dashboard → Hosting → New site, or run `npx usebecky deploy` once on your computer.' : 'See your sites with `npx usebecky hosting list`.')}`);
144
+ return 1;
145
+ }
146
+ ui.error(e.message);
147
+ if (e.hint)
148
+ ui.write(` ${c.dim(e.hint)}`);
149
+ return 1;
150
+ }
151
+ // ---- Which project and site --------------------------------------------------------------------------------
152
+ /** The project a command is about: --project, usebecky/hosting.json, then the env file's publishable key. */
153
+ export function projectRef(ctx, link) {
154
+ return ctx.project ?? link?.project ?? ctx.linkedRef ?? null;
155
+ }
156
+ export function noProject(ctx) {
157
+ ctx.ui.error('Which project? This folder isn’t connected to one.');
158
+ ctx.ui.write(` ${c.dim('Pass --project <ref> (Dashboard → Settings → General), or run `npx usebecky init` in your app folder.')}`);
159
+ return 1;
160
+ }
161
+ /** The token for a call: the session for everything; a deploy token where it's allowed (`deployOk`). Signs in when needed. */
162
+ export async function tokenFor(ctx, deployOk) {
163
+ if (deployOk && ctx.deployToken)
164
+ return ctx.deployToken;
165
+ if (ctx.sessionToken)
166
+ return ctx.sessionToken;
167
+ if (ctx.deployToken) {
168
+ ctx.ui.error('A deploy token (USEBECKY_DEPLOY_TOKEN) can only deploy.');
169
+ ctx.ui.write(` ${c.dim('Sign in with `npx usebecky login` for this command.')}`);
170
+ return null;
171
+ }
172
+ if (ctx.yes) {
173
+ ctx.ui.error('Not signed in. Run `npx usebecky login` first (in CI: set USEBECKY_DEPLOY_TOKEN).');
174
+ return null;
175
+ }
176
+ return ctx.signIn();
177
+ }
@@ -0,0 +1,15 @@
1
+ export type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';
2
+ /** Where `npx usebecky hosting github` writes the workflow. */
3
+ export declare const WORKFLOW_PATH = ".github/workflows/usebecky-deploy.yml";
4
+ /** The repository secret the workflow reads. */
5
+ export declare const DEPLOY_TOKEN_SECRET = "USEBECKY_DEPLOY_TOKEN";
6
+ /**
7
+ * The workflow file: pushes to main go live, pull requests get a preview address.
8
+ * `packageManager` null: no package.json (a plain HTML folder), so nothing to install.
9
+ */
10
+ export declare function githubWorkflow(opts: {
11
+ project: string;
12
+ site: string;
13
+ packageManager?: PackageManager | null;
14
+ branch?: string;
15
+ }): string;