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