@biltme/backend 0.8.0 → 0.9.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
@@ -183,11 +183,15 @@ const { data, error } = await bilt.notifications.send({
183
183
  // data.outcome: 'accepted' | 'no_devices' | 'notifications_off' | 'platform_off'
184
184
  ```
185
185
 
186
- Sends to the recipient's Android devices as the signed-in user, authenticated
186
+ A `to` typed as `string` could hold `'all'`, so its answer is typed as either
187
+ shape: `data.outcome` is set for one user and `data.counts` for all.
188
+
189
+ Sends to the recipient's devices as the signed-in user, authenticated
187
190
  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
+ else `accessToken`, else the session, else the client's key. The client's other
192
+ `global.headers` go along. Bilt Cloud accepts the key only from an edge
193
+ function, so an app without a session gets a 403 `auth_role_denied`. `accepted` means
194
+ Apple or Google took the notification, not that it arrived. `url` must be an in-app path
191
195
  starting with a single `/`, `data` may not have its own `url` key, and the two
192
196
  together stay under 2 KB. A user may send 10 a minute
193
197
  and 200 a day, and a recipient receives at most 30 a minute; over that, `error`
@@ -195,6 +199,27 @@ is a `NotificationsError` with `code` `rate_limited` and `status` 429. The
195
199
  method never throws. The app registers devices and handles taps through
196
200
  `@biltme/notifications-expo`.
197
201
 
202
+ ### From an edge function
203
+
204
+ ```ts
205
+ import { createClient } from 'npm:@biltme/backend'
206
+
207
+ const bilt = createClient(Deno.env.get('EXPO_PUBLIC_BILT_URL')!, Deno.env.get('BILT_SERVICE_KEY')!)
208
+ await bilt.notifications.send({ to: userId, title: 'Order shipped', body: 'It arrives Friday' })
209
+ const { data } = await bilt.notifications.send({ to: 'all', title: 'We are back', body: 'Service is restored' })
210
+ // data.counts: { accepted, notifications_off, platform_off, error, rate_limited }, in devices
211
+ ```
212
+
213
+ A function sends with its `BILT_SERVICE_KEY` and needs no session. Only a
214
+ function may send `to: 'all'`, which reaches every registered device of the app
215
+ and answers how many devices had each outcome instead of one outcome. A function
216
+ has no per-user limit, but each recipient still receives at most 30 a minute: a
217
+ send to `'all'` skips a recipient over that and counts its devices as
218
+ `rate_limited`, and a device Apple or Google failed for counts as `error` rather
219
+ than failing the send. A send to `'all'` has the request's 10 seconds, which
220
+ reaches roughly 800 devices per platform; devices past the deadline count as
221
+ `error`.
222
+
198
223
  `bilt.notifications` is typed on the client a bare `createClient(url, key, options)`
199
224
  returns. It exists at runtime with explicit type arguments too, but isn't in that
200
225
  client's type.
@@ -225,7 +250,7 @@ const bilt = createClient(url, key, {
225
250
  arguments defaults its schema to the augmentable `Database` interface above instead of `any`.
226
251
  - `Database`, the empty interface a project augments to type its schema.
227
252
  - 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).
253
+ - `bilt.notifications.send` sends a push notification to one end user, or from an edge function to every device (see Push notifications).
229
254
  - Realtime is not available: `bilt.channel()` throws `REALTIME_NOT_SUPPORTED`. Refetch with `bilt.from(...)` on an interval or on screen focus instead.
230
255
  - `asyncStorage(impl)` factory wrapping `@react-native-async-storage/async-storage` to the supabase-js storage shape.
231
256
  - `webStorage()` and `memoryStorage()` for completeness.
package/dist/index.d.ts CHANGED
@@ -107,7 +107,7 @@ export type BiltClient = ReturnType<BareCall> & {
107
107
  type BareCreateClient = (...args: Parameters<BareCall>) => BiltClient;
108
108
  export { REALTIME_NOT_SUPPORTED } from './realtime';
109
109
  export { NotificationsError } from './notifications';
110
- export type { Notifications, NotificationMessage, NotificationOutcome, NotificationSendResult } from './notifications';
110
+ export type { Notifications, NotificationMessage, NotificationOutcome, NotificationSendResult, NotificationCounts, NotificationSendAllResult, } from './notifications';
111
111
  export { webStorage, memoryStorage, asyncStorage } from './storage';
112
112
  export type { StorageAdapter } from './storage';
113
113
  export { FunctionsHttpError, FunctionsRelayError, FunctionsFetchError, FunctionRegion } from '@supabase/supabase-js';
package/dist/index.js CHANGED
@@ -11818,44 +11818,40 @@ function notifications(client, url, key, options = {}) {
11818
11818
  throw error;
11819
11819
  return data.session?.access_token ?? null;
11820
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;
11821
+ async function send(message) {
11822
+ const headers = new Headers(options.global?.headers);
11823
+ if (!headers.has("Authorization")) {
11824
+ let token;
11846
11825
  try {
11847
- res = await fetchImpl(endpoint, { method: "POST", headers, body: JSON.stringify(message) });
11826
+ token = await userToken();
11848
11827
  } 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 };
11828
+ return {
11829
+ data: null,
11830
+ error: new NotificationsError(`Couldn't read the session: ${String(err)}`, 0, "session_unavailable")
11831
+ };
11854
11832
  }
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") };
11833
+ headers.set("Authorization", `Bearer ${token ?? key}`);
11857
11834
  }
11858
- };
11835
+ if (!headers.has("apikey"))
11836
+ headers.set("apikey", key);
11837
+ headers.set("Content-Type", "application/json");
11838
+ let res;
11839
+ try {
11840
+ res = await fetchImpl(endpoint, { method: "POST", headers, body: JSON.stringify(message) });
11841
+ } catch (err) {
11842
+ return { data: null, error: new NotificationsError(`Bilt Cloud didn't answer: ${String(err)}`, 0, "network") };
11843
+ }
11844
+ const body = await res.json().catch(() => null);
11845
+ if (res.ok && body?.outcome) {
11846
+ return { data: { outcome: body.outcome }, error: null };
11847
+ }
11848
+ if (res.ok && body?.counts) {
11849
+ return { data: { counts: body.counts }, error: null };
11850
+ }
11851
+ const detail = body?.error?.message ?? `Bilt Cloud answered ${res.status}`;
11852
+ return { data: null, error: new NotificationsError(detail, res.status, body?.error?.code ?? "unknown") };
11853
+ }
11854
+ return { send };
11859
11855
  }
11860
11856
 
11861
11857
  // src/realtime.ts
@@ -1,7 +1,7 @@
1
1
  import type { SupabaseClient } from '@supabase/supabase-js';
2
- /** The push notification {@link Notifications.send} delivers to one end user. */
2
+ /** The push notification {@link Notifications.send} delivers to one end user, or from an edge function to all. */
3
3
  export type NotificationMessage = {
4
- /** The recipient's user id. */
4
+ /** The recipient's user id, or `'all'` for every registered device of the app, which only an edge function may send. */
5
5
  to: string;
6
6
  /** A later send with the same id replaces the earlier notification on the device. */
7
7
  id?: string;
@@ -26,6 +26,24 @@ export declare class NotificationsError extends Error {
26
26
  export type NotificationSendResult = {
27
27
  data: {
28
28
  outcome: NotificationOutcome;
29
+ counts?: undefined;
30
+ };
31
+ error: null;
32
+ } | {
33
+ data: null;
34
+ error: NotificationsError;
35
+ };
36
+ export type NotificationCounts = {
37
+ accepted: number;
38
+ notifications_off: number;
39
+ platform_off: number;
40
+ error: number;
41
+ rate_limited: number;
42
+ };
43
+ export type NotificationSendAllResult = {
44
+ data: {
45
+ counts: NotificationCounts;
46
+ outcome?: undefined;
29
47
  };
30
48
  error: null;
31
49
  } | {
@@ -33,11 +51,21 @@ export type NotificationSendResult = {
33
51
  error: NotificationsError;
34
52
  };
35
53
  export type Notifications = {
54
+ /**
55
+ * Sends a push notification to every registered device of the app and
56
+ * returns how many devices had each outcome. Only an edge function may send it.
57
+ */
58
+ send(message: NotificationMessage & {
59
+ to: 'all';
60
+ }): Promise<NotificationSendAllResult>;
36
61
  /**
37
62
  * Sends a push notification to one end user's devices, as the signed-in user.
38
- * Without a session bilt-cloud refuses it.
63
+ * Without a session it sends with the client's key, which bilt-cloud accepts
64
+ * only from an edge function's `BILT_SERVICE_KEY`. A `to` typed as `string`
65
+ * may hold `'all'`, so the answer is either shape: read `data.outcome` for
66
+ * one user and `data.counts` for all.
39
67
  */
40
- send(message: NotificationMessage): Promise<NotificationSendResult>;
68
+ send(message: NotificationMessage): Promise<NotificationSendResult | NotificationSendAllResult>;
41
69
  };
42
70
  /** The supabase-js options `send` honours, so it authenticates the way the client's own calls do. */
43
71
  export type NotificationsOptions = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@biltme/backend",
3
- "version": "0.8.0",
3
+ "version": "0.9.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",