File size: 26,766 Bytes
7538088
aeb21e9
7a367e7
 
7538088
 
aeb21e9
 
7538088
 
 
 
 
01ab508
7538088
d6f7739
a4a7fb2
 
 
7a367e7
7538088
7a367e7
 
 
 
d6f7739
7a367e7
 
d6f7739
 
 
 
 
 
7a367e7
 
 
 
 
 
 
 
 
d3655e4
7a367e7
d3655e4
 
7a367e7
d3655e4
 
 
 
 
 
 
 
 
 
 
 
7a367e7
 
 
 
 
d3655e4
7a367e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3655e4
7a367e7
 
 
d6f7739
 
 
 
a4a7fb2
 
d6f7739
 
 
a4a7fb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f7739
 
 
a4a7fb2
d6f7739
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4a7fb2
d6f7739
 
 
 
a4a7fb2
d6f7739
 
a4a7fb2
 
 
d6f7739
 
 
a4a7fb2
 
 
 
 
 
d6f7739
 
 
 
 
 
 
a4a7fb2
 
 
d6f7739
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca0888e
 
 
 
 
 
 
 
 
 
 
7538088
49a03ba
7538088
49a03ba
 
a4a7fb2
 
 
 
 
49a03ba
 
7a367e7
7538088
 
8e2d0dd
 
 
 
49a03ba
 
 
 
 
 
a4a7fb2
49a03ba
 
 
99091a7
 
 
49a03ba
 
 
 
 
a4a7fb2
 
 
7a367e7
a4a7fb2
 
 
 
 
 
49a03ba
 
 
 
 
 
 
 
 
a4a7fb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f7739
 
 
a4a7fb2
 
 
 
 
 
 
 
d6f7739
 
7a367e7
 
 
a4a7fb2
7a367e7
 
 
 
 
 
 
 
 
 
 
 
 
49a03ba
 
 
9ceac12
49a03ba
 
01ab508
ca0888e
 
 
01ab508
 
 
8e2d0dd
d6f7739
49a03ba
 
 
7538088
 
49a03ba
 
 
 
 
 
01ab508
49a03ba
7538088
ca0888e
ee872c7
 
 
 
 
 
 
 
 
7a367e7
ee872c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a03ba
01ab508
ca0888e
 
 
02a27d4
 
 
 
 
 
49a03ba
01ab508
 
 
ee872c7
 
 
 
a4a7fb2
ee872c7
 
8e2d0dd
49a03ba
 
 
 
 
 
 
 
 
 
9ceac12
49a03ba
01ab508
 
 
 
 
 
 
 
 
ca0888e
01ab508
ca0888e
01ab508
 
 
 
 
 
 
49a03ba
 
7538088
489d865
 
 
 
 
 
 
 
ca0888e
 
 
 
 
49a03ba
 
a4a7fb2
49a03ba
ca0888e
 
 
 
 
 
49a03ba
ca0888e
 
49a03ba
 
01ab508
ca0888e
01ab508
ca0888e
01ab508
ca0888e
01ab508
 
 
49a03ba
 
 
7538088
 
49a03ba
7538088
d6f7739
49a03ba
ee872c7
49a03ba
 
 
 
 
ee872c7
49a03ba
 
 
 
 
b9bb1a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01ab508
 
 
 
 
 
 
 
 
02a27d4
 
 
 
 
 
 
051e928
02a27d4
 
051e928
49a03ba
 
 
 
 
 
 
 
 
 
 
 
b9bb1a9
49a03ba
 
 
 
 
 
 
 
 
7538088
aeb21e9
 
 
 
 
 
 
49a03ba
 
 
 
 
aeb21e9
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
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/**
 * @typedef {{response: Promise<Response> | Response}} ReaderTextPrepared
 * @typedef {{extension?: string, resolvedReaderData?: {original_extension?: unknown} | null}} ReaderOriginalFormat
 * @typedef {object} ReaderTextHost
 * @property {() => void} assertReaderActive
 * @property {HTMLElement} content
 * @property {HTMLElement} status
 * @property {() => Promise<Response>} fetchReaderResponse
 * @property {() => void} markReaderContentReady
 * @property {() => Promise<void>} waitForReader
 * @property {(cleanup: () => void) => () => void} trackReaderResource
 * @property {() => Error} readerAbortError
 * @property {<T>(promise: T | PromiseLike<T>) => Promise<Awaited<T>>} awaitReader
 * @property {(bytes: Uint8Array, hint?: string, leading?: boolean) => string} detectTextEncoding
 * @property {{title: string}} documentState
 * @property {(entries: {label: string; depth: number; target: HTMLElement; activate(): void}[]) => void} setToc
 * @property {{query: string}} searchState
 * @property {(name: string) => unknown} nextReaderGeneration
 * @property {() => void} clearFullSearchMarks
 * @typedef {ReaderTextHost & ReaderOriginalFormat} ReaderTextContext
 */

const VCARD_PREVIEW_BYTES = 64 * 1024;

/** @param {ReaderOriginalFormat} context */
function originalTextExtension(context) {
  const original = context.resolvedReaderData?.original_extension;
  const extension = typeof original === "string" && original ? original : context.extension;
  return extension?.toLowerCase().replace(/^\./, "");
}

/** @param {ReaderOriginalFormat} context */
export function isReaderVCard(context) {
  return originalTextExtension(context) === "vcf";
}

const vCardLabels = new Map([
  ["FN", "姓名"], ["N", "姓名"], ["ORG", "单位"], ["TITLE", "职务"],
  ["TEL", "电话"], ["EMAIL", "电子邮箱"], ["ADR", "地址"], ["URL", "网址"], ["NOTE", "备注"]
]);

/** @param {string} text */
function formatVCard(text) {
  // Summarize one vCard 3.0 or 4.0. This is not a contact import or validator.
  const lines = text.replace(/\r?\n[ \t]/g, "").replace(/\r?\n$/, "").split(/\r?\n/);
  if (lines[0]?.toUpperCase() !== "BEGIN:VCARD" || lines.at(-1)?.toUpperCase() !== "END:VCARD") return null;
  let version = "";
  const fields = [];
  for (let index = 1; index < lines.length - 1; index++) {
    const line = lines[index] ?? "";
    const versionValue = /^VERSION:([34]\.0)$/i.exec(line)?.[1];
    if (versionValue) {
      // vCard 4.0 requires VERSION immediately after BEGIN; 3.0 does not.
      if (version || (versionValue === "4.0" && index !== 1)) return null;
      version = versionValue;
      continue;
    }
    // Parameters (including lists of quoted values) are metadata only.
    // Never interpret a URI, attachment or transfer encoding.
    const [, property, parameters, raw] = /^(?:[\da-z-]+\.)?([\da-z-]+)((?:;[\da-z-]+=(?:"[^"\r\n]*"|[^;:,"\r\n]*)(?:,(?:"[^"\r\n]*"|[^;:,"\r\n]*))*)*):([^\r\n]*)$/i.exec(line) || [];
    if (!property || raw === undefined) return null;
    const key = property.toUpperCase();
    if (key === "BEGIN" || key === "END" || key === "VERSION") return null;
    const label = vCardLabels.get(key);
    if (!label) continue;
    if (parameters && /;(?:encoding|charset)=/i.test(parameters.replace(/"[^"]*"/g, ""))) return null;
    const structured = key === "ORG" || key === "ADR" || key === "N";
    const components = [];
    let start = 0, component = "";
    // Consume escapes before delimiters so an escaped semicolon remains text.
    for (const match of raw.matchAll(/\\([\\;,nN])|;/g)) {
      component += raw.slice(start, match.index);
      start = match.index + match[0].length;
      const escape = match[1];
      if (escape) component += /^[nN]$/.test(escape) ? "\n" : escape;
      else if (structured) { components.push(component); component = ""; }
      else component += ";";
    }
    components.push(component + raw.slice(start));
    const value = components.filter(part => part.trim()).join(" · ");
    if (value.trim()) fields.push({ key, text: `${label}:${value}` });
  }
  const hasFullName = fields.some(field => field.key === "FN");
  if (!version || (!hasFullName && (version === "4.0" || !fields.some(field => field.key === "N")))) return null;
  return fields.filter(field => !hasFullName || field.key !== "N").map(field => field.text).join("\n");
}

// Apply layout only to bounded TXT documents, after decoding and before restoring
// the position. Never replace the text used by search, speech or the original download.
const TXT_LAYOUT_BYTES = 128 * 1024;
const TXT_LAYOUT_EDITS = 1024;
const TXT_TOC_ENTRIES = 512;
const TXT_TITLE_LENGTH = 72;
const TXT_CHAPTER = /^第[ \u3000]*[\d0-9〇零一二三四五六七八九十百千万两]+[ \u3000]*([卷部篇章节回])(?:$|[ \t\u3000..::、—–-]+[^\r\n]+$)/u;

/** @typedef {{ start: number; end: number; heading?: string; depth?: number }} TextLayoutEdit */
/** @typedef {{element: HTMLElement; length: number}} TextBlock */

function createTxtOutline() {
  /** @type {TextLayoutEdit[]} */
  const headings = [];
  const newline = /[\r\n]/g;
  let prefix = "", lineStart = 0, heldSpace = 0, spaceText = "", skipped = false;
  /** @param {string} text @param {number} start */
  function take(text, start) {
    if (skipped) return;
    if (!prefix) {
      const trimmed = text.trimStart();
      lineStart = start + text.length - trimmed.length;
      text = trimmed;
    }
    // Ignore trailing whitespace until more content makes it internal.
    // Never retain a body-sized line or let its next chunk look like a title.
    const content = text.trimEnd();
    if (content) {
      if (prefix.length + heldSpace + content.length > TXT_TITLE_LENGTH) { skipped = true; return; }
      prefix += spaceText + content;
      heldSpace = 0;
      spaceText = "";
    }
    if (heldSpace + text.length - content.length <= TXT_TITLE_LENGTH) spaceText += text.slice(content.length);
    heldSpace = Math.min(TXT_TITLE_LENGTH + 1, heldSpace + text.length - content.length);
  }
  function finishLine() {
    if (prefix && !skipped && headings.length < TXT_TOC_ENTRIES) {
      const kind = TXT_CHAPTER.exec(prefix)?.[1];
      if (kind && !/[。!?;!?]$/u.test(prefix))
        headings.push({ start: lineStart, end: lineStart + prefix.length, heading: prefix, depth: kind === "节" ? 1 : 0 });
    }
    prefix = "";
    heldSpace = 0;
    spaceText = "";
    skipped = false;
  }
  return {
    /** @param {string} text @param {number} start */
    append(text, start) {
      let cursor = 0;
      newline.lastIndex = 0;
      // CRLF behaves like two boundaries with an empty line between them;
      // an empty line never creates a title, even across packet boundaries.
      for (let match; headings.length < TXT_TOC_ENTRIES && (match = newline.exec(text));) {
        take(text.slice(cursor, match.index), start + cursor);
        finishLine();
        cursor = newline.lastIndex;
      }
      if (headings.length < TXT_TOC_ENTRIES && cursor < text.length) take(text.slice(cursor), start + cursor);
    },
    finish() { finishLine(); return headings; },
    reset() { headings.length = 0; prefix = spaceText = ""; heldSpace = 0; skipped = false; }
  };
}

/** @param {string} text */
function planTextLayout(text) {
  /** @type {TextLayoutEdit[]} */
  const indents = [], gaps = [];
  let total = 0, padded = 0, prose = 0, blankLines = 0;
  /** @type {TextLayoutEdit | null} */
  let gap = null;
  for (const line of text.matchAll(/[^\r\n]*(?:\r\n|\r|\n|$)/g)) {
    const raw = line[0], start = line.index;
    if (!raw) break;
    const label = raw.trim();
    if (!label) {
      if (gap) gap.end = start + raw.length;
      else if (++blankLines === 3) {
        gap = { start, end: start + raw.length };
        gaps.push(gap);
      }
    } else {
      blankLines = 0;
      gap = null;
      total++;
      if (label.length >= 16 && /[。!?;,、]|[.!?;](?:\s|$)/u.test(label)) prose++;
      const indent = /^[ \u3000]{8,}/u.exec(raw)?.[0];
      if (indent) {
        padded++;
        indents.push({ start: start + 2, end: start + indent.length });
      }
    }
    if (indents.length + gaps.length > TXT_LAYOUT_EDITS) return [];
  }
  // A few indented lines are not a padding convention. Require recurring long
  // indents and sentence-like prose; keep meaningful whitespace in code/tables.
  const compact = total >= 8 && padded * 4 >= total * 3 && prose >= 3;
  return [...(compact ? indents : []), ...gaps];
}

/** @param {TextBlock[]} blocks @param {TextLayoutEdit[]} edits @param {boolean} emphasize */
function typesetPlainText(blocks, edits, emphasize) {
  edits.sort((a, b) => a.start - b.start);
  /** @type {{label: string; depth: number; target: HTMLElement; activate(): void}[]} */
  const toc = [];
  let from = 0, editIndex = 0;
  for (const {element: block, length} of blocks) {
    const next = edits[editIndex];
    if (!next) break;
    const to = from + length;
    if (next.start < to) {
      const text = block.textContent ?? "";
      /** @type {Node[]} */
      const nodes = [];
      let cursor = from;
      for (let edit; (edit = edits[editIndex]) && edit.start < to;) {
        const begin = Math.max(from, edit.start), end = Math.min(to, edit.end);
        if (cursor < begin) nodes.push(document.createTextNode(text.slice(cursor - from, begin - from)));
        const span = document.createElement("span");
        span.className = edit.heading
          ? emphasize ? "reader-text-chapter-title" : "reader-text-chapter-anchor"
          : "reader-text-padding";
        span.textContent = text.slice(begin - from, end - from);
        nodes.push(span);
        if (edit.heading && edit.start >= from) {
          toc.push({ label: edit.heading, depth: edit.depth ?? 0, target: span,
            activate: () => span.scrollIntoView({ block: "start" }) });
        }
        cursor = end;
        if (edit.end > to) break;
        editIndex++;
      }
      if (cursor < to) nodes.push(document.createTextNode(text.slice(cursor - from)));
      block.replaceChildren(...nodes);
    }
    from = to;
  }
  return toc;
}

/** @param {Uint8Array} bytes @param {number} limit */
function nonNullAsciiPrefix(bytes, limit) {
  let end = 0;
  while (end < limit) {
    const byte = /** @type {number} */ (bytes[end]);
    if (byte === 0 || byte >= 128) break;
    end++;
  }
  return end;
}

/** @param {ReaderTextContext} readerContext */
export function createReaderTextFormat(readerContext) {
  /** @param {Response} response */
  async function renderPlainText(response) {
    readerContext.assertReaderActive();
    const extension = originalTextExtension(readerContext), vCard = extension === "vcf";
    const outline = extension === "txt" ? createTxtOutline() : null;
    /** @type {TextBlock[]} */
    const blocks = [];
    let position = 0;
    const pre = document.createElement("div");
    pre.className = "reader-text";
    if (!vCard) readerContext.content.appendChild(pre);
    let /** @type {HTMLPreElement | null} */ block = null, blockLength = 0;
    /** @param {string} value @param {string} [encoding] */
    const appendDecoded = async (value, encoding = "utf-8") => {
      // Unicode can contain a literal replacement character. Keep legacy
      // damaged-codepage cleanup scoped to non-Unicode decoding.
      const text = encoding.startsWith("utf-") ? value : value.replace(/\ufffd/g, "");
      let offset = 0, deadline = performance.now() + 8;
      while (offset < text.length) {
        if (!block) {
          block = document.createElement("pre");
          block.className = "reader-text-block";
          pre.appendChild(block);
          if (outline) blocks.push({ element: block, length: 0 });
        }
        let end = Math.min(text.length, offset + 32768 - blockLength);
        if (end < text.length) {
          // An unbroken chunk must not rescan the already appended prefix.
          const newline = text.slice(offset, end).lastIndexOf("\n");
          if (newline >= 0) end = offset + newline + 1;
          const previous = text.charCodeAt(end - 1), next = text.charCodeAt(end);
          if ((previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) ||
              (previous === 13 && next === 10)) end--;
        }
        if (end === offset) { block = null; blockLength = 0; continue; }
        const tail = block.lastChild, part = text.slice(offset, end);
        if (tail?.nodeType === Node.TEXT_NODE) (/** @type {Text} */ (tail)).appendData(part);
        else block.appendChild(document.createTextNode(part));
        if (!vCard) readerContext.markReaderContentReady();
        blockLength += part.length;
        if (outline) {
          outline.append(part, position);
          /** @type {TextBlock} */ (blocks.at(-1)).length = blockLength;
          position += part.length;
        }
        offset = end;
        if (offset < text.length || blockLength >= 32768) { block = null; blockLength = 0; }
        if (offset < text.length && performance.now() >= deadline) {
          await readerContext.waitForReader();
          readerContext.assertReaderActive();
          deadline = performance.now() + 8;
        }
      }
    };
    // Search may have started during streaming. The ready path already
    // reruns an open query after its text nodes and chapter targets settle.
    const invalidateSearch = () => {
      if (!vCard && readerContext.searchState.query) {
        readerContext.nextReaderGeneration("search");
        readerContext.clearFullSearchMarks();
      }
    };
    const resetText = () => {
      invalidateSearch();
      pre.textContent = "";
      block = null;
      blockLength = position = blocks.length = 0;
      outline?.reset();
    };
    /** @param {number} length */
    const finishText = async (length) => {
      if (!vCard) {
        if (!outline) return;
        const emphasize = length <= TXT_LAYOUT_BYTES;
        const edits = outline.finish();
        if (emphasize) edits.push(...planTextLayout(pre.textContent ?? ""));
        if (!edits.length) return;
        invalidateSearch();
        const toc = typesetPlainText(blocks, edits, emphasize);
        if (toc.length) readerContext.setToc(toc);
        return;
      }
      readerContext.assertReaderActive();
      const summary = formatVCard(pre.textContent ?? "");
      if (summary !== null) {
        resetText();
        await appendDecoded(summary);
      }
      readerContext.assertReaderActive();
      readerContext.content.appendChild(pre);
      readerContext.markReaderContentReady();
    };
    const documentLimit = VoiceOfMLReaderSecurity.LIMITS.documentBytes;
    const limit = vCard ? Math.min(documentLimit, VCARD_PREVIEW_BYTES) : documentLimit, sampleLimit = 65540;
    try { VoiceOfMLReaderSecurity.assertResponseSize(response, limit); }
    catch (reason) {
      if (vCard) void response.body?.cancel().catch(() => {});
      throw reason;
    }
    if (!response.body?.getReader) {
      const bytes = new Uint8Array(await response.arrayBuffer());
      if (bytes.byteLength > limit) {
        throw Object.assign(new Error("READER_RESOURCE_LIMIT"), { code: "READER_RESOURCE_LIMIT" });
      }
      readerContext.assertReaderActive();
      let start = 0;
      if (bytes.length >= sampleLimit && nonNullAsciiPrefix(bytes, sampleLimit) === sampleLimit) {
        start = sampleLimit;
        while (start < bytes.length && (/** @type {number} */ (bytes[start])) < 128) start++;
      }
      const decoder = new TextDecoder(readerContext.detectTextEncoding(bytes.subarray(start, start + sampleLimit),
        readerContext.documentState.title, start === 0));
      await appendDecoded(decoder.decode(bytes), decoder.encoding);
      await finishText(bytes.byteLength);
      return;
    }
    const reader = response.body.getReader(),
      /** @type {Uint8Array[]} */ sampleChunks = [],
      /** @type {number[]} */ signature = [],
      previewDecoder = new TextDecoder("utf-8");
    const untrack = readerContext.trackReaderResource(() => {
      reader.cancel(readerContext.readerAbortError()).catch(() => {});
    });
    let length = 0,
      sampleLength = 0,
      committedAscii = false,
      displayedSampleSize = 0,
      /** @type {TextDecoder | null} */ decoder = null,
      previewLeadingAscii = true,
      /** @type {TextDecoder | null} */ utf8Preview = new TextDecoder("utf-8", { fatal: true }),
      previewText = "";
    const clearUtf8Preview = () => {
      delete pre.dataset.textPreview;
      utf8Preview = null;
      previewText = "";
    };
    /** @param {Uint8Array} chunk */
    const showUtf8Preview = chunk => {
      if (vCard || !utf8Preview) return;
      if (displayedSampleSize || chunk.includes(0)) { clearUtf8Preview(); return; }
      let decoded;
      try { decoded = utf8Preview.decode(chunk, { stream: true }); }
      catch (_) { clearUtf8Preview(); return; }
      // Keep this tentative, bounded text out of the document's text nodes so
      // search, speech and bookmark excerpts cannot consume a charset guess.
      if (previewText.length < 2048) {
        const end = 2048 - previewText.length;
        const last = decoded.charCodeAt(end - 1);
        previewText += decoded.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end);
        if (/^(?:[^\u3400-\u9fff]*[\u3400-\u9fff]){4}/.test(previewText)) {
          pre.dataset.textPreview = previewText;
          readerContext.markReaderContentReady();
        }
      }
    };
    const startDecoder = async () => {
      // Use the fixed sample bytes without copying a contiguous view.
      let sample;
      if (sampleChunks.length === 1) sample = /** @type {Uint8Array} */ (sampleChunks[0]);
      else {
        sample = new Uint8Array(sampleLength);
        let offset = 0;
        for (const chunk of sampleChunks) {
          sample.set(chunk, offset);
          offset += chunk.byteLength;
        }
      }
      const encoding = readerContext.detectTextEncoding(sample, readerContext.documentState.title, !committedAscii);
      // Do not strip an internal UTF-8 BOM after an ASCII preface.
      decoder = new TextDecoder(encoding, { ignoreBOM: committedAscii });
      clearUtf8Preview();
      if (decoder.encoding.startsWith("utf-16") && displayedSampleSize) {
        // A late NUL pattern can choose UTF-16 even after the ASCII preview
        // stopped. Rebuild from byte zero, not the ASCII preview's byte offset.
        resetText();
        displayedSampleSize = 0;
      }
      await appendDecoded(decoder.decode(sample.subarray(displayedSampleSize), { stream: true }), decoder.encoding);
      sampleChunks.length = 0;
    };
    try {
      while (true) {
        const { value, done } = await readerContext.awaitReader(reader.read());
        readerContext.assertReaderActive();
        if (done) break;
        if (!value?.byteLength) continue;
        length += value.byteLength;
        if (length > limit) {
          throw Object.assign(new Error("READER_RESOURCE_LIMIT"), { code: "READER_RESOURCE_LIMIT" });
        }
        for (let pending = value; pending.length;) {
          if (decoder) {
            const active = /** @type {TextDecoder} */ (/** @type {unknown} */ (decoder));
            await appendDecoded(active.decode(pending, { stream: true }), active.encoding);
            break;
          }
          // Pure ASCII cannot distinguish UTF-8 from a legacy code page.
          // Render it as it arrives and start a fresh bounded sample at the
          // first high byte, regardless of where the response is split.
          if (committedAscii && sampleLength === 0) {
            let skip = 0;
            while (skip < pending.length && (/** @type {number} */ (pending[skip])) < 128) skip++;
            if (skip) await appendDecoded(previewDecoder.decode(pending.subarray(0, skip)));
            if (skip === pending.length) break;
            pending = pending.subarray(skip);
          }
          const take = Math.min(pending.length, sampleLimit - sampleLength);
          const value = take === pending.length ? pending : pending.subarray(0, take);
          pending = pending.subarray(take);
          sampleChunks.push(value);
          sampleLength += value.byteLength;
          for (let i = 0; i < value.byteLength && signature.length < 3; i++) signature.push(/** @type {number} */ (value[i]));
          // A BOM determines the decoder without waiting for the heuristic
          // sample. Retain streaming decoder state across split code units.
          if ((signature[0] === 0xef && signature[1] === 0xbb && signature[2] === 0xbf) ||
              (signature[0] === 0xff && signature[1] === 0xfe) ||
              (signature[0] === 0xfe && signature[1] === 0xff)) {
            await startDecoder();
            continue;
          }
          if (previewLeadingAscii) {
            const asciiLength = nonNullAsciiPrefix(value, value.length);
            previewLeadingAscii = asciiLength === value.length;
            // While previewing, every earlier sample byte was non-NUL ASCII.
            const prefixLength = sampleLength - value.length + asciiLength;
            if (value[asciiLength] === 0) {
              // A split UTF-16 prefix must not leave an ASCII preview behind.
              resetText();
              displayedSampleSize = 0;
            } else if (asciiLength && prefixLength >= 4) {
              // Replay only the small chunks held back by the four-byte
              // threshold. After that, preview just the new chunk's prefix.
              if (!displayedSampleSize) {
                for (let i = 0; i < sampleChunks.length - 1; i++)
                  await appendDecoded(previewDecoder.decode(sampleChunks[i]));
              }
              await appendDecoded(previewDecoder.decode(value.subarray(0, asciiLength)));
              displayedSampleSize = prefixLength;
            }
          }
          if (sampleLength < sampleLimit) { showUtf8Preview(value); continue; }
          if (previewLeadingAscii) {
            committedAscii = true;
            previewLeadingAscii = false;
            sampleChunks.length = 0;
            sampleLength = displayedSampleSize = 0;
            clearUtf8Preview();
            continue;
          }
          await startDecoder();
        }
      }
      // If no decoder was selected during streaming, successful completion of
      // startDecoder assigns one even for an empty sample. A failure is caught.
      if (!decoder) await startDecoder();
      await appendDecoded((/** @type {TextDecoder} */ (/** @type {unknown} */ (decoder))).decode(), (/** @type {TextDecoder} */ (/** @type {unknown} */ (decoder))).encoding);
      await finishText(length);
    } catch (reason) {
      clearUtf8Preview();
      try {
        await reader.cancel(reason);
      } catch (_) {}
      throw reason;
    } finally {
      clearUtf8Preview();
      untrack();
      reader.releaseLock();
    }
  }

  /** @type {Uint8Array | undefined} */
  let cjkWeights;

  function getCjkWeights() {
    // Index just the CJK range, and only allocate this on the legacy path.
    const weights = new Uint8Array(0x9fff - 0x3400 + 1).fill(1);
    const common = "的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经之进着等部家自理起现实都体制当本性应开合因由然前外政社义事相全与关各重新内正反明原利质向道命此变结解问意建公系军情者立代通题党程展料员革文总品活长求老基资级图统知组别期论运农指区战任处理世";
    for (let i = 0; i < common.length; i++) weights[common.charCodeAt(i) - 0x3400] = 6;
    return weights;
  }

  /** @param {string} text */
  function legacyEncodingScore(text) {
    // Tally the same UTF-16 code units and weights in one pass, without
    // materializing an array of matches for each class and candidate.
    const weights = cjkWeights ??= getCjkWeights();
    let cjk = 0, cyrillic = 0, controls = 0, replacements = 0;
    for (let i = 0; i < text.length; i++) {
      const code = text.charCodeAt(i);
      if (code >= 0x3400 && code <= 0x9fff) cjk += /** @type {number} */ (weights[code - 0x3400]);
      else if (code >= 0x0400 && code <= 0x04ff) cyrillic++;
      else if (code === 0xfffd) replacements++;
      else if (code < 0x20 && code !== 9 && code !== 10 && code !== 13) controls++;
    }
    return Math.max(cjk, cyrillic) - controls * 20 - replacements * 40;
  }

  /** @param {Uint8Array} bytes @param {string} [hint] @param {boolean} [leading] */
  function detectTextEncoding(bytes, hint = "", leading = true) {
    if (leading) {
      if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) return "utf-8";
      if (bytes[0] === 0xff && bytes[1] === 0xfe) return "utf-16le";
      if (bytes[0] === 0xfe && bytes[1] === 0xff) return "utf-16be";
    }
    // A late sample cannot reinterpret the committed ASCII prefix as UTF-16.
    const firstNull = leading ? bytes.indexOf(0) : -1;
    if (firstNull !== -1) {
      let evenNulls = 0, oddNulls = 0;
      for (let index = firstNull; index < bytes.length; index++) {
        if (!bytes[index]) {
          if (index % 2 === 0) evenNulls++;
          else oddNulls++;
        }
      }
      if (oddNulls > bytes.length / 8 && oddNulls > evenNulls * 4) return "utf-16le";
      if (evenNulls > bytes.length / 8 && evenNulls > oddNulls * 4) return "utf-16be";
    }
    try {
      new TextDecoder("utf-8", { fatal: true }).decode(bytes, { stream: true });
      return "utf-8";
    } catch (_) {}
    if (/[\u0400-\u04ff]/.test(hint)) return "windows-1251";
    const candidates = /[\u3400-\u9fff]/.test(hint)
      ? ["gb18030", "big5"]
      : ["gb18030", "big5", "windows-1251", "windows-1252"];
    let best = "gb18030",
      bestScore = -Infinity;
    for (const encoding of candidates) {
      try {
        const score = legacyEncodingScore(new TextDecoder(encoding).decode(bytes));
        if (score > bestScore) {
          best = encoding;
          bestScore = score;
        }
      } catch (_) {}
    }
    return best;
  }

  /** @param {ReaderTextPrepared} prepared */
  async function renderTextDocument(prepared) {
    let response = await prepared.response;
    if (!response.ok) response = await readerContext.fetchReaderResponse();
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    await renderPlainText(response);
    readerContext.markReaderContentReady();
    readerContext.status.textContent = "已加载";
  }

  return {
    renderPlainText,
    detectTextEncoding,
    renderTextDocument
  };
}