@deepseek-ai/dsh-im-telegram-store 0.0.0-stage → 0.2.3-alpha.4

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,40 @@
1
+ # Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
2
+ # section, a hash of its English and Chinese blocks outside code blocks and generated regions.
3
+ # After editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/experimental/im-telegram-store/README.md
5
+ /:
6
+ en: da514987e0b07c75
7
+ zh: 4f2d28401a4437ce
8
+ /deepseek-ai-dsh-im-telegram-store:
9
+ en: 904e2e8de180e5b6
10
+ zh: 968e2b0fba2f6bc0
11
+ /deepseek-ai-dsh-im-telegram-store/summary:
12
+ en: 3e7f0420fb49a0a7
13
+ zh: f28eba36a23cbdb8
14
+ /deepseek-ai-dsh-im-telegram-store/table-of-contents:
15
+ en: d152484eb41ac6b4
16
+ zh: 4ebceb2533647b32
17
+ /deepseek-ai-dsh-im-telegram-store/use-this-package:
18
+ en: 2275a6f6739ba6a5
19
+ zh: 67684f4baead86b5
20
+ /deepseek-ai-dsh-im-telegram-store/understand-the-implementation:
21
+ en: ec701c7ed619206c
22
+ zh: d06c9d876ce3a4e1
23
+ /deepseek-ai-dsh-im-telegram-store/understand-the-implementation/source-map:
24
+ en: 4c6e00c1c9f0f52a
25
+ zh: 9673950765a5fdb7
26
+ /deepseek-ai-dsh-im-telegram-store/further-exploration:
27
+ en: 8a6dbafc363cfc4f
28
+ zh: de57239ad5c00e7f
29
+ /deepseek-ai-dsh-im-telegram-store/model-experience:
30
+ en: 1b3c6ebc4491f9d1
31
+ zh: d05936afcd066071
32
+ /deepseek-ai-dsh-im-telegram-store/model-experience/kv-cache-effect:
33
+ en: 34f5d4355389a623
34
+ zh: fe3d222bb8c4c780
35
+ /deepseek-ai-dsh-im-telegram-store/known-limitations-and-deferred-work:
36
+ en: 794526cef16df45b
37
+ zh: 32c2151ca8463efb
38
+ /deepseek-ai-dsh-im-telegram-store/known-limitations-and-deferred-work/dev-note:
39
+ en: 75ff90fa170b9fd6
40
+ zh: 3fe90e58e081c582
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ ---
2
+ description: "Keep the Telegram IM adapter's session across restarts: authorization keys as credential records, update cursors and caches in the `im_telegram` storage domain."
3
+ kind: "package-reference"
4
+ ---
2
5
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
6
+ # @deepseek-ai/dsh-im-telegram-store
7
+
8
+ English | [中文](README.zh.md)
9
+
10
+ ## Summary
11
+
12
+ Provide the `telegram-store` service that the Telegram IM adapter (`@deepseek-ai/cordis-plugin-im-adapter-telegram`) requires, over dsh's own durable storage. An account's authorization keys are a secret whose loss means logging in again, so they live in the credential store as one grant record per account. Its update cursors, peer cache and long-callback table are rebuilt by Telegram when lost, so they live in the `im_telegram` storage domain under `$DSH_HOME/storages`. A restart therefore reuses the session instead of logging in again, which Telegram answers with a flood wait when it happens often.
13
+
14
+ ## Table of Contents
15
+
16
+ - [Use this package](#use-this-package)
17
+ - [Understand the implementation](#understand-the-implementation)
18
+ - [Further Exploration](#further-exploration)
19
+ - [Model Experience](#model-experience)
20
+ - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
21
+ - [Dev Note](#dev-note)
22
+
23
+ -----
24
+
25
+ <a id="use-this-package"></a>
26
+ ## Use this package
27
+
28
+ Mount the plugin before the Telegram adapter, in a profile that provides `credentials` and `storageDomain`. The [IM bundle](../im-bundle/README.md) mounts neither row and the [IM connector](../im-connector/README.md) has no Telegram platform, so the IM host admits a Telegram bot's messages only when another plugin provides an admission rule for that bot through `ctx.im.sources.provide`.
29
+
30
+ ```yaml
31
+ - id: im-telegram-store
32
+ name: '@deepseek-ai/dsh-im-telegram-store'
33
+ - id: im-telegram
34
+ name: '@deepseek-ai/cordis-plugin-im-adapter-telegram'
35
+ config:
36
+ account:
37
+ type: bot
38
+ token: !!js process.env.DSH_TELEGRAM_BOT_TOKEN
39
+ ```
40
+
41
+ | What | Where | Lost means |
42
+ |---|---|---|
43
+ | Authorization key per data center, the account's data center and identity | Credential record `im-telegram-store/bot-<id>` (or `user-<id>`) | Logging in again |
44
+ | Update cursors (`pts`, `qts`, `seq`, `date`, per-channel `pts`) | `im_telegram` table `cursors` | Updates sent while the process was down are skipped |
45
+ | Peer cache (access hashes) | `im_telegram` table `peers` | Peers are resolved again as they appear |
46
+ | Long button callbacks (`~<hash>` → id and payload) | `im_telegram` table `callbacks` | Clicks on older long-id buttons cannot be routed |
47
+
48
+ Deleting the credential record logs the account in again on the next start; the cursors of the old authorization are discarded with it.
49
+
50
+ -----
51
+
52
+ <a id="understand-the-implementation"></a>
53
+ ## Understand the implementation
54
+
55
+ <details>
56
+ <summary>Implementation internals — click to expand</summary>
57
+
58
+ The adapter's `TelegramStorage` keeps mtcute's session in memory and calls the store: `writeGrant` before mtcute uses a new authorization key, `writeState` for the tables when mtcute saves its session and before a message with a long callback key is published. This plugin implements `readGrant` / `writeGrant` with `ctx.credentials.readRecord` and `modifyRecord` (`deleteRecord` for a removed grant) and validates a grant read back; a record of another kind or shape is ignored, so the account logs in again. `readState` / `writeState` read and put one record per account in the domain tables; the domain sets an unreadable record aside (`invalidRecords: 'backup-and-skip'`) because every table is rebuildable.
59
+
60
+ ### Source map
61
+
62
+ | File | Role |
63
+ |---|---|
64
+ | [`src/index.ts`](src/index.ts) | Plugin entry, the `im_telegram` domain, grant validation and the credential key of an account |
65
+
66
+ </details>
67
+
68
+ -----
69
+
70
+ <a id="further-exploration"></a>
71
+ ## Further Exploration
72
+
73
+ - [IM host](../im/README.md) — the admission rules that decide which Telegram messages reach a session.
74
+ - [Vendored packages](../../../vendor/README.md) — the Telegram adapter (V69) and its storage contract.
75
+ - [IM subsystem](../../../docs/subsystems/im.md) — the IM host, storage domains and adapters.
76
+
77
+ -----
78
+
79
+ <a id="model-experience"></a>
80
+ ## Model Experience
81
+
82
+ None, as the plugin stores session state of a chat platform account and adds nothing to any model request.
83
+
84
+ #### KV Cache effect
85
+
86
+ Independent: nothing it stores reaches a request.
87
+
88
+ ## Known Limitations and Deferred Work
89
+
90
+ <a id="known-limitations-and-deferred-work"></a>
91
+
92
+ The following constraints apply to `@deepseek-ai/dsh-im-telegram-store`:
93
+
94
+ - **One process per account** — two processes sharing one `$DSH_HOME` and one Telegram account would advance the same cursors and authorization concurrently.
95
+ - **Temporary keys are not stored** — perfect-forward-secrecy keys and server salts are renegotiated after a restart.
96
+
97
+ <a id="dev-note"></a>
98
+ ### Dev Note
99
+
100
+ <details>
101
+ <summary>Working context for maintainers — click to expand</summary>
102
+
103
+ The grant format (`v: 1`) is owned by the adapter's `TelegramGrant`; a new version needs a reader here that accepts the old one or a deliberate re-login.
104
+
105
+ </details>
package/README.zh.md ADDED
@@ -0,0 +1,105 @@
1
+ ---
2
+ description: "跨重启保留 Telegram IM 适配器的会话:授权密钥存为凭据记录,更新游标与缓存存入 `im_telegram` 存储域。"
3
+ kind: "package-reference"
4
+ ---
5
+
6
+ # @deepseek-ai/dsh-im-telegram-store
7
+
8
+ [English](README.md) | 中文
9
+
10
+ ## 概述
11
+
12
+ 在 dsh 自身的持久化存储之上提供 Telegram IM 适配器(`@deepseek-ai/cordis-plugin-im-adapter-telegram`)所需的 `telegram-store` 服务。账号的授权密钥属于机密,丢失即需重新登录,因此以每个账号一条授权记录的形式存入凭据存储。更新游标、peer 缓存与长回调表丢失后可由 Telegram 重建,因此存入 `$DSH_HOME/storages` 下的 `im_telegram` 存储域。这样重启后会复用原会话,而不是重新登录——频繁登录会被 Telegram 以 flood wait 拒绝。
13
+
14
+ ## 目录
15
+
16
+ - [使用方式](#use-this-package)
17
+ - [实现机制](#understand-the-implementation)
18
+ - [进一步阅读](#further-exploration)
19
+ - [模型体验](#model-experience)
20
+ - [已知限制与后续工作](#known-limitations-and-deferred-work)
21
+ - [开发备注](#dev-note)
22
+
23
+ -----
24
+
25
+ <a id="use-this-package"></a>
26
+ ## 使用方式
27
+
28
+ 在提供 `credentials` 与 `storageDomain` 的 profile 中,把本插件挂在 Telegram 适配器之前。[IM 组合包](../im-bundle/README.zh.md) 不挂载这两个条目,[IM 连接器](../im-connector/README.zh.md) 也没有 Telegram 平台,因此只有当其他插件通过 `ctx.im.sources.provide` 为该机器人提供接纳规则时,IM 宿主才会接纳 Telegram 机器人的消息。
29
+
30
+ ```yaml
31
+ - id: im-telegram-store
32
+ name: '@deepseek-ai/dsh-im-telegram-store'
33
+ - id: im-telegram
34
+ name: '@deepseek-ai/cordis-plugin-im-adapter-telegram'
35
+ config:
36
+ account:
37
+ type: bot
38
+ token: !!js process.env.DSH_TELEGRAM_BOT_TOKEN
39
+ ```
40
+
41
+ | 内容 | 位置 | 丢失后果 |
42
+ |---|---|---|
43
+ | 各数据中心的授权密钥、账号所在数据中心与身份 | 凭据记录 `im-telegram-store/bot-<id>`(或 `user-<id>`) | 需要重新登录 |
44
+ | 更新游标(`pts`、`qts`、`seq`、`date`、各频道 `pts`) | `im_telegram` 的 `cursors` 表 | 进程停止期间的更新被跳过 |
45
+ | peer 缓存(access hash) | `im_telegram` 的 `peers` 表 | peer 在再次出现时重新解析 |
46
+ | 长按钮回调(`~<hash>` → id 与负载) | `im_telegram` 的 `callbacks` 表 | 旧的长 id 按钮被点击时无法路由 |
47
+
48
+ 删除凭据记录后,下次启动时账号会重新登录,旧授权下的游标随之丢弃。
49
+
50
+ -----
51
+
52
+ <a id="understand-the-implementation"></a>
53
+ ## 实现机制
54
+
55
+ <details>
56
+ <summary>实现细节——点击展开</summary>
57
+
58
+ 适配器的 `TelegramStorage` 在内存中保存 mtcute 的会话,并调用本存储:在 mtcute 使用新授权密钥之前调用 `writeGrant`;在 mtcute 保存会话时、以及发布带长回调键的消息之前,对各表调用 `writeState`。本插件用 `ctx.credentials.readRecord` 与 `modifyRecord`(授权被删除时用 `deleteRecord`)实现 `readGrant` / `writeGrant`,并校验读回的授权;类型或结构不符的记录会被忽略,账号随之重新登录。`readState` / `writeState` 在存储域各表中按账号读写一条记录;由于各表均可重建,存储域会把无法读取的记录移到一旁(`invalidRecords: 'backup-and-skip'`)。
59
+
60
+ ### 源码结构
61
+
62
+ | 文件 | 职责 |
63
+ |---|---|
64
+ | [`src/index.ts`](src/index.ts) | 插件入口、`im_telegram` 存储域、授权校验与账号的凭据键 |
65
+
66
+ </details>
67
+
68
+ -----
69
+
70
+ <a id="further-exploration"></a>
71
+ ## 进一步阅读
72
+
73
+ - [IM 宿主](../im/README.zh.md) — 决定哪些 Telegram 消息进入会话的接纳规则。
74
+ - [Vendor 包](../../../vendor/README.md) — Telegram 适配器(V69)及其存储约定。
75
+ - [IM 子系统](../../../docs/subsystems/im.zh.md) — IM 宿主、存储域与适配器。
76
+
77
+ -----
78
+
79
+ <a id="model-experience"></a>
80
+ ## 模型体验
81
+
82
+ 无,本插件只保存聊天平台账号的会话状态,不向任何模型请求添加内容。
83
+
84
+ #### KV Cache 影响
85
+
86
+ 独立:它保存的内容不会进入任何请求。
87
+
88
+ ## 已知限制与后续工作
89
+
90
+ <a id="known-limitations-and-deferred-work"></a>
91
+
92
+ `@deepseek-ai/dsh-im-telegram-store` 当前存在以下限制:
93
+
94
+ - **每个账号只能由一个进程使用** — 两个进程共用同一 `$DSH_HOME` 与同一 Telegram 账号时,会并发推进同一组游标与授权。
95
+ - **不保存临时密钥** — 前向保密的临时密钥与服务器 salt 在重启后重新协商。
96
+
97
+ <a id="dev-note"></a>
98
+ ### 开发备注
99
+
100
+ <details>
101
+ <summary>维护者工作记录——点击展开</summary>
102
+
103
+ 授权格式(`v: 1`)由适配器的 `TelegramGrant` 定义;新版本需要在这里提供兼容旧版本的读取,或明确地重新登录。
104
+
105
+ </details>
package/lib/index.js ADDED
@@ -0,0 +1,141 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { credentialKey } from "@deepseek-ai/dsh-credentials";
3
+ import { defineDomain, domainTable } from "@deepseek-ai/dsh-storage-domain";
4
+ import * as zod from "zod";
5
+ //#region lib/types/store.js
6
+ /**
7
+ * The `telegram-store` implementation behind the plugin entry: the record shapes, the `im_telegram` storage domain,
8
+ * the credential keys and the service object the adapter injects.
9
+ *
10
+ * The package entry exports only what the Loader mounts (`name`, `inject`, `Config`, `apply`) and the types a consumer
11
+ * names, so these values stay in this module: the plugin's own tests import them from here
12
+ * ([package surface](../../../../docs/defensive-patterns/package-surface.md)).
13
+ *
14
+ * @module @deepseek-ai/dsh-im-telegram-store/store
15
+ */
16
+ /** This package's registered name: the plugin name and the scope of the credential records it writes. */
17
+ const PLUGIN_NAME = "im-telegram-store";
18
+ const grantSchema = zod.object({
19
+ v: zod.literal(1),
20
+ keys: zod.record(zod.string(), zod.string()),
21
+ kv: zod.record(zod.string(), zod.string())
22
+ });
23
+ const cursorsSchema = zod.record(zod.string(), zod.number().int());
24
+ const peersSchema = zod.record(zod.string(), zod.object({
25
+ id: zod.number(),
26
+ accessHash: zod.string(),
27
+ isMin: zod.boolean(),
28
+ usernames: zod.array(zod.string()),
29
+ updated: zod.number(),
30
+ phone: zod.exactOptional(zod.string()),
31
+ complete: zod.string()
32
+ }));
33
+ const callbacksSchema = zod.record(zod.string(), zod.object({
34
+ id: zod.string(),
35
+ data: zod.exactOptional(zod.string()),
36
+ time: zod.number()
37
+ }));
38
+ /**
39
+ * The `im_telegram` storage domain: one record per account (keyed by the adapter's bot id) in each table.
40
+ */
41
+ const telegramDomain = defineDomain({
42
+ name: "im_telegram",
43
+ version: 1,
44
+ invalidRecords: "backup-and-skip",
45
+ tables: {
46
+ cursors: domainTable(cursorsSchema),
47
+ peers: domainTable(peersSchema),
48
+ callbacks: domainTable(callbacksSchema)
49
+ }
50
+ });
51
+ /**
52
+ * The credential key of an account's grant.
53
+ *
54
+ * @param account - the adapter's bot id: `telegram:<id>` or `telegram:user:<id>`.
55
+ * @returns the record key `im-telegram-store/bot-<id>` or `im-telegram-store/user-<id>`.
56
+ * @throws TypeError for a bot id of another form.
57
+ */
58
+ function grantKey(account) {
59
+ const match = /^telegram:(user:)?(\d+)$/.exec(account);
60
+ if (!match) throw new TypeError(`im-telegram-store: "${account}" is not a Telegram bot id`);
61
+ return credentialKey(PLUGIN_NAME, `${match[1] ? "user" : "bot"}-${match[2]}`);
62
+ }
63
+ /**
64
+ * The store over an open domain and the credential service.
65
+ *
66
+ * @param ctx - a context carrying `credentials`.
67
+ * @param domain - the open `im_telegram` domain.
68
+ * @returns the `telegram-store` implementation.
69
+ */
70
+ function createStore(ctx, domain) {
71
+ return {
72
+ async readGrant(account) {
73
+ const record = await ctx.credentials.readRecord(grantKey(account));
74
+ if (!record) return void 0;
75
+ if (record.kind !== "grant") return void 0;
76
+ const parsed = grantSchema.safeParse(record.payload);
77
+ if (!parsed.success) {
78
+ ctx.logger.warn("im-telegram-store: the stored grant of %s is malformed and is ignored", account);
79
+ return;
80
+ }
81
+ return parsed.data;
82
+ },
83
+ async writeGrant(account, grant) {
84
+ const key = grantKey(account);
85
+ if (!grant) {
86
+ await ctx.credentials.deleteRecord(key);
87
+ return;
88
+ }
89
+ await ctx.credentials.modifyRecord(key, () => Promise.resolve({
90
+ kind: "grant",
91
+ payload: grant
92
+ }));
93
+ },
94
+ readState(account, table) {
95
+ const target = domain.table(table);
96
+ return Promise.resolve(target.get(account));
97
+ },
98
+ async writeState(account, table, value) {
99
+ await domain.table(table).put(account, value);
100
+ }
101
+ };
102
+ }
103
+ //#endregion
104
+ //#region lib/types/index.js
105
+ /**
106
+ * The `telegram-store` service of the Telegram IM adapter over dsh's own durable storage.
107
+ *
108
+ * What a Telegram account must keep across restarts splits by what losing it means:
109
+ *
110
+ * - The **grant** — the account's authorization keys per data center and the session facts that belong to them — is a
111
+ * secret whose loss means logging in again. It is one credential record per account (`ctx.credentials`, scope
112
+ * `im-telegram-store`, id `bot-<id>` / `user-<id>`), written through `modifyRecord` before the adapter uses a new
113
+ * key, and validated when read back.
114
+ * - The **state** — update cursors, the peer cache and the long-callback table — is rebuilt by the platform when lost.
115
+ * It lives in the `im_telegram` storage domain, one record per account in each of the tables `cursors`, `peers`
116
+ * and `callbacks`.
117
+ *
118
+ * The entry mounts the plugin; the record shapes, the domain, the credential keys and the service object live in
119
+ * [`./store.ts`](./store.ts), which the tests read directly.
120
+ *
121
+ * @module @deepseek-ai/dsh-im-telegram-store
122
+ */
123
+ /** Scope of the credential records: this plugin's registered name. */
124
+ const name = PLUGIN_NAME;
125
+ /** The credential seam holds the grants, the domain facility the state. */
126
+ const inject = ["credentials", "storageDomain"];
127
+ const Config = z.object({}).description("Telegram 账号会话存储");
128
+ /**
129
+ * Open the domain and provide `telegram-store`; the domain closes with the plugin.
130
+ *
131
+ * @param ctx - context carrying `credentials` and `storageDomain`.
132
+ */
133
+ async function apply(ctx) {
134
+ const domain = await ctx.storageDomain.open(telegramDomain);
135
+ ctx.effect(function* () {
136
+ yield ctx.effect(() => () => domain.close());
137
+ yield ctx.provide("telegram-store", createStore(ctx, domain));
138
+ }, "im-telegram-store");
139
+ }
140
+ //#endregion
141
+ export { Config, apply, inject, name };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The `telegram-store` service of the Telegram IM adapter over dsh's own durable storage.
3
+ *
4
+ * What a Telegram account must keep across restarts splits by what losing it means:
5
+ *
6
+ * - The **grant** — the account's authorization keys per data center and the session facts that belong to them — is a
7
+ * secret whose loss means logging in again. It is one credential record per account (`ctx.credentials`, scope
8
+ * `im-telegram-store`, id `bot-<id>` / `user-<id>`), written through `modifyRecord` before the adapter uses a new
9
+ * key, and validated when read back.
10
+ * - The **state** — update cursors, the peer cache and the long-callback table — is rebuilt by the platform when lost.
11
+ * It lives in the `im_telegram` storage domain, one record per account in each of the tables `cursors`, `peers`
12
+ * and `callbacks`.
13
+ *
14
+ * The entry mounts the plugin; the record shapes, the domain, the credential keys and the service object live in
15
+ * [`./store.ts`](./store.ts), which the tests read directly.
16
+ *
17
+ * @module @deepseek-ai/dsh-im-telegram-store
18
+ */
19
+ import type { Context } from '@deepseek-ai/cordis';
20
+ import z from '@deepseek-ai/schemastery';
21
+ export type { TelegramCallbackRecord, TelegramDomain, TelegramGrant, TelegramPeerRecord, TelegramStateTable, TelegramStateTables, TelegramStore, } from './store.ts';
22
+ /** Scope of the credential records: this plugin's registered name. */
23
+ export declare const name = "im-telegram-store";
24
+ /** The credential seam holds the grants, the domain facility the state. */
25
+ export declare const inject: string[];
26
+ /** The plugin takes no configuration. */
27
+ export interface Config {
28
+ }
29
+ export declare const Config: z<Config>;
30
+ /**
31
+ * Open the domain and provide `telegram-store`; the domain closes with the plugin.
32
+ *
33
+ * @param ctx - context carrying `credentials` and `storageDomain`.
34
+ */
35
+ export declare function apply(ctx: Context): Promise<void>;
36
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAGxC,YAAY,EACV,sBAAsB,EACtB,cAAc,EACd,aAAa,EACb,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,aAAa,GACd,MAAM,YAAY,CAAA;AAEnB,sEAAsE;AACtE,eAAO,MAAM,IAAI,sBAAc,CAAA;AAC/B,2EAA2E;AAC3E,eAAO,MAAM,MAAM,UAAmC,CAAA;AAEtD,yCAAyC;AACzC,MAAM,WAAW,MAAM;CAAG;AAE1B,eAAO,MAAM,MAAM,EAAE,CAAC,CAAC,MAAM,CAA+C,CAAA;AAE5E;;;;GAIG;AACH,wBAAsB,KAAK,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAMvD"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAGH,OAAO,CAAC,MAAM,0BAA0B,CAAA;AACxC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAYrE,sEAAsE;AACtE,MAAM,CAAC,MAAM,IAAI,GAAG,WAAW,CAAA;AAC/B,2EAA2E;AAC3E,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,aAAa,EAAE,eAAe,CAAC,CAAA;AAKtD,MAAM,CAAC,MAAM,MAAM,GAAc,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,WAAW,CAAC,iBAAiB,CAAC,CAAA;AAE5E;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,KAAK,CAAC,GAAY;IACtC,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,aAAa,CAAC,IAAI,CAAC,cAAc,CAAC,CAAA;IAC3D,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC;QAClB,MAAM,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAA;QAC5C,MAAM,GAAG,CAAC,OAAO,CAAC,gBAAgB,EAAE,WAAW,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,CAAA;IAC/D,CAAC,EAAE,mBAAmB,CAAC,CAAA;AACzB,CAAC"}
@@ -0,0 +1,112 @@
1
+ /**
2
+ * The `telegram-store` implementation behind the plugin entry: the record shapes, the `im_telegram` storage domain,
3
+ * the credential keys and the service object the adapter injects.
4
+ *
5
+ * The package entry exports only what the Loader mounts (`name`, `inject`, `Config`, `apply`) and the types a consumer
6
+ * names, so these values stay in this module: the plugin's own tests import them from here
7
+ * ([package surface](../../../../docs/defensive-patterns/package-surface.md)).
8
+ *
9
+ * @module @deepseek-ai/dsh-im-telegram-store/store
10
+ */
11
+ import type { Context } from '@deepseek-ai/cordis';
12
+ import { type CredentialKey } from '@deepseek-ai/dsh-credentials';
13
+ import { type Domain } from '@deepseek-ai/dsh-storage-domain';
14
+ import * as zod from 'zod';
15
+ /** This package's registered name: the plugin name and the scope of the credential records it writes. */
16
+ export declare const PLUGIN_NAME = "im-telegram-store";
17
+ declare const grantSchema: zod.ZodObject<{
18
+ v: zod.ZodLiteral<1>;
19
+ keys: zod.ZodRecord<zod.ZodString, zod.ZodString>;
20
+ kv: zod.ZodRecord<zod.ZodString, zod.ZodString>;
21
+ }, zod.z.core.$strip>;
22
+ declare const cursorsSchema: zod.ZodRecord<zod.ZodString, zod.ZodNumber>;
23
+ declare const peersSchema: zod.ZodRecord<zod.ZodString, zod.ZodObject<{
24
+ id: zod.ZodNumber;
25
+ accessHash: zod.ZodString;
26
+ isMin: zod.ZodBoolean;
27
+ usernames: zod.ZodArray<zod.ZodString>;
28
+ updated: zod.ZodNumber;
29
+ phone: zod.ZodExactOptional<zod.ZodString>;
30
+ complete: zod.ZodString;
31
+ }, zod.z.core.$strip>>;
32
+ declare const callbacksSchema: zod.ZodRecord<zod.ZodString, zod.ZodObject<{
33
+ id: zod.ZodString;
34
+ data: zod.ZodExactOptional<zod.ZodString>;
35
+ time: zod.ZodNumber;
36
+ }, zod.z.core.$strip>>;
37
+ /**
38
+ * One account's secret session facts: the Telegram adapter's grant record, `v: 1`.
39
+ *
40
+ * Declared here rather than imported from the adapter package: a `packages/**` module reaches a platform only
41
+ * through the Satori contracts (`packages/experimental/im/tests/boundaries.spec.ts`), and the two declarations are
42
+ * checked against each other in the tests.
43
+ */
44
+ export type TelegramGrant = zod.infer<typeof grantSchema>;
45
+ /** One cached peer (the adapter's `TelegramPeerRecord`). */
46
+ export type TelegramPeerRecord = zod.infer<typeof peersSchema>[string];
47
+ /** One long button callback (the adapter's `TelegramCallbackRecord`). */
48
+ export type TelegramCallbackRecord = zod.infer<typeof callbacksSchema>[string];
49
+ /** The persisted tables of one account (the adapter's `TelegramStateTables`). */
50
+ export interface TelegramStateTables {
51
+ cursors: zod.infer<typeof cursorsSchema>;
52
+ peers: zod.infer<typeof peersSchema>;
53
+ callbacks: zod.infer<typeof callbacksSchema>;
54
+ }
55
+ /** One table name of {@link TelegramStateTables}. */
56
+ export type TelegramStateTable = keyof TelegramStateTables;
57
+ /** The `telegram-store` service the adapter injects (same shape as its `TelegramStore`). */
58
+ export interface TelegramStore {
59
+ /** @param account - the configured bot id. @returns the stored grant, or `undefined` when none is stored. */
60
+ readGrant(account: string): Promise<TelegramGrant | undefined>;
61
+ /** @param account - the configured bot id. @param grant - the new grant, `undefined` to delete it. */
62
+ writeGrant(account: string, grant: TelegramGrant | undefined): Promise<void>;
63
+ /** @param account - the configured bot id. @param table - the table to read. @returns its stored content. */
64
+ readState<T extends TelegramStateTable>(account: string, table: T): Promise<TelegramStateTables[T] | undefined>;
65
+ /** @param account - the configured bot id. @param table - the table to write. @param value - its new content. */
66
+ writeState<T extends TelegramStateTable>(account: string, table: T, value: TelegramStateTables[T]): Promise<void>;
67
+ }
68
+ /**
69
+ * The `im_telegram` storage domain: one record per account (keyed by the adapter's bot id) in each table.
70
+ */
71
+ export declare const telegramDomain: {
72
+ name: string;
73
+ version: number;
74
+ invalidRecords: "backup-and-skip";
75
+ tables: {
76
+ cursors: import("@deepseek-ai/dsh-storage-domain").DomainTableSpec<string, Record<string, number>>;
77
+ peers: import("@deepseek-ai/dsh-storage-domain").DomainTableSpec<string, Record<string, {
78
+ id: number;
79
+ accessHash: string;
80
+ isMin: boolean;
81
+ usernames: string[];
82
+ updated: number;
83
+ complete: string;
84
+ phone?: string;
85
+ }>>;
86
+ callbacks: import("@deepseek-ai/dsh-storage-domain").DomainTableSpec<string, Record<string, {
87
+ id: string;
88
+ time: number;
89
+ data?: string;
90
+ }>>;
91
+ };
92
+ };
93
+ /** The open `im_telegram` domain. */
94
+ export type TelegramDomain = Domain<typeof telegramDomain>;
95
+ /**
96
+ * The credential key of an account's grant.
97
+ *
98
+ * @param account - the adapter's bot id: `telegram:<id>` or `telegram:user:<id>`.
99
+ * @returns the record key `im-telegram-store/bot-<id>` or `im-telegram-store/user-<id>`.
100
+ * @throws TypeError for a bot id of another form.
101
+ */
102
+ export declare function grantKey(account: string): CredentialKey;
103
+ /**
104
+ * The store over an open domain and the credential service.
105
+ *
106
+ * @param ctx - a context carrying `credentials`.
107
+ * @param domain - the open `im_telegram` domain.
108
+ * @returns the `telegram-store` implementation.
109
+ */
110
+ export declare function createStore(ctx: Context, domain: TelegramDomain): TelegramStore;
111
+ export {};
112
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,KAAK,aAAa,EAAiB,MAAM,8BAA8B,CAAA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YAC7B,IAAI,CAAC,KAAK,EAAE,CAAC;gBACX,MAAM,GAAG,CAAC,WAAW,CAAC,YAAY,CAAC,GAAG,CAAC,CAAA;gBACvC,OAAM;YACR,CAAC;YACD,MAAM,GAAG,CAAC,WAAW,CAAC,YAAY,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC,CAAA;QACnG,CAAC;QACD,SAAS,CAA+B,OAAe,EAAE,KAAQ;YAC/D,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAA6D,CAAA;YAC9F,OAAO,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAA;QAC7C,CAAC;QACD,KAAK,CAAC,UAAU,CAA+B,OAAe,EAAE,KAAQ,EAAE,KAA6B;YACrG,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAuE,CAAA;YACxG,MAAM,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;QAClC,CAAC;KACF,CAAA;AACH,CAAC"}
package/locale/de.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Telegram-Sitzungsspeicher",
4
+ "description": "Speichert die Autorisierungsschlüssel von Telegram-IM-Konten als Anmeldedaten und ihre Update-Cursor und Caches lokal, damit ein Neustart keine erneute Anmeldung erfordert."
5
+ }
6
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Telegram session storage",
4
+ "description": "Keep the authorization keys of Telegram IM accounts as credential records and their update cursors and caches in local storage, so a restart does not log in again."
5
+ }
6
+ }
package/locale/es.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Almacenamiento de sesiones de Telegram",
4
+ "description": "Guarda las claves de autorización de las cuentas de Telegram como credenciales y sus cursores de actualización y cachés en el almacenamiento local, para que un reinicio no vuelva a iniciar sesión."
5
+ }
6
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Stockage des sessions Telegram",
4
+ "description": "Conserve les clés d'autorisation des comptes Telegram comme identifiants, et leurs curseurs de mise à jour et caches en stockage local, pour qu'un redémarrage ne reconnecte pas le compte."
5
+ }
6
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Telegram セッションストレージ",
4
+ "description": "Telegram IM アカウントの認可キーを認証情報レコードとして、更新カーソルとキャッシュをローカルストレージに保存し、再起動時に再ログインしないようにします。"
5
+ }
6
+ }
package/locale/pt.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Armazenamento de sessões do Telegram",
4
+ "description": "Guarda as chaves de autorização das contas do Telegram como credenciais e os cursores de atualização e caches no armazenamento local, para que um reinício não faça login novamente."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Хранилище сеансов Telegram",
4
+ "description": "Хранит ключи авторизации аккаунтов Telegram как учётные данные, а курсоры обновлений и кэши — в локальном хранилище, чтобы после перезапуска не входить заново."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Telegram 会话存储",
4
+ "description": "把 Telegram IM 账号的授权密钥存为凭据记录,把更新游标和缓存存入本地存储,重启后无需重新登录。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@deepseek-ai/dsh-im-telegram-store",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Durable session storage of the Telegram IM adapter: authorization keys as credential records, update cursors and caches in a storage domain",
4
+ "version": "0.2.3-alpha.4",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
11
+ "directory": "packages/experimental/im-telegram-store"
12
+ },
13
+ "type": "module",
14
+ "main": "lib/index.js",
15
+ "types": "lib/types/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./lib/types/index.d.ts",
19
+ "default": "./lib/index.js"
20
+ },
21
+ "./src/*": "./src/*",
22
+ "./locale/*.json": "./locale/*.json",
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "locale/*.json",
27
+ "lib/index.js",
28
+ "lib/types/**/*.d.ts",
29
+ "lib/types/**/*.d.ts.map",
30
+ "lib/**/*.js.map",
31
+ "src"
32
+ ],
33
+ "license": "MIT",
34
+ "peerDependencies": {
35
+ "@deepseek-ai/cordis": "~4.2.0-alpha.3",
36
+ "@deepseek-ai/dsh-credentials": "0.2.3-alpha.4",
37
+ "@deepseek-ai/dsh-storage-domain": "0.2.3-alpha.4"
38
+ },
39
+ "devDependencies": {
40
+ "@deepseek-ai/cordis": "~4.2.0-alpha.3",
41
+ "@deepseek-ai/cordis-plugin-im-adapter-telegram": "~4.0.1-alpha.3",
42
+ "@deepseek-ai/dsh-credentials": "0.2.3-alpha.4",
43
+ "@deepseek-ai/dsh-credentials-local": "0.2.3-alpha.4",
44
+ "@deepseek-ai/dsh-storage": "0.2.3-alpha.4",
45
+ "@deepseek-ai/dsh-storage-domain": "0.2.3-alpha.4",
46
+ "@deepseek-ai/dsh-storage-json": "0.2.3-alpha.4"
47
+ },
48
+ "dependencies": {
49
+ "@deepseek-ai/schemastery": "~3.20.0-alpha.3",
50
+ "zod": "4.6.6"
51
+ }
6
52
  }
package/src/index.ts ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The `telegram-store` service of the Telegram IM adapter over dsh's own durable storage.
3
+ *
4
+ * What a Telegram account must keep across restarts splits by what losing it means:
5
+ *
6
+ * - The **grant** — the account's authorization keys per data center and the session facts that belong to them — is a
7
+ * secret whose loss means logging in again. It is one credential record per account (`ctx.credentials`, scope
8
+ * `im-telegram-store`, id `bot-<id>` / `user-<id>`), written through `modifyRecord` before the adapter uses a new
9
+ * key, and validated when read back.
10
+ * - The **state** — update cursors, the peer cache and the long-callback table — is rebuilt by the platform when lost.
11
+ * It lives in the `im_telegram` storage domain, one record per account in each of the tables `cursors`, `peers`
12
+ * and `callbacks`.
13
+ *
14
+ * The entry mounts the plugin; the record shapes, the domain, the credential keys and the service object live in
15
+ * [`./store.ts`](./store.ts), which the tests read directly.
16
+ *
17
+ * @module @deepseek-ai/dsh-im-telegram-store
18
+ */
19
+
20
+ import type { Context } from '@deepseek-ai/cordis'
21
+ import z from '@deepseek-ai/schemastery'
22
+ import { createStore, PLUGIN_NAME, telegramDomain } from './store.ts'
23
+
24
+ export type {
25
+ TelegramCallbackRecord,
26
+ TelegramDomain,
27
+ TelegramGrant,
28
+ TelegramPeerRecord,
29
+ TelegramStateTable,
30
+ TelegramStateTables,
31
+ TelegramStore,
32
+ } from './store.ts'
33
+
34
+ /** Scope of the credential records: this plugin's registered name. */
35
+ export const name = PLUGIN_NAME
36
+ /** The credential seam holds the grants, the domain facility the state. */
37
+ export const inject = ['credentials', 'storageDomain']
38
+
39
+ /** The plugin takes no configuration. */
40
+ export interface Config {}
41
+
42
+ export const Config: z<Config> = z.object({}).description('Telegram 账号会话存储')
43
+
44
+ /**
45
+ * Open the domain and provide `telegram-store`; the domain closes with the plugin.
46
+ *
47
+ * @param ctx - context carrying `credentials` and `storageDomain`.
48
+ */
49
+ export async function apply(ctx: Context): Promise<void> {
50
+ const domain = await ctx.storageDomain.open(telegramDomain)
51
+ ctx.effect(function* () {
52
+ yield ctx.effect(() => () => domain.close())
53
+ yield ctx.provide('telegram-store', createStore(ctx, domain))
54
+ }, 'im-telegram-store')
55
+ }
package/src/store.ts ADDED
@@ -0,0 +1,146 @@
1
+ /**
2
+ * The `telegram-store` implementation behind the plugin entry: the record shapes, the `im_telegram` storage domain,
3
+ * the credential keys and the service object the adapter injects.
4
+ *
5
+ * The package entry exports only what the Loader mounts (`name`, `inject`, `Config`, `apply`) and the types a consumer
6
+ * names, so these values stay in this module: the plugin's own tests import them from here
7
+ * ([package surface](../../../../docs/defensive-patterns/package-surface.md)).
8
+ *
9
+ * @module @deepseek-ai/dsh-im-telegram-store/store
10
+ */
11
+
12
+ import type { Context } from '@deepseek-ai/cordis'
13
+ import { type CredentialKey, credentialKey } from '@deepseek-ai/dsh-credentials'
14
+ import { defineDomain, type Domain, domainTable } from '@deepseek-ai/dsh-storage-domain'
15
+ import * as zod from 'zod'
16
+
17
+ /** This package's registered name: the plugin name and the scope of the credential records it writes. */
18
+ export const PLUGIN_NAME = 'im-telegram-store'
19
+
20
+ const grantSchema = zod.object({
21
+ v: zod.literal(1),
22
+ keys: zod.record(zod.string(), zod.string()),
23
+ kv: zod.record(zod.string(), zod.string()),
24
+ })
25
+
26
+ const cursorsSchema = zod.record(zod.string(), zod.number().int())
27
+ const peersSchema = zod.record(zod.string(), zod.object({
28
+ id: zod.number(),
29
+ accessHash: zod.string(),
30
+ isMin: zod.boolean(),
31
+ usernames: zod.array(zod.string()),
32
+ updated: zod.number(),
33
+ phone: zod.exactOptional(zod.string()),
34
+ complete: zod.string(),
35
+ }))
36
+ const callbacksSchema = zod.record(zod.string(), zod.object({
37
+ id: zod.string(),
38
+ data: zod.exactOptional(zod.string()),
39
+ time: zod.number(),
40
+ }))
41
+
42
+ /**
43
+ * One account's secret session facts: the Telegram adapter's grant record, `v: 1`.
44
+ *
45
+ * Declared here rather than imported from the adapter package: a `packages/**` module reaches a platform only
46
+ * through the Satori contracts (`packages/experimental/im/tests/boundaries.spec.ts`), and the two declarations are
47
+ * checked against each other in the tests.
48
+ */
49
+ export type TelegramGrant = zod.infer<typeof grantSchema>
50
+ /** One cached peer (the adapter's `TelegramPeerRecord`). */
51
+ export type TelegramPeerRecord = zod.infer<typeof peersSchema>[string]
52
+ /** One long button callback (the adapter's `TelegramCallbackRecord`). */
53
+ export type TelegramCallbackRecord = zod.infer<typeof callbacksSchema>[string]
54
+
55
+ /** The persisted tables of one account (the adapter's `TelegramStateTables`). */
56
+ export interface TelegramStateTables {
57
+ cursors: zod.infer<typeof cursorsSchema>
58
+ peers: zod.infer<typeof peersSchema>
59
+ callbacks: zod.infer<typeof callbacksSchema>
60
+ }
61
+
62
+ /** One table name of {@link TelegramStateTables}. */
63
+ export type TelegramStateTable = keyof TelegramStateTables
64
+
65
+ /** The `telegram-store` service the adapter injects (same shape as its `TelegramStore`). */
66
+ export interface TelegramStore {
67
+ /** @param account - the configured bot id. @returns the stored grant, or `undefined` when none is stored. */
68
+ readGrant(account: string): Promise<TelegramGrant | undefined>
69
+ /** @param account - the configured bot id. @param grant - the new grant, `undefined` to delete it. */
70
+ writeGrant(account: string, grant: TelegramGrant | undefined): Promise<void>
71
+ /** @param account - the configured bot id. @param table - the table to read. @returns its stored content. */
72
+ readState<T extends TelegramStateTable>(account: string, table: T): Promise<TelegramStateTables[T] | undefined>
73
+ /** @param account - the configured bot id. @param table - the table to write. @param value - its new content. */
74
+ writeState<T extends TelegramStateTable>(account: string, table: T, value: TelegramStateTables[T]): Promise<void>
75
+ }
76
+
77
+ /**
78
+ * The `im_telegram` storage domain: one record per account (keyed by the adapter's bot id) in each table.
79
+ */
80
+ export const telegramDomain = defineDomain({
81
+ name: 'im_telegram',
82
+ version: 1,
83
+ // Every record is rebuilt by the platform when lost: an unreadable one is set aside rather than failing the open.
84
+ invalidRecords: 'backup-and-skip',
85
+ tables: {
86
+ cursors: domainTable<string, TelegramStateTables['cursors']>(cursorsSchema),
87
+ peers: domainTable<string, TelegramStateTables['peers']>(peersSchema),
88
+ callbacks: domainTable<string, TelegramStateTables['callbacks']>(callbacksSchema),
89
+ },
90
+ })
91
+
92
+ /** The open `im_telegram` domain. */
93
+ export type TelegramDomain = Domain<typeof telegramDomain>
94
+
95
+ /**
96
+ * The credential key of an account's grant.
97
+ *
98
+ * @param account - the adapter's bot id: `telegram:<id>` or `telegram:user:<id>`.
99
+ * @returns the record key `im-telegram-store/bot-<id>` or `im-telegram-store/user-<id>`.
100
+ * @throws TypeError for a bot id of another form.
101
+ */
102
+ export function grantKey(account: string): CredentialKey {
103
+ const match = /^telegram:(user:)?(\d+)$/.exec(account)
104
+ if (!match) throw new TypeError(`im-telegram-store: "${account}" is not a Telegram bot id`)
105
+ return credentialKey(PLUGIN_NAME, `${match[1] ? 'user' : 'bot'}-${match[2]}`)
106
+ }
107
+
108
+ /**
109
+ * The store over an open domain and the credential service.
110
+ *
111
+ * @param ctx - a context carrying `credentials`.
112
+ * @param domain - the open `im_telegram` domain.
113
+ * @returns the `telegram-store` implementation.
114
+ */
115
+ export function createStore(ctx: Context, domain: TelegramDomain): TelegramStore {
116
+ return {
117
+ async readGrant(account) {
118
+ const record = await ctx.credentials.readRecord(grantKey(account))
119
+ if (!record) return undefined
120
+ // A record of another shape is not a grant this adapter wrote: logging in again replaces it.
121
+ if (record.kind !== 'grant') return undefined
122
+ const parsed = grantSchema.safeParse(record.payload)
123
+ if (!parsed.success) {
124
+ ctx.logger.warn('im-telegram-store: the stored grant of %s is malformed and is ignored', account)
125
+ return undefined
126
+ }
127
+ return parsed.data
128
+ },
129
+ async writeGrant(account, grant) {
130
+ const key = grantKey(account)
131
+ if (!grant) {
132
+ await ctx.credentials.deleteRecord(key)
133
+ return
134
+ }
135
+ await ctx.credentials.modifyRecord(key, () => Promise.resolve({ kind: 'grant', payload: grant }))
136
+ },
137
+ readState<T extends TelegramStateTable>(account: string, table: T): Promise<TelegramStateTables[T] | undefined> {
138
+ const target = domain.table(table) as { get(key: string): TelegramStateTables[T] | undefined }
139
+ return Promise.resolve(target.get(account))
140
+ },
141
+ async writeState<T extends TelegramStateTable>(account: string, table: T, value: TelegramStateTables[T]): Promise<void> {
142
+ const target = domain.table(table) as { put(key: string, entry: TelegramStateTables[T]): Promise<void> }
143
+ await target.put(account, value)
144
+ },
145
+ }
146
+ }