示例工程 13-project-file-explorer

13-project-file-explorer/app/shared/ipc.ts

typescript · 2.4 KB

export const CH = {
  tree: "fs:tree",
  read: "fs:read",
  save: "fs:save",
  reset: "fs:reset",
} as const;

export type Entry = {
  path: string;
  name: string;
  type: "file" | "dir";
  depth: number;
  sizeBytes: number;
};

export type FileRead = {
  path: string;
  content: string;
  sizeBytes: number;
  updatedAt: number;
};

export type SaveResult = {
  path: string;
  sizeBytes: number;
  updatedAt: number;
};

export type PublicError = {
  code: string;
  message: string;
  detail?: string;
  requestId: string;
};

export type Envelope<T> =
  { ok: true; value: T; requestId: string } | { ok: false; error: PublicError };

export class WorkspaceError extends Error {
  readonly code: string;
  readonly detail?: string;

  constructor(code: string, message: string, detail?: string) {
    super(message);
    this.name = "WorkspaceError";
    this.code = code;
    this.detail = detail;
  }
}

export function toPublicError(error: unknown, requestId: string): PublicError {
  if (error instanceof WorkspaceError) {
    return {
      code: error.code,
      message: error.message,
      ...(error.detail ? { detail: error.detail } : {}),
      requestId,
    };
  }
  return {
    code: "INTERNAL",
    message: "内部错误,请稍后重试",
    requestId,
  };
}

export function parsePathReq(value: unknown): { path: string } {
  if (typeof value !== "object" || value === null) {
    throw new WorkspaceError("BAD_SHAPE", "请求必须是对象");
  }
  const path = (value as { path?: unknown }).path;
  if (
    typeof path !== "string" ||
    path.length === 0 ||
    path.length > 200 ||
    path.includes("\0")
  ) {
    throw new WorkspaceError(
      "BAD_PATH",
      "path 必须是 1–200 字符的字符串",
      "path",
    );
  }
  return { path };
}

export function parseSaveReq(value: unknown): {
  path: string;
  content: string;
} {
  if (typeof value !== "object" || value === null) {
    throw new WorkspaceError("BAD_SHAPE", "请求必须是对象");
  }
  const record = value as Record<string, unknown>;
  const { path } = parsePathReq({ path: record.path });
  if (typeof record.content !== "string") {
    throw new WorkspaceError("BAD_CONTENT", "content 必须是字符串", "content");
  }
  if (record.content.length > 100_000) {
    throw new WorkspaceError(
      "CONTENT_TOO_LONG",
      "content 不能超过 100000 字符",
      "content",
    );
  }
  return { path, content: record.content };
}