tempTextAttachment.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { randomUUID } from "node:crypto";
  3. import { join } from "node:path";
  4. import { getZCodeDataRootDir } from "@zcode/services/node";
  5. import type {
  6. CreateTempTextAttachmentRequest,
  7. CreateTempTextAttachmentResult,
  8. } from "@zcode/shared";
  9. const TEMP_TEXT_ATTACHMENT_DIR = "paste-attachments";
  10. const MIME_TYPE = "text/plain" as const;
  11. export async function createTempTextAttachment(
  12. payload: CreateTempTextAttachmentRequest,
  13. ): Promise<CreateTempTextAttachmentResult> {
  14. if (typeof payload.text !== "string" || payload.text.length === 0) {
  15. throw new Error("Temporary text attachment content is empty");
  16. }
  17. const now = new Date();
  18. const dateDir = [now.getFullYear(), pad(now.getMonth() + 1), pad(now.getDate())].join("-");
  19. const rootDir = join(getZCodeDataRootDir(), "tmp", TEMP_TEXT_ATTACHMENT_DIR, dateDir);
  20. await mkdir(rootDir, { recursive: true });
  21. const filename = buildTempTextAttachmentFilename(payload.filename);
  22. const localPath = join(rootDir, filename);
  23. const content = Buffer.from(payload.text, "utf8");
  24. await writeFile(localPath, content, { flag: "wx" });
  25. return {
  26. filename,
  27. localPath,
  28. mimeType: MIME_TYPE,
  29. sizeBytes: content.byteLength,
  30. };
  31. }
  32. function buildTempTextAttachmentFilename(filename: string | undefined): string {
  33. const rawBase = filename?.trim() || "pasted-text.txt";
  34. const normalized = rawBase.replaceAll("\0", "-").replace(/[\\/:]/gu, "-");
  35. const safeName = normalized.endsWith(".txt") ? normalized : `${normalized}.txt`;
  36. const suffix = randomUUID().slice(0, 8);
  37. const dotIndex = safeName.lastIndexOf(".");
  38. if (dotIndex <= 0) {
  39. return `${safeName}-${suffix}.txt`;
  40. }
  41. return `${safeName.slice(0, dotIndex)}-${suffix}${safeName.slice(dotIndex)}`;
  42. }
  43. function pad(value: number): string {
  44. return String(value).padStart(2, "0");
  45. }