2026-02-15 13:30:37 +00:00
|
|
|
import type { ChatAttachment } from "../chat-attachments.js";
|
|
|
|
|
|
|
|
|
|
export type RpcAttachmentInput = {
|
|
|
|
|
type?: unknown;
|
|
|
|
|
mimeType?: unknown;
|
|
|
|
|
fileName?: unknown;
|
|
|
|
|
content?: unknown;
|
2026-03-18 20:12:30 -07:00
|
|
|
source?: unknown;
|
2026-02-15 13:30:37 +00:00
|
|
|
};
|
|
|
|
|
|
2026-03-18 20:12:30 -07:00
|
|
|
function normalizeAttachmentContent(content: unknown): string | undefined {
|
|
|
|
|
if (typeof content === "string") {
|
|
|
|
|
return content;
|
|
|
|
|
}
|
|
|
|
|
if (ArrayBuffer.isView(content)) {
|
|
|
|
|
return Buffer.from(content.buffer, content.byteOffset, content.byteLength).toString("base64");
|
|
|
|
|
}
|
|
|
|
|
if (content instanceof ArrayBuffer) {
|
|
|
|
|
return Buffer.from(content).toString("base64");
|
|
|
|
|
}
|
|
|
|
|
return undefined;
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-15 13:30:37 +00:00
|
|
|
export function normalizeRpcAttachmentsToChatAttachments(
|
|
|
|
|
attachments: RpcAttachmentInput[] | undefined,
|
|
|
|
|
): ChatAttachment[] {
|
|
|
|
|
return (
|
|
|
|
|
attachments
|
2026-03-18 20:12:30 -07:00
|
|
|
?.map((a) => {
|
|
|
|
|
const source = a?.source && typeof a.source === "object" ? a.source : undefined;
|
|
|
|
|
const sourceRecord = source as
|
|
|
|
|
| { type?: unknown; media_type?: unknown; data?: unknown }
|
|
|
|
|
| undefined;
|
|
|
|
|
const sourceType = typeof sourceRecord?.type === "string" ? sourceRecord.type : undefined;
|
|
|
|
|
const sourceMimeType =
|
|
|
|
|
typeof sourceRecord?.media_type === "string" ? sourceRecord.media_type : undefined;
|
|
|
|
|
const sourceContent =
|
|
|
|
|
sourceType === "base64" ? normalizeAttachmentContent(sourceRecord?.data) : undefined;
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
type: typeof a?.type === "string" ? a.type : undefined,
|
|
|
|
|
mimeType: typeof a?.mimeType === "string" ? a.mimeType : sourceMimeType,
|
|
|
|
|
fileName: typeof a?.fileName === "string" ? a.fileName : undefined,
|
|
|
|
|
content: normalizeAttachmentContent(a?.content) ?? sourceContent,
|
|
|
|
|
};
|
|
|
|
|
})
|
2026-02-15 13:30:37 +00:00
|
|
|
.filter((a) => a.content) ?? []
|
|
|
|
|
);
|
|
|
|
|
}
|