pdf-skryba 0.10.0 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  // src/lib/chunk.ts
2
2
  function chunk(items, size) {
3
- const out = [];
4
- for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
5
- return out;
3
+ const groups = [];
4
+ for (let start = 0; start < items.length; start += size) groups.push(items.slice(start, start + size));
5
+ return groups;
6
6
  }
7
7
 
8
8
  // src/lib/link-schemes.ts
@@ -10,131 +10,157 @@ var PUBLISHED_SCHEME = /^(?:https?|mailto):/i;
10
10
 
11
11
  // src/pipeline/glued-word-repair.ts
12
12
  import { conservationKey } from "doc-ir";
13
- var UNIT = /[\s\S]/gu;
14
- var unitsOf = (text) => [...text.matchAll(UNIT)].map((m) => ({ text: m[0], key: conservationKey(m[0]), end: m.index + m[0].length }));
15
- var wordsOf = (units) => {
13
+ var CODE_POINT = /[\s\S]/gu;
14
+ var splitCodePoints = (text) => [...text.matchAll(CODE_POINT)].map((match) => ({
15
+ text: match[0],
16
+ key: conservationKey(match[0]),
17
+ end: match.index + match[0].length
18
+ }));
19
+ var splitWords = (codePoints) => {
16
20
  const words = [];
17
21
  let current = [];
18
- const close = () => {
19
- if (conservationKey(current.map((u) => u.text).join("")).length > 0) words.push(current);
22
+ const closeWord = () => {
23
+ if (conservationKey(current.map((codePoint) => codePoint.text).join("")).length > 0) words.push(current);
20
24
  current = [];
21
25
  };
22
- for (const u of units) {
23
- if (/^\s+$/u.test(u.text)) close();
24
- else current.push(u);
26
+ for (const codePoint of codePoints) {
27
+ if (/^\s+$/u.test(codePoint.text)) closeWord();
28
+ else current.push(codePoint);
25
29
  }
26
- close();
30
+ closeWord();
27
31
  return words;
28
32
  };
29
- var edge = (raw, side) => {
30
- const chars = [...raw];
31
- const order = side === "lead" ? chars : [...chars].reverse();
32
- const out = [];
33
- for (const c of order) {
34
- if (conservationKey(c).length > 0) break;
35
- out.push(c);
33
+ var readNonLetterEdge = (word, side) => {
34
+ const characters = [...word];
35
+ const ordered = side === "lead" ? characters : [...characters].reverse();
36
+ const edge = [];
37
+ for (const character of ordered) {
38
+ if (conservationKey(character).length > 0) break;
39
+ edge.push(character);
36
40
  }
37
- return (side === "lead" ? out : [...out].reverse()).join("");
41
+ return (side === "lead" ? edge : [...edge].reverse()).join("");
38
42
  };
39
- var visible = (text) => text.replaceAll("\u200B", "");
40
- var insertionsFor = (blocks, r) => {
41
- const at = r.pageWords[0];
42
- if (r.kind !== "glued" || r.pageWords.length !== 1 || at === void 0 || r.sourceWords.length < 2) return void 0;
43
- const text = blocks[at.block];
44
- const units = text === void 0 ? void 0 : unitsOf(text);
45
- const word = units === void 0 ? void 0 : wordsOf(units)[at.word];
46
- if (word === void 0) return void 0;
47
- const keys = r.sourceWords.map(conservationKey);
48
- const tokenKey = conservationKey(word.map((u2) => u2.text).join(""));
49
- if (word.map((u2) => u2.key).join("") !== tokenKey || keys.join("") !== tokenKey) return void 0;
43
+ var removeZeroWidthSpaces = (text) => text.replaceAll("\u200B", "");
44
+ var findGluedToken = (blocks, respacing) => {
45
+ const pageWord = respacing.pageWords[0];
46
+ if (respacing.kind !== "glued" || respacing.pageWords.length !== 1 || pageWord === void 0 || respacing.sourceWords.length < 2)
47
+ return void 0;
48
+ const text = blocks[pageWord.block];
49
+ if (text === void 0) return void 0;
50
+ return splitWords(splitCodePoints(text))[pageWord.word];
51
+ };
52
+ var countTrailingCodePoints = (between, trail, lead) => {
53
+ if (removeZeroWidthSpaces(between.map((codePoint) => codePoint.text).join("")) !== trail + lead) return void 0;
54
+ let taken = "";
55
+ let takenCount = 0;
56
+ while (taken.length < trail.length && takenCount < between.length) {
57
+ taken += removeZeroWidthSpaces(between[takenCount++].text);
58
+ }
59
+ return taken === trail ? takenCount : void 0;
60
+ };
61
+ var findSpaceInsertions = (blocks, respacing) => {
62
+ const token = findGluedToken(blocks, respacing);
63
+ if (token === void 0) return void 0;
64
+ const sourceKeys = respacing.sourceWords.map(conservationKey);
65
+ const tokenKey = conservationKey(token.map((codePoint) => codePoint.text).join(""));
66
+ if (token.map((codePoint) => codePoint.key).join("") !== tokenKey || sourceKeys.join("") !== tokenKey)
67
+ return void 0;
50
68
  const offsets = [];
51
- let u = 0;
52
- let letters = 0;
53
- for (let i = 0; i < keys.length - 1; i++) {
54
- const boundary = letters + keys[i].length;
55
- while (u < word.length && letters + word[u].key.length <= boundary && letters < boundary)
56
- letters += word[u++].key.length;
57
- if (letters !== boundary) return void 0;
58
- let next = u;
59
- while (next < word.length && word[next].key.length === 0) next++;
60
- const between = word.slice(u, next);
61
- const trail = edge(r.sourceWords[i], "trail");
62
- if (visible(between.map((x) => x.text).join("")) !== trail + edge(r.sourceWords[i + 1], "lead")) return void 0;
63
- let taken = "";
64
- let k = 0;
65
- while (taken.length < trail.length && k < between.length) taken += visible(between[k++].text);
66
- if (taken !== trail) return void 0;
67
- offsets.push(word[u + k - 1].end);
68
- u += k;
69
+ let position = 0;
70
+ let letterCount = 0;
71
+ for (let sourceIndex = 0; sourceIndex < sourceKeys.length - 1; sourceIndex++) {
72
+ const boundary = letterCount + sourceKeys[sourceIndex].length;
73
+ while (position < token.length && letterCount + token[position].key.length <= boundary && letterCount < boundary)
74
+ letterCount += token[position++].key.length;
75
+ if (letterCount !== boundary) return void 0;
76
+ let nextLetter = position;
77
+ while (nextLetter < token.length && token[nextLetter].key.length === 0) nextLetter++;
78
+ const takenCount = countTrailingCodePoints(
79
+ token.slice(position, nextLetter),
80
+ readNonLetterEdge(respacing.sourceWords[sourceIndex], "trail"),
81
+ readNonLetterEdge(respacing.sourceWords[sourceIndex + 1], "lead")
82
+ );
83
+ if (takenCount === void 0) return void 0;
84
+ offsets.push(token[position + takenCount - 1].end);
85
+ position += takenCount;
69
86
  }
70
87
  return offsets;
71
88
  };
72
89
  function gluedWordEdits(page, respacings) {
73
- const glued = respacings.filter((r) => r.kind === "glued");
90
+ const glued = respacings.filter((respacing) => respacing.kind === "glued");
74
91
  if (glued.length === 0) return { edits: [], repaired: 0 };
75
- const taken = /* @__PURE__ */ new Set();
92
+ const takenOffsets = /* @__PURE__ */ new Set();
76
93
  const edits = [];
77
94
  let repaired = 0;
78
- for (const r of glued) {
79
- const block = r.pageWords[0]?.block;
80
- const at = insertionsFor(page.blocks, r);
81
- if (at === void 0 || block === void 0 || at.some((o) => taken.has(`${block}:${o}`))) continue;
82
- for (const atChar of at) {
83
- taken.add(`${block}:${atChar}`);
95
+ for (const respacing of glued) {
96
+ const block = respacing.pageWords[0]?.block;
97
+ const offsets = findSpaceInsertions(page.blocks, respacing);
98
+ if (offsets === void 0 || block === void 0 || offsets.some((offset) => takenOffsets.has(`${block}:${offset}`)))
99
+ continue;
100
+ for (const atChar of offsets) {
101
+ takenOffsets.add(`${block}:${atChar}`);
84
102
  edits.push({ kind: "insert-space", block, atChar });
85
103
  }
86
104
  repaired += 1;
87
105
  }
88
106
  return { edits, repaired };
89
107
  }
90
- var noWorse = (before, after, repaired) => after.lostLetters <= before.lostLetters && (after.decision !== "lost" || before.decision === "lost") && after.decision !== "abstain" && after.gluedWords <= before.gluedWords - repaired && after.unmatchedPageWords <= before.unmatchedPageWords && after.respacings.filter((r) => r.kind === "split").length <= before.respacings.filter((r) => r.kind === "split").length;
108
+ var countSplitWords = (verdict) => verdict.respacings.filter((respacing) => respacing.kind === "split").length;
109
+ var noWorse = (before, after, repaired) => after.lostLetters <= before.lostLetters && (after.decision !== "lost" || before.decision === "lost") && after.decision !== "abstain" && after.gluedWords <= before.gluedWords - repaired && after.unmatchedPageWords <= before.unmatchedPageWords && countSplitWords(after) <= countSplitWords(before);
91
110
 
92
111
  // src/pipeline/lost-text-repair.ts
93
112
  import {
94
113
  conservationKey as conservationKey2,
95
114
  wordKeysOf
96
115
  } from "doc-ir";
116
+ var isAfterInPageOrder = (later, earlier) => later.block > earlier.block || later.block === earlier.block && later.word > earlier.word;
97
117
  function placeLostPassages(page, passages) {
98
118
  const insertions = [];
99
119
  const abstentions = [];
100
120
  if (passages.length === 0) return { insertions, abstentions };
101
121
  const units = page.units;
102
- const words = page.blocks.map((text) => wordKeysOf(text).length);
103
- const lastBlock = words.length - 1;
104
- const unitOf = (block) => units?.findIndex((unit) => unit.blocks.includes(block)) ?? -1;
105
- const edgeOf = (at, side) => {
106
- const u = unitOf(at.block);
107
- if (u < 0 || units?.[u]?.paragraphOrHeading !== true) return "anchor-in-container";
108
- const neighbourBlock = side === "before" ? at.block + 1 : at.block - 1;
109
- const atEdge = side === "before" ? at.word === (words[at.block] ?? 0) - 1 : at.word === 0;
110
- if (!atEdge || unitOf(neighbourBlock) === u) return "loss-inside-block";
111
- return u;
122
+ const wordCountByBlock = page.blocks.map((text) => wordKeysOf(text).length);
123
+ const lastBlock = wordCountByBlock.length - 1;
124
+ const findUnitOfBlock = (block) => units?.findIndex((unit) => unit.blocks.includes(block)) ?? -1;
125
+ const findAnchorUnit = (anchor, side) => {
126
+ const unitIndex = findUnitOfBlock(anchor.block);
127
+ if (unitIndex < 0 || units?.[unitIndex]?.paragraphOrHeading !== true) return "anchor-in-container";
128
+ const neighbourBlock = side === "before" ? anchor.block + 1 : anchor.block - 1;
129
+ const isAtEdge = side === "before" ? anchor.word === (wordCountByBlock[anchor.block] ?? 0) - 1 : anchor.word === 0;
130
+ if (!isAtEdge || findUnitOfBlock(neighbourBlock) === unitIndex) return "loss-inside-block";
131
+ return unitIndex;
112
132
  };
113
- const place = (passage) => {
133
+ const placePassage = (passage) => {
114
134
  const { before, after } = passage;
115
135
  if (before === "unanchored" || after === "unanchored") return "anchor-unmatched";
116
136
  if (before === "document-edge" && after === "document-edge") return "no-anchor";
117
- if (before !== "document-edge" && after !== "document-edge") {
118
- if (after.block < before.block || after.block === before.block && after.word <= before.word)
119
- return "anchors-out-of-order";
137
+ if (before !== "document-edge" && after !== "document-edge" && !isAfterInPageOrder(after, before))
138
+ return "anchors-out-of-order";
139
+ const unitBefore = before === "document-edge" ? void 0 : findAnchorUnit(before, "before");
140
+ if (typeof unitBefore === "string") return unitBefore;
141
+ const unitAfter = after === "document-edge" ? void 0 : findAnchorUnit(after, "after");
142
+ if (typeof unitAfter === "string") return unitAfter;
143
+ if (unitBefore === void 0) {
144
+ if (unitAfter === void 0 || after === "document-edge" || after.block !== 0) return "no-anchor";
145
+ return unitAfter - 1;
146
+ }
147
+ if (unitAfter === void 0) {
148
+ if (before === "document-edge" || before.block !== lastBlock) return "no-anchor";
149
+ return unitBefore;
120
150
  }
121
- const u1 = before === "document-edge" ? void 0 : edgeOf(before, "before");
122
- if (typeof u1 === "string") return u1;
123
- const u2 = after === "document-edge" ? void 0 : edgeOf(after, "after");
124
- if (typeof u2 === "string") return u2;
125
- if (u1 === void 0) return after !== "document-edge" && after.block === 0 ? u2 - 1 : "no-anchor";
126
- if (u2 === void 0) return before !== "document-edge" && before.block === lastBlock ? u1 : "no-anchor";
127
- return u2 === u1 + 1 && units?.[u1]?.adjacentToNext === true ? u1 : "blocks-not-adjacent";
151
+ if (unitAfter !== unitBefore + 1 || units?.[unitBefore]?.adjacentToNext !== true) return "blocks-not-adjacent";
152
+ return unitBefore;
128
153
  };
129
154
  for (const passage of passages) {
130
- const at = place(passage);
131
- if (typeof at === "string") abstentions.push(at);
132
- else {
133
- insertions.push({
134
- edit: { kind: "insert-unit-after", unit: at, text: passage.sourceWords.join(" ") },
135
- letters: passage.sourceWords.reduce((n, w) => n + conservationKey2(w).length, 0)
136
- });
155
+ const placement = placePassage(passage);
156
+ if (typeof placement === "string") {
157
+ abstentions.push(placement);
158
+ continue;
137
159
  }
160
+ insertions.push({
161
+ edit: { kind: "insert-unit-after", unit: placement, text: passage.sourceWords.join(" ") },
162
+ letters: passage.sourceWords.reduce((letterTotal, word) => letterTotal + conservationKey2(word).length, 0)
163
+ });
138
164
  }
139
165
  return { insertions, abstentions };
140
166
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/lib/chunk.ts", "../src/lib/link-schemes.ts", "../src/pipeline/glued-word-repair.ts", "../src/pipeline/lost-text-repair.ts"],
4
- "sourcesContent": ["/** Splits a list into consecutive groups of at most `size` items, in order. A LEAF module: it imports nothing.\n * NOT here: what a group means (a batch of pages, of records, of audit lines) or its size: each caller names its own.\n * Called by: `extractor/pdf-scanned.ts`, `orchestrator/publish-batch.ts`, `adapters/forge-audit-store.ts`. */\nexport function chunk<T>(items: readonly T[], size: number): T[][] {\n const out: T[][] = [];\n for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));\n return out;\n}\n", "/** The schemes an external link may leave a published page with: ONE definition (review of 27/09/2026, arbitrage of 28/09/2026).\n * NOT here: rendering a link (`renderer/storage.ts`), tying a PDF link annotation to words (`extractor/pdf-links.ts`), nor\n * which target of an Office file may become a link at all (`lib/external-link-target.ts`).\n * Called by: `renderer/storage.ts`, `extractor/pdf-links.ts`. */\n\n/** http, https, mailto \u2014 anything else (javascript:, file:, tel:\u2026) leaves the words as plain text. */\nexport const PUBLISHED_SCHEME = /^(?:https?|mailto):/i;\n", "/** Re-splits a glued page word where the PDF's own reading proves the boundaries, by adding spaces to the storage XHTML's text nodes \u2014 and undoes the whole repair if the re-check comes out worse in any way.\n * NOT here: finding the glued words (`pipeline/text-conservation.ts`), what the document record keeps (`pipeline/publish-conservation.ts`), nor joining a word published split \u2014 this lot repairs glued words only.\n * Called by: `pipeline/publish-conservation.ts`, once per checked PDF render. */\n\n/**\n * THE RULE (21/09/2026, lot 4). A page token is re-split ONLY when\n * its letters, as the check normalises them, are EXACTLY the concatenation of\n * the 2+ consecutive source words the word reading proved; a space goes at\n * each boundary the source gives, and nothing else changes. Anything less\n * certain is left alone and stays counted as glued, visible on the dashboard.\n *\n * WHY THE XHTML AND NOT THE DOCUMENT MODEL. The finding locates a word by\n * block and word index in the storage XHTML the check read; the same reader\n * hands back the text nodes those indices came from, so the edit lands on the\n * exact characters, with no second mapping to get wrong. A space added inside\n * a text node leaves every tag where it was: bold runs, links and images keep\n * their markup, and an image is never inside a word (it ends the\n * block for the reader). A boundary at a formatting edge gets its space at\n * the end of the first word's text node, inside that run.\n *\n * WHERE PUNCTUATION GOES. Between the last letter of one source word and the\n * first of the next, the page may carry non-letters (\u00AB IV.1.1)Vrsta \u00BB). They\n * are split as the source words carry them \u2014 the first word's trailing\n * characters, then the next word's leading ones; if the page's characters\n * there are not exactly those, the token is left alone rather than guessed.\n *\n * THE UNDO. The repaired page is checked again. It must lose no letter, keep\n * every page letter in the same order, create no word the PDF lacks, and\n * leave at most the glued words it did not repair; otherwise the original\n * page and its verdict are kept, whole \u2014 never a partial repair.\n *\n * \u26A0\uFE0F CLIENT TEXT, in memory only, like the verdict it reads.\n */\n\nimport { conservationKey, type ConservationVerdict, type PageEdit, type PublishedPage, type Respacing } from \"doc-ir\";\n\n/** One character of a published block: its text, its letters, and where it ends IN THAT BLOCK'S TEXT.\n * Until 09/11/2026 `end` was an offset in the storage XHTML and a unit could be an entity (`&amp;`): the decision\n * then only worked on one markup. It is now an index in the text the caller published, which every destination has. */\ninterface Unit {\n text: string;\n key: string;\n end: number;\n}\n\n/** One code point (the `u` flag makes `[\\s\\S]` match a whole one), so `end` is a UTF-16 index usable for `slice`. */\nconst UNIT = /[\\s\\S]/gu;\n\n/** The units of one published block. */\nconst unitsOf = (text: string): Unit[] =>\n [...text.matchAll(UNIT)].map((m) => ({ text: m[0], key: conservationKey(m[0]), end: m.index + m[0].length }));\n\n/** The block's words, as the check splits them: runs of non-space units with at least one letter.\n * Same split as `text-conservation.ts#wordKeysOf`, kept by unit to locate offsets. */\nconst wordsOf = (units: readonly Unit[]): Unit[][] => {\n const words: Unit[][] = [];\n let current: Unit[] = [];\n const close = (): void => {\n if (conservationKey(current.map((u) => u.text).join(\"\")).length > 0) words.push(current);\n current = [];\n };\n for (const u of units) {\n if (/^\\s+$/u.test(u.text)) close();\n else current.push(u);\n }\n close();\n return words;\n};\n\n/** Leading or trailing characters of a source word that carry no letter. */\nconst edge = (raw: string, side: \"lead\" | \"trail\"): string => {\n const chars = [...raw];\n const order = side === \"lead\" ? chars : [...chars].reverse();\n const out: string[] = [];\n for (const c of order) {\n if (conservationKey(c).length > 0) break;\n out.push(c);\n }\n return (side === \"lead\" ? out : [...out].reverse()).join(\"\");\n};\n\n/** The renderer's zero-width space before a superscript glued to a word (`renderer/storage.ts#renderInlines`, PLATFORM-STATUS \u00A781)\n * carries nothing the source says: it is passed over between the words, and the space goes before it. */\nconst visible = (text: string): string => text.replaceAll(\"\\u200B\", \"\");\n\n/** Where in its block one glued token takes its spaces (character indices), or `undefined` to leave it alone. */\nconst insertionsFor = (blocks: readonly string[], r: Respacing): number[] | undefined => {\n const at = r.pageWords[0];\n if (r.kind !== \"glued\" || r.pageWords.length !== 1 || at === undefined || r.sourceWords.length < 2) return undefined;\n const text = blocks[at.block];\n const units = text === undefined ? undefined : unitsOf(text);\n const word = units === undefined ? undefined : wordsOf(units)[at.word];\n if (word === undefined) return undefined;\n const keys = r.sourceWords.map(conservationKey);\n const tokenKey = conservationKey(word.map((u) => u.text).join(\"\"));\n // Unit by unit, the letters must add up to the token's own (NFKC can join\n // across characters), and the token must be exactly the source words.\n if (word.map((u) => u.key).join(\"\") !== tokenKey || keys.join(\"\") !== tokenKey) return undefined;\n\n const offsets: number[] = [];\n let u = 0;\n let letters = 0;\n for (let i = 0; i < keys.length - 1; i++) {\n const boundary = letters + keys[i]!.length;\n // The unit carrying the first word's last letter must end exactly there.\n while (u < word.length && letters + word[u]!.key.length <= boundary && letters < boundary)\n letters += word[u++]!.key.length;\n if (letters !== boundary) return undefined;\n // Non-letters up to the next word's first letter, split as the source says.\n let next = u;\n while (next < word.length && word[next]!.key.length === 0) next++;\n const between = word.slice(u, next);\n const trail = edge(r.sourceWords[i]!, \"trail\");\n if (visible(between.map((x) => x.text).join(\"\")) !== trail + edge(r.sourceWords[i + 1]!, \"lead\")) return undefined;\n let taken = \"\";\n let k = 0;\n while (taken.length < trail.length && k < between.length) taken += visible(between[k++]!.text);\n if (taken !== trail) return undefined;\n offsets.push(word[u + k - 1]!.end);\n u += k;\n }\n return offsets;\n};\n\n/** The spaces this check PROVES, as edits for the caller to apply to its own page; `repaired` counts the glued tokens\n * that got all of theirs. Writes nothing: composing a page is the caller's job (`PageEdit`). */\nexport function gluedWordEdits(\n page: PublishedPage,\n respacings: readonly Respacing[],\n): { edits: PageEdit[]; repaired: number } {\n const glued = respacings.filter((r) => r.kind === \"glued\");\n if (glued.length === 0) return { edits: [], repaired: 0 };\n const taken = new Set<string>();\n const edits: PageEdit[] = [];\n let repaired = 0;\n for (const r of glued) {\n const block = r.pageWords[0]?.block;\n const at = insertionsFor(page.blocks, r);\n if (at === undefined || block === undefined || at.some((o) => taken.has(`${block}:${o}`))) continue;\n for (const atChar of at) {\n taken.add(`${block}:${atChar}`);\n edits.push({ kind: \"insert-space\", block, atChar });\n }\n repaired += 1;\n }\n return { edits, repaired };\n}\n\n/** Whether the re-checked page is no worse than the original in any way. Exported since 09/11/2026: the loop that\n * applies the edits and re-checks belongs to the caller (it writes the page), but the RULE for keeping or undoing a\n * repair is this check's and stays here \u2014 a caller that invented its own could keep a page that lost a letter. */\nexport const noWorse = (before: ConservationVerdict, after: ConservationVerdict, repaired: number): boolean =>\n after.lostLetters <= before.lostLetters &&\n (after.decision !== \"lost\" || before.decision === \"lost\") &&\n after.decision !== \"abstain\" &&\n after.gluedWords <= before.gluedWords - repaired &&\n after.unmatchedPageWords <= before.unmatchedPageWords &&\n after.respacings.filter((r) => r.kind === \"split\").length <=\n before.respacings.filter((r) => r.kind === \"split\").length;\n", "/** Decides WHERE a passage the render lost goes back into the published page, as its own paragraph between the two adjacent top-level paragraphs that hold its source neighbours \u2014 and hands the caller the edit and the letters it puts back, or why it abstains.\n * NOT here: finding the lost words and their neighbours (`pipeline/text-conservation.ts`), glued words (`pipeline/glued-word-repair.ts`), nor applying an edit, checking the page again and keeping or undoing the repair: all three are the caller's.\n * Called by: a caller of the published light door (`lib/pdf-light.ts`), once per checked PDF render. */\n\n/**\n * THE RULE (21/09/2026, lot 5). A lost passage is a run of\n * consecutive source words neither reading found. Its neighbours are the\n * source words right before and right after it. It goes back ONLY when:\n * - each neighbour is a word the page matched (not an alt text, a list\n * number, a re-spacing: those have no single place in the page);\n * - the neighbour before is the LAST word of a top-level paragraph or\n * heading, the one after the FIRST word of the next top-level element,\n * with nothing between the two elements;\n * - at the start or the end of the document, the one neighbour opens the\n * page's first text block, or closes its last one.\n * Anything else abstains by name and the page stays \u00AB lost \u00BB, visible on the\n * dashboard: a loss inside a paragraph, a table cell, a list, an image\n * between the two paragraphs. A paragraph cut in the wrong place reads as if\n * nothing were wrong; a \u00AB N characters are not published \u00BB line does not.\n *\n * WHY THE XHTML AND NOT THE DOCUMENT MODEL (as lot 4). The check locates each\n * neighbour by block and word in the XHTML it read; the insertion goes at an\n * element boundary of that same XHTML, so no second mapping can disagree. The\n * inserted paragraph is the words as the PDF reads them, joined by single\n * spaces, escaped by the serializer's own `escapeText`.\n *\n * THE UNDO IS THE CALLER'S, NOT THIS MODULE'S. A caller applies the edits,\n * checks the repaired page again, and decides alone whether to keep it or to\n * restore the original page and its verdict. This module publishes only what\n * that re-check needs: for each passage placed, the edit and the number of\n * letters it puts back (`LostTextInsertion`); for each passage left where it\n * was, why (`LostTextAbstention`). A caller that wants an exact repair keeps\n * it only when the lost letters drop by EXACTLY the letters handed back here\n * and nothing else of the page moves: that rule is written where it is run.\n *\n * WHERE IT LANDS IS THE SOURCE'S ORDER, NOT THE RENDER'S. The neighbours are\n * read in content-stream order. Measured on 871 paragraphs cut from the 45\n * fixture renders (21/09/2026): 426 put back with the page's letters exactly\n * as before, 22 put back elsewhere \u2014 where the stream reads them. Some of\n * those read better than the render did (a form label, 0000523), some worse\n * (a second column read line by line, fixture 11). Tried and NOT kept: also\n * requiring the blocks on each side to follow the source's order \u2014 it\n * caught 8 of the 22 and cost 17 exact repairs. Text back in the page is what\n * search needs; a paragraph slightly out of place is the lesser defect.\n *\n * \u26A0\uFE0F CLIENT TEXT, in memory only, like the verdict it reads.\n */\n\nimport {\n conservationKey,\n wordKeysOf,\n type LostPassage,\n type PageEdit,\n type PageWordAt,\n type PublishedPage,\n} from \"doc-ir\";\n\n/** Why a lost passage was not put back \u2014 a closed list. */\nexport type LostTextAbstention =\n | \"no-anchor\"\n | \"anchor-unmatched\"\n | \"anchors-out-of-order\"\n | \"anchor-in-container\"\n | \"loss-inside-block\"\n | \"blocks-not-adjacent\";\n\n/** One passage placed: the edit the caller applies, and the letters it puts back (for the caller's accounting). */\nexport interface LostTextInsertion {\n edit: PageEdit;\n letters: number;\n}\n\n/** Where each lost passage goes, as an edit for the caller to apply \u2014 or why it does not go anywhere.\n *\n * It reasons on the page's UNITS (`PublishedPage.units`), never on markup (09/11/2026): a passage is put back between\n * two units only when the source word before it is the LAST word of its unit, the one after it the FIRST of the next,\n * both units are prose or a title, and nothing of the page sits between them. Anything less certain abstains by name,\n * and the name travels to the caller so a reader of the dashboard knows why nothing was repaired.\n *\n * `units` absent (the caller cannot say what a unit is): every passage abstains with `anchor-in-container` \u2014 the same\n * answer as a page whose anchors sit somewhere a paragraph may not go.\n */\nexport function placeLostPassages(\n page: PublishedPage,\n passages: readonly LostPassage[],\n): { insertions: LostTextInsertion[]; abstentions: LostTextAbstention[] } {\n const insertions: LostTextInsertion[] = [];\n const abstentions: LostTextAbstention[] = [];\n if (passages.length === 0) return { insertions, abstentions };\n const units = page.units;\n const words = page.blocks.map((text) => wordKeysOf(text).length);\n const lastBlock = words.length - 1;\n const unitOf = (block: number): number => units?.findIndex((unit) => unit.blocks.includes(block)) ?? -1;\n\n /** The anchor's unit, or why it cannot anchor. */\n const edgeOf = (at: PageWordAt, side: \"before\" | \"after\"): number | LostTextAbstention => {\n const u = unitOf(at.block);\n if (u < 0 || units?.[u]?.paragraphOrHeading !== true) return \"anchor-in-container\";\n // The last word of the unit (before) or its first (after): the loss must sit at the unit's edge, not inside it.\n const neighbourBlock = side === \"before\" ? at.block + 1 : at.block - 1;\n const atEdge = side === \"before\" ? at.word === (words[at.block] ?? 0) - 1 : at.word === 0;\n if (!atEdge || unitOf(neighbourBlock) === u) return \"loss-inside-block\";\n return u;\n };\n\n /** The unit the passage goes AFTER (`-1`: before the first unit), or why it does not. */\n const place = (passage: LostPassage): number | LostTextAbstention => {\n const { before, after } = passage;\n if (before === \"unanchored\" || after === \"unanchored\") return \"anchor-unmatched\";\n if (before === \"document-edge\" && after === \"document-edge\") return \"no-anchor\";\n if (before !== \"document-edge\" && after !== \"document-edge\") {\n if (after.block < before.block || (after.block === before.block && after.word <= before.word))\n return \"anchors-out-of-order\";\n }\n const u1 = before === \"document-edge\" ? undefined : edgeOf(before, \"before\");\n if (typeof u1 === \"string\") return u1;\n const u2 = after === \"document-edge\" ? undefined : edgeOf(after, \"after\");\n if (typeof u2 === \"string\") return u2;\n if (u1 === undefined) return after !== \"document-edge\" && after.block === 0 ? u2! - 1 : \"no-anchor\";\n if (u2 === undefined) return before !== \"document-edge\" && before.block === lastBlock ? u1 : \"no-anchor\";\n return u2 === u1 + 1 && units?.[u1]?.adjacentToNext === true ? u1 : \"blocks-not-adjacent\";\n };\n\n for (const passage of passages) {\n const at = place(passage);\n if (typeof at === \"string\") abstentions.push(at);\n else {\n insertions.push({\n edit: { kind: \"insert-unit-after\", unit: at, text: passage.sourceWords.join(\" \") },\n letters: passage.sourceWords.reduce((n, w) => n + conservationKey(w).length, 0),\n });\n }\n }\n return { insertions, abstentions };\n}\n"],
5
- "mappings": ";AAGO,SAAS,MAAS,OAAqB,MAAqB;AACjE,QAAM,MAAa,CAAC;AACpB,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,KAAM,KAAI,KAAK,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC;AAC9E,SAAO;AACT;;;ACDO,IAAM,mBAAmB;;;AC4BhC,SAAS,uBAAoG;AAY7G,IAAM,OAAO;AAGb,IAAM,UAAU,CAAC,SACf,CAAC,GAAG,KAAK,SAAS,IAAI,CAAC,EA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,EACtE;AAEA,aAAW,WAAW,UAAU;AAC9B,UAAM,KAAK,MAAM,OAAO;AACxB,QAAI,OAAO,OAAO,SAAU,aAAY,KAAK,EAAE;AAAA,SAC1C;AACH,iBAAW,KAAK;AAAA,QACd,MAAM,EAAE,MAAM,qBAAqB,MAAM,IAAI,MAAM,QAAQ,YAAY,KAAK,GAAG,EAAE;AAAA,QACjF,SAAS,QAAQ,YAAY,OAAO,CAAC,GAAG,MAAM,IAAIA,iBAAgB,CAAC,EAAE,QAAQ,CAAC;AAAA,MAChF,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO,EAAE,YAAY,YAAY;AACnC;",
6
- "names": ["u", "conservationKey"]
4
+ "sourcesContent": ["/** Splits a list into consecutive groups of at most `size` items, in order. Each caller decides what a group is and\n * how large it may be; this module imports nothing. */\nexport function chunk<T>(items: readonly T[], size: number): T[][] {\n const groups: T[][] = [];\n for (let start = 0; start < items.length; start += size) groups.push(items.slice(start, start + size));\n return groups;\n}\n", "/** The URI schemes an external link may keep when it is published: http, https and mailto. A link whose\n * target is not a web page or a mail address is not one a published page vouches for (`javascript:` runs a script,\n * `file:` points at the reader's own disk), so the words of any other scheme stay plain text. */\nexport const PUBLISHED_SCHEME = /^(?:https?|mailto):/i;\n", "/**\n * Proves where a glued page word should be split again, from the PDF's own reading, and hands the spaces back to the\n * caller as edits. The caller applies them and re-checks the page with `noWorse`.\n *\n * THE RULE. A page token is split only when its letters, as the conservation check normalises them, are exactly the\n * concatenation of the two or more consecutive source words the word reading proved. A space goes at each boundary the\n * source gives, and nothing else changes. Anything less certain is left alone and stays counted as glued.\n *\n * WHERE PUNCTUATION GOES. Between the last letter of one source word and the first of the next, the page may carry\n * non-letters (\u00AB IV.1.1)Vrsta \u00BB). They are split as the source words carry them: the first word's trailing characters,\n * then the next word's leading ones. When the page's characters there are not exactly those, the token is left alone\n * rather than guessed.\n *\n * Offsets are indices in the text the caller published, block by block, so the decision holds for any markup.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport { conservationKey, type ConservationVerdict, type PageEdit, type PublishedPage, type Respacing } from \"doc-ir\";\n\n/** One code point of a published block: its text, its letters as the check normalises them, and where it ends in\n * that block's text. */\ninterface CodePoint {\n readonly text: string;\n readonly key: string;\n readonly end: number;\n}\n\n/** One code point (the `u` flag makes `[\\s\\S]` match a whole surrogate pair), so that `end` is a UTF-16 index usable\n * with `slice`. */\nconst CODE_POINT = /[\\s\\S]/gu;\n\nconst splitCodePoints = (text: string): CodePoint[] =>\n [...text.matchAll(CODE_POINT)].map((match) => ({\n text: match[0],\n key: conservationKey(match[0]),\n end: match.index + match[0].length,\n }));\n\n/** The block's words as the check splits them: runs of non-space code points holding at least one letter. The same\n * split as doc-ir's `wordKeysOf`, kept by code point so that offsets can be located. */\nconst splitWords = (codePoints: readonly CodePoint[]): CodePoint[][] => {\n const words: CodePoint[][] = [];\n let current: CodePoint[] = [];\n const closeWord = (): void => {\n if (conservationKey(current.map((codePoint) => codePoint.text).join(\"\")).length > 0) words.push(current);\n current = [];\n };\n for (const codePoint of codePoints) {\n if (/^\\s+$/u.test(codePoint.text)) closeWord();\n else current.push(codePoint);\n }\n closeWord();\n return words;\n};\n\n/** The leading or trailing characters of a source word that carry no letter. */\nconst readNonLetterEdge = (word: string, side: \"lead\" | \"trail\"): string => {\n const characters = [...word];\n const ordered = side === \"lead\" ? characters : [...characters].reverse();\n const edge: string[] = [];\n for (const character of ordered) {\n if (conservationKey(character).length > 0) break;\n edge.push(character);\n }\n return (side === \"lead\" ? edge : [...edge].reverse()).join(\"\");\n};\n\n/** A renderer may put a zero-width space before a superscript glued to a word. It carries nothing the source says:\n * it is passed over between the words, and the space goes before it. */\nconst removeZeroWidthSpaces = (text: string): string => text.replaceAll(\"\\u200B\", \"\");\n\n/** The page token a respacing points at, or `undefined` when the respacing is not one glued page word made of two or\n * more source words. */\nconst findGluedToken = (blocks: readonly string[], respacing: Respacing): CodePoint[] | undefined => {\n const pageWord = respacing.pageWords[0];\n if (\n respacing.kind !== \"glued\" ||\n respacing.pageWords.length !== 1 ||\n pageWord === undefined ||\n respacing.sourceWords.length < 2\n )\n return undefined;\n const text = blocks[pageWord.block];\n if (text === undefined) return undefined;\n return splitWords(splitCodePoints(text))[pageWord.word];\n};\n\n/** How many of the non-letter code points between two source words belong to the first word, or `undefined` when they\n * are not exactly the first word's trailing characters followed by the next word's leading ones. */\nconst countTrailingCodePoints = (between: readonly CodePoint[], trail: string, lead: string): number | undefined => {\n if (removeZeroWidthSpaces(between.map((codePoint) => codePoint.text).join(\"\")) !== trail + lead) return undefined;\n let taken = \"\";\n let takenCount = 0;\n while (taken.length < trail.length && takenCount < between.length) {\n taken += removeZeroWidthSpaces(between[takenCount++]!.text);\n }\n return taken === trail ? takenCount : undefined;\n};\n\n/** Where in its block one glued token takes its spaces (character indices), or `undefined` to leave it alone. */\nconst findSpaceInsertions = (blocks: readonly string[], respacing: Respacing): number[] | undefined => {\n const token = findGluedToken(blocks, respacing);\n if (token === undefined) return undefined;\n const sourceKeys = respacing.sourceWords.map(conservationKey);\n const tokenKey = conservationKey(token.map((codePoint) => codePoint.text).join(\"\"));\n // Code point by code point, the letters must add up to the token's own (NFKC can join across characters), and the\n // token must be exactly the source words.\n if (token.map((codePoint) => codePoint.key).join(\"\") !== tokenKey || sourceKeys.join(\"\") !== tokenKey)\n return undefined;\n\n const offsets: number[] = [];\n let position = 0;\n let letterCount = 0;\n for (let sourceIndex = 0; sourceIndex < sourceKeys.length - 1; sourceIndex++) {\n const boundary = letterCount + sourceKeys[sourceIndex]!.length;\n // The code point carrying the first word's last letter must end exactly at the boundary.\n while (position < token.length && letterCount + token[position]!.key.length <= boundary && letterCount < boundary)\n letterCount += token[position++]!.key.length;\n if (letterCount !== boundary) return undefined;\n // The non-letters up to the next word's first letter, split as the source says.\n let nextLetter = position;\n while (nextLetter < token.length && token[nextLetter]!.key.length === 0) nextLetter++;\n const takenCount = countTrailingCodePoints(\n token.slice(position, nextLetter),\n readNonLetterEdge(respacing.sourceWords[sourceIndex]!, \"trail\"),\n readNonLetterEdge(respacing.sourceWords[sourceIndex + 1]!, \"lead\"),\n );\n if (takenCount === undefined) return undefined;\n offsets.push(token[position + takenCount - 1]!.end);\n position += takenCount;\n }\n return offsets;\n};\n\n/** The spaces this check proves, as edits for the caller to apply to its own page; `repaired` counts the glued tokens\n * that got all of theirs. It writes nothing: composing a page is the caller's job. */\nexport function gluedWordEdits(\n page: PublishedPage,\n respacings: readonly Respacing[],\n): { edits: PageEdit[]; repaired: number } {\n const glued = respacings.filter((respacing) => respacing.kind === \"glued\");\n if (glued.length === 0) return { edits: [], repaired: 0 };\n const takenOffsets = new Set<string>();\n const edits: PageEdit[] = [];\n let repaired = 0;\n for (const respacing of glued) {\n const block = respacing.pageWords[0]?.block;\n const offsets = findSpaceInsertions(page.blocks, respacing);\n if (\n offsets === undefined ||\n block === undefined ||\n offsets.some((offset) => takenOffsets.has(`${block}:${offset}`))\n )\n continue;\n for (const atChar of offsets) {\n takenOffsets.add(`${block}:${atChar}`);\n edits.push({ kind: \"insert-space\", block, atChar });\n }\n repaired += 1;\n }\n return { edits, repaired };\n}\n\n/** How many respacings of the verdict are splits: a source word published as several page words. */\nconst countSplitWords = (verdict: ConservationVerdict): number =>\n verdict.respacings.filter((respacing) => respacing.kind === \"split\").length;\n\n/** Whether the re-checked page is no worse than the original in any way. The caller applies the edits and re-checks,\n * because it writes the page; the rule for keeping or undoing a repair stays here, so that no caller keeps a page\n * that lost a letter. A repair is kept whole or not at all. */\nexport const noWorse = (before: ConservationVerdict, after: ConservationVerdict, repaired: number): boolean =>\n after.lostLetters <= before.lostLetters &&\n (after.decision !== \"lost\" || before.decision === \"lost\") &&\n after.decision !== \"abstain\" &&\n after.gluedWords <= before.gluedWords - repaired &&\n after.unmatchedPageWords <= before.unmatchedPageWords &&\n countSplitWords(after) <= countSplitWords(before);\n", "/**\n * Decides where a passage the render lost goes back into the published page, as its own unit between the two adjacent\n * units that hold its source neighbours. It hands the caller the edit and the letters it puts back, or why it\n * abstains; applying the edit, re-checking the page and keeping or undoing the repair are the caller's.\n *\n * THE RULE. A lost passage is a run of consecutive source words neither reading of the conservation check found. Its\n * neighbours are the source words right before and right after it. It goes back only when:\n * - each neighbour is a word the page matched (not an alternate text, a list number or a re-spacing: those have no\n * single place in the page);\n * - the neighbour before is the last word of a paragraph or heading unit, the one after the first word of the next\n * unit, with nothing between the two;\n * - at the start or the end of the document, the one neighbour opens the page's first block, or closes its last one.\n * Anything else abstains by name and the page stays \u00AB lost \u00BB: a loss inside a paragraph, a table cell or a list, or an\n * image between the two paragraphs. A paragraph cut in the wrong place reads as if nothing were wrong; a \u00AB N characters\n * are not published \u00BB notice does not.\n *\n * THE UNDO IS THE CALLER'S. This module hands back only what the re-check needs: for each passage placed, the edit\n * and the number of letters it puts back (`LostTextInsertion`); for each passage left out, why\n * (`LostTextAbstention`). A caller that wants an exact repair keeps it only when the lost letters drop by exactly the\n * letters handed back and nothing else of the page moves.\n *\n * WHERE IT LANDS IS THE SOURCE'S ORDER, NOT THE RENDER'S. The neighbours are read in content stream order. Measured on\n * 871 paragraphs cut from 45 renders: 426 put back with the page's letters exactly as before, 22 put back elsewhere,\n * where the content stream reads them; some of those read better than the render did, some worse (a second column read\n * line by line). Tried and not kept: also requiring the blocks on each side to follow the source's order. It caught 8\n * of the 22 and cost 17 exact repairs. Text back in the page is what search needs; a paragraph slightly out of place\n * is the lesser defect.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport {\n conservationKey,\n wordKeysOf,\n type LostPassage,\n type PageEdit,\n type PageWordAt,\n type PublishedPage,\n} from \"doc-ir\";\n\n/** Why a lost passage was not put back: a closed list. */\nexport type LostTextAbstention =\n | \"no-anchor\"\n | \"anchor-unmatched\"\n | \"anchors-out-of-order\"\n | \"anchor-in-container\"\n | \"loss-inside-block\"\n | \"blocks-not-adjacent\";\n\n/** One passage placed: the edit the caller applies, and the letters it puts back, for the caller's accounting. */\nexport interface LostTextInsertion {\n edit: PageEdit;\n letters: number;\n}\n\n/** Whether `later` sits strictly after `earlier` in the page's reading order (block, then word). */\nconst isAfterInPageOrder = (later: PageWordAt, earlier: PageWordAt): boolean =>\n later.block > earlier.block || (later.block === earlier.block && later.word > earlier.word);\n\n/** Where each lost passage goes, as an edit for the caller to apply, or why it goes nowhere.\n *\n * It reasons on the page's units (`PublishedPage.units`), never on markup. The reason of each abstention travels to the\n * caller, so that a reader of the result knows why nothing was repaired.\n *\n * `units` absent (the caller cannot say what a unit is): every passage abstains with `anchor-in-container`, the same\n * answer as for a page whose anchors sit where a paragraph may not go.\n */\nexport function placeLostPassages(\n page: PublishedPage,\n passages: readonly LostPassage[],\n): { insertions: LostTextInsertion[]; abstentions: LostTextAbstention[] } {\n const insertions: LostTextInsertion[] = [];\n const abstentions: LostTextAbstention[] = [];\n if (passages.length === 0) return { insertions, abstentions };\n const units = page.units;\n const wordCountByBlock = page.blocks.map((text) => wordKeysOf(text).length);\n const lastBlock = wordCountByBlock.length - 1;\n const findUnitOfBlock = (block: number): number => units?.findIndex((unit) => unit.blocks.includes(block)) ?? -1;\n\n /** The anchor's unit, or why it cannot anchor. */\n const findAnchorUnit = (anchor: PageWordAt, side: \"before\" | \"after\"): number | LostTextAbstention => {\n const unitIndex = findUnitOfBlock(anchor.block);\n if (unitIndex < 0 || units?.[unitIndex]?.paragraphOrHeading !== true) return \"anchor-in-container\";\n // The loss must sit at the unit's edge: the anchor before is the unit's last word, the anchor after its first.\n const neighbourBlock = side === \"before\" ? anchor.block + 1 : anchor.block - 1;\n const isAtEdge = side === \"before\" ? anchor.word === (wordCountByBlock[anchor.block] ?? 0) - 1 : anchor.word === 0;\n if (!isAtEdge || findUnitOfBlock(neighbourBlock) === unitIndex) return \"loss-inside-block\";\n return unitIndex;\n };\n\n /** The unit the passage goes after (`-1`: before the first unit), or why it goes nowhere. */\n const placePassage = (passage: LostPassage): number | LostTextAbstention => {\n const { before, after } = passage;\n if (before === \"unanchored\" || after === \"unanchored\") return \"anchor-unmatched\";\n if (before === \"document-edge\" && after === \"document-edge\") return \"no-anchor\";\n if (before !== \"document-edge\" && after !== \"document-edge\" && !isAfterInPageOrder(after, before))\n return \"anchors-out-of-order\";\n const unitBefore = before === \"document-edge\" ? undefined : findAnchorUnit(before, \"before\");\n if (typeof unitBefore === \"string\") return unitBefore;\n const unitAfter = after === \"document-edge\" ? undefined : findAnchorUnit(after, \"after\");\n if (typeof unitAfter === \"string\") return unitAfter;\n // At the start of the document, the passage goes before the unit that opens the page's first block.\n if (unitBefore === undefined) {\n if (unitAfter === undefined || after === \"document-edge\" || after.block !== 0) return \"no-anchor\";\n return unitAfter - 1;\n }\n // At the end of the document, the passage goes after the unit that closes the page's last block.\n if (unitAfter === undefined) {\n if (before === \"document-edge\" || before.block !== lastBlock) return \"no-anchor\";\n return unitBefore;\n }\n if (unitAfter !== unitBefore + 1 || units?.[unitBefore]?.adjacentToNext !== true) return \"blocks-not-adjacent\";\n return unitBefore;\n };\n\n for (const passage of passages) {\n const placement = placePassage(passage);\n if (typeof placement === \"string\") {\n abstentions.push(placement);\n continue;\n }\n insertions.push({\n edit: { kind: \"insert-unit-after\", unit: placement, text: passage.sourceWords.join(\" \") },\n letters: passage.sourceWords.reduce((letterTotal, word) => letterTotal + conservationKey(word).length, 0),\n });\n }\n return { insertions, abstentions };\n}\n"],
5
+ "mappings": ";AAEO,SAAS,MAAS,OAAqB,MAAqB;AACjE,QAAM,SAAgB,CAAC;AACvB,WAAS,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,KAAM,QAAO,KAAK,MAAM,MAAM,OAAO,QAAQ,IAAI,CAAC;AACrG,SAAO;AACT;;;ACHO,IAAM,mBAAmB;;;ACehC,SAAS,uBAAoG;AAY7G,IAAM,aAAa;AAEnB,IAAM,kBAAkB,CAAC,SACvB,CAAC,GAAG,KAAK,SAAS,UAAU,CAAC,EAAE,IAAI,CAAC,WAAW;AAAA,EAC7C,MAAM,MAAM,CAAC;AAAA,EAC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