react-smart-copy 1.11.0 → 1.13.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/code.js ADDED
@@ -0,0 +1,1169 @@
1
+ //#region src/core/errors.ts
2
+ function createCopyError(type, message, cause) {
3
+ return cause === void 0 ? {
4
+ type,
5
+ message
6
+ } : {
7
+ type,
8
+ message,
9
+ cause
10
+ };
11
+ }
12
+ /**
13
+ * Branded (not `instanceof`) so failures stay recognisable even when the core
14
+ * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
15
+ */
16
+ const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
17
+ /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
18
+ var CopyFailure = class extends Error {
19
+ constructor(copyError) {
20
+ super(copyError.message);
21
+ this[COPY_FAILURE_BRAND] = true;
22
+ this.name = "CopyFailure";
23
+ this.copyError = copyError;
24
+ }
25
+ };
26
+ /** Shorthand for throwing a classified failure. */
27
+ function copyFailure(type, message, cause) {
28
+ return new CopyFailure(createCopyError(type, message, cause));
29
+ }
30
+ //#endregion
31
+ //#region src/code/inspect.ts
32
+ /** Every finding kind, in a stable order. */
33
+ const CODE_FINDING_KINDS = Object.freeze([
34
+ "bidi-control",
35
+ "invisible",
36
+ "control",
37
+ "unusual-space",
38
+ "confusable-punctuation",
39
+ "mixed-script"
40
+ ]);
41
+ const DEFAULT_CODE_MAX_FINDINGS = 1e3;
42
+ const rule = (kind, severity, replacement, name) => ({
43
+ kind,
44
+ severity,
45
+ replacement,
46
+ name
47
+ });
48
+ /** Characters with a fixed verdict. Ranges and context-dependent ones are handled in `classify`. */
49
+ const TABLE = /* @__PURE__ */ new Map([
50
+ [8234, rule("bidi-control", "danger", "", "LEFT-TO-RIGHT EMBEDDING")],
51
+ [8235, rule("bidi-control", "danger", "", "RIGHT-TO-LEFT EMBEDDING")],
52
+ [8236, rule("bidi-control", "danger", "", "POP DIRECTIONAL FORMATTING")],
53
+ [8237, rule("bidi-control", "danger", "", "LEFT-TO-RIGHT OVERRIDE")],
54
+ [8238, rule("bidi-control", "danger", "", "RIGHT-TO-LEFT OVERRIDE")],
55
+ [8294, rule("bidi-control", "danger", "", "LEFT-TO-RIGHT ISOLATE")],
56
+ [8295, rule("bidi-control", "danger", "", "RIGHT-TO-LEFT ISOLATE")],
57
+ [8296, rule("bidi-control", "danger", "", "FIRST STRONG ISOLATE")],
58
+ [8297, rule("bidi-control", "danger", "", "POP DIRECTIONAL ISOLATE")],
59
+ [8206, rule("bidi-control", "warning", "", "LEFT-TO-RIGHT MARK")],
60
+ [8207, rule("bidi-control", "warning", "", "RIGHT-TO-LEFT MARK")],
61
+ [1564, rule("bidi-control", "warning", "", "ARABIC LETTER MARK")],
62
+ [4447, rule("invisible", "danger", "", "HANGUL CHOSEONG FILLER")],
63
+ [4448, rule("invisible", "danger", "", "HANGUL JUNGSEONG FILLER")],
64
+ [12644, rule("invisible", "danger", "", "HANGUL FILLER")],
65
+ [65440, rule("invisible", "danger", "", "HALFWIDTH HANGUL FILLER")],
66
+ [8203, rule("invisible", "warning", "", "ZERO WIDTH SPACE")],
67
+ [8288, rule("invisible", "warning", "", "WORD JOINER")],
68
+ [8289, rule("invisible", "warning", "", "FUNCTION APPLICATION")],
69
+ [8290, rule("invisible", "warning", "", "INVISIBLE TIMES")],
70
+ [8291, rule("invisible", "warning", "", "INVISIBLE SEPARATOR")],
71
+ [8292, rule("invisible", "warning", "", "INVISIBLE PLUS")],
72
+ [65279, rule("invisible", "warning", "", "ZERO WIDTH NO-BREAK SPACE")],
73
+ [173, rule("invisible", "warning", "", "SOFT HYPHEN")],
74
+ [847, rule("invisible", "warning", "", "COMBINING GRAPHEME JOINER")],
75
+ [6158, rule("invisible", "warning", "", "MONGOLIAN VOWEL SEPARATOR")],
76
+ [6068, rule("invisible", "warning", "", "KHMER VOWEL INHERENT AQ")],
77
+ [6069, rule("invisible", "warning", "", "KHMER VOWEL INHERENT AA")],
78
+ [8232, rule("control", "warning", "\n", "LINE SEPARATOR")],
79
+ [8233, rule("control", "warning", "\n", "PARAGRAPH SEPARATOR")],
80
+ [133, rule("control", "warning", "\n", "NEXT LINE")],
81
+ [160, rule("unusual-space", "warning", " ", "NO-BREAK SPACE")],
82
+ [5760, rule("unusual-space", "warning", " ", "OGHAM SPACE MARK")],
83
+ [8239, rule("unusual-space", "warning", " ", "NARROW NO-BREAK SPACE")],
84
+ [8287, rule("unusual-space", "warning", " ", "MEDIUM MATHEMATICAL SPACE")],
85
+ [12288, rule("unusual-space", "warning", " ", "IDEOGRAPHIC SPACE")],
86
+ [8216, rule("confusable-punctuation", "warning", "'", "LEFT SINGLE QUOTATION MARK")],
87
+ [8217, rule("confusable-punctuation", "warning", "'", "RIGHT SINGLE QUOTATION MARK")],
88
+ [8218, rule("confusable-punctuation", "warning", "'", "SINGLE LOW-9 QUOTATION MARK")],
89
+ [8219, rule("confusable-punctuation", "warning", "'", "SINGLE HIGH-REVERSED-9 QUOTATION MARK")],
90
+ [8242, rule("confusable-punctuation", "warning", "'", "PRIME")],
91
+ [700, rule("confusable-punctuation", "warning", "'", "MODIFIER LETTER APOSTROPHE")],
92
+ [8220, rule("confusable-punctuation", "warning", "\"", "LEFT DOUBLE QUOTATION MARK")],
93
+ [8221, rule("confusable-punctuation", "warning", "\"", "RIGHT DOUBLE QUOTATION MARK")],
94
+ [8222, rule("confusable-punctuation", "warning", "\"", "DOUBLE LOW-9 QUOTATION MARK")],
95
+ [8223, rule("confusable-punctuation", "warning", "\"", "DOUBLE HIGH-REVERSED-9 QUOTATION MARK")],
96
+ [8243, rule("confusable-punctuation", "warning", "\"", "DOUBLE PRIME")],
97
+ [8208, rule("confusable-punctuation", "warning", "-", "HYPHEN")],
98
+ [8209, rule("confusable-punctuation", "warning", "-", "NON-BREAKING HYPHEN")],
99
+ [8210, rule("confusable-punctuation", "warning", "-", "FIGURE DASH")],
100
+ [8211, rule("confusable-punctuation", "warning", "-", "EN DASH")],
101
+ [8722, rule("confusable-punctuation", "warning", "-", "MINUS SIGN")],
102
+ [8212, rule("confusable-punctuation", "warning", "--", "EM DASH")],
103
+ [8213, rule("confusable-punctuation", "warning", "--", "HORIZONTAL BAR")],
104
+ [8230, rule("confusable-punctuation", "warning", "...", "HORIZONTAL ELLIPSIS")],
105
+ [8260, rule("confusable-punctuation", "warning", "/", "FRACTION SLASH")],
106
+ [8725, rule("confusable-punctuation", "warning", "/", "DIVISION SLASH")],
107
+ [894, rule("confusable-punctuation", "warning", ";", "GREEK QUESTION MARK")]
108
+ ]);
109
+ const LOOKALIKES = /* @__PURE__ */ new Map(/* @__PURE__ */ [
110
+ [1072, "a"],
111
+ [1077, "e"],
112
+ [1110, "i"],
113
+ [1112, "j"],
114
+ [1086, "o"],
115
+ [1088, "p"],
116
+ [1089, "c"],
117
+ [1091, "y"],
118
+ [1093, "x"],
119
+ [1109, "s"],
120
+ [1281, "d"],
121
+ [1307, "q"],
122
+ [1309, "w"],
123
+ [1211, "h"],
124
+ [1231, "l"],
125
+ [1040, "A"],
126
+ [1042, "B"],
127
+ [1045, "E"],
128
+ [1050, "K"],
129
+ [1052, "M"],
130
+ [1053, "H"],
131
+ [1054, "O"],
132
+ [1056, "P"],
133
+ [1057, "C"],
134
+ [1058, "T"],
135
+ [1061, "X"],
136
+ [1059, "Y"],
137
+ [1030, "I"],
138
+ [1032, "J"],
139
+ [1029, "S"],
140
+ [1280, "D"],
141
+ [1306, "Q"],
142
+ [1308, "W"],
143
+ [1210, "H"],
144
+ [1216, "I"],
145
+ [945, "a"],
146
+ [959, "o"],
147
+ [957, "v"],
148
+ [961, "p"],
149
+ [953, "i"],
150
+ [965, "u"],
151
+ [967, "x"],
152
+ [913, "A"],
153
+ [914, "B"],
154
+ [917, "E"],
155
+ [918, "Z"],
156
+ [919, "H"],
157
+ [921, "I"],
158
+ [922, "K"],
159
+ [924, "M"],
160
+ [925, "N"],
161
+ [927, "O"],
162
+ [929, "P"],
163
+ [932, "T"],
164
+ [933, "Y"],
165
+ [935, "X"]
166
+ ].map(([codePoint, latin]) => [String.fromCharCode(codePoint), latin]));
167
+ const LATIN = /\p{Script=Latin}/u;
168
+ const FOREIGN = /[\p{Script=Cyrillic}\p{Script=Greek}]/u;
169
+ const FOREIGN_LETTER = /^[\p{Script=Cyrillic}\p{Script=Greek}]$/u;
170
+ /** Identifier-like runs: letters, marks, digits, `_` and `$`. */
171
+ const WORD = /[\p{L}\p{M}\p{Nd}_$]+/gu;
172
+ /** Joiners are part of emoji sequences and of Arabic and Indic spelling. */
173
+ const JOINS = /[\p{L}\p{M}\p{Extended_Pictographic}]/u;
174
+ const JOINS_ASCII = /[\0-\x7f]/;
175
+ const CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u3000-\u303f\uff00-\uffef]/u;
176
+ /** A character with a glyph: not a space, a control or a format character. */
177
+ const VISIBLE = /^[^\s\p{Cc}\p{Cf}\p{Zs}]/u;
178
+ const hex = (codePoint) => `U+${codePoint.toString(16).toUpperCase().padStart(4, "0")}`;
179
+ const isSelector = (codePoint) => codePoint >= 65024 && codePoint <= 65039 || codePoint >= 917760 && codePoint <= 917999;
180
+ const joinsHere = (char) => char !== void 0 && !JOINS_ASCII.test(char) && JOINS.test(char);
181
+ /** The verdict for one character, given its neighbours (code points, `undefined` at the text's edges). */
182
+ function classify(codePoint, before, after) {
183
+ const fixed = TABLE.get(codePoint);
184
+ if (fixed !== void 0) return fixed;
185
+ if (codePoint === 8204 || codePoint === 8205) {
186
+ const charBefore = before === void 0 ? void 0 : String.fromCodePoint(before);
187
+ const charAfter = after === void 0 ? void 0 : String.fromCodePoint(after);
188
+ if (joinsHere(charBefore) && joinsHere(charAfter)) return null;
189
+ return rule("invisible", "warning", "", codePoint === 8204 ? "ZERO WIDTH NON-JOINER" : "ZERO WIDTH JOINER");
190
+ }
191
+ if (isSelector(codePoint)) {
192
+ const base = before === void 0 ? "" : String.fromCodePoint(before);
193
+ if (VISIBLE.test(base) && !isSelector(before) && (after === void 0 || !isSelector(after))) return null;
194
+ return rule("invisible", "warning", "", "VARIATION SELECTOR");
195
+ }
196
+ if (codePoint >= 917504 && codePoint <= 917631) return rule("invisible", "danger", "", "TAG CHARACTER");
197
+ if (codePoint === 9 || codePoint === 10 || codePoint === 12 || codePoint === 13) return null;
198
+ if (codePoint < 32 || codePoint >= 127 && codePoint <= 159) return rule("control", "warning", "", "CONTROL CHARACTER");
199
+ if (codePoint >= 8192 && codePoint <= 8202) return rule("unusual-space", "warning", " ", "SPACE");
200
+ if (codePoint >= 65281 && codePoint <= 65374) {
201
+ const charBefore = before === void 0 ? "" : String.fromCodePoint(before);
202
+ const charAfter = after === void 0 ? "" : String.fromCodePoint(after);
203
+ if (CJK.test(charBefore) || CJK.test(charAfter)) return null;
204
+ return rule("confusable-punctuation", "warning", String.fromCharCode(codePoint - 65248), "FULLWIDTH FORM");
205
+ }
206
+ return null;
207
+ }
208
+ const ALL = /* @__PURE__ */ new Set(CODE_FINDING_KINDS);
209
+ function kindSet(kinds, name) {
210
+ if (kinds === void 0) return ALL;
211
+ if (!Array.isArray(kinds) || !kinds.every((kind) => ALL.has(kind))) throw copyFailure("invalid-payload", `\`${name}\` must be a list of: ${CODE_FINDING_KINDS.join(", ")}.`);
212
+ return new Set(kinds);
213
+ }
214
+ /** Every suspicious character in `text`, in order of position. Stops once `limit` are found. */
215
+ function scan(text, kinds, limit) {
216
+ const found = [];
217
+ let before;
218
+ for (let index = 0; index < text.length && found.length < limit;) {
219
+ const codePoint = text.codePointAt(index);
220
+ const length = codePoint > 65535 ? 2 : 1;
221
+ if (codePoint < 32 || codePoint >= 127) {
222
+ const verdict = classify(codePoint, before, text.codePointAt(index + length));
223
+ if (verdict !== null && kinds.has(verdict.kind)) found.push({
224
+ index,
225
+ length,
226
+ codePoint,
227
+ rule: verdict
228
+ });
229
+ }
230
+ before = codePoint;
231
+ index += length;
232
+ }
233
+ if (kinds.has("mixed-script") && FOREIGN.test(text)) {
234
+ const mixed = [];
235
+ for (const match of text.matchAll(WORD)) {
236
+ const word = match[0];
237
+ if (!LATIN.test(word) || !FOREIGN.test(word)) continue;
238
+ let offset = 0;
239
+ for (const char of word) {
240
+ if (FOREIGN_LETTER.test(char)) {
241
+ const lookalike = LOOKALIKES.get(char);
242
+ const codePoint = char.codePointAt(0);
243
+ mixed.push({
244
+ index: match.index + offset,
245
+ length: char.length,
246
+ codePoint,
247
+ rule: lookalike === void 0 ? rule("mixed-script", "warning", null, "NON-LATIN LETTER IN A LATIN WORD") : rule("mixed-script", "danger", lookalike, `LOOKALIKE OF "${lookalike}"`)
248
+ });
249
+ }
250
+ offset += char.length;
251
+ }
252
+ }
253
+ return merge(found, mixed).slice(0, limit);
254
+ }
255
+ return found;
256
+ }
257
+ function merge(a, b) {
258
+ if (b.length === 0) return [...a];
259
+ const out = [];
260
+ let i = 0;
261
+ let j = 0;
262
+ while (i < a.length || j < b.length) {
263
+ const next = j >= b.length || i < a.length && a[i].index < b[j].index ? a[i++] : b[j++];
264
+ out.push(next);
265
+ }
266
+ return out;
267
+ }
268
+ /** Offsets where each line starts. */
269
+ function lineStarts(text) {
270
+ const starts = [0];
271
+ for (let index = 0; index < text.length; index += 1) {
272
+ const char = text.charCodeAt(index);
273
+ if (char === 10 || char === 13 && text.charCodeAt(index + 1) !== 10) starts.push(index + 1);
274
+ }
275
+ return starts;
276
+ }
277
+ function toFindings(text, raw) {
278
+ if (raw.length === 0) return [];
279
+ const starts = lineStarts(text);
280
+ return raw.map(({ index, length, codePoint, rule: { kind, severity, replacement, name } }) => {
281
+ let low = 0;
282
+ let high = starts.length - 1;
283
+ while (low < high) {
284
+ const mid = low + high + 1 >> 1;
285
+ if (starts[mid] <= index) low = mid;
286
+ else high = mid - 1;
287
+ }
288
+ return {
289
+ kind,
290
+ severity,
291
+ index,
292
+ length,
293
+ line: low + 1,
294
+ column: index - starts[low] + 1,
295
+ codePoint,
296
+ label: `${hex(codePoint)} ${name}`,
297
+ replacement
298
+ };
299
+ });
300
+ }
301
+ function positiveLimit(value, fallback, name) {
302
+ if (value === void 0) return fallback;
303
+ if (value === Infinity || Number.isInteger(value) && value > 0) return value;
304
+ throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
305
+ }
306
+ /**
307
+ * Finds characters that make code read differently from how it runs, or that a
308
+ * copy through a word processor or chat app slipped in: bidirectional overrides
309
+ * (Trojan Source), invisible characters and identifiers, control characters,
310
+ * unusual spaces, curly quotes and dashes, and Cyrillic or Greek lookalikes inside
311
+ * Latin words. Works anywhere, including on the server.
312
+ *
313
+ * @example
314
+ * const { danger, findings } = inspectCode(pasted);
315
+ * if (danger) warn(findings.map((f) => `${f.line}:${f.column} ${f.label}`));
316
+ */
317
+ function inspectCode(code, options = {}) {
318
+ const kinds = kindSet(options.kinds, "kinds");
319
+ const max = positiveLimit(options.maxFindings, DEFAULT_CODE_MAX_FINDINGS, "maxFindings");
320
+ const raw = scan(code, kinds, max === Infinity ? Infinity : max + 1);
321
+ const truncated = raw.length > max;
322
+ const findings = toFindings(code, truncated ? raw.slice(0, max) : raw);
323
+ return {
324
+ findings,
325
+ danger: findings.some((finding) => finding.severity === "danger"),
326
+ truncated
327
+ };
328
+ }
329
+ /** Applies the replacement of each (fixable) finding, from the end so earlier offsets stay valid. */
330
+ function applyFixes(text, fixable) {
331
+ let out = text;
332
+ for (let at = fixable.length - 1; at >= 0; at -= 1) {
333
+ const { index, length, rule: verdict } = fixable[at];
334
+ out = out.slice(0, index) + verdict.replacement + out.slice(index + length);
335
+ }
336
+ return out;
337
+ }
338
+ const fixableIn = (text, kinds) => scan(text, kinds, Infinity).filter((finding) => finding.rule.replacement !== null);
339
+ /**
340
+ * Maps an offset in the text after `fixes` back to the text they were applied to.
341
+ * The offset is never inside a replacement: replacements are ASCII (or a line
342
+ * feed), which is never suspicious, so a later pass can't find anything in them.
343
+ */
344
+ function beforeFixes(index, fixes) {
345
+ let shift = 0;
346
+ for (const { index: at, length, rule: verdict } of fixes) {
347
+ if (index < at + shift) break;
348
+ shift += verdict.replacement.length - length;
349
+ }
350
+ return index - shift;
351
+ }
352
+ /**
353
+ * Fixes until nothing fixable is left: removing a character can expose another
354
+ * finding (a zero-width space between `a` and a Cyrillic letter hides a mixed
355
+ * word). Every pass removes or replaces suspicious characters with ASCII, which is
356
+ * never suspicious, so this ends. Returns what was fixed, positioned in `text`.
357
+ */
358
+ function fixAll(text, kinds) {
359
+ const passes = [];
360
+ let out = text;
361
+ for (let fixable = fixableIn(out, kinds); fixable.length > 0; fixable = fixableIn(out, kinds)) {
362
+ passes.push(fixable);
363
+ out = applyFixes(out, fixable);
364
+ }
365
+ const fixed = passes.flatMap((found, pass) => found.map((finding) => {
366
+ let index = finding.index;
367
+ for (let earlier = pass - 1; earlier >= 0; earlier -= 1) index = beforeFixes(index, passes[earlier]);
368
+ return {
369
+ ...finding,
370
+ index
371
+ };
372
+ }));
373
+ return {
374
+ text: out,
375
+ fixed: fixed.sort((x, y) => x.index - y.index)
376
+ };
377
+ }
378
+ /**
379
+ * Replaces what {@link inspectCode} finds with safe ASCII: removes bidi controls,
380
+ * invisible and control characters, turns unusual spaces into spaces, curly quotes
381
+ * and dashes into `'` `"` `-`, and lookalike letters into the Latin letters they
382
+ * imitate. Letters with no lookalike are reported in `remaining`, never guessed.
383
+ *
384
+ * @example
385
+ * cleanCode('const s = \u201Chi\u201D;').code; // 'const s = "hi";'
386
+ */
387
+ function cleanCode(code, options = {}) {
388
+ const kinds = kindSet(options.kinds, "kinds");
389
+ const { text, fixed } = fixAll(code, kinds);
390
+ return {
391
+ code: text,
392
+ fixed: toFindings(code, fixed),
393
+ remaining: toFindings(text, scan(text, kinds, Infinity))
394
+ };
395
+ }
396
+ //#endregion
397
+ //#region src/code/lines.ts
398
+ /** Line breaks: CRLF, LF, CR, and the Unicode line and paragraph separators and NEL. */
399
+ const BREAK = /\r\n|[\n\r\u2028\u2029\u0085]/;
400
+ const lineText = (line) => line.map((run) => run.text).join("");
401
+ /** Splits runs into lines. */
402
+ function toLines(runs) {
403
+ const lines = [[]];
404
+ let carriageReturn = false;
405
+ for (const run of runs) {
406
+ const text = carriageReturn && run.text.startsWith("\n") ? run.text.slice(1) : run.text;
407
+ if (run.text !== "") carriageReturn = run.text.endsWith("\r");
408
+ text.split(BREAK).forEach((part, at) => {
409
+ if (at > 0) lines.push([]);
410
+ if (part !== "") lines[lines.length - 1].push({
411
+ text: part,
412
+ style: run.style
413
+ });
414
+ });
415
+ }
416
+ return lines;
417
+ }
418
+ /** The characters of a line from `from` to `to` (UTF-16 offsets), with their styles. */
419
+ function slice(line, from, to = Infinity) {
420
+ const out = [];
421
+ let offset = 0;
422
+ for (const run of line) {
423
+ const start = Math.max(from - offset, 0);
424
+ const end = Math.min(to - offset, run.text.length);
425
+ if (start < end) out.push(start === 0 && end === run.text.length ? run : {
426
+ text: run.text.slice(start, end),
427
+ style: run.style
428
+ });
429
+ offset += run.text.length;
430
+ }
431
+ return out;
432
+ }
433
+ /** Applies non-overlapping replacements of at least one character, sorted by `index`; the new text keeps the style of what it replaces. */
434
+ function edit(line, edits) {
435
+ if (edits.length === 0) return line;
436
+ const out = [];
437
+ let at = 0;
438
+ for (const { index, length, text } of edits) {
439
+ out.push(...slice(line, at, index));
440
+ if (text !== "") out.push({
441
+ text,
442
+ style: slice(line, index, index + length)[0].style
443
+ });
444
+ at = index + length;
445
+ }
446
+ out.push(...slice(line, at));
447
+ return out;
448
+ }
449
+ //#endregion
450
+ //#region src/code/normalize.ts
451
+ /** Every built-in prompt style. `'auto'` tries all but `node`, whose `> ` is too common to guess. */
452
+ const PROMPT_STYLES = Object.freeze([
453
+ "shell",
454
+ "powershell",
455
+ "cmd",
456
+ "python",
457
+ "ipython",
458
+ "node"
459
+ ]);
460
+ const PROMPTS = {
461
+ shell: {
462
+ command: /^(?:\([^()\s]{1,64}\) )?(?:[\w.-]{1,64}@[\w.-]{1,253}:?)?(?:[~/][^\s$]{0,1024})? ?\$(?: |$)/,
463
+ continuation: null,
464
+ shell: true
465
+ },
466
+ powershell: {
467
+ command: /^PS(?: [^>\r\n]{0,1024})?> ?/,
468
+ continuation: /^>> ?/,
469
+ shell: false
470
+ },
471
+ cmd: {
472
+ command: /^[A-Za-z]:\\[^>\r\n]{0,1024}> ?/,
473
+ continuation: /^More\? ?/,
474
+ shell: false
475
+ },
476
+ python: {
477
+ command: /^>>>(?: |$)/,
478
+ continuation: /^\.\.\.(?: |$)/,
479
+ shell: false
480
+ },
481
+ ipython: {
482
+ command: /^In \[\d{0,9}\]: ?/,
483
+ continuation: /^ {0,64}\.{3,}: ?/,
484
+ shell: false
485
+ },
486
+ node: {
487
+ command: /^>(?: |$)/,
488
+ continuation: /^\.\.\.(?: |$)/,
489
+ shell: false
490
+ }
491
+ };
492
+ const AUTO = [
493
+ "powershell",
494
+ "cmd",
495
+ "ipython",
496
+ "python",
497
+ "shell"
498
+ ];
499
+ /** A user pattern without `g` / `y`, so `exec` is stateless. */
500
+ function stateless(pattern, name) {
501
+ if (!(pattern instanceof RegExp)) throw copyFailure("invalid-payload", `\`prompt.${name}\` must be a RegExp.`);
502
+ return new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""));
503
+ }
504
+ function resolvePrompt(prompt, fallback) {
505
+ const value = prompt ?? fallback;
506
+ if (value === false) return null;
507
+ if (value === "auto") return "auto";
508
+ if (typeof value === "string") {
509
+ if (!Object.prototype.hasOwnProperty.call(PROMPTS, value)) throw copyFailure("invalid-payload", `\`prompt\` must be 'auto', false, a PromptPattern or one of: ${PROMPT_STYLES.join(", ")}.`);
510
+ return PROMPTS[value];
511
+ }
512
+ if (typeof value !== "object" || value === null) throw copyFailure("invalid-payload", `\`prompt\` must be 'auto', false, a PromptPattern or one of: ${PROMPT_STYLES.join(", ")}.`);
513
+ return {
514
+ command: stateless(value.command, "command"),
515
+ continuation: value.continuation === void 0 ? null : stateless(value.continuation, "continuation"),
516
+ shell: false
517
+ };
518
+ }
519
+ /** The length of the prompt at the start of `text`, or -1. */
520
+ function promptLength(pattern, text) {
521
+ const match = pattern.exec(text);
522
+ return match?.index === 0 ? match[0].length : -1;
523
+ }
524
+ const HEREDOC = /<<-?[ \t]*(['"]?)([A-Za-z_][\w-]{0,63})\1/;
525
+ function readShell(text, state) {
526
+ if (state.heredoc !== null) {
527
+ if (text.replace(/^\t+/, "") === state.heredoc) state.heredoc = null;
528
+ state.escaped = false;
529
+ return;
530
+ }
531
+ let escaped = false;
532
+ for (let at = 0; at < text.length; at += 1) {
533
+ const char = text.charAt(at);
534
+ if (escaped) escaped = false;
535
+ else if (char === "\\" && state.quote !== "'") escaped = true;
536
+ else if (state.quote === null && (char === "\"" || char === "'")) state.quote = char;
537
+ else if (char === state.quote) state.quote = null;
538
+ else if (state.quote !== null) continue;
539
+ else if (char === "#") break;
540
+ else if (char === "<" && state.heredoc === null) {
541
+ const heredoc = HEREDOC.exec(text.slice(at));
542
+ if (heredoc?.index === 0) state.heredoc = heredoc[2];
543
+ }
544
+ }
545
+ state.escaped = escaped;
546
+ }
547
+ const continues = (state) => state.escaped || state.quote !== null || state.heredoc !== null;
548
+ function firstNonBlank(lines) {
549
+ for (const line of lines) {
550
+ const text = lineText(line);
551
+ if (text.trim() !== "") return text;
552
+ }
553
+ return "";
554
+ }
555
+ /** Keeps the commands of a session, without prompts; drops its output. */
556
+ function stripPrompts(lines, setting) {
557
+ let prompt;
558
+ if (setting === "auto") {
559
+ const first = firstNonBlank(lines);
560
+ const style = AUTO.find((name) => promptLength(PROMPTS[name].command, first) >= 0);
561
+ if (style === void 0) return [...lines];
562
+ prompt = PROMPTS[style];
563
+ } else prompt = setting;
564
+ const out = [];
565
+ const shell = {
566
+ quote: null,
567
+ heredoc: null,
568
+ escaped: false
569
+ };
570
+ let inCommand = false;
571
+ /** Shell continuation lines carry a `> ` prompt (PS2) when the first one does. */
572
+ let ps2 = null;
573
+ for (const line of lines) {
574
+ const text = lineText(line);
575
+ if (prompt.shell && continues(shell)) {
576
+ if (ps2 === null) ps2 = /^>(?: |$)/.test(text);
577
+ const rest = slice(line, ps2 ? text.startsWith("> ") ? 2 : text === ">" ? 1 : 0 : 0);
578
+ out.push(rest);
579
+ readShell(lineText(rest), shell);
580
+ continue;
581
+ }
582
+ const command = promptLength(prompt.command, text);
583
+ if (command >= 0) {
584
+ const rest = slice(line, command);
585
+ out.push(rest);
586
+ inCommand = true;
587
+ ps2 = null;
588
+ if (prompt.shell) readShell(lineText(rest), shell);
589
+ continue;
590
+ }
591
+ const continuation = inCommand && prompt.continuation !== null ? promptLength(prompt.continuation, text) : -1;
592
+ if (continuation >= 0) {
593
+ out.push(slice(line, continuation));
594
+ continue;
595
+ }
596
+ inCommand = false;
597
+ }
598
+ return out;
599
+ }
600
+ const DIFF_HEADER = /^(?:diff |index |--- |\+\+\+ |new file mode|deleted file mode|old mode|new mode|similarity index|dissimilarity index|rename from|rename to|copy from|copy to|Binary files)/;
601
+ /** Keeps one side of a unified diff, without the `+`, `-` and space markers. */
602
+ function pickSide(lines, side) {
603
+ const keep = side === "after" ? "+" : "-";
604
+ const drop = side === "after" ? "-" : "+";
605
+ const out = [];
606
+ let header = /^(?:diff |--- |index )/.test(firstNonBlank(lines));
607
+ for (const line of lines) {
608
+ const text = lineText(line);
609
+ if (text.startsWith("diff --git ")) header = true;
610
+ if (header) {
611
+ if (text.startsWith("@@")) header = false;
612
+ else if (DIFF_HEADER.test(text) || text.trim() === "") continue;
613
+ else header = false;
614
+ }
615
+ if (text.startsWith("@@") || text.startsWith("\\ ")) continue;
616
+ const marker = text.charAt(0);
617
+ if (marker === drop) continue;
618
+ out.push(marker === keep || marker === " " ? slice(line, 1) : line);
619
+ }
620
+ return out;
621
+ }
622
+ const NUMBERED = /^[ \t]*(\d{1,9})(?:[ \t]*[:|\u2502](?: |$)|[ \t]+|$)/;
623
+ function stripLineNumbers(lines) {
624
+ const cuts = [];
625
+ let expected = null;
626
+ for (const line of lines) {
627
+ const match = NUMBERED.exec(lineText(line));
628
+ if (match === null) return [...lines];
629
+ const number = Number(match[1]);
630
+ if (expected !== null && number !== expected) return [...lines];
631
+ expected = number + 1;
632
+ cuts.push(match[0].length);
633
+ }
634
+ if (cuts.length < 2) return [...lines];
635
+ return lines.map((line, at) => slice(line, cuts[at]));
636
+ }
637
+ function trimEnd(line) {
638
+ const text = lineText(line);
639
+ const end = text.replace(/[ \t]+$/, "").length;
640
+ return end === text.length ? line : slice(line, 0, end);
641
+ }
642
+ function dedentLines(lines) {
643
+ let common = null;
644
+ for (const line of lines) {
645
+ const text = lineText(line);
646
+ if (text.trim() === "") continue;
647
+ const indent = /^[ \t]*/.exec(text)?.[0];
648
+ if (common === null) common = indent;
649
+ else {
650
+ let shared = 0;
651
+ while (shared < common.length && shared < indent.length && common[shared] === indent[shared]) shared += 1;
652
+ common = common.slice(0, shared);
653
+ }
654
+ if (common === "") return [...lines];
655
+ }
656
+ if (common === null) return [...lines];
657
+ const width = common.length;
658
+ return lines.map((line) => slice(line, Math.min(width, /^[ \t]*/.exec(lineText(line))?.[0].length)));
659
+ }
660
+ const oneOf = (value, allowed, fallback, name) => {
661
+ if (value === void 0) return fallback;
662
+ if (allowed.includes(value)) return value;
663
+ throw copyFailure("invalid-payload", `\`${name}\` must be one of: ${allowed.map((option) => JSON.stringify(option)).join(", ")}.`);
664
+ };
665
+ const flag = (value, fallback, name) => oneOf(value, [true, false], fallback, name);
666
+ function resolveText(options, defaults) {
667
+ const clean = options.clean ?? defaults.clean;
668
+ return {
669
+ prompt: resolvePrompt(options.prompt, defaults.prompt),
670
+ diff: oneOf(options.diff, [
671
+ false,
672
+ "after",
673
+ "before"
674
+ ], false, "diff") || null,
675
+ lineNumbers: flag(options.lineNumbers, false, "lineNumbers"),
676
+ dedent: flag(options.dedent, true, "dedent"),
677
+ trimTrailingWhitespace: flag(options.trimTrailingWhitespace, true, "trimTrailingWhitespace"),
678
+ trimBlankLines: flag(options.trimBlankLines, true, "trimBlankLines"),
679
+ eol: oneOf(options.lineEnding, ["lf", "crlf"], "lf", "lineEnding") === "crlf" ? "\r\n" : "\n",
680
+ finalNewline: flag(options.finalNewline, false, "finalNewline"),
681
+ clean: clean === false ? null : kindSet(clean === true ? void 0 : clean, "clean")
682
+ };
683
+ }
684
+ function transform(input, options) {
685
+ let lines = [...input];
686
+ let fixed = 0;
687
+ const kinds = options.clean;
688
+ if (kinds !== null) lines = lines.map((line) => {
689
+ const { fixed: found } = fixAll(lineText(line), kinds);
690
+ fixed += found.length;
691
+ return edit(line, found.map(({ index, length, rule: { replacement } }) => ({
692
+ index,
693
+ length,
694
+ text: replacement
695
+ })));
696
+ });
697
+ if (options.diff !== null) lines = pickSide(lines, options.diff);
698
+ if (options.prompt !== null) lines = stripPrompts(options.dedent ? dedentLines(lines) : lines, options.prompt);
699
+ if (options.lineNumbers) lines = stripLineNumbers(lines);
700
+ if (options.trimTrailingWhitespace) lines = lines.map(trimEnd);
701
+ if (options.trimBlankLines) {
702
+ const blank = (line) => lineText(line).trim() === "";
703
+ let start = 0;
704
+ let end = lines.length;
705
+ while (start < end && blank(lines[start])) start += 1;
706
+ while (end > start && blank(lines[end - 1])) end -= 1;
707
+ lines = lines.slice(start, end);
708
+ }
709
+ if (options.dedent) lines = dedentLines(lines);
710
+ return {
711
+ lines,
712
+ fixed
713
+ };
714
+ }
715
+ /** The text of transformed lines. */
716
+ function render(lines, options) {
717
+ const text = lines.map(lineText).join(options.eol);
718
+ return options.finalNewline && text !== "" ? text + options.eol : text;
719
+ }
720
+ /**
721
+ * Code as it should be copied or saved: a terminal session becomes its commands,
722
+ * a diff one side of the change, typed line numbers and shared indentation are
723
+ * removed, line endings are normalised. Works anywhere, including on the server.
724
+ *
725
+ * @example
726
+ * normalizeCode('$ npm install react-smart-copy\nadded 1 package'); // 'npm install react-smart-copy'
727
+ */
728
+ function normalizeCode(code, options = {}) {
729
+ const resolved = resolveText(options, {
730
+ prompt: "auto",
731
+ clean: false
732
+ });
733
+ return render(transform(toLines([{
734
+ text: code,
735
+ style: ""
736
+ }]), resolved).lines, resolved);
737
+ }
738
+ //#endregion
739
+ //#region src/code/element.ts
740
+ /** Never code: scripts, embedded content, form controls (the block's own Copy button) and media. */
741
+ const SKIP = /* @__PURE__ */ new Set([
742
+ "script",
743
+ "style",
744
+ "template",
745
+ "noscript",
746
+ "head",
747
+ "button",
748
+ "input",
749
+ "textarea",
750
+ "select",
751
+ "option",
752
+ "datalist",
753
+ "dialog",
754
+ "svg",
755
+ "math",
756
+ "canvas",
757
+ "iframe",
758
+ "object",
759
+ "embed",
760
+ "img",
761
+ "picture",
762
+ "video",
763
+ "audio",
764
+ "source",
765
+ "track"
766
+ ]);
767
+ /** Elements that start their own line. */
768
+ const BLOCK = /* @__PURE__ */ new Set([
769
+ "address",
770
+ "article",
771
+ "aside",
772
+ "blockquote",
773
+ "dd",
774
+ "details",
775
+ "div",
776
+ "dl",
777
+ "dt",
778
+ "figcaption",
779
+ "figure",
780
+ "footer",
781
+ "form",
782
+ "h1",
783
+ "h2",
784
+ "h3",
785
+ "h4",
786
+ "h5",
787
+ "h6",
788
+ "header",
789
+ "hr",
790
+ "li",
791
+ "main",
792
+ "nav",
793
+ "ol",
794
+ "p",
795
+ "pre",
796
+ "section",
797
+ "summary",
798
+ "table",
799
+ "tbody",
800
+ "tfoot",
801
+ "thead",
802
+ "tr",
803
+ "ul"
804
+ ]);
805
+ /**
806
+ * Line-number gutters by the class names highlighters give them (Prism, highlight.js,
807
+ * Rouge, Pygments, react-syntax-highlighter, CodeMirror and others).
808
+ */
809
+ /** Whitespace between table rows and cells is never rendered. */
810
+ const TABLE_PARTS = /* @__PURE__ */ new Set([
811
+ "table",
812
+ "thead",
813
+ "tbody",
814
+ "tfoot",
815
+ "tr",
816
+ "colgroup"
817
+ ]);
818
+ const GUTTER = /(?:^|[\s_-])(?:gutter|linenos?|lineno|line-?numbers?|ln-numbers?|line-?nums?)(?:$|[\s_-])/i;
819
+ const NO_SELECT = /(?:^|;)\s*(?:-webkit-)?user-select\s*:\s*none/i;
820
+ /** Colours as browsers serialise them. Anything else (`url(...)`, `var(...)`) is never copied into the HTML. */
821
+ const SAFE_COLOR = /^(?:#[\da-f]{3,8}|[a-z]{3,20}|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\([\d\s.,%/+-]{1,80}\)|color\([a-z\d-]{1,24}[\d\s.,%/+-]{1,80}\))$/i;
822
+ const TRANSPARENT = /^(?:transparent|rgba\(\s*0,\s*0,\s*0,\s*0\s*\))$/i;
823
+ function assertElement(value, name) {
824
+ if (typeof value !== "object" || value === null || value.nodeType !== 1) throw copyFailure("invalid-payload", `\`${name}\` must be a string or an Element.`);
825
+ }
826
+ function lookOf(style) {
827
+ const weight = style.fontWeight;
828
+ const decoration = `${style.textDecorationLine || style.textDecoration} `;
829
+ return {
830
+ color: SAFE_COLOR.test(style.color) ? style.color : "",
831
+ bold: weight === "bold" || weight === "bolder" || Number(weight) >= 600,
832
+ italic: style.fontStyle === "italic" || style.fontStyle.startsWith("oblique"),
833
+ decoration: ["underline", "line-through"].filter((line) => decoration.includes(line)).join(" ")
834
+ };
835
+ }
836
+ /**
837
+ * The code a rendered block shows, as styled runs: line-number gutters, hidden
838
+ * and unselectable parts (`user-select: none`), `aria-hidden` decorations,
839
+ * buttons and anything marked `data-copy-ignore` are left out.
840
+ */
841
+ function extract(root, options) {
842
+ const { ignore } = options;
843
+ if (ignore !== void 0) try {
844
+ root.matches(ignore);
845
+ } catch (cause) {
846
+ throw copyFailure("invalid-payload", `\`ignore\` is not a valid CSS selector: ${ignore}`, cause);
847
+ }
848
+ const view = root.ownerDocument.defaultView;
849
+ const computed = (element) => view === null ? null : view.getComputedStyle(element);
850
+ const rootStyle = computed(root);
851
+ const base = rootStyle === null ? {
852
+ color: "",
853
+ bold: false,
854
+ italic: false,
855
+ decoration: ""
856
+ } : lookOf(rootStyle);
857
+ const runs = [];
858
+ const styles = /* @__PURE__ */ new Map();
859
+ let last = "";
860
+ const push = (text, style) => {
861
+ if (text === "") return;
862
+ const previous = runs[runs.length - 1];
863
+ if (previous?.style === style) runs[runs.length - 1] = {
864
+ text: previous.text + text,
865
+ style
866
+ };
867
+ else runs.push({
868
+ text,
869
+ style
870
+ });
871
+ last = text.charAt(text.length - 1);
872
+ };
873
+ const breakLine = () => {
874
+ if (last !== "" && last !== "\n") push("\n", "");
875
+ };
876
+ const styleOf = (element) => {
877
+ let style = styles.get(element);
878
+ if (style === void 0) {
879
+ const declared = computed(element);
880
+ style = "";
881
+ if (declared !== null) {
882
+ const look = lookOf(declared);
883
+ if (look.color !== "" && look.color !== base.color) style += `color:${look.color};`;
884
+ if (look.bold && !base.bold) style += "font-weight:bold;";
885
+ if (look.italic && !base.italic) style += "font-style:italic;";
886
+ if (look.decoration !== "" && look.decoration !== base.decoration) style += `text-decoration:${look.decoration};`;
887
+ }
888
+ styles.set(element, style);
889
+ }
890
+ return style;
891
+ };
892
+ const leftOut = (element) => {
893
+ if (SKIP.has(element.localName)) return true;
894
+ if (element.hasAttribute("hidden") || element.hasAttribute("data-copy-ignore") || element.getAttribute("aria-hidden") === "true") return true;
895
+ if (GUTTER.test(element.getAttribute("class") ?? "") || NO_SELECT.test(element.getAttribute("style") ?? "")) return true;
896
+ if (ignore !== void 0 && element.matches(ignore)) return true;
897
+ const style = computed(element);
898
+ return style !== null && (style.display === "none" || style.userSelect === "none" || style.getPropertyValue("-webkit-user-select") === "none");
899
+ };
900
+ const walk = (parent) => {
901
+ for (let node = parent.firstChild; node !== null; node = node.nextSibling) if (node.nodeType === 3) {
902
+ const { data } = node;
903
+ if (TABLE_PARTS.has(parent.localName) && data.trim() === "") continue;
904
+ push(data, options.styles ? styleOf(parent) : "");
905
+ } else if (node.nodeType === 1) {
906
+ const element = node;
907
+ if (leftOut(element)) continue;
908
+ if (element.localName === "br") push("\n", "");
909
+ else if (BLOCK.has(element.localName)) {
910
+ breakLine();
911
+ walk(element);
912
+ breakLine();
913
+ } else walk(element);
914
+ }
915
+ };
916
+ walk(root);
917
+ let blockStyle = "";
918
+ if (options.styles && rootStyle !== null) {
919
+ if (base.color !== "") blockStyle += `color:${base.color};`;
920
+ const background = rootStyle.backgroundColor;
921
+ if (SAFE_COLOR.test(background) && !TRANSPARENT.test(background)) blockStyle += `background-color:${background};`;
922
+ }
923
+ return {
924
+ runs,
925
+ blockStyle
926
+ };
927
+ }
928
+ //#endregion
929
+ //#region src/code/payload.ts
930
+ const LANGUAGE = /^[A-Za-z0-9_+#.-]{1,64}$/;
931
+ const MONOSPACE = "font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,'Liberation Mono',monospace;white-space:pre;";
932
+ /** HTML can't hold U+0000: parsers turn it into U+FFFD, so the HTML says so itself (the text flavour keeps it). */
933
+ const escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/\0/g, "�");
934
+ function toHtml(lines, blockStyle, language) {
935
+ const body = lines.map((line) => line.map(({ text, style }) => style === "" ? escapeHtml(text) : `<span style="${escapeHtml(style)}">${escapeHtml(text)}</span>`).join("")).join("\n");
936
+ const cls = language === void 0 ? "" : ` class="language-${language}"`;
937
+ return `<pre style="${escapeHtml(MONOSPACE + blockStyle)}"><code${cls}>${body}</code></pre>`;
938
+ }
939
+ /**
940
+ * The code a rendered block shows, ready to run or save: see {@link extract} for
941
+ * what is left out, and {@link CodeTextOptions} for prompts, diffs and whitespace.
942
+ *
943
+ * @example
944
+ * codeFromElement(preRef.current, { prompt: 'shell' });
945
+ */
946
+ function codeFromElement(element, options = {}) {
947
+ assertElement(element, "element");
948
+ const resolved = resolveText(options, {
949
+ prompt: "auto",
950
+ clean: false
951
+ });
952
+ const { runs } = extract(element, {
953
+ ignore: options.ignore,
954
+ styles: false
955
+ });
956
+ return render(transform(toLines(runs), resolved).lines, resolved);
957
+ }
958
+ /**
959
+ * A copy payload for code: plain text for editors and terminals, plus
960
+ * monospaced HTML (with the block's syntax colours when you pass the element)
961
+ * for documents and chat. A terminal session is copied as its commands
962
+ * (`prompt: 'auto'`). Code that ends up empty gives an empty text payload, which
963
+ * `copy()` reports as an `invalid-payload` error.
964
+ *
965
+ * @example
966
+ * const { copy } = useCopy();
967
+ * <button onClick={() => copy(() => codePayload(preRef.current!, { language: 'tsx' }))}>Copy</button>
968
+ */
969
+ function codePayload(source, options = {}) {
970
+ const resolved = resolveText(options, {
971
+ prompt: "auto",
972
+ clean: false
973
+ });
974
+ const withHtml = options.html ?? true;
975
+ if (typeof withHtml !== "boolean") throw copyFailure("invalid-payload", "`html` must be a boolean.");
976
+ const { language } = options;
977
+ if (language !== void 0 && (typeof language !== "string" || !LANGUAGE.test(language))) throw copyFailure("invalid-payload", "`language` may only hold letters, digits and _ + # . - (at most 64).");
978
+ let lines;
979
+ let blockStyle = "";
980
+ if (typeof source === "string") lines = toLines([{
981
+ text: source,
982
+ style: ""
983
+ }]);
984
+ else {
985
+ assertElement(source, "source");
986
+ const extracted = extract(source, {
987
+ ignore: options.ignore,
988
+ styles: withHtml
989
+ });
990
+ lines = toLines(extracted.runs);
991
+ blockStyle = extracted.blockStyle;
992
+ }
993
+ const out = transform(lines, resolved).lines;
994
+ const text = render(out, resolved);
995
+ if (!withHtml || text === "") return {
996
+ kind: "text",
997
+ value: text
998
+ };
999
+ return {
1000
+ kind: "html",
1001
+ text,
1002
+ html: toHtml(out, blockStyle, language)
1003
+ };
1004
+ }
1005
+ //#endregion
1006
+ //#region src/core/text-field.ts
1007
+ const TEXT_INPUTS = /* @__PURE__ */ new Set([
1008
+ "text",
1009
+ "search",
1010
+ "url",
1011
+ "tel",
1012
+ "password"
1013
+ ]);
1014
+ function asTextField(target) {
1015
+ if (typeof target !== "object" || target === null) return null;
1016
+ const element = target;
1017
+ if (element.nodeName === "TEXTAREA") return target;
1018
+ if (element.nodeName === "INPUT" && typeof element.type === "string" && TEXT_INPUTS.has(element.type)) return target;
1019
+ return null;
1020
+ }
1021
+ /**
1022
+ * Inserts text at the cursor of a `<textarea>` or text `<input>`, replacing the
1023
+ * selection, as typing or pasting would: the browser's undo (Ctrl/⌘+Z) still
1024
+ * works, `input` events fire (so React and other frameworks see the change),
1025
+ * and `maxlength` is respected. Returns `false` for disabled or read-only fields.
1026
+ */
1027
+ function insertText(field, text) {
1028
+ if (field.disabled || field.readOnly) return false;
1029
+ const value = field.nodeName === "INPUT" ? text.replace(/[ \t]*(?:\r\n|\r|\n)+[ \t]*/g, " ") : text;
1030
+ const doc = field.ownerDocument;
1031
+ field.focus();
1032
+ const start = field.selectionStart;
1033
+ const end = field.selectionEnd;
1034
+ try {
1035
+ if (start !== null && end !== null) field.setSelectionRange(start, end);
1036
+ if (doc.activeElement === field && doc.execCommand("insertText", false, value)) return true;
1037
+ } catch {}
1038
+ const from = start ?? field.value.length;
1039
+ const to = end ?? from;
1040
+ let insert = value;
1041
+ if (field.maxLength >= 0) {
1042
+ const room = Math.max(0, field.maxLength - (field.value.length - (to - from)));
1043
+ insert = insert.slice(0, room);
1044
+ if (/[\ud800-\udbff]$/.test(insert)) insert = insert.slice(0, -1);
1045
+ }
1046
+ if (start === null) setNativeValue(field, field.value + insert);
1047
+ else field.setRangeText(insert, from, to, "end");
1048
+ const view = doc.defaultView;
1049
+ const event = view !== null && typeof view.InputEvent === "function" ? new view.InputEvent("input", {
1050
+ bubbles: true,
1051
+ inputType: "insertFromPaste",
1052
+ data: insert
1053
+ }) : new Event("input", { bubbles: true });
1054
+ field.dispatchEvent(event);
1055
+ return true;
1056
+ }
1057
+ /**
1058
+ * Sets a field's value through the prototype's setter. React tracks the value
1059
+ * set on the element itself; going around it lets React see the change and
1060
+ * call `onChange` for the `input` event that follows.
1061
+ */
1062
+ function setNativeValue(field, next) {
1063
+ const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(field), "value")?.set;
1064
+ if (setter) setter.call(field, next);
1065
+ else field.value = next;
1066
+ }
1067
+ //#endregion
1068
+ //#region src/code/paste.ts
1069
+ const DEFAULT_CODE_MAX_LENGTH = 2e6;
1070
+ const INDENT = /^[ \t]*$/;
1071
+ function indentLines(lines, indent) {
1072
+ if (indent === "") return [...lines];
1073
+ return lines.map((line, at) => at === 0 || lineText(line) === "" ? line : [{
1074
+ text: indent,
1075
+ style: ""
1076
+ }, ...line]);
1077
+ }
1078
+ /**
1079
+ * Code for what was pasted: the plain text (or, when only HTML was copied, the
1080
+ * text of its code), cleaned of invisible and lookalike characters, curly quotes
1081
+ * and odd spaces, dedented, and re-indented with `indent`. Every finding is
1082
+ * reported. Returns `null` when there is nothing to paste.
1083
+ *
1084
+ * @example
1085
+ * usePaste({ accept: ['text'], onPaste: (result) => {
1086
+ * const pasted = pasteToCode(result);
1087
+ * if (pasted?.danger) showWarning(pasted.remaining);
1088
+ * } });
1089
+ */
1090
+ function pasteToCode(source, options = {}) {
1091
+ const resolved = resolveText(options, {
1092
+ prompt: false,
1093
+ clean: true
1094
+ });
1095
+ const maxLength = positiveLimit(options.maxLength, DEFAULT_CODE_MAX_LENGTH, "maxLength");
1096
+ const indent = options.indent ?? "";
1097
+ if (typeof indent !== "string" || !INDENT.test(indent)) throw copyFailure("invalid-payload", "`indent` may only hold spaces and tabs.");
1098
+ let text = source.text ?? "";
1099
+ let from = "text";
1100
+ if (text === "" && typeof source.html === "string" && source.html.trim() !== "" && typeof DOMParser !== "undefined") {
1101
+ if (source.html.length > maxLength) throw copyFailure("too-large", `The pasted HTML is longer than maxLength (${String(maxLength)}).`);
1102
+ const body = new DOMParser().parseFromString(source.html, "text/html").body;
1103
+ text = extract(body, { styles: false }).runs.map((run) => run.text).join("");
1104
+ from = "html";
1105
+ }
1106
+ if (text.length > maxLength) throw copyFailure("too-large", `The pasted text is longer than maxLength (${String(maxLength)}).`);
1107
+ if (text.trim() === "") return null;
1108
+ const { lines, fixed } = transform(toLines([{
1109
+ text,
1110
+ style: ""
1111
+ }]), resolved);
1112
+ const code = render(indentLines(lines, indent), {
1113
+ eol: resolved.eol,
1114
+ finalNewline: false
1115
+ });
1116
+ const remaining = inspectCode(code, { maxFindings: Infinity }).findings;
1117
+ return {
1118
+ code,
1119
+ source: from,
1120
+ findings: inspectCode(text).findings,
1121
+ fixed,
1122
+ remaining,
1123
+ danger: remaining.some((finding) => finding.severity === "danger")
1124
+ };
1125
+ }
1126
+ /**
1127
+ * A paste handler for code fields (`<textarea>`, or a text `<input>` for one-line
1128
+ * commands): pastes the code from {@link pasteToCode} at the cursor with the
1129
+ * browser's undo intact. Returns whether it took over the paste: `false` leaves
1130
+ * the paste to the browser (nothing to paste, a field it can't write to, invalid
1131
+ * options, or a paste past `maxLength`).
1132
+ *
1133
+ * @example
1134
+ * <textarea onPaste={pasteAsCode} />
1135
+ * <textarea onPaste={(event) => pasteAsCode(event, { onPaste: (r) => !r.danger || confirm('Paste anyway?') })} />
1136
+ */
1137
+ function pasteAsCode(event, options = {}) {
1138
+ if (event.defaultPrevented || event.clipboardData === null) return false;
1139
+ const field = asTextField(event.currentTarget) ?? asTextField(event.target);
1140
+ if (field === null || field.disabled || field.readOnly) return false;
1141
+ const { indentToCursor, onPaste, ...rest } = options;
1142
+ let indent = "";
1143
+ if (indentToCursor !== false && field.nodeName === "TEXTAREA" && field.selectionStart !== null) {
1144
+ const before = field.value.slice(0, field.selectionStart);
1145
+ indent = /^[ \t]*/.exec(before.slice(before.lastIndexOf("\n") + 1))?.[0];
1146
+ }
1147
+ let result;
1148
+ try {
1149
+ result = pasteToCode({
1150
+ text: event.clipboardData.getData("text/plain"),
1151
+ html: event.clipboardData.getData("text/html")
1152
+ }, {
1153
+ ...rest,
1154
+ indent
1155
+ });
1156
+ } catch (error) {
1157
+ if (error instanceof CopyFailure) return false;
1158
+ throw error;
1159
+ }
1160
+ if (result === null) return false;
1161
+ event.preventDefault();
1162
+ if (onPaste?.(result) === false) return true;
1163
+ insertText(field, result.code);
1164
+ return true;
1165
+ }
1166
+ //#endregion
1167
+ export { CODE_FINDING_KINDS, DEFAULT_CODE_MAX_FINDINGS, DEFAULT_CODE_MAX_LENGTH, PROMPT_STYLES, cleanCode, codeFromElement, codePayload, insertText, inspectCode, normalizeCode, pasteAsCode, pasteToCode };
1168
+
1169
+ //# sourceMappingURL=code.js.map