@theokit/gateway 0.21.0 → 0.22.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.cts CHANGED
@@ -1101,6 +1101,83 @@ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
1101
1101
  */
1102
1102
  declare function parseFlatXml(xml: string): Record<string, string>;
1103
1103
 
1104
+ /**
1105
+ * `GatewayConfigurationError` — shared base for per-adapter configuration
1106
+ * errors (roadmap M0/M2).
1107
+ *
1108
+ * Every platform adapter previously defined an identical
1109
+ * `ConfigurationError extends Error` (same `code`/`detail` fields, same
1110
+ * options interface, same `` `${pkg}: ${code}` `` default message) — only the
1111
+ * package prefix differed. This base single-sources that contract. Adapters
1112
+ * extend it, pin their prefix, and keep `name = "ConfigurationError"` plus
1113
+ * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).
1114
+ *
1115
+ * @public
1116
+ */
1117
+ /** Public input shape for the {@link GatewayConfigurationError} constructor. */
1118
+ interface GatewayConfigurationErrorOptions {
1119
+ readonly code: string;
1120
+ readonly message?: string;
1121
+ readonly detail?: string;
1122
+ }
1123
+ /**
1124
+ * Base configuration error. Not thrown directly by adapters — they subclass it
1125
+ * with a fixed package prefix.
1126
+ */
1127
+ declare class GatewayConfigurationError extends Error {
1128
+ readonly name: string;
1129
+ readonly code: string;
1130
+ readonly detail: string | undefined;
1131
+ /**
1132
+ * @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
1133
+ * @param opts `code` (required), optional explicit `message`, optional `detail`.
1134
+ */
1135
+ constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
1136
+ }
1137
+
1138
+ /**
1139
+ * `channelConfigReaders` — the config readers every channel's `create` needs, written once.
1140
+ *
1141
+ * Each channel package used to carry its own copy of `invalid`, `readString`, `requiredString`
1142
+ * and friends; only the error prefix differed. The readers throw a configuration error coded
1143
+ * `invalid_config` with the message `${prefix}: config.${key} must be ${expected}`.
1144
+ *
1145
+ * @public
1146
+ */
1147
+
1148
+ /** A channel's config object, as `create` receives it. */
1149
+ type ChannelConfigInput = Readonly<Record<string, unknown>>;
1150
+ /** The readers bound to one package prefix. */
1151
+ interface ChannelConfigReaders {
1152
+ /** Builds (does not throw) the `invalid_config` error for `key`. */
1153
+ invalid(key: string, expected: string): GatewayConfigurationError;
1154
+ /** `undefined`, `null` and `""` are absent. */
1155
+ isAbsent(value: unknown): boolean;
1156
+ /** An optional string; absent gives `undefined`, a non-string throws. */
1157
+ readString(config: ChannelConfigInput, key: string): string | undefined;
1158
+ /** A required string; absent, empty or a non-string throws. */
1159
+ requiredString(config: ChannelConfigInput, key: string): string;
1160
+ /** An optional boolean; absent gives `undefined`, a non-boolean throws. */
1161
+ readBoolean(config: ChannelConfigInput, key: string): boolean | undefined;
1162
+ /**
1163
+ * An optional function; absent gives `undefined`, a non-function throws. Only callability is
1164
+ * checked: the caller names the signature `T` and is responsible for it.
1165
+ */
1166
+ readFunction<T extends (...args: never[]) => unknown>(config: ChannelConfigInput, key: string): T | undefined;
1167
+ }
1168
+ /**
1169
+ * Returns the config readers for a package.
1170
+ *
1171
+ * @param prefix Package prefix in every message, e.g. `"gateway-line"`.
1172
+ * @param createError Builds the error to throw; defaults to `GatewayConfigurationError`. Pass a
1173
+ * package's own subclass to keep its `instanceof` contract.
1174
+ */
1175
+ declare function channelConfigReaders(prefix: string, createError?: (options: {
1176
+ readonly code: string;
1177
+ readonly message: string;
1178
+ readonly detail: string;
1179
+ }) => GatewayConfigurationError): ChannelConfigReaders;
1180
+
1104
1181
  /**
1105
1182
  * `ChannelDescriptor` — one platform's channel described as data (FR-001, ADR D1 of B-018).
1106
1183
  *
@@ -1240,11 +1317,12 @@ interface EnvConfig {
1240
1317
  /** Values of present fields marked secret, for a log mask. Never logged. */
1241
1318
  readonly secrets: readonly string[];
1242
1319
  }
1320
+ type Env = Readonly<Record<string, string | undefined>>;
1243
1321
  /**
1244
1322
  * Read a descriptor's fields from `env`, using `prefix + field.env` as the variable name. Fields
1245
1323
  * without `env` are skipped.
1246
1324
  */
1247
- declare function configFromEnv(descriptor: ChannelDescriptor, env: Readonly<Record<string, string | undefined>>, prefix?: string): EnvConfig;
1325
+ declare function configFromEnv(descriptor: ChannelDescriptor, env: Env, prefix?: string): EnvConfig;
1248
1326
  /**
1249
1327
  * The descriptor to use for `name`: the descriptor itself when `name` is undefined and it has no
1250
1328
  * variants, otherwise the named variant. Throws `unknown_channel_variant` for a name that is not a
@@ -1253,40 +1331,6 @@ declare function configFromEnv(descriptor: ChannelDescriptor, env: Readonly<Reco
1253
1331
  */
1254
1332
  declare function selectVariant(descriptor: ChannelDescriptor, name: string | undefined): ChannelDescriptor;
1255
1333
 
1256
- /**
1257
- * `GatewayConfigurationError` — shared base for per-adapter configuration
1258
- * errors (roadmap M0/M2).
1259
- *
1260
- * Every platform adapter previously defined an identical
1261
- * `ConfigurationError extends Error` (same `code`/`detail` fields, same
1262
- * options interface, same `` `${pkg}: ${code}` `` default message) — only the
1263
- * package prefix differed. This base single-sources that contract. Adapters
1264
- * extend it, pin their prefix, and keep `name = "ConfigurationError"` plus
1265
- * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).
1266
- *
1267
- * @public
1268
- */
1269
- /** Public input shape for the {@link GatewayConfigurationError} constructor. */
1270
- interface GatewayConfigurationErrorOptions {
1271
- readonly code: string;
1272
- readonly message?: string;
1273
- readonly detail?: string;
1274
- }
1275
- /**
1276
- * Base configuration error. Not thrown directly by adapters — they subclass it
1277
- * with a fixed package prefix.
1278
- */
1279
- declare class GatewayConfigurationError extends Error {
1280
- readonly name: string;
1281
- readonly code: string;
1282
- readonly detail: string | undefined;
1283
- /**
1284
- * @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
1285
- * @param opts `code` (required), optional explicit `message`, optional `detail`.
1286
- */
1287
- constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
1288
- }
1289
-
1290
1334
  /**
1291
1335
  * `createChannels` — build every configured channel from its descriptor (FR-002 of B-018).
1292
1336
  *
@@ -1938,6 +1982,22 @@ declare function redactSecrets(value: unknown): string;
1938
1982
  */
1939
1983
  declare function maskSecrets(text: string, secrets: ReadonlyArray<string>): string;
1940
1984
 
1985
+ /**
1986
+ * A small key/value store for credentials an adapter must keep across restarts, such as a rotated
1987
+ * OAuth refresh token.
1988
+ *
1989
+ * @public
1990
+ */
1991
+ /** Reads and writes one string credential per key. @public */
1992
+ interface CredentialStore {
1993
+ /** The stored value, or `undefined` when the key was never set. */
1994
+ get(key: string): Promise<string | undefined>;
1995
+ /** Store `value` under `key`, replacing any earlier value. */
1996
+ set(key: string, value: string): Promise<void>;
1997
+ }
1998
+ /** One file per key under `dir`, mode 0600, written to a temp file and renamed. @public */
1999
+ declare function createFileCredentialStore(dir: string): CredentialStore;
2000
+
1941
2001
  /**
1942
2002
  * `SessionRouter` — pure routing logic: `MessageEvent → agentId`
1943
2003
  * (T2.1, ADR D174).
@@ -2386,4 +2446,4 @@ interface WebhookHandlerOptions {
2386
2446
  */
2387
2447
  declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
2388
2448
 
2389
- export { type AccessPolicyOptions, type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, DEFAULT_WEBHOOK_MAX_BYTES, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, type DmScope, type EmailMessageEvent, type EnvConfig, type FeishuLarkMessageEvent, type FenceRegion, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PairingStore, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, type ReconnectPolicy, type SMSMessageEvent, type ScopedStrategyOptions, SeenIds, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TwitchMessageEvent, type UncoveredShape, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, bindingStrategy, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
2449
+ export { type AccessPolicyOptions, type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelConfigInput, type ChannelConfigReaders, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type CredentialStore, DEFAULT_WEBHOOK_MAX_BYTES, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, type DmScope, type EmailMessageEvent, type EnvConfig, type FeishuLarkMessageEvent, type FenceRegion, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PairingStore, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, type ReconnectPolicy, type SMSMessageEvent, type ScopedStrategyOptions, SeenIds, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TwitchMessageEvent, type UncoveredShape, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
package/dist/index.d.ts CHANGED
@@ -1101,6 +1101,83 @@ declare abstract class WeixinAdapterBase extends BasePlatformAdapter {
1101
1101
  */
1102
1102
  declare function parseFlatXml(xml: string): Record<string, string>;
1103
1103
 
1104
+ /**
1105
+ * `GatewayConfigurationError` — shared base for per-adapter configuration
1106
+ * errors (roadmap M0/M2).
1107
+ *
1108
+ * Every platform adapter previously defined an identical
1109
+ * `ConfigurationError extends Error` (same `code`/`detail` fields, same
1110
+ * options interface, same `` `${pkg}: ${code}` `` default message) — only the
1111
+ * package prefix differed. This base single-sources that contract. Adapters
1112
+ * extend it, pin their prefix, and keep `name = "ConfigurationError"` plus
1113
+ * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).
1114
+ *
1115
+ * @public
1116
+ */
1117
+ /** Public input shape for the {@link GatewayConfigurationError} constructor. */
1118
+ interface GatewayConfigurationErrorOptions {
1119
+ readonly code: string;
1120
+ readonly message?: string;
1121
+ readonly detail?: string;
1122
+ }
1123
+ /**
1124
+ * Base configuration error. Not thrown directly by adapters — they subclass it
1125
+ * with a fixed package prefix.
1126
+ */
1127
+ declare class GatewayConfigurationError extends Error {
1128
+ readonly name: string;
1129
+ readonly code: string;
1130
+ readonly detail: string | undefined;
1131
+ /**
1132
+ * @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
1133
+ * @param opts `code` (required), optional explicit `message`, optional `detail`.
1134
+ */
1135
+ constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
1136
+ }
1137
+
1138
+ /**
1139
+ * `channelConfigReaders` — the config readers every channel's `create` needs, written once.
1140
+ *
1141
+ * Each channel package used to carry its own copy of `invalid`, `readString`, `requiredString`
1142
+ * and friends; only the error prefix differed. The readers throw a configuration error coded
1143
+ * `invalid_config` with the message `${prefix}: config.${key} must be ${expected}`.
1144
+ *
1145
+ * @public
1146
+ */
1147
+
1148
+ /** A channel's config object, as `create` receives it. */
1149
+ type ChannelConfigInput = Readonly<Record<string, unknown>>;
1150
+ /** The readers bound to one package prefix. */
1151
+ interface ChannelConfigReaders {
1152
+ /** Builds (does not throw) the `invalid_config` error for `key`. */
1153
+ invalid(key: string, expected: string): GatewayConfigurationError;
1154
+ /** `undefined`, `null` and `""` are absent. */
1155
+ isAbsent(value: unknown): boolean;
1156
+ /** An optional string; absent gives `undefined`, a non-string throws. */
1157
+ readString(config: ChannelConfigInput, key: string): string | undefined;
1158
+ /** A required string; absent, empty or a non-string throws. */
1159
+ requiredString(config: ChannelConfigInput, key: string): string;
1160
+ /** An optional boolean; absent gives `undefined`, a non-boolean throws. */
1161
+ readBoolean(config: ChannelConfigInput, key: string): boolean | undefined;
1162
+ /**
1163
+ * An optional function; absent gives `undefined`, a non-function throws. Only callability is
1164
+ * checked: the caller names the signature `T` and is responsible for it.
1165
+ */
1166
+ readFunction<T extends (...args: never[]) => unknown>(config: ChannelConfigInput, key: string): T | undefined;
1167
+ }
1168
+ /**
1169
+ * Returns the config readers for a package.
1170
+ *
1171
+ * @param prefix Package prefix in every message, e.g. `"gateway-line"`.
1172
+ * @param createError Builds the error to throw; defaults to `GatewayConfigurationError`. Pass a
1173
+ * package's own subclass to keep its `instanceof` contract.
1174
+ */
1175
+ declare function channelConfigReaders(prefix: string, createError?: (options: {
1176
+ readonly code: string;
1177
+ readonly message: string;
1178
+ readonly detail: string;
1179
+ }) => GatewayConfigurationError): ChannelConfigReaders;
1180
+
1104
1181
  /**
1105
1182
  * `ChannelDescriptor` — one platform's channel described as data (FR-001, ADR D1 of B-018).
1106
1183
  *
@@ -1240,11 +1317,12 @@ interface EnvConfig {
1240
1317
  /** Values of present fields marked secret, for a log mask. Never logged. */
1241
1318
  readonly secrets: readonly string[];
1242
1319
  }
1320
+ type Env = Readonly<Record<string, string | undefined>>;
1243
1321
  /**
1244
1322
  * Read a descriptor's fields from `env`, using `prefix + field.env` as the variable name. Fields
1245
1323
  * without `env` are skipped.
1246
1324
  */
1247
- declare function configFromEnv(descriptor: ChannelDescriptor, env: Readonly<Record<string, string | undefined>>, prefix?: string): EnvConfig;
1325
+ declare function configFromEnv(descriptor: ChannelDescriptor, env: Env, prefix?: string): EnvConfig;
1248
1326
  /**
1249
1327
  * The descriptor to use for `name`: the descriptor itself when `name` is undefined and it has no
1250
1328
  * variants, otherwise the named variant. Throws `unknown_channel_variant` for a name that is not a
@@ -1253,40 +1331,6 @@ declare function configFromEnv(descriptor: ChannelDescriptor, env: Readonly<Reco
1253
1331
  */
1254
1332
  declare function selectVariant(descriptor: ChannelDescriptor, name: string | undefined): ChannelDescriptor;
1255
1333
 
1256
- /**
1257
- * `GatewayConfigurationError` — shared base for per-adapter configuration
1258
- * errors (roadmap M0/M2).
1259
- *
1260
- * Every platform adapter previously defined an identical
1261
- * `ConfigurationError extends Error` (same `code`/`detail` fields, same
1262
- * options interface, same `` `${pkg}: ${code}` `` default message) — only the
1263
- * package prefix differed. This base single-sources that contract. Adapters
1264
- * extend it, pin their prefix, and keep `name = "ConfigurationError"` plus
1265
- * their own subclasses (`SDKNotInstalledError`, `BackendNotInstalledError`, …).
1266
- *
1267
- * @public
1268
- */
1269
- /** Public input shape for the {@link GatewayConfigurationError} constructor. */
1270
- interface GatewayConfigurationErrorOptions {
1271
- readonly code: string;
1272
- readonly message?: string;
1273
- readonly detail?: string;
1274
- }
1275
- /**
1276
- * Base configuration error. Not thrown directly by adapters — they subclass it
1277
- * with a fixed package prefix.
1278
- */
1279
- declare class GatewayConfigurationError extends Error {
1280
- readonly name: string;
1281
- readonly code: string;
1282
- readonly detail: string | undefined;
1283
- /**
1284
- * @param prefix Package prefix used in the default message (e.g. `"gateway-line"`).
1285
- * @param opts `code` (required), optional explicit `message`, optional `detail`.
1286
- */
1287
- constructor(prefix: string, opts: GatewayConfigurationErrorOptions);
1288
- }
1289
-
1290
1334
  /**
1291
1335
  * `createChannels` — build every configured channel from its descriptor (FR-002 of B-018).
1292
1336
  *
@@ -1938,6 +1982,22 @@ declare function redactSecrets(value: unknown): string;
1938
1982
  */
1939
1983
  declare function maskSecrets(text: string, secrets: ReadonlyArray<string>): string;
1940
1984
 
1985
+ /**
1986
+ * A small key/value store for credentials an adapter must keep across restarts, such as a rotated
1987
+ * OAuth refresh token.
1988
+ *
1989
+ * @public
1990
+ */
1991
+ /** Reads and writes one string credential per key. @public */
1992
+ interface CredentialStore {
1993
+ /** The stored value, or `undefined` when the key was never set. */
1994
+ get(key: string): Promise<string | undefined>;
1995
+ /** Store `value` under `key`, replacing any earlier value. */
1996
+ set(key: string, value: string): Promise<void>;
1997
+ }
1998
+ /** One file per key under `dir`, mode 0600, written to a temp file and renamed. @public */
1999
+ declare function createFileCredentialStore(dir: string): CredentialStore;
2000
+
1941
2001
  /**
1942
2002
  * `SessionRouter` — pure routing logic: `MessageEvent → agentId`
1943
2003
  * (T2.1, ADR D174).
@@ -2386,4 +2446,4 @@ interface WebhookHandlerOptions {
2386
2446
  */
2387
2447
  declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
2388
2448
 
2389
- export { type AccessPolicyOptions, type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, DEFAULT_WEBHOOK_MAX_BYTES, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, type DmScope, type EmailMessageEvent, type EnvConfig, type FeishuLarkMessageEvent, type FenceRegion, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PairingStore, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, type ReconnectPolicy, type SMSMessageEvent, type ScopedStrategyOptions, SeenIds, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TwitchMessageEvent, type UncoveredShape, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, bindingStrategy, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
2449
+ export { type AccessPolicyOptions, type AdapterCapabilities, type AdapterState, type AgentBindingRule, type AgentBindings, type AgentBindingsOptions, type AgentIdStrategy, type BaseMessageEvent, BasePlatformAdapter, type BuiltChannel, type BuzzMessageEvent, CREDENTIAL_SHAPES, type ChannelConfigField, type ChannelConfigInput, type ChannelConfigReaders, type ChannelDescriptor, type ChannelEntry, type ChannelRejection, type ChannelRendering, type ChannelWebhook, type ChatCommand, type ChunkByGraphemeOptions, type ChunkTextOptions, type ClickClackMessageEvent, type ConnectFailure, type CoveredShape, type CreateChannelsResult, type CredentialStore, DEFAULT_WEBHOOK_MAX_BYTES, type DeliveryRequest, DeliveryRouter, type DeliveryTarget, type DiscordMessageEvent, type DmPolicy, type DmScope, type EmailMessageEvent, type EnvConfig, type FeishuLarkMessageEvent, type FenceRegion, GatewayConfigurationError, type GatewayConfigurationErrorOptions, type GatewayContext, type GatewayHandler, type GatewayHook, GatewayLifecycleError, type GatewayLifecycleErrorOptions, GatewayRunner, type GatewayRunnerOptions, type GoogleChatMessageEvent, type HookDecision, HookExecutor, type HookName, type IMessageMessageEvent, type InboundAudio, type IngestResult, type IrcMessageEvent, type LineMessageEvent, type ListenableApp, type ListenerLike, type MatrixMessageEvent, type MattermostMessageEvent, type MediaUnderstandingOptions, type MessageEvent, type NextcloudTalkMessageEvent, type NostrMessageEvent, type OnErrorContext, type OutboundAttachment, type OutboundMessage, type PairingStore, type ParsedChatCommand, type PlatformEventRegistry, type PlatformName, type PostOutboundContext, type PreInboundContext, type QQMessageEvent, type RaftMessageEvent, type RawBodyCaptureOptions, type RawBodyRequest, type ReconnectPolicy, type SMSMessageEvent, type ScopedStrategyOptions, SeenIds, type SendResult, type SenderIdentity, SessionRouter, type SignalMessageEvent, type SlackMessageEvent, type StartResult, type SynologyChatMessageEvent, type TeamsMessageEvent, type TelegramMessageEvent, type TlonUrbitMessageEvent, type TwitchMessageEvent, type UncoveredShape, type WeChatMessageEvent, type WeComMessageEvent, type WebhookAnswer, type WebhookHandlerOptions, type WebhookRequest, WeixinAdapterBase, type WeixinAdapterConfig, type WeixinFetch, type WeixinSendRequest, type WeixinWebhookAnswer, type WhatsAppMessageEvent, type XMessageEvent, type XThreadTweet, type YuanbaoMessageEvent, type ZaloMessageEvent, type ZaloPersonalMessageEvent, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { Security } from '@theokit/sdk';
2
- import { randomInt, randomUUID } from 'crypto';
2
+ import { randomInt, randomBytes, randomUUID } from 'crypto';
3
3
  import { readFileSync, mkdirSync, writeFileSync, renameSync } from 'fs';
4
4
  import { join } from 'path';
5
+ import { mkdir, writeFile, chmod, rename, unlink, readFile } from 'fs/promises';
5
6
 
6
7
  // src/text/fence.ts
7
8
  var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
@@ -555,11 +556,6 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
555
556
  }
556
557
  };
557
558
 
558
- // src/channel/channel-descriptor.ts
559
- function isAuthenticatedSender(descriptor) {
560
- return descriptor.senderIdentity === "authenticated";
561
- }
562
-
563
559
  // src/errors/config-error.ts
564
560
  var GatewayConfigurationError = class extends Error {
565
561
  name = "GatewayConfigurationError";
@@ -576,18 +572,63 @@ var GatewayConfigurationError = class extends Error {
576
572
  }
577
573
  };
578
574
 
575
+ // src/channel/channel-config-readers.ts
576
+ function channelConfigReaders(prefix, createError = (options) => new GatewayConfigurationError(prefix, options)) {
577
+ const invalid2 = (key, expected) => createError({
578
+ code: "invalid_config",
579
+ message: `${prefix}: config.${key} must be ${expected}`,
580
+ detail: key
581
+ });
582
+ const isAbsent2 = (value) => value === void 0 || value === null || value === "";
583
+ const readString = (config, key) => {
584
+ const value = config[key];
585
+ if (isAbsent2(value)) return void 0;
586
+ if (typeof value !== "string") throw invalid2(key, "a string");
587
+ return value;
588
+ };
589
+ return {
590
+ invalid: invalid2,
591
+ isAbsent: isAbsent2,
592
+ readString,
593
+ requiredString(config, key) {
594
+ const value = config[key];
595
+ if (typeof value !== "string" || value === "") throw invalid2(key, "a non-empty string");
596
+ return value;
597
+ },
598
+ readBoolean(config, key) {
599
+ const value = config[key];
600
+ if (isAbsent2(value)) return void 0;
601
+ if (typeof value !== "boolean") throw invalid2(key, "a boolean");
602
+ return value;
603
+ },
604
+ readFunction(config, key) {
605
+ const value = config[key];
606
+ if (isAbsent2(value)) return void 0;
607
+ if (typeof value !== "function") throw invalid2(key, "a function");
608
+ return value;
609
+ }
610
+ };
611
+ }
612
+
613
+ // src/channel/channel-descriptor.ts
614
+ function isAuthenticatedSender(descriptor) {
615
+ return descriptor.senderIdentity === "authenticated";
616
+ }
617
+
579
618
  // src/channel/config-from-env.ts
619
+ function envVarName(field, prefix = "") {
620
+ return field.env === void 0 ? void 0 : prefix + field.env;
621
+ }
580
622
  function readValue(env, name) {
581
- const value = env[name]?.trim();
582
- return value ? value : void 0;
623
+ return env[name]?.trim() || void 0;
583
624
  }
584
625
  function configFromEnv(descriptor, env, prefix = "") {
585
626
  const config = {};
586
627
  const missing = [];
587
628
  const secrets = [];
588
629
  for (const field of descriptor.config) {
589
- if (field.env === void 0) continue;
590
- const name = prefix + field.env;
630
+ const name = envVarName(field, prefix);
631
+ if (name === void 0) continue;
591
632
  const value = readValue(env, name);
592
633
  if (value === void 0) {
593
634
  if (field.required) missing.push(name);
@@ -629,9 +670,10 @@ function isAbsent(value) {
629
670
  return value === void 0 || value === null || value === "";
630
671
  }
631
672
  function missingRequiredKeys(entry, values) {
632
- return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map(
633
- (field) => field.env === void 0 ? field.key : `${field.key} (env ${(entry.envPrefix ?? "") + field.env})`
634
- );
673
+ return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map((field) => {
674
+ const name = envVarName(field, entry.envPrefix);
675
+ return name === void 0 ? field.key : `${field.key} (env ${name})`;
676
+ });
635
677
  }
636
678
  function refused(platform, code, reason) {
637
679
  return {
@@ -1697,6 +1739,46 @@ function withMediaUnderstanding(handler, options) {
1697
1739
  return handler(wrapped, ctx);
1698
1740
  };
1699
1741
  }
1742
+ var KEY_PATTERN = /^[A-Za-z0-9._:-]+$(?![\s\S])/;
1743
+ function fileFor(dir, key) {
1744
+ if (!KEY_PATTERN.test(key) || key === "." || key === "..") {
1745
+ throw new GatewayConfigurationError("gateway", {
1746
+ code: "invalid_credential_key",
1747
+ message: `gateway: invalid_credential_key (keys match [A-Za-z0-9._:-]+): ${JSON.stringify(key)}`
1748
+ });
1749
+ }
1750
+ return join(dir, key.replaceAll(":", "%3A"));
1751
+ }
1752
+ function createFileCredentialStore(dir) {
1753
+ return {
1754
+ async get(key) {
1755
+ const path = fileFor(dir, key);
1756
+ try {
1757
+ return await readFile(path, "utf8");
1758
+ } catch (err) {
1759
+ if (err.code === "ENOENT") return void 0;
1760
+ throw new GatewayConfigurationError("gateway", {
1761
+ code: "credential_store_unreadable",
1762
+ message: `gateway: credential_store_unreadable: ${path}`,
1763
+ detail: err instanceof Error ? err.message : String(err)
1764
+ });
1765
+ }
1766
+ },
1767
+ async set(key, value) {
1768
+ const path = fileFor(dir, key);
1769
+ await mkdir(dir, { recursive: true });
1770
+ const tmp = `${path}.${randomBytes(6).toString("hex")}.tmp`;
1771
+ try {
1772
+ await writeFile(tmp, value, { mode: 384 });
1773
+ await chmod(tmp, 384);
1774
+ await rename(tmp, path);
1775
+ } catch (err) {
1776
+ await unlink(tmp).catch(() => void 0);
1777
+ throw err;
1778
+ }
1779
+ }
1780
+ };
1781
+ }
1700
1782
 
1701
1783
  // src/session/router.ts
1702
1784
  function defaultStrategy(event) {
@@ -1790,7 +1872,7 @@ function bindingStrategy(bindings, inner) {
1790
1872
  }
1791
1873
 
1792
1874
  // src/session/scoped-strategy.ts
1793
- var join2 = (...segments) => segments.map(sanitize).join("-");
1875
+ var join3 = (...segments) => segments.map(sanitize).join("-");
1794
1876
  function invalid(message, detail) {
1795
1877
  return new GatewayConfigurationError("gateway", {
1796
1878
  code: "invalid_session_scope",
@@ -1814,21 +1896,21 @@ function scopedStrategy(options) {
1814
1896
  return "_m-dm";
1815
1897
  case "per-peer": {
1816
1898
  const peer = peerLinks?.get(`${platform}:${senderId}`);
1817
- return peer === void 0 ? join2(platform, "dm", senderId) : `_p-dm-${sanitize(peer)}`;
1899
+ return peer === void 0 ? join3(platform, "dm", senderId) : `_p-dm-${sanitize(peer)}`;
1818
1900
  }
1819
1901
  case "per-channel-peer":
1820
- return join2(platform, "dm", senderId);
1902
+ return join3(platform, "dm", senderId);
1821
1903
  case "per-account-channel-peer":
1822
- return join2(platform, "dm", accountLabel ?? "", senderId);
1904
+ return join3(platform, "dm", accountLabel ?? "", senderId);
1823
1905
  }
1824
1906
  };
1825
1907
  return (event) => {
1826
1908
  const { platform, channel, sender } = event;
1827
1909
  if (channel.type === "dm") return dmKey(platform, sender.id);
1828
1910
  if (channel.type === "thread" && channel.topicId !== void 0) {
1829
- return join2(platform, "tpc", channel.id, channel.topicId);
1911
+ return join3(platform, "tpc", channel.id, channel.topicId);
1830
1912
  }
1831
- return groupScope === "channel-sender" ? join2(platform, "grp", channel.id, sender.id) : join2(platform, "grp", channel.id);
1913
+ return groupScope === "channel-sender" ? join3(platform, "grp", channel.id, sender.id) : join3(platform, "grp", channel.id);
1832
1914
  };
1833
1915
  }
1834
1916
 
@@ -2311,6 +2393,6 @@ async function dispatch(webhook, adapter, request) {
2311
2393
  return runDefault(webhook, adapter, request);
2312
2394
  }
2313
2395
 
2314
- export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, bindingStrategy, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
2396
+ export { BasePlatformAdapter, CREDENTIAL_SHAPES, DEFAULT_WEBHOOK_MAX_BYTES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, bindingStrategy, channelConfigReaders, channelRendering, chunkByGrapheme, chunkText, commandHook, configFromEnv, createAccessPolicyHook, createAgentBindings, createChannels, createFileCredentialStore, createFilePairingStore, createWebhookHandler, defaultStrategy, helpText, isAuthenticatedSender, listenerLifecycle, loadPeer, maskSecrets, maskShapes, parseChatCommand, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, scopedStrategy, selectVariant, senderKey, splitKeepingRows, statusForDeliver, toDialect, withMediaUnderstanding };
2315
2397
  //# sourceMappingURL=index.js.map
2316
2398
  //# sourceMappingURL=index.js.map