@arbidocs/react 0.4.68 → 0.4.70

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.
Files changed (70) hide show
  1. package/README.md +8 -0
  2. package/dist/annotations/index.cjs +186 -2450
  3. package/dist/annotations/index.cjs.map +1 -1
  4. package/dist/annotations/index.d.cts +3 -33
  5. package/dist/annotations/index.d.ts +3 -33
  6. package/dist/annotations/index.js +4 -2411
  7. package/dist/annotations/index.js.map +1 -1
  8. package/dist/artifacts/index.cjs +88 -112
  9. package/dist/artifacts/index.cjs.map +1 -1
  10. package/dist/artifacts/index.js +12 -61
  11. package/dist/artifacts/index.js.map +1 -1
  12. package/dist/artifacts/redline-core.cjs +8 -7
  13. package/dist/artifacts/redline-core.js +2 -1
  14. package/dist/{chunk-PATLJSAO.cjs → chunk-3AADNIOK.cjs} +9 -52
  15. package/dist/chunk-3AADNIOK.cjs.map +1 -0
  16. package/dist/chunk-3QF5DNAP.js +2413 -0
  17. package/dist/chunk-3QF5DNAP.js.map +1 -0
  18. package/dist/chunk-5DCRIWCA.cjs +243 -0
  19. package/dist/chunk-5DCRIWCA.cjs.map +1 -0
  20. package/dist/{chunk-NA3FOYSF.cjs → chunk-5SZ2J2WT.cjs} +5 -177
  21. package/dist/chunk-5SZ2J2WT.cjs.map +1 -0
  22. package/dist/{chunk-43AKLNBC.js → chunk-74N436VK.js} +4 -40
  23. package/dist/chunk-74N436VK.js.map +1 -0
  24. package/dist/{chunk-Z3RRZ3KV.cjs → chunk-7CL7QHT6.cjs} +2 -240
  25. package/dist/chunk-7CL7QHT6.cjs.map +1 -0
  26. package/dist/{chunk-BWVIAATD.cjs → chunk-BTRIS3HY.cjs} +4 -4
  27. package/dist/{chunk-BWVIAATD.cjs.map → chunk-BTRIS3HY.cjs.map} +1 -1
  28. package/dist/chunk-G6FHNURH.js +234 -0
  29. package/dist/chunk-G6FHNURH.js.map +1 -0
  30. package/dist/chunk-HKUD2NZN.js +61 -0
  31. package/dist/chunk-HKUD2NZN.js.map +1 -0
  32. package/dist/chunk-QRCMKEE6.js +173 -0
  33. package/dist/chunk-QRCMKEE6.js.map +1 -0
  34. package/dist/{chunk-PFKLOVGQ.js → chunk-SYPUFZGA.js} +3 -233
  35. package/dist/chunk-SYPUFZGA.js.map +1 -0
  36. package/dist/chunk-T4IJHRRD.cjs +71 -0
  37. package/dist/chunk-T4IJHRRD.cjs.map +1 -0
  38. package/dist/chunk-ULU5LEWF.cjs +2460 -0
  39. package/dist/chunk-ULU5LEWF.cjs.map +1 -0
  40. package/dist/{chunk-TQ6FRVAH.js → chunk-V4CXOPLB.js} +3 -3
  41. package/dist/{chunk-TQ6FRVAH.js.map → chunk-V4CXOPLB.js.map} +1 -1
  42. package/dist/chunk-VOFNX4P6.cjs +50 -0
  43. package/dist/chunk-VOFNX4P6.cjs.map +1 -0
  44. package/dist/chunk-WUTL62MC.js +42 -0
  45. package/dist/chunk-WUTL62MC.js.map +1 -0
  46. package/dist/{chunk-JPGV7NMY.js → chunk-YXSXGTYQ.js} +4 -173
  47. package/dist/chunk-YXSXGTYQ.js.map +1 -0
  48. package/dist/chunk-Z3LLUO32.cjs +177 -0
  49. package/dist/chunk-Z3LLUO32.cjs.map +1 -0
  50. package/dist/document-tools/index.cjs +683 -0
  51. package/dist/document-tools/index.cjs.map +1 -0
  52. package/dist/document-tools/index.d.cts +392 -0
  53. package/dist/document-tools/index.d.ts +392 -0
  54. package/dist/document-tools/index.js +639 -0
  55. package/dist/document-tools/index.js.map +1 -0
  56. package/dist/index.cjs +320 -318
  57. package/dist/index.cjs.map +1 -1
  58. package/dist/index.js +9 -6
  59. package/dist/index.js.map +1 -1
  60. package/dist/store-CqkkD7Ho.d.cts +35 -0
  61. package/dist/store-D1nhbkgk.d.ts +35 -0
  62. package/dist/ui/index.cjs +138 -137
  63. package/dist/ui/index.js +3 -2
  64. package/package.json +11 -3
  65. package/dist/chunk-43AKLNBC.js.map +0 -1
  66. package/dist/chunk-JPGV7NMY.js.map +0 -1
  67. package/dist/chunk-NA3FOYSF.cjs.map +0 -1
  68. package/dist/chunk-PATLJSAO.cjs.map +0 -1
  69. package/dist/chunk-PFKLOVGQ.js.map +0 -1
  70. package/dist/chunk-Z3RRZ3KV.cjs.map +0 -1
@@ -0,0 +1,234 @@
1
+ import { normalizeCitationMarkup } from './chunk-QRCMKEE6.js';
2
+
3
+ // src/ai/stored-markdown.ts
4
+ var FENCE = /^\s*(```|~~~)/;
5
+ function mapOutsideFences(text, fn) {
6
+ let inFence = false;
7
+ return text.split("\n").map((line) => {
8
+ if (FENCE.test(line)) {
9
+ inFence = !inFence;
10
+ return line;
11
+ }
12
+ return inFence ? line : fn(line);
13
+ }).join("\n");
14
+ }
15
+ var ESCAPED_PUNCTUATION = /\\([\\`*_{}[\]()#+\-.!|>~<])/g;
16
+ var ESCAPED_EMPHASIS = /\\([*_])/g;
17
+ var INLINE_CODE = /(`+)(?!`)(.+?)(?<!`)\1(?!`)/g;
18
+ function unescapeMarkdown(text) {
19
+ if (!text.includes("\\")) return text;
20
+ return mapOutsideFences(text, (line) => {
21
+ if (!line.includes("\\")) return line;
22
+ let out = "";
23
+ let last = 0;
24
+ for (const span of line.matchAll(INLINE_CODE)) {
25
+ const at = span.index ?? 0;
26
+ out += line.slice(last, at).replace(ESCAPED_PUNCTUATION, "$1") + span[0].replace(ESCAPED_EMPHASIS, "$1");
27
+ last = at + span[0].length;
28
+ }
29
+ return out + line.slice(last).replace(ESCAPED_PUNCTUATION, "$1");
30
+ });
31
+ }
32
+ function repairParsedTitle(text) {
33
+ const lines = text.split("\n");
34
+ const first = lines.findIndex((l) => l.trim());
35
+ if (first < 0) return text;
36
+ const doubled = /^#{1,6}\s+(#{1,6}\s+\S.*)$/.exec(lines[first]);
37
+ if (doubled) {
38
+ lines[first] = doubled[1];
39
+ return lines.join("\n");
40
+ }
41
+ if (/^\s*```\s*$/.test(lines[first]) && /^#{1,6}\s+\S/.test(lines[first + 1] ?? "")) {
42
+ if (/^\s*```\s*$/.test(lines[first + 2] ?? "")) lines.splice(first + 2, 1);
43
+ else return text;
44
+ lines.splice(first, 1);
45
+ return lines.join("\n");
46
+ }
47
+ return text;
48
+ }
49
+ var DOUBLED_HEADING = /^#{1,6}\s+(#{1,6}\s+\S.*)$/;
50
+ var LIST_HEADING = /^[-*+]\s+(#{1,6}\s+\S.*)$/;
51
+ var LIST_IN_LIST = /^[-*+]\s+[-*+]\s+(\S.*)$/;
52
+ var LIST_ORDINAL = /^[-*+]\s+(\d{1,9})([.)])\s+(\S.*)$/;
53
+ var LIST_ITEM_LINE = /^\s*(?:[-*+]|\d{1,9}[.)])\s/;
54
+ var TABLE_DELIMITER_CELL = /^:?-{1,}:?$/;
55
+ function splitRunOfOrdinals(first, delimiter, rest) {
56
+ const items = [];
57
+ let n = first;
58
+ let remaining = rest;
59
+ for (; ; ) {
60
+ const next = new RegExp(`^(.+?)\\s+${n + 1}\\${delimiter}\\s+(\\S.*)$`).exec(remaining);
61
+ if (!next) break;
62
+ items.push(`${n}${delimiter} ${next[1]}`);
63
+ n += 1;
64
+ remaining = next[2];
65
+ }
66
+ items.push(`${n}${delimiter} ${remaining}`);
67
+ return items;
68
+ }
69
+ function rebuildFlatTable(line) {
70
+ const trimmed = line.trim();
71
+ if (!trimmed.startsWith("|") || !trimmed.endsWith("|")) return null;
72
+ const cells = trimmed.slice(1, -1).split("|").map((c) => c.trim());
73
+ const firstRule = cells.findIndex((c) => TABLE_DELIMITER_CELL.test(c));
74
+ if (firstRule < 2 || cells[firstRule - 1] !== "") return null;
75
+ const columns = firstRule - 1;
76
+ const rows = [];
77
+ for (let at = 0; at < cells.length; at += columns + 1) {
78
+ const row = cells.slice(at, at + columns);
79
+ const gap = cells[at + columns];
80
+ if (row.length !== columns || gap !== void 0 && gap !== "") return null;
81
+ rows.push(row);
82
+ }
83
+ const [header, rule, ...body] = rows;
84
+ if (!rule.every((c) => TABLE_DELIMITER_CELL.test(c))) return null;
85
+ const fmt = (row) => `| ${row.join(" | ")} |`;
86
+ return [fmt(header), fmt(rule.map(() => "---")), ...body.map(fmt)];
87
+ }
88
+ function repairParsedStructure(text) {
89
+ const out = [];
90
+ let inFence = false;
91
+ for (const line of text.split("\n")) {
92
+ if (FENCE.test(line)) {
93
+ inFence = !inFence;
94
+ out.push(line);
95
+ continue;
96
+ }
97
+ if (inFence) {
98
+ out.push(line);
99
+ continue;
100
+ }
101
+ const table = rebuildFlatTable(line);
102
+ if (table) {
103
+ out.push(...table);
104
+ continue;
105
+ }
106
+ const heading = DOUBLED_HEADING.exec(line) ?? LIST_HEADING.exec(line);
107
+ if (heading) {
108
+ out.push(heading[1]);
109
+ continue;
110
+ }
111
+ const ordinal = LIST_ORDINAL.exec(line);
112
+ if (ordinal) {
113
+ out.push(...splitRunOfOrdinals(Number(ordinal[1]), ordinal[2], ordinal[3]));
114
+ continue;
115
+ }
116
+ const nested = LIST_IN_LIST.exec(line);
117
+ out.push(nested ? `- ${nested[1]}` : line);
118
+ }
119
+ return out.filter(
120
+ (line, i) => !(line === "" && LIST_ITEM_LINE.test(out[i - 1] ?? "") && LIST_ITEM_LINE.test(out[i + 1] ?? ""))
121
+ ).join("\n");
122
+ }
123
+ var SOURCE_NOTE = /[ \t]*(?:\*+\(\s*Sources?\s*:[^)\n]*\)\*+|\(\s*\*{0,2}\s*Sources?\s*:[^)\n]*\))/gi;
124
+ var CITE_TOKEN = /^\]\(#cite-[\w-]+\)/;
125
+ function removeCitationLinks(line) {
126
+ if (!line.includes("](#cite-")) return line;
127
+ const drop = /* @__PURE__ */ new Set();
128
+ const open = [];
129
+ for (let i = 0; i < line.length; i++) {
130
+ const c = line[i];
131
+ if (c === "[") open.push(i);
132
+ else if (c === "]") {
133
+ const token = CITE_TOKEN.exec(line.slice(i, i + 40));
134
+ if (token) {
135
+ const opener = open.pop();
136
+ if (opener !== void 0) drop.add(opener);
137
+ for (let k = i; k < i + token[0].length; k++) drop.add(k);
138
+ i += token[0].length - 1;
139
+ } else open.pop();
140
+ }
141
+ }
142
+ let out = "";
143
+ for (let i = 0; i < line.length; i++) if (!drop.has(i)) out += line[i];
144
+ return out;
145
+ }
146
+ function balanceBold(line) {
147
+ if (/^\s*\*\*#{1,6}\s/.test(line)) return line.replace(/\*\*/g, "").trim();
148
+ if ((line.match(/\*\*/g)?.length ?? 0) % 2 === 0) return line;
149
+ if (/^#{1,6}\s/.test(line)) return line.replace(/\*\*/g, "");
150
+ return line.replace(/\*\*\s*$/, "").replace(/^(\s*(?:[-*]\s+)?)\*\*(?=\s)/, "$1");
151
+ }
152
+ function unwrapCitationLinks(text) {
153
+ const withoutNotes = mapOutsideFences(text, (line) => line.replace(SOURCE_NOTE, ""));
154
+ return mapOutsideFences(normalizeCitationMarkup(withoutNotes), (line) => {
155
+ const unlinked = removeCitationLinks(line);
156
+ return unlinked === line ? line : balanceBold(unlinked);
157
+ });
158
+ }
159
+ var HEADING = /^#{1,6}\s+\S/;
160
+ var HR_ONLY = /^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/;
161
+ var BOLD_LINE = /^\*\*[^*#].*\*\*$/;
162
+ var MAX_PREAMBLE_CHARS = 900;
163
+ var MAX_PREAMBLE_PARAGRAPHS = 4;
164
+ var MAX_TITLE_CHARS = 100;
165
+ var NARRATION_OPENER = /^(?:I(?:['’](?:ll|ve|m|d))?\s|let me\b|here(?:['’]s| is| are)\b|below is\b|sure[,.! ]|certainly[,.! ]|of course[,.! ]|okay[,.! ]|based on (?:the|your|my)\b|per the (?:user|instructions?)|as requested\b|the workspace\b|no (?:relevant |workspace |matching )?documents?\b|there (?:are|is) no (?:relevant |workspace )?documents?\b|after (?:reviewing|reading|searching)\b)/i;
166
+ var STRUCTURED = /^\s*(?:[-*+>|]|\d{1,9}[.)]\s|#{1,6}\s|```|~~~)|\*\*|\]\(/m;
167
+ function stripAgentPreamble(text) {
168
+ const lines = text.split("\n");
169
+ const start = lines.findIndex((l) => HEADING.test(l));
170
+ if (start <= 0) return text;
171
+ const before = lines.slice(0, start).filter((l) => !HR_ONLY.test(l)).join("\n").trim();
172
+ if (!before) return lines.slice(start).join("\n");
173
+ const paragraphs = before.split(/\n\s*\n/).map((p) => p.trim());
174
+ const narration = before.length <= MAX_PREAMBLE_CHARS && paragraphs.length <= MAX_PREAMBLE_PARAGRAPHS && !STRUCTURED.test(before) && paragraphs.every((p) => NARRATION_OPENER.test(p));
175
+ return narration ? lines.slice(start).join("\n") : text;
176
+ }
177
+ function promoteBoldTitle(text) {
178
+ const lines = text.split("\n");
179
+ const first = lines.findIndex((l) => l.trim());
180
+ if (first < 0) return text;
181
+ const line = lines[first].trim();
182
+ if (!BOLD_LINE.test(line)) return text;
183
+ const title = line.replace(/\*\*/g, "").trim();
184
+ if (title.length === 0 || title.length > MAX_TITLE_CHARS || !/^[\p{Lu}\d]/u.test(title) || /[,;:]$/.test(title) || /[.!?]\s+\S/.test(title)) {
185
+ return text;
186
+ }
187
+ lines[first] = `# ${title}`;
188
+ return lines.join("\n");
189
+ }
190
+ function cleanHeadings(text) {
191
+ return mapOutsideFences(
192
+ text,
193
+ (line) => /^\s*#{1,6}\s/.test(line) ? line.replace(/\*\*/g, "").trim() : line
194
+ );
195
+ }
196
+ var MIN_RATIO = 0.7;
197
+ var countMatches = (text, re) => text.match(re)?.length ?? 0;
198
+ var LIST_NUMBER = /^\s*\d{1,9}[.)]\s/gm;
199
+ var HEADING_LINE = /^#{1,6}\s/gm;
200
+ var withoutCitationMarkup = (raw) => mapOutsideFences(raw.replace(SOURCE_NOTE, ""), removeCitationLinks).trim();
201
+ var tidy = (text) => text.replace(/\n{3,}/g, "\n\n").trim();
202
+ var isPrefixCut = (before, after) => before.trimEnd().endsWith(after.trim());
203
+ var keepsStructure = (candidate, reference) => countMatches(candidate, LIST_NUMBER) >= countMatches(reference, LIST_NUMBER) && countMatches(candidate, HEADING_LINE) >= countMatches(reference, HEADING_LINE);
204
+ var DEFAULT_CLEAN_STEPS = {
205
+ unwrap: unwrapCitationLinks,
206
+ strip: stripAgentPreamble,
207
+ promote: promoteBoldTitle
208
+ };
209
+ function cleanDraftWithReport(raw, steps = DEFAULT_CLEAN_STEPS) {
210
+ const floor = withoutCitationMarkup(raw);
211
+ const ratio = (t) => floor.length ? t.length / floor.length : 1;
212
+ const unwrapped = tidy(steps.unwrap(raw));
213
+ const stripped = tidy(steps.strip(unwrapped));
214
+ const titled = tidy(cleanHeadings(steps.promote(stripped)));
215
+ const changedBy = [];
216
+ if (unwrapped !== raw.trim()) changedBy.push("citations");
217
+ if (stripped !== unwrapped) changedBy.push("preamble");
218
+ if (titled !== stripped) changedBy.push("title");
219
+ const unwrappedOk = unwrapped.length >= MIN_RATIO * floor.length && keepsStructure(unwrapped, raw);
220
+ if (!unwrappedOk) return { text: raw, stage: "raw", ratio: 1, changedBy, guarded: true };
221
+ const strippedOk = stripped === unwrapped || isPrefixCut(unwrapped, stripped) && keepsStructure(stripped, unwrapped);
222
+ const titledOk = titled.length >= MIN_RATIO * stripped.length && keepsStructure(titled, stripped);
223
+ if (strippedOk && titledOk) {
224
+ return { text: titled, stage: "cleaned", ratio: ratio(titled), changedBy, guarded: false };
225
+ }
226
+ return { text: unwrapped, stage: "unwrapped", ratio: ratio(unwrapped), changedBy, guarded: true };
227
+ }
228
+ function cleanDraftMarkdown(raw) {
229
+ return cleanDraftWithReport(raw).text;
230
+ }
231
+
232
+ export { cleanDraftMarkdown, cleanDraftWithReport, promoteBoldTitle, repairParsedStructure, repairParsedTitle, stripAgentPreamble, unescapeMarkdown, unwrapCitationLinks };
233
+ //# sourceMappingURL=chunk-G6FHNURH.js.map
234
+ //# sourceMappingURL=chunk-G6FHNURH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ai/stored-markdown.ts"],"names":[],"mappings":";;;AAgBA,IAAM,KAAA,GAAQ,eAAA;AAGd,SAAS,gBAAA,CAAiB,MAAc,EAAA,EAAsC;AAC5E,EAAA,IAAI,OAAA,GAAU,KAAA;AACd,EAAA,OAAO,KACJ,KAAA,CAA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AK,OAAO,CAAA;AAE/C,EAAA,MAAM,WAAA,GAAc,UAAU,MAAA,IAAU,SAAA,GAAY,MAAM,MAAA,IAAU,cAAA,CAAe,WAAW,GAAG,CAAA;AACjG,EAAA,IAAI,CAAC,WAAA,EAAa,OAAO,EAAE,IAAA,EAAM,GAAA,EAAK,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,CAAA,EAAG,SAAA,EAAW,OAAA,EAAS,IAAA,EAAK;AACvF,EAAA,MAAM,UAAA,GACJ,aAAa,SAAA,IACZ,WAAA,CAAY,WAAW,QAAQ,CAAA,IAAK,cAAA,CAAe,QAAA,EAAU,SAAS,CAAA;AACzE,EAAA,MAAM,QAAA,GAAW,OAAO,MAAA,IAAU,SAAA,GAAY,SAAS,MAAA,IAAU,cAAA,CAAe,QAAQ,QAAQ,CAAA;AAChG,EAAA,IAAI,cAAc,QAAA,EAAU;AAC1B,IAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,KAAA,EAAO,SAAA,EAAW,KAAA,EAAO,KAAA,CAAM,MAAM,CAAA,EAAG,SAAA,EAAW,OAAA,EAAS,KAAA,EAAM;AAAA,EAC3F;AACA,EAAA,OAAO,EAAE,IAAA,EAAM,SAAA,EAAW,KAAA,EAAO,WAAA,EAAa,KAAA,EAAO,KAAA,CAAM,SAAS,CAAA,EAAG,SAAA,EAAW,OAAA,EAAS,IAAA,EAAK;AAClG;AAOO,SAAS,mBAAmB,GAAA,EAAqB;AACtD,EAAA,OAAO,oBAAA,CAAqB,GAAG,CAAA,CAAE,IAAA;AACnC","file":"chunk-G6FHNURH.js","sourcesContent":["/**\n * Helpers for markdown that is STORED (an agent's draft saved as an artifact, then read back from\n * the backend's parse). Pure and SDK-free; they sit next to `normalizeCitationMarkup`, which they\n * build on.\n *\n * Two directions:\n *\n * - Going in (`cleanDraftMarkdown` = `unwrapCitationLinks` + `stripAgentPreamble` +\n * `promoteBoldTitle`): a streamed draft carries citation links, `(*Source: ...*)` notes and\n * sometimes narration before the document. A stored letter should hold only the letter.\n * - Coming out (`unescapeMarkdown`): the backend's parse of a stored `.md` returns the text with\n * markdown punctuation backslash-escaped (`**Fees.**` comes back as `\\*\\*Fees\\.\\*\\*`).\n */\n\nimport { normalizeCitationMarkup } from './normalize-citations'\n\nconst FENCE = /^\\s*(```|~~~)/\n\n/** Run `fn` on every line outside a fenced code block. */\nfunction mapOutsideFences(text: string, fn: (line: string) => string): string {\n let inFence = false\n return text\n .split('\\n')\n .map((line) => {\n if (FENCE.test(line)) {\n inFence = !inFence\n return line\n }\n return inFence ? line : fn(line)\n })\n .join('\\n')\n}\n\n// ---------------------------------------------------------------------------------------------\n// Coming out: undo the parser's escaping\n// ---------------------------------------------------------------------------------------------\n\n/** A backslash followed by markdown punctuation: the only thing the parser's escaping produces. */\nconst ESCAPED_PUNCTUATION = /\\\\([\\\\`*_{}[\\]()#+\\-.!|>~<])/g\n/** The only escapes the parser puts inside an inline code span. */\nconst ESCAPED_EMPHASIS = /\\\\([*_])/g\nconst INLINE_CODE = /(`+)(?!`)(.+?)(?<!`)\\1(?!`)/g\n\n/**\n * Undo the backend's escaping of a markdown artifact: `\\*\\*Scope\\.\\*\\*` becomes `**Scope.**`.\n *\n * THE RULE. Apply this ONLY to text of an artifact that was stored from markdown (an agent draft\n * or an edited version, always uploaded as `.md`): for those the parser escapes every markdown\n * punctuation character, including the backslash itself, so removing one level of escaping is the\n * exact inverse (an author's literal `\\*` is stored as `\\\\\\*` and comes back as `\\*`). Do not\n * apply it to a PDF or Word parse, where a backslash is just a character.\n *\n * Details:\n * - Only a backslash followed by markdown punctuation (``\\ ` * _ { } [ ] ( ) # + - . ! | > ~ <``)\n * is removed; `\\n`, `C:\\temp` and a trailing backslash are left alone.\n * - Pairs are read left to right, so `\\\\*` is an escaped backslash followed by a bare `*`.\n * - Fenced code blocks are never touched (the parser does not escape inside them).\n * - Inline code spans: the parser DOES escape `*` and `_` there (`` `a*b` `` comes back as\n * `` `a\\*b` ``), so only `\\*` and `\\_` are undone inside a span; any other backslash in code\n * (`` `re\\.x` ``) is a literal and stays.\n */\nexport function unescapeMarkdown(text: string): string {\n if (!text.includes('\\\\')) return text\n return mapOutsideFences(text, (line) => {\n if (!line.includes('\\\\')) return line\n let out = ''\n let last = 0\n for (const span of line.matchAll(INLINE_CODE)) {\n const at = span.index ?? 0\n out +=\n line.slice(last, at).replace(ESCAPED_PUNCTUATION, '$1') +\n span[0].replace(ESCAPED_EMPHASIS, '$1')\n last = at + span[0].length\n }\n return out + line.slice(last).replace(ESCAPED_PUNCTUATION, '$1')\n })\n}\n\n/**\n * The parser also mangles the TITLE of a stored markdown document (seen on a real backend): the\n * first heading comes back doubled (`## # Title`) or alone inside a code fence\n * (a fence, `# Title`, a fence). Both are repaired, on the first non-blank line only, so a code\n * block or heading later in the text is never touched. Like `unescapeMarkdown`, apply it only to\n * artifacts stored from markdown.\n */\nexport function repairParsedTitle(text: string): string {\n const lines = text.split('\\n')\n const first = lines.findIndex((l) => l.trim())\n if (first < 0) return text\n const doubled = /^#{1,6}\\s+(#{1,6}\\s+\\S.*)$/.exec(lines[first])\n if (doubled) {\n lines[first] = doubled[1]\n return lines.join('\\n')\n }\n if (/^\\s*```\\s*$/.test(lines[first]) && /^#{1,6}\\s+\\S/.test(lines[first + 1] ?? '')) {\n if (/^\\s*```\\s*$/.test(lines[first + 2] ?? '')) lines.splice(first + 2, 1)\n else return text\n lines.splice(first, 1)\n return lines.join('\\n')\n }\n return text\n}\n\nconst DOUBLED_HEADING = /^#{1,6}\\s+(#{1,6}\\s+\\S.*)$/\nconst LIST_HEADING = /^[-*+]\\s+(#{1,6}\\s+\\S.*)$/\nconst LIST_IN_LIST = /^[-*+]\\s+[-*+]\\s+(\\S.*)$/\nconst LIST_ORDINAL = /^[-*+]\\s+(\\d{1,9})([.)])\\s+(\\S.*)$/\nconst LIST_ITEM_LINE = /^\\s*(?:[-*+]|\\d{1,9}[.)])\\s/\nconst TABLE_DELIMITER_CELL = /^:?-{1,}:?$/\n\n/** `1. a 2. b 3. c` (one line) split where the next ordinal follows: `['1. a', '2. b', '3. c']`. */\nfunction splitRunOfOrdinals(first: number, delimiter: string, rest: string): string[] {\n const items: string[] = []\n let n = first\n let remaining = rest\n for (;;) {\n const next = new RegExp(`^(.+?)\\\\s+${n + 1}\\\\${delimiter}\\\\s+(\\\\S.*)$`).exec(remaining)\n if (!next) break\n items.push(`${n}${delimiter} ${next[1]}`)\n n += 1\n remaining = next[2]\n }\n items.push(`${n}${delimiter} ${remaining}`)\n return items\n}\n\n/**\n * A table the parser put on ONE line (`| h | h | |---|---| | a | b |`, rows joined by a space, which\n * leaves one empty cell between rows) back as a pipe table. `null` when the line is not that shape.\n */\nfunction rebuildFlatTable(line: string): string[] | null {\n const trimmed = line.trim()\n if (!trimmed.startsWith('|') || !trimmed.endsWith('|')) return null\n const cells = trimmed\n .slice(1, -1)\n .split('|')\n .map((c) => c.trim())\n const firstRule = cells.findIndex((c) => TABLE_DELIMITER_CELL.test(c))\n if (firstRule < 2 || cells[firstRule - 1] !== '') return null\n const columns = firstRule - 1\n const rows: string[][] = []\n for (let at = 0; at < cells.length; at += columns + 1) {\n const row = cells.slice(at, at + columns)\n const gap = cells[at + columns]\n if (row.length !== columns || (gap !== undefined && gap !== '')) return null\n rows.push(row)\n }\n const [header, rule, ...body] = rows\n if (!rule.every((c) => TABLE_DELIMITER_CELL.test(c))) return null\n const fmt = (row: string[]): string => `| ${row.join(' | ')} |`\n return [fmt(header), fmt(rule.map(() => '---')), ...body.map(fmt)]\n}\n\n/**\n * Undo how the backend's parse of a stored `.md` restructures it (seen on a real backend):\n * - a heading comes back doubled (`## # Title`) or as a list item (`- # Title`);\n * - every list item gets a `- ` of its own on top of the original marker, so `* a` returns as\n * `- * a` and `1. a` as `- 1. a`, which a markdown editor loads as a list inside a list item\n * (and saves as `- - a`); a run of ordinals can come back on one line (`- 1. a 2. b`);\n * - a table comes back on one line.\n * List nesting and the bullet/ordered difference of a flat `- x` cannot be recovered, so items\n * stay flat. Items of one list are kept tight (no blank line between them). Fenced code is\n * never touched. Like `unescapeMarkdown`, apply it only to artifacts stored from markdown.\n */\nexport function repairParsedStructure(text: string): string {\n const out: string[] = []\n let inFence = false\n for (const line of text.split('\\n')) {\n if (FENCE.test(line)) {\n inFence = !inFence\n out.push(line)\n continue\n }\n if (inFence) {\n out.push(line)\n continue\n }\n const table = rebuildFlatTable(line)\n if (table) {\n out.push(...table)\n continue\n }\n const heading = DOUBLED_HEADING.exec(line) ?? LIST_HEADING.exec(line)\n if (heading) {\n out.push(heading[1])\n continue\n }\n const ordinal = LIST_ORDINAL.exec(line)\n if (ordinal) {\n out.push(...splitRunOfOrdinals(Number(ordinal[1]), ordinal[2], ordinal[3]))\n continue\n }\n const nested = LIST_IN_LIST.exec(line)\n out.push(nested ? `- ${nested[1]}` : line)\n }\n // Items parsed as separate chunks arrive one blank line apart: that is one tight list.\n return out\n .filter(\n (line, i) =>\n !(\n line === '' &&\n LIST_ITEM_LINE.test(out[i - 1] ?? '') &&\n LIST_ITEM_LINE.test(out[i + 1] ?? '')\n )\n )\n .join('\\n')\n}\n\n// ---------------------------------------------------------------------------------------------\n// Going in: clean a streamed draft before it is stored\n// ---------------------------------------------------------------------------------------------\n\n/** `(*Source: Terms.pdf*)`, `(Sources: a, b)` and the italic form `*(Source: ...)*`. */\nconst SOURCE_NOTE =\n /[ \\t]*(?:\\*+\\(\\s*Sources?\\s*:[^)\\n]*\\)\\*+|\\(\\s*\\*{0,2}\\s*Sources?\\s*:[^)\\n]*\\))/gi\nconst CITE_TOKEN = /^\\]\\(#cite-[\\w-]+\\)/\n\n/**\n * Remove the citation links of ONE line and keep every word. A link is `[text](#cite-N)`, but the\n * model also writes brackets inside the text (`[We act for [PLACEHOLDER].](#cite-1)`) and links that\n * overlap other brackets, so a regex cannot find the opening bracket. This scans the line with a\n * stack of `[`: a `](#cite-N)` takes the nearest open `[` with it (both are removed, the text\n * between stays); a plain `]` closes the nearest `[`; a `](#cite-N)` with no open `[` loses only\n * the marker. Brackets that are not part of a link are never touched.\n */\nfunction removeCitationLinks(line: string): string {\n if (!line.includes('](#cite-')) return line\n const drop = new Set<number>()\n const open: number[] = []\n for (let i = 0; i < line.length; i++) {\n const c = line[i]\n if (c === '[') open.push(i)\n else if (c === ']') {\n const token = CITE_TOKEN.exec(line.slice(i, i + 40))\n if (token) {\n const opener = open.pop()\n if (opener !== undefined) drop.add(opener)\n for (let k = i; k < i + token[0].length; k++) drop.add(k)\n i += token[0].length - 1\n } else open.pop()\n }\n }\n let out = ''\n for (let i = 0; i < line.length; i++) if (!drop.has(i)) out += line[i]\n return out\n}\n\n/** A line whose `**` do not pair up (one half was wrapped into a link) loses the stray marks. */\nfunction balanceBold(line: string): string {\n // A bold-wrapped heading (`**# Title**`) is just a heading.\n if (/^\\s*\\*\\*#{1,6}\\s/.test(line)) return line.replace(/\\*\\*/g, '').trim()\n if ((line.match(/\\*\\*/g)?.length ?? 0) % 2 === 0) return line\n if (/^#{1,6}\\s/.test(line)) return line.replace(/\\*\\*/g, '')\n return line.replace(/\\*\\*\\s*$/, '').replace(/^(\\s*(?:[-*]\\s+)?)\\*\\*(?=\\s)/, '$1')\n}\n\n/**\n * Text for storage from text that carries citations: `normalizeCitationMarkup` first (it hoists\n * list, heading and bold tokens out of the link so unwrapping cannot orphan half of a `**` pair),\n * then `[text](#cite-N)` becomes `text`, `(*Source: ...*)` notes are dropped, and a bold or\n * heading marker that lost its partner is repaired. Fenced code is left alone.\n */\nexport function unwrapCitationLinks(text: string): string {\n const withoutNotes = mapOutsideFences(text, (line) => line.replace(SOURCE_NOTE, ''))\n return mapOutsideFences(normalizeCitationMarkup(withoutNotes), (line) => {\n const unlinked = removeCitationLinks(line)\n return unlinked === line ? line : balanceBold(unlinked)\n })\n}\n\nconst HEADING = /^#{1,6}\\s+\\S/\nconst HR_ONLY = /^\\s*(?:-{3,}|\\*{3,}|_{3,})\\s*$/\n/** A whole-line bold title: `**Client Engagement Letter**`. */\nconst BOLD_LINE = /^\\*\\*[^*#].*\\*\\*$/\nconst MAX_PREAMBLE_CHARS = 900\nconst MAX_PREAMBLE_PARAGRAPHS = 4\nconst MAX_TITLE_CHARS = 100\n\n/**\n * How a paragraph of agent narration opens. An ALLOW-LIST: a paragraph that opens any other way is\n * treated as document text and never removed.\n */\nconst NARRATION_OPENER =\n /^(?:I(?:['’](?:ll|ve|m|d))?\\s|let me\\b|here(?:['’]s| is| are)\\b|below is\\b|sure[,.! ]|certainly[,.! ]|of course[,.! ]|okay[,.! ]|based on (?:the|your|my)\\b|per the (?:user|instructions?)|as requested\\b|the workspace\\b|no (?:relevant |workspace |matching )?documents?\\b|there (?:are|is) no (?:relevant |workspace )?documents?\\b|after (?:reviewing|reading|searching)\\b)/i\n\n/** Structure a covering note would not have: lists, tables, quotes, code, headings, bold, links. */\nconst STRUCTURED = /^\\s*(?:[-*+>|]|\\d{1,9}[.)]\\s|#{1,6}\\s|```|~~~)|\\*\\*|\\]\\(/m\n\n/**\n * Cut the agent's narration written BEFORE the document. Strictly non-destructive: if in doubt the\n * text is returned whole (a stray sentence is easy to delete, a lost clause is not recoverable).\n *\n * Text is removed only when ALL of these hold:\n * 1. a real markdown heading line (`# Title`, any level) follows it, and the cut stops exactly at\n * the FIRST such line (never at a bold line, never at a line that merely contains `**`);\n * 2. what precedes it is at most 4 paragraphs and 900 characters of plain prose (horizontal rules\n * between them are ignored): no list, table, quote, code, heading, bold or link;\n * 3. EVERY paragraph opens with an allow-listed narration opener: first person (\"I'll ...\",\n * \"I now have ...\"), \"Let me\", \"Here is/are\", \"Below is\", \"Sure\", \"Based on the ...\", \"Per the\n * instructions\", \"As requested\", \"The workspace ...\", \"No (relevant) documents ...\", \"There is\n * no document ...\", \"After reviewing ...\".\n * Anything else (a dateline, an address, a salutation, a sentence of the letter) keeps the text whole.\n */\nexport function stripAgentPreamble(text: string): string {\n const lines = text.split('\\n')\n const start = lines.findIndex((l) => HEADING.test(l))\n if (start <= 0) return text\n const before = lines\n .slice(0, start)\n .filter((l) => !HR_ONLY.test(l))\n .join('\\n')\n .trim()\n if (!before) return lines.slice(start).join('\\n')\n const paragraphs = before.split(/\\n\\s*\\n/).map((p) => p.trim())\n const narration =\n before.length <= MAX_PREAMBLE_CHARS &&\n paragraphs.length <= MAX_PREAMBLE_PARAGRAPHS &&\n !STRUCTURED.test(before) &&\n paragraphs.every((p) => NARRATION_OPENER.test(p))\n return narration ? lines.slice(start).join('\\n') : text\n}\n\n/**\n * Make the document's title a real heading: the FIRST non-blank line of the text, when it is a\n * short whole-line bold title (`**Letter**`, even with a stray inner `**`), becomes `# Letter`.\n * Nothing else is ever promoted: not a later line, not a mid-sentence fragment (the title must\n * start with a capital or digit, be at most 100 characters, hold no sentence break and not end in\n * `,` `;` or `:`), and a document that already opens with a heading is left alone.\n */\nexport function promoteBoldTitle(text: string): string {\n const lines = text.split('\\n')\n const first = lines.findIndex((l) => l.trim())\n if (first < 0) return text\n const line = lines[first].trim()\n if (!BOLD_LINE.test(line)) return text\n const title = line.replace(/\\*\\*/g, '').trim()\n if (\n title.length === 0 ||\n title.length > MAX_TITLE_CHARS ||\n !/^[\\p{Lu}\\d]/u.test(title) ||\n /[,;:]$/.test(title) ||\n /[.!?]\\s+\\S/.test(title)\n ) {\n return text\n }\n lines[first] = `# ${title}`\n return lines.join('\\n')\n}\n\n/** Tidy headings only: strip stray bold marks from heading lines (`# **Title**`). */\nfunction cleanHeadings(text: string): string {\n return mapOutsideFences(text, (line) =>\n /^\\s*#{1,6}\\s/.test(line) ? line.replace(/\\*\\*/g, '').trim() : line\n )\n}\n\n/** Which stage of the cleanup produced the text that is returned. */\nexport type DraftCleanStage = 'cleaned' | 'unwrapped' | 'raw'\n\nexport interface DraftCleanReport {\n /** What to store. */\n text: string\n /**\n * `cleaned`: the full cleanup. `unwrapped`: only the citation links were removed (the preamble or\n * title step was rejected by the guard). `raw`: the input as streamed (even link removal was\n * rejected).\n */\n stage: DraftCleanStage\n /** Length of the returned text over the length of the input without its citation markup. */\n ratio: number\n /** Which steps changed the text before the guard (for logs). */\n changedBy: ('citations' | 'preamble' | 'title')[]\n /** The guard rejected a step because it would have lost content. */\n guarded: boolean\n}\n\nconst MIN_RATIO = 0.7\nconst countMatches = (text: string, re: RegExp): number => text.match(re)?.length ?? 0\nconst LIST_NUMBER = /^\\s*\\d{1,9}[.)]\\s/gm\nconst HEADING_LINE = /^#{1,6}\\s/gm\n/** The text with only its citation markup gone: the floor no cleanup may go far under. */\nconst withoutCitationMarkup = (raw: string): string =>\n mapOutsideFences(raw.replace(SOURCE_NOTE, ''), removeCitationLinks).trim()\nconst tidy = (text: string): string => text.replace(/\\n{3,}/g, '\\n\\n').trim()\n/** `after` is `before` with a leading part removed (a prefix cut, never a cut in the middle). */\nconst isPrefixCut = (before: string, after: string): boolean =>\n before.trimEnd().endsWith(after.trim())\n/** Nothing structural was lost: headings and numbered items are all still there. */\nconst keepsStructure = (candidate: string, reference: string): boolean =>\n countMatches(candidate, LIST_NUMBER) >= countMatches(reference, LIST_NUMBER) &&\n countMatches(candidate, HEADING_LINE) >= countMatches(reference, HEADING_LINE)\n\n/** The three text steps of the cleanup; replaceable so the guard can be tested. */\nexport interface DraftCleanSteps {\n unwrap: (text: string) => string\n strip: (text: string) => string\n promote: (text: string) => string\n}\nconst DEFAULT_CLEAN_STEPS: DraftCleanSteps = {\n unwrap: unwrapCitationLinks,\n strip: stripAgentPreamble,\n promote: promoteBoldTitle,\n}\n\n/**\n * `cleanDraftMarkdown` with a safety net and a report, for storing a streamed draft. Each stage is\n * accepted only if it provably cost nothing but narration and citation markup:\n * - links removed: at least 70% of the text length remains and no heading or numbered item is lost\n * (else `raw`, the input exactly as streamed);\n * - narration removed: only a pure prefix of the text may go, and nothing structural;\n * - title and heading tidy: at least 70% of the text remains and no heading or numbered item is lost.\n * A rejected stage falls back to the previous one (`cleaned` -> `unwrapped` -> `raw`).\n */\nexport function cleanDraftWithReport(\n raw: string,\n steps: DraftCleanSteps = DEFAULT_CLEAN_STEPS\n): DraftCleanReport {\n const floor = withoutCitationMarkup(raw)\n const ratio = (t: string): number => (floor.length ? t.length / floor.length : 1)\n const unwrapped = tidy(steps.unwrap(raw))\n const stripped = tidy(steps.strip(unwrapped))\n const titled = tidy(cleanHeadings(steps.promote(stripped)))\n const changedBy: DraftCleanReport['changedBy'] = []\n if (unwrapped !== raw.trim()) changedBy.push('citations')\n if (stripped !== unwrapped) changedBy.push('preamble')\n if (titled !== stripped) changedBy.push('title')\n\n const unwrappedOk = unwrapped.length >= MIN_RATIO * floor.length && keepsStructure(unwrapped, raw)\n if (!unwrappedOk) return { text: raw, stage: 'raw', ratio: 1, changedBy, guarded: true }\n const strippedOk =\n stripped === unwrapped ||\n (isPrefixCut(unwrapped, stripped) && keepsStructure(stripped, unwrapped))\n const titledOk = titled.length >= MIN_RATIO * stripped.length && keepsStructure(titled, stripped)\n if (strippedOk && titledOk) {\n return { text: titled, stage: 'cleaned', ratio: ratio(titled), changedBy, guarded: false }\n }\n return { text: unwrapped, stage: 'unwrapped', ratio: ratio(unwrapped), changedBy, guarded: true }\n}\n\n/**\n * Everything a streamed draft needs before it is stored as the artifact's first version:\n * `unwrapCitationLinks`, `stripAgentPreamble`, `promoteBoldTitle`, clean headings, collapsed blank\n * runs, trimmed, under the guard of `cleanDraftWithReport` (use it to know which stage was kept).\n */\nexport function cleanDraftMarkdown(raw: string): string {\n return cleanDraftWithReport(raw).text\n}\n"]}
@@ -0,0 +1,61 @@
1
+ import { repairParsedStructure, repairParsedTitle, unescapeMarkdown } from './chunk-G6FHNURH.js';
2
+ import { normalizeMarkdown } from './chunk-WUTL62MC.js';
3
+
4
+ // src/artifacts/versions.ts
5
+ var VERSION_REF = /^(doc-[A-Za-z0-9]+)@v([1-9][0-9]*)$/;
6
+ function versionRef(docId, version) {
7
+ return `${docId}@v${version}`;
8
+ }
9
+ function parseVersionRef(ref) {
10
+ const match = VERSION_REF.exec(ref ?? "");
11
+ if (!match) return { docId: ref ?? "", version: null };
12
+ return { docId: match[1], version: Number(match[2]) };
13
+ }
14
+ function savedFromId(docId, entry) {
15
+ if (entry.made_from) return versionRef(docId, entry.made_from);
16
+ return entry.n > 1 ? versionRef(docId, entry.n - 1) : null;
17
+ }
18
+ function toArtifactVersions(docId, entries, currentVersion) {
19
+ if (!docId) return [];
20
+ const current = currentVersion ?? entries?.find((e) => e.is_current)?.n ?? null;
21
+ return [...entries ?? []].sort((a, b) => a.n - b.n).map((e) => ({
22
+ id: versionRef(docId, e.n),
23
+ docId,
24
+ name: e.file_name ?? "",
25
+ createdAt: e.created_at ?? "",
26
+ number: e.n,
27
+ reason: e.reason ?? "upload",
28
+ isCurrent: current != null ? e.n === current : !!e.is_current,
29
+ savedFromId: savedFromId(docId, e)
30
+ }));
31
+ }
32
+ function documentVersions(doc) {
33
+ if (!doc?.external_id) return [];
34
+ const entries = doc.versions?.length ? doc.versions : [{ n: doc.current_version ?? 1, file_name: doc.file_name, created_at: doc.created_at }];
35
+ return toArtifactVersions(doc.external_id, entries, doc.current_version ?? null);
36
+ }
37
+ function findVersion(versions, ref) {
38
+ if (!ref) return void 0;
39
+ const { docId, version } = parseVersionRef(ref);
40
+ return version == null ? versions.find((v) => v.docId === docId && v.isCurrent) : versions.find((v) => v.docId === docId && v.number === version);
41
+ }
42
+ function versionLabel(versions, ref) {
43
+ if (!ref || versions.length <= 1) return null;
44
+ const version = findVersion(versions, ref);
45
+ return version ? `v${version.number}` : null;
46
+ }
47
+ function flattenChunks(chunks, options) {
48
+ const text = (chunks ?? []).map((c) => (c.content ?? "").trim()).join("\n\n");
49
+ if (!options?.unescape) return text;
50
+ return normalizeMarkdown(
51
+ repairParsedStructure(repairParsedTitle(unescapeMarkdown(text)))
52
+ ).replace(/\n$/, "");
53
+ }
54
+ var DOC_ID = /^doc/;
55
+ function isDocumentId(id) {
56
+ return !!id && DOC_ID.test(id);
57
+ }
58
+
59
+ export { documentVersions, findVersion, flattenChunks, isDocumentId, parseVersionRef, savedFromId, toArtifactVersions, versionLabel, version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,CAAC,CAAA,KAAM,EAAE,KAAA,KAAU,KAAA,IAAS,CAAA,CAAE,MAAA,KAAW,OAAO,CAAA;AACpE;AAMO,SAAS,YAAA,CACd,UACA,GAAA,EACe;AACf,EAAA,IAAI,CAAC,GAAA,IAAO,QAAA,CAAS,MAAA,IAAU,GAAG,OAAO,IAAA;AACzC,EAAA,MAAM,OAAA,GAAU,WAAA,CAAY,QAAA,EAAU,GAAG,CAAA;AACzC,EAAA,OAAO,OAAA,GAAU,CAAA,CAAA,EAAI,OAAA,CAAQ,MAAM,CAAA,CAAA,GAAK,IAAA;AAC1C;AAWO,SAAS,aAAA,CACd,QACA,OAAA,EACQ;AACR,EAAA,MAAM,IAAA,GAAA,CAAQ,MAAA,IAAU,EAAC,EAAG,IAAI,CAAC,CAAA,KAAA,CAAO,CAAA,CAAE,OAAA,IAAW,EAAA,EAAI,IAAA,EAAM,CAAA,CAAE,KAAK,MAAM,CAAA;AAC5E,EAAA,IAAI,CAAC,OAAA,EAAS,QAAA,EAAU,OAAO,IAAA;AAE/B,EAAA,OAAO,iBAAA;AAAA,IACL,qBAAA,CAAsB,iBAAA,CAAkB,gBAAA,CAAiB,IAAI,CAAC,CAAC;AAAA,GACjE,CAAE,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACrB;AAGA,IAAM,MAAA,GAAS,MAAA;AAGR,SAAS,aAAa,EAAA,EAA6C;AACxE,EAAA,OAAO,CAAC,CAAC,EAAA,IAAM,MAAA,CAAO,KAAK,EAAE,CAAA;AAC/B","file":"chunk-HKUD2NZN.js","sourcesContent":["/**\n * Versions of a document. A document keeps ONE id for its whole life; its versions live inside it\n * (`current_version` + `versions`, numbered 1..n). A version is named by a version reference\n * `doc-…@v{n}`; a plain document id means its current version. The workspace list carries every\n * document's `versions`, and `GET /v1/document/{id}/versions` (`arbi.documents.versions`) the same\n * list on its own.\n */\n\nimport { repairParsedStructure, repairParsedTitle, unescapeMarkdown } from '../ai/stored-markdown'\nimport { normalizeMarkdown } from './normalize-markdown'\n\n/** One version entry as the API returns it (a subset of `DocVersion`). */\nexport interface DocVersionEntry {\n n: number\n file_name?: string | null\n created_at?: string | null\n reason?: string | null\n /** The version an edit started from, when it was not the previous one. */\n made_from?: number | null\n is_current?: boolean | null\n}\n\n/** The fields of a workspace document the version list needs (a subset of the API type). */\nexport interface VersionedDoc {\n external_id?: string | null\n current_version?: number | null\n versions?: readonly DocVersionEntry[] | null\n file_name?: string | null\n created_at?: string | null\n}\n\n/** One row of a version list. Matches `VersionEntry` of `@arbidocs/blocks/artifacts`. */\nexport interface ArtifactVersion {\n /** The version reference `doc-…@v{n}`: what opening or comparing this version names. */\n id: string\n /** The document (the same for every version). */\n docId: string\n /** File name as stored. */\n name: string\n /** ISO timestamp. */\n createdAt: string\n /** 1-based version number within the document. */\n number: number\n /** upload | edit | signed | sync */\n reason: string\n isCurrent: boolean\n /** The version this one was saved from (an older one than the previous version when restored). */\n savedFromId?: string | null\n}\n\nconst VERSION_REF = /^(doc-[A-Za-z0-9]+)@v([1-9][0-9]*)$/\n\n/** `doc-…@v{n}`: a reference to version `n` of a document. */\nexport function versionRef(docId: string, version: number): string {\n return `${docId}@v${version}`\n}\n\n/**\n * Split a reference into the document and the version it names. A plain document id (or anything\n * else) names no version: the document's current one.\n */\nexport function parseVersionRef(ref: string | null | undefined): {\n docId: string\n version: number | null\n} {\n const match = VERSION_REF.exec(ref ?? '')\n if (!match) return { docId: ref ?? '', version: null }\n return { docId: match[1], version: Number(match[2]) }\n}\n\n/** The version a version was saved from: `made_from`, else the one before it. */\nexport function savedFromId(docId: string, entry: DocVersionEntry): string | null {\n if (entry.made_from) return versionRef(docId, entry.made_from)\n return entry.n > 1 ? versionRef(docId, entry.n - 1) : null\n}\n\n/** A document's version entries (oldest first) as plain version rows. */\nexport function toArtifactVersions(\n docId: string | null | undefined,\n entries: readonly DocVersionEntry[] | null | undefined,\n currentVersion?: number | null\n): ArtifactVersion[] {\n if (!docId) return []\n const current = currentVersion ?? entries?.find((e) => e.is_current)?.n ?? null\n return [...(entries ?? [])]\n .sort((a, b) => a.n - b.n)\n .map((e) => ({\n id: versionRef(docId, e.n),\n docId,\n name: e.file_name ?? '',\n createdAt: e.created_at ?? '',\n number: e.n,\n reason: e.reason ?? 'upload',\n isCurrent: current != null ? e.n === current : !!e.is_current,\n savedFromId: savedFromId(docId, e),\n }))\n}\n\n/** The versions of a listed document, oldest first (`[]` when the document is not given). */\nexport function documentVersions(doc: VersionedDoc | null | undefined): ArtifactVersion[] {\n if (!doc?.external_id) return []\n const entries = doc.versions?.length\n ? doc.versions\n : [{ n: doc.current_version ?? 1, file_name: doc.file_name, created_at: doc.created_at }]\n return toArtifactVersions(doc.external_id, entries, doc.current_version ?? null)\n}\n\n/** The row `ref` names: an exact version, or (a plain document id) the current version. */\nexport function findVersion(\n versions: readonly ArtifactVersion[],\n ref: string | null | undefined\n): ArtifactVersion | undefined {\n if (!ref) return undefined\n const { docId, version } = parseVersionRef(ref)\n return version == null\n ? versions.find((v) => v.docId === docId && v.isCurrent)\n : versions.find((v) => v.docId === docId && v.number === version)\n}\n\n/**\n * \"v2\": the version number `ref` names. `null` when there is nothing to tell apart (the document\n * has a single version, or it is unknown), so unversioned documents stay unlabelled.\n */\nexport function versionLabel(\n versions: readonly ArtifactVersion[],\n ref: string | null | undefined\n): string | null {\n if (!ref || versions.length <= 1) return null\n const version = findVersion(versions, ref)\n return version ? `v${version.number}` : null\n}\n\n/**\n * Join parsed chunks into one markdown text (blank line between chunks).\n *\n * `unescape: true` for an artifact stored from markdown: the backend's parse of a `.md` escapes\n * markdown punctuation, which `unescapeMarkdown` undoes (see its rule), and mangles its title\n * (`repairParsedTitle`, `repairParsedStructure`: doubled headings, `- ` stacked on list markers,\n * one-line tables), then normalised. Leave it off for the parse\n * of a PDF or Word file.\n */\nexport function flattenChunks(\n chunks: readonly { content?: string | null }[] | null | undefined,\n options?: { unescape?: boolean }\n): string {\n const text = (chunks ?? []).map((c) => (c.content ?? '').trim()).join('\\n\\n')\n if (!options?.unescape) return text\n // Canonical spelling last, so the text an editor starts from is what a save would persist.\n return normalizeMarkdown(\n repairParsedStructure(repairParsedTitle(unescapeMarkdown(text)))\n ).replace(/\\n$/, '')\n}\n\n/** The backend's pattern for a document id. Anything else (a streamed draft's placeholder) is local. */\nconst DOC_ID = /^doc/\n\n/** Is `id` a real, saved document id? Local drafts have placeholder ids and no backend document. */\nexport function isDocumentId(id: string | null | undefined): id is string {\n return !!id && DOC_ID.test(id)\n}\n"]}
@@ -0,0 +1,173 @@
1
+ // src/ai/normalize-citations.ts
2
+ var SOURCE_RESIDUE = /\(\*+\s*(Sources?\s*:[^\n]*?)\s*\*+\)/g;
3
+ var CITE_CLOSE = /^\]\((#cite-[\w-]+)\)/;
4
+ var BLOCK_MARKER = /^(?:[-*+]|\d{1,9}[.)]|#{1,6})[ \t]+/;
5
+ var LEADING_EMPHASIS = /^(?:\*\*|__|\*|_)+/;
6
+ var TRAILING_EMPHASIS = /(\*\*|__|\*|_)(:?)$/;
7
+ function countToken(text, token) {
8
+ const double = token + token;
9
+ if (token.length === 2) return text.split(token).length - 1;
10
+ const withoutDouble = text.split(double).join("");
11
+ return withoutDouble.split(token).length - 1;
12
+ }
13
+ function emphasisTokens(run) {
14
+ const char = run[0];
15
+ const tokens = [];
16
+ let rest = run;
17
+ while (rest.length > 0) {
18
+ const size = rest.length >= 2 ? 2 : 1;
19
+ tokens.push(char.repeat(size));
20
+ rest = rest.slice(size);
21
+ }
22
+ return tokens;
23
+ }
24
+ function hoistFromLink(text, before, after) {
25
+ let body = text;
26
+ let prefix = "";
27
+ let suffix = "";
28
+ if (before.trim() === "") {
29
+ const marker = BLOCK_MARKER.exec(body);
30
+ if (marker) {
31
+ prefix += marker[0];
32
+ body = body.slice(marker[0].length);
33
+ }
34
+ }
35
+ const closer = /^(\*\*|__|\*|_)(\s+)(?=\S)/.exec(body);
36
+ if (closer && countToken(before + prefix, closer[1]) % 2 === 1) {
37
+ prefix += closer[1] + closer[2];
38
+ body = body.slice(closer[0].length);
39
+ }
40
+ const leading = LEADING_EMPHASIS.exec(body);
41
+ if (leading) {
42
+ let kept = "";
43
+ let rest = body.slice(leading[0].length);
44
+ for (const token of emphasisTokens(leading[0]).reverse()) {
45
+ if (countToken(rest, token) % 2 === 1) {
46
+ kept = token + kept;
47
+ continue;
48
+ }
49
+ if (countToken(after, token) % 2 === 1) prefix += token;
50
+ else kept = token + kept;
51
+ }
52
+ body = kept + rest;
53
+ rest = "";
54
+ }
55
+ for (const token of ["**", "__"]) {
56
+ const at = body.indexOf(token);
57
+ if (at === -1 || countToken(body, token) % 2 === 0) continue;
58
+ if (countToken(before + prefix, token) % 2 === 0) continue;
59
+ const rest = body.slice(at + token.length);
60
+ if (!/[\p{L}\p{N}]/u.test(rest)) continue;
61
+ prefix += body.slice(0, at + token.length) + rest.slice(0, rest.length - rest.trimStart().length);
62
+ body = rest.trimStart();
63
+ break;
64
+ }
65
+ const trailing = TRAILING_EMPHASIS.exec(body);
66
+ if (trailing) {
67
+ const token = trailing[1];
68
+ const inner = body.slice(0, body.length - trailing[0].length);
69
+ const openedBefore = countToken(before + prefix, token) % 2 === 1;
70
+ if (countToken(inner, token) % 2 === 0 && openedBefore) {
71
+ body = inner;
72
+ suffix = trailing[0];
73
+ }
74
+ }
75
+ if (!suffix) {
76
+ for (const token of ["**", "*"]) {
77
+ const at = lastUnmatchedOpener(body, token);
78
+ if (at > 0 && countToken(after, token) % 2 === 1) {
79
+ suffix = " " + body.slice(at);
80
+ body = body.slice(0, at).trimEnd();
81
+ break;
82
+ }
83
+ }
84
+ }
85
+ return [prefix, body, suffix];
86
+ }
87
+ function lastUnmatchedOpener(text, token) {
88
+ if (countToken(text, token) % 2 === 0) return -1;
89
+ const pattern = token === "**" ? /\*\*(?=\S)/g : /(?<!\*)\*(?![*\s])/g;
90
+ let at = -1;
91
+ for (const m of text.matchAll(pattern)) at = m.index ?? -1;
92
+ return at;
93
+ }
94
+ function findCiteLinks(line) {
95
+ const links = [];
96
+ const open = [];
97
+ for (let i = 0; i < line.length; i++) {
98
+ const c = line[i];
99
+ if (c === "[") open.push(i);
100
+ else if (c === "]") {
101
+ const opener = open.pop();
102
+ const close = CITE_CLOSE.exec(line.slice(i, i + 40));
103
+ if (opener !== void 0 && close) {
104
+ links.push({
105
+ start: opener,
106
+ end: i + close[0].length,
107
+ text: line.slice(opener + 1, i),
108
+ href: close[1]
109
+ });
110
+ i += close[0].length - 1;
111
+ }
112
+ }
113
+ }
114
+ return links.sort((x, y) => x.start - y.start);
115
+ }
116
+ function normalizeLine(line) {
117
+ if (!line.includes("](#cite-")) return line;
118
+ let out = "";
119
+ let last = 0;
120
+ for (const link of findCiteLinks(line)) {
121
+ if (link.start < last) continue;
122
+ if (link.text.includes("](#cite-")) {
123
+ out += line.slice(last, link.start) + link.text;
124
+ last = link.end;
125
+ continue;
126
+ }
127
+ const before = line.slice(0, link.start);
128
+ const after = line.slice(link.end);
129
+ const [prefix, body, suffix] = hoistFromLink(link.text, before, after);
130
+ out += line.slice(last, link.start);
131
+ out += `${prefix}[${body}](${link.href})${suffix}`;
132
+ last = link.end;
133
+ }
134
+ return out + line.slice(last);
135
+ }
136
+ function normalizeSourceResidue(line) {
137
+ return line.includes("(*") ? line.replace(SOURCE_RESIDUE, "*($1)*") : line;
138
+ }
139
+ function normalizeCitationMarkup(markdown) {
140
+ if (!markdown.includes("](#cite-") && !markdown.includes("(*")) return markdown;
141
+ let inFence = false;
142
+ return markdown.split("\n").map((line) => {
143
+ if (/^\s*(```|~~~)/.test(line)) {
144
+ inFence = !inFence;
145
+ return line;
146
+ }
147
+ return inFence ? line : normalizeSourceResidue(normalizeLine(line));
148
+ }).join("\n");
149
+ }
150
+ var OPEN_CITATION_TAIL = /\[[^\]\n]*(?:\](?:\((?:#(?:c(?:i(?:t(?:e(?:-[\w-]*)?)?)?)?)?)?)?)?$/;
151
+ function trimOpenCitation(markdown) {
152
+ return markdown.replace(OPEN_CITATION_TAIL, "");
153
+ }
154
+ function boldMarks(line) {
155
+ return (line.replace(/`[^`]*`/g, "").match(/\*\*/g) ?? []).length;
156
+ }
157
+ function closeOpenEmphasis(markdown) {
158
+ const cut = markdown.lastIndexOf("\n") + 1;
159
+ const head = markdown.slice(0, cut);
160
+ const fences = head.split("\n").filter((l) => /^\s*(```|~~~)/.test(l)).length;
161
+ let line = markdown.slice(cut);
162
+ if (fences % 2 === 1 || /^\s*(```|~~~)/.test(line)) return markdown;
163
+ line = line.replace(/(^|[\s|])\*$/, "$1");
164
+ if (boldMarks(line) % 2 === 0) return head + line;
165
+ line = line.replace(/([^*\s])\*$/, "$1");
166
+ if (boldMarks(line) % 2 === 0) return head + line;
167
+ if (/\*\*\s*$/.test(line)) return head + line.replace(/\s*\*\*\s*$/, " ");
168
+ return head + line + "**";
169
+ }
170
+
171
+ export { closeOpenEmphasis, normalizeCitationMarkup, trimOpenCitation };
172
+ //# sourceMappingURL=chunk-QRCMKEE6.js.map
173
+ //# sourceMappingURL=chunk-QRCMKEE6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ai/normalize-citations.ts"],"names":[],"mappings":";AAwBA,IAAM,cAAA,GAAiB,wCAAA;AAEvB,IAAM,UAAA,GAAa,uBAAA;AACnB,IAAM,YAAA,GAAe,qCAAA;AACrB,IAAM,gBAAA,GAAmB,oBAAA;AACzB,IAAM,iBAAA,GAAoB,qBAAA;AAG1B,SAAS,UAAA,CAAW,MAAc,KAAA,EAAuB;AACvD,EAAA,MAAM,SAAS,KAAA,GAAQ,KAAA;AACvB,EAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG,OAAO,KAAK,KAAA,CAAM,KAAK,EAAE,MAAA,GAAS,CAAA;AAC1D,EAAA,MAAM,gBAAgB,IAAA,CAAK,KAAA,CAAM,MAAM,CAAA,CAAE,KAAK,EAAE,CAAA;AAChD,EAAA,OAAO,aAAA,CAAc,KAAA,CAAM,KAAK,CAAA,CAAE,MAAA,GAAS,CAAA;AAC7C;AAGA,S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,CAAY,IAAI,CAAA,GAAI,CAAA;AACzC,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,KAAA,CAAM,CAAA,EAAG,GAAG,CAAA;AAClC,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA,CAAE,MAAA,CAAO,CAAC,CAAA,KAAM,eAAA,CAAgB,IAAA,CAAK,CAAC,CAAC,CAAA,CAAE,MAAA;AACvE,EAAA,IAAI,IAAA,GAAO,QAAA,CAAS,KAAA,CAAM,GAAG,CAAA;AAC7B,EAAA,IAAI,SAAS,CAAA,KAAM,CAAA,IAAK,gBAAgB,IAAA,CAAK,IAAI,GAAG,OAAO,QAAA;AAE3D,EAAA,IAAA,GAAO,IAAA,CAAK,OAAA,CAAQ,cAAA,EAAgB,IAAI,CAAA;AACxC,EAAA,IAAI,UAAU,IAAI,CAAA,GAAI,CAAA,KAAM,CAAA,SAAU,IAAA,GAAO,IAAA;AAE7C,EAAA,IAAA,GAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,IAAI,CAAA;AACvC,EAAA,IAAI,UAAU,IAAI,CAAA,GAAI,CAAA,KAAM,CAAA,SAAU,IAAA,GAAO,IAAA;AAC7C,EAAA,IAAI,UAAA,CAAW,KAAK,IAAI,CAAA,SAAU,IAAA,GAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,GAAG,CAAA;AACxE,EAAA,OAAO,OAAO,IAAA,GAAO,IAAA;AACvB","file":"chunk-QRCMKEE6.js","sourcesContent":["/**\n * Citation markup normaliser.\n *\n * The backend marks a cited statement as a markdown link, `[statement](#cite-N)`, and the\n * statement can include the markdown that surrounds it: a list marker, a heading marker or the\n * opener of a bold/italic span whose closer sits after the link. Inside link text those tokens\n * are not parsed as block or inline syntax, so they show literally and break lists and bold:\n *\n * [- **Claimed quantum (by Claimant)](#cite-1):** **USD 47 million**\n *\n * `normalizeCitationMarkup` hoists the leading tokens out of the link text (and a trailing\n * emphasis closer after it), so the link only wraps the words:\n *\n * - **[Claimed quantum (by Claimant)](#cite-1):** **USD 47 million**\n *\n * It is conservative: emphasis that opens and closes inside the link text is valid markdown and\n * is left alone, an opener is only hoisted when its closer follows on the same line, and fenced\n * code blocks are never touched. The result is idempotent.\n *\n * It also tidies the residue the model leaves when it cites in prose as well: a literal\n * `(*Source: Award.pdf, p. 12*)` shows its asterisks, because `(*` does not open emphasis. It\n * becomes the italic note `*(Source: Award.pdf, p. 12)*`.\n */\n\nconst SOURCE_RESIDUE = /\\(\\*+\\s*(Sources?\\s*:[^\\n]*?)\\s*\\*+\\)/g\n\nconst CITE_CLOSE = /^\\]\\((#cite-[\\w-]+)\\)/\nconst BLOCK_MARKER = /^(?:[-*+]|\\d{1,9}[.)]|#{1,6})[ \\t]+/\nconst LEADING_EMPHASIS = /^(?:\\*\\*|__|\\*|_)+/\nconst TRAILING_EMPHASIS = /(\\*\\*|__|\\*|_)(:?)$/\n\n/** Occurrences of `token` in `text`; a single `*` is counted outside any `**` pair. */\nfunction countToken(text: string, token: string): number {\n const double = token + token\n if (token.length === 2) return text.split(token).length - 1\n const withoutDouble = text.split(double).join('')\n return withoutDouble.split(token).length - 1\n}\n\n/** Split a run of emphasis characters (`***`, `**`, `*`...) into its parser-level tokens. */\nfunction emphasisTokens(run: string): string[] {\n const char = run[0]\n const tokens: string[] = []\n let rest = run\n while (rest.length > 0) {\n const size = rest.length >= 2 ? 2 : 1\n tokens.push(char.repeat(size))\n rest = rest.slice(size)\n }\n return tokens\n}\n\nfunction hoistFromLink(text: string, before: string, after: string): [string, string, string] {\n let body = text\n let prefix = ''\n let suffix = ''\n\n if (before.trim() === '') {\n const marker = BLOCK_MARKER.exec(body)\n if (marker) {\n prefix += marker[0]\n body = body.slice(marker[0].length)\n }\n }\n\n // The link opened inside an emphasis span: `*Sources:[* Letter](#cite-2)`. A leading token that\n // the text before the link left open, and that is followed by a space, is the span's CLOSER (an\n // opener cannot precede a space), so it moves out in front of the link with its space.\n const closer = /^(\\*\\*|__|\\*|_)(\\s+)(?=\\S)/.exec(body)\n if (closer && countToken(before + prefix, closer[1]) % 2 === 1) {\n prefix += closer[1] + closer[2]\n body = body.slice(closer[0].length)\n }\n\n const leading = LEADING_EMPHASIS.exec(body)\n if (leading) {\n let kept = ''\n let rest = body.slice(leading[0].length)\n for (const token of emphasisTokens(leading[0]).reverse()) {\n // Balanced inside the link text: valid as written.\n if (countToken(rest, token) % 2 === 1) {\n kept = token + kept\n continue\n }\n // Unmatched here: hoist only if the line closes it after the link.\n if (countToken(after, token) % 2 === 1) prefix += token\n else kept = token + kept\n }\n body = kept + rest\n rest = ''\n }\n\n // A span opened before the link and closed inside it (`**Spence v. [Costa Rica** arbitration.]`)\n // cannot close across the link boundary: move the words up to the closer out of the link.\n for (const token of ['**', '__']) {\n const at = body.indexOf(token)\n if (at === -1 || countToken(body, token) % 2 === 0) continue\n if (countToken(before + prefix, token) % 2 === 0) continue\n const rest = body.slice(at + token.length)\n if (!/[\\p{L}\\p{N}]/u.test(rest)) continue\n prefix +=\n body.slice(0, at + token.length) + rest.slice(0, rest.length - rest.trimStart().length)\n body = rest.trimStart()\n break\n }\n\n const trailing = TRAILING_EMPHASIS.exec(body)\n if (trailing) {\n const token = trailing[1]\n const inner = body.slice(0, body.length - trailing[0].length)\n const openedBefore = countToken(before + prefix, token) % 2 === 1\n if (countToken(inner, token) % 2 === 0 && openedBefore) {\n body = inner\n suffix = trailing[0]\n }\n }\n\n // The link ends inside an emphasis span that closes after it: `*(Source](#cite-1): a.md)*`. The\n // unmatched opener and the words after it leave the link, so the span opens and closes in the\n // same text again: `[words](#cite-1) *(Source: a.md)*`.\n if (!suffix) {\n for (const token of ['**', '*']) {\n const at = lastUnmatchedOpener(body, token)\n if (at > 0 && countToken(after, token) % 2 === 1) {\n suffix = ' ' + body.slice(at)\n body = body.slice(0, at).trimEnd()\n break\n }\n }\n }\n\n return [prefix, body, suffix]\n}\n\n/** Index of the last `token` in `text` that opens emphasis (followed by a non-space) and has no closer. */\nfunction lastUnmatchedOpener(text: string, token: string): number {\n if (countToken(text, token) % 2 === 0) return -1\n const pattern = token === '**' ? /\\*\\*(?=\\S)/g : /(?<!\\*)\\*(?![*\\s])/g\n let at = -1\n for (const m of text.matchAll(pattern)) at = m.index ?? -1\n return at\n}\n\ninterface CiteLink {\n start: number\n end: number\n text: string\n href: string\n}\n\n/**\n * The `[text](#cite-N)` links of a line. The text may hold brackets of its own\n * (`[2. **[PLACEHOLDER]** names the claimant.](#cite-3)`), so a regex cannot find the opener: a\n * stack of `[` is scanned, and a `](#cite-N)` takes the nearest open one.\n */\nfunction findCiteLinks(line: string): CiteLink[] {\n const links: CiteLink[] = []\n const open: number[] = []\n for (let i = 0; i < line.length; i++) {\n const c = line[i]\n if (c === '[') open.push(i)\n else if (c === ']') {\n const opener = open.pop()\n const close = CITE_CLOSE.exec(line.slice(i, i + 40))\n if (opener !== undefined && close) {\n links.push({\n start: opener,\n end: i + close[0].length,\n text: line.slice(opener + 1, i),\n href: close[1],\n })\n i += close[0].length - 1\n }\n }\n }\n return links.sort((x, y) => x.start - y.start)\n}\n\nfunction normalizeLine(line: string): string {\n if (!line.includes('](#cite-')) return line\n let out = ''\n let last = 0\n for (const link of findCiteLinks(line)) {\n // A link inside another link's text is part of that text.\n if (link.start < last) continue\n // Markdown links do not nest: a citation that wraps another citation (`[a [9](#cite-9)](#cite-10)`)\n // keeps the words and the inner mark, and the outer wrapper is dropped.\n if (link.text.includes('](#cite-')) {\n out += line.slice(last, link.start) + link.text\n last = link.end\n continue\n }\n const before = line.slice(0, link.start)\n const after = line.slice(link.end)\n const [prefix, body, suffix] = hoistFromLink(link.text, before, after)\n out += line.slice(last, link.start)\n out += `${prefix}[${body}](${link.href})${suffix}`\n last = link.end\n }\n return out + line.slice(last)\n}\n\nfunction normalizeSourceResidue(line: string): string {\n return line.includes('(*') ? line.replace(SOURCE_RESIDUE, '*($1)*') : line\n}\n\nexport function normalizeCitationMarkup(markdown: string): string {\n if (!markdown.includes('](#cite-') && !markdown.includes('(*')) return markdown\n let inFence = false\n return markdown\n .split('\\n')\n .map((line) => {\n if (/^\\s*(```|~~~)/.test(line)) {\n inFence = !inFence\n return line\n }\n return inFence ? line : normalizeSourceResidue(normalizeLine(line))\n })\n .join('\\n')\n}\n\n/** A trailing, still-open `[words](#cite-N` marker (or an unclosed `[words`) on the last line. */\nconst OPEN_CITATION_TAIL = /\\[[^\\]\\n]*(?:\\](?:\\((?:#(?:c(?:i(?:t(?:e(?:-[\\w-]*)?)?)?)?)?)?)?)?$/\n\n/**\n * Drops an unfinished citation marker from the end of text that is still streaming (or was\n * stopped mid-marker), so `[Change of control](#cite-` never shows as raw markup: the words appear\n * once the marker is complete. Complete markers and everything else are left alone.\n */\nexport function trimOpenCitation(markdown: string): string {\n return markdown.replace(OPEN_CITATION_TAIL, '')\n}\n\n/** `**` pairs outside inline code in a line. */\nfunction boldMarks(line: string): number {\n return (line.replace(/`[^`]*`/g, '').match(/\\*\\*/g) ?? []).length\n}\n\n/**\n * Makes the tail of text that is still streaming (or was stopped) render cleanly: a `**` opened\n * in the last line and not yet closed (`| Valuation | **[USD 6.2 million](#cite-2)`) would show as\n * literal asterisks until its closer arrives, because an unclosed emphasis is not emphasis. The\n * open bold is closed at the end of the line, or removed when it has no text yet (`| **`, or a\n * half-typed closer `**USD 6*`). Text with balanced emphasis, and every line but the last, is\n * left alone. Apply after `trimOpenCitation`.\n */\nexport function closeOpenEmphasis(markdown: string): string {\n const cut = markdown.lastIndexOf('\\n') + 1\n const head = markdown.slice(0, cut)\n const fences = head.split('\\n').filter((l) => /^\\s*(```|~~~)/.test(l)).length\n let line = markdown.slice(cut)\n if (fences % 2 === 1 || /^\\s*(```|~~~)/.test(line)) return markdown\n // A half-typed opener: the first `*` of `**` after a space or a cell border.\n line = line.replace(/(^|[\\s|])\\*$/, '$1')\n if (boldMarks(line) % 2 === 0) return head + line\n // A half-typed closer: `**USD 6*` -> the second asterisk has not arrived.\n line = line.replace(/([^*\\s])\\*$/, '$1')\n if (boldMarks(line) % 2 === 0) return head + line\n if (/\\*\\*\\s*$/.test(line)) return head + line.replace(/\\s*\\*\\*\\s*$/, ' ')\n return head + line + '**'\n}\n"]}