@molecule/api-push-notifications-molecule 1.1.2 → 1.2.1

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
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
3
  Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
4
  Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
5
  To change this document, edit the module-level JSDoc in src/index.ts.
6
- Generated: 2026-10-16T23:31:01.976Z
6
+ Generated: 2026-11-16T10:33:18.280Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-push-notifications-molecule
@@ -91,6 +91,43 @@ class MoleculeServiceError extends Error {
91
91
  }
92
92
  ```
93
93
 
94
+ #### `PushServiceError`
95
+
96
+ The push service (FCM, Mozilla autopush, Apple) answered a send with a status outside 2xx.
97
+
98
+ Thrown by `send` and placed in `SendManyResult.error`, with the push service's status on
99
+ `statusCode` — the shape web-push's `WebPushError` has — so the core's documented pruning
100
+ (`error.statusCode` 404 or 410 means the subscription is gone) works whichever push bond is
101
+ wired. A resolved `SendResult` therefore always means the push service accepted the message.
102
+
103
+ ```typescript
104
+ class PushServiceError extends Error {
105
+ /** The push service's HTTP status: 404/410 mean the subscription is gone; 429 means slow down. */
106
+ readonly statusCode: number
107
+ /** The push service's response headers. */
108
+ readonly headers: Record<string, string>
109
+ /** The push service's response body. */
110
+ readonly body: string
111
+
112
+ /**
113
+ * Create the error.
114
+ *
115
+ * @param result - The push service's answer, as molecule.dev relayed it.
116
+ */
117
+ constructor(result: SendResult) {
118
+ const gone = result.statusCode === 404 || result.statusCode === 410
119
+ super(
120
+ `The push service answered ${result.statusCode}` +
121
+ (gone ? ': the subscription is gone; delete it.' : '.'),
122
+ )
123
+ this.name = 'PushServiceError'
124
+ this.statusCode = result.statusCode
125
+ this.headers = result.headers ?? {}
126
+ this.body = result.body ?? ''
127
+ }
128
+ }
129
+ ```
130
+
94
131
  #### `MoleculePushProvider`
95
132
 
96
133
  Push provider backed by molecule.dev's hosted service.
@@ -103,6 +140,7 @@ class MoleculePushProvider implements PushNotificationProvider {
103
140
  private readonly servicesUrl: string
104
141
  private readonly timeoutMs: number
105
142
  private cachedPublicKey: string | undefined
143
+ private publicKeyRequest: Promise<string> | undefined
106
144
 
107
145
  /**
108
146
  * Create the provider.
@@ -132,31 +170,46 @@ class MoleculePushProvider implements PushNotificationProvider {
132
170
  *
133
171
  * @param subscription - The push subscription (endpoint + keys).
134
172
  * @param payload - The notification payload (title + display options).
135
- * @returns The push service's answer: `statusCode` 201 means delivered;
136
- * 404/410 mean the subscription is dead and should be pruned.
173
+ * @param options - Optional delivery settings (TTL, urgency, topic); molecule.dev sends them
174
+ * to the push service as its TTL, Urgency and Topic headers.
175
+ * @returns The push service's acceptance (`statusCode` 2xx).
176
+ * @throws {PushServiceError} When the push service answered outside 2xx; `statusCode`
177
+ * 404/410 means the subscription is dead and should be pruned.
137
178
  */
138
- async send(subscription: PushSubscription, payload: NotificationPayload): Promise<SendResult> {
179
+ async send(
180
+ subscription: PushSubscription,
181
+ payload: NotificationPayload,
182
+ options?: SendOptions,
183
+ ): Promise<SendResult> {
139
184
  assertValidSubscription(subscription)
140
185
  assertValidPayload(payload)
141
- return this.request<SendResult>('send', { subscription, payload })
186
+ const result = await this.request<SendResult>('send', {
187
+ subscription,
188
+ payload,
189
+ ...(options ? { options } : {}),
190
+ })
191
+ if (result.statusCode < 200 || result.statusCode > 299) throw new PushServiceError(result)
192
+ return result
142
193
  }
143
194
 
144
195
  /**
145
196
  * Sends a push notification to multiple subscriptions. One refused or
146
197
  * failed subscription never aborts the batch — each entry carries either
147
- * `result` or `error` (a dead subscription arrives as a `result` whose
148
- * `statusCode` is 404/410; prune on it).
198
+ * `result` or `error` (a dead subscription arrives as a `PushServiceError`
199
+ * in `error` whose `statusCode` is 404/410; prune on it).
149
200
  *
150
201
  * @param subscriptions - The push subscriptions to send to.
151
202
  * @param payload - The notification payload with title and optional display options.
203
+ * @param options - Optional delivery settings applied to every message.
152
204
  * @returns One result entry per subscription.
153
205
  */
154
206
  async sendMany(
155
207
  subscriptions: PushSubscription[],
156
208
  payload: NotificationPayload,
209
+ options?: SendOptions,
157
210
  ): Promise<SendManyResult[]> {
158
211
  const settled = await Promise.allSettled(
159
- (subscriptions ?? []).map((subscription) => this.send(subscription, payload)),
212
+ (subscriptions ?? []).map((subscription) => this.send(subscription, payload, options)),
160
213
  )
161
214
  return settled.map((outcome, i) =>
162
215
  outcome.status === 'fulfilled'
@@ -172,11 +225,12 @@ class MoleculePushProvider implements PushNotificationProvider {
172
225
  *
173
226
  * The core's method is SYNCHRONOUS while the key lives behind a service
174
227
  * call, so this returns the cache: `undefined` until {@link fetchPublicKey}
175
- * has run (or a send cached it). Await the fetch first:
228
+ * has run. Serve the key with the core's `fetchPublicKey()`,
229
+ * which calls {@link fetchPublicKey} on this provider:
176
230
  *
177
231
  * ```typescript
178
- * await provider.fetchPublicKey() // once, e.g. at startup
179
- * const applicationServerKey = provider.getPublicKey()
232
+ * import { fetchPublicKey } from '@molecule/api-push-notifications'
233
+ * const applicationServerKey = await fetchPublicKey()
180
234
  * ```
181
235
  *
182
236
  * @returns The cached public key, or `undefined` before the first fetch.
@@ -186,15 +240,27 @@ class MoleculePushProvider implements PushNotificationProvider {
186
240
  }
187
241
 
188
242
  /**
189
- * Fetches molecule.dev's public VAPID key from the hosted service and
190
- * caches it for {@link getPublicKey}.
243
+ * Fetches molecule.dev's public VAPID key from the hosted service once and caches it
244
+ * for {@link getPublicKey}. Later calls answer from the cache, and calls made while
245
+ * the request is in flight share it, so a public-key route that calls this per request
246
+ * asks the service once per process. A failed request is not cached: the next call
247
+ * asks again.
191
248
  *
192
249
  * @returns The public key string.
193
250
  */
194
- async fetchPublicKey(): Promise<string> {
195
- const { publicKey } = await this.request<{ publicKey: string }>('vapid-key', {})
196
- this.cachedPublicKey = publicKey
197
- return publicKey
251
+ fetchPublicKey(): Promise<string> {
252
+ if (this.cachedPublicKey) return Promise.resolve(this.cachedPublicKey)
253
+ this.publicKeyRequest ??= this.request<{ publicKey: string }>('vapid-key', {}).then(
254
+ ({ publicKey }) => {
255
+ this.cachedPublicKey = publicKey
256
+ return publicKey
257
+ },
258
+ (error: unknown) => {
259
+ this.publicKeyRequest = undefined
260
+ throw error
261
+ },
262
+ )
263
+ return this.publicKeyRequest
198
264
  }
199
265
 
200
266
  /**
@@ -334,7 +400,7 @@ export function setupPushNotificationsMolecule(): void {
334
400
 
335
401
  Peer dependencies:
336
402
 
337
- - `@molecule/api-push-notifications` >=1.0.2
403
+ - `@molecule/api-push-notifications` ^1.1.0
338
404
  - `@molecule/api-secrets` ^1.0.1
339
405
 
340
406
  ### Environment Variables
package/dist/index.d.ts CHANGED
@@ -9,13 +9,14 @@
9
9
  *
10
10
  * @example
11
11
  * ```typescript
12
- * import { setProvider, send } from '@molecule/api-push-notifications'
12
+ * import { fetchPublicKey, send, setProvider } from '@molecule/api-push-notifications'
13
13
  * import { provider as push } from '@molecule/api-push-notifications-molecule'
14
14
  *
15
15
  * setProvider(push) // reads MOLECULE_API_KEY from the environment
16
16
  *
17
- * // One-time: give the browser molecule.dev's public key to subscribe with.
18
- * const applicationServerKey = await push.fetchPublicKey()
17
+ * // The browser subscribes with molecule.dev's public key; serve it from your
18
+ * // public-key route. The core's fetchPublicKey() asks the service once and caches it.
19
+ * const applicationServerKey = await fetchPublicKey()
19
20
  *
20
21
  * await send(subscription, { title: 'Order shipped', options: { body: 'Track it here.' } })
21
22
  * ```
@@ -28,12 +29,14 @@
28
29
  * refused unless the host is loopback or a private-network endpoint such as
29
30
  * the sandbox gateway `host.docker.internal` (RFC 1918 / *.docker.internal)).
30
31
  * - **Subscriptions are bound to the VAPID key they were created with.** A
31
- * browser subscribes with the `applicationServerKey` returned by
32
+ * browser subscribes with the `applicationServerKey` returned by the core's
32
33
  * `fetchPublicKey()` — molecule.dev's public key — and only molecule.dev can
33
34
  * then send to those subscriptions. Moving to your own VAPID identity (the
34
35
  * web-push bond) means your users re-subscribe.
35
36
  * - `getPublicKey()` is the core's SYNCHRONOUS method, so it returns the
36
- * cache: `undefined` until `fetchPublicKey()` has run. `configure()` is a
37
+ * cache: `undefined` until `fetchPublicKey()` has run. Serve the key with the core's
38
+ * `fetchPublicKey()` (`@molecule/api-resource-device`'s public-key route does), which
39
+ * works with this bond and with the web-push bond alike. `configure()` is a
37
40
  * no-op (the service holds the keys), and `generateVapidKeys()` throws —
38
41
  * generating your own keys is a self-hosted concern (`@molecule/api-push-notifications-web-push`).
39
42
  * - Payloads are bounded at 3072 characters of serialized JSON (the Web Push
@@ -41,9 +44,11 @@
41
44
  * overhead); subscriptions need the exact `endpoint` + `keys.p256dh` +
42
45
  * `keys.auth` values `pushManager.subscribe()` returned. Bad calls are
43
46
  * refused locally with 400/413 and never leave the process.
44
- * - Every push-service answer arrives as a resolved `SendResult`: `statusCode`
45
- * 201 means delivered; 404/410 mean the subscription is dead — prune it.
46
- * `sendMany()` never aborts the batch on one dead subscription.
47
+ * - A resolved `SendResult` means the push service accepted the message. Any other
48
+ * answer throws `PushServiceError` with the push service's status on `statusCode`,
49
+ * as web-push's `WebPushError` does, so the core's pruning works with either bond:
50
+ * `statusCode` 404/410 means the subscription is dead — delete it. `sendMany()`
51
+ * never aborts the batch; a dead subscription's entry carries the error.
47
52
  * - Metered per send and billed to the project; the upstream push services
48
53
  * (FCM, Mozilla autopush, Apple) are free, so the real upstream cost is 0 —
49
54
  * the send still counts against the project's rate limit and free-tier
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AACH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA;AAE1B,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAA;AAOhF;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,wBASrB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AACH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA;AAE1B,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAA;AAOhF;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,wBASrB,CAAA"}
package/dist/index.js CHANGED
@@ -9,13 +9,14 @@
9
9
  *
10
10
  * @example
11
11
  * ```typescript
12
- * import { setProvider, send } from '@molecule/api-push-notifications'
12
+ * import { fetchPublicKey, send, setProvider } from '@molecule/api-push-notifications'
13
13
  * import { provider as push } from '@molecule/api-push-notifications-molecule'
14
14
  *
15
15
  * setProvider(push) // reads MOLECULE_API_KEY from the environment
16
16
  *
17
- * // One-time: give the browser molecule.dev's public key to subscribe with.
18
- * const applicationServerKey = await push.fetchPublicKey()
17
+ * // The browser subscribes with molecule.dev's public key; serve it from your
18
+ * // public-key route. The core's fetchPublicKey() asks the service once and caches it.
19
+ * const applicationServerKey = await fetchPublicKey()
19
20
  *
20
21
  * await send(subscription, { title: 'Order shipped', options: { body: 'Track it here.' } })
21
22
  * ```
@@ -28,12 +29,14 @@
28
29
  * refused unless the host is loopback or a private-network endpoint such as
29
30
  * the sandbox gateway `host.docker.internal` (RFC 1918 / *.docker.internal)).
30
31
  * - **Subscriptions are bound to the VAPID key they were created with.** A
31
- * browser subscribes with the `applicationServerKey` returned by
32
+ * browser subscribes with the `applicationServerKey` returned by the core's
32
33
  * `fetchPublicKey()` — molecule.dev's public key — and only molecule.dev can
33
34
  * then send to those subscriptions. Moving to your own VAPID identity (the
34
35
  * web-push bond) means your users re-subscribe.
35
36
  * - `getPublicKey()` is the core's SYNCHRONOUS method, so it returns the
36
- * cache: `undefined` until `fetchPublicKey()` has run. `configure()` is a
37
+ * cache: `undefined` until `fetchPublicKey()` has run. Serve the key with the core's
38
+ * `fetchPublicKey()` (`@molecule/api-resource-device`'s public-key route does), which
39
+ * works with this bond and with the web-push bond alike. `configure()` is a
37
40
  * no-op (the service holds the keys), and `generateVapidKeys()` throws —
38
41
  * generating your own keys is a self-hosted concern (`@molecule/api-push-notifications-web-push`).
39
42
  * - Payloads are bounded at 3072 characters of serialized JSON (the Web Push
@@ -41,9 +44,11 @@
41
44
  * overhead); subscriptions need the exact `endpoint` + `keys.p256dh` +
42
45
  * `keys.auth` values `pushManager.subscribe()` returned. Bad calls are
43
46
  * refused locally with 400/413 and never leave the process.
44
- * - Every push-service answer arrives as a resolved `SendResult`: `statusCode`
45
- * 201 means delivered; 404/410 mean the subscription is dead — prune it.
46
- * `sendMany()` never aborts the batch on one dead subscription.
47
+ * - A resolved `SendResult` means the push service accepted the message. Any other
48
+ * answer throws `PushServiceError` with the push service's status on `statusCode`,
49
+ * as web-push's `WebPushError` does, so the core's pruning works with either bond:
50
+ * `statusCode` 404/410 means the subscription is dead — delete it. `sendMany()`
51
+ * never aborts the batch; a dead subscription's entry carries the error.
47
52
  * - Metered per send and billed to the project; the upstream push services
48
53
  * (FCM, Mozilla autopush, Apple) are free, so the real upstream cost is 0 —
49
54
  * the send still counts against the project's rate limit and free-tier
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * @module
9
9
  */
10
- import type { NotificationPayload, PushNotificationProvider, PushSubscription, SendManyResult, SendResult, VapidConfig } from '@molecule/api-push-notifications';
10
+ import type { NotificationPayload, PushNotificationProvider, PushSubscription, SendManyResult, SendOptions, SendResult, VapidConfig } from '@molecule/api-push-notifications';
11
11
  import type { MoleculePushConfig } from './types.js';
12
12
  /** Default hosted services base URL. */
13
13
  export declare const DEFAULT_SERVICES_URL = "https://api.molecule.dev/api/v1/services";
@@ -36,6 +36,28 @@ export declare class MoleculeServiceError extends Error {
36
36
  */
37
37
  constructor(message: string, status: number, errorKey?: string, cause?: unknown);
38
38
  }
39
+ /**
40
+ * The push service (FCM, Mozilla autopush, Apple) answered a send with a status outside 2xx.
41
+ *
42
+ * Thrown by `send` and placed in `SendManyResult.error`, with the push service's status on
43
+ * `statusCode` — the shape web-push's `WebPushError` has — so the core's documented pruning
44
+ * (`error.statusCode` 404 or 410 means the subscription is gone) works whichever push bond is
45
+ * wired. A resolved `SendResult` therefore always means the push service accepted the message.
46
+ */
47
+ export declare class PushServiceError extends Error {
48
+ /** The push service's HTTP status: 404/410 mean the subscription is gone; 429 means slow down. */
49
+ readonly statusCode: number;
50
+ /** The push service's response headers. */
51
+ readonly headers: Record<string, string>;
52
+ /** The push service's response body. */
53
+ readonly body: string;
54
+ /**
55
+ * Create the error.
56
+ *
57
+ * @param result - The push service's answer, as molecule.dev relayed it.
58
+ */
59
+ constructor(result: SendResult);
60
+ }
39
61
  /**
40
62
  * Push provider backed by molecule.dev's hosted service.
41
63
  */
@@ -45,6 +67,7 @@ export declare class MoleculePushProvider implements PushNotificationProvider {
45
67
  private readonly servicesUrl;
46
68
  private readonly timeoutMs;
47
69
  private cachedPublicKey;
70
+ private publicKeyRequest;
48
71
  /**
49
72
  * Create the provider.
50
73
  *
@@ -65,21 +88,25 @@ export declare class MoleculePushProvider implements PushNotificationProvider {
65
88
  *
66
89
  * @param subscription - The push subscription (endpoint + keys).
67
90
  * @param payload - The notification payload (title + display options).
68
- * @returns The push service's answer: `statusCode` 201 means delivered;
69
- * 404/410 mean the subscription is dead and should be pruned.
91
+ * @param options - Optional delivery settings (TTL, urgency, topic); molecule.dev sends them
92
+ * to the push service as its TTL, Urgency and Topic headers.
93
+ * @returns The push service's acceptance (`statusCode` 2xx).
94
+ * @throws {PushServiceError} When the push service answered outside 2xx; `statusCode`
95
+ * 404/410 means the subscription is dead and should be pruned.
70
96
  */
71
- send(subscription: PushSubscription, payload: NotificationPayload): Promise<SendResult>;
97
+ send(subscription: PushSubscription, payload: NotificationPayload, options?: SendOptions): Promise<SendResult>;
72
98
  /**
73
99
  * Sends a push notification to multiple subscriptions. One refused or
74
100
  * failed subscription never aborts the batch — each entry carries either
75
- * `result` or `error` (a dead subscription arrives as a `result` whose
76
- * `statusCode` is 404/410; prune on it).
101
+ * `result` or `error` (a dead subscription arrives as a `PushServiceError`
102
+ * in `error` whose `statusCode` is 404/410; prune on it).
77
103
  *
78
104
  * @param subscriptions - The push subscriptions to send to.
79
105
  * @param payload - The notification payload with title and optional display options.
106
+ * @param options - Optional delivery settings applied to every message.
80
107
  * @returns One result entry per subscription.
81
108
  */
82
- sendMany(subscriptions: PushSubscription[], payload: NotificationPayload): Promise<SendManyResult[]>;
109
+ sendMany(subscriptions: PushSubscription[], payload: NotificationPayload, options?: SendOptions): Promise<SendManyResult[]>;
83
110
  /**
84
111
  * Returns molecule.dev's public VAPID key — the `applicationServerKey` a
85
112
  * browser's `pushManager.subscribe()` must be given for the resulting
@@ -87,19 +114,23 @@ export declare class MoleculePushProvider implements PushNotificationProvider {
87
114
  *
88
115
  * The core's method is SYNCHRONOUS while the key lives behind a service
89
116
  * call, so this returns the cache: `undefined` until {@link fetchPublicKey}
90
- * has run (or a send cached it). Await the fetch first:
117
+ * has run. Serve the key with the core's `fetchPublicKey()`,
118
+ * which calls {@link fetchPublicKey} on this provider:
91
119
  *
92
120
  * ```typescript
93
- * await provider.fetchPublicKey() // once, e.g. at startup
94
- * const applicationServerKey = provider.getPublicKey()
121
+ * import { fetchPublicKey } from '@molecule/api-push-notifications'
122
+ * const applicationServerKey = await fetchPublicKey()
95
123
  * ```
96
124
  *
97
125
  * @returns The cached public key, or `undefined` before the first fetch.
98
126
  */
99
127
  getPublicKey(): string | undefined;
100
128
  /**
101
- * Fetches molecule.dev's public VAPID key from the hosted service and
102
- * caches it for {@link getPublicKey}.
129
+ * Fetches molecule.dev's public VAPID key from the hosted service once and caches it
130
+ * for {@link getPublicKey}. Later calls answer from the cache, and calls made while
131
+ * the request is in flight share it, so a public-key route that calls this per request
132
+ * asks the service once per process. A failed request is not cached: the next call
133
+ * asks again.
103
134
  *
104
135
  * @returns The public key string.
105
136
  */
@@ -1 +1 @@
1
- {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,gBAAgB,EAChB,cAAc,EACd,UAAU,EACV,WAAW,EACZ,MAAM,kCAAkC,CAAA;AAEzC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAEpD,wCAAwC;AACxC,eAAO,MAAM,oBAAoB,6CAA6C,CAAA;AAkE9E,gDAAgD;AAChD,eAAO,MAAM,mBAAmB;IAC9B,gIAAgI;;IAEhI,wFAAwF;;IAExF,wBAAwB;;CAEhB,CAAA;AAEV,gEAAgE;AAChE,qBAAa,oBAAqB,SAAQ,KAAK;IAC7C,qCAAqC;IACrC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,8EAA8E;IAC9E,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAA;IAErC;;;;;;;OAOG;gBACS,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAMhF;AAoFD;;GAEG;AACH,qBAAa,oBAAqB,YAAW,wBAAwB;IACnE,QAAQ,CAAC,IAAI,cAAa;IAE1B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAC/B,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAQ;IACpC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAQ;IAClC,OAAO,CAAC,eAAe,CAAoB;IAE3C;;;;OAIG;gBACS,MAAM,GAAE,kBAAuB;IAQ3C;;;;;;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IACH,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC;IAejC;;;;;;;;OAQG;IACH,iBAAiB,IAAI,KAAK;IAQ1B,sCAAsC;YACxB,OAAO;CAyCtB;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,kBAAkB,GAAG,wBAAwB,CAEpF"}
package/dist/provider.js CHANGED
@@ -103,6 +103,36 @@ export class MoleculeServiceError extends Error {
103
103
  this.errorKey = errorKey;
104
104
  }
105
105
  }
106
+ /**
107
+ * The push service (FCM, Mozilla autopush, Apple) answered a send with a status outside 2xx.
108
+ *
109
+ * Thrown by `send` and placed in `SendManyResult.error`, with the push service's status on
110
+ * `statusCode` — the shape web-push's `WebPushError` has — so the core's documented pruning
111
+ * (`error.statusCode` 404 or 410 means the subscription is gone) works whichever push bond is
112
+ * wired. A resolved `SendResult` therefore always means the push service accepted the message.
113
+ */
114
+ export class PushServiceError extends Error {
115
+ /** The push service's HTTP status: 404/410 mean the subscription is gone; 429 means slow down. */
116
+ statusCode;
117
+ /** The push service's response headers. */
118
+ headers;
119
+ /** The push service's response body. */
120
+ body;
121
+ /**
122
+ * Create the error.
123
+ *
124
+ * @param result - The push service's answer, as molecule.dev relayed it.
125
+ */
126
+ constructor(result) {
127
+ const gone = result.statusCode === 404 || result.statusCode === 410;
128
+ super(`The push service answered ${result.statusCode}` +
129
+ (gone ? ': the subscription is gone; delete it.' : '.'));
130
+ this.name = 'PushServiceError';
131
+ this.statusCode = result.statusCode;
132
+ this.headers = result.headers ?? {};
133
+ this.body = result.body ?? '';
134
+ }
135
+ }
106
136
  /** What to tell the developer for each refusal the service can return. */
107
137
  const HINTS = {
108
138
  400: 'The subscription or payload was refused — check that `keys.p256dh`/`keys.auth` are the exact base64url values pushManager.subscribe() returned and that the endpoint URL is unchanged.',
@@ -158,6 +188,7 @@ export class MoleculePushProvider {
158
188
  servicesUrl;
159
189
  timeoutMs;
160
190
  cachedPublicKey;
191
+ publicKeyRequest;
161
192
  /**
162
193
  * Create the provider.
163
194
  *
@@ -182,26 +213,37 @@ export class MoleculePushProvider {
182
213
  *
183
214
  * @param subscription - The push subscription (endpoint + keys).
184
215
  * @param payload - The notification payload (title + display options).
185
- * @returns The push service's answer: `statusCode` 201 means delivered;
186
- * 404/410 mean the subscription is dead and should be pruned.
216
+ * @param options - Optional delivery settings (TTL, urgency, topic); molecule.dev sends them
217
+ * to the push service as its TTL, Urgency and Topic headers.
218
+ * @returns The push service's acceptance (`statusCode` 2xx).
219
+ * @throws {PushServiceError} When the push service answered outside 2xx; `statusCode`
220
+ * 404/410 means the subscription is dead and should be pruned.
187
221
  */
188
- async send(subscription, payload) {
222
+ async send(subscription, payload, options) {
189
223
  assertValidSubscription(subscription);
190
224
  assertValidPayload(payload);
191
- return this.request('send', { subscription, payload });
225
+ const result = await this.request('send', {
226
+ subscription,
227
+ payload,
228
+ ...(options ? { options } : {}),
229
+ });
230
+ if (result.statusCode < 200 || result.statusCode > 299)
231
+ throw new PushServiceError(result);
232
+ return result;
192
233
  }
193
234
  /**
194
235
  * Sends a push notification to multiple subscriptions. One refused or
195
236
  * failed subscription never aborts the batch — each entry carries either
196
- * `result` or `error` (a dead subscription arrives as a `result` whose
197
- * `statusCode` is 404/410; prune on it).
237
+ * `result` or `error` (a dead subscription arrives as a `PushServiceError`
238
+ * in `error` whose `statusCode` is 404/410; prune on it).
198
239
  *
199
240
  * @param subscriptions - The push subscriptions to send to.
200
241
  * @param payload - The notification payload with title and optional display options.
242
+ * @param options - Optional delivery settings applied to every message.
201
243
  * @returns One result entry per subscription.
202
244
  */
203
- async sendMany(subscriptions, payload) {
204
- const settled = await Promise.allSettled((subscriptions ?? []).map((subscription) => this.send(subscription, payload)));
245
+ async sendMany(subscriptions, payload, options) {
246
+ const settled = await Promise.allSettled((subscriptions ?? []).map((subscription) => this.send(subscription, payload, options)));
205
247
  return settled.map((outcome, i) => outcome.status === 'fulfilled'
206
248
  ? { subscription: subscriptions[i], result: outcome.value }
207
249
  : { subscription: subscriptions[i], error: outcome.reason });
@@ -213,11 +255,12 @@ export class MoleculePushProvider {
213
255
  *
214
256
  * The core's method is SYNCHRONOUS while the key lives behind a service
215
257
  * call, so this returns the cache: `undefined` until {@link fetchPublicKey}
216
- * has run (or a send cached it). Await the fetch first:
258
+ * has run. Serve the key with the core's `fetchPublicKey()`,
259
+ * which calls {@link fetchPublicKey} on this provider:
217
260
  *
218
261
  * ```typescript
219
- * await provider.fetchPublicKey() // once, e.g. at startup
220
- * const applicationServerKey = provider.getPublicKey()
262
+ * import { fetchPublicKey } from '@molecule/api-push-notifications'
263
+ * const applicationServerKey = await fetchPublicKey()
221
264
  * ```
222
265
  *
223
266
  * @returns The cached public key, or `undefined` before the first fetch.
@@ -226,15 +269,25 @@ export class MoleculePushProvider {
226
269
  return this.cachedPublicKey;
227
270
  }
228
271
  /**
229
- * Fetches molecule.dev's public VAPID key from the hosted service and
230
- * caches it for {@link getPublicKey}.
272
+ * Fetches molecule.dev's public VAPID key from the hosted service once and caches it
273
+ * for {@link getPublicKey}. Later calls answer from the cache, and calls made while
274
+ * the request is in flight share it, so a public-key route that calls this per request
275
+ * asks the service once per process. A failed request is not cached: the next call
276
+ * asks again.
231
277
  *
232
278
  * @returns The public key string.
233
279
  */
234
- async fetchPublicKey() {
235
- const { publicKey } = await this.request('vapid-key', {});
236
- this.cachedPublicKey = publicKey;
237
- return publicKey;
280
+ fetchPublicKey() {
281
+ if (this.cachedPublicKey)
282
+ return Promise.resolve(this.cachedPublicKey);
283
+ this.publicKeyRequest ??= this.request('vapid-key', {}).then(({ publicKey }) => {
284
+ this.cachedPublicKey = publicKey;
285
+ return publicKey;
286
+ }, (error) => {
287
+ this.publicKeyRequest = undefined;
288
+ throw error;
289
+ });
290
+ return this.publicKeyRequest;
238
291
  }
239
292
  /**
240
293
  * Not supported on the hosted path: sends are signed with molecule.dev's
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@molecule/api-push-notifications-molecule",
3
- "version": "1.1.2",
4
- "description": "molecule.dev hosted push notifications provider — web push delivery through your molecule project, VAPID handled for you",
3
+ "version": "1.2.1",
4
+ "description": "molecule.dev hosted push notifications provider — web push delivered through your molecule project, VAPID handled for you",
5
5
  "homepage": "https://www.molecule.dev/packages/api-push-notifications-molecule",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",
@@ -35,11 +35,11 @@
35
35
  "directory": "packages/api/bonds/push-notifications/molecule"
36
36
  },
37
37
  "peerDependencies": {
38
- "@molecule/api-push-notifications": ">=1.0.2",
38
+ "@molecule/api-push-notifications": "^1.1.0",
39
39
  "@molecule/api-secrets": "^1.0.1"
40
40
  },
41
41
  "devDependencies": {
42
- "@molecule/api-push-notifications": "1.0.3",
42
+ "@molecule/api-push-notifications": "1.2.0",
43
43
  "@types/node": "26.6.5",
44
44
  "typescript": "6.0.3",
45
45
  "vitest": "4.1.12"