cleanpastedtext 0.0.0-stage → 0.2.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,1332 @@
1
+ /**
2
+ * CleanPastedText cleaning engine.
3
+ *
4
+ * Detection-first: every run scans the ORIGINAL text and produces a
5
+ * transparent, per-codepoint report (`detections`) naming every hidden
6
+ * character, AI watermark artifact, and typography change — before any
7
+ * transformation happens. NFKC normalization only runs after detection, so
8
+ * characters like U+202F (narrow no-break space, the widely reported ChatGPT
9
+ * watermark character) are counted and named instead of being silently
10
+ * folded into a plain space.
11
+ *
12
+ * Nothing changes silently: the NFKC and whitespace stages diff their own
13
+ * output and report what they rewrote, so an empty report always means the
14
+ * text came out byte-for-byte identical.
15
+ *
16
+ * Emoji-safe: zero width joiners, emoji presentation selectors (U+FE0E /
17
+ * U+FE0F), and emoji tag sequences that are part of a REAL emoji sequence
18
+ * (family ZWJ sequences, hearts with U+FE0F, keycaps, subdivision flags) are
19
+ * preserved in every preset except "Plain ASCII". Protection is granted by
20
+ * parsing the sequence, never by proximity: the supplementary-plane variation
21
+ * selectors (U+E0100–U+E01EF) used for hidden-byte smuggling are never part of
22
+ * an emoji and are always removed when the variation-selector pass is on.
23
+ */
24
+ export const DEFAULT_PRESET = "AI Clean";
25
+ export const PRESETS = {
26
+ "AI Clean": {
27
+ removeChatArtifacts: true,
28
+ normalizeUnicode: true,
29
+ removeInvisibleChars: true,
30
+ removeJoinControls: true,
31
+ removeBiDi: true,
32
+ removeTagChars: true,
33
+ removeVariationSelectors: true,
34
+ removeControlChars: true,
35
+ normalizeSpaces: true,
36
+ normalizeWhitespace: true,
37
+ normalizeTypography: true,
38
+ stripMarkdown: false,
39
+ plainAscii: false,
40
+ },
41
+ "Safe Clean": {
42
+ removeChatArtifacts: true,
43
+ normalizeUnicode: true,
44
+ removeInvisibleChars: true,
45
+ removeJoinControls: true,
46
+ removeBiDi: true,
47
+ removeTagChars: true,
48
+ removeVariationSelectors: false,
49
+ removeControlChars: true,
50
+ normalizeSpaces: true,
51
+ normalizeWhitespace: true,
52
+ normalizeTypography: true,
53
+ stripMarkdown: false,
54
+ plainAscii: false,
55
+ },
56
+ "Keep Typography": {
57
+ removeChatArtifacts: true,
58
+ normalizeUnicode: true,
59
+ removeInvisibleChars: true,
60
+ removeJoinControls: true,
61
+ removeBiDi: true,
62
+ removeTagChars: true,
63
+ removeVariationSelectors: false,
64
+ removeControlChars: true,
65
+ normalizeSpaces: true,
66
+ normalizeWhitespace: true,
67
+ normalizeTypography: false,
68
+ stripMarkdown: false,
69
+ plainAscii: false,
70
+ },
71
+ "Plain ASCII": {
72
+ removeChatArtifacts: true,
73
+ normalizeUnicode: true,
74
+ removeInvisibleChars: true,
75
+ removeJoinControls: true,
76
+ removeBiDi: true,
77
+ removeTagChars: true,
78
+ removeVariationSelectors: true,
79
+ removeControlChars: true,
80
+ normalizeSpaces: true,
81
+ normalizeWhitespace: true,
82
+ normalizeTypography: true,
83
+ stripMarkdown: false,
84
+ plainAscii: true,
85
+ },
86
+ "Markdown to Text": {
87
+ removeChatArtifacts: true,
88
+ stripMarkdown: true,
89
+ normalizeWhitespace: true,
90
+ },
91
+ "Join Lines": {
92
+ removeChatArtifacts: true,
93
+ normalizeUnicode: true,
94
+ removeInvisibleChars: true,
95
+ removeJoinControls: true,
96
+ removeBiDi: true,
97
+ removeTagChars: true,
98
+ removeVariationSelectors: false,
99
+ removeControlChars: true,
100
+ normalizeSpaces: true,
101
+ normalizeWhitespace: true,
102
+ normalizeTypography: false,
103
+ stripMarkdown: false,
104
+ plainAscii: false,
105
+ joinLines: true,
106
+ },
107
+ };
108
+ /** One-line description of each preset, as shown in the web tool. */
109
+ export const PRESET_DESCRIPTIONS = {
110
+ "Markdown to Text": "Removes common Markdown syntax while keeping typography and list markers.",
111
+ "AI Clean": "Removes hidden characters and standardizes AI-style punctuation.",
112
+ "Safe Clean": "Removes invisible and unsafe characters while keeping more formatting.",
113
+ "Keep Typography": "Keeps smart quotes, dashes, and ellipses while cleaning hidden characters.",
114
+ "Plain ASCII": "Converts the result to keyboard characters for code and older systems.",
115
+ "Join Lines": "Joins lines broken by PDF wrapping into paragraphs and removes hidden characters. Keeps typography.",
116
+ };
117
+ const CHAR_INFO = new Map();
118
+ function registerChars(cps, category, disposition) {
119
+ for (const cp of cps)
120
+ CHAR_INFO.set(cp, { category, disposition });
121
+ }
122
+ function codepointRange(from, to) {
123
+ const out = [];
124
+ for (let cp = from; cp <= to; cp++)
125
+ out.push(cp);
126
+ return out;
127
+ }
128
+ // AI-artifact spaces: special spaces & marks known to appear in AI output.
129
+ // U+202F was widely reported in ChatGPT output in April 2025.
130
+ registerChars([...codepointRange(0x2000, 0x200a), 0x202f, 0x205f, 0x3000], "ai-artifact", "space");
131
+ // Mongolian vowel separator: invisible format character in modern Unicode.
132
+ registerChars([0x180e], "ai-artifact", "remove");
133
+ // Invisible / zero-width characters.
134
+ registerChars([
135
+ 0x200b, // zero width space
136
+ 0x200c, // zero width non-joiner (gated by removeJoinControls)
137
+ 0x200d, // zero width joiner (emoji-safe handling below)
138
+ 0x2060, // word joiner
139
+ 0xfeff, // BOM / zero width no-break space
140
+ 0x00ad, // soft hyphen
141
+ 0x034f, // combining grapheme joiner
142
+ 0xfffc, // object replacement character
143
+ 0xfff9, // interlinear annotation anchor
144
+ 0xfffa, // interlinear annotation separator
145
+ 0xfffb, // interlinear annotation terminator
146
+ 0x115f, // hangul choseong filler
147
+ 0x1160, // hangul jungseong filler
148
+ 0x17b4, // khmer vowel inherent aq
149
+ 0x17b5, // khmer vowel inherent aa
150
+ 0x3164, // hangul filler
151
+ 0xffa0, // halfwidth hangul filler
152
+ ], "invisible", "remove");
153
+ // Bidirectional control characters.
154
+ registerChars([0x200e, 0x200f, 0x061c, ...codepointRange(0x202a, 0x202e), ...codepointRange(0x2066, 0x2069)], "bidi", "remove");
155
+ // Non-breaking space: replaced with a regular space.
156
+ registerChars([0x00a0], "space", "space");
157
+ // Line/paragraph separators and NEL become real newlines.
158
+ registerChars([0x2028, 0x2029, 0x0085], "control", "newline");
159
+ const TAG_INFO = { category: "tag", disposition: "remove" };
160
+ const VS_INFO = { category: "variation-selector", disposition: "remove" };
161
+ const CONTROL_INFO = { category: "control", disposition: "remove" };
162
+ function isTagChar(cp) {
163
+ return cp >= 0xe0000 && cp <= 0xe007f;
164
+ }
165
+ /** Supplementary-plane variation selectors VS17–VS256 — never part of an emoji. */
166
+ function isSupplementaryVariationSelector(cp) {
167
+ return cp >= 0xe0100 && cp <= 0xe01ef;
168
+ }
169
+ function isVariationSelector(cp) {
170
+ return (cp >= 0xfe00 && cp <= 0xfe0f) || isSupplementaryVariationSelector(cp);
171
+ }
172
+ const INVISIBLE_INFO = { category: "invisible", disposition: "remove" };
173
+ const FLAG_INFO = { category: "control", disposition: "flag" };
174
+ /**
175
+ * Format characters with a visible or script-specific job, left alone even
176
+ * though Unicode classes them as format (Cf) or default-ignorable: Arabic,
177
+ * Syriac and Kaithi number signs that print above digits, Egyptian
178
+ * hieroglyph and Duployan shorthand format controls.
179
+ */
180
+ function isScriptFormatChar(cp) {
181
+ return ((cp >= 0x0600 && cp <= 0x0605) ||
182
+ cp === 0x06dd ||
183
+ cp === 0x070f ||
184
+ cp === 0x0890 ||
185
+ cp === 0x0891 ||
186
+ cp === 0x08e2 ||
187
+ cp === 0x110bd ||
188
+ cp === 0x110cd ||
189
+ (cp >= 0x13430 && cp <= 0x1345f) ||
190
+ (cp >= 0x1bca0 && cp <= 0x1bca3));
191
+ }
192
+ /**
193
+ * Joiners that spell words in some scripts: ZWNJ/ZWJ (Persian, Indic) and the
194
+ * Mongolian free variation selectors. They share the removeJoinControls switch.
195
+ */
196
+ function isScriptJoinControl(cp) {
197
+ return cp === 0x200c || cp === 0x200d || (cp >= 0x180b && cp <= 0x180d) || cp === 0x180f;
198
+ }
199
+ const IGNORABLE = /[\p{Default_Ignorable_Code_Point}\p{Cf}]/u;
200
+ const PRIVATE_USE = /\p{Co}/u;
201
+ const NONCHARACTER = /\p{Noncharacter_Code_Point}/u;
202
+ const PROPERTY_CACHE = new Map();
203
+ /**
204
+ * Everything the hand-written tables above do not name, classified from the
205
+ * Unicode properties built into the JavaScript engine, so coverage follows
206
+ * the Unicode version of the browser or Node.js running it: every
207
+ * default-ignorable or format character becomes "invisible", private-use
208
+ * characters and noncharacters become "control", and U+FFFD is flagged.
209
+ */
210
+ function classifyByProperty(cp) {
211
+ if (cp < 0xad)
212
+ return null;
213
+ const cached = PROPERTY_CACHE.get(cp);
214
+ if (cached !== undefined)
215
+ return cached;
216
+ const ch = String.fromCodePoint(cp);
217
+ let info = null;
218
+ if (cp === 0x2800)
219
+ info = { category: "invisible", disposition: "space" };
220
+ else if (cp === 0xfffd)
221
+ info = FLAG_INFO;
222
+ else if (isScriptFormatChar(cp))
223
+ info = null;
224
+ else if (IGNORABLE.test(ch))
225
+ info = INVISIBLE_INFO;
226
+ else if (PRIVATE_USE.test(ch) || NONCHARACTER.test(ch))
227
+ info = CONTROL_INFO;
228
+ PROPERTY_CACHE.set(cp, info);
229
+ return info;
230
+ }
231
+ function classify(cp) {
232
+ const single = CHAR_INFO.get(cp);
233
+ if (single)
234
+ return single;
235
+ if (isTagChar(cp))
236
+ return TAG_INFO;
237
+ if (isVariationSelector(cp))
238
+ return VS_INFO;
239
+ if ((cp <= 0x1f && cp !== 0x09 && cp !== 0x0a && cp !== 0x0d) ||
240
+ cp === 0x7f ||
241
+ (cp >= 0x80 && cp <= 0x9f)) {
242
+ return CONTROL_INFO;
243
+ }
244
+ return classifyByProperty(cp);
245
+ }
246
+ // Typography characters — counted only when typography normalization is on.
247
+ const TYPOGRAPHY_CPS = new Set([
248
+ 0x2018, 0x2019, 0x201c, 0x201d, 0x00ab, 0x00bb, 0x2013, 0x2014, 0x2026,
249
+ ]);
250
+ /* ------------------------------------------------------------------ */
251
+ /* Names and notes */
252
+ /* ------------------------------------------------------------------ */
253
+ export function formatCodepoint(cp) {
254
+ return "U+" + cp.toString(16).toUpperCase().padStart(4, "0");
255
+ }
256
+ const SINGLE_NAMES = {
257
+ 0x0000: "Null",
258
+ 0x0007: "Bell",
259
+ 0x0008: "Backspace",
260
+ 0x000b: "Vertical tab",
261
+ 0x000c: "Form feed",
262
+ 0x001b: "Escape",
263
+ 0x007f: "Delete (DEL)",
264
+ 0x0085: "Next line (NEL)",
265
+ 0x00a0: "No-break space (NBSP)",
266
+ 0x00ab: "Left guillemet («)",
267
+ 0x00ad: "Soft hyphen",
268
+ 0x00bb: "Right guillemet (»)",
269
+ 0x034f: "Combining grapheme joiner",
270
+ 0x061c: "Arabic letter mark",
271
+ 0x115f: "Hangul choseong filler",
272
+ 0x1160: "Hangul jungseong filler",
273
+ 0x17b4: "Khmer vowel inherent aq",
274
+ 0x17b5: "Khmer vowel inherent aa",
275
+ 0x180b: "Mongolian free variation selector one",
276
+ 0x180c: "Mongolian free variation selector two",
277
+ 0x180d: "Mongolian free variation selector three",
278
+ 0x180e: "Mongolian vowel separator",
279
+ 0x180f: "Mongolian free variation selector four",
280
+ 0x2000: "En quad",
281
+ 0x2001: "Em quad",
282
+ 0x2002: "En space",
283
+ 0x2003: "Em space",
284
+ 0x2004: "Three-per-em space",
285
+ 0x2005: "Four-per-em space",
286
+ 0x2006: "Six-per-em space",
287
+ 0x2007: "Figure space",
288
+ 0x2008: "Punctuation space",
289
+ 0x2009: "Thin space",
290
+ 0x200a: "Hair space",
291
+ 0x200b: "Zero width space",
292
+ 0x200c: "Zero width non-joiner",
293
+ 0x200d: "Zero width joiner",
294
+ 0x200e: "Left-to-right mark",
295
+ 0x200f: "Right-to-left mark",
296
+ 0x2013: "En dash",
297
+ 0x2014: "Em dash",
298
+ 0x2018: "Left single quotation mark",
299
+ 0x2019: "Right single quotation mark",
300
+ 0x201c: "Left double quotation mark",
301
+ 0x201d: "Right double quotation mark",
302
+ 0x2026: "Horizontal ellipsis",
303
+ 0x2028: "Line separator",
304
+ 0x2029: "Paragraph separator",
305
+ 0x202a: "Left-to-right embedding",
306
+ 0x202b: "Right-to-left embedding",
307
+ 0x202c: "Pop directional formatting",
308
+ 0x202d: "Left-to-right override",
309
+ 0x202e: "Right-to-left override",
310
+ 0x202f: "Narrow no-break space",
311
+ 0x205f: "Medium mathematical space",
312
+ 0x2060: "Word joiner",
313
+ 0x2061: "Function application (invisible)",
314
+ 0x2062: "Invisible times",
315
+ 0x2063: "Invisible separator",
316
+ 0x2064: "Invisible plus",
317
+ 0x206a: "Inhibit symmetric swapping (deprecated)",
318
+ 0x206b: "Activate symmetric swapping (deprecated)",
319
+ 0x206c: "Inhibit Arabic form shaping (deprecated)",
320
+ 0x206d: "Activate Arabic form shaping (deprecated)",
321
+ 0x206e: "National digit shapes (deprecated)",
322
+ 0x206f: "Nominal digit shapes (deprecated)",
323
+ 0x2800: "Braille pattern blank",
324
+ 0x2066: "Left-to-right isolate",
325
+ 0x2067: "Right-to-left isolate",
326
+ 0x2068: "First strong isolate",
327
+ 0x2069: "Pop directional isolate",
328
+ 0x3000: "Ideographic space",
329
+ 0x3164: "Hangul filler",
330
+ 0xfe0e: "Variation selector-15 (text style)",
331
+ 0xfe0f: "Variation selector-16 (emoji style)",
332
+ 0xfeff: "Byte order mark (BOM)",
333
+ 0xffa0: "Halfwidth Hangul filler",
334
+ 0xfff9: "Interlinear annotation anchor",
335
+ 0xfffa: "Interlinear annotation separator",
336
+ 0xfffb: "Interlinear annotation terminator",
337
+ 0xfffc: "Object replacement character",
338
+ 0xfffd: "Replacement character (�)",
339
+ 0x1d173: "Musical symbol begin beam (invisible)",
340
+ 0x1d174: "Musical symbol end beam (invisible)",
341
+ 0x1d175: "Musical symbol begin tie (invisible)",
342
+ 0x1d176: "Musical symbol end tie (invisible)",
343
+ 0x1d177: "Musical symbol begin slur (invisible)",
344
+ 0x1d178: "Musical symbol end slur (invisible)",
345
+ 0x1d179: "Musical symbol begin phrase (invisible)",
346
+ 0x1d17a: "Musical symbol end phrase (invisible)",
347
+ 0xe0001: "Language tag",
348
+ 0xe0020: "Tag space",
349
+ 0xe007f: "Cancel tag",
350
+ };
351
+ export function codepointName(cp) {
352
+ const single = SINGLE_NAMES[cp];
353
+ if (single)
354
+ return single;
355
+ if (cp >= 0xe0021 && cp <= 0xe007e) {
356
+ return `Tag character (hidden "${String.fromCodePoint(cp - 0xe0000)}")`;
357
+ }
358
+ if (isTagChar(cp))
359
+ return "Tag character";
360
+ if (cp >= 0xfe00 && cp <= 0xfe0f)
361
+ return `Variation selector-${cp - 0xfe00 + 1}`;
362
+ if (isSupplementaryVariationSelector(cp))
363
+ return `Variation selector-${cp - 0xe0100 + 17}`;
364
+ if (cp <= 0x1f)
365
+ return "Control character (C0)";
366
+ if (cp >= 0x80 && cp <= 0x9f)
367
+ return "Control character (C1)";
368
+ const ch = String.fromCodePoint(cp);
369
+ if (PRIVATE_USE.test(ch))
370
+ return "Private-use character";
371
+ if (NONCHARACTER.test(ch))
372
+ return "Noncharacter";
373
+ if (IGNORABLE.test(ch))
374
+ return "Invisible format character";
375
+ return `Character ${formatCodepoint(cp)}`;
376
+ }
377
+ const NOTES = {
378
+ 0x202f: "Widely reported in ChatGPT output, April 2025",
379
+ 0x00a0: "Common in AI output and copied web text",
380
+ 0x2009: "Special space repeatedly flagged in AI-generated text",
381
+ 0x200b: "Invisible; breaks search, diffs, and code",
382
+ 0x200c: "Needed inside Persian and Indic words — removing it changes spelling",
383
+ 0x200d: "Joins emoji and Indic conjuncts — removed only outside emoji sequences",
384
+ 0x00ad: "Invisible until a line wraps; a common paste artifact",
385
+ 0xfeff: "Zero width no-break space; stray BOMs corrupt files",
386
+ 0x202e: "Reorders displayed text; used in spoofing attacks",
387
+ 0x2014: "Frequently cited as an AI typography tell",
388
+ 0x180e: "Renders invisibly in modern fonts",
389
+ 0x2800: "Looks like a space; a popular invisible filler outside Braille text",
390
+ 0xfffd: "The original character was lost in an encoding error and can't be recovered; check the source",
391
+ 0x2062: "Invisible math operator; no visible glyph in prose",
392
+ };
393
+ function codepointNote(cp) {
394
+ const note = NOTES[cp];
395
+ if (note)
396
+ return note;
397
+ if (isTagChar(cp))
398
+ return "Used for invisible data smuggling and AI watermarking";
399
+ if (isSupplementaryVariationSelector(cp)) {
400
+ return "Never part of an emoji — the channel used to hide bytes inside ordinary text";
401
+ }
402
+ if (isVariationSelector(cp))
403
+ return "Invisible; can encode hidden data after ordinary characters";
404
+ const ch = String.fromCodePoint(cp);
405
+ if (PRIVATE_USE.test(ch))
406
+ return "Only displays with the font that defined it; shows as a box elsewhere";
407
+ return undefined;
408
+ }
409
+ const EMOJI_KEPT_NOTE = "Part of an emoji sequence — kept so your emoji don't break";
410
+ /* ------------------------------------------------------------------ */
411
+ /* Emoji safety */
412
+ /* ------------------------------------------------------------------ */
413
+ const ZWJ = 0x200d;
414
+ const VS15 = 0xfe0e;
415
+ const VS16 = 0xfe0f;
416
+ const COMBINING_KEYCAP = 0x20e3;
417
+ const CANCEL_TAG = 0xe007f;
418
+ const BLACK_FLAG = 0x1f3f4;
419
+ const EXTENDED_PICTOGRAPHIC = /\p{Extended_Pictographic}/u;
420
+ const PICTOGRAPHIC_CACHE = new Map();
421
+ function isPictographic(cp) {
422
+ // Nothing below U+00A9 (©, the first Extended_Pictographic codepoint) can be
423
+ // an emoji base, so ordinary prose never pays for the regex.
424
+ if (cp < 0x00a9)
425
+ return false;
426
+ const cached = PICTOGRAPHIC_CACHE.get(cp);
427
+ if (cached !== undefined)
428
+ return cached;
429
+ const value = EXTENDED_PICTOGRAPHIC.test(String.fromCodePoint(cp));
430
+ if (PICTOGRAPHIC_CACHE.size > 4096)
431
+ PICTOGRAPHIC_CACHE.clear();
432
+ PICTOGRAPHIC_CACHE.set(cp, value);
433
+ return value;
434
+ }
435
+ function isRegionalIndicator(cp) {
436
+ return cp >= 0x1f1e6 && cp <= 0x1f1ff;
437
+ }
438
+ function isSkinToneModifier(cp) {
439
+ return cp >= 0x1f3fb && cp <= 0x1f3ff;
440
+ }
441
+ /** 0-9, # and * — emoji bases ONLY when the sequence continues to U+20E3. */
442
+ function isKeycapBase(cp) {
443
+ return (cp >= 0x30 && cp <= 0x39) || cp === 0x23 || cp === 0x2a;
444
+ }
445
+ function isPresentationSelector(cp) {
446
+ return cp === VS15 || cp === VS16;
447
+ }
448
+ /** Tag characters valid inside an emoji tag sequence: "0"-"9" and "a"-"z". */
449
+ function isTagSpec(cp) {
450
+ return (cp >= 0xe0030 && cp <= 0xe0039) || (cp >= 0xe0061 && cp <= 0xe007a);
451
+ }
452
+ /**
453
+ * Parses the emoji sequence starting at `start`, marking every hidden member
454
+ * (ZWJ, U+FE0E/U+FE0F, tag characters) that must be preserved. Returns the
455
+ * number of codepoints consumed, or 0 when no emoji sequence starts here.
456
+ *
457
+ * Only well-formed sequences are protected:
458
+ * keycap := [0-9#*] U+FE0F? U+20E3
459
+ * flag := RI RI
460
+ * tag flag := U+1F3F4 tag_spec{2,6} U+E007F
461
+ * zwj seq := core (ZWJ core)* where core := pictographic VS? modifier? VS?
462
+ *
463
+ * Everything else — a payload of variation selectors after an emoji, tag
464
+ * characters after a lone black flag, a ZWJ after a digit — is left unmarked
465
+ * and therefore stripped by the normal passes.
466
+ *
467
+ * Base codepoints used as emoji (a heart before U+FE0F, the two halves of a
468
+ * ZWJ sequence) are collected in `emojiBases` so the NFKC stage can leave them
469
+ * alone: compatibility folding would otherwise turn the emoji U+2122 U+FE0F
470
+ * into "TM" and U+2139 U+FE0F into "i".
471
+ */
472
+ function scanEmojiSequence(cps, start, marks, emojiBases) {
473
+ const n = cps.length;
474
+ const cp = cps[start];
475
+ // Keycap sequence — the ONLY reason a digit, "#" or "*" is an emoji base.
476
+ if (isKeycapBase(cp)) {
477
+ let j = start + 1;
478
+ let vsIndex = -1;
479
+ if (j < n && cps[j] === VS16) {
480
+ vsIndex = j;
481
+ j++;
482
+ }
483
+ if (j < n && cps[j] === COMBINING_KEYCAP) {
484
+ if (vsIndex >= 0)
485
+ marks[vsIndex] = 1;
486
+ return j + 1 - start;
487
+ }
488
+ return 1;
489
+ }
490
+ // Regional indicator pair (country flag) — nothing hidden inside.
491
+ if (isRegionalIndicator(cp)) {
492
+ return start + 1 < n && isRegionalIndicator(cps[start + 1]) ? 2 : 1;
493
+ }
494
+ // Emoji tag sequence (subdivision flags such as Scotland / Wales / England).
495
+ if (cp === BLACK_FLAG && start + 1 < n && isTagSpec(cps[start + 1])) {
496
+ let j = start + 1;
497
+ let specs = 0;
498
+ while (j < n && specs < 6 && isTagSpec(cps[j])) {
499
+ j++;
500
+ specs++;
501
+ }
502
+ if (specs >= 2 && j < n && cps[j] === CANCEL_TAG) {
503
+ for (let k = start + 1; k <= j; k++)
504
+ marks[k] = 1;
505
+ return j + 1 - start;
506
+ }
507
+ return 1; // black flag followed by a smuggled tag payload: protect nothing.
508
+ }
509
+ // ZWJ sequence of pictographic cores (family emoji, professions, flags).
510
+ if (!isPictographic(cp))
511
+ return 0;
512
+ let j = start;
513
+ for (;;) {
514
+ const base = cps[j];
515
+ j++; // pictographic base
516
+ if (j < n && isPresentationSelector(cps[j])) {
517
+ marks[j] = 1;
518
+ emojiBases.add(base);
519
+ j++;
520
+ }
521
+ if (j < n && isSkinToneModifier(cps[j]))
522
+ j++;
523
+ if (j < n && isPresentationSelector(cps[j])) {
524
+ marks[j] = 1;
525
+ emojiBases.add(base);
526
+ j++;
527
+ }
528
+ if (j + 1 < n && cps[j] === ZWJ && isPictographic(cps[j + 1])) {
529
+ marks[j] = 1;
530
+ emojiBases.add(base);
531
+ emojiBases.add(cps[j + 1]);
532
+ j++;
533
+ continue;
534
+ }
535
+ break;
536
+ }
537
+ return j - start;
538
+ }
539
+ /**
540
+ * One linear left-to-right scan of the whole text; every index is visited a
541
+ * bounded number of times, so a pathological run of joiners, tag characters or
542
+ * variation selectors costs O(n) instead of the O(n^2) a backward look-back
543
+ * would cost.
544
+ */
545
+ function markEmojiSequences(cps) {
546
+ const marks = new Uint8Array(cps.length);
547
+ const emojiBases = new Set();
548
+ let i = 0;
549
+ while (i < cps.length) {
550
+ const consumed = scanEmojiSequence(cps, i, marks, emojiBases);
551
+ i += consumed > 0 ? consumed : 1;
552
+ }
553
+ return { marks, emojiBases };
554
+ }
555
+ /* ------------------------------------------------------------------ */
556
+ /* Option gating */
557
+ /* ------------------------------------------------------------------ */
558
+ function isCategoryEnabled(category, cp, o) {
559
+ const ascii = !!o.plainAscii;
560
+ switch (category) {
561
+ case "ai-artifact":
562
+ return !!o.normalizeSpaces || ascii;
563
+ case "invisible":
564
+ // ZWNJ/ZWJ carry meaning in Persian and Indic scripts, so they get their
565
+ // own switch; it falls back to removeInvisibleChars for older callers.
566
+ if (isScriptJoinControl(cp)) {
567
+ return (o.removeJoinControls ?? !!o.removeInvisibleChars) || ascii;
568
+ }
569
+ return !!o.removeInvisibleChars || ascii;
570
+ case "bidi":
571
+ return !!o.removeBiDi || ascii;
572
+ case "tag":
573
+ return !!o.removeTagChars || ascii;
574
+ case "variation-selector":
575
+ return !!o.removeVariationSelectors || ascii;
576
+ case "space":
577
+ return !!o.normalizeWhitespace || ascii;
578
+ case "control":
579
+ // Line separator / paragraph separator / NEL are whitespace concerns too.
580
+ if (cp === 0x2028 || cp === 0x2029 || cp === 0x0085) {
581
+ return !!o.removeControlChars || !!o.normalizeWhitespace || ascii;
582
+ }
583
+ return !!o.removeControlChars || ascii;
584
+ }
585
+ }
586
+ /**
587
+ * Single pass over the original text: detects and counts every known hidden
588
+ * character on the untouched input, and applies per-character removals and
589
+ * replacements according to the options.
590
+ */
591
+ function runCharacterPass(text, o) {
592
+ const emojiSafe = !o.plainAscii;
593
+ const countTypography = !!o.normalizeTypography || !!o.plainAscii;
594
+ const chars = Array.from(text);
595
+ const cps = new Array(chars.length);
596
+ for (let i = 0; i < chars.length; i++)
597
+ cps[i] = chars[i].codePointAt(0);
598
+ const emoji = emojiSafe ? markEmojiSequences(cps) : null;
599
+ const emojiMarks = emoji ? emoji.marks : null;
600
+ const outParts = [];
601
+ const occurrences = new Map();
602
+ const typographyCounts = new Map();
603
+ const record = (cp, category, action, emojiKept) => {
604
+ const key = `${cp}|${emojiKept ? 1 : 0}`;
605
+ const existing = occurrences.get(key);
606
+ if (existing) {
607
+ existing.count++;
608
+ }
609
+ else {
610
+ occurrences.set(key, { cp, category, action, emojiKept, count: 1 });
611
+ }
612
+ };
613
+ for (let i = 0; i < chars.length; i++) {
614
+ const ch = chars[i];
615
+ const cp = cps[i];
616
+ if (TYPOGRAPHY_CPS.has(cp)) {
617
+ if (countTypography) {
618
+ typographyCounts.set(cp, (typographyCounts.get(cp) ?? 0) + 1);
619
+ }
620
+ outParts.push(ch); // actual replacement happens in the typography stage
621
+ continue;
622
+ }
623
+ const info = classify(cp);
624
+ if (!info) {
625
+ outParts.push(ch);
626
+ continue;
627
+ }
628
+ const enabled = isCategoryEnabled(info.category, cp, o);
629
+ if (!enabled) {
630
+ record(cp, info.category, "kept", false);
631
+ outParts.push(ch);
632
+ continue;
633
+ }
634
+ // Protection comes from the sequence parser, never from proximity: only
635
+ // ZWJs, U+FE0E/U+FE0F and tag characters inside a well-formed emoji
636
+ // sequence are marked.
637
+ if (emojiMarks !== null && emojiMarks[i] === 1) {
638
+ record(cp, info.category, "kept", true);
639
+ outParts.push(ch);
640
+ continue;
641
+ }
642
+ if (info.disposition === "flag") {
643
+ record(cp, info.category, "kept", false);
644
+ outParts.push(ch);
645
+ continue;
646
+ }
647
+ if (info.disposition === "remove") {
648
+ record(cp, info.category, "removed", false);
649
+ }
650
+ else {
651
+ record(cp, info.category, "replaced", false);
652
+ outParts.push(info.disposition === "space" ? " " : "\n");
653
+ }
654
+ }
655
+ return {
656
+ out: outParts.join(""),
657
+ occurrences,
658
+ typographyCounts,
659
+ emojiBases: emoji ? emoji.emojiBases : new Set(),
660
+ };
661
+ }
662
+ const NFKC_FOLD_CACHE = new Map();
663
+ /** Returns the NFKC form of a single character, or null when it is unchanged. */
664
+ function nfkcFold(cp, ch) {
665
+ if (cp < 0x80)
666
+ return null; // ASCII is NFKC-stable
667
+ const cached = NFKC_FOLD_CACHE.get(cp);
668
+ if (cached !== undefined)
669
+ return cached;
670
+ const folded = ch.normalize("NFKC");
671
+ const value = folded === ch ? null : folded;
672
+ if (NFKC_FOLD_CACHE.size > 4096)
673
+ NFKC_FOLD_CACHE.clear();
674
+ NFKC_FOLD_CACHE.set(cp, value);
675
+ return value;
676
+ }
677
+ /**
678
+ * NFKC normalization that shields characters whose dedicated option is OFF,
679
+ * so toggles stay truthful: with "Keep Typography", U+2026 must survive even
680
+ * though NFKC would fold it to "..."; same for NBSP and exotic spaces when
681
+ * their toggles are off.
682
+ *
683
+ * It also diffs itself: every codepoint it rewrites is reported, so the panel
684
+ * can never claim "nothing found" about text NFKC just changed.
685
+ */
686
+ function nfkcStage(text, shielded, skipReporting) {
687
+ const changes = new Map();
688
+ let out = "";
689
+ let buffer = "";
690
+ for (const ch of text) {
691
+ const cp = ch.codePointAt(0);
692
+ if (shielded.has(cp)) {
693
+ out += buffer.normalize("NFKC") + ch;
694
+ buffer = "";
695
+ continue;
696
+ }
697
+ if (!skipReporting.has(cp)) {
698
+ const folded = nfkcFold(cp, ch);
699
+ if (folded !== null) {
700
+ const entry = changes.get(cp);
701
+ if (entry)
702
+ entry.count++;
703
+ else
704
+ changes.set(cp, { count: 1, to: folded });
705
+ }
706
+ }
707
+ buffer += ch;
708
+ }
709
+ out += buffer.normalize("NFKC");
710
+ return { out, changes, composed: changes.size === 0 && out !== text };
711
+ }
712
+ function buildNfkcShield(o) {
713
+ const shielded = new Set();
714
+ const ascii = !!o.plainAscii;
715
+ if (!o.normalizeTypography && !ascii) {
716
+ shielded.add(0x2026); // NFKC folds the ellipsis to "..."
717
+ }
718
+ if (!o.normalizeWhitespace && !ascii) {
719
+ shielded.add(0x00a0);
720
+ }
721
+ if (!o.normalizeSpaces && !ascii) {
722
+ for (const cp of [...codepointRange(0x2000, 0x200a), 0x202f, 0x205f, 0x3000]) {
723
+ shielded.add(cp);
724
+ }
725
+ }
726
+ return shielded;
727
+ }
728
+ function emptyWhitespaceCounts() {
729
+ return { carriageReturns: 0, trailing: new Map(), blankLinesCollapsed: 0 };
730
+ }
731
+ function addWhitespaceCounts(into, extra) {
732
+ into.carriageReturns += extra.carriageReturns;
733
+ into.blankLinesCollapsed += extra.blankLinesCollapsed;
734
+ for (const [cp, count] of extra.trailing) {
735
+ into.trailing.set(cp, (into.trailing.get(cp) ?? 0) + count);
736
+ }
737
+ }
738
+ function normalizeWhitespaceStage(text) {
739
+ const counts = emptyWhitespaceCounts();
740
+ for (let i = 0; i < text.length; i++) {
741
+ if (text.charCodeAt(i) === 0x0d)
742
+ counts.carriageReturns++;
743
+ }
744
+ let out = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
745
+ out = out
746
+ .split("\n")
747
+ .map((line) => {
748
+ const trimmed = line.trimEnd();
749
+ for (const ch of line.slice(trimmed.length)) {
750
+ const cp = ch.codePointAt(0);
751
+ counts.trailing.set(cp, (counts.trailing.get(cp) ?? 0) + 1);
752
+ }
753
+ return trimmed;
754
+ })
755
+ .join("\n");
756
+ let blankStreak = 0;
757
+ const collapsed = [];
758
+ for (const line of out.split("\n")) {
759
+ if (line.trim() === "") {
760
+ blankStreak++;
761
+ if (blankStreak <= 2) {
762
+ collapsed.push(line);
763
+ }
764
+ else {
765
+ counts.blankLinesCollapsed++;
766
+ }
767
+ }
768
+ else {
769
+ blankStreak = 0;
770
+ collapsed.push(line);
771
+ }
772
+ }
773
+ return { out: collapsed.join("\n"), counts };
774
+ }
775
+ /** A line that starts a list item keeps its own line when wrapped lines are joined. */
776
+ const LIST_ITEM_START = /^\s*(?:[-*+\u2022\u2023\u2043\u25AA\u25E6]|\d{1,3}[.)]|[a-zA-Z][.)])\s/;
777
+ function joinLinesStage(text) {
778
+ let joined = 0;
779
+ let hyphensRejoined = 0;
780
+ const out = [];
781
+ for (const line of text.split("\n")) {
782
+ const last = out.length - 1;
783
+ const prev = last >= 0 ? out[last] : "";
784
+ if (last >= 0 && prev.trim() !== "" && line.trim() !== "" && !LIST_ITEM_START.test(line)) {
785
+ const head = prev.replace(/[ \t]+$/, "");
786
+ const tail = line.trimStart();
787
+ if (/\p{L}-$/u.test(head) && /^\p{Ll}/u.test(tail)) {
788
+ out[last] = head.slice(0, -1) + tail;
789
+ hyphensRejoined++;
790
+ }
791
+ else {
792
+ out[last] = `${head} ${tail}`;
793
+ joined++;
794
+ }
795
+ continue;
796
+ }
797
+ out.push(line);
798
+ }
799
+ return { out: out.join("\n"), joined, hyphensRejoined };
800
+ }
801
+ function whitespaceTotal(counts) {
802
+ let total = counts.carriageReturns;
803
+ for (const count of counts.trailing.values())
804
+ total += count;
805
+ return total;
806
+ }
807
+ function whitespaceDetections(counts) {
808
+ const rows = [];
809
+ if (counts.carriageReturns > 0) {
810
+ rows.push({
811
+ codepoint: "U+000D",
812
+ name: "Carriage return",
813
+ count: counts.carriageReturns,
814
+ category: "normalization",
815
+ action: "replaced",
816
+ note: "Windows line ending (CRLF) converted to a plain newline",
817
+ });
818
+ }
819
+ for (const [cp, count] of counts.trailing) {
820
+ const base = cp === 0x20 ? "Trailing space" : cp === 0x09 ? "Trailing tab" : `Trailing ${codepointName(cp)}`;
821
+ rows.push({
822
+ codepoint: formatCodepoint(cp),
823
+ name: base,
824
+ count,
825
+ category: "normalization",
826
+ action: "removed",
827
+ note: "Whitespace left at the end of a line",
828
+ });
829
+ }
830
+ if (counts.blankLinesCollapsed > 0) {
831
+ rows.push({
832
+ codepoint: "U+000A",
833
+ name: "Extra blank line",
834
+ count: counts.blankLinesCollapsed,
835
+ category: "normalization",
836
+ action: "removed",
837
+ note: "Runs of three or more blank lines collapsed to two",
838
+ });
839
+ }
840
+ return rows;
841
+ }
842
+ function normalizeTypographyStage(text) {
843
+ return text
844
+ .replace(/[\u201C\u201D\u00AB\u00BB]/g, '"')
845
+ .replace(/[\u2018\u2019]/g, "'")
846
+ .replace(/[\u2013\u2014]/g, "-")
847
+ .replace(/\u2026/g, "...");
848
+ }
849
+ /* ------------------------------------------------------------------ */
850
+ /* Markdown stripping */
851
+ /* ------------------------------------------------------------------ */
852
+ /** A link target has to look like one; "a[i](b)" in code must survive. */
853
+ const MD_URL = /^<?\s*(?:[a-z][a-z0-9+.-]*:|[/#?]|\.{1,2}\/|[\w-]+(?:\.[\w-]+)+(?:[/?#]|$))/i;
854
+ function looksLikeUrl(target) {
855
+ const trimmed = target.trim();
856
+ return trimmed.length > 0 && MD_URL.test(trimmed);
857
+ }
858
+ /**
859
+ * Replaces the body of every fenced code block with a placeholder so the rest
860
+ * of the Markdown pass cannot rewrite code. The fence lines themselves stay in
861
+ * place and are removed (and counted) by the normal fence rule.
862
+ */
863
+ function maskFencedCode(text, blocks, placeholder) {
864
+ const fences = [];
865
+ const fenceLine = /^[ \t]{0,3}(?:```|~~~)[^\n]*$/gm;
866
+ let match;
867
+ while ((match = fenceLine.exec(text)) !== null) {
868
+ fences.push({ start: match.index, end: match.index + match[0].length });
869
+ }
870
+ if (fences.length === 0)
871
+ return text;
872
+ const ranges = [];
873
+ for (let i = 0; i + 1 < fences.length; i += 2) {
874
+ // Skip the newline after the opening fence and leave the newline before the
875
+ // closing fence in place, so the closing fence stays at the start of a line.
876
+ ranges.push({ start: Math.min(fences[i].end + 1, text.length), end: fences[i + 1].start - 1 });
877
+ }
878
+ if (fences.length % 2 === 1) {
879
+ const last = fences[fences.length - 1];
880
+ ranges.push({ start: Math.min(last.end + 1, text.length), end: text.length });
881
+ }
882
+ let out = text;
883
+ for (let i = ranges.length - 1; i >= 0; i--) {
884
+ const { start, end } = ranges[i];
885
+ if (end <= start)
886
+ continue;
887
+ const index = blocks.length;
888
+ blocks.push(text.slice(start, end));
889
+ out = out.slice(0, start) + placeholder(index) + out.slice(end);
890
+ }
891
+ return out;
892
+ }
893
+ /**
894
+ * Deterministically strips Markdown residue commonly left by AI chat output.
895
+ * List markers ("- ", "1. ") are intentionally kept, fenced and inline code is
896
+ * spliced back verbatim, and identifiers like `__init__`, `my_snake_var`, array
897
+ * indexing `a[i](b)` and paths like `/tmp/_private_/x` are left alone.
898
+ */
899
+ function stripMarkdownStage(text) {
900
+ let removed = 0;
901
+ const blocks = [];
902
+ let sentinel = "\u0000";
903
+ while (text.includes(sentinel + "MD"))
904
+ sentinel += "\u0000";
905
+ const placeholder = (index) => `${sentinel}MD${index}${sentinel}`;
906
+ const placeholderPattern = new RegExp(`${sentinel}MD(\\d+)${sentinel}`, "g");
907
+ // Code first: fenced blocks, then inline spans. Their content is immune to
908
+ // every rule below.
909
+ let out = maskFencedCode(text, blocks, placeholder);
910
+ out = out.replace(/`([^`\n]+?)`/g, (_m, inner) => {
911
+ removed++;
912
+ blocks.push(inner);
913
+ return placeholder(blocks.length - 1);
914
+ });
915
+ // ``` fence lines (the fenced content was masked above).
916
+ out = out.replace(/^[ \t]{0,3}(?:```|~~~)[^\n]*\n?/gm, () => {
917
+ removed++;
918
+ return "";
919
+ });
920
+ // "> " blockquote markers (before headings so "> # x" fully unwraps).
921
+ out = out.replace(/^(?:>[ \t]?)+/gm, () => {
922
+ removed++;
923
+ return "";
924
+ });
925
+ // Heading markers.
926
+ out = out.replace(/^#{1,6}[ \t]+/gm, () => {
927
+ removed++;
928
+ return "";
929
+ });
930
+ // Images ![alt](url) -> alt, then links [text](url) -> text — only when the
931
+ // target actually looks like a URL.
932
+ out = out.replace(/!\[([^\]\n]*)\]\(([^)\n]*)\)/g, (m, alt, target) => {
933
+ if (!looksLikeUrl(target))
934
+ return m;
935
+ removed++;
936
+ return alt;
937
+ });
938
+ out = out.replace(/\[([^\]\n]*)\]\(([^)\n]*)\)/g, (m, label, target) => {
939
+ if (!looksLikeUrl(target))
940
+ return m;
941
+ removed++;
942
+ return label;
943
+ });
944
+ // Bold, then italic (word-wrapping markers only; list bullets are untouched).
945
+ // Real emphasis never has whitespace against the delimiter, which keeps
946
+ // expressions such as "a = **p + **q" intact.
947
+ out = out.replace(/\*\*([^*\s](?:[^*\n]*[^*\s])?)\*\*/g, (_m, inner) => {
948
+ removed++;
949
+ return inner;
950
+ });
951
+ // __bold__ requires a non-identifier character inside, so Python dunders
952
+ // (__init__, __name__) and __CONSTANTS__ survive.
953
+ out = out.replace(/(^|[^\w\\])__([^_\s](?:[^_\n]*[^_\s])?)__(?![\w_])/gm, (m, pre, inner) => {
954
+ if (!/[^\w]/.test(inner))
955
+ return m;
956
+ removed++;
957
+ return pre + inner;
958
+ });
959
+ out = out.replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s).,;:!?]|$)/gm, (_m, pre, inner) => {
960
+ removed++;
961
+ return pre + inner;
962
+ });
963
+ // _italic_ only at word boundaries: my_snake_var and /tmp/_private_/x stay.
964
+ out = out.replace(/(^|[\s(])_([^_\s](?:[^_\n]*[^_\s])?)_(?=[\s).,;:!?]|$)/gm, (_m, pre, inner) => {
965
+ removed++;
966
+ return pre + inner;
967
+ });
968
+ // Splice code back in verbatim.
969
+ out = out.replace(placeholderPattern, (_m, index) => blocks[Number(index)] ?? "");
970
+ return { out, removed };
971
+ }
972
+ function plainAsciiStage(text) {
973
+ // Decompose so accented letters fold to their ASCII base (e-acute -> e) instead
974
+ // of being deleted outright, then drop everything outside printable ASCII.
975
+ // U+2044 is normalization's own output (NFKC turns 1/2 into 1 + U+2044 + 2), so it becomes
976
+ // a slash rather than vanishing and gluing "1" to "2".
977
+ return text
978
+ .replace(/[\u2044\u2215]/g, "/")
979
+ .normalize("NFD")
980
+ .replace(/\p{M}/gu, "")
981
+ .replace(/[^\t\n\x20-\x7E]/g, "");
982
+ }
983
+ /**
984
+ * Pull the display name out of a ChatGPT entity marker body such as
985
+ * ["city","Paris","capital of France"] — the second string is what the
986
+ * answer showed as a link.
987
+ */
988
+ function entityDisplayName(body) {
989
+ const strings = body.match(/"((?:[^"\\]|\\.)*)"/g);
990
+ if (!strings || strings.length === 0)
991
+ return "";
992
+ const pick = strings.length > 1 ? strings[1] : strings[0];
993
+ return pick.slice(1, -1).replace(/\\(.)/g, "$1");
994
+ }
995
+ const CHAT_ARTIFACT_RULES = [
996
+ {
997
+ // U+E200 <kind> U+E202 <payload> U+E201 — ChatGPT's private-use citation,
998
+ // entity and widget markers. Entities keep their visible name.
999
+ label: "U+E200…U+E201",
1000
+ name: "ChatGPT citation or entity marker",
1001
+ note: "Private-use markers ChatGPT uses for sources and links; they show as boxes or text like \"cite turn0search0\" when pasted",
1002
+ pattern: /\uE200([a-z_]+)\uE202([\s\S]*?)\uE201/g,
1003
+ replace: (_m, kind, payload) => (kind === "entity" ? entityDisplayName(payload) : ""),
1004
+ },
1005
+ {
1006
+ label: "oaicite",
1007
+ name: "ChatGPT content reference (oaicite)",
1008
+ note: "Citation placeholder from ChatGPT answers, e.g. :contentReference[oaicite:0]{index=0}",
1009
+ pattern: /[ \t]?:?contentReference\[oaicite:\d+\](?:\{index=\d+\})?/g,
1010
+ replace: () => "",
1011
+ },
1012
+ {
1013
+ label: "【†】",
1014
+ name: "ChatGPT source marker",
1015
+ note: "Citation marker from ChatGPT file and browsing answers, e.g. 【4†source】",
1016
+ pattern: /[ \t]?【\d+(?::\d+)?†[^】\n]{0,40}】/g,
1017
+ replace: () => "",
1018
+ },
1019
+ {
1020
+ // The same citations after the private-use delimiters were stripped by
1021
+ // another app: "citeturn0search0turn0news2".
1022
+ label: "citeturn",
1023
+ name: "ChatGPT citation marker (flattened)",
1024
+ note: "What ChatGPT's citation marker becomes when the invisible delimiters are lost",
1025
+ pattern: /[ \t]?\b(?:file)?cite(?:turn\d+[a-z]+\d+)+/g,
1026
+ replace: () => "",
1027
+ },
1028
+ {
1029
+ label: "entity[…]",
1030
+ name: "ChatGPT entity marker (flattened)",
1031
+ note: "A linked name from a ChatGPT answer that lost its invisible delimiters; the name is kept",
1032
+ pattern: /\bentity(\["[^\]\n]{1,300}\])/g,
1033
+ replace: (_m, body) => entityDisplayName(body),
1034
+ },
1035
+ ];
1036
+ function stripChatArtifactsStage(text) {
1037
+ const rows = [];
1038
+ let out = text;
1039
+ for (const rule of CHAT_ARTIFACT_RULES) {
1040
+ let count = 0;
1041
+ out = out.replace(rule.pattern, (...args) => {
1042
+ count++;
1043
+ const groups = args.slice(1, -2);
1044
+ return rule.replace(args[0], ...groups);
1045
+ });
1046
+ if (count > 0) {
1047
+ rows.push({ codepoint: rule.label, name: rule.name, count, category: "chat-artifact", action: "removed", note: rule.note });
1048
+ }
1049
+ }
1050
+ return { out, rows };
1051
+ }
1052
+ /* ------------------------------------------------------------------ */
1053
+ /* Hidden message decoding */
1054
+ /* ------------------------------------------------------------------ */
1055
+ const HIDDEN_MESSAGE_LIMIT = 500;
1056
+ function utf8Decode(bytes) {
1057
+ try {
1058
+ return decodeURIComponent(bytes.map((b) => "%" + b.toString(16).padStart(2, "0")).join(""));
1059
+ }
1060
+ catch {
1061
+ return null;
1062
+ }
1063
+ }
1064
+ function isReadable(text) {
1065
+ if (text.trim().length === 0)
1066
+ return false;
1067
+ const printable = Array.from(text).filter((c) => /[\p{L}\p{N}\p{P}\p{S}\p{Zs}\n\t]/u.test(c)).length;
1068
+ return printable / Array.from(text).length >= 0.9;
1069
+ }
1070
+ /**
1071
+ * Decodes the two known ways of hiding text in invisible characters:
1072
+ * runs of Unicode tag characters that spell ASCII (outside real emoji flag
1073
+ * sequences), and "emoji smuggling", where each byte of a UTF-8 message is a
1074
+ * variation selector (U+FE00–U+FE0F for 0–15, U+E0100–U+E01EF for 16–255).
1075
+ */
1076
+ export function findHiddenMessages(text) {
1077
+ const cps = Array.from(text, (c) => c.codePointAt(0));
1078
+ const found = [];
1079
+ let i = 0;
1080
+ while (i < cps.length) {
1081
+ const cp = cps[i];
1082
+ if (cp >= 0xe0020 && cp <= 0xe007e) {
1083
+ let j = i;
1084
+ while (j < cps.length && cps[j] >= 0xe0020 && cps[j] <= 0xe007e)
1085
+ j++;
1086
+ // A subdivision flag is U+1F3F4, lowercase tag letters, then CANCEL TAG.
1087
+ const isFlag = i > 0 && cps[i - 1] === BLACK_FLAG && cps[j] === CANCEL_TAG;
1088
+ if (!isFlag) {
1089
+ const decoded = String.fromCharCode(...cps.slice(i, j).map((c) => c - 0xe0000));
1090
+ if (isReadable(decoded)) {
1091
+ found.push({ kind: "tag", text: decoded.slice(0, HIDDEN_MESSAGE_LIMIT), carriers: j - i });
1092
+ }
1093
+ }
1094
+ i = j;
1095
+ continue;
1096
+ }
1097
+ if (isVariationSelector(cp)) {
1098
+ let j = i;
1099
+ const bytes = [];
1100
+ while (j < cps.length && isVariationSelector(cps[j])) {
1101
+ const v = cps[j];
1102
+ bytes.push(v <= 0xfe0f ? v - 0xfe00 : v - 0xe0100 + 16);
1103
+ j++;
1104
+ }
1105
+ // One selector is ordinary emoji styling; a message needs at least two bytes.
1106
+ if (j - i >= 2) {
1107
+ const decoded = utf8Decode(bytes);
1108
+ if (decoded !== null && isReadable(decoded)) {
1109
+ found.push({ kind: "variation-selector", text: decoded.slice(0, HIDDEN_MESSAGE_LIMIT), carriers: j - i });
1110
+ }
1111
+ }
1112
+ i = j;
1113
+ continue;
1114
+ }
1115
+ i++;
1116
+ }
1117
+ return found;
1118
+ }
1119
+ export function cleanText(text, options) {
1120
+ const o = options ?? {};
1121
+ const normalizationRows = [];
1122
+ const hiddenMessages = findHiddenMessages(text);
1123
+ // Stage 0 — AI chat citation markers. Runs before the character pass,
1124
+ // which would otherwise delete their private-use delimiters and leave the
1125
+ // visible "citeturn0search0" text behind.
1126
+ const artifactRows = [];
1127
+ if (o.removeChatArtifacts) {
1128
+ const artifacts = stripChatArtifactsStage(text);
1129
+ text = artifacts.out;
1130
+ artifactRows.push(...artifacts.rows);
1131
+ }
1132
+ // A soft hyphen at a line end marks a word the PDF split across two lines.
1133
+ // Stage 1 would delete it and leave "hyph" + newline + "enation", so when
1134
+ // lines are being joined, rejoin those words first.
1135
+ let softHyphensRejoined = 0;
1136
+ if (o.joinLines) {
1137
+ text = text.replace(/\u00AD[ \t]*\r?\n[ \t]*(?=\p{Ll})/gu, () => {
1138
+ softHyphensRejoined++;
1139
+ return "";
1140
+ });
1141
+ }
1142
+ // Stage 1 — detect on the ORIGINAL text and apply per-character strips.
1143
+ const pass = runCharacterPass(text, o);
1144
+ let cleaned = pass.out;
1145
+ // Stage 2 — Unicode normalization (NFKC), shielding characters whose
1146
+ // dedicated toggle is off so it never silently undercuts a choice. Every
1147
+ // fold it performs is reported.
1148
+ let unicodeNormalized = 0;
1149
+ if (o.normalizeUnicode) {
1150
+ const shield = buildNfkcShield(o);
1151
+ // Characters actually used as emoji keep their emoji identity: NFKC would
1152
+ // otherwise fold "™️" (U+2122 U+FE0F) to "TM" and "ℹ️" to "i".
1153
+ for (const cp of pass.emojiBases)
1154
+ shield.add(cp);
1155
+ const nfkc = nfkcStage(cleaned, shield, TYPOGRAPHY_CPS);
1156
+ cleaned = nfkc.out;
1157
+ for (const [cp, change] of nfkc.changes) {
1158
+ unicodeNormalized += change.count;
1159
+ normalizationRows.push({
1160
+ codepoint: formatCodepoint(cp),
1161
+ name: SINGLE_NAMES[cp] ?? `Compatibility character "${String.fromCodePoint(cp)}"`,
1162
+ count: change.count,
1163
+ category: "normalization",
1164
+ action: "replaced",
1165
+ note: `Unicode NFKC rewrites this as "${change.to}"`,
1166
+ });
1167
+ }
1168
+ if (nfkc.composed) {
1169
+ unicodeNormalized += 1;
1170
+ normalizationRows.push({
1171
+ codepoint: "NFKC",
1172
+ name: "Unicode normalization (NFKC)",
1173
+ count: 1,
1174
+ category: "normalization",
1175
+ action: "replaced",
1176
+ note: "Combining marks were composed into their precomposed equivalents",
1177
+ });
1178
+ }
1179
+ }
1180
+ // Stage 3 — whitespace normalization.
1181
+ const whitespaceCounts = emptyWhitespaceCounts();
1182
+ if (o.normalizeWhitespace) {
1183
+ const ws = normalizeWhitespaceStage(cleaned);
1184
+ cleaned = ws.out;
1185
+ addWhitespaceCounts(whitespaceCounts, ws.counts);
1186
+ }
1187
+ // Stage 4 — typography normalization (also forced under Plain ASCII so
1188
+ // smart quotes transliterate instead of being deleted).
1189
+ if (o.normalizeTypography || o.plainAscii) {
1190
+ cleaned = normalizeTypographyStage(cleaned);
1191
+ }
1192
+ // Stage 5 — optional Markdown residue strip.
1193
+ let markdownArtifactsRemoved = 0;
1194
+ if (o.stripMarkdown) {
1195
+ const md = stripMarkdownStage(cleaned);
1196
+ cleaned = md.out;
1197
+ markdownArtifactsRemoved = md.removed;
1198
+ }
1199
+ // Stage 5b — optional joining of hard-wrapped lines (runs after Markdown
1200
+ // stripping so list markers are judged on the text the user will get).
1201
+ let linesJoined = 0;
1202
+ if (o.joinLines) {
1203
+ const jl = joinLinesStage(cleaned);
1204
+ cleaned = jl.out;
1205
+ linesJoined = jl.joined + jl.hyphensRejoined + softHyphensRejoined;
1206
+ if (softHyphensRejoined > 0) {
1207
+ normalizationRows.push({
1208
+ codepoint: "U+00AD",
1209
+ name: "Soft hyphen at line end",
1210
+ count: softHyphensRejoined,
1211
+ category: "normalization",
1212
+ action: "removed",
1213
+ note: "Word split across two lines rejoined",
1214
+ });
1215
+ }
1216
+ if (jl.joined > 0) {
1217
+ normalizationRows.push({
1218
+ codepoint: "U+000A",
1219
+ name: "Wrapped line break",
1220
+ count: jl.joined,
1221
+ category: "normalization",
1222
+ action: "replaced",
1223
+ note: "Line break inside a paragraph joined with a space",
1224
+ });
1225
+ }
1226
+ if (jl.hyphensRejoined > 0) {
1227
+ normalizationRows.push({
1228
+ codepoint: "U+002D",
1229
+ name: "Hyphen at line end",
1230
+ count: jl.hyphensRejoined,
1231
+ category: "normalization",
1232
+ action: "removed",
1233
+ note: "Word split across two lines rejoined. Check real hyphenated words such as well-known",
1234
+ });
1235
+ }
1236
+ }
1237
+ // Stage 6 — optional aggressive ASCII projection. Deleting non-ASCII
1238
+ // characters leaves new trailing spaces and blank lines behind, so the
1239
+ // whitespace pass runs again over its output (keeping the tool idempotent).
1240
+ if (o.plainAscii) {
1241
+ cleaned = plainAsciiStage(cleaned);
1242
+ if (o.normalizeWhitespace) {
1243
+ const ws = normalizeWhitespaceStage(cleaned);
1244
+ cleaned = ws.out;
1245
+ addWhitespaceCounts(whitespaceCounts, ws.counts);
1246
+ }
1247
+ }
1248
+ normalizationRows.push(...whitespaceDetections(whitespaceCounts));
1249
+ // Build the detection report.
1250
+ const detections = [];
1251
+ for (const occ of pass.occurrences.values()) {
1252
+ detections.push({
1253
+ codepoint: formatCodepoint(occ.cp),
1254
+ name: codepointName(occ.cp),
1255
+ count: occ.count,
1256
+ category: occ.category,
1257
+ action: occ.action,
1258
+ note: occ.emojiKept ? EMOJI_KEPT_NOTE : codepointNote(occ.cp),
1259
+ });
1260
+ }
1261
+ for (const [cp, count] of pass.typographyCounts) {
1262
+ detections.push({
1263
+ codepoint: formatCodepoint(cp),
1264
+ name: codepointName(cp),
1265
+ count,
1266
+ category: "typography",
1267
+ action: "replaced",
1268
+ note: codepointNote(cp),
1269
+ });
1270
+ }
1271
+ detections.push(...artifactRows);
1272
+ detections.push(...normalizationRows);
1273
+ // Most frequent first; on a tie, character findings outrank formatting ones.
1274
+ const rank = (d) => (d.category === "normalization" ? 1 : 0);
1275
+ detections.sort((a, b) => b.count - a.count || rank(a) - rank(b) || a.codepoint.localeCompare(b.codepoint));
1276
+ // Aggregate stats (legacy fields + new totals).
1277
+ const stats = {
1278
+ invisibleCharactersRemoved: 0,
1279
+ directionalMarkersRemoved: 0,
1280
+ nbspConverted: 0,
1281
+ quotesDashesNormalized: 0,
1282
+ blankLinesCollapsed: whitespaceCounts.blankLinesCollapsed,
1283
+ aiArtifactsRemoved: 0,
1284
+ controlCharactersRemoved: 0,
1285
+ markdownArtifactsRemoved,
1286
+ unicodeNormalized,
1287
+ whitespaceNormalized: whitespaceTotal(whitespaceCounts),
1288
+ linesJoined,
1289
+ };
1290
+ for (const d of detections) {
1291
+ if (d.action === "kept")
1292
+ continue;
1293
+ switch (d.category) {
1294
+ case "invisible":
1295
+ stats.invisibleCharactersRemoved += d.count;
1296
+ break;
1297
+ case "bidi":
1298
+ stats.directionalMarkersRemoved += d.count;
1299
+ break;
1300
+ case "space":
1301
+ stats.nbspConverted += d.count;
1302
+ break;
1303
+ case "typography":
1304
+ stats.quotesDashesNormalized += d.count;
1305
+ break;
1306
+ case "ai-artifact":
1307
+ case "chat-artifact":
1308
+ case "tag":
1309
+ case "variation-selector":
1310
+ stats.aiArtifactsRemoved += d.count;
1311
+ break;
1312
+ case "control":
1313
+ stats.controlCharactersRemoved += d.count;
1314
+ break;
1315
+ case "normalization":
1316
+ // Counted from the stages themselves (unicodeNormalized /
1317
+ // whitespaceNormalized / blankLinesCollapsed).
1318
+ break;
1319
+ }
1320
+ }
1321
+ return { cleanedText: cleaned, stats, detections, hiddenMessages };
1322
+ }
1323
+ /**
1324
+ * Scans text for hidden characters and AI watermark artifacts without
1325
+ * transforming it. Actions reflect what the recommended "AI Clean" preset
1326
+ * would do; characters it keeps (emoji parts), visible typography (em dashes,
1327
+ * smart quotes) and formatting-only changes are not reported here, so a
1328
+ * non-empty result always means real hidden characters are present.
1329
+ */
1330
+ export function detectHiddenCharacters(text) {
1331
+ return cleanText(text, PRESETS[DEFAULT_PRESET]).detections.filter((d) => d.action !== "kept" && d.category !== "typography" && d.category !== "normalization");
1332
+ }