ai-chatbot/lib/agents/psd-local-cache.ts
Your Name db46934025
Some checks failed
Lint / build (20) (push) Has been cancelled
Playwright Tests / test (push) Has been cancelled
fix: stabilize PSD template parsing workflow
2026-04-10 21:03:59 +08:00

100 lines
2.4 KiB
TypeScript

import "server-only";
import os from "node:os";
import path from "node:path";
import { promises as fs } from "node:fs";
const PSD_LOCAL_CACHE_ROOT = path.join(
process.env.AGENT_PSD_LOCAL_CACHE_DIR || os.tmpdir(),
"agent-psd-cache"
);
function sanitizePathSegment(value: string, fallback: string) {
const normalized = String(value || "")
.trim()
.replace(/[^a-zA-Z0-9_-]/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "");
return normalized || fallback;
}
function normalizeTemplateExtension(fileName: string) {
const normalized = String(fileName || "").trim().toLowerCase();
if (normalized.endsWith(".psb")) {
return "psb";
}
return "psd";
}
function toBuffer(value: ArrayBuffer | Buffer) {
if (Buffer.isBuffer(value)) {
return value;
}
return Buffer.from(value);
}
export function resolveAgentPsdLocalCachePath(params: {
templateId: string;
fileName?: string | null;
}) {
const templateId = sanitizePathSegment(params.templateId, "template");
const extension = normalizeTemplateExtension(String(params.fileName || ""));
return path.join(PSD_LOCAL_CACHE_ROOT, `${templateId}.${extension}`);
}
export async function cacheAgentPsdSourceLocally(params: {
templateId: string;
fileName?: string | null;
buffer: ArrayBuffer | Buffer;
}) {
const localFilePath = resolveAgentPsdLocalCachePath({
templateId: params.templateId,
fileName: params.fileName,
});
await fs.mkdir(path.dirname(localFilePath), { recursive: true });
await fs.writeFile(localFilePath, toBuffer(params.buffer));
return localFilePath;
}
export async function readAgentPsdSourceFromLocalCache(params: {
templateId: string;
fileName?: string | null;
}) {
return fs.readFile(
resolveAgentPsdLocalCachePath({
templateId: params.templateId,
fileName: params.fileName,
})
);
}
export async function hasAgentPsdLocalCache(params: {
templateId: string;
fileName?: string | null;
}) {
try {
await fs.access(
resolveAgentPsdLocalCachePath({
templateId: params.templateId,
fileName: params.fileName,
})
);
return true;
} catch {
return false;
}
}
export async function deleteAgentPsdLocalCache(params: {
templateId: string;
fileName?: string | null;
}) {
const localFilePath = resolveAgentPsdLocalCachePath({
templateId: params.templateId,
fileName: params.fileName,
});
await fs.rm(localFilePath, { force: true });
}