@useherald/core 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { T as Targets, P as ProcessOptions, a as ProcessSummary, I as InboxQuery, b as InboxPage, S as Store, R as ResolvePreferences, c as ResolveAddress, H as Hooks, L as Logger, d as RetryPolicy } from './store-BaqPfkS_.js';
2
+ export { C as ClaimedDelivery, D as DeliveryInfo, e as DeliveryPage, f as DeliveryQuery, g as DeliveryRecord, h as DeliveryResult, i as DeliveryStatus, j as InboxItem, k as ListedDelivery, N as NewDelivery, l as NewNotification, m as NotificationRecord, n as Priority, o as RawTarget, p as RecipientRef, q as TerminalStatus } from './store-BaqPfkS_.js';
3
+
1
4
  interface SendContext {
2
5
  /** Stable per delivery across retries. Pass to providers that dedupe. */
3
6
  idempotencyKey: string;
@@ -63,257 +66,6 @@ type Conform<D, Ch extends ChannelMap> = D extends EventDef<infer P, infer K, an
63
66
  };
64
67
  } : never;
65
68
 
66
- type Priority = "normal" | "critical";
67
- /** The app's own recipient. Herald only needs a stable id; apps carry extra fields freely. */
68
- interface RecipientRef {
69
- id: string;
70
- }
71
- /** A destination given directly, bypassing address resolution (e.g. a Slack channel id). */
72
- interface RawTarget<C extends string = string> {
73
- channel: C;
74
- address: unknown;
75
- }
76
- interface Targets<C extends string = string> {
77
- to: ReadonlyArray<RecipientRef | RawTarget<C>>;
78
- /** Subset of the event's allowed channels. Omitted = all of them. */
79
- channels?: readonly C[];
80
- /** `critical` bypasses recipient preferences. */
81
- priority?: Priority;
82
- /** Herald generates one when omitted. */
83
- idempotencyKey?: string;
84
- /**
85
- * Opaque tag for what this notification is about, e.g. `"lead:42"`. Not part of
86
- * the idempotency key. Lets you `cancel({ subject })` and filter `listDeliveries`.
87
- */
88
- subject?: string;
89
- }
90
- type DeliveryStatus = "pending" | "sending" | "sent" | "retry" | "dead" | "skipped" | "cancelled";
91
- /** Statuses a delivery never leaves on its own. Only these can be purged. */
92
- type TerminalStatus = "sent" | "dead" | "skipped" | "cancelled";
93
- /** What hooks receive after each attempt outcome. */
94
- interface DeliveryInfo {
95
- notificationId: string;
96
- deliveryId: string;
97
- event: string;
98
- channel: string;
99
- recipientId?: string;
100
- attempt: number;
101
- error?: unknown;
102
- }
103
- interface Hooks {
104
- onSent?(info: DeliveryInfo): void | Promise<void>;
105
- onFailed?(info: DeliveryInfo & {
106
- nextAttemptAt: Date;
107
- }): void | Promise<void>;
108
- onDead?(info: DeliveryInfo): void | Promise<void>;
109
- }
110
- interface Logger {
111
- debug(msg: string, meta?: Record<string, unknown>): void;
112
- info(msg: string, meta?: Record<string, unknown>): void;
113
- warn(msg: string, meta?: Record<string, unknown>): void;
114
- error(msg: string, meta?: Record<string, unknown>): void;
115
- }
116
- interface RetryPolicy {
117
- /** Total attempts including the first. Default 5. */
118
- maxAttempts: number;
119
- /** First retry delay. Doubles each attempt. Default 30_000. */
120
- baseMs: number;
121
- /** Delay ceiling. Default 3_600_000. */
122
- maxMs: number;
123
- /** Randomize delays to avoid thundering herds. Default true. */
124
- jitter: boolean;
125
- }
126
- /** Narrows channels per recipient. Called once per `notify()` with all recipients. Never adds channels. */
127
- type ResolvePreferences = (recipients: readonly RecipientRef[], event: string) => Promise<ReadonlyMap<string, readonly string[]>> | ReadonlyMap<string, readonly string[]>;
128
- /** Maps a recipient to a channel address. `null` skips that delivery (recorded as `skipped`). */
129
- type ResolveAddress = (recipient: RecipientRef, channel: string) => Promise<unknown | null> | unknown | null;
130
- interface ProcessOptions {
131
- /** Max deliveries to claim this call. Default 50. */
132
- batchSize?: number;
133
- /** Stop starting new sends after this many ms (fits function timeouts). Default 20_000. */
134
- budgetMs?: number;
135
- }
136
- interface ProcessSummary {
137
- claimed: number;
138
- sent: number;
139
- retried: number;
140
- dead: number;
141
- }
142
-
143
- interface NewDelivery {
144
- channel: string;
145
- /** Resolved address, or the raw target's address. `null` when resolution skipped it. */
146
- address: unknown;
147
- recipientId?: string;
148
- status: "pending" | "skipped";
149
- }
150
- interface NewNotification {
151
- event: string;
152
- payload: unknown;
153
- priority: Priority;
154
- idempotencyKey: string;
155
- /** Plain nullable indexed column, e.g. `"lead:42"`. Never part of the idempotency key. */
156
- subject: string | null;
157
- /** Final channels per recipient, after preferences. Retries never change them. */
158
- deliveries: readonly NewDelivery[];
159
- }
160
- interface NotificationRecord {
161
- id: string;
162
- event: string;
163
- payload: unknown;
164
- priority: Priority;
165
- idempotencyKey: string;
166
- subject: string | null;
167
- createdAt: Date;
168
- }
169
- interface DeliveryRecord {
170
- id: string;
171
- notificationId: string;
172
- channel: string;
173
- address: unknown;
174
- recipientId?: string;
175
- status: DeliveryStatus;
176
- attempts: number;
177
- nextAttemptAt: Date | null;
178
- leaseUntil: Date | null;
179
- lastError: string | null;
180
- createdAt: Date;
181
- }
182
- /** A delivery leased to this worker, with the notification data needed to render it. */
183
- interface ClaimedDelivery extends DeliveryRecord {
184
- notification: NotificationRecord;
185
- }
186
- type DeliveryResult = {
187
- status: "sent";
188
- providerId?: string;
189
- } | {
190
- status: "retry";
191
- nextAttemptAt: Date;
192
- error: string;
193
- } | {
194
- status: "dead";
195
- error: string;
196
- };
197
- interface DeliveryQuery {
198
- recipientId?: string;
199
- event?: string;
200
- channel?: string;
201
- status?: DeliveryStatus;
202
- subject?: string;
203
- /** Inclusive lower bound on delivery `createdAt`. */
204
- since?: Date;
205
- /** Exclusive upper bound on delivery `createdAt`. */
206
- until?: Date;
207
- limit?: number;
208
- /** Opaque. Pass the previous page's `nextCursor`. Keyset on (createdAt, id), newest first. */
209
- cursor?: string;
210
- }
211
- /** A delivery with the notification fields an admin page needs. */
212
- interface ListedDelivery extends DeliveryRecord {
213
- event: string;
214
- subject: string | null;
215
- }
216
- interface DeliveryPage {
217
- items: ListedDelivery[];
218
- nextCursor: string | null;
219
- }
220
- interface InboxItem {
221
- id: string;
222
- recipientId: string;
223
- notificationId: string;
224
- title: string;
225
- body: string;
226
- data?: unknown;
227
- createdAt: Date;
228
- readAt: Date | null;
229
- }
230
- interface InboxQuery {
231
- recipientId: string;
232
- unreadOnly?: boolean;
233
- limit?: number;
234
- cursor?: string;
235
- }
236
- interface InboxPage {
237
- items: InboxItem[];
238
- nextCursor: string | null;
239
- }
240
- /**
241
- * Persistence contract. Herald never sees a driver type. A store never sees
242
- * templates, channels or preferences.
243
- */
244
- interface Store {
245
- /**
246
- * Atomically insert the notification and its delivery rows. Unique on
247
- * `idempotencyKey`: a repeat returns the existing id with `created: false`.
248
- */
249
- enqueue(n: NewNotification): Promise<{
250
- id: string;
251
- created: boolean;
252
- }>;
253
- /**
254
- * Lease up to `limit` deliveries that are due (`pending`/`retry` with
255
- * `nextAttemptAt <= now`) or whose lease expired. Sets `leaseUntil = now + leaseMs`
256
- * and status `sending`. Concurrent callers must never receive the same row
257
- * (Postgres: `FOR UPDATE SKIP LOCKED`). Lease expiry is what makes a killed
258
- * worker's rows reappear: delivery is at-least-once.
259
- */
260
- claim(opts: {
261
- limit: number;
262
- now: Date;
263
- leaseMs: number;
264
- }): Promise<ClaimedDelivery[]>;
265
- /**
266
- * Record an attempt outcome: status, attempts, error; clears the lease.
267
- * Must only apply to a row that is still `sending` (`WHERE status = 'sending'`);
268
- * otherwise it is a silent no-op. This is what stops a late worker result from
269
- * un-cancelling a row.
270
- */
271
- recordResult(deliveryId: string, result: DeliveryResult): Promise<void>;
272
- /**
273
- * Admin and support visibility. Newest first, keyset-paginated on
274
- * (createdAt, id), never by offset. Filters combine with AND.
275
- */
276
- listDeliveries(q: DeliveryQuery): Promise<DeliveryPage>;
277
- /**
278
- * Re-queue a `dead` delivery: status `pending`, attempts reset to 0 (fresh
279
- * retry budget), due now. Returns false if the delivery was not `dead`.
280
- */
281
- retryDelivery(deliveryId: string): Promise<boolean>;
282
- /**
283
- * Cancel every `pending` or `retry` delivery of notifications with this
284
- * subject. `sending` rows are already out the door and are left alone, as are
285
- * terminal rows. Sets status `cancelled` (distinct from `skipped`).
286
- * Returns the number of deliveries cancelled.
287
- */
288
- cancel(q: {
289
- subject: string;
290
- }): Promise<number>;
291
- /**
292
- * Retention. Deletes deliveries created before `olderThan` whose status is
293
- * terminal (default: all terminal statuses), then notifications left with no
294
- * deliveries. Never deletes `pending`, `retry` or `sending` rows. Does not
295
- * touch the inbox. Returns the number of deliveries deleted.
296
- */
297
- purge(opts: {
298
- olderThan: Date;
299
- statuses?: readonly TerminalStatus[];
300
- }): Promise<number>;
301
- getNotification(id: string): Promise<{
302
- notification: NotificationRecord;
303
- deliveries: DeliveryRecord[];
304
- } | null>;
305
- inboxAdd(item: Omit<InboxItem, "id" | "createdAt" | "readAt">): Promise<InboxItem>;
306
- inboxList(q: InboxQuery): Promise<InboxPage>;
307
- inboxMarkRead(recipientId: string, ids: readonly string[]): Promise<void>;
308
- /** Unread items for the bell badge. */
309
- inboxUnreadCount(recipientId: string): Promise<number>;
310
- /** Marks every unread item read. Returns the number of rows updated. */
311
- inboxMarkAllRead(recipientId: string): Promise<number>;
312
- /** Create or upgrade Herald's tables. Optional: apps may manage schema themselves. */
313
- migrate?(): Promise<void>;
314
- close?(): Promise<void>;
315
- }
316
-
317
69
  interface HeraldConfig<Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>> {
318
70
  store: Store;
319
71
  channels: Ch;
@@ -342,16 +94,16 @@ interface Herald<Ev extends Record<string, AnyEventDef>> {
342
94
  declare const defaultRetry: RetryPolicy;
343
95
  /**
344
96
  * Validates config at startup (missing templates, unregistered channels are
345
- * errors here, not at send time). Behavior lands in later releases: `notify`,
346
- * `processPending` and `inbox` are typed but throw `not_implemented` for now.
97
+ * errors here, not at send time). `notify` queues durably; `processPending` and
98
+ * `inbox` are typed but throw `not_implemented` until later releases.
347
99
  */
348
100
  declare function createHerald<const Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>>(config: HeraldConfig<Ch, Ev>): Herald<Ev>;
349
101
 
350
- type HeraldErrorCode = "invalid_config" | "unknown_event" | "channel_not_allowed" | "missing_template" | "not_implemented";
102
+ type HeraldErrorCode = "invalid_config" | "unknown_event" | "channel_not_allowed" | "invalid_targets" | "missing_template" | "not_implemented";
351
103
  /** Every error Herald throws on its own behalf. Channel failures never surface through here. */
352
104
  declare class HeraldError extends Error {
353
105
  readonly code: HeraldErrorCode;
354
106
  constructor(code: HeraldErrorCode, message: string);
355
107
  }
356
108
 
357
- export { type AllowedChannel, type Channel, type ChannelMap, type ClaimedDelivery, type DeliveryInfo, type DeliveryPage, type DeliveryQuery, type DeliveryRecord, type DeliveryResult, type DeliveryStatus, type ErrorClass, type EventDef, type Herald, type HeraldConfig, HeraldError, type HeraldErrorCode, type Hooks, type InboxItem, type InboxPage, type InboxQuery, type ListedDelivery, type Logger, type MessageOf, type NewDelivery, type NewNotification, type NotificationRecord, type PayloadOf, type Priority, type ProcessOptions, type ProcessSummary, type RawTarget, type RecipientRef, type ResolveAddress, type ResolvePreferences, type RetryPolicy, type SendContext, type SendResult, type Store, type Targets, type TerminalStatus, createHerald, defaultRetry, defineEvent };
109
+ export { type AllowedChannel, type Channel, type ChannelMap, type ErrorClass, type EventDef, type Herald, type HeraldConfig, HeraldError, type HeraldErrorCode, Hooks, InboxPage, InboxQuery, Logger, type MessageOf, type PayloadOf, ProcessOptions, ProcessSummary, ResolveAddress, ResolvePreferences, RetryPolicy, type SendContext, type SendResult, Store, Targets, createHerald, defaultRetry, defineEvent };
package/dist/index.js CHANGED
@@ -8,6 +8,65 @@ var HeraldError = class extends Error {
8
8
  }
9
9
  };
10
10
 
11
+ // src/notify.ts
12
+ var isRaw = (t) => "channel" in t;
13
+ async function notify(deps, event, payload, targets) {
14
+ const def = deps.events[event];
15
+ if (!def) throw new HeraldError("unknown_event", `unknown event "${event}"`);
16
+ if (!targets.to?.length)
17
+ throw new HeraldError("invalid_targets", `notify("${event}") needs at least one target in "to"`);
18
+ const channels = [...new Set(targets.channels ?? def.channels)];
19
+ for (const ch of channels) {
20
+ if (!def.channels.includes(ch))
21
+ throw new HeraldError("channel_not_allowed", `event "${event}" does not allow channel "${ch}"`);
22
+ }
23
+ const raws = targets.to.filter(isRaw);
24
+ for (const r of raws) {
25
+ if (!channels.includes(r.channel))
26
+ throw new HeraldError(
27
+ "channel_not_allowed",
28
+ `raw target channel "${r.channel}" is not in the channels requested for "${event}"`
29
+ );
30
+ }
31
+ const seen = /* @__PURE__ */ new Set();
32
+ const recipients = [];
33
+ for (const t of targets.to) {
34
+ if (isRaw(t) || seen.has(t.id)) continue;
35
+ seen.add(t.id);
36
+ recipients.push(t);
37
+ }
38
+ const priority = targets.priority ?? "normal";
39
+ let prefs;
40
+ if (deps.resolvePreferences && priority !== "critical" && recipients.length > 0) {
41
+ prefs = await deps.resolvePreferences(recipients, event);
42
+ }
43
+ const pairs = recipients.flatMap((r) => {
44
+ const allowed = prefs?.get(r.id);
45
+ return channels.filter((ch) => !allowed || allowed.includes(ch)).map((ch) => ({ r, ch }));
46
+ });
47
+ const resolved = await Promise.all(
48
+ pairs.map(async ({ r, ch }) => {
49
+ const address = deps.resolveAddress ? await deps.resolveAddress(r, ch) : r.id;
50
+ return address === null || address === void 0 ? { channel: ch, address: null, recipientId: r.id, status: "skipped" } : { channel: ch, address, recipientId: r.id, status: "pending" };
51
+ })
52
+ );
53
+ const rawDeliveries = raws.map((r) => ({
54
+ channel: r.channel,
55
+ address: r.address,
56
+ status: "pending"
57
+ }));
58
+ const { id, created } = await deps.store.enqueue({
59
+ event,
60
+ payload,
61
+ priority,
62
+ idempotencyKey: targets.idempotencyKey ?? globalThis.crypto.randomUUID(),
63
+ subject: targets.subject ?? null,
64
+ deliveries: [...resolved, ...rawDeliveries]
65
+ });
66
+ deps.logger?.debug("notification queued", { id, event, created });
67
+ return id;
68
+ }
69
+
11
70
  // src/herald.ts
12
71
  var defaultRetry = {
13
72
  maxAttempts: 5,
@@ -66,17 +125,19 @@ function createHerald(config) {
66
125
  throw new HeraldError("not_implemented", `${what} is not implemented yet`);
67
126
  };
68
127
  return {
69
- async notify(event, _payload, targets) {
70
- const def = config.events[event];
71
- if (!def) throw new HeraldError("unknown_event", `unknown event "${event}"`);
72
- for (const ch of targets.channels ?? []) {
73
- if (!def.channels.includes(ch))
74
- throw new HeraldError(
75
- "channel_not_allowed",
76
- `event "${event}" does not allow channel "${ch}"`
77
- );
78
- }
79
- return notImplemented("notify()");
128
+ notify(event, payload, targets) {
129
+ return notify(
130
+ {
131
+ store: config.store,
132
+ events: config.events,
133
+ resolvePreferences: config.resolvePreferences,
134
+ resolveAddress: config.resolveAddress,
135
+ logger: config.logger
136
+ },
137
+ event,
138
+ payload,
139
+ targets
140
+ );
80
141
  },
81
142
  async processPending() {
82
143
  return notImplemented("processPending()");
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/herald.ts","../src/events.ts"],"sourcesContent":["export type HeraldErrorCode =\n | \"invalid_config\"\n | \"unknown_event\"\n | \"channel_not_allowed\"\n | \"missing_template\"\n | \"not_implemented\";\n\n/** Every error Herald throws on its own behalf. Channel failures never surface through here. */\nexport class HeraldError extends Error {\n readonly code: HeraldErrorCode;\n\n constructor(code: HeraldErrorCode, message: string) {\n super(message);\n this.name = \"HeraldError\";\n this.code = code;\n }\n}\n","import type { Channel } from \"./channel.js\";\r\nimport { HeraldError } from \"./errors.js\";\r\nimport type { AllowedChannel, AnyEventDef, ChannelMap, Conform, PayloadOf } from \"./events.js\";\r\nimport type { InboxPage, InboxQuery, Store } from \"./store.js\";\r\nimport type {\r\n Hooks,\r\n Logger,\r\n ProcessOptions,\r\n ProcessSummary,\r\n ResolveAddress,\r\n ResolvePreferences,\r\n RetryPolicy,\r\n Targets,\r\n} from \"./types.js\";\r\n\r\nexport interface HeraldConfig<Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>> {\r\n store: Store;\r\n channels: Ch;\r\n /** Each event must conform to the channel map: registered channels, matching message types. */\r\n events: Ev & { [E in keyof Ev]: Conform<Ev[E], Ch> };\r\n resolvePreferences?: ResolvePreferences;\r\n resolveAddress?: ResolveAddress;\r\n hooks?: Hooks;\r\n logger?: Logger;\r\n retry?: Partial<RetryPolicy>;\r\n /** Clock override for tests. */\r\n now?: () => Date;\r\n}\r\n\r\nexport interface Herald<Ev extends Record<string, AnyEventDef>> {\r\n /** Queue a notification. Resolves with its id; channel failures never reach the caller. */\r\n notify<E extends keyof Ev & string>(\r\n event: E,\r\n payload: PayloadOf<Ev[E]>,\r\n targets: Targets<AllowedChannel<Ev[E]>>,\r\n ): Promise<string>;\r\n /** Claim and deliver due work. The host schedules this (interval, cron, queue trigger). */\r\n processPending(opts?: ProcessOptions): Promise<ProcessSummary>;\r\n inbox: {\r\n list(q: InboxQuery): Promise<InboxPage>;\r\n markRead(recipientId: string, ids: readonly string[]): Promise<void>;\r\n };\r\n}\r\n\r\nexport const defaultRetry: RetryPolicy = {\r\n maxAttempts: 5,\r\n baseMs: 30_000,\r\n maxMs: 3_600_000,\r\n jitter: true,\r\n};\r\n\r\nconst fn = (v: unknown): boolean => typeof v === \"function\";\r\n\r\nconst STORE_METHODS = [\r\n \"enqueue\",\r\n \"claim\",\r\n \"recordResult\",\r\n \"listDeliveries\",\r\n \"retryDelivery\",\r\n \"cancel\",\r\n \"purge\",\r\n \"getNotification\",\r\n \"inboxAdd\",\r\n \"inboxList\",\r\n \"inboxMarkRead\",\r\n \"inboxUnreadCount\",\r\n \"inboxMarkAllRead\",\r\n] as const;\r\n\r\nfunction validate(config: HeraldConfig<ChannelMap, Record<string, AnyEventDef>>): void {\r\n const bad = (msg: string): never => {\r\n throw new HeraldError(\"invalid_config\", msg);\r\n };\r\n\r\n const { store, channels, events } = config;\r\n for (const m of STORE_METHODS) {\r\n if (!fn((store as unknown as Record<string, unknown> | undefined)?.[m]))\r\n bad(`store.${m} is not a function`);\r\n }\r\n\r\n for (const [name, ch] of Object.entries(channels ?? {})) {\r\n const c = ch as Channel | undefined;\r\n if (!c || !fn(c.send) || !fn(c.classifyError))\r\n bad(`channel \"${name}\" must implement send() and classifyError()`);\r\n }\r\n\r\n const names = Object.keys(events ?? {});\r\n if (names.length === 0) bad(\"at least one event is required\");\r\n\r\n for (const [event, def] of Object.entries(events)) {\r\n if (!def.channels?.length) bad(`event \"${event}\" must allow at least one channel`);\r\n for (const ch of def.channels) {\r\n if (!(ch in channels)) bad(`event \"${event}\" allows unregistered channel \"${ch}\"`);\r\n if (!fn((def.templates as Record<string, unknown> | undefined)?.[ch]))\r\n throw new HeraldError(\"missing_template\", `event \"${event}\" has no template for channel \"${ch}\"`);\r\n }\r\n for (const ch of Object.keys(def.templates ?? {})) {\r\n if (!def.channels.includes(ch))\r\n bad(`event \"${event}\" has a template for \"${ch}\" which is not in its allowed channels`);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Validates config at startup (missing templates, unregistered channels are\r\n * errors here, not at send time). Behavior lands in later releases: `notify`,\r\n * `processPending` and `inbox` are typed but throw `not_implemented` for now.\r\n */\r\nexport function createHerald<\r\n const Ch extends ChannelMap,\r\n Ev extends Record<string, AnyEventDef>,\r\n>(config: HeraldConfig<Ch, Ev>): Herald<Ev> {\r\n validate(config as unknown as HeraldConfig<ChannelMap, Record<string, AnyEventDef>>);\r\n\r\n const notImplemented = (what: string): never => {\r\n throw new HeraldError(\"not_implemented\", `${what} is not implemented yet`);\r\n };\r\n\r\n return {\r\n async notify(event, _payload, targets) {\r\n const def = config.events[event] as AnyEventDef | undefined;\r\n if (!def) throw new HeraldError(\"unknown_event\", `unknown event \"${event}\"`);\r\n for (const ch of targets.channels ?? []) {\r\n if (!def.channels.includes(ch))\r\n throw new HeraldError(\r\n \"channel_not_allowed\",\r\n `event \"${event}\" does not allow channel \"${ch}\"`,\r\n );\r\n }\r\n return notImplemented(\"notify()\");\r\n },\r\n async processPending() {\r\n return notImplemented(\"processPending()\");\r\n },\r\n inbox: {\r\n async list() {\r\n return notImplemented(\"inbox.list()\");\r\n },\r\n async markRead() {\r\n return notImplemented(\"inbox.markRead()\");\r\n },\r\n },\r\n };\r\n}\r\n","import type { Channel } from \"./channel.js\";\r\n\r\n/* eslint-disable @typescript-eslint/no-explicit-any -- `any` is how Channel<M, A> is matched regardless of its params */\r\nexport type ChannelMap = Record<string, Channel<any, any>>;\r\n\r\n/** The message type a channel expects from its templates. */\r\nexport type MessageOf<C> = C extends Channel<infer M, any> ? M : never;\r\n\r\n/**\r\n * An event: its allowed channels and one template per channel. `P` is the\r\n * payload type (type-only, via `__payload`); templates are plain functions.\r\n */\r\nexport interface EventDef<\r\n P = unknown,\r\n K extends string = string,\r\n T extends { readonly [C in K]: (payload: P) => unknown } = {\r\n readonly [C in K]: (payload: P) => unknown;\r\n },\r\n> {\r\n readonly channels: readonly K[];\r\n readonly templates: T;\r\n readonly __payload?: P;\r\n}\r\n\r\nexport type AnyEventDef = EventDef<any, string, any>;\r\nexport type PayloadOf<D> = D extends EventDef<infer P, any, any> ? P : never;\r\nexport type AllowedChannel<D> = D extends EventDef<any, infer K, any> ? K : never;\r\n\r\n/**\r\n * Curried so the payload type is explicit while channel names are inferred:\r\n * `defineEvent<{ name: string }>()({ channels: [\"slack\"], templates: { slack: (p) => ... } })`.\r\n */\r\nexport function defineEvent<P>() {\r\n return <const K extends string, T extends { [C in K]: (payload: P) => unknown }>(def: {\r\n channels: readonly K[];\r\n templates: T;\r\n }): EventDef<P, K, T> => def;\r\n}\r\n\r\n/**\r\n * What an event must look like against a concrete channel map: every allowed\r\n * channel is registered, and each template returns that channel's message type.\r\n */\r\nexport type Conform<D, Ch extends ChannelMap> =\r\n D extends EventDef<infer P, infer K, any>\r\n ? {\r\n readonly channels: readonly (K & keyof Ch)[];\r\n readonly templates: {\r\n readonly [C in K]: C extends keyof Ch ? (payload: P) => MessageOf<Ch[C]> : never;\r\n };\r\n }\r\n : never;\r\n"],"mappings":";AAQO,IAAM,cAAN,cAA0B,MAAM;AAAA,EAC5B;AAAA,EAET,YAAY,MAAuB,SAAiB;AAClD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,O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AAE,GAAG;AAAA,IACpG;AACA,eAAW,MAAM,OAAO,KAAK,IAAI,aAAa,CAAC,CAAC,GAAG;AACjD,UAAI,CAAC,IAAI,SAAS,SAAS,EAAE;AAC3B,YAAI,UAAU,KAAK,yBAAyB,EAAE,wCAAwC;AAAA,IAC1F;AAAA,EACF;AACF;AAOO,SAAS,aAGd,QAA0C;AAC1C,WAAS,MAA0E;AAEnF,QAAM,iBAAiB,CAAC,SAAwB;AAC9C,UAAM,IAAI,YAAY,mBAAmB,GAAG,IAAI,yBAAyB;AAAA,EAC3E;AAEA,SAAO;AAAA,IACL,MAAM,OAAO,OAAO,UAAU,SAAS;AACrC,YAAM,MAAM,OAAO,OAAO,KAAK;AAC/B,UAAI,CAAC,IAAK,OAAM,IAAI,YAAY,iBAAiB,kBAAkB,KAAK,GAAG;AAC3E,iBAAW,MAAM,QAAQ,YAAY,CAAC,GAAG;AACvC,YAAI,CAAC,IAAI,SAAS,SAAS,EAAE;AAC3B,gBAAM,IAAI;AAAA,YACR;AAAA,YACA,UAAU,KAAK,6BAA6B,EAAE;AAAA,UAChD;AAAA,MACJ;AACA,aAAO,eAAe,UAAU;AAAA,IAClC;AAAA,IACA,MAAM,iBAAiB;AACrB,aAAO,eAAe,kBAAkB;AAAA,IAC1C;AAAA,IACA,OAAO;AAAA,MACL,MAAM,OAAO;AACX,eAAO,eAAe,cAAc;AAAA,MACtC;AAAA,MACA,MAAM,WAAW;AACf,eAAO,eAAe,kBAAkB;AAAA,MAC1C;AAAA,IACF;AAAA,EACF;AACF;;;AC/GO,SAAS,cAAiB;AAC/B,SAAO,CAA0E,QAGxD;AAC3B;","names":[]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/notify.ts","../src/herald.ts","../src/events.ts"],"sourcesContent":["export type HeraldErrorCode =\r\n | \"invalid_config\"\r\n | \"unknown_event\"\r\n | \"channel_not_allowed\"\r\n | \"invalid_targets\"\r\n | \"missing_template\"\r\n | \"not_implemented\";\r\n\r\n/** Every error Herald throws on its own behalf. Channel failures never surface through here. */\r\nexport class HeraldError extends Error {\r\n readonly code: HeraldErrorCode;\r\n\r\n constructor(code: HeraldErrorCode, message: string) {\r\n super(message);\r\n this.name = \"HeraldError\";\r\n this.code = code;\r\n }\r\n}\r\n","import { HeraldError } from \"./errors.js\";\nimport type { AnyEventDef } from \"./events.js\";\nimport type { NewDelivery, Store } from \"./store.js\";\nimport type {\n Logger,\n RawTarget,\n RecipientRef,\n ResolveAddress,\n ResolvePreferences,\n Targets,\n} from \"./types.js\";\n\nexport interface NotifyDeps {\n store: Store;\n events: Record<string, AnyEventDef>;\n resolvePreferences?: ResolvePreferences;\n resolveAddress?: ResolveAddress;\n logger?: Logger;\n}\n\nconst isRaw = (t: RecipientRef | RawTarget): t is RawTarget => \"channel\" in t;\n\n/**\n * Validate, narrow by preferences, resolve addresses, and durably queue.\n * Returns the notification id. Resolver failures propagate and nothing is\n * queued (fail closed: never notify someone who may have opted out).\n */\nexport async function notify(\n deps: NotifyDeps,\n event: string,\n payload: unknown,\n targets: Targets,\n): Promise<string> {\n const def = deps.events[event];\n if (!def) throw new HeraldError(\"unknown_event\", `unknown event \"${event}\"`);\n if (!targets.to?.length)\n throw new HeraldError(\"invalid_targets\", `notify(\"${event}\") needs at least one target in \"to\"`);\n\n const channels = [...new Set(targets.channels ?? def.channels)];\n for (const ch of channels) {\n if (!def.channels.includes(ch))\n throw new HeraldError(\"channel_not_allowed\", `event \"${event}\" does not allow channel \"${ch}\"`);\n }\n\n const raws = targets.to.filter(isRaw);\n for (const r of raws) {\n if (!channels.includes(r.channel))\n throw new HeraldError(\n \"channel_not_allowed\",\n `raw target channel \"${r.channel}\" is not in the channels requested for \"${event}\"`,\n );\n }\n\n const seen = new Set<string>();\n const recipients: RecipientRef[] = [];\n for (const t of targets.to) {\n if (isRaw(t) || seen.has(t.id)) continue;\n seen.add(t.id);\n recipients.push(t);\n }\n\n const priority = targets.priority ?? \"normal\";\n\n // Preferences: one batched call; only narrows; critical bypasses.\n let prefs: ReadonlyMap<string, readonly string[]> | undefined;\n if (deps.resolvePreferences && priority !== \"critical\" && recipients.length > 0) {\n prefs = await deps.resolvePreferences(recipients, event);\n }\n\n const pairs = recipients.flatMap((r) => {\n const allowed = prefs?.get(r.id);\n return channels\n .filter((ch) => !allowed || allowed.includes(ch))\n .map((ch) => ({ r, ch }));\n });\n\n const resolved = await Promise.all(\n pairs.map(async ({ r, ch }): Promise<NewDelivery> => {\n // No resolver configured: the recipient id is the address.\n const address = deps.resolveAddress ? await deps.resolveAddress(r, ch) : r.id;\n return address === null || address === undefined\n ? { channel: ch, address: null, recipientId: r.id, status: \"skipped\" }\n : { channel: ch, address, recipientId: r.id, status: \"pending\" };\n }),\n );\n\n const rawDeliveries: NewDelivery[] = raws.map((r) => ({\n channel: r.channel,\n address: r.address,\n status: \"pending\",\n }));\n\n const { id, created } = await deps.store.enqueue({\n event,\n payload,\n priority,\n idempotencyKey: targets.idempotencyKey ?? globalThis.crypto.randomUUID(),\n subject: targets.subject ?? null,\n deliveries: [...resolved, ...rawDeliveries],\n });\n\n deps.logger?.debug(\"notification queued\", { id, event, created });\n return id;\n}\n","import type { Channel } from \"./channel.js\";\r\nimport { HeraldError } from \"./errors.js\";\r\nimport { notify as runNotify } from \"./notify.js\";\r\nimport type { AllowedChannel, AnyEventDef, ChannelMap, Conform, PayloadOf } from \"./events.js\";\r\nimport type { InboxPage, InboxQuery, Store } from \"./store.js\";\r\nimport type {\r\n Hooks,\r\n Logger,\r\n ProcessOptions,\r\n ProcessSummary,\r\n ResolveAddress,\r\n ResolvePreferences,\r\n RetryPolicy,\r\n Targets,\r\n} from \"./types.js\";\r\n\r\nexport interface HeraldConfig<Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>> {\r\n store: Store;\r\n channels: Ch;\r\n /** Each event must conform to the channel map: registered channels, matching message types. */\r\n events: Ev & { [E in keyof Ev]: Conform<Ev[E], Ch> };\r\n resolvePreferences?: ResolvePreferences;\r\n resolveAddress?: ResolveAddress;\r\n hooks?: Hooks;\r\n logger?: Logger;\r\n retry?: Partial<RetryPolicy>;\r\n /** Clock override for tests. */\r\n now?: () => Date;\r\n}\r\n\r\nexport interface Herald<Ev extends Record<string, AnyEventDef>> {\r\n /** Queue a notification. Resolves with its id; channel failures never reach the caller. */\r\n notify<E extends keyof Ev & string>(\r\n event: E,\r\n payload: PayloadOf<Ev[E]>,\r\n targets: Targets<AllowedChannel<Ev[E]>>,\r\n ): Promise<string>;\r\n /** Claim and deliver due work. The host schedules this (interval, cron, queue trigger). */\r\n processPending(opts?: ProcessOptions): Promise<ProcessSummary>;\r\n inbox: {\r\n list(q: InboxQuery): Promise<InboxPage>;\r\n markRead(recipientId: string, ids: readonly string[]): Promise<void>;\r\n };\r\n}\r\n\r\nexport const defaultRetry: RetryPolicy = {\r\n maxAttempts: 5,\r\n baseMs: 30_000,\r\n maxMs: 3_600_000,\r\n jitter: true,\r\n};\r\n\r\nconst fn = (v: unknown): boolean => typeof v === \"function\";\r\n\r\nconst STORE_METHODS = [\r\n \"enqueue\",\r\n \"claim\",\r\n \"recordResult\",\r\n \"listDeliveries\",\r\n \"retryDelivery\",\r\n \"cancel\",\r\n \"purge\",\r\n \"getNotification\",\r\n \"inboxAdd\",\r\n \"inboxList\",\r\n \"inboxMarkRead\",\r\n \"inboxUnreadCount\",\r\n \"inboxMarkAllRead\",\r\n] as const;\r\n\r\nfunction validate(config: HeraldConfig<ChannelMap, Record<string, AnyEventDef>>): void {\r\n const bad = (msg: string): never => {\r\n throw new HeraldError(\"invalid_config\", msg);\r\n };\r\n\r\n const { store, channels, events } = config;\r\n for (const m of STORE_METHODS) {\r\n if (!fn((store as unknown as Record<string, unknown> | undefined)?.[m]))\r\n bad(`store.${m} is not a function`);\r\n }\r\n\r\n for (const [name, ch] of Object.entries(channels ?? {})) {\r\n const c = ch as Channel | undefined;\r\n if (!c || !fn(c.send) || !fn(c.classifyError))\r\n bad(`channel \"${name}\" must implement send() and classifyError()`);\r\n }\r\n\r\n const names = Object.keys(events ?? {});\r\n if (names.length === 0) bad(\"at least one event is required\");\r\n\r\n for (const [event, def] of Object.entries(events)) {\r\n if (!def.channels?.length) bad(`event \"${event}\" must allow at least one channel`);\r\n for (const ch of def.channels) {\r\n if (!(ch in channels)) bad(`event \"${event}\" allows unregistered channel \"${ch}\"`);\r\n if (!fn((def.templates as Record<string, unknown> | undefined)?.[ch]))\r\n throw new HeraldError(\"missing_template\", `event \"${event}\" has no template for channel \"${ch}\"`);\r\n }\r\n for (const ch of Object.keys(def.templates ?? {})) {\r\n if (!def.channels.includes(ch))\r\n bad(`event \"${event}\" has a template for \"${ch}\" which is not in its allowed channels`);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Validates config at startup (missing templates, unregistered channels are\r\n * errors here, not at send time). `notify` queues durably; `processPending` and\r\n * `inbox` are typed but throw `not_implemented` until later releases.\r\n */\r\nexport function createHerald<\r\n const Ch extends ChannelMap,\r\n Ev extends Record<string, AnyEventDef>,\r\n>(config: HeraldConfig<Ch, Ev>): Herald<Ev> {\r\n validate(config as unknown as HeraldConfig<ChannelMap, Record<string, AnyEventDef>>);\r\n\r\n const notImplemented = (what: string): never => {\r\n throw new HeraldError(\"not_implemented\", `${what} is not implemented yet`);\r\n };\r\n\r\n return {\r\n notify(event, payload, targets) {\r\n return runNotify(\r\n {\r\n store: config.store,\r\n events: config.events as Record<string, AnyEventDef>,\r\n resolvePreferences: config.resolvePreferences,\r\n resolveAddress: config.resolveAddress,\r\n logger: config.logger,\r\n },\r\n event,\r\n payload,\r\n targets as Targets,\r\n );\r\n },\r\n async processPending() {\r\n return notImplemented(\"processPending()\");\r\n },\r\n inbox: {\r\n async list() {\r\n return notImplemented(\"inbox.list()\");\r\n },\r\n async markRead() {\r\n return notImplemented(\"inbox.markRead()\");\r\n },\r\n },\r\n };\r\n}\r\n","import type { Channel } from \"./channel.js\";\r\n\r\n/* eslint-disable @typescript-eslint/no-explicit-any -- `any` is how Channel<M, A> is matched regardless of its params */\r\nexport type ChannelMap = Record<string, Channel<any, any>>;\r\n\r\n/** The message type a channel expects from its templates. */\r\nexport type MessageOf<C> = C extends Channel<infer M, any> ? M : never;\r\n\r\n/**\r\n * An event: its allowed channels and one template per channel. `P` is the\r\n * payload type (type-only, via `__payload`); templates are plain functions.\r\n */\r\nexport interface EventDef<\r\n P = unknown,\r\n K extends string = string,\r\n T extends { readonly [C in K]: (payload: P) => unknown } = {\r\n readonly [C in K]: (payload: P) => unknown;\r\n },\r\n> {\r\n readonly channels: readonly K[];\r\n readonly templates: T;\r\n readonly __payload?: P;\r\n}\r\n\r\nexport type AnyEventDef = EventDef<any, string, any>;\r\nexport type PayloadOf<D> = D extends EventDef<infer P, any, any> ? P : never;\r\nexport type AllowedChannel<D> = D extends EventDef<any, infer K, any> ? K : never;\r\n\r\n/**\r\n * Curried so the payload type is explicit while channel names are inferred:\r\n * `defineEvent<{ name: string }>()({ channels: [\"slack\"], templates: { slack: (p) => ... } })`.\r\n */\r\nexport function defineEvent<P>() {\r\n return <const K extends string, T extends { [C in K]: (payload: P) => unknown }>(def: {\r\n channels: readonly K[];\r\n templates: T;\r\n }): EventDef<P, K, T> => def;\r\n}\r\n\r\n/**\r\n * What an event must look like against a concrete channel map: every allowed\r\n * channel is registered, and each template returns that channel's message type.\r\n */\r\nexport type Conform<D, Ch extends ChannelMap> =\r\n D extends EventDef<infer P, infer K, any>\r\n ? {\r\n readonly channels: readonly (K & keyof Ch)[];\r\n readonly templates: {\r\n readonly [C in K]: C extends keyof Ch ? (payload: P) => MessageOf<Ch[C]> : never;\r\n };\r\n }\r\n : never;\r\n"],"mappings":";AASO,IAAM,cAAN,cAA0B,MAAM;AAAA,EAC5B;AAAA,EAET,YAAY,MAAuB,SAAiB;AAClD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;;;ACGA,IAAM,QAAQ,CAAC,MAAgD,aAAa;AAO5E,eAAsB,OACpB,MACA,OACA,SACA,SACiB;AACjB,QAAM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AQ,OAAO;AAAA,UACf,oBAAoB,OAAO;AAAA,UAC3B,gBAAgB,OAAO;AAAA,UACvB,QAAQ,OAAO;AAAA,QACjB;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,IACA,MAAM,iBAAiB;AACrB,aAAO,eAAe,kBAAkB;AAAA,IAC1C;AAAA,IACA,OAAO;AAAA,MACL,MAAM,OAAO;AACX,eAAO,eAAe,cAAc;AAAA,MACtC;AAAA,MACA,MAAM,WAAW;AACf,eAAO,eAAe,kBAAkB;AAAA,MAC1C;AAAA,IACF;AAAA,EACF;AACF;;;AClHO,SAAS,cAAiB;AAC/B,SAAO,CAA0E,QAGxD;AAC3B;","names":[]}
@@ -0,0 +1,14 @@
1
+ import { S as Store } from './store-BaqPfkS_.js';
2
+
3
+ interface MemoryStoreOptions {
4
+ /** Clock override for tests. */
5
+ now?: () => Date;
6
+ }
7
+ /**
8
+ * Complete in-process Store. Reference implementation of the Store contract,
9
+ * for tests and local development. Not durable and not shared across processes.
10
+ * `claim` is atomic because JS is single-threaded; the contract suite still proves it.
11
+ */
12
+ declare function memoryStore(options?: MemoryStoreOptions): Store;
13
+
14
+ export { type MemoryStoreOptions, memoryStore };
package/dist/memory.js ADDED
@@ -0,0 +1,203 @@
1
+ // src/memory.ts
2
+ var TERMINAL = ["sent", "dead", "skipped", "cancelled"];
3
+ var DEFAULT_PAGE = 50;
4
+ var pad = (n) => String(n).padStart(12, "0");
5
+ var newestFirst = (a, b) => b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
6
+ var encodeCursor = (x) => btoa(`${x.createdAt.getTime()}|${x.id}`);
7
+ function afterCursor(x, cursor) {
8
+ const [ms, id] = atob(cursor).split("|");
9
+ const t = x.createdAt.getTime();
10
+ const c = Number(ms);
11
+ return t < c || t === c && x.id < id;
12
+ }
13
+ function page(rows, limit, cursor) {
14
+ const size = limit ?? DEFAULT_PAGE;
15
+ const sorted = rows.sort(newestFirst).filter((r) => !cursor || afterCursor(r, cursor));
16
+ const items = sorted.slice(0, size);
17
+ const last = items[items.length - 1];
18
+ return { items, nextCursor: sorted.length > size && last ? encodeCursor(last) : null };
19
+ }
20
+ function memoryStore(options = {}) {
21
+ const clock = options.now ?? (() => /* @__PURE__ */ new Date());
22
+ let seq = 0;
23
+ const nextId = (p) => `${p}_${pad(++seq)}`;
24
+ const notifications = /* @__PURE__ */ new Map();
25
+ const byKey = /* @__PURE__ */ new Map();
26
+ const deliveries = /* @__PURE__ */ new Map();
27
+ const inbox = /* @__PURE__ */ new Map();
28
+ const out = (v) => structuredClone(v);
29
+ const claimedView = (d) => {
30
+ const notification = notifications.get(d.notificationId);
31
+ return out({ ...d, notification });
32
+ };
33
+ return {
34
+ async enqueue(n) {
35
+ const existing = byKey.get(n.idempotencyKey);
36
+ if (existing) return { id: existing, created: false };
37
+ const createdAt = clock();
38
+ const id = nextId("n");
39
+ notifications.set(id, {
40
+ id,
41
+ event: n.event,
42
+ payload: out(n.payload),
43
+ priority: n.priority,
44
+ idempotencyKey: n.idempotencyKey,
45
+ subject: n.subject,
46
+ createdAt
47
+ });
48
+ byKey.set(n.idempotencyKey, id);
49
+ for (const d of n.deliveries) {
50
+ const did = nextId("d");
51
+ deliveries.set(did, {
52
+ id: did,
53
+ notificationId: id,
54
+ channel: d.channel,
55
+ address: out(d.address),
56
+ ...d.recipientId !== void 0 && { recipientId: d.recipientId },
57
+ status: d.status,
58
+ attempts: 0,
59
+ nextAttemptAt: null,
60
+ // null = due immediately
61
+ leaseUntil: null,
62
+ lastError: null,
63
+ createdAt
64
+ });
65
+ }
66
+ return { id, created: true };
67
+ },
68
+ async claim({ limit, now, leaseMs }) {
69
+ const due = [...deliveries.values()].filter((d) => {
70
+ if (d.status === "pending" || d.status === "retry")
71
+ return d.nextAttemptAt === null || d.nextAttemptAt <= now;
72
+ return d.status === "sending" && d.leaseUntil !== null && d.leaseUntil <= now;
73
+ }).sort(
74
+ (a, b) => (a.nextAttemptAt?.getTime() ?? 0) - (b.nextAttemptAt?.getTime() ?? 0) || a.createdAt.getTime() - b.createdAt.getTime() || (a.id < b.id ? -1 : 1)
75
+ ).slice(0, limit);
76
+ return due.map((d) => {
77
+ d.status = "sending";
78
+ d.attempts += 1;
79
+ d.leaseUntil = new Date(now.getTime() + leaseMs);
80
+ return claimedView(d);
81
+ });
82
+ },
83
+ async recordResult(deliveryId, result) {
84
+ const d = deliveries.get(deliveryId);
85
+ if (!d || d.status !== "sending") return;
86
+ d.leaseUntil = null;
87
+ if (result.status === "sent") {
88
+ d.status = "sent";
89
+ d.nextAttemptAt = null;
90
+ d.lastError = null;
91
+ } else if (result.status === "retry") {
92
+ d.status = "retry";
93
+ d.nextAttemptAt = new Date(result.nextAttemptAt);
94
+ d.lastError = result.error;
95
+ } else {
96
+ d.status = "dead";
97
+ d.nextAttemptAt = null;
98
+ d.lastError = result.error;
99
+ }
100
+ },
101
+ async getNotification(id) {
102
+ const notification = notifications.get(id);
103
+ if (!notification) return null;
104
+ return out({
105
+ notification,
106
+ deliveries: [...deliveries.values()].filter((d) => d.notificationId === id)
107
+ });
108
+ },
109
+ async listDeliveries(q) {
110
+ const rows = [];
111
+ for (const d of deliveries.values()) {
112
+ const n = notifications.get(d.notificationId);
113
+ if (q.recipientId !== void 0 && d.recipientId !== q.recipientId) continue;
114
+ if (q.event !== void 0 && n.event !== q.event) continue;
115
+ if (q.channel !== void 0 && d.channel !== q.channel) continue;
116
+ if (q.status !== void 0 && d.status !== q.status) continue;
117
+ if (q.subject !== void 0 && n.subject !== q.subject) continue;
118
+ if (q.since && d.createdAt < q.since) continue;
119
+ if (q.until && d.createdAt >= q.until) continue;
120
+ rows.push({ ...d, event: n.event, subject: n.subject });
121
+ }
122
+ return out(page(rows, q.limit, q.cursor));
123
+ },
124
+ async retryDelivery(deliveryId) {
125
+ const d = deliveries.get(deliveryId);
126
+ if (!d || d.status !== "dead") return false;
127
+ d.status = "pending";
128
+ d.attempts = 0;
129
+ d.nextAttemptAt = null;
130
+ d.leaseUntil = null;
131
+ return true;
132
+ },
133
+ async cancel({ subject }) {
134
+ const ids = new Set(
135
+ [...notifications.values()].filter((n) => n.subject === subject).map((n) => n.id)
136
+ );
137
+ let count = 0;
138
+ for (const d of deliveries.values()) {
139
+ if (!ids.has(d.notificationId)) continue;
140
+ if (d.status !== "pending" && d.status !== "retry") continue;
141
+ d.status = "cancelled";
142
+ d.nextAttemptAt = null;
143
+ d.leaseUntil = null;
144
+ count += 1;
145
+ }
146
+ return count;
147
+ },
148
+ async purge({ olderThan, statuses }) {
149
+ const allowed = statuses ?? TERMINAL;
150
+ let count = 0;
151
+ for (const [id, d] of deliveries) {
152
+ if (d.createdAt < olderThan && TERMINAL.includes(d.status) && allowed.includes(d.status)) {
153
+ deliveries.delete(id);
154
+ count += 1;
155
+ }
156
+ }
157
+ const withDeliveries = new Set([...deliveries.values()].map((d) => d.notificationId));
158
+ for (const [id, n] of notifications) {
159
+ if (n.createdAt < olderThan && !withDeliveries.has(id)) {
160
+ notifications.delete(id);
161
+ byKey.delete(n.idempotencyKey);
162
+ }
163
+ }
164
+ return count;
165
+ },
166
+ async inboxAdd(item) {
167
+ const created = { ...out(item), id: nextId("i"), createdAt: clock(), readAt: null };
168
+ inbox.set(created.id, created);
169
+ return out(created);
170
+ },
171
+ async inboxList(q) {
172
+ const rows = [...inbox.values()].filter(
173
+ (i) => i.recipientId === q.recipientId && (!q.unreadOnly || i.readAt === null)
174
+ );
175
+ return out(page(rows, q.limit, q.cursor));
176
+ },
177
+ async inboxMarkRead(recipientId, ids) {
178
+ const now = clock();
179
+ for (const id of ids) {
180
+ const i = inbox.get(id);
181
+ if (i && i.recipientId === recipientId && i.readAt === null) i.readAt = now;
182
+ }
183
+ },
184
+ async inboxUnreadCount(recipientId) {
185
+ return [...inbox.values()].filter((i) => i.recipientId === recipientId && i.readAt === null).length;
186
+ },
187
+ async inboxMarkAllRead(recipientId) {
188
+ const now = clock();
189
+ let count = 0;
190
+ for (const i of inbox.values()) {
191
+ if (i.recipientId === recipientId && i.readAt === null) {
192
+ i.readAt = now;
193
+ count += 1;
194
+ }
195
+ }
196
+ return count;
197
+ }
198
+ };
199
+ }
200
+ export {
201
+ memoryStore
202
+ };
203
+ //# sourceMappingURL=memory.js.map