@lunora/notify 1.0.0-alpha.3 → 1.0.0-alpha.30
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 +49 -1
- package/dist/index.d.mts +326 -17
- package/dist/index.d.ts +326 -17
- package/dist/index.mjs +1 -8
- package/dist/packem_shared/FCM_ENV_KEYS-BbhPScGH.mjs +1 -0
- package/dist/packem_shared/buildEngine-oDWs9Pom.mjs +1 -0
- package/dist/packem_shared/createNotify-BDE42tvH.mjs +1 -0
- package/dist/packem_shared/d1SubscriptionStore-s-AJH4hS.mjs +1 -0
- package/dist/packem_shared/defineNotify-CUi2k7pP.mjs +1 -0
- package/dist/packem_shared/enqueuePushBroadcast-B6v3DLLp.mjs +1 -0
- package/dist/packem_shared/fcmId-Dwh_R5xe.mjs +1 -0
- package/dist/packem_shared/memorySubscriptionStore-FY8yANEM.mjs +1 -0
- package/dist/packem_shared/ssrf-host-BCpHorGa.mjs +1 -0
- package/dist/web.d.mts +0 -15
- package/dist/web.d.ts +0 -15
- package/dist/web.mjs +1 -44
- package/package.json +3 -3
- package/dist/packem_shared/FCM_ENV_KEYS-DY4-A717.mjs +0 -32
- package/dist/packem_shared/buildEngine-DlmjvnNk.mjs +0 -65
- package/dist/packem_shared/createNotify-bDWs4qBm.mjs +0 -191
- package/dist/packem_shared/d1SubscriptionStore-Dv3VPMI_.mjs +0 -107
- package/dist/packem_shared/defineNotify-B6S_47C2.mjs +0 -18
- package/dist/packem_shared/enqueuePushBroadcast-DiK7Hyja.mjs +0 -4
- package/dist/packem_shared/fcmId-B-YPgHi7.mjs +0 -68
- package/dist/packem_shared/memorySubscriptionStore-DhS-YnLe.mjs +0 -46
package/dist/index.d.ts
CHANGED
|
@@ -75,8 +75,58 @@ 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;
|
|
104
|
+
/**
|
|
105
|
+
* Cap the number of rows returned (a `LIMIT`). Applied server-side by the
|
|
106
|
+
* store, so a large audience never materializes wholesale in the isolate.
|
|
107
|
+
* A non-positive/absent value means "no cap"; a fractional value is truncated.
|
|
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).
|
|
128
|
+
*/
|
|
129
|
+
limit?: number;
|
|
80
130
|
/** Restrict to a single owning user. */
|
|
81
131
|
userId?: string | null;
|
|
82
132
|
}
|
|
@@ -90,7 +140,13 @@ interface SubscriptionStore {
|
|
|
90
140
|
delete: (id: string) => Promise<void>;
|
|
91
141
|
/** Read a subscription by id, or `undefined`. */
|
|
92
142
|
get: (id: string) => Promise<StoredSubscription | undefined>;
|
|
93
|
-
/**
|
|
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
|
+
*/
|
|
94
150
|
list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
|
|
95
151
|
/** Record the latest delivery outcome for a subscription (best-effort). */
|
|
96
152
|
markStatus: (id: string, status: SubscriptionStatus, error?: string) => Promise<void>;
|
|
@@ -119,6 +175,18 @@ interface BroadcastResult {
|
|
|
119
175
|
/** Total subscriptions attempted. */
|
|
120
176
|
total: number;
|
|
121
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
|
+
}
|
|
122
190
|
/**
|
|
123
191
|
* The compact, stable delivery-status vocabulary emitted on notify observability
|
|
124
192
|
* signals — the `status` dimension on the `notify.send` metric and the failure
|
|
@@ -173,10 +241,36 @@ interface LunoraPush {
|
|
|
173
241
|
* Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
|
|
174
242
|
* the push service reports as gone (HTTP 404/410, FCM `UNREGISTERED`). The `to`
|
|
175
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 `runPushBroadcastPage` does) to bound a single queue message
|
|
251
|
+
* to one page.
|
|
176
252
|
*/
|
|
177
253
|
broadcast: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastResult>;
|
|
178
|
-
/**
|
|
179
|
-
|
|
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 `runPushBroadcastPage` 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>;
|
|
266
|
+
/**
|
|
267
|
+
* List stored subscriptions (optionally filtered), with the delivery
|
|
268
|
+
* **secrets** stripped — the Web Push `keys` (RFC 8291 `auth`/`p256dh`) and the
|
|
269
|
+
* FCM `token`. Those, plus the endpoint, are enough to deliver arbitrary push to
|
|
270
|
+
* a device, so they never cross the app-facing facade; the raw rows are
|
|
271
|
+
* reachable only through the internal `SubscriptionStore`.
|
|
272
|
+
*/
|
|
273
|
+
list: (filter?: SubscriptionFilter) => Promise<PushSubscriptionDevice[]>;
|
|
180
274
|
/** Register (upsert) a device subscription and return the stored record. */
|
|
181
275
|
register: (input: RegisterInput) => Promise<StoredSubscription>;
|
|
182
276
|
/** Send a push to a single stored subscription (by id or record); `to` is derived from it. */
|
|
@@ -213,6 +307,22 @@ type WebPushConfigFactory = (env: NotifyEnv) => WebPushConfig | undefined;
|
|
|
213
307
|
type FcmConfigFactory = (env: NotifyEnv) => FcmConfig | undefined;
|
|
214
308
|
/** Options accepted by `defineNotify`. */
|
|
215
309
|
interface NotifyConfig {
|
|
310
|
+
/**
|
|
311
|
+
* Exact origins (`https://host[:port]`) a client-supplied Web Push `endpoint`
|
|
312
|
+
* may register from. When set (non-empty), `register()` requires the endpoint's
|
|
313
|
+
* origin to be one of these — the strongest anti-SSRF posture, and the way to
|
|
314
|
+
* close DNS rebinding for a facade that accepts client-controlled endpoints.
|
|
315
|
+
*
|
|
316
|
+
* When unset, the default posture applies: an endpoint must be `https:` with a
|
|
317
|
+
* host a STRING classifier does not flag as private / loopback / link-local.
|
|
318
|
+
* That classifier does NOT resolve DNS, so a public hostname resolving to a
|
|
319
|
+
* private/internal IP (e.g. `https://127.0.0.1.nip.io/…`) is NOT blocked by it
|
|
320
|
+
* — `register()` also emits a one-shot dev warning in this case. Set this to the
|
|
321
|
+
* push services your app actually uses (e.g. `["https://fcm.googleapis.com",
|
|
322
|
+
* "https://updates.push.services.mozilla.com"]` — exact origins only, no
|
|
323
|
+
* wildcards) to hard-pin the boundary and close DNS rebinding.
|
|
324
|
+
*/
|
|
325
|
+
allowedPushOrigins?: string[];
|
|
216
326
|
/**
|
|
217
327
|
* Optional chat provider factory (Slack/Discord/Teams/Telegram). Wire with a
|
|
218
328
|
* provider from `@visulima/notification/providers/*`. Edge-safe (fetch-based).
|
|
@@ -303,6 +413,16 @@ declare const defineNotify: (config: NotifyConfig) => NotifyDefinition;
|
|
|
303
413
|
declare const isNotifyDefinition: (value: unknown) => value is NotifyDefinition;
|
|
304
414
|
/** Options for {@link createNotify}. */
|
|
305
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 `runPushBroadcastPage`) uses. A test/tuning seam — most apps never
|
|
423
|
+
* need to set this.
|
|
424
|
+
*/
|
|
425
|
+
broadcastPageSize?: number;
|
|
306
426
|
/** Max concurrent sends during a `broadcast` (default 10). */
|
|
307
427
|
concurrency?: number;
|
|
308
428
|
/**
|
|
@@ -347,6 +467,11 @@ declare const createNotify: (definition: NotifyDefinition, env: NotifyEnv, optio
|
|
|
347
467
|
};
|
|
348
468
|
/** Options for {@link routingPushProvider}. */
|
|
349
469
|
interface RoutingPushOptions {
|
|
470
|
+
/**
|
|
471
|
+
* The definition's exact-origin allowlist, when configured. Its presence
|
|
472
|
+
* disables the send-time rebinding re-check (see {@link assertPushTargetResolvable}).
|
|
473
|
+
*/
|
|
474
|
+
allowedPushOrigins?: string[];
|
|
350
475
|
fcm?: Provider<unknown, PushPayload>;
|
|
351
476
|
webPush?: Provider<unknown, PushPayload>;
|
|
352
477
|
}
|
|
@@ -360,6 +485,8 @@ interface RoutingPushOptions {
|
|
|
360
485
|
declare const routingPushProvider: (options: RoutingPushOptions) => Provider<unknown, PushPayload>;
|
|
361
486
|
/** A resolved, ready-to-wire set of channel configs (edge-safe channels only). */
|
|
362
487
|
interface ResolvedProviders {
|
|
488
|
+
/** The definition's `allowedPushOrigins`, threaded to the push router's send-time SSRF guard. */
|
|
489
|
+
allowedPushOrigins?: string[];
|
|
363
490
|
chat?: Provider;
|
|
364
491
|
fcm?: FcmConfig;
|
|
365
492
|
inApp?: Provider;
|
|
@@ -377,23 +504,48 @@ declare const buildEngine: (resolved: ResolvedProviders) => Notification;
|
|
|
377
504
|
* A broadcast job body — the JSON-serialisable payload enqueued for off-request
|
|
378
505
|
* fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
|
|
379
506
|
* `@lunora/notify` depending on `@lunora/queue` (the seam stays structural).
|
|
507
|
+
* `filter.after`, when set, resumes a broadcast partway through (see
|
|
508
|
+
* {@link runPushBroadcastPage}'s continuation semantics).
|
|
380
509
|
*/
|
|
381
510
|
interface PushBroadcastJob {
|
|
382
|
-
/** Subscription filter (which devices/users to target). */
|
|
511
|
+
/** Subscription filter (which devices/users to target; `filter.after` resumes a paged broadcast). */
|
|
383
512
|
filter?: SubscriptionFilter;
|
|
384
513
|
/** The push payload to deliver (the `to` target is derived per subscription). */
|
|
385
514
|
payload: PushContent;
|
|
515
|
+
/**
|
|
516
|
+
* Redeliver to exactly these subscription ids instead of walking a page —
|
|
517
|
+
* an earlier page's {@link PushBroadcastPageOutcome.failedIds}. Set by the
|
|
518
|
+
* consumer when it re-enqueues a page's transient failures; `filter` is
|
|
519
|
+
* ignored on such a job. See {@link runPushBroadcastPage}.
|
|
520
|
+
*/
|
|
521
|
+
retryIds?: string[];
|
|
386
522
|
/** Discriminator so a shared queue can multiplex message kinds. */
|
|
387
523
|
type: "lunora.push.broadcast";
|
|
388
524
|
}
|
|
389
|
-
/**
|
|
525
|
+
/**
|
|
526
|
+
* One page's outcome plus the ids that need redelivering.
|
|
527
|
+
*
|
|
528
|
+
* The consumer MUST act on BOTH fields: `nextCursor` continues the broadcast and
|
|
529
|
+
* `failedIds` redelivers the recipients this page missed. Acking a message while
|
|
530
|
+
* ignoring either silently drops part of the audience.
|
|
531
|
+
*/
|
|
532
|
+
interface PushBroadcastPageOutcome extends BroadcastPageResult {
|
|
533
|
+
/**
|
|
534
|
+
* Subscriptions that failed transiently on this run (gone/pruned devices are
|
|
535
|
+
* NOT here — they are deleted, not retried). Re-enqueue a job carrying these
|
|
536
|
+
* as `retryIds` to redeliver to just them.
|
|
537
|
+
*/
|
|
538
|
+
failedIds: string[];
|
|
539
|
+
}
|
|
540
|
+
/** The structural slice of a `@lunora/queue` producer (`ctx.queues.<name>`) used here. */
|
|
390
541
|
interface QueueProducerLike {
|
|
391
542
|
send: (body: PushBroadcastJob) => Promise<void>;
|
|
392
543
|
}
|
|
393
544
|
/**
|
|
394
545
|
* Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
|
|
395
|
-
* queue instead of blocking the request. Pair with {@link
|
|
396
|
-
* the queue consumer
|
|
546
|
+
* queue instead of blocking the request. Pair with {@link runPushBroadcastPage} in
|
|
547
|
+
* the queue consumer — see its doc comment for how a large audience continues
|
|
548
|
+
* across MULTIPLE messages (one bounded page per message), not one.
|
|
397
549
|
*
|
|
398
550
|
* ```ts
|
|
399
551
|
* // in a mutation/action:
|
|
@@ -401,17 +553,62 @@ interface QueueProducerLike {
|
|
|
401
553
|
*
|
|
402
554
|
* // in lunora/queues.ts consumer:
|
|
403
555
|
* export const push = defineQueue({ async handler(batch, ctx) {
|
|
404
|
-
* for (const message of batch.messages)
|
|
556
|
+
* for (const message of batch.messages) {
|
|
557
|
+
* const { failedIds, nextCursor } = await runPushBroadcastPage(ctx.push, message.body);
|
|
558
|
+
*
|
|
559
|
+
* if (nextCursor !== undefined) {
|
|
560
|
+
* // More pages remain — enqueue the continuation. Each message still
|
|
561
|
+
* // does only ONE bounded page of work.
|
|
562
|
+
* await enqueuePushBroadcast(ctx.queues.push, {
|
|
563
|
+
* payload: message.body.payload,
|
|
564
|
+
* filter: { ...message.body.filter, after: nextCursor },
|
|
565
|
+
* });
|
|
566
|
+
* }
|
|
567
|
+
*
|
|
568
|
+
* if (failedIds.length > 0) {
|
|
569
|
+
* // Redeliver ONLY the recipients that failed — never the whole page.
|
|
570
|
+
* await enqueuePushBroadcast(ctx.queues.push, { payload: message.body.payload, retryIds: failedIds });
|
|
571
|
+
* }
|
|
572
|
+
*
|
|
573
|
+
* message.ack();
|
|
574
|
+
* }
|
|
405
575
|
* }});
|
|
406
576
|
* ```
|
|
407
577
|
*/
|
|
408
578
|
declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
|
|
409
579
|
/**
|
|
410
|
-
* Run an enqueued broadcast job on the consumer side,
|
|
411
|
-
*
|
|
412
|
-
* gone
|
|
580
|
+
* Run ONE bounded page of an enqueued broadcast job on the consumer side,
|
|
581
|
+
* delivering through the push facade's {@link LunoraPush.broadcastPage} (which
|
|
582
|
+
* reuses the engine's retry + circuit-breaker middleware and prunes gone
|
|
583
|
+
* subscriptions).
|
|
584
|
+
*
|
|
585
|
+
* RETRY / CONTINUATION SEMANTICS:
|
|
586
|
+
*
|
|
587
|
+
* - A job processes exactly ONE bounded page (see `CreateNotifyOptions`'s
|
|
588
|
+
* page-size option, default 250, or `job.filter.limit` when smaller),
|
|
589
|
+
* keyset-paginated on the subscription `id` (see `SubscriptionFilter.after`)
|
|
590
|
+
* — so per-message work is bounded regardless of total audience size.
|
|
591
|
+
* - A page NEVER throws for a partial failure. Throwing discarded the page's
|
|
592
|
+
* `nextCursor`, which is the only way the broadcast advances: one device that
|
|
593
|
+
* fails permanently (a rotated VAPID keypair leaves a stale device answering
|
|
594
|
+
* `403 VapidPkHashMismatch` forever) would then stall the cursor, re-POST
|
|
595
|
+
* every already-delivered recipient on each retry, dead-letter, and leave
|
|
596
|
+
* every LATER page unreached. The page's `nextCursor` and its `failedIds`
|
|
597
|
+
* both come back instead.
|
|
598
|
+
* - The CALLER (the `lunora/queues.ts` consumer) re-enqueues: `filter.after:
|
|
599
|
+
* nextCursor` while more pages remain, and a `retryIds: failedIds` job when
|
|
600
|
+
* any recipient failed. `@lunora/notify` cannot do it itself — it has no
|
|
601
|
+
* `@lunora/queue` dependency (the seam stays structural) and no reference to
|
|
602
|
+
* the producer that enqueued this message. See the consumer example on
|
|
603
|
+
* {@link enqueuePushBroadcast}.
|
|
604
|
+
* - A `retryIds` job redelivers to exactly those ids and DOES throw while any
|
|
605
|
+
* of them still fails, so the queue's backoff/dead-letter bounds it. That
|
|
606
|
+
* message contains no already-delivered recipient, so nothing is re-sent.
|
|
607
|
+
* - Gone subscriptions (404/410, FCM `UNREGISTERED`) are pruned by the page and
|
|
608
|
+
* never appear in `failedIds` — an all-`pruned` page is a success, not a
|
|
609
|
+
* failure, as is an empty page.
|
|
413
610
|
*/
|
|
414
|
-
declare const
|
|
611
|
+
declare const runPushBroadcastPage: (push: LunoraPush, job: PushBroadcastJob) => Promise<PushBroadcastPageOutcome>;
|
|
415
612
|
/**
|
|
416
613
|
* The minimal structural slice of Cloudflare's `D1Database` this store uses. A
|
|
417
614
|
* structural type (rather than importing `@cloudflare/workers-types`) keeps the
|
|
@@ -438,6 +635,15 @@ interface D1StoreOptions {
|
|
|
438
635
|
* backing table is created lazily on first use (`CREATE TABLE IF NOT EXISTS`), so
|
|
439
636
|
* no migration step is required for the subscription table itself.
|
|
440
637
|
*
|
|
638
|
+
* ID SCHEME / LAZY MIGRATION: `id` (the `PRIMARY KEY`, upserted via `ON
|
|
639
|
+
* CONFLICT(id) DO UPDATE`) is a version-prefixed digest of the endpoint/token —
|
|
640
|
+
* currently `wp2_`/`fcm2_` (64-bit FNV-1a; see `normalize.ts`). No table migration
|
|
641
|
+
* runs when the id scheme is revised: a returning device re-registers under its new
|
|
642
|
+
* id and upserts a fresh row, while its old-prefix row (`wp_`/`fcm_`) ages out via
|
|
643
|
+
* the normal gone-pruning on the next failed send. So a table can transiently hold
|
|
644
|
+
* both an old- and new-prefix row for one device — expected, self-healing, and the
|
|
645
|
+
* reason a prefix must NEVER be reused for a different scheme.
|
|
646
|
+
*
|
|
441
647
|
* ```ts
|
|
442
648
|
* export default defineNotify({
|
|
443
649
|
* webPush: (env) => webPushFromEnv(env),
|
|
@@ -453,16 +659,43 @@ declare const d1SubscriptionStore: (database: D1Like, options?: D1StoreOptions)
|
|
|
453
659
|
* (or another backing store) for production so subscriptions survive restarts.
|
|
454
660
|
*/
|
|
455
661
|
declare const memorySubscriptionStore: () => SubscriptionStore;
|
|
456
|
-
/**
|
|
662
|
+
/**
|
|
663
|
+
* Stable store id for a web-push endpoint.
|
|
664
|
+
*
|
|
665
|
+
* The `wp2_` prefix is a version tag (see also {@link fcmId}'s `fcm2_`): it marks
|
|
666
|
+
* the 64-bit-id revision so the pre-existing 32-bit `wp_` rows stay readable and a
|
|
667
|
+
* returning device simply re-registers under the new id, its stale `wp_` row aging
|
|
668
|
+
* out via normal gone-pruning. A future third revision must mint `wp3_` and repeat
|
|
669
|
+
* the lazy migration — NEVER reuse a prefix.
|
|
670
|
+
*/
|
|
457
671
|
declare const webPushId: (endpoint: string) => string;
|
|
458
|
-
/** Stable store id for an FCM device token. */
|
|
672
|
+
/** Stable store id for an FCM device token. See {@link webPushId} for the `_2` version-prefix contract. */
|
|
459
673
|
declare const fcmId: (token: string) => string;
|
|
674
|
+
/** Options threaded into {@link normalizeRegisterInput} from the notify definition. */
|
|
675
|
+
interface NormalizeOptions {
|
|
676
|
+
/**
|
|
677
|
+
* Exact origins (`https://host[:port]`) a web-push endpoint may register from.
|
|
678
|
+
* When set (non-empty), the endpoint's origin must be one of these — the
|
|
679
|
+
* strongest anti-SSRF posture, and the ONLY way to close DNS rebinding for a
|
|
680
|
+
* facade that accepts client-controlled endpoints.
|
|
681
|
+
*
|
|
682
|
+
* When unset, the default posture applies: `https:` scheme + a host the
|
|
683
|
+
* {@link assertPushEndpoint} STRING classifier does not flag as
|
|
684
|
+
* private/loopback, plus a resolved-address re-check at send time. Setting
|
|
685
|
+
* this allowlist replaces both with an exact-origin match — the hard
|
|
686
|
+
* guarantee, and the only one that also covers an internal push service you
|
|
687
|
+
* deliberately want to reach.
|
|
688
|
+
*/
|
|
689
|
+
allowedPushOrigins?: string[];
|
|
690
|
+
}
|
|
460
691
|
/**
|
|
461
692
|
* Normalise a `register(...)` input into a {@link StoredSubscription}. Validates
|
|
462
693
|
* the shape (a web-push subscription needs `endpoint` + `keys.{p256dh,auth}`; an
|
|
463
|
-
* FCM entry needs a non-empty `token`)
|
|
694
|
+
* FCM entry needs a non-empty `token`), enforces the anti-SSRF endpoint boundary
|
|
695
|
+
* (see {@link assertPushEndpoint}), validates `metadata` (see
|
|
696
|
+
* {@link validateMetadata}), and stamps `createdAt`/`lastSeenAt`.
|
|
464
697
|
*/
|
|
465
|
-
declare const normalizeRegisterInput: (input: RegisterInput, now?: number) => StoredSubscription;
|
|
698
|
+
declare const normalizeRegisterInput: (input: RegisterInput, now?: number, options?: NormalizeOptions) => StoredSubscription;
|
|
466
699
|
/**
|
|
467
700
|
* The provider `to` target for a stored subscription: the W3C Push subscription
|
|
468
701
|
* (JSON-stringified) for web-push, or the raw device token for FCM. Matches the
|
|
@@ -481,4 +714,80 @@ declare const targetOf: (subscription: StoredSubscription) => string;
|
|
|
481
714
|
* (a cert/session expiry) can never permanently drop a valid subscription.
|
|
482
715
|
*/
|
|
483
716
|
declare const isGoneError: (message: string | undefined) => boolean;
|
|
484
|
-
export { type BroadcastOutcome, type BroadcastResult, type CreateNotifyOptions, type D1Like, type D1PreparedLike, type D1StoreOptions,
|
|
717
|
+
export { type BroadcastOutcome, type BroadcastResult, type CreateNotifyOptions, type D1Like, type D1PreparedLike, type D1StoreOptions,
|
|
718
|
+
/**
|
|
719
|
+
* `@lunora/notify`
|
|
720
|
+
*
|
|
721
|
+
* Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
|
|
722
|
+
* engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
|
|
723
|
+
* (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
|
|
724
|
+
* and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
|
|
725
|
+
* → `ctx.flags`).
|
|
726
|
+
*
|
|
727
|
+
* Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
|
|
728
|
+
* Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
|
|
729
|
+
* deliberately **not** on the edge facade — route heavy fan-out through
|
|
730
|
+
* `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
|
|
731
|
+
*
|
|
732
|
+
* - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
|
|
733
|
+
* - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
|
|
734
|
+
* @packageDocumentation
|
|
735
|
+
*/
|
|
736
|
+
FCM_ENV_KEYS, type FcmConfigFactory, type LunoraNotify, type LunoraPush, type NotifyConfig, type NotifyDefinition, type NotifyDeliveryStatus, type NotifyEnv, type NotifyLogger, type NotifyMetrics, type NotifySkipReason, type PushBroadcastJob, type PushBroadcastPageOutcome, type PushSubscriptionDevice, type PushSubscriptionsResult, type QueueProducerLike, type RegisterInput, type ResolvedProviders, type RoutingPushOptions, type StoredSubscription, type SubscriptionFilter, type SubscriptionKind, type SubscriptionStatus, type SubscriptionStore,
|
|
737
|
+
/**
|
|
738
|
+
* `@lunora/notify`
|
|
739
|
+
*
|
|
740
|
+
* Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
|
|
741
|
+
* engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
|
|
742
|
+
* (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
|
|
743
|
+
* and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
|
|
744
|
+
* → `ctx.flags`).
|
|
745
|
+
*
|
|
746
|
+
* Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
|
|
747
|
+
* Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
|
|
748
|
+
* deliberately **not** on the edge facade — route heavy fan-out through
|
|
749
|
+
* `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
|
|
750
|
+
*
|
|
751
|
+
* - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
|
|
752
|
+
* - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
|
|
753
|
+
* @packageDocumentation
|
|
754
|
+
*/
|
|
755
|
+
WEB_PUSH_ENV_KEYS, type WebPushConfigFactory, buildEngine, createNotify, d1SubscriptionStore, defineNotify, enqueuePushBroadcast,
|
|
756
|
+
/**
|
|
757
|
+
* `@lunora/notify`
|
|
758
|
+
*
|
|
759
|
+
* Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
|
|
760
|
+
* engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
|
|
761
|
+
* (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
|
|
762
|
+
* and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
|
|
763
|
+
* → `ctx.flags`).
|
|
764
|
+
*
|
|
765
|
+
* Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
|
|
766
|
+
* Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
|
|
767
|
+
* deliberately **not** on the edge facade — route heavy fan-out through
|
|
768
|
+
* `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
|
|
769
|
+
*
|
|
770
|
+
* - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
|
|
771
|
+
* - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
|
|
772
|
+
* @packageDocumentation
|
|
773
|
+
*/
|
|
774
|
+
fcmFromEnv, fcmId, isGoneError, isNotifyDefinition, memorySubscriptionStore, normalizeRegisterInput, routingPushProvider, runPushBroadcastPage, targetOf,
|
|
775
|
+
/**
|
|
776
|
+
* `@lunora/notify`
|
|
777
|
+
*
|
|
778
|
+
* Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
|
|
779
|
+
* engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
|
|
780
|
+
* (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
|
|
781
|
+
* and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
|
|
782
|
+
* → `ctx.flags`).
|
|
783
|
+
*
|
|
784
|
+
* Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
|
|
785
|
+
* Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
|
|
786
|
+
* deliberately **not** on the edge facade — route heavy fan-out through
|
|
787
|
+
* `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastPage`).
|
|
788
|
+
*
|
|
789
|
+
* - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
|
|
790
|
+
* - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
|
|
791
|
+
* @packageDocumentation
|
|
792
|
+
*/
|
|
793
|
+
webPushFromEnv, webPushId };
|
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { defineNotify, isNotifyDefinition } from './packem_shared/defineNotify-B6S_47C2.mjs';
|
|
3
|
-
export { createNotify } from './packem_shared/createNotify-bDWs4qBm.mjs';
|
|
4
|
-
export { buildEngine, routingPushProvider } from './packem_shared/buildEngine-DlmjvnNk.mjs';
|
|
5
|
-
export { enqueuePushBroadcast, runPushBroadcastJob } from './packem_shared/enqueuePushBroadcast-DiK7Hyja.mjs';
|
|
6
|
-
export { d1SubscriptionStore } from './packem_shared/d1SubscriptionStore-Dv3VPMI_.mjs';
|
|
7
|
-
export { memorySubscriptionStore } from './packem_shared/memorySubscriptionStore-DhS-YnLe.mjs';
|
|
8
|
-
export { fcmId, isGoneError, normalizeRegisterInput, targetOf, webPushId } from './packem_shared/fcmId-B-YPgHi7.mjs';
|
|
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-BbhPScGH.mjs";import{defineNotify as n,isNotifyDefinition as u}from"./packem_shared/defineNotify-CUi2k7pP.mjs";import{createNotify as p}from"./packem_shared/createNotify-BDE42tvH.mjs";import{buildEngine as a,routingPushProvider as d}from"./packem_shared/buildEngine-oDWs9Pom.mjs";import{enqueuePushBroadcast as P,runPushBroadcastPage as c}from"./packem_shared/enqueuePushBroadcast-B6v3DLLp.mjs";import{d1SubscriptionStore as b}from"./packem_shared/d1SubscriptionStore-s-AJH4hS.mjs";import{memorySubscriptionStore as h}from"./packem_shared/memorySubscriptionStore-FY8yANEM.mjs";import{fcmId as _,isGoneError as y,normalizeRegisterInput as v,targetOf as B,webPushId as F}from"./packem_shared/fcmId-Dwh_R5xe.mjs";export{e as FCM_ENV_KEYS,t as WEB_PUSH_ENV_KEYS,a as buildEngine,p as createNotify,b as d1SubscriptionStore,n as defineNotify,P as enqueuePushBroadcast,i as fcmFromEnv,_ as fcmId,y as isGoneError,u as isNotifyDefinition,h as memorySubscriptionStore,v as normalizeRegisterInput,d as routingPushProvider,c as runPushBroadcastPage,B as targetOf,f as webPushFromEnv,F as webPushId};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r={privateKey:"VAPID_PRIVATE_KEY",publicKey:"VAPID_PUBLIC_KEY",subject:"VAPID_SUBJECT"},i={accessToken:"FCM_ACCESS_TOKEN",projectId:"FCM_PROJECT_ID"},t=(c,o)=>{const e=c[o];return typeof e=="string"&&e!==""?e:void 0},d=(c,o)=>{const e=t(c,r.publicKey),s=t(c,r.privateKey),n=t(c,r.subject);if(!(e===void 0||s===void 0||n===void 0))return{vapidPrivateKey:s,vapidPublicKey:e,vapidSubject:n,...o}},E=(c,o)=>{const e=t(c,i.projectId);return e===void 0?void 0:{accessToken:t(c,i.accessToken),projectId:e,...o}};export{i as FCM_ENV_KEYS,r as WEB_PUSH_ENV_KEYS,E as fcmFromEnv,d as webPushFromEnv};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as k}from"@lunora/errors";import{createNotification as A}from"@visulima/notification";import{retryMiddleware as E,circuitBreakerMiddleware as I}from"@visulima/notification/middleware";import{fcmProvider as R}from"@visulima/notification/providers/fcm";import{webPushProvider as T}from"@visulima/notification/providers/web-push";import{n as D,p as h,a as _,b as S}from"./ssrf-host-BCpHorGa.mjs";const N=(e,n)=>{if(e.size<n)return;const t=e.keys().next().value;t!==void 0&&e.delete(t)},O="https://cloudflare-dns.com/dns-query",u=1,l=28,C=2e3,M=(e,n)=>{if(n===u){const t=h(e);return t===void 0||_(t)}return S(e.toLowerCase())},f=async(e,n,t)=>{try{const r=await fetch(`${O}?name=${encodeURIComponent(e)}&type=${String(n)}`,{headers:{accept:"application/dns-json"},signal:AbortSignal.timeout(t)});return r.ok?(await r.json()).Answer??[]:void 0}catch{return}},z=async(e,n=C)=>{const t=D(e);if(t.includes(":")||h(t)!==void 0)return{kind:"unknown"};const[r,i]=await Promise.all([f(t,u,n),f(t,l,n)]);if(r===void 0&&i===void 0)return{kind:"unknown"};for(const o of[...r??[],...i??[]])if((o.type===u||o.type===l)&&M(o.data,o.type))return{address:o.data,kind:"private"};return{kind:"public"}},$=e=>{let n=e;if(typeof e=="string"){if(!e.startsWith("{"))return;try{n=JSON.parse(e)}catch{return}}const t=n?.endpoint;return typeof t=="string"?t:void 0},d=new Map,j=256,H=async(e,n)=>{if(n!==void 0&&n.length>0)return;let t;try{({hostname:t}=new URL(e))}catch{return}const r=d.get(t),i=r??z(t),o=await i;if(r===void 0&&o.kind!=="unknown"&&(N(d,j),d.set(t,i)),o.kind==="private")throw new k("FORBIDDEN",`@lunora/notify: web-push endpoint host "${t}" resolves to a private/internal address (${o.address}); refusing to send (DNS-rebinding guard)`)},L=(e,n)=>{const t=[e.provider,n.provider].filter(i=>i!==void 0),r=[...e.recipients??[],...n.recipients??[]];return{...e,messageId:[e.messageId,n.messageId].join(","),response:[e.response,n.response],sent:e.sent&&n.sent,timestamp:new Date(Math.max(e.timestamp.getTime(),n.timestamp.getTime())),...t.length>0?{provider:t.join(",")}:{},...r.length>0?{recipients:r}:{}}},x=(e,n)=>{if(!e.success||!n.success)return e.success||n.success?e.success?n:e:{error:new AggregateError([e.error,n.error],"@lunora/notify: both push target groups failed"),success:!1};const t=e.data===void 0||n.data===void 0?e.data??n.data:L(e.data,n.data);return t===void 0?{success:!0}:{data:t,success:!0}},B=e=>{const n=t=>{const r=t===void 0?e.fcm:e.webPush;if(r===void 0)throw new Error(t===void 0?"@lunora/notify: received an FCM token target but no `fcm` channel is configured":"@lunora/notify: received a web-push target but no `webPush` channel is configured");return r};return{channel:"push",id:"lunora-push-router",initialize:async()=>{await e.webPush?.initialize(),await e.fcm?.initialize()},isAvailable:()=>(e.webPush??e.fcm)!==void 0,send:async t=>{const r=Array.isArray(t.to)?t.to:[t.to],i=r.map(s=>$(s));for(const s of i)s!==void 0&&await H(s,e.allowedPushOrigins);const o=r.filter((s,a)=>i[a]!==void 0),p=r.filter((s,a)=>i[a]===void 0),c=i.find(s=>s!==void 0);if(p.length===0&&c!==void 0)return n(c).send(t);if(o.length===0)return n(void 0).send(t);const m=s=>({...t,to:s.length===1&&s[0]!==void 0?s[0]:s}),w=n(c),g=n(void 0),v=async(s,a)=>s.send(m(a)),b=await Promise.allSettled([v(w,o),v(g,p)]),[P,y]=b.map(s=>s.status==="fulfilled"?s.value:{error:s.reason,success:!1});return x(P,y)}}},J=e=>{const n=e.webPush===void 0?void 0:T(e.webPush),t=e.fcm===void 0?void 0:R(e.fcm),r={};(n!==void 0||t!==void 0)&&(r.push=B({allowedPushOrigins:e.allowedPushOrigins,fcm:t,webPush:n})),e.chat!==void 0&&(r.chat=e.chat),e.inApp!==void 0&&(r.inapp=e.inApp),e.webhook!==void 0&&(r.webhook=e.webhook);const i=A(r);return i.use(E()).use(I()),i};export{J as buildEngine,B as routingPushProvider};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{buildEngine as F}from"./buildEngine-oDWs9Pom.mjs";import{memorySubscriptionStore as R}from"./memorySubscriptionStore-FY8yANEM.mjs";import{normalizeRegisterInput as z,targetOf as B,isGoneError as L}from"./fcmId-Dwh_R5xe.mjs";const W=250,w=(s,l)=>typeof s=="function"?s(l):s,S=s=>s.successful?void 0:s.errorMessages.join("; "),U=(s,l)=>s.successful?"accepted":L(l)?"gone":"failed",j=async(s,l,d)=>{const u=Array.from({length:s.length});let h=0;const g=async()=>{for(;h<s.length;){const f=h;h+=1,u[f]=await d(s[f])}};return await Promise.all(Array.from({length:Math.min(l,s.length)},()=>g())),u},G=(s,l)=>({allowedPushOrigins:s.allowedPushOrigins,chat:w(s.chat,l),fcm:w(s.fcm,l),inApp:w(s.inApp,l),webhook:w(s.webhook,l),webPush:w(s.webPush,l)}),x=new WeakMap,Q=(s,l)=>{let d=x.get(s);d===void 0&&(d=new WeakMap,x.set(s,d));let u=d.get(l);return u===void 0&&(u={warnedNoPushOriginAllowlist:!1,warnedNoStore:!1},d.set(l,u)),u},Y=(s,l,d={})=>{const u=Q(s,l);let h;d.engine===void 0?(u.engine??=F(G(s,l)),h=u.engine):h=d.engine,u.store??=s.store?.(l);let{store:g}=u;g===void 0&&(u.fallbackStore??=R(),!d.silent&&!u.warnedNoStore&&(u.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=u.fallbackStore);const f=g,C=Math.max(1,d.concurrency??10),b=Math.max(1,d.broadcastPageSize??W),{log:M,metrics:P}=d,p=(e,t,r,n=1)=>{P?.count("notify.send",n,{channel:e,provider:t??e,status:r})},y=(e,t,r)=>{M?.warn(`notify ${e} delivery failed`,{channel:e,provider:t??e,status:"failed",...r})},A=(e,t)=>{P?.count("notify.skipped",1,{channel:e,reason:t})},I=()=>{const e=s.allowedPushOrigins!==void 0&&s.allowedPushOrigins.length>0;d.silent||e||u.warnedNoPushOriginAllowlist||(u.warnedNoPushOriginAllowlist=!0,console.warn("@lunora/notify: Web Push registered without `allowedPushOrigins` — endpoints are guarded by a string classifier at register time and a best-effort DNS re-check at send time, both of which are defeatable. Set `allowedPushOrigins` to the exact push-service origins for a hard guarantee."))},T=async e=>(await f.list(e)).map(({keys:r,token:n,...a})=>a),_=async e=>{if(typeof e!="string")return e;const t=await f.get(e);if(t===void 0)throw new v("BAD_REQUEST",`@lunora/notify: no registered subscription with id "${e}"`);return t},E=async(e,t,r)=>{let n,a,o;try{n=await h.sendToChannel("push",{...t,to:B(e)}),a=S(n),o=U(n,a)}catch(c){o="failed",a=c instanceof Error?c.message:String(c)}try{o==="accepted"?await f.markStatus(e.id,"ok"):o==="gone"?await f.delete(e.id):await f.markStatus(e.id,"failed",a)}catch{}return o==="failed"&&y("push",e.kind,{error:a,subscriptionId:e.id,userId:e.userId??null}),r&&p("push",e.kind,o),{error:a,receipt:n,status:o}},D=async(e,t)=>{const r=await j(t,C,async o=>{const{error:c,status:i}=await E(o,e,!1);return{error:c,kind:o.kind,status:i,subscription:o}}),n=new Map;for(const{kind:o,status:c}of r){const i=`${o} ${c}`,m=n.get(i);m===void 0?n.set(i,{count:1,kind:o,status:c}):m.count+=1}for(const{count:o,kind:c,status:i}of n.values())p("push",c,i,o);const a=r.map(({error:o,status:c,subscription:i})=>c==="accepted"?{id:i.id,status:"ok"}:c==="gone"?{error:o,id:i.id,status:"expired"}:{error:o,id:i.id,status:"failed"});return{failed:a.filter(o=>o.status==="failed").length,outcomes:a,pruned:a.filter(o=>o.status==="expired").length,sent:a.filter(o=>o.status==="ok").length,total:a.length}},O=async(e,t)=>{if(t?.limit!==void 0&&t.limit<=0)return{nextCursor:void 0,result:{failed:0,outcomes:[],pruned:0,sent:0,total:0}};const r=t?.limit!==void 0&&t.limit>0?Math.trunc(t.limit):void 0,n=r===void 0?b:Math.min(r,b),a=await f.list({after:t?.after,kind:t?.kind,limit:n+1,userId:t?.userId}),o=t?.after===void 0?a:a.filter($=>$.id>t.after),c=o.length>n,i=c?o.slice(0,n):o;i.length===0&&t?.after===void 0&&A("push","no-subscriptions-matched");const m=await D(e,i);return{nextCursor:c?i[i.length-1]?.id:void 0,result:m}},N={broadcast:async(e,t)=>{const r={failed:0,outcomes:[],pruned:0,sent:0,total:0};let n=t?.after;const a=t?.limit;if(a!==void 0&&a<=0)return r;for(;;){const o=a===void 0?{...t,after:n}:{...t,after:n,limit:a-r.total},{nextCursor:c,result:i}=await O(e,o);if(r.failed+=i.failed,r.pruned+=i.pruned,r.sent+=i.sent,r.total+=i.total,r.outcomes.push(...i.outcomes),a!==void 0&&r.total>=a||c===void 0||c===n)break;n=c}return r},broadcastPage:O,list:e=>T(e),register:e=>("token"in e||I(),f.put(z(e,void 0,{allowedPushOrigins:s.allowedPushOrigins}))),send:async(e,t)=>{const{error:r,receipt:n}=await E(await _(e),t,!0);if(n===void 0)throw new v("INTERNAL",`@lunora/notify: push send failed: ${r??"unknown error"}`);return n},unregister:e=>f.delete(e)},k=async(e,t)=>{if(h.getProvider(e)===void 0)throw A(e,"channel-not-configured"),new v("BAD_REQUEST",`@lunora/notify: the "${e}" channel is not configured in defineNotify(...)`);const r=await h.sendToChannel(e,t),n=r.successful?"accepted":"failed";return p(e,r.provider,n),n==="failed"&&y(e,r.provider,{error:S(r)}),r};return{notify:{chat:e=>k("chat",e),inApp:e=>k("inapp",e),push:N,send:async e=>{const t=await h.send(e);for(const r of t){const n=r.channel??"unknown",a=r.successful?"accepted":"failed";p(n,r.provider,a),a==="failed"&&y(n,r.provider,{error:S(r)})}return t},webhook:e=>k("webhook",e)},push:N}};export{Y as createNotify};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{legacyIdFor as S}from"./fcmId-Dwh_R5xe.mjs";const c=e=>/^[A-Z_]\w*$/i.test(e),E=e=>{const i={createdAt:e.created_at,id:e.id,kind:e.kind,lastSeenAt:e.last_seen_at,userId:e.user_id};if(e.endpoint!==null&&(i.endpoint=e.endpoint),e.p256dh!==null&&e.auth!==null&&(i.keys={auth:e.auth,p256dh:e.p256dh}),e.token!==null&&(i.token=e.token),e.last_status!==null&&(i.lastStatus=e.last_status),e.last_error!==null&&(i.lastError=e.last_error),e.metadata!==null)try{i.metadata=JSON.parse(e.metadata)}catch{}return i},O=(e,i={})=>{const n=i.tableName??"lunora_push_subscriptions";if(!c(n))throw new p("BAD_REQUEST",`@lunora/notify: d1SubscriptionStore tableName "${n}" is not a bare SQL identifier`);let r;const s=()=>(r===void 0&&(r=e.prepare(`CREATE TABLE IF NOT EXISTS ${n} (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(()=>e.prepare(`CREATE INDEX IF NOT EXISTS ${n}_user_id_idx ON ${n} (user_id)`).run()).then(()=>e.prepare(`CREATE INDEX IF NOT EXISTS ${n}_kind_idx ON ${n} (kind)`).run()).then(()=>{}),r.catch(()=>{r=void 0})),r),l=async t=>{await s();const a=await e.prepare(`SELECT * FROM ${n} WHERE id = ?1`).bind(t).first();return a===null?void 0:E(a)};return{delete:async t=>{await s(),await e.prepare(`DELETE FROM ${n} WHERE id = ?1`).bind(t).run()},get:l,list:async t=>{await s();const a=[],d=[];t?.kind!==void 0&&(d.push(t.kind),a.push(`kind = ?${d.length.toString()}`)),t?.userId!==void 0&&(t.userId===null?a.push("user_id IS NULL"):(d.push(t.userId),a.push(`user_id = ?${d.length.toString()}`))),t?.after!==void 0&&(d.push(t.after),a.push(`id > ?${d.length.toString()}`));const o=a.length===0?"":` WHERE ${a.join(" AND ")}`,T=" ORDER BY id ASC";let u="";t?.limit!==void 0&&t.limit>0&&(d.push(Math.trunc(t.limit)),u=` LIMIT ?${d.length.toString()}`);const{results:_}=await e.prepare(`SELECT * FROM ${n}${o}${T}${u}`).bind(...d).all();return _.map(h=>E(h))},markStatus:async(t,a,d)=>{await s(),await e.prepare(`UPDATE ${n} SET last_status = ?2, last_error = ?3, last_seen_at = ?4 WHERE id = ?1`).bind(t,a,d??null,Date.now()).run()},put:async t=>{await s(),await e.prepare(`INSERT INTO ${n} (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 a=S(t);return a!==void 0&&a!==t.id&&await e.prepare(`DELETE FROM ${n} WHERE id = ?1`).bind(a).run(),await l(t.id)??t}}};export{O as d1SubscriptionStore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=e=>{if(e.webPush!==void 0&&typeof e.webPush!="function"&&typeof e.webPush!="object")throw new TypeError("defineNotify: `webPush` must be a WebPushConfig object or an `(env) => WebPushConfig` function");if(e.fcm!==void 0&&typeof e.fcm!="function"&&typeof e.fcm!="object")throw new TypeError("defineNotify: `fcm` must be an FcmConfig object or an `(env) => FcmConfig` function");if(e.store!==void 0&&typeof e.store!="function")throw new TypeError("defineNotify: `store` must be a function `(env) => SubscriptionStore` when provided");if(e.allowedPushOrigins!==void 0&&(!Array.isArray(e.allowedPushOrigins)||e.allowedPushOrigins.some(o=>typeof o!="string")))throw new TypeError('defineNotify: `allowedPushOrigins` must be an array of origin strings (e.g. ["https://fcm.googleapis.com"]) when provided');if(e.webPush===void 0&&e.fcm===void 0)throw new TypeError("defineNotify: configure at least one push channel — `webPush` and/or `fcm`");return{...e,isLunoraNotify:!0}},r=e=>typeof e=="object"&&e!==null&&e.isLunoraNotify===!0;export{t as defineNotify,r as isNotifyDefinition};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";const u=e=>e.filter(t=>t.status==="failed").map(t=>t.id),h=(e,t)=>e.send({...t,type:"lunora.push.broadcast"}),c=async(e,t,s)=>{const r=[];for(const a of s)try{const o=await e.send(a,t);r.push({id:a,status:o.successful?"ok":"failed"})}catch(o){r.push({error:o instanceof Error?o.message:String(o),id:a,status:"failed"})}const n=u(r),d=r.length-n.length,l={failed:n.length,outcomes:r,pruned:0,sent:d,total:r.length};if(n.length>0)throw new i("INTERNAL",`@lunora/notify: push retry failed for ${n.length.toString()} of ${r.length.toString()} subscription(s) — throwing so the queue retries and eventually dead-letters them`);return{failedIds:n,nextCursor:void 0,result:l}},g=async(e,t)=>{if(t.retryIds!==void 0&&t.retryIds.length>0)return c(e,t.payload,t.retryIds);const s=await e.broadcastPage(t.payload,t.filter);return{failedIds:u(s.result.outcomes),nextCursor:s.nextCursor,result:s.result}};export{h as enqueuePushBroadcast,g as runPushBroadcastPage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{i as A}from"./ssrf-host-BCpHorGa.mjs";const b=2166136261,_=16777619,m=(t,e=b)=>{let n=e;for(let o=0;o<t.length;o+=1)n^=t.codePointAt(o)??0,n=Math.imul(n,_);return(n>>>0).toString(16).padStart(8,"0")},f=4096,h=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 s("BAD_REQUEST","@lunora/notify: register() `metadata` must be a plain object");let o;try{o=JSON.stringify(t)}catch(i){throw new s("BAD_REQUEST",`@lunora/notify: register() \`metadata\` is not JSON-serialisable: ${i instanceof Error?i.message:String(i)}`)}const r=new TextEncoder().encode(o).length;if(r>f)throw new s("BAD_REQUEST",`@lunora/notify: register() \`metadata\` is ${r.toString()} bytes, exceeding the ${f.toString()}-byte cap`);return t},d=t=>t.toString(16).padStart(4,"0"),p=t=>{let e=8997,n=33826,o=40164,r=52210;for(let i=0;i<t.length;i+=1){const a=t.codePointAt(i)??0;e^=a&65535,n^=a>>>16&65535;const c=e*435,y=n*435,E=o*435+e*256,w=r*435+n*256,l=y+(c>>>16),u=E+(l>>>16),S=w+(u>>>16);e=c&65535,n=l&65535,o=u&65535,r=S&65535}return d(r)+d(o)+d(n)+d(e)},T=t=>`wp2_${p(t)}`,O=t=>`fcm2_${p(t)}`,g=t=>m(t),k=t=>`wp_${g(t)}`,v=t=>`fcm_${g(t)}`,U=t=>t.kind==="fcm"?t.token===void 0?void 0:v(t.token):t.endpoint===void 0?void 0:k(t.endpoint),R=t=>{if(typeof t!="string")return t??{};try{return JSON.parse(t)}catch(e){throw new s("BAD_REQUEST",`@lunora/notify: register() web-push subscription is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}},B=(t,e)=>{let n;try{n=new URL(t)}catch{throw new s("BAD_REQUEST",`@lunora/notify: register() web-push \`endpoint\` must be an absolute https URL (got "${t}")`)}if(n.protocol!=="https:")throw new s("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 s("FORBIDDEN",`@lunora/notify: register() web-push endpoint origin "${n.origin}" is not in the configured allowedPushOrigins allowlist`);return}if(A(n.hostname))throw new s("FORBIDDEN",`@lunora/notify: register() web-push endpoint host "${n.hostname}" is a private/internal address; configure allowedPushOrigins to permit a specific origin`)},x=(t,e=Date.now(),n={})=>{if("token"in t){const{token:c}=t;if(typeof c!="string"||c==="")throw new s("BAD_REQUEST","@lunora/notify: register() fcm input requires a non-empty `token`");return{createdAt:e,id:O(c),kind:"fcm",lastSeenAt:e,metadata:h(t.metadata),token:c,userId:t.userId??null}}const o=R(t.subscription),{endpoint:r}=o,i=o.keys?.p256dh,a=o.keys?.auth;if(typeof r!="string"||r===""||typeof i!="string"||typeof a!="string")throw new s("BAD_REQUEST","@lunora/notify: register() web-push subscription requires `endpoint` and `keys.{p256dh, auth}`");return B(r,n.allowedPushOrigins),{createdAt:e,endpoint:r,id:T(r),keys:{auth:a,p256dh:i},kind:"web-push",lastSeenAt:e,metadata:h(t.metadata),userId:t.userId??null}},F=t=>t.kind==="fcm"?t.token??"":JSON.stringify({endpoint:t.endpoint,keys:t.keys}),D=/\bhttp\s*4(?:04|10)\b/iu,I=/\b(?:unregistered|not[\s-]?registered|registration-token-not-registered)\b/iu,N=/\bsubscription (?:is )?(?:gone|expired|no longer valid)\b/iu,Q=t=>t===void 0?!1:D.test(t)||I.test(t)||N.test(t);export{O as fcmId,Q as isGoneError,v as legacyFcmId,U as legacyIdFor,k as legacyWebPushId,x as normalizeRegisterInput,F as targetOf,T as webPushId};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{legacyIdFor as n}from"./fcmId-Dwh_R5xe.mjs";const i=(t,e)=>t.id<e.id?-1:t.id>e.id?1:0,a=(t,e)=>e===void 0?!0:!(e.kind!==void 0&&t.kind!==e.kind||e.userId!==void 0&&(t.userId??null)!==e.userId),c=()=>{const t=new Map;return{delete:e=>(t.delete(e),Promise.resolve()),get:e=>Promise.resolve(t.get(e)),list:e=>{const r=[];for(const d of t.values())a(d,e)&&r.push(d);r.sort(i);const o=e?.after===void 0?r:r.filter(d=>d.id>e.after),s=e?.limit!==void 0&&e.limit>0?o.slice(0,Math.trunc(e.limit)):o;return Promise.resolve(s)},markStatus:(e,r,o)=>{const s=t.get(e);return s!==void 0&&t.set(e,{...s,lastError:o,lastSeenAt:Date.now(),lastStatus:r}),Promise.resolve()},put:e=>{const r=n(e);r!==void 0&&r!==e.id&&t.delete(r);const o=t.get(e.id),s=o===void 0?e:{...o,...e,createdAt:o.createdAt};return t.set(s.id,s),Promise.resolve(s)}}};export{c as memorySubscriptionStore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const u=/^\d{1,3}$/u,d=/^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u,p=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/u,l=/^::(\d{1,3}(?:\.\d{1,3}){3})$/u,P=/^::([\da-f]{1,4}):([\da-f]{1,4})$/u,h=/^64:ff9b::[\da-f]{1,4}:[\da-f]{1,4}$/u,v=/^\[|\]$/gu,I=/\.$/u,a=e=>{const t=e.split(".");if(t.length!==4)return;const s=t.map(r=>u.test(r)?Number(r):-1);if(!s.some(r=>r<0||r>255))return[s[0],s[1],s[2],s[3]]},o=([e,t])=>e===0||e===10||e===127||e===100&&t>=64&&t<=127||e===169&&t===254||e===172&&t>=16&&t<=31||e===192&&t===168||e>=224,f=(e,t)=>{const s=Number.parseInt(e??"",16),r=Number.parseInt(t??"",16);return!Number.isFinite(s)||!Number.isFinite(r)?!0:o([Math.floor(s/256),s%256,Math.floor(r/256),r%256])},m=e=>{const t=e.toLowerCase(),s=d.exec(t);if(s)return f(s[1],s[2]);const r=p.exec(t);if(r){const n=a(r[1]??"");return n===void 0||o(n)}const c=l.exec(t);if(c){const n=a(c[1]??"");return n===void 0||o(n)}const i=P.exec(t);return i?f(i[1],i[2]):h.test(t)||t.startsWith("2002:")||t.startsWith("2001:0:")?!0:t==="::"||t==="::1"||t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe8")||t.startsWith("fe9")||t.startsWith("fea")||t.startsWith("feb")},_=e=>e==="localhost"||e.endsWith(".localhost")||e.endsWith(".local")||e.endsWith(".internal")||e.endsWith(".home.arpa"),E=e=>e.replaceAll(v,"").replace(I,"").toLowerCase(),T=e=>{const t=E(e);if(t.includes(":"))return m(t);const s=a(t);return s===void 0?_(t):o(s)};export{o as a,m as b,T as i,E as n,a as p};
|
package/dist/web.d.mts
CHANGED
|
@@ -1,18 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `@lunora/notify/web` — the browser-side helper for registering a service-worker
|
|
3
|
-
* Web Push subscription. Runs in the browser (Push API + `navigator.serviceWorker`),
|
|
4
|
-
* has no server imports, and returns a plain, JSON-serialisable subscription you
|
|
5
|
-
* hand to a Lunora mutation calling `ctx.push.register({ subscription, userId })`.
|
|
6
|
-
*
|
|
7
|
-
* ```ts
|
|
8
|
-
* import { subscribeToPush } from "@lunora/notify/web";
|
|
9
|
-
*
|
|
10
|
-
* const subscription = await subscribeToPush({ serviceWorkerUrl: "/sw.js", vapidPublicKey });
|
|
11
|
-
* await client.mutation("registerDevice", { subscription });
|
|
12
|
-
* ```
|
|
13
|
-
* @packageDocumentation
|
|
14
|
-
*/
|
|
15
|
-
/** A plain, JSON-serialisable Web Push subscription (the shape `ctx.push.register` accepts). */
|
|
16
1
|
interface SerializedPushSubscription {
|
|
17
2
|
endpoint: string;
|
|
18
3
|
expirationTime: number | null;
|
package/dist/web.d.ts
CHANGED
|
@@ -1,18 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `@lunora/notify/web` — the browser-side helper for registering a service-worker
|
|
3
|
-
* Web Push subscription. Runs in the browser (Push API + `navigator.serviceWorker`),
|
|
4
|
-
* has no server imports, and returns a plain, JSON-serialisable subscription you
|
|
5
|
-
* hand to a Lunora mutation calling `ctx.push.register({ subscription, userId })`.
|
|
6
|
-
*
|
|
7
|
-
* ```ts
|
|
8
|
-
* import { subscribeToPush } from "@lunora/notify/web";
|
|
9
|
-
*
|
|
10
|
-
* const subscription = await subscribeToPush({ serviceWorkerUrl: "/sw.js", vapidPublicKey });
|
|
11
|
-
* await client.mutation("registerDevice", { subscription });
|
|
12
|
-
* ```
|
|
13
|
-
* @packageDocumentation
|
|
14
|
-
*/
|
|
15
|
-
/** A plain, JSON-serialisable Web Push subscription (the shape `ctx.push.register` accepts). */
|
|
16
1
|
interface SerializedPushSubscription {
|
|
17
2
|
endpoint: string;
|
|
18
3
|
expirationTime: number | null;
|
package/dist/web.mjs
CHANGED
|
@@ -1,44 +1 @@
|
|
|
1
|
-
const
|
|
2
|
-
const padding = "=".repeat((4 - base64.length % 4) % 4);
|
|
3
|
-
const normalized = (base64 + padding).replaceAll("-", "+").replaceAll("_", "/");
|
|
4
|
-
const raw = atob(normalized);
|
|
5
|
-
const output = new Uint8Array(raw.length);
|
|
6
|
-
for (let index = 0; index < raw.length; index += 1) {
|
|
7
|
-
output[index] = raw.codePointAt(index) ?? 0;
|
|
8
|
-
}
|
|
9
|
-
return output;
|
|
10
|
-
};
|
|
11
|
-
const browserGlobals = globalThis;
|
|
12
|
-
const isPushSupported = () => browserGlobals.navigator?.serviceWorker !== void 0 && browserGlobals.PushManager !== void 0;
|
|
13
|
-
const subscribeToPush = async (options) => {
|
|
14
|
-
if (!isPushSupported()) {
|
|
15
|
-
throw new Error("@lunora/notify: Web Push is not supported in this browser (needs service workers + PushManager)");
|
|
16
|
-
}
|
|
17
|
-
let registration;
|
|
18
|
-
if (options.serviceWorkerUrl === void 0) {
|
|
19
|
-
registration = await navigator.serviceWorker.ready;
|
|
20
|
-
} else {
|
|
21
|
-
const registerOptions = options.scope === void 0 ? void 0 : { scope: options.scope };
|
|
22
|
-
registration = await navigator.serviceWorker.register(options.serviceWorkerUrl, registerOptions);
|
|
23
|
-
}
|
|
24
|
-
const permission = await Notification.requestPermission();
|
|
25
|
-
if (permission !== "granted") {
|
|
26
|
-
throw new Error(`@lunora/notify: notification permission was not granted (got "${permission}")`);
|
|
27
|
-
}
|
|
28
|
-
const existing = await registration.pushManager.getSubscription();
|
|
29
|
-
const subscription = existing ?? await registration.pushManager.subscribe({
|
|
30
|
-
applicationServerKey: urlBase64ToUint8Array(options.vapidPublicKey),
|
|
31
|
-
userVisibleOnly: true
|
|
32
|
-
});
|
|
33
|
-
return subscription.toJSON();
|
|
34
|
-
};
|
|
35
|
-
const unsubscribeFromPush = async () => {
|
|
36
|
-
if (!isPushSupported()) {
|
|
37
|
-
return false;
|
|
38
|
-
}
|
|
39
|
-
const registration = await navigator.serviceWorker.ready;
|
|
40
|
-
const subscription = await registration.pushManager.getSubscription();
|
|
41
|
-
return subscription === null ? false : subscription.unsubscribe();
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
export { isPushSupported, subscribeToPush, unsubscribeFromPush };
|
|
1
|
+
const l=r=>{const e=atob(r),s=new Uint8Array(e.length);for(let t=0;t<e.length;t+=1)s[t]=e.codePointAt(t)??0;return s},u=r=>{const e=r.replaceAll("-","+").replaceAll("_","/"),s=e+"=".repeat((4-e.length%4)%4);return l(s)},o=r=>u(r),b=(r,e)=>r.length===e.length&&r.every((s,t)=>s===e[t]),g=(r,e)=>{const s=r.options.applicationServerKey;return s===null?!1:b(new Uint8Array(s),o(e))},n=globalThis,a=()=>n.navigator?.serviceWorker!==void 0&&n.PushManager!==void 0,d=async r=>{if(!a())throw new Error("@lunora/notify: Web Push is not supported in this browser (needs service workers + PushManager)");let e;if(r.serviceWorkerUrl===void 0)e=await navigator.serviceWorker.ready;else{const c=r.scope===void 0?void 0:{scope:r.scope};e=await navigator.serviceWorker.register(r.serviceWorkerUrl,c)}const s=await Notification.requestPermission();if(s!=="granted")throw new Error(`@lunora/notify: notification permission was not granted (got "${s}")`);const t=await e.pushManager.getSubscription();let i=null;return t!==null&&(g(t,r.vapidPublicKey)?i=t:await t.unsubscribe()),(i??await e.pushManager.subscribe({applicationServerKey:o(r.vapidPublicKey),userVisibleOnly:!0})).toJSON()},v=async()=>{if(!a())return!1;const e=await(await navigator.serviceWorker.ready).pushManager.getSubscription();return e===null?!1:e.unsubscribe()};export{a as isPushSupported,d as subscribeToPush,v as unsubscribeFromPush};
|