assets.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { ASSET_PREFIX, FILE_PREFIX, type FileHandle } from "#office/contract.ts";
  2. import { getHost } from "#ui/host.ts";
  3. async function read(uri: string) {
  4. const host = getHost();
  5. await host.ready();
  6. const result = await host.app.readServerResource({ uri });
  7. const item = result.contents[0];
  8. if (!item) throw new Error(`Empty resource ${uri}`);
  9. return item as { text?: string; blob?: string };
  10. }
  11. export async function readText(name: string): Promise<string> {
  12. const item = await read(ASSET_PREFIX + name);
  13. if (typeof item.text !== "string") throw new Error(`Asset ${name} is not text`);
  14. return item.text;
  15. }
  16. function decode(base64: string): Uint8Array<ArrayBuffer> {
  17. const binary = atob(base64);
  18. const bytes = new Uint8Array(binary.length);
  19. for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
  20. return bytes;
  21. }
  22. const binaryCache = new Map<string, Promise<Uint8Array<ArrayBuffer>>>();
  23. /** Binary asset (wasm, pdf.js cMaps and fonts); cached for the life of the page. */
  24. export function readBinary(name: string): Promise<Uint8Array<ArrayBuffer>> {
  25. let cached = binaryCache.get(name);
  26. if (!cached) {
  27. cached = read(ASSET_PREFIX + name).then((item) => {
  28. if (typeof item.blob !== "string") throw new Error(`Asset ${name} is not binary`);
  29. return decode(item.blob);
  30. });
  31. cached.catch(() => binaryCache.delete(name));
  32. binaryCache.set(name, cached);
  33. }
  34. return cached;
  35. }
  36. /** Read a loaded document's bytes chunk by chunk. */
  37. export async function readFileBytes(
  38. handle: FileHandle,
  39. signal?: AbortSignal,
  40. ): Promise<ArrayBuffer> {
  41. const out = new Uint8Array(handle.bytes);
  42. let offset = 0;
  43. for (let index = 0; index < handle.chunks; index++) {
  44. signal?.throwIfAborted();
  45. const item = await read(`${FILE_PREFIX}${handle.token}/${index}`);
  46. if (typeof item.blob !== "string") throw new Error("File chunk is not binary");
  47. const chunk = decode(item.blob);
  48. out.set(chunk, offset);
  49. offset += chunk.byteLength;
  50. }
  51. if (offset !== handle.bytes) throw new Error("The file changed while it was loading; reload it.");
  52. return out.buffer;
  53. }