@biltme/backend 0.8.0 → 0.10.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
@@ -179,22 +179,53 @@ const { data, error } = await bilt.notifications.send({
179
179
  body: 'See you at 8',
180
180
  data: { chatId: chat.id }, // optional, passed to the app on open
181
181
  url: `/chat/${chat.id}`, // optional in-app path a tap opens
182
+ category: 'New messages', // optional: a kind of notification the user can turn off
182
183
  })
183
- // data.outcome: 'accepted' | 'no_devices' | 'notifications_off' | 'platform_off'
184
+ // data.outcome: 'accepted' | 'no_devices' | 'notifications_off' | 'platform_off' | 'opted_out' | 'suspended'
184
185
  ```
185
186
 
186
- Sends to the recipient's Android devices as the signed-in user, authenticated
187
+ A `to` typed as `string` could hold `'all'`, so its answer is typed as either
188
+ shape: `data.outcome` is set for one user and `data.counts` for all.
189
+
190
+ Sends to the recipient's devices as the signed-in user, authenticated
187
191
  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
192
+ else `accessToken`, else the session, else the client's key. The client's other
193
+ `global.headers` go along. Bilt Cloud accepts the key only from an edge
194
+ function, so an app without a session gets a 403 `auth_role_denied`. `accepted` means
195
+ Apple or Google took the notification, not that it arrived. `suspended` means Bilt has
196
+ stopped push for this app: nothing was sent, and the owner should contact Bilt support. `url` must be an in-app path
191
197
  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
198
+ together stay under 2 KB. `category`, at most 64 bytes, names a kind of
199
+ notification such as new messages or daily reminders. A recipient who turned it
200
+ off with `@biltme/notifications-expo`'s `setCategoryEnabled` gets `opted_out`:
201
+ nothing is sent, and the send counts against no limit. On Android the category is
202
+ also the notification channel, shown by this name in system settings. A user may send 10 a minute
193
203
  and 200 a day, and a recipient receives at most 30 a minute; over that, `error`
194
204
  is a `NotificationsError` with `code` `rate_limited` and `status` 429. The
195
205
  method never throws. The app registers devices and handles taps through
196
206
  `@biltme/notifications-expo`.
197
207
 
208
+ ### From an edge function
209
+
210
+ ```ts
211
+ import { createClient } from 'npm:@biltme/backend'
212
+
213
+ const bilt = createClient(Deno.env.get('EXPO_PUBLIC_BILT_URL')!, Deno.env.get('BILT_SERVICE_KEY')!)
214
+ await bilt.notifications.send({ to: userId, title: 'Order shipped', body: 'It arrives Friday' })
215
+ const { data } = await bilt.notifications.send({ to: 'all', title: 'We are back', body: 'Service is restored' })
216
+ // data.counts: { accepted, notifications_off, platform_off, error, rate_limited, opted_out, suspended }, in devices
217
+ ```
218
+
219
+ A function sends with its `BILT_SERVICE_KEY` and needs no session. Only a
220
+ function may send `to: 'all'`, which reaches every registered device of the app
221
+ and answers how many devices had each outcome instead of one outcome. A function
222
+ has no per-user limit, but each recipient still receives at most 30 a minute: a
223
+ send to `'all'` skips a recipient over that and counts its devices as
224
+ `rate_limited`, and a device Apple or Google failed for counts as `error` rather
225
+ than failing the send. A send to `'all'` has the request's 10 seconds, which
226
+ reaches roughly 800 devices per platform; devices past the deadline count as
227
+ `error`.
228
+
198
229
  `bilt.notifications` is typed on the client a bare `createClient(url, key, options)`
199
230
  returns. It exists at runtime with explicit type arguments too, but isn't in that
200
231
  client's type.
@@ -225,7 +256,7 @@ const bilt = createClient(url, key, {
225
256
  arguments defaults its schema to the augmentable `Database` interface above instead of `any`.
226
257
  - `Database`, the empty interface a project augments to type its schema.
227
258
  - 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).
259
+ - `bilt.notifications.send` sends a push notification to one end user, or from an edge function to every device (see Push notifications).
229
260
  - Realtime is not available: `bilt.channel()` throws `REALTIME_NOT_SUPPORTED`. Refetch with `bilt.from(...)` on an interval or on screen focus instead.
230
261
  - `asyncStorage(impl)` factory wrapping `@react-native-async-storage/async-storage` to the supabase-js storage shape.
231
262
  - `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;
@@ -11,12 +11,20 @@ export type NotificationMessage = {
11
11
  data?: Record<string, unknown>;
12
12
  /** An in-app path such as `/chat/123`, opened on tap. */
13
13
  url?: string;
14
+ /**
15
+ * The kind of notification, such as `'New messages'`, at most 64 bytes. A
16
+ * recipient who turned it off gets nothing. On Android it is also the
17
+ * notification channel, which the user sees by this name in system settings.
18
+ */
19
+ category?: string;
14
20
  };
15
21
  /**
16
22
  * What happened for the recipient. `accepted` means Google or Apple took the
17
- * notification, not that it arrived.
23
+ * notification, not that it arrived. `opted_out` means the recipient turned
24
+ * the send's category off, and `suspended` that Bilt has stopped push for
25
+ * this app; neither sends anything.
18
26
  */
19
- export type NotificationOutcome = 'accepted' | 'no_devices' | 'notifications_off' | 'platform_off';
27
+ export type NotificationOutcome = 'accepted' | 'no_devices' | 'notifications_off' | 'platform_off' | 'opted_out' | 'suspended';
20
28
  /** A send bilt-cloud refused or never answered, with its error code, such as `rate_limited`. */
21
29
  export declare class NotificationsError extends Error {
22
30
  readonly status: number;
@@ -26,6 +34,28 @@ export declare class NotificationsError extends Error {
26
34
  export type NotificationSendResult = {
27
35
  data: {
28
36
  outcome: NotificationOutcome;
37
+ counts?: undefined;
38
+ };
39
+ error: null;
40
+ } | {
41
+ data: null;
42
+ error: NotificationsError;
43
+ };
44
+ export type NotificationCounts = {
45
+ accepted: number;
46
+ notifications_off: number;
47
+ platform_off: number;
48
+ error: number;
49
+ rate_limited: number;
50
+ /** Devices whose user, or the signed-out device itself, turned the send's category off. */
51
+ opted_out: number;
52
+ /** Every device of an app Bilt has stopped push for; then the only nonzero count. */
53
+ suspended: number;
54
+ };
55
+ export type NotificationSendAllResult = {
56
+ data: {
57
+ counts: NotificationCounts;
58
+ outcome?: undefined;
29
59
  };
30
60
  error: null;
31
61
  } | {
@@ -33,11 +63,21 @@ export type NotificationSendResult = {
33
63
  error: NotificationsError;
34
64
  };
35
65
  export type Notifications = {
66
+ /**
67
+ * Sends a push notification to every registered device of the app and
68
+ * returns how many devices had each outcome. Only an edge function may send it.
69
+ */
70
+ send(message: NotificationMessage & {
71
+ to: 'all';
72
+ }): Promise<NotificationSendAllResult>;
36
73
  /**
37
74
  * Sends a push notification to one end user's devices, as the signed-in user.
38
- * Without a session bilt-cloud refuses it.
75
+ * Without a session it sends with the client's key, which bilt-cloud accepts
76
+ * only from an edge function's `BILT_SERVICE_KEY`. A `to` typed as `string`
77
+ * may hold `'all'`, so the answer is either shape: read `data.outcome` for
78
+ * one user and `data.counts` for all.
39
79
  */
40
- send(message: NotificationMessage): Promise<NotificationSendResult>;
80
+ send(message: NotificationMessage): Promise<NotificationSendResult | NotificationSendAllResult>;
41
81
  };
42
82
  /** The supabase-js options `send` honours, so it authenticates the way the client's own calls do. */
43
83
  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.10.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",