@tanstack/ai-persistence
Version:
Composable state persistence for TanStack AI messages, runs, interrupts, metadata, and locks.
47 lines (46 loc) • 1.37 kB
JavaScript
//#region src/merge-stored.ts
function mergeStoredMessages(stored, incoming) {
if (incoming.length === 0) return stored.slice();
let cutoff = stored.length;
for (let index = incoming.length - 1; index >= 0; index--) {
const id = incoming[index]?.id;
if (id === void 0) continue;
const storedIndex = stored.findIndex((message) => message.id === id);
if (storedIndex >= 0) {
cutoff = storedIndex + 1;
break;
}
}
const prefix = stored.slice(0, cutoff);
const incomingById = /* @__PURE__ */ new Map();
for (const message of incoming) {
const id = message.id;
if (id) incomingById.set(id, message);
}
const storedIds = /* @__PURE__ */ new Set();
const merged = [];
for (const message of prefix) {
const id = message.id;
if (id) {
storedIds.add(id);
merged.push(incomingById.get(id) ?? message);
continue;
}
merged.push(message);
}
for (let index = 0; index < incoming.length; index++) {
const message = incoming[index];
if (!message) continue;
const id = message.id;
if (id && storedIds.has(id)) continue;
if (!id) {
const existing = merged[index];
if (existing && existing.id === void 0 && existing.role === message.role && existing.content === message.content) continue;
}
merged.push(message);
}
return merged;
}
//#endregion
export { mergeStoredMessages };
//# sourceMappingURL=merge-stored.js.map