@theokit/gateway 0.9.0 → 0.11.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/CHANGELOG.md +107 -0
- package/README.md +118 -1
- package/dist/index.cjs +160 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +250 -35
- package/dist/index.d.ts +250 -35
- package/dist/index.js +158 -23
- package/dist/index.js.map +1 -1
- package/package.json +21 -4
package/dist/index.d.ts
CHANGED
|
@@ -483,46 +483,80 @@ declare abstract class BasePlatformAdapter {
|
|
|
483
483
|
}
|
|
484
484
|
|
|
485
485
|
/**
|
|
486
|
-
* `
|
|
486
|
+
* `ChannelDescriptor` — one platform's channel described as data (FR-001, ADR D1 of B-018).
|
|
487
487
|
*
|
|
488
|
-
*
|
|
489
|
-
*
|
|
490
|
-
*
|
|
491
|
-
*
|
|
488
|
+
* A platform package exports one static descriptor: the config fields its channel needs, how to
|
|
489
|
+
* build its adapter from them, and, for a channel that receives webhooks, how to verify and ingest
|
|
490
|
+
* a request. An app then wires every channel with the same loop (`createChannels`) instead of one
|
|
491
|
+
* branch per platform. The core only reads these shapes; it never names a platform.
|
|
492
492
|
*
|
|
493
493
|
* @public
|
|
494
494
|
*/
|
|
495
495
|
|
|
496
|
-
/**
|
|
497
|
-
interface
|
|
498
|
-
|
|
499
|
-
readonly
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
496
|
+
/** One configuration field a channel reads. */
|
|
497
|
+
interface ChannelConfigField {
|
|
498
|
+
/** The key `create` reads from its config object. */
|
|
499
|
+
readonly key: string;
|
|
500
|
+
/** A required field that is absent, `null` or `""` rejects the channel before `create` runs. */
|
|
501
|
+
readonly required: boolean;
|
|
502
|
+
/** The value is a credential: never log it, and keep it out of anything shown to a user. */
|
|
503
|
+
readonly secret: boolean;
|
|
504
|
+
/** What the field is, for a human configuring the channel. */
|
|
505
|
+
readonly description: string;
|
|
504
506
|
}
|
|
505
|
-
/**
|
|
506
|
-
interface
|
|
507
|
-
|
|
508
|
-
readonly
|
|
509
|
-
|
|
507
|
+
/** A webhook request as the app's HTTP layer received it, before anything parsed the body. */
|
|
508
|
+
interface WebhookRequest {
|
|
509
|
+
/** The exact request bytes as text; signatures are computed over them. */
|
|
510
|
+
readonly rawBody: string;
|
|
511
|
+
/** Request headers. Descriptors look a header up without regard to case. */
|
|
512
|
+
readonly headers: Readonly<Record<string, string | undefined>>;
|
|
510
513
|
}
|
|
511
514
|
/**
|
|
512
|
-
*
|
|
515
|
+
* What `ingest` did with a verified payload: `"delivered"` dispatched it, `"malformed"` refused it
|
|
516
|
+
* without dispatching, and `"no_handler"` dispatched nothing because the payload holds a message
|
|
517
|
+
* for the handler and none is subscribed (before the runner starts, after it stops, or for an
|
|
518
|
+
* adapter whose connect failed under `connectFailure: "isolate"`). Answer only `"delivered"` with
|
|
519
|
+
* a success status, so a platform that redelivers can send the rest again.
|
|
520
|
+
*/
|
|
521
|
+
type IngestResult = "delivered" | "malformed" | "no_handler";
|
|
522
|
+
/**
|
|
523
|
+
* The webhook half of a channel: verify a request, then hand its payload to the adapter.
|
|
513
524
|
*
|
|
514
|
-
*
|
|
515
|
-
*
|
|
516
|
-
*
|
|
517
|
-
*
|
|
525
|
+
* `verify` and `ingest` are declared as methods on purpose. Method parameters are bivariant, which
|
|
526
|
+
* is what lets a descriptor typed for its own adapter class sit in a list of
|
|
527
|
+
* `ChannelDescriptor<BasePlatformAdapter>`; written as function-typed properties, that assignment
|
|
528
|
+
* would fail under `strictFunctionTypes`.
|
|
529
|
+
*/
|
|
530
|
+
interface ChannelWebhook<TAdapter extends BasePlatformAdapter> {
|
|
531
|
+
/** `true` when the request carries a valid signature for this adapter's credentials. */
|
|
532
|
+
verify(adapter: TAdapter, request: WebhookRequest): boolean;
|
|
533
|
+
/** Dispatch a parsed, verified payload, or report it malformed without dispatching. */
|
|
534
|
+
ingest(adapter: TAdapter, payload: unknown): Promise<IngestResult>;
|
|
535
|
+
}
|
|
536
|
+
interface ChannelDescriptorBase<TAdapter extends BasePlatformAdapter> {
|
|
537
|
+
/** The platform the built adapter reports as its `platform`. */
|
|
538
|
+
readonly platform: PlatformName;
|
|
539
|
+
/** Every field `create` reads. */
|
|
540
|
+
readonly config: ReadonlyArray<ChannelConfigField>;
|
|
541
|
+
/**
|
|
542
|
+
* Build the adapter. Throws a `GatewayConfigurationError` (or a subclass) for a value it refuses,
|
|
543
|
+
* which `createChannels` reports as a rejected channel; it performs no network call.
|
|
544
|
+
*/
|
|
545
|
+
create(config: Readonly<Record<string, unknown>>): TAdapter;
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* A channel described as data. A `socket` channel opens its own connection to the platform; a
|
|
549
|
+
* `webhook` channel receives requests the app routes to `webhook.verify` and `webhook.ingest`.
|
|
518
550
|
*
|
|
519
551
|
* @public
|
|
520
552
|
*/
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
553
|
+
type ChannelDescriptor<TAdapter extends BasePlatformAdapter = BasePlatformAdapter> = (ChannelDescriptorBase<TAdapter> & {
|
|
554
|
+
readonly transport: "socket";
|
|
555
|
+
readonly webhook?: never;
|
|
556
|
+
}) | (ChannelDescriptorBase<TAdapter> & {
|
|
557
|
+
readonly transport: "webhook";
|
|
558
|
+
readonly webhook: ChannelWebhook<TAdapter>;
|
|
559
|
+
});
|
|
526
560
|
|
|
527
561
|
/**
|
|
528
562
|
* `GatewayConfigurationError` — shared base for per-adapter configuration
|
|
@@ -558,6 +592,87 @@ declare class GatewayConfigurationError extends Error {
|
|
|
558
592
|
constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
|
|
559
593
|
}
|
|
560
594
|
|
|
595
|
+
/**
|
|
596
|
+
* `createChannels` — build every configured channel from its descriptor (FR-002 of B-018).
|
|
597
|
+
*
|
|
598
|
+
* One loop replaces the per-platform constructor calls an app used to write. A channel whose
|
|
599
|
+
* configuration is refused lands in `rejected` and the others are still built, so one bad entry
|
|
600
|
+
* never stops the healthy ones. Nothing here connects or performs I/O (NFR-001): connecting is the
|
|
601
|
+
* runner's job, after the app has seen what was rejected.
|
|
602
|
+
*
|
|
603
|
+
* @public
|
|
604
|
+
*/
|
|
605
|
+
|
|
606
|
+
/** One channel to build: its descriptor and the configuration the app supplies for it. */
|
|
607
|
+
interface ChannelEntry {
|
|
608
|
+
readonly descriptor: ChannelDescriptor<BasePlatformAdapter>;
|
|
609
|
+
/** Values keyed by the descriptor's field keys. Absent means every required field is missing. */
|
|
610
|
+
readonly config?: Readonly<Record<string, unknown>>;
|
|
611
|
+
}
|
|
612
|
+
/** A channel that was not built, and the configuration error that says why. */
|
|
613
|
+
interface ChannelRejection {
|
|
614
|
+
readonly platform: PlatformName;
|
|
615
|
+
readonly error: GatewayConfigurationError;
|
|
616
|
+
}
|
|
617
|
+
/** What `createChannels` built and what it refused. */
|
|
618
|
+
interface CreateChannelsResult {
|
|
619
|
+
readonly adapters: BasePlatformAdapter[];
|
|
620
|
+
readonly rejected: ChannelRejection[];
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Build an adapter for each entry whose required fields are present.
|
|
624
|
+
*
|
|
625
|
+
* An entry missing a required field (absent, `null` or `""`; `0` and `false` count as present) is
|
|
626
|
+
* rejected with a `GatewayConfigurationError` coded `missing_required_config` that names every
|
|
627
|
+
* missing key, and its `create` is never called. A `GatewayConfigurationError` thrown by `create`
|
|
628
|
+
* is reported the same way. Any other throw is a defect, not a configuration fault, and propagates.
|
|
629
|
+
*
|
|
630
|
+
* @public
|
|
631
|
+
*/
|
|
632
|
+
declare function createChannels(entries: ReadonlyArray<ChannelEntry>): CreateChannelsResult;
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* `DeliveryRouter` — outbound dispatch by platform (T3.1, ADR D175).
|
|
636
|
+
*
|
|
637
|
+
* The router holds a map of `platform → adapter` and forwards
|
|
638
|
+
* `DeliveryRequest` to the right adapter's `sendMessage`. Composes
|
|
639
|
+
* with `Cron` from `@theokit/sdk` for scheduled delivery — the
|
|
640
|
+
* router is the "WHERE to send", Cron is the "WHEN to fire".
|
|
641
|
+
*
|
|
642
|
+
* @public
|
|
643
|
+
*/
|
|
644
|
+
|
|
645
|
+
/** Target for an outbound delivery. */
|
|
646
|
+
interface DeliveryTarget {
|
|
647
|
+
readonly platform: PlatformName;
|
|
648
|
+
readonly channel: {
|
|
649
|
+
readonly id: string;
|
|
650
|
+
readonly type: "dm" | "group" | "thread";
|
|
651
|
+
readonly topicId?: string;
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
/** Full outbound request: target + content. */
|
|
655
|
+
interface DeliveryRequest extends DeliveryTarget {
|
|
656
|
+
readonly text: string;
|
|
657
|
+
readonly format?: "plain" | "markdown" | "html";
|
|
658
|
+
readonly replyTo?: string;
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* Routes outbound requests to the correct adapter.
|
|
662
|
+
*
|
|
663
|
+
* **Contract:**
|
|
664
|
+
* - `register` is last-writer-wins by platform.
|
|
665
|
+
* - `send` with unknown platform returns `{ ok: false, code: "no_adapter" }`.
|
|
666
|
+
* - `send` never throws on platform errors (delegates to adapter's SendResult).
|
|
667
|
+
*
|
|
668
|
+
* @public
|
|
669
|
+
*/
|
|
670
|
+
declare class DeliveryRouter {
|
|
671
|
+
private readonly adapters;
|
|
672
|
+
register(adapter: BasePlatformAdapter): void;
|
|
673
|
+
send(req: DeliveryRequest): Promise<SendResult>;
|
|
674
|
+
}
|
|
675
|
+
|
|
561
676
|
/**
|
|
562
677
|
* `GatewayLifecycleError` — a lifecycle method was called from a state that
|
|
563
678
|
* cannot honour it.
|
|
@@ -676,9 +791,11 @@ declare class HookExecutor {
|
|
|
676
791
|
* adapter matching `event.platform` (EC-G).
|
|
677
792
|
*
|
|
678
793
|
* **Lifecycle:**
|
|
679
|
-
* - `start()` connects all adapters in parallel
|
|
680
|
-
*
|
|
681
|
-
*
|
|
794
|
+
* - `start()` connects all adapters in parallel and resolves a `StartResult`.
|
|
795
|
+
* By default (`connectFailure: "rollback"`) partial failure rolls back:
|
|
796
|
+
* connected adapters get `disconnect()`, then the error rethrows. Under
|
|
797
|
+
* `connectFailure: "isolate"` the adapters that connected keep running and
|
|
798
|
+
* the rest are reported in `StartResult.failed`.
|
|
682
799
|
* - `stop()` drains in-flight handlers up to `drainTimeoutMs` (default 10s)
|
|
683
800
|
* BEFORE disconnecting (EC-E). Idempotent, and terminal: a stopped runner
|
|
684
801
|
* cannot be restarted, and `start()` on one throws `GatewayLifecycleError`.
|
|
@@ -724,6 +841,36 @@ interface GatewayRunnerOptions {
|
|
|
724
841
|
* @public
|
|
725
842
|
*/
|
|
726
843
|
readonly commandPrefixes?: ReadonlyArray<string>;
|
|
844
|
+
/**
|
|
845
|
+
* What `start()` does when an adapter fails to connect. `"rollback"` (the default) disconnects
|
|
846
|
+
* the adapters that did connect and rethrows: all or nothing. `"isolate"` keeps the adapters that
|
|
847
|
+
* connected, wires inbound only for them, and reports the others in the resolved
|
|
848
|
+
* `StartResult.failed`, so one channel that cannot connect does not stop the healthy ones.
|
|
849
|
+
*
|
|
850
|
+
* @public
|
|
851
|
+
*/
|
|
852
|
+
readonly connectFailure?: ConnectFailure;
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* How `GatewayRunner.start()` treats an adapter that fails to connect: `"rollback"` (all or
|
|
856
|
+
* nothing, the default) or `"isolate"` (keep the ones that connected).
|
|
857
|
+
*
|
|
858
|
+
* @public
|
|
859
|
+
*/
|
|
860
|
+
type ConnectFailure = "rollback" | "isolate";
|
|
861
|
+
/**
|
|
862
|
+
* What `GatewayRunner.start()` connected. Under `"rollback"` `failed` is always empty, because a
|
|
863
|
+
* failure rejects instead; under `"isolate"` it names each adapter that did not connect and why,
|
|
864
|
+
* with any credential in the reason redacted.
|
|
865
|
+
*
|
|
866
|
+
* @public
|
|
867
|
+
*/
|
|
868
|
+
interface StartResult {
|
|
869
|
+
readonly connected: ReadonlyArray<PlatformName>;
|
|
870
|
+
readonly failed: ReadonlyArray<{
|
|
871
|
+
readonly platform: PlatformName;
|
|
872
|
+
readonly reason: string;
|
|
873
|
+
}>;
|
|
727
874
|
}
|
|
728
875
|
/**
|
|
729
876
|
* Holds the registered adapters and dispatches inbound events through
|
|
@@ -740,7 +887,7 @@ declare class GatewayRunner {
|
|
|
740
887
|
private readonly unsubs;
|
|
741
888
|
/** Slash command registry: name → handler (word-boundary match, EC-A). */
|
|
742
889
|
private readonly commands;
|
|
743
|
-
private
|
|
890
|
+
private startResult;
|
|
744
891
|
private stopped;
|
|
745
892
|
constructor(opts: GatewayRunnerOptions);
|
|
746
893
|
/**
|
|
@@ -751,12 +898,26 @@ declare class GatewayRunner {
|
|
|
751
898
|
*/
|
|
752
899
|
command(name: string, handler: GatewayHandler): void;
|
|
753
900
|
/**
|
|
754
|
-
* Connect
|
|
901
|
+
* Connect the adapters and wire inbound dispatch for the ones that connected.
|
|
902
|
+
*
|
|
903
|
+
* Resolves with what connected. A second call after the first resolved returns the same result
|
|
904
|
+
* without connecting again.
|
|
755
905
|
*
|
|
756
906
|
* @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
|
|
757
907
|
* stopped. A stopped runner is spent; construct a new one.
|
|
908
|
+
* @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after the
|
|
909
|
+
* adapters that did connect were disconnected.
|
|
758
910
|
*/
|
|
759
|
-
start(): Promise<
|
|
911
|
+
start(): Promise<StartResult>;
|
|
912
|
+
/** All or nothing: one failure disconnects the adapters already open, then rethrows. */
|
|
913
|
+
private connectAllOrRollback;
|
|
914
|
+
/**
|
|
915
|
+
* Connect every adapter and keep the ones that connected. The `async` wrapper turns a
|
|
916
|
+
* synchronous throw inside `connect()` into a rejection `allSettled` sees; a bare
|
|
917
|
+
* `a => a.connect()` would let it escape `map` and reject `start()` itself.
|
|
918
|
+
*/
|
|
919
|
+
private connectIsolated;
|
|
920
|
+
private wireInbound;
|
|
760
921
|
/**
|
|
761
922
|
* Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
|
|
762
923
|
* then disconnects adapters. Idempotent (EC-E).
|
|
@@ -858,6 +1019,50 @@ declare class SessionRouter {
|
|
|
858
1019
|
resolveAgentId(event: MessageEvent): string;
|
|
859
1020
|
}
|
|
860
1021
|
|
|
1022
|
+
/**
|
|
1023
|
+
* What `ChatPresenter` needs to know about one platform: how to rewrite the text, and which
|
|
1024
|
+
* `format` to declare on the message (B-019 FR-001, FR-002).
|
|
1025
|
+
*
|
|
1026
|
+
* `toDialect` alone is not enough, and composing it with the presenter's defaults proved it:
|
|
1027
|
+
* `ChatPresenter` declares `markdown` unless told otherwise, and `toDialect` passes a platform it
|
|
1028
|
+
* was not taught through unchanged. So matrix and email put `**bold**` on the wire as characters
|
|
1029
|
+
* (matrix drops `markdown` with a warning, email escapes it into `<pre>`), and telegram and slack
|
|
1030
|
+
* were handed a bold spelled for a dialect whose bold is a single asterisk. The text rewrite and
|
|
1031
|
+
* the format flag have to be chosen together, per platform, by the package that knows what each
|
|
1032
|
+
* adapter does with `format` — this one.
|
|
1033
|
+
*
|
|
1034
|
+
* Pure data and pure functions: no I/O, and the same input always gives the same output.
|
|
1035
|
+
* `@theokit/gateway` still does not depend on `@theokit/presenter`; `ChannelRendering` matches
|
|
1036
|
+
* the presenter's `translate` and `format` options structurally.
|
|
1037
|
+
*/
|
|
1038
|
+
|
|
1039
|
+
/**
|
|
1040
|
+
* The pair a consumer spreads into `ChatPresenter`'s options for one platform.
|
|
1041
|
+
*
|
|
1042
|
+
* @public
|
|
1043
|
+
*/
|
|
1044
|
+
interface ChannelRendering {
|
|
1045
|
+
/** The rendering hint the adapter receives as `OutboundMessage.format`. */
|
|
1046
|
+
readonly format: "plain" | "markdown";
|
|
1047
|
+
/** Rewrites the assembled answer for the platform. Pure and deterministic. */
|
|
1048
|
+
readonly translate: (text: string) => string;
|
|
1049
|
+
}
|
|
1050
|
+
/**
|
|
1051
|
+
* The rendering `ChatPresenter` needs for `platform`.
|
|
1052
|
+
*
|
|
1053
|
+
* Only the four inline markers `toDialect` knows are rewritten: bold, italic, strikethrough and
|
|
1054
|
+
* inline code. Headings, links, lists and block quotes pass through on every platform, and fenced
|
|
1055
|
+
* code is not handled yet (the inline-code rule rewrites a fence's backticks).
|
|
1056
|
+
*
|
|
1057
|
+
* @param platform - the destination, typically `event.platform` of the inbound message
|
|
1058
|
+
* @returns the `{ translate, format }` pair for that platform
|
|
1059
|
+
* @throws RangeError when `platform` is not one of the ten this package knows. Answering with
|
|
1060
|
+
* nothing would let the presenter fall back to identity and `markdown`, which is the defect this
|
|
1061
|
+
* function exists to remove.
|
|
1062
|
+
* @public
|
|
1063
|
+
*/
|
|
1064
|
+
declare function channelRendering(platform: PlatformName): ChannelRendering;
|
|
1065
|
+
|
|
861
1066
|
/**
|
|
862
1067
|
* `chunkText` — transport-agnostic, boundary-preferring text chunker.
|
|
863
1068
|
*
|
|
@@ -947,6 +1152,16 @@ interface ChunkByGraphemeOptions {
|
|
|
947
1152
|
*/
|
|
948
1153
|
declare function chunkByGrapheme(text: string, options: ChunkByGraphemeOptions): string[];
|
|
949
1154
|
|
|
1155
|
+
/**
|
|
1156
|
+
* Rewrite `text` for `platform`.
|
|
1157
|
+
*
|
|
1158
|
+
* @param text - the assembled answer, in markdown as the model produced it
|
|
1159
|
+
* @param platform - the destination; one this function has not been taught passes through
|
|
1160
|
+
* @returns the text in the platform's dialect, or unchanged when none is known
|
|
1161
|
+
* @public
|
|
1162
|
+
*/
|
|
1163
|
+
declare function toDialect(text: string, platform: string): string;
|
|
1164
|
+
|
|
950
1165
|
/**
|
|
951
1166
|
* The half of an Express webhook server that is the same for every platform.
|
|
952
1167
|
*
|
|
@@ -1026,4 +1241,4 @@ declare function listenerLifecycle(opts: {
|
|
|
1026
1241
|
stop(): Promise<void>;
|
|
1027
1242
|
};
|
|
1028
1243
|
|
|
1029
|
-
export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, CREDENTIAL_SHAPES, type ChunkByGraphemeOptions, type ChunkTextOptions, type CoveredShape, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type RawBodyRequest, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type UncoveredShape, type WhatsAppMessageEvent, chunkByGrapheme, chunkText, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets };
|
|
1244
|
+
export { type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChunkByGraphemeOptions, type ChunkTextOptions, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type EmailMessageEvent, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type HookDecision, HookExecutor, type HookName, type IngestResult, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MessageEvent, type OnErrorContext, type OutboundMessage, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type RawBodyRequest, type SMSMessageEvent, type SendResult, SessionRouter, type SlackMessageEvent, type StartResult, type TeamsMessageEvent, type TelegramMessageEvent, type UncoveredShape, type WebhookRequest, type WhatsAppMessageEvent, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets, toDialect };
|
package/dist/index.js
CHANGED
|
@@ -34,6 +34,56 @@ var BasePlatformAdapter = class {
|
|
|
34
34
|
}
|
|
35
35
|
};
|
|
36
36
|
|
|
37
|
+
// src/errors/config-error.ts
|
|
38
|
+
var GatewayConfigurationError = class extends Error {
|
|
39
|
+
name = "GatewayConfigurationError";
|
|
40
|
+
code;
|
|
41
|
+
detail;
|
|
42
|
+
/**
|
|
43
|
+
* @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
|
|
44
|
+
* @param opts `code` (required), optional explicit `message`, optional `detail`.
|
|
45
|
+
*/
|
|
46
|
+
constructor(prefix, opts) {
|
|
47
|
+
super(opts.message ?? `${prefix}: ${opts.code}`);
|
|
48
|
+
this.code = opts.code;
|
|
49
|
+
this.detail = opts.detail;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// src/channel/create-channels.ts
|
|
54
|
+
function isAbsent(value) {
|
|
55
|
+
return value === void 0 || value === null || value === "";
|
|
56
|
+
}
|
|
57
|
+
function missingRequiredKeys(entry, values) {
|
|
58
|
+
return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map((field) => field.key);
|
|
59
|
+
}
|
|
60
|
+
function createChannels(entries) {
|
|
61
|
+
const adapters = [];
|
|
62
|
+
const rejected = [];
|
|
63
|
+
for (const entry of entries) {
|
|
64
|
+
const values = entry.config ?? {};
|
|
65
|
+
const platform = entry.descriptor.platform;
|
|
66
|
+
const missing = missingRequiredKeys(entry, values);
|
|
67
|
+
if (missing.length > 0) {
|
|
68
|
+
rejected.push({
|
|
69
|
+
platform,
|
|
70
|
+
error: new GatewayConfigurationError("gateway", {
|
|
71
|
+
code: "missing_required_config",
|
|
72
|
+
message: `channel ${platform}: missing required config ${missing.join(", ")}`
|
|
73
|
+
})
|
|
74
|
+
});
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
adapters.push(entry.descriptor.create(values));
|
|
79
|
+
} catch (err) {
|
|
80
|
+
if (!(err instanceof GatewayConfigurationError)) throw err;
|
|
81
|
+
rejected.push({ platform, error: err });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return { adapters, rejected };
|
|
85
|
+
}
|
|
86
|
+
|
|
37
87
|
// src/delivery/router.ts
|
|
38
88
|
var DeliveryRouter = class {
|
|
39
89
|
adapters = /* @__PURE__ */ new Map();
|
|
@@ -57,22 +107,6 @@ var DeliveryRouter = class {
|
|
|
57
107
|
}
|
|
58
108
|
};
|
|
59
109
|
|
|
60
|
-
// src/errors/config-error.ts
|
|
61
|
-
var GatewayConfigurationError = class extends Error {
|
|
62
|
-
name = "GatewayConfigurationError";
|
|
63
|
-
code;
|
|
64
|
-
detail;
|
|
65
|
-
/**
|
|
66
|
-
* @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
|
|
67
|
-
* @param opts `code` (required), optional explicit `message`, optional `detail`.
|
|
68
|
-
*/
|
|
69
|
-
constructor(prefix, opts) {
|
|
70
|
-
super(opts.message ?? `${prefix}: ${opts.code}`);
|
|
71
|
-
this.code = opts.code;
|
|
72
|
-
this.detail = opts.detail;
|
|
73
|
-
}
|
|
74
|
-
};
|
|
75
|
-
|
|
76
110
|
// src/errors/lifecycle-error.ts
|
|
77
111
|
var GatewayLifecycleError = class extends Error {
|
|
78
112
|
name = "GatewayLifecycleError";
|
|
@@ -252,6 +286,11 @@ var HookExecutor = class {
|
|
|
252
286
|
// src/runner/gateway-runner.ts
|
|
253
287
|
var DEFAULT_DRAIN_MS = 1e4;
|
|
254
288
|
var DEFAULT_COMMAND_PREFIXES = ["/"];
|
|
289
|
+
function connectFailureReason(outcome) {
|
|
290
|
+
if (outcome.status === "fulfilled") return "connect returned false";
|
|
291
|
+
const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
|
|
292
|
+
return redactSecrets(message);
|
|
293
|
+
}
|
|
255
294
|
var GatewayRunner = class {
|
|
256
295
|
constructor(opts) {
|
|
257
296
|
this.opts = opts;
|
|
@@ -265,7 +304,7 @@ var GatewayRunner = class {
|
|
|
265
304
|
unsubs = [];
|
|
266
305
|
/** Slash command registry: name → handler (word-boundary match, EC-A). */
|
|
267
306
|
commands = /* @__PURE__ */ new Map();
|
|
268
|
-
|
|
307
|
+
startResult;
|
|
269
308
|
stopped = false;
|
|
270
309
|
/**
|
|
271
310
|
* Register a slash command. Match rule (EC-A): text === "/" + name
|
|
@@ -277,10 +316,15 @@ var GatewayRunner = class {
|
|
|
277
316
|
this.commands.set(name, handler);
|
|
278
317
|
}
|
|
279
318
|
/**
|
|
280
|
-
* Connect
|
|
319
|
+
* Connect the adapters and wire inbound dispatch for the ones that connected.
|
|
320
|
+
*
|
|
321
|
+
* Resolves with what connected. A second call after the first resolved returns the same result
|
|
322
|
+
* without connecting again.
|
|
281
323
|
*
|
|
282
324
|
* @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
|
|
283
325
|
* stopped. A stopped runner is spent; construct a new one.
|
|
326
|
+
* @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after the
|
|
327
|
+
* adapters that did connect were disconnected.
|
|
284
328
|
*/
|
|
285
329
|
async start() {
|
|
286
330
|
if (this.stopped) {
|
|
@@ -289,7 +333,17 @@ var GatewayRunner = class {
|
|
|
289
333
|
message: "GatewayRunner.start(): this runner has already been stopped and cannot be restarted. Construct a new GatewayRunner instead."
|
|
290
334
|
});
|
|
291
335
|
}
|
|
292
|
-
if (this.
|
|
336
|
+
if (this.startResult !== void 0) return this.startResult;
|
|
337
|
+
const result = (this.opts.connectFailure ?? "rollback") === "isolate" ? await this.connectIsolated() : await this.connectAllOrRollback();
|
|
338
|
+
this.wireInbound(result.connected);
|
|
339
|
+
this.startResult = {
|
|
340
|
+
connected: result.connected.map((a) => a.platform),
|
|
341
|
+
failed: result.failed
|
|
342
|
+
};
|
|
343
|
+
return this.startResult;
|
|
344
|
+
}
|
|
345
|
+
/** All or nothing: one failure disconnects the adapters already open, then rethrows. */
|
|
346
|
+
async connectAllOrRollback() {
|
|
293
347
|
const connected = [];
|
|
294
348
|
try {
|
|
295
349
|
await Promise.all(
|
|
@@ -303,7 +357,27 @@ var GatewayRunner = class {
|
|
|
303
357
|
await Promise.all(connected.map((a) => a.disconnect().catch(() => void 0)));
|
|
304
358
|
throw err;
|
|
305
359
|
}
|
|
306
|
-
|
|
360
|
+
return { connected: [...this.opts.adapters], failed: [] };
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Connect every adapter and keep the ones that connected. The `async` wrapper turns a
|
|
364
|
+
* synchronous throw inside `connect()` into a rejection `allSettled` sees; a bare
|
|
365
|
+
* `a => a.connect()` would let it escape `map` and reject `start()` itself.
|
|
366
|
+
*/
|
|
367
|
+
async connectIsolated() {
|
|
368
|
+
const adapters = this.opts.adapters;
|
|
369
|
+
const settled = await Promise.allSettled(adapters.map(async (a) => a.connect()));
|
|
370
|
+
const connected = [];
|
|
371
|
+
const failed = [];
|
|
372
|
+
settled.forEach((outcome, i) => {
|
|
373
|
+
const adapter = adapters[i];
|
|
374
|
+
if (outcome.status === "fulfilled" && outcome.value) connected.push(adapter);
|
|
375
|
+
else failed.push({ platform: adapter.platform, reason: connectFailureReason(outcome) });
|
|
376
|
+
});
|
|
377
|
+
return { connected, failed };
|
|
378
|
+
}
|
|
379
|
+
wireInbound(adapters) {
|
|
380
|
+
for (const a of adapters) {
|
|
307
381
|
const unsub = a.onInbound(async (event) => {
|
|
308
382
|
const p = this.dispatch(event);
|
|
309
383
|
this.inflight.add(p);
|
|
@@ -311,7 +385,6 @@ var GatewayRunner = class {
|
|
|
311
385
|
});
|
|
312
386
|
this.unsubs.push(unsub);
|
|
313
387
|
}
|
|
314
|
-
this.connected = true;
|
|
315
388
|
}
|
|
316
389
|
/**
|
|
317
390
|
* Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
|
|
@@ -344,7 +417,6 @@ var GatewayRunner = class {
|
|
|
344
417
|
await Promise.all(
|
|
345
418
|
[...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => void 0))
|
|
346
419
|
);
|
|
347
|
-
this.connected = false;
|
|
348
420
|
}
|
|
349
421
|
/**
|
|
350
422
|
* @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
|
|
@@ -469,6 +541,69 @@ var SessionRouter = class {
|
|
|
469
541
|
}
|
|
470
542
|
};
|
|
471
543
|
|
|
544
|
+
// src/text/dialect.ts
|
|
545
|
+
var DIALECTS = {
|
|
546
|
+
// WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
|
|
547
|
+
whatsapp: { bold: "*", italic: "_", strike: "~", code: "```" },
|
|
548
|
+
// LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.
|
|
549
|
+
line: {},
|
|
550
|
+
// SMS is plain text by definition of the medium.
|
|
551
|
+
sms: {}
|
|
552
|
+
};
|
|
553
|
+
var PATTERN = /\*\*(?<bold>.+?)\*\*|~~(?<strike>.+?)~~|(?<![*\w])\*(?!\s)(?<italicStar>.+?)(?<!\s)\*(?!\*)|(?<![_\w])_(?!\s)(?<italicUnderscore>.+?)(?<!\s)_(?!\w)|`(?<code>.+?)`/gu;
|
|
554
|
+
var GROUP_MARKERS = [
|
|
555
|
+
["bold", "bold"],
|
|
556
|
+
["strike", "strike"],
|
|
557
|
+
["italicStar", "italic"],
|
|
558
|
+
["italicUnderscore", "italic"],
|
|
559
|
+
["code", "code"]
|
|
560
|
+
];
|
|
561
|
+
function toDialect(text, platform) {
|
|
562
|
+
const dialect = DIALECTS[platform];
|
|
563
|
+
if (dialect === void 0) return text;
|
|
564
|
+
return rewriteMarkers(text, dialect);
|
|
565
|
+
}
|
|
566
|
+
function rewriteMarkers(text, dialect) {
|
|
567
|
+
return text.replace(PATTERN, (matched, ...args) => {
|
|
568
|
+
const groups = args.at(-1);
|
|
569
|
+
if (groups === void 0) return matched;
|
|
570
|
+
for (const [group, marker] of GROUP_MARKERS) {
|
|
571
|
+
const content = groups[group];
|
|
572
|
+
if (content === void 0) continue;
|
|
573
|
+
const wrap = dialect[marker];
|
|
574
|
+
return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
|
|
575
|
+
}
|
|
576
|
+
return matched;
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// src/text/channel-rendering.ts
|
|
581
|
+
var SLACK = { bold: "*", italic: "_", strike: "~", code: "`" };
|
|
582
|
+
var STRIP = {};
|
|
583
|
+
var identity = (text) => text;
|
|
584
|
+
var translateWith = (dialect) => (text) => rewriteMarkers(text, dialect);
|
|
585
|
+
var RENDERINGS = {
|
|
586
|
+
whatsapp: { format: "plain", translate: translateWith(DIALECTS.whatsapp) },
|
|
587
|
+
slack: { format: "markdown", translate: translateWith(SLACK) },
|
|
588
|
+
discord: { format: "markdown", translate: identity },
|
|
589
|
+
mattermost: { format: "markdown", translate: identity },
|
|
590
|
+
teams: { format: "markdown", translate: identity },
|
|
591
|
+
line: { format: "plain", translate: translateWith(DIALECTS.line) },
|
|
592
|
+
sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
|
|
593
|
+
telegram: { format: "plain", translate: translateWith(STRIP) },
|
|
594
|
+
matrix: { format: "plain", translate: translateWith(STRIP) },
|
|
595
|
+
email: { format: "plain", translate: translateWith(STRIP) }
|
|
596
|
+
};
|
|
597
|
+
function channelRendering(platform) {
|
|
598
|
+
const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
|
|
599
|
+
if (rendering === void 0) {
|
|
600
|
+
throw new RangeError(
|
|
601
|
+
`channelRendering: unknown platform "${String(platform)}"; expected one of ${Object.keys(RENDERINGS).join(", ")}`
|
|
602
|
+
);
|
|
603
|
+
}
|
|
604
|
+
return rendering;
|
|
605
|
+
}
|
|
606
|
+
|
|
472
607
|
// src/text/chunk.ts
|
|
473
608
|
function searchBoundary(remaining, window, boundaries) {
|
|
474
609
|
let cut = window;
|
|
@@ -608,6 +743,6 @@ function listenerLifecycle(opts) {
|
|
|
608
743
|
};
|
|
609
744
|
}
|
|
610
745
|
|
|
611
|
-
export { BasePlatformAdapter, CREDENTIAL_SHAPES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SessionRouter, chunkByGrapheme, chunkText, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets };
|
|
746
|
+
export { BasePlatformAdapter, CREDENTIAL_SHAPES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SessionRouter, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets, toDialect };
|
|
612
747
|
//# sourceMappingURL=index.js.map
|
|
613
748
|
//# sourceMappingURL=index.js.map
|