@biltme/backend 0.7.0 → 0.8.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 CHANGED
@@ -163,6 +163,42 @@ Bucket admin (`createBucket`, `updateBucket`, `deleteBucket`, `emptyBucket`,
163
163
  policies on `storage.objects` — author them with the `bilt_storage_apply`
164
164
  agent tool or the SQL editor.
165
165
 
166
+ On React Native, a `Blob` passed to `upload`, `update` or `uploadToSignedUrl`
167
+ is sent as bytes labelled with `contentType`, so `fetch(uri).blob()` from a
168
+ picked file passes a bucket's MIME allowlist. Pass `contentType` for such
169
+ files: a React Native Blob has no type of its own, and without one the upload
170
+ is labelled `application/octet-stream`.
171
+
172
+ ## Push notifications
173
+
174
+ ```ts
175
+ const { data, error } = await bilt.notifications.send({
176
+ to: otherUser.id, // the recipient's user id
177
+ id: `chat-${chat.id}`, // optional: a later send with the same id replaces this one
178
+ title: 'Ana',
179
+ body: 'See you at 8',
180
+ data: { chatId: chat.id }, // optional, passed to the app on open
181
+ url: `/chat/${chat.id}`, // optional in-app path a tap opens
182
+ })
183
+ // data.outcome: 'accepted' | 'no_devices' | 'notifications_off' | 'platform_off'
184
+ ```
185
+
186
+ Sends to the recipient's Android devices as the signed-in user, authenticated
187
+ the way the client's other calls are: a `global.headers` Authorization header,
188
+ else `accessToken`, else the session. The client's other `global.headers` go
189
+ along. Without any of those nothing is sent and `error.code` is `not_signed_in`. `accepted` means
190
+ Google took the notification, not that it arrived. `url` must be an in-app path
191
+ starting with a single `/`, `data` may not have its own `url` key, and the two
192
+ together stay under 2 KB. A user may send 10 a minute
193
+ and 200 a day, and a recipient receives at most 30 a minute; over that, `error`
194
+ is a `NotificationsError` with `code` `rate_limited` and `status` 429. The
195
+ method never throws. The app registers devices and handles taps through
196
+ `@biltme/notifications-expo`.
197
+
198
+ `bilt.notifications` is typed on the client a bare `createClient(url, key, options)`
199
+ returns. It exists at runtime with explicit type arguments too, but isn't in that
200
+ client's type.
201
+
166
202
  ## Web
167
203
 
168
204
  ```ts
@@ -188,6 +224,9 @@ const bilt = createClient(url, key, {
188
224
  - `createClient` *is* supabase-js's `createClient`, re-typed so that a call with no type
189
225
  arguments defaults its schema to the augmentable `Database` interface above instead of `any`.
190
226
  - `Database`, the empty interface a project augments to type its schema.
227
+ - On React Native, storage uploads send a `Blob` as bytes so `contentType` reaches the bucket (see Storage).
228
+ - `bilt.notifications.send` sends a push notification to one end user (see Push notifications).
229
+ - Realtime is not available: `bilt.channel()` throws `REALTIME_NOT_SUPPORTED`. Refetch with `bilt.from(...)` on an interval or on screen focus instead.
191
230
  - `asyncStorage(impl)` factory wrapping `@react-native-async-storage/async-storage` to the supabase-js storage shape.
192
231
  - `webStorage()` and `memoryStorage()` for completeness.
193
232
  - `FunctionsHttpError`, `FunctionsRelayError`, `FunctionsFetchError`, `FunctionRegion` re-exports for clean `catch` and option typing.
@@ -196,6 +235,6 @@ const bilt = createClient(url, key, {
196
235
 
197
236
  ## Docs
198
237
 
199
- For everything else (auth flows, RLS, OAuth, realtime, functions reference),
238
+ For everything else (auth flows, RLS, OAuth, functions reference),
200
239
  use [Supabase's docs](https://supabase.com/docs/reference/javascript/introduction).
201
240
  The bilt backend speaks the same wire protocol.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createClient as createSupabaseClient } from '@supabase/supabase-js';
2
+ import { type Notifications } from './notifications';
2
3
  /**
3
4
  * Schema of the project's database, in postgrest-js's `Database` shape.
4
5
  *
@@ -82,17 +83,31 @@ export type TablesUpdate<Name extends keyof PublicTables> = PublicTables[Name] e
82
83
  Update: infer U;
83
84
  } ? U : never;
84
85
  /**
85
- * Creates a Bilt client. supabase-js's `createClient` with two changes: called
86
+ * Creates a Bilt client. supabase-js's `createClient` with five changes: called
86
87
  * with no type arguments, the schema is {@link BiltDatabase} instead of `any`,
87
- * and a missing or malformed URL or key names Bilt Cloud rather than Supabase.
88
+ * a missing or malformed URL or key names Bilt Cloud rather than Supabase, on
89
+ * React Native a Blob upload is sent as bytes so `contentType` reaches the
90
+ * bucket's MIME allowlist (see {@link sendNativeBlobsAsBytes}), opening a
91
+ * realtime channel throws because Bilt Cloud has no realtime (see {@link blockRealtime}),
92
+ * and the client has `notifications` (see {@link Notifications}).
88
93
  *
89
94
  * The second member of the intersection is supabase-js's own signature. An
90
95
  * intersection of function types is an overload set, so a bare call takes the
91
96
  * first member and any call with explicit type arguments falls through to the
92
97
  * second. Restating the parameter list here instead would have to track
93
- * supabase-js's defaults by hand across a caret range.
98
+ * supabase-js's defaults by hand across a caret range. For the same reason only
99
+ * the bare call's type carries `notifications`; it is there at runtime either way.
94
100
  */
95
- export declare const createClient: typeof createSupabaseClient<BiltDatabase> & typeof createSupabaseClient;
101
+ export declare const createClient: BareCreateClient & typeof createSupabaseClient;
102
+ type BareCall = typeof createSupabaseClient<BiltDatabase>;
103
+ /** What a bare `createClient(url, key, options?)` returns: supabase-js's client plus Bilt's additions. */
104
+ export type BiltClient = ReturnType<BareCall> & {
105
+ notifications: Notifications;
106
+ };
107
+ type BareCreateClient = (...args: Parameters<BareCall>) => BiltClient;
108
+ export { REALTIME_NOT_SUPPORTED } from './realtime';
109
+ export { NotificationsError } from './notifications';
110
+ export type { Notifications, NotificationMessage, NotificationOutcome, NotificationSendResult } from './notifications';
96
111
  export { webStorage, memoryStorage, asyncStorage } from './storage';
97
112
  export type { StorageAdapter } from './storage';
98
113
  export { FunctionsHttpError, FunctionsRelayError, FunctionsFetchError, FunctionRegion } from '@supabase/supabase-js';
package/dist/index.js CHANGED
@@ -11796,6 +11796,113 @@ function shouldShowDeprecationWarning() {
11796
11796
  if (shouldShowDeprecationWarning())
11797
11797
  console.warn("⚠️ Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");
11798
11798
 
11799
+ // src/notifications.ts
11800
+ class NotificationsError extends Error {
11801
+ status;
11802
+ code;
11803
+ constructor(message, status, code) {
11804
+ super(message);
11805
+ this.name = "NotificationsError";
11806
+ this.status = status;
11807
+ this.code = code;
11808
+ }
11809
+ }
11810
+ function notifications(client, url, key, options = {}) {
11811
+ const endpoint = `${url.trim().replace(/\/+$/, "")}/notifications/v1/send`;
11812
+ const fetchImpl = options.global?.fetch ?? fetch;
11813
+ const userToken = async () => {
11814
+ if (options.accessToken)
11815
+ return options.accessToken();
11816
+ const { data, error } = await client.auth.getSession();
11817
+ if (error)
11818
+ throw error;
11819
+ return data.session?.access_token ?? null;
11820
+ };
11821
+ return {
11822
+ async send(message) {
11823
+ const headers = new Headers(options.global?.headers);
11824
+ if (!headers.has("Authorization")) {
11825
+ let token;
11826
+ try {
11827
+ token = await userToken();
11828
+ } catch (err) {
11829
+ return {
11830
+ data: null,
11831
+ error: new NotificationsError(`Couldn't read the session: ${String(err)}`, 0, "session_unavailable")
11832
+ };
11833
+ }
11834
+ if (!token) {
11835
+ return {
11836
+ data: null,
11837
+ error: new NotificationsError("Sending a notification needs a signed-in user.", 0, "not_signed_in")
11838
+ };
11839
+ }
11840
+ headers.set("Authorization", `Bearer ${token}`);
11841
+ }
11842
+ if (!headers.has("apikey"))
11843
+ headers.set("apikey", key);
11844
+ headers.set("Content-Type", "application/json");
11845
+ let res;
11846
+ try {
11847
+ res = await fetchImpl(endpoint, { method: "POST", headers, body: JSON.stringify(message) });
11848
+ } catch (err) {
11849
+ return { data: null, error: new NotificationsError(`Bilt Cloud didn't answer: ${String(err)}`, 0, "network") };
11850
+ }
11851
+ const body = await res.json().catch(() => null);
11852
+ if (res.ok && body?.outcome) {
11853
+ return { data: { outcome: body.outcome }, error: null };
11854
+ }
11855
+ const detail = body?.error?.message ?? `Bilt Cloud answered ${res.status}`;
11856
+ return { data: null, error: new NotificationsError(detail, res.status, body?.error?.code ?? "unknown") };
11857
+ }
11858
+ };
11859
+ }
11860
+
11861
+ // src/realtime.ts
11862
+ var REALTIME_NOT_SUPPORTED = "Realtime is not supported by Bilt Cloud yet. Refetch with bilt.from(...) on an interval or when the screen regains focus instead.";
11863
+ function notSupported() {
11864
+ throw new Error(REALTIME_NOT_SUPPORTED);
11865
+ }
11866
+ function blockRealtime(client) {
11867
+ client.channel = notSupported;
11868
+ client.realtime.channel = notSupported;
11869
+ client.realtime.connect = notSupported;
11870
+ }
11871
+
11872
+ // src/uploads.ts
11873
+ function isReactNative() {
11874
+ return typeof navigator !== "undefined" && navigator.product === "ReactNative";
11875
+ }
11876
+ function readBytes(blob) {
11877
+ if (typeof FileReader === "undefined")
11878
+ return blob.arrayBuffer();
11879
+ return new Promise((resolve, reject) => {
11880
+ const reader = new FileReader;
11881
+ reader.onload = () => resolve(reader.result);
11882
+ reader.onerror = () => reject(reader.error);
11883
+ reader.readAsArrayBuffer(blob);
11884
+ });
11885
+ }
11886
+ async function asBytes(body, options) {
11887
+ if (!isReactNative() || typeof Blob === "undefined" || !(body instanceof Blob))
11888
+ return [body, options];
11889
+ const contentType = options?.contentType ?? (body.type || "application/octet-stream");
11890
+ return [await readBytes(body), { ...options, contentType }];
11891
+ }
11892
+ function sendNativeBlobsAsBytes(client) {
11893
+ const storage = client.storage;
11894
+ const from = storage.from.bind(storage);
11895
+ storage.from = (id) => {
11896
+ const api = from(id);
11897
+ const upload = api.upload.bind(api);
11898
+ const update = api.update.bind(api);
11899
+ const uploadToSignedUrl = api.uploadToSignedUrl.bind(api);
11900
+ api.upload = async (path, body, options) => upload(path, ...await asBytes(body, options));
11901
+ api.update = async (path, body, options) => update(path, ...await asBytes(body, options));
11902
+ api.uploadToSignedUrl = async (path, token, body, options) => uploadToSignedUrl(path, token, ...await asBytes(body, options));
11903
+ return api;
11904
+ };
11905
+ }
11799
11906
  // src/storage/memory.ts
11800
11907
  function memoryStorage() {
11801
11908
  const store = new Map;
@@ -11879,7 +11986,10 @@ function assertCredentials(url, key) {
11879
11986
  }
11880
11987
  var createClient2 = (url, key, options) => {
11881
11988
  assertCredentials(url, key);
11882
- return createClient(url, key, options);
11989
+ const client = createClient(url, key, options);
11990
+ sendNativeBlobsAsBytes(client);
11991
+ blockRealtime(client);
11992
+ return Object.assign(client, { notifications: notifications(client, url, key, options) });
11883
11993
  };
11884
11994
  var export_FunctionsRelayError = import_functions_js.FunctionsRelayError;
11885
11995
  var export_FunctionsHttpError = import_functions_js.FunctionsHttpError;
@@ -11892,6 +12002,8 @@ export {
11892
12002
  createClient2 as createClient,
11893
12003
  asyncStorage,
11894
12004
  StorageApiError,
12005
+ REALTIME_NOT_SUPPORTED,
12006
+ NotificationsError,
11895
12007
  export_FunctionsRelayError as FunctionsRelayError,
11896
12008
  export_FunctionsHttpError as FunctionsHttpError,
11897
12009
  export_FunctionsFetchError as FunctionsFetchError,
@@ -0,0 +1,50 @@
1
+ import type { SupabaseClient } from '@supabase/supabase-js';
2
+ /** The push notification {@link Notifications.send} delivers to one end user. */
3
+ export type NotificationMessage = {
4
+ /** The recipient's user id. */
5
+ to: string;
6
+ /** A later send with the same id replaces the earlier notification on the device. */
7
+ id?: string;
8
+ title: string;
9
+ body: string;
10
+ /** Passed to the app as is when the notification is opened. With `url`, at most 2 KB of JSON. */
11
+ data?: Record<string, unknown>;
12
+ /** An in-app path such as `/chat/123`, opened on tap. */
13
+ url?: string;
14
+ };
15
+ /**
16
+ * What happened for the recipient. `accepted` means Google or Apple took the
17
+ * notification, not that it arrived.
18
+ */
19
+ export type NotificationOutcome = 'accepted' | 'no_devices' | 'notifications_off' | 'platform_off';
20
+ /** A send bilt-cloud refused or never answered, with its error code, such as `rate_limited`. */
21
+ export declare class NotificationsError extends Error {
22
+ readonly status: number;
23
+ readonly code: string;
24
+ constructor(message: string, status: number, code: string);
25
+ }
26
+ export type NotificationSendResult = {
27
+ data: {
28
+ outcome: NotificationOutcome;
29
+ };
30
+ error: null;
31
+ } | {
32
+ data: null;
33
+ error: NotificationsError;
34
+ };
35
+ export type Notifications = {
36
+ /**
37
+ * Sends a push notification to one end user's devices, as the signed-in user.
38
+ * Without a session bilt-cloud refuses it.
39
+ */
40
+ send(message: NotificationMessage): Promise<NotificationSendResult>;
41
+ };
42
+ /** The supabase-js options `send` honours, so it authenticates the way the client's own calls do. */
43
+ export type NotificationsOptions = {
44
+ global?: {
45
+ fetch?: typeof fetch;
46
+ headers?: Record<string, string>;
47
+ };
48
+ accessToken?: () => Promise<string | null>;
49
+ };
50
+ export declare function notifications(client: SupabaseClient<any, any, any>, url: string, key: string, options?: NotificationsOptions): Notifications;
@@ -0,0 +1,11 @@
1
+ import type { SupabaseClient } from '@supabase/supabase-js';
2
+ export declare const REALTIME_NOT_SUPPORTED = "Realtime is not supported by Bilt Cloud yet. Refetch with bilt.from(...) on an interval or when the screen regains focus instead.";
3
+ /**
4
+ * Makes every way of opening a realtime socket throw {@link REALTIME_NOT_SUPPORTED}.
5
+ *
6
+ * bilt-cloud has no realtime endpoint, so a channel would retry its socket against
7
+ * a 404 for as long as the app runs. `setAuth`, `getChannels`, `removeChannel` and
8
+ * `removeAllChannels` keep working: supabase-js calls `setAuth` on every auth
9
+ * change, and cleanup code must not throw.
10
+ */
11
+ export declare function blockRealtime(client: SupabaseClient<any, any, any>): void;
@@ -0,0 +1,3 @@
1
+ import type { SupabaseClient } from '@supabase/supabase-js';
2
+ /** Makes `upload`, `update` and `uploadToSignedUrl` send React Native Blobs as bytes typed by `contentType`. */
3
+ export declare function sendNativeBlobsAsBytes(client: SupabaseClient<any, any, any>): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@biltme/backend",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Bilt backend SDK — thin shim over @supabase/supabase-js for bilt-cloud projects",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",