@lunora/notify 0.0.0 → 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,425 @@
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
+ /** Restrict to a delivery kind. */
79
+ kind?: SubscriptionKind;
80
+ /** Restrict to a single owning user. */
81
+ userId?: string | null;
82
+ }
83
+ /**
84
+ * Persistence for device subscriptions. Implementations back `ctx.push`'s
85
+ * lifecycle (register, list, prune). Ships with an in-memory store (tests/dev)
86
+ * and a D1-backed store (durable, edge-safe).
87
+ */
88
+ interface SubscriptionStore {
89
+ /** Remove a subscription by id (idempotent). */
90
+ delete: (id: string) => Promise<void>;
91
+ /** Read a subscription by id, or `undefined`. */
92
+ get: (id: string) => Promise<StoredSubscription | undefined>;
93
+ /** List subscriptions, optionally filtered. */
94
+ list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
95
+ /** Record the latest delivery outcome for a subscription (best-effort). */
96
+ markStatus: (id: string, status: SubscriptionStatus, error?: string) => Promise<void>;
97
+ /** Insert or update a subscription (upsert by id). */
98
+ put: (subscription: StoredSubscription) => Promise<StoredSubscription>;
99
+ }
100
+ /** Per-recipient outcome from a fan-out `broadcast`. */
101
+ interface BroadcastOutcome {
102
+ /** Delivery error message when `status` is not `ok`. */
103
+ error?: string;
104
+ /** The subscription this outcome belongs to. */
105
+ id: string;
106
+ /** `expired` subscriptions were pruned from the store. */
107
+ status: SubscriptionStatus;
108
+ }
109
+ /** Aggregate result of a `broadcast`. */
110
+ interface BroadcastResult {
111
+ /** Number of subscriptions that failed (non-gone). */
112
+ failed: number;
113
+ /** Per-subscription outcomes. */
114
+ outcomes: BroadcastOutcome[];
115
+ /** Number of pruned (gone/expired) subscriptions. */
116
+ pruned: number;
117
+ /** Number of subscriptions delivered successfully. */
118
+ sent: number;
119
+ /** Total subscriptions attempted. */
120
+ total: number;
121
+ }
122
+ /**
123
+ * The push sub-facade — spliced onto ctx as `ctx.push` (and reachable as
124
+ * `ctx.notify.push`). Owns the device-subscription lifecycle plus targeted and
125
+ * fan-out push delivery through the edge-safe Web Push / FCM providers.
126
+ */
127
+ interface LunoraPush {
128
+ /**
129
+ * Fan-out a push to every stored subscription matching `filter` (default: all).
130
+ * Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
131
+ * the push service reports as gone (HTTP 404/410, FCM `UNREGISTERED`). The `to`
132
+ * target is derived from each subscription, so it is omitted from the payload.
133
+ */
134
+ broadcast: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastResult>;
135
+ /** List stored subscriptions (optionally filtered). */
136
+ list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
137
+ /** Register (upsert) a device subscription and return the stored record. */
138
+ register: (input: RegisterInput) => Promise<StoredSubscription>;
139
+ /** Send a push to a single stored subscription (by id or record); `to` is derived from it. */
140
+ send: (target: StoredSubscription | string, payload: PushContent) => Promise<Receipt>;
141
+ /** Remove a subscription by id (idempotent). */
142
+ unregister: (id: string) => Promise<void>;
143
+ }
144
+ /** A push payload without its `to` target — the facade derives `to` from the stored subscription. */
145
+ type PushContent = Omit<PushPayload, "to">;
146
+ /**
147
+ * The multi-channel notification facade — spliced onto ctx as `ctx.notify`.
148
+ * `send` delivers a fully-specified multi-channel message through the engine;
149
+ * `push` is the device-push sub-facade; `chat` / `inApp` / `webhook` are
150
+ * single-channel convenience senders for the edge-safe channels.
151
+ */
152
+ interface LunoraNotify {
153
+ /** Send an outbound webhook. */
154
+ chat: (payload: ChatPayload) => Promise<Receipt>;
155
+ /** Deliver an in-app inbox notification. */
156
+ inApp: (payload: InAppPayload) => Promise<Receipt>;
157
+ /** The device-push sub-facade (identical object to `ctx.push`). */
158
+ push: LunoraPush;
159
+ /** Deliver a multi-channel message (one payload per channel). */
160
+ send: (message: NotificationMessage) => Promise<Receipt[]>;
161
+ /** Post to a chat channel (Slack/Discord/Teams/Telegram). */
162
+ webhook: (payload: WebhookPayload) => Promise<Receipt>;
163
+ }
164
+ /**
165
+ * Resolves a channel provider factory from the Worker `env`. Receiving `env`
166
+ * (rather than a constructed provider) lets a config read VAPID/FCM secrets and
167
+ * bindings at request time. Return `undefined` to leave the channel unwired.
168
+ */
169
+ type WebPushConfigFactory = (env: NotifyEnv) => WebPushConfig | undefined;
170
+ type FcmConfigFactory = (env: NotifyEnv) => FcmConfig | undefined;
171
+ /** Options accepted by `defineNotify`. */
172
+ interface NotifyConfig {
173
+ /**
174
+ * Optional chat provider factory (Slack/Discord/Teams/Telegram). Wire with a
175
+ * provider from `@visulima/notification/providers/*`. Edge-safe (fetch-based).
176
+ */
177
+ chat?: (env: NotifyEnv) => unknown;
178
+ /** FCM (Firebase Cloud Messaging HTTP v1) config. Edge-safe — supply an OAuth2 token. */
179
+ fcm?: FcmConfig | FcmConfigFactory;
180
+ /** Optional in-app inbox provider factory. Edge-safe. */
181
+ inApp?: (env: NotifyEnv) => unknown;
182
+ /**
183
+ * Builds the subscription store from `env` (usually a D1-backed store from a
184
+ * binding). Defaults to a non-durable in-memory store with a dev warning.
185
+ */
186
+ store?: (env: NotifyEnv) => SubscriptionStore;
187
+ /** Optional outbound-webhook provider factory. Edge-safe (fetch-based). */
188
+ webhook?: (env: NotifyEnv) => unknown;
189
+ /** Web Push (VAPID + RFC 8291) config. Fully edge-safe (Web Crypto only). */
190
+ webPush?: WebPushConfig | WebPushConfigFactory;
191
+ }
192
+ /**
193
+ * A branded {@link NotifyConfig} produced by `defineNotify`. This is the default
194
+ * export of `lunora/notify.ts`; codegen imports it into the generated worker and
195
+ * wires `ctx.notify` / `ctx.push` from it (mirroring `defineFlags` → `ctx.flags`).
196
+ */
197
+ interface NotifyDefinition extends NotifyConfig {
198
+ /** Runtime brand used by `isNotifyDefinition` and codegen discovery. */
199
+ readonly isLunoraNotify: true;
200
+ }
201
+ /**
202
+ * `.dev.vars` / Worker `env` keys the built-in config resolvers read. Mirrored in
203
+ * `@lunora/config`'s package-secrets registry so `lunora dev` scaffolds them into
204
+ * `.dev.vars.example`.
205
+ */
206
+ declare const WEB_PUSH_ENV_KEYS: {
207
+ readonly privateKey: "VAPID_PRIVATE_KEY";
208
+ readonly publicKey: "VAPID_PUBLIC_KEY";
209
+ readonly subject: "VAPID_SUBJECT";
210
+ };
211
+ declare const FCM_ENV_KEYS: {
212
+ readonly accessToken: "FCM_ACCESS_TOKEN";
213
+ readonly projectId: "FCM_PROJECT_ID";
214
+ };
215
+ /**
216
+ * Resolve a {@link WebPushConfig} from the Worker `env` VAPID secrets
217
+ * (`VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY`, `VAPID_SUBJECT`). Returns `undefined`
218
+ * when any is missing, leaving the Web Push channel unwired rather than throwing —
219
+ * so an app can ship FCM-only (or vice versa) without failing ctx construction.
220
+ *
221
+ * Generate a VAPID keypair once with `npx web-push generate-vapid-keys` (or any
222
+ * P-256 tool) and set `VAPID_SUBJECT` to a `mailto:` or `https:` contact.
223
+ */
224
+ declare const webPushFromEnv: (env: NotifyEnv, overrides?: Partial<WebPushConfig>) => WebPushConfig | undefined;
225
+ /**
226
+ * Resolve an {@link FcmConfig} from the Worker `env` (`FCM_PROJECT_ID` plus a
227
+ * static `FCM_ACCESS_TOKEN`). Returns `undefined` when the project id is missing.
228
+ *
229
+ * The static token is convenient for local dev but expires; in production prefer
230
+ * passing your own `getAccessToken` (e.g. wrapping `google-auth-library`) via
231
+ * `defineNotify({ fcm: (env) => ({ ...fcmFromEnv(env), getAccessToken }) })` —
232
+ * that keeps the provider edge-safe (no Google SDK / `node:crypto` bundled).
233
+ */
234
+ declare const fcmFromEnv: (env: NotifyEnv, overrides?: Partial<FcmConfig>) => FcmConfig | undefined;
235
+ /**
236
+ * Declare the notification channels for a Lunora app. Pure validation +
237
+ * branding — codegen discovers the default export of `lunora/notify.ts`, imports
238
+ * it into the generated worker, and wires `ctx.notify` / `ctx.push` from it
239
+ * (mirrors how `defineFlags` feeds codegen to build `ctx.flags`).
240
+ *
241
+ * ```ts
242
+ * // lunora/notify.ts
243
+ * import { defineNotify, webPushFromEnv, fcmFromEnv } from "@lunora/notify";
244
+ * import { d1SubscriptionStore } from "@lunora/notify";
245
+ *
246
+ * export default defineNotify({
247
+ * webPush: (env) => webPushFromEnv(env), // VAPID_* from .dev.vars
248
+ * fcm: (env) => fcmFromEnv(env), // FCM_PROJECT_ID / FCM_ACCESS_TOKEN
249
+ * store: (env) => d1SubscriptionStore(env.DB),
250
+ * });
251
+ * ```
252
+ *
253
+ * Only edge-safe channels are wired here — Web Push and FCM run on Web Crypto +
254
+ * `fetch` under workerd. APNs (`node:http2`) and SMS/Node-only queue adapters are
255
+ * intentionally **not** exposed on the edge facade; route heavy fan-out through
256
+ * `@lunora/queue` instead (see `broadcastViaQueue`).
257
+ */
258
+ declare const defineNotify: (config: NotifyConfig) => NotifyDefinition;
259
+ /** True when a value is a {@link defineNotify} result (the runtime brand check). */
260
+ declare const isNotifyDefinition: (value: unknown) => value is NotifyDefinition;
261
+ /** Options for {@link createNotify}. */
262
+ interface CreateNotifyOptions {
263
+ /** Max concurrent sends during a `broadcast` (default 10). */
264
+ concurrency?: number;
265
+ /**
266
+ * Override the assembled `@visulima/notification` engine. Advanced/testing
267
+ * seam — pass a `Notification` built with your own (mock) providers to bypass
268
+ * config resolution entirely.
269
+ */
270
+ engine?: Notification;
271
+ /** Suppress the in-memory-store dev warning (tests set this). */
272
+ silent?: boolean;
273
+ }
274
+ /**
275
+ * Build the `ctx.notify` / `ctx.push` facades for a request from a
276
+ * {@link NotifyDefinition} (the `lunora/notify.ts` default export) and the Worker
277
+ * `env`. Codegen calls this to splice the facades onto ctx — the same shape as
278
+ * `createFlags` for `ctx.flags`. Returns both facades; `notify.push` is the very
279
+ * same object exposed as `ctx.push`.
280
+ *
281
+ * The engine and the dev fallback store are memoized per isolate (see
282
+ * {@link NotifyRuntime}), so repeat calls with the same `definition`/`env` are
283
+ * cheap — only the thin facade closures below are rebuilt each call.
284
+ */
285
+ declare const createNotify: (definition: NotifyDefinition, env: NotifyEnv, options?: CreateNotifyOptions) => {
286
+ notify: LunoraNotify;
287
+ push: LunoraPush;
288
+ };
289
+ /** Options for {@link routingPushProvider}. */
290
+ interface RoutingPushOptions {
291
+ fcm?: Provider<unknown, PushPayload>;
292
+ webPush?: Provider<unknown, PushPayload>;
293
+ }
294
+ /**
295
+ * A composite push {@link Provider} that dispatches each send to the Web Push or
296
+ * FCM provider by the shape of the payload `to` target — so a single `push`
297
+ * channel on the {@link Notification} facade transparently handles both browser
298
+ * subscriptions and mobile device tokens, and the engine's middleware wraps them
299
+ * uniformly.
300
+ */
301
+ declare const routingPushProvider: (options: RoutingPushOptions) => Provider<unknown, PushPayload>;
302
+ /** A resolved, ready-to-wire set of channel configs (edge-safe channels only). */
303
+ interface ResolvedProviders {
304
+ chat?: Provider;
305
+ fcm?: FcmConfig;
306
+ inApp?: Provider;
307
+ webhook?: Provider;
308
+ webPush?: WebPushConfig;
309
+ }
310
+ /**
311
+ * Assemble the `@visulima/notification` engine from resolved channel configs and
312
+ * attach the reused retry + circuit-breaker middleware. Only edge-safe channels
313
+ * are wired (Web Push, FCM, chat, in-app, webhook); APNs and SMS are excluded
314
+ * from the edge facade by construction.
315
+ */
316
+ declare const buildEngine: (resolved: ResolvedProviders) => Notification;
317
+ /**
318
+ * A broadcast job body — the JSON-serialisable payload enqueued for off-request
319
+ * fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
320
+ * `@lunora/notify` depending on `@lunora/queue` (the seam stays structural).
321
+ */
322
+ interface PushBroadcastJob {
323
+ /** Subscription filter (which devices/users to target). */
324
+ filter?: SubscriptionFilter;
325
+ /** The push payload to deliver (the `to` target is derived per subscription). */
326
+ payload: PushContent;
327
+ /** Discriminator so a shared queue can multiplex message kinds. */
328
+ type: "lunora.push.broadcast";
329
+ }
330
+ /** The structural slice of a `@lunora/queue` producer (`ctx.queues.&lt;name>`) used here. */
331
+ interface QueueProducerLike {
332
+ send: (body: PushBroadcastJob) => Promise<void>;
333
+ }
334
+ /**
335
+ * Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
336
+ * queue instead of blocking the request. Pair with {@link runPushBroadcastJob} in
337
+ * the queue consumer.
338
+ *
339
+ * ```ts
340
+ * // in a mutation/action:
341
+ * await enqueuePushBroadcast(ctx.queues.push, { payload: { title: "New drop", body: "…" } });
342
+ *
343
+ * // in lunora/queues.ts consumer:
344
+ * export const push = defineQueue({ async handler(batch, ctx) {
345
+ * for (const message of batch.messages) await runPushBroadcastJob(ctx.push, message.body);
346
+ * }});
347
+ * ```
348
+ */
349
+ declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
350
+ /**
351
+ * Run an enqueued broadcast job on the consumer side, delivering through the push
352
+ * facade (which reuses the engine's retry + circuit-breaker middleware and prunes
353
+ * gone subscriptions).
354
+ */
355
+ declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<unknown>;
356
+ /**
357
+ * The minimal structural slice of Cloudflare's `D1Database` this store uses. A
358
+ * structural type (rather than importing `@cloudflare/workers-types`) keeps the
359
+ * store runtime-agnostic and trivially fakeable in tests.
360
+ */
361
+ interface D1Like {
362
+ prepare: (query: string) => D1PreparedLike;
363
+ }
364
+ interface D1PreparedLike {
365
+ all: <T = Record<string, unknown>>() => Promise<{
366
+ results: T[];
367
+ }>;
368
+ bind: (...values: unknown[]) => D1PreparedLike;
369
+ first: <T = Record<string, unknown>>() => Promise<T | null>;
370
+ run: () => Promise<unknown>;
371
+ }
372
+ /** Options for {@link d1SubscriptionStore}. */
373
+ interface D1StoreOptions {
374
+ /** Table name (default `lunora_push_subscriptions`). Must be a bare identifier. */
375
+ tableName?: string;
376
+ }
377
+ /**
378
+ * A D1-backed {@link SubscriptionStore}. Edge-safe (D1 is a Worker binding). The
379
+ * backing table is created lazily on first use (`CREATE TABLE IF NOT EXISTS`), so
380
+ * no migration step is required for the subscription table itself.
381
+ *
382
+ * ```ts
383
+ * export default defineNotify({
384
+ * webPush: (env) => webPushFromEnv(env),
385
+ * store: (env) => d1SubscriptionStore(env.DB),
386
+ * });
387
+ * ```
388
+ */
389
+ declare const d1SubscriptionStore: (database: D1Like, options?: D1StoreOptions) => SubscriptionStore;
390
+ /**
391
+ * An in-memory {@link SubscriptionStore} — the zero-dependency default. Suitable
392
+ * for tests, local dev and a single-isolate app, but **not durable**: entries live
393
+ * only for the isolate's lifetime. Use {@link import("./d1-store").d1SubscriptionStore}
394
+ * (or another backing store) for production so subscriptions survive restarts.
395
+ */
396
+ declare const memorySubscriptionStore: () => SubscriptionStore;
397
+ /** Stable store id for a web-push endpoint. */
398
+ declare const webPushId: (endpoint: string) => string;
399
+ /** Stable store id for an FCM device token. */
400
+ declare const fcmId: (token: string) => string;
401
+ /**
402
+ * Normalise a `register(...)` input into a {@link StoredSubscription}. Validates
403
+ * the shape (a web-push subscription needs `endpoint` + `keys.{p256dh,auth}`; an
404
+ * FCM entry needs a non-empty `token`) and stamps `createdAt`/`lastSeenAt`.
405
+ */
406
+ declare const normalizeRegisterInput: (input: RegisterInput, now?: number) => StoredSubscription;
407
+ /**
408
+ * The provider `to` target for a stored subscription: the W3C Push subscription
409
+ * (JSON-stringified) for web-push, or the raw device token for FCM. Matches the
410
+ * shapes the `@visulima/notification` web-push / fcm providers accept.
411
+ */
412
+ declare const targetOf: (subscription: StoredSubscription) => string;
413
+ /**
414
+ * Whether a provider error message indicates the subscription is permanently gone
415
+ * (the browser/device unsubscribed) and should be pruned — as opposed to a
416
+ * transient failure worth retrying.
417
+ *
418
+ * Gates on STRUCTURED signals first: a Web Push `HTTP 404/410` status or an FCM
419
+ * `UNREGISTERED`/`NOT_REGISTERED` code, both of which the providers surface in
420
+ * their failure receipts. The free-text {@link GONE_TEXT_FALLBACK} is a tightened
421
+ * last resort only, so a transient error that happens to contain `expired`
422
+ * (a cert/session expiry) can never permanently drop a valid subscription.
423
+ */
424
+ declare const isGoneError: (message: string | undefined) => boolean;
425
+ 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 NotifyEnv, 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 };
package/dist/index.mjs ADDED
@@ -0,0 +1,8 @@
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-Gg40Htm-.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';
@@ -0,0 +1,32 @@
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 };
@@ -0,0 +1,65 @@
1
+ import { createNotification } from '@visulima/notification';
2
+ import { retryMiddleware, circuitBreakerMiddleware } from '@visulima/notification/middleware';
3
+ import { fcmProvider } from '@visulima/notification/providers/fcm';
4
+ import { webPushProvider } from '@visulima/notification/providers/web-push';
5
+
6
+ const isWebPushTarget = (target) => {
7
+ if (typeof target !== "string") {
8
+ return typeof target === "object" && target !== null && "endpoint" in target;
9
+ }
10
+ if (!target.startsWith("{")) {
11
+ return false;
12
+ }
13
+ try {
14
+ const parsed = JSON.parse(target);
15
+ return typeof parsed.endpoint === "string" && typeof parsed.keys === "object";
16
+ } catch {
17
+ return false;
18
+ }
19
+ };
20
+ const routingPushProvider = (options) => {
21
+ const pick = (target) => {
22
+ const provider = isWebPushTarget(target) ? options.webPush : options.fcm;
23
+ if (provider === void 0) {
24
+ throw new Error(
25
+ isWebPushTarget(target) ? "@lunora/notify: received a web-push target but no `webPush` channel is configured" : "@lunora/notify: received an FCM token target but no `fcm` channel is configured"
26
+ );
27
+ }
28
+ return provider;
29
+ };
30
+ return {
31
+ channel: "push",
32
+ id: "lunora-push-router",
33
+ initialize: async () => {
34
+ await options.webPush?.initialize();
35
+ await options.fcm?.initialize();
36
+ },
37
+ isAvailable: () => (options.webPush ?? options.fcm) !== void 0,
38
+ send: (payload) => {
39
+ const target = Array.isArray(payload.to) ? payload.to[0] : payload.to;
40
+ return pick(target).send(payload);
41
+ }
42
+ };
43
+ };
44
+ const buildEngine = (resolved) => {
45
+ const webPush = resolved.webPush === void 0 ? void 0 : webPushProvider(resolved.webPush);
46
+ const fcm = resolved.fcm === void 0 ? void 0 : fcmProvider(resolved.fcm);
47
+ const providers = {};
48
+ if (webPush !== void 0 || fcm !== void 0) {
49
+ providers.push = routingPushProvider({ fcm, webPush });
50
+ }
51
+ if (resolved.chat !== void 0) {
52
+ providers.chat = resolved.chat;
53
+ }
54
+ if (resolved.inApp !== void 0) {
55
+ providers.inapp = resolved.inApp;
56
+ }
57
+ if (resolved.webhook !== void 0) {
58
+ providers.webhook = resolved.webhook;
59
+ }
60
+ const engine = createNotification(providers);
61
+ engine.use(retryMiddleware()).use(circuitBreakerMiddleware());
62
+ return engine;
63
+ };
64
+
65
+ export { buildEngine, routingPushProvider };
@@ -0,0 +1,128 @@
1
+ import { LunoraError } from '@lunora/errors';
2
+ import { buildEngine } from './buildEngine-DlmjvnNk.mjs';
3
+ import { memorySubscriptionStore } from './memorySubscriptionStore-DhS-YnLe.mjs';
4
+ import { normalizeRegisterInput, targetOf, isGoneError } from './fcmId-B-YPgHi7.mjs';
5
+
6
+ const resolveMaybeFactory = (value, env) => typeof value === "function" ? value(env) : value;
7
+ const receiptError = (receipt) => receipt.successful ? void 0 : receipt.errorMessages.join("; ");
8
+ const mapWithConcurrency = async (items, limit, task) => {
9
+ const results = Array.from({ length: items.length });
10
+ let cursor = 0;
11
+ const worker = async () => {
12
+ while (cursor < items.length) {
13
+ const index = cursor;
14
+ cursor += 1;
15
+ results[index] = await task(items[index]);
16
+ }
17
+ };
18
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
19
+ return results;
20
+ };
21
+ const resolveProviders = (definition, env) => {
22
+ return {
23
+ chat: resolveMaybeFactory(definition.chat, env),
24
+ fcm: resolveMaybeFactory(definition.fcm, env),
25
+ inApp: resolveMaybeFactory(definition.inApp, env),
26
+ webhook: resolveMaybeFactory(definition.webhook, env),
27
+ webPush: resolveMaybeFactory(definition.webPush, env)
28
+ };
29
+ };
30
+ const runtimeCache = /* @__PURE__ */ new WeakMap();
31
+ const runtimeFor = (definition, env) => {
32
+ let byEnv = runtimeCache.get(definition);
33
+ if (byEnv === void 0) {
34
+ byEnv = /* @__PURE__ */ new WeakMap();
35
+ runtimeCache.set(definition, byEnv);
36
+ }
37
+ let runtime = byEnv.get(env);
38
+ if (runtime === void 0) {
39
+ runtime = { warnedNoStore: false };
40
+ byEnv.set(env, runtime);
41
+ }
42
+ return runtime;
43
+ };
44
+ const createNotify = (definition, env, options = {}) => {
45
+ const runtime = runtimeFor(definition, env);
46
+ let engine;
47
+ if (options.engine === void 0) {
48
+ runtime.engine ??= buildEngine(resolveProviders(definition, env));
49
+ engine = runtime.engine;
50
+ } else {
51
+ engine = options.engine;
52
+ }
53
+ let store = definition.store?.(env);
54
+ if (store === void 0) {
55
+ runtime.fallbackStore ??= memorySubscriptionStore();
56
+ if (!options.silent && !runtime.warnedNoStore) {
57
+ runtime.warnedNoStore = true;
58
+ console.warn(
59
+ "@lunora/notify: no `store` configured — using a non-durable in-memory subscription store. Configure `store: (env) => d1SubscriptionStore(env.DB)` for production."
60
+ );
61
+ }
62
+ store = runtime.fallbackStore;
63
+ }
64
+ const subscriptionStore = store;
65
+ const concurrency = Math.max(1, options.concurrency ?? 10);
66
+ const resolveSubscription = async (target) => {
67
+ if (typeof target !== "string") {
68
+ return target;
69
+ }
70
+ const found = await subscriptionStore.get(target);
71
+ if (found === void 0) {
72
+ throw new LunoraError("BAD_REQUEST", `@lunora/notify: no registered subscription with id "${target}"`);
73
+ }
74
+ return found;
75
+ };
76
+ const deliver = async (subscription, payload) => {
77
+ const receipt = await engine.sendToChannel("push", { ...payload, to: targetOf(subscription) });
78
+ const error = receiptError(receipt);
79
+ if (receipt.successful) {
80
+ await subscriptionStore.markStatus(subscription.id, "ok");
81
+ } else if (isGoneError(error)) {
82
+ await subscriptionStore.delete(subscription.id);
83
+ } else {
84
+ await subscriptionStore.markStatus(subscription.id, "failed", error);
85
+ }
86
+ return receipt;
87
+ };
88
+ const push = {
89
+ broadcast: async (payload, filter) => {
90
+ const subscriptions = await subscriptionStore.list(filter);
91
+ const outcomes = await mapWithConcurrency(subscriptions, concurrency, async (subscription) => {
92
+ const receipt = await deliver(subscription, payload);
93
+ if (receipt.successful) {
94
+ return { id: subscription.id, status: "ok" };
95
+ }
96
+ const error = receiptError(receipt);
97
+ return isGoneError(error) ? { error, id: subscription.id, status: "expired" } : { error, id: subscription.id, status: "failed" };
98
+ });
99
+ return {
100
+ failed: outcomes.filter((outcome) => outcome.status === "failed").length,
101
+ outcomes,
102
+ pruned: outcomes.filter((outcome) => outcome.status === "expired").length,
103
+ sent: outcomes.filter((outcome) => outcome.status === "ok").length,
104
+ total: outcomes.length
105
+ };
106
+ },
107
+ list: (filter) => subscriptionStore.list(filter),
108
+ register: (input) => subscriptionStore.put(normalizeRegisterInput(input)),
109
+ send: async (target, payload) => deliver(await resolveSubscription(target), payload),
110
+ unregister: (id) => subscriptionStore.delete(id)
111
+ };
112
+ const sendToChannel = async (channel, payload) => {
113
+ if (engine.getProvider(channel) === void 0) {
114
+ throw new LunoraError("BAD_REQUEST", `@lunora/notify: the "${channel}" channel is not configured in defineNotify(...)`);
115
+ }
116
+ return engine.sendToChannel(channel, payload);
117
+ };
118
+ const notify = {
119
+ chat: (payload) => sendToChannel("chat", payload),
120
+ inApp: (payload) => sendToChannel("inapp", payload),
121
+ push,
122
+ send: (message) => engine.send(message),
123
+ webhook: (payload) => sendToChannel("webhook", payload)
124
+ };
125
+ return { notify, push };
126
+ };
127
+
128
+ export { createNotify };