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,106 @@
|
|
|
1
|
+
import { UseBeckyError } from "../lib/errors.js";
|
|
2
|
+
const g = globalThis;
|
|
3
|
+
function invalid(message, hint) {
|
|
4
|
+
return new UseBeckyError({ code: 'invalid_input', message, hint, status: 0 });
|
|
5
|
+
}
|
|
6
|
+
function isFormElement(v) {
|
|
7
|
+
return typeof g.HTMLFormElement === 'function' && v instanceof g.HTMLFormElement;
|
|
8
|
+
}
|
|
9
|
+
/** FormData → plain object. Repeated names become lists. Files are refused (forms take text only). */
|
|
10
|
+
function fromFormData(fd) {
|
|
11
|
+
const out = {};
|
|
12
|
+
for (const [k, v] of fd.entries()) {
|
|
13
|
+
if (typeof v !== 'string') {
|
|
14
|
+
if (!v.size && !v.name)
|
|
15
|
+
continue; // empty file input
|
|
16
|
+
return new UseBeckyError({ code: 'files_not_supported', message: "This form can't receive files.", hint: 'Upload files with baas.storage and send the file link in a text field instead.', status: 0 });
|
|
17
|
+
}
|
|
18
|
+
const prev = out[k];
|
|
19
|
+
out[k] = prev === undefined ? v : Array.isArray(prev) ? [...prev, v] : [String(prev), v];
|
|
20
|
+
}
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
/** The current page without query string or fragment, so the inbox shows where the message came from. */
|
|
24
|
+
function currentPage() {
|
|
25
|
+
try {
|
|
26
|
+
const loc = g.location;
|
|
27
|
+
if (loc && typeof loc.origin === 'string' && /^https?:/.test(loc.protocol))
|
|
28
|
+
return `${loc.origin}${loc.pathname}`;
|
|
29
|
+
}
|
|
30
|
+
catch { }
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
function path(formIdOrKey) {
|
|
34
|
+
return `/forms/v1/f/${encodeURIComponent(formIdOrKey.trim())}`;
|
|
35
|
+
}
|
|
36
|
+
export class FormsClient {
|
|
37
|
+
http;
|
|
38
|
+
consent;
|
|
39
|
+
/** `consent`: the visitor's consent state for a server-side tagging extension (generate_lead), see `analytics.consentRef()`. */
|
|
40
|
+
constructor(http, consent = () => Promise.resolve(undefined)) {
|
|
41
|
+
this.http = http;
|
|
42
|
+
this.consent = consent;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Send a submission to a form made in Dashboard → Forms.
|
|
46
|
+
*
|
|
47
|
+
* await baas.forms.submit('contact', { name: 'Ada', email: 'ada@example.com', message: 'Hi!' })
|
|
48
|
+
* await baas.forms.submit('contact', event.currentTarget) // a <form> element (React onSubmit)
|
|
49
|
+
*
|
|
50
|
+
* `formIdOrKey` is the form's key (e.g. "contact") or its id ("f_..."). Field names must match the
|
|
51
|
+
* form's fields; extra fields are kept too. Fields starting with "_" are reserved.
|
|
52
|
+
* With bot protection on: `await baas.forms.submit('contact', values, { captchaToken })`.
|
|
53
|
+
*/
|
|
54
|
+
async submit(formIdOrKey, data, options = {}) {
|
|
55
|
+
if (typeof formIdOrKey !== 'string' || !formIdOrKey.trim()) {
|
|
56
|
+
return { data: null, error: invalid('Pass the form key or id as the first argument, e.g. baas.forms.submit("contact", {...}).', 'Find both in Dashboard → Forms → your form.') };
|
|
57
|
+
}
|
|
58
|
+
let values;
|
|
59
|
+
if (isFormElement(data))
|
|
60
|
+
data = new g.FormData(data);
|
|
61
|
+
if (typeof g.FormData === 'function' && data instanceof g.FormData) {
|
|
62
|
+
const converted = fromFormData(data);
|
|
63
|
+
if (converted instanceof UseBeckyError)
|
|
64
|
+
return { data: null, error: converted };
|
|
65
|
+
values = converted;
|
|
66
|
+
}
|
|
67
|
+
else if (data && typeof data === 'object' && !Array.isArray(data)) {
|
|
68
|
+
values = data;
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
return { data: null, error: invalid('Pass the form values as an object, e.g. { name: "Ada", email: "ada@example.com" }.') };
|
|
72
|
+
}
|
|
73
|
+
const body = {};
|
|
74
|
+
for (const [k, v] of Object.entries(values))
|
|
75
|
+
if (v !== undefined)
|
|
76
|
+
body[k] = v;
|
|
77
|
+
const page = currentPage();
|
|
78
|
+
if (page && body._page === undefined)
|
|
79
|
+
body._page = page;
|
|
80
|
+
if (options.captchaToken)
|
|
81
|
+
body.captcha_token = options.captchaToken;
|
|
82
|
+
// The visitor's consent state, for a server-side tagging extension (generate_lead): hidden fields, as a plain
|
|
83
|
+
// HTML form would send them. Nothing when nobody answered (or the form sets them itself).
|
|
84
|
+
try {
|
|
85
|
+
const consent = await this.consent();
|
|
86
|
+
if (consent && body._consent === undefined) {
|
|
87
|
+
body._consent = consent.analytics ? 'granted' : 'denied';
|
|
88
|
+
if (consent.ga_client_id)
|
|
89
|
+
body._ga_client_id = consent.ga_client_id;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
catch { }
|
|
93
|
+
const res = await this.http.request(path(formIdOrKey), { method: 'POST', body, token: null });
|
|
94
|
+
if (res.error)
|
|
95
|
+
return { data: null, error: res.error };
|
|
96
|
+
return { data: { ok: res.data?.ok ?? true, message: res.data?.message ?? '' }, error: null };
|
|
97
|
+
}
|
|
98
|
+
/** The public definition of a form (name, fields, success message), e.g. to render it yourself. */
|
|
99
|
+
async get(formIdOrKey) {
|
|
100
|
+
if (typeof formIdOrKey !== 'string' || !formIdOrKey.trim()) {
|
|
101
|
+
return { data: null, error: invalid('Pass the form key or id, e.g. baas.forms.get("contact").') };
|
|
102
|
+
}
|
|
103
|
+
const res = await this.http.request(path(formIdOrKey), { token: null });
|
|
104
|
+
return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { HttpClient, QueryInput } from '../lib/http.ts';
|
|
2
|
+
import type { Result } from '../lib/types.ts';
|
|
3
|
+
/** Options for `invoke()`. */
|
|
4
|
+
export interface InvokeOptions {
|
|
5
|
+
/** What to send. Objects and arrays are sent as JSON; strings, Blobs, FormData, ArrayBuffers and streams as they are. */
|
|
6
|
+
body?: unknown;
|
|
7
|
+
/** HTTP method. Default POST. */
|
|
8
|
+
method?: string;
|
|
9
|
+
/** Extra request headers, e.g. { 'x-request-id': '...' }. */
|
|
10
|
+
headers?: Record<string, string>;
|
|
11
|
+
/** Query string parameters: { page: 2 } → ?page=2. */
|
|
12
|
+
query?: QueryInput;
|
|
13
|
+
/** More path after the function name: invoke('api', { path: '/orders/42' }) calls /functions/v1/api/orders/42. */
|
|
14
|
+
path?: string;
|
|
15
|
+
/**
|
|
16
|
+
* How to read the answer. `auto` (default): JSON when the function answers with JSON, otherwise text.
|
|
17
|
+
* `text`: always a string. `blob`: the raw bytes as a Blob (images, PDFs, files).
|
|
18
|
+
*/
|
|
19
|
+
responseType?: 'auto' | 'text' | 'blob';
|
|
20
|
+
/** Cancel the call. */
|
|
21
|
+
signal?: AbortSignal;
|
|
22
|
+
}
|
|
23
|
+
export declare const FUNCTION_NAME_RE: RegExp;
|
|
24
|
+
export declare class FunctionsClient {
|
|
25
|
+
private http;
|
|
26
|
+
constructor(http: HttpClient);
|
|
27
|
+
/**
|
|
28
|
+
* Run one of your functions and get its answer.
|
|
29
|
+
*
|
|
30
|
+
* const { data, error } = await baas.functions.invoke('hello', { body: { name: 'Ada' } })
|
|
31
|
+
* const { data } = await baas.functions.invoke('report', { method: 'GET', query: { month: '2026-11' } })
|
|
32
|
+
*
|
|
33
|
+
* `error` is set when the function couldn't run or answered with an error status (4xx/5xx): its
|
|
34
|
+
* `code` is e.g. `function_error`, `function_timeout`, `not_signed_in`, `function_not_found`.
|
|
35
|
+
*/
|
|
36
|
+
invoke<T = any>(name: string, options?: InvokeOptions): Promise<Result<T>>;
|
|
37
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Functions: call your own code running on usebecky (Dashboard → Functions, or `npx usebecky functions deploy`).
|
|
2
|
+
//
|
|
3
|
+
// const { data, error } = await baas.functions.invoke('send-welcome', { body: { userId } })
|
|
4
|
+
//
|
|
5
|
+
// In apps the call carries your publishable key and, when someone is signed in, their access token
|
|
6
|
+
// (so "signed-in users only" functions know who is calling: ctx.user). From `usebecky/server` it carries
|
|
7
|
+
// your secret key, so "servers only" functions work too. API: <api>/functions/v1/<name>[/<path>].
|
|
8
|
+
import { UseBeckyError } from "../lib/errors.js";
|
|
9
|
+
export const FUNCTION_NAME_RE = /^[a-z][a-z0-9-]{0,62}$/;
|
|
10
|
+
function invalid(message, hint) {
|
|
11
|
+
return new UseBeckyError({ code: 'invalid_input', message, hint, status: 0 });
|
|
12
|
+
}
|
|
13
|
+
export class FunctionsClient {
|
|
14
|
+
http;
|
|
15
|
+
constructor(http) {
|
|
16
|
+
this.http = http;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Run one of your functions and get its answer.
|
|
20
|
+
*
|
|
21
|
+
* const { data, error } = await baas.functions.invoke('hello', { body: { name: 'Ada' } })
|
|
22
|
+
* const { data } = await baas.functions.invoke('report', { method: 'GET', query: { month: '2026-11' } })
|
|
23
|
+
*
|
|
24
|
+
* `error` is set when the function couldn't run or answered with an error status (4xx/5xx): its
|
|
25
|
+
* `code` is e.g. `function_error`, `function_timeout`, `not_signed_in`, `function_not_found`.
|
|
26
|
+
*/
|
|
27
|
+
async invoke(name, options = {}) {
|
|
28
|
+
if (typeof name !== 'string' || !FUNCTION_NAME_RE.test(name.trim())) {
|
|
29
|
+
return {
|
|
30
|
+
data: null,
|
|
31
|
+
error: invalid(`"${String(name).slice(0, 64)}" is not a function name.`, 'Use the name from Dashboard → Functions: lowercase letters, numbers and dashes, like "send-welcome".'),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
let extra = '';
|
|
35
|
+
if (options.path !== undefined && options.path !== null && options.path !== '') {
|
|
36
|
+
if (typeof options.path !== 'string')
|
|
37
|
+
return { data: null, error: invalid('`path` must be a string like "/orders/42".') };
|
|
38
|
+
extra = options.path.startsWith('/') ? options.path : `/${options.path}`;
|
|
39
|
+
if (/[?#]/.test(extra))
|
|
40
|
+
return { data: null, error: invalid('Put query parameters in `query`, not in `path`.', 'Example: invoke("api", { path: "/orders", query: { page: 2 } })') };
|
|
41
|
+
}
|
|
42
|
+
const method = (options.method ?? 'POST').toUpperCase();
|
|
43
|
+
const res = await this.http.request(`/functions/v1/${name.trim()}${extra}`, {
|
|
44
|
+
method,
|
|
45
|
+
body: options.body,
|
|
46
|
+
headers: options.headers,
|
|
47
|
+
query: options.query,
|
|
48
|
+
signal: options.signal,
|
|
49
|
+
parse: 'blob',
|
|
50
|
+
});
|
|
51
|
+
if (res.error)
|
|
52
|
+
return { data: null, error: res.error };
|
|
53
|
+
const blob = res.data;
|
|
54
|
+
if (!blob)
|
|
55
|
+
return { data: null, error: null };
|
|
56
|
+
if (options.responseType === 'blob')
|
|
57
|
+
return { data: blob, error: null };
|
|
58
|
+
let text;
|
|
59
|
+
try {
|
|
60
|
+
text = await blob.text();
|
|
61
|
+
}
|
|
62
|
+
catch (err) {
|
|
63
|
+
return { data: null, error: new UseBeckyError({ code: 'invalid_response', message: `Could not read the function's answer: ${err.message}`, status: res.status }) };
|
|
64
|
+
}
|
|
65
|
+
const type = res.headers?.get('content-type') ?? '';
|
|
66
|
+
if (options.responseType !== 'text' && /\bjson\b/i.test(type) && text) {
|
|
67
|
+
try {
|
|
68
|
+
return { data: JSON.parse(text), error: null };
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
// Says JSON but isn't: hand over the text.
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { data: text, error: null };
|
|
75
|
+
}
|
|
76
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export { createClient, UseBeckyClient, type ClientOptions } from './client.ts';
|
|
2
|
+
export { HOSTED_API_URL } from './lib/hosted.ts';
|
|
3
|
+
export { UseBeckyError, isUseBeckyError } from './lib/errors.ts';
|
|
4
|
+
export { memoryStorage, type StorageAdapter } from './lib/storage-adapter.ts';
|
|
5
|
+
export { AuthClient, type AuthListener } from './auth/client.ts';
|
|
6
|
+
export { passkeysSupported, type PasskeyCreate, type PasskeyGet } from './auth/webauthn.ts';
|
|
7
|
+
export { QueryBuilder, TableQuery, type QueryResult, type CountOption } from './db/query.ts';
|
|
8
|
+
export { StorageClient, BucketApi, type UploadOptions, type UploadResult, type FileBody, type TransformOptions } from './storage/client.ts';
|
|
9
|
+
export { RealtimeClient, RealtimeChannel, type RealtimeOptions, type SubscribeOptions, type RealtimeStatus } from './realtime/client.ts';
|
|
10
|
+
export { PaymentsClient, OrdersClient, type PaymentSetup, type StripeConfig, type CheckoutCart, type CheckoutItem, type CheckoutResult, type CartQuote, type CartPaymentSetup, type CartShipping, type ShippingRateOption } from './payments/client.ts';
|
|
11
|
+
export { AnalyticsClient, type AnalyticsOptions, type ConsentRef, type VisitRef } from './analytics/client.ts';
|
|
12
|
+
export { FunctionsClient, type InvokeOptions } from './functions/client.ts';
|
|
13
|
+
export { FormsClient, type FormInput, type FormValue, type FormSubmitOptions, type FormSubmitResult, type PublicForm, type PublicFormField } from './forms/client.ts';
|
|
14
|
+
export { NewsletterClient, type NewsletterSubscribeOptions, type NewsletterSubscribeResult, type NewsletterSubscriber, type NewsletterSubscriberStatus } from './newsletter/client.ts';
|
|
15
|
+
export { PushClient, vapidKeyToBytes, type PushPlatform, type PushRegisterOptions, type PushDevice, type PushConfig, type WebPushOptions, type WebPushSubscriptionJSON, type PushServiceWorkerRegistration } from './push/client.ts';
|
|
16
|
+
export type { GenericSchema, GenericTable, GenericFunction, SelectResult } from './db/types.ts';
|
|
17
|
+
export type { Result, User, Session, Identity, Factor, AuthChangeEvent, AuthSettings, CaptchaInfo, OAuthProvider, Passkey, Product, Price, Subscription, SubscriptionSource, AccessSource, AccessInfo, Purchase, Order, OrderItem, OrderDownload, OrderList, OrderStatus, OrderFulfillment, OrderAddress, BillingInfo, PaymentsMode, Bucket, FileObject, ObjectInfo, Change, ChangeEvent, PresenceState, } from './lib/types.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// `usebecky`: the browser / app entry point. Server code: `usebecky/server`.
|
|
2
|
+
export { createClient, UseBeckyClient } from "./client.js";
|
|
3
|
+
export { HOSTED_API_URL } from "./lib/hosted.js";
|
|
4
|
+
export { UseBeckyError, isUseBeckyError } from "./lib/errors.js";
|
|
5
|
+
export { memoryStorage } from "./lib/storage-adapter.js";
|
|
6
|
+
export { AuthClient } from "./auth/client.js";
|
|
7
|
+
export { passkeysSupported } from "./auth/webauthn.js";
|
|
8
|
+
export { QueryBuilder, TableQuery } from "./db/query.js";
|
|
9
|
+
export { StorageClient, BucketApi } from "./storage/client.js";
|
|
10
|
+
export { RealtimeClient, RealtimeChannel } from "./realtime/client.js";
|
|
11
|
+
export { PaymentsClient, OrdersClient } from "./payments/client.js";
|
|
12
|
+
export { AnalyticsClient } from "./analytics/client.js";
|
|
13
|
+
export { FunctionsClient } from "./functions/client.js";
|
|
14
|
+
export { FormsClient } from "./forms/client.js";
|
|
15
|
+
export { NewsletterClient } from "./newsletter/client.js";
|
|
16
|
+
export { PushClient, vapidKeyToBytes } from "./push/client.js";
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** The Project URL, the publishable key (ub_pk_...) and the secret key (ub_sk_...). */
|
|
2
|
+
export declare const DASHBOARD_API_KEYS = "Dashboard \u2192 Settings \u2192 API keys";
|
|
3
|
+
/** The list of tables, with their access-rule badges. */
|
|
4
|
+
export declare const DASHBOARD_TABLES = "Dashboard \u2192 Database \u2192 Tables";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Where things live in the usebecky dashboard, for hints in SDK errors and CLI output. Keep every
|
|
2
|
+
// mention here so a renamed sidebar item is fixed in one place. (src/cli/framework.ts is copied into
|
|
3
|
+
// create-usebecky on its own, so it repeats DASHBOARD_API_KEYS; test/cli-dashboard-paths.test.ts keeps
|
|
4
|
+
// the two equal.)
|
|
5
|
+
/** The Project URL, the publishable key (ub_pk_...) and the secret key (ub_sk_...). */
|
|
6
|
+
export const DASHBOARD_API_KEYS = 'Dashboard → Settings → API keys';
|
|
7
|
+
/** The list of tables, with their access-rule badges. */
|
|
8
|
+
export const DASHBOARD_TABLES = 'Dashboard → Database → Tables';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Read any env var by name (server-side helper). */
|
|
2
|
+
export declare function readEnv(name: string): string | undefined;
|
|
3
|
+
export declare function envUrl(): string | undefined;
|
|
4
|
+
export declare function envPublishableKey(): string | undefined;
|
|
5
|
+
/** True when running in a web browser page (not Node, not a worker, not React Native). */
|
|
6
|
+
export declare function isBrowser(): boolean;
|
|
7
|
+
/** Project ref embedded in an API key (`ub_pk_<ref>_...`, or `yb_pk_` from before the rename to usebecky), or null. */
|
|
8
|
+
export declare function refFromKey(key: string): string | null;
|
|
9
|
+
export declare function keyType(key: string): 'publishable' | 'secret' | 'unknown';
|
package/dist/lib/env.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Environment lookup that works in Node, Deno/Bun, and in bundlers that inline
|
|
2
|
+
// `process.env.NEXT_PUBLIC_*` / `process.env.EXPO_PUBLIC_*` at build time.
|
|
3
|
+
// Each literal access is wrapped in try/catch because `process` may not exist (browsers).
|
|
4
|
+
function first(...getters) {
|
|
5
|
+
for (const get of getters) {
|
|
6
|
+
try {
|
|
7
|
+
const v = get();
|
|
8
|
+
if (typeof v === 'string' && v.trim() !== '')
|
|
9
|
+
return v.trim();
|
|
10
|
+
}
|
|
11
|
+
catch { }
|
|
12
|
+
}
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
function dynamic(name) {
|
|
16
|
+
const env = globalThis.process?.env;
|
|
17
|
+
if (env && typeof env[name] === 'string')
|
|
18
|
+
return env[name];
|
|
19
|
+
try {
|
|
20
|
+
const deno = globalThis.Deno;
|
|
21
|
+
if (deno?.env?.get)
|
|
22
|
+
return deno.env.get(name);
|
|
23
|
+
}
|
|
24
|
+
catch { }
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
/** Read any env var by name (server-side helper). */
|
|
28
|
+
export function readEnv(name) {
|
|
29
|
+
return first(() => dynamic(name));
|
|
30
|
+
}
|
|
31
|
+
export function envUrl() {
|
|
32
|
+
return first(
|
|
33
|
+
// Literal accesses so Next.js / Expo can inline them in browser bundles.
|
|
34
|
+
() => process.env.NEXT_PUBLIC_USEBECKY_URL, () => process.env.EXPO_PUBLIC_USEBECKY_URL, () => process.env.USEBECKY_URL, () => dynamic('USEBECKY_URL'), () => dynamic('NEXT_PUBLIC_USEBECKY_URL'), () => dynamic('EXPO_PUBLIC_USEBECKY_URL'), () => dynamic('VITE_USEBECKY_URL'));
|
|
35
|
+
}
|
|
36
|
+
export function envPublishableKey() {
|
|
37
|
+
return first(() => process.env.NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY, () => process.env.EXPO_PUBLIC_USEBECKY_PUBLISHABLE_KEY, () => process.env.USEBECKY_PUBLISHABLE_KEY, () => dynamic('USEBECKY_PUBLISHABLE_KEY'), () => dynamic('NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY'), () => dynamic('EXPO_PUBLIC_USEBECKY_PUBLISHABLE_KEY'), () => dynamic('VITE_USEBECKY_PUBLISHABLE_KEY'));
|
|
38
|
+
}
|
|
39
|
+
/** True when running in a web browser page (not Node, not a worker, not React Native). */
|
|
40
|
+
export function isBrowser() {
|
|
41
|
+
const g = globalThis;
|
|
42
|
+
return typeof g.window === 'object' && g.window !== null && typeof g.document === 'object' && g.document !== null;
|
|
43
|
+
}
|
|
44
|
+
/** Project ref embedded in an API key (`ub_pk_<ref>_...`, or `yb_pk_` from before the rename to usebecky), or null. */
|
|
45
|
+
export function refFromKey(key) {
|
|
46
|
+
const m = /^[uy]b_(?:pk|sk)_([a-z0-9]+)_/.exec(key);
|
|
47
|
+
return m ? m[1] : null;
|
|
48
|
+
}
|
|
49
|
+
export function keyType(key) {
|
|
50
|
+
if (/^[uy]b_pk_/.test(key))
|
|
51
|
+
return 'publishable';
|
|
52
|
+
if (/^[uy]b_sk_/.test(key))
|
|
53
|
+
return 'secret';
|
|
54
|
+
return 'unknown';
|
|
55
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export interface ErrorInit {
|
|
2
|
+
code: string;
|
|
3
|
+
message: string;
|
|
4
|
+
hint?: string;
|
|
5
|
+
status?: number;
|
|
6
|
+
}
|
|
7
|
+
export declare class UseBeckyError extends Error {
|
|
8
|
+
/** Stable, machine-readable error code, e.g. `invalid_credentials` or `network_error`. */
|
|
9
|
+
code: string;
|
|
10
|
+
/** HTTP status code. 0 means the request never reached the server. */
|
|
11
|
+
status: number;
|
|
12
|
+
/** What to do next, when we know. */
|
|
13
|
+
hint?: string;
|
|
14
|
+
constructor(init: ErrorInit);
|
|
15
|
+
toJSON(): ErrorInit;
|
|
16
|
+
toString(): string;
|
|
17
|
+
}
|
|
18
|
+
/** Build an error from any HTTP error response body. */
|
|
19
|
+
export declare function errorFromResponse(status: number, body: unknown, statusText?: string): UseBeckyError;
|
|
20
|
+
/** The request never reached the server (offline, DNS, CORS, wrong URL...). */
|
|
21
|
+
export declare function networkError(url: string, cause?: unknown): UseBeckyError;
|
|
22
|
+
export declare function isUseBeckyError(value: unknown): value is UseBeckyError;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Every SDK call returns `{ data, error }`. `error` is always a UseBeckyError with a stable
|
|
2
|
+
// snake_case `code`, a plain-English `message`, an optional `hint` and the HTTP `status`
|
|
3
|
+
// (0 when the request never reached the server).
|
|
4
|
+
import { DASHBOARD_API_KEYS } from "./dashboard-paths.js";
|
|
5
|
+
export class UseBeckyError extends Error {
|
|
6
|
+
/** Stable, machine-readable error code, e.g. `invalid_credentials` or `network_error`. */
|
|
7
|
+
code;
|
|
8
|
+
/** HTTP status code. 0 means the request never reached the server. */
|
|
9
|
+
status;
|
|
10
|
+
/** What to do next, when we know. */
|
|
11
|
+
hint;
|
|
12
|
+
constructor(init) {
|
|
13
|
+
super(init.message);
|
|
14
|
+
this.name = 'UseBeckyError';
|
|
15
|
+
this.code = init.code;
|
|
16
|
+
this.status = init.status ?? 0;
|
|
17
|
+
if (init.hint)
|
|
18
|
+
this.hint = init.hint;
|
|
19
|
+
}
|
|
20
|
+
toJSON() {
|
|
21
|
+
const out = { code: this.code, message: this.message, status: this.status };
|
|
22
|
+
if (this.hint)
|
|
23
|
+
out.hint = this.hint;
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
toString() {
|
|
27
|
+
return this.hint ? `${this.message} ${this.hint}` : this.message;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const STATUS_DEFAULTS = {
|
|
31
|
+
400: ['bad_request', 'The request was not valid.'],
|
|
32
|
+
401: ['unauthorized', 'You are not signed in, or your API key is not valid.', `Sign in again, and check the key in ${DASHBOARD_API_KEYS}.`],
|
|
33
|
+
403: ['forbidden', 'You do not have permission to do that.'],
|
|
34
|
+
404: ['not_found', 'That was not found.'],
|
|
35
|
+
406: ['not_single_row', 'Expected exactly one row.'],
|
|
36
|
+
409: ['conflict', 'That conflicts with existing data.'],
|
|
37
|
+
413: ['payload_too_large', 'That is too large to upload.'],
|
|
38
|
+
429: ['too_many_requests', 'Too many requests. Please wait a moment and try again.'],
|
|
39
|
+
502: ['bad_gateway', 'The usebecky API is temporarily unreachable. Please try again in a moment.'],
|
|
40
|
+
503: ['service_unavailable', 'The usebecky API is temporarily unavailable. Please try again in a moment.'],
|
|
41
|
+
};
|
|
42
|
+
/** Build an error from any HTTP error response body. */
|
|
43
|
+
export function errorFromResponse(status, body, statusText = '') {
|
|
44
|
+
const obj = body && typeof body === 'object' ? body : null;
|
|
45
|
+
const inner = obj && obj.error && typeof obj.error === 'object' ? obj.error : obj;
|
|
46
|
+
if (inner && typeof inner.message === 'string') {
|
|
47
|
+
return new UseBeckyError({
|
|
48
|
+
code: typeof inner.code === 'string' && inner.code ? inner.code : defaultCode(status),
|
|
49
|
+
message: inner.message,
|
|
50
|
+
hint: typeof inner.hint === 'string' ? inner.hint : undefined,
|
|
51
|
+
status,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
if (obj && typeof obj.error === 'string') {
|
|
55
|
+
return new UseBeckyError({ code: obj.error, message: obj.error_description ?? obj.message ?? obj.error, status });
|
|
56
|
+
}
|
|
57
|
+
const def = STATUS_DEFAULTS[status];
|
|
58
|
+
const text = typeof body === 'string' && body.length > 0 && body.length < 300 && !body.trimStart().startsWith('<') ? body : '';
|
|
59
|
+
return new UseBeckyError({
|
|
60
|
+
code: def?.[0] ?? defaultCode(status),
|
|
61
|
+
message: text || def?.[1] || (status >= 500 ? 'Something went wrong on the usebecky server. Please try again in a moment.' : `Request failed (${status}${statusText ? ' ' + statusText : ''}).`),
|
|
62
|
+
hint: def?.[2],
|
|
63
|
+
status,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
function defaultCode(status) {
|
|
67
|
+
return STATUS_DEFAULTS[status]?.[0] ?? (status >= 500 ? 'server_error' : `http_${status}`);
|
|
68
|
+
}
|
|
69
|
+
/** The request never reached the server (offline, DNS, CORS, wrong URL...). */
|
|
70
|
+
export function networkError(url, cause) {
|
|
71
|
+
let origin = url;
|
|
72
|
+
try {
|
|
73
|
+
origin = new URL(url).origin;
|
|
74
|
+
}
|
|
75
|
+
catch { }
|
|
76
|
+
const aborted = cause instanceof Error && (cause.name === 'AbortError' || cause.name === 'TimeoutError');
|
|
77
|
+
if (aborted) {
|
|
78
|
+
return new UseBeckyError({ code: cause.name === 'TimeoutError' ? 'timeout' : 'aborted', message: cause.name === 'TimeoutError' ? 'The request took too long and was stopped.' : 'The request was cancelled.', status: 0 });
|
|
79
|
+
}
|
|
80
|
+
const detail = cause instanceof Error && cause.message ? ` (${cause.cause?.code ?? cause.message})` : '';
|
|
81
|
+
return new UseBeckyError({
|
|
82
|
+
code: 'network_error',
|
|
83
|
+
message: `Could not reach the usebecky API at ${origin}${detail}.`,
|
|
84
|
+
hint: `Check your internet connection and that your usebecky URL is correct (${DASHBOARD_API_KEYS}).`,
|
|
85
|
+
status: 0,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
export function isUseBeckyError(value) {
|
|
89
|
+
return value instanceof UseBeckyError;
|
|
90
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// The one place the hosted API address lives. usebecky is a hosted service: every project runs in our
|
|
2
|
+
// cloud behind this address, so createClient("ub_pk_...") needs nothing else. The SDK, the CLI
|
|
3
|
+
// (`npx usebecky init`) and create-usebecky (copied by its scripts/sync-shared.mjs) all read it from here.
|
|
4
|
+
// An explicit URL (createClient(url, key), --api-url, USEBECKY_URL / USEBECKY_API_URL) still wins,
|
|
5
|
+
// which is how the usebecky team points everything at a local API while working on it.
|
|
6
|
+
/** The hosted usebecky API (placeholder until the final domain is set). */
|
|
7
|
+
export const HOSTED_API_URL = 'https://api.usebecky.com';
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { type UseBeckyError } from './errors.ts';
|
|
2
|
+
export declare const VERSION = "0.2.0";
|
|
3
|
+
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
4
|
+
export type QueryInput = Record<string, string | number | boolean | null | undefined> | Array<[string, string]>;
|
|
5
|
+
export interface RequestOptions {
|
|
6
|
+
method?: string;
|
|
7
|
+
query?: QueryInput;
|
|
8
|
+
headers?: Record<string, string>;
|
|
9
|
+
body?: unknown;
|
|
10
|
+
/** `undefined` → use the current user's token; `null`/`false` → send no user token; string → this token. */
|
|
11
|
+
token?: string | null | false;
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
/** How to read a successful response. Default: json (falls back to text). */
|
|
14
|
+
parse?: 'json' | 'blob' | 'text' | 'none';
|
|
15
|
+
}
|
|
16
|
+
export interface HttpResponse<T = any> {
|
|
17
|
+
data: T | null;
|
|
18
|
+
error: UseBeckyError | null;
|
|
19
|
+
status: number;
|
|
20
|
+
headers: Headers | null;
|
|
21
|
+
}
|
|
22
|
+
export interface HttpClientInit {
|
|
23
|
+
url: string;
|
|
24
|
+
key: string;
|
|
25
|
+
fetch?: FetchLike;
|
|
26
|
+
/** Returns the current user's access token (refreshing it first if needed). */
|
|
27
|
+
getToken?: () => Promise<string | null>;
|
|
28
|
+
/** Called when the server rejects `token` as expired/invalid; returns a fresh token to retry with. */
|
|
29
|
+
onTokenRejected?: (token: string) => Promise<string | null>;
|
|
30
|
+
headers?: Record<string, string>;
|
|
31
|
+
/**
|
|
32
|
+
* The language sent as `Accept-Language` on every request (for the emails usebecky sends), shared with
|
|
33
|
+
* every copy made by `withToken`. `value: null` → send none (browsers then send their own).
|
|
34
|
+
*/
|
|
35
|
+
locale?: {
|
|
36
|
+
value: string | null;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export declare function isRawBody(body: unknown): boolean;
|
|
40
|
+
export declare function buildUrl(base: string, path: string, query?: QueryInput): string;
|
|
41
|
+
export declare class HttpClient {
|
|
42
|
+
readonly url: string;
|
|
43
|
+
readonly key: string;
|
|
44
|
+
private fetchImpl;
|
|
45
|
+
private getToken;
|
|
46
|
+
private onTokenRejected?;
|
|
47
|
+
private extraHeaders;
|
|
48
|
+
private localeRef;
|
|
49
|
+
constructor(init: HttpClientInit);
|
|
50
|
+
/** The language sent as `Accept-Language`, or null for none. */
|
|
51
|
+
get locale(): string | null;
|
|
52
|
+
/** Change the `Accept-Language` language for every later request (null = send none). */
|
|
53
|
+
setLocale(locale: string | null): void;
|
|
54
|
+
/** Same client, but every request carries `token` as the user token. */
|
|
55
|
+
withToken(token: string | null): HttpClient;
|
|
56
|
+
authHeaders(token?: string | null | false): Promise<Record<string, string>>;
|
|
57
|
+
request<T = any>(path: string, opts?: RequestOptions): Promise<HttpResponse<T>>;
|
|
58
|
+
private send;
|
|
59
|
+
}
|