@operad-io/telegram 0.0.0-stage → 0.1.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/src/state.ts ADDED
@@ -0,0 +1,205 @@
1
+ /**
2
+ * The plugin's own state file, `<home>/telegram/state.json`. It holds how far
3
+ * `getUpdates` has been read; dedupe never depends on it, only the next request
4
+ * does, so a process killed before the file is written reads the update again
5
+ * and the event key keeps it one.
6
+ */
7
+
8
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
9
+ import { dirname, join } from "node:path";
10
+ import { isRecord } from "@operad-io/engine";
11
+
12
+ /** The directory the plugin keeps its own files in. */
13
+ export function telegramStateDirectory(home: string): string {
14
+ return join(home, "telegram");
15
+ }
16
+
17
+ /** The file the next `getUpdates` offset is in. */
18
+ export function telegramStatePath(home: string): string {
19
+ return join(telegramStateDirectory(home), "state.json");
20
+ }
21
+
22
+ /** The recorded offset; 0 when the file is missing or unusable. */
23
+ export function readOffset(home: string): number {
24
+ let parsed: unknown;
25
+ try {
26
+ parsed = JSON.parse(readFileSync(telegramStatePath(home), "utf8"));
27
+ } catch {
28
+ return 0;
29
+ }
30
+ if (!isRecord(parsed)) return 0;
31
+ const offset = parsed.offset;
32
+ return typeof offset === "number" && Number.isInteger(offset) && offset >= 0 ? offset : 0;
33
+ }
34
+
35
+ /** Records the next offset and the time it was written. */
36
+ export function writeOffset(home: string, offset: number, at: number): void {
37
+ const path = telegramStatePath(home);
38
+ mkdirSync(dirname(path), { recursive: true });
39
+ const temporary = `${path}.${process.pid}.tmp`;
40
+ writeFileSync(temporary, `${JSON.stringify({ offset, at })}\n`, "utf8");
41
+ renameSync(temporary, path);
42
+ }
43
+
44
+ /** What was sent of one assistant message. */
45
+ export interface SentRecord {
46
+ /** How many chunks of the message reached Telegram. */
47
+ readonly chunks: number;
48
+ /** The Telegram `message_id` of the last chunk sent. */
49
+ readonly telegramId?: number | undefined;
50
+ /** The whole message is sent. */
51
+ readonly done: boolean;
52
+ /** Sending gave up; the chat's history says so. */
53
+ readonly failed?: true | undefined;
54
+ }
55
+
56
+ /** What the reply side remembers: since when it counts, and what it sent. */
57
+ export interface SentState {
58
+ /** Epoch milliseconds the reply side first ran; older messages are not new. */
59
+ readonly since: number;
60
+ readonly sent: Readonly<Record<string, SentRecord>>;
61
+ }
62
+
63
+ /** The file the sent messages are recorded in. */
64
+ export function telegramSentPath(home: string): string {
65
+ return join(telegramStateDirectory(home), "sent.json");
66
+ }
67
+
68
+ function recordOf(value: unknown): SentRecord | undefined {
69
+ if (!isRecord(value) || typeof value.chunks !== "number" || typeof value.done !== "boolean") return undefined;
70
+ return {
71
+ chunks: value.chunks,
72
+ done: value.done,
73
+ ...(typeof value.telegramId === "number" ? { telegramId: value.telegramId } : {}),
74
+ ...(value.failed === true ? { failed: true as const } : {}),
75
+ };
76
+ }
77
+
78
+ /** The recorded sends; `undefined` when the file is missing or unusable. */
79
+ export function readSent(home: string): SentState | undefined {
80
+ let parsed: unknown;
81
+ try {
82
+ parsed = JSON.parse(readFileSync(telegramSentPath(home), "utf8"));
83
+ } catch {
84
+ return undefined;
85
+ }
86
+ if (!isRecord(parsed) || typeof parsed.since !== "number" || !isRecord(parsed.sent)) return undefined;
87
+ const sent: Record<string, SentRecord> = {};
88
+ for (const [key, value] of Object.entries(parsed.sent)) {
89
+ const record = recordOf(value);
90
+ if (record !== undefined) sent[key] = record;
91
+ }
92
+ return { since: parsed.since, sent };
93
+ }
94
+
95
+ /** Records the sends, replacing the file whole. */
96
+ export function writeSent(home: string, state: SentState): void {
97
+ const path = telegramSentPath(home);
98
+ mkdirSync(dirname(path), { recursive: true });
99
+ const temporary = `${path}.${process.pid}.tmp`;
100
+ writeFileSync(temporary, `${JSON.stringify(state)}\n`, "utf8");
101
+ renameSync(temporary, path);
102
+ }
103
+
104
+ /** One thing a message of the pending side offers. */
105
+ export interface SentOption {
106
+ /** The words on the button, and in "answered: X". */
107
+ readonly label: string;
108
+ /** `act` runs an action, `choice` answers one of the question's choices, `free` takes any text. */
109
+ readonly how: "act" | "choice" | "free";
110
+ /** The action's `<plugin>:<action>` for `act`. */
111
+ readonly action?: string | undefined;
112
+ /** The action needs a note, so it is answered by replying. */
113
+ readonly note?: true | undefined;
114
+ }
115
+
116
+ /** One pending item as it was sent to one Telegram chat. */
117
+ export interface SentItem {
118
+ readonly runId: string;
119
+ readonly waitId?: string | undefined;
120
+ /** The object the item is about, as `type:id`. */
121
+ readonly object?: string | undefined;
122
+ readonly chatId: number;
123
+ readonly messageId: number;
124
+ /** The text as sent; "answered: X" is added to it. */
125
+ readonly text: string;
126
+ readonly options: readonly SentOption[];
127
+ /** When it was sent, epoch milliseconds. */
128
+ readonly at: number;
129
+ /** The words the item was answered with; set once the message was changed. */
130
+ readonly answered?: string | undefined;
131
+ }
132
+
133
+ /** What the pending side remembers, by the item and Telegram chat it was sent to. */
134
+ export type PendingState = Readonly<Record<string, SentItem>>;
135
+
136
+ /** The file the sent pending items are recorded in. */
137
+ export function telegramPendingPath(home: string): string {
138
+ return join(telegramStateDirectory(home), "pending.json");
139
+ }
140
+
141
+ function optionOf(value: unknown): SentOption | undefined {
142
+ if (!isRecord(value) || typeof value.label !== "string") return undefined;
143
+ if (value.how !== "act" && value.how !== "choice" && value.how !== "free") return undefined;
144
+ return {
145
+ label: value.label,
146
+ how: value.how,
147
+ ...(typeof value.action === "string" ? { action: value.action } : {}),
148
+ ...(value.note === true ? { note: true as const } : {}),
149
+ };
150
+ }
151
+
152
+ function itemOf(value: unknown): SentItem | undefined {
153
+ if (
154
+ !isRecord(value) ||
155
+ typeof value.runId !== "string" ||
156
+ typeof value.chatId !== "number" ||
157
+ typeof value.messageId !== "number" ||
158
+ typeof value.text !== "string" ||
159
+ typeof value.at !== "number" ||
160
+ !Array.isArray(value.options)
161
+ ) {
162
+ return undefined;
163
+ }
164
+ const options = value.options.flatMap((entry: unknown) => {
165
+ const option = optionOf(entry);
166
+ return option === undefined ? [] : [option];
167
+ });
168
+ return {
169
+ runId: value.runId,
170
+ chatId: value.chatId,
171
+ messageId: value.messageId,
172
+ text: value.text,
173
+ at: value.at,
174
+ options,
175
+ ...(typeof value.waitId === "string" ? { waitId: value.waitId } : {}),
176
+ ...(typeof value.object === "string" ? { object: value.object } : {}),
177
+ ...(typeof value.answered === "string" ? { answered: value.answered } : {}),
178
+ };
179
+ }
180
+
181
+ /** The recorded pending sends; empty when the file is missing or unusable. */
182
+ export function readPending(home: string): PendingState {
183
+ let parsed: unknown;
184
+ try {
185
+ parsed = JSON.parse(readFileSync(telegramPendingPath(home), "utf8"));
186
+ } catch {
187
+ return {};
188
+ }
189
+ if (!isRecord(parsed)) return {};
190
+ const items: Record<string, SentItem> = {};
191
+ for (const [key, value] of Object.entries(parsed)) {
192
+ const item = itemOf(value);
193
+ if (item !== undefined) items[key] = item;
194
+ }
195
+ return items;
196
+ }
197
+
198
+ /** Records the pending sends, replacing the file whole. */
199
+ export function writePending(home: string, state: PendingState): void {
200
+ const path = telegramPendingPath(home);
201
+ mkdirSync(dirname(path), { recursive: true });
202
+ const temporary = `${path}.${process.pid}.tmp`;
203
+ writeFileSync(temporary, `${JSON.stringify(state)}\n`, "utf8");
204
+ renameSync(temporary, path);
205
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://operad.io/schemas/telegram.schema.json",
4
+ "title": "telegram",
5
+ "description": "The telegram plugin's settings: who may write, which bot opens a chat, and which plugins' pending items are also sent.",
6
+ "type": "object",
7
+ "properties": {
8
+ "users": {
9
+ "type": "array",
10
+ "items": { "type": "integer", "minimum": 1 },
11
+ "default": [],
12
+ "description": "The Telegram user ids whose private messages become chat messages. A message from anyone else is recorded and answered with nothing."
13
+ },
14
+ "bot": {
15
+ "type": "string",
16
+ "minLength": 1,
17
+ "default": "default",
18
+ "description": "The bot a chat is opened on when a listed user writes first."
19
+ },
20
+ "pending": {
21
+ "type": "array",
22
+ "items": { "type": "string", "minLength": 1 },
23
+ "default": [],
24
+ "description": "The plugins whose pending items are also sent to Telegram, such as [\"dev\"]. Items of a chat bound to Telegram are always sent."
25
+ }
26
+ },
27
+ "additionalProperties": false
28
+ }