@useherald/core 0.1.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,185 +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
- type DeliveryStatus = "pending" | "sending" | "sent" | "retry" | "dead" | "skipped";
86
- /** What hooks receive after each attempt outcome. */
87
- interface DeliveryInfo {
88
- notificationId: string;
89
- deliveryId: string;
90
- event: string;
91
- channel: string;
92
- recipientId?: string;
93
- attempt: number;
94
- error?: unknown;
95
- }
96
- interface Hooks {
97
- onSent?(info: DeliveryInfo): void | Promise<void>;
98
- onFailed?(info: DeliveryInfo & {
99
- nextAttemptAt: Date;
100
- }): void | Promise<void>;
101
- onDead?(info: DeliveryInfo): void | Promise<void>;
102
- }
103
- interface Logger {
104
- debug(msg: string, meta?: Record<string, unknown>): void;
105
- info(msg: string, meta?: Record<string, unknown>): void;
106
- warn(msg: string, meta?: Record<string, unknown>): void;
107
- error(msg: string, meta?: Record<string, unknown>): void;
108
- }
109
- interface RetryPolicy {
110
- /** Total attempts including the first. Default 5. */
111
- maxAttempts: number;
112
- /** First retry delay. Doubles each attempt. Default 30_000. */
113
- baseMs: number;
114
- /** Delay ceiling. Default 3_600_000. */
115
- maxMs: number;
116
- /** Randomize delays to avoid thundering herds. Default true. */
117
- jitter: boolean;
118
- }
119
- /** Narrows channels per recipient. Called once per `notify()` with all recipients. Never adds channels. */
120
- type ResolvePreferences = (recipients: readonly RecipientRef[], event: string) => Promise<ReadonlyMap<string, readonly string[]>> | ReadonlyMap<string, readonly string[]>;
121
- /** Maps a recipient to a channel address. `null` skips that delivery (recorded as `skipped`). */
122
- type ResolveAddress = (recipient: RecipientRef, channel: string) => Promise<unknown | null> | unknown | null;
123
- interface ProcessOptions {
124
- /** Max deliveries to claim this call. Default 50. */
125
- batchSize?: number;
126
- /** Stop starting new sends after this many ms (fits function timeouts). Default 20_000. */
127
- budgetMs?: number;
128
- }
129
- interface ProcessSummary {
130
- claimed: number;
131
- sent: number;
132
- retried: number;
133
- dead: number;
134
- }
135
-
136
- interface NewDelivery {
137
- channel: string;
138
- /** Resolved address, or the raw target's address. `null` when resolution skipped it. */
139
- address: unknown;
140
- recipientId?: string;
141
- status: "pending" | "skipped";
142
- }
143
- interface NewNotification {
144
- event: string;
145
- payload: unknown;
146
- priority: Priority;
147
- idempotencyKey: string;
148
- /** Final channels per recipient, after preferences. Retries never change them. */
149
- deliveries: readonly NewDelivery[];
150
- }
151
- interface NotificationRecord {
152
- id: string;
153
- event: string;
154
- payload: unknown;
155
- priority: Priority;
156
- idempotencyKey: string;
157
- createdAt: Date;
158
- }
159
- interface DeliveryRecord {
160
- id: string;
161
- notificationId: string;
162
- channel: string;
163
- address: unknown;
164
- recipientId?: string;
165
- status: DeliveryStatus;
166
- attempts: number;
167
- nextAttemptAt: Date | null;
168
- leaseUntil: Date | null;
169
- lastError: string | null;
170
- }
171
- /** A delivery leased to this worker, with the notification data needed to render it. */
172
- interface ClaimedDelivery extends DeliveryRecord {
173
- notification: NotificationRecord;
174
- }
175
- type DeliveryResult = {
176
- status: "sent";
177
- providerId?: string;
178
- } | {
179
- status: "retry";
180
- nextAttemptAt: Date;
181
- error: string;
182
- } | {
183
- status: "dead";
184
- error: string;
185
- };
186
- interface InboxItem {
187
- id: string;
188
- recipientId: string;
189
- notificationId: string;
190
- title: string;
191
- body: string;
192
- data?: unknown;
193
- createdAt: Date;
194
- readAt: Date | null;
195
- }
196
- interface InboxQuery {
197
- recipientId: string;
198
- unreadOnly?: boolean;
199
- limit?: number;
200
- cursor?: string;
201
- }
202
- interface InboxPage {
203
- items: InboxItem[];
204
- nextCursor: string | null;
205
- }
206
- /**
207
- * Persistence contract. Herald never sees a driver type. A store never sees
208
- * templates, channels or preferences.
209
- */
210
- interface Store {
211
- /**
212
- * Atomically insert the notification and its delivery rows. Unique on
213
- * `idempotencyKey`: a repeat returns the existing id with `created: false`.
214
- */
215
- enqueue(n: NewNotification): Promise<{
216
- id: string;
217
- created: boolean;
218
- }>;
219
- /**
220
- * Lease up to `limit` deliveries that are due (`pending`/`retry` with
221
- * `nextAttemptAt <= now`) or whose lease expired. Sets `leaseUntil = now + leaseMs`
222
- * and status `sending`. Concurrent callers must never receive the same row
223
- * (Postgres: `FOR UPDATE SKIP LOCKED`). Lease expiry is what makes a killed
224
- * worker's rows reappear: delivery is at-least-once.
225
- */
226
- claim(opts: {
227
- limit: number;
228
- now: Date;
229
- leaseMs: number;
230
- }): Promise<ClaimedDelivery[]>;
231
- /** Record an attempt outcome: status, attempts, error; clears the lease. */
232
- recordResult(deliveryId: string, result: DeliveryResult): Promise<void>;
233
- getNotification(id: string): Promise<{
234
- notification: NotificationRecord;
235
- deliveries: DeliveryRecord[];
236
- } | null>;
237
- inboxAdd(item: Omit<InboxItem, "id" | "createdAt" | "readAt">): Promise<InboxItem>;
238
- inboxList(q: InboxQuery): Promise<InboxPage>;
239
- inboxMarkRead(recipientId: string, ids: readonly string[]): Promise<void>;
240
- /** Create or upgrade Herald's tables. Optional: apps may manage schema themselves. */
241
- migrate?(): Promise<void>;
242
- close?(): Promise<void>;
243
- }
244
-
245
69
  interface HeraldConfig<Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>> {
246
70
  store: Store;
247
71
  channels: Ch;
@@ -270,16 +94,16 @@ interface Herald<Ev extends Record<string, AnyEventDef>> {
270
94
  declare const defaultRetry: RetryPolicy;
271
95
  /**
272
96
  * Validates config at startup (missing templates, unregistered channels are
273
- * errors here, not at send time). Behavior lands in later releases: `notify`,
274
- * `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.
275
99
  */
276
100
  declare function createHerald<const Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>>(config: HeraldConfig<Ch, Ev>): Herald<Ev>;
277
101
 
278
- 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";
279
103
  /** Every error Herald throws on its own behalf. Channel failures never surface through here. */
280
104
  declare class HeraldError extends Error {
281
105
  readonly code: HeraldErrorCode;
282
106
  constructor(code: HeraldErrorCode, message: string);
283
107
  }
284
108
 
285
- export { type AllowedChannel, type Channel, type ChannelMap, type ClaimedDelivery, type DeliveryInfo, 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 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, 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,
@@ -16,12 +75,27 @@ var defaultRetry = {
16
75
  jitter: true
17
76
  };
18
77
  var fn = (v) => typeof v === "function";
78
+ var STORE_METHODS = [
79
+ "enqueue",
80
+ "claim",
81
+ "recordResult",
82
+ "listDeliveries",
83
+ "retryDelivery",
84
+ "cancel",
85
+ "purge",
86
+ "getNotification",
87
+ "inboxAdd",
88
+ "inboxList",
89
+ "inboxMarkRead",
90
+ "inboxUnreadCount",
91
+ "inboxMarkAllRead"
92
+ ];
19
93
  function validate(config) {
20
94
  const bad = (msg) => {
21
95
  throw new HeraldError("invalid_config", msg);
22
96
  };
23
97
  const { store, channels, events } = config;
24
- for (const m of ["enqueue", "claim", "recordResult"]) {
98
+ for (const m of STORE_METHODS) {
25
99
  if (!fn(store?.[m]))
26
100
  bad(`store.${m} is not a function`);
27
101
  }
@@ -51,17 +125,19 @@ function createHerald(config) {
51
125
  throw new HeraldError("not_implemented", `${what} is not implemented yet`);
52
126
  };
53
127
  return {
54
- async notify(event, _payload, targets) {
55
- const def = config.events[event];
56
- if (!def) throw new HeraldError("unknown_event", `unknown event "${event}"`);
57
- for (const ch of targets.channels ?? []) {
58
- if (!def.channels.includes(ch))
59
- throw new HeraldError(
60
- "channel_not_allowed",
61
- `event "${event}" does not allow channel "${ch}"`
62
- );
63
- }
64
- 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
+ );
65
141
  },
66
142
  async processPending() {
67
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\";\nimport { HeraldError } from \"./errors.js\";\nimport type { AllowedChannel, AnyEventDef, ChannelMap, Conform, PayloadOf } from \"./events.js\";\nimport type { InboxPage, InboxQuery, Store } from \"./store.js\";\nimport type {\n Hooks,\n Logger,\n ProcessOptions,\n ProcessSummary,\n ResolveAddress,\n ResolvePreferences,\n RetryPolicy,\n Targets,\n} from \"./types.js\";\n\nexport interface HeraldConfig<Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>> {\n store: Store;\n channels: Ch;\n /** Each event must conform to the channel map: registered channels, matching message types. */\n events: Ev & { [E in keyof Ev]: Conform<Ev[E], Ch> };\n resolvePreferences?: ResolvePreferences;\n resolveAddress?: ResolveAddress;\n hooks?: Hooks;\n logger?: Logger;\n retry?: Partial<RetryPolicy>;\n /** Clock override for tests. */\n now?: () => Date;\n}\n\nexport interface Herald<Ev extends Record<string, AnyEventDef>> {\n /** Queue a notification. Resolves with its id; channel failures never reach the caller. */\n notify<E extends keyof Ev & string>(\n event: E,\n payload: PayloadOf<Ev[E]>,\n targets: Targets<AllowedChannel<Ev[E]>>,\n ): Promise<string>;\n /** Claim and deliver due work. The host schedules this (interval, cron, queue trigger). */\n processPending(opts?: ProcessOptions): Promise<ProcessSummary>;\n inbox: {\n list(q: InboxQuery): Promise<InboxPage>;\n markRead(recipientId: string, ids: readonly string[]): Promise<void>;\n };\n}\n\nexport const defaultRetry: RetryPolicy = {\n maxAttempts: 5,\n baseMs: 30_000,\n maxMs: 3_600_000,\n jitter: true,\n};\n\nconst fn = (v: unknown): boolean => typeof v === \"function\";\n\nfunction validate(config: HeraldConfig<ChannelMap, Record<string, AnyEventDef>>): void {\n const bad = (msg: string): never => {\n throw new HeraldError(\"invalid_config\", msg);\n };\n\n const { store, channels, events } = config;\n for (const m of [\"enqueue\", \"claim\", \"recordResult\"] as const) {\n if (!fn((store as unknown as Record<string, unknown> | undefined)?.[m]))\n bad(`store.${m} is not a function`);\n }\n\n for (const [name, ch] of Object.entries(channels ?? {})) {\n const c = ch as Channel | undefined;\n if (!c || !fn(c.send) || !fn(c.classifyError))\n bad(`channel \"${name}\" must implement send() and classifyError()`);\n }\n\n const names = Object.keys(events ?? {});\n if (names.length === 0) bad(\"at least one event is required\");\n\n for (const [event, def] of Object.entries(events)) {\n if (!def.channels?.length) bad(`event \"${event}\" must allow at least one channel`);\n for (const ch of def.channels) {\n if (!(ch in channels)) bad(`event \"${event}\" allows unregistered channel \"${ch}\"`);\n if (!fn((def.templates as Record<string, unknown> | undefined)?.[ch]))\n throw new HeraldError(\"missing_template\", `event \"${event}\" has no template for channel \"${ch}\"`);\n }\n for (const ch of Object.keys(def.templates ?? {})) {\n if (!def.channels.includes(ch))\n bad(`event \"${event}\" has a template for \"${ch}\" which is not in its allowed channels`);\n }\n }\n}\n\n/**\n * Validates config at startup (missing templates, unregistered channels are\n * errors here, not at send time). Behavior lands in later releases: `notify`,\n * `processPending` and `inbox` are typed but throw `not_implemented` for now.\n */\nexport function createHerald<\n const Ch extends ChannelMap,\n Ev extends Record<string, AnyEventDef>,\n>(config: HeraldConfig<Ch, Ev>): Herald<Ev> {\n validate(config as unknown as HeraldConfig<ChannelMap, Record<string, AnyEventDef>>);\n\n const notImplemented = (what: string): never => {\n throw new HeraldError(\"not_implemented\", `${what} is not implemented yet`);\n };\n\n return {\n async notify(event, _payload, targets) {\n const def = config.events[event] as AnyEventDef | undefined;\n if (!def) throw new HeraldError(\"unknown_event\", `unknown event \"${event}\"`);\n for (const ch of targets.channels ?? []) {\n if (!def.channels.includes(ch))\n throw new HeraldError(\n \"channel_not_allowed\",\n `event \"${event}\" does not allow channel \"${ch}\"`,\n );\n }\n return notImplemented(\"notify()\");\n },\n async processPending() {\n return notImplemented(\"processPending()\");\n },\n inbox: {\n async list() {\n return notImplemented(\"inbox.list()\");\n },\n async markRead() {\n return notImplemented(\"inbox.markRead()\");\n },\n },\n };\n}\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,OAAO;AAAA,EACd;AACF;;;AC4BO,IAAM,eAA4B;AAAA,EACvC,aAAa;AAAA,EACb,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,QAAQ;AACV;AAEA,IAAM,KAAK,CAAC,MAAwB,OAAO,MAAM;AAEjD,SAAS,SAAS,QAAqE;AACrF,QAAM,MAAM,CAAC,QAAuB;AAClC,UAAM,IAAI,YAAY,kBAAkB,GAAG;AAAA,EAC7C;AAEA,QAAM,EAAE,OAAO,UAAU,OAAO,IAAI;AACpC,aAAW,KAAK,CAAC,WAAW,SAAS,cAAc,GAAY;AAC7D,QAAI,CAAC,GAAI,QAA2D,CAAC,CAAC;AAC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AG;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/FO,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,MAAM,KAAK,OAAO,KAAK;AAC7B,MAAI,CAAC,IAAK,OAAM,IAAI,YAAY,iBAAiB,kBAAkB,KAAK,GAAG;AAC3E,MAAI,CAAC,QAAQ,IAAI;AACf,UAAM,IAAI,YAAY,mBAAmB,WAAW,KAAK,sCAAsC;AAEjG,QAAM,WAAW,CAAC,GAAG,IAAI,IAAI,QAAQ,YAAY,IAAI,QAAQ,CAAC;AAC9D,aAAW,MAAM,UAAU;AACzB,QAAI,CAAC,IAAI,SAAS,SAAS,EAAE;AAC3B,YAAM,IAAI,YAAY,uBAAuB,UAAU,KAAK,6BAA6B,EAAE,GAAG;AAAA,EAClG;AAEA,QAAM,OAAO,QAAQ,GAAG,OAAO,KAAK;AACpC,aAAW,KAAK,MAAM;AACpB,QAAI,CAAC,SAAS,SAAS,EAAE,OAAO;AAC9B,YAAM,IAAI;AAAA,QACR;AAAA,QACA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UAAU,KAAK,mCAAmC;AACjF,eAAW,MAAM,IAAI,UAAU;AAC7B,UAAI,EAAE,MAAM,UAAW,KAAI,UAAU,KAAK,kCAAkC,EAAE,GAAG;AACjF,UAAI,CAAC,GAAI,IAAI,YAAoD,EAAE,CAAC;AAClE,cAAM,IAAI,YAAY,oBAAoB,UAAU,KAAK,kCAAkC,EAAE,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,OAAO,OAAO,SAAS,SAAS;AAC9B,aAAO;AAAA,QACL;AAAA,UACE,OAAO,OAAO;AAAA,UACd,QAAQ,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
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/memory.ts"],"sourcesContent":["import type {\n ClaimedDelivery,\n DeliveryPage,\n DeliveryQuery,\n DeliveryRecord,\n DeliveryResult,\n InboxItem,\n InboxPage,\n InboxQuery,\n ListedDelivery,\n NewNotification,\n NotificationRecord,\n Store,\n} from \"./store.js\";\nimport type { TerminalStatus } from \"./types.js\";\n\nexport interface MemoryStoreOptions {\n /** Clock override for tests. */\n now?: () => Date;\n}\n\nconst TERMINAL: readonly TerminalStatus[] = [\"sent\", \"dead\", \"skipped\", \"cancelled\"];\nconst DEFAULT_PAGE = 50;\n\nconst pad = (n: number) => String(n).padStart(12, \"0\");\n\n/** Newest first: (createdAt desc, id desc). */\nconst newestFirst = (a: { createdAt: Date; id: string }, b: { createdAt: Date; id: string }) =>\n b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);\n\nconst encodeCursor = (x: { createdAt: Date; id: string }) => btoa(`${x.createdAt.getTime()}|${x.id}`);\n\n/** True when `x` sorts strictly after the cursor position in newest-first order. */\nfunction afterCursor(x: { createdAt: Date; id: string }, cursor: string): boolean {\n const [ms, id] = atob(cursor).split(\"|\") as [string, string];\n const t = x.createdAt.getTime();\n const c = Number(ms);\n return t < c || (t === c && x.id < id);\n}\n\nfunction page<T extends { createdAt: Date; id: string }>(\n rows: T[],\n limit: number | undefined,\n cursor: string | undefined,\n): { items: T[]; nextCursor: string | null } {\n const size = limit ?? DEFAULT_PAGE;\n const sorted = rows.sort(newestFirst).filter((r) => !cursor || afterCursor(r, cursor));\n const items = sorted.slice(0, size);\n const last = items[items.length - 1];\n return { items, nextCursor: sorted.length > size && last ? encodeCursor(last) : null };\n}\n\n/**\n * Complete in-process Store. Reference implementation of the Store contract,\n * for tests and local development. Not durable and not shared across processes.\n * `claim` is atomic because JS is single-threaded; the contract suite still proves it.\n */\nexport function memoryStore(options: MemoryStoreOptions = {}): Store {\n const clock = options.now ?? (() => new Date());\n let seq = 0;\n const nextId = (p: string) => `${p}_${pad(++seq)}`;\n\n const notifications = new Map<string, NotificationRecord>();\n const byKey = new Map<string, string>();\n const deliveries = new Map<string, DeliveryRecord>();\n const inbox = new Map<string, InboxItem>();\n\n const out = <T>(v: T): T => structuredClone(v);\n\n const claimedView = (d: DeliveryRecord): ClaimedDelivery => {\n const notification = notifications.get(d.notificationId) as NotificationRecord;\n return out({ ...d, notification });\n };\n\n return {\n async enqueue(n: NewNotification) {\n const existing = byKey.get(n.idempotencyKey);\n if (existing) return { id: existing, created: false };\n\n const createdAt = clock();\n const id = nextId(\"n\");\n notifications.set(id, {\n id,\n event: n.event,\n payload: out(n.payload),\n priority: n.priority,\n idempotencyKey: n.idempotencyKey,\n subject: n.subject,\n createdAt,\n });\n byKey.set(n.idempotencyKey, id);\n\n for (const d of n.deliveries) {\n const did = nextId(\"d\");\n deliveries.set(did, {\n id: did,\n notificationId: id,\n channel: d.channel,\n address: out(d.address),\n ...(d.recipientId !== undefined && { recipientId: d.recipientId }),\n status: d.status,\n attempts: 0,\n nextAttemptAt: null, // null = due immediately\n leaseUntil: null,\n lastError: null,\n createdAt,\n });\n }\n return { id, created: true };\n },\n\n async claim({ limit, now, leaseMs }) {\n const due = [...deliveries.values()]\n .filter((d) => {\n if (d.status === \"pending\" || d.status === \"retry\")\n return d.nextAttemptAt === null || d.nextAttemptAt <= now;\n return d.status === \"sending\" && d.leaseUntil !== null && d.leaseUntil <= now;\n })\n .sort(\n (a, b) =>\n (a.nextAttemptAt?.getTime() ?? 0) - (b.nextAttemptAt?.getTime() ?? 0) ||\n a.createdAt.getTime() - b.createdAt.getTime() ||\n (a.id < b.id ? -1 : 1),\n )\n .slice(0, limit);\n\n return due.map((d) => {\n d.status = \"sending\";\n d.attempts += 1; // attempts = the number of the attempt being made\n d.leaseUntil = new Date(now.getTime() + leaseMs);\n return claimedView(d);\n });\n },\n\n async recordResult(deliveryId: string, result: DeliveryResult) {\n const d = deliveries.get(deliveryId);\n if (!d || d.status !== \"sending\") return; // e.g. cancelled while in flight\n d.leaseUntil = null;\n if (result.status === \"sent\") {\n d.status = \"sent\";\n d.nextAttemptAt = null;\n d.lastError = null;\n } else if (result.status === \"retry\") {\n d.status = \"retry\";\n d.nextAttemptAt = new Date(result.nextAttemptAt);\n d.lastError = result.error;\n } else {\n d.status = \"dead\";\n d.nextAttemptAt = null;\n d.lastError = result.error;\n }\n },\n\n async getNotification(id: string) {\n const notification = notifications.get(id);\n if (!notification) return null;\n return out({\n notification,\n deliveries: [...deliveries.values()].filter((d) => d.notificationId === id),\n });\n },\n\n async listDeliveries(q: DeliveryQuery): Promise<DeliveryPage> {\n const rows: ListedDelivery[] = [];\n for (const d of deliveries.values()) {\n const n = notifications.get(d.notificationId) as NotificationRecord;\n if (q.recipientId !== undefined && d.recipientId !== q.recipientId) continue;\n if (q.event !== undefined && n.event !== q.event) continue;\n if (q.channel !== undefined && d.channel !== q.channel) continue;\n if (q.status !== undefined && d.status !== q.status) continue;\n if (q.subject !== undefined && n.subject !== q.subject) continue;\n if (q.since && d.createdAt < q.since) continue;\n if (q.until && d.createdAt >= q.until) continue;\n rows.push({ ...d, event: n.event, subject: n.subject });\n }\n return out(page(rows, q.limit, q.cursor));\n },\n\n async retryDelivery(deliveryId: string) {\n const d = deliveries.get(deliveryId);\n if (!d || d.status !== \"dead\") return false;\n d.status = \"pending\";\n d.attempts = 0;\n d.nextAttemptAt = null;\n d.leaseUntil = null;\n return true;\n },\n\n async cancel({ subject }) {\n const ids = new Set(\n [...notifications.values()].filter((n) => n.subject === subject).map((n) => n.id),\n );\n let count = 0;\n for (const d of deliveries.values()) {\n if (!ids.has(d.notificationId)) continue;\n if (d.status !== \"pending\" && d.status !== \"retry\") continue;\n d.status = \"cancelled\";\n d.nextAttemptAt = null;\n d.leaseUntil = null;\n count += 1;\n }\n return count;\n },\n\n async purge({ olderThan, statuses }) {\n const allowed: readonly string[] = statuses ?? TERMINAL;\n let count = 0;\n for (const [id, d] of deliveries) {\n if (d.createdAt < olderThan && TERMINAL.includes(d.status as TerminalStatus) && allowed.includes(d.status)) {\n deliveries.delete(id);\n count += 1;\n }\n }\n const withDeliveries = new Set([...deliveries.values()].map((d) => d.notificationId));\n for (const [id, n] of notifications) {\n if (n.createdAt < olderThan && !withDeliveries.has(id)) {\n notifications.delete(id);\n byKey.delete(n.idempotencyKey);\n }\n }\n return count;\n },\n\n async inboxAdd(item) {\n const created: InboxItem = { ...out(item), id: nextId(\"i\"), createdAt: clock(), readAt: null };\n inbox.set(created.id, created);\n return out(created);\n },\n\n async inboxList(q: InboxQuery): Promise<InboxPage> {\n const rows = [...inbox.values()].filter(\n (i) => i.recipientId === q.recipientId && (!q.unreadOnly || i.readAt === null),\n );\n return out(page(rows, q.limit, q.cursor));\n },\n\n async inboxMarkRead(recipientId, ids) {\n const now = clock();\n for (const id of ids) {\n const i = inbox.get(id);\n if (i && i.recipientId === recipientId && i.readAt === null) i.readAt = now;\n }\n },\n\n async inboxUnreadCount(recipientId) {\n return [...inbox.values()].filter((i) => i.recipientId === recipientId && i.readAt === null)\n .length;\n },\n\n async inboxMarkAllRead(recipientId) {\n const now = clock();\n let count = 0;\n for (const i of inbox.values()) {\n if (i.recipientId === recipientId && i.readAt === null) {\n i.readAt = now;\n count += 1;\n }\n }\n return count;\n },\n };\n}\n"],"mappings":";AAqBA,IAAM,WAAsC,CAAC,QAAQ,QAAQ,WAAW,WAAW;AACnF,IAAM,eAAe;AAErB,IAAM,MAAM,CAAC,MAAc,OAAO,CAAC,EAAE,SAAS,IAAI,GAAG;AAGrD,IAAM,cAAc,CAAC,GAAoC,MACvD,EAAE,UAAU,QAAQ,IAAI,EAAE,UAAU,QAAQ,MAAM,EAAE,KAAK,EAAE,KAAK,IAAI,EAAE,KAAK,EAAE,KAAK,KAAK;AAEzF,IAAM,eAAe,CAAC,MAAuC,KAAK,GAAG,EAAE,UAAU,QAAQ,CAAC,IAAI,EAAE,EAAE,EAAE;AAGpG,SAAS,YAAY,GAAoC,QAAyB;AAChF,QAAM,CAAC,IAAI,EAAE,IAAI,KAAK,MAAM,EAAE,MAAM,GAAG;AACvC,QAAM,IAAI,EAAE,UAAU,QAAQ;AAC9B,QAAM,IAAI,OAAO,EAAE;AACnB,SAAO,IAAI,KAAM,MAAM,KAAK,EAAE,KAAK;AACrC;AAEA,SAAS,KACP,MACA,OACA,QAC2C;AAC3C,QAAM,OAAO,SAAS;AACtB,QAAM,SAAS,KAAK,KAAK,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,UAAU,YAAY,GAAG,MAAM,CAAC;AACrF,QAAM,QA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