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.
- package/README.md +701 -2
- package/dist/analytics/client.d.ts +219 -0
- package/dist/analytics/client.js +923 -0
- package/dist/analytics/cmp.d.ts +20 -0
- package/dist/analytics/cmp.js +166 -0
- package/dist/analytics/context.d.ts +29 -0
- package/dist/analytics/context.js +97 -0
- package/dist/auth/client.d.ts +401 -0
- package/dist/auth/client.js +1081 -0
- package/dist/auth/webauthn.d.ts +18 -0
- package/dist/auth/webauthn.js +138 -0
- package/dist/cli/ai.d.ts +54 -0
- package/dist/cli/ai.js +202 -0
- package/dist/cli/analytics.d.ts +53 -0
- package/dist/cli/analytics.js +357 -0
- package/dist/cli/config.d.ts +75 -0
- package/dist/cli/config.js +718 -0
- package/dist/cli/db.d.ts +48 -0
- package/dist/cli/db.js +215 -0
- package/dist/cli/deploy-api.d.ts +168 -0
- package/dist/cli/deploy-api.js +177 -0
- package/dist/cli/deploy-ci.d.ts +15 -0
- package/dist/cli/deploy-ci.js +54 -0
- package/dist/cli/deploy-detect.d.ts +64 -0
- package/dist/cli/deploy-detect.js +249 -0
- package/dist/cli/deploy-files.d.ts +112 -0
- package/dist/cli/deploy-files.js +778 -0
- package/dist/cli/deploy.d.ts +10 -0
- package/dist/cli/deploy.js +430 -0
- package/dist/cli/emails.d.ts +29 -0
- package/dist/cli/emails.js +122 -0
- package/dist/cli/framework.d.ts +135 -0
- package/dist/cli/framework.js +459 -0
- package/dist/cli/functions.d.ts +59 -0
- package/dist/cli/functions.js +426 -0
- package/dist/cli/hosting.d.ts +4 -0
- package/dist/cli/hosting.js +532 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +9 -0
- package/dist/cli/payments.d.ts +35 -0
- package/dist/cli/payments.js +176 -0
- package/dist/cli/push.d.ts +36 -0
- package/dist/cli/push.js +172 -0
- package/dist/cli/run.d.ts +65 -0
- package/dist/cli/run.js +850 -0
- package/dist/cli/social.d.ts +52 -0
- package/dist/cli/social.js +532 -0
- package/dist/cli/tokens.d.ts +28 -0
- package/dist/cli/tokens.js +114 -0
- package/dist/cli/ui.d.ts +38 -0
- package/dist/cli/ui.js +140 -0
- package/dist/client.d.ts +94 -0
- package/dist/client.js +156 -0
- package/dist/db/query.d.ts +162 -0
- package/dist/db/query.js +336 -0
- package/dist/db/types.d.ts +93 -0
- package/dist/db/types.js +4 -0
- package/dist/forms/client.d.ts +65 -0
- package/dist/forms/client.js +106 -0
- package/dist/functions/client.d.ts +37 -0
- package/dist/functions/client.js +76 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +16 -0
- package/dist/lib/dashboard-paths.d.ts +4 -0
- package/dist/lib/dashboard-paths.js +8 -0
- package/dist/lib/env.d.ts +9 -0
- package/dist/lib/env.js +55 -0
- package/dist/lib/errors.d.ts +22 -0
- package/dist/lib/errors.js +90 -0
- package/dist/lib/hosted.d.ts +2 -0
- package/dist/lib/hosted.js +7 -0
- package/dist/lib/http.d.ts +59 -0
- package/dist/lib/http.js +172 -0
- package/dist/lib/jwt.d.ts +1 -0
- package/dist/lib/jwt.js +31 -0
- package/dist/lib/locale.d.ts +12 -0
- package/dist/lib/locale.js +51 -0
- package/dist/lib/pkce.d.ts +20 -0
- package/dist/lib/pkce.js +124 -0
- package/dist/lib/storage-adapter.d.ts +15 -0
- package/dist/lib/storage-adapter.js +91 -0
- package/dist/lib/types.d.ts +339 -0
- package/dist/lib/types.js +1 -0
- package/dist/newsletter/client.d.ts +140 -0
- package/dist/newsletter/client.js +85 -0
- package/dist/payments/client.d.ts +352 -0
- package/dist/payments/client.js +323 -0
- package/dist/push/client.d.ts +110 -0
- package/dist/push/client.js +179 -0
- package/dist/realtime/client.d.ts +131 -0
- package/dist/realtime/client.js +513 -0
- package/dist/server/analytics.d.ts +176 -0
- package/dist/server/analytics.js +49 -0
- package/dist/server/cache.d.ts +74 -0
- package/dist/server/cache.js +154 -0
- package/dist/server/emails.d.ts +142 -0
- package/dist/server/emails.js +123 -0
- package/dist/server/events.d.ts +357 -0
- package/dist/server/events.js +219 -0
- package/dist/server/functions.d.ts +40 -0
- package/dist/server/functions.js +1 -0
- package/dist/server/http-utils.d.ts +10 -0
- package/dist/server/http-utils.js +115 -0
- package/dist/server/index.d.ts +195 -0
- package/dist/server/index.js +314 -0
- package/dist/server/payments.d.ts +218 -0
- package/dist/server/payments.js +150 -0
- package/dist/server/push.d.ts +85 -0
- package/dist/server/push.js +37 -0
- package/dist/server/usage.d.ts +43 -0
- package/dist/server/usage.js +8 -0
- package/dist/storage/client.d.ts +143 -0
- package/dist/storage/client.js +224 -0
- package/package.json +52 -4
- package/skill/usebecky/SKILL.md +339 -0
- package/skill/usebecky/references/access-rules.md +307 -0
- package/skill/usebecky/references/addons.md +68 -0
- package/skill/usebecky/references/analytics.md +166 -0
- package/skill/usebecky/references/android.md +434 -0
- package/skill/usebecky/references/auth.md +379 -0
- package/skill/usebecky/references/cache.md +51 -0
- package/skill/usebecky/references/components.md +127 -0
- package/skill/usebecky/references/emails.md +105 -0
- package/skill/usebecky/references/expo.md +147 -0
- package/skill/usebecky/references/functions.md +99 -0
- package/skill/usebecky/references/hosting.md +119 -0
- package/skill/usebecky/references/http-api.md +233 -0
- package/skill/usebecky/references/ios.md +355 -0
- package/skill/usebecky/references/payments.md +493 -0
- package/skill/usebecky/references/realtime.md +143 -0
- package/skill/usebecky/references/scheduled-jobs.md +82 -0
- package/skill/usebecky/references/sdk.md +838 -0
- package/skill/usebecky/references/storage.md +210 -0
- package/skill/usebecky/references/templates.md +191 -0
- package/skill/usebecky/references/wordpress.md +87 -0
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// `npx usebecky tokens <list|create|delete>`: project tokens for CI and scripts (server: platform/project-tokens.ts).
|
|
2
|
+
//
|
|
3
|
+
// tokens list the project's tokens (name, scopes, last used)
|
|
4
|
+
// tokens create <name> --scope db,config [--expires 90] a new token, shown once
|
|
5
|
+
// tokens delete <name or id> it stops working at once
|
|
6
|
+
//
|
|
7
|
+
// In CI: USEBECKY_ACCESS_TOKEN=ubpt_… (instead of `usebecky login`) with --project <ref> or the app's .env.
|
|
8
|
+
import { c } from "./ui.js";
|
|
9
|
+
export const SCOPE_TEXT = {
|
|
10
|
+
db: 'database migrations and types',
|
|
11
|
+
config: 'settings in usebecky/config.json',
|
|
12
|
+
deploy: 'deploy sites (Hosting)',
|
|
13
|
+
functions: 'deploy functions, their secrets and logs',
|
|
14
|
+
admin: 'everything an admin can do in this project',
|
|
15
|
+
};
|
|
16
|
+
const HELP = `
|
|
17
|
+
${c.bold('npx usebecky tokens')}: project tokens for CI and scripts, instead of a personal login
|
|
18
|
+
|
|
19
|
+
${c.cyan('tokens list')} The project's tokens
|
|
20
|
+
${c.cyan('tokens create <name> --scope db,config')} A new token (shown once); --expires <days> to let it run out
|
|
21
|
+
${c.cyan('tokens delete <name>')} Stop a token at once
|
|
22
|
+
|
|
23
|
+
Scopes: ${Object.entries(SCOPE_TEXT).map(([k, v]) => `${k} (${v})`).join(', ')}.
|
|
24
|
+
In CI: USEBECKY_ACCESS_TOKEN=ubpt_… npx usebecky db push --project <ref>
|
|
25
|
+
Options: --project <ref>, -y (don't ask)
|
|
26
|
+
`;
|
|
27
|
+
/** `--scope db,config`, `--scope=db --scope config`, `--expires 90` out of the positional words. */
|
|
28
|
+
function options(args) {
|
|
29
|
+
const words = [];
|
|
30
|
+
const scopes = [];
|
|
31
|
+
let expires = null;
|
|
32
|
+
for (let i = 0; i < args.length; i++) {
|
|
33
|
+
const a = args[i];
|
|
34
|
+
const [flag, inline] = a.startsWith('--') && a.includes('=') ? [a.slice(0, a.indexOf('=')), a.slice(a.indexOf('=') + 1)] : [a, undefined];
|
|
35
|
+
if (flag === '--scope' || flag === '--scopes')
|
|
36
|
+
scopes.push(...(inline ?? args[++i] ?? '').split(',').map((s) => s.trim()).filter(Boolean));
|
|
37
|
+
else if (flag === '--expires')
|
|
38
|
+
expires = inline ?? args[++i] ?? null;
|
|
39
|
+
else
|
|
40
|
+
words.push(a);
|
|
41
|
+
}
|
|
42
|
+
return { words, scopes, expires };
|
|
43
|
+
}
|
|
44
|
+
const day = (iso) => (iso ? new Date(iso).toISOString().slice(0, 10) : null);
|
|
45
|
+
export async function tokensCommand(ctx) {
|
|
46
|
+
const { ui } = ctx;
|
|
47
|
+
const { words, scopes, expires } = options(ctx.args);
|
|
48
|
+
const [sub, ...rest] = words;
|
|
49
|
+
if (!sub || sub === 'help') {
|
|
50
|
+
ui.write(HELP);
|
|
51
|
+
return sub ? 0 : 1;
|
|
52
|
+
}
|
|
53
|
+
if (!['list', 'ls', 'create', 'delete', 'rm'].includes(sub)) {
|
|
54
|
+
ui.error(`Unknown command "tokens ${sub}".`);
|
|
55
|
+
ui.write(HELP);
|
|
56
|
+
return 1;
|
|
57
|
+
}
|
|
58
|
+
const name = rest.join(' ').trim();
|
|
59
|
+
if (sub === 'create' && (!name || !scopes.length)) {
|
|
60
|
+
ui.error(!name ? 'Give the token a name: npx usebecky tokens create "GitHub Actions" --scope db,config' : 'Say what the token may do: --scope db,config (or deploy, functions, admin)');
|
|
61
|
+
return 1;
|
|
62
|
+
}
|
|
63
|
+
if ((sub === 'delete' || sub === 'rm') && !name) {
|
|
64
|
+
ui.error('Which token? npx usebecky tokens delete "GitHub Actions"');
|
|
65
|
+
return 1;
|
|
66
|
+
}
|
|
67
|
+
if (!ctx.ref)
|
|
68
|
+
return ctx.noProject();
|
|
69
|
+
if (!(await ctx.signIn()))
|
|
70
|
+
return 1;
|
|
71
|
+
if (sub === 'create') {
|
|
72
|
+
const r = await ctx.api('POST', '/tokens', { name, scopes, ...(expires ? { expires_in_days: Number(expires) } : {}) });
|
|
73
|
+
if (r.error || !r.data)
|
|
74
|
+
return ctx.printError(r.error ?? { message: 'Could not make the token.' });
|
|
75
|
+
ui.success(`Made the token ${c.bold(r.data.name)} (${r.data.scopes.join(', ')})${r.data.expires_at ? `, runs out on ${day(r.data.expires_at)}` : ''}.`);
|
|
76
|
+
ui.write('');
|
|
77
|
+
ui.write(` ${c.bold(r.data.token)}`);
|
|
78
|
+
ui.write('');
|
|
79
|
+
ui.write(c.dim(' Copy it now: it is shown only once. Keep it in your CI secrets as USEBECKY_ACCESS_TOKEN,'));
|
|
80
|
+
ui.write(c.dim(` e.g. GitHub → Settings → Secrets and variables → Actions. Then: npx usebecky db push --project ${ctx.ref}`));
|
|
81
|
+
return 0;
|
|
82
|
+
}
|
|
83
|
+
const list = await ctx.api('GET', '/tokens');
|
|
84
|
+
if (list.error || !list.data)
|
|
85
|
+
return ctx.printError(list.error ?? { message: 'Could not load the tokens.' });
|
|
86
|
+
const tokens = list.data.tokens;
|
|
87
|
+
if (sub === 'list' || sub === 'ls') {
|
|
88
|
+
if (!tokens.length) {
|
|
89
|
+
ui.info('No project tokens yet. Make one for CI: npx usebecky tokens create "GitHub Actions" --scope db,config');
|
|
90
|
+
return 0;
|
|
91
|
+
}
|
|
92
|
+
for (const t of tokens) {
|
|
93
|
+
const used = t.last_used_at ? `last used ${day(t.last_used_at)}` : 'never used';
|
|
94
|
+
ui.write(`${c.bold(t.name)} ${c.cyan(t.scopes.join(', '))} ${c.dim(`${t.hint} ${used}${t.expires_at ? ` runs out ${day(t.expires_at)}` : ''}`)}`);
|
|
95
|
+
}
|
|
96
|
+
return 0;
|
|
97
|
+
}
|
|
98
|
+
const matching = tokens.filter((t) => t.id === name || t.name === name);
|
|
99
|
+
if (matching.length !== 1) {
|
|
100
|
+
ui.error(matching.length ? `${matching.length} tokens are called "${name}". Delete one by its id.` : `There is no token "${name}" in project ${ctx.ref}.`);
|
|
101
|
+
if (matching.length)
|
|
102
|
+
for (const t of matching)
|
|
103
|
+
ui.write(` ${t.id} ${c.dim(t.hint)}`);
|
|
104
|
+
return 1;
|
|
105
|
+
}
|
|
106
|
+
const t = matching[0];
|
|
107
|
+
if (!ctx.yes && !(await ui.confirm(`Delete the token ${t.name}? Jobs that use it stop working.`, false)))
|
|
108
|
+
return 1;
|
|
109
|
+
const r = await ctx.api('DELETE', `/tokens/${encodeURIComponent(t.id)}`);
|
|
110
|
+
if (r.error)
|
|
111
|
+
return ctx.printError(r.error);
|
|
112
|
+
ui.success(`Deleted the token ${t.name}.`);
|
|
113
|
+
return 0;
|
|
114
|
+
}
|
package/dist/cli/ui.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export interface Io {
|
|
2
|
+
input: NodeJS.ReadableStream & {
|
|
3
|
+
isTTY?: boolean;
|
|
4
|
+
setRawMode?: (mode: boolean) => void;
|
|
5
|
+
};
|
|
6
|
+
output: NodeJS.WritableStream & {
|
|
7
|
+
isTTY?: boolean;
|
|
8
|
+
};
|
|
9
|
+
/** Non-interactive: accept defaults, never overwrite, never block on input. */
|
|
10
|
+
yes: boolean;
|
|
11
|
+
}
|
|
12
|
+
export declare const c: {
|
|
13
|
+
bold: (s: string) => string;
|
|
14
|
+
dim: (s: string) => string;
|
|
15
|
+
red: (s: string) => string;
|
|
16
|
+
green: (s: string) => string;
|
|
17
|
+
yellow: (s: string) => string;
|
|
18
|
+
blue: (s: string) => string;
|
|
19
|
+
magenta: (s: string) => string;
|
|
20
|
+
cyan: (s: string) => string;
|
|
21
|
+
gray: (s: string) => string;
|
|
22
|
+
};
|
|
23
|
+
export declare function createUi(io: Io): {
|
|
24
|
+
write: (s?: string) => boolean;
|
|
25
|
+
ask: (question: string, defaultValue?: string) => Promise<string>;
|
|
26
|
+
askHidden: (question: string) => Promise<string>;
|
|
27
|
+
confirm: (question: string, defaultYes?: boolean) => Promise<boolean>;
|
|
28
|
+
choose: <T>(question: string, options: Array<{
|
|
29
|
+
label: string;
|
|
30
|
+
value: T;
|
|
31
|
+
}>, defaultIndex?: number) => Promise<T>;
|
|
32
|
+
success: (s: string) => boolean;
|
|
33
|
+
info: (s: string) => boolean;
|
|
34
|
+
warn: (s: string) => boolean;
|
|
35
|
+
error: (s: string) => boolean;
|
|
36
|
+
close: () => void;
|
|
37
|
+
};
|
|
38
|
+
export type Ui = ReturnType<typeof createUi>;
|
package/dist/cli/ui.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// Tiny terminal UI: colors and prompts with zero dependencies.
|
|
2
|
+
import readline from 'node:readline';
|
|
3
|
+
const useColor = () => !!process.stdout.isTTY && !process.env.NO_COLOR && process.env.TERM !== 'dumb';
|
|
4
|
+
const wrap = (code, close = 39) => (s) => (useColor() ? `\u001b[${code}m${s}\u001b[${close}m` : s);
|
|
5
|
+
export const c = {
|
|
6
|
+
bold: wrap(1, 22),
|
|
7
|
+
dim: wrap(2, 22),
|
|
8
|
+
red: wrap(31),
|
|
9
|
+
green: wrap(32),
|
|
10
|
+
yellow: wrap(33),
|
|
11
|
+
blue: wrap(34),
|
|
12
|
+
magenta: wrap(35),
|
|
13
|
+
cyan: wrap(36),
|
|
14
|
+
gray: wrap(90),
|
|
15
|
+
};
|
|
16
|
+
export function createUi(io) {
|
|
17
|
+
const write = (s = '') => io.output.write(s + '\n');
|
|
18
|
+
let rl = null;
|
|
19
|
+
let lineQueue = [];
|
|
20
|
+
let waiting = null;
|
|
21
|
+
let closed = false;
|
|
22
|
+
function ensureRl() {
|
|
23
|
+
if (!rl) {
|
|
24
|
+
rl = readline.createInterface({ input: io.input, terminal: false });
|
|
25
|
+
rl.on('line', (line) => {
|
|
26
|
+
if (waiting) {
|
|
27
|
+
const w = waiting;
|
|
28
|
+
waiting = null;
|
|
29
|
+
w(line);
|
|
30
|
+
}
|
|
31
|
+
else
|
|
32
|
+
lineQueue.push(line);
|
|
33
|
+
});
|
|
34
|
+
rl.on('close', () => {
|
|
35
|
+
closed = true;
|
|
36
|
+
if (waiting) {
|
|
37
|
+
const w = waiting;
|
|
38
|
+
waiting = null;
|
|
39
|
+
w(null);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return rl;
|
|
44
|
+
}
|
|
45
|
+
function readLine() {
|
|
46
|
+
ensureRl();
|
|
47
|
+
if (lineQueue.length)
|
|
48
|
+
return Promise.resolve(lineQueue.shift());
|
|
49
|
+
if (closed)
|
|
50
|
+
return Promise.resolve(null);
|
|
51
|
+
return new Promise((resolve) => (waiting = resolve));
|
|
52
|
+
}
|
|
53
|
+
async function ask(question, defaultValue = '') {
|
|
54
|
+
if (io.yes)
|
|
55
|
+
return defaultValue;
|
|
56
|
+
io.output.write(`${c.cyan('?')} ${question}${defaultValue ? c.dim(` (${defaultValue})`) : ''} `);
|
|
57
|
+
const line = await readLine();
|
|
58
|
+
if (line === null)
|
|
59
|
+
return defaultValue;
|
|
60
|
+
return line.trim() || defaultValue;
|
|
61
|
+
}
|
|
62
|
+
async function askHidden(question) {
|
|
63
|
+
if (io.yes)
|
|
64
|
+
return '';
|
|
65
|
+
const input = io.input;
|
|
66
|
+
if (!input.isTTY || typeof input.setRawMode !== 'function')
|
|
67
|
+
return ask(question);
|
|
68
|
+
io.output.write(`${c.cyan('?')} ${question} `);
|
|
69
|
+
// Pause our line reader while reading raw keypresses.
|
|
70
|
+
rl?.pause();
|
|
71
|
+
return new Promise((resolve) => {
|
|
72
|
+
let value = '';
|
|
73
|
+
input.setRawMode(true);
|
|
74
|
+
input.resume();
|
|
75
|
+
const onData = (buf) => {
|
|
76
|
+
for (const ch of buf.toString('utf8')) {
|
|
77
|
+
if (ch === '\r' || ch === '\n' || ch === '\u0004') {
|
|
78
|
+
input.setRawMode(false);
|
|
79
|
+
input.removeListener('data', onData);
|
|
80
|
+
io.output.write('\n');
|
|
81
|
+
rl?.resume();
|
|
82
|
+
return resolve(value);
|
|
83
|
+
}
|
|
84
|
+
if (ch === '\u0003') {
|
|
85
|
+
input.setRawMode(false);
|
|
86
|
+
io.output.write('\n');
|
|
87
|
+
process.exit(130);
|
|
88
|
+
}
|
|
89
|
+
if (ch === '\u007f' || ch === '\b') {
|
|
90
|
+
if (value.length) {
|
|
91
|
+
value = value.slice(0, -1);
|
|
92
|
+
io.output.write('\b \b');
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
else if (ch >= ' ') {
|
|
96
|
+
value += ch;
|
|
97
|
+
io.output.write('*');
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
input.on('data', onData);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
async function confirm(question, defaultYes = false) {
|
|
105
|
+
if (io.yes)
|
|
106
|
+
return defaultYes;
|
|
107
|
+
const answer = (await ask(`${question} ${c.dim(defaultYes ? '[Y/n]' : '[y/N]')}`)).toLowerCase();
|
|
108
|
+
if (!answer)
|
|
109
|
+
return defaultYes;
|
|
110
|
+
return answer === 'y' || answer === 'yes';
|
|
111
|
+
}
|
|
112
|
+
async function choose(question, options, defaultIndex = 0) {
|
|
113
|
+
if (io.yes || options.length === 1)
|
|
114
|
+
return options[defaultIndex].value;
|
|
115
|
+
write(`${c.cyan('?')} ${question}`);
|
|
116
|
+
options.forEach((o, i) => write(` ${c.bold(String(i + 1))}) ${o.label}`));
|
|
117
|
+
for (;;) {
|
|
118
|
+
const answer = await ask('Enter a number', String(defaultIndex + 1));
|
|
119
|
+
const n = Number(answer);
|
|
120
|
+
if (Number.isInteger(n) && n >= 1 && n <= options.length)
|
|
121
|
+
return options[n - 1].value;
|
|
122
|
+
write(c.yellow(` Please enter a number from 1 to ${options.length}.`));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
write,
|
|
127
|
+
ask,
|
|
128
|
+
askHidden,
|
|
129
|
+
confirm,
|
|
130
|
+
choose,
|
|
131
|
+
success: (s) => write(`${c.green('✔')} ${s}`),
|
|
132
|
+
info: (s) => write(`${c.blue('ℹ')} ${s}`),
|
|
133
|
+
warn: (s) => write(`${c.yellow('!')} ${s}`),
|
|
134
|
+
error: (s) => write(`${c.red('✖')} ${s}`),
|
|
135
|
+
close: () => {
|
|
136
|
+
rl?.close();
|
|
137
|
+
rl = null;
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { AnalyticsClient, type AnalyticsOptions } from './analytics/client.ts';
|
|
2
|
+
import { AuthClient } from './auth/client.ts';
|
|
3
|
+
import { Database } from './db/query.ts';
|
|
4
|
+
import { FormsClient } from './forms/client.ts';
|
|
5
|
+
import { FunctionsClient } from './functions/client.ts';
|
|
6
|
+
import { NewsletterClient } from './newsletter/client.ts';
|
|
7
|
+
import { PushClient } from './push/client.ts';
|
|
8
|
+
import { type FetchLike } from './lib/http.ts';
|
|
9
|
+
import { type StorageAdapter } from './lib/storage-adapter.ts';
|
|
10
|
+
import { PaymentsClient } from './payments/client.ts';
|
|
11
|
+
import { RealtimeClient, type RealtimeOptions } from './realtime/client.ts';
|
|
12
|
+
import { StorageClient } from './storage/client.ts';
|
|
13
|
+
export interface ClientOptions {
|
|
14
|
+
/** Where to keep the session. Default: localStorage in browsers, memory elsewhere. Pass AsyncStorage in React Native. */
|
|
15
|
+
storage?: StorageAdapter;
|
|
16
|
+
/** Refresh the access token before it expires. Default true. */
|
|
17
|
+
autoRefresh?: boolean;
|
|
18
|
+
/** Finish OAuth / magic-link / password-reset redirects by reading the URL fragment. Default true. */
|
|
19
|
+
detectSessionInUrl?: boolean;
|
|
20
|
+
/** Mirror the access token to a `ub-access-token` cookie so your server can read it (SSR). Default true in browsers. */
|
|
21
|
+
cookie?: boolean;
|
|
22
|
+
/** Custom storage key for the session. */
|
|
23
|
+
storageKey?: string;
|
|
24
|
+
/** Custom fetch implementation. */
|
|
25
|
+
fetch?: FetchLike;
|
|
26
|
+
/** Extra headers sent with every request. */
|
|
27
|
+
headers?: Record<string, string>;
|
|
28
|
+
/** Realtime settings (e.g. a WebSocket implementation for older runtimes). */
|
|
29
|
+
realtime?: RealtimeOptions;
|
|
30
|
+
/** Product analytics (`baas.analytics`). `false` turns it off (call `baas.analytics.enable()` later, e.g. after consent). Default on, no automatic page views. */
|
|
31
|
+
analytics?: boolean | AnalyticsOptions;
|
|
32
|
+
/**
|
|
33
|
+
* The language of the emails usebecky sends to your users (sign-up confirmation, magic link, password
|
|
34
|
+
* reset, form auto-replies...), like `'de'` or `'pt-BR'`. Sent as the `Accept-Language` header on every
|
|
35
|
+
* request. Default: none, so browsers send their own language and emails come in it automatically.
|
|
36
|
+
* Change it later with `baas.setLocale()`. A language your project hasn't turned on falls back to your
|
|
37
|
+
* default language (Dashboard → Emails).
|
|
38
|
+
*/
|
|
39
|
+
locale?: string;
|
|
40
|
+
}
|
|
41
|
+
/** The error createClient() throws without a publishable key. The URL is never missing: it defaults to HOSTED_API_URL. */
|
|
42
|
+
export declare function missingConfigMessage(): string;
|
|
43
|
+
export declare function validateUrl(url: string, name?: string): string;
|
|
44
|
+
export declare class UseBeckyClient<DB = any> extends Database<DB> {
|
|
45
|
+
/** Your project's API URL. */
|
|
46
|
+
readonly url: string;
|
|
47
|
+
/** The publishable key this client uses. */
|
|
48
|
+
readonly key: string;
|
|
49
|
+
/** Sign up, sign in (password, magic link, Google/GitHub/Apple), sessions, MFA. */
|
|
50
|
+
readonly auth: AuthClient;
|
|
51
|
+
/** Upload and download files. */
|
|
52
|
+
readonly storage: StorageClient;
|
|
53
|
+
/** Live table changes, broadcast and presence. */
|
|
54
|
+
readonly realtime: RealtimeClient<DB>;
|
|
55
|
+
/** Stripe products, checkout, customer portal and access checks. */
|
|
56
|
+
readonly payments: PaymentsClient;
|
|
57
|
+
/** Product analytics: track events and page views (`track`, `page`, `identify`, `flush`). */
|
|
58
|
+
readonly analytics: AnalyticsClient;
|
|
59
|
+
/** Contact forms and other forms made in Dashboard → Forms (`submit`, `get`). */
|
|
60
|
+
readonly forms: FormsClient;
|
|
61
|
+
/** Newsletter sign-ups made in Dashboard → Newsletter (`subscribe`). */
|
|
62
|
+
readonly newsletter: NewsletterClient;
|
|
63
|
+
/** Push notifications: `register` this device, `subscribeWebPush` a browser, `unregister`. */
|
|
64
|
+
readonly push: PushClient;
|
|
65
|
+
/** Your own code on usebecky (Dashboard → Functions): `invoke('name', { body })`. Sends the signed-in user's token. */
|
|
66
|
+
readonly functions: FunctionsClient;
|
|
67
|
+
constructor(url: string, key: string, options?: ClientOptions);
|
|
68
|
+
/** The language set with the `locale` option or `setLocale()`, or null (then browsers send their own). */
|
|
69
|
+
get locale(): string | null;
|
|
70
|
+
/**
|
|
71
|
+
* Set the language of the emails usebecky sends to this user from now on, like `'de'` or `'pt-BR'`
|
|
72
|
+
* (sent as the `Accept-Language` header on every request). `null` goes back to the browser's language.
|
|
73
|
+
* Call it when someone picks a language in your app:
|
|
74
|
+
*
|
|
75
|
+
* baas.setLocale('de')
|
|
76
|
+
*
|
|
77
|
+
* To remember the choice for emails sent later (even from another device), also save it on the user:
|
|
78
|
+
* `baas.auth.updateUser({ data: { locale: 'de' } })`. A value that isn't a language code is ignored.
|
|
79
|
+
*/
|
|
80
|
+
setLocale(locale: string | null): void;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Create your usebecky client. Your project runs on the hosted API (HOSTED_API_URL), so the
|
|
84
|
+
* publishable key is all it needs:
|
|
85
|
+
*
|
|
86
|
+
* import { createClient } from 'usebecky'
|
|
87
|
+
* export const baas = createClient('ub_pk_...')
|
|
88
|
+
*
|
|
89
|
+
* With no arguments it reads the key from environment variables (USEBECKY_PUBLISHABLE_KEY,
|
|
90
|
+
* NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY, EXPO_PUBLIC_USEBECKY_PUBLISHABLE_KEY). `createClient(url, key)`
|
|
91
|
+
* and the *_USEBECKY_URL variables still work, to use a different API address.
|
|
92
|
+
*/
|
|
93
|
+
export declare function createClient<DB = any>(publishableKey: string, options?: ClientOptions): UseBeckyClient<DB>;
|
|
94
|
+
export declare function createClient<DB = any>(url?: string, publishableKey?: string, options?: ClientOptions): UseBeckyClient<DB>;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// The browser / app client returned by createClient().
|
|
2
|
+
import { AnalyticsClient } from "./analytics/client.js";
|
|
3
|
+
import { AuthClient } from "./auth/client.js";
|
|
4
|
+
import { Database } from "./db/query.js";
|
|
5
|
+
import { FormsClient } from "./forms/client.js";
|
|
6
|
+
import { FunctionsClient } from "./functions/client.js";
|
|
7
|
+
import { NewsletterClient } from "./newsletter/client.js";
|
|
8
|
+
import { PushClient } from "./push/client.js";
|
|
9
|
+
import { envPublishableKey, envUrl, isBrowser, keyType, refFromKey } from "./lib/env.js";
|
|
10
|
+
import { HOSTED_API_URL } from "./lib/hosted.js";
|
|
11
|
+
import { HttpClient } from "./lib/http.js";
|
|
12
|
+
import { readLocale } from "./lib/locale.js";
|
|
13
|
+
import { DASHBOARD_API_KEYS } from "./lib/dashboard-paths.js";
|
|
14
|
+
import { defaultStorage, withLegacyKeys } from "./lib/storage-adapter.js";
|
|
15
|
+
import { PaymentsClient } from "./payments/client.js";
|
|
16
|
+
import { RealtimeClient } from "./realtime/client.js";
|
|
17
|
+
import { StorageClient } from "./storage/client.js";
|
|
18
|
+
const g = globalThis;
|
|
19
|
+
function warn(msg) {
|
|
20
|
+
try {
|
|
21
|
+
g.console?.warn?.(msg);
|
|
22
|
+
}
|
|
23
|
+
catch { }
|
|
24
|
+
}
|
|
25
|
+
/** The error createClient() throws without a publishable key. The URL is never missing: it defaults to HOSTED_API_URL. */
|
|
26
|
+
export function missingConfigMessage() {
|
|
27
|
+
return [
|
|
28
|
+
'usebecky: createClient() is missing your publishable key.',
|
|
29
|
+
'',
|
|
30
|
+
`Pass it in, createClient("ub_pk_..."), or set it as an environment variable (copy it from ${DASHBOARD_API_KEYS}):`,
|
|
31
|
+
' Next.js: NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY (in .env.local)',
|
|
32
|
+
' Vite: VITE_USEBECKY_PUBLISHABLE_KEY (in .env.local, then pass it in:',
|
|
33
|
+
' createClient(import.meta.env.VITE_USEBECKY_PUBLISHABLE_KEY))',
|
|
34
|
+
' Expo: EXPO_PUBLIC_USEBECKY_PUBLISHABLE_KEY (in .env)',
|
|
35
|
+
' Node: USEBECKY_PUBLISHABLE_KEY (in .env)',
|
|
36
|
+
'',
|
|
37
|
+
'Or run `npx usebecky init` to set everything up.',
|
|
38
|
+
].join('\n');
|
|
39
|
+
}
|
|
40
|
+
export function validateUrl(url, name = 'URL') {
|
|
41
|
+
const trimmed = url.trim().replace(/\/+$/, '');
|
|
42
|
+
if (!/^https?:\/\/[^/]+/i.test(trimmed)) {
|
|
43
|
+
throw new Error(`usebecky: the project ${name} must start with http:// or https:// (got "${url}"). Copy it from ${DASHBOARD_API_KEYS}.`);
|
|
44
|
+
}
|
|
45
|
+
return trimmed.replace(/\/(rest|auth|storage|realtime|payments|analytics|forms|newsletter|push|functions)\/v1$/, '');
|
|
46
|
+
}
|
|
47
|
+
export class UseBeckyClient extends Database {
|
|
48
|
+
/** Your project's API URL. */
|
|
49
|
+
url;
|
|
50
|
+
/** The publishable key this client uses. */
|
|
51
|
+
key;
|
|
52
|
+
/** Sign up, sign in (password, magic link, Google/GitHub/Apple), sessions, MFA. */
|
|
53
|
+
auth;
|
|
54
|
+
/** Upload and download files. */
|
|
55
|
+
storage;
|
|
56
|
+
/** Live table changes, broadcast and presence. */
|
|
57
|
+
realtime;
|
|
58
|
+
/** Stripe products, checkout, customer portal and access checks. */
|
|
59
|
+
payments;
|
|
60
|
+
/** Product analytics: track events and page views (`track`, `page`, `identify`, `flush`). */
|
|
61
|
+
analytics;
|
|
62
|
+
/** Contact forms and other forms made in Dashboard → Forms (`submit`, `get`). */
|
|
63
|
+
forms;
|
|
64
|
+
/** Newsletter sign-ups made in Dashboard → Newsletter (`subscribe`). */
|
|
65
|
+
newsletter;
|
|
66
|
+
/** Push notifications: `register` this device, `subscribeWebPush` a browser, `unregister`. */
|
|
67
|
+
push;
|
|
68
|
+
/** Your own code on usebecky (Dashboard → Functions): `invoke('name', { body })`. Sends the signed-in user's token. */
|
|
69
|
+
functions;
|
|
70
|
+
constructor(url, key, options = {}) {
|
|
71
|
+
let authRef = null;
|
|
72
|
+
const http = new HttpClient({
|
|
73
|
+
url,
|
|
74
|
+
key,
|
|
75
|
+
fetch: options.fetch,
|
|
76
|
+
headers: options.headers,
|
|
77
|
+
locale: { value: readLocale(options.locale, 'createClient({ locale })') },
|
|
78
|
+
getToken: () => (authRef ? authRef.getAccessToken() : Promise.resolve(null)),
|
|
79
|
+
onTokenRejected: (token) => (authRef ? authRef.handleRejectedToken(token) : Promise.resolve(null)),
|
|
80
|
+
});
|
|
81
|
+
super(http);
|
|
82
|
+
this.url = http.url;
|
|
83
|
+
this.key = key;
|
|
84
|
+
const ref = refFromKey(key);
|
|
85
|
+
let host = 'default';
|
|
86
|
+
try {
|
|
87
|
+
host = new URL(this.url).host;
|
|
88
|
+
}
|
|
89
|
+
catch { }
|
|
90
|
+
const storage = withLegacyKeys(options.storage ?? defaultStorage());
|
|
91
|
+
this.auth = new AuthClient({
|
|
92
|
+
http,
|
|
93
|
+
storage,
|
|
94
|
+
storageKey: options.storageKey ?? `ub-${ref ?? host}-auth`,
|
|
95
|
+
autoRefresh: options.autoRefresh ?? true,
|
|
96
|
+
detectSessionInUrl: options.detectSessionInUrl ?? true,
|
|
97
|
+
cookie: options.cookie ?? true,
|
|
98
|
+
// Created below; only called later, from signUp() / sendMagicLink().
|
|
99
|
+
consent: () => this.analytics.consentRef(),
|
|
100
|
+
});
|
|
101
|
+
authRef = this.auth;
|
|
102
|
+
this.storage = new StorageClient(http, keyType(key) === 'secret' ? null : key);
|
|
103
|
+
this.realtime = new RealtimeClient({ url: this.url, key, getToken: () => this.auth.getAccessToken(), options: options.realtime });
|
|
104
|
+
this.analytics = new AnalyticsClient({ http, key, storage, storageKey: `ub-${ref ?? host}`, getSession: () => this.auth.getSession().data.session, options: options.analytics });
|
|
105
|
+
this.payments = new PaymentsClient(http, async () => !!(await this.auth.getAccessToken()), () => this.analytics.visitRef(), () => this.analytics.consentRef());
|
|
106
|
+
this.forms = new FormsClient(http, () => this.analytics.consentRef());
|
|
107
|
+
this.newsletter = new NewsletterClient(http);
|
|
108
|
+
this.push = new PushClient(http, storage, `ub-${ref ?? host}-push`, this.auth);
|
|
109
|
+
this.functions = new FunctionsClient(http);
|
|
110
|
+
this.auth.onAuthStateChange((_event, session) => this.realtime.setAuth(session?.access_token ?? null));
|
|
111
|
+
}
|
|
112
|
+
/** The language set with the `locale` option or `setLocale()`, or null (then browsers send their own). */
|
|
113
|
+
get locale() {
|
|
114
|
+
return this.http.locale;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Set the language of the emails usebecky sends to this user from now on, like `'de'` or `'pt-BR'`
|
|
118
|
+
* (sent as the `Accept-Language` header on every request). `null` goes back to the browser's language.
|
|
119
|
+
* Call it when someone picks a language in your app:
|
|
120
|
+
*
|
|
121
|
+
* baas.setLocale('de')
|
|
122
|
+
*
|
|
123
|
+
* To remember the choice for emails sent later (even from another device), also save it on the user:
|
|
124
|
+
* `baas.auth.updateUser({ data: { locale: 'de' } })`. A value that isn't a language code is ignored.
|
|
125
|
+
*/
|
|
126
|
+
setLocale(locale) {
|
|
127
|
+
if (locale === null || locale === undefined || locale === '')
|
|
128
|
+
return this.http.setLocale(null);
|
|
129
|
+
const tidy = readLocale(locale, 'setLocale()');
|
|
130
|
+
if (tidy)
|
|
131
|
+
this.http.setLocale(tidy);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/** True for the one-argument form createClient("ub_pk_...", options?): a key, not a URL, in first place. */
|
|
135
|
+
function isKeyFirst(first, second) {
|
|
136
|
+
return typeof first === 'string' && typeof second !== 'string' && !/^[a-z][a-z0-9+.-]*:\/\//i.test(first.trim()) && first.trim() !== '';
|
|
137
|
+
}
|
|
138
|
+
export function createClient(first, second, third) {
|
|
139
|
+
const keyFirst = isKeyFirst(first, second);
|
|
140
|
+
const url = keyFirst ? undefined : first;
|
|
141
|
+
const publishableKey = keyFirst ? first : second;
|
|
142
|
+
const options = (keyFirst ? second : third) ?? {};
|
|
143
|
+
const finalUrl = url || envUrl() || HOSTED_API_URL;
|
|
144
|
+
const finalKey = publishableKey || envPublishableKey();
|
|
145
|
+
if (!finalKey)
|
|
146
|
+
throw new Error(missingConfigMessage());
|
|
147
|
+
const type = keyType(finalKey);
|
|
148
|
+
if (type === 'secret' && isBrowser()) {
|
|
149
|
+
warn('[usebecky] ⚠️ You passed your SECRET key to createClient() in a browser. Anyone can read it and bypass all your security rules.\n' +
|
|
150
|
+
`Use the publishable key (ub_pk_...) here, keep the secret key on your server only, and roll it now in ${DASHBOARD_API_KEYS}.`);
|
|
151
|
+
}
|
|
152
|
+
else if (type === 'unknown') {
|
|
153
|
+
warn(`[usebecky] The key passed to createClient() does not look like a usebecky key (they start with "ub_pk_"). Copy it from ${DASHBOARD_API_KEYS}.`);
|
|
154
|
+
}
|
|
155
|
+
return new UseBeckyClient(validateUrl(finalUrl), finalKey, options);
|
|
156
|
+
}
|