rpc.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { FILE_CHUNK_BYTES, type DocKind } from "#office/contract.ts";
  2. import { getHost } from "#ui/host.ts";
  3. /** A failed server tool call; `code` is the server's OfficeErrorCode when it sent one. */
  4. export class CallError extends Error {
  5. constructor(
  6. message: string,
  7. readonly code?: string,
  8. ) {
  9. super(message);
  10. this.name = "CallError";
  11. }
  12. }
  13. export async function call<T>(name: string, args: Record<string, unknown> = {}): Promise<T> {
  14. const host = getHost();
  15. await host.ready();
  16. const result = await host.app.callServerTool({ name, arguments: args });
  17. const structured = result.structuredContent as Record<string, unknown> | undefined;
  18. const error = structured?.error as { message?: string; code?: string } | undefined;
  19. if (result.isError || error) {
  20. const text = (result.content?.[0] as { text?: string } | undefined)?.text;
  21. throw new CallError(error?.message ?? text ?? `${name} failed`, error?.code);
  22. }
  23. return structured as T;
  24. }
  25. export interface WorkspaceFile {
  26. path: string;
  27. kind: DocKind;
  28. bytes: number;
  29. mtimeMs?: number;
  30. }
  31. let listing: Promise<WorkspaceFile[]> | undefined;
  32. /** Workspace documents, newest first. Cached for the page's lifetime unless `fresh`. */
  33. export function listDocuments(fresh = false): Promise<WorkspaceFile[]> {
  34. if (fresh || !listing)
  35. listing = call<{ documents: WorkspaceFile[] }>("list_documents").then(
  36. (result) => [...result.documents].sort((a, b) => (b.mtimeMs ?? 0) - (a.mtimeMs ?? 0)),
  37. (error) => {
  38. listing = undefined;
  39. throw error;
  40. },
  41. );
  42. return listing;
  43. }
  44. export const baseName = (path: string) => path.slice(path.lastIndexOf("/") + 1);
  45. export const dirName = (path: string) => {
  46. const slash = path.lastIndexOf("/");
  47. return slash > 0 ? path.slice(0, slash) : "";
  48. };
  49. /** 通过系统选择器授权的 File 分块导入,桌面与 Web 都不需要暴露本机绝对路径。 */
  50. export async function importSelectedFile(file: File): Promise<string> {
  51. const { id } = await call<{ id: string }>("begin_file_import", {
  52. name: file.name,
  53. size: file.size,
  54. });
  55. try {
  56. for (let offset = 0; offset < file.size; offset += FILE_CHUNK_BYTES) {
  57. const data = await new Promise<string>((resolve, reject) => {
  58. const reader = new FileReader();
  59. reader.onload = () => resolve(String(reader.result).split(",")[1]!);
  60. reader.onerror = () => reject(reader.error);
  61. reader.readAsDataURL(file.slice(offset, offset + FILE_CHUNK_BYTES));
  62. });
  63. await call("write_file_import", { id, offset, data });
  64. }
  65. const result = await call<{ path: string }>("finish_file_import", { id });
  66. return result.path;
  67. } catch (error) {
  68. await call("cancel_file_import", { id }).catch(() => undefined);
  69. throw error;
  70. }
  71. }