@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.
- package/LICENSE.md +111 -0
- package/README.md +86 -28
- package/dist/index.d.mts +425 -0
- package/dist/index.d.ts +425 -0
- package/dist/index.mjs +8 -0
- package/dist/packem_shared/FCM_ENV_KEYS-DY4-A717.mjs +32 -0
- package/dist/packem_shared/buildEngine-DlmjvnNk.mjs +65 -0
- package/dist/packem_shared/createNotify-Gg40Htm-.mjs +128 -0
- package/dist/packem_shared/d1SubscriptionStore-Dv3VPMI_.mjs +107 -0
- package/dist/packem_shared/defineNotify-B6S_47C2.mjs +18 -0
- package/dist/packem_shared/enqueuePushBroadcast-DiK7Hyja.mjs +4 -0
- package/dist/packem_shared/fcmId-B-YPgHi7.mjs +68 -0
- package/dist/packem_shared/memorySubscriptionStore-DhS-YnLe.mjs +46 -0
- package/dist/web.d.mts +52 -0
- package/dist/web.d.ts +52 -0
- package/dist/web.mjs +44 -0
- package/package.json +55 -7
package/LICENSE.md
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# Functional Source License, Version 1.1, Apache 2.0 Future License
|
|
2
|
+
|
|
3
|
+
## Abbreviation
|
|
4
|
+
|
|
5
|
+
FSL-1.1-Apache-2.0
|
|
6
|
+
|
|
7
|
+
## Notice
|
|
8
|
+
|
|
9
|
+
Copyright 2026 anolilab and contributors
|
|
10
|
+
|
|
11
|
+
## Terms and Conditions
|
|
12
|
+
|
|
13
|
+
### Licensor ("We")
|
|
14
|
+
|
|
15
|
+
The party offering the Software under these Terms and Conditions.
|
|
16
|
+
|
|
17
|
+
### The Software
|
|
18
|
+
|
|
19
|
+
The "Software" is each version of the software that we make available under
|
|
20
|
+
these Terms and Conditions, as indicated by our inclusion of these Terms and
|
|
21
|
+
Conditions with the Software.
|
|
22
|
+
|
|
23
|
+
### License Grant
|
|
24
|
+
|
|
25
|
+
Subject to your compliance with this License Grant and the Patents,
|
|
26
|
+
Redistribution and Trademark clauses below, we hereby grant you the right to
|
|
27
|
+
use, copy, modify, create derivative works, publicly perform, publicly display
|
|
28
|
+
and redistribute the Software for any Permitted Purpose identified below.
|
|
29
|
+
|
|
30
|
+
### Permitted Purpose
|
|
31
|
+
|
|
32
|
+
A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
|
|
33
|
+
means making the Software available to others in a commercial product or service
|
|
34
|
+
that:
|
|
35
|
+
|
|
36
|
+
1. substitutes for the Software;
|
|
37
|
+
|
|
38
|
+
2. substitutes for any other product or service we offer using the Software that
|
|
39
|
+
exists as of the date we make the Software available; or
|
|
40
|
+
|
|
41
|
+
3. offers the same or substantially similar functionality as the Software.
|
|
42
|
+
|
|
43
|
+
Permitted Purposes specifically include using the Software:
|
|
44
|
+
|
|
45
|
+
1. for your internal use and access;
|
|
46
|
+
|
|
47
|
+
2. for non-commercial education;
|
|
48
|
+
|
|
49
|
+
3. for non-commercial research; and
|
|
50
|
+
|
|
51
|
+
4. in connection with professional services that you provide to a licensee using
|
|
52
|
+
the Software in accordance with these Terms and Conditions.
|
|
53
|
+
|
|
54
|
+
### Patents
|
|
55
|
+
|
|
56
|
+
To the extent your use for a Permitted Purpose would necessarily infringe our
|
|
57
|
+
patents, the license grant above includes a license under our patents. If you
|
|
58
|
+
make a claim against any party that the Software infringes or contributes to the
|
|
59
|
+
infringement of any patent, then your patent license to the Software ends
|
|
60
|
+
immediately.
|
|
61
|
+
|
|
62
|
+
### Redistribution
|
|
63
|
+
|
|
64
|
+
The Terms and Conditions apply to all copies, modifications and derivatives of
|
|
65
|
+
the Software.
|
|
66
|
+
|
|
67
|
+
If you redistribute any copies, modifications or derivatives of the Software,
|
|
68
|
+
you must include a copy of or a link to these Terms and Conditions and not
|
|
69
|
+
remove any copyright notices provided in or with the Software.
|
|
70
|
+
|
|
71
|
+
### Disclaimer
|
|
72
|
+
|
|
73
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
|
|
74
|
+
IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
|
|
75
|
+
PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
|
|
76
|
+
|
|
77
|
+
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
|
|
78
|
+
SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, EVEN
|
|
79
|
+
IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
|
|
80
|
+
|
|
81
|
+
### Trademarks
|
|
82
|
+
|
|
83
|
+
Except for displaying the License Details and identifying us as the origin of
|
|
84
|
+
the Software, you have no right under these Terms and Conditions to use our
|
|
85
|
+
trademarks, trade names, service marks or product names.
|
|
86
|
+
|
|
87
|
+
## Grant of Future License
|
|
88
|
+
|
|
89
|
+
We hereby irrevocably grant you an additional license to use the Software under
|
|
90
|
+
the Apache License, Version 2.0 that is effective on the second anniversary of
|
|
91
|
+
the date we make the Software available. On or after that date, you may use the
|
|
92
|
+
Software under the Apache License, Version 2.0, in which case the following will
|
|
93
|
+
apply:
|
|
94
|
+
|
|
95
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
96
|
+
this file except in compliance with the License.
|
|
97
|
+
|
|
98
|
+
You may obtain a copy of the License at
|
|
99
|
+
|
|
100
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
101
|
+
|
|
102
|
+
Unless required by applicable law or agreed to in writing, software distributed
|
|
103
|
+
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
|
104
|
+
CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
|
105
|
+
specific language governing permissions and limitations under the License.
|
|
106
|
+
|
|
107
|
+
<!-- DEPENDENCIES -->
|
|
108
|
+
<!-- /DEPENDENCIES -->
|
|
109
|
+
|
|
110
|
+
<!-- TYPE_DEPENDENCIES -->
|
|
111
|
+
<!-- /TYPE_DEPENDENCIES -->
|
package/README.md
CHANGED
|
@@ -1,45 +1,103 @@
|
|
|
1
1
|
# @lunora/notify
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Multi-channel notifications for Lunora, wrapping the [`@visulima/notification`](https://visulima.com/packages/notification) engine. Web Push + FCM first (both edge-safe under workerd), plus chat, in-app inbox, and webhook channels — with device-subscription storage and queue-backed fan-out.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
- `ctx.notify` — the multi-channel facade (`send`, `chat`, `inApp`, `webhook`, `push`).
|
|
6
|
+
- `ctx.push` — the device-push sub-facade (`register`, `send`, `broadcast`, `list`, `unregister`).
|
|
6
7
|
|
|
7
|
-
|
|
8
|
+
## Edge safety
|
|
8
9
|
|
|
9
|
-
|
|
10
|
+
Web Push (VAPID + RFC 8291) and FCM (HTTP v1) run on `fetch` + Web Crypto — no `node:*`. **APNs** (`node:http2`) and the **BullMQ / pg-boss / SQS** queue adapters are Node-only and are **not** wired into this facade; route heavy fan-out through `@lunora/queue`.
|
|
10
11
|
|
|
11
|
-
|
|
12
|
-
1. Configure OIDC trusted publishing for the package name `@lunora/notify`
|
|
13
|
-
2. Enable secure, token-less publishing from CI/CD workflows
|
|
14
|
-
3. Establish provenance for packages published under this name
|
|
12
|
+
## Configure
|
|
15
13
|
|
|
16
|
-
|
|
14
|
+
```ts
|
|
15
|
+
// lunora/notify.ts
|
|
16
|
+
import { defineNotify, webPushFromEnv, fcmFromEnv, d1SubscriptionStore } from "@lunora/notify";
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
export default defineNotify({
|
|
19
|
+
webPush: (env) => webPushFromEnv(env), // reads VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY / VAPID_SUBJECT
|
|
20
|
+
fcm: (env) => fcmFromEnv(env), // reads FCM_PROJECT_ID / FCM_ACCESS_TOKEN (prefer a getAccessToken in prod)
|
|
21
|
+
store: (env) => d1SubscriptionStore(env.DB),
|
|
22
|
+
});
|
|
23
|
+
```
|
|
19
24
|
|
|
20
|
-
|
|
25
|
+
`.dev.vars` (scaffolded by `lunora dev` from `@lunora/config`'s package-secrets registry):
|
|
21
26
|
|
|
22
|
-
|
|
27
|
+
```
|
|
28
|
+
VAPID_PUBLIC_KEY=<your-vapid-public-key>
|
|
29
|
+
VAPID_PRIVATE_KEY=<your-vapid-private-key>
|
|
30
|
+
VAPID_SUBJECT=mailto:you@example.com
|
|
31
|
+
FCM_PROJECT_ID=<your-firebase-project-id>
|
|
32
|
+
FCM_ACCESS_TOKEN=<your-fcm-access-token>
|
|
33
|
+
```
|
|
23
34
|
|
|
24
|
-
|
|
25
|
-
2. Configure the trusted publisher (e.g., GitHub Actions)
|
|
26
|
-
3. Specify the repository and workflow that should be allowed to publish
|
|
27
|
-
4. Use the configured workflow to publish your actual package
|
|
35
|
+
Generate a VAPID keypair once: `npx web-push generate-vapid-keys`.
|
|
28
36
|
|
|
29
|
-
##
|
|
37
|
+
## Register a device (browser)
|
|
30
38
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
- Provides no functionality
|
|
34
|
-
- Should not be installed as a dependency
|
|
35
|
-
- Exists only for administrative purposes
|
|
39
|
+
```ts
|
|
40
|
+
import { subscribeToPush } from "@lunora/notify/web";
|
|
36
41
|
|
|
37
|
-
|
|
42
|
+
const subscription = await subscribeToPush({ serviceWorkerUrl: "/sw.js", vapidPublicKey });
|
|
43
|
+
await client.mutation("registerDevice", { subscription });
|
|
44
|
+
```
|
|
38
45
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
46
|
+
```ts
|
|
47
|
+
// lunora/registerDevice.ts (a mutation — storage write is fine here)
|
|
48
|
+
export const registerDevice = mutation({
|
|
49
|
+
args: { subscription: v.any() },
|
|
50
|
+
handler: async (ctx, { subscription }) => {
|
|
51
|
+
await ctx.push.register({ subscription, userId: ctx.auth?.userId });
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
```
|
|
42
55
|
|
|
43
|
-
|
|
56
|
+
## Send (from an action)
|
|
44
57
|
|
|
45
|
-
**
|
|
58
|
+
Notification sends are external I/O, so they belong in **actions** (the `notify_send_outside_action` advisor lint enforces this):
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
export const announce = action({
|
|
62
|
+
args: { title: v.string(), body: v.string() },
|
|
63
|
+
handler: async (ctx, { title, body }) => {
|
|
64
|
+
const result = await ctx.push.broadcast({ title, body });
|
|
65
|
+
// result: { total, sent, pruned, failed, outcomes }
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`broadcast` reuses the engine's retry + circuit-breaker middleware and prunes subscriptions the push service reports as gone (HTTP 404/410, FCM `UNREGISTERED`). A single targeted send:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
await ctx.push.send(subscriptionId, { title: "Hi", body: "…" });
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Multi-channel through `ctx.notify.send`:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
await ctx.notify.send({
|
|
80
|
+
push: { title: "New drop", body: "…", to: pushTarget },
|
|
81
|
+
chat: { text: "New drop shipped" },
|
|
82
|
+
});
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Queue-backed fan-out
|
|
86
|
+
|
|
87
|
+
Move a large broadcast off the request path with `@lunora/queue`:
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
// producer (mutation/action)
|
|
91
|
+
await enqueuePushBroadcast(ctx.queues.push, { payload: { title: "New drop", body: "…" } });
|
|
92
|
+
|
|
93
|
+
// consumer (lunora/queues.ts)
|
|
94
|
+
for (const message of batch.messages) await runPushBroadcastJob(ctx.push, message.body);
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Subscription storage
|
|
98
|
+
|
|
99
|
+
`SubscriptionStore` implementations: `memorySubscriptionStore()` (non-durable default, tests/dev) and `d1SubscriptionStore(db)` (durable, edge-safe, lazy table creation). Lifecycle: register (upsert), list/filter (by kind or user), status marking, and automatic prune of gone subscriptions on send/broadcast.
|
|
100
|
+
|
|
101
|
+
## Status
|
|
102
|
+
|
|
103
|
+
Phases 0–2 and the Phase-3 advisor lints + queue-backed fan-out are shipped. Remaining: the codegen ctx-splice that auto-wires `ctx.notify` / `ctx.push` from `lunora/notify.ts` (mirroring `defineFlags` → `ctx.flags`; `createNotify` is the factory it calls), the codegen advisor feeder, and the Studio Notifications page. See `plans/165-push-notifications.md`.
|
package/dist/index.d.mts
ADDED
|
@@ -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.<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 };
|