openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
813 lines (812 loc) • 28.5 kB
JavaScript
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { D as parseStrictPositiveInteger, T as parseStrictInteger } from "./number-coercion-D6u-4YD8.mjs";
import { b as uniqueStrings } from "./string-normalization-DLmfYZXI.mjs";
import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs";
import { n as normalizeAccountId } from "./account-id-BqKT3GuY.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { t as createDedupeCache } from "./dedupe-DxT0h2gR.mjs";
import "./channel-outbound-DQFse8vD.mjs";
import { a as parseAccessGroupAllowFromEntry, i as mergeDmAllowFromSources, n as firstDefined, r as isSenderIdAllowed } from "./allow-from-BGE4RL6B.mjs";
import { t as formatLocationText } from "./location-oMDzIggt.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import "./security-runtime-C-zE_Zy_.mjs";
import { t as expandAllowFromWithAccessGroups } from "./access-groups-TMZDMoGF.mjs";
import "./number-runtime-W4chuk8B.mjs";
import "./runtime-env-D-Pa5lD6.mjs";
import { h as resolveChannelPreviewStreamMode } from "./streaming-DsQF8isK.mjs";
import "./routing-DmgGYTrU.mjs";
import { t as readChannelAllowFromStore } from "./pairing-store.read-5Rowoyv-.mjs";
import "./channel-inbound-DA48LBlQ.mjs";
import "./dedupe-runtime-C9knj5Aa.mjs";
import "./conversation-runtime-CefOz30L.mjs";
import "./allow-from-KJPYRCAd.mjs";
import { t as buildTelegramConversationId } from "./topic-conversation-CDf2PinB.mjs";
//#region extensions/telegram/src/bot-access.ts
const warnedInvalidEntries = createDedupeCache({
ttlMs: 0,
maxSize: 256
});
const log = createSubsystemLogger("telegram/bot-access");
function warnInvalidAllowFromEntries(e) {
if (process.env.VITEST || false) return;
for (const t of e) {
if (warnedInvalidEntries.check(t)) continue;
log.warn([
"Invalid allowFrom entry:",
JSON.stringify(t),
"- allowFrom/groupAllowFrom authorization expects numeric Telegram sender user IDs only.",
"To allow a Telegram group or supergroup, add its negative chat ID under \"channels.telegram.groups\" instead.",
"If you had \"@username\" entries, re-run setup (it resolves @username to IDs) or replace them manually."
].join(" "));
}
}
const normalizeAllowFrom = (e) => {
const t = (e ?? []).map((e) => normalizeOptionalString(String(e)) ?? "").filter(Boolean);
const n = t.includes("*");
const r = t.filter((e) => e !== "*").map((e) => e.replace(/^(telegram|tg):/i, ""));
const i = r.filter((e) => !/^\d+$/.test(e));
if (i.length > 0) warnInvalidAllowFromEntries(uniqueStrings(i));
return {
entries: r.filter((e) => /^\d+$/.test(e)),
hasWildcard: n,
hasEntries: t.length > 0,
invalidEntries: i
};
};
const normalizeDmAllowFromWithStore = (e) => normalizeAllowFrom(mergeDmAllowFromSources(e));
function resolveTelegramEffectiveDmPolicy(e) {
if (!e.isGroup && e.groupConfig && "dmPolicy" in e.groupConfig) return e.groupConfig.dmPolicy ?? e.dmPolicy ?? "pairing";
return e.dmPolicy ?? "pairing";
}
//#endregion
//#region extensions/telegram/src/access-groups.ts
async function expandTelegramAllowFromWithAccessGroups(e) {
const t = (e.allowFrom ?? []).map(String);
const n = e.senderId?.trim() ?? "";
const r = e.cfg && n ? await expandAllowFromWithAccessGroups({
cfg: e.cfg,
allowFrom: t,
channel: "telegram",
accountId: e.accountId ?? "default",
senderId: n,
isSenderAllowed: (e, t) => isSenderIdAllowed(normalizeAllowFrom(t), e, true)
}) : t;
const i = new Set(t);
return r.some((e) => !i.has(e)) ? r.filter((e) => parseAccessGroupAllowFromEntry(e) == null) : r;
}
async function resolveTelegramDmAllow(e) {
const t = e.groupAllowOverride ?? e.allowFrom;
const n = await expandTelegramAllowFromWithAccessGroups({
...e,
allowFrom: t
});
return {
allowFrom: t,
effectiveAllow: normalizeDmAllowFromWithStore({
allowFrom: n,
storeAllowFrom: e.storeAllowFrom,
dmPolicy: e.dmPolicy
})
};
}
//#endregion
//#region extensions/telegram/src/bot/inbound-text-entities.ts
const TELEGRAM_ENTITY_MARKDOWN_PRIORITY = {
blockquote: 0,
expandable_blockquote: 0,
bold: 10,
italic: 20,
underline: 30,
strikethrough: 40,
spoiler: 50,
text_link: 60,
code: 70,
pre: 80
};
const TELEGRAM_FORMATTING_MARKERS = /* @__PURE__ */ new Map([
["bold", "**"],
["italic", "_"],
["underline", "__"],
["strikethrough", "~~"],
["spoiler", "||"]
]);
function isTelegramBlockquoteEntity(e) {
return e.type === "blockquote" || e.type === "expandable_blockquote";
}
function hasValidTelegramEntityRange(e, t) {
return Number.isInteger(t.offset) && Number.isInteger(t.length) && t.offset >= 0 && t.length > 0 && t.offset + t.length <= e.length;
}
function longestBacktickRun(e) {
let t = 0;
for (const n of e.matchAll(/`+/g)) t = Math.max(t, n[0].length);
return t;
}
function markdownInlineCodeDelimiters(e) {
const t = "`".repeat(longestBacktickRun(e) + 1);
const n = /^[ \r\n`]|[ \r\n`]$/u.test(e) && /[^ \r\n]/u.test(e) ? " " : "";
return [`${t}${n}`, `${n}${t}`];
}
function markdownPreAffixes(e, t) {
const n = e.language?.replace(/[\s`]+/g, "");
const r = "`".repeat(Math.max(3, longestBacktickRun(t) + 1));
return [n ? `${r}${n}\n` : `${r}\n`, t.endsWith("\n") ? r : `\n${r}`];
}
function markdownAffixesForTelegramEntity(e, t) {
const n = TELEGRAM_FORMATTING_MARKERS.get(e.type);
if (n) return [n, n];
switch (e.type) {
case "blockquote":
case "expandable_blockquote": return ["> ", ""];
case "code": return markdownInlineCodeDelimiters(t);
case "pre": return markdownPreAffixes(e, t);
case "text_link": return ["[", `](${e.url.replace(/[\\()<>\s]/gu, (e) => e === "(" || e === ")" ? `\\${e}` : encodeURIComponent(e))})`];
default: return null;
}
}
function splitTelegramFormattingAtQuoteEdges(e, t, n) {
if (!TELEGRAM_FORMATTING_MARKERS.has(t.type)) return [t];
const r = t.offset + t.length;
const i = n.filter((e) => t.offset < e && e < r);
if (i.length === 0) return [t];
const a = [];
let o = t.offset;
for (const n of [...i, r]) {
let r = n;
while (o < r && /\s/u.test(e.charAt(o))) o += 1;
while (r > o && /\s/u.test(e.charAt(r - 1))) r -= 1;
if (o < r) a.push({
...t,
offset: o,
length: r - o
});
o = n;
}
return a;
}
function resolveTelegramBlockquoteClose(e, t, n) {
let r = 0;
let i = n;
while (i > t && e.charAt(i - 1) === "\n") {
r += 1;
i -= e.charAt(i - 2) === "\r" ? 2 : 1;
}
i = n;
while (i < e.length) if (e.charAt(i) === "\n") {
r += 1;
i += 1;
} else if (e.charAt(i) === "\r" && e.charAt(i + 1) === "\n") {
r += 1;
i += 2;
} else break;
const a = (n < e.length ? 2 : 1) - r;
return (e.charAt(n) === "\r" || e.charAt(n - 2) === "\r" ? "\r\n" : "\n").repeat(Math.max(0, a));
}
function renderTelegramTextEntities(e, t) {
if (!e || !t?.length) return e;
const n = /* @__PURE__ */ new Set();
const r = /* @__PURE__ */ new Set();
for (const i of t) {
if (!isTelegramBlockquoteEntity(i) || !hasValidTelegramEntityRange(e, i)) continue;
const t = i.offset + i.length;
r.add(i.offset);
r.add(t);
for (let r = i.offset + 1; r < t; r += 1) if (e[r - 1] === "\n") n.add(r);
}
const i = [...r].sort((e, t) => e - t);
const a = /* @__PURE__ */ new Map();
const o = /* @__PURE__ */ new Set();
const addBoundary = (e, t) => {
const n = a.get(e);
if (n) n.push(t);
else a.set(e, [t]);
};
t.forEach((t, n) => {
if (!hasValidTelegramEntityRange(e, t)) return;
for (const r of splitTelegramFormattingAtQuoteEdges(e, t, i)) {
const t = e.slice(r.offset, r.offset + r.length);
if (r.type === "text_link") for (const e of t.matchAll(/[\\[\]]/gu)) o.add(r.offset + e.index);
const i = markdownAffixesForTelegramEntity(r, t);
if (!i) continue;
const a = r.offset + r.length;
if (isTelegramBlockquoteEntity(r)) i[1] = resolveTelegramBlockquoteClose(e, r.offset, a);
const s = {
open: i[0],
close: i[1],
start: r.offset,
end: a,
length: r.length,
priority: TELEGRAM_ENTITY_MARKDOWN_PRIORITY[r.type] ?? 100,
index: n
};
addBoundary(s.start, s);
addBoundary(s.end, s);
}
});
if (a.size === 0) return e;
let s = "";
for (let t = 0; t <= e.length; t += 1) {
if (n.has(t)) s += "> ";
const r = a.get(t);
if (r) {
r.filter((e) => e.end === t).sort((e, t) => e.length - t.length || t.priority - e.priority || t.index - e.index).forEach((e) => {
s += e.close;
});
r.filter((e) => e.start === t).sort((e, t) => t.length - e.length || e.priority - t.priority || e.index - t.index).forEach((e) => {
s += e.open;
});
}
if (t < e.length) s += o.has(t) ? `\\${e[t]}` : e[t];
}
return s;
}
//#endregion
//#region extensions/telegram/src/bot/body-helpers.ts
function buildSenderName(e) {
return [e.from?.first_name, e.from?.last_name].filter(Boolean).join(" ").trim() || e.from?.username || void 0;
}
function resolveTelegramPrimaryMedia(e) {
if (!e) return;
const t = [
["image", e.photo?.[e.photo.length - 1]],
["video", e.video ?? e.video_note ?? e.animation],
["audio", e.audio ?? e.voice],
["document", e.document],
["sticker", e.sticker]
];
for (const [e, n] of t) if (n) return {
kind: e,
fileRef: n
};
}
function buildSenderLabel(e, t) {
const n = buildSenderName(e);
const r = e.from?.username ? `@${e.from.username}` : void 0;
const i = n && r ? `${n} (${r})` : n || r;
const a = (t != null ? normalizeOptionalString(String(t)) : void 0) ?? (e.from?.id != null ? String(e.from.id) : void 0);
return [i, a ? `id:${a}` : void 0].filter(Boolean).join(" ") || "id:unknown";
}
const TELEGRAM_RICH_MESSAGE_PLACEHOLDER = "[unsupported Telegram rich_message received]";
function compactRichText(e) {
return e.split("\n").map((e) => e.trim()).filter(Boolean).join("\n");
}
function joinRichText(e) {
return e.map(compactRichText).filter(Boolean).join("\n");
}
function renderRichInlineText(e) {
if (e === void 0) return "";
if (typeof e === "string") return e;
if (Array.isArray(e)) return e.map(renderRichInlineText).filter(Boolean).join("");
switch (e.type) {
case "anchor": return "";
case "button": return renderRichInlineText(e.button.text);
case "custom_emoji": return e.alternative_text;
case "mathematical_expression": return e.expression;
default: return renderRichInlineText(e.text);
}
}
function renderRichCaption(e) {
return e ? joinRichText([renderRichInlineText(e.text), renderRichInlineText(e.credit)]) : "";
}
function renderRichBlock(e) {
switch (e.type) {
case "paragraph":
case "heading":
case "pre":
case "footer":
case "thinking": return renderRichInlineText(e.text);
case "expandable_blockquote":
case "pullquote": return renderRichCaption(e);
case "mathematical_expression": return e.expression;
case "blockquote": return joinRichText([renderRichInlineText(e.credit), renderRichBlocks(e.blocks)]);
case "collage":
case "slideshow": return joinRichText([renderRichCaption(e.caption), renderRichBlocks(e.blocks)]);
case "details": return joinRichText([renderRichInlineText(e.summary), renderRichBlocks(e.blocks)]);
case "list": return joinRichText(e.items.map((e) => joinRichText([e.label, renderRichBlocks(e.blocks)])));
case "table": return joinRichText([renderRichInlineText(e.caption), ...e.cells.flatMap((e) => e.map((e) => renderRichInlineText(e.text)))]);
case "animation":
case "audio":
case "document":
case "map":
case "photo":
case "video":
case "voice_note": return renderRichCaption(e.caption);
case "buttons": return joinRichText(e.buttons.map((e) => renderRichInlineText(e.text)));
case "anchor":
case "divider": return "";
}
return "";
}
function renderRichBlocks(e) {
return joinRichText(e.map(renderRichBlock));
}
function resolveTelegramRichMessagePlaceholder(e) {
return e.rich_message ? TELEGRAM_RICH_MESSAGE_PLACEHOLDER : void 0;
}
function isBinaryContent(e) {
for (let t = 0; t < e.length; t++) {
const n = e.charCodeAt(t);
if (n <= 31 && n !== 9 && n !== 10 && n !== 13) return true;
}
return false;
}
function resolveTelegramTextContent(e, t) {
const n = typeof e === "string" ? e : typeof t === "string" ? t : "";
return isBinaryContent(n) ? "" : n;
}
function formatTelegramPollText(e) {
const t = new Set(e.correct_option_ids ?? []);
const n = e.options.map((e, n) => {
const r = renderTelegramTextEntities(e.text, e.text_entities);
const i = e.voter_count === 1 ? "vote" : "votes";
const a = t.has(n) ? " (correct)" : "";
return `${n + 1}. ${r} — ${e.voter_count} ${i}${a}`;
});
return [
`[Poll] ${renderTelegramTextEntities(e.question, e.question_entities)}`,
...e.description ? [renderTelegramTextEntities(e.description, e.description_entities)] : [],
...n,
`Total voters: ${e.total_voter_count}`,
`Type: ${e.type}`,
`Visibility: ${e.is_anonymous ? "anonymous" : "public"}`,
`Selection: ${e.allows_multiple_answers ? "multiple answers" : "single answer"}`,
`Status: ${e.is_closed ? "closed" : "open"}`,
...e.explanation ? [`Explanation: ${renderTelegramTextEntities(e.explanation, e.explanation_entities)}`] : []
].join("\n");
}
function getTelegramTextParts(e) {
const t = resolveTelegramTextContent(e.text, e.caption);
if (t) return {
text: t,
entities: e.entities ?? e.caption_entities ?? []
};
if (e.contact) return {
text: `[Shared contact] ${[[e.contact.first_name, e.contact.last_name].map((e) => normalizeOptionalString(e)).filter(Boolean).join(" "), normalizeOptionalString(e.contact.phone_number)].filter(Boolean).join(", ") || "no details"}`,
entities: []
};
if (e.poll) return {
text: formatTelegramPollText(e.poll),
entities: []
};
return {
text: e.rich_message ? renderRichBlocks(e.rich_message.blocks) : "",
entities: []
};
}
function joinTelegramTextParts(e, t) {
const n = [];
const r = [];
let i = 0;
let a;
for (const o of e) {
const e = getTelegramTextParts(o);
if (!e.text) continue;
if (a) {
const e = typeof t === "string" ? t : t(a);
n.push(e);
i += e.length;
}
r.push(...e.entities.map((e) => ({
...e,
offset: e.offset + i
})));
n.push(e.text);
i += e.text.length;
a = o;
}
return {
text: n.join(""),
entities: r
};
}
function isTelegramMentionWordChar(e) {
return e != null && /[a-z0-9_]/i.test(e);
}
function hasStandaloneTelegramMention(e, t) {
let n = 0;
while (n < e.length) {
const r = e.indexOf(t, n);
if (r === -1) return false;
const i = r > 0 ? e[r - 1] : void 0;
const a = e[r + t.length];
if (!isTelegramMentionWordChar(i) && !isTelegramMentionWordChar(a)) return true;
n = r + 1;
}
return false;
}
function isBotCommandAddressedToMention(e, t) {
const n = normalizeLowercaseStringOrEmpty(e);
if (!n.startsWith("/") || !n.endsWith(t)) return false;
return n.lastIndexOf(t) > 1;
}
function hasBotMention(e, t, n) {
if (e.contact) return false;
const { text: r, entities: i } = getTelegramTextParts(e);
const a = normalizeLowercaseStringOrEmpty(`@${t}`);
if (hasStandaloneTelegramMention(normalizeLowercaseStringOrEmpty(r), a)) return true;
for (const e of i) {
const t = r.slice(e.offset, e.offset + e.length);
if (e.type === "mention" && normalizeLowercaseStringOrEmpty(t) === a) return true;
if (e.type === "bot_command" && isBotCommandAddressedToMention(t, a)) return true;
if (e.type === "text_mention" && n !== void 0 && e.user?.id === n) return true;
}
return false;
}
function hasLeadingBotCommandAddressedToOtherBot(e, t) {
const { text: n, entities: r } = getTelegramTextParts(e);
const i = normalizeLowercaseStringOrEmpty(t).replace(/^@/u, "");
if (!i) return false;
const a = r.find((e) => e.type === "bot_command" && e.offset === 0);
if (!a) return false;
const o = n.slice(0, a.length).match(/^\/[^@\s]+@([a-z0-9_]+)$/iu)?.[1];
return Boolean(o && o.toLowerCase() !== i);
}
function normalizeForwardedContext(e) {
const t = e.forward_origin;
if (!t) return null;
const n = {
date: t.date,
fromType: t.type
};
switch (t.type) {
case "user": {
const e = t.sender_user;
const r = [e.first_name, e.last_name].filter(Boolean).join(" ").trim();
const i = normalizeOptionalString(e.username);
const a = String(e.id);
const o = (r && i ? `${r} (@${i})` : r || (i ? `@${i}` : void 0)) || `user:${a}`;
return {
...n,
from: o,
fromId: a,
fromUsername: i,
fromTitle: r || void 0
};
}
case "hidden_user": {
const e = t.sender_user_name?.trim();
return e ? {
...n,
from: e,
fromTitle: e
} : null;
}
case "chat":
case "channel": {
const e = t.type === "channel" ? t.chat : t.sender_chat;
const r = normalizeOptionalString(e.title);
const i = normalizeOptionalString(e.username);
const a = String(e.id);
const o = r || (i ? `@${i}` : void 0) || `${t.type}:${a}`;
const s = normalizeOptionalString(t.author_signature);
return {
...n,
from: s ? `${o} (${s})` : o,
fromId: a,
fromUsername: i,
fromTitle: r,
fromSignature: s,
fromChatType: normalizeOptionalString(e.type),
fromMessageId: t.type === "channel" ? t.message_id : void 0
};
}
default: return null;
}
}
/** Shared by inbound bodies, cached messages, and reply targets. */
function resolveTelegramNonTextBody(e) {
const t = extractTelegramLocation(e);
if (t) return {
kind: "location",
text: formatLocationText(t),
location: t
};
const n = e.dice;
const r = normalizeOptionalString(n?.emoji);
return n && r && Number.isFinite(n.value) ? {
kind: "dice",
text: `[Dice ${r} = ${n.value}]`
} : void 0;
}
function extractTelegramLocation(e) {
const { venue: t } = e;
const n = t?.location ?? e.location;
if (!n) return null;
const r = !t && typeof n.live_period === "number" && n.live_period > 0;
return {
latitude: n.latitude,
longitude: n.longitude,
accuracy: n.horizontal_accuracy,
...t ? {
name: t.title,
address: t.address
} : {},
source: t ? "place" : r ? "live" : "pin",
isLive: r
};
}
//#endregion
//#region extensions/telegram/src/preview-streaming.ts
function resolveTelegramPreviewStreamMode(e = {}) {
return resolveChannelPreviewStreamMode(e, "progress");
}
//#endregion
//#region extensions/telegram/src/outbound-params.ts
function parseTelegramReplyToMessageId(e) {
return parseStrictInteger(e);
}
function parseTelegramThreadId(e) {
if (typeof e !== "string") return parseStrictInteger(e);
const t = e.trim();
const n = /^-?\d+:(?:topic:(\d+)|(-?\d+))$/.exec(t);
return parseStrictInteger(n?.[1] ?? n?.[2] ?? t);
}
//#endregion
//#region extensions/telegram/src/bot/helpers.ts
const TELEGRAM_GENERAL_TOPIC_ID = 1;
const TELEGRAM_FORUM_FLAG_CACHE_MAX_CHATS = 1024;
const TELEGRAM_FORUM_FLAG_CACHE_TTL_MS = 6e5;
const telegramForumFlagByChatId = /* @__PURE__ */ new Map();
function cacheTelegramForumFlag(e, t, n = Date.now()) {
const r = String(e);
telegramForumFlagByChatId.set(r, {
expiresAtMs: n + TELEGRAM_FORUM_FLAG_CACHE_TTL_MS,
isForum: t
});
pruneMapToMaxSize(telegramForumFlagByChatId, TELEGRAM_FORUM_FLAG_CACHE_MAX_CHATS);
}
function getCachedTelegramForumFlag(e) {
const t = String(e);
const n = telegramForumFlagByChatId.get(t);
if (!n) return;
if (n.expiresAtMs <= Date.now()) return;
return n.isForum;
}
function hadUnsafeTelegramText(e, t) {
return typeof e === "string" && e.trim().length > 0 && t.trim().length === 0;
}
function shouldUseTelegramDmThreadSession(e) {
return e.dmThreadId != null && e.botHasTopicsEnabled === true;
}
function resolveTelegramBotHasTopicsEnabled(e) {
return e !== null && typeof e === "object" && "has_topics_enabled" in e && e.has_topics_enabled === true;
}
function extractTelegramForumFlag(e) {
if (!e || typeof e !== "object" || !("is_forum" in e)) return;
const t = e.is_forum;
return typeof t === "boolean" ? t : void 0;
}
function resolveTelegramMessageForumFlagHint(e) {
if (e.chatType === "supergroup" && e.isTopicMessage === true) return true;
return typeof e.isForum === "boolean" ? e.isForum : void 0;
}
async function resolveTelegramForumFlag(e) {
const t = resolveTelegramMessageForumFlagHint(e);
if (typeof t === "boolean") {
if (e.isGroup && e.chatType === "supergroup") cacheTelegramForumFlag(e.chatId, t);
return t;
}
if (!e.isGroup || e.chatType !== "supergroup" || !e.getChat) return false;
const n = String(e.chatId);
const r = Date.now();
const i = telegramForumFlagByChatId.get(n);
if (i) {
if (i.expiresAtMs > r) return i.isForum;
telegramForumFlagByChatId.delete(n);
}
try {
const t = extractTelegramForumFlag(await e.getChat(e.chatId)) === true;
cacheTelegramForumFlag(e.chatId, t, r);
return t;
} catch {
return false;
}
}
function withResolvedTelegramForumFlag(e, t) {
if (extractTelegramForumFlag(e.chat) === t) return e;
return {
...e,
chat: {
...e.chat,
is_forum: t
}
};
}
async function resolveTelegramGroupAllowFromContext(e) {
const t = normalizeAccountId(e.accountId);
const n = e.threadSpec ?? resolveTelegramThreadSpec({
isGroup: e.isGroup ?? false,
isForum: e.isForum,
messageThreadId: e.messageThreadId
});
const r = n.scope === "forum" || n.scope === "direct-messages" ? n.id : void 0;
const i = n.scope === "dm" ? n.id : void 0;
const a = r ?? i;
const { groupConfig: o, topicConfig: s } = e.resolveTelegramGroupConfig(e.chatId, a, e.cfg);
const c = firstDefined(s?.allowFrom, o?.allowFrom);
const l = resolveTelegramEffectiveDmPolicy({
isGroup: e.isGroup ?? false,
groupConfig: o,
dmPolicy: e.dmPolicy
});
const u = c ?? e.allowFrom;
let d = !e.skipPairingStoreRead && !e.isGroup && l === "pairing";
if (d && u?.length) {
const n = normalizeAllowFrom(await expandTelegramAllowFromWithAccessGroups({
...e,
accountId: t,
allowFrom: u
}));
d = !n.hasEntries || !isSenderIdAllowed(n, e.senderId, true);
}
let f = [];
if (d) try {
f = await (e.readChannelAllowFromStore ?? readChannelAllowFromStore)("telegram", process.env, t);
} catch (e) {
throw new TelegramPairingStoreReadError(e);
}
const p = await expandTelegramAllowFromWithAccessGroups({
cfg: e.cfg,
allowFrom: c ?? e.groupAllowFrom,
accountId: t,
senderId: e.senderId
});
const m = normalizeAllowFrom(p);
return {
threadSpec: n,
resolvedThreadId: r,
dmThreadId: i,
storeAllowFrom: f,
groupConfig: o,
topicConfig: s,
groupAllowOverride: c,
effectiveGroupAllow: m,
hasGroupAllowOverride: c !== void 0
};
}
var TelegramPairingStoreReadError = class extends Error {
constructor(e) {
super(`Telegram pairing store read failed: ${String(e)}`);
this.name = "TelegramPairingStoreReadError";
this.cause = e;
}
};
function resolveTelegramForumThreadId(e) {
return e.isForum ? e.messageThreadId ?? 1 : void 0;
}
function resolveTelegramThreadSpec(e) {
if (e.isGroup) {
const t = resolveTelegramForumThreadId(e);
return t === void 0 ? { scope: "none" } : {
id: t,
scope: "forum"
};
}
if (e.messageThreadId == null) return { scope: "dm" };
return {
id: e.messageThreadId,
scope: "dm"
};
}
function resolveTelegramMessageThreadSpec(e, t) {
if (e.chat.is_direct_messages === true) {
const t = parseStrictPositiveInteger(e.direct_messages_topic?.topic_id);
return t === void 0 ? { scope: "none" } : {
id: t,
scope: "direct-messages"
};
}
return resolveTelegramThreadSpec({
isGroup: e.chat.type === "group" || e.chat.type === "supergroup",
isForum: t ?? resolveTelegramMessageForumFlagHint({
chatType: e.chat.type,
isForum: e.chat.is_forum,
isTopicMessage: e.is_topic_message
}),
messageThreadId: e.message_thread_id
});
}
function buildTelegramThreadParams(e) {
if (e?.id == null) return;
const t = Math.trunc(e.id);
if (!Number.isFinite(t)) return;
if (e.scope === "dm") return t > 0 ? { message_thread_id: t } : void 0;
if (e.scope === "direct-messages") return t > 0 ? { direct_messages_topic_id: t } : void 0;
if (e.scope === "none") return;
if (t === 1) return;
return { message_thread_id: t };
}
function buildTelegramRoutingTarget(e, t) {
const n = `telegram:${e}`;
const r = buildTelegramThreadParams(t);
if (r?.direct_messages_topic_id != null) return `${n}:direct-topic:${r.direct_messages_topic_id}`;
return r?.message_thread_id != null ? `${n}:topic:${r.message_thread_id}` : n;
}
function buildTelegramInboundOriginTarget(e, t) {
if (t?.scope !== "forum" && t?.scope !== "direct-messages") return `telegram:${e}`;
return buildTelegramRoutingTarget(e, t);
}
function buildTypingThreadParams(e) {
if (e == null) return;
return { message_thread_id: Math.trunc(e) };
}
function buildTelegramGroupPeerId(e, t) {
return buildTelegramConversationId({
chatId: e,
thread: (typeof t === "number" ? {
id: t,
scope: "forum"
} : t) ?? { scope: "none" }
});
}
function buildTelegramGroupFrom(e, t) {
return `telegram:group:${buildTelegramGroupPeerId(e, t)}`;
}
function isTelegramCommandsAllowFromConfigured(e) {
const t = e.commands?.allowFrom;
return t != null && typeof t === "object" && (Array.isArray(t.telegram) || Array.isArray(t["*"]));
}
function buildTelegramParentPeer(e) {
if (!e.isGroup || e.resolvedThreadId == null) return;
return {
kind: "group",
id: String(e.chatId)
};
}
function buildGroupLabel(e, t, n) {
const r = e.chat?.title;
const i = n != null ? ` topic:${n}` : "";
if (r) return `${r} id:${t}${i}`;
return `group:${t}${i}`;
}
function describeReplyTarget(e) {
const t = e.reply_to_message;
const n = e.external_reply;
const r = e.quote ?? n?.quote;
const i = r?.text;
const a = resolveTelegramTextContent(i);
let o = a.trim();
const s = o ? "quote" : "reply";
const c = hadUnsafeTelegramText(i, a);
const l = t ?? n;
const u = t ? void 0 : e.external_reply?.origin;
const d = l && u?.type === "user" ? {
...l,
from: u.sender_user
} : l;
const f = resolveTelegramPrimaryMedia(l);
const p = l && typeof l.text === "string" ? l.text : l && typeof l.caption === "string" ? l.caption : void 0;
const m = l ? getTelegramTextParts(l) : void 0;
const h = m?.text ?? "";
let g = false;
if (!o && l) {
const e = h.trim() || resolveTelegramRichMessagePlaceholder(l) || "";
g = hadUnsafeTelegramText(p, e);
o = e;
if (!o) o = resolveTelegramNonTextBody(l)?.text ?? "";
}
if (!o && !l) return null;
if (!o && !f && !c && !g) return null;
const _ = (d ? buildSenderName(d) : void 0) ?? "unknown sender";
const v = t ? "reply_to_message" : "external_reply";
const y = s === "quote" && typeof r?.position === "number" && Number.isFinite(r.position) ? Math.trunc(r.position) : void 0;
const b = s === "quote" && Array.isArray(r?.entities) ? r.entities : void 0;
const x = l ? normalizeForwardedContext(l) ?? void 0 : void 0;
return {
id: l?.message_id ? String(l.message_id) : void 0,
sender: _,
senderId: d?.from?.id != null ? String(d.from.id) : void 0,
senderUsername: d?.from?.username ?? void 0,
body: o || void 0,
mediaType: f?.kind,
kind: s,
source: v,
quoteText: s === "quote" ? a : void 0,
quotePosition: y,
quoteEntities: b,
forwardedFrom: x,
quoteSourceText: m?.text || void 0,
quoteSourceEntities: m?.entities
};
}
//#endregion
export { hasBotMention as A, resolveTelegramDmAllow as B, parseTelegramReplyToMessageId as C, buildSenderName as D, buildSenderLabel as E, resolveTelegramNonTextBody as F, normalizeDmAllowFromWithStore as H, resolveTelegramPrimaryMedia as I, resolveTelegramRichMessagePlaceholder as L, isBinaryContent as M, joinTelegramTextParts as N, extractTelegramLocation as O, normalizeForwardedContext as P, renderTelegramTextEntities as R, withResolvedTelegramForumFlag as S, resolveTelegramPreviewStreamMode as T, resolveTelegramEffectiveDmPolicy as U, normalizeAllowFrom as V, resolveTelegramGroupAllowFromContext as _, buildTelegramInboundOriginTarget as a, resolveTelegramThreadSpec as b, buildTelegramThreadParams as c, extractTelegramForumFlag as d, getCachedTelegramForumFlag as f, resolveTelegramForumThreadId as g, resolveTelegramForumFlag as h, buildTelegramGroupPeerId as i, hasLeadingBotCommandAddressedToOtherBot as j, getTelegramTextParts as k, buildTypingThreadParams as l, resolveTelegramBotHasTopicsEnabled as m, buildGroupLabel as n, buildTelegramParentPeer as o, isTelegramCommandsAllowFromConfigured as p, buildTelegramGroupFrom as r, buildTelegramRoutingTarget as s, TelegramPairingStoreReadError as t, describeReplyTarget as u, resolveTelegramMessageForumFlagHint as v, parseTelegramThreadId as w, shouldUseTelegramDmThreadSession as x, resolveTelegramMessageThreadSpec as y, expandTelegramAllowFromWithAccessGroups as z };