@biltme/backend 0.7.1 → 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
@@ -169,6 +169,36 @@ picked file passes a bucket's MIME allowlist. Pass `contentType` for such
169
169
  files: a React Native Blob has no type of its own, and without one the upload
170
170
  is labelled `application/octet-stream`.
171
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
+
172
202
  ## Web
173
203
 
174
204
  ```ts
@@ -195,6 +225,7 @@ const bilt = createClient(url, key, {
195
225
  arguments defaults its schema to the augmentable `Database` interface above instead of `any`.
196
226
  - `Database`, the empty interface a project augments to type its schema.
197
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).
198
229
  - Realtime is not available: `bilt.channel()` throws `REALTIME_NOT_SUPPORTED`. Refetch with `bilt.from(...)` on an interval or on screen focus instead.
199
230
  - `asyncStorage(impl)` factory wrapping `@react-native-async-storage/async-storage` to the supabase-js storage shape.
200
231
  - `webStorage()` and `memoryStorage()` for completeness.
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,21 +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 four 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
88
  * a missing or malformed URL or key names Bilt Cloud rather than Supabase, on
88
89
  * React Native a Blob upload is sent as bytes so `contentType` reaches the
89
- * bucket's MIME allowlist (see {@link sendNativeBlobsAsBytes}), and opening a
90
- * realtime channel throws because Bilt Cloud has no realtime (see {@link blockRealtime}).
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}).
91
93
  *
92
94
  * The second member of the intersection is supabase-js's own signature. An
93
95
  * intersection of function types is an overload set, so a bare call takes the
94
96
  * first member and any call with explicit type arguments falls through to the
95
97
  * second. Restating the parameter list here instead would have to track
96
- * 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.
97
100
  */
98
- 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;
99
108
  export { REALTIME_NOT_SUPPORTED } from './realtime';
109
+ export { NotificationsError } from './notifications';
110
+ export type { Notifications, NotificationMessage, NotificationOutcome, NotificationSendResult } from './notifications';
100
111
  export { webStorage, memoryStorage, asyncStorage } from './storage';
101
112
  export type { StorageAdapter } from './storage';
102
113
  export { FunctionsHttpError, FunctionsRelayError, FunctionsFetchError, FunctionRegion } from '@supabase/supabase-js';
package/dist/index.js CHANGED
@@ -11796,6 +11796,68 @@ 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
+
11799
11861
  // src/realtime.ts
11800
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.";
11801
11863
  function notSupported() {
@@ -11927,7 +11989,7 @@ var createClient2 = (url, key, options) => {
11927
11989
  const client = createClient(url, key, options);
11928
11990
  sendNativeBlobsAsBytes(client);
11929
11991
  blockRealtime(client);
11930
- return client;
11992
+ return Object.assign(client, { notifications: notifications(client, url, key, options) });
11931
11993
  };
11932
11994
  var export_FunctionsRelayError = import_functions_js.FunctionsRelayError;
11933
11995
  var export_FunctionsHttpError = import_functions_js.FunctionsHttpError;
@@ -11941,6 +12003,7 @@ export {
11941
12003
  asyncStorage,
11942
12004
  StorageApiError,
11943
12005
  REALTIME_NOT_SUPPORTED,
12006
+ NotificationsError,
11944
12007
  export_FunctionsRelayError as FunctionsRelayError,
11945
12008
  export_FunctionsHttpError as FunctionsHttpError,
11946
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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@biltme/backend",
3
- "version": "0.7.1",
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",