dislop 0.9.0 → 1.0.1

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 (124) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/.codex-plugin/plugin.json +7 -8
  4. package/.cursor-plugin/plugin.json +2 -3
  5. package/.pre-commit-hooks.yaml +5 -12
  6. package/PRODUCT.md +19 -57
  7. package/README.md +360 -252
  8. package/README.zh-CN.md +390 -240
  9. package/action.yml +30 -39
  10. package/bin/dislop-mcp.mjs +3 -4
  11. package/bin/dislop.mjs +4 -4582
  12. package/gemini-extension.json +2 -2
  13. package/llms-install.md +68 -0
  14. package/package.json +17 -55
  15. package/packs/common/artifact-qa/pack.json +5 -0
  16. package/packs/common/artifact-qa/prompts/rules.md +11 -0
  17. package/packs/common/artifact-qa/scripts/index.mjs +173 -0
  18. package/packs/common/slide-deck/pack.json +6 -0
  19. package/packs/common/slide-deck/prompts/rules.md +11 -0
  20. package/packs/common/slide-deck/scripts/index.mjs +62 -0
  21. package/packs/common/web-ui/pack.json +6 -0
  22. package/packs/common/web-ui/prompts/rules.md +11 -0
  23. package/packs/common/web-ui/scripts/index.mjs +80 -0
  24. package/packs/en/artifact-qa/pack.json +6 -0
  25. package/packs/en/artifact-qa/prompts/rules.md +14 -0
  26. package/packs/en/artifact-qa/scripts/index.mjs +90 -0
  27. package/packs/en/prose/pack.json +7 -0
  28. package/packs/en/prose/prompts/rules.md +26 -0
  29. package/packs/en/prose/scripts/index.mjs +290 -0
  30. package/packs/en/slide-deck/pack.json +7 -0
  31. package/packs/en/slide-deck/prompts/rules.md +17 -0
  32. package/packs/en/slide-deck/scripts/index.mjs +81 -0
  33. package/packs/en/web-ui/pack.json +7 -0
  34. package/packs/en/web-ui/prompts/rules.md +20 -0
  35. package/packs/en/web-ui/scripts/index.mjs +103 -0
  36. package/packs/zh/artifact-qa/pack.json +6 -0
  37. package/packs/zh/artifact-qa/prompts/rules.md +14 -0
  38. package/packs/zh/artifact-qa/scripts/index.mjs +89 -0
  39. package/packs/zh/prose/pack.json +7 -0
  40. package/packs/zh/prose/prompts/rules.md +26 -0
  41. package/packs/zh/prose/scripts/index.mjs +305 -0
  42. package/packs/zh/slide-deck/pack.json +7 -0
  43. package/packs/zh/slide-deck/prompts/rules.md +17 -0
  44. package/packs/zh/slide-deck/scripts/index.mjs +75 -0
  45. package/packs/zh/web-ui/pack.json +7 -0
  46. package/packs/zh/web-ui/prompts/rules.md +20 -0
  47. package/packs/zh/web-ui/scripts/index.mjs +98 -0
  48. package/plugin.json +5 -6
  49. package/server.json +8 -2
  50. package/skills/deslop-docs/SKILL.md +10 -8
  51. package/skills/deslop-slides-docx/SKILL.md +7 -8
  52. package/skills/deslop-verify/SKILL.md +7 -8
  53. package/skills/deslop-web-ui/SKILL.md +7 -8
  54. package/skills/dislop/SKILL.md +16 -28
  55. package/skills/dislop/references/essay.md +1 -1
  56. package/skills/dislop/references/essay.zh-CN.md +1 -1
  57. package/skills/dislop/references/office.md +1 -1
  58. package/skills/dislop/references/office.zh-CN.md +1 -1
  59. package/skills/dislop/references/web-ui.md +1 -1
  60. package/skills/dislop/references/web-ui.zh-CN.md +1 -1
  61. package/skills/dislop/references/work-docs.md +1 -1
  62. package/skills/dislop/references/work-docs.zh-CN.md +1 -1
  63. package/src/cli-main.mjs +210 -0
  64. package/src/commands/check-fix.mjs +169 -0
  65. package/src/commands/doctor.mjs +110 -0
  66. package/src/commands/init.mjs +49 -0
  67. package/src/commands/login.mjs +82 -0
  68. package/src/commands/model.mjs +130 -0
  69. package/src/commands/packs.mjs +44 -0
  70. package/src/commands/verify.mjs +133 -0
  71. package/src/commands/voice.mjs +84 -0
  72. package/src/kernel/config.mjs +232 -0
  73. package/src/kernel/document-model.mjs +1412 -0
  74. package/src/kernel/fact-gate.mjs +615 -0
  75. package/src/kernel/file-discovery.mjs +139 -0
  76. package/src/{binary-node.mjs → kernel/ooxml-binary.mjs} +532 -893
  77. package/src/kernel/pack-loader.mjs +715 -0
  78. package/src/kernel/patcher.mjs +341 -0
  79. package/src/kernel/pipeline.mjs +267 -0
  80. package/src/kernel/prompt-assembler.mjs +307 -0
  81. package/src/kernel/voice-profile.mjs +177 -0
  82. package/src/mcp/stdio-server.mjs +372 -0
  83. package/src/runners/auto-fix.mjs +59 -0
  84. package/src/runners/interactive-tty.mjs +461 -0
  85. package/src/runners/reporters.mjs +256 -0
  86. package/src/runtime/chunker.mjs +87 -0
  87. package/src/runtime/json-extract.mjs +144 -0
  88. package/src/runtime/privacy-gate.mjs +97 -0
  89. package/src/runtime/providers/anthropic.mjs +65 -0
  90. package/src/runtime/providers/cloud.mjs +136 -0
  91. package/src/runtime/providers/gemini.mjs +91 -0
  92. package/src/runtime/providers/local-model.mjs +139 -0
  93. package/src/runtime/providers/openai-compat.mjs +130 -0
  94. package/src/runtime/router.mjs +315 -0
  95. package/src/sdk/index.mjs +137 -0
  96. package/models/manifest.json +0 -90
  97. package/models/pocket-slop-v1.json +0 -1
  98. package/packs/business-brief/pack.json +0 -937
  99. package/packs/core/pack.json +0 -209
  100. package/packs/deck-and-ui/pack.json +0 -539
  101. package/packs/engineering-spec/pack.json +0 -144
  102. package/packs/executive-deck/pack.json +0 -98
  103. package/packs/literary-essay/pack.json +0 -344
  104. package/packs/regulated-comms/pack.json +0 -99
  105. package/patterns/ai-tic-rubric.json +0 -252
  106. package/patterns/banks/composite-fusion.json +0 -48
  107. package/patterns/banks/discourse-rhythm.json +0 -95
  108. package/patterns/banks/lexical-signals.json +0 -92
  109. package/patterns/banks/syntactic-frames.json +0 -52
  110. package/patterns/banks/visual-deck.json +0 -44
  111. package/patterns/dimensions/artifacts.json +0 -121
  112. package/patterns/dimensions/discourse.json +0 -438
  113. package/patterns/dimensions/lexical.json +0 -198
  114. package/patterns/dimensions/rhythm.json +0 -258
  115. package/patterns/dimensions/syntactic.json +0 -285
  116. package/patterns/dimensions/visual-and-deck.json +0 -530
  117. package/patterns/taxonomy.json +0 -112
  118. package/src/core.mjs +0 -5497
  119. package/src/dislop/review-picker.vim +0 -114
  120. package/src/local-model.mjs +0 -997
  121. package/src/pattern-engine.mjs +0 -1003
  122. package/src/pocket-model.mjs +0 -729
  123. package/src/review-apply.mjs +0 -151
  124. package/src/review-client.mjs +0 -1073
@@ -0,0 +1,1412 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { inspectImageBuffer, inspectPdfBuffer, readZipArchive } from "./ooxml-binary.mjs";
4
+
5
+ const EXT_TO_FORMAT = Object.freeze({
6
+ ".md": "md",
7
+ ".markdown": "md",
8
+ ".mdx": "mdx",
9
+ ".txt": "txt",
10
+ ".text": "txt",
11
+ ".html": "html",
12
+ ".htm": "html",
13
+ ".css": "css",
14
+ ".jsx": "jsx",
15
+ ".tsx": "tsx",
16
+ ".svg": "svg",
17
+ ".docx": "docx",
18
+ ".pptx": "pptx",
19
+ ".pdf": "pdf",
20
+ ".png": "png",
21
+ ".jpg": "jpg",
22
+ ".jpeg": "jpeg",
23
+ ".webp": "webp",
24
+ ".gif": "gif",
25
+ });
26
+
27
+ const FORMAT_TO_MODALITY = Object.freeze({
28
+ md: "prose",
29
+ mdx: "prose",
30
+ txt: "prose",
31
+ html: "markup",
32
+ jsx: "markup",
33
+ tsx: "markup",
34
+ css: "stylesheet",
35
+ svg: "vector",
36
+ docx: "document",
37
+ pptx: "presentation",
38
+ pdf: "presentation",
39
+ png: "image",
40
+ jpg: "image",
41
+ jpeg: "image",
42
+ webp: "image",
43
+ gif: "image",
44
+ });
45
+
46
+ const ABBREVIATIONS = new Set([
47
+ "e.g",
48
+ "i.e",
49
+ "vs",
50
+ "mr",
51
+ "mrs",
52
+ "ms",
53
+ "dr",
54
+ "prof",
55
+ "sr",
56
+ "jr",
57
+ "st",
58
+ "fig",
59
+ "eq",
60
+ "no",
61
+ "vol",
62
+ "inc",
63
+ "ltd",
64
+ "co",
65
+ "corp",
66
+ "etc",
67
+ "approx",
68
+ "est",
69
+ ]);
70
+
71
+ export function detectFormatFromPath(filePath) {
72
+ const ext = path.extname(String(filePath || "")).toLowerCase();
73
+ return EXT_TO_FORMAT[ext] || null;
74
+ }
75
+
76
+ export function detectDocumentLanguage(text) {
77
+ const sample = String(text || "");
78
+ const cjkMatches = sample.match(/[\u4e00-\u9fff]/g);
79
+ const cjkCount = cjkMatches ? cjkMatches.length : 0;
80
+ const nonWs = sample.replace(/\s+/g, "").length;
81
+ if (cjkCount >= 6 || (nonWs > 0 && cjkCount / nonWs >= 0.12)) {
82
+ return "zh";
83
+ }
84
+ return "en";
85
+ }
86
+
87
+ export function buildLineTable(text) {
88
+ const starts = [0];
89
+ for (let i = 0; i < text.length; i += 1) {
90
+ if (text.charCodeAt(i) === 10) starts.push(i + 1);
91
+ }
92
+ return starts;
93
+ }
94
+
95
+ export function offsetToLine(lineStarts, offset) {
96
+ let lo = 0;
97
+ let hi = lineStarts.length - 1;
98
+ while (lo <= hi) {
99
+ const mid = (lo + hi) >> 1;
100
+ if (lineStarts[mid] <= offset) lo = mid + 1;
101
+ else hi = mid - 1;
102
+ }
103
+ return Math.max(0, hi) + 1;
104
+ }
105
+
106
+ export function decodeXmlEntities(str) {
107
+ return String(str || "")
108
+ .replace(/&lt;/g, "<")
109
+ .replace(/&gt;/g, ">")
110
+ .replace(/&quot;/g, '"')
111
+ .replace(/&apos;/g, "'")
112
+ .replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))
113
+ .replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(parseInt(dec, 10)))
114
+ .replace(/&amp;/g, "&");
115
+ }
116
+
117
+ /**
118
+ * Split a prose slice into sentence spans `[{ relStart, relEnd, text }]` while protecting
119
+ * inline code spans, Markdown links, decimals, and common English abbreviations.
120
+ */
121
+ export function splitParagraphIntoSentences(slice) {
122
+ const len = slice.length;
123
+ const protectedMask = new Uint8Array(len);
124
+
125
+ // Protect inline code `...`
126
+ const codeRe = /`+[^`]+`+/g;
127
+ let m;
128
+ while ((m = codeRe.exec(slice)) !== null) {
129
+ protectedMask.fill(1, m.index, m.index + m[0].length);
130
+ }
131
+
132
+ // Protect Markdown links [label](url) and raw URLs
133
+ const linkRe = /\[[^\]]*\]\([^)\n]*\)|https?:\/\/[^\s)>\]]+/g;
134
+ while ((m = linkRe.exec(slice)) !== null) {
135
+ protectedMask.fill(1, m.index, m.index + m[0].length);
136
+ }
137
+
138
+ const spans = [];
139
+ let sentStart = 0;
140
+
141
+ const pushSpan = (rawStart, rawEnd) => {
142
+ let s = rawStart;
143
+ let e = rawEnd;
144
+ while (s < e && /\s/.test(slice[s])) s += 1;
145
+ while (e > s && /\s/.test(slice[e - 1])) e -= 1;
146
+ if (e > s) {
147
+ spans.push({
148
+ relStart: s,
149
+ relEnd: e,
150
+ text: slice.slice(s, e),
151
+ });
152
+ }
153
+ };
154
+
155
+ for (let i = 0; i < len; i += 1) {
156
+ if (protectedMask[i]) continue;
157
+ const ch = slice[i];
158
+
159
+ // CJK sentence-ending punctuation
160
+ if (ch === "\u3002" || ch === "\uff01" || ch === "\uff1f") {
161
+ if (ch === "\uff01") {
162
+ const leadInZh = slice.slice(sentStart, i).trim();
163
+ if (/^(?:\u597d\u7684|\u5f53\u7136|\u5f53\u7136\u53ef\u4ee5|\u6ca1\u95ee\u9898)$/.test(leadInZh) && i + 1 < len) {
164
+ continue;
165
+ }
166
+ }
167
+ let endIdx = i + 1;
168
+ while (endIdx < len && /[\u201d\u2019\u300d\u300f\uff09\u300b"'\]\uff09]/.test(slice[endIdx])) endIdx += 1;
169
+ pushSpan(sentStart, endIdx);
170
+ sentStart = endIdx;
171
+ i = endIdx - 1;
172
+ continue;
173
+ }
174
+
175
+ // ASCII sentence-ending punctuation
176
+ if (ch === "." || ch === "!" || ch === "?") {
177
+ if (ch === "!") {
178
+ const leadIn = slice.slice(sentStart, i).trim();
179
+ if (
180
+ /^(?:Certainly|Sure|Of course|Absolutely|Great|Awesome|Great question|Happy to help|Glad to help)$/i.test(
181
+ leadIn,
182
+ ) &&
183
+ i + 1 < len &&
184
+ /\s/.test(slice[i + 1])
185
+ ) {
186
+ continue;
187
+ }
188
+ }
189
+ if (ch === ".") {
190
+ // Ellipsis ...
191
+ if (slice[i + 1] === "." || (i > 0 && slice[i - 1] === ".")) continue;
192
+ // Decimal number 3.14 or version v1.2
193
+ if (i > 0 && /\d/.test(slice[i - 1]) && i + 1 < len && /\d/.test(slice[i + 1])) continue;
194
+ // Check preceding word for abbreviations
195
+ const before = slice.slice(Math.max(0, i - 12), i);
196
+ const wordMatch = before.match(/([A-Za-z]+(?:\.[A-Za-z]+)*)$/);
197
+ if (wordMatch) {
198
+ const word = wordMatch[1].toLowerCase();
199
+ if (ABBREVIATIONS.has(word) || (word.length === 1 && /[A-Z]/.test(wordMatch[1]))) {
200
+ continue;
201
+ }
202
+ }
203
+ }
204
+
205
+ let endIdx = i + 1;
206
+ while (endIdx < len && /["')\]”’]/.test(slice[endIdx])) endIdx += 1;
207
+ if (endIdx < len && !/\s/.test(slice[endIdx])) continue;
208
+
209
+ pushSpan(sentStart, endIdx);
210
+ sentStart = endIdx;
211
+ i = endIdx - 1;
212
+ }
213
+ }
214
+
215
+ if (sentStart < len) {
216
+ pushSpan(sentStart, len);
217
+ }
218
+ return spans;
219
+ }
220
+
221
+ function detectRawMarkdownLeaksInRun(text, segmentId, line, locator) {
222
+ const leaks = [];
223
+ const rules = [
224
+ { pattern: "bold-asterisks", re: /\*\*[^*\n]{2,120}\*\*/g },
225
+ { pattern: "atx-heading", re: /(?:^|\n)\s*#{2,6}\s+\S[^\n]{1,120}/g },
226
+ { pattern: "markdown-link", re: /\[[^\]\n]{1,80}\]\(https?:\/\/[^)\s]+\)/g },
227
+ {
228
+ pattern: "code-fence",
229
+ re: /(?:^|\n)[ \t]*```[a-zA-Z0-9_+-]*[ \t]*(?:\r?\n|$)|```[a-zA-Z0-9_+-]*\r?\n[\s\S]*?```/g,
230
+ },
231
+ ];
232
+ for (const { pattern, re } of rules) {
233
+ let m;
234
+ while ((m = re.exec(text)) !== null) {
235
+ leaks.push({
236
+ pattern,
237
+ text: m[0],
238
+ segmentId,
239
+ ...(line !== undefined ? { line } : {}),
240
+ ...(locator ? { locator } : {}),
241
+ });
242
+ }
243
+ }
244
+ return leaks;
245
+ }
246
+
247
+ function applySuppressionDirectives(rawText, masked) {
248
+ let m;
249
+ const blockDirectiveRe =
250
+ /<!--\s*dislop-(?:ignore|quote|disable)-start\s*-->[\s\S]*?<!--\s*dislop-(?:ignore|quote|disable)-end\s*-->/gi;
251
+ while ((m = blockDirectiveRe.exec(rawText)) !== null) {
252
+ masked.fill(1, m.index, m.index + m[0].length);
253
+ }
254
+ const nextLineDirectiveRe =
255
+ /<!--\s*dislop-(?:ignore|disable)(?:-next-line)?\s*-->[ \t]*\r?\n[^\r\n]*/gi;
256
+ while ((m = nextLineDirectiveRe.exec(rawText)) !== null) {
257
+ masked.fill(1, m.index, m.index + m[0].length);
258
+ }
259
+ }
260
+
261
+ function splitMarkdownTableRow(rowText, rowStart) {
262
+ const cells = [];
263
+ let inCode = false;
264
+ let cellStart = 0;
265
+ const len = rowText.length;
266
+ for (let i = 0; i < len; i += 1) {
267
+ const ch = rowText[i];
268
+ if (ch === "`") {
269
+ inCode = !inCode;
270
+ continue;
271
+ }
272
+ if (ch === "\\" && i + 1 < len) {
273
+ i += 1;
274
+ continue;
275
+ }
276
+ if (!inCode && ch === "|") {
277
+ const rawCell = rowText.slice(cellStart, i);
278
+ const lead = rawCell.match(/^\s*/)[0].length;
279
+ const trail = rawCell.match(/\s*$/)[0].length;
280
+ const s = rowStart + cellStart + lead;
281
+ const e = rowStart + i - trail;
282
+ if (e > s) cells.push({ start: s, end: e, text: rowText.slice(cellStart + lead, i - trail) });
283
+ cellStart = i + 1;
284
+ }
285
+ }
286
+ if (cellStart < len) {
287
+ const rawCell = rowText.slice(cellStart);
288
+ const lead = rawCell.match(/^\s*/)[0].length;
289
+ const trail = rawCell.match(/\s*$/)[0].length;
290
+ const s = rowStart + cellStart + lead;
291
+ const e = rowStart + len - trail;
292
+ if (e > s) cells.push({ start: s, end: e, text: rowText.slice(cellStart + lead, len - trail) });
293
+ }
294
+ return cells;
295
+ }
296
+
297
+ function parseMarkdownOrText(rawText, filePath, format) {
298
+ const lineStarts = buildLineTable(rawText);
299
+ const len = rawText.length;
300
+ const masked = new Uint8Array(len);
301
+ const codeBlocks = [];
302
+ const links = [];
303
+ const rawFormattingLeaks = [];
304
+
305
+ // 1. Mask YAML frontmatter at byte 0
306
+ if (format === "md" || format === "mdx") {
307
+ const fmMatch = rawText.match(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/);
308
+ if (fmMatch) {
309
+ masked.fill(1, 0, fmMatch[0].length);
310
+ }
311
+ }
312
+
313
+ // 2. Mask fenced code blocks ``` or ~~~ and HTML/suppression comments
314
+ if (format === "md" || format === "mdx") {
315
+ const fenceRe = /(^[ \t]*(`{3,}|~{3,})([^\r\n]*)\r?\n)([\s\S]*?)(^[ \t]*\2[ \t]*(?:\r?\n|$))/gm;
316
+ let m;
317
+ while ((m = fenceRe.exec(rawText)) !== null) {
318
+ masked.fill(1, m.index, m.index + m[0].length);
319
+ codeBlocks.push({
320
+ lang: m[3].trim(),
321
+ content: m[4],
322
+ line: offsetToLine(lineStarts, m.index),
323
+ });
324
+ }
325
+
326
+ applySuppressionDirectives(rawText, masked);
327
+
328
+ const commentRe = /<!--[\s\S]*?-->/g;
329
+ while ((m = commentRe.exec(rawText)) !== null) {
330
+ masked.fill(1, m.index, m.index + m[0].length);
331
+ }
332
+ }
333
+
334
+ // 3. Mask MDX top-level import/export statements
335
+ if (format === "mdx") {
336
+ const mdxImportRe = /^(?:import|export)\s+[^\r\n]+(?:\r?\n|$)/gm;
337
+ let m;
338
+ while ((m = mdxImportRe.exec(rawText)) !== null) {
339
+ if (!masked[m.index]) masked.fill(1, m.index, m.index + m[0].length);
340
+ }
341
+ }
342
+
343
+ // 4. Scan lines into logical paragraphs
344
+ const lines = [];
345
+ let cursor = 0;
346
+ while (cursor <= len) {
347
+ const nl = rawText.indexOf("\n", cursor);
348
+ const lineEnd = nl === -1 ? len : nl;
349
+ const contentEnd = lineEnd > cursor && rawText[lineEnd - 1] === "\r" ? lineEnd - 1 : lineEnd;
350
+ lines.push({
351
+ start: cursor,
352
+ end: contentEnd,
353
+ rawEnd: nl === -1 ? len : nl + 1,
354
+ lineNumber: lines.length + 1,
355
+ text: rawText.slice(cursor, contentEnd),
356
+ });
357
+ if (nl === -1) break;
358
+ cursor = nl + 1;
359
+ }
360
+
361
+ const rawBlocks = [];
362
+ let currentLines = [];
363
+
364
+ const flushCurrent = () => {
365
+ if (currentLines.length === 0) return;
366
+ rawBlocks.push({ kind: "prose", lines: currentLines });
367
+ currentLines = [];
368
+ };
369
+
370
+ for (const ln of lines) {
371
+ if (ln.start < len && masked[ln.start]) {
372
+ flushCurrent();
373
+ continue;
374
+ }
375
+ const trimmed = ln.text.trim();
376
+ if (!trimmed) {
377
+ flushCurrent();
378
+ continue;
379
+ }
380
+ // Mask Markdown blockquotes (> ...) so quoted external copy never triggers author-prose warnings
381
+ if ((format === "md" || format === "mdx") && /^\s*>/.test(ln.text)) {
382
+ flushCurrent();
383
+ masked.fill(1, ln.start, ln.rawEnd);
384
+ continue;
385
+ }
386
+ // Table separator rows |---|---|
387
+ if ((format === "md" || format === "mdx") && /^\|?(?:\s*:?-+:?\s*\|)+\s*:?-+:?\s*\|?$/.test(trimmed)) {
388
+ flushCurrent();
389
+ continue;
390
+ }
391
+ // Pipe table rows | a | b |
392
+ if ((format === "md" || format === "mdx") && /^\s*\|.*\|\s*$/.test(ln.text)) {
393
+ flushCurrent();
394
+ rawBlocks.push({ kind: "table-row", lines: [ln] });
395
+ continue;
396
+ }
397
+ // Horizontal rules
398
+ if ((format === "md" || format === "mdx") && /^(?:---+|\*\*\*+|___+)$/.test(trimmed)) {
399
+ flushCurrent();
400
+ continue;
401
+ }
402
+ // Headings & list items each form clean standalone addressable blocks
403
+ if ((format === "md" || format === "mdx") && /^\s*#{1,6}\s+/.test(ln.text)) {
404
+ flushCurrent();
405
+ rawBlocks.push({ kind: "heading", lines: [ln] });
406
+ continue;
407
+ }
408
+ if ((format === "md" || format === "mdx") && /^\s*(?:[-*+]|\d+\.|[\u2460-\u2473])\s+/.test(ln.text)) {
409
+ flushCurrent();
410
+ rawBlocks.push({ kind: "list-item", lines: [ln] });
411
+ continue;
412
+ }
413
+ currentLines.push(ln);
414
+ }
415
+ flushCurrent();
416
+
417
+ const segments = [];
418
+ const paragraphs = [];
419
+ let pCounter = 0;
420
+
421
+ for (const blockEntry of rawBlocks) {
422
+ const blk = blockEntry.lines;
423
+ const blkStart = blk[0].start;
424
+ const blkEnd = blk[blk.length - 1].end;
425
+
426
+ if (blockEntry.kind === "table-row") {
427
+ const cells = splitMarkdownTableRow(blk[0].text, blkStart);
428
+ for (const cell of cells) {
429
+ pCounter += 1;
430
+ const paragraphId = `P${pCounter}`;
431
+ const sentenceSpans = splitParagraphIntoSentences(cell.text);
432
+ if (sentenceSpans.length === 0) continue;
433
+ const segIds = [];
434
+ let sCounter = 0;
435
+ for (const sp of sentenceSpans) {
436
+ sCounter += 1;
437
+ const absStart = cell.start + sp.relStart;
438
+ const absEnd = cell.start + sp.relEnd;
439
+ const id = `${paragraphId}-S${sCounter}`;
440
+ segIds.push(id);
441
+ segments.push({
442
+ id,
443
+ paragraphId,
444
+ blockKind: "table-cell",
445
+ line: offsetToLine(lineStarts, absStart),
446
+ text: sp.text,
447
+ locator: {
448
+ kind: "text-span",
449
+ start: absStart,
450
+ end: absEnd,
451
+ lineStart: blkStart,
452
+ lineEnd: blk[0].rawEnd,
453
+ },
454
+ });
455
+ }
456
+ paragraphs.push({
457
+ id: paragraphId,
458
+ blockKind: "table-cell",
459
+ line: offsetToLine(lineStarts, cell.start),
460
+ text: cell.text,
461
+ segmentIds: segIds,
462
+ locator: {
463
+ kind: "text-span",
464
+ start: cell.start,
465
+ end: cell.end,
466
+ lineStart: blkStart,
467
+ lineEnd: blk[0].rawEnd,
468
+ },
469
+ });
470
+ }
471
+ continue;
472
+ }
473
+
474
+ let bodyStart = blkStart;
475
+ const firstText = blk[0].text;
476
+ let blockKind = blockEntry.kind === "prose" ? "paragraph" : blockEntry.kind;
477
+
478
+ if (format === "md" || format === "mdx") {
479
+ const headingPrefix = firstText.match(/^(\s*#{1,6}\s+)/);
480
+ const listPrefix = !headingPrefix
481
+ ? firstText.match(/^(\s*(?:[-*+]|\d+\.|[\u2460-\u2473])\s+(?:\[[ xX]\]\s+)?)/)
482
+ : null;
483
+ const prefix = headingPrefix?.[1] || listPrefix?.[1] || "";
484
+ bodyStart += prefix.length;
485
+ }
486
+
487
+ const slice = rawText.slice(bodyStart, blkEnd);
488
+ if (!slice.trim()) continue;
489
+
490
+ pCounter += 1;
491
+ const paragraphId = `P${pCounter}`;
492
+ const sentenceSpans = splitParagraphIntoSentences(slice);
493
+ if (sentenceSpans.length === 0) continue;
494
+
495
+ const segIds = [];
496
+ let sCounter = 0;
497
+ for (const sp of sentenceSpans) {
498
+ sCounter += 1;
499
+ const absStart = bodyStart + sp.relStart;
500
+ const absEnd = bodyStart + sp.relEnd;
501
+ const segLine = offsetToLine(lineStarts, absStart);
502
+ const id = `${paragraphId}-S${sCounter}`;
503
+ segIds.push(id);
504
+ segments.push({
505
+ id,
506
+ paragraphId,
507
+ blockKind,
508
+ line: segLine,
509
+ text: sp.text,
510
+ locator: {
511
+ kind: "text-span",
512
+ start: absStart,
513
+ end: absEnd,
514
+ lineStart: blkStart,
515
+ lineEnd: blk[blk.length - 1].rawEnd,
516
+ },
517
+ });
518
+ }
519
+
520
+ paragraphs.push({
521
+ id: paragraphId,
522
+ blockKind,
523
+ line: offsetToLine(lineStarts, bodyStart),
524
+ text: slice,
525
+ segmentIds: segIds,
526
+ locator: {
527
+ kind: "text-span",
528
+ start: bodyStart,
529
+ end: blkEnd,
530
+ lineStart: blkStart,
531
+ lineEnd: blk[blk.length - 1].rawEnd,
532
+ },
533
+ });
534
+ }
535
+
536
+ // 5. Extract Markdown links outside masked regions & inline code
537
+ if (format === "md" || format === "mdx") {
538
+ const inlineCodeMask = new Uint8Array(masked);
539
+ const icRe = /`+[^`]+`+/g;
540
+ let im;
541
+ while ((im = icRe.exec(rawText)) !== null) {
542
+ inlineCodeMask.fill(1, im.index, im.index + im[0].length);
543
+ }
544
+
545
+ const mdLinkRe = /!?\[([^\]\n]*)\]\((<[^>\n]*>|[^)\n]*)\)/g;
546
+ let lm;
547
+ while ((lm = mdLinkRe.exec(rawText)) !== null) {
548
+ if (inlineCodeMask[lm.index]) continue;
549
+ let rawUrl = lm[2].trim().replace(/\s+["'][^"']*["']$/, "");
550
+ const angleMatch = rawUrl.match(/^<([\s\S]*)>$/);
551
+ if (angleMatch) rawUrl = angleMatch[1].trim();
552
+ const line = offsetToLine(lineStarts, lm.index);
553
+ const seg = segments.find(
554
+ (s) => s.locator.start <= lm.index && s.locator.end >= lm.index + lm[0].length,
555
+ );
556
+ links.push({
557
+ url: rawUrl,
558
+ label: lm[1],
559
+ raw: lm[0],
560
+ ...(seg ? { segmentId: seg.id } : {}),
561
+ line,
562
+ locator: { kind: "text-span", start: lm.index, end: lm.index + lm[0].length },
563
+ });
564
+ }
565
+ }
566
+
567
+ const proseCorpus = segments.map((s) => s.text).join("\n") || rawText;
568
+ return {
569
+ filePath,
570
+ format,
571
+ modality: FORMAT_TO_MODALITY[format] || "prose",
572
+ language: detectDocumentLanguage(proseCorpus),
573
+ segments,
574
+ paragraphs,
575
+ artifacts: {
576
+ links,
577
+ codeBlocks,
578
+ rawFormattingLeaks,
579
+ },
580
+ };
581
+ }
582
+
583
+ function parseLengthPx(rawVal) {
584
+ if (!rawVal) return null;
585
+ const m = String(rawVal).trim().match(/^(\d+(?:\.\d+)?)(?:px)?$/i);
586
+ return m ? Number(m[1]) : null;
587
+ }
588
+
589
+ function collectUiSignals(rawSource, format, scriptText = "") {
590
+ const purplePinkGradients = [];
591
+ const glowBlobs = [];
592
+ const pillBadges = [];
593
+ const disabledButtonsWithoutTitle = [];
594
+ let missingSvgViewBox = false;
595
+
596
+ const gradRe =
597
+ /(?:from-(?:purple|indigo|violet|fuchsia)-\d{2,3}[^\n"']{0,60}(?:via|to)-(?:pink|purple|fuchsia|indigo|cyan)-\d{2,3}|linear-gradient\([^)]*(?:#(?:8b5cf6|a855f7|ec4899|6366f1|d946ef)|purple|violet|magenta)[^)]*\))/gi;
598
+ let m;
599
+ while ((m = gradRe.exec(rawSource)) !== null) {
600
+ purplePinkGradients.push({ text: m[0], offset: m.index });
601
+ }
602
+
603
+ // SVG purple-pink gradients
604
+ const svgGradRe = /<(?:linearGradient|radialGradient)\b[\s\S]*?<\/(?:linearGradient|radialGradient)>/gi;
605
+ while ((m = svgGradRe.exec(rawSource)) !== null) {
606
+ const block = m[0];
607
+ const hasPurpleStop = /#(?:8b5cf6|a855f7|6366f1|7c3aed)\b/i.test(block);
608
+ const hasPinkOrCyanStop = /#(?:ec4899|d946ef|f43f5e|06b6d4)\b/i.test(block);
609
+ if (hasPurpleStop && hasPinkOrCyanStop) {
610
+ purplePinkGradients.push({ text: block.slice(0, 120), offset: m.index });
611
+ }
612
+ }
613
+
614
+ const blobRe = /\bblur-3xl\b[^\n"']{0,80}\b(?:opacity-(?:20|30|40)|animate-pulse|rounded-full)\b/gi;
615
+ while ((m = blobRe.exec(rawSource)) !== null) {
616
+ glowBlobs.push({ text: m[0], offset: m.index });
617
+ }
618
+
619
+ const cssBlurRe = /filter\s*:\s*blur\(\s*(?:[4-9]\d|\d{3,})px\s*\)/gi;
620
+ while ((m = cssBlurRe.exec(rawSource)) !== null) {
621
+ glowBlobs.push({ text: m[0], offset: m.index });
622
+ }
623
+
624
+ const svgBlurRe = /<feGaussianBlur\b[^>]*\bstdDeviation\s*=\s*["']?(?:1[2-9]|[2-9]\d|\d{3,})\b[^>]*>/gi;
625
+ while ((m = svgBlurRe.exec(rawSource)) !== null) {
626
+ glowBlobs.push({ text: m[0], offset: m.index });
627
+ }
628
+
629
+ const pillRe =
630
+ /<(?:span|div)\b([^>]*class(?:Name)?=["'][^"']*\brounded-full\b[^"']*["'][^>]*)>([^<]{1,40})<\/(?:span|div)>/gi;
631
+ while ((m = pillRe.exec(rawSource)) !== null) {
632
+ const classMatch = m[1].match(/\bclass(?:Name)?=["']([^"']*)["']/i);
633
+ const cls = classMatch ? classMatch[1] : "";
634
+ const inner = m[2].trim();
635
+ const isSquareAvatar =
636
+ /\bw-(\d+(?:\.\d+)?)\b[^\n"']*\bh-\1\b/.test(cls) ||
637
+ /\bh-(\d+(?:\.\d+)?)\b[^\n"']*\bw-\1\b/.test(cls) ||
638
+ /\bsize-\d+\b/.test(cls);
639
+ if (!inner || isSquareAvatar || /^[A-Z]{1,2}$/.test(inner)) {
640
+ continue;
641
+ }
642
+ pillBadges.push({ text: m[0], offset: m.index });
643
+ }
644
+
645
+ const btnRe = /<button\b([^>]*\bdisabled\b[^>]*)>([\s\S]*?)<\/button>/gi;
646
+ while ((m = btnRe.exec(rawSource)) !== null) {
647
+ const attrs = m[1];
648
+ if (/\b(?:title|aria-label|aria-describedby)=/i.test(attrs)) continue;
649
+ const innerText = m[2].replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
650
+ const isLoadingLabel =
651
+ /(?:\.\.\.|\u2026|\b(?:loading|pending|preparing|initializing|saving|submitting|connecting|please wait)\b|\u51c6\u5907\u4e2d|\u52a0\u8f7d\u4e2d|\u5904\u7406\u4e2d|\u751f\u6210\u4e2d|\u8bf7\u7a0d\u5019)/i.test(
652
+ innerText,
653
+ );
654
+ if (isLoadingLabel) continue;
655
+ const idMatch = attrs.match(/\bid\s*=\s*(?:"([A-Za-z0-9_-]+)"|'([A-Za-z0-9_-]+)')/i);
656
+ const btnId = idMatch ? idMatch[1] || idMatch[2] : "";
657
+ if (btnId && scriptText) {
658
+ const escId = btnId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
659
+ if (new RegExp(`\\b${escId}\\b`).test(scriptText)) continue;
660
+ }
661
+ disabledButtonsWithoutTitle.push({ text: m[0], offset: m.index });
662
+ }
663
+
664
+ if (format === "svg" && /<svg\b/i.test(rawSource)) {
665
+ const svgOpen = rawSource.match(/<svg\b[^>]*>/i);
666
+ if (svgOpen && !/\bviewBox\s*=/i.test(svgOpen[0])) {
667
+ const wMatch = svgOpen[0].match(/\bwidth\s*=\s*["']([^"']+)["']/i);
668
+ const hMatch = svgOpen[0].match(/\bheight\s*=\s*["']([^"']+)["']/i);
669
+ const wPx = parseLengthPx(wMatch?.[1]);
670
+ const hPx = parseLengthPx(hMatch?.[1]);
671
+ const isSmallIcon = wPx !== null && hPx !== null && wPx <= 48 && hPx <= 48;
672
+ if (!isSmallIcon) {
673
+ missingSvgViewBox = true;
674
+ }
675
+ }
676
+ }
677
+
678
+ const backdropBlurMatches = rawSource.match(
679
+ /\bbackdrop-blur(?:-(?:sm|md|lg|xl|2xl|3xl))?\b|backdrop-filter\s*:\s*blur\(/gi,
680
+ );
681
+ const backdropBlurCount = backdropBlurMatches ? backdropBlurMatches.length : 0;
682
+
683
+ return {
684
+ purplePinkGradients,
685
+ glowBlobs,
686
+ pillBadges,
687
+ disabledButtonsWithoutTitle,
688
+ missingSvgViewBox,
689
+ backdropBlurCount,
690
+ };
691
+ }
692
+
693
+ const HTML_VOID_TAGS = new Set([
694
+ "area",
695
+ "base",
696
+ "br",
697
+ "col",
698
+ "embed",
699
+ "hr",
700
+ "img",
701
+ "input",
702
+ "link",
703
+ "meta",
704
+ "param",
705
+ "source",
706
+ "track",
707
+ "wbr",
708
+ ]);
709
+
710
+ const PROSE_ELEMENT_TAGS = new Set([
711
+ "p",
712
+ "h1",
713
+ "h2",
714
+ "h3",
715
+ "h4",
716
+ "h5",
717
+ "h6",
718
+ "li",
719
+ "figcaption",
720
+ "td",
721
+ "th",
722
+ "dt",
723
+ "dd",
724
+ "summary",
725
+ "blockquote",
726
+ "button",
727
+ "label",
728
+ "text",
729
+ "div",
730
+ "span",
731
+ "a",
732
+ ]);
733
+
734
+ function maskElementsByAttr(rawText, masked, attrRe) {
735
+ const tagRe = /<(\/?)([a-zA-Z][a-zA-Z0-9:-]*)([^>]*)>/g;
736
+ const ignoreStack = [];
737
+ let m;
738
+ while ((m = tagRe.exec(rawText)) !== null) {
739
+ const isClose = m[1] === "/";
740
+ const tag = m[2].toLowerCase();
741
+ const attrs = m[3] || "";
742
+ const selfClose = /\/\s*$/.test(attrs) || HTML_VOID_TAGS.has(tag);
743
+
744
+ if (!isClose) {
745
+ if (selfClose) {
746
+ if (attrRe.test(attrs)) masked.fill(1, m.index, m.index + m[0].length);
747
+ } else {
748
+ ignoreStack.push({ tag, start: m.index, ignored: attrRe.test(attrs) });
749
+ }
750
+ } else {
751
+ for (let i = ignoreStack.length - 1; i >= 0; i -= 1) {
752
+ if (ignoreStack[i].tag === tag) {
753
+ const popped = ignoreStack.splice(i, ignoreStack.length - i)[0];
754
+ if (popped.ignored) {
755
+ masked.fill(1, popped.start, m.index + m[0].length);
756
+ }
757
+ break;
758
+ }
759
+ }
760
+ }
761
+ }
762
+ }
763
+
764
+ function collectHtmlProseBlocks(rawText, proseMask) {
765
+ const tagRe = /<(\/?)([a-zA-Z][a-zA-Z0-9:-]*)([^>]*)>/g;
766
+ const stack = [];
767
+ const candidates = [];
768
+ let m;
769
+
770
+ while ((m = tagRe.exec(rawText)) !== null) {
771
+ if (proseMask[m.index]) continue;
772
+ const isClose = m[1] === "/";
773
+ const tag = m[2].toLowerCase();
774
+ const attrs = m[3] || "";
775
+ const selfClose = /\/\s*$/.test(attrs) || HTML_VOID_TAGS.has(tag);
776
+
777
+ if (!isClose) {
778
+ if (!selfClose) {
779
+ stack.push({ tag, openStart: m.index, innerStart: m.index + m[0].length });
780
+ }
781
+ continue;
782
+ }
783
+
784
+ for (let i = stack.length - 1; i >= 0; i -= 1) {
785
+ if (stack[i].tag === tag) {
786
+ const popped = stack.splice(i, stack.length - i)[0];
787
+ if (!PROSE_ELEMENT_TAGS.has(tag)) break;
788
+ const innerEnd = m.index;
789
+ const rawInner = rawText.slice(popped.innerStart, innerEnd);
790
+ if (!rawInner.trim()) break;
791
+
792
+ const hasNestedBlock =
793
+ /<(?:div|section|article|main|header|footer|nav|aside|ul|ol|dl|table|thead|tbody|tr|p|h[1-6]|li|blockquote|pre|figure|figcaption|form|svg)\b/i.test(
794
+ rawInner,
795
+ );
796
+ const hasNestedInlineContainer = /<(?:td|th|dt|dd|summary|button|label|text|span|a)\b/i.test(rawInner);
797
+
798
+ if (tag === "div" && (hasNestedBlock || hasNestedInlineContainer)) break;
799
+ if ((tag === "span" || tag === "a") && (hasNestedBlock || hasNestedInlineContainer)) break;
800
+ if (hasNestedBlock) break;
801
+
802
+ candidates.push({
803
+ tag,
804
+ openStart: popped.openStart,
805
+ innerStart: popped.innerStart,
806
+ innerEnd,
807
+ rawInner,
808
+ });
809
+ break;
810
+ }
811
+ }
812
+ }
813
+
814
+ candidates.sort((a, b) => a.innerStart - b.innerStart);
815
+ const filtered = [];
816
+ for (const cand of candidates) {
817
+ if (cand.tag === "span" || cand.tag === "a") {
818
+ const insideEmitted = filtered.some(
819
+ (p) => cand.openStart >= p.innerStart && cand.innerEnd <= p.innerEnd,
820
+ );
821
+ if (insideEmitted) continue;
822
+ }
823
+ filtered.push(cand);
824
+ }
825
+ return filtered;
826
+ }
827
+
828
+ function normalizeHtmlInnerToPieces(rawInner, innerOffset) {
829
+ // Split on <br> tags into logical line pieces while keeping rough source offsets
830
+ const brSplitRe = /<br\s*\/?>/gi;
831
+ const parts = [];
832
+ let lastIdx = 0;
833
+ let bm;
834
+ while ((bm = brSplitRe.exec(rawInner)) !== null) {
835
+ parts.push({ raw: rawInner.slice(lastIdx, bm.index), offset: innerOffset + lastIdx });
836
+ lastIdx = bm.index + bm[0].length;
837
+ }
838
+ parts.push({ raw: rawInner.slice(lastIdx), offset: innerOffset + lastIdx });
839
+
840
+ const out = [];
841
+ for (const part of parts) {
842
+ const raw = part.raw;
843
+ if (!raw.trim()) continue;
844
+ // Convert inline <code>...</code> to backtick spans so maskInlineCode protects them
845
+ const withInlineCode = raw
846
+ .replace(/<code\b[^>]*>([\s\S]*?)<\/code>/gi, (_, body) => `\`${decodeXmlEntities(body).trim()}\``)
847
+ .replace(/<\/?[a-zA-Z][a-zA-Z0-9:-]*(?:\s+[^>]*)?>/g, "")
848
+ .replace(/(?<!\{)\{[^{}\n]{1,120}\}(?!\})/g, "");
849
+ const decoded = decodeXmlEntities(withInlineCode);
850
+ if (!decoded.trim()) continue;
851
+ out.push({
852
+ rawPart: raw,
853
+ partOffset: part.offset,
854
+ text: decoded,
855
+ exactOneToOne: raw === decoded,
856
+ });
857
+ }
858
+ return out;
859
+ }
860
+
861
+ function parseMarkupOrStylesheet(rawText, filePath, format) {
862
+ const lineStarts = buildLineTable(rawText);
863
+ const links = [];
864
+ const codeBlocks = [];
865
+ const rawFormattingLeaks = [];
866
+ const segments = [];
867
+ const paragraphs = [];
868
+
869
+ if (format === "css") {
870
+ const uiSignals = collectUiSignals(rawText, format);
871
+ return {
872
+ filePath,
873
+ format,
874
+ modality: "stylesheet",
875
+ language: "en",
876
+ segments,
877
+ paragraphs,
878
+ artifacts: {
879
+ links,
880
+ codeBlocks,
881
+ rawFormattingLeaks,
882
+ uiSignals,
883
+ },
884
+ };
885
+ }
886
+
887
+ const len = rawText.length;
888
+ const nonUiMask = new Uint8Array(len);
889
+
890
+ const maskRegexOn = (targetMask, re) => {
891
+ let m;
892
+ while ((m = re.exec(rawText)) !== null) {
893
+ targetMask.fill(1, m.index, m.index + m[0].length);
894
+ }
895
+ };
896
+
897
+ const scriptBodies = [];
898
+ for (const sm of rawText.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)) {
899
+ if (sm[1]) scriptBodies.push(sm[1]);
900
+ }
901
+ const scriptText = scriptBodies.join("\n");
902
+
903
+ applySuppressionDirectives(rawText, nonUiMask);
904
+ maskRegexOn(nonUiMask, /<!--[\s\S]*?-->/g);
905
+ maskRegexOn(nonUiMask, /\{\/\*[\s\S]*?\*\/\}/g);
906
+ maskRegexOn(nonUiMask, /<script\b[^>]*>[\s\S]*?<\/script>/gi);
907
+ maskRegexOn(nonUiMask, /<pre\b[^>]*>[\s\S]*?<\/pre>/gi);
908
+ maskRegexOn(nonUiMask, /<code\b[^>]*>[\s\S]*?<\/code>/gi);
909
+ maskRegexOn(nonUiMask, /<samp\b[^>]*>[\s\S]*?<\/samp>/gi);
910
+ maskRegexOn(nonUiMask, /<kbd\b[^>]*>[\s\S]*?<\/kbd>/gi);
911
+ maskRegexOn(nonUiMask, /<del\b[^>]*>[\s\S]*?<\/del>/gi);
912
+ maskRegexOn(nonUiMask, /<template\b[^>]*>[\s\S]*?<\/template>/gi);
913
+ maskRegexOn(nonUiMask, /<noscript\b[^>]*>[\s\S]*?<\/noscript>/gi);
914
+ maskElementsByAttr(rawText, nonUiMask, /\bdata-dislop-ignore\b/i);
915
+
916
+ const maskedUiSource = Array.from(rawText)
917
+ .map((ch, idx) => (nonUiMask[idx] ? (ch === "\n" ? "\n" : " ") : ch))
918
+ .join("");
919
+ const uiSignals = collectUiSignals(maskedUiSource, format, scriptText);
920
+
921
+ const proseMask = new Uint8Array(nonUiMask);
922
+ maskRegexOn(proseMask, /<style\b[^>]*>[\s\S]*?<\/style>/gi);
923
+
924
+ // Extract <a ... href="..."> links outside masked regions
925
+ const anchorRe = /<a\b([^>]*)>([\s\S]*?)<\/a>/gi;
926
+ let am;
927
+ while ((am = anchorRe.exec(rawText)) !== null) {
928
+ if (nonUiMask[am.index]) continue;
929
+ const hrefMatch = am[1].match(/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
930
+ if (hrefMatch) {
931
+ const url = hrefMatch[1] ?? hrefMatch[2] ?? "";
932
+ links.push({
933
+ url,
934
+ label: am[2].replace(/<[^>]+>/g, "").trim(),
935
+ raw: am[0],
936
+ line: offsetToLine(lineStarts, am.index),
937
+ locator: { kind: "html-span", start: am.index, end: am.index + am[0].length },
938
+ });
939
+ }
940
+ }
941
+
942
+ const blocks = collectHtmlProseBlocks(rawText, proseMask);
943
+ let bCounter = 0;
944
+
945
+ for (const blk of blocks) {
946
+ const pieces = normalizeHtmlInnerToPieces(blk.rawInner, blk.innerStart);
947
+ if (pieces.length === 0) continue;
948
+
949
+ let blockKind = "paragraph";
950
+ if (/^h[1-6]$/.test(blk.tag)) blockKind = "heading";
951
+ else if (blk.tag === "li") blockKind = "list-item";
952
+ else if (blk.tag === "td" || blk.tag === "th") blockKind = "table-cell";
953
+ else if (blk.tag === "button" || blk.tag === "label" || blk.tag === "a") blockKind = "ui-control";
954
+
955
+ for (const piece of pieces) {
956
+ const cleanSlice = piece.text;
957
+ bCounter += 1;
958
+ const blockId = `B${bCounter}`;
959
+ const sentenceSpans = splitParagraphIntoSentences(cleanSlice);
960
+ if (sentenceSpans.length === 0) continue;
961
+
962
+ const segIds = [];
963
+ let sCounter = 0;
964
+ for (const sp of sentenceSpans) {
965
+ sCounter += 1;
966
+ let absStart = piece.partOffset + sp.relStart;
967
+ let absEnd = piece.partOffset + sp.relEnd;
968
+ let locatorKind = "html-readonly";
969
+
970
+ if (piece.exactOneToOne && rawText.slice(absStart, absEnd) === sp.text) {
971
+ locatorKind = "html-span";
972
+ } else {
973
+ const idx = piece.rawPart.indexOf(sp.text);
974
+ if (idx !== -1 && piece.rawPart.indexOf(sp.text, idx + 1) === -1) {
975
+ absStart = piece.partOffset + idx;
976
+ absEnd = absStart + sp.text.length;
977
+ locatorKind = "html-span";
978
+ }
979
+ }
980
+
981
+ const line = offsetToLine(lineStarts, absStart);
982
+ const id = `${blockId}-S${sCounter}`;
983
+ const locator = { kind: locatorKind, start: absStart, end: absEnd };
984
+ segIds.push(id);
985
+ segments.push({
986
+ id,
987
+ paragraphId: blockId,
988
+ blockKind,
989
+ line,
990
+ text: sp.text,
991
+ locator,
992
+ });
993
+
994
+ const maskedForLeakCheck = sp.text.replace(/`+[^`]+`+/g, (cm) => " ".repeat(cm.length));
995
+ const leaks = detectRawMarkdownLeaksInRun(maskedForLeakCheck, id, line, locator);
996
+ rawFormattingLeaks.push(...leaks);
997
+ }
998
+
999
+ paragraphs.push({
1000
+ id: blockId,
1001
+ blockKind,
1002
+ line: offsetToLine(lineStarts, piece.partOffset),
1003
+ text: cleanSlice.trim(),
1004
+ segmentIds: segIds,
1005
+ locator: {
1006
+ kind: piece.exactOneToOne ? "html-span" : "html-readonly",
1007
+ start: piece.partOffset,
1008
+ end: piece.partOffset + piece.rawPart.length,
1009
+ },
1010
+ });
1011
+ }
1012
+ }
1013
+
1014
+ const proseCorpus = segments.map((s) => s.text).join("\n");
1015
+ return {
1016
+ filePath,
1017
+ format,
1018
+ modality: FORMAT_TO_MODALITY[format] || "markup",
1019
+ language: proseCorpus ? detectDocumentLanguage(proseCorpus) : "en",
1020
+ segments,
1021
+ paragraphs,
1022
+ artifacts: {
1023
+ links,
1024
+ codeBlocks,
1025
+ rawFormattingLeaks,
1026
+ uiSignals,
1027
+ },
1028
+ };
1029
+ }
1030
+
1031
+ function parseOoxmlParagraphsFromXml(xml, entryName, nsPrefix, bCounterStart) {
1032
+ const pTagRe = nsPrefix === "w" ? /<w:p\b[^>]*>[\s\S]*?<\/w:p>/g : /<a:p\b[^>]*>[\s\S]*?<\/a:p>/g;
1033
+ const tTagRe = nsPrefix === "w" ? /<w:t(?:\s+[^>]*)?>([\s\S]*?)<\/w:t>/g : /<a:t(?:\s+[^>]*)?>([\s\S]*?)<\/a:t>/g;
1034
+
1035
+ const segments = [];
1036
+ const paragraphs = [];
1037
+ const leaks = [];
1038
+ let bCounter = bCounterStart;
1039
+ let pOrd = 0;
1040
+ let pm;
1041
+
1042
+ while ((pm = pTagRe.exec(xml)) !== null) {
1043
+ const pXml = pm[0];
1044
+ const pIdx = pOrd;
1045
+ pOrd += 1;
1046
+
1047
+ const runTexts = [];
1048
+ let tm;
1049
+ tTagRe.lastIndex = 0;
1050
+ while ((tm = tTagRe.exec(pXml)) !== null) {
1051
+ runTexts.push(decodeXmlEntities(tm[1]));
1052
+ }
1053
+ const joined = runTexts.join("");
1054
+ if (!joined.trim()) continue;
1055
+
1056
+ bCounter += 1;
1057
+ const blockId = `B${bCounter}`;
1058
+ const sentenceSpans = splitParagraphIntoSentences(joined);
1059
+ if (sentenceSpans.length === 0) continue;
1060
+
1061
+ const segIds = [];
1062
+ let sCounter = 0;
1063
+ for (const sp of sentenceSpans) {
1064
+ sCounter += 1;
1065
+ const id = `${blockId}-S${sCounter}`;
1066
+ const locator = {
1067
+ kind: "ooxml-span",
1068
+ entryName,
1069
+ nsPrefix,
1070
+ paragraphOrd: pIdx,
1071
+ charStart: sp.relStart,
1072
+ charEnd: sp.relEnd,
1073
+ };
1074
+ segIds.push(id);
1075
+ segments.push({
1076
+ id,
1077
+ paragraphId: blockId,
1078
+ text: sp.text,
1079
+ locator,
1080
+ });
1081
+ leaks.push(...detectRawMarkdownLeaksInRun(sp.text, id, undefined, locator));
1082
+ }
1083
+
1084
+ paragraphs.push({
1085
+ id: blockId,
1086
+ text: joined,
1087
+ segmentIds: segIds,
1088
+ locator: {
1089
+ kind: "ooxml-span",
1090
+ entryName,
1091
+ nsPrefix,
1092
+ paragraphOrd: pIdx,
1093
+ charStart: 0,
1094
+ charEnd: joined.length,
1095
+ },
1096
+ });
1097
+ }
1098
+
1099
+ return { segments, paragraphs, leaks, nextBCounter: bCounter };
1100
+ }
1101
+
1102
+ function parseRelsHyperlinks(relsXml) {
1103
+ const links = [];
1104
+ if (!relsXml) return links;
1105
+ const relRe = /<Relationship\b([^>]*?)\/?>/gi;
1106
+ let m;
1107
+ while ((m = relRe.exec(relsXml)) !== null) {
1108
+ const attrs = m[1];
1109
+ if (!/Type="[^"]*\/hyperlink"/i.test(attrs)) continue;
1110
+ const targetMatch = attrs.match(/\bTarget="([^"]*)"/i);
1111
+ if (targetMatch) {
1112
+ const url = decodeXmlEntities(targetMatch[1]);
1113
+ links.push({ url, raw: m[0] });
1114
+ }
1115
+ }
1116
+ return links;
1117
+ }
1118
+
1119
+ function resolvePptxSlideOrder(xmlEntries) {
1120
+ const presXml = xmlEntries["ppt/presentation.xml"];
1121
+ const presRels = xmlEntries["ppt/_rels/presentation.xml.rels"];
1122
+ if (presXml && presRels) {
1123
+ const ridToTarget = new Map();
1124
+ const relRe = /<Relationship\b([^>]*?)\/?>/gi;
1125
+ let m;
1126
+ while ((m = relRe.exec(presRels)) !== null) {
1127
+ const idMatch = m[1].match(/\bId="([^"]+)"/i);
1128
+ const targetMatch = m[1].match(/\bTarget="([^"]+)"/i);
1129
+ if (idMatch && targetMatch) {
1130
+ const clean = targetMatch[1].replace(/^\/+/, "");
1131
+ const full = clean.startsWith("ppt/") ? clean : `ppt/${clean}`;
1132
+ ridToTarget.set(idMatch[1], full);
1133
+ }
1134
+ }
1135
+ const ordered = [];
1136
+ const sldIdRe = /<p:sldId\b[^>]*\br:id="([^"]+)"/gi;
1137
+ while ((m = sldIdRe.exec(presXml)) !== null) {
1138
+ const target = ridToTarget.get(m[1]);
1139
+ if (target && xmlEntries[target]) ordered.push(target);
1140
+ }
1141
+ if (ordered.length > 0) return ordered;
1142
+ }
1143
+
1144
+ return Object.keys(xmlEntries)
1145
+ .filter((k) => /^ppt\/slides\/slide\d+\.xml$/i.test(k))
1146
+ .sort((a, b) => {
1147
+ const na = parseInt(a.match(/(\d+)\.xml$/)[1], 10);
1148
+ const nb = parseInt(b.match(/(\d+)\.xml$/)[1], 10);
1149
+ return na - nb;
1150
+ });
1151
+ }
1152
+
1153
+ function parseOoxmlDocument(buffer, filePath, format) {
1154
+ const { xmlEntries } = readZipArchive(buffer);
1155
+ const segments = [];
1156
+ const paragraphs = [];
1157
+ const rawFormattingLeaks = [];
1158
+ const links = [];
1159
+ let bCounter = 0;
1160
+
1161
+ if (format === "docx") {
1162
+ const docXml = xmlEntries["word/document.xml"];
1163
+ if (!docXml) {
1164
+ throw new Error("Invalid .docx archive: missing word/document.xml");
1165
+ }
1166
+ const res = parseOoxmlParagraphsFromXml(docXml, "word/document.xml", "w", bCounter);
1167
+ segments.push(...res.segments);
1168
+ paragraphs.push(...res.paragraphs);
1169
+ rawFormattingLeaks.push(...res.leaks);
1170
+ links.push(...parseRelsHyperlinks(xmlEntries["word/_rels/document.xml.rels"]));
1171
+
1172
+ const corpus = segments.map((s) => s.text).join("\n");
1173
+ return {
1174
+ filePath,
1175
+ format: "docx",
1176
+ modality: "document",
1177
+ language: detectDocumentLanguage(corpus),
1178
+ segments,
1179
+ paragraphs,
1180
+ artifacts: {
1181
+ links,
1182
+ codeBlocks: [],
1183
+ rawFormattingLeaks,
1184
+ },
1185
+ };
1186
+ }
1187
+
1188
+ // format === "pptx"
1189
+ const slideNames = resolvePptxSlideOrder(xmlEntries);
1190
+ if (slideNames.length === 0) {
1191
+ throw new Error("Invalid .pptx archive: no slide XML entries found");
1192
+ }
1193
+
1194
+ const slideMetrics = [];
1195
+ let visibleSlideCount = 0;
1196
+ for (let idx = 0; idx < slideNames.length; idx += 1) {
1197
+ const entryName = slideNames[idx];
1198
+ const xml = xmlEntries[entryName];
1199
+ if (/<p:sld\b[^>]*\bshow\s*=\s*["'](?:0|false)["']/i.test(xml)) {
1200
+ continue;
1201
+ }
1202
+ visibleSlideCount += 1;
1203
+ const startSegIdx = segments.length;
1204
+ const res = parseOoxmlParagraphsFromXml(xml, entryName, "a", bCounter);
1205
+ bCounter = res.nextBCounter;
1206
+ segments.push(...res.segments);
1207
+ paragraphs.push(...res.paragraphs);
1208
+ rawFormattingLeaks.push(...res.leaks);
1209
+
1210
+ const slideBasename = path.basename(entryName);
1211
+ const relsName = `ppt/slides/_rels/${slideBasename}.rels`;
1212
+ links.push(...parseRelsHyperlinks(xmlEntries[relsName]));
1213
+
1214
+ const slideText = res.paragraphs.map((p) => p.text).join(" ");
1215
+ const words = slideText.trim() ? slideText.trim().split(/\s+/).length : 0;
1216
+ const cjkCount = (slideText.match(/[\u4e00-\u9fff]/g) || []).length;
1217
+ const bulletMatches = xml.match(/<a:bu(?:Char|AutoNum)\b/g);
1218
+ const bulletCount = bulletMatches ? bulletMatches.length : 0;
1219
+ const autofitMatch = xml.match(/<a:normAutofit\b[^>]*\bfontScale="(\d+)"/i);
1220
+ const autofitFontScale = autofitMatch ? parseInt(autofitMatch[1], 10) / 1000 : 100;
1221
+ const firstSegmentId = segments[startSegIdx]?.id || null;
1222
+
1223
+ slideMetrics.push({
1224
+ index: visibleSlideCount,
1225
+ entryName,
1226
+ firstSegmentId,
1227
+ title: res.paragraphs[0]?.text || "",
1228
+ wordCount: words,
1229
+ cjkCount,
1230
+ bulletCount,
1231
+ autofitFontScale,
1232
+ });
1233
+ }
1234
+
1235
+ const corpus = segments.map((s) => s.text).join("\n");
1236
+ return {
1237
+ filePath,
1238
+ format: "pptx",
1239
+ modality: "presentation",
1240
+ language: detectDocumentLanguage(corpus),
1241
+ segments,
1242
+ paragraphs,
1243
+ artifacts: {
1244
+ links,
1245
+ codeBlocks: [],
1246
+ rawFormattingLeaks,
1247
+ deckSignals: {
1248
+ slideCount: visibleSlideCount,
1249
+ slides: slideMetrics,
1250
+ },
1251
+ },
1252
+ };
1253
+ }
1254
+
1255
+ /**
1256
+ * Parse any supported file on disk into a unified `DocumentModel`.
1257
+ */
1258
+ export function parseDocumentFile(filePath, explicitFormat = null) {
1259
+ const format = explicitFormat || detectFormatFromPath(filePath);
1260
+ if (!format) {
1261
+ throw new Error(`Unsupported file extension for '${filePath}'`);
1262
+ }
1263
+
1264
+ if (format === "docx" || format === "pptx") {
1265
+ const buf = fs.readFileSync(filePath);
1266
+ return parseOoxmlDocument(buf, filePath, format);
1267
+ }
1268
+
1269
+ if (["png", "jpg", "jpeg", "webp", "gif"].includes(format)) {
1270
+ const buf = fs.readFileSync(filePath);
1271
+ const mediaSignals = inspectImageBuffer(buf, format);
1272
+ return {
1273
+ filePath,
1274
+ format,
1275
+ modality: "image",
1276
+ language: "en",
1277
+ segments: [],
1278
+ paragraphs: [],
1279
+ artifacts: {
1280
+ links: [],
1281
+ codeBlocks: [],
1282
+ rawFormattingLeaks: [],
1283
+ mediaSignals,
1284
+ },
1285
+ };
1286
+ }
1287
+
1288
+ if (format === "pdf") {
1289
+ const buf = fs.readFileSync(filePath);
1290
+ const pdfInfo = inspectPdfBuffer(buf);
1291
+ const pages = pdfInfo.pages || [];
1292
+ const segments = [];
1293
+ const paragraphs = [];
1294
+ const rawFormattingLeaks = [];
1295
+ let pCounter = 0;
1296
+
1297
+ for (const page of pages) {
1298
+ if (!page.text || !page.text.trim()) continue;
1299
+ const pageDoc = parseMarkdownOrText(page.text, filePath, "txt");
1300
+ const pageIdOffset = pCounter;
1301
+ for (const seg of pageDoc.segments) {
1302
+ const pNum = parseInt(seg.paragraphId.slice(1), 10) + pageIdOffset;
1303
+ const sNum = seg.id.split("-")[1];
1304
+ const id = `P${pNum}-${sNum}`;
1305
+ const locator = { kind: "pdf-readonly", page: page.index };
1306
+ segments.push({
1307
+ ...seg,
1308
+ id,
1309
+ paragraphId: `P${pNum}`,
1310
+ line: page.index,
1311
+ locator,
1312
+ });
1313
+ }
1314
+ for (const para of pageDoc.paragraphs) {
1315
+ const pNum = parseInt(para.id.slice(1), 10) + pageIdOffset;
1316
+ paragraphs.push({
1317
+ ...para,
1318
+ id: `P${pNum}`,
1319
+ line: page.index,
1320
+ segmentIds: para.segmentIds.map((sid) => {
1321
+ const sNum = sid.split("-")[1];
1322
+ return `P${pNum}-${sNum}`;
1323
+ }),
1324
+ locator: { kind: "pdf-readonly", page: page.index },
1325
+ });
1326
+ }
1327
+ pCounter += pageDoc.paragraphs.length;
1328
+
1329
+ if (page.nonMonoText && page.nonMonoText.trim()) {
1330
+ const nonMonoDoc = parseMarkdownOrText(page.nonMonoText, filePath, "txt");
1331
+ for (const seg of nonMonoDoc.segments) {
1332
+ rawFormattingLeaks.push(
1333
+ ...detectRawMarkdownLeaksInRun(seg.text, null, page.index, {
1334
+ kind: "pdf-readonly",
1335
+ page: page.index,
1336
+ }),
1337
+ );
1338
+ }
1339
+ }
1340
+ }
1341
+
1342
+ const landscapeSlidePages = pages.filter((p) => p.width > p.height * 1.25);
1343
+ const wordCounts = landscapeSlidePages.map((p) => p.wordCount).sort((a, b) => a - b);
1344
+ const cjkCounts = landscapeSlidePages.map((p) => p.cjkCount).sort((a, b) => a - b);
1345
+ const medianWords = wordCounts.length ? wordCounts[Math.floor(wordCounts.length / 2)] : 0;
1346
+ const medianCjk = cjkCounts.length ? cjkCounts[Math.floor(cjkCounts.length / 2)] : 0;
1347
+ const isSlideDeckPdf =
1348
+ pages.length >= 2 &&
1349
+ landscapeSlidePages.length >= Math.ceil(pages.length * 0.7) &&
1350
+ medianWords <= 180 &&
1351
+ medianCjk <= 420;
1352
+
1353
+ const corpus = segments.map((s) => s.text).join("\n");
1354
+ return {
1355
+ filePath,
1356
+ format: "pdf",
1357
+ modality: "presentation",
1358
+ language: corpus ? detectDocumentLanguage(corpus) : "en",
1359
+ segments,
1360
+ paragraphs,
1361
+ artifacts: {
1362
+ links: [],
1363
+ codeBlocks: [],
1364
+ rawFormattingLeaks,
1365
+ ...(isSlideDeckPdf
1366
+ ? {
1367
+ deckSignals: {
1368
+ slideCount: pages.length,
1369
+ slides: pages.map((p) => ({
1370
+ index: p.index,
1371
+ firstSegmentId: segments.find((s) => s.line === p.index)?.id || null,
1372
+ title: (p.text.split("\n")[0] || "").slice(0, 80),
1373
+ wordCount: p.wordCount,
1374
+ cjkCount: p.cjkCount,
1375
+ bulletCount: 0,
1376
+ autofitFontScale: 100,
1377
+ })),
1378
+ },
1379
+ }
1380
+ : {}),
1381
+ mediaSignals: {
1382
+ encrypted: pdfInfo.encrypted,
1383
+ pageCount: pdfInfo.pageCount,
1384
+ },
1385
+ },
1386
+ };
1387
+ }
1388
+
1389
+ const buf = fs.readFileSync(filePath);
1390
+ // Reject binary NUL bytes in supposed UTF-8 text files
1391
+ if (buf.includes(0)) {
1392
+ throw new Error(`Binary or non-UTF-8 file cannot be parsed as ${format}: '${filePath}'`);
1393
+ }
1394
+ const rawText = buf.toString("utf8");
1395
+ return parseDocumentText(rawText, filePath, format);
1396
+ }
1397
+
1398
+ /**
1399
+ * Parse an in-memory UTF-8 text document into a `DocumentModel`.
1400
+ */
1401
+ export function parseDocumentText(rawText, filePath = "untitled.md", explicitFormat = null) {
1402
+ const format = explicitFormat || detectFormatFromPath(filePath) || "md";
1403
+ if (["html", "jsx", "tsx", "svg", "css"].includes(format)) {
1404
+ return parseMarkupOrStylesheet(rawText, filePath, format);
1405
+ }
1406
+ return parseMarkdownOrText(rawText, filePath, format);
1407
+ }
1408
+
1409
+ export function formatDisplayCoordinate(targetId, line) {
1410
+ if (!targetId) return line ? `[L${line}]` : "[doc]";
1411
+ return line ? `[${targetId}|L${line}]` : `[${targetId}]`;
1412
+ }