ai-chatbot/lib/agents/psd-template-format.ts

74 lines
1.8 KiB
TypeScript

import "server-only";
export type AgentPsdTemplateFileFormat = "psd" | "psb" | "unknown";
export interface AgentPsdTemplateFileInspection {
signature: string;
version: number;
format: AgentPsdTemplateFileFormat;
channels: number;
height: number;
width: number;
depth: number;
colorMode: number;
}
export const AGENT_PSD_TEMPLATE_INVALID_FORMAT_MESSAGE =
"模板文件格式不正确,请上传 Photoshop PSD / PSB 文件。";
export const AGENT_PSD_TEMPLATE_INCOMPATIBLE_PSB_MESSAGE =
"当前 PSB 文件包含现有解析器暂不兼容的图层扩展信息,请在 Photoshop 中另存为 PSD 后再上传解析。";
export function inspectAgentPsdTemplateFile(
value: ArrayBuffer | Buffer
): AgentPsdTemplateFileInspection {
const buffer = Buffer.isBuffer(value)
? value
: Buffer.from(value);
if (buffer.byteLength < 26) {
return {
signature: "",
version: 0,
format: "unknown",
channels: 0,
height: 0,
width: 0,
depth: 0,
colorMode: 0,
};
}
const signature = buffer.subarray(0, 4).toString("ascii");
const version = buffer.readUInt16BE(4);
const format =
signature === "8BPS" && version === 1
? "psd"
: signature === "8BPS" && version === 2
? "psb"
: "unknown";
return {
signature,
version,
format,
channels: buffer.readUInt16BE(12),
height: buffer.readUInt32BE(14),
width: buffer.readUInt32BE(18),
depth: buffer.readUInt16BE(22),
colorMode: buffer.readUInt16BE(24),
};
}
export function assertSupportedAgentPsdTemplateFile(
value: ArrayBuffer | Buffer
) {
const inspection = inspectAgentPsdTemplateFile(value);
if (inspection.format === "psd" || inspection.format === "psb") {
return inspection;
}
throw new Error(AGENT_PSD_TEMPLATE_INVALID_FORMAT_MESSAGE);
}