@lunora/notify 1.0.0-alpha.7 → 1.0.0-alpha.9
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/dist/index.d.mts +146 -22
- package/dist/index.d.ts +146 -22
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/createNotify-jNlehALj.mjs +1 -0
- package/dist/packem_shared/d1SubscriptionStore-67jpK0Vx.mjs +1 -0
- package/dist/packem_shared/enqueuePushBroadcast-tf1LqgzA.mjs +1 -0
- package/dist/packem_shared/fcmId-CFZ8IquF.mjs +1 -0
- package/dist/packem_shared/memorySubscriptionStore-FKZR4-fB.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/createNotify-iBbs9Bew.mjs +0 -1
- package/dist/packem_shared/d1SubscriptionStore-BwssRgeI.mjs +0 -1
- package/dist/packem_shared/enqueuePushBroadcast-DMwYIM0o.mjs +0 -1
- package/dist/packem_shared/fcmId-CLRyQJVw.mjs +0 -1
- package/dist/packem_shared/memorySubscriptionStore-BxKdyxjC.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -75,14 +75,56 @@ type RegisterInput = {
|
|
|
75
75
|
};
|
|
76
76
|
/** Filter narrowing which stored subscriptions a `list`/`broadcast` targets. */
|
|
77
77
|
interface SubscriptionFilter {
|
|
78
|
+
/**
|
|
79
|
+
* Keyset pagination cursor: return only rows with `id` strictly GREATER
|
|
80
|
+
* than this value, ordered ascending by `id`. `id` is a stable,
|
|
81
|
+
* content-derived hash (see `webPushId`/`fcmId`), so ordering by it is
|
|
82
|
+
* immune to concurrent inserts/deletes elsewhere in the table — a page
|
|
83
|
+
* already walked never re-delivers or skips a row when another device
|
|
84
|
+
* registers mid-broadcast (the reviewer-flagged "stable under concurrent
|
|
85
|
+
* registers" property). `broadcastPage`/`broadcast` set this internally to
|
|
86
|
+
* walk pages; a direct `list()` caller may also page through results with
|
|
87
|
+
* it.
|
|
88
|
+
*
|
|
89
|
+
* OPTIONAL for a reason: `SubscriptionStore` is implementable outside this
|
|
90
|
+
* package. An external store that does not support cursoring may ignore
|
|
91
|
+
* `after` entirely and keep returning its (from-the-top) unpaged result —
|
|
92
|
+
* `broadcastPage` defensively re-filters whatever the store returns down
|
|
93
|
+
* to `id > after` itself, so a non-cursoring store can never cause a
|
|
94
|
+
* double-send or an infinite page-walk (each page's result only ever
|
|
95
|
+
* contains ids the previous page didn't already deliver), but it also
|
|
96
|
+
* cannot deliver the FULL matched audience beyond whatever the store's own
|
|
97
|
+
* (unpaged) response window happens to contain — implement `after`
|
|
98
|
+
* (ordered ascending by `id`, exclusive) to get real, complete pagination
|
|
99
|
+
* over a large audience.
|
|
100
|
+
*/
|
|
101
|
+
after?: string;
|
|
78
102
|
/** Restrict to a delivery kind. */
|
|
79
103
|
kind?: SubscriptionKind;
|
|
80
104
|
/**
|
|
81
105
|
* Cap the number of rows returned (a `LIMIT`). Applied server-side by the
|
|
82
106
|
* store, so a large audience never materializes wholesale in the isolate.
|
|
83
107
|
* A non-positive/absent value means "no cap"; a fractional value is truncated.
|
|
84
|
-
*
|
|
85
|
-
*
|
|
108
|
+
*
|
|
109
|
+
* For `list`/admin reads this bounds the returned page as before. For
|
|
110
|
+
* `broadcast`, this is now an OVERALL cap on the total number of
|
|
111
|
+
* subscriptions reached across every internally-walked page (still
|
|
112
|
+
* deliberately left unset by default — it must reach every matched
|
|
113
|
+
* device); the PER-PAGE batch size is a separate, independent knob (see
|
|
114
|
+
* `CreateNotifyOptions`'s `broadcastPageSize`, default 250) so a caller
|
|
115
|
+
* that sets `limit` to bound the audience doesn't also have to reason
|
|
116
|
+
* about page sizing.
|
|
117
|
+
*
|
|
118
|
+
* The non-positive sentinel means something different at each layer: at
|
|
119
|
+
* the STORE layer (`list`, and the `d1-store`/`memory-store` fetch-size
|
|
120
|
+
* hint) a non-positive `limit` means "no cap" — fetch everything. At the
|
|
121
|
+
* `broadcast`/`broadcastPage` layer, where `limit` is an AUDIENCE cap, a
|
|
122
|
+
* non-positive value instead means "no deliveries" — `broadcast({ limit: 0
|
|
123
|
+
* })` reaches nobody, not everybody. This asymmetry is deliberate: the two
|
|
124
|
+
* layers answer different questions ("how many rows to fetch" vs. "how
|
|
125
|
+
* many recipients to reach"), and unifying them would either break `list`
|
|
126
|
+
* callers relying on "no cap" or reintroduce the over-delivery this
|
|
127
|
+
* distinction fixes (see `broadcastPage`'s doc comment).
|
|
86
128
|
*/
|
|
87
129
|
limit?: number;
|
|
88
130
|
/** Restrict to a single owning user. */
|
|
@@ -98,7 +140,13 @@ interface SubscriptionStore {
|
|
|
98
140
|
delete: (id: string) => Promise<void>;
|
|
99
141
|
/** Read a subscription by id, or `undefined`. */
|
|
100
142
|
get: (id: string) => Promise<StoredSubscription | undefined>;
|
|
101
|
-
/**
|
|
143
|
+
/**
|
|
144
|
+
* List subscriptions, optionally filtered. When `filter.after` is set,
|
|
145
|
+
* results are keyset-paginated: only rows with `id` strictly greater than
|
|
146
|
+
* `filter.after` are returned, ordered ascending by `id`. Implementing
|
|
147
|
+
* `after` is OPTIONAL (see {@link SubscriptionFilter.after}) — a store
|
|
148
|
+
* that ignores it may keep returning its unpaged result.
|
|
149
|
+
*/
|
|
102
150
|
list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
|
|
103
151
|
/** Record the latest delivery outcome for a subscription (best-effort). */
|
|
104
152
|
markStatus: (id: string, status: SubscriptionStatus, error?: string) => Promise<void>;
|
|
@@ -127,6 +175,18 @@ interface BroadcastResult {
|
|
|
127
175
|
/** Total subscriptions attempted. */
|
|
128
176
|
total: number;
|
|
129
177
|
}
|
|
178
|
+
/**
|
|
179
|
+
* Result of `broadcastPage` — one bounded page of a fan-out, plus the cursor
|
|
180
|
+
* to fetch the next page. `nextCursor` is `undefined` when this was the last
|
|
181
|
+
* page (or the store doesn't support cursoring — see
|
|
182
|
+
* {@link SubscriptionFilter.after}'s documented unpaged fallback).
|
|
183
|
+
*/
|
|
184
|
+
interface BroadcastPageResult {
|
|
185
|
+
/** Cursor for the next page (pass as `filter.after`), or `undefined` when done. */
|
|
186
|
+
nextCursor?: string;
|
|
187
|
+
/** The delivery outcome for just this page. */
|
|
188
|
+
result: BroadcastResult;
|
|
189
|
+
}
|
|
130
190
|
/**
|
|
131
191
|
* The compact, stable delivery-status vocabulary emitted on notify observability
|
|
132
192
|
* signals — the `status` dimension on the `notify.send` metric and the failure
|
|
@@ -181,8 +241,28 @@ interface LunoraPush {
|
|
|
181
241
|
* Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
|
|
182
242
|
* the push service reports as gone (HTTP 404/410, FCM `UNREGISTERED`). The `to`
|
|
183
243
|
* target is derived from each subscription, so it is omitted from the payload.
|
|
244
|
+
*
|
|
245
|
+
* Internally walks the audience in bounded pages (via {@link LunoraPush.broadcastPage},
|
|
246
|
+
* keyset-paginated on the subscription `id`) so a huge audience is never
|
|
247
|
+
* materialized wholesale in the isolate — see `CreateNotifyOptions`'s
|
|
248
|
+
* `broadcastPageSize`. This call still processes the WHOLE matched
|
|
249
|
+
* audience in one request/queue message; use {@link LunoraPush.broadcastPage}
|
|
250
|
+
* directly (as `runPushBroadcastJob` does) to bound a single queue message
|
|
251
|
+
* to one page.
|
|
184
252
|
*/
|
|
185
253
|
broadcast: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastResult>;
|
|
254
|
+
/**
|
|
255
|
+
* Fan-out a push to ONE bounded page of stored subscriptions matching
|
|
256
|
+
* `filter` (page size: `CreateNotifyOptions`'s `broadcastPageSize`, default
|
|
257
|
+
* 250, capped by `filter.limit` when set). Same delivery semantics as
|
|
258
|
+
* {@link LunoraPush.broadcast} (retry/circuit-breaker, gone-pruning) but
|
|
259
|
+
* scoped to a single page; returns the page's own {@link BroadcastResult}
|
|
260
|
+
* plus a `nextCursor` to fetch the next page (`undefined` when done).
|
|
261
|
+
* Backs `runPushBroadcastJob` so one queue message does bounded work
|
|
262
|
+
* regardless of audience size — most app code should call
|
|
263
|
+
* {@link LunoraPush.broadcast} instead.
|
|
264
|
+
*/
|
|
265
|
+
broadcastPage: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastPageResult>;
|
|
186
266
|
/**
|
|
187
267
|
* List stored subscriptions (optionally filtered), with the delivery
|
|
188
268
|
* **secrets** stripped — the Web Push `keys` (RFC 8291 `auth`/`p256dh`) and the
|
|
@@ -333,6 +413,16 @@ declare const defineNotify: (config: NotifyConfig) => NotifyDefinition;
|
|
|
333
413
|
declare const isNotifyDefinition: (value: unknown) => value is NotifyDefinition;
|
|
334
414
|
/** Options for {@link createNotify}. */
|
|
335
415
|
interface CreateNotifyOptions {
|
|
416
|
+
/**
|
|
417
|
+
* Page size for `push.broadcast`'s internal keyset pagination over the
|
|
418
|
+
* subscription store (default {@link DEFAULT_BROADCAST_PAGE_SIZE}, 250).
|
|
419
|
+
* Each page is fetched, delivered, and counted independently before the
|
|
420
|
+
* next page's store round trip, so a huge audience is never materialized
|
|
421
|
+
* wholesale in the isolate. Also the per-message bound `push.broadcastPage`
|
|
422
|
+
* (and so `runPushBroadcastJob`) uses. A test/tuning seam — most apps never
|
|
423
|
+
* need to set this.
|
|
424
|
+
*/
|
|
425
|
+
broadcastPageSize?: number;
|
|
336
426
|
/** Max concurrent sends during a `broadcast` (default 10). */
|
|
337
427
|
concurrency?: number;
|
|
338
428
|
/**
|
|
@@ -407,9 +497,11 @@ declare const buildEngine: (resolved: ResolvedProviders) => Notification;
|
|
|
407
497
|
* A broadcast job body — the JSON-serialisable payload enqueued for off-request
|
|
408
498
|
* fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
|
|
409
499
|
* `@lunora/notify` depending on `@lunora/queue` (the seam stays structural).
|
|
500
|
+
* `filter.after`, when set, resumes a broadcast partway through (see
|
|
501
|
+
* {@link runPushBroadcastJob}'s continuation semantics).
|
|
410
502
|
*/
|
|
411
503
|
interface PushBroadcastJob {
|
|
412
|
-
/** Subscription filter (which devices/users to target). */
|
|
504
|
+
/** Subscription filter (which devices/users to target; `filter.after` resumes a paged broadcast). */
|
|
413
505
|
filter?: SubscriptionFilter;
|
|
414
506
|
/** The push payload to deliver (the `to` target is derived per subscription). */
|
|
415
507
|
payload: PushContent;
|
|
@@ -423,7 +515,8 @@ interface QueueProducerLike {
|
|
|
423
515
|
/**
|
|
424
516
|
* Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
|
|
425
517
|
* queue instead of blocking the request. Pair with {@link runPushBroadcastJob} in
|
|
426
|
-
* the queue consumer
|
|
518
|
+
* the queue consumer — see its doc comment for how a large audience continues
|
|
519
|
+
* across MULTIPLE messages (one bounded page per message), not one.
|
|
427
520
|
*
|
|
428
521
|
* ```ts
|
|
429
522
|
* // in a mutation/action:
|
|
@@ -431,29 +524,59 @@ interface QueueProducerLike {
|
|
|
431
524
|
*
|
|
432
525
|
* // in lunora/queues.ts consumer:
|
|
433
526
|
* export const push = defineQueue({ async handler(batch, ctx) {
|
|
434
|
-
* for (const message of batch.messages)
|
|
527
|
+
* for (const message of batch.messages) {
|
|
528
|
+
* const { nextCursor } = await runPushBroadcastJob(ctx.push, message.body);
|
|
529
|
+
*
|
|
530
|
+
* if (nextCursor !== undefined) {
|
|
531
|
+
* // More pages remain — enqueue the continuation. Each message still
|
|
532
|
+
* // does only ONE bounded page of work.
|
|
533
|
+
* await enqueuePushBroadcast(ctx.queues.push, {
|
|
534
|
+
* payload: message.body.payload,
|
|
535
|
+
* filter: { ...message.body.filter, after: nextCursor },
|
|
536
|
+
* });
|
|
537
|
+
* }
|
|
538
|
+
* }
|
|
435
539
|
* }});
|
|
436
540
|
* ```
|
|
437
541
|
*/
|
|
438
542
|
declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
|
|
439
543
|
/**
|
|
440
|
-
* Run an enqueued broadcast job on the consumer side,
|
|
441
|
-
*
|
|
442
|
-
* gone
|
|
544
|
+
* Run ONE bounded page of an enqueued broadcast job on the consumer side,
|
|
545
|
+
* delivering through the push facade's {@link LunoraPush.broadcastPage} (which
|
|
546
|
+
* reuses the engine's retry + circuit-breaker middleware and prunes gone
|
|
547
|
+
* subscriptions).
|
|
548
|
+
*
|
|
549
|
+
* RETRY / CONTINUATION SEMANTICS (rewritten for plan 222 / NOTIFY-01 — a
|
|
550
|
+
* broadcast job used to process the WHOLE audience in one message, which could
|
|
551
|
+
* exceed Worker CPU/wall limits for a large audience and made a retry re-run
|
|
552
|
+
* everything):
|
|
443
553
|
*
|
|
444
|
-
*
|
|
445
|
-
*
|
|
446
|
-
*
|
|
447
|
-
*
|
|
448
|
-
*
|
|
449
|
-
*
|
|
450
|
-
*
|
|
451
|
-
*
|
|
452
|
-
*
|
|
453
|
-
*
|
|
454
|
-
*
|
|
554
|
+
* - A job now processes exactly ONE bounded page (see `CreateNotifyOptions`'s
|
|
555
|
+
* page-size option, default 250, or `job.filter.limit` when smaller),
|
|
556
|
+
* keyset-paginated on the subscription `id` (see `SubscriptionFilter.after`)
|
|
557
|
+
* — so per-message work is bounded regardless of total audience size.
|
|
558
|
+
* - Retry is still gated on `result.failed` — the count of TRANSIENT delivery
|
|
559
|
+
* errors (a provider 5xx / network fault worth another attempt). When at
|
|
560
|
+
* least one recipient in THIS PAGE `failed`, the job is RE-THROWN so the
|
|
561
|
+
* queue does NOT ack it and its normal retry/backoff (and, on exhaustion,
|
|
562
|
+
* dead-letter) applies — to just this page, not the whole broadcast.
|
|
563
|
+
* - A page with zero `failed` resolves and is acked — this includes the
|
|
564
|
+
* all-`pruned` case (every device on the page had unsubscribed:
|
|
565
|
+
* `sent:0`, `failed:0`, `pruned:N`), which is a SUCCESSFUL prune, not a
|
|
566
|
+
* failure, so throwing on it would spuriously retry and pressure the DLQ;
|
|
567
|
+
* and the empty-page case (zero `total`), which has nothing to retry.
|
|
568
|
+
* - The returned `nextCursor` is set when more pages remain. `@lunora/notify`
|
|
569
|
+
* does NOT enqueue the continuation itself — it has no `@lunora/queue`
|
|
570
|
+
* dependency (the seam stays structural) and no reference to the producer
|
|
571
|
+
* that enqueued this message — so the CALLER (the `lunora/queues.ts`
|
|
572
|
+
* consumer) is responsible for re-enqueueing with `filter.after: nextCursor`
|
|
573
|
+
* when present. See the consumer example on {@link enqueuePushBroadcast}.
|
|
574
|
+
* - A retry of a page redelivers only that page's already-delivered recipients
|
|
575
|
+
* on a transient partial failure (a page is not individually idempotent) —
|
|
576
|
+
* the accepted cost of getting the transiently failed ones redelivered, now
|
|
577
|
+
* scoped to one page instead of the whole broadcast.
|
|
455
578
|
*/
|
|
456
|
-
declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<
|
|
579
|
+
declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<BroadcastPageResult>;
|
|
457
580
|
/**
|
|
458
581
|
* The minimal structural slice of Cloudflare's `D1Database` this store uses. A
|
|
459
582
|
* structural type (rather than importing `@cloudflare/workers-types`) keeps the
|
|
@@ -536,7 +659,8 @@ interface NormalizeOptions {
|
|
|
536
659
|
* Normalise a `register(...)` input into a {@link StoredSubscription}. Validates
|
|
537
660
|
* the shape (a web-push subscription needs `endpoint` + `keys.{p256dh,auth}`; an
|
|
538
661
|
* FCM entry needs a non-empty `token`), enforces the anti-SSRF endpoint boundary
|
|
539
|
-
* (see {@link assertPushEndpoint}),
|
|
662
|
+
* (see {@link assertPushEndpoint}), validates `metadata` (see
|
|
663
|
+
* {@link validateMetadata}), and stamps `createdAt`/`lastSeenAt`.
|
|
540
664
|
*/
|
|
541
665
|
declare const normalizeRegisterInput: (input: RegisterInput, now?: number, options?: NormalizeOptions) => StoredSubscription;
|
|
542
666
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -75,14 +75,56 @@ type RegisterInput = {
|
|
|
75
75
|
};
|
|
76
76
|
/** Filter narrowing which stored subscriptions a `list`/`broadcast` targets. */
|
|
77
77
|
interface SubscriptionFilter {
|
|
78
|
+
/**
|
|
79
|
+
* Keyset pagination cursor: return only rows with `id` strictly GREATER
|
|
80
|
+
* than this value, ordered ascending by `id`. `id` is a stable,
|
|
81
|
+
* content-derived hash (see `webPushId`/`fcmId`), so ordering by it is
|
|
82
|
+
* immune to concurrent inserts/deletes elsewhere in the table — a page
|
|
83
|
+
* already walked never re-delivers or skips a row when another device
|
|
84
|
+
* registers mid-broadcast (the reviewer-flagged "stable under concurrent
|
|
85
|
+
* registers" property). `broadcastPage`/`broadcast` set this internally to
|
|
86
|
+
* walk pages; a direct `list()` caller may also page through results with
|
|
87
|
+
* it.
|
|
88
|
+
*
|
|
89
|
+
* OPTIONAL for a reason: `SubscriptionStore` is implementable outside this
|
|
90
|
+
* package. An external store that does not support cursoring may ignore
|
|
91
|
+
* `after` entirely and keep returning its (from-the-top) unpaged result —
|
|
92
|
+
* `broadcastPage` defensively re-filters whatever the store returns down
|
|
93
|
+
* to `id > after` itself, so a non-cursoring store can never cause a
|
|
94
|
+
* double-send or an infinite page-walk (each page's result only ever
|
|
95
|
+
* contains ids the previous page didn't already deliver), but it also
|
|
96
|
+
* cannot deliver the FULL matched audience beyond whatever the store's own
|
|
97
|
+
* (unpaged) response window happens to contain — implement `after`
|
|
98
|
+
* (ordered ascending by `id`, exclusive) to get real, complete pagination
|
|
99
|
+
* over a large audience.
|
|
100
|
+
*/
|
|
101
|
+
after?: string;
|
|
78
102
|
/** Restrict to a delivery kind. */
|
|
79
103
|
kind?: SubscriptionKind;
|
|
80
104
|
/**
|
|
81
105
|
* Cap the number of rows returned (a `LIMIT`). Applied server-side by the
|
|
82
106
|
* store, so a large audience never materializes wholesale in the isolate.
|
|
83
107
|
* A non-positive/absent value means "no cap"; a fractional value is truncated.
|
|
84
|
-
*
|
|
85
|
-
*
|
|
108
|
+
*
|
|
109
|
+
* For `list`/admin reads this bounds the returned page as before. For
|
|
110
|
+
* `broadcast`, this is now an OVERALL cap on the total number of
|
|
111
|
+
* subscriptions reached across every internally-walked page (still
|
|
112
|
+
* deliberately left unset by default — it must reach every matched
|
|
113
|
+
* device); the PER-PAGE batch size is a separate, independent knob (see
|
|
114
|
+
* `CreateNotifyOptions`'s `broadcastPageSize`, default 250) so a caller
|
|
115
|
+
* that sets `limit` to bound the audience doesn't also have to reason
|
|
116
|
+
* about page sizing.
|
|
117
|
+
*
|
|
118
|
+
* The non-positive sentinel means something different at each layer: at
|
|
119
|
+
* the STORE layer (`list`, and the `d1-store`/`memory-store` fetch-size
|
|
120
|
+
* hint) a non-positive `limit` means "no cap" — fetch everything. At the
|
|
121
|
+
* `broadcast`/`broadcastPage` layer, where `limit` is an AUDIENCE cap, a
|
|
122
|
+
* non-positive value instead means "no deliveries" — `broadcast({ limit: 0
|
|
123
|
+
* })` reaches nobody, not everybody. This asymmetry is deliberate: the two
|
|
124
|
+
* layers answer different questions ("how many rows to fetch" vs. "how
|
|
125
|
+
* many recipients to reach"), and unifying them would either break `list`
|
|
126
|
+
* callers relying on "no cap" or reintroduce the over-delivery this
|
|
127
|
+
* distinction fixes (see `broadcastPage`'s doc comment).
|
|
86
128
|
*/
|
|
87
129
|
limit?: number;
|
|
88
130
|
/** Restrict to a single owning user. */
|
|
@@ -98,7 +140,13 @@ interface SubscriptionStore {
|
|
|
98
140
|
delete: (id: string) => Promise<void>;
|
|
99
141
|
/** Read a subscription by id, or `undefined`. */
|
|
100
142
|
get: (id: string) => Promise<StoredSubscription | undefined>;
|
|
101
|
-
/**
|
|
143
|
+
/**
|
|
144
|
+
* List subscriptions, optionally filtered. When `filter.after` is set,
|
|
145
|
+
* results are keyset-paginated: only rows with `id` strictly greater than
|
|
146
|
+
* `filter.after` are returned, ordered ascending by `id`. Implementing
|
|
147
|
+
* `after` is OPTIONAL (see {@link SubscriptionFilter.after}) — a store
|
|
148
|
+
* that ignores it may keep returning its unpaged result.
|
|
149
|
+
*/
|
|
102
150
|
list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
|
|
103
151
|
/** Record the latest delivery outcome for a subscription (best-effort). */
|
|
104
152
|
markStatus: (id: string, status: SubscriptionStatus, error?: string) => Promise<void>;
|
|
@@ -127,6 +175,18 @@ interface BroadcastResult {
|
|
|
127
175
|
/** Total subscriptions attempted. */
|
|
128
176
|
total: number;
|
|
129
177
|
}
|
|
178
|
+
/**
|
|
179
|
+
* Result of `broadcastPage` — one bounded page of a fan-out, plus the cursor
|
|
180
|
+
* to fetch the next page. `nextCursor` is `undefined` when this was the last
|
|
181
|
+
* page (or the store doesn't support cursoring — see
|
|
182
|
+
* {@link SubscriptionFilter.after}'s documented unpaged fallback).
|
|
183
|
+
*/
|
|
184
|
+
interface BroadcastPageResult {
|
|
185
|
+
/** Cursor for the next page (pass as `filter.after`), or `undefined` when done. */
|
|
186
|
+
nextCursor?: string;
|
|
187
|
+
/** The delivery outcome for just this page. */
|
|
188
|
+
result: BroadcastResult;
|
|
189
|
+
}
|
|
130
190
|
/**
|
|
131
191
|
* The compact, stable delivery-status vocabulary emitted on notify observability
|
|
132
192
|
* signals — the `status` dimension on the `notify.send` metric and the failure
|
|
@@ -181,8 +241,28 @@ interface LunoraPush {
|
|
|
181
241
|
* Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
|
|
182
242
|
* the push service reports as gone (HTTP 404/410, FCM `UNREGISTERED`). The `to`
|
|
183
243
|
* target is derived from each subscription, so it is omitted from the payload.
|
|
244
|
+
*
|
|
245
|
+
* Internally walks the audience in bounded pages (via {@link LunoraPush.broadcastPage},
|
|
246
|
+
* keyset-paginated on the subscription `id`) so a huge audience is never
|
|
247
|
+
* materialized wholesale in the isolate — see `CreateNotifyOptions`'s
|
|
248
|
+
* `broadcastPageSize`. This call still processes the WHOLE matched
|
|
249
|
+
* audience in one request/queue message; use {@link LunoraPush.broadcastPage}
|
|
250
|
+
* directly (as `runPushBroadcastJob` does) to bound a single queue message
|
|
251
|
+
* to one page.
|
|
184
252
|
*/
|
|
185
253
|
broadcast: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastResult>;
|
|
254
|
+
/**
|
|
255
|
+
* Fan-out a push to ONE bounded page of stored subscriptions matching
|
|
256
|
+
* `filter` (page size: `CreateNotifyOptions`'s `broadcastPageSize`, default
|
|
257
|
+
* 250, capped by `filter.limit` when set). Same delivery semantics as
|
|
258
|
+
* {@link LunoraPush.broadcast} (retry/circuit-breaker, gone-pruning) but
|
|
259
|
+
* scoped to a single page; returns the page's own {@link BroadcastResult}
|
|
260
|
+
* plus a `nextCursor` to fetch the next page (`undefined` when done).
|
|
261
|
+
* Backs `runPushBroadcastJob` so one queue message does bounded work
|
|
262
|
+
* regardless of audience size — most app code should call
|
|
263
|
+
* {@link LunoraPush.broadcast} instead.
|
|
264
|
+
*/
|
|
265
|
+
broadcastPage: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastPageResult>;
|
|
186
266
|
/**
|
|
187
267
|
* List stored subscriptions (optionally filtered), with the delivery
|
|
188
268
|
* **secrets** stripped — the Web Push `keys` (RFC 8291 `auth`/`p256dh`) and the
|
|
@@ -333,6 +413,16 @@ declare const defineNotify: (config: NotifyConfig) => NotifyDefinition;
|
|
|
333
413
|
declare const isNotifyDefinition: (value: unknown) => value is NotifyDefinition;
|
|
334
414
|
/** Options for {@link createNotify}. */
|
|
335
415
|
interface CreateNotifyOptions {
|
|
416
|
+
/**
|
|
417
|
+
* Page size for `push.broadcast`'s internal keyset pagination over the
|
|
418
|
+
* subscription store (default {@link DEFAULT_BROADCAST_PAGE_SIZE}, 250).
|
|
419
|
+
* Each page is fetched, delivered, and counted independently before the
|
|
420
|
+
* next page's store round trip, so a huge audience is never materialized
|
|
421
|
+
* wholesale in the isolate. Also the per-message bound `push.broadcastPage`
|
|
422
|
+
* (and so `runPushBroadcastJob`) uses. A test/tuning seam — most apps never
|
|
423
|
+
* need to set this.
|
|
424
|
+
*/
|
|
425
|
+
broadcastPageSize?: number;
|
|
336
426
|
/** Max concurrent sends during a `broadcast` (default 10). */
|
|
337
427
|
concurrency?: number;
|
|
338
428
|
/**
|
|
@@ -407,9 +497,11 @@ declare const buildEngine: (resolved: ResolvedProviders) => Notification;
|
|
|
407
497
|
* A broadcast job body — the JSON-serialisable payload enqueued for off-request
|
|
408
498
|
* fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
|
|
409
499
|
* `@lunora/notify` depending on `@lunora/queue` (the seam stays structural).
|
|
500
|
+
* `filter.after`, when set, resumes a broadcast partway through (see
|
|
501
|
+
* {@link runPushBroadcastJob}'s continuation semantics).
|
|
410
502
|
*/
|
|
411
503
|
interface PushBroadcastJob {
|
|
412
|
-
/** Subscription filter (which devices/users to target). */
|
|
504
|
+
/** Subscription filter (which devices/users to target; `filter.after` resumes a paged broadcast). */
|
|
413
505
|
filter?: SubscriptionFilter;
|
|
414
506
|
/** The push payload to deliver (the `to` target is derived per subscription). */
|
|
415
507
|
payload: PushContent;
|
|
@@ -423,7 +515,8 @@ interface QueueProducerLike {
|
|
|
423
515
|
/**
|
|
424
516
|
* Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
|
|
425
517
|
* queue instead of blocking the request. Pair with {@link runPushBroadcastJob} in
|
|
426
|
-
* the queue consumer
|
|
518
|
+
* the queue consumer — see its doc comment for how a large audience continues
|
|
519
|
+
* across MULTIPLE messages (one bounded page per message), not one.
|
|
427
520
|
*
|
|
428
521
|
* ```ts
|
|
429
522
|
* // in a mutation/action:
|
|
@@ -431,29 +524,59 @@ interface QueueProducerLike {
|
|
|
431
524
|
*
|
|
432
525
|
* // in lunora/queues.ts consumer:
|
|
433
526
|
* export const push = defineQueue({ async handler(batch, ctx) {
|
|
434
|
-
* for (const message of batch.messages)
|
|
527
|
+
* for (const message of batch.messages) {
|
|
528
|
+
* const { nextCursor } = await runPushBroadcastJob(ctx.push, message.body);
|
|
529
|
+
*
|
|
530
|
+
* if (nextCursor !== undefined) {
|
|
531
|
+
* // More pages remain — enqueue the continuation. Each message still
|
|
532
|
+
* // does only ONE bounded page of work.
|
|
533
|
+
* await enqueuePushBroadcast(ctx.queues.push, {
|
|
534
|
+
* payload: message.body.payload,
|
|
535
|
+
* filter: { ...message.body.filter, after: nextCursor },
|
|
536
|
+
* });
|
|
537
|
+
* }
|
|
538
|
+
* }
|
|
435
539
|
* }});
|
|
436
540
|
* ```
|
|
437
541
|
*/
|
|
438
542
|
declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
|
|
439
543
|
/**
|
|
440
|
-
* Run an enqueued broadcast job on the consumer side,
|
|
441
|
-
*
|
|
442
|
-
* gone
|
|
544
|
+
* Run ONE bounded page of an enqueued broadcast job on the consumer side,
|
|
545
|
+
* delivering through the push facade's {@link LunoraPush.broadcastPage} (which
|
|
546
|
+
* reuses the engine's retry + circuit-breaker middleware and prunes gone
|
|
547
|
+
* subscriptions).
|
|
548
|
+
*
|
|
549
|
+
* RETRY / CONTINUATION SEMANTICS (rewritten for plan 222 / NOTIFY-01 — a
|
|
550
|
+
* broadcast job used to process the WHOLE audience in one message, which could
|
|
551
|
+
* exceed Worker CPU/wall limits for a large audience and made a retry re-run
|
|
552
|
+
* everything):
|
|
443
553
|
*
|
|
444
|
-
*
|
|
445
|
-
*
|
|
446
|
-
*
|
|
447
|
-
*
|
|
448
|
-
*
|
|
449
|
-
*
|
|
450
|
-
*
|
|
451
|
-
*
|
|
452
|
-
*
|
|
453
|
-
*
|
|
454
|
-
*
|
|
554
|
+
* - A job now processes exactly ONE bounded page (see `CreateNotifyOptions`'s
|
|
555
|
+
* page-size option, default 250, or `job.filter.limit` when smaller),
|
|
556
|
+
* keyset-paginated on the subscription `id` (see `SubscriptionFilter.after`)
|
|
557
|
+
* — so per-message work is bounded regardless of total audience size.
|
|
558
|
+
* - Retry is still gated on `result.failed` — the count of TRANSIENT delivery
|
|
559
|
+
* errors (a provider 5xx / network fault worth another attempt). When at
|
|
560
|
+
* least one recipient in THIS PAGE `failed`, the job is RE-THROWN so the
|
|
561
|
+
* queue does NOT ack it and its normal retry/backoff (and, on exhaustion,
|
|
562
|
+
* dead-letter) applies — to just this page, not the whole broadcast.
|
|
563
|
+
* - A page with zero `failed` resolves and is acked — this includes the
|
|
564
|
+
* all-`pruned` case (every device on the page had unsubscribed:
|
|
565
|
+
* `sent:0`, `failed:0`, `pruned:N`), which is a SUCCESSFUL prune, not a
|
|
566
|
+
* failure, so throwing on it would spuriously retry and pressure the DLQ;
|
|
567
|
+
* and the empty-page case (zero `total`), which has nothing to retry.
|
|
568
|
+
* - The returned `nextCursor` is set when more pages remain. `@lunora/notify`
|
|
569
|
+
* does NOT enqueue the continuation itself — it has no `@lunora/queue`
|
|
570
|
+
* dependency (the seam stays structural) and no reference to the producer
|
|
571
|
+
* that enqueued this message — so the CALLER (the `lunora/queues.ts`
|
|
572
|
+
* consumer) is responsible for re-enqueueing with `filter.after: nextCursor`
|
|
573
|
+
* when present. See the consumer example on {@link enqueuePushBroadcast}.
|
|
574
|
+
* - A retry of a page redelivers only that page's already-delivered recipients
|
|
575
|
+
* on a transient partial failure (a page is not individually idempotent) —
|
|
576
|
+
* the accepted cost of getting the transiently failed ones redelivered, now
|
|
577
|
+
* scoped to one page instead of the whole broadcast.
|
|
455
578
|
*/
|
|
456
|
-
declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<
|
|
579
|
+
declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<BroadcastPageResult>;
|
|
457
580
|
/**
|
|
458
581
|
* The minimal structural slice of Cloudflare's `D1Database` this store uses. A
|
|
459
582
|
* structural type (rather than importing `@cloudflare/workers-types`) keeps the
|
|
@@ -536,7 +659,8 @@ interface NormalizeOptions {
|
|
|
536
659
|
* Normalise a `register(...)` input into a {@link StoredSubscription}. Validates
|
|
537
660
|
* the shape (a web-push subscription needs `endpoint` + `keys.{p256dh,auth}`; an
|
|
538
661
|
* FCM entry needs a non-empty `token`), enforces the anti-SSRF endpoint boundary
|
|
539
|
-
* (see {@link assertPushEndpoint}),
|
|
662
|
+
* (see {@link assertPushEndpoint}), validates `metadata` (see
|
|
663
|
+
* {@link validateMetadata}), and stamps `createdAt`/`lastSeenAt`.
|
|
540
664
|
*/
|
|
541
665
|
declare const normalizeRegisterInput: (input: RegisterInput, now?: number, options?: NormalizeOptions) => StoredSubscription;
|
|
542
666
|
/**
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FCM_ENV_KEYS as e,WEB_PUSH_ENV_KEYS as t,fcmFromEnv as i,webPushFromEnv as f}from"./packem_shared/FCM_ENV_KEYS-D0tvRTLQ.mjs";import{defineNotify as n,isNotifyDefinition as u}from"./packem_shared/defineNotify-DLEy53HJ.mjs";import{createNotify as p}from"./packem_shared/createNotify-
|
|
1
|
+
import{FCM_ENV_KEYS as e,WEB_PUSH_ENV_KEYS as t,fcmFromEnv as i,webPushFromEnv as f}from"./packem_shared/FCM_ENV_KEYS-D0tvRTLQ.mjs";import{defineNotify as n,isNotifyDefinition as u}from"./packem_shared/defineNotify-DLEy53HJ.mjs";import{createNotify as p}from"./packem_shared/createNotify-jNlehALj.mjs";import{buildEngine as d,routingPushProvider as x}from"./packem_shared/buildEngine-Jlzf2Jzn.mjs";import{enqueuePushBroadcast as c,runPushBroadcastJob as P}from"./packem_shared/enqueuePushBroadcast-tf1LqgzA.mjs";import{d1SubscriptionStore as b}from"./packem_shared/d1SubscriptionStore-67jpK0Vx.mjs";import{memorySubscriptionStore as N}from"./packem_shared/memorySubscriptionStore-FKZR4-fB.mjs";import{fcmId as g,isGoneError as y,normalizeRegisterInput as v,targetOf as B,webPushId as F}from"./packem_shared/fcmId-CFZ8IquF.mjs";export{e as FCM_ENV_KEYS,t as WEB_PUSH_ENV_KEYS,d as buildEngine,p as createNotify,b as d1SubscriptionStore,n as defineNotify,c as enqueuePushBroadcast,i as fcmFromEnv,g as fcmId,y as isGoneError,u as isNotifyDefinition,N as memorySubscriptionStore,v as normalizeRegisterInput,x as routingPushProvider,P as runPushBroadcastJob,B as targetOf,f as webPushFromEnv,F as webPushId};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as k}from"@lunora/errors";import{buildEngine as R}from"./buildEngine-Jlzf2Jzn.mjs";import{memorySubscriptionStore as W}from"./memorySubscriptionStore-FKZR4-fB.mjs";import{normalizeRegisterInput as Q,targetOf as U,isGoneError as j}from"./fcmId-CFZ8IquF.mjs";const z=250,g=(o,l)=>typeof o=="function"?o(l):o,b=o=>o.successful?void 0:o.errorMessages.join("; "),G=(o,l)=>o.successful?"accepted":j(l)?"gone":"failed",L=async(o,l,c)=>{const d=Array.from({length:o.length});let h=0;const p=async()=>{for(;h<o.length;){const f=h;h+=1,d[f]=await c(o[f])}};return await Promise.all(Array.from({length:Math.min(l,o.length)},()=>p())),d},_=(o,l)=>({chat:g(o.chat,l),fcm:g(o.fcm,l),inApp:g(o.inApp,l),webhook:g(o.webhook,l),webPush:g(o.webPush,l)}),E=new WeakMap,q=(o,l)=>{let c=E.get(o);c===void 0&&(c=new WeakMap,E.set(o,c));let d=c.get(l);return d===void 0&&(d={warnedNoPushOriginAllowlist:!1,warnedNoStore:!1},c.set(l,d)),d},V=(o,l,c={})=>{const d=q(o,l);let h;c.engine===void 0?(d.engine??=R(_(o,l)),h=d.engine):h=c.engine,d.store??=o.store?.(l);let{store:p}=d;p===void 0&&(d.fallbackStore??=W(),!c.silent&&!d.warnedNoStore&&(d.warnedNoStore=!0,console.warn("@lunora/notify: no `store` configured — using a non-durable in-memory subscription store. Configure `store: (env) => d1SubscriptionStore(env.DB)` for production.")),p=d.fallbackStore);const f=p,M=Math.max(1,c.concurrency??10),S=Math.max(1,c.broadcastPageSize??z),{log:T,metrics:P}=c,w=(t,e,r,i=1)=>{P?.count("notify.send",i,{channel:t,provider:e??t,status:r})},v=(t,e,r)=>{T?.warn(`notify ${t} delivery failed`,{channel:t,provider:e??t,status:"failed",...r})},N=(t,e)=>{P?.count("notify.skipped",1,{channel:t,reason:e})},$=()=>{const t=o.allowedPushOrigins!==void 0&&o.allowedPushOrigins.length>0;c.silent||t||d.warnedNoPushOriginAllowlist||(d.warnedNoPushOriginAllowlist=!0,console.warn("@lunora/notify: Web Push registered without `allowedPushOrigins` — the endpoint host is validated by a string classifier that does NOT resolve DNS, so a public hostname resolving to a private/internal IP (e.g. `https://127.0.0.1.nip.io/…`) is NOT blocked. Set `allowedPushOrigins` to the exact push-service origins to close DNS rebinding."))},I=async t=>(await f.list(t)).map(({keys:e,token:r,...i})=>i),C=async t=>{if(typeof t!="string")return t;const e=await f.get(t);if(e===void 0)throw new k("BAD_REQUEST",`@lunora/notify: no registered subscription with id "${t}"`);return e},O=async(t,e,r)=>{let i,s,n;try{i=await h.sendToChannel("push",{...e,to:U(t)}),s=b(i),n=G(i,s)}catch(u){n="failed",s=u instanceof Error?u.message:String(u)}try{n==="accepted"?await f.markStatus(t.id,"ok"):n==="gone"?await f.delete(t.id):await f.markStatus(t.id,"failed",s)}catch{}return n==="failed"&&v("push",t.kind,{error:s,subscriptionId:t.id,userId:t.userId??null}),r&&w("push",t.kind,n),{error:s,receipt:i,status:n}},D=async(t,e)=>{const r=await L(e,M,async n=>{const{error:u,status:a}=await O(n,t,!1);return{error:u,kind:n.kind,status:a,subscription:n}}),i=new Map;for(const{kind:n,status:u}of r){const a=`${n} ${u}`,m=i.get(a);m===void 0?i.set(a,{count:1,kind:n,status:u}):m.count+=1}for(const{count:n,kind:u,status:a}of i.values())w("push",u,a,n);const s=r.map(({error:n,status:u,subscription:a})=>u==="accepted"?{id:a.id,status:"ok"}:u==="gone"?{error:n,id:a.id,status:"expired"}:{error:n,id:a.id,status:"failed"});return{failed:s.filter(n=>n.status==="failed").length,outcomes:s,pruned:s.filter(n=>n.status==="expired").length,sent:s.filter(n=>n.status==="ok").length,total:s.length}},A=async(t,e)=>{if(e?.limit!==void 0&&e.limit<=0)return{nextCursor:void 0,result:{failed:0,outcomes:[],pruned:0,sent:0,total:0}};const r=e?.limit!==void 0&&e.limit>0?Math.trunc(e.limit):void 0,i=r===void 0?S:Math.min(r,S),s=await f.list({after:e?.after,kind:e?.kind,limit:i+1,userId:e?.userId}),n=e?.after===void 0?s:s.filter(B=>B.id>e.after),u=n.length>i,a=u?n.slice(0,i):n;a.length===0&&e?.after===void 0&&N("push","no-subscriptions-matched");const m=await D(t,a);return{nextCursor:u?a[a.length-1]?.id:void 0,result:m}},x={broadcast:async(t,e)=>{const r={failed:0,outcomes:[],pruned:0,sent:0,total:0};let i=e?.after;const s=e?.limit;if(s!==void 0&&s<=0)return r;for(;;){const n=s===void 0?{...e,after:i}:{...e,after:i,limit:s-r.total},{nextCursor:u,result:a}=await A(t,n);if(r.failed+=a.failed,r.pruned+=a.pruned,r.sent+=a.sent,r.total+=a.total,r.outcomes.push(...a.outcomes),s!==void 0&&r.total>=s||u===void 0||u===i)break;i=u}return r},broadcastPage:A,list:t=>I(t),register:t=>("token"in t||$(),f.put(Q(t,void 0,{allowedPushOrigins:o.allowedPushOrigins}))),send:async(t,e)=>{const{error:r,receipt:i}=await O(await C(t),e,!0);if(i===void 0)throw new k("INTERNAL",`@lunora/notify: push send failed: ${r??"unknown error"}`);return i},unregister:t=>f.delete(t)},y=async(t,e)=>{if(h.getProvider(t)===void 0)throw N(t,"channel-not-configured"),new k("BAD_REQUEST",`@lunora/notify: the "${t}" channel is not configured in defineNotify(...)`);const r=await h.sendToChannel(t,e),i=r.successful?"accepted":"failed";return w(t,r.provider,i),i==="failed"&&v(t,r.provider,{error:b(r)}),r};return{notify:{chat:t=>y("chat",t),inApp:t=>y("inapp",t),push:x,send:async t=>{const e=await h.send(t);for(const r of e){const i=r.channel??"unknown",s=r.successful?"accepted":"failed";w(i,r.provider,s),s==="failed"&&v(i,r.provider,{error:b(r)})}return e},webhook:t=>y("webhook",t)},push:x}};export{V as createNotify};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{legacyIdFor as S}from"./fcmId-CFZ8IquF.mjs";const o=a=>{const e={createdAt:a.created_at,id:a.id,kind:a.kind,lastSeenAt:a.last_seen_at,userId:a.user_id};if(a.endpoint!==null&&(e.endpoint=a.endpoint),a.p256dh!==null&&a.auth!==null&&(e.keys={auth:a.auth,p256dh:a.p256dh}),a.token!==null&&(e.token=a.token),a.last_status!==null&&(e.lastStatus=a.last_status),a.last_error!==null&&(e.lastError=a.last_error),a.metadata!==null)try{e.metadata=JSON.parse(a.metadata)}catch{}return e},c=/^[A-Za-z_]\w*$/u,k=(a,e={})=>{const r=e.tableName??"lunora_push_subscriptions";if(!c.test(r))throw new h("BAD_REQUEST",`@lunora/notify: d1SubscriptionStore tableName "${r}" is not a bare SQL identifier`);let s;const d=()=>(s===void 0&&(s=a.prepare(`CREATE TABLE IF NOT EXISTS ${r} (id TEXT PRIMARY KEY, kind TEXT NOT NULL, endpoint TEXT, p256dh TEXT, auth TEXT, token TEXT, user_id TEXT, metadata TEXT, created_at INTEGER NOT NULL, last_seen_at INTEGER NOT NULL, last_status TEXT, last_error TEXT)`).run().then(()=>a.prepare(`CREATE INDEX IF NOT EXISTS ${r}_user_id_idx ON ${r} (user_id)`).run()).then(()=>a.prepare(`CREATE INDEX IF NOT EXISTS ${r}_kind_idx ON ${r} (kind)`).run()).then(()=>{}),s.catch(()=>{s=void 0})),s),l=async t=>{await d();const n=await a.prepare(`SELECT * FROM ${r} WHERE id = ?1`).bind(t).first();return n===null?void 0:o(n)};return{delete:async t=>{await d(),await a.prepare(`DELETE FROM ${r} WHERE id = ?1`).bind(t).run()},get:l,list:async t=>{await d();const n=[],i=[];t?.kind!==void 0&&(i.push(t.kind),n.push(`kind = ?${i.length.toString()}`)),t?.userId!==void 0&&(t.userId===null?n.push("user_id IS NULL"):(i.push(t.userId),n.push(`user_id = ?${i.length.toString()}`))),t?.after!==void 0&&(i.push(t.after),n.push(`id > ?${i.length.toString()}`));const E=n.length===0?"":` WHERE ${n.join(" AND ")}`,p=" ORDER BY id ASC";let u="";t?.limit!==void 0&&t.limit>0&&(i.push(Math.trunc(t.limit)),u=` LIMIT ?${i.length.toString()}`);const{results:T}=await a.prepare(`SELECT * FROM ${r}${E}${p}${u}`).bind(...i).all();return T.map(_=>o(_))},markStatus:async(t,n,i)=>{await d(),await a.prepare(`UPDATE ${r} SET last_status = ?2, last_error = ?3, last_seen_at = ?4 WHERE id = ?1`).bind(t,n,i??null,Date.now()).run()},put:async t=>{await d(),await a.prepare(`INSERT INTO ${r} (id, kind, endpoint, p256dh, auth, token, user_id, metadata, created_at, last_seen_at, last_status, last_error) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) ON CONFLICT(id) DO UPDATE SET kind = ?2, endpoint = ?3, p256dh = ?4, auth = ?5, token = ?6, user_id = ?7, metadata = ?8, last_seen_at = ?10`).bind(t.id,t.kind,t.endpoint??null,t.keys?.p256dh??null,t.keys?.auth??null,t.token??null,t.userId??null,t.metadata===void 0?null:JSON.stringify(t.metadata),t.createdAt,t.lastSeenAt,t.lastStatus??null,t.lastError??null).run();const n=S(t);return n!==void 0&&n!==t.id&&await a.prepare(`DELETE FROM ${r} WHERE id = ?1`).bind(n).run(),await l(t.id)??t}}};export{k as d1SubscriptionStore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";const o=(e,r)=>e.send({...r,type:"lunora.push.broadcast"}),n=async(e,r)=>{const t=await e.broadcastPage(r.payload,r.filter);if(t.result.failed>0)throw new s("INTERNAL",`@lunora/notify: push broadcast page had ${t.result.failed.toString()} transient failure(s) of ${t.result.total.toString()} subscription(s) (${t.result.sent.toString()} sent, ${t.result.pruned.toString()} pruned) — throwing so the queue retries this page`);return t};export{o as enqueuePushBroadcast,n as runPushBroadcastJob};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";const k=/^\d{1,3}$/u,A=/^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u,I=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/u,v=/^::(\d{1,3}(?:\.\d{1,3}){3})$/u,O=/^::([\da-f]{1,4}):([\da-f]{1,4})$/u,D=/^64:ff9b::[\da-f]{1,4}:[\da-f]{1,4}$/u,R=/^\[|\]$/gu,_=/\.$/u,c=t=>{const e=t.split(".");if(e.length!==4)return;const n=e.map(r=>k.test(r)?Number(r):-1);if(!n.some(r=>r<0||r>255))return[n[0],n[1],n[2],n[3]]},f=([t,e])=>t===0||t===10||t===127||t===100&&e>=64&&e<=127||t===169&&e===254||t===172&&e>=16&&e<=31||t===192&&e===168||t>=224,h=(t,e)=>{const n=Number.parseInt(t??"",16),r=Number.parseInt(e??"",16);return!Number.isFinite(n)||!Number.isFinite(r)?!0:f([Math.floor(n/256),n%256,Math.floor(r/256),r%256])},N=t=>{const e=t.toLowerCase(),n=A.exec(e);if(n)return h(n[1],n[2]);const r=I.exec(e);if(r){const i=c(r[1]??"");return i===void 0||f(i)}const o=v.exec(e);if(o){const i=c(o[1]??"");return i===void 0||f(i)}const s=O.exec(e);return s?h(s[1],s[2]):D.test(e)||e.startsWith("2002:")||e.startsWith("2001:0:")?!0:e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||e.startsWith("fe8")||e.startsWith("fe9")||e.startsWith("fea")||e.startsWith("feb")},W=t=>t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa"),B=t=>t.replaceAll(R,"").replace(_,"").toLowerCase(),P=t=>{const e=B(t);if(e.includes(":"))return N(e);const n=c(e);return n===void 0?W(e):f(n)},g=4096,w=t=>{if(t===void 0)return;const e=typeof t=="object"&&t!==null?Object.getPrototypeOf(t):void 0;if(!(typeof t=="object"&&t!==null&&!Array.isArray(t)&&(e===Object.prototype||e===null)))throw new a("BAD_REQUEST","@lunora/notify: register() `metadata` must be a plain object");let n;try{n=JSON.stringify(t)}catch(o){throw new a("BAD_REQUEST",`@lunora/notify: register() \`metadata\` is not JSON-serialisable: ${o instanceof Error?o.message:String(o)}`)}const r=new TextEncoder().encode(n).length;if(r>g)throw new a("BAD_REQUEST",`@lunora/notify: register() \`metadata\` is ${r.toString()} bytes, exceeding the ${g.toString()}-byte cap`);return t},d=t=>t.toString(16).padStart(4,"0"),b=t=>{let e=8997,n=33826,r=40164,o=52210;for(let s=0;s<t.length;s+=1){const i=t.codePointAt(s)??0;e^=i&65535,n^=i>>>16&65535;const u=e*435,m=n*435,$=r*435+e*256,E=o*435+n*256,l=m+(u>>>16),p=$+(l>>>16),S=E+(p>>>16);e=u&65535,n=l&65535,r=p&65535,o=S&65535}return d(o)+d(r)+d(n)+d(e)},T=t=>`wp2_${b(t)}`,U=t=>`fcm2_${b(t)}`,y=t=>{let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.codePointAt(n)??0,e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")},x=t=>`wp_${y(t)}`,Q=t=>`fcm_${y(t)}`,C=t=>t.kind==="fcm"?t.token===void 0?void 0:Q(t.token):t.endpoint===void 0?void 0:x(t.endpoint),F=t=>{if(typeof t!="string")return t??{};try{return JSON.parse(t)}catch(e){throw new a("BAD_REQUEST",`@lunora/notify: register() web-push subscription is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}},j=(t,e)=>{let n;try{n=new URL(t)}catch{throw new a("BAD_REQUEST",`@lunora/notify: register() web-push \`endpoint\` must be an absolute https URL (got "${t}")`)}if(n.protocol!=="https:")throw new a("BAD_REQUEST",`@lunora/notify: register() web-push \`endpoint\` must use https (got "${n.protocol}")`);if(e!==void 0&&e.length>0){if(!e.includes(n.origin))throw new a("FORBIDDEN",`@lunora/notify: register() web-push endpoint origin "${n.origin}" is not in the configured allowedPushOrigins allowlist`);return}if(P(n.hostname))throw new a("FORBIDDEN",`@lunora/notify: register() web-push endpoint host "${n.hostname}" is a private/internal address; configure allowedPushOrigins to permit a specific origin`)},z=(t,e=Date.now(),n={})=>{if("token"in t){const{token:u}=t;if(typeof u!="string"||u==="")throw new a("BAD_REQUEST","@lunora/notify: register() fcm input requires a non-empty `token`");return{createdAt:e,id:U(u),kind:"fcm",lastSeenAt:e,metadata:w(t.metadata),token:u,userId:t.userId??null}}const r=F(t.subscription),{endpoint:o}=r,s=r.keys?.p256dh,i=r.keys?.auth;if(typeof o!="string"||o===""||typeof s!="string"||typeof i!="string")throw new a("BAD_REQUEST","@lunora/notify: register() web-push subscription requires `endpoint` and `keys.{p256dh, auth}`");return j(o,n.allowedPushOrigins),{createdAt:e,endpoint:o,id:T(o),keys:{auth:i,p256dh:s},kind:"web-push",lastSeenAt:e,metadata:w(t.metadata),userId:t.userId??null}},G=t=>t.kind==="fcm"?t.token??"":JSON.stringify({endpoint:t.endpoint,keys:t.keys}),J=/\bhttp\s*4(?:04|10)\b/iu,L=/\b(?:unregistered|not[\s-]?registered|registration-token-not-registered)\b/iu,M=/\bsubscription (?:is )?(?:gone|expired|no longer valid)\b/iu,H=t=>t===void 0?!1:J.test(t)||L.test(t)||M.test(t);export{U as fcmId,H as isGoneError,Q as legacyFcmId,C as legacyIdFor,x as legacyWebPushId,z as normalizeRegisterInput,G as targetOf,T as webPushId};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{legacyIdFor as d}from"./fcmId-CFZ8IquF.mjs";const n=(r,t)=>r.id<t.id?-1:r.id>t.id?1:0,l=(r,t)=>t===void 0?!0:!(t.kind!==void 0&&r.kind!==t.kind||t.userId!==void 0&&(r.userId??null)!==t.userId),u=()=>{const r=new Map;return{delete:t=>(r.delete(t),Promise.resolve()),get:t=>Promise.resolve(r.get(t)),list:t=>{const e=[];for(const s of r.values())l(s,t)&&e.push(s);e.sort(n);const o=t?.after===void 0?e:e.filter(s=>s.id>t.after),i=t?.limit!==void 0&&t.limit>0?o.slice(0,Math.trunc(t.limit)):o;return Promise.resolve(i)},markStatus:(t,e,o)=>{const i=r.get(t);return i!==void 0&&r.set(t,{...i,lastError:o,lastSeenAt:Date.now(),lastStatus:e}),Promise.resolve()},put:t=>{const e=d(t);e!==void 0&&e!==t.id&&r.delete(e);const o=r.get(t.id),i=o===void 0?t:{...o,...t,createdAt:o.createdAt};return r.set(i.id,i),Promise.resolve(i)}}};export{u as memorySubscriptionStore};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/notify",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.9",
|
|
4
4
|
"description": "Multi-channel notifications for Lunora — ctx.notify / ctx.push over @visulima/notification: edge-safe Web Push + FCM, plus chat, in-app inbox and webhook channels, with subscription storage and queue-backed fan-out",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"access": "public"
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
52
|
+
"@lunora/errors": "1.0.0-alpha.12",
|
|
53
53
|
"@visulima/notification": "1.0.5"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as v}from"@lunora/errors";import{buildEngine as R}from"./buildEngine-Jlzf2Jzn.mjs";import{memorySubscriptionStore as x}from"./memorySubscriptionStore-BxKdyxjC.mjs";import{normalizeRegisterInput as C,targetOf as W,isGoneError as B}from"./fcmId-CLRyQJVw.mjs";const w=(t,s)=>typeof t=="function"?t(s):t,b=t=>t.successful?void 0:t.errorMessages.join("; "),L=(t,s)=>t.successful?"accepted":B(s)?"gone":"failed",_=async(t,s,l)=>{const a=Array.from({length:t.length});let f=0;const g=async()=>{for(;f<t.length;){const c=f;f+=1,a[c]=await l(t[c])}};return await Promise.all(Array.from({length:Math.min(s,t.length)},()=>g())),a},j=(t,s)=>({chat:w(t.chat,s),fcm:w(t.fcm,s),inApp:w(t.inApp,s),webhook:w(t.webhook,s),webPush:w(t.webPush,s)}),E=new WeakMap,Q=(t,s)=>{let l=E.get(t);l===void 0&&(l=new WeakMap,E.set(t,l));let a=l.get(s);return a===void 0&&(a={warnedNoPushOriginAllowlist:!1,warnedNoStore:!1},l.set(s,a)),a},F=(t,s,l={})=>{const a=Q(t,s);let f;l.engine===void 0?(a.engine??=R(j(t,s)),f=a.engine):f=l.engine,a.store??=t.store?.(s);let{store:g}=a;g===void 0&&(a.fallbackStore??=x(),!l.silent&&!a.warnedNoStore&&(a.warnedNoStore=!0,console.warn("@lunora/notify: no `store` configured — using a non-durable in-memory subscription store. Configure `store: (env) => d1SubscriptionStore(env.DB)` for production.")),g=a.fallbackStore);const c=g,T=Math.max(1,l.concurrency??10),{log:$,metrics:S}=l,y=(e,o,n,i=1)=>{S?.count("notify.send",i,{channel:e,provider:o??e,status:n})},m=(e,o,n)=>{$?.warn(`notify ${e} delivery failed`,{channel:e,provider:o??e,status:"failed",...n})},P=(e,o)=>{S?.count("notify.skipped",1,{channel:e,reason:o})},I=()=>{const e=t.allowedPushOrigins!==void 0&&t.allowedPushOrigins.length>0;l.silent||e||a.warnedNoPushOriginAllowlist||(a.warnedNoPushOriginAllowlist=!0,console.warn("@lunora/notify: Web Push registered without `allowedPushOrigins` — the endpoint host is validated by a string classifier that does NOT resolve DNS, so a public hostname resolving to a private/internal IP (e.g. `https://127.0.0.1.nip.io/…`) is NOT blocked. Set `allowedPushOrigins` to the exact push-service origins to close DNS rebinding."))},D=async e=>(await c.list(e)).map(({keys:o,token:n,...i})=>i),M=async e=>{if(typeof e!="string")return e;const o=await c.get(e);if(o===void 0)throw new v("BAD_REQUEST",`@lunora/notify: no registered subscription with id "${e}"`);return o},N=async(e,o,n)=>{let i,u,d;try{i=await f.sendToChannel("push",{...o,to:W(e)}),u=b(i),d=L(i,u)}catch(r){d="failed",u=r instanceof Error?r.message:String(r)}try{d==="accepted"?await c.markStatus(e.id,"ok"):d==="gone"?await c.delete(e.id):await c.markStatus(e.id,"failed",u)}catch{}return d==="failed"&&m("push",e.kind,{error:u,subscriptionId:e.id,userId:e.userId??null}),n&&y("push",e.kind,d),{error:u,receipt:i,status:d}},O={broadcast:async(e,o)=>{const n=await c.list(o);n.length===0&&P("push","no-subscriptions-matched");const i=await _(n,T,async r=>{const{error:p,status:h}=await N(r,e,!1);return{error:p,kind:r.kind,status:h,subscription:r}}),u=new Map;for(const{kind:r,status:p}of i){const h=`${r}\0${p}`,A=u.get(h);A===void 0?u.set(h,{count:1,kind:r,status:p}):A.count+=1}for(const{count:r,kind:p,status:h}of u.values())y("push",p,h,r);const d=i.map(({error:r,status:p,subscription:h})=>p==="accepted"?{id:h.id,status:"ok"}:p==="gone"?{error:r,id:h.id,status:"expired"}:{error:r,id:h.id,status:"failed"});return{failed:d.filter(r=>r.status==="failed").length,outcomes:d,pruned:d.filter(r=>r.status==="expired").length,sent:d.filter(r=>r.status==="ok").length,total:d.length}},list:e=>D(e),register:e=>("token"in e||I(),c.put(C(e,void 0,{allowedPushOrigins:t.allowedPushOrigins}))),send:async(e,o)=>{const{error:n,receipt:i}=await N(await M(e),o,!0);if(i===void 0)throw new v("INTERNAL",`@lunora/notify: push send failed: ${n??"unknown error"}`);return i},unregister:e=>c.delete(e)},k=async(e,o)=>{if(f.getProvider(e)===void 0)throw P(e,"channel-not-configured"),new v("BAD_REQUEST",`@lunora/notify: the "${e}" channel is not configured in defineNotify(...)`);const n=await f.sendToChannel(e,o),i=n.successful?"accepted":"failed";return y(e,n.provider,i),i==="failed"&&m(e,n.provider,{error:b(n)}),n};return{notify:{chat:e=>k("chat",e),inApp:e=>k("inapp",e),push:O,send:async e=>{const o=await f.send(e);for(const n of o){const i=n.channel??"unknown",u=n.successful?"accepted":"failed";y(i,n.provider,u),u==="failed"&&m(i,n.provider,{error:b(n)})}return o},webhook:e=>k("webhook",e)},push:O}};export{F as createNotify};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as _}from"@lunora/errors";import{legacyIdFor as h}from"./fcmId-CLRyQJVw.mjs";const o=a=>{const i={createdAt:a.created_at,id:a.id,kind:a.kind,lastSeenAt:a.last_seen_at,userId:a.user_id};if(a.endpoint!==null&&(i.endpoint=a.endpoint),a.p256dh!==null&&a.auth!==null&&(i.keys={auth:a.auth,p256dh:a.p256dh}),a.token!==null&&(i.token=a.token),a.last_status!==null&&(i.lastStatus=a.last_status),a.last_error!==null&&(i.lastError=a.last_error),a.metadata!==null)try{i.metadata=JSON.parse(a.metadata)}catch{}return i},S=/^[A-Za-z_]\w*$/u,I=(a,i={})=>{const r=i.tableName??"lunora_push_subscriptions";if(!S.test(r))throw new _("BAD_REQUEST",`@lunora/notify: d1SubscriptionStore tableName "${r}" is not a bare SQL identifier`);let s;const d=()=>(s===void 0&&(s=a.prepare(`CREATE TABLE IF NOT EXISTS ${r} (id TEXT PRIMARY KEY, kind TEXT NOT NULL, endpoint TEXT, p256dh TEXT, auth TEXT, token TEXT, user_id TEXT, metadata TEXT, created_at INTEGER NOT NULL, last_seen_at INTEGER NOT NULL, last_status TEXT, last_error TEXT)`).run().then(()=>a.prepare(`CREATE INDEX IF NOT EXISTS ${r}_user_id_idx ON ${r} (user_id)`).run()).then(()=>a.prepare(`CREATE INDEX IF NOT EXISTS ${r}_kind_idx ON ${r} (kind)`).run()).then(()=>{}),s.catch(()=>{s=void 0})),s),l=async t=>{await d();const n=await a.prepare(`SELECT * FROM ${r} WHERE id = ?1`).bind(t).first();return n===null?void 0:o(n)};return{delete:async t=>{await d(),await a.prepare(`DELETE FROM ${r} WHERE id = ?1`).bind(t).run()},get:l,list:async t=>{await d();const n=[],e=[];t?.kind!==void 0&&(e.push(t.kind),n.push(`kind = ?${e.length.toString()}`)),t?.userId!==void 0&&(t.userId===null?n.push("user_id IS NULL"):(e.push(t.userId),n.push(`user_id = ?${e.length.toString()}`)));const E=n.length===0?"":` WHERE ${n.join(" AND ")}`;let u="";t?.limit!==void 0&&t.limit>0&&(e.push(Math.trunc(t.limit)),u=` LIMIT ?${e.length.toString()}`);const{results:p}=await a.prepare(`SELECT * FROM ${r}${E}${u}`).bind(...e).all();return p.map(T=>o(T))},markStatus:async(t,n,e)=>{await d(),await a.prepare(`UPDATE ${r} SET last_status = ?2, last_error = ?3, last_seen_at = ?4 WHERE id = ?1`).bind(t,n,e??null,Date.now()).run()},put:async t=>{await d(),await a.prepare(`INSERT INTO ${r} (id, kind, endpoint, p256dh, auth, token, user_id, metadata, created_at, last_seen_at, last_status, last_error) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) ON CONFLICT(id) DO UPDATE SET kind = ?2, endpoint = ?3, p256dh = ?4, auth = ?5, token = ?6, user_id = ?7, metadata = ?8, last_seen_at = ?10`).bind(t.id,t.kind,t.endpoint??null,t.keys?.p256dh??null,t.keys?.auth??null,t.token??null,t.userId??null,t.metadata===void 0?null:JSON.stringify(t.metadata),t.createdAt,t.lastSeenAt,t.lastStatus??null,t.lastError??null).run();const n=h(t);return n!==void 0&&n!==t.id&&await a.prepare(`DELETE FROM ${r} WHERE id = ?1`).bind(n).run(),await l(t.id)??t}}};export{I as d1SubscriptionStore};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";const e=(o,r)=>o.send({...r,type:"lunora.push.broadcast"}),s=async(o,r)=>{const t=await o.broadcast(r.payload,r.filter);if(t.failed>0)throw new a("INTERNAL",`@lunora/notify: push broadcast had ${t.failed.toString()} transient failure(s) of ${t.total.toString()} subscription(s) (${t.sent.toString()} sent, ${t.pruned.toString()} pruned) — throwing so the queue retries`);return t};export{e as enqueuePushBroadcast,s as runPushBroadcastJob};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as u}from"@lunora/errors";const k=/^\d{1,3}$/u,E=/^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u,I=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/u,S=/^::(\d{1,3}(?:\.\d{1,3}){3})$/u,v=/^::([\da-f]{1,4}):([\da-f]{1,4})$/u,A=/^64:ff9b::[\da-f]{1,4}:[\da-f]{1,4}$/u,W=/^\[|\]$/gu,N=/\.$/u,l=t=>{const e=t.split(".");if(e.length!==4)return;const n=e.map(r=>k.test(r)?Number(r):-1);if(!n.some(r=>r<0||r>255))return[n[0],n[1],n[2],n[3]]},f=([t,e])=>t===0||t===10||t===127||t===100&&e>=64&&e<=127||t===169&&e===254||t===172&&e>=16&&e<=31||t===192&&e===168||t>=224,p=(t,e)=>{const n=Number.parseInt(t??"",16),r=Number.parseInt(e??"",16);return!Number.isFinite(n)||!Number.isFinite(r)?!0:f([Math.floor(n/256),n%256,Math.floor(r/256),r%256])},R=t=>{const e=t.toLowerCase(),n=E.exec(e);if(n)return p(n[1],n[2]);const r=I.exec(e);if(r){const o=l(r[1]??"");return o===void 0||f(o)}const i=S.exec(e);if(i){const o=l(i[1]??"");return o===void 0||f(o)}const s=v.exec(e);return s?p(s[1],s[2]):A.test(e)||e.startsWith("2002:")||e.startsWith("2001:0:")?!0:e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||e.startsWith("fe8")||e.startsWith("fe9")||e.startsWith("fea")||e.startsWith("feb")},_=t=>t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa"),D=t=>t.replaceAll(W,"").replace(N,"").toLowerCase(),O=t=>{const e=D(t);if(e.includes(":"))return R(e);const n=l(e);return n===void 0?_(e):f(n)},d=t=>t.toString(16).padStart(4,"0"),g=t=>{let e=8997,n=33826,r=40164,i=52210;for(let s=0;s<t.length;s+=1){const o=t.codePointAt(s)??0;e^=o&65535,n^=o>>>16&65535;const a=e*435,w=n*435,b=r*435+e*256,y=i*435+n*256,c=w+(a>>>16),h=b+(c>>>16),$=y+(h>>>16);e=a&65535,n=c&65535,r=h&65535,i=$&65535}return d(i)+d(r)+d(n)+d(e)},P=t=>`wp2_${g(t)}`,B=t=>`fcm2_${g(t)}`,m=t=>{let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.codePointAt(n)??0,e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")},U=t=>`wp_${m(t)}`,x=t=>`fcm_${m(t)}`,q=t=>t.kind==="fcm"?t.token===void 0?void 0:x(t.token):t.endpoint===void 0?void 0:U(t.endpoint),F=t=>{if(typeof t!="string")return t??{};try{return JSON.parse(t)}catch(e){throw new u("BAD_REQUEST",`@lunora/notify: register() web-push subscription is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}},T=(t,e)=>{let n;try{n=new URL(t)}catch{throw new u("BAD_REQUEST",`@lunora/notify: register() web-push \`endpoint\` must be an absolute https URL (got "${t}")`)}if(n.protocol!=="https:")throw new u("BAD_REQUEST",`@lunora/notify: register() web-push \`endpoint\` must use https (got "${n.protocol}")`);if(e!==void 0&&e.length>0){if(!e.includes(n.origin))throw new u("FORBIDDEN",`@lunora/notify: register() web-push endpoint origin "${n.origin}" is not in the configured allowedPushOrigins allowlist`);return}if(O(n.hostname))throw new u("FORBIDDEN",`@lunora/notify: register() web-push endpoint host "${n.hostname}" is a private/internal address; configure allowedPushOrigins to permit a specific origin`)},C=(t,e=Date.now(),n={})=>{if("token"in t){const{token:a}=t;if(typeof a!="string"||a==="")throw new u("BAD_REQUEST","@lunora/notify: register() fcm input requires a non-empty `token`");return{createdAt:e,id:B(a),kind:"fcm",lastSeenAt:e,metadata:t.metadata,token:a,userId:t.userId??null}}const r=F(t.subscription),{endpoint:i}=r,s=r.keys?.p256dh,o=r.keys?.auth;if(typeof i!="string"||i===""||typeof s!="string"||typeof o!="string")throw new u("BAD_REQUEST","@lunora/notify: register() web-push subscription requires `endpoint` and `keys.{p256dh, auth}`");return T(i,n.allowedPushOrigins),{createdAt:e,endpoint:i,id:P(i),keys:{auth:o,p256dh:s},kind:"web-push",lastSeenAt:e,metadata:t.metadata,userId:t.userId??null}},z=t=>t.kind==="fcm"?t.token??"":JSON.stringify({endpoint:t.endpoint,keys:t.keys}),L=/\bhttp\s*4(?:04|10)\b/iu,Q=/\b(?:unregistered|not[\s-]?registered|registration-token-not-registered)\b/iu,J=/\bsubscription (?:is )?(?:gone|expired|no longer valid)\b/iu,G=t=>t===void 0?!1:L.test(t)||Q.test(t)||J.test(t);export{B as fcmId,G as isGoneError,x as legacyFcmId,q as legacyIdFor,U as legacyWebPushId,C as normalizeRegisterInput,z as targetOf,P as webPushId};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{legacyIdFor as i}from"./fcmId-CLRyQJVw.mjs";const d=(e,t)=>t===void 0?!0:!(t.kind!==void 0&&e.kind!==t.kind||t.userId!==void 0&&(e.userId??null)!==t.userId),l=()=>{const e=new Map;return{delete:t=>(e.delete(t),Promise.resolve()),get:t=>Promise.resolve(e.get(t)),list:t=>{const r=[];for(const o of e.values())d(o,t)&&r.push(o);const s=t?.limit!==void 0&&t.limit>0?r.slice(0,Math.trunc(t.limit)):r;return Promise.resolve(s)},markStatus:(t,r,s)=>{const o=e.get(t);return o!==void 0&&e.set(t,{...o,lastError:s,lastSeenAt:Date.now(),lastStatus:r}),Promise.resolve()},put:t=>{const r=i(t);r!==void 0&&r!==t.id&&e.delete(r);const s=e.get(t.id),o=s===void 0?t:{...s,...t,createdAt:s.createdAt};return e.set(o.id,o),Promise.resolve(o)}}};export{l as memorySubscriptionStore};
|