react-smart-copy 1.17.2 → 1.19.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.
Files changed (154) hide show
  1. package/README.md +86 -5
  2. package/dist/capture.cjs +30 -153
  3. package/dist/capture.cjs.map +1 -1
  4. package/dist/capture.d.cts +2 -25
  5. package/dist/capture.d.ts +2 -25
  6. package/dist/capture.js +5 -128
  7. package/dist/capture.js.map +1 -1
  8. package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs +102 -0
  9. package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs.map +1 -0
  10. package/dist/chunks/clipboard-adapter-CtH4VELE.d.cts +43 -0
  11. package/dist/chunks/clipboard-adapter-DEXkXxwV.js +97 -0
  12. package/dist/chunks/clipboard-adapter-DEXkXxwV.js.map +1 -0
  13. package/dist/chunks/clipboard-adapter-Ds0irroN.d.ts +43 -0
  14. package/dist/chunks/contrast-C6CVklEI.cjs +842 -0
  15. package/dist/chunks/contrast-C6CVklEI.cjs.map +1 -0
  16. package/dist/chunks/contrast-DpK2JIVu.js +789 -0
  17. package/dist/chunks/contrast-DpK2JIVu.js.map +1 -0
  18. package/dist/chunks/copy-interceptor-C6NABy1l.d.ts +141 -0
  19. package/dist/chunks/copy-interceptor-CZWzGOkL.d.cts +141 -0
  20. package/dist/chunks/core-Cp2HSpaz.js +1035 -0
  21. package/dist/chunks/core-Cp2HSpaz.js.map +1 -0
  22. package/dist/chunks/core-DYf_Lhbe.cjs +1142 -0
  23. package/dist/chunks/core-DYf_Lhbe.cjs.map +1 -0
  24. package/dist/chunks/deadline-C29AlS_Q.js +46 -0
  25. package/dist/chunks/deadline-C29AlS_Q.js.map +1 -0
  26. package/dist/chunks/deadline-DkiB8ZHE.cjs +51 -0
  27. package/dist/chunks/deadline-DkiB8ZHE.cjs.map +1 -0
  28. package/dist/chunks/errors-9h8sdFFX.js +120 -0
  29. package/dist/chunks/errors-9h8sdFFX.js.map +1 -0
  30. package/dist/chunks/errors-BwOF6T_M.cjs +167 -0
  31. package/dist/chunks/errors-BwOF6T_M.cjs.map +1 -0
  32. package/dist/chunks/index-mr7sSAgP.d.ts +426 -0
  33. package/dist/chunks/index-vz0iW5V2.d.cts +426 -0
  34. package/dist/chunks/inert-html-D75NyVvT.js +34 -0
  35. package/dist/chunks/inert-html-D75NyVvT.js.map +1 -0
  36. package/dist/chunks/inert-html-DyxjWDok.cjs +39 -0
  37. package/dist/chunks/inert-html-DyxjWDok.cjs.map +1 -0
  38. package/dist/chunks/mime--LB7kdqG.cjs +153 -0
  39. package/dist/chunks/mime--LB7kdqG.cjs.map +1 -0
  40. package/dist/chunks/mime-aa-HA2dm.js +100 -0
  41. package/dist/chunks/mime-aa-HA2dm.js.map +1 -0
  42. package/dist/chunks/paste-adapter--SPL4PRE.d.cts +35 -0
  43. package/dist/chunks/paste-adapter-uahXnTYk.d.ts +35 -0
  44. package/dist/chunks/paste-reader-Bo01IMC_.cjs +289 -0
  45. package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +1 -0
  46. package/dist/chunks/paste-reader-D9i7yMXF.js +224 -0
  47. package/dist/chunks/paste-reader-D9i7yMXF.js.map +1 -0
  48. package/dist/chunks/paste-reader-DcXnRWQr.d.cts +96 -0
  49. package/dist/chunks/paste-reader-DcXnRWQr.d.ts +96 -0
  50. package/dist/chunks/payload-CUymxwim.cjs +100 -0
  51. package/dist/chunks/payload-CUymxwim.cjs.map +1 -0
  52. package/dist/chunks/payload-CcwKJ_bU.d.cts +162 -0
  53. package/dist/chunks/payload-Cl_8hCI5.d.ts +162 -0
  54. package/dist/chunks/payload-DGw-JOo7.js +71 -0
  55. package/dist/chunks/payload-DGw-JOo7.js.map +1 -0
  56. package/dist/chunks/payload-DI5AorDz.js +103 -0
  57. package/dist/chunks/payload-DI5AorDz.js.map +1 -0
  58. package/dist/chunks/payload-J6GjHuh3.cjs +132 -0
  59. package/dist/chunks/payload-J6GjHuh3.cjs.map +1 -0
  60. package/dist/chunks/share-Bop47Znn.js +208 -0
  61. package/dist/chunks/share-Bop47Znn.js.map +1 -0
  62. package/dist/chunks/share-C0esXvRK.d.cts +115 -0
  63. package/dist/chunks/share-ayDz974N.cjs +231 -0
  64. package/dist/chunks/share-ayDz974N.cjs.map +1 -0
  65. package/dist/chunks/share-e7FenIr2.d.ts +115 -0
  66. package/dist/chunks/text-field-Ba8W3v4R.cjs +77 -0
  67. package/dist/chunks/text-field-Ba8W3v4R.cjs.map +1 -0
  68. package/dist/chunks/text-field-C0SGmvvR.d.cts +18 -0
  69. package/dist/chunks/text-field-C0SGmvvR.d.ts +18 -0
  70. package/dist/chunks/text-field-DUvrMMaK.js +66 -0
  71. package/dist/chunks/text-field-DUvrMMaK.js.map +1 -0
  72. package/dist/chunks/url-B9jdFGQy.cjs +86 -0
  73. package/dist/chunks/url-B9jdFGQy.cjs.map +1 -0
  74. package/dist/chunks/url-BcMYVCXQ.js +135 -0
  75. package/dist/chunks/url-BcMYVCXQ.js.map +1 -0
  76. package/dist/chunks/url-D4PGsRm8.cjs +164 -0
  77. package/dist/chunks/url-D4PGsRm8.cjs.map +1 -0
  78. package/dist/chunks/url-DWdElCT3.d.cts +43 -0
  79. package/dist/chunks/url-DWdElCT3.d.ts +43 -0
  80. package/dist/chunks/url-vJaFPbNL.js +57 -0
  81. package/dist/chunks/url-vJaFPbNL.js.map +1 -0
  82. package/dist/code.cjs +22 -113
  83. package/dist/code.cjs.map +1 -1
  84. package/dist/code.d.cts +4 -28
  85. package/dist/code.d.ts +4 -28
  86. package/dist/code.js +5 -96
  87. package/dist/code.js.map +1 -1
  88. package/dist/color.cjs +21 -893
  89. package/dist/color.cjs.map +1 -1
  90. package/dist/color.d.cts +4 -28
  91. package/dist/color.d.ts +4 -28
  92. package/dist/color.js +4 -876
  93. package/dist/color.js.map +1 -1
  94. package/dist/core.cjs +52 -1659
  95. package/dist/core.d.cts +8 -878
  96. package/dist/core.d.ts +8 -878
  97. package/dist/core.js +7 -1614
  98. package/dist/image.cjs +23 -94
  99. package/dist/image.cjs.map +1 -1
  100. package/dist/image.d.cts +1 -0
  101. package/dist/image.d.ts +1 -0
  102. package/dist/image.js +3 -74
  103. package/dist/image.js.map +1 -1
  104. package/dist/index.cjs +74 -2072
  105. package/dist/index.cjs.map +1 -1
  106. package/dist/index.d.cts +8 -978
  107. package/dist/index.d.ts +8 -978
  108. package/dist/index.js +7 -2005
  109. package/dist/index.js.map +1 -1
  110. package/dist/link.cjs +26 -339
  111. package/dist/link.cjs.map +1 -1
  112. package/dist/link.d.cts +5 -83
  113. package/dist/link.d.ts +5 -83
  114. package/dist/link.js +7 -320
  115. package/dist/link.js.map +1 -1
  116. package/dist/markdown.cjs +19 -159
  117. package/dist/markdown.cjs.map +1 -1
  118. package/dist/markdown.d.cts +3 -16
  119. package/dist/markdown.d.ts +3 -16
  120. package/dist/markdown.js +6 -146
  121. package/dist/markdown.js.map +1 -1
  122. package/dist/rich.cjs +1123 -940
  123. package/dist/rich.cjs.map +1 -1
  124. package/dist/rich.d.cts +101 -91
  125. package/dist/rich.d.ts +101 -91
  126. package/dist/rich.js +1099 -919
  127. package/dist/rich.js.map +1 -1
  128. package/dist/share.cjs +5 -640
  129. package/dist/share.d.cts +3 -248
  130. package/dist/share.d.ts +3 -248
  131. package/dist/share.js +1 -637
  132. package/dist/structured.cjs +13 -95
  133. package/dist/structured.cjs.map +1 -1
  134. package/dist/structured.d.cts +2 -11
  135. package/dist/structured.d.ts +2 -11
  136. package/dist/structured.js +4 -86
  137. package/dist/structured.js.map +1 -1
  138. package/dist/table.cjs +13 -40
  139. package/dist/table.cjs.map +1 -1
  140. package/dist/table.d.cts +2 -12
  141. package/dist/table.d.ts +2 -12
  142. package/dist/table.js +4 -31
  143. package/dist/table.js.map +1 -1
  144. package/dist/testing.cjs +10 -43
  145. package/dist/testing.cjs.map +1 -1
  146. package/dist/testing.d.cts +6 -181
  147. package/dist/testing.d.ts +6 -181
  148. package/dist/testing.js +3 -36
  149. package/dist/testing.js.map +1 -1
  150. package/package.json +37 -5
  151. package/dist/core.cjs.map +0 -1
  152. package/dist/core.js.map +0 -1
  153. package/dist/share.cjs.map +0 -1
  154. package/dist/share.js.map +0 -1
package/dist/core.js CHANGED
@@ -1,1615 +1,8 @@
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
- const RETRYABLE_ERRORS = /* @__PURE__ */ new Set([
13
- "permission-denied",
14
- "not-focused",
15
- "blob-generation-failed",
16
- "timeout",
17
- "unknown"
18
- ]);
19
- /** Whether retrying the same payload could plausibly succeed. */
20
- function isRetryableError(error) {
21
- return RETRYABLE_ERRORS.has(error.type);
22
- }
23
- /**
24
- * Branded (not `instanceof`) so failures stay recognisable even when the core
25
- * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
26
- */
27
- const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
28
- /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
29
- var CopyFailure = class extends Error {
30
- constructor(copyError) {
31
- super(copyError.message);
32
- this[COPY_FAILURE_BRAND] = true;
33
- this.name = "CopyFailure";
34
- this.copyError = copyError;
35
- }
36
- };
37
- function isCopyFailure(value) {
38
- return typeof value === "object" && value !== null && value[COPY_FAILURE_BRAND] === true;
39
- }
40
- /** Shorthand for throwing a classified failure. */
41
- function copyFailure(type, message, cause) {
42
- return new CopyFailure(createCopyError(type, message, cause));
43
- }
44
- function readString(value, key) {
45
- if (typeof value !== "object" || value === null) return void 0;
46
- const field = value[key];
47
- return typeof field === "string" ? field : void 0;
48
- }
49
- /**
50
- * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.
51
- * `operation` only tailors the developer-facing message.
52
- */
53
- function toCopyError(cause, operation = "write") {
54
- if (isCopyFailure(cause)) return cause.copyError;
55
- const name = readString(cause, "name");
56
- const message = readString(cause, "message") ?? "";
57
- const verb = operation === "read" ? "read" : "write";
58
- switch (name) {
59
- case "NotAllowedError": return /focus/i.test(message) ? createCopyError("not-focused", `The document was not focused during the clipboard ${verb}.`, cause) : createCopyError("permission-denied", `Clipboard ${verb} permission was denied.`, cause);
60
- case "SecurityError": return createCopyError("insecure-context", "The clipboard is blocked in this context.", cause);
61
- case "NotSupportedError":
62
- case "DataError": return createCopyError("unsupported-format", "The browser rejected this clipboard format.", cause);
63
- case "AbortError": return createCopyError("aborted", `The clipboard ${verb} was aborted.`, cause);
64
- case "TimeoutError": return createCopyError("timeout", `The clipboard ${verb} timed out.`, cause);
65
- default: return createCopyError("unknown", message || `The clipboard ${verb} failed for an unknown reason.`, cause);
66
- }
67
- }
68
- const COPY_DESCRIPTIONS = {
69
- unsupported: "Copying isn't supported in this browser.",
70
- "insecure-context": "Copying requires a secure (HTTPS) connection.",
71
- "permission-denied": "Clipboard access was blocked. Allow it and try again.",
72
- "not-focused": "The page lost focus while copying. Try again.",
73
- "invalid-payload": "There is nothing to copy.",
74
- "unsupported-format": "This content can't be copied in this browser.",
75
- "blob-generation-failed": "The image couldn't be prepared for copying.",
76
- "max-retries-exceeded": "Copying failed after several attempts.",
77
- "no-content": "There is nothing to copy.",
78
- "too-large": "This content is too large to copy.",
79
- timeout: "Copying took too long. Try again.",
80
- aborted: "Copying was cancelled.",
81
- unknown: "Couldn't copy to the clipboard. Try again."
82
- };
83
- const PASTE_DESCRIPTIONS = {
84
- unsupported: "Pasting isn't supported in this browser.",
85
- "insecure-context": "Pasting requires a secure (HTTPS) connection.",
86
- "permission-denied": "Clipboard access was blocked. Allow it and try again.",
87
- "not-focused": "The page lost focus while pasting. Try again.",
88
- "invalid-payload": "The clipboard content couldn't be read.",
89
- "unsupported-format": "This clipboard content isn't supported here.",
90
- "blob-generation-failed": "The pasted image couldn't be read.",
91
- "max-retries-exceeded": "Pasting failed after several attempts.",
92
- "no-content": "The clipboard doesn't contain anything that can be pasted here.",
93
- "too-large": "The clipboard content is too large to paste.",
94
- timeout: "Pasting took too long. Try again.",
95
- aborted: "Pasting was cancelled.",
96
- unknown: "Couldn't read the clipboard. Try again."
97
- };
98
- /** Default English, user-facing sentence for a copy error. Replace for i18n. */
99
- function describeCopyError(error) {
100
- return COPY_DESCRIPTIONS[error.type];
101
- }
102
- /** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */
103
- const DROP_DESCRIPTIONS = {
104
- "invalid-payload": "The dropped content couldn't be read.",
105
- "no-content": "Nothing that was dropped can be used here.",
106
- "too-large": "The dropped content is too large.",
107
- unknown: "Couldn't read the dropped content. Try again."
108
- };
109
- /**
110
- * Default English, user-facing sentence for a paste error. Pass the error
111
- * state's `source` to word drag-and-drop failures as drops. Replace for i18n.
112
- */
113
- function describePasteError(error, source) {
114
- return (source === "drop" ? DROP_DESCRIPTIONS[error.type] : void 0) ?? PASTE_DESCRIPTIONS[error.type];
115
- }
116
- //#endregion
117
- //#region src/core/payload.ts
118
- /** The only image MIME type with reliable cross-browser clipboard write support. */
119
- const IMAGE_MIME_TYPE = "image/png";
120
- function normalizePayload(input) {
121
- return typeof input === "string" ? {
122
- kind: "text",
123
- value: input
124
- } : input;
125
- }
126
- function isBlob(value) {
127
- if (typeof Blob !== "undefined" && value instanceof Blob) return true;
128
- const tag = Object.prototype.toString.call(value);
129
- return tag === "[object Blob]" || tag === "[object File]";
130
- }
131
- function isThenable(value) {
132
- return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
133
- }
134
- const invalid$2 = (message) => createCopyError("invalid-payload", message);
135
- /**
136
- * Structural validation. Typed callers can't produce most of these states,
137
- * but plain-JS callers and runtime data can, so the check is always on.
138
- */
139
- function validatePayload(payload) {
140
- if (typeof payload !== "object" || payload === null) return invalid$2("Copy input must be a string or a payload object.");
141
- const candidate = payload;
142
- switch (candidate["kind"]) {
143
- case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid$2("Text payload must be a non-empty string.");
144
- case "html":
145
- if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid$2("HTML payload requires a non-empty `html` string.");
146
- return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid$2("HTML payload requires a non-empty plain-text `text` fallback.");
147
- case "image": {
148
- const source = candidate["blob"];
149
- return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid$2("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
150
- }
151
- case "json": return candidate["value"] === void 0 ? invalid$2("JSON payload value is undefined.") : null;
152
- case "multi": {
153
- const items = candidate["items"];
154
- if (!Array.isArray(items) || items.length === 0) return invalid$2("Multi payload requires at least one item.");
155
- const seen = /* @__PURE__ */ new Set();
156
- for (const item of items) {
157
- const entry = typeof item === "object" && item !== null ? item : {};
158
- const mimeType = entry["mimeType"];
159
- const data = entry["data"];
160
- if (typeof mimeType !== "string" || mimeType.length === 0) return invalid$2("Every multi item needs a non-empty `mimeType`.");
161
- if (seen.has(mimeType)) return invalid$2(`Duplicate MIME type "${mimeType}" in multi payload.`);
162
- seen.add(mimeType);
163
- if (typeof data !== "string" && !isBlob(data)) return invalid$2(`Multi item "${mimeType}" must contain a string or a Blob.`);
164
- }
165
- return null;
166
- }
167
- default: return invalid$2(`Unknown payload kind: ${String(candidate["kind"])}.`);
168
- }
169
- }
170
- /** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */
171
- function serializeJson(payload) {
172
- const indent = payload.pretty === true ? 2 : typeof payload.pretty === "number" ? payload.pretty : void 0;
173
- let text;
174
- try {
175
- text = JSON.stringify(payload.value, null, indent);
176
- } catch (cause) {
177
- throw new CopyFailure(createCopyError("invalid-payload", "JSON payload could not be serialised (circular reference or BigInt?).", cause));
178
- }
179
- if (typeof text !== "string") throw new CopyFailure(createCopyError("invalid-payload", "JSON payload serialised to nothing (functions, symbols and undefined are not JSON)."));
180
- return text;
181
- }
182
- //#endregion
183
- //#region src/core/mime.ts
184
- /**
185
- * MIME helpers shared by paste and capture. Everything that comes from the
186
- * clipboard is untrusted input, so types are normalised and validated before
187
- * they are compared, and image types are confirmed from the bytes themselves.
188
- */
189
- /** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */
190
- const MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
191
- /** SVG is XML that can carry scripts; it is never matched by a wildcard. */
192
- const SVG_MIME_TYPE = "image/svg+xml";
193
- /** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */
194
- function normalizeMimeType(value) {
195
- const separator = value.indexOf(";");
196
- const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();
197
- return MIME_SHAPE.test(base) ? base : null;
198
- }
199
- /** Prefix of the async Clipboard API's web custom formats (`web application/vnd.acme+json`). */
200
- const WEB_CUSTOM_FORMAT_PREFIX = "web ";
201
- /** Whether a clipboard type is a web custom format (`web type/subtype`). */
202
- function isWebCustomFormat(type) {
203
- return type.slice(0, 4).toLowerCase() === WEB_CUSTOM_FORMAT_PREFIX;
204
- }
205
- /**
206
- * Like {@link normalizeMimeType}, but also accepts web custom formats
207
- * (`web type/subtype`), returned as `web ` + the normalised MIME type.
208
- */
209
- function normalizeClipboardType(value) {
210
- if (!isWebCustomFormat(value)) return normalizeMimeType(value);
211
- const inner = normalizeMimeType(value.slice(4));
212
- return inner === null ? null : WEB_CUSTOM_FORMAT_PREFIX + inner;
213
- }
214
- /**
215
- * Types a wildcard never matches, so accepting them must be explicit:
216
- * `image/svg+xml` (scriptable XML), web custom formats and structured `+json` types
217
- * (application-specific data that only the app that defined them should read).
218
- */
219
- function requiresExactMatch(mimeType) {
220
- return mimeType === "image/svg+xml" || isWebCustomFormat(mimeType) || mimeType.endsWith("+json");
221
- }
222
- /**
223
- * Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\/*`)?
224
- * Wildcards never match `image/svg+xml`, web custom formats or `+json` types: those must be listed exactly.
225
- */
226
- function matchesMimePattern(mimeType, pattern) {
227
- if (pattern === mimeType) return true;
228
- if (requiresExactMatch(mimeType)) return false;
229
- if (pattern === "*/*") return true;
230
- return pattern.endsWith("/*") && mimeType.startsWith(pattern.slice(0, -1));
231
- }
232
- /** Types whose clipboard data is text and is therefore surfaced as a `string`. */
233
- function isTextualMimeType(mimeType) {
234
- const type = isWebCustomFormat(mimeType) ? mimeType.slice(4) : mimeType;
235
- return type.startsWith("text/") || type === "image/svg+xml" || type === "application/json" || type === "application/xml" || type.endsWith("+json");
236
- }
237
- const SNIFF_BYTES = 16;
238
- function startsWith(bytes, signature, offset = 0) {
239
- return signature.every((byte, index) => bytes[offset + index] === byte);
240
- }
241
- const ascii = (text) => Array.from(text, (char) => char.charCodeAt(0));
242
- const PNG = [
243
- 137,
244
- 80,
245
- 78,
246
- 71,
247
- 13,
248
- 10,
249
- 26,
250
- 10
251
- ];
252
- const JPEG = [
253
- 255,
254
- 216,
255
- 255
256
- ];
257
- const GIF = ascii("GIF8");
258
- const RIFF = ascii("RIFF");
259
- const WEBP = ascii("WEBP");
260
- const BMP = ascii("BM");
261
- const FTYP_AVIF = ascii("ftypavif");
262
- const FTYP_AVIS = ascii("ftypavis");
263
- /** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */
264
- function sniffImageBytes(bytes) {
265
- if (startsWith(bytes, PNG)) return "image/png";
266
- if (startsWith(bytes, JPEG)) return "image/jpeg";
267
- if (startsWith(bytes, GIF)) return "image/gif";
268
- if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return "image/webp";
269
- if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return "image/avif";
270
- if (startsWith(bytes, BMP)) return "image/bmp";
271
- return null;
272
- }
273
- /** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */
274
- async function sniffImageType(blob) {
275
- const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();
276
- return sniffImageBytes(new Uint8Array(head));
277
- }
278
- //#endregion
279
- //#region src/core/clipboard-adapter.ts
280
- const fail = (type, message, cause) => new CopyFailure(createCopyError(type, message, cause));
281
- const noop = () => void 0;
282
- function defaultEnvironment$1() {
283
- return typeof window === "undefined" ? void 0 : window;
284
- }
285
- function getRichClipboard(env, clipboard) {
286
- const Item = env.ClipboardItem;
287
- if (!Item || typeof clipboard.write !== "function") return null;
288
- return {
289
- Item,
290
- write: clipboard.write.bind(clipboard)
291
- };
292
- }
293
- function isTypeSupported(Item, type) {
294
- return typeof Item.supports !== "function" || Item.supports(type);
295
- }
296
- function writeText(clipboard, text) {
297
- if (typeof clipboard.writeText !== "function") throw fail("unsupported", "navigator.clipboard.writeText() is not available.");
298
- return clipboard.writeText(text);
299
- }
300
- async function resolveImageBlob(source, context) {
301
- let blob;
302
- try {
303
- blob = await (typeof source === "function" ? source(context ?? { signal: new AbortController().signal }) : source);
304
- } catch (cause) {
305
- if (context?.signal.aborted) throw fail("aborted", "The image copy was cancelled.", cause);
306
- throw fail("blob-generation-failed", "The image source threw or rejected while producing a Blob.", cause);
307
- }
308
- if (!isBlob(blob)) throw fail("blob-generation-failed", "The image source did not produce a Blob.");
309
- if (blob.type !== "image/png") throw fail("unsupported-format", `Only ${IMAGE_MIME_TYPE} can be written to the clipboard (received "${blob.type || "unknown"}"). Convert with canvas.toBlob(cb, "${IMAGE_MIME_TYPE}").`);
310
- return blob;
311
- }
312
- async function writeImage(rich, source, context) {
313
- if (!isTypeSupported(rich.Item, "image/png")) throw fail("unsupported-format", `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);
314
- const blob = resolveImageBlob(source, context);
315
- blob.catch(noop);
316
- try {
317
- await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);
318
- } catch (error) {
319
- throw await blob.then(noop, (inner) => inner) ?? error;
320
- }
321
- await blob;
322
- }
323
- async function writeToClipboard(payload, env, degradeHtmlToText, context) {
324
- if (!env) throw fail("unsupported", "No browser environment: the clipboard only exists in the browser.");
325
- if (env.isSecureContext === false) throw fail("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
326
- const clipboard = env.navigator?.clipboard;
327
- if (!clipboard) throw fail("unsupported", "navigator.clipboard is not available in this browser.");
328
- switch (payload.kind) {
329
- case "text": return writeText(clipboard, payload.value);
330
- case "json": return writeText(clipboard, serializeJson(payload));
331
- case "html": {
332
- const rich = getRichClipboard(env, clipboard);
333
- if (!rich || !isTypeSupported(rich.Item, "text/html")) {
334
- if (degradeHtmlToText) return writeText(clipboard, payload.text);
335
- throw fail("unsupported-format", "Rich HTML copy requires ClipboardItem and navigator.clipboard.write().");
336
- }
337
- return rich.write([new rich.Item({
338
- "text/html": new Blob([payload.html], { type: "text/html" }),
339
- "text/plain": new Blob([payload.text], { type: "text/plain" })
340
- })]);
341
- }
342
- case "image": {
343
- const rich = getRichClipboard(env, clipboard);
344
- if (!rich) throw fail("unsupported-format", "Image copy requires ClipboardItem and navigator.clipboard.write().");
345
- return writeImage(rich, payload.blob, context);
346
- }
347
- case "multi": {
348
- const rich = getRichClipboard(env, clipboard);
349
- if (!rich) throw fail("unsupported-format", "Multi-format copy requires ClipboardItem and navigator.clipboard.write().");
350
- const record = Object.create(null);
351
- let written = 0;
352
- for (const { mimeType, data, optional } of payload.items) {
353
- if (optional === true && !(typeof rich.Item.supports === "function" && rich.Item.supports(mimeType))) continue;
354
- if (!isTypeSupported(rich.Item, mimeType)) throw fail("unsupported-format", `This browser cannot write "${mimeType}" to the clipboard.`);
355
- record[mimeType] = typeof data === "string" ? new Blob([data], { type: mimeType }) : data;
356
- written += 1;
357
- }
358
- if (written === 0) throw fail("unsupported-format", "This browser can write none of the payload types.");
359
- return rich.write([new rich.Item(record)]);
360
- }
361
- }
362
- }
363
- /** The default adapter: async Clipboard API with feature detection and honest errors. */
364
- function createBrowserClipboardAdapter(options = {}) {
365
- const getEnvironment = options.getEnvironment ?? defaultEnvironment$1;
366
- const degradeHtmlToText = options.degradeHtmlToText ?? true;
367
- return { write: (payload, context) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText, context) };
368
- }
369
- //#endregion
370
- //#region src/core/copy-coordinator.ts
371
- function createCopyCoordinator() {
372
- let active = null;
373
- return {
374
- activate: (member) => {
375
- const previous = active;
376
- active = member;
377
- if (previous !== null && previous !== member) previous.release();
378
- },
379
- deactivate: (member) => {
380
- if (active === member) active = null;
381
- },
382
- getActive: () => active
383
- };
384
- }
385
- //#endregion
386
- //#region src/core/machine-shared.ts
387
- /**
388
- * Internals shared by the copy and paste state machines. Kept in one module so
389
- * apps that use both don't ship two copies.
390
- */
391
- const DEFAULT_MAX_RETRIES = 3;
392
- function resolveMaxRetries(value) {
393
- if (value === Infinity) return Infinity;
394
- if (value === void 0 || !Number.isFinite(value)) return 3;
395
- return Math.max(0, Math.floor(value));
396
- }
397
- function reportCallbackError(error) {
398
- const scope = globalThis;
399
- if (typeof scope.reportError === "function") scope.reportError(error);
400
- else setTimeout(() => {
401
- throw error;
402
- }, 0);
403
- }
404
- /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
405
- function invoke(fn, ...args) {
406
- if (!fn) return;
407
- try {
408
- fn(...args);
409
- } catch (error) {
410
- reportCallbackError(error);
411
- }
412
- }
413
- /** One cancellable operation at a time. Signals only fire while their operation is unfinished. */
414
- function createOperations() {
415
- let controller;
416
- const abort = () => {
417
- if (!controller) return false;
418
- controller.abort();
419
- controller = void 0;
420
- return true;
421
- };
422
- return {
423
- start: () => {
424
- abort();
425
- controller = new AbortController();
426
- return { signal: controller.signal };
427
- },
428
- end: (context) => {
429
- if (controller?.signal === context.signal) controller = void 0;
430
- },
431
- abort
432
- };
433
- }
434
- //#endregion
435
- //#region src/core/source-error.ts
436
- /**
437
- * The error for a user-supplied source (copy source, drag source, copy transform)
438
- * that threw. A thrown `CopyFailure` keeps its classification, so a helper such as
439
- * `tablePayload()` can report `too-large` instead of a generic `invalid-payload`.
440
- * Internal: not part of the public API.
441
- */
442
- function sourceError(cause, message) {
443
- return isCopyFailure(cause) ? cause.copyError : createCopyError("invalid-payload", message, cause);
444
- }
445
- //#endregion
446
- //#region src/core/copy-machine.ts
447
- const DEFAULT_RESET_AFTER_MS = 2e3;
448
- const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
449
- const IGNORED_IN_FLIGHT$1 = /* @__PURE__ */ Object.freeze({
450
- status: "ignored",
451
- reason: "in-flight"
452
- });
453
- const IGNORED_NOTHING$1 = /* @__PURE__ */ Object.freeze({
454
- status: "ignored",
455
- reason: "nothing-to-retry"
456
- });
457
- const IGNORED_NOT_RETRYABLE$1 = /* @__PURE__ */ Object.freeze({
458
- status: "ignored",
459
- reason: "not-retryable"
460
- });
461
- const IGNORED_CANCELLED$1 = /* @__PURE__ */ Object.freeze({
462
- status: "ignored",
463
- reason: "cancelled"
464
- });
465
- function resolveResetDelay$1(value) {
466
- if (value === false || value === Infinity) return null;
467
- if (value === void 0 || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;
468
- return Math.max(0, value);
469
- }
470
- /** Pure helper: can `retry()` do anything from this state? */
471
- function canRetryState(state, maxRetries) {
472
- return state.status === "error" && state.payload !== null && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
473
- }
474
- let defaultAdapter$1;
475
- const getDefaultAdapter$1 = () => defaultAdapter$1 ?? (defaultAdapter$1 = createBrowserClipboardAdapter());
476
- /** Framework-agnostic copy state machine. */
477
- function createCopyMachine(options = {}) {
478
- const read = typeof options === "function" ? options : () => options;
479
- const listeners = /* @__PURE__ */ new Set();
480
- let state = IDLE_STATE;
481
- let generation = 0;
482
- let resetTimer;
483
- const operations = createOperations();
484
- const now = () => (read().now ?? Date.now)();
485
- let joined = null;
486
- const member = { release: () => {
487
- if (state.status === "copied") {
488
- clearResetTimer();
489
- setState(IDLE_STATE);
490
- }
491
- } };
492
- const setState = (next) => {
493
- if (next === state) return;
494
- const previous = state;
495
- state = next;
496
- if (previous.status === "copied" && next.status !== "copied" && joined) {
497
- joined.deactivate(member);
498
- joined = null;
499
- }
500
- for (const listener of Array.from(listeners)) listener();
501
- };
502
- const joinCoordinator = () => {
503
- joined = read().coordinator ?? null;
504
- joined?.activate(member);
505
- };
506
- const clearResetTimer = () => {
507
- if (resetTimer !== void 0) {
508
- clearTimeout(resetTimer);
509
- resetTimer = void 0;
510
- }
511
- };
512
- const scheduleReset = (copied) => {
513
- clearResetTimer();
514
- const delay = resolveResetDelay$1(read().resetAfterMs);
515
- if (delay === null) return;
516
- const remaining = Math.max(0, delay - (now() - copied.at));
517
- resetTimer = setTimeout(() => {
518
- resetTimer = void 0;
519
- setState(IDLE_STATE);
520
- }, remaining);
521
- };
522
- const settleError = (error, payload, retryCount) => {
523
- setState({
524
- status: "error",
525
- payload,
526
- error,
527
- retryCount
528
- });
529
- invoke(read().onError, error, payload);
530
- };
531
- const run = (source, retryCount) => {
532
- clearResetTimer();
533
- const current = ++generation;
534
- let payload;
535
- try {
536
- const resolved = typeof source === "function" ? source() : source;
537
- const resolvedUnknown = resolved;
538
- if (resolvedUnknown !== null && typeof resolvedUnknown === "object" && typeof resolvedUnknown.then === "function") {
539
- const error = createCopyError("invalid-payload", "The copy source function must be synchronous. Returning a Promise breaks the user-gesture window required for clipboard writes. Generate your content before calling copy().");
540
- settleError(error, null, retryCount);
541
- return Promise.resolve({
542
- status: "error",
543
- error
544
- });
545
- }
546
- payload = normalizePayload(resolved);
547
- } catch (cause) {
548
- const error = sourceError(cause, "The copy source function threw.");
549
- settleError(error, null, retryCount);
550
- return Promise.resolve({
551
- status: "error",
552
- error
553
- });
554
- }
555
- const invalid = validatePayload(payload);
556
- if (invalid) {
557
- settleError(invalid, payload, retryCount);
558
- return Promise.resolve({
559
- status: "error",
560
- error: invalid
561
- });
562
- }
563
- setState({
564
- status: "copying",
565
- payload,
566
- retryCount
567
- });
568
- const context = operations.start();
569
- let pending;
570
- try {
571
- pending = (read().adapter ?? getDefaultAdapter$1()).write(payload, context);
572
- } catch (cause) {
573
- pending = Promise.reject(cause);
574
- }
575
- return pending.then(() => {
576
- operations.end(context);
577
- if (current === generation) {
578
- const copied = {
579
- status: "copied",
580
- payload,
581
- at: now()
582
- };
583
- setState(copied);
584
- joinCoordinator();
585
- scheduleReset(copied);
586
- invoke(read().onCopy, payload);
587
- }
588
- return {
589
- status: "copied",
590
- payload
591
- };
592
- }, (cause) => {
593
- operations.end(context);
594
- if (context.signal.aborted) return IGNORED_CANCELLED$1;
595
- const error = toCopyError(cause);
596
- settleError(error, payload, retryCount);
597
- return {
598
- status: "error",
599
- error
600
- };
601
- });
602
- };
603
- const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT$1) : run(source, 0);
604
- const retry = () => {
605
- if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING$1);
606
- if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE$1);
607
- if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
608
- const error = createCopyError("max-retries-exceeded", `Copy failed after ${String(state.retryCount)} retries.`, state.error);
609
- settleError(error, state.payload, state.retryCount);
610
- return Promise.resolve({
611
- status: "error",
612
- error
613
- });
614
- }
615
- return run(state.payload, state.retryCount + 1);
616
- };
617
- const reset = () => {
618
- ++generation;
619
- const cancelled = operations.abort();
620
- clearResetTimer();
621
- const wasIdle = state.status === "idle";
622
- setState(IDLE_STATE);
623
- if (cancelled) invoke(read().onCancel, "reset");
624
- if (!wasIdle) invoke(read().onReset);
625
- };
626
- const connect = () => {
627
- if (state.status === "copied") scheduleReset(state);
628
- return () => {
629
- ++generation;
630
- const cancelled = operations.abort();
631
- clearResetTimer();
632
- if (state.status === "copying") setState(IDLE_STATE);
633
- if (cancelled) invoke(read().onCancel, "disconnect");
634
- };
635
- };
636
- return {
637
- getSnapshot: () => state,
638
- subscribe: (listener) => {
639
- listeners.add(listener);
640
- return () => {
641
- listeners.delete(listener);
642
- };
643
- },
644
- copy,
645
- retry,
646
- reset,
647
- connect
648
- };
649
- }
650
- //#endregion
651
- //#region src/core/copy-interceptor.ts
652
- const DEFAULT_INTERCEPTED_EVENTS = ["copy", "cut"];
653
- function isNode(value) {
654
- return typeof value === "object" && value !== null && typeof value.nodeType === "number";
655
- }
656
- function readTextField(target) {
657
- if (!isNode(target) || target.nodeType !== 1) return null;
658
- const tag = target.tagName;
659
- if (tag !== "INPUT" && tag !== "TEXTAREA") return null;
660
- const field = target;
661
- try {
662
- const { selectionStart: start, selectionEnd: end } = field;
663
- return typeof start === "number" && typeof end === "number" ? {
664
- field,
665
- start,
666
- end
667
- } : null;
668
- } catch {
669
- return null;
670
- }
671
- }
672
- function documentOf(target) {
673
- if (isNode(target)) return target.nodeType === 9 ? target : target.ownerDocument;
674
- return typeof document === "undefined" ? null : document;
675
- }
676
- function isEditableNode(node) {
677
- return (node.nodeType === 1 ? node : node.parentElement)?.isContentEditable === true;
678
- }
679
- function selectedRanges(doc) {
680
- const selection = doc?.getSelection();
681
- if (!selection || selection.isCollapsed) return null;
682
- const ranges = [];
683
- for (let index = 0; index < selection.rangeCount; index += 1) ranges.push(selection.getRangeAt(index));
684
- return {
685
- selection,
686
- ranges
687
- };
688
- }
689
- function readSelection(event) {
690
- const kind = event.type === "cut" ? "cut" : "copy";
691
- const fieldSelection = readTextField(event.target);
692
- if (fieldSelection) {
693
- const { field, start, end } = fieldSelection;
694
- const text = field.value.slice(Math.min(start, end), Math.max(start, end));
695
- if (text.length === 0) return null;
696
- return {
697
- selection: {
698
- kind,
699
- text,
700
- html: null,
701
- fragment: null,
702
- field,
703
- editable: !field.readOnly && !field.disabled
704
- },
705
- doc: field.ownerDocument
706
- };
707
- }
708
- const doc = documentOf(event.target);
709
- const selected = selectedRanges(doc);
710
- const first = selected?.ranges[0];
711
- if (!doc || !selected || !first) return null;
712
- const text = selected.selection.toString();
713
- if (text.length === 0) return null;
714
- const container = doc.createElement("div");
715
- for (const range of selected.ranges) container.appendChild(range.cloneContents());
716
- const html = container.innerHTML;
717
- const fragment = doc.createDocumentFragment();
718
- while (container.firstChild) fragment.appendChild(container.firstChild);
719
- return {
720
- selection: {
721
- kind,
722
- text,
723
- html,
724
- fragment,
725
- field: null,
726
- editable: isEditableNode(first.startContainer)
727
- },
728
- doc
729
- };
730
- }
731
- /** Reads the selection behind a copy event, or `null` if nothing readable is selected. */
732
- function readCopySelection(event) {
733
- const read = readSelection(event);
734
- return read ? read.selection : null;
735
- }
736
- const nonEmpty$1 = (value) => typeof value === "string" && value.length > 0;
737
- const invalid$1 = (message, cause) => ({
738
- ok: false,
739
- error: createCopyError("invalid-payload", message, cause)
740
- });
741
- const unsupported$1 = (message) => ({
742
- ok: false,
743
- error: createCopyError("unsupported-format", message)
744
- });
745
- /**
746
- * Validates a decision and turns it into `[mimeType, data]` pairs. Kept
747
- * self-contained (no shared validator) so the interceptor stays small; the
748
- * checks still run for plain-JS callers the types can't protect.
749
- */
750
- function prepare(decision) {
751
- const candidate = typeof decision === "string" ? {
752
- kind: "text",
753
- value: decision
754
- } : decision;
755
- if (typeof candidate !== "object" || candidate === null) return invalid$1("Copy transforms must return a string, a payload, false, or nothing.");
756
- if (typeof candidate.then === "function") return invalid$1("Copy transforms must be synchronous; the clipboard closes when the event ends.");
757
- const payload = candidate;
758
- const fields = candidate;
759
- const ok = (entries) => ({
760
- ok: true,
761
- payload,
762
- entries
763
- });
764
- switch (fields["kind"]) {
765
- case "text": return nonEmpty$1(fields["value"]) ? ok([["text/plain", fields["value"]]]) : invalid$1("Text payload must be a non-empty string.");
766
- case "html": return nonEmpty$1(fields["html"]) && nonEmpty$1(fields["text"]) ? ok([["text/html", fields["html"]], ["text/plain", fields["text"]]]) : invalid$1("HTML payload requires non-empty `html` and plain-text `text`.");
767
- case "json": {
768
- const pretty = fields["pretty"];
769
- const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
770
- let json;
771
- try {
772
- json = JSON.stringify(fields["value"], null, indent);
773
- } catch (cause) {
774
- return invalid$1("JSON payload could not be serialised (circular reference or BigInt?).", cause);
775
- }
776
- return typeof json === "string" ? ok([["text/plain", json]]) : invalid$1("JSON payload serialised to nothing.");
777
- }
778
- case "multi": {
779
- const items = fields["items"];
780
- if (!Array.isArray(items) || items.length === 0) return invalid$1("Multi payload requires at least one item.");
781
- const entries = [];
782
- for (const item of items) {
783
- const { mimeType, data } = item ?? {};
784
- if (!nonEmpty$1(mimeType) || entries.some(([seen]) => seen === mimeType)) return invalid$1("Every multi item needs a unique, non-empty `mimeType`.");
785
- if (typeof data !== "string") return unsupported$1(`Multi item "${mimeType}" must be a string during a copy event.`);
786
- entries.push([mimeType, data]);
787
- }
788
- const writable = entries.filter(([mimeType]) => !isWebCustomFormat(mimeType));
789
- return writable.length > 0 ? ok(writable) : unsupported$1("Web custom formats need the async Clipboard API (useCopy).");
790
- }
791
- default: return unsupported$1(`"${String(fields["kind"])}" payloads cannot be written during a copy event; use useCopy() for images.`);
792
- }
793
- }
794
- /** Deletes the selection the way a native cut would (keeps undo history, fires `input`). */
795
- function deleteSelection(doc) {
796
- const legacy = doc;
797
- try {
798
- return legacy.execCommand?.("delete") === true;
799
- } catch {
800
- return false;
801
- }
802
- }
803
- /**
804
- * Applies a transform to one `copy`/`cut` event. Use directly from an
805
- * `onCopy` handler, or let {@link registerCopyInterceptor} scope it.
806
- */
807
- function interceptCopyEvent(event, options) {
808
- if (event.type !== "copy" && event.type !== "cut") return {
809
- status: "passed",
810
- reason: "unsupported-event",
811
- selection: null
812
- };
813
- if (event.defaultPrevented) return {
814
- status: "passed",
815
- reason: "already-handled",
816
- selection: null
817
- };
818
- const read = readSelection(event);
819
- if (!read) return {
820
- status: "passed",
821
- reason: "no-selection",
822
- selection: null
823
- };
824
- const { selection, doc } = read;
825
- const fail = (error) => {
826
- const fallback = options.failureMode ?? "block";
827
- if (fallback === "block") event.preventDefault();
828
- return {
829
- status: "failed",
830
- selection,
831
- error,
832
- fallback
833
- };
834
- };
835
- let decision;
836
- try {
837
- decision = options.transform(selection);
838
- } catch (cause) {
839
- return fail(sourceError(cause, "The copy transform threw."));
840
- }
841
- if (decision === null || decision === void 0) return {
842
- status: "passed",
843
- reason: "declined",
844
- selection
845
- };
846
- if (decision === false) {
847
- event.preventDefault();
848
- return {
849
- status: "blocked",
850
- selection
851
- };
852
- }
853
- const prepared = prepare(decision);
854
- if (!prepared.ok) return fail(prepared.error);
855
- const data = event.clipboardData;
856
- if (!data) return fail(createCopyError("unsupported", "This browser exposes no clipboardData on copy events."));
857
- event.preventDefault();
858
- try {
859
- for (const [mimeType, value] of prepared.entries) data.setData(mimeType, value);
860
- } catch (cause) {
861
- try {
862
- data.clearData?.();
863
- } catch {}
864
- return {
865
- status: "failed",
866
- selection,
867
- error: createCopyError("unknown", "The browser rejected the clipboard write.", cause),
868
- fallback: "block"
869
- };
870
- }
871
- const deleted = selection.kind === "cut" && selection.editable && deleteSelection(doc);
872
- return {
873
- status: "written",
874
- selection,
875
- payload: prepared.payload,
876
- deleted
877
- };
878
- }
879
- const registries = /* @__PURE__ */ new WeakMap();
880
- function touches(root, event) {
881
- const fieldSelection = readTextField(event.target);
882
- if (fieldSelection) return root.contains(fieldSelection.field);
883
- const selected = selectedRanges(root.ownerDocument);
884
- return selected !== null && selected.ranges.some((range) => range.intersectsNode(root));
885
- }
886
- const priorityOf = (scope) => scope.read().priority ?? 0;
887
- /**
888
- * Highest `priority` first; then the innermost scope; then document order;
889
- * then registration order (same root). A total order, so the result never
890
- * depends on effect timing.
891
- */
892
- function compareScopes(a, b) {
893
- const byPriority = priorityOf(b) - priorityOf(a);
894
- if (byPriority !== 0) return byPriority;
895
- const position = a.root.compareDocumentPosition(b.root);
896
- if (position === 0) return 0;
897
- if (position & 16) return 1;
898
- if (position & 8) return -1;
899
- return position & 4 ? -1 : 1;
900
- }
901
- function dispatch(registry, event) {
902
- if (event.defaultPrevented) return;
903
- const kind = event.type;
904
- const [scope] = [...registry.scopes].filter((scope) => (scope.read().events ?? DEFAULT_INTERCEPTED_EVENTS).includes(kind) && touches(scope.root, event)).sort(compareScopes);
905
- if (!scope) return;
906
- const options = scope.read();
907
- const outcome = interceptCopyEvent(event, options);
908
- invoke(options.onIntercept, outcome);
909
- if (outcome.status === "failed") invoke(options.onError, outcome.error);
910
- }
911
- /**
912
- * Intercepts native copies and cuts whose selection touches `root`. Returns
913
- * an unsubscribe function. Pass a getter to always read the latest options.
914
- *
915
- * One listener per document serves every scope, so overlapping scopes
916
- * resolve deterministically (see `priority`) regardless of registration order.
917
- * Handlers that call `preventDefault()` first (e.g. a React `onCopy`) win.
918
- */
919
- function registerCopyInterceptor(root, options) {
920
- const doc = root.ownerDocument;
921
- let registry = registries.get(doc);
922
- if (!registry) {
923
- const created = {
924
- scopes: /* @__PURE__ */ new Set(),
925
- listener: (event) => {
926
- dispatch(created, event);
927
- }
928
- };
929
- registry = created;
930
- registries.set(doc, created);
931
- doc.addEventListener("copy", created.listener);
932
- doc.addEventListener("cut", created.listener);
933
- }
934
- const scope = {
935
- root,
936
- read: typeof options === "function" ? options : () => options
937
- };
938
- registry.scopes.add(scope);
939
- const active = registry;
940
- let registered = true;
941
- return () => {
942
- if (!registered) return;
943
- registered = false;
944
- active.scopes.delete(scope);
945
- if (active.scopes.size === 0) {
946
- doc.removeEventListener("copy", active.listener);
947
- doc.removeEventListener("cut", active.listener);
948
- registries.delete(doc);
949
- }
950
- };
951
- }
952
- //#endregion
953
- //#region src/core/drag-copy.ts
954
- /**
955
- * Drag-to-copy: populate `DataTransfer` when the user starts dragging an
956
- * element, so whatever they drop it into receives structured data — plain text,
957
- * HTML, JSON, or multiple MIME types — instead of the browser's default
958
- * text-extraction of the dragged DOM.
959
- *
960
- * No Clipboard API, no permission prompt, works in every browser that supports
961
- * HTML5 drag-and-drop (all modern browsers and IE11+).
962
- */
963
- const nonEmpty = (value) => typeof value === "string" && value.length > 0;
964
- const invalid = (message, cause) => ({
965
- ok: false,
966
- error: createCopyError("invalid-payload", message, cause)
967
- });
968
- const unsupported = (message) => ({
969
- ok: false,
970
- error: createCopyError("unsupported-format", message)
971
- });
972
- function prepareDragDecision(decision) {
973
- const candidate = typeof decision === "string" ? {
974
- kind: "text",
975
- value: decision
976
- } : decision;
977
- if (typeof candidate !== "object" || candidate === null) return invalid("Drag source must return a string, a payload, false, or nothing.");
978
- if (typeof candidate.then === "function") return invalid("Drag sources must be synchronous; DataTransfer closes when dragstart returns.");
979
- const payload = candidate;
980
- const fields = candidate;
981
- const ok = (items) => ({
982
- ok: true,
983
- payload,
984
- items
985
- });
986
- switch (fields["kind"]) {
987
- case "text": return nonEmpty(fields["value"]) ? ok([{
988
- mimeType: "text/plain",
989
- data: fields["value"]
990
- }]) : invalid("Text payload must be a non-empty string.");
991
- case "html": return nonEmpty(fields["html"]) && nonEmpty(fields["text"]) ? ok([{
992
- mimeType: "text/html",
993
- data: fields["html"]
994
- }, {
995
- mimeType: "text/plain",
996
- data: fields["text"]
997
- }]) : invalid("HTML payload requires non-empty `html` and `text`.");
998
- case "json": {
999
- const pretty = fields["pretty"];
1000
- const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
1001
- let json;
1002
- try {
1003
- json = JSON.stringify(fields["value"], null, indent);
1004
- } catch (cause) {
1005
- return invalid("JSON payload could not be serialised (circular reference or BigInt?).", cause);
1006
- }
1007
- return typeof json === "string" ? ok([{
1008
- mimeType: "text/plain",
1009
- data: json
1010
- }]) : invalid("JSON payload serialised to nothing.");
1011
- }
1012
- case "multi": {
1013
- const items = fields["items"];
1014
- if (!Array.isArray(items) || items.length === 0) return invalid("Multi payload requires at least one item.");
1015
- const out = [];
1016
- for (const item of items) {
1017
- const { mimeType, data } = item ?? {};
1018
- if (!nonEmpty(mimeType) || out.some((i) => i.mimeType === mimeType)) return invalid("Every multi item needs a unique, non-empty `mimeType`.");
1019
- if (typeof data !== "string") return unsupported(`Multi item "${mimeType}" must be a string; DataTransfer does not accept Blobs.`);
1020
- out.push({
1021
- mimeType,
1022
- data
1023
- });
1024
- }
1025
- const writable = out.filter((item) => !isWebCustomFormat(item.mimeType));
1026
- return writable.length > 0 ? ok(writable) : unsupported("Web custom formats need the async Clipboard API (useCopy).");
1027
- }
1028
- default: return unsupported(`"${String(fields["kind"])}" payloads cannot be used for drag-copy; use useCopy() for images.`);
1029
- }
1030
- }
1031
- /**
1032
- * Populates a `dragstart` event's `DataTransfer` with the given payload.
1033
- * Use this from a raw `dragstart` handler or a React `onDragStart` prop.
1034
- * Returns the outcome so you can inspect what happened.
1035
- */
1036
- function applyDragCopy(event, options) {
1037
- if (event.defaultPrevented) return {
1038
- status: "passed",
1039
- reason: "declined"
1040
- };
1041
- let decision;
1042
- try {
1043
- decision = options.source(event);
1044
- } catch (cause) {
1045
- return {
1046
- status: "failed",
1047
- error: sourceError(cause, "The drag source threw.")
1048
- };
1049
- }
1050
- if (decision === null || decision === void 0) return {
1051
- status: "passed",
1052
- reason: "declined"
1053
- };
1054
- if (decision === false) {
1055
- event.preventDefault();
1056
- return {
1057
- status: "passed",
1058
- reason: "cancelled"
1059
- };
1060
- }
1061
- const transfer = event.dataTransfer;
1062
- if (!transfer) return {
1063
- status: "passed",
1064
- reason: "no-transfer"
1065
- };
1066
- const prepared = prepareDragDecision(decision);
1067
- if (!prepared.ok) return {
1068
- status: "failed",
1069
- error: prepared.error
1070
- };
1071
- try {
1072
- transfer.effectAllowed = options.effectAllowed ?? "copy";
1073
- for (const { mimeType, data } of prepared.items) transfer.setData(mimeType, data);
1074
- } catch (cause) {
1075
- try {
1076
- transfer.clearData?.();
1077
- } catch {}
1078
- return {
1079
- status: "failed",
1080
- error: createCopyError("unknown", "The browser rejected the DataTransfer write.", cause)
1081
- };
1082
- }
1083
- return {
1084
- status: "written",
1085
- payload: prepared.payload
1086
- };
1087
- }
1088
- /**
1089
- * Attaches `dragstart` and `dragend` listeners to `element`, calling
1090
- * `applyDragCopy` on every drag start. Returns an object with an
1091
- * `unsubscribe` function.
1092
- *
1093
- * Pass an options getter so the latest options are always used without
1094
- * re-registering — safe to pass an inline object from a React render.
1095
- *
1096
- * ```ts
1097
- * const { unsubscribe } = registerDragCopy(el, () => ({
1098
- * source: () => `${title}\n${url}`,
1099
- * }));
1100
- * ```
1101
- */
1102
- function registerDragCopy(element, options) {
1103
- const read = typeof options === "function" ? options : () => options;
1104
- let unsubscribed = false;
1105
- let currentOutcome = null;
1106
- function onDragStart(raw) {
1107
- const event = raw;
1108
- const opts = read();
1109
- const outcome = applyDragCopy({
1110
- type: event.type,
1111
- dataTransfer: event.dataTransfer,
1112
- get defaultPrevented() {
1113
- return event.defaultPrevented;
1114
- },
1115
- preventDefault: () => {
1116
- event.preventDefault();
1117
- }
1118
- }, opts);
1119
- currentOutcome = outcome;
1120
- const state = {
1121
- status: "dragging",
1122
- outcome
1123
- };
1124
- if (outcome.status === "failed") invoke(opts.onError, outcome.error);
1125
- invoke(opts.onDrag, state);
1126
- }
1127
- function onDragEnd() {
1128
- const opts = read();
1129
- const state = {
1130
- status: "done",
1131
- outcome: currentOutcome
1132
- };
1133
- invoke(opts.onDrag, state);
1134
- currentOutcome = null;
1135
- }
1136
- element.setAttribute("draggable", "true");
1137
- element.addEventListener("dragstart", onDragStart);
1138
- element.addEventListener("dragend", onDragEnd);
1139
- return { unsubscribe() {
1140
- if (unsubscribed) return;
1141
- unsubscribed = true;
1142
- element.removeEventListener("dragstart", onDragStart);
1143
- element.removeEventListener("dragend", onDragEnd);
1144
- element.removeAttribute("draggable");
1145
- } };
1146
- }
1147
- //#endregion
1148
- //#region src/core/paste-reader.ts
1149
- /** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
1150
- function completePasteResult(result) {
1151
- const images = new Set(result.images);
1152
- return {
1153
- ...result,
1154
- imageFiles: result.files.filter((file) => images.has(file))
1155
- };
1156
- }
1157
- const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
1158
- const DEFAULT_PASTE_MAX_BYTES = 33554432;
1159
- const DEFAULT_PASTE_MAX_ITEMS = 32;
1160
- const SHORTHANDS = /* @__PURE__ */ new Map([
1161
- ["text", "text/plain"],
1162
- ["html", "text/html"],
1163
- ["image", "image/*"],
1164
- ["any", "*/*"]
1165
- ]);
1166
- const TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
1167
- function resolvePattern(entry) {
1168
- if (typeof entry !== "string") return null;
1169
- const shorthand = SHORTHANDS.get(entry);
1170
- if (shorthand !== void 0) return shorthand;
1171
- if (entry === "*/*") return entry;
1172
- if (entry.endsWith("/*")) {
1173
- const type = entry.slice(0, -2).toLowerCase();
1174
- return TYPE_TOKEN.test(type) ? `${type}/*` : null;
1175
- }
1176
- return normalizeClipboardType(entry);
1177
- }
1178
- function resolveLimit(value, fallback, name) {
1179
- if (value === void 0) return fallback;
1180
- if (value === Infinity || Number.isInteger(value) && value > 0) return value;
1181
- throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
1182
- }
1183
- /** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
1184
- function resolvePasteReadOptions(options = {}) {
1185
- const accept = [];
1186
- for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {
1187
- const pattern = resolvePattern(entry);
1188
- if (pattern === null) throw copyFailure("invalid-payload", `Invalid \`accept\` entry: ${JSON.stringify(entry)}.`);
1189
- if (!accept.includes(pattern)) accept.push(pattern);
1190
- }
1191
- if (accept.length === 0) throw copyFailure("invalid-payload", "`accept` must list at least one type.");
1192
- return {
1193
- accept,
1194
- maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, "maxBytes"),
1195
- maxItems: resolveLimit(options.maxItems, 32, "maxItems")
1196
- };
1197
- }
1198
- /** Whether a normalised MIME type is allowed by the resolved `accept` list. */
1199
- function isAccepted(mimeType, options) {
1200
- return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));
1201
- }
1202
- function createBudget(options) {
1203
- let bytes = 0;
1204
- let items = 0;
1205
- return { charge: (size) => {
1206
- items += 1;
1207
- bytes += size;
1208
- if (items > options.maxItems) throw copyFailure("too-large", `The paste has more than ${String(options.maxItems)} accepted items.`);
1209
- if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
1210
- } };
1211
- }
1212
- /**
1213
- * UTF-8 byte length of a string, without allocating an encoded copy.
1214
- * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.
1215
- */
1216
- function utf8ByteLength(text) {
1217
- let bytes = 0;
1218
- for (let i = 0; i < text.length; i += 1) {
1219
- const unit = text.charCodeAt(i);
1220
- if (unit < 128) bytes += 1;
1221
- else if (unit < 2048) bytes += 2;
1222
- else if (unit >= 55296 && unit <= 56319 && i + 1 < text.length && (text.charCodeAt(i + 1) & 64512) === 56320) {
1223
- bytes += 4;
1224
- i += 1;
1225
- } else bytes += 3;
1226
- }
1227
- return bytes;
1228
- }
1229
- /** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */
1230
- const sizeOf = (data) => typeof data === "string" ? utf8ByteLength(data) : data.size;
1231
- /** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
1232
- function enforcePasteLimits(entries, options) {
1233
- const budget = createBudget(options);
1234
- for (const entry of entries) budget.charge(sizeOf(entry.data));
1235
- }
1236
- /**
1237
- * Whether a drag in progress could drop anything `accept`s. Uses only what
1238
- * browsers expose before the drop (item kinds and types, never the data).
1239
- * A file whose type is not known yet (some browsers hide it while dragging)
1240
- * counts as a maybe: the drop itself is checked against `accept`.
1241
- */
1242
- function canAcceptDrag(data, options) {
1243
- const items = data.items ?? Array.from(data.types, (type) => type === "Files" ? {
1244
- kind: "file",
1245
- type: ""
1246
- } : {
1247
- kind: "string",
1248
- type
1249
- });
1250
- return Array.from(items).some(({ kind, type: raw }) => {
1251
- const file = kind === "file";
1252
- const type = normalizeClipboardType(raw);
1253
- if (type === null) return file;
1254
- return (file || isTextualMimeType(type)) && isAccepted(type, options);
1255
- });
1256
- }
1257
- /**
1258
- * Synchronously copies the accepted parts of a paste event's `DataTransfer`.
1259
- * It must run during the event: browsers empty the object afterwards.
1260
- */
1261
- function snapshotDataTransfer(data, options) {
1262
- const entries = [];
1263
- const seen = /* @__PURE__ */ new Set();
1264
- for (const raw of Array.from(data.types)) {
1265
- const type = normalizeClipboardType(raw);
1266
- if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;
1267
- seen.add(type);
1268
- const text = data.getData(raw);
1269
- if (text.length > 0) entries.push({
1270
- type,
1271
- data: text,
1272
- file: false
1273
- });
1274
- }
1275
- for (const file of Array.from(data.files ?? [])) {
1276
- const type = normalizeMimeType(file.type) ?? "application/octet-stream";
1277
- if (isAccepted(type, options)) entries.push({
1278
- type,
1279
- data: file,
1280
- file: true
1281
- });
1282
- }
1283
- return entries;
1284
- }
1285
- /**
1286
- * Reads the accepted types from `navigator.clipboard.read()` items, enforcing
1287
- * the limits *before* decoding any text so an oversized paste is never buffered twice.
1288
- */
1289
- async function collectClipboardItems(items, options, signal) {
1290
- const budget = createBudget(options);
1291
- const entries = [];
1292
- const seen = /* @__PURE__ */ new Set();
1293
- for (const item of items) for (const raw of item.types) {
1294
- const type = normalizeClipboardType(raw);
1295
- if (type === null || seen.has(type) || !isAccepted(type, options)) continue;
1296
- seen.add(type);
1297
- let blob;
1298
- try {
1299
- blob = await item.getType(raw);
1300
- } catch {
1301
- continue;
1302
- }
1303
- if (signal?.aborted) throw copyFailure("aborted", "The paste was cancelled.");
1304
- if (blob.size === 0) continue;
1305
- budget.charge(blob.size);
1306
- entries.push({
1307
- type,
1308
- data: isTextualMimeType(type) ? await blob.text() : blob,
1309
- file: false
1310
- });
1311
- }
1312
- return entries;
1313
- }
1314
- function retype(entry, data, type) {
1315
- if (entry.file) {
1316
- const file = data;
1317
- return new File([file], file.name, {
1318
- type,
1319
- lastModified: file.lastModified
1320
- });
1321
- }
1322
- return data.slice(0, data.size, type);
1323
- }
1324
- /**
1325
- * Verifies image bytes, then builds the result. Blobs that claim to be images
1326
- * but aren't (or whose real format is not accepted) are dropped. Throws
1327
- * `no-content` when nothing survives.
1328
- */
1329
- async function finalizePaste(entries, source, options) {
1330
- const items = [];
1331
- const images = [];
1332
- const files = [];
1333
- let text = null;
1334
- let html = null;
1335
- for (const entry of entries) {
1336
- let { type, data } = entry;
1337
- if (typeof data === "string") {
1338
- if (type === "text/plain") text = data;
1339
- else if (type === "text/html") html = data;
1340
- } else if (type.startsWith("image/")) {
1341
- const actual = await sniffImageType(data);
1342
- if (actual === null || !isAccepted(actual, options)) continue;
1343
- if (actual !== type) {
1344
- data = retype(entry, data, actual);
1345
- type = actual;
1346
- }
1347
- images.push(data);
1348
- }
1349
- if (entry.file) files.push(data);
1350
- items.push({
1351
- type,
1352
- data
1353
- });
1354
- }
1355
- if (items.length === 0) throw copyFailure("no-content", "The content holds nothing that matches `accept`.");
1356
- return {
1357
- source,
1358
- items,
1359
- text,
1360
- html,
1361
- images,
1362
- files
1363
- };
1364
- }
1365
- //#endregion
1366
- //#region src/core/paste-adapter.ts
1367
- function defaultEnvironment() {
1368
- return typeof window === "undefined" ? void 0 : window;
1369
- }
1370
- const canRead = (clipboard) => typeof clipboard.read === "function";
1371
- const canReadText = (clipboard) => typeof clipboard.readText === "function";
1372
- async function readPlainText(clipboard, options) {
1373
- let text;
1374
- try {
1375
- text = await clipboard.readText();
1376
- } catch (cause) {
1377
- throw new CopyFailure(toCopyError(cause, "read"));
1378
- }
1379
- const entries = text.length > 0 ? [{
1380
- type: "text/plain",
1381
- data: text,
1382
- file: false
1383
- }] : [];
1384
- enforcePasteLimits(entries, options);
1385
- return finalizePaste(entries, "clipboard", options);
1386
- }
1387
- async function readRich(clipboard, options, signal) {
1388
- let items;
1389
- try {
1390
- items = await clipboard.read();
1391
- } catch (cause) {
1392
- throw new CopyFailure(toCopyError(cause, "read"));
1393
- }
1394
- return finalizePaste(await collectClipboardItems(items, options, signal), "clipboard", options);
1395
- }
1396
- function readFromClipboard(env, options, signal) {
1397
- if (!env) throw copyFailure("unsupported", "No browser environment: the clipboard only exists in the browser.");
1398
- if (env.isSecureContext === false) throw copyFailure("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
1399
- const clipboard = env.navigator?.clipboard;
1400
- if (!clipboard) throw copyFailure("unsupported", "navigator.clipboard is not available in this browser.");
1401
- const plainOnly = options.accept.every((pattern) => pattern === "text/plain");
1402
- const acceptsPlain = options.accept.some((pattern) => matchesMimePattern("text/plain", pattern));
1403
- if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options, signal);
1404
- if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);
1405
- throw canReadText(clipboard) ? copyFailure("unsupported-format", "Reading non-text clipboard content requires navigator.clipboard.read().") : copyFailure("unsupported", "This browser cannot read the clipboard.");
1406
- }
1407
- /** The default paste adapter: async Clipboard API with feature detection and honest errors. */
1408
- function createBrowserPasteAdapter(options = {}) {
1409
- const getEnvironment = options.getEnvironment ?? defaultEnvironment;
1410
- return { read: (resolved, context) => {
1411
- try {
1412
- return readFromClipboard(getEnvironment(), resolved, context?.signal);
1413
- } catch (cause) {
1414
- return Promise.reject(cause);
1415
- }
1416
- } };
1417
- }
1418
- //#endregion
1419
- //#region src/core/paste-machine.ts
1420
- const PASTE_IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
1421
- const PASTE_READING_STATE = /* @__PURE__ */ Object.freeze({ status: "reading" });
1422
- const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
1423
- status: "ignored",
1424
- reason: "in-flight"
1425
- });
1426
- const IGNORED_NO_CONTENT = /* @__PURE__ */ Object.freeze({
1427
- status: "ignored",
1428
- reason: "no-accepted-content"
1429
- });
1430
- const IGNORED_NOTHING = /* @__PURE__ */ Object.freeze({
1431
- status: "ignored",
1432
- reason: "nothing-to-retry"
1433
- });
1434
- const IGNORED_NOT_RETRYABLE = /* @__PURE__ */ Object.freeze({
1435
- status: "ignored",
1436
- reason: "not-retryable"
1437
- });
1438
- const IGNORED_CANCELLED = /* @__PURE__ */ Object.freeze({
1439
- status: "ignored",
1440
- reason: "cancelled"
1441
- });
1442
- function resolveResetDelay(value) {
1443
- if (value === void 0 || value === false || value === Infinity || Number.isNaN(value)) return null;
1444
- return Math.max(0, value);
1445
- }
1446
- /** Pure helper: can `retry()` do anything from this state? */
1447
- function canRetryPasteState(state, maxRetries) {
1448
- return state.status === "error" && state.source === "clipboard" && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
1449
- }
1450
- let defaultAdapter;
1451
- const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserPasteAdapter());
1452
- /** Framework-agnostic paste state machine. */
1453
- function createPasteMachine(options = {}) {
1454
- const read = typeof options === "function" ? options : () => options;
1455
- const listeners = /* @__PURE__ */ new Set();
1456
- let state = PASTE_IDLE_STATE;
1457
- let generation = 0;
1458
- let resetTimer;
1459
- const operations = createOperations();
1460
- const now = () => (read().now ?? Date.now)();
1461
- const setState = (next) => {
1462
- if (next === state) return;
1463
- state = next;
1464
- for (const listener of Array.from(listeners)) listener();
1465
- };
1466
- const clearResetTimer = () => {
1467
- if (resetTimer !== void 0) {
1468
- clearTimeout(resetTimer);
1469
- resetTimer = void 0;
1470
- }
1471
- };
1472
- const scheduleReset = (readState) => {
1473
- clearResetTimer();
1474
- const delay = resolveResetDelay(read().resetAfterMs);
1475
- if (delay === null) return;
1476
- const remaining = Math.max(0, delay - (now() - readState.at));
1477
- resetTimer = setTimeout(() => {
1478
- resetTimer = void 0;
1479
- setState(PASTE_IDLE_STATE);
1480
- }, remaining);
1481
- };
1482
- const settleError = (error, source, retryCount) => {
1483
- setState({
1484
- status: "error",
1485
- error,
1486
- source,
1487
- retryCount
1488
- });
1489
- invoke(read().onError, error);
1490
- };
1491
- /** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */
1492
- const run = (produce, source, retryCount) => {
1493
- clearResetTimer();
1494
- const current = ++generation;
1495
- const superseded = operations.abort();
1496
- const context = operations.start();
1497
- setState(PASTE_READING_STATE);
1498
- if (superseded) invoke(read().onCancel, "superseded");
1499
- let pending;
1500
- try {
1501
- pending = produce(context);
1502
- } catch (cause) {
1503
- pending = Promise.reject(cause);
1504
- }
1505
- return pending.then(completePasteResult).then((result) => {
1506
- operations.end(context);
1507
- if (current === generation) {
1508
- const readState = {
1509
- status: "read",
1510
- result,
1511
- at: now()
1512
- };
1513
- setState(readState);
1514
- scheduleReset(readState);
1515
- invoke(read().onPaste, result);
1516
- }
1517
- return {
1518
- status: "read",
1519
- result
1520
- };
1521
- }, (cause) => {
1522
- operations.end(context);
1523
- if (context.signal.aborted) return IGNORED_CANCELLED;
1524
- const error = toCopyError(cause, "read");
1525
- settleError(error, source, retryCount);
1526
- return {
1527
- status: "error",
1528
- error
1529
- };
1530
- });
1531
- };
1532
- const readClipboard = (retryCount) => run((context) => (read().adapter ?? getDefaultAdapter()).read(resolvePasteReadOptions(read()), context), "clipboard", retryCount);
1533
- const paste = () => state.status === "reading" ? Promise.resolve(IGNORED_IN_FLIGHT) : readClipboard(0);
1534
- const retry = () => {
1535
- if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
1536
- if (state.source !== "clipboard" || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
1537
- if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
1538
- const error = createCopyError("max-retries-exceeded", `Paste failed after ${String(state.retryCount)} retries.`, state.error);
1539
- settleError(error, "clipboard", state.retryCount);
1540
- return Promise.resolve({
1541
- status: "error",
1542
- error
1543
- });
1544
- }
1545
- return readClipboard(state.retryCount + 1);
1546
- };
1547
- /** Shared by paste and drop events: their `DataTransfer` has the same shape and lifetime. */
1548
- const transfer = (data, event, source) => {
1549
- const current = read();
1550
- if (source === "drop" && current.preventDefault !== false) event.preventDefault();
1551
- if (!data) return Promise.resolve(IGNORED_NO_CONTENT);
1552
- let resolved;
1553
- try {
1554
- resolved = resolvePasteReadOptions(current);
1555
- } catch (cause) {
1556
- const error = toCopyError(cause, "read");
1557
- ++generation;
1558
- const superseded = operations.abort();
1559
- clearResetTimer();
1560
- settleError(error, source, 0);
1561
- if (superseded) invoke(current.onCancel, "superseded");
1562
- return Promise.resolve({
1563
- status: "error",
1564
- error
1565
- });
1566
- }
1567
- const entries = snapshotDataTransfer(data, resolved);
1568
- if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);
1569
- if (source === "event" && current.preventDefault !== false) event.preventDefault();
1570
- return run(() => {
1571
- enforcePasteLimits(entries, resolved);
1572
- return finalizePaste(entries, source, resolved);
1573
- }, source, 0);
1574
- };
1575
- const pasteEvent = (event) => transfer(event.clipboardData, event, "event");
1576
- const dropEvent = (event) => transfer(event.dataTransfer, event, "drop");
1577
- const reset = () => {
1578
- ++generation;
1579
- const cancelled = operations.abort();
1580
- clearResetTimer();
1581
- const wasIdle = state.status === "idle";
1582
- setState(PASTE_IDLE_STATE);
1583
- if (cancelled) invoke(read().onCancel, "reset");
1584
- if (!wasIdle) invoke(read().onReset);
1585
- };
1586
- const connect = () => {
1587
- if (state.status === "read") scheduleReset(state);
1588
- return () => {
1589
- ++generation;
1590
- const cancelled = operations.abort();
1591
- clearResetTimer();
1592
- if (state.status === "reading") setState(PASTE_IDLE_STATE);
1593
- if (cancelled) invoke(read().onCancel, "disconnect");
1594
- };
1595
- };
1596
- return {
1597
- getSnapshot: () => state,
1598
- subscribe: (listener) => {
1599
- listeners.add(listener);
1600
- return () => {
1601
- listeners.delete(listener);
1602
- };
1603
- },
1604
- paste,
1605
- pasteEvent,
1606
- dropEvent,
1607
- retry,
1608
- reset,
1609
- connect
1610
- };
1611
- }
1612
- //#endregion
1613
- export { CopyFailure, DEFAULT_INTERCEPTED_EVENTS, DEFAULT_MAX_RETRIES, DEFAULT_PASTE_ACCEPT, DEFAULT_PASTE_MAX_BYTES, DEFAULT_PASTE_MAX_ITEMS, DEFAULT_RESET_AFTER_MS, IDLE_STATE, IMAGE_MIME_TYPE, PASTE_IDLE_STATE, SVG_MIME_TYPE, WEB_CUSTOM_FORMAT_PREFIX, applyDragCopy, canAcceptDrag, canRetryPasteState, canRetryState, copyFailure, createBrowserClipboardAdapter, createBrowserPasteAdapter, createCopyCoordinator, createCopyError, createCopyMachine, createPasteMachine, describeCopyError, describePasteError, interceptCopyEvent, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, isWebCustomFormat, matchesMimePattern, normalizeClipboardType, normalizeMimeType, normalizePayload, readCopySelection, registerCopyInterceptor, registerDragCopy, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, validatePayload };
1614
1
 
1615
- //# sourceMappingURL=core.js.map
2
+ import { a as describePasteError, c as toCopyError, i as describeCopyError, n as copyFailure, o as isCopyFailure, r as createCopyError, s as isRetryableError, t as CopyFailure } from "./chunks/errors-9h8sdFFX.js";
3
+ import { a as validatePayload, i as serializeJson, n as isBlob, r as normalizePayload, t as IMAGE_MIME_TYPE } from "./chunks/payload-DGw-JOo7.js";
4
+ import { a as matchesMimePattern, c as sniffImageBytes, i as isWebCustomFormat, l as sniffImageType, n as WEB_CUSTOM_FORMAT_PREFIX, o as normalizeClipboardType, r as isTextualMimeType, s as normalizeMimeType, t as SVG_MIME_TYPE } from "./chunks/mime-aa-HA2dm.js";
5
+ import { t as createBrowserClipboardAdapter } from "./chunks/clipboard-adapter-DEXkXxwV.js";
6
+ import { _ as resolveMaxRetries, a as applyDragCopy, c as interceptCopyEvent, d as DEFAULT_RESET_AFTER_MS, f as IDLE_STATE, h as DEFAULT_MAX_RETRIES, i as createBrowserPasteAdapter, l as readCopySelection, m as createCopyMachine, n as canRetryPasteState, o as registerDragCopy, p as canRetryState, r as createPasteMachine, s as DEFAULT_INTERCEPTED_EVENTS, t as PASTE_IDLE_STATE, u as registerCopyInterceptor, v as createCopyCoordinator } from "./chunks/core-Cp2HSpaz.js";
7
+ import { i as canAcceptDrag, l as resolvePasteReadOptions, n as DEFAULT_PASTE_MAX_BYTES, r as DEFAULT_PASTE_MAX_ITEMS, t as DEFAULT_PASTE_ACCEPT } from "./chunks/paste-reader-D9i7yMXF.js";
8
+ export { CopyFailure, DEFAULT_INTERCEPTED_EVENTS, DEFAULT_MAX_RETRIES, DEFAULT_PASTE_ACCEPT, DEFAULT_PASTE_MAX_BYTES, DEFAULT_PASTE_MAX_ITEMS, DEFAULT_RESET_AFTER_MS, IDLE_STATE, IMAGE_MIME_TYPE, PASTE_IDLE_STATE, SVG_MIME_TYPE, WEB_CUSTOM_FORMAT_PREFIX, applyDragCopy, canAcceptDrag, canRetryPasteState, canRetryState, copyFailure, createBrowserClipboardAdapter, createBrowserPasteAdapter, createCopyCoordinator, createCopyError, createCopyMachine, createPasteMachine, describeCopyError, describePasteError, interceptCopyEvent, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, isWebCustomFormat, matchesMimePattern, normalizeClipboardType, normalizeMimeType, normalizePayload, readCopySelection, registerCopyInterceptor, registerDragCopy, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, validatePayload };