File size: 11,592 Bytes
74bdc1f
 
 
 
 
 
 
 
 
 
 
 
6c8fd46
74bdc1f
6c8fd46
68f392a
6c8fd46
2315c7d
74bdc1f
 
 
 
 
 
 
 
 
 
 
 
49a03ba
74bdc1f
49a03ba
 
9ceac12
49a03ba
 
74bdc1f
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ceac12
49a03ba
 
68f392a
49a03ba
 
 
 
74bdc1f
 
 
6c8fd46
 
 
49a03ba
 
 
6c8fd46
 
49a03ba
 
6c8fd46
49a03ba
 
 
6c8fd46
74bdc1f
6c8fd46
 
49a03ba
 
 
 
6c8fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a03ba
6c8fd46
49a03ba
6c8fd46
49a03ba
6c8fd46
49a03ba
 
d3f4b21
49a03ba
 
 
aba4489
 
 
 
 
 
 
 
 
 
2315c7d
 
aba4489
2315c7d
 
 
aba4489
6c8fd46
2315c7d
 
 
6c8fd46
 
 
aba4489
 
49a03ba
aba4489
49a03ba
 
74bdc1f
49a03ba
 
 
 
 
 
 
 
 
74bdc1f
49a03ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74bdc1f
49a03ba
 
 
 
 
 
58fdd73
 
 
 
49a03ba
 
2315c7d
 
aba4489
2315c7d
 
 
 
 
 
 
 
 
 
 
 
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/**
 * @typedef {{ status?: number, name?: string, message?: string, code?: string }} ReaderLoaderError
 * @typedef {{manifestUrl?: string, manifest?: Promise<Response> | null}} ReaderManifestPreload
 * @typedef {{response: Promise<Response>, engines: Promise<unknown[]>}} PreparedReaderDocument
 * @typedef {object} ReaderDocumentLoaderContext
 * @property {() => void} assertReaderActive
 * @property {() => Error} readerAbortError
 * @property {(cleanup: () => void) => () => void} trackReaderResource
 * @property {ReaderRequestManager} readerRequestManager
 * @property {number} READER_PROXY_TIMEOUT_MS
 * @property {(error: unknown) => boolean} retryableReaderProxyError
 * @property {(delay: number) => Promise<void>} waitForReader
 * @property {<T>(promise: T | PromiseLike<T>, signal?: AbortSignal | null) => Promise<Awaited<T>>} awaitReader
 * @property {(rawUrl: string) => string} readerContentUrl
 * @property {(path: string) => string} readerDownloadApiUrl
 * @property {(url: string, timeoutMs?: number, requestInit?: ReaderRequestInit) => Promise<Response>} fetchWithReaderTimeout
 * @property {<T>(open: () => Promise<T>, signal?: AbortSignal | null) => Promise<T>} retryReaderProxy
 * @property {(url: string, requestInit?: RequestInit, policy?: {retryBucket?: boolean}) => Promise<Response>} fetchReaderUrl
 * @property {() => Promise<Response>} fetchReaderResponse
 * @property {(tasks: Promise<unknown>[]) => PreparedReaderDocument} prepareReaderDocument
 * @property {(url: string) => Promise<void>} loadScript
 * @property {string} sourceUrl
 * @property {string | null | undefined} chapterManifestUrl
 * @property {string} MARKED_URL
 * @property {string} PURIFY_URL
 * @property {{title: string}} documentState
 * @property {AbortController} readerAbortController
 * @property {{load: (image: HTMLImageElement, url: string, signal: AbortSignal, deadline: number) => Promise<HTMLImageElement>}} imageLoader
 */
/** @param {ReaderDocumentLoaderContext} readerContext */
export function createReaderDocumentLoader(readerContext) {
  /** @param {string} url */
  function loadScript(url) {
    readerContext.assertReaderActive();
    return /** @type {Promise<void>} */ (new Promise((resolve, reject) => {
      const script = document.createElement("script");
      let settled = false, timeout = 0, untrack = () => {};
      /** @param {Error} [error] */
      const finish = (error) => {
        if (settled) return;
        settled = true;
        clearTimeout(timeout);
        untrack();
        script.onload = script.onerror = null;
        if (error) {
          script.remove();
          reject(error);
        } else resolve();
      };
      const networkError = () => Object.assign(
        new Error("阅读组件下载失败,请检查网络后重试加载,或下载原文件。"),
        { code: "READER_ENGINE_NETWORK" }
      );
      untrack = readerContext.trackReaderResource(() => finish(readerContext.readerAbortError()));
      // Download sibling engines concurrently, execute in dependency order.
      script.async = false;
      script.src = url;
      script.onload = () => finish();
      script.onerror = () => finish(networkError());
      timeout = setTimeout(() => finish(networkError()), 20000);
      document.head.appendChild(script);
    }));
  }

  /** @param {string} url @param {number} [timeoutMs] @param {ReaderRequestInit} [requestInit] */
  function fetchWithReaderTimeout(url, timeoutMs = readerContext.READER_PROXY_TIMEOUT_MS, requestInit = {}) {
    return readerContext.readerRequestManager.request(url, timeoutMs, requestInit);
  }

  /** @param {unknown} value */
  function retryableReaderProxyError(value) {
    const error = /** @type {ReaderLoaderError | null | undefined} */ (value);
    if (error?.name === "AbortError" || error?.code === "READER_BODY_INTERRUPTED") return false;
    if (typeof error?.status === "number") return [408, 429, 500, 502, 503, 504].includes(error.status);
    return /** @type {(string | undefined)[]} */ (["TypeError", "TimeoutError"]).includes(error?.name) ||
      /failed to fetch|network|timeout|HTTP\s*(?:408|429|5\d\d)|server response\s*\((?:408|429|5\d\d)\)/i.test(error?.message || "");
  }

  /** @template T @param {() => Promise<T>} open @param {AbortSignal | null} [signal] @returns {Promise<T>} */
  async function retryReaderProxy(open, signal) {
    for (let attempt = 0; ; attempt++) {
      readerContext.assertReaderActive();
      signal?.throwIfAborted();
      try {
        return await open();
      } catch (error) {
        signal?.throwIfAborted();
        if (attempt >= 2 || /** @type {ReaderLoaderError | null | undefined} */ (error)?.code === "READER_PDF_RATE_LIMIT" || !readerContext.retryableReaderProxyError(error)) throw error;
        const backoff = readerContext.waitForReader(350 * (attempt + 1));
        await (signal ? readerContext.awaitReader(backoff, signal) : backoff);
      }
    }
  }

  /** @param {string} rawUrl @param {RequestInit} [requestInit] @param {{retryBucket?: boolean}} [policy] */
  function fetchReaderUrl(rawUrl, requestInit = {}, {retryBucket = false} = {}) {
    let proxyUrl = readerContext.readerContentUrl(rawUrl), alreadyProxied = false;
    // Some chapter URLs already name the deployed API, even on a local Space
    // origin. Don't interpret an arbitrary URL containing the route as a proxy.
    try {
      const base = typeof location === "undefined" ? "https://voiceofml-search.hf.space" : location.href;
      const target = new URL(rawUrl, base);
      const proxyOrigin = new URL(readerContext.readerDownloadApiUrl("/api/reader-bucket-resource"), base).origin;
      if (["https://voiceofml-search.hf.space", proxyOrigin].includes(target.origin) &&
          !target.username && !target.password && !target.hash && target.pathname === "/api/reader-bucket-resource" &&
          target.searchParams.getAll("path").length === 1 && [...target.searchParams.keys()].every(key => key === "path")) {
        alreadyProxied = true;
        if (/^https?:\/\//.test(rawUrl)) proxyUrl = target.href;
      }
    } catch (_) {}
    // OCR and other sidecars already own their own recovery policy.
    if (alreadyProxied && !retryBucket)
      return readerContext.fetchWithReaderTimeout(proxyUrl, readerContext.READER_PROXY_TIMEOUT_MS, requestInit);
    return readerContext.retryReaderProxy(async () => {
      const response = await readerContext.fetchWithReaderTimeout(proxyUrl, readerContext.READER_PROXY_TIMEOUT_MS, requestInit);
      if (response.ok) return response;
      void response.body?.cancel().catch(() => {});
      throw Object.assign(new Error(`HTTP ${response.status}`), { status: response.status });
    }, requestInit.signal).catch(error => {
      readerContext.assertReaderActive();
      requestInit.signal?.throwIfAborted();
      throw error;
    });
  }

  /** @param {string} target @param {ReaderManifestPreload | undefined} early */
  function takeMatchingManifestPreload(target, early) {
    if (!early) return null;
    const pending = early.manifest;
    if (!pending) return null;
    if (early.manifestUrl !== new URL(target, location.href).href) return null;
    early.manifest = null;
    return pending;
  }

  /** @param {string} target @param {ReaderManifestPreload | undefined} early @param {boolean} [retryBucket] */
  function fetchManifestWithPreload(target, early, retryBucket = false) {
    const pending = takeMatchingManifestPreload(target, early);
    const fallback = () => retryBucket
      ? readerContext.fetchReaderUrl(target, { signal: readerContext.readerAbortController.signal }, {retryBucket})
      : readerContext.fetchReaderUrl(target);
    if (!pending) return fallback();
    return pending.then(response => {
      // A matching chapter preload can also tell us the manifest is missing.
      // Do not fetch it again just to rediscover a permanent HTTP error.
      if (response?.ok || (retryBucket && response && !readerContext.retryableReaderProxyError(response))) return response;
      void response?.body?.cancel().catch(() => {});
      return fallback();
    }, fallback);
  }

  function fetchReaderResponse() {
    return fetchManifestWithPreload(readerContext.sourceUrl, window.__VOICE_PDF_PRELOAD__);
  }

  /** @param {Promise<unknown>[]} engineTasks @returns {PreparedReaderDocument} */
  function prepareReaderDocument(engineTasks) {
    const engines = Promise.all(engineTasks);
    const response = Promise.race([readerContext.fetchReaderResponse(), engines.then(() => new Promise(() => {}))]);
    // Rendering owns both promises; early rejection must not become unhandled.
    response.catch(() => {});
    engines.catch(() => {});
    return {response, engines};
  }

  /** @param {Promise<Response>} response @param {Promise<unknown>} engines @param {number} [limit] */
  function readPreparedBytes(response, engines, limit = VoiceOfMLReaderSecurity.LIMITS.documentBytes) {
    return Promise.all([Promise.resolve(response).then(response => {
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      return VoiceOfMLReaderSecurity.readBytes(response,limit);
    }), engines]).then(([bytes]) => bytes);
  }

  function loadTextDocument() {
    return readerContext.fetchReaderResponse().then((response) => ({ response }));
  }

  function loadMarkdownDocument() {
    return readerContext.prepareReaderDocument([readerContext.loadScript(readerContext.MARKED_URL), readerContext.loadScript(readerContext.PURIFY_URL)]);
  }

  function loadHtmlDocument() {
    const {response, engines} = readerContext.prepareReaderDocument([readerContext.loadScript(readerContext.PURIFY_URL)]);
    return {response, engine:engines};
  }

  /** @param {string} [target] */
  async function loadImageDocument(target = readerContext.sourceUrl) {
    const deadline = performance.now() + readerContext.READER_PROXY_TIMEOUT_MS;
    const image = new Image();
    image.className = "reader-image";
    image.alt = readerContext.documentState.title;
    image.decoding = "async";
    readerContext.assertReaderActive();
    // Do not fall through to the dataset URL. huggingface.co does not open on
    // this network, so a failed proxy must stay on the proxied URL.
    return readerContext.imageLoader.load(image, readerContext.readerContentUrl(target), readerContext.readerAbortController.signal, deadline);
  }

  async function loadChapterManifestDocument() {
    readerContext.assertReaderActive();
    const target = readerContext.chapterManifestUrl || readerContext.sourceUrl;
    try {
      const response = await fetchManifestWithPreload(target, window.__VOICE_READER_CHAPTER_PRELOAD__, true);
      if (!response.ok || readerContext.readerAbortController.signal.aborted)
        void response.body?.cancel().catch(() => {});
      readerContext.assertReaderActive();
      if (!response.ok) throw Object.assign(new Error(`HTTP ${response.status}`), { status: response.status });
      return response;
    } catch (error) {
      readerContext.assertReaderActive();
      if (!readerContext.retryableReaderProxyError(error)) throw error;
      throw Object.assign(new Error("Chapter manifest request failed", {cause: error}), {code: "READER_CHAPTER_MANIFEST_TRANSIENT"});
    }
  }

  return {
    loadScript,
    fetchWithReaderTimeout,
    retryableReaderProxyError,
    retryReaderProxy,
    fetchReaderUrl,
    fetchReaderResponse,
    prepareReaderDocument,
    readPreparedBytes,
    loadTextDocument,
    loadMarkdownDocument,
    loadHtmlDocument,
    loadImageDocument,
    loadChapterManifestDocument
  };
}