@prosody-events/prosody 0.3.1 → 0.5.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.
Files changed (6) hide show
  1. package/README.md +657 -353
  2. package/bindings.d.ts +780 -48
  3. package/bindings.js +226 -83
  4. package/index.d.ts +706 -22
  5. package/index.js +1446 -105
  6. package/package.json +23 -20
package/index.d.ts CHANGED
@@ -5,14 +5,80 @@
5
5
  */
6
6
 
7
7
  import type {
8
+ AdminClient,
8
9
  Configuration,
9
10
  ConsumerState,
10
- Message,
11
+ ExciseMessage as NativeExciseMessage,
12
+ Message as NativeMessage,
11
13
  Mode,
14
+ ReadCacheConfiguration,
12
15
  Timer,
13
16
  } from "./bindings";
14
17
 
15
- export { Configuration, ConsumerState, Message, Timer, Mode };
18
+ export {
19
+ AdminClient,
20
+ Configuration,
21
+ ConsumerState,
22
+ ReadCacheConfiguration,
23
+ Timer,
24
+ Mode,
25
+ };
26
+
27
+ /** Exports all pending telemetry data. */
28
+ export function flushTelemetry(): void;
29
+
30
+ /** Stops the global telemetry providers after they export pending data. */
31
+ export function shutdownTelemetry(): void;
32
+
33
+ /** A primitive value representable in JSON. */
34
+ export type JsonPrimitive = null | boolean | number | string;
35
+
36
+ /**
37
+ * Any value representable in JSON.
38
+ *
39
+ * This is a compile-time contract. Prosody serializes payloads at runtime but
40
+ * does not validate them against a more specific application payload type.
41
+ */
42
+ export type JsonValue =
43
+ JsonPrimitive | readonly JsonValue[] | { readonly [key: string]: JsonValue };
44
+
45
+ /**
46
+ * Maps an application type to its JSON-compatible shape. This lets APIs
47
+ * accept ordinary interfaces and type aliases without requiring an index
48
+ * signature, while rejecting non-JSON members wherever they are nested.
49
+ */
50
+ export type JsonCompatible<T> = T extends JsonPrimitive
51
+ ? T
52
+ : T extends bigint | symbol | undefined | ((...args: never[]) => unknown)
53
+ ? never
54
+ : T extends readonly (infer Item)[]
55
+ ? readonly JsonCompatible<Item>[]
56
+ : T extends object
57
+ ? { readonly [Key in keyof T]: JsonCompatible<T[Key]> }
58
+ : never;
59
+
60
+ /** A value that a handler can return now or through a promise. */
61
+ export type MaybePromise<T> = T | PromiseLike<T>;
62
+
63
+ /**
64
+ * Represents a message consumed from a Kafka topic.
65
+ *
66
+ * The optional payload type parameter is annotation-level only: the runtime
67
+ * payload is unchanged. An unparameterized `Message` uses {@link JsonValue};
68
+ * provide an application payload type for precise field-level checking.
69
+ * Message-backed keyed-state collections vend their items as `Message<P>`.
70
+ *
71
+ * A message can be stored into a message collection, whether it arrived from the
72
+ * topic or was read back out of a collection. What is stored is the message
73
+ * itself, so mutating its parsed `payload` does not change what is written.
74
+ */
75
+ export interface Message<P = JsonValue> extends Omit<NativeMessage, "payload"> {
76
+ /** The message payload as a JSON-serializable value. */
77
+ payload: P;
78
+ }
79
+
80
+ /** An excise record with Kafka metadata and no payload. */
81
+ export type ExciseMessage = NativeExciseMessage;
16
82
 
17
83
  /**
18
84
  * Wrapper around `MessageContext` for use in Node.js bindings.
@@ -74,6 +140,454 @@ export declare class Context {
74
140
  * @throws Error if retrieval fails.
75
141
  */
76
142
  scheduled(): Promise<Array<Date>>;
143
+
144
+ /**
145
+ * Binds a registered message single-value collection, vending a handle whose
146
+ * item is the full `Message<P>`.
147
+ *
148
+ * The handle and any iterator it opens are valid only within this event
149
+ * attempt. Throws a {@link PermanentStateError} if the collection name is
150
+ * unregistered or its registered identity mismatches.
151
+ * @param definition - A definition from {@link messageValue}.
152
+ */
153
+ state<P>(definition: MessageValueDefinition<P>): ValueState<Message<P>>;
154
+ /**
155
+ * Binds a registered message ordered-map collection, vending a handle whose
156
+ * values are the full `Message<P>`. Valid only within this event attempt;
157
+ * throws {@link PermanentStateError} on an unregistered name or identity
158
+ * mismatch.
159
+ * @param definition - A definition from {@link messageMap}.
160
+ */
161
+ state<P>(definition: MessageMapDefinition<P>): MapState<Message<P>>;
162
+ /**
163
+ * Binds a registered message deque collection, vending a handle whose
164
+ * elements are the full `Message<P>`. Valid only within this event attempt;
165
+ * throws {@link PermanentStateError} on an unregistered name or identity
166
+ * mismatch.
167
+ * @param definition - A definition from {@link messageDeque}.
168
+ */
169
+ state<P>(definition: MessageDequeDefinition<P>): DequeState<Message<P>>;
170
+ /**
171
+ * Binds a registered single-value JSON collection. Valid only within this
172
+ * event attempt; throws {@link PermanentStateError} on an unregistered name
173
+ * or identity mismatch.
174
+ * @param definition - A definition from {@link value}.
175
+ */
176
+ state<T>(definition: ValueDefinition<T>): ValueState<T>;
177
+ /**
178
+ * Binds a registered ordered-map JSON collection (string keys). Valid only
179
+ * within this event attempt; throws {@link PermanentStateError} on an
180
+ * unregistered name or identity mismatch.
181
+ * @param definition - A definition from {@link map}.
182
+ */
183
+ state<V>(definition: MapDefinition<V>): MapState<V>;
184
+ /**
185
+ * Binds a registered deque JSON collection. Valid only within this event
186
+ * attempt; throws {@link PermanentStateError} on an unregistered name or
187
+ * identity mismatch.
188
+ * @param definition - A definition from {@link deque}.
189
+ */
190
+ state<T>(definition: DequeDefinition<T>): DequeState<T>;
191
+ }
192
+
193
+ /**
194
+ * Scan direction over a map or deque collection. `"forward"` visits a map in
195
+ * ascending key order and a deque from front to back; `"backward"` reverses
196
+ * each. Defaults to `"forward"` wherever it is optional.
197
+ */
198
+ export type ScanDirection = "forward" | "backward";
199
+
200
+ /** Options accepted by every keyed-state definition constructor. */
201
+ export interface StateDefinitionOptions {
202
+ /**
203
+ * Optional per-write TTL in whole seconds. Must be at least 1 and must
204
+ * exceed the client's recovery delay (enforced core-side).
205
+ */
206
+ ttlSeconds?: number;
207
+ /**
208
+ * Opt out of transactional staging (read-uncommitted, at-least-once).
209
+ * Defaults to transactional.
210
+ */
211
+ readUncommitted?: boolean;
212
+ }
213
+
214
+ /** Options accepted by JSON collections that may be published. */
215
+ export interface PublishedStateDefinitionOptions extends StateDefinitionOptions {
216
+ /** Allow read-only access from other consumer groups. */
217
+ published?: boolean;
218
+ /** Override caching when this descriptor opens a published reader. */
219
+ readCache?: ReadCacheOptions | false;
220
+ }
221
+
222
+ /** Options accepted by the map definition constructors. */
223
+ export interface MapDefinitionOptions extends PublishedStateDefinitionOptions {
224
+ /**
225
+ * Keyset bound for ordered scans (`0..=4096`; default 128 core-side; `0`
226
+ * disables ordered-scan tracking). Map collections only.
227
+ */
228
+ keysetLimit?: number;
229
+ }
230
+
231
+ /** Options accepted by the deque definition constructors. */
232
+ export interface DequeDefinitionOptions extends PublishedStateDefinitionOptions {
233
+ /**
234
+ * Optional maximum element count (bounded backlog). Must be a whole number
235
+ * >= 1. Runtime-only: not persisted, not part of collection identity, and
236
+ * changeable across deploys. Enforced lazily on push — the opposite end is
237
+ * evicted toward the bound (no decode, no fetch); a shrunk deque reports its
238
+ * old length until the next push trims it. Deque collections only.
239
+ */
240
+ capacity?: number;
241
+ }
242
+
243
+ /** Options accepted by message-map definitions, which cannot be published. */
244
+ export interface MessageMapDefinitionOptions extends StateDefinitionOptions {
245
+ /** Keyset bound for ordered scans (`0..=4096`; default 128 core-side). */
246
+ keysetLimit?: number;
247
+ }
248
+
249
+ /** Options accepted by message-deque definitions, which cannot be published. */
250
+ export interface MessageDequeDefinitionOptions extends StateDefinitionOptions {
251
+ /** Optional maximum element count. Must be a whole number >= 1. */
252
+ capacity?: number;
253
+ }
254
+
255
+ /**
256
+ * Phantom brand carrying a definition's item type. Never present at runtime —
257
+ * it exists only so the item type survives on the frozen definition object and
258
+ * flows into the vended handle.
259
+ */
260
+ declare const StateItem: unique symbol;
261
+ declare const StateDescriptor: unique symbol;
262
+
263
+ interface DefinitionBrand {
264
+ readonly [StateDescriptor]: true;
265
+ }
266
+
267
+ /** A frozen single-value JSON collection definition. */
268
+ export interface ValueDefinition<T = JsonValue> extends DefinitionBrand {
269
+ readonly name: string;
270
+ readonly kind: "value";
271
+ readonly payload: "json";
272
+ readonly ttlSeconds?: number;
273
+ readonly readUncommitted?: boolean;
274
+ readonly published?: boolean;
275
+ readonly readCache?: ReadCacheOptions | false;
276
+ readonly [StateItem]?: T;
277
+ }
278
+
279
+ /** A frozen ordered-map JSON collection definition (string keys). */
280
+ export interface MapDefinition<V = JsonValue> extends DefinitionBrand {
281
+ readonly name: string;
282
+ readonly kind: "map";
283
+ readonly payload: "json";
284
+ readonly ttlSeconds?: number;
285
+ readonly readUncommitted?: boolean;
286
+ readonly published?: boolean;
287
+ readonly readCache?: ReadCacheOptions | false;
288
+ readonly keysetLimit?: number;
289
+ readonly [StateItem]?: V;
290
+ }
291
+
292
+ /** A frozen deque JSON collection definition. */
293
+ export interface DequeDefinition<T = JsonValue> extends DefinitionBrand {
294
+ readonly name: string;
295
+ readonly kind: "deque";
296
+ readonly payload: "json";
297
+ readonly ttlSeconds?: number;
298
+ readonly readUncommitted?: boolean;
299
+ readonly published?: boolean;
300
+ readonly readCache?: ReadCacheOptions | false;
301
+ readonly capacity?: number;
302
+ readonly [StateItem]?: T;
303
+ }
304
+
305
+ /** A frozen single-value message collection definition (items are `Message<P>`). */
306
+ export interface MessageValueDefinition<P = JsonValue> extends DefinitionBrand {
307
+ readonly name: string;
308
+ readonly kind: "value";
309
+ readonly payload: "message";
310
+ readonly ttlSeconds?: number;
311
+ readonly readUncommitted?: boolean;
312
+ readonly [StateItem]?: P;
313
+ }
314
+
315
+ /** A frozen ordered-map message collection definition (values are `Message<P>`). */
316
+ export interface MessageMapDefinition<P = JsonValue> extends DefinitionBrand {
317
+ readonly name: string;
318
+ readonly kind: "map";
319
+ readonly payload: "message";
320
+ readonly ttlSeconds?: number;
321
+ readonly readUncommitted?: boolean;
322
+ readonly keysetLimit?: number;
323
+ readonly [StateItem]?: P;
324
+ }
325
+
326
+ /** A frozen deque message collection definition (elements are `Message<P>`). */
327
+ export interface MessageDequeDefinition<P = JsonValue> extends DefinitionBrand {
328
+ readonly name: string;
329
+ readonly kind: "deque";
330
+ readonly payload: "message";
331
+ readonly ttlSeconds?: number;
332
+ readonly readUncommitted?: boolean;
333
+ readonly capacity?: number;
334
+ readonly [StateItem]?: P;
335
+ }
336
+
337
+ /**
338
+ * Declares a single-value JSON collection. The returned frozen definition is
339
+ * the single source of typing: place it in `Configuration.stateCollections` to
340
+ * register the collection, and pass it to `Context.state()` to vend a typed
341
+ * handle. The type parameter annotates the stored value and is compile-time
342
+ * only — payloads cross as plain JSON with no runtime validation.
343
+ * @param name - The collection name (unique per client).
344
+ * @param options - Optional retention, transaction, publication, and read-cache
345
+ * settings.
346
+ */
347
+ export function value<T = JsonValue>(
348
+ name: string,
349
+ options?: PublishedStateDefinitionOptions,
350
+ ): ValueDefinition<T>;
351
+
352
+ /**
353
+ * Declares an ordered-map JSON collection. Map keys are always `string`. The
354
+ * returned frozen definition is used both in `Configuration.stateCollections`
355
+ * and with `Context.state()`. The type parameter annotates the stored value
356
+ * (compile-time only).
357
+ * @param name - The collection name (unique per client).
358
+ * @param options - Optional retention, transaction, publication, read-cache,
359
+ * and `keysetLimit` settings.
360
+ */
361
+ export function map<V = JsonValue>(
362
+ name: string,
363
+ options?: MapDefinitionOptions,
364
+ ): MapDefinition<V>;
365
+
366
+ /**
367
+ * Declares a double-ended-queue JSON collection. The returned frozen definition
368
+ * is used both in `Configuration.stateCollections` and with `Context.state()`.
369
+ * The type parameter annotates the stored element (compile-time only).
370
+ * @param name - The collection name (unique per client).
371
+ * @param options - Optional retention, transaction, publication, read-cache,
372
+ * and `capacity` settings.
373
+ */
374
+ export function deque<T = JsonValue>(
375
+ name: string,
376
+ options?: DequeDefinitionOptions,
377
+ ): DequeDefinition<T>;
378
+
379
+ /**
380
+ * Declares a single-value message collection: each stored item is the full
381
+ * Kafka `Message<P>` the handler received. The type parameter annotates the
382
+ * message payload (compile-time only).
383
+ * @param name - The collection name (unique per client).
384
+ * @param options - Optional `ttlSeconds` (whole seconds) and `readUncommitted`.
385
+ */
386
+ export function messageValue<P = JsonValue>(
387
+ name: string,
388
+ options?: StateDefinitionOptions,
389
+ ): MessageValueDefinition<P>;
390
+
391
+ /**
392
+ * Declares an ordered-map message collection (string keys; values are the full
393
+ * Kafka `Message<P>`). The type parameter annotates the message payload
394
+ * (compile-time only).
395
+ * @param name - The collection name (unique per client).
396
+ * @param options - Optional `ttlSeconds`, `readUncommitted`, and `keysetLimit`.
397
+ */
398
+ export function messageMap<P = JsonValue>(
399
+ name: string,
400
+ options?: MessageMapDefinitionOptions,
401
+ ): MessageMapDefinition<P>;
402
+
403
+ /**
404
+ * Declares a double-ended-queue message collection: each stored element is the
405
+ * full Kafka `Message<P>`. The type parameter annotates the message payload
406
+ * (compile-time only).
407
+ * @param name - The collection name (unique per client).
408
+ * @param options - Optional `ttlSeconds` (whole seconds), `readUncommitted`, and
409
+ * `capacity` (bounded backlog; enforced lazily on push).
410
+ */
411
+ export function messageDeque<P = JsonValue>(
412
+ name: string,
413
+ options?: MessageDequeDefinitionOptions,
414
+ ): MessageDequeDefinition<P>;
415
+
416
+ /**
417
+ * Typed handle over a single-value keyed-state collection, vended by
418
+ * `Context.state()`. Valid only within the handler invocation (attempt) that
419
+ * vended it. Every method opens its own per-operation trace span.
420
+ */
421
+ export declare class ValueState<T = JsonValue> {
422
+ /** Vended only by {@link Context#state}; not constructible directly. */
423
+ private constructor(native: unknown);
424
+ /** Reads the current value, or null when absent/cleared. */
425
+ get(): Promise<T | null>;
426
+ /**
427
+ * Buffers a write of the value. The parameter type excludes `null`/`undefined`
428
+ * (via {@link !NonNullable}) because a top-level `null` is not a storable
429
+ * value — writing one (or an unrepresentable value) is a caller mistake,
430
+ * rejected at runtime with a {@link TransientStateError} naming `clear()` —
431
+ * use {@link ValueState#clear}. Transient so it retries and stays visible
432
+ * rather than discarding the message. (Nested `null`, e.g. inside an object or
433
+ * array, is permitted and round-trips.)
434
+ */
435
+ set(value: NonNullable<T>): Promise<void>;
436
+ /** Deletes the stored value. */
437
+ clear(): Promise<void>;
438
+ /**
439
+ * Durably commits the buffered operations mid-handler (at-least-once).
440
+ * Resolves with no value — the erased seam drops the store outcome.
441
+ */
442
+ commit(): Promise<void>;
443
+ /** Discards buffered uncommitted operations back to the committed floor. */
444
+ rollback(): Promise<void>;
445
+ }
446
+
447
+ /**
448
+ * Typed handle over an ordered-map keyed-state collection, vended by
449
+ * `Context.state()`. Map keys are always `string`. Valid only within the
450
+ * handler invocation (attempt) that vended it. Every method opens its own
451
+ * per-operation trace span.
452
+ */
453
+ export declare class MapState<V = JsonValue> {
454
+ /** Vended only by {@link Context#state}; not constructible directly. */
455
+ private constructor(native: unknown);
456
+ /** Reads the value for `key`, or null when the key is absent. */
457
+ get(key: string): Promise<V | null>;
458
+ /**
459
+ * Reads several keys in a single call. Returns an array with one entry per
460
+ * key, in the same order you asked, so `result[i]` is the value for
461
+ * `keys[i]`. A key that isn't there comes back as `null`, and a key you list
462
+ * more than once is answered at each spot. The whole read happens as one
463
+ * step, so no other change to this event's state can slip in partway through.
464
+ */
465
+ getMany(keys: readonly string[]): Promise<(V | null)[]>;
466
+ /**
467
+ * Reports whether `key` currently has a stored value. A presence check that
468
+ * skips the value decode and the resolver: for a message-backed map it
469
+ * answers with zero Kafka fetches and can report `true` for a message that
470
+ * can no longer be fetched. Not zero-I/O — a cache miss can still reach the
471
+ * store — but cheaper than {@link MapState#get} when you only need presence.
472
+ */
473
+ has(key: string): Promise<boolean>;
474
+ /**
475
+ * Inserts or overwrites `key`. The value type excludes `null`/`undefined`
476
+ * (via {@link !NonNullable}) because a top-level `null` is not a storable
477
+ * value — writing one (or an unrepresentable value) is a caller mistake,
478
+ * rejected at runtime with a {@link TransientStateError} — use
479
+ * {@link MapState#delete} to remove. Transient so it retries and stays visible
480
+ * rather than discarding the message. (Nested `null` is permitted.)
481
+ */
482
+ set(key: string, value: NonNullable<V>): Promise<void>;
483
+ /**
484
+ * Removes `key`.
485
+ *
486
+ * Deliberate divergence from `Map#delete`: returns void, NOT a boolean
487
+ * "was present" flag — surfacing that boolean would force a hidden read on
488
+ * every delete. (The underlying native operation is named `remove`.)
489
+ */
490
+ delete(key: string): Promise<void>;
491
+ /** Removes every entry. */
492
+ clear(): Promise<void>;
493
+ /**
494
+ * Async iterator over the live `[key, value]` entries in key order. Valid
495
+ * only within the handler invocation (attempt) that opened it; early exit
496
+ * from a `for await` loop closes the underlying cursor.
497
+ */
498
+ entries(direction?: ScanDirection): AsyncIterableIterator<[string, V]>;
499
+ /**
500
+ * Async iterator over the live keys in key order. Skips the value decode and
501
+ * the resolver, so a message-backed map enumerates keys with zero Kafka
502
+ * fetches; it still reads presence, so it is not zero-I/O. Valid only within
503
+ * the handler invocation (attempt) that opened it; early exit from a
504
+ * `for await` loop closes the underlying cursor.
505
+ */
506
+ keys(direction?: ScanDirection): AsyncIterableIterator<string>;
507
+ /**
508
+ * Async iterator over the live values in key order. Valid only within the
509
+ * handler invocation (attempt) that opened it; early exit from a `for await`
510
+ * loop closes the underlying cursor.
511
+ */
512
+ values(direction?: ScanDirection): AsyncIterableIterator<V>;
513
+ /**
514
+ * Forward iteration over `[key, value]` entries. Valid only within the
515
+ * handler invocation (attempt) that opened it.
516
+ */
517
+ [Symbol.asyncIterator](): AsyncIterableIterator<[string, V]>;
518
+ /**
519
+ * Durably commits the buffered operations mid-handler (at-least-once).
520
+ * Resolves with no value — the erased seam drops the store outcome.
521
+ */
522
+ commit(): Promise<void>;
523
+ /** Discards buffered uncommitted operations back to the committed floor. */
524
+ rollback(): Promise<void>;
525
+ }
526
+
527
+ /**
528
+ * Typed handle over a double-ended-queue keyed-state collection, vended by
529
+ * `Context.state()`. Valid only within the handler invocation (attempt) that
530
+ * vended it. Every method opens its own per-operation trace span.
531
+ */
532
+ export declare class DequeState<T = JsonValue> {
533
+ /** Vended only by {@link Context#state}; not constructible directly. */
534
+ private constructor(native: unknown);
535
+ /**
536
+ * Appends an element at the back. The item type excludes `null`/`undefined`
537
+ * (via {@link !NonNullable}) because a top-level `null` is not a storable
538
+ * element — writing one (or an unrepresentable value) is a caller mistake,
539
+ * rejected at runtime with a {@link TransientStateError} so it retries and
540
+ * stays visible rather than discarding the message. (Nested `null` is
541
+ * permitted.)
542
+ */
543
+ push(item: NonNullable<T>): Promise<void>;
544
+ /**
545
+ * Prepends an element at the front. The item type excludes `null`/`undefined`
546
+ * (via {@link !NonNullable}); see {@link DequeState#push}.
547
+ */
548
+ unshift(item: NonNullable<T>): Promise<void>;
549
+ /** Removes and returns the back element, or null when empty. */
550
+ pop(): Promise<T | null>;
551
+ /** Removes and returns the front element, or null when empty. */
552
+ shift(): Promise<T | null>;
553
+ /** Returns the number of live elements. */
554
+ length(): Promise<number>;
555
+ /** Reports whether the deque holds no live elements. */
556
+ isEmpty(): Promise<boolean>;
557
+ /** Removes every element. */
558
+ clear(): Promise<void>;
559
+ /**
560
+ * Reads the element at `index`, like `Array.prototype.at`: a non-negative
561
+ * `index` counts from the front (`0` is the front), a negative `index` counts
562
+ * back from the end (`-1` is the back). Any out-of-range position — including
563
+ * every index on an empty deque — resolves to null. `index` must be a safe
564
+ * integer; a fractional, `NaN`, or infinite value is a caller mistake,
565
+ * rejected with a {@link TransientStateError} (it retries and stays visible).
566
+ *
567
+ * The endpoints `at(0)` and `at(-1)` ride the front/back peeks — a single
568
+ * read, and `at(-1)` makes no length read. Any other negative `index` is
569
+ * resolved against the current {@link DequeState#length}, so it makes an
570
+ * extra boundary crossing that a non-negative one does not.
571
+ */
572
+ at(index: number): Promise<T | null>;
573
+ /**
574
+ * Async iterator over the live elements in index order. Valid only within
575
+ * the handler invocation (attempt) that opened it; early exit from a
576
+ * `for await` loop closes the underlying cursor.
577
+ */
578
+ values(direction?: ScanDirection): AsyncIterableIterator<T>;
579
+ /**
580
+ * Forward iteration over the elements. Valid only within the handler
581
+ * invocation (attempt) that opened it.
582
+ */
583
+ [Symbol.asyncIterator](): AsyncIterableIterator<T>;
584
+ /**
585
+ * Durably commits the buffered operations mid-handler (at-least-once).
586
+ * Resolves with no value — the erased seam drops the store outcome.
587
+ */
588
+ commit(): Promise<void>;
589
+ /** Discards buffered uncommitted operations back to the committed floor. */
590
+ rollback(): Promise<void>;
77
591
  }
78
592
 
79
593
  /**
@@ -83,31 +597,52 @@ export declare class Context {
83
597
  */
84
598
  export interface Logger {
85
599
  /** Logs error-level messages. */
86
- error: (message: string | undefined | null, metadata?: any) => void;
600
+ error: (
601
+ message: string | undefined | null,
602
+ metadata?: Record<string, unknown>,
603
+ ) => void;
87
604
  /** Logs warning-level messages. */
88
- warn: (message: string | undefined | null, metadata?: any) => void;
605
+ warn: (
606
+ message: string | undefined | null,
607
+ metadata?: Record<string, unknown>,
608
+ ) => void;
89
609
  /** Logs info-level messages. */
90
- info: (message: string | undefined | null, metadata?: any) => void;
610
+ info: (
611
+ message: string | undefined | null,
612
+ metadata?: Record<string, unknown>,
613
+ ) => void;
91
614
  /** Logs debug-level messages. */
92
- debug: (message: string | undefined | null, metadata?: any) => void;
615
+ debug: (
616
+ message: string | undefined | null,
617
+ metadata?: Record<string, unknown>,
618
+ ) => void;
93
619
  /** Logs trace-level messages. */
94
- trace: (message: string | undefined | null, metadata?: any) => void;
620
+ trace: (
621
+ message: string | undefined | null,
622
+ metadata?: Record<string, unknown>,
623
+ ) => void;
95
624
  }
96
625
 
97
- export interface EventHandler {
626
+ export interface EventHandler<P = JsonValue, R = JsonValue> {
627
+ /** Handles an excise record. */
628
+ onExcise: (
629
+ context: Context,
630
+ message: ExciseMessage,
631
+ signal: AbortSignal,
632
+ ) => MaybePromise<R & JsonCompatible<R>>;
98
633
  /**
99
634
  * Callback function to handle incoming messages.
100
635
  *
101
636
  * @param context - The context of the message processing.
102
637
  * @param message - The received Kafka message.
103
638
  * @param signal - An AbortSignal that can be used to cancel the message processing.
104
- * @returns A promise that resolves when the message has been processed.
639
+ * @returns A JSON response for subsystem requests. JSON null is valid.
105
640
  */
106
- onMessage?: (
641
+ onMessage: (
107
642
  context: Context,
108
- message: Message,
643
+ message: Message<P>,
109
644
  signal: AbortSignal,
110
- ) => Promise<void>;
645
+ ) => MaybePromise<R & JsonCompatible<R>>;
111
646
 
112
647
  /**
113
648
  * Callback function to handle timers.
@@ -115,22 +650,56 @@ export interface EventHandler {
115
650
  * @param context - The context of the message processing.
116
651
  * @param timer - The triggered timer.
117
652
  * @param signal - An AbortSignal that can be used to cancel the message processing.
118
- * @returns A promise that resolves when the timer has been processed.
653
+ * @returns No value.
119
654
  */
120
- onTimer?: (
655
+ onTimer: (
121
656
  context: Context,
122
657
  timer: Timer,
123
658
  signal: AbortSignal,
124
- ) => Promise<void>;
659
+ ) => MaybePromise<void>;
660
+ }
661
+
662
+ /** One successful subsystem outcome. */
663
+ export interface Success<T> {
664
+ readonly ok: true;
665
+ readonly value: T;
666
+ }
667
+
668
+ /** One failed subsystem outcome. */
669
+ export interface Failure {
670
+ readonly ok: false;
671
+ readonly error: ResponseError;
672
+ }
673
+
674
+ /** One subsystem outcome. */
675
+ export type Outcome<T> = Success<T> | Failure;
676
+
677
+ /** One subsystem failure. */
678
+ export type ResponseError =
679
+ | { readonly kind: "handler"; readonly message: string }
680
+ | { readonly kind: "timeout"; readonly message: string }
681
+ | { readonly kind: "formatMismatch"; readonly message: string }
682
+ | { readonly kind: "malformedResponse"; readonly message: string };
683
+
684
+ /** Request targets, deadline, and cancellation. */
685
+ export interface RequestOptions {
686
+ /** The subsystems that must respond. */
687
+ readonly subsystems: readonly string[];
688
+ /** The response deadline in milliseconds. */
689
+ readonly timeoutMs: number;
690
+ /** Cancels the local wait. */
691
+ readonly signal?: AbortSignal;
125
692
  }
126
693
 
127
694
  export declare class ProsodyClient {
695
+ private constructor();
696
+
128
697
  /**
129
- * Creates a new ProsodyClient instance.
698
+ * Creates a Prosody client without blocking the Node.js event loop.
130
699
  *
131
700
  * @param config - The configuration options for the client.
132
701
  */
133
- constructor(config: Configuration);
702
+ static create(config: Configuration): Promise<ProsodyClient>;
134
703
 
135
704
  /**
136
705
  * Gets the current state of the consumer.
@@ -156,6 +725,22 @@ export declare class ProsodyClient {
156
725
  */
157
726
  isStalled(): Promise<boolean>;
158
727
 
728
+ /** Opens a read-only view of a published JSON value collection. */
729
+ state<T>(
730
+ subsystem: string,
731
+ definition: ValueDefinition<T>,
732
+ ): Promise<PublishedValue<T>>;
733
+ /** Opens a read-only view of a published JSON map collection. */
734
+ state<V>(
735
+ subsystem: string,
736
+ definition: MapDefinition<V>,
737
+ ): Promise<PublishedMap<V>>;
738
+ /** Opens a read-only view of a published JSON deque collection. */
739
+ state<T>(
740
+ subsystem: string,
741
+ definition: DequeDefinition<T>,
742
+ ): Promise<PublishedDeque<T>>;
743
+
159
744
  /**
160
745
  * Gets the source system identifier configured for the client.
161
746
  *
@@ -173,29 +758,96 @@ export declare class ProsodyClient {
173
758
  * @returns A promise that resolves when the message has been successfully sent.
174
759
  * @throws Error if the send operation fails or is aborted.
175
760
  */
176
- send(
761
+ send<P>(
177
762
  topic: string,
178
763
  key: string,
179
- payload: unknown,
764
+ payload: P & JsonCompatible<P>,
180
765
  signal?: AbortSignal,
181
766
  ): Promise<void>;
182
767
 
768
+ /** Sends an excise record for a key. */
769
+ excise(topic: string, key: string, signal?: AbortSignal): Promise<void>;
770
+
771
+ /**
772
+ * Sends a request and returns one outcome for each subsystem.
773
+ *
774
+ * The map contains every selected subsystem. A missing response has a timeout outcome.
775
+ * @throws Error if the input is invalid, sending fails, shutdown starts, or the signal aborts.
776
+ */
777
+ request<R = JsonValue>(
778
+ topic: string,
779
+ key: string,
780
+ payload: JsonValue,
781
+ options: RequestOptions,
782
+ ): Promise<ReadonlyMap<string, Outcome<R>>>;
783
+
784
+ /** Sends an excise request and returns one outcome for each subsystem. */
785
+ requestExcise<R = JsonValue>(
786
+ topic: string,
787
+ key: string,
788
+ options: RequestOptions,
789
+ ): Promise<ReadonlyMap<string, Outcome<R>>>;
790
+
183
791
  /**
184
792
  * Subscribes to receive messages using the provided event handler.
185
793
  *
186
794
  * @param eventHandler - The event handler to process received messages and timers.
187
795
  * @returns A promise that resolves when the subscription is successfully established and the consumer is ready to receive messages.
796
+ * @throws TypeError if any required handler method is missing.
188
797
  * @throws Error if the subscription fails to establish.
189
798
  */
190
- subscribe(eventHandler: EventHandler): Promise<void>;
799
+ subscribe<P = JsonValue, R = JsonValue>(
800
+ eventHandler: EventHandler<P, R>,
801
+ ): Promise<void>;
191
802
 
192
803
  /**
193
- * Unsubscribes from receiving messages and shuts down the consumer.
804
+ * Stops the consumer. You can subscribe again later.
194
805
  *
195
806
  * @returns A promise that resolves when the unsubscribe operation is complete.
196
807
  * @throws Error if the unsubscribe operation fails.
197
808
  */
198
809
  unsubscribe(): Promise<void>;
810
+
811
+ /**
812
+ * Shuts down the client and all its services.
813
+ * Concurrent and repeated calls await the same shutdown operation.
814
+ *
815
+ * @returns A promise that resolves when shutdown is complete.
816
+ * @throws Error if shutdown fails.
817
+ */
818
+ shutdown(): Promise<void>;
819
+ }
820
+
821
+ /** Per-collection cache override for published reads. */
822
+ export interface ReadCacheOptions {
823
+ /** Cache duration in milliseconds. */
824
+ ttlMs: number;
825
+ }
826
+
827
+ /** Read-only published value collection. */
828
+ export declare class PublishedValue<T = JsonValue> {
829
+ get(key: string): Promise<T | null>;
830
+ }
831
+
832
+ /** Read-only published map collection. */
833
+ export declare class PublishedMap<V = JsonValue> {
834
+ get(key: string, mapKey: string): Promise<V | null>;
835
+ getMany(key: string, mapKeys: string[]): Promise<Array<V | null>>;
836
+ has(key: string, mapKey: string): Promise<boolean>;
837
+ entries(
838
+ key: string,
839
+ direction?: ScanDirection,
840
+ ): AsyncIterableIterator<[string, V]>;
841
+ keys(key: string, direction?: ScanDirection): AsyncIterableIterator<string>;
842
+ values(key: string, direction?: ScanDirection): AsyncIterableIterator<V>;
843
+ }
844
+
845
+ /** Read-only published deque collection. */
846
+ export declare class PublishedDeque<T = JsonValue> {
847
+ length(key: string): Promise<number>;
848
+ isEmpty(key: string): Promise<boolean>;
849
+ at(key: string, index: number): Promise<T | null>;
850
+ values(key: string, direction?: ScanDirection): AsyncIterableIterator<T>;
199
851
  }
200
852
 
201
853
  /**
@@ -277,8 +929,40 @@ export class PermanentError extends EventHandlerError {
277
929
  get isPermanent(): true;
278
930
  }
279
931
 
932
+ /**
933
+ * Represents a transient keyed-state failure that may succeed on a later
934
+ * attempt — a store read/write timeout, AND every caller mistake (a
935
+ * null/unrepresentable write, an item-shape mismatch, an out-of-range index, an
936
+ * invalid scan direction). Caller mistakes are transient on purpose so they
937
+ * retry and stay visible rather than discarding the message. Subclasses
938
+ * {@link TransientError}, so rethrowing it from a handler classifies the event
939
+ * transient through the existing error bridge unchanged.
940
+ */
941
+ export class TransientStateError extends TransientError {}
942
+
943
+ /**
944
+ * Represents a permanent keyed-state failure a retry cannot resolve in-process
945
+ * — an unregistered collection name, a registered-identity mismatch, or a
946
+ * duplicate registration (or one a handler throws explicitly). Caller mistakes
947
+ * are NOT permanent; they are {@link TransientStateError}. Subclasses
948
+ * {@link PermanentError}, so rethrowing it from a handler classifies the event
949
+ * permanent through the existing error bridge unchanged.
950
+ */
951
+ export class PermanentStateError extends PermanentError {}
952
+
953
+ /**
954
+ * Name-branded predicate that narrows to either keyed-state error class,
955
+ * regardless of category.
956
+ *
957
+ * @param error - The value to test.
958
+ * @returns True when the value is a keyed-state error.
959
+ */
960
+ export function isStateError(
961
+ error: unknown,
962
+ ): error is PermanentStateError | TransientStateError;
963
+
280
964
  /** Type alias for a constructor of an Error subclass. */
281
- type ErrorClass<T extends Error> = new (...args: any[]) => T;
965
+ type ErrorClass<T extends Error> = new (...args: never[]) => T;
282
966
 
283
967
  /**
284
968
  * Type for a decorator function that can be applied to both methods and standalone functions.