@useherald/core 0.0.1 → 0.2.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 +356 -2
- package/dist/index.js +102 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,357 @@
|
|
|
1
|
-
|
|
1
|
+
interface SendContext {
|
|
2
|
+
/** Stable per delivery across retries. Pass to providers that dedupe. */
|
|
3
|
+
idempotencyKey: string;
|
|
4
|
+
/** 1-based attempt number. */
|
|
5
|
+
attempt: number;
|
|
6
|
+
/** Aborts when the processing time budget runs out. */
|
|
7
|
+
signal?: AbortSignal;
|
|
8
|
+
}
|
|
9
|
+
interface SendResult {
|
|
10
|
+
providerId?: string;
|
|
11
|
+
}
|
|
12
|
+
interface ErrorClass {
|
|
13
|
+
/** `false` = permanent, the delivery goes straight to `dead`. */
|
|
14
|
+
retryable: boolean;
|
|
15
|
+
/** From e.g. a Slack 429 `Retry-After`. Overrides backoff when present. */
|
|
16
|
+
retryAfterMs?: number;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* One delivery mechanism. `send` throws on failure; the engine asks
|
|
20
|
+
* `classifyError` whether to retry. Adapters own that classification.
|
|
21
|
+
*/
|
|
22
|
+
interface Channel<TMessage = unknown, TAddress = unknown> {
|
|
23
|
+
readonly name: string;
|
|
24
|
+
send(message: TMessage, to: TAddress, ctx: SendContext): Promise<SendResult>;
|
|
25
|
+
classifyError(err: unknown): ErrorClass;
|
|
26
|
+
}
|
|
2
27
|
|
|
3
|
-
|
|
28
|
+
type ChannelMap = Record<string, Channel<any, any>>;
|
|
29
|
+
/** The message type a channel expects from its templates. */
|
|
30
|
+
type MessageOf<C> = C extends Channel<infer M, any> ? M : never;
|
|
31
|
+
/**
|
|
32
|
+
* An event: its allowed channels and one template per channel. `P` is the
|
|
33
|
+
* payload type (type-only, via `__payload`); templates are plain functions.
|
|
34
|
+
*/
|
|
35
|
+
interface EventDef<P = unknown, K extends string = string, T extends {
|
|
36
|
+
readonly [C in K]: (payload: P) => unknown;
|
|
37
|
+
} = {
|
|
38
|
+
readonly [C in K]: (payload: P) => unknown;
|
|
39
|
+
}> {
|
|
40
|
+
readonly channels: readonly K[];
|
|
41
|
+
readonly templates: T;
|
|
42
|
+
readonly __payload?: P;
|
|
43
|
+
}
|
|
44
|
+
type AnyEventDef = EventDef<any, string, any>;
|
|
45
|
+
type PayloadOf<D> = D extends EventDef<infer P, any, any> ? P : never;
|
|
46
|
+
type AllowedChannel<D> = D extends EventDef<any, infer K, any> ? K : never;
|
|
47
|
+
/**
|
|
48
|
+
* Curried so the payload type is explicit while channel names are inferred:
|
|
49
|
+
* `defineEvent<{ name: string }>()({ channels: ["slack"], templates: { slack: (p) => ... } })`.
|
|
50
|
+
*/
|
|
51
|
+
declare function defineEvent<P>(): <const K extends string, T extends { [C in K]: (payload: P) => unknown; }>(def: {
|
|
52
|
+
channels: readonly K[];
|
|
53
|
+
templates: T;
|
|
54
|
+
}) => EventDef<P, K, T>;
|
|
55
|
+
/**
|
|
56
|
+
* What an event must look like against a concrete channel map: every allowed
|
|
57
|
+
* channel is registered, and each template returns that channel's message type.
|
|
58
|
+
*/
|
|
59
|
+
type Conform<D, Ch extends ChannelMap> = D extends EventDef<infer P, infer K, any> ? {
|
|
60
|
+
readonly channels: readonly (K & keyof Ch)[];
|
|
61
|
+
readonly templates: {
|
|
62
|
+
readonly [C in K]: C extends keyof Ch ? (payload: P) => MessageOf<Ch[C]> : never;
|
|
63
|
+
};
|
|
64
|
+
} : never;
|
|
65
|
+
|
|
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
|
+
interface HeraldConfig<Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>> {
|
|
318
|
+
store: Store;
|
|
319
|
+
channels: Ch;
|
|
320
|
+
/** Each event must conform to the channel map: registered channels, matching message types. */
|
|
321
|
+
events: Ev & {
|
|
322
|
+
[E in keyof Ev]: Conform<Ev[E], Ch>;
|
|
323
|
+
};
|
|
324
|
+
resolvePreferences?: ResolvePreferences;
|
|
325
|
+
resolveAddress?: ResolveAddress;
|
|
326
|
+
hooks?: Hooks;
|
|
327
|
+
logger?: Logger;
|
|
328
|
+
retry?: Partial<RetryPolicy>;
|
|
329
|
+
/** Clock override for tests. */
|
|
330
|
+
now?: () => Date;
|
|
331
|
+
}
|
|
332
|
+
interface Herald<Ev extends Record<string, AnyEventDef>> {
|
|
333
|
+
/** Queue a notification. Resolves with its id; channel failures never reach the caller. */
|
|
334
|
+
notify<E extends keyof Ev & string>(event: E, payload: PayloadOf<Ev[E]>, targets: Targets<AllowedChannel<Ev[E]>>): Promise<string>;
|
|
335
|
+
/** Claim and deliver due work. The host schedules this (interval, cron, queue trigger). */
|
|
336
|
+
processPending(opts?: ProcessOptions): Promise<ProcessSummary>;
|
|
337
|
+
inbox: {
|
|
338
|
+
list(q: InboxQuery): Promise<InboxPage>;
|
|
339
|
+
markRead(recipientId: string, ids: readonly string[]): Promise<void>;
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
declare const defaultRetry: RetryPolicy;
|
|
343
|
+
/**
|
|
344
|
+
* 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.
|
|
347
|
+
*/
|
|
348
|
+
declare function createHerald<const Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>>(config: HeraldConfig<Ch, Ev>): Herald<Ev>;
|
|
349
|
+
|
|
350
|
+
type HeraldErrorCode = "invalid_config" | "unknown_event" | "channel_not_allowed" | "missing_template" | "not_implemented";
|
|
351
|
+
/** Every error Herald throws on its own behalf. Channel failures never surface through here. */
|
|
352
|
+
declare class HeraldError extends Error {
|
|
353
|
+
readonly code: HeraldErrorCode;
|
|
354
|
+
constructor(code: HeraldErrorCode, message: string);
|
|
355
|
+
}
|
|
356
|
+
|
|
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 };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,105 @@
|
|
|
1
|
-
// src/
|
|
2
|
-
var
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var HeraldError = class extends Error {
|
|
3
|
+
code;
|
|
4
|
+
constructor(code, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "HeraldError";
|
|
7
|
+
this.code = code;
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
// src/herald.ts
|
|
12
|
+
var defaultRetry = {
|
|
13
|
+
maxAttempts: 5,
|
|
14
|
+
baseMs: 3e4,
|
|
15
|
+
maxMs: 36e5,
|
|
16
|
+
jitter: true
|
|
17
|
+
};
|
|
18
|
+
var fn = (v) => typeof v === "function";
|
|
19
|
+
var STORE_METHODS = [
|
|
20
|
+
"enqueue",
|
|
21
|
+
"claim",
|
|
22
|
+
"recordResult",
|
|
23
|
+
"listDeliveries",
|
|
24
|
+
"retryDelivery",
|
|
25
|
+
"cancel",
|
|
26
|
+
"purge",
|
|
27
|
+
"getNotification",
|
|
28
|
+
"inboxAdd",
|
|
29
|
+
"inboxList",
|
|
30
|
+
"inboxMarkRead",
|
|
31
|
+
"inboxUnreadCount",
|
|
32
|
+
"inboxMarkAllRead"
|
|
33
|
+
];
|
|
34
|
+
function validate(config) {
|
|
35
|
+
const bad = (msg) => {
|
|
36
|
+
throw new HeraldError("invalid_config", msg);
|
|
37
|
+
};
|
|
38
|
+
const { store, channels, events } = config;
|
|
39
|
+
for (const m of STORE_METHODS) {
|
|
40
|
+
if (!fn(store?.[m]))
|
|
41
|
+
bad(`store.${m} is not a function`);
|
|
42
|
+
}
|
|
43
|
+
for (const [name, ch] of Object.entries(channels ?? {})) {
|
|
44
|
+
const c = ch;
|
|
45
|
+
if (!c || !fn(c.send) || !fn(c.classifyError))
|
|
46
|
+
bad(`channel "${name}" must implement send() and classifyError()`);
|
|
47
|
+
}
|
|
48
|
+
const names = Object.keys(events ?? {});
|
|
49
|
+
if (names.length === 0) bad("at least one event is required");
|
|
50
|
+
for (const [event, def] of Object.entries(events)) {
|
|
51
|
+
if (!def.channels?.length) bad(`event "${event}" must allow at least one channel`);
|
|
52
|
+
for (const ch of def.channels) {
|
|
53
|
+
if (!(ch in channels)) bad(`event "${event}" allows unregistered channel "${ch}"`);
|
|
54
|
+
if (!fn(def.templates?.[ch]))
|
|
55
|
+
throw new HeraldError("missing_template", `event "${event}" has no template for channel "${ch}"`);
|
|
56
|
+
}
|
|
57
|
+
for (const ch of Object.keys(def.templates ?? {})) {
|
|
58
|
+
if (!def.channels.includes(ch))
|
|
59
|
+
bad(`event "${event}" has a template for "${ch}" which is not in its allowed channels`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function createHerald(config) {
|
|
64
|
+
validate(config);
|
|
65
|
+
const notImplemented = (what) => {
|
|
66
|
+
throw new HeraldError("not_implemented", `${what} is not implemented yet`);
|
|
67
|
+
};
|
|
68
|
+
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()");
|
|
80
|
+
},
|
|
81
|
+
async processPending() {
|
|
82
|
+
return notImplemented("processPending()");
|
|
83
|
+
},
|
|
84
|
+
inbox: {
|
|
85
|
+
async list() {
|
|
86
|
+
return notImplemented("inbox.list()");
|
|
87
|
+
},
|
|
88
|
+
async markRead() {
|
|
89
|
+
return notImplemented("inbox.markRead()");
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// src/events.ts
|
|
96
|
+
function defineEvent() {
|
|
97
|
+
return (def) => def;
|
|
98
|
+
}
|
|
3
99
|
export {
|
|
4
|
-
|
|
100
|
+
HeraldError,
|
|
101
|
+
createHerald,
|
|
102
|
+
defaultRetry,
|
|
103
|
+
defineEvent
|
|
5
104
|
};
|
|
6
105
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/
|
|
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,OAAO;AAAA,EACd;AACF;;;AC4BO,IAAM,eAA4B;AAAA,EACvC,aAAa;AAAA,EACb,QAAQ;AAA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