@lunora/notify 0.0.0 → 1.0.0-alpha.10

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.
@@ -0,0 +1,684 @@
1
+ import { FcmConfig } from '@visulima/notification/providers/fcm';
2
+ export type { FcmConfig } from '@visulima/notification/providers/fcm';
3
+ import { PushSubscriptionLike, WebPushConfig } from '@visulima/notification/providers/web-push';
4
+ export type { PushSubscriptionLike, WebPushConfig } from '@visulima/notification/providers/web-push';
5
+ import { ChatPayload, Receipt, InAppPayload, PushPayload, NotificationMessage, WebhookPayload, Notification, Provider } from '@visulima/notification';
6
+ export type { ChatPayload, InAppPayload, NotificationMessage, PushPayload, Receipt, WebhookPayload } from '@visulima/notification';
7
+ /**
8
+ * A Worker `env` projected as a plain record (vars, secrets and bindings are
9
+ * `unknown`-valued). `defineNotify` factories receive this so a config can read
10
+ * VAPID/FCM secrets and pick bindings (D1, Queues) at request/isolate time —
11
+ * mirroring the `config.ai?.(env)` / flags `provider(env)` thunk pattern.
12
+ */
13
+ type NotifyEnv = Record<string, unknown>;
14
+ /** The delivery kind a stored device subscription targets. */
15
+ type SubscriptionKind = "fcm" | "web-push";
16
+ /** The last-known delivery outcome recorded on a subscription. */
17
+ type SubscriptionStatus = "expired" | "failed" | "ok";
18
+ /**
19
+ * A registered device/browser subscription. Web Push carries a W3C Push API
20
+ * `endpoint` + `keys`; FCM carries a device registration `token`. `id` is a
21
+ * stable, storage-safe identifier derived from the target (see `subscriptionId`).
22
+ */
23
+ interface StoredSubscription {
24
+ /** Unix-ms creation time. */
25
+ createdAt: number;
26
+ /** Web Push service endpoint URL (web-push only). */
27
+ endpoint?: string;
28
+ /** Stable identifier (endpoint/token derived) used as the store key. */
29
+ id: string;
30
+ /** Web Push client keys (web-push only). */
31
+ keys?: {
32
+ auth: string;
33
+ p256dh: string;
34
+ };
35
+ /** The delivery channel this subscription targets. */
36
+ kind: SubscriptionKind;
37
+ /** Last delivery error message, when `lastStatus` is `failed`/`expired`. */
38
+ lastError?: string;
39
+ /** Unix-ms time of the most recent register/send touch. */
40
+ lastSeenAt: number;
41
+ /** Last-known delivery outcome. */
42
+ lastStatus?: SubscriptionStatus;
43
+ /** Arbitrary app metadata (device name, locale, topics, …). */
44
+ metadata?: Record<string, unknown>;
45
+ /** FCM device registration token (fcm only). */
46
+ token?: string;
47
+ /** Owning user id, or `null` when anonymous. */
48
+ userId?: string | null;
49
+ }
50
+ /**
51
+ * The admin-facing projection of a {@link StoredSubscription} — a registered
52
+ * device as surfaced by the gated `__lunora_admin__:listPushSubscriptions` RPC
53
+ * (backing the Studio Notifications page). The delivery **secrets** are dropped:
54
+ * the Web Push `keys` (the RFC 8291 `auth`/`p256dh` encryption material) and the
55
+ * FCM `token` are never sent to the browser — only the endpoint / kind / owner /
56
+ * timestamps and the last-send status + error the page renders.
57
+ */
58
+ type PushSubscriptionDevice = Omit<StoredSubscription, "keys" | "token">;
59
+ /** Payload of a `__lunora_admin__:listPushSubscriptions` call — the registered devices, secrets redacted. */
60
+ interface PushSubscriptionsResult {
61
+ /** The registered device subscriptions matching the request filter (secrets stripped). */
62
+ subscriptions: PushSubscriptionDevice[];
63
+ }
64
+ /** Input accepted by `ctx.push.register(...)` — a web-push subscription or an FCM token. */
65
+ type RegisterInput = {
66
+ kind?: "web-push";
67
+ metadata?: Record<string, unknown>;
68
+ subscription: PushSubscriptionLike | string;
69
+ userId?: string | null;
70
+ } | {
71
+ kind: "fcm";
72
+ metadata?: Record<string, unknown>;
73
+ token: string;
74
+ userId?: string | null;
75
+ };
76
+ /** Filter narrowing which stored subscriptions a `list`/`broadcast` targets. */
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;
102
+ /** Restrict to a delivery kind. */
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;
130
+ /** Restrict to a single owning user. */
131
+ userId?: string | null;
132
+ }
133
+ /**
134
+ * Persistence for device subscriptions. Implementations back `ctx.push`'s
135
+ * lifecycle (register, list, prune). Ships with an in-memory store (tests/dev)
136
+ * and a D1-backed store (durable, edge-safe).
137
+ */
138
+ interface SubscriptionStore {
139
+ /** Remove a subscription by id (idempotent). */
140
+ delete: (id: string) => Promise<void>;
141
+ /** Read a subscription by id, or `undefined`. */
142
+ get: (id: string) => Promise<StoredSubscription | undefined>;
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
+ */
150
+ list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
151
+ /** Record the latest delivery outcome for a subscription (best-effort). */
152
+ markStatus: (id: string, status: SubscriptionStatus, error?: string) => Promise<void>;
153
+ /** Insert or update a subscription (upsert by id). */
154
+ put: (subscription: StoredSubscription) => Promise<StoredSubscription>;
155
+ }
156
+ /** Per-recipient outcome from a fan-out `broadcast`. */
157
+ interface BroadcastOutcome {
158
+ /** Delivery error message when `status` is not `ok`. */
159
+ error?: string;
160
+ /** The subscription this outcome belongs to. */
161
+ id: string;
162
+ /** `expired` subscriptions were pruned from the store. */
163
+ status: SubscriptionStatus;
164
+ }
165
+ /** Aggregate result of a `broadcast`. */
166
+ interface BroadcastResult {
167
+ /** Number of subscriptions that failed (non-gone). */
168
+ failed: number;
169
+ /** Per-subscription outcomes. */
170
+ outcomes: BroadcastOutcome[];
171
+ /** Number of pruned (gone/expired) subscriptions. */
172
+ pruned: number;
173
+ /** Number of subscriptions delivered successfully. */
174
+ sent: number;
175
+ /** Total subscriptions attempted. */
176
+ total: number;
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
+ }
190
+ /**
191
+ * The compact, stable delivery-status vocabulary emitted on notify observability
192
+ * signals — the `status` dimension on the `notify.send` metric and the failure
193
+ * log line. Modeled on Novu's execution status, but honest to edge push:
194
+ *
195
+ * - `accepted` — the provider took the message (a `Receipt.successful` send).
196
+ * - `failed` — a provider error; the log line carries the `error` text.
197
+ * - `gone` — the endpoint is unregistered (404/410, FCM `UNREGISTERED`) and pruned; push-only.
198
+ *
199
+ * Web Push and FCM give no delivery/open receipts, so the vocabulary stops at the
200
+ * send attempt: a `delivered`/`opened` status would be a lie for these channels.
201
+ * The one place a later `seen`/`read` is real is the in-app inbox, where the
202
+ * client posts a read receipt back — out of scope here.
203
+ */
204
+ type NotifyDeliveryStatus = "accepted" | "failed" | "gone";
205
+ /**
206
+ * Why a send fanned out to nobody — the "sent 0 because…" signal (mirrors Novu's
207
+ * pre-send `DetailEnum` reasons). Emitted as the `reason` dimension on a
208
+ * `notify.skipped` metric so a no-op is visible in the Studio metric/trend view
209
+ * instead of silent.
210
+ *
211
+ * - `no-subscriptions-matched` — the store held no device for the broadcast filter.
212
+ * - `channel-not-configured` — the target channel was never wired in `defineNotify`.
213
+ */
214
+ type NotifySkipReason = "channel-not-configured" | "no-subscriptions-matched";
215
+ /**
216
+ * The minimal structural slice of `ctx.log` the notify facade emits through — just
217
+ * the `warn` severity it uses for a failed delivery. Structural (rather than a
218
+ * dependency on `@lunora/server`'s `LunoraLogger`) so codegen passes the real
219
+ * `ctx.log` and a test passes a spy — the D1-store `D1Like` pattern, applied to
220
+ * observability.
221
+ */
222
+ interface NotifyLogger {
223
+ warn: (message: string, fields?: Record<string, unknown>) => void;
224
+ }
225
+ /**
226
+ * The minimal structural slice of `ctx.metrics` the notify facade emits through —
227
+ * the `count` instrument backing the `notify.send` / `notify.skipped` series.
228
+ * Structural for the same reason as {@link NotifyLogger}.
229
+ */
230
+ interface NotifyMetrics {
231
+ count: (name: string, value?: number, attributes?: Record<string, unknown>) => void;
232
+ }
233
+ /**
234
+ * The push sub-facade — spliced onto ctx as `ctx.push` (and reachable as
235
+ * `ctx.notify.push`). Owns the device-subscription lifecycle plus targeted and
236
+ * fan-out push delivery through the edge-safe Web Push / FCM providers.
237
+ */
238
+ interface LunoraPush {
239
+ /**
240
+ * Fan-out a push to every stored subscription matching `filter` (default: all).
241
+ * Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
242
+ * the push service reports as gone (HTTP 404/410, FCM `UNREGISTERED`). The `to`
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.
252
+ */
253
+ broadcast: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastResult>;
254
+ /**
255
+ * Fan-out a push to ONE bounded page of stored subscriptions matching
256
+ * `filter` (page size: `CreateNotifyOptions`'s `broadcastPageSize`, default
257
+ * 250, capped by `filter.limit` when set). Same delivery semantics as
258
+ * {@link LunoraPush.broadcast} (retry/circuit-breaker, gone-pruning) but
259
+ * scoped to a single page; returns the page's own {@link BroadcastResult}
260
+ * plus a `nextCursor` to fetch the next page (`undefined` when done).
261
+ * Backs `runPushBroadcastJob` so one queue message does bounded work
262
+ * regardless of audience size — most app code should call
263
+ * {@link LunoraPush.broadcast} instead.
264
+ */
265
+ broadcastPage: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastPageResult>;
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[]>;
274
+ /** Register (upsert) a device subscription and return the stored record. */
275
+ register: (input: RegisterInput) => Promise<StoredSubscription>;
276
+ /** Send a push to a single stored subscription (by id or record); `to` is derived from it. */
277
+ send: (target: StoredSubscription | string, payload: PushContent) => Promise<Receipt>;
278
+ /** Remove a subscription by id (idempotent). */
279
+ unregister: (id: string) => Promise<void>;
280
+ }
281
+ /** A push payload without its `to` target — the facade derives `to` from the stored subscription. */
282
+ type PushContent = Omit<PushPayload, "to">;
283
+ /**
284
+ * The multi-channel notification facade — spliced onto ctx as `ctx.notify`.
285
+ * `send` delivers a fully-specified multi-channel message through the engine;
286
+ * `push` is the device-push sub-facade; `chat` / `inApp` / `webhook` are
287
+ * single-channel convenience senders for the edge-safe channels.
288
+ */
289
+ interface LunoraNotify {
290
+ /** Send an outbound webhook. */
291
+ chat: (payload: ChatPayload) => Promise<Receipt>;
292
+ /** Deliver an in-app inbox notification. */
293
+ inApp: (payload: InAppPayload) => Promise<Receipt>;
294
+ /** The device-push sub-facade (identical object to `ctx.push`). */
295
+ push: LunoraPush;
296
+ /** Deliver a multi-channel message (one payload per channel). */
297
+ send: (message: NotificationMessage) => Promise<Receipt[]>;
298
+ /** Post to a chat channel (Slack/Discord/Teams/Telegram). */
299
+ webhook: (payload: WebhookPayload) => Promise<Receipt>;
300
+ }
301
+ /**
302
+ * Resolves a channel provider factory from the Worker `env`. Receiving `env`
303
+ * (rather than a constructed provider) lets a config read VAPID/FCM secrets and
304
+ * bindings at request time. Return `undefined` to leave the channel unwired.
305
+ */
306
+ type WebPushConfigFactory = (env: NotifyEnv) => WebPushConfig | undefined;
307
+ type FcmConfigFactory = (env: NotifyEnv) => FcmConfig | undefined;
308
+ /** Options accepted by `defineNotify`. */
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[];
326
+ /**
327
+ * Optional chat provider factory (Slack/Discord/Teams/Telegram). Wire with a
328
+ * provider from `@visulima/notification/providers/*`. Edge-safe (fetch-based).
329
+ */
330
+ chat?: (env: NotifyEnv) => unknown;
331
+ /** FCM (Firebase Cloud Messaging HTTP v1) config. Edge-safe — supply an OAuth2 token. */
332
+ fcm?: FcmConfig | FcmConfigFactory;
333
+ /** Optional in-app inbox provider factory. Edge-safe. */
334
+ inApp?: (env: NotifyEnv) => unknown;
335
+ /**
336
+ * Builds the subscription store from `env` (usually a D1-backed store from a
337
+ * binding). Defaults to a non-durable in-memory store with a dev warning.
338
+ */
339
+ store?: (env: NotifyEnv) => SubscriptionStore;
340
+ /** Optional outbound-webhook provider factory. Edge-safe (fetch-based). */
341
+ webhook?: (env: NotifyEnv) => unknown;
342
+ /** Web Push (VAPID + RFC 8291) config. Fully edge-safe (Web Crypto only). */
343
+ webPush?: WebPushConfig | WebPushConfigFactory;
344
+ }
345
+ /**
346
+ * A branded {@link NotifyConfig} produced by `defineNotify`. This is the default
347
+ * export of `lunora/notify.ts`; codegen imports it into the generated worker and
348
+ * wires `ctx.notify` / `ctx.push` from it (mirroring `defineFlags` → `ctx.flags`).
349
+ */
350
+ interface NotifyDefinition extends NotifyConfig {
351
+ /** Runtime brand used by `isNotifyDefinition` and codegen discovery. */
352
+ readonly isLunoraNotify: true;
353
+ }
354
+ /**
355
+ * `.dev.vars` / Worker `env` keys the built-in config resolvers read. Mirrored in
356
+ * `@lunora/config`'s package-secrets registry so `lunora dev` scaffolds them into
357
+ * `.dev.vars.example`.
358
+ */
359
+ declare const WEB_PUSH_ENV_KEYS: {
360
+ readonly privateKey: "VAPID_PRIVATE_KEY";
361
+ readonly publicKey: "VAPID_PUBLIC_KEY";
362
+ readonly subject: "VAPID_SUBJECT";
363
+ };
364
+ declare const FCM_ENV_KEYS: {
365
+ readonly accessToken: "FCM_ACCESS_TOKEN";
366
+ readonly projectId: "FCM_PROJECT_ID";
367
+ };
368
+ /**
369
+ * Resolve a {@link WebPushConfig} from the Worker `env` VAPID secrets
370
+ * (`VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY`, `VAPID_SUBJECT`). Returns `undefined`
371
+ * when any is missing, leaving the Web Push channel unwired rather than throwing —
372
+ * so an app can ship FCM-only (or vice versa) without failing ctx construction.
373
+ *
374
+ * Generate a VAPID keypair once with `npx web-push generate-vapid-keys` (or any
375
+ * P-256 tool) and set `VAPID_SUBJECT` to a `mailto:` or `https:` contact.
376
+ */
377
+ declare const webPushFromEnv: (env: NotifyEnv, overrides?: Partial<WebPushConfig>) => WebPushConfig | undefined;
378
+ /**
379
+ * Resolve an {@link FcmConfig} from the Worker `env` (`FCM_PROJECT_ID` plus a
380
+ * static `FCM_ACCESS_TOKEN`). Returns `undefined` when the project id is missing.
381
+ *
382
+ * The static token is convenient for local dev but expires; in production prefer
383
+ * passing your own `getAccessToken` (e.g. wrapping `google-auth-library`) via
384
+ * `defineNotify({ fcm: (env) => ({ ...fcmFromEnv(env), getAccessToken }) })` —
385
+ * that keeps the provider edge-safe (no Google SDK / `node:crypto` bundled).
386
+ */
387
+ declare const fcmFromEnv: (env: NotifyEnv, overrides?: Partial<FcmConfig>) => FcmConfig | undefined;
388
+ /**
389
+ * Declare the notification channels for a Lunora app. Pure validation +
390
+ * branding — codegen discovers the default export of `lunora/notify.ts`, imports
391
+ * it into the generated worker, and wires `ctx.notify` / `ctx.push` from it
392
+ * (mirrors how `defineFlags` feeds codegen to build `ctx.flags`).
393
+ *
394
+ * ```ts
395
+ * // lunora/notify.ts
396
+ * import { defineNotify, webPushFromEnv, fcmFromEnv } from "@lunora/notify";
397
+ * import { d1SubscriptionStore } from "@lunora/notify";
398
+ *
399
+ * export default defineNotify({
400
+ * webPush: (env) => webPushFromEnv(env), // VAPID_* from .dev.vars
401
+ * fcm: (env) => fcmFromEnv(env), // FCM_PROJECT_ID / FCM_ACCESS_TOKEN
402
+ * store: (env) => d1SubscriptionStore(env.DB),
403
+ * });
404
+ * ```
405
+ *
406
+ * Only edge-safe channels are wired here — Web Push and FCM run on Web Crypto +
407
+ * `fetch` under workerd. APNs (`node:http2`) and SMS/Node-only queue adapters are
408
+ * intentionally **not** exposed on the edge facade; route heavy fan-out through
409
+ * `@lunora/queue` instead (see `broadcastViaQueue`).
410
+ */
411
+ declare const defineNotify: (config: NotifyConfig) => NotifyDefinition;
412
+ /** True when a value is a {@link defineNotify} result (the runtime brand check). */
413
+ declare const isNotifyDefinition: (value: unknown) => value is NotifyDefinition;
414
+ /** Options for {@link createNotify}. */
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;
426
+ /** Max concurrent sends during a `broadcast` (default 10). */
427
+ concurrency?: number;
428
+ /**
429
+ * Override the assembled `@visulima/notification` engine. Advanced/testing
430
+ * seam — pass a `Notification` built with your own (mock) providers to bypass
431
+ * config resolution entirely.
432
+ */
433
+ engine?: Notification;
434
+ /**
435
+ * The request's `ctx.log` (structural {@link NotifyLogger}). Codegen threads
436
+ * `ctx.log` in; when present the facade emits one `warn` line per FAILED
437
+ * delivery — trace-correlated to the enclosing action and durably archived by
438
+ * the log sink. Successes and prunes stay off the log to keep the archive
439
+ * clean; they are counted on `metrics` instead. Absent ⇒ no log emits.
440
+ */
441
+ log?: NotifyLogger;
442
+ /**
443
+ * The request's `ctx.metrics` (structural {@link NotifyMetrics}). Codegen
444
+ * threads `ctx.metrics` in; when present the facade counts every send on the
445
+ * `notify.send` series (dimensions `channel` / `provider` / `status`) and every
446
+ * no-op on `notify.skipped` (`channel` / `reason`) — feeding the durable metric
447
+ * history + trend charts. Absent ⇒ no metric emits.
448
+ */
449
+ metrics?: NotifyMetrics;
450
+ /** Suppress the in-memory-store dev warning (tests set this). */
451
+ silent?: boolean;
452
+ }
453
+ /**
454
+ * Build the `ctx.notify` / `ctx.push` facades for a request from a
455
+ * {@link NotifyDefinition} (the `lunora/notify.ts` default export) and the Worker
456
+ * `env`. Codegen calls this to splice the facades onto ctx — the same shape as
457
+ * `createFlags` for `ctx.flags`. Returns both facades; `notify.push` is the very
458
+ * same object exposed as `ctx.push`.
459
+ *
460
+ * The engine and the dev fallback store are memoized per isolate (see
461
+ * {@link NotifyRuntime}), so repeat calls with the same `definition`/`env` are
462
+ * cheap — only the thin facade closures below are rebuilt each call.
463
+ */
464
+ declare const createNotify: (definition: NotifyDefinition, env: NotifyEnv, options?: CreateNotifyOptions) => {
465
+ notify: LunoraNotify;
466
+ push: LunoraPush;
467
+ };
468
+ /** Options for {@link routingPushProvider}. */
469
+ interface RoutingPushOptions {
470
+ fcm?: Provider<unknown, PushPayload>;
471
+ webPush?: Provider<unknown, PushPayload>;
472
+ }
473
+ /**
474
+ * A composite push {@link Provider} that dispatches each send to the Web Push or
475
+ * FCM provider by the shape of the payload `to` target — so a single `push`
476
+ * channel on the {@link Notification} facade transparently handles both browser
477
+ * subscriptions and mobile device tokens, and the engine's middleware wraps them
478
+ * uniformly.
479
+ */
480
+ declare const routingPushProvider: (options: RoutingPushOptions) => Provider<unknown, PushPayload>;
481
+ /** A resolved, ready-to-wire set of channel configs (edge-safe channels only). */
482
+ interface ResolvedProviders {
483
+ chat?: Provider;
484
+ fcm?: FcmConfig;
485
+ inApp?: Provider;
486
+ webhook?: Provider;
487
+ webPush?: WebPushConfig;
488
+ }
489
+ /**
490
+ * Assemble the `@visulima/notification` engine from resolved channel configs and
491
+ * attach the reused retry + circuit-breaker middleware. Only edge-safe channels
492
+ * are wired (Web Push, FCM, chat, in-app, webhook); APNs and SMS are excluded
493
+ * from the edge facade by construction.
494
+ */
495
+ declare const buildEngine: (resolved: ResolvedProviders) => Notification;
496
+ /**
497
+ * A broadcast job body — the JSON-serialisable payload enqueued for off-request
498
+ * fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
499
+ * `@lunora/notify` depending on `@lunora/queue` (the seam stays structural).
500
+ * `filter.after`, when set, resumes a broadcast partway through (see
501
+ * {@link runPushBroadcastJob}'s continuation semantics).
502
+ */
503
+ interface PushBroadcastJob {
504
+ /** Subscription filter (which devices/users to target; `filter.after` resumes a paged broadcast). */
505
+ filter?: SubscriptionFilter;
506
+ /** The push payload to deliver (the `to` target is derived per subscription). */
507
+ payload: PushContent;
508
+ /** Discriminator so a shared queue can multiplex message kinds. */
509
+ type: "lunora.push.broadcast";
510
+ }
511
+ /** The structural slice of a `@lunora/queue` producer (`ctx.queues.&lt;name>`) used here. */
512
+ interface QueueProducerLike {
513
+ send: (body: PushBroadcastJob) => Promise<void>;
514
+ }
515
+ /**
516
+ * Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
517
+ * queue instead of blocking the request. Pair with {@link runPushBroadcastJob} in
518
+ * the queue consumer — see its doc comment for how a large audience continues
519
+ * across MULTIPLE messages (one bounded page per message), not one.
520
+ *
521
+ * ```ts
522
+ * // in a mutation/action:
523
+ * await enqueuePushBroadcast(ctx.queues.push, { payload: { title: "New drop", body: "…" } });
524
+ *
525
+ * // in lunora/queues.ts consumer:
526
+ * export const push = defineQueue({ async handler(batch, ctx) {
527
+ * for (const message of batch.messages) {
528
+ * const { nextCursor } = await runPushBroadcastJob(ctx.push, message.body);
529
+ *
530
+ * if (nextCursor !== undefined) {
531
+ * // More pages remain — enqueue the continuation. Each message still
532
+ * // does only ONE bounded page of work.
533
+ * await enqueuePushBroadcast(ctx.queues.push, {
534
+ * payload: message.body.payload,
535
+ * filter: { ...message.body.filter, after: nextCursor },
536
+ * });
537
+ * }
538
+ * }
539
+ * }});
540
+ * ```
541
+ */
542
+ declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
543
+ /**
544
+ * Run ONE bounded page of an enqueued broadcast job on the consumer side,
545
+ * delivering through the push facade's {@link LunoraPush.broadcastPage} (which
546
+ * reuses the engine's retry + circuit-breaker middleware and prunes gone
547
+ * subscriptions).
548
+ *
549
+ * RETRY / CONTINUATION SEMANTICS (rewritten for plan 222 / NOTIFY-01 — a
550
+ * broadcast job used to process the WHOLE audience in one message, which could
551
+ * exceed Worker CPU/wall limits for a large audience and made a retry re-run
552
+ * everything):
553
+ *
554
+ * - A job now processes exactly ONE bounded page (see `CreateNotifyOptions`'s
555
+ * page-size option, default 250, or `job.filter.limit` when smaller),
556
+ * keyset-paginated on the subscription `id` (see `SubscriptionFilter.after`)
557
+ * — so per-message work is bounded regardless of total audience size.
558
+ * - Retry is still gated on `result.failed` — the count of TRANSIENT delivery
559
+ * errors (a provider 5xx / network fault worth another attempt). When at
560
+ * least one recipient in THIS PAGE `failed`, the job is RE-THROWN so the
561
+ * queue does NOT ack it and its normal retry/backoff (and, on exhaustion,
562
+ * dead-letter) applies — to just this page, not the whole broadcast.
563
+ * - A page with zero `failed` resolves and is acked — this includes the
564
+ * all-`pruned` case (every device on the page had unsubscribed:
565
+ * `sent:0`, `failed:0`, `pruned:N`), which is a SUCCESSFUL prune, not a
566
+ * failure, so throwing on it would spuriously retry and pressure the DLQ;
567
+ * and the empty-page case (zero `total`), which has nothing to retry.
568
+ * - The returned `nextCursor` is set when more pages remain. `@lunora/notify`
569
+ * does NOT enqueue the continuation itself — it has no `@lunora/queue`
570
+ * dependency (the seam stays structural) and no reference to the producer
571
+ * that enqueued this message — so the CALLER (the `lunora/queues.ts`
572
+ * consumer) is responsible for re-enqueueing with `filter.after: nextCursor`
573
+ * when present. See the consumer example on {@link enqueuePushBroadcast}.
574
+ * - A retry of a page redelivers only that page's already-delivered recipients
575
+ * on a transient partial failure (a page is not individually idempotent) —
576
+ * the accepted cost of getting the transiently failed ones redelivered, now
577
+ * scoped to one page instead of the whole broadcast.
578
+ */
579
+ declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<BroadcastPageResult>;
580
+ /**
581
+ * The minimal structural slice of Cloudflare's `D1Database` this store uses. A
582
+ * structural type (rather than importing `@cloudflare/workers-types`) keeps the
583
+ * store runtime-agnostic and trivially fakeable in tests.
584
+ */
585
+ interface D1Like {
586
+ prepare: (query: string) => D1PreparedLike;
587
+ }
588
+ interface D1PreparedLike {
589
+ all: <T = Record<string, unknown>>() => Promise<{
590
+ results: T[];
591
+ }>;
592
+ bind: (...values: unknown[]) => D1PreparedLike;
593
+ first: <T = Record<string, unknown>>() => Promise<T | null>;
594
+ run: () => Promise<unknown>;
595
+ }
596
+ /** Options for {@link d1SubscriptionStore}. */
597
+ interface D1StoreOptions {
598
+ /** Table name (default `lunora_push_subscriptions`). Must be a bare identifier. */
599
+ tableName?: string;
600
+ }
601
+ /**
602
+ * A D1-backed {@link SubscriptionStore}. Edge-safe (D1 is a Worker binding). The
603
+ * backing table is created lazily on first use (`CREATE TABLE IF NOT EXISTS`), so
604
+ * no migration step is required for the subscription table itself.
605
+ *
606
+ * ID SCHEME / LAZY MIGRATION: `id` (the `PRIMARY KEY`, upserted via `ON
607
+ * CONFLICT(id) DO UPDATE`) is a version-prefixed digest of the endpoint/token —
608
+ * currently `wp2_`/`fcm2_` (64-bit FNV-1a; see `normalize.ts`). No table migration
609
+ * runs when the id scheme is revised: a returning device re-registers under its new
610
+ * id and upserts a fresh row, while its old-prefix row (`wp_`/`fcm_`) ages out via
611
+ * the normal gone-pruning on the next failed send. So a table can transiently hold
612
+ * both an old- and new-prefix row for one device — expected, self-healing, and the
613
+ * reason a prefix must NEVER be reused for a different scheme.
614
+ *
615
+ * ```ts
616
+ * export default defineNotify({
617
+ * webPush: (env) => webPushFromEnv(env),
618
+ * store: (env) => d1SubscriptionStore(env.DB),
619
+ * });
620
+ * ```
621
+ */
622
+ declare const d1SubscriptionStore: (database: D1Like, options?: D1StoreOptions) => SubscriptionStore;
623
+ /**
624
+ * An in-memory {@link SubscriptionStore} — the zero-dependency default. Suitable
625
+ * for tests, local dev and a single-isolate app, but **not durable**: entries live
626
+ * only for the isolate's lifetime. Use {@link import("./d1-store").d1SubscriptionStore}
627
+ * (or another backing store) for production so subscriptions survive restarts.
628
+ */
629
+ declare const memorySubscriptionStore: () => SubscriptionStore;
630
+ /**
631
+ * Stable store id for a web-push endpoint.
632
+ *
633
+ * The `wp2_` prefix is a version tag (see also {@link fcmId}'s `fcm2_`): it marks
634
+ * the 64-bit-id revision so the pre-existing 32-bit `wp_` rows stay readable and a
635
+ * returning device simply re-registers under the new id, its stale `wp_` row aging
636
+ * out via normal gone-pruning. A future third revision must mint `wp3_` and repeat
637
+ * the lazy migration — NEVER reuse a prefix.
638
+ */
639
+ declare const webPushId: (endpoint: string) => string;
640
+ /** Stable store id for an FCM device token. See {@link webPushId} for the `_2` version-prefix contract. */
641
+ declare const fcmId: (token: string) => string;
642
+ /** Options threaded into {@link normalizeRegisterInput} from the notify definition. */
643
+ interface NormalizeOptions {
644
+ /**
645
+ * Exact origins (`https://host[:port]`) a web-push endpoint may register from.
646
+ * When set (non-empty), the endpoint's origin must be one of these — the
647
+ * strongest anti-SSRF posture, and the ONLY way to close DNS rebinding for a
648
+ * facade that accepts client-controlled endpoints.
649
+ *
650
+ * When unset, the default posture applies: `https:` scheme + a host the
651
+ * {@link assertPushEndpoint} STRING classifier does not flag as
652
+ * private/loopback. That classifier does NOT resolve DNS, so a public hostname
653
+ * resolving to a private/internal IP (e.g. `https://127.0.0.1.nip.io/…`) is NOT
654
+ * blocked by it — set this allowlist to close that gap.
655
+ */
656
+ allowedPushOrigins?: string[];
657
+ }
658
+ /**
659
+ * Normalise a `register(...)` input into a {@link StoredSubscription}. Validates
660
+ * the shape (a web-push subscription needs `endpoint` + `keys.{p256dh,auth}`; an
661
+ * FCM entry needs a non-empty `token`), enforces the anti-SSRF endpoint boundary
662
+ * (see {@link assertPushEndpoint}), validates `metadata` (see
663
+ * {@link validateMetadata}), and stamps `createdAt`/`lastSeenAt`.
664
+ */
665
+ declare const normalizeRegisterInput: (input: RegisterInput, now?: number, options?: NormalizeOptions) => StoredSubscription;
666
+ /**
667
+ * The provider `to` target for a stored subscription: the W3C Push subscription
668
+ * (JSON-stringified) for web-push, or the raw device token for FCM. Matches the
669
+ * shapes the `@visulima/notification` web-push / fcm providers accept.
670
+ */
671
+ declare const targetOf: (subscription: StoredSubscription) => string;
672
+ /**
673
+ * Whether a provider error message indicates the subscription is permanently gone
674
+ * (the browser/device unsubscribed) and should be pruned — as opposed to a
675
+ * transient failure worth retrying.
676
+ *
677
+ * Gates on STRUCTURED signals first: a Web Push `HTTP 404/410` status or an FCM
678
+ * `UNREGISTERED`/`NOT_REGISTERED` code, both of which the providers surface in
679
+ * their failure receipts. The free-text {@link GONE_TEXT_FALLBACK} is a tightened
680
+ * last resort only, so a transient error that happens to contain `expired`
681
+ * (a cert/session expiry) can never permanently drop a valid subscription.
682
+ */
683
+ declare const isGoneError: (message: string | undefined) => boolean;
684
+ 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 };