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/dist/code.d.ts ADDED
@@ -0,0 +1,292 @@
1
+ //#region src/code/inspect.d.ts
2
+ /**
3
+ * What a character in code can be suspicious for.
4
+ *
5
+ * - `bidi-control`: reorders how text is displayed (Trojan Source, CVE-2021-42574).
6
+ * - `invisible`: renders as nothing (zero-width spaces, tag characters, Hangul fillers).
7
+ * - `control`: a control character other than tab, line feed, carriage return or form feed.
8
+ * - `unusual-space`: a space that is not U+0020 (no-break, em, ideographic and similar spaces).
9
+ * - `confusable-punctuation`: typographic punctuation in place of ASCII, as word
10
+ * processors and chat apps write it (curly quotes, dashes, a Greek question mark).
11
+ * - `mixed-script`: a Cyrillic or Greek letter inside a Latin word (a homoglyph attack).
12
+ */
13
+ type CodeFindingKind = 'bidi-control' | 'invisible' | 'control' | 'unusual-space' | 'confusable-punctuation' | 'mixed-script';
14
+ /** Every finding kind, in a stable order. */
15
+ export declare const CODE_FINDING_KINDS: readonly CodeFindingKind[];
16
+ /**
17
+ * `danger`: the code can run differently from how it reads (a bidi override, an
18
+ * invisible identifier, a lookalike letter). `warning`: likely a copy artifact
19
+ * that breaks the code or hides in it (curly quotes, a zero-width space).
20
+ */
21
+ type CodeFindingSeverity = 'danger' | 'warning';
22
+ interface CodeFinding {
23
+ readonly kind: CodeFindingKind;
24
+ readonly severity: CodeFindingSeverity;
25
+ /** Offset in the inspected text, in UTF-16 code units (as `String.prototype.slice` counts). */
26
+ readonly index: number;
27
+ /** Length in UTF-16 code units: 1, or 2 for a character outside the Basic Multilingual Plane. */
28
+ readonly length: number;
29
+ /** 1-based line. Lines end at `\n`, `\r\n` or `\r`. */
30
+ readonly line: number;
31
+ /** 1-based column in UTF-16 code units, as most editors count it. */
32
+ readonly column: number;
33
+ readonly codePoint: number;
34
+ /** Developer-facing, e.g. `U+202E RIGHT-TO-LEFT OVERRIDE`. */
35
+ readonly label: string;
36
+ /** The safe replacement `cleanCode` writes (`''` removes it), or `null` when there is none to guess. */
37
+ readonly replacement: string | null;
38
+ }
39
+ interface InspectCodeOptions {
40
+ /** Which kinds to look for. Default: all of {@link CODE_FINDING_KINDS}. */
41
+ readonly kinds?: readonly CodeFindingKind[];
42
+ /** Stop after this many findings and set `truncated`. Default {@link DEFAULT_CODE_MAX_FINDINGS}. */
43
+ readonly maxFindings?: number;
44
+ }
45
+ interface CodeInspection {
46
+ /** In order of position. */
47
+ readonly findings: readonly CodeFinding[];
48
+ /** Whether any finding is `danger`. */
49
+ readonly danger: boolean;
50
+ /** Whether `maxFindings` stopped the scan early. */
51
+ readonly truncated: boolean;
52
+ }
53
+ export declare const DEFAULT_CODE_MAX_FINDINGS = 1000;
54
+ /**
55
+ * Finds characters that make code read differently from how it runs, or that a
56
+ * copy through a word processor or chat app slipped in: bidirectional overrides
57
+ * (Trojan Source), invisible characters and identifiers, control characters,
58
+ * unusual spaces, curly quotes and dashes, and Cyrillic or Greek lookalikes inside
59
+ * Latin words. Works anywhere, including on the server.
60
+ *
61
+ * @example
62
+ * const { danger, findings } = inspectCode(pasted);
63
+ * if (danger) warn(findings.map((f) => `${f.line}:${f.column} ${f.label}`));
64
+ */
65
+ export declare function inspectCode(code: string, options?: InspectCodeOptions): CodeInspection;
66
+ interface CleanCodeOptions {
67
+ /** Which kinds to fix. Default: all. Findings without a `replacement` are never changed. */
68
+ readonly kinds?: readonly CodeFindingKind[];
69
+ }
70
+ interface CleanCode {
71
+ readonly code: string;
72
+ /** What was replaced or removed, in order, with positions in the original text. */
73
+ readonly fixed: readonly CodeFinding[];
74
+ /** What is still in `code` (positions in `code`): findings without a safe replacement. */
75
+ readonly remaining: readonly CodeFinding[];
76
+ }
77
+ /**
78
+ * Replaces what {@link inspectCode} finds with safe ASCII: removes bidi controls,
79
+ * invisible and control characters, turns unusual spaces into spaces, curly quotes
80
+ * and dashes into `'` `"` `-`, and lookalike letters into the Latin letters they
81
+ * imitate. Letters with no lookalike are reported in `remaining`, never guessed.
82
+ *
83
+ * @example
84
+ * cleanCode('const s = \u201Chi\u201D;').code; // 'const s = "hi";'
85
+ */
86
+ export declare function cleanCode(code: string, options?: CleanCodeOptions): CleanCode;
87
+ //#endregion
88
+ //#region src/code/normalize.d.ts
89
+ /** Built-in prompt styles for terminal and REPL sessions. */
90
+ type PromptStyle = 'shell' | 'powershell' | 'cmd' | 'python' | 'ipython' | 'node';
91
+ /** Every built-in prompt style. `'auto'` tries all but `node`, whose `> ` is too common to guess. */
92
+ export declare const PROMPT_STYLES: readonly PromptStyle[];
93
+ /**
94
+ * A custom prompt. `command` matches the prompt at the start of a command line,
95
+ * `continuation` the prompt of the lines that continue it. Matches must start at
96
+ * the beginning of the line; the `g` and `y` flags are ignored.
97
+ */
98
+ interface PromptPattern {
99
+ readonly command: RegExp;
100
+ readonly continuation?: RegExp;
101
+ }
102
+ interface CodeTextOptions {
103
+ /**
104
+ * Copy a terminal or REPL session as the commands to run: prompts are removed
105
+ * and output lines are dropped. `'auto'` (the default for copying) does this only
106
+ * when the first line starts with a `$`, `PS>`, `C:\>`, `>>>` or `In [1]:`
107
+ * prompt; `false` keeps the text as it is.
108
+ */
109
+ readonly prompt?: 'auto' | false | PromptStyle | PromptPattern;
110
+ /** Copy a unified diff as the code after (`'after'`) or before (`'before'`) the change. Default `false`. */
111
+ readonly diff?: false | 'after' | 'before';
112
+ /**
113
+ * Remove line numbers typed into the text (`1: code`, ` 12 | code`). Only
114
+ * applied when every line starts with a number and the numbers count up by one.
115
+ * Default `false`.
116
+ */
117
+ readonly lineNumbers?: boolean;
118
+ /** Remove the indentation every line shares. Default `true`. */
119
+ readonly dedent?: boolean;
120
+ /** Default `true`. */
121
+ readonly trimTrailingWhitespace?: boolean;
122
+ /** Remove blank lines at the start and the end. Default `true`. */
123
+ readonly trimBlankLines?: boolean;
124
+ /** Default `'lf'`. */
125
+ readonly lineEnding?: 'lf' | 'crlf';
126
+ /** End with a line break. Default `false`. */
127
+ readonly finalNewline?: boolean;
128
+ /**
129
+ * Fix what `inspectCode` finds (see `cleanCode`): `true` for every kind, or a
130
+ * list of kinds. Default `false` when copying, `true` when pasting.
131
+ */
132
+ readonly clean?: boolean | readonly CodeFindingKind[];
133
+ }
134
+ /**
135
+ * Code as it should be copied or saved: a terminal session becomes its commands,
136
+ * a diff one side of the change, typed line numbers and shared indentation are
137
+ * removed, line endings are normalised. Works anywhere, including on the server.
138
+ *
139
+ * @example
140
+ * normalizeCode('$ npm install react-smart-copy\nadded 1 package'); // 'npm install react-smart-copy'
141
+ */
142
+ export declare function normalizeCode(code: string, options?: CodeTextOptions): string;
143
+ //#endregion
144
+ //#region src/core/payload.d.ts
145
+ interface TextPayload {
146
+ readonly kind: 'text';
147
+ readonly value: string;
148
+ }
149
+ interface HtmlPayload {
150
+ readonly kind: 'html';
151
+ readonly html: string;
152
+ /** Required plain-text fallback for targets that don't understand HTML. */
153
+ readonly text: string;
154
+ }
155
+ //#endregion
156
+ //#region src/code/payload.d.ts
157
+ /** Code to copy: a string, or a rendered (and possibly highlighted) code block. */
158
+ type CodeSource = string | Element;
159
+ interface CodeFromElementOptions extends CodeTextOptions {
160
+ /**
161
+ * A CSS selector for more parts of the block to leave out. Gutters, hidden and
162
+ * `user-select: none` parts, `aria-hidden` decorations, buttons and anything with
163
+ * `data-copy-ignore` are always left out.
164
+ */
165
+ readonly ignore?: string;
166
+ }
167
+ interface CodePayloadOptions extends CodeFromElementOptions {
168
+ /**
169
+ * Add an HTML flavour (`<pre><code>`), so the code stays monospaced when pasted
170
+ * into Google Docs, Word, Slack, Teams or a mail; from an element, with its
171
+ * syntax colours. Editors and terminals still paste the plain text. Default `true`.
172
+ */
173
+ readonly html?: boolean;
174
+ /** Written as `class="language-<name>"` on the `<code>` element. Letters, digits and `_ + # . -` only. */
175
+ readonly language?: string;
176
+ }
177
+ /**
178
+ * The code a rendered block shows, ready to run or save: see {@link extract} for
179
+ * what is left out, and {@link CodeTextOptions} for prompts, diffs and whitespace.
180
+ *
181
+ * @example
182
+ * codeFromElement(preRef.current, { prompt: 'shell' });
183
+ */
184
+ export declare function codeFromElement(element: Element, options?: CodeFromElementOptions): string;
185
+ /**
186
+ * A copy payload for code: plain text for editors and terminals, plus
187
+ * monospaced HTML (with the block's syntax colours when you pass the element)
188
+ * for documents and chat. A terminal session is copied as its commands
189
+ * (`prompt: 'auto'`). Code that ends up empty gives an empty text payload, which
190
+ * `copy()` reports as an `invalid-payload` error.
191
+ *
192
+ * @example
193
+ * const { copy } = useCopy();
194
+ * <button onClick={() => copy(() => codePayload(preRef.current!, { language: 'tsx' }))}>Copy</button>
195
+ */
196
+ export declare function codePayload(source: CodeSource, options?: CodePayloadOptions): HtmlPayload | TextPayload;
197
+ //#endregion
198
+ //#region src/code/paste.d.ts
199
+ export declare const DEFAULT_CODE_MAX_LENGTH = 2000000;
200
+ interface PasteToCodeOptions extends Omit<CodeTextOptions, 'finalNewline'> {
201
+ /**
202
+ * Indentation for every line after the first, which lands where the cursor is.
203
+ * `pasteAsCode` sets it to the cursor line's indentation.
204
+ */
205
+ readonly indent?: string;
206
+ /**
207
+ * Longest paste to process, in UTF-16 code units. Longer pastes throw a
208
+ * `too-large` error (`pasteAsCode` leaves them to the browser): code is never cut.
209
+ * Default {@link DEFAULT_CODE_MAX_LENGTH}.
210
+ */
211
+ readonly maxLength?: number;
212
+ }
213
+ interface PasteCode {
214
+ readonly code: string;
215
+ /** `text` for the plain-text flavour; `html` when only HTML was on the clipboard. */
216
+ readonly source: 'text' | 'html';
217
+ /** What the pasted text held, before anything was fixed (positions in the pasted text, at most 1000). */
218
+ readonly findings: readonly CodeFinding[];
219
+ /** How many characters `clean` replaced or removed. */
220
+ readonly fixed: number;
221
+ /** What is still in `code` (positions in `code`), e.g. a non-Latin letter with no lookalike. */
222
+ readonly remaining: readonly CodeFinding[];
223
+ /** Whether `remaining` holds a `danger` finding. */
224
+ readonly danger: boolean;
225
+ }
226
+ /** The clipboard flavours: a `PasteResult` from `usePaste`, or anything with `text` / `html`. */
227
+ interface CodePasteSource {
228
+ readonly text?: string | null;
229
+ readonly html?: string | null;
230
+ }
231
+ /**
232
+ * Code for what was pasted: the plain text (or, when only HTML was copied, the
233
+ * text of its code), cleaned of invisible and lookalike characters, curly quotes
234
+ * and odd spaces, dedented, and re-indented with `indent`. Every finding is
235
+ * reported. Returns `null` when there is nothing to paste.
236
+ *
237
+ * @example
238
+ * usePaste({ accept: ['text'], onPaste: (result) => {
239
+ * const pasted = pasteToCode(result);
240
+ * if (pasted?.danger) showWarning(pasted.remaining);
241
+ * } });
242
+ */
243
+ export declare function pasteToCode(source: CodePasteSource, options?: PasteToCodeOptions): PasteCode | null;
244
+ /** Structural paste event: a DOM `ClipboardEvent` and React's `onPaste` event both fit. */
245
+ interface CodePasteEvent {
246
+ readonly clipboardData: {
247
+ getData(format: string): string;
248
+ } | null;
249
+ readonly currentTarget: EventTarget | null;
250
+ readonly target: EventTarget | null;
251
+ readonly defaultPrevented: boolean;
252
+ preventDefault(): void;
253
+ }
254
+ interface PasteAsCodeOptions extends Omit<PasteToCodeOptions, 'indent'> {
255
+ /** Indent the pasted lines to the cursor line's indentation, as code editors do. Default `true`. */
256
+ readonly indentToCursor?: boolean;
257
+ /**
258
+ * Called before the code is inserted. Return `false` to cancel the paste, e.g.
259
+ * when `danger` is set and the user declines.
260
+ */
261
+ readonly onPaste?: (result: PasteCode) => boolean | void;
262
+ }
263
+ /**
264
+ * A paste handler for code fields (`<textarea>`, or a text `<input>` for one-line
265
+ * commands): pastes the code from {@link pasteToCode} at the cursor with the
266
+ * browser's undo intact. Returns whether it took over the paste: `false` leaves
267
+ * the paste to the browser (nothing to paste, a field it can't write to, invalid
268
+ * options, or a paste past `maxLength`).
269
+ *
270
+ * @example
271
+ * <textarea onPaste={pasteAsCode} />
272
+ * <textarea onPaste={(event) => pasteAsCode(event, { onPaste: (r) => !r.danger || confirm('Paste anyway?') })} />
273
+ */
274
+ export declare function pasteAsCode(event: CodePasteEvent, options?: PasteAsCodeOptions): boolean;
275
+ //#endregion
276
+ //#region src/core/text-field.d.ts
277
+ /**
278
+ * Text-field helpers shared by the paste handlers of the opt-in entry points.
279
+ * Internal: not part of `react-smart-copy/core`'s public API.
280
+ */
281
+ /** Text fields `setRangeText` and `execCommand('insertText')` both support. */
282
+ type TextField = HTMLTextAreaElement | HTMLInputElement;
283
+ /**
284
+ * Inserts text at the cursor of a `<textarea>` or text `<input>`, replacing the
285
+ * selection, as typing or pasting would: the browser's undo (Ctrl/⌘+Z) still
286
+ * works, `input` events fire (so React and other frameworks see the change),
287
+ * and `maxlength` is respected. Returns `false` for disabled or read-only fields.
288
+ */
289
+ export declare function insertText(field: TextField, text: string): boolean;
290
+ //#endregion
291
+ export type { CleanCode, CleanCodeOptions, CodeFinding, CodeFindingKind, CodeFindingSeverity, CodeFromElementOptions, CodeInspection, CodePasteEvent, CodePasteSource, CodePayloadOptions, CodeSource, CodeTextOptions, InspectCodeOptions, PasteAsCodeOptions, PasteCode, PasteToCodeOptions, PromptPattern, PromptStyle };
292
+ //# sourceMappingURL=code.d.ts.map