File size: 23,713 Bytes
dac2ca2
7dac701
8268665
722c78c
 
a191f34
 
 
 
 
 
dac2ca2
52361de
 
 
 
a191f34
 
 
 
8268665
 
7b2f60d
 
52361de
56c51f4
90a0da1
7b2f60d
 
 
 
 
 
 
 
 
dac2ca2
52361de
 
 
 
 
 
 
7b2f60d
 
52361de
 
 
 
 
7b2f60d
 
52361de
 
 
 
 
a191f34
7b2f60d
a191f34
 
8268665
a191f34
ee10dd3
 
 
 
 
 
 
 
dac2ca2
ee10dd3
 
 
 
 
 
 
 
 
 
90a0da1
ee10dd3
dac2ca2
ee10dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dac701
 
 
 
 
52361de
7dac701
dac2ca2
7dac701
52361de
 
c3a96a2
0bd6c4a
52361de
 
 
 
 
 
ec64e3c
 
52361de
 
 
 
 
ec64e3c
 
52361de
 
 
 
 
 
ec64e3c
 
 
52361de
 
 
9ae8ec6
 
7dac701
76d6c6d
ae3a71a
52361de
 
 
 
a4ddaa3
52361de
 
 
 
 
c3a96a2
 
 
 
 
 
 
 
52361de
 
4fbb2dd
52361de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8268665
 
 
 
 
 
 
 
52361de
 
 
 
 
 
 
9ae8ec6
 
 
 
 
 
 
 
52361de
 
7dac701
dac2ca2
7dac701
 
76d6c6d
 
7dac701
 
58f6e54
 
 
52361de
ae3a71a
52361de
7dac701
 
 
dac2ca2
7dac701
 
 
 
 
8268665
56b51ea
8268665
39e321e
3ce2d9e
456b371
3ce2d9e
0bd6c4a
e6e90f2
 
 
681df39
dac2ca2
8268665
 
169f8e1
8268665
2ae19b0
 
 
8268665
9ae8ec6
 
8268665
 
dac2ca2
2bb6661
e6e90f2
fece768
2bb6661
fb915bd
 
09726f9
fece768
8268665
 
 
2f1b004
dac2ca2
c3a96a2
8268665
 
 
c3a96a2
 
 
26cc602
 
8268665
 
681df39
 
8268665
26cc602
 
8268665
2f1b004
8268665
fece768
09726f9
681df39
 
dac2ca2
1778128
8268665
3ce2d9e
e6e90f2
 
681df39
6c8fd46
 
 
 
 
 
2f1b004
3ce2d9e
1778128
 
 
 
8268665
 
 
1778128
 
 
 
8268665
 
 
 
 
dac2ca2
c3a96a2
 
 
 
4bcd2b0
 
 
 
 
 
 
 
dac2ca2
56b51ea
4bcd2b0
 
 
 
3ce2d9e
 
 
4bcd2b0
 
 
 
 
 
 
56b51ea
4bcd2b0
3ce2d9e
4bcd2b0
 
 
8268665
f563661
e6e90f2
4bcd2b0
dac2ca2
4bcd2b0
 
 
8268665
 
4bcd2b0
8268665
169f8e1
 
4bcd2b0
169f8e1
 
 
 
4bcd2b0
 
8268665
dac2ca2
4bcd2b0
 
2f1b004
74afd5e
4bcd2b0
8268665
 
 
dac2ca2
7dac701
4bcd2b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dac701
dac2ca2
a1ef07f
 
 
d85a20b
 
 
 
 
 
dac2ca2
a1ef07f
 
 
 
 
 
d85a20b
 
a1ef07f
1a6ecb4
dac2ca2
52361de
1a6ecb4
 
52361de
1a6ecb4
a1ef07f
1a6ecb4
 
 
 
 
52361de
1a6ecb4
52361de
 
7dac701
aeb21e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52361de
aeb21e9
52361de
 
 
 
 
8268665
 
 
c3a96a2
a1ef07f
8268665
52361de
 
8268665
ee10dd3
7dac701
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
(/** @param {import('../../../typings/reader-contract-strict').ContractRoot} root */ function (root) {
  "use strict";
  function preloadPdfOpeningResources() {
    // Classic-script and module consumers share the same in-flight preload.
    if (root.__VOICE_PDF_PRELOAD__) return;
    try {
      const params = new URLSearchParams(location.search);
      const id = params.get("id") || "";
      let source = params.get("url") || "";
      if (!source && id) {
        for (const key of [`reader-source:${id}`, `reader-resolve:${id}`]) {
          const value = /** @type {import('../../../typings/reader-contract-strict').StoredSource | null} */ (JSON.parse(sessionStorage.getItem(key) || "null"));
          if (value?.url) {
            source = value.url;
            break;
          }
        }
      }
      if (!source) return;
      const manifestUrl = new URL(source, location.origin);
      const sourceInfo = pdfPageSource(manifestUrl.href, location.origin, location.origin);
      if (!sourceInfo) return;
      const security = root.VoiceOfMLReaderSecurity;
      if (!security) return;
      const controller = new AbortController(),
        directSource = ["huggingface.co", "hf-mirror.com"].includes(manifestUrl.hostname),
        timer = setTimeout(() => controller.abort(), directSource ? 1500 : 10000);
      let disposed = false;
      let preload;
      const dispose = () => {
        if (disposed) return;
        disposed = true;
        clearTimeout(timer);
        controller.abort();
        root.removeEventListener?.("pagehide", onPageHide);
      };
      /** @param {PageTransitionEvent} event */
      const onPageHide = (event) => {
        if (!event.persisted) dispose();
      };
      const manifestRequest = fetch(manifestUrl.href, {
        priority: "low",
        signal: controller.signal
      })
        .then(async (response) => {
          const bytes = await security.readBytes(response, security.LIMITS.manifestBytes);
          return new Response(bytes, {
            status: response.status,
            statusText: response.statusText,
            headers: response.headers
          });
        })
        .finally(() => clearTimeout(timer));
      preload = {
        manifestUrl: manifestUrl.href,
        manifest: manifestRequest,
        dispose
      };
      preload.manifest.catch(() => {});
      root.addEventListener?.("pagehide", onPageHide);
      root.__VOICE_PDF_PRELOAD__ = preload;
    } catch (_) {}
  }

  function preloadChapterOpeningResources() {
    if (root.__VOICE_READER_CHAPTER_PRELOAD__) return;
    try {
      if (!location.pathname.endsWith("/reader.html")) return;
      const params = new URLSearchParams(location.search), id = params.get("id") || "";
      let source = params.get("chapter_manifest") || params.get("url") || "";
      if (!source && id) {
        for (const key of [`reader-source:${id}`, `reader-resolve:${id}`]) {
          const value = /** @type {import('../../../typings/reader-contract-strict').StoredSource | null} */ (JSON.parse(sessionStorage.getItem(key) || "null"));
          if (value?.url) { source = value.chapter_manifest || value.url; break; }
        }
      }
      const url = new URL(source, location.href), path = url.searchParams.get("path") || "";
      if ((url.origin !== location.origin && url.origin !== "https://voiceofml-search.hf.space") ||
          url.username || url.password || url.hash || url.pathname !== "/api/reader-bucket-resource" ||
          [...url.searchParams.keys()].length !== 1 || !isBucketPath(path, true) ||
          !path.startsWith("chapters/ebook/") || !path.endsWith("/chapter-manifest.json")) return;
      const security = root.VoiceOfMLReaderSecurity;
      if (!security) return;
      const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 10000);
      let disposed = false;
      /** @param {PageTransitionEvent} event */
      const onPageHide = event => { if (!event.persisted) dispose(); };
      const dispose = () => {
        if (disposed) return;
        disposed = true;
        clearTimeout(timer);
        controller.abort();
        root.removeEventListener?.("pagehide", onPageHide);
        root.removeEventListener?.("voice-reader-dispose", dispose);
      };
      const manifest = fetch(url.href, { signal: controller.signal, priority: "high", credentials: "omit" })
        .then(async response => {
          const bytes = await security.readBytes(response, security.LIMITS.manifestBytes);
          return new Response(bytes, { status: response.status, statusText: response.statusText, headers: response.headers });
        }).finally(() => clearTimeout(timer));
      manifest.catch(() => {});
      root.__VOICE_READER_CHAPTER_PRELOAD__ = { manifestUrl: url.href, manifest, dispose };
      root.addEventListener?.("pagehide", onPageHide);
      root.addEventListener?.("voice-reader-dispose", dispose);
    } catch (_) {}
  }

  const ReaderMode = Object.freeze({
    UNSUPPORTED: 0,
    ORIGINAL: 1,
    CONVERTED: 2,
    PENDING: 3,
    FAILED: 4
  });
  /** @type {Readonly<Record<string, string>>} */
  const modes = Object.freeze({
    pdf: "pdf",
    "pdf-pages": "pdf-pages",
    "image-pages": "image-pages",
    image: "image",
    "epub-chapters": "epub-chapters",
    html: "html",
    htm: "html",
    txt: "text",
    md: "markdown",
    markdown: "markdown",
    vcf: "text",
    ini: "text",
    jpg: "image",
    jpeg: "image",
    png: "image",
    gif: "image",
    bmp: "image",
    tif: "image",
    tiff: "image",
    webp: "image",
    mp3: "audio",
    wav: "audio",
    m4a: "audio",
    flac: "audio",
    mpga: "audio",
    wma: "audio",
    ape: "audio",
    amr: "audio",
    audio: "audio",
    mp4: "video",
    mov: "video",
    video: "video",
    swf: "swf"
  });
  const articleExtensions = Object.freeze([...Object.keys(modes), "djvu"]);
  /** @satisfies {Readonly<Record<string, import('../../../typings/reader-contract-strict').ReaderFeatures>>} */
  const features = Object.freeze({
    pdf: { toc: true, search: true, zoom: true, bookmarks: true, pagination: true, media: false },
    "pdf-pages": {
      toc: true,
      search: true,
      zoom: true,
      bookmarks: true,
      pagination: true,
      media: false
    },
    "image-pages": {
      toc: false,
      search: false,
      zoom: true,
      bookmarks: true,
      pagination: true,
      media: false
    },
    "epub-chapters": {
      toc: true,
      search: true,
      zoom: true,
      bookmarks: true,
      pagination: false,
      media: false
    },
    html: { toc: true, search: true, zoom: true, bookmarks: true, pagination: false, media: false },
    text: {
      toc: false,
      search: true,
      zoom: true,
      bookmarks: true,
      pagination: false,
      media: false
    },
    markdown: {
      toc: true,
      search: true,
      zoom: true,
      bookmarks: true,
      pagination: false,
      media: false
    },
    image: {
      toc: false,
      search: false,
      zoom: true,
      bookmarks: true,
      pagination: false,
      media: false
    },
    audio: {
      toc: false,
      search: false,
      zoom: false,
      bookmarks: true,
      pagination: false,
      media: true
    },
    unsupported: {
      toc: false,
      search: false,
      zoom: false,
      bookmarks: false,
      pagination: false,
      media: false
    },
    video: {
      toc: false,
      search: false,
      zoom: false,
      bookmarks: true,
      pagination: false,
      media: true
    },
    swf: {
      toc: false,
      search: false,
      zoom: false,
      bookmarks: true,
      pagination: false,
      media: true
    }
  });

  /** @param {string | null | undefined} extension */
  function capability(extension) {
    const normalized = String(extension || "").toLowerCase();
    // Native DjVu reuses the paginated document UI but never PDF.js.
    const mode = normalized === "djvu" ? "pdf" : modes[normalized];
    return Object.freeze({
      extension: normalized,
      mode: mode || null,
      readerMode: mode ? ReaderMode.ORIGINAL : ReaderMode.UNSUPPORTED,
      article: !!mode,
      features: Object.freeze({
        ...(mode && mode in features && features[/** @type {keyof typeof features} */ (mode)] || features.unsupported)
      })
    });
  }

  /** @param {unknown} value @param {number} minimum @param {number} maximum @param {number} fallback */
  function clampNumber(value, minimum, maximum, fallback) {
    const numeric = Math.round(Number(value));
    return Number.isFinite(numeric) ? Math.min(maximum, Math.max(minimum, numeric)) : fallback;
  }

  const assetRoot = String.raw`objects/[0-9a-f]{2}/[0-9a-f]{64}/`;
  const v3BucketPathPattern = new RegExp(`^${assetRoot}[0-9a-f]{16}/(?:reading-manifest\\.json|page-map\\.json\\.gz|text-layer-manifest\\.json|text-review-manifest\\.json|text/(?:page-[0-9]{6}\\.json\\.gz|book-text\\.json\\.gz|search-[0-9]{6}-[0-9]{6}\\.json\\.gz|partition-[0-9]{6}-[0-9]{6}-manifest\\.json)|preview/(?:page-[0-9]{6}\\.(?:png|webp|jpeg|svg|jxl)|partition-[0-9]{6}-[0-9]{6}-manifest\\.json))$`);
  const assetVersion = String.raw`(?:[0-9a-f]{16}/)?`;
  const assetPages = String.raw`(?:page-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl|png))`;
  const assetOcr = String.raw`(?:ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz))`;
  const v2ChapterPathPattern = new RegExp(`^chapters/ebook/(?:epub|mobi|azw3|fb2|chm)/[0-9a-f]{64}/[0-9a-f]{16}/(?:chapter-manifest\\.json|epub-search-index\\.json\\.gz|chapters/chapter-[0-9]{4}\\.xhtml|resources/(?!\\.{1,2}(?:/|$))[^/]+(?:/(?!\\.{1,2}(?:/|$))[^/]+)*)$`);
  const bucketPathPattern = new RegExp(`^${assetRoot}${assetVersion}(?:${assetPages}|${assetOcr})$`);
  const staticBucketPathPattern = new RegExp(`^(?:${assetRoot}(?:[0-9a-f]{16}/)?(?:[a-z0-9-]+/)?(?:document\\.(?:html|txt|md|webp|jpg|jpeg|png|gif|bmp|swf)|audio\\.(?:mp3|wav|m4a|flac|mpga)|video\\.(?:mp4|mov))|documents/(?:text|web|spreadsheet|office|pdf)/[a-z0-9_-]+/[0-9a-f]{64}/document\\.(?:txt|md|html|pdf|vcf|ini)|media/(?:audio|video|swf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:audio\\.[a-z0-9]+|video\\.[a-z0-9]+|document\\.swf)|pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp|gif)/[0-9a-f]{64}/(?:document\\.webp|page-manifest\\.json|pages/page-[0-9]{6}\\.webp)|derived/[A-Za-z0-9._-]+/[a-z0-9]{32}/document\\.pdf|chapters/ebook/(?:epub|mobi|azw3|fb2|chm)/[0-9a-f]{64}/[0-9a-f]{16}/(?:chapter-manifest\\.json|epub-search-index\\.json\\.gz))$`);
  const imageBucketRoot = String.raw`pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp|gif)/[0-9a-f]{64}/`;
  const avifDocumentPath = new RegExp(String.raw`^${imageBucketRoot}document\.avif$`);
  const avifPagePath = new RegExp(String.raw`^${imageBucketRoot}pages/page-[0-9]{6}\.avif$`);
  const versionedBucketPathPattern = new RegExp(`^${assetRoot}[0-9a-f]{16}/(?:${assetPages}|${assetOcr})$`);
  /** @type {Readonly<Record<string, string>>} */
  const assetModes = Object.freeze({
    p: "pdf",
    e: "epub-chapters",
    h: "html",
    t: "txt",
    k: "md",
    i: "webp",
    a: "audio",
    v: "video",
    f: "swf"
  });

  /** @param {string} path @param {boolean} [versioned] @param {string} [bucket] */
  function isBucketPath(path, versioned = false, bucket = "vomebook/pdf-pages-v2") {
    if (bucket === "vomebook/reader-assets-v2") return avifDocumentPath.test(path) || avifPagePath.test(path) ||
      staticBucketPathPattern.test(path) || v2ChapterPathPattern.test(path) || bucketPathPattern.test(path);
    if (bucket !== "vomebook/pdf-pages-v2") return false;
    return /^objects\/([0-9a-f]{2})\/\1[0-9a-f]{62}\/[0-9a-f]{16}\/document\.djvu$/.test(path) ||
      /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/[0-9a-f]{16}\/document\.pdf$/.test(path) ||
      (versioned ? versionedBucketPathPattern : bucketPathPattern).test(path) ||
      v3BucketPathPattern.test(path) || staticBucketPathPattern.test(path);
  }

  // One parser for opening preload, manifest validation and page navigation.
  // Bucket paths require a 16-hex version segment.
  /** @param {string} raw @param {string} base @param {string} bucketOrigin @param {string} [filename] @param {string} [bucketName] @returns {import('../../../typings/reader-contract-strict').PageSource | null} */
  function pdfPageSource(raw, base, bucketOrigin, filename = "page-manifest.json", bucketName = "vomebook/pdf-pages-v2") {
    try {
      const url = new URL(raw, base);
      if (url.username || url.password || url.hash) return null;
      const bucket = [bucketOrigin, "https://voiceofml-search.hf.space"].includes(url.origin) &&
        url.pathname === "/api/reader-bucket-resource";
      const bucketPrefix = `/buckets/${bucketName}/resolve/`;
      const directBucket = url.origin === "https://huggingface.co" &&
        url.pathname.startsWith(bucketPrefix) && !url.search;
      let path;
      if (bucket) {
        if (url.searchParams.getAll("path").length !== 1 ||
            [...url.searchParams.keys()].some((key) => key !== "path")) return null;
        path = url.searchParams.get("path") || "";
      } else if (directBucket) {
        path = decodeURIComponent(url.pathname.slice(bucketPrefix.length));
      } else {
        return null;
      }
      if (!isBucketPath(path, true, bucketName)) return null;
      if (!["page-manifest.json", "ocr-manifest.json", "reading-manifest.json"].includes(filename) ||
          !path.endsWith(`/${filename}`)) return null;
      const rootPath = path.slice(0, -filename.length - 1);
      /** @type {import('../../../typings/reader-contract-strict').PageSource} */
      const source = {
        root: rootPath,
        assetUrl(relativePath) {
          const scope = avifPagePath.test(relativePath) ? rootPath : rootPath.split("/").slice(0, 3).join("/");
          if (!isBucketPath(relativePath, true, bucketName) || !relativePath.startsWith(`${scope}/`))
            throw new Error("PDF_ASSET_INVALID");
          // Page images are assigned directly to Image.src (both preload and
          // rendering). Derive their proxy URL here, not a raw Bucket URL.
          const imagePages = bucketName === "vomebook/reader-assets-v2" && filename === "page-manifest.json";
          const target = directBucket && imagePages
            ? new URL("/api/reader-bucket-resource", bucketOrigin) : new URL(url.href);
          if (bucket || imagePages) target.searchParams.set("path", relativePath);
          else target.pathname = `${bucketPrefix}${relativePath}`;
          return target.href;
        }
      };
      if (bucketName === "vomebook/reader-assets-v2" && filename === "page-manifest.json") {
        source.pageUrl = (page) => {
          if (!Number.isInteger(page) || page < 1 || page > 999999)
            throw new Error("PDF_PAGE_INVALID");
          const filename = `pages/page-${String(page).padStart(6, "0")}.webp`;
          return source.assetUrl(`${rootPath}/${filename}`);
        };
      }
      return source;
    } catch (_) {
      return null;
    }
  }

  /** @param {string} raw @param {string} base @param {string} bucketOrigin */
  function imagePageSource(raw, base, bucketOrigin) {
    return pdfPageSource(raw, base, bucketOrigin, "page-manifest.json", "vomebook/reader-assets-v2");
  }

  /** @param {import('../../../typings/reader-contract-strict').Asset} asset @param {string} bucketBase */
  function pdfDocumentUrl(asset, bucketBase) {
    const { pd, pdb } = asset;
    return typeof pd === "string" && (pdb === "vomebook/reader-assets-v2" || pdb === "vomebook/pdf-pages-v2") &&
      pd.endsWith("/document.pdf") && isBucketPath(pd, true, pdb)
      ? `${bucketBase}?path=${encodeURIComponent(pd)}` : "";
  }

  /** @param {import('../../../typings/reader-contract-strict').Asset | null | undefined} asset @param {string} bucketBase @param {string} [originalExtension] @returns {import('../../../typings/reader-contract-strict').AssetFields | null} */
  function assetFields(asset, bucketBase, originalExtension = "") {
    if (!asset) return null;
    const path = String(asset.p || "");
    const ocrPath = String(asset.o || "");
    const ocrBucket = asset.b === "vomebook/pdf-pages-v2" || asset.ob === "vomebook/pdf-pages-v2";
    const ocrUrl = ocrPath.endsWith("/ocr-manifest.json") && ocrBucket && isBucketPath(ocrPath, true)
      ? `${bucketBase}?path=${encodeURIComponent(ocrPath)}`
      : "";
    const ocr = ocrUrl ? { ReaderOcrManifest: ocrUrl, ReaderOcrMode: String(asset.om || "") } : null;
    if (asset.s === 3) return ocr;
    if (asset.s !== 2) return null;
    if (originalExtension.toLowerCase().replace(/^\./, "") === "djvu") return ocr;
    if (asset.m === "p" && !asset.c && originalExtension && path.endsWith("/page-manifest.json")) {
      const pdfUrl = pdfDocumentUrl(asset, bucketBase);
      return pdfUrl ? { ...ocr, ReaderLink: pdfUrl, ReaderExtension: "pdf" } : ocr;
    }
    const bucketName = String(asset.b || "vomebook/reader-assets-v2");
    const bucket = isBucketPath(path, true, bucketName);
    const avif = avifDocumentPath.test(path);
    const chapterBucket = asset.cb === "vomebook/reader-assets-v2" &&
      v2ChapterPathPattern.test(String(asset.c || ""));
    if (
      path.endsWith(".djvu") ||
      avifPagePath.test(path) || // AVIF page URLs need pins from the manifest.
      (avif && asset.m !== "i") ||
      !Object.prototype.hasOwnProperty.call(assetModes, /** @type {string} */ (asset.m)) ||
      !bucket ||
      (asset.b && bucketName !== "vomebook/pdf-pages-v2" && bucketName !== "vomebook/reader-assets-v2") ||
      (asset.cb && !chapterBucket)
    )
      return null;
    if (asset.m === "e" && !chapterBucket) return ocr;
    const extension =
      asset.m === "p" && /\/(?:page|reading)-manifest\.json$/.test(path)
        ? "pdf-pages"
        : asset.m === "i" && (path.endsWith("document.webp") || avif)
          ? "image"
          : asset.m === "i" && path.endsWith("page-manifest.json")
            ? "image-pages"
            : assetModes[/** @type {string} */ (asset.m)];
    const readerExtension = asset.c ? "epub-chapters" : extension;
    if (!readerExtension) return {};
    return {
      ReaderLink: `${bucketBase}?path=${encodeURIComponent(/** @type {string} */ (chapterBucket ? asset.c : path))}`,
      ReaderExtension: readerExtension,
      ReaderChapterManifest: asset.c ? `${bucketBase}?path=${encodeURIComponent(asset.c)}` : "",
      ReaderOcrManifest: ocrUrl,
      ReaderOcrMode: String(asset.om || ""),
      ReaderPdfDocument: pdfDocumentUrl(asset, bucketBase)
    };
  }

  /** @param {import('../../../typings/reader-contract-strict').ReaderRecord | null | undefined} record @param {string} [basePath] */
  function readerUrl(record, basePath) {
    if (!record) return "";
    const originalLink = record.Link || record.link;
    const originalExtension = record.Extension || record.extension;
    const source = record.ReaderLink || record.readerLink || originalLink;
    const ext = record.ReaderExtension || record.readerExtension || originalExtension || "";
    if (!source || capability(ext).readerMode === ReaderMode.UNSUPPORTED) return "";
    const download = record.DownloadLink || record.downloadLink;
    const originalSource = download || originalLink || "";
    const title = (record.File || record.name || "") + (originalExtension ? "." + originalExtension : "");
    const base = basePath || "/static/reader.html";
    if (/^https:\/\/huggingface\.co\/datasets\/VoiceOfML\//.test(originalSource)) {
      return base + "?" + new URLSearchParams({ id: shortSourceId(originalSource), title, ext });
    }
    const params = new URLSearchParams({ url: source, title, ext });
    const repo = String(record.Repo || record.repo || "").split("/").pop();
    const folders = record.Folder || record.folder;
    const folder = Array.isArray(folders) ? folders.join("/") : "";
    const extras = {
      download,
      ocr_manifest: record.ReaderOcrManifest || record.readerOcrManifest,
      pdf_document: record.ReaderPdfDocument,
      chapter_manifest: record.ReaderChapterManifest || record.readerChapterManifest || record.ChapterManifest || record.chapterManifest,
      return: record.ReturnUrl || record.returnUrl,
      path: repo && (folder ? `${repo}/${folder}` : repo),
      folder_url: record.FolderUrl || record.folderUrl
    };
    for (const [key, value] of Object.entries(extras)) {
      if (value) params.set(key, value);
    }
    return base + "?" + params.toString();
  }
  /** @param {string} value */
  function canonicalSourceUrl(value) {
    // Normalize path bytes, not decoded URLs: %2F must remain distinct from /,
    // and %2528 must never become %28. Query/fragment delimiters stay intact.
    return value.replace(/^(https:\/\/huggingface\.co\/datasets\/VoiceOfML\/)([^?#]*)/, (_, prefix, path) => {
      // Canonical paths need no per-escape replacement. A lowercase/invalid
      // escape, percent-encoded unreserved byte, or raw unsafe character must
      // still take the established normalization and URI-error path below.
      if (!/%(?![0-9A-F]{2})|%(?:2[DE]|3[0-9]|4[1-9A-F]|5[0-9AF]|6[1-9A-F]|7[0-9AE])|[^A-Za-z0-9._~/%-]/.test(path))
        return prefix + path;
      return prefix + path.replace(/%[0-9a-fA-F]{2}|[^A-Za-z0-9._~/-]/gu, /** @param {string} token */ (token) => {
        if (/^%[0-9a-f]{2}$/i.test(token)) {
          const char = String.fromCharCode(parseInt(token.slice(1), 16));
          return /^[A-Za-z0-9._~-]$/.test(char) ? char : token.toUpperCase();
        }
        return encodeURIComponent(token).replace(/[!'()*]/g, (char) =>
          "%" + char.charCodeAt(0).toString(16).toUpperCase());
      });
    });
  }
  const FNV32_MASK = 0xffffffffn;
  /** @param {string} value */
  function shortSourceId(value) {
    // Two 32-bit halves avoid per-byte BigInt multiplication while preserving
    // the exact FNV-1a 64-bit wraparound and the established stable IDs.
    let hash = 1469598103934665603n;
    let high = Number(hash >> 32n), low = Number(hash & FNV32_MASK);
    for (const byte of new TextEncoder().encode(canonicalSourceUrl(value))) {
      low = (low ^ byte) >>> 0;
      const product = low * 435;
      const carry = Math.floor(product / 4294967296);
      high = (Math.imul(high, 435) + Math.imul(low, 256) + carry) >>> 0;
      low = product >>> 0;
    }
    hash = (BigInt(high) << 32n) | BigInt(low);
    return hash.toString(36).padStart(13, "0");
  }

  // Shared by the classic Search host and the Reader before its lazy speech player loads.
  const speechResumePrefix = "reader-speech-resume:";
  const speechHandoff = Object.freeze({
    storageKey: "reader-speech-handoff",
    windowMs: 300000,
    /** @param {{name: string}} frame */
    takeFramePayload(frame) {
      if (!String(frame.name).startsWith(speechResumePrefix)) return "";
      const payload = frame.name.slice(speechResumePrefix.length);
      frame.name = "";
      return payload;
    },
    /** @param {{pending?: boolean, unit?: number, offset?: number, settings?: unknown}} value */
    frameName(value) {
      return speechResumePrefix + JSON.stringify(value.pending
        ? { pending: true, settings: value.settings }
        : { unit: value.unit, offset: value.offset, settings: value.settings });
    }
  });

  root.VoiceOfMLReader = Object.freeze({
    speechHandoff,
    ReaderMode,
    articleExtensions,
    capability,
    features,
    clampNumber,
    assetFields,
    isBucketPath,
    pdfPageSource,
    imagePageSource,
    canonicalSourceUrl,
    shortSourceId,
    readerUrl
  });
  preloadPdfOpeningResources();
  preloadChapterOpeningResources();
})(typeof self !== "undefined" ? self : window);