File size: 3,689 Bytes
7acdcc9
 
 
71f083d
7acdcc9
 
49a03ba
7acdcc9
49a03ba
 
7acdcc9
49a03ba
 
7acdcc9
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d6c14d
49a03ba
 
7acdcc9
49a03ba
 
7acdcc9
49a03ba
 
 
 
 
 
 
 
6d6c14d
 
 
 
 
7acdcc9
 
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
 * @param {{assertActive: () => void, abortError: () => Error,
 *   trackResource: (cleanup: () => void) => () => void,
 *   request: (url: string, timeout: number, options: {signal: AbortSignal | undefined, priority: RequestPriority}) => Promise<Response>,
 *   readBytes: (response: Response) => Promise<Uint8Array<ArrayBuffer>>, timeoutMs: number}} options
 */
export function createReaderImageLoader({assertActive, abortError, trackResource, request, readBytes, timeoutMs}) {
  /** @param {HTMLImageElement} image @param {string} target @param {number} timeoutMs @param {AbortSignal | undefined} signal */
  function wait(image, target, timeoutMs, signal) {
    assertActive();
    return /** @type {Promise<HTMLImageElement>} */ (new Promise((resolve, reject) => {
      let settled = false, timeout = 0, untrack = () => {};
      const abort = () => finish(abortError());
      /** @param {Error} [error] */
      const finish = (error) => {
        if (settled) return;
        settled = true;
        clearTimeout(timeout);
        untrack();
        signal?.removeEventListener("abort", abort);
        image.onload = image.onerror = null;
        if (error) {
          image.removeAttribute("src");
          reject(error);
        } else resolve(image);
      };
      untrack = trackResource(() => finish(abortError()));
      signal?.addEventListener("abort", abort, { once: true });
      if (signal?.aborted) abort();
      if (settled) return;
      timeout = setTimeout(() => finish(new DOMException("Reader image stalled", "TimeoutError")), timeoutMs);
      image.onload = () => finish();
      image.onerror = () => finish(Object.assign(new Error("image load failed"), {code: "READER_IMAGE_LOAD"}));
      if (image.src !== new URL(target, location.href).href) image.src = target;
      if (image.complete && image.naturalWidth) finish();
    }));
  }

  /** @param {HTMLImageElement} image @param {string} target @param {AbortSignal | undefined} signal @param {number} [deadline] */
  async function load(image, target, signal, deadline = performance.now() + timeoutMs) {
    const remaining = () => Math.max(1, deadline - performance.now());
    const network = /^https?:$/.test(new URL(target, location.href).protocol);
    try {
      return await wait(image, target, Math.min(network ? 15000 : timeoutMs, remaining()), signal);
    } catch (error) {
      assertActive();
      signal?.throwIfAborted();
      // Retry the same proxied image once after a load error, including converted
      // TIFF pages. Never retry local blobs or aborted reader sessions.
      if (network && typeof error === "object" && error !== null && "code" in error &&
          error.code === "READER_IMAGE_LOAD" && performance.now() < deadline && navigator.onLine)
        return wait(image, target, Math.min(15000, remaining()), signal);
      if (!network || typeof error !== "object" || error === null || !("name" in error) ||
          error.name !== "TimeoutError" || !navigator.onLine) throw error;
    }
    const response = await request(target, remaining(),
      { signal, priority: image.fetchPriority || "auto" });
    if (!response.ok) {
      await response.body?.cancel();
      throw Object.assign(new Error(`HTTP ${response.status}`), {status: response.status});
    }
    const bytes = await readBytes(response);
    assertActive();
    signal?.throwIfAborted();
    const blobUrl = URL.createObjectURL(new Blob([bytes], {type: response.headers.get("Content-Type") || ""}));
    try {
      return await wait(image, blobUrl, Math.min(20000, remaining()), signal);
    } finally {
      URL.revokeObjectURL(blobUrl);
    }
  }

  return Object.freeze({load});
}