示例工程 32-deep-links-file-association

32-deep-links-file-association/app/shared/ipc.ts

typescript · 1.6 KB

export const CH = {
  get: "links:get",
  simulateUrl: "links:simulate-url",
  simulateFile: "links:simulate-file",
  simulateSecond: "links:simulate-second",
  clear: "links:clear",
  changed: "links:changed",
} as const;

export type LinkResult = {
  ok: boolean;
  kind: "open" | "search" | "none";
  label: string;
  detail: string;
};

export type FileResult = {
  ok: boolean;
  path: string;
  title: string;
  body: string;
  size: number;
  error: string;
};

export type LinkEvent = {
  at: number;
  source: "open-url" | "second-instance" | "open-file" | "simulate" | "system";
  text: string;
};

export type LinksSnapshot = {
  platform: string;
  packaged: boolean;
  protocolRegistered: boolean;
  singleInstance: boolean;
  samplePath: string;
  lastLink: LinkResult | null;
  lastFile: FileResult | null;
  lastError: string;
  events: LinkEvent[];
};

export function assertUrlReq(value: unknown): asserts value is { url: string } {
  if (typeof value !== "object" || value === null) {
    throw new Error("BAD_URL_REQ");
  }
  const url = (value as { url?: unknown }).url;
  if (typeof url !== "string" || url.length === 0 || url.length > 4096) {
    throw new Error("BAD_URL_REQ");
  }
}

export function assertFileReq(
  value: unknown,
): asserts value is { path: string } {
  if (typeof value !== "object" || value === null) {
    throw new Error("BAD_FILE_REQ");
  }
  const filePath = (value as { path?: unknown }).path;
  if (
    typeof filePath !== "string" ||
    filePath.length === 0 ||
    filePath.length > 4096
  ) {
    throw new Error("BAD_FILE_REQ");
  }
}