@aomex/logger-telegram 0.0.0-stage → 3.30.8-alpha.62.sha-92b25bb
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 +21 -0
- package/README.md +2 -2
- package/dist/index.d.ts +89 -0
- package/dist/index.js +178 -0
- package/dist/index.js.map +1 -0
- package/package.json +43 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023-2024 geekact
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @aomex/logger-telegram
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
文档:https://aomex.js.org
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { Api } from "grammy";
|
|
2
|
+
import { LogRecord, SerializedError, Transport } from "@aomex/logger";
|
|
3
|
+
export declare const TELEGRAM_MESSAGE_MAX_LENGTH = 4096;
|
|
4
|
+
/** 指纹中如何纳入 `bindings`:默认不纳入;`'all'` 为全部;数组为白名单键 */
|
|
5
|
+
type TelegramDedupeBindingKeys = 'all' | readonly string[];
|
|
6
|
+
interface TelegramDedupeOptions {
|
|
7
|
+
/**
|
|
8
|
+
* 合并间隔(毫秒)。默认 `30_000`。
|
|
9
|
+
* 间隔内相同指纹只发一条,正文带 `(×N)`。
|
|
10
|
+
*/
|
|
11
|
+
interval?: number;
|
|
12
|
+
/**
|
|
13
|
+
* 纳入指纹的 bindings。默认不纳入(只按 `level` / `message` / `exception`),
|
|
14
|
+
* 避免业务侧关联字段拆散合并;需要时自行传 `'all'` 或键名白名单。
|
|
15
|
+
*/
|
|
16
|
+
bindingKeys?: TelegramDedupeBindingKeys;
|
|
17
|
+
/** 自定义指纹;默认走 `fingerprintLog` */
|
|
18
|
+
fingerprint?: (log: LogRecord) => string;
|
|
19
|
+
}
|
|
20
|
+
interface TelegramTransportOptions {
|
|
21
|
+
/** Bot token(来自 @BotFather) */
|
|
22
|
+
botToken: string;
|
|
23
|
+
/** 目标 chat / 群 / 频道 id */
|
|
24
|
+
chatId: string | number;
|
|
25
|
+
/**
|
|
26
|
+
* 请求总超时(毫秒,含 auto-retry 等待)。默认 `120_000`。
|
|
27
|
+
*/
|
|
28
|
+
timeout?: number;
|
|
29
|
+
/** 自定义消息正文;默认 `formatTelegramMessage` */
|
|
30
|
+
format?: (log: LogRecord) => string;
|
|
31
|
+
/**
|
|
32
|
+
* 间隔内相同指纹合并为一条后再发送。默认开启(间隔 30s,指纹不含 bindings)。
|
|
33
|
+
* 传 `false` 则每条立即发送。
|
|
34
|
+
*/
|
|
35
|
+
dedupe?: boolean | TelegramDedupeOptions;
|
|
36
|
+
}
|
|
37
|
+
type TelegramDedupeConfig = {
|
|
38
|
+
interval: number;
|
|
39
|
+
bindingKeys?: TelegramDedupeBindingKeys;
|
|
40
|
+
fingerprint?: (log: LogRecord) => string;
|
|
41
|
+
};
|
|
42
|
+
type DedupeBufferEntry = {
|
|
43
|
+
log: LogRecord;
|
|
44
|
+
count: number;
|
|
45
|
+
timer: ReturnType<typeof setTimeout>;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* 通过 [grammy](https://grammy.dev) `Api.sendMessage` 推送日志,
|
|
49
|
+
* 固定启用 [`@grammyjs/auto-retry`](https://grammy.dev/plugins/auto-retry)。
|
|
50
|
+
*
|
|
51
|
+
* ```typescript
|
|
52
|
+
* new TelegramTransport({
|
|
53
|
+
* botToken: process.env.TELEGRAM_BOT_TOKEN!,
|
|
54
|
+
* chatId: process.env.TELEGRAM_CHAT_ID!,
|
|
55
|
+
* })
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
export declare class TelegramTransport extends Transport {
|
|
59
|
+
protected readonly chatId: string | number;
|
|
60
|
+
protected readonly timeout: number;
|
|
61
|
+
protected readonly api: Api;
|
|
62
|
+
protected readonly customFormat?: (log: LogRecord) => string;
|
|
63
|
+
protected readonly dedupe: TelegramDedupeConfig | false;
|
|
64
|
+
protected readonly pending: Set<Promise<void>>;
|
|
65
|
+
protected readonly buffer: Map<string, DedupeBufferEntry>;
|
|
66
|
+
constructor(opts: TelegramTransportOptions);
|
|
67
|
+
consume(log: LogRecord): Promise<void>;
|
|
68
|
+
flush(): Promise<void>;
|
|
69
|
+
protected resolveDedupe(dedupe: boolean | TelegramDedupeOptions | undefined): TelegramDedupeConfig | false;
|
|
70
|
+
/** 组装待发送正文(自定义 `format` 优先) */
|
|
71
|
+
protected formatMessage(log: LogRecord): string;
|
|
72
|
+
/** 默认消息模板;子类可 override */
|
|
73
|
+
protected formatTelegramMessage(log: LogRecord): string;
|
|
74
|
+
protected formatBufferedMessage(log: LogRecord, count: number): string;
|
|
75
|
+
/** 解析最终指纹(自定义 `fingerprint` 优先) */
|
|
76
|
+
protected fingerprint(log: LogRecord): string;
|
|
77
|
+
/**
|
|
78
|
+
* 默认指纹:`level` + `message` + `exception`;
|
|
79
|
+
* 传入 `bindingKeys` 时再附加对应 bindings。
|
|
80
|
+
*/
|
|
81
|
+
protected fingerprintLog(log: LogRecord, bindingKeys?: TelegramDedupeBindingKeys): string;
|
|
82
|
+
protected fingerprintException(exception: SerializedError): unknown;
|
|
83
|
+
protected pickBindingsForFingerprint(bindings: Record<string, unknown>, bindingKeys: TelegramDedupeBindingKeys | undefined): Record<string, unknown> | undefined;
|
|
84
|
+
protected enqueue(log: LogRecord): void;
|
|
85
|
+
protected flushBuffer(): Promise<void>;
|
|
86
|
+
protected flushFingerprint(fp: string): Promise<void>;
|
|
87
|
+
protected sendText(text: string): Promise<void>;
|
|
88
|
+
}
|
|
89
|
+
export type { TelegramDedupeBindingKeys, TelegramDedupeOptions, TelegramTransportOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { Api } from "grammy";
|
|
2
|
+
import { autoRetry } from "@grammyjs/auto-retry";
|
|
3
|
+
import { Transport } from "@aomex/logger";
|
|
4
|
+
import { I18n, createI18n } from "@aomex/common";
|
|
5
|
+
// src/i18n/locales/zh-cn.ts
|
|
6
|
+
const zh = I18n.define({ send_message_timed_out: "Telegram 发送消息超时" });
|
|
7
|
+
// src/i18n/locales/en-us.ts
|
|
8
|
+
const en = I18n.satisfies(zh).define({ send_message_timed_out: "Telegram message send timed out" });
|
|
9
|
+
// src/i18n/index.ts
|
|
10
|
+
const i18n = createI18n({
|
|
11
|
+
zh,
|
|
12
|
+
en,
|
|
13
|
+
load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href)
|
|
14
|
+
});
|
|
15
|
+
// src/telegram-transport.ts
|
|
16
|
+
const TELEGRAM_MESSAGE_MAX_LENGTH = 4096;
|
|
17
|
+
/**
|
|
18
|
+
* 通过 [grammy](https://grammy.dev) `Api.sendMessage` 推送日志,
|
|
19
|
+
* 固定启用 [`@grammyjs/auto-retry`](https://grammy.dev/plugins/auto-retry)。
|
|
20
|
+
*
|
|
21
|
+
* ```typescript
|
|
22
|
+
* new TelegramTransport({
|
|
23
|
+
* botToken: process.env.TELEGRAM_BOT_TOKEN!,
|
|
24
|
+
* chatId: process.env.TELEGRAM_CHAT_ID!,
|
|
25
|
+
* })
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
var TelegramTransport = class extends Transport {
|
|
29
|
+
chatId;
|
|
30
|
+
timeout;
|
|
31
|
+
api;
|
|
32
|
+
customFormat;
|
|
33
|
+
dedupe;
|
|
34
|
+
pending = /* @__PURE__ */ new Set();
|
|
35
|
+
buffer = /* @__PURE__ */ new Map();
|
|
36
|
+
constructor(opts) {
|
|
37
|
+
super();
|
|
38
|
+
this.chatId = opts.chatId;
|
|
39
|
+
this.timeout = opts.timeout ?? 12e4;
|
|
40
|
+
this.customFormat = opts.format;
|
|
41
|
+
this.dedupe = this.resolveDedupe(opts.dedupe);
|
|
42
|
+
const api = new Api(opts.botToken);
|
|
43
|
+
api.config.use(autoRetry({
|
|
44
|
+
maxRetryAttempts: 3,
|
|
45
|
+
maxDelaySeconds: 60
|
|
46
|
+
}));
|
|
47
|
+
this.api = api;
|
|
48
|
+
}
|
|
49
|
+
async consume(log) {
|
|
50
|
+
if (this.dedupe) {
|
|
51
|
+
this.enqueue(log);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const task = this.sendText(this.formatMessage(log)).finally(() => {
|
|
55
|
+
this.pending.delete(task);
|
|
56
|
+
});
|
|
57
|
+
this.pending.add(task);
|
|
58
|
+
await task;
|
|
59
|
+
}
|
|
60
|
+
async flush() {
|
|
61
|
+
await this.flushBuffer();
|
|
62
|
+
await Promise.all([...this.pending]);
|
|
63
|
+
}
|
|
64
|
+
resolveDedupe(dedupe) {
|
|
65
|
+
if (dedupe === false) return false;
|
|
66
|
+
const opts = dedupe === true || dedupe == null ? {} : dedupe;
|
|
67
|
+
return {
|
|
68
|
+
interval: opts.interval ?? 3e4,
|
|
69
|
+
bindingKeys: opts.bindingKeys,
|
|
70
|
+
fingerprint: opts.fingerprint
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** 组装待发送正文(自定义 `format` 优先) */
|
|
74
|
+
formatMessage(log) {
|
|
75
|
+
return this.customFormat?.(log) ?? this.formatTelegramMessage(log);
|
|
76
|
+
}
|
|
77
|
+
/** 默认消息模板;子类可 override */
|
|
78
|
+
formatTelegramMessage(log) {
|
|
79
|
+
let text = `[${log.level}] ${log.timestamp.toISOString()}\n${log.message}`;
|
|
80
|
+
if (log.bindings) text += `\n${JSON.stringify(log.bindings)}`;
|
|
81
|
+
if (log.exception?.stack) text += `\n\n${log.exception.stack}`;
|
|
82
|
+
else if (log.exception) text += `\n\n${log.exception.type}: ${log.exception.message}`;
|
|
83
|
+
if (text.length <= 4096) return text;
|
|
84
|
+
return `${text.slice(0, 4095)}…`;
|
|
85
|
+
}
|
|
86
|
+
formatBufferedMessage(log, count) {
|
|
87
|
+
let text = this.formatMessage(log);
|
|
88
|
+
if (count > 1) text += `\n(×${count})`;
|
|
89
|
+
if (text.length <= 4096) return text;
|
|
90
|
+
return `${text.slice(0, 4095)}…`;
|
|
91
|
+
}
|
|
92
|
+
/** 解析最终指纹(自定义 `fingerprint` 优先) */
|
|
93
|
+
fingerprint(log) {
|
|
94
|
+
const dedupe = this.dedupe;
|
|
95
|
+
if (!dedupe) return this.fingerprintLog(log);
|
|
96
|
+
return dedupe.fingerprint?.(log) ?? this.fingerprintLog(log, dedupe.bindingKeys);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* 默认指纹:`level` + `message` + `exception`;
|
|
100
|
+
* 传入 `bindingKeys` 时再附加对应 bindings。
|
|
101
|
+
*/
|
|
102
|
+
fingerprintLog(log, bindingKeys) {
|
|
103
|
+
const parts = [log.level, log.message];
|
|
104
|
+
if (log.exception) parts.push(this.fingerprintException(log.exception));
|
|
105
|
+
if (log.bindings) {
|
|
106
|
+
const picked = this.pickBindingsForFingerprint(log.bindings, bindingKeys);
|
|
107
|
+
if (picked) parts.push(picked);
|
|
108
|
+
}
|
|
109
|
+
return JSON.stringify(parts);
|
|
110
|
+
}
|
|
111
|
+
fingerprintException(exception) {
|
|
112
|
+
return {
|
|
113
|
+
type: exception.type,
|
|
114
|
+
message: exception.message,
|
|
115
|
+
stack: exception.stack,
|
|
116
|
+
...exception.cause ? { cause: this.fingerprintException(exception.cause) } : {}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
pickBindingsForFingerprint(bindings, bindingKeys) {
|
|
120
|
+
if (bindingKeys == null) return void 0;
|
|
121
|
+
const filtered = {};
|
|
122
|
+
if (bindingKeys === "all") for (const key of Object.keys(bindings).sort()) filtered[key] = bindings[key];
|
|
123
|
+
else for (const key of [...bindingKeys].sort()) if (Object.hasOwn(bindings, key)) filtered[key] = bindings[key];
|
|
124
|
+
return Object.keys(filtered).length > 0 ? filtered : void 0;
|
|
125
|
+
}
|
|
126
|
+
enqueue(log) {
|
|
127
|
+
const dedupe = this.dedupe;
|
|
128
|
+
if (!dedupe) return;
|
|
129
|
+
const fp = this.fingerprint(log);
|
|
130
|
+
const existing = this.buffer.get(fp);
|
|
131
|
+
if (existing) {
|
|
132
|
+
existing.count += 1;
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const timer = setTimeout(() => {
|
|
136
|
+
this.flushFingerprint(fp).catch((err) => {
|
|
137
|
+
const detail = Error.isError(err) ? err.stack ?? err.message : String(err);
|
|
138
|
+
console.error(`[aomex/logger-telegram] dedupe flush failed: ${detail}`);
|
|
139
|
+
});
|
|
140
|
+
}, dedupe.interval);
|
|
141
|
+
timer.unref?.();
|
|
142
|
+
this.buffer.set(fp, {
|
|
143
|
+
log,
|
|
144
|
+
count: 1,
|
|
145
|
+
timer
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
async flushBuffer() {
|
|
149
|
+
const fingerprints = [...this.buffer.keys()];
|
|
150
|
+
await Promise.all(fingerprints.map((fp) => this.flushFingerprint(fp)));
|
|
151
|
+
}
|
|
152
|
+
async flushFingerprint(fp) {
|
|
153
|
+
const entry = this.buffer.get(fp);
|
|
154
|
+
if (!entry) return;
|
|
155
|
+
clearTimeout(entry.timer);
|
|
156
|
+
this.buffer.delete(fp);
|
|
157
|
+
const task = this.sendText(this.formatBufferedMessage(entry.log, entry.count)).finally(() => {
|
|
158
|
+
this.pending.delete(task);
|
|
159
|
+
});
|
|
160
|
+
this.pending.add(task);
|
|
161
|
+
await task;
|
|
162
|
+
}
|
|
163
|
+
async sendText(text) {
|
|
164
|
+
const controller = new AbortController();
|
|
165
|
+
const timer = setTimeout(() => controller.abort(), this.timeout);
|
|
166
|
+
try {
|
|
167
|
+
await this.api.sendMessage(this.chatId, text, { link_preview_options: { is_disabled: true } }, controller.signal);
|
|
168
|
+
} catch (err) {
|
|
169
|
+
if (Error.isError(err) && err.name === "AbortError") throw new Error(i18n.t("send_message_timed_out"));
|
|
170
|
+
throw err;
|
|
171
|
+
} finally {
|
|
172
|
+
clearTimeout(timer);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
export { TELEGRAM_MESSAGE_MAX_LENGTH, TelegramTransport };
|
|
177
|
+
|
|
178
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/i18n/locales/zh-cn.ts","../src/i18n/locales/en-us.ts","../src/i18n/index.ts","../src/telegram-transport.ts"],"sourcesContent":["import { I18n } from '@aomex/common';\n\nexport const zh = I18n.define({\n send_message_timed_out: 'Telegram 发送消息超时',\n});\n","import { I18n } from '@aomex/common';\nimport { zh } from './zh-cn';\n\nexport const en = I18n.satisfies(zh).define({\n send_message_timed_out: 'Telegram message send timed out',\n});\n","import { createI18n } from '@aomex/common';\nimport { zh } from './locales/zh-cn';\nimport { en } from './locales/en-us';\n\nexport const i18n = createI18n({\n zh,\n en,\n load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href),\n});\n","import { Api } from 'grammy';\nimport { autoRetry } from '@grammyjs/auto-retry';\nimport { Transport, type LogRecord, type SerializedError } from '@aomex/logger';\nimport { i18n } from './i18n';\n\nexport const TELEGRAM_MESSAGE_MAX_LENGTH = 4096;\n\n/** 指纹中如何纳入 `bindings`:默认不纳入;`'all'` 为全部;数组为白名单键 */\nexport type TelegramDedupeBindingKeys = 'all' | readonly string[];\n\nexport interface TelegramDedupeOptions {\n /**\n * 合并间隔(毫秒)。默认 `30_000`。\n * 间隔内相同指纹只发一条,正文带 `(×N)`。\n */\n interval?: number;\n /**\n * 纳入指纹的 bindings。默认不纳入(只按 `level` / `message` / `exception`),\n * 避免业务侧关联字段拆散合并;需要时自行传 `'all'` 或键名白名单。\n */\n bindingKeys?: TelegramDedupeBindingKeys;\n /** 自定义指纹;默认走 `fingerprintLog` */\n fingerprint?: (log: LogRecord) => string;\n}\n\nexport interface TelegramTransportOptions {\n /** Bot token(来自 @BotFather) */\n botToken: string;\n /** 目标 chat / 群 / 频道 id */\n chatId: string | number;\n /**\n * 请求总超时(毫秒,含 auto-retry 等待)。默认 `120_000`。\n */\n timeout?: number;\n /** 自定义消息正文;默认 `formatTelegramMessage` */\n format?: (log: LogRecord) => string;\n /**\n * 间隔内相同指纹合并为一条后再发送。默认开启(间隔 30s,指纹不含 bindings)。\n * 传 `false` 则每条立即发送。\n */\n dedupe?: boolean | TelegramDedupeOptions;\n}\n\ntype TelegramDedupeConfig = {\n interval: number;\n bindingKeys?: TelegramDedupeBindingKeys;\n fingerprint?: (log: LogRecord) => string;\n};\n\ntype DedupeBufferEntry = {\n log: LogRecord;\n count: number;\n timer: ReturnType<typeof setTimeout>;\n};\n\n/**\n * 通过 [grammy](https://grammy.dev) `Api.sendMessage` 推送日志,\n * 固定启用 [`@grammyjs/auto-retry`](https://grammy.dev/plugins/auto-retry)。\n *\n * ```typescript\n * new TelegramTransport({\n * botToken: process.env.TELEGRAM_BOT_TOKEN!,\n * chatId: process.env.TELEGRAM_CHAT_ID!,\n * })\n * ```\n */\nexport class TelegramTransport extends Transport {\n protected readonly chatId: string | number;\n protected readonly timeout: number;\n protected readonly api: Api;\n protected readonly customFormat?: (log: LogRecord) => string;\n protected readonly dedupe: TelegramDedupeConfig | false;\n protected readonly pending = new Set<Promise<void>>();\n protected readonly buffer = new Map<string, DedupeBufferEntry>();\n\n constructor(opts: TelegramTransportOptions) {\n super();\n this.chatId = opts.chatId;\n this.timeout = opts.timeout ?? 120_000;\n this.customFormat = opts.format;\n this.dedupe = this.resolveDedupe(opts.dedupe);\n\n const api = new Api(opts.botToken);\n api.config.use(autoRetry({ maxRetryAttempts: 3, maxDelaySeconds: 60 }));\n this.api = api;\n }\n\n override async consume(log: LogRecord): Promise<void> {\n if (this.dedupe) {\n this.enqueue(log);\n return;\n }\n const task = this.sendText(this.formatMessage(log)).finally(() => {\n this.pending.delete(task);\n });\n this.pending.add(task);\n await task;\n }\n\n override async flush(): Promise<void> {\n await this.flushBuffer();\n await Promise.all([...this.pending]);\n }\n\n protected resolveDedupe(\n dedupe: boolean | TelegramDedupeOptions | undefined,\n ): TelegramDedupeConfig | false {\n if (dedupe === false) return false;\n const opts = dedupe === true || dedupe == null ? {} : dedupe;\n return {\n interval: opts.interval ?? 30_000,\n bindingKeys: opts.bindingKeys,\n fingerprint: opts.fingerprint,\n };\n }\n\n /** 组装待发送正文(自定义 `format` 优先) */\n protected formatMessage(log: LogRecord): string {\n return this.customFormat?.(log) ?? this.formatTelegramMessage(log);\n }\n\n /** 默认消息模板;子类可 override */\n protected formatTelegramMessage(log: LogRecord): string {\n let text = `[${log.level}] ${log.timestamp.toISOString()}\\n${log.message}`;\n if (log.bindings) {\n text += `\\n${JSON.stringify(log.bindings)}`;\n }\n if (log.exception?.stack) {\n text += `\\n\\n${log.exception.stack}`;\n } else if (log.exception) {\n text += `\\n\\n${log.exception.type}: ${log.exception.message}`;\n }\n if (text.length <= TELEGRAM_MESSAGE_MAX_LENGTH) return text;\n return `${text.slice(0, TELEGRAM_MESSAGE_MAX_LENGTH - 1)}…`;\n }\n\n protected formatBufferedMessage(log: LogRecord, count: number): string {\n let text = this.formatMessage(log);\n if (count > 1) {\n text += `\\n(×${count})`;\n }\n if (text.length <= TELEGRAM_MESSAGE_MAX_LENGTH) return text;\n return `${text.slice(0, TELEGRAM_MESSAGE_MAX_LENGTH - 1)}…`;\n }\n\n /** 解析最终指纹(自定义 `fingerprint` 优先) */\n protected fingerprint(log: LogRecord): string {\n const dedupe = this.dedupe;\n if (!dedupe) {\n return this.fingerprintLog(log);\n }\n return dedupe.fingerprint?.(log) ?? this.fingerprintLog(log, dedupe.bindingKeys);\n }\n\n /**\n * 默认指纹:`level` + `message` + `exception`;\n * 传入 `bindingKeys` 时再附加对应 bindings。\n */\n protected fingerprintLog(\n log: LogRecord,\n bindingKeys?: TelegramDedupeBindingKeys,\n ): string {\n const parts: unknown[] = [log.level, log.message];\n if (log.exception) {\n parts.push(this.fingerprintException(log.exception));\n }\n if (log.bindings) {\n const picked = this.pickBindingsForFingerprint(log.bindings, bindingKeys);\n if (picked) {\n parts.push(picked);\n }\n }\n return JSON.stringify(parts);\n }\n\n protected fingerprintException(exception: SerializedError): unknown {\n return {\n type: exception.type,\n message: exception.message,\n stack: exception.stack,\n ...(exception.cause ? { cause: this.fingerprintException(exception.cause) } : {}),\n };\n }\n\n protected pickBindingsForFingerprint(\n bindings: Record<string, unknown>,\n bindingKeys: TelegramDedupeBindingKeys | undefined,\n ): Record<string, unknown> | undefined {\n if (bindingKeys == null) return undefined;\n const filtered: Record<string, unknown> = {};\n if (bindingKeys === 'all') {\n for (const key of Object.keys(bindings).sort()) {\n filtered[key] = bindings[key];\n }\n } else {\n for (const key of [...bindingKeys].sort()) {\n if (Object.hasOwn(bindings, key)) {\n filtered[key] = bindings[key];\n }\n }\n }\n return Object.keys(filtered).length > 0 ? filtered : undefined;\n }\n\n protected enqueue(log: LogRecord): void {\n const dedupe = this.dedupe;\n if (!dedupe) return;\n\n const fp = this.fingerprint(log);\n const existing = this.buffer.get(fp);\n if (existing) {\n existing.count += 1;\n return;\n }\n\n const timer = setTimeout(() => {\n void this.flushFingerprint(fp).catch((err) => {\n const detail = Error.isError(err) ? (err.stack ?? err.message) : String(err);\n console.error(`[aomex/logger-telegram] dedupe flush failed: ${detail}`);\n });\n }, dedupe.interval);\n timer.unref?.();\n this.buffer.set(fp, { log, count: 1, timer });\n }\n\n protected async flushBuffer(): Promise<void> {\n const fingerprints = [...this.buffer.keys()];\n await Promise.all(fingerprints.map((fp) => this.flushFingerprint(fp)));\n }\n\n protected async flushFingerprint(fp: string): Promise<void> {\n const entry = this.buffer.get(fp);\n if (!entry) return;\n clearTimeout(entry.timer);\n this.buffer.delete(fp);\n\n const task = this.sendText(\n this.formatBufferedMessage(entry.log, entry.count),\n ).finally(() => {\n this.pending.delete(task);\n });\n this.pending.add(task);\n await task;\n }\n\n protected async sendText(text: string): Promise<void> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n try {\n await this.api.sendMessage(\n this.chatId,\n text,\n { link_preview_options: { is_disabled: true } },\n // grammy 使用独立 AbortSignal 类型\n controller.signal as Parameters<Api['sendMessage']>[3],\n );\n } catch (err) {\n if (Error.isError(err) && err.name === 'AbortError') {\n throw new Error(i18n.t('send_message_timed_out'));\n }\n throw err;\n } finally {\n clearTimeout(timer);\n }\n }\n}\n"],"mappings":";;;;;AAEA,MAAa,KAAK,KAAK,OAAO,EAC5B,wBAAwB,kBAC1B,CAAC;;ACDD,MAAa,KAAK,KAAK,UAAU,EAAE,CAAC,CAAC,OAAO,EAC1C,wBAAwB,kCAC1B,CAAC;;ACDD,MAAa,OAAO,WAAW;CAC7B;CACA;CACA,O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C,cAAc;GACd,KAAK,QAAQ,OAAO,IAAI;EAC1B,CAAC;EACD,KAAK,QAAQ,IAAI,IAAI;EACrB,MAAM;CACR;CAEA,MAAgB,SAAS,MAA6B;EACpD,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,QAAQ,iBAAiB,WAAW,MAAM,GAAG,KAAK,OAAO;EAC/D,IAAI;GACF,MAAM,KAAK,IAAI,YACb,KAAK,QACL,MACA,EAAE,sBAAsB,EAAE,aAAa,KAAK,EAAE,GAE9C,WAAW,MACb;EACF,SAAS,KAAK;GACZ,IAAI,MAAM,QAAQ,GAAG,KAAK,IAAI,SAAS,cACrC,MAAM,IAAI,MAAM,KAAK,EAAE,wBAAwB,CAAC;GAElD,MAAM;EACR,UAAU;GACR,aAAa,KAAK;EACpB;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aomex/logger-telegram",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "3.30.8-alpha.62.sha-92b25bb",
|
|
4
|
+
"description": "aomex logger Telegram Bot transport (grammy)",
|
|
5
|
+
"repository": "git@github.com:aomex/aomex.git",
|
|
6
|
+
"homepage": "https://aomex.js.org",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"sideEffects": false,
|
|
10
|
+
"scripts": {
|
|
11
|
+
"prepublishOnly": "tsdown"
|
|
12
|
+
},
|
|
13
|
+
"types": "src/index.ts",
|
|
14
|
+
"exports": "./src/index.ts",
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"package.json",
|
|
18
|
+
"README.md",
|
|
19
|
+
"CHANGELOG.md"
|
|
20
|
+
],
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"types": "dist/index.d.ts",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./package.json": "./package.json"
|
|
29
|
+
},
|
|
30
|
+
"access": "public"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@aomex/common": "^4.0.0",
|
|
34
|
+
"@aomex/logger": "^4.0.0"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@grammyjs/auto-retry": "^2.0.2",
|
|
38
|
+
"grammy": "^1.46.0"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@aomex/common": "3.30.8-alpha.62.sha-92b25bb",
|
|
42
|
+
"@aomex/logger": "3.30.8-alpha.62.sha-92b25bb"
|
|
43
|
+
},
|
|
44
|
+
"gitHead": "92b25bbcd6c3ae28160316117a74c88619b5bc8d"
|
|
45
|
+
}
|