Add Telegram and Discord IM channels

This commit is contained in:
xmanrui 2026-08-16 14:47:16 +08:00
parent 7123fce47a
commit cb74e1c4c7
66 changed files with 8579 additions and 1910 deletions

View file

@ -0,0 +1,107 @@
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
const EMPTY_STATE = Object.freeze({ version: 1, sessions: {}, seenMessageIds: [], cursor: null });
function normalizeState(value) {
if (!value || typeof value !== 'object') return structuredClone(EMPTY_STATE);
const sessions = {};
if (value.sessions && typeof value.sessions === 'object' && !Array.isArray(value.sessions)) {
for (const [key, sessionId] of Object.entries(value.sessions)) {
if (typeof key === 'string' && key && typeof sessionId === 'string' && sessionId) {
sessions[key] = sessionId;
}
}
}
return {
version: 1,
sessions,
seenMessageIds: Array.isArray(value.seenMessageIds)
? value.seenMessageIds.filter((id) => typeof id === 'string' && id).slice(-1_000)
: [],
cursor: Number.isSafeInteger(value.cursor) && value.cursor >= 0 ? value.cursor : null,
};
}
export class ConversationStateStore {
#path;
#state = structuredClone(EMPTY_STATE);
#writeQueue = Promise.resolve();
constructor(path) {
this.#path = path;
}
async load() {
try {
this.#state = normalizeState(JSON.parse(await readFile(this.#path, 'utf8')));
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
this.#state = structuredClone(EMPTY_STATE);
await this.#persist();
}
return this;
}
sessionFor(key) {
return this.#state.sessions[key] ?? null;
}
async setSession(key, sessionId) {
this.#state.sessions[key] = sessionId;
await this.#persist();
}
async clearSession(key) {
delete this.#state.sessions[key];
await this.#persist();
}
hasSeen(messageId) {
return this.#state.seenMessageIds.includes(messageId);
}
async markSeen(messageId) {
if (this.hasSeen(messageId)) return;
this.#state.seenMessageIds.push(messageId);
if (this.#state.seenMessageIds.length > 1_000) {
this.#state.seenMessageIds.splice(0, this.#state.seenMessageIds.length - 1_000);
}
await this.#persist();
}
cursor() {
return this.#state.cursor;
}
async setCursor(cursor) {
if (!Number.isSafeInteger(cursor) || cursor < 0) throw new TypeError('Invalid update cursor');
this.#state.cursor = cursor;
await this.#persist();
}
snapshot() {
return structuredClone(this.#state);
}
async remove() {
try {
await unlink(this.#path);
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
}
this.#state = structuredClone(EMPTY_STATE);
}
async #persist() {
const snapshot = `${JSON.stringify(this.#state, null, 2)}\n`;
const operation = this.#writeQueue.then(async () => {
await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
const temporary = `${this.#path}.tmp`;
await writeFile(temporary, snapshot, { encoding: 'utf8', mode: 0o600 });
await rename(temporary, this.#path);
});
this.#writeQueue = operation.then(() => undefined, () => undefined);
await operation;
}
}

View file

@ -0,0 +1,81 @@
export function splitMessageText(value, limit) {
const text = typeof value === 'string' ? value.trim() : '';
if (!text) return [];
const chunks = [];
let remaining = text;
while (remaining.length > limit) {
let cut = remaining.lastIndexOf('\n', limit);
if (cut < Math.floor(limit * 0.55)) cut = remaining.lastIndexOf(' ', limit);
if (cut < Math.floor(limit * 0.55)) cut = limit;
chunks.push(remaining.slice(0, cut).trim());
remaining = remaining.slice(cut).trimStart();
}
if (remaining) chunks.push(remaining);
return chunks;
}
export function createEditableMessageStream({
initialText = '正在处理…',
limit,
updateIntervalMs = 800,
create,
edit,
sendRemainder,
logger = console,
}) {
let messageId;
let pending = null;
let timer = null;
let inFlight = null;
let closed = false;
let lastSent = initialText;
const schedule = () => {
if (closed || timer !== null || inFlight || !pending) return;
timer = setTimeout(() => {
timer = null;
const text = pending;
pending = null;
const next = splitMessageText(text, limit)[0] ?? initialText;
inFlight = Promise.resolve(next === lastSent ? undefined : edit(messageId, next))
.then(() => { lastSent = next; })
.catch((error) => logger.warn?.('[dsh-im] streamed message update failed:', error))
.finally(() => {
inFlight = null;
schedule();
});
}, updateIntervalMs);
timer?.unref?.();
};
return {
async start() {
messageId = await create(initialText);
return this;
},
update(text) {
if (closed || typeof text !== 'string' || !text.trim()) return;
pending = text;
schedule();
},
async finish(text) {
if (closed) throw new Error('Message stream is already closed');
closed = true;
if (timer !== null) clearTimeout(timer);
timer = null;
pending = null;
await inFlight?.catch(() => undefined);
const chunks = splitMessageText(text, limit);
const first = chunks[0] ?? '处理完成。';
if (first !== lastSent) await edit(messageId, first);
lastSent = first;
for (const chunk of chunks.slice(1)) await sendRemainder(chunk);
},
cancel() {
closed = true;
pending = null;
if (timer !== null) clearTimeout(timer);
timer = null;
},
};
}

View file

@ -0,0 +1,180 @@
function cleanText(value) {
return typeof value === 'string' ? value.trim() : '';
}
export function createTextBridgeStatus() {
return {
messagesReceived: 0,
messagesReplied: 0,
messagesRejected: 0,
lastMessageAt: null,
lastReplyAt: null,
lastRejectedAt: null,
lastError: null,
};
}
export class TextHarnessBridge {
#descriptor;
#bot;
#harness;
#state;
#status;
#logger;
#replyTimeoutMs;
#queues = new Map();
constructor({
descriptor,
bot,
harness,
state,
status = createTextBridgeStatus(),
logger = console,
replyTimeoutMs = 600_000,
}) {
if (!descriptor?.key || !descriptor?.label) throw new TypeError('A channel descriptor is required');
if (!bot || typeof bot.sendText !== 'function') throw new TypeError('A bot client is required');
if (!harness || !state) throw new TypeError('Harness client and state store are required');
this.#descriptor = descriptor;
this.#bot = bot;
this.#harness = harness;
this.#state = state;
this.#status = status;
this.#logger = logger;
this.#replyTimeoutMs = replyTimeoutMs;
}
get status() {
return structuredClone(this.#status);
}
accept(message) {
const conversationId = cleanText(message?.conversationId);
const kind = message?.kind === 'group' ? 'group' : 'direct';
const key = `${kind}:${conversationId}`;
const previous = this.#queues.get(key) ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#process({ ...message, kind, conversationId }))
.finally(() => {
if (this.#queues.get(key) === current) this.#queues.delete(key);
});
this.#queues.set(key, current);
return current;
}
async waitForIdle() {
await Promise.allSettled([...this.#queues.values()]);
}
async #process(message) {
const messageId = cleanText(message.messageId);
const senderId = cleanText(message.senderId);
if (!messageId || !senderId || !message.conversationId || message.senderIsBot === true) return;
if (this.#state.hasSeen(messageId)) return;
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
if (message.kind === 'group' && message.addressed !== true) {
this.#status.messagesRejected += 1;
this.#status.lastRejectedAt = new Date().toISOString();
return;
}
const target = message.replyTarget;
const text = cleanText(message.content);
try {
if (!text) {
await this.#bot.sendText(target, '目前仅支持文字消息。');
await this.#state.markSeen(messageId);
return;
}
const command = text.toLowerCase();
if (command === '/help') {
await this.#bot.sendText(target, [
`${this.#descriptor.label}机器人已连接 DeepSeek Harness。`,
'',
'直接发送文字即可继续当前会话。',
'/new 开启一个全新会话',
'/status 检查连接状态',
'/help 显示本帮助',
].join('\n'));
await this.#state.markSeen(messageId);
return;
}
if (command === '/status') {
await this.#harness.ensureRunning();
await this.#bot.sendText(target, `${this.#descriptor.label}机器人与 DeepSeek Harness 连接正常。`);
await this.#state.markSeen(messageId);
return;
}
const conversationKey = `${message.kind}:${message.conversationId}`;
if (command === '/new') {
await this.#state.clearSession(conversationKey);
await this.#bot.sendText(target, '已开启新会话。请发送你的问题。');
await this.#state.markSeen(messageId);
return;
}
let sessionId = this.#state.sessionFor(conversationKey);
if (!sessionId || !(await this.#harness.sessionExists(sessionId))) {
sessionId = await this.#harness.createSession();
await this.#state.setSession(conversationKey, sessionId);
}
await this.#bot.sendTyping?.(target).catch((error) => {
this.#logger.warn?.(`[dsh-im:${this.#descriptor.key}] typing indicator failed:`, error);
});
let stream = null;
let streamFinished = false;
if (typeof this.#bot.openStream === 'function') {
try {
stream = await this.#bot.openStream(target);
} catch (error) {
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] unable to start a streamed reply; using text:`,
error,
);
}
}
const answer = await this.#harness.ask(sessionId, text, {
timeoutMs: this.#replyTimeoutMs,
onUpdate: stream ? async (update) => {
const progress = update.type === 'text' ? update.text
: update.type === 'tool' ? `正在使用${update.name}…` : update.text;
if (progress) await stream.update(progress);
} : undefined,
});
if (stream) {
try {
await stream.finish(answer);
streamFinished = true;
} catch (error) {
stream.cancel?.();
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] streamed reply finalization failed; using text:`,
error,
);
}
}
if (!streamFinished) await this.#bot.sendText(target, answer);
await this.#state.markSeen(messageId);
this.#status.messagesReplied += 1;
this.#status.lastReplyAt = new Date().toISOString();
this.#status.lastError = null;
} catch (error) {
this.#status.lastError = error?.message ?? String(error);
this.#logger.error?.(`[dsh-im:${this.#descriptor.key}] failed to process a message:`, error);
try {
await this.#bot.sendText(target, '消息处理失败,请稍后重试。');
await this.#state.markSeen(messageId);
} catch (sendError) {
this.#logger.error?.(
`[dsh-im:${this.#descriptor.key}] failed to send the safe error reply:`,
sendError,
);
}
}
}
}

View file

@ -0,0 +1,298 @@
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function safeError(code, message) {
return Object.freeze({ code, message });
}
export class TokenBotController {
#descriptor;
#credentials;
#configStore;
#inspectToken;
#deriveIdentity;
#maskPlatformId;
#createRuntime;
#deleteState;
#logger;
#runtimes = new Map();
#errors = new Map();
#transitions = new Map();
#revision = 0;
#closed = false;
constructor({
descriptor,
credentials,
configStore,
inspectToken,
deriveIdentity,
maskPlatformId,
createRuntime,
deleteState = async () => {},
logger = console,
}) {
if (!descriptor?.key || !descriptor?.label || !descriptor?.connectionLabel) {
throw new TypeError('TokenBotController requires a channel descriptor');
}
if (!credentials || typeof credentials.resolve !== 'function'
|| typeof credentials.set !== 'function' || typeof credentials.unset !== 'function') {
throw new TypeError(`${descriptor.label} requires the DSH credential provider`);
}
if (!configStore || typeof configStore.list !== 'function'
|| typeof configStore.save !== 'function' || typeof configStore.remove !== 'function') {
throw new TypeError(`${descriptor.label} requires a config store`);
}
if (typeof inspectToken !== 'function' || typeof deriveIdentity !== 'function'
|| typeof maskPlatformId !== 'function' || typeof createRuntime !== 'function') {
throw new TypeError(`${descriptor.label} controller dependencies are incomplete`);
}
this.#descriptor = descriptor;
this.#credentials = credentials;
this.#configStore = configStore;
this.#inspectToken = inspectToken;
this.#deriveIdentity = deriveIdentity;
this.#maskPlatformId = maskPlatformId;
this.#createRuntime = createRuntime;
this.#deleteState = deleteState;
this.#logger = logger;
}
async initialize() {
if (this.#closed) return this.status();
for (const config of this.#configStore.list()) {
await this.#withBotTransition(config.botId, async () => {
if (this.#closed || this.#runtimes.get(config.botId)?.status?.ready) return;
const token = await this.#resolveToken(config.tokenRef);
if (!token) {
this.#errors.set(config.botId, safeError(
'missing-token',
`${this.#descriptor.label}机器人凭据缺失,请移除后重新接入。`,
));
return;
}
try {
await this.#startRuntime(config, token);
this.#errors.delete(config.botId);
} catch (error) {
this.#errors.set(config.botId, safeError(
'connection-failed',
`${this.#descriptor.label}连接未就绪,插件会自动重试。`,
));
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] bot ${config.botId} failed to initialize:`,
error,
);
} finally {
this.#touch();
}
});
}
return this.status();
}
async bindCredentials({ token } = {}) {
if (this.#closed) throw new Error(`${this.#descriptor.label} controller is closed`);
const normalizedToken = cleanString(token);
if (!normalizedToken) throw new TypeError(`${this.#descriptor.label} Bot Token is required`);
const inspected = await this.#inspectToken(normalizedToken);
const platformId = cleanString(inspected?.platformId);
const name = cleanString(inspected?.name);
if (!platformId || !name) throw new Error(`${this.#descriptor.label} returned an invalid bot identity`);
const identity = this.#deriveIdentity(platformId);
await this.#withBotTransition(identity.botId, async () => {
if (this.#closed) throw new Error(`${this.#descriptor.label} controller is closed`);
const previousConfig = this.#configStore.getByPlatformId(platformId);
const previousToken = await this.#credentials.resolve(identity.tokenRef).catch(() => undefined);
const config = {
botId: identity.botId,
platformId,
tokenRef: identity.tokenRef,
name,
username: cleanString(inspected.username),
createdAt: previousConfig?.createdAt ?? new Date().toISOString(),
connectedAt: new Date().toISOString(),
};
await this.#credentials.set(identity.tokenRef, normalizedToken);
try {
await this.#configStore.save(config);
} catch (error) {
await this.#restoreCredential(identity.tokenRef, previousToken);
throw error;
}
try {
await this.#startRuntime(config, normalizedToken);
this.#errors.delete(identity.botId);
} catch (error) {
this.#errors.set(identity.botId, safeError(
'connection-failed',
`${this.#descriptor.label}机器人已接入,消息连接暂未就绪。`,
));
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] bot ${identity.botId} credential connection failed:`,
error,
);
}
this.#touch();
});
return this.status();
}
async reconnectBot(botId) {
const config = this.#configStore.get(botId);
if (!config) throw new Error(`Unknown ${this.#descriptor.label} bot`);
await this.#withBotTransition(botId, async () => {
const token = await this.#resolveToken(config.tokenRef);
if (!token) throw new Error(`${this.#descriptor.label} bot token is missing`);
try {
await this.#startRuntime(config, token);
this.#errors.delete(botId);
} catch (error) {
this.#errors.set(botId, safeError(
'connection-failed',
`${this.#descriptor.label}连接仍未就绪,请稍后重试。`,
));
throw error;
} finally {
this.#touch();
}
});
return this.status();
}
async deleteBot(botId) {
const config = this.#configStore.get(botId);
if (!config) throw new Error(`Unknown ${this.#descriptor.label} bot`);
await this.#withBotTransition(botId, async () => {
const previous = await this.#credentials.resolve(config.tokenRef).catch(() => undefined);
await this.#stopRuntime(botId);
try {
await this.#credentials.unset(config.tokenRef);
await this.#configStore.remove(botId);
} catch (error) {
if (previous?.value) {
await this.#credentials.set(config.tokenRef, previous.value).catch(() => undefined);
await this.#startRuntime(config, previous.value).catch(() => undefined);
}
throw new Error(`Unable to remove the ${this.#descriptor.label} bot safely.`, { cause: error });
}
await this.#deleteState({ botId, config }).catch((error) => {
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] bot ${botId} state cleanup failed:`,
error,
);
});
this.#errors.delete(botId);
this.#touch();
});
return this.status();
}
status() {
const bots = this.#configStore.list().map((config) => {
const runtimeStatus = this.#runtimes.get(config.botId)?.status ?? null;
const connected = runtimeStatus?.ready === true
&& runtimeStatus.connectionState === 'connected'
&& runtimeStatus.harnessReachable === true;
const state = connected ? 'connected'
: runtimeStatus?.connectionState === 'connecting' ? 'connecting'
: this.#errors.has(config.botId) || runtimeStatus?.connectionState === 'failed'
? 'error' : 'offline';
return {
botId: config.botId,
state,
connected,
configured: true,
bot: {
name: config.name,
username: config.username,
idMasked: this.#maskPlatformId(config.platformId),
},
health: {
status: connected ? 'healthy' : state === 'error' ? 'error' : 'offline',
summary: connected ? `${this.#descriptor.label}${this.#descriptor.connectionLabel}运行正常`
: state === 'error' ? `${this.#descriptor.label}连接未就绪,插件会自动重试`
: `${this.#descriptor.label}连接当前离线`,
lastCheckedAt: runtimeStatus?.lastCheckedAt ?? null,
lastConnectedAt: runtimeStatus?.lastConnectedAt ?? null,
},
stats: {
messagesReceived: runtimeStatus?.messagesReceived ?? 0,
messagesReplied: runtimeStatus?.messagesReplied ?? 0,
},
error: structuredClone(this.#errors.get(config.botId) ?? null),
};
});
const connectedCount = bots.filter((bot) => bot.connected).length;
return {
schemaVersion: 1,
revision: this.#revision,
state: bots.length === 0 ? 'disconnected'
: connectedCount === bots.length ? 'connected'
: connectedCount > 0 ? 'degraded' : 'offline',
bots,
totals: { configured: bots.length, connected: connectedCount },
};
}
async close() {
if (this.#closed) return;
this.#closed = true;
await Promise.allSettled([...this.#transitions.values()]);
await Promise.allSettled([...this.#runtimes.keys()].map((botId) => this.#stopRuntime(botId)));
}
async #startRuntime(config, token) {
if (this.#closed) throw new Error(`${this.#descriptor.label} controller is closed`);
await this.#stopRuntime(config.botId);
if (this.#closed) throw new Error(`${this.#descriptor.label} controller is closed`);
const runtime = await this.#createRuntime({ botId: config.botId, config, token });
if (!runtime || typeof runtime.start !== 'function' || typeof runtime.stop !== 'function') {
throw new TypeError(`createRuntime returned an invalid ${this.#descriptor.label} runtime`);
}
this.#runtimes.set(config.botId, runtime);
try {
await runtime.start();
} catch (error) {
await runtime.stop().catch(() => undefined);
this.#runtimes.delete(config.botId);
throw error;
}
}
async #stopRuntime(botId) {
const runtime = this.#runtimes.get(botId);
this.#runtimes.delete(botId);
await runtime?.stop().catch((error) => {
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] bot ${botId} failed to stop cleanly:`,
error,
);
});
}
async #resolveToken(ref) {
const result = await this.#credentials.resolve(ref).catch(() => undefined);
return cleanString(result?.value);
}
async #restoreCredential(ref, previous) {
if (previous?.value) await this.#credentials.set(ref, previous.value).catch(() => undefined);
else await this.#credentials.unset(ref).catch(() => undefined);
}
#withBotTransition(botId, operation) {
const previous = this.#transitions.get(botId) ?? Promise.resolve();
const current = previous.catch(() => undefined).then(operation);
const settled = current.finally(() => {
if (this.#transitions.get(botId) === settled) this.#transitions.delete(botId);
});
this.#transitions.set(botId, settled);
return settled;
}
#touch() {
this.#revision += 1;
}
}

View file

@ -0,0 +1,180 @@
import { createHash } from 'node:crypto';
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
const EMPTY_DOCUMENT = Object.freeze({ version: 1, bots: Object.freeze([]) });
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function escapePattern(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export function deriveTokenBotIdentity(platformId, { botPrefix, tokenRefPrefix }) {
const raw = cleanString(platformId);
if (!raw) throw new TypeError('platformId is required');
const digest = createHash('sha256').update(raw).digest('hex').slice(0, 24);
return {
botId: `${botPrefix}_${digest}`,
tokenRef: `${tokenRefPrefix}_${digest.toUpperCase()}`,
};
}
export function maskPlatformId(platformId, fallback) {
const value = cleanString(platformId) ?? '';
if (value.length <= 10) return value ? `${value.slice(0, 3)}•••` : fallback;
return `${value.slice(0, 6)}••••${value.slice(-4)}`;
}
export class TokenBotConfigStore {
#path;
#channel;
#botPrefix;
#tokenRefPrefix;
#botIdPattern;
#tokenRefPattern;
#value = EMPTY_DOCUMENT;
#writeQueue = Promise.resolve();
constructor(path, { channel, botPrefix, tokenRefPrefix }) {
this.#path = path;
this.#channel = channel;
this.#botPrefix = botPrefix;
this.#tokenRefPrefix = tokenRefPrefix;
this.#botIdPattern = new RegExp(`^${escapePattern(botPrefix)}_[a-f0-9]{24}$`);
this.#tokenRefPattern = new RegExp(`^${escapePattern(tokenRefPrefix)}_[A-F0-9]{24}$`);
}
async load() {
try {
const normalized = this.#normalizeDocument(JSON.parse(await readFile(this.#path, 'utf8')));
if (!normalized) throw new Error(`dsh-im ${this.#channel} config contains invalid bot data`);
this.#value = normalized;
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
this.#value = EMPTY_DOCUMENT;
}
return this;
}
list() {
return structuredClone(this.#value.bots);
}
get(botId) {
const bot = this.#value.bots.find((candidate) => candidate.botId === botId);
return bot ? structuredClone(bot) : null;
}
getByPlatformId(platformId) {
const bot = this.#value.bots.find((candidate) => candidate.platformId === platformId);
return bot ? structuredClone(bot) : null;
}
async save(value) {
const normalized = this.#normalizeBot(value);
if (!normalized) throw new Error(`Refusing to persist incomplete ${this.#channel} bot data`);
return this.#mutate((bots) => {
const identityCollision = bots.find(
(bot) => bot.platformId === normalized.platformId && bot.botId !== normalized.botId,
);
const refCollision = bots.find(
(bot) => bot.tokenRef === normalized.tokenRef && bot.botId !== normalized.botId,
);
if (identityCollision || refCollision) throw new Error(`Duplicate ${this.#channel} bot identity`);
const index = bots.findIndex((bot) => bot.botId === normalized.botId);
if (index === -1) bots.push(normalized);
else bots[index] = normalized;
return structuredClone(normalized);
});
}
async remove(botId) {
if (!this.#botIdPattern.test(botId)) throw new TypeError(`Invalid ${this.#channel} bot id`);
return this.#mutate((bots) => {
const index = bots.findIndex((bot) => bot.botId === botId);
if (index === -1) return null;
const [removed] = bots.splice(index, 1);
return structuredClone(removed);
});
}
async clear() {
const operation = this.#writeQueue.then(async () => {
try {
await unlink(this.#path);
} catch (error) {
if (error?.code !== 'ENOENT') throw error;
}
this.#value = EMPTY_DOCUMENT;
});
this.#writeQueue = operation.then(() => undefined, () => undefined);
await operation;
}
#normalizeBot(value) {
if (!value || typeof value !== 'object') return null;
const platformId = cleanString(value.platformId);
const botId = cleanString(value.botId);
const tokenRef = cleanString(value.tokenRef);
const name = cleanString(value.name);
if (!platformId || !botId || !tokenRef || !name
|| !this.#botIdPattern.test(botId) || !this.#tokenRefPattern.test(tokenRef)) return null;
const derived = deriveTokenBotIdentity(platformId, {
botPrefix: this.#botPrefix,
tokenRefPrefix: this.#tokenRefPrefix,
});
if (derived.botId !== botId || derived.tokenRef !== tokenRef) return null;
return Object.freeze({
botId,
platformId,
tokenRef,
name,
username: cleanString(value.username),
createdAt: cleanString(value.createdAt) ?? new Date().toISOString(),
connectedAt: cleanString(value.connectedAt),
});
}
#normalizeDocument(value) {
if (!value || value.version !== 1 || !Array.isArray(value.bots)) return null;
const bots = value.bots.map((bot) => this.#normalizeBot(bot));
if (bots.some((bot) => bot === null)) return null;
const ids = new Set();
const platformIds = new Set();
const refs = new Set();
for (const bot of bots) {
if (ids.has(bot.botId) || platformIds.has(bot.platformId) || refs.has(bot.tokenRef)) return null;
ids.add(bot.botId);
platformIds.add(bot.platformId);
refs.add(bot.tokenRef);
}
return Object.freeze({ version: 1, bots: Object.freeze(bots) });
}
async #mutate(mutator) {
let result;
const operation = this.#writeQueue.then(async () => {
const bots = [...this.#value.bots];
result = mutator(bots);
const document = Object.freeze({ version: 1, bots: Object.freeze(bots) });
await this.#write(document);
this.#value = document;
});
this.#writeQueue = operation.then(() => undefined, () => undefined);
await operation;
return result;
}
async #write(document) {
await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
const temporary = `${this.#path}.tmp`;
await writeFile(temporary, `${JSON.stringify(document, null, 2)}\n`, {
encoding: 'utf8',
mode: 0o600,
});
await rename(temporary, this.#path);
}
}