@lunora/notify 1.0.0-alpha.2 → 1.0.0-alpha.21

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.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
- /** List subscriptions, optionally filtered. */
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 `runPushBroadcastJob` does) to bound a single queue message
251
+ * to one page.
176
252
  */
177
253
  broadcast: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastResult>;
178
- /** List stored subscriptions (optionally filtered). */
179
- list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
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>;
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 `runPushBroadcastJob`) 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,26 @@ 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 runPushBroadcastJob}'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;
386
515
  /** Discriminator so a shared queue can multiplex message kinds. */
387
516
  type: "lunora.push.broadcast";
388
517
  }
389
- /** The structural slice of a `@lunora/queue` producer (`ctx.queues.&lt;name>`) used here. */
518
+ /** The structural slice of a `@lunora/queue` producer (`ctx.queues.<name>`) used here. */
390
519
  interface QueueProducerLike {
391
520
  send: (body: PushBroadcastJob) => Promise<void>;
392
521
  }
393
522
  /**
394
523
  * Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
395
524
  * queue instead of blocking the request. Pair with {@link runPushBroadcastJob} in
396
- * the queue consumer.
525
+ * the queue consumer — see its doc comment for how a large audience continues
526
+ * across MULTIPLE messages (one bounded page per message), not one.
397
527
  *
398
528
  * ```ts
399
529
  * // in a mutation/action:
@@ -401,17 +531,59 @@ interface QueueProducerLike {
401
531
  *
402
532
  * // in lunora/queues.ts consumer:
403
533
  * export const push = defineQueue({ async handler(batch, ctx) {
404
- * for (const message of batch.messages) await runPushBroadcastJob(ctx.push, message.body);
534
+ * for (const message of batch.messages) {
535
+ * const { nextCursor } = await runPushBroadcastJob(ctx.push, message.body);
536
+ *
537
+ * if (nextCursor !== undefined) {
538
+ * // More pages remain — enqueue the continuation. Each message still
539
+ * // does only ONE bounded page of work.
540
+ * await enqueuePushBroadcast(ctx.queues.push, {
541
+ * payload: message.body.payload,
542
+ * filter: { ...message.body.filter, after: nextCursor },
543
+ * });
544
+ * }
545
+ * }
405
546
  * }});
406
547
  * ```
407
548
  */
408
549
  declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
409
550
  /**
410
- * Run an enqueued broadcast job on the consumer side, delivering through the push
411
- * facade (which reuses the engine's retry + circuit-breaker middleware and prunes
412
- * gone subscriptions).
551
+ * Run ONE bounded page of an enqueued broadcast job on the consumer side,
552
+ * delivering through the push facade's {@link LunoraPush.broadcastPage} (which
553
+ * reuses the engine's retry + circuit-breaker middleware and prunes gone
554
+ * subscriptions).
555
+ *
556
+ * RETRY / CONTINUATION SEMANTICS (rewritten for plan 222 / NOTIFY-01 — a
557
+ * broadcast job used to process the WHOLE audience in one message, which could
558
+ * exceed Worker CPU/wall limits for a large audience and made a retry re-run
559
+ * everything):
560
+ *
561
+ * - A job now processes exactly ONE bounded page (see `CreateNotifyOptions`'s
562
+ * page-size option, default 250, or `job.filter.limit` when smaller),
563
+ * keyset-paginated on the subscription `id` (see `SubscriptionFilter.after`)
564
+ * — so per-message work is bounded regardless of total audience size.
565
+ * - Retry is still gated on `result.failed` — the count of TRANSIENT delivery
566
+ * errors (a provider 5xx / network fault worth another attempt). When at
567
+ * least one recipient in THIS PAGE `failed`, the job is RE-THROWN so the
568
+ * queue does NOT ack it and its normal retry/backoff (and, on exhaustion,
569
+ * dead-letter) applies — to just this page, not the whole broadcast.
570
+ * - A page with zero `failed` resolves and is acked — this includes the
571
+ * all-`pruned` case (every device on the page had unsubscribed:
572
+ * `sent:0`, `failed:0`, `pruned:N`), which is a SUCCESSFUL prune, not a
573
+ * failure, so throwing on it would spuriously retry and pressure the DLQ;
574
+ * and the empty-page case (zero `total`), which has nothing to retry.
575
+ * - The returned `nextCursor` is set when more pages remain. `@lunora/notify`
576
+ * does NOT enqueue the continuation itself — it has no `@lunora/queue`
577
+ * dependency (the seam stays structural) and no reference to the producer
578
+ * that enqueued this message — so the CALLER (the `lunora/queues.ts`
579
+ * consumer) is responsible for re-enqueueing with `filter.after: nextCursor`
580
+ * when present. See the consumer example on {@link enqueuePushBroadcast}.
581
+ * - A retry of a page redelivers only that page's already-delivered recipients
582
+ * on a transient partial failure (a page is not individually idempotent) —
583
+ * the accepted cost of getting the transiently failed ones redelivered, now
584
+ * scoped to one page instead of the whole broadcast.
413
585
  */
414
- declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<unknown>;
586
+ declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<BroadcastPageResult>;
415
587
  /**
416
588
  * The minimal structural slice of Cloudflare's `D1Database` this store uses. A
417
589
  * structural type (rather than importing `@cloudflare/workers-types`) keeps the
@@ -438,6 +610,15 @@ interface D1StoreOptions {
438
610
  * backing table is created lazily on first use (`CREATE TABLE IF NOT EXISTS`), so
439
611
  * no migration step is required for the subscription table itself.
440
612
  *
613
+ * ID SCHEME / LAZY MIGRATION: `id` (the `PRIMARY KEY`, upserted via `ON
614
+ * CONFLICT(id) DO UPDATE`) is a version-prefixed digest of the endpoint/token —
615
+ * currently `wp2_`/`fcm2_` (64-bit FNV-1a; see `normalize.ts`). No table migration
616
+ * runs when the id scheme is revised: a returning device re-registers under its new
617
+ * id and upserts a fresh row, while its old-prefix row (`wp_`/`fcm_`) ages out via
618
+ * the normal gone-pruning on the next failed send. So a table can transiently hold
619
+ * both an old- and new-prefix row for one device — expected, self-healing, and the
620
+ * reason a prefix must NEVER be reused for a different scheme.
621
+ *
441
622
  * ```ts
442
623
  * export default defineNotify({
443
624
  * webPush: (env) => webPushFromEnv(env),
@@ -453,16 +634,43 @@ declare const d1SubscriptionStore: (database: D1Like, options?: D1StoreOptions)
453
634
  * (or another backing store) for production so subscriptions survive restarts.
454
635
  */
455
636
  declare const memorySubscriptionStore: () => SubscriptionStore;
456
- /** Stable store id for a web-push endpoint. */
637
+ /**
638
+ * Stable store id for a web-push endpoint.
639
+ *
640
+ * The `wp2_` prefix is a version tag (see also {@link fcmId}'s `fcm2_`): it marks
641
+ * the 64-bit-id revision so the pre-existing 32-bit `wp_` rows stay readable and a
642
+ * returning device simply re-registers under the new id, its stale `wp_` row aging
643
+ * out via normal gone-pruning. A future third revision must mint `wp3_` and repeat
644
+ * the lazy migration — NEVER reuse a prefix.
645
+ */
457
646
  declare const webPushId: (endpoint: string) => string;
458
- /** Stable store id for an FCM device token. */
647
+ /** Stable store id for an FCM device token. See {@link webPushId} for the `_2` version-prefix contract. */
459
648
  declare const fcmId: (token: string) => string;
649
+ /** Options threaded into {@link normalizeRegisterInput} from the notify definition. */
650
+ interface NormalizeOptions {
651
+ /**
652
+ * Exact origins (`https://host[:port]`) a web-push endpoint may register from.
653
+ * When set (non-empty), the endpoint's origin must be one of these — the
654
+ * strongest anti-SSRF posture, and the ONLY way to close DNS rebinding for a
655
+ * facade that accepts client-controlled endpoints.
656
+ *
657
+ * When unset, the default posture applies: `https:` scheme + a host the
658
+ * {@link assertPushEndpoint} STRING classifier does not flag as
659
+ * private/loopback, plus a resolved-address re-check at send time. Setting
660
+ * this allowlist replaces both with an exact-origin match — the hard
661
+ * guarantee, and the only one that also covers an internal push service you
662
+ * deliberately want to reach.
663
+ */
664
+ allowedPushOrigins?: string[];
665
+ }
460
666
  /**
461
667
  * Normalise a `register(...)` input into a {@link StoredSubscription}. Validates
462
668
  * the shape (a web-push subscription needs `endpoint` + `keys.{p256dh,auth}`; an
463
- * FCM entry needs a non-empty `token`) and stamps `createdAt`/`lastSeenAt`.
669
+ * FCM entry needs a non-empty `token`), enforces the anti-SSRF endpoint boundary
670
+ * (see {@link assertPushEndpoint}), validates `metadata` (see
671
+ * {@link validateMetadata}), and stamps `createdAt`/`lastSeenAt`.
464
672
  */
465
- declare const normalizeRegisterInput: (input: RegisterInput, now?: number) => StoredSubscription;
673
+ declare const normalizeRegisterInput: (input: RegisterInput, now?: number, options?: NormalizeOptions) => StoredSubscription;
466
674
  /**
467
675
  * The provider `to` target for a stored subscription: the W3C Push subscription
468
676
  * (JSON-stringified) for web-push, or the raw device token for FCM. Matches the
@@ -481,4 +689,80 @@ declare const targetOf: (subscription: StoredSubscription) => string;
481
689
  * (a cert/session expiry) can never permanently drop a valid subscription.
482
690
  */
483
691
  declare const isGoneError: (message: string | undefined) => boolean;
484
- export { type BroadcastOutcome, type BroadcastResult, type CreateNotifyOptions, type D1Like, type D1PreparedLike, type D1StoreOptions, 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 PushSubscriptionDevice, type PushSubscriptionsResult, type QueueProducerLike, type RegisterInput, type ResolvedProviders, type RoutingPushOptions, type StoredSubscription, type SubscriptionFilter, type SubscriptionKind, type SubscriptionStatus, type SubscriptionStore, WEB_PUSH_ENV_KEYS, type WebPushConfigFactory, buildEngine, createNotify, d1SubscriptionStore, defineNotify, enqueuePushBroadcast, fcmFromEnv, fcmId, isGoneError, isNotifyDefinition, memorySubscriptionStore, normalizeRegisterInput, routingPushProvider, runPushBroadcastJob, targetOf, webPushFromEnv, webPushId };
692
+ export { type BroadcastOutcome, type BroadcastResult, type CreateNotifyOptions, type D1Like, type D1PreparedLike, type D1StoreOptions,
693
+ /**
694
+ * `@lunora/notify`
695
+ *
696
+ * Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
697
+ * engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
698
+ * (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
699
+ * and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
700
+ * → `ctx.flags`).
701
+ *
702
+ * Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
703
+ * Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
704
+ * deliberately **not** on the edge facade — route heavy fan-out through
705
+ * `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastJob`).
706
+ *
707
+ * - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
708
+ * - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
709
+ * @packageDocumentation
710
+ */
711
+ 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 PushSubscriptionDevice, type PushSubscriptionsResult, type QueueProducerLike, type RegisterInput, type ResolvedProviders, type RoutingPushOptions, type StoredSubscription, type SubscriptionFilter, type SubscriptionKind, type SubscriptionStatus, type SubscriptionStore,
712
+ /**
713
+ * `@lunora/notify`
714
+ *
715
+ * Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
716
+ * engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
717
+ * (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
718
+ * and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
719
+ * → `ctx.flags`).
720
+ *
721
+ * Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
722
+ * Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
723
+ * deliberately **not** on the edge facade — route heavy fan-out through
724
+ * `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastJob`).
725
+ *
726
+ * - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
727
+ * - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
728
+ * @packageDocumentation
729
+ */
730
+ WEB_PUSH_ENV_KEYS, type WebPushConfigFactory, buildEngine, createNotify, d1SubscriptionStore, defineNotify, enqueuePushBroadcast,
731
+ /**
732
+ * `@lunora/notify`
733
+ *
734
+ * Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
735
+ * engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
736
+ * (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
737
+ * and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
738
+ * → `ctx.flags`).
739
+ *
740
+ * Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
741
+ * Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
742
+ * deliberately **not** on the edge facade — route heavy fan-out through
743
+ * `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastJob`).
744
+ *
745
+ * - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
746
+ * - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
747
+ * @packageDocumentation
748
+ */
749
+ fcmFromEnv, fcmId, isGoneError, isNotifyDefinition, memorySubscriptionStore, normalizeRegisterInput, routingPushProvider, runPushBroadcastJob, targetOf,
750
+ /**
751
+ * `@lunora/notify`
752
+ *
753
+ * Multi-channel notifications for Lunora, wrapping the `@visulima/notification`
754
+ * engine. `defineNotify` in `lunora/notify.ts` configures the edge-safe channels
755
+ * (Web Push + FCM, plus chat / in-app inbox / webhook); codegen wires `ctx.notify`
756
+ * and its `ctx.push` alias onto every handler ctx from it (mirroring `defineFlags`
757
+ * → `ctx.flags`).
758
+ *
759
+ * Edge-safety: Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web
760
+ * Crypto under workerd. APNs (`node:http2`) and SMS / Node-only queue adapters are
761
+ * deliberately **not** on the edge facade — route heavy fan-out through
762
+ * `@lunora/queue` (`enqueuePushBroadcast` / `runPushBroadcastJob`).
763
+ *
764
+ * - `@lunora/notify` — `defineNotify`, `createNotify`, config resolvers, subscription stores and types.
765
+ * - `@lunora/notify/web` — the browser `subscribeToPush` service-worker helper.
766
+ * @packageDocumentation
767
+ */
768
+ webPushFromEnv, webPushId };
package/dist/index.mjs CHANGED
@@ -1,8 +1 @@
1
- export { FCM_ENV_KEYS, WEB_PUSH_ENV_KEYS, fcmFromEnv, webPushFromEnv } from './packem_shared/FCM_ENV_KEYS-DY4-A717.mjs';
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-GgvLs28y.mjs";import{buildEngine as d,routingPushProvider as x}from"./packem_shared/buildEngine-Cl_c6i9_.mjs";import{enqueuePushBroadcast as c,runPushBroadcastJob as P}from"./packem_shared/enqueuePushBroadcast-tf1LqgzA.mjs";import{d1SubscriptionStore as b}from"./packem_shared/d1SubscriptionStore-D5VVGBxm.mjs";import{memorySubscriptionStore as N}from"./packem_shared/memorySubscriptionStore-B60C_I7v.mjs";import{fcmId as g,isGoneError as y,normalizeRegisterInput as v,targetOf as B,webPushId as F}from"./packem_shared/fcmId-ggkSOUHd.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
+ 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 f}from"@lunora/errors";import{createNotification as p}from"@visulima/notification";import{retryMiddleware as h,circuitBreakerMiddleware as v}from"@visulima/notification/middleware";import{fcmProvider as w}from"@visulima/notification/providers/fcm";import{webPushProvider as l}from"@visulima/notification/providers/web-push";import{n as b,p as u,a as m,b as P}from"./ssrf-host-BCpHorGa.mjs";const y=(n,i)=>{if(n.size<i)return;const t=n.keys().next().value;t!==void 0&&n.delete(t)},g="https://cloudflare-dns.com/dns-query",a=1,c=28,k=2e3,A=(n,i)=>{if(i===a){const t=u(n);return t===void 0||m(t)}return P(n.toLowerCase())},d=async(n,i,t)=>{try{const e=await fetch(`${g}?name=${encodeURIComponent(n)}&type=${String(i)}`,{headers:{accept:"application/dns-json"},signal:AbortSignal.timeout(t)});return e.ok?(await e.json()).Answer??[]:void 0}catch{return}},E=async(n,i=k)=>{const t=b(n);if(t.includes(":")||u(t)!==void 0)return{kind:"unknown"};const[e,r]=await Promise.all([d(t,a,i),d(t,c,i)]);if(e===void 0&&r===void 0)return{kind:"unknown"};for(const o of[...e??[],...r??[]])if((o.type===a||o.type===c)&&A(o.data,o.type))return{address:o.data,kind:"private"};return{kind:"public"}},I=n=>{let i=n;if(typeof n=="string"){if(!n.startsWith("{"))return;try{i=JSON.parse(n)}catch{return}}const t=i?.endpoint;return typeof t=="string"?t:void 0},s=new Map,D=256,N=async(n,i)=>{if(i!==void 0&&i.length>0)return;let t;try{({hostname:t}=new URL(n))}catch{return}const e=s.get(t),r=e??E(t),o=await r;if(e===void 0&&o.kind!=="unknown"&&(y(s,D),s.set(t,r)),o.kind==="private")throw new f("FORBIDDEN",`@lunora/notify: web-push endpoint host "${t}" resolves to a private/internal address (${o.address}); refusing to send (DNS-rebinding guard)`)},O=n=>{const i=t=>{const e=t===void 0?n.fcm:n.webPush;if(e===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 e};return{channel:"push",id:"lunora-push-router",initialize:async()=>{await n.webPush?.initialize(),await n.fcm?.initialize()},isAvailable:()=>(n.webPush??n.fcm)!==void 0,send:async t=>{const r=(Array.isArray(t.to)?t.to:[t.to]).map(o=>I(o));for(const o of r)o!==void 0&&await N(o,n.allowedPushOrigins);return i(r[0]).send(t)}}},M=n=>{const i=n.webPush===void 0?void 0:l(n.webPush),t=n.fcm===void 0?void 0:w(n.fcm),e={};(i!==void 0||t!==void 0)&&(e.push=O({allowedPushOrigins:n.allowedPushOrigins,fcm:t,webPush:i})),n.chat!==void 0&&(e.chat=n.chat),n.inApp!==void 0&&(e.inapp=n.inApp),n.webhook!==void 0&&(e.webhook=n.webhook);const r=p(e);return r.use(h()).use(v()),r};export{M as buildEngine,O as routingPushProvider};
@@ -0,0 +1 @@
1
+ import{LunoraError as v}from"@lunora/errors";import{buildEngine as F}from"./buildEngine-Cl_c6i9_.mjs";import{memorySubscriptionStore as R}from"./memorySubscriptionStore-B60C_I7v.mjs";import{normalizeRegisterInput as z,targetOf as B,isGoneError as L}from"./fcmId-ggkSOUHd.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-ggkSOUHd.mjs";const 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},c=/^[A-Za-z_]\w*$/u,O=(e,i={})=>{const n=i.tableName??"lunora_push_subscriptions";if(!c.test(n))throw new p("BAD_REQUEST",`@lunora/notify: d1SubscriptionStore tableName "${n}" is not a bare SQL identifier`);let r;const l=()=>(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),s=async t=>{await l();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 l(),await e.prepare(`DELETE FROM ${n} WHERE id = ?1`).bind(t).run()},get:s,list:async t=>{await l();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 T=a.length===0?"":` WHERE ${a.join(" AND ")}`,o=" 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}${T}${o}${u}`).bind(...d).all();return _.map(h=>E(h))},markStatus:async(t,a,d)=>{await l(),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 l(),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 s(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 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 s}from"@lunora/errors";import{i as S}from"./ssrf-host-BCpHorGa.mjs";const 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 r;try{r=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 o=new TextEncoder().encode(r).length;if(o>f)throw new s("BAD_REQUEST",`@lunora/notify: register() \`metadata\` is ${o.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,r=40164,o=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=r*435+e*256,w=o*435+n*256,l=y+(c>>>16),u=E+(l>>>16),b=w+(u>>>16);e=c&65535,n=l&65535,r=u&65535,o=b&65535}return d(o)+d(r)+d(n)+d(e)},A=t=>`wp2_${p(t)}`,_=t=>`fcm2_${p(t)}`,g=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")},m=t=>`wp_${g(t)}`,T=t=>`fcm_${g(t)}`,I=t=>t.kind==="fcm"?t.token===void 0?void 0:T(t.token):t.endpoint===void 0?void 0:m(t.endpoint),k=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)}`)}},O=(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(S(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`)},N=(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:_(c),kind:"fcm",lastSeenAt:e,metadata:h(t.metadata),token:c,userId:t.userId??null}}const r=k(t.subscription),{endpoint:o}=r,i=r.keys?.p256dh,a=r.keys?.auth;if(typeof o!="string"||o===""||typeof i!="string"||typeof a!="string")throw new s("BAD_REQUEST","@lunora/notify: register() web-push subscription requires `endpoint` and `keys.{p256dh, auth}`");return O(o,n.allowedPushOrigins),{createdAt:e,endpoint:o,id:A(o),keys:{auth:a,p256dh:i},kind:"web-push",lastSeenAt:e,metadata:h(t.metadata),userId:t.userId??null}},$=t=>t.kind==="fcm"?t.token??"":JSON.stringify({endpoint:t.endpoint,keys:t.keys}),v=/\bhttp\s*4(?:04|10)\b/iu,R=/\b(?:unregistered|not[\s-]?registered|registration-token-not-registered)\b/iu,D=/\bsubscription (?:is )?(?:gone|expired|no longer valid)\b/iu,U=t=>t===void 0?!1:v.test(t)||R.test(t)||D.test(t);export{_ as fcmId,U as isGoneError,T as legacyFcmId,I as legacyIdFor,m as legacyWebPushId,N as normalizeRegisterInput,$ as targetOf,A as webPushId};
@@ -0,0 +1 @@
1
+ import{legacyIdFor as n}from"./fcmId-ggkSOUHd.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.mjs CHANGED
@@ -1,44 +1 @@
1
- const urlBase64ToUint8Array = (base64) => {
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 a=e=>{const r="=".repeat((4-e.length%4)%4),i=(e+r).replaceAll("-","+").replaceAll("_","/"),t=atob(i),s=new Uint8Array(t.length);for(let n=0;n<t.length;n+=1)s[n]=t.codePointAt(n)??0;return s},l=(e,r)=>e.length===r.length&&e.every((i,t)=>i===r[t]),g=(e,r)=>{const i=e.options.applicationServerKey;return i===null?!1:l(new Uint8Array(i),a(r))},o=globalThis,c=()=>o.navigator?.serviceWorker!==void 0&&o.PushManager!==void 0,p=async e=>{if(!c())throw new Error("@lunora/notify: Web Push is not supported in this browser (needs service workers + PushManager)");let r;if(e.serviceWorkerUrl===void 0)r=await navigator.serviceWorker.ready;else{const u=e.scope===void 0?void 0:{scope:e.scope};r=await navigator.serviceWorker.register(e.serviceWorkerUrl,u)}const i=await Notification.requestPermission();if(i!=="granted")throw new Error(`@lunora/notify: notification permission was not granted (got "${i}")`);const t=await r.pushManager.getSubscription();let s=null;return t!==null&&(g(t,e.vapidPublicKey)?s=t:await t.unsubscribe()),(s??await r.pushManager.subscribe({applicationServerKey:a(e.vapidPublicKey),userVisibleOnly:!0})).toJSON()},b=async()=>{if(!c())return!1;const r=await(await navigator.serviceWorker.ready).pushManager.getSubscription();return r===null?!1:r.unsubscribe()};export{c as isPushSupported,p as subscribeToPush,b as unsubscribeFromPush};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/notify",
3
- "version": "1.0.0-alpha.2",
3
+ "version": "1.0.0-alpha.21",
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,8 +49,8 @@
49
49
  "access": "public"
50
50
  },
51
51
  "dependencies": {
52
- "@lunora/errors": "1.0.0-alpha.7",
53
- "@visulima/notification": "1.0.5"
52
+ "@lunora/errors": "1.0.0-alpha.22",
53
+ "@visulima/notification": "1.0.12"
54
54
  },
55
55
  "engines": {
56
56
  "node": "^22.15.0 || >=24.11.0"
@@ -1,32 +0,0 @@
1
- const WEB_PUSH_ENV_KEYS = {
2
- privateKey: "VAPID_PRIVATE_KEY",
3
- publicKey: "VAPID_PUBLIC_KEY",
4
- subject: "VAPID_SUBJECT"
5
- };
6
- const FCM_ENV_KEYS = {
7
- accessToken: "FCM_ACCESS_TOKEN",
8
- projectId: "FCM_PROJECT_ID"
9
- };
10
- const readString = (env, key) => {
11
- const value = env[key];
12
- return typeof value === "string" && value !== "" ? value : void 0;
13
- };
14
- const webPushFromEnv = (env, overrides) => {
15
- const vapidPublicKey = readString(env, WEB_PUSH_ENV_KEYS.publicKey);
16
- const vapidPrivateKey = readString(env, WEB_PUSH_ENV_KEYS.privateKey);
17
- const vapidSubject = readString(env, WEB_PUSH_ENV_KEYS.subject);
18
- if (vapidPublicKey === void 0 || vapidPrivateKey === void 0 || vapidSubject === void 0) {
19
- return void 0;
20
- }
21
- return { vapidPrivateKey, vapidPublicKey, vapidSubject, ...overrides };
22
- };
23
- const fcmFromEnv = (env, overrides) => {
24
- const projectId = readString(env, FCM_ENV_KEYS.projectId);
25
- if (projectId === void 0) {
26
- return void 0;
27
- }
28
- const accessToken = readString(env, FCM_ENV_KEYS.accessToken);
29
- return { accessToken, projectId, ...overrides };
30
- };
31
-
32
- export { FCM_ENV_KEYS, WEB_PUSH_ENV_KEYS, fcmFromEnv, webPushFromEnv };