react-smart-copy 1.17.2 → 1.18.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 (146) hide show
  1. package/README.md +9 -3
  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/mime--LB7kdqG.cjs +153 -0
  35. package/dist/chunks/mime--LB7kdqG.cjs.map +1 -0
  36. package/dist/chunks/mime-aa-HA2dm.js +100 -0
  37. package/dist/chunks/mime-aa-HA2dm.js.map +1 -0
  38. package/dist/chunks/paste-adapter--SPL4PRE.d.cts +35 -0
  39. package/dist/chunks/paste-adapter-uahXnTYk.d.ts +35 -0
  40. package/dist/chunks/paste-reader-Bo01IMC_.cjs +289 -0
  41. package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +1 -0
  42. package/dist/chunks/paste-reader-D9i7yMXF.js +224 -0
  43. package/dist/chunks/paste-reader-D9i7yMXF.js.map +1 -0
  44. package/dist/chunks/paste-reader-DcXnRWQr.d.cts +96 -0
  45. package/dist/chunks/paste-reader-DcXnRWQr.d.ts +96 -0
  46. package/dist/chunks/payload-CUymxwim.cjs +100 -0
  47. package/dist/chunks/payload-CUymxwim.cjs.map +1 -0
  48. package/dist/chunks/payload-CcwKJ_bU.d.cts +162 -0
  49. package/dist/chunks/payload-Cl_8hCI5.d.ts +162 -0
  50. package/dist/chunks/payload-DGw-JOo7.js +71 -0
  51. package/dist/chunks/payload-DGw-JOo7.js.map +1 -0
  52. package/dist/chunks/payload-DI5AorDz.js +103 -0
  53. package/dist/chunks/payload-DI5AorDz.js.map +1 -0
  54. package/dist/chunks/payload-J6GjHuh3.cjs +132 -0
  55. package/dist/chunks/payload-J6GjHuh3.cjs.map +1 -0
  56. package/dist/chunks/share-Bop47Znn.js +208 -0
  57. package/dist/chunks/share-Bop47Znn.js.map +1 -0
  58. package/dist/chunks/share-C0esXvRK.d.cts +115 -0
  59. package/dist/chunks/share-ayDz974N.cjs +231 -0
  60. package/dist/chunks/share-ayDz974N.cjs.map +1 -0
  61. package/dist/chunks/share-e7FenIr2.d.ts +115 -0
  62. package/dist/chunks/text-field-Ba8W3v4R.cjs +77 -0
  63. package/dist/chunks/text-field-Ba8W3v4R.cjs.map +1 -0
  64. package/dist/chunks/text-field-C0SGmvvR.d.cts +18 -0
  65. package/dist/chunks/text-field-C0SGmvvR.d.ts +18 -0
  66. package/dist/chunks/text-field-DUvrMMaK.js +66 -0
  67. package/dist/chunks/text-field-DUvrMMaK.js.map +1 -0
  68. package/dist/chunks/url-BcMYVCXQ.js +135 -0
  69. package/dist/chunks/url-BcMYVCXQ.js.map +1 -0
  70. package/dist/chunks/url-D4PGsRm8.cjs +164 -0
  71. package/dist/chunks/url-D4PGsRm8.cjs.map +1 -0
  72. package/dist/chunks/url-DWdElCT3.d.cts +43 -0
  73. package/dist/chunks/url-DWdElCT3.d.ts +43 -0
  74. package/dist/code.cjs +20 -112
  75. package/dist/code.cjs.map +1 -1
  76. package/dist/code.d.cts +4 -28
  77. package/dist/code.d.ts +4 -28
  78. package/dist/code.js +3 -95
  79. package/dist/code.js.map +1 -1
  80. package/dist/color.cjs +21 -893
  81. package/dist/color.cjs.map +1 -1
  82. package/dist/color.d.cts +4 -28
  83. package/dist/color.d.ts +4 -28
  84. package/dist/color.js +4 -876
  85. package/dist/color.js.map +1 -1
  86. package/dist/core.cjs +52 -1659
  87. package/dist/core.d.cts +8 -878
  88. package/dist/core.d.ts +8 -878
  89. package/dist/core.js +7 -1614
  90. package/dist/image.cjs +23 -94
  91. package/dist/image.cjs.map +1 -1
  92. package/dist/image.d.cts +1 -0
  93. package/dist/image.d.ts +1 -0
  94. package/dist/image.js +3 -74
  95. package/dist/image.js.map +1 -1
  96. package/dist/index.cjs +74 -2072
  97. package/dist/index.cjs.map +1 -1
  98. package/dist/index.d.cts +8 -978
  99. package/dist/index.d.ts +8 -978
  100. package/dist/index.js +7 -2005
  101. package/dist/index.js.map +1 -1
  102. package/dist/link.cjs +24 -338
  103. package/dist/link.cjs.map +1 -1
  104. package/dist/link.d.cts +5 -83
  105. package/dist/link.d.ts +5 -83
  106. package/dist/link.js +5 -319
  107. package/dist/link.js.map +1 -1
  108. package/dist/markdown.cjs +8 -97
  109. package/dist/markdown.cjs.map +1 -1
  110. package/dist/markdown.d.cts +3 -16
  111. package/dist/markdown.d.ts +3 -16
  112. package/dist/markdown.js +3 -92
  113. package/dist/markdown.js.map +1 -1
  114. package/dist/rich.cjs +26 -934
  115. package/dist/rich.cjs.map +1 -1
  116. package/dist/rich.d.cts +4 -90
  117. package/dist/rich.d.ts +4 -90
  118. package/dist/rich.js +4 -912
  119. package/dist/rich.js.map +1 -1
  120. package/dist/share.cjs +5 -640
  121. package/dist/share.d.cts +3 -248
  122. package/dist/share.d.ts +3 -248
  123. package/dist/share.js +1 -637
  124. package/dist/structured.cjs +13 -95
  125. package/dist/structured.cjs.map +1 -1
  126. package/dist/structured.d.cts +2 -11
  127. package/dist/structured.d.ts +2 -11
  128. package/dist/structured.js +4 -86
  129. package/dist/structured.js.map +1 -1
  130. package/dist/table.cjs +11 -39
  131. package/dist/table.cjs.map +1 -1
  132. package/dist/table.d.cts +2 -12
  133. package/dist/table.d.ts +2 -12
  134. package/dist/table.js +2 -30
  135. package/dist/table.js.map +1 -1
  136. package/dist/testing.cjs +10 -43
  137. package/dist/testing.cjs.map +1 -1
  138. package/dist/testing.d.cts +6 -181
  139. package/dist/testing.d.ts +6 -181
  140. package/dist/testing.js +3 -36
  141. package/dist/testing.js.map +1 -1
  142. package/package.json +20 -2
  143. package/dist/core.cjs.map +0 -1
  144. package/dist/core.js.map +0 -1
  145. package/dist/share.cjs.map +0 -1
  146. package/dist/share.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,1619 +1,14 @@
1
1
  "use client";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const require_errors = require("./chunks/errors-BwOF6T_M.cjs");
4
+ const require_payload = require("./chunks/payload-CUymxwim.cjs");
5
+ const require_mime = require("./chunks/mime--LB7kdqG.cjs");
6
+ const require_clipboard_adapter = require("./chunks/clipboard-adapter-Cfz-rzw3.cjs");
7
+ const require_core = require("./chunks/core-DYf_Lhbe.cjs");
8
+ const require_paste_reader = require("./chunks/paste-reader-Bo01IMC_.cjs");
9
+ const require_share = require("./chunks/share-ayDz974N.cjs");
3
10
  let react = require("react");
4
11
  let react_jsx_runtime = require("react/jsx-runtime");
5
- //#region src/core/errors.ts
6
- function createCopyError(type, message, cause) {
7
- return cause === void 0 ? {
8
- type,
9
- message
10
- } : {
11
- type,
12
- message,
13
- cause
14
- };
15
- }
16
- const RETRYABLE_ERRORS = /* @__PURE__ */ new Set([
17
- "permission-denied",
18
- "not-focused",
19
- "blob-generation-failed",
20
- "timeout",
21
- "unknown"
22
- ]);
23
- /** Whether retrying the same payload could plausibly succeed. */
24
- function isRetryableError(error) {
25
- return RETRYABLE_ERRORS.has(error.type);
26
- }
27
- /**
28
- * Branded (not `instanceof`) so failures stay recognisable even when the core
29
- * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
30
- */
31
- const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
32
- /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
33
- var CopyFailure = class extends Error {
34
- constructor(copyError) {
35
- super(copyError.message);
36
- this[COPY_FAILURE_BRAND] = true;
37
- this.name = "CopyFailure";
38
- this.copyError = copyError;
39
- }
40
- };
41
- function isCopyFailure(value) {
42
- return typeof value === "object" && value !== null && value[COPY_FAILURE_BRAND] === true;
43
- }
44
- /** Shorthand for throwing a classified failure. */
45
- function copyFailure(type, message, cause) {
46
- return new CopyFailure(createCopyError(type, message, cause));
47
- }
48
- function readString(value, key) {
49
- if (typeof value !== "object" || value === null) return void 0;
50
- const field = value[key];
51
- return typeof field === "string" ? field : void 0;
52
- }
53
- /**
54
- * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.
55
- * `operation` only tailors the developer-facing message.
56
- */
57
- function toCopyError(cause, operation = "write") {
58
- if (isCopyFailure(cause)) return cause.copyError;
59
- const name = readString(cause, "name");
60
- const message = readString(cause, "message") ?? "";
61
- const verb = operation === "read" ? "read" : "write";
62
- switch (name) {
63
- 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);
64
- case "SecurityError": return createCopyError("insecure-context", "The clipboard is blocked in this context.", cause);
65
- case "NotSupportedError":
66
- case "DataError": return createCopyError("unsupported-format", "The browser rejected this clipboard format.", cause);
67
- case "AbortError": return createCopyError("aborted", `The clipboard ${verb} was aborted.`, cause);
68
- case "TimeoutError": return createCopyError("timeout", `The clipboard ${verb} timed out.`, cause);
69
- default: return createCopyError("unknown", message || `The clipboard ${verb} failed for an unknown reason.`, cause);
70
- }
71
- }
72
- const COPY_DESCRIPTIONS = {
73
- unsupported: "Copying isn't supported in this browser.",
74
- "insecure-context": "Copying requires a secure (HTTPS) connection.",
75
- "permission-denied": "Clipboard access was blocked. Allow it and try again.",
76
- "not-focused": "The page lost focus while copying. Try again.",
77
- "invalid-payload": "There is nothing to copy.",
78
- "unsupported-format": "This content can't be copied in this browser.",
79
- "blob-generation-failed": "The image couldn't be prepared for copying.",
80
- "max-retries-exceeded": "Copying failed after several attempts.",
81
- "no-content": "There is nothing to copy.",
82
- "too-large": "This content is too large to copy.",
83
- timeout: "Copying took too long. Try again.",
84
- aborted: "Copying was cancelled.",
85
- unknown: "Couldn't copy to the clipboard. Try again."
86
- };
87
- const PASTE_DESCRIPTIONS = {
88
- unsupported: "Pasting isn't supported in this browser.",
89
- "insecure-context": "Pasting requires a secure (HTTPS) connection.",
90
- "permission-denied": "Clipboard access was blocked. Allow it and try again.",
91
- "not-focused": "The page lost focus while pasting. Try again.",
92
- "invalid-payload": "The clipboard content couldn't be read.",
93
- "unsupported-format": "This clipboard content isn't supported here.",
94
- "blob-generation-failed": "The pasted image couldn't be read.",
95
- "max-retries-exceeded": "Pasting failed after several attempts.",
96
- "no-content": "The clipboard doesn't contain anything that can be pasted here.",
97
- "too-large": "The clipboard content is too large to paste.",
98
- timeout: "Pasting took too long. Try again.",
99
- aborted: "Pasting was cancelled.",
100
- unknown: "Couldn't read the clipboard. Try again."
101
- };
102
- /** Default English, user-facing sentence for a copy error. Replace for i18n. */
103
- function describeCopyError(error) {
104
- return COPY_DESCRIPTIONS[error.type];
105
- }
106
- /** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */
107
- const DROP_DESCRIPTIONS = {
108
- "invalid-payload": "The dropped content couldn't be read.",
109
- "no-content": "Nothing that was dropped can be used here.",
110
- "too-large": "The dropped content is too large.",
111
- unknown: "Couldn't read the dropped content. Try again."
112
- };
113
- /**
114
- * Default English, user-facing sentence for a paste error. Pass the error
115
- * state's `source` to word drag-and-drop failures as drops. Replace for i18n.
116
- */
117
- function describePasteError(error, source) {
118
- return (source === "drop" ? DROP_DESCRIPTIONS[error.type] : void 0) ?? PASTE_DESCRIPTIONS[error.type];
119
- }
120
- //#endregion
121
- //#region src/core/payload.ts
122
- /** The only image MIME type with reliable cross-browser clipboard write support. */
123
- const IMAGE_MIME_TYPE = "image/png";
124
- function normalizePayload(input) {
125
- return typeof input === "string" ? {
126
- kind: "text",
127
- value: input
128
- } : input;
129
- }
130
- function isBlob(value) {
131
- if (typeof Blob !== "undefined" && value instanceof Blob) return true;
132
- const tag = Object.prototype.toString.call(value);
133
- return tag === "[object Blob]" || tag === "[object File]";
134
- }
135
- function isThenable(value) {
136
- return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
137
- }
138
- const invalid$5 = (message) => createCopyError("invalid-payload", message);
139
- /**
140
- * Structural validation. Typed callers can't produce most of these states,
141
- * but plain-JS callers and runtime data can, so the check is always on.
142
- */
143
- function validatePayload(payload) {
144
- if (typeof payload !== "object" || payload === null) return invalid$5("Copy input must be a string or a payload object.");
145
- const candidate = payload;
146
- switch (candidate["kind"]) {
147
- case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid$5("Text payload must be a non-empty string.");
148
- case "html":
149
- if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid$5("HTML payload requires a non-empty `html` string.");
150
- return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid$5("HTML payload requires a non-empty plain-text `text` fallback.");
151
- case "image": {
152
- const source = candidate["blob"];
153
- return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid$5("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
154
- }
155
- case "json": return candidate["value"] === void 0 ? invalid$5("JSON payload value is undefined.") : null;
156
- case "multi": {
157
- const items = candidate["items"];
158
- if (!Array.isArray(items) || items.length === 0) return invalid$5("Multi payload requires at least one item.");
159
- const seen = /* @__PURE__ */ new Set();
160
- for (const item of items) {
161
- const entry = typeof item === "object" && item !== null ? item : {};
162
- const mimeType = entry["mimeType"];
163
- const data = entry["data"];
164
- if (typeof mimeType !== "string" || mimeType.length === 0) return invalid$5("Every multi item needs a non-empty `mimeType`.");
165
- if (seen.has(mimeType)) return invalid$5(`Duplicate MIME type "${mimeType}" in multi payload.`);
166
- seen.add(mimeType);
167
- if (typeof data !== "string" && !isBlob(data)) return invalid$5(`Multi item "${mimeType}" must contain a string or a Blob.`);
168
- }
169
- return null;
170
- }
171
- default: return invalid$5(`Unknown payload kind: ${String(candidate["kind"])}.`);
172
- }
173
- }
174
- /** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */
175
- function serializeJson(payload) {
176
- const indent = payload.pretty === true ? 2 : typeof payload.pretty === "number" ? payload.pretty : void 0;
177
- let text;
178
- try {
179
- text = JSON.stringify(payload.value, null, indent);
180
- } catch (cause) {
181
- throw new CopyFailure(createCopyError("invalid-payload", "JSON payload could not be serialised (circular reference or BigInt?).", cause));
182
- }
183
- if (typeof text !== "string") throw new CopyFailure(createCopyError("invalid-payload", "JSON payload serialised to nothing (functions, symbols and undefined are not JSON)."));
184
- return text;
185
- }
186
- //#endregion
187
- //#region src/core/mime.ts
188
- /**
189
- * MIME helpers shared by paste and capture. Everything that comes from the
190
- * clipboard is untrusted input, so types are normalised and validated before
191
- * they are compared, and image types are confirmed from the bytes themselves.
192
- */
193
- /** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */
194
- const MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
195
- /** SVG is XML that can carry scripts; it is never matched by a wildcard. */
196
- const SVG_MIME_TYPE = "image/svg+xml";
197
- /** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */
198
- function normalizeMimeType(value) {
199
- const separator = value.indexOf(";");
200
- const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();
201
- return MIME_SHAPE.test(base) ? base : null;
202
- }
203
- /** Prefix of the async Clipboard API's web custom formats (`web application/vnd.acme+json`). */
204
- const WEB_CUSTOM_FORMAT_PREFIX = "web ";
205
- /** Whether a clipboard type is a web custom format (`web type/subtype`). */
206
- function isWebCustomFormat(type) {
207
- return type.slice(0, 4).toLowerCase() === WEB_CUSTOM_FORMAT_PREFIX;
208
- }
209
- /**
210
- * Like {@link normalizeMimeType}, but also accepts web custom formats
211
- * (`web type/subtype`), returned as `web ` + the normalised MIME type.
212
- */
213
- function normalizeClipboardType(value) {
214
- if (!isWebCustomFormat(value)) return normalizeMimeType(value);
215
- const inner = normalizeMimeType(value.slice(4));
216
- return inner === null ? null : WEB_CUSTOM_FORMAT_PREFIX + inner;
217
- }
218
- /**
219
- * Types a wildcard never matches, so accepting them must be explicit:
220
- * `image/svg+xml` (scriptable XML), web custom formats and structured `+json` types
221
- * (application-specific data that only the app that defined them should read).
222
- */
223
- function requiresExactMatch(mimeType) {
224
- return mimeType === "image/svg+xml" || isWebCustomFormat(mimeType) || mimeType.endsWith("+json");
225
- }
226
- /**
227
- * Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\/*`)?
228
- * Wildcards never match `image/svg+xml`, web custom formats or `+json` types: those must be listed exactly.
229
- */
230
- function matchesMimePattern(mimeType, pattern) {
231
- if (pattern === mimeType) return true;
232
- if (requiresExactMatch(mimeType)) return false;
233
- if (pattern === "*/*") return true;
234
- return pattern.endsWith("/*") && mimeType.startsWith(pattern.slice(0, -1));
235
- }
236
- /** Types whose clipboard data is text and is therefore surfaced as a `string`. */
237
- function isTextualMimeType(mimeType) {
238
- const type = isWebCustomFormat(mimeType) ? mimeType.slice(4) : mimeType;
239
- return type.startsWith("text/") || type === "image/svg+xml" || type === "application/json" || type === "application/xml" || type.endsWith("+json");
240
- }
241
- const SNIFF_BYTES = 16;
242
- function startsWith(bytes, signature, offset = 0) {
243
- return signature.every((byte, index) => bytes[offset + index] === byte);
244
- }
245
- const ascii = (text) => Array.from(text, (char) => char.charCodeAt(0));
246
- const PNG = [
247
- 137,
248
- 80,
249
- 78,
250
- 71,
251
- 13,
252
- 10,
253
- 26,
254
- 10
255
- ];
256
- const JPEG = [
257
- 255,
258
- 216,
259
- 255
260
- ];
261
- const GIF = ascii("GIF8");
262
- const RIFF = ascii("RIFF");
263
- const WEBP = ascii("WEBP");
264
- const BMP = ascii("BM");
265
- const FTYP_AVIF = ascii("ftypavif");
266
- const FTYP_AVIS = ascii("ftypavis");
267
- /** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */
268
- function sniffImageBytes(bytes) {
269
- if (startsWith(bytes, PNG)) return "image/png";
270
- if (startsWith(bytes, JPEG)) return "image/jpeg";
271
- if (startsWith(bytes, GIF)) return "image/gif";
272
- if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return "image/webp";
273
- if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return "image/avif";
274
- if (startsWith(bytes, BMP)) return "image/bmp";
275
- return null;
276
- }
277
- /** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */
278
- async function sniffImageType(blob) {
279
- const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();
280
- return sniffImageBytes(new Uint8Array(head));
281
- }
282
- //#endregion
283
- //#region src/core/clipboard-adapter.ts
284
- const fail = (type, message, cause) => new CopyFailure(createCopyError(type, message, cause));
285
- const noop = () => void 0;
286
- function defaultEnvironment$2() {
287
- return typeof window === "undefined" ? void 0 : window;
288
- }
289
- function getRichClipboard(env, clipboard) {
290
- const Item = env.ClipboardItem;
291
- if (!Item || typeof clipboard.write !== "function") return null;
292
- return {
293
- Item,
294
- write: clipboard.write.bind(clipboard)
295
- };
296
- }
297
- function isTypeSupported(Item, type) {
298
- return typeof Item.supports !== "function" || Item.supports(type);
299
- }
300
- function writeText(clipboard, text) {
301
- if (typeof clipboard.writeText !== "function") throw fail("unsupported", "navigator.clipboard.writeText() is not available.");
302
- return clipboard.writeText(text);
303
- }
304
- async function resolveImageBlob(source, context) {
305
- let blob;
306
- try {
307
- blob = await (typeof source === "function" ? source(context ?? { signal: new AbortController().signal }) : source);
308
- } catch (cause) {
309
- if (context?.signal.aborted) throw fail("aborted", "The image copy was cancelled.", cause);
310
- throw fail("blob-generation-failed", "The image source threw or rejected while producing a Blob.", cause);
311
- }
312
- if (!isBlob(blob)) throw fail("blob-generation-failed", "The image source did not produce a Blob.");
313
- 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}").`);
314
- return blob;
315
- }
316
- async function writeImage(rich, source, context) {
317
- if (!isTypeSupported(rich.Item, "image/png")) throw fail("unsupported-format", `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);
318
- const blob = resolveImageBlob(source, context);
319
- blob.catch(noop);
320
- try {
321
- await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);
322
- } catch (error) {
323
- throw await blob.then(noop, (inner) => inner) ?? error;
324
- }
325
- await blob;
326
- }
327
- async function writeToClipboard(payload, env, degradeHtmlToText, context) {
328
- if (!env) throw fail("unsupported", "No browser environment: the clipboard only exists in the browser.");
329
- if (env.isSecureContext === false) throw fail("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
330
- const clipboard = env.navigator?.clipboard;
331
- if (!clipboard) throw fail("unsupported", "navigator.clipboard is not available in this browser.");
332
- switch (payload.kind) {
333
- case "text": return writeText(clipboard, payload.value);
334
- case "json": return writeText(clipboard, serializeJson(payload));
335
- case "html": {
336
- const rich = getRichClipboard(env, clipboard);
337
- if (!rich || !isTypeSupported(rich.Item, "text/html")) {
338
- if (degradeHtmlToText) return writeText(clipboard, payload.text);
339
- throw fail("unsupported-format", "Rich HTML copy requires ClipboardItem and navigator.clipboard.write().");
340
- }
341
- return rich.write([new rich.Item({
342
- "text/html": new Blob([payload.html], { type: "text/html" }),
343
- "text/plain": new Blob([payload.text], { type: "text/plain" })
344
- })]);
345
- }
346
- case "image": {
347
- const rich = getRichClipboard(env, clipboard);
348
- if (!rich) throw fail("unsupported-format", "Image copy requires ClipboardItem and navigator.clipboard.write().");
349
- return writeImage(rich, payload.blob, context);
350
- }
351
- case "multi": {
352
- const rich = getRichClipboard(env, clipboard);
353
- if (!rich) throw fail("unsupported-format", "Multi-format copy requires ClipboardItem and navigator.clipboard.write().");
354
- const record = Object.create(null);
355
- let written = 0;
356
- for (const { mimeType, data, optional } of payload.items) {
357
- if (optional === true && !(typeof rich.Item.supports === "function" && rich.Item.supports(mimeType))) continue;
358
- if (!isTypeSupported(rich.Item, mimeType)) throw fail("unsupported-format", `This browser cannot write "${mimeType}" to the clipboard.`);
359
- record[mimeType] = typeof data === "string" ? new Blob([data], { type: mimeType }) : data;
360
- written += 1;
361
- }
362
- if (written === 0) throw fail("unsupported-format", "This browser can write none of the payload types.");
363
- return rich.write([new rich.Item(record)]);
364
- }
365
- }
366
- }
367
- /** The default adapter: async Clipboard API with feature detection and honest errors. */
368
- function createBrowserClipboardAdapter(options = {}) {
369
- const getEnvironment = options.getEnvironment ?? defaultEnvironment$2;
370
- const degradeHtmlToText = options.degradeHtmlToText ?? true;
371
- return { write: (payload, context) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText, context) };
372
- }
373
- //#endregion
374
- //#region src/core/copy-coordinator.ts
375
- function createCopyCoordinator() {
376
- let active = null;
377
- return {
378
- activate: (member) => {
379
- const previous = active;
380
- active = member;
381
- if (previous !== null && previous !== member) previous.release();
382
- },
383
- deactivate: (member) => {
384
- if (active === member) active = null;
385
- },
386
- getActive: () => active
387
- };
388
- }
389
- //#endregion
390
- //#region src/core/machine-shared.ts
391
- /**
392
- * Internals shared by the copy and paste state machines. Kept in one module so
393
- * apps that use both don't ship two copies.
394
- */
395
- const DEFAULT_MAX_RETRIES = 3;
396
- function resolveMaxRetries(value) {
397
- if (value === Infinity) return Infinity;
398
- if (value === void 0 || !Number.isFinite(value)) return 3;
399
- return Math.max(0, Math.floor(value));
400
- }
401
- function reportCallbackError(error) {
402
- const scope = globalThis;
403
- if (typeof scope.reportError === "function") scope.reportError(error);
404
- else setTimeout(() => {
405
- throw error;
406
- }, 0);
407
- }
408
- /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
409
- function invoke(fn, ...args) {
410
- if (!fn) return;
411
- try {
412
- fn(...args);
413
- } catch (error) {
414
- reportCallbackError(error);
415
- }
416
- }
417
- /** One cancellable operation at a time. Signals only fire while their operation is unfinished. */
418
- function createOperations() {
419
- let controller;
420
- const abort = () => {
421
- if (!controller) return false;
422
- controller.abort();
423
- controller = void 0;
424
- return true;
425
- };
426
- return {
427
- start: () => {
428
- abort();
429
- controller = new AbortController();
430
- return { signal: controller.signal };
431
- },
432
- end: (context) => {
433
- if (controller?.signal === context.signal) controller = void 0;
434
- },
435
- abort
436
- };
437
- }
438
- //#endregion
439
- //#region src/core/source-error.ts
440
- /**
441
- * The error for a user-supplied source (copy source, drag source, copy transform)
442
- * that threw. A thrown `CopyFailure` keeps its classification, so a helper such as
443
- * `tablePayload()` can report `too-large` instead of a generic `invalid-payload`.
444
- * Internal: not part of the public API.
445
- */
446
- function sourceError(cause, message) {
447
- return isCopyFailure(cause) ? cause.copyError : createCopyError("invalid-payload", message, cause);
448
- }
449
- //#endregion
450
- //#region src/core/copy-machine.ts
451
- const DEFAULT_RESET_AFTER_MS = 2e3;
452
- const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
453
- const IGNORED_IN_FLIGHT$1 = /* @__PURE__ */ Object.freeze({
454
- status: "ignored",
455
- reason: "in-flight"
456
- });
457
- const IGNORED_NOTHING$1 = /* @__PURE__ */ Object.freeze({
458
- status: "ignored",
459
- reason: "nothing-to-retry"
460
- });
461
- const IGNORED_NOT_RETRYABLE$1 = /* @__PURE__ */ Object.freeze({
462
- status: "ignored",
463
- reason: "not-retryable"
464
- });
465
- const IGNORED_CANCELLED$1 = /* @__PURE__ */ Object.freeze({
466
- status: "ignored",
467
- reason: "cancelled"
468
- });
469
- function resolveResetDelay$1(value) {
470
- if (value === false || value === Infinity) return null;
471
- if (value === void 0 || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;
472
- return Math.max(0, value);
473
- }
474
- /** Pure helper: can `retry()` do anything from this state? */
475
- function canRetryState(state, maxRetries) {
476
- return state.status === "error" && state.payload !== null && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
477
- }
478
- let defaultAdapter$1;
479
- const getDefaultAdapter$1 = () => defaultAdapter$1 ?? (defaultAdapter$1 = createBrowserClipboardAdapter());
480
- /** Framework-agnostic copy state machine. */
481
- function createCopyMachine(options = {}) {
482
- const read = typeof options === "function" ? options : () => options;
483
- const listeners = /* @__PURE__ */ new Set();
484
- let state = IDLE_STATE;
485
- let generation = 0;
486
- let resetTimer;
487
- const operations = createOperations();
488
- const now = () => (read().now ?? Date.now)();
489
- let joined = null;
490
- const member = { release: () => {
491
- if (state.status === "copied") {
492
- clearResetTimer();
493
- setState(IDLE_STATE);
494
- }
495
- } };
496
- const setState = (next) => {
497
- if (next === state) return;
498
- const previous = state;
499
- state = next;
500
- if (previous.status === "copied" && next.status !== "copied" && joined) {
501
- joined.deactivate(member);
502
- joined = null;
503
- }
504
- for (const listener of Array.from(listeners)) listener();
505
- };
506
- const joinCoordinator = () => {
507
- joined = read().coordinator ?? null;
508
- joined?.activate(member);
509
- };
510
- const clearResetTimer = () => {
511
- if (resetTimer !== void 0) {
512
- clearTimeout(resetTimer);
513
- resetTimer = void 0;
514
- }
515
- };
516
- const scheduleReset = (copied) => {
517
- clearResetTimer();
518
- const delay = resolveResetDelay$1(read().resetAfterMs);
519
- if (delay === null) return;
520
- const remaining = Math.max(0, delay - (now() - copied.at));
521
- resetTimer = setTimeout(() => {
522
- resetTimer = void 0;
523
- setState(IDLE_STATE);
524
- }, remaining);
525
- };
526
- const settleError = (error, payload, retryCount) => {
527
- setState({
528
- status: "error",
529
- payload,
530
- error,
531
- retryCount
532
- });
533
- invoke(read().onError, error, payload);
534
- };
535
- const run = (source, retryCount) => {
536
- clearResetTimer();
537
- const current = ++generation;
538
- let payload;
539
- try {
540
- const resolved = typeof source === "function" ? source() : source;
541
- const resolvedUnknown = resolved;
542
- if (resolvedUnknown !== null && typeof resolvedUnknown === "object" && typeof resolvedUnknown.then === "function") {
543
- 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().");
544
- settleError(error, null, retryCount);
545
- return Promise.resolve({
546
- status: "error",
547
- error
548
- });
549
- }
550
- payload = normalizePayload(resolved);
551
- } catch (cause) {
552
- const error = sourceError(cause, "The copy source function threw.");
553
- settleError(error, null, retryCount);
554
- return Promise.resolve({
555
- status: "error",
556
- error
557
- });
558
- }
559
- const invalid = validatePayload(payload);
560
- if (invalid) {
561
- settleError(invalid, payload, retryCount);
562
- return Promise.resolve({
563
- status: "error",
564
- error: invalid
565
- });
566
- }
567
- setState({
568
- status: "copying",
569
- payload,
570
- retryCount
571
- });
572
- const context = operations.start();
573
- let pending;
574
- try {
575
- pending = (read().adapter ?? getDefaultAdapter$1()).write(payload, context);
576
- } catch (cause) {
577
- pending = Promise.reject(cause);
578
- }
579
- return pending.then(() => {
580
- operations.end(context);
581
- if (current === generation) {
582
- const copied = {
583
- status: "copied",
584
- payload,
585
- at: now()
586
- };
587
- setState(copied);
588
- joinCoordinator();
589
- scheduleReset(copied);
590
- invoke(read().onCopy, payload);
591
- }
592
- return {
593
- status: "copied",
594
- payload
595
- };
596
- }, (cause) => {
597
- operations.end(context);
598
- if (context.signal.aborted) return IGNORED_CANCELLED$1;
599
- const error = toCopyError(cause);
600
- settleError(error, payload, retryCount);
601
- return {
602
- status: "error",
603
- error
604
- };
605
- });
606
- };
607
- const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT$1) : run(source, 0);
608
- const retry = () => {
609
- if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING$1);
610
- if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE$1);
611
- if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
612
- const error = createCopyError("max-retries-exceeded", `Copy failed after ${String(state.retryCount)} retries.`, state.error);
613
- settleError(error, state.payload, state.retryCount);
614
- return Promise.resolve({
615
- status: "error",
616
- error
617
- });
618
- }
619
- return run(state.payload, state.retryCount + 1);
620
- };
621
- const reset = () => {
622
- ++generation;
623
- const cancelled = operations.abort();
624
- clearResetTimer();
625
- const wasIdle = state.status === "idle";
626
- setState(IDLE_STATE);
627
- if (cancelled) invoke(read().onCancel, "reset");
628
- if (!wasIdle) invoke(read().onReset);
629
- };
630
- const connect = () => {
631
- if (state.status === "copied") scheduleReset(state);
632
- return () => {
633
- ++generation;
634
- const cancelled = operations.abort();
635
- clearResetTimer();
636
- if (state.status === "copying") setState(IDLE_STATE);
637
- if (cancelled) invoke(read().onCancel, "disconnect");
638
- };
639
- };
640
- return {
641
- getSnapshot: () => state,
642
- subscribe: (listener) => {
643
- listeners.add(listener);
644
- return () => {
645
- listeners.delete(listener);
646
- };
647
- },
648
- copy,
649
- retry,
650
- reset,
651
- connect
652
- };
653
- }
654
- //#endregion
655
- //#region src/core/copy-interceptor.ts
656
- const DEFAULT_INTERCEPTED_EVENTS = ["copy", "cut"];
657
- function isNode(value) {
658
- return typeof value === "object" && value !== null && typeof value.nodeType === "number";
659
- }
660
- function readTextField(target) {
661
- if (!isNode(target) || target.nodeType !== 1) return null;
662
- const tag = target.tagName;
663
- if (tag !== "INPUT" && tag !== "TEXTAREA") return null;
664
- const field = target;
665
- try {
666
- const { selectionStart: start, selectionEnd: end } = field;
667
- return typeof start === "number" && typeof end === "number" ? {
668
- field,
669
- start,
670
- end
671
- } : null;
672
- } catch {
673
- return null;
674
- }
675
- }
676
- function documentOf(target) {
677
- if (isNode(target)) return target.nodeType === 9 ? target : target.ownerDocument;
678
- return typeof document === "undefined" ? null : document;
679
- }
680
- function isEditableNode(node) {
681
- return (node.nodeType === 1 ? node : node.parentElement)?.isContentEditable === true;
682
- }
683
- function selectedRanges(doc) {
684
- const selection = doc?.getSelection();
685
- if (!selection || selection.isCollapsed) return null;
686
- const ranges = [];
687
- for (let index = 0; index < selection.rangeCount; index += 1) ranges.push(selection.getRangeAt(index));
688
- return {
689
- selection,
690
- ranges
691
- };
692
- }
693
- function readSelection(event) {
694
- const kind = event.type === "cut" ? "cut" : "copy";
695
- const fieldSelection = readTextField(event.target);
696
- if (fieldSelection) {
697
- const { field, start, end } = fieldSelection;
698
- const text = field.value.slice(Math.min(start, end), Math.max(start, end));
699
- if (text.length === 0) return null;
700
- return {
701
- selection: {
702
- kind,
703
- text,
704
- html: null,
705
- fragment: null,
706
- field,
707
- editable: !field.readOnly && !field.disabled
708
- },
709
- doc: field.ownerDocument
710
- };
711
- }
712
- const doc = documentOf(event.target);
713
- const selected = selectedRanges(doc);
714
- const first = selected?.ranges[0];
715
- if (!doc || !selected || !first) return null;
716
- const text = selected.selection.toString();
717
- if (text.length === 0) return null;
718
- const container = doc.createElement("div");
719
- for (const range of selected.ranges) container.appendChild(range.cloneContents());
720
- const html = container.innerHTML;
721
- const fragment = doc.createDocumentFragment();
722
- while (container.firstChild) fragment.appendChild(container.firstChild);
723
- return {
724
- selection: {
725
- kind,
726
- text,
727
- html,
728
- fragment,
729
- field: null,
730
- editable: isEditableNode(first.startContainer)
731
- },
732
- doc
733
- };
734
- }
735
- /** Reads the selection behind a copy event, or `null` if nothing readable is selected. */
736
- function readCopySelection(event) {
737
- const read = readSelection(event);
738
- return read ? read.selection : null;
739
- }
740
- const nonEmpty$1 = (value) => typeof value === "string" && value.length > 0;
741
- const invalid$4 = (message, cause) => ({
742
- ok: false,
743
- error: createCopyError("invalid-payload", message, cause)
744
- });
745
- const unsupported$1 = (message) => ({
746
- ok: false,
747
- error: createCopyError("unsupported-format", message)
748
- });
749
- /**
750
- * Validates a decision and turns it into `[mimeType, data]` pairs. Kept
751
- * self-contained (no shared validator) so the interceptor stays small; the
752
- * checks still run for plain-JS callers the types can't protect.
753
- */
754
- function prepare(decision) {
755
- const candidate = typeof decision === "string" ? {
756
- kind: "text",
757
- value: decision
758
- } : decision;
759
- if (typeof candidate !== "object" || candidate === null) return invalid$4("Copy transforms must return a string, a payload, false, or nothing.");
760
- if (typeof candidate.then === "function") return invalid$4("Copy transforms must be synchronous; the clipboard closes when the event ends.");
761
- const payload = candidate;
762
- const fields = candidate;
763
- const ok = (entries) => ({
764
- ok: true,
765
- payload,
766
- entries
767
- });
768
- switch (fields["kind"]) {
769
- case "text": return nonEmpty$1(fields["value"]) ? ok([["text/plain", fields["value"]]]) : invalid$4("Text payload must be a non-empty string.");
770
- case "html": return nonEmpty$1(fields["html"]) && nonEmpty$1(fields["text"]) ? ok([["text/html", fields["html"]], ["text/plain", fields["text"]]]) : invalid$4("HTML payload requires non-empty `html` and plain-text `text`.");
771
- case "json": {
772
- const pretty = fields["pretty"];
773
- const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
774
- let json;
775
- try {
776
- json = JSON.stringify(fields["value"], null, indent);
777
- } catch (cause) {
778
- return invalid$4("JSON payload could not be serialised (circular reference or BigInt?).", cause);
779
- }
780
- return typeof json === "string" ? ok([["text/plain", json]]) : invalid$4("JSON payload serialised to nothing.");
781
- }
782
- case "multi": {
783
- const items = fields["items"];
784
- if (!Array.isArray(items) || items.length === 0) return invalid$4("Multi payload requires at least one item.");
785
- const entries = [];
786
- for (const item of items) {
787
- const { mimeType, data } = item ?? {};
788
- if (!nonEmpty$1(mimeType) || entries.some(([seen]) => seen === mimeType)) return invalid$4("Every multi item needs a unique, non-empty `mimeType`.");
789
- if (typeof data !== "string") return unsupported$1(`Multi item "${mimeType}" must be a string during a copy event.`);
790
- entries.push([mimeType, data]);
791
- }
792
- const writable = entries.filter(([mimeType]) => !isWebCustomFormat(mimeType));
793
- return writable.length > 0 ? ok(writable) : unsupported$1("Web custom formats need the async Clipboard API (useCopy).");
794
- }
795
- default: return unsupported$1(`"${String(fields["kind"])}" payloads cannot be written during a copy event; use useCopy() for images.`);
796
- }
797
- }
798
- /** Deletes the selection the way a native cut would (keeps undo history, fires `input`). */
799
- function deleteSelection(doc) {
800
- const legacy = doc;
801
- try {
802
- return legacy.execCommand?.("delete") === true;
803
- } catch {
804
- return false;
805
- }
806
- }
807
- /**
808
- * Applies a transform to one `copy`/`cut` event. Use directly from an
809
- * `onCopy` handler, or let {@link registerCopyInterceptor} scope it.
810
- */
811
- function interceptCopyEvent(event, options) {
812
- if (event.type !== "copy" && event.type !== "cut") return {
813
- status: "passed",
814
- reason: "unsupported-event",
815
- selection: null
816
- };
817
- if (event.defaultPrevented) return {
818
- status: "passed",
819
- reason: "already-handled",
820
- selection: null
821
- };
822
- const read = readSelection(event);
823
- if (!read) return {
824
- status: "passed",
825
- reason: "no-selection",
826
- selection: null
827
- };
828
- const { selection, doc } = read;
829
- const fail = (error) => {
830
- const fallback = options.failureMode ?? "block";
831
- if (fallback === "block") event.preventDefault();
832
- return {
833
- status: "failed",
834
- selection,
835
- error,
836
- fallback
837
- };
838
- };
839
- let decision;
840
- try {
841
- decision = options.transform(selection);
842
- } catch (cause) {
843
- return fail(sourceError(cause, "The copy transform threw."));
844
- }
845
- if (decision === null || decision === void 0) return {
846
- status: "passed",
847
- reason: "declined",
848
- selection
849
- };
850
- if (decision === false) {
851
- event.preventDefault();
852
- return {
853
- status: "blocked",
854
- selection
855
- };
856
- }
857
- const prepared = prepare(decision);
858
- if (!prepared.ok) return fail(prepared.error);
859
- const data = event.clipboardData;
860
- if (!data) return fail(createCopyError("unsupported", "This browser exposes no clipboardData on copy events."));
861
- event.preventDefault();
862
- try {
863
- for (const [mimeType, value] of prepared.entries) data.setData(mimeType, value);
864
- } catch (cause) {
865
- try {
866
- data.clearData?.();
867
- } catch {}
868
- return {
869
- status: "failed",
870
- selection,
871
- error: createCopyError("unknown", "The browser rejected the clipboard write.", cause),
872
- fallback: "block"
873
- };
874
- }
875
- const deleted = selection.kind === "cut" && selection.editable && deleteSelection(doc);
876
- return {
877
- status: "written",
878
- selection,
879
- payload: prepared.payload,
880
- deleted
881
- };
882
- }
883
- const registries = /* @__PURE__ */ new WeakMap();
884
- function touches(root, event) {
885
- const fieldSelection = readTextField(event.target);
886
- if (fieldSelection) return root.contains(fieldSelection.field);
887
- const selected = selectedRanges(root.ownerDocument);
888
- return selected !== null && selected.ranges.some((range) => range.intersectsNode(root));
889
- }
890
- const priorityOf = (scope) => scope.read().priority ?? 0;
891
- /**
892
- * Highest `priority` first; then the innermost scope; then document order;
893
- * then registration order (same root). A total order, so the result never
894
- * depends on effect timing.
895
- */
896
- function compareScopes(a, b) {
897
- const byPriority = priorityOf(b) - priorityOf(a);
898
- if (byPriority !== 0) return byPriority;
899
- const position = a.root.compareDocumentPosition(b.root);
900
- if (position === 0) return 0;
901
- if (position & 16) return 1;
902
- if (position & 8) return -1;
903
- return position & 4 ? -1 : 1;
904
- }
905
- function dispatch(registry, event) {
906
- if (event.defaultPrevented) return;
907
- const kind = event.type;
908
- const [scope] = [...registry.scopes].filter((scope) => (scope.read().events ?? DEFAULT_INTERCEPTED_EVENTS).includes(kind) && touches(scope.root, event)).sort(compareScopes);
909
- if (!scope) return;
910
- const options = scope.read();
911
- const outcome = interceptCopyEvent(event, options);
912
- invoke(options.onIntercept, outcome);
913
- if (outcome.status === "failed") invoke(options.onError, outcome.error);
914
- }
915
- /**
916
- * Intercepts native copies and cuts whose selection touches `root`. Returns
917
- * an unsubscribe function. Pass a getter to always read the latest options.
918
- *
919
- * One listener per document serves every scope, so overlapping scopes
920
- * resolve deterministically (see `priority`) regardless of registration order.
921
- * Handlers that call `preventDefault()` first (e.g. a React `onCopy`) win.
922
- */
923
- function registerCopyInterceptor(root, options) {
924
- const doc = root.ownerDocument;
925
- let registry = registries.get(doc);
926
- if (!registry) {
927
- const created = {
928
- scopes: /* @__PURE__ */ new Set(),
929
- listener: (event) => {
930
- dispatch(created, event);
931
- }
932
- };
933
- registry = created;
934
- registries.set(doc, created);
935
- doc.addEventListener("copy", created.listener);
936
- doc.addEventListener("cut", created.listener);
937
- }
938
- const scope = {
939
- root,
940
- read: typeof options === "function" ? options : () => options
941
- };
942
- registry.scopes.add(scope);
943
- const active = registry;
944
- let registered = true;
945
- return () => {
946
- if (!registered) return;
947
- registered = false;
948
- active.scopes.delete(scope);
949
- if (active.scopes.size === 0) {
950
- doc.removeEventListener("copy", active.listener);
951
- doc.removeEventListener("cut", active.listener);
952
- registries.delete(doc);
953
- }
954
- };
955
- }
956
- //#endregion
957
- //#region src/core/drag-copy.ts
958
- /**
959
- * Drag-to-copy: populate `DataTransfer` when the user starts dragging an
960
- * element, so whatever they drop it into receives structured data — plain text,
961
- * HTML, JSON, or multiple MIME types — instead of the browser's default
962
- * text-extraction of the dragged DOM.
963
- *
964
- * No Clipboard API, no permission prompt, works in every browser that supports
965
- * HTML5 drag-and-drop (all modern browsers and IE11+).
966
- */
967
- const nonEmpty = (value) => typeof value === "string" && value.length > 0;
968
- const invalid$3 = (message, cause) => ({
969
- ok: false,
970
- error: createCopyError("invalid-payload", message, cause)
971
- });
972
- const unsupported = (message) => ({
973
- ok: false,
974
- error: createCopyError("unsupported-format", message)
975
- });
976
- function prepareDragDecision(decision) {
977
- const candidate = typeof decision === "string" ? {
978
- kind: "text",
979
- value: decision
980
- } : decision;
981
- if (typeof candidate !== "object" || candidate === null) return invalid$3("Drag source must return a string, a payload, false, or nothing.");
982
- if (typeof candidate.then === "function") return invalid$3("Drag sources must be synchronous; DataTransfer closes when dragstart returns.");
983
- const payload = candidate;
984
- const fields = candidate;
985
- const ok = (items) => ({
986
- ok: true,
987
- payload,
988
- items
989
- });
990
- switch (fields["kind"]) {
991
- case "text": return nonEmpty(fields["value"]) ? ok([{
992
- mimeType: "text/plain",
993
- data: fields["value"]
994
- }]) : invalid$3("Text payload must be a non-empty string.");
995
- case "html": return nonEmpty(fields["html"]) && nonEmpty(fields["text"]) ? ok([{
996
- mimeType: "text/html",
997
- data: fields["html"]
998
- }, {
999
- mimeType: "text/plain",
1000
- data: fields["text"]
1001
- }]) : invalid$3("HTML payload requires non-empty `html` and `text`.");
1002
- case "json": {
1003
- const pretty = fields["pretty"];
1004
- const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
1005
- let json;
1006
- try {
1007
- json = JSON.stringify(fields["value"], null, indent);
1008
- } catch (cause) {
1009
- return invalid$3("JSON payload could not be serialised (circular reference or BigInt?).", cause);
1010
- }
1011
- return typeof json === "string" ? ok([{
1012
- mimeType: "text/plain",
1013
- data: json
1014
- }]) : invalid$3("JSON payload serialised to nothing.");
1015
- }
1016
- case "multi": {
1017
- const items = fields["items"];
1018
- if (!Array.isArray(items) || items.length === 0) return invalid$3("Multi payload requires at least one item.");
1019
- const out = [];
1020
- for (const item of items) {
1021
- const { mimeType, data } = item ?? {};
1022
- if (!nonEmpty(mimeType) || out.some((i) => i.mimeType === mimeType)) return invalid$3("Every multi item needs a unique, non-empty `mimeType`.");
1023
- if (typeof data !== "string") return unsupported(`Multi item "${mimeType}" must be a string; DataTransfer does not accept Blobs.`);
1024
- out.push({
1025
- mimeType,
1026
- data
1027
- });
1028
- }
1029
- const writable = out.filter((item) => !isWebCustomFormat(item.mimeType));
1030
- return writable.length > 0 ? ok(writable) : unsupported("Web custom formats need the async Clipboard API (useCopy).");
1031
- }
1032
- default: return unsupported(`"${String(fields["kind"])}" payloads cannot be used for drag-copy; use useCopy() for images.`);
1033
- }
1034
- }
1035
- /**
1036
- * Populates a `dragstart` event's `DataTransfer` with the given payload.
1037
- * Use this from a raw `dragstart` handler or a React `onDragStart` prop.
1038
- * Returns the outcome so you can inspect what happened.
1039
- */
1040
- function applyDragCopy(event, options) {
1041
- if (event.defaultPrevented) return {
1042
- status: "passed",
1043
- reason: "declined"
1044
- };
1045
- let decision;
1046
- try {
1047
- decision = options.source(event);
1048
- } catch (cause) {
1049
- return {
1050
- status: "failed",
1051
- error: sourceError(cause, "The drag source threw.")
1052
- };
1053
- }
1054
- if (decision === null || decision === void 0) return {
1055
- status: "passed",
1056
- reason: "declined"
1057
- };
1058
- if (decision === false) {
1059
- event.preventDefault();
1060
- return {
1061
- status: "passed",
1062
- reason: "cancelled"
1063
- };
1064
- }
1065
- const transfer = event.dataTransfer;
1066
- if (!transfer) return {
1067
- status: "passed",
1068
- reason: "no-transfer"
1069
- };
1070
- const prepared = prepareDragDecision(decision);
1071
- if (!prepared.ok) return {
1072
- status: "failed",
1073
- error: prepared.error
1074
- };
1075
- try {
1076
- transfer.effectAllowed = options.effectAllowed ?? "copy";
1077
- for (const { mimeType, data } of prepared.items) transfer.setData(mimeType, data);
1078
- } catch (cause) {
1079
- try {
1080
- transfer.clearData?.();
1081
- } catch {}
1082
- return {
1083
- status: "failed",
1084
- error: createCopyError("unknown", "The browser rejected the DataTransfer write.", cause)
1085
- };
1086
- }
1087
- return {
1088
- status: "written",
1089
- payload: prepared.payload
1090
- };
1091
- }
1092
- /**
1093
- * Attaches `dragstart` and `dragend` listeners to `element`, calling
1094
- * `applyDragCopy` on every drag start. Returns an object with an
1095
- * `unsubscribe` function.
1096
- *
1097
- * Pass an options getter so the latest options are always used without
1098
- * re-registering — safe to pass an inline object from a React render.
1099
- *
1100
- * ```ts
1101
- * const { unsubscribe } = registerDragCopy(el, () => ({
1102
- * source: () => `${title}\n${url}`,
1103
- * }));
1104
- * ```
1105
- */
1106
- function registerDragCopy(element, options) {
1107
- const read = typeof options === "function" ? options : () => options;
1108
- let unsubscribed = false;
1109
- let currentOutcome = null;
1110
- function onDragStart(raw) {
1111
- const event = raw;
1112
- const opts = read();
1113
- const outcome = applyDragCopy({
1114
- type: event.type,
1115
- dataTransfer: event.dataTransfer,
1116
- get defaultPrevented() {
1117
- return event.defaultPrevented;
1118
- },
1119
- preventDefault: () => {
1120
- event.preventDefault();
1121
- }
1122
- }, opts);
1123
- currentOutcome = outcome;
1124
- const state = {
1125
- status: "dragging",
1126
- outcome
1127
- };
1128
- if (outcome.status === "failed") invoke(opts.onError, outcome.error);
1129
- invoke(opts.onDrag, state);
1130
- }
1131
- function onDragEnd() {
1132
- const opts = read();
1133
- const state = {
1134
- status: "done",
1135
- outcome: currentOutcome
1136
- };
1137
- invoke(opts.onDrag, state);
1138
- currentOutcome = null;
1139
- }
1140
- element.setAttribute("draggable", "true");
1141
- element.addEventListener("dragstart", onDragStart);
1142
- element.addEventListener("dragend", onDragEnd);
1143
- return { unsubscribe() {
1144
- if (unsubscribed) return;
1145
- unsubscribed = true;
1146
- element.removeEventListener("dragstart", onDragStart);
1147
- element.removeEventListener("dragend", onDragEnd);
1148
- element.removeAttribute("draggable");
1149
- } };
1150
- }
1151
- //#endregion
1152
- //#region src/core/paste-reader.ts
1153
- /** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
1154
- function completePasteResult(result) {
1155
- const images = new Set(result.images);
1156
- return {
1157
- ...result,
1158
- imageFiles: result.files.filter((file) => images.has(file))
1159
- };
1160
- }
1161
- const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
1162
- const DEFAULT_PASTE_MAX_BYTES = 33554432;
1163
- const DEFAULT_PASTE_MAX_ITEMS = 32;
1164
- const SHORTHANDS = /* @__PURE__ */ new Map([
1165
- ["text", "text/plain"],
1166
- ["html", "text/html"],
1167
- ["image", "image/*"],
1168
- ["any", "*/*"]
1169
- ]);
1170
- const TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
1171
- function resolvePattern(entry) {
1172
- if (typeof entry !== "string") return null;
1173
- const shorthand = SHORTHANDS.get(entry);
1174
- if (shorthand !== void 0) return shorthand;
1175
- if (entry === "*/*") return entry;
1176
- if (entry.endsWith("/*")) {
1177
- const type = entry.slice(0, -2).toLowerCase();
1178
- return TYPE_TOKEN.test(type) ? `${type}/*` : null;
1179
- }
1180
- return normalizeClipboardType(entry);
1181
- }
1182
- function resolveLimit(value, fallback, name) {
1183
- if (value === void 0) return fallback;
1184
- if (value === Infinity || Number.isInteger(value) && value > 0) return value;
1185
- throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
1186
- }
1187
- /** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
1188
- function resolvePasteReadOptions(options = {}) {
1189
- const accept = [];
1190
- for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {
1191
- const pattern = resolvePattern(entry);
1192
- if (pattern === null) throw copyFailure("invalid-payload", `Invalid \`accept\` entry: ${JSON.stringify(entry)}.`);
1193
- if (!accept.includes(pattern)) accept.push(pattern);
1194
- }
1195
- if (accept.length === 0) throw copyFailure("invalid-payload", "`accept` must list at least one type.");
1196
- return {
1197
- accept,
1198
- maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, "maxBytes"),
1199
- maxItems: resolveLimit(options.maxItems, 32, "maxItems")
1200
- };
1201
- }
1202
- /** Whether a normalised MIME type is allowed by the resolved `accept` list. */
1203
- function isAccepted(mimeType, options) {
1204
- return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));
1205
- }
1206
- function createBudget(options) {
1207
- let bytes = 0;
1208
- let items = 0;
1209
- return { charge: (size) => {
1210
- items += 1;
1211
- bytes += size;
1212
- if (items > options.maxItems) throw copyFailure("too-large", `The paste has more than ${String(options.maxItems)} accepted items.`);
1213
- if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
1214
- } };
1215
- }
1216
- /**
1217
- * UTF-8 byte length of a string, without allocating an encoded copy.
1218
- * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.
1219
- */
1220
- function utf8ByteLength(text) {
1221
- let bytes = 0;
1222
- for (let i = 0; i < text.length; i += 1) {
1223
- const unit = text.charCodeAt(i);
1224
- if (unit < 128) bytes += 1;
1225
- else if (unit < 2048) bytes += 2;
1226
- else if (unit >= 55296 && unit <= 56319 && i + 1 < text.length && (text.charCodeAt(i + 1) & 64512) === 56320) {
1227
- bytes += 4;
1228
- i += 1;
1229
- } else bytes += 3;
1230
- }
1231
- return bytes;
1232
- }
1233
- /** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */
1234
- const sizeOf = (data) => typeof data === "string" ? utf8ByteLength(data) : data.size;
1235
- /** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
1236
- function enforcePasteLimits(entries, options) {
1237
- const budget = createBudget(options);
1238
- for (const entry of entries) budget.charge(sizeOf(entry.data));
1239
- }
1240
- /**
1241
- * Whether a drag in progress could drop anything `accept`s. Uses only what
1242
- * browsers expose before the drop (item kinds and types, never the data).
1243
- * A file whose type is not known yet (some browsers hide it while dragging)
1244
- * counts as a maybe: the drop itself is checked against `accept`.
1245
- */
1246
- function canAcceptDrag(data, options) {
1247
- const items = data.items ?? Array.from(data.types, (type) => type === "Files" ? {
1248
- kind: "file",
1249
- type: ""
1250
- } : {
1251
- kind: "string",
1252
- type
1253
- });
1254
- return Array.from(items).some(({ kind, type: raw }) => {
1255
- const file = kind === "file";
1256
- const type = normalizeClipboardType(raw);
1257
- if (type === null) return file;
1258
- return (file || isTextualMimeType(type)) && isAccepted(type, options);
1259
- });
1260
- }
1261
- /**
1262
- * Synchronously copies the accepted parts of a paste event's `DataTransfer`.
1263
- * It must run during the event: browsers empty the object afterwards.
1264
- */
1265
- function snapshotDataTransfer(data, options) {
1266
- const entries = [];
1267
- const seen = /* @__PURE__ */ new Set();
1268
- for (const raw of Array.from(data.types)) {
1269
- const type = normalizeClipboardType(raw);
1270
- if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;
1271
- seen.add(type);
1272
- const text = data.getData(raw);
1273
- if (text.length > 0) entries.push({
1274
- type,
1275
- data: text,
1276
- file: false
1277
- });
1278
- }
1279
- for (const file of Array.from(data.files ?? [])) {
1280
- const type = normalizeMimeType(file.type) ?? "application/octet-stream";
1281
- if (isAccepted(type, options)) entries.push({
1282
- type,
1283
- data: file,
1284
- file: true
1285
- });
1286
- }
1287
- return entries;
1288
- }
1289
- /**
1290
- * Reads the accepted types from `navigator.clipboard.read()` items, enforcing
1291
- * the limits *before* decoding any text so an oversized paste is never buffered twice.
1292
- */
1293
- async function collectClipboardItems(items, options, signal) {
1294
- const budget = createBudget(options);
1295
- const entries = [];
1296
- const seen = /* @__PURE__ */ new Set();
1297
- for (const item of items) for (const raw of item.types) {
1298
- const type = normalizeClipboardType(raw);
1299
- if (type === null || seen.has(type) || !isAccepted(type, options)) continue;
1300
- seen.add(type);
1301
- let blob;
1302
- try {
1303
- blob = await item.getType(raw);
1304
- } catch {
1305
- continue;
1306
- }
1307
- if (signal?.aborted) throw copyFailure("aborted", "The paste was cancelled.");
1308
- if (blob.size === 0) continue;
1309
- budget.charge(blob.size);
1310
- entries.push({
1311
- type,
1312
- data: isTextualMimeType(type) ? await blob.text() : blob,
1313
- file: false
1314
- });
1315
- }
1316
- return entries;
1317
- }
1318
- function retype(entry, data, type) {
1319
- if (entry.file) {
1320
- const file = data;
1321
- return new File([file], file.name, {
1322
- type,
1323
- lastModified: file.lastModified
1324
- });
1325
- }
1326
- return data.slice(0, data.size, type);
1327
- }
1328
- /**
1329
- * Verifies image bytes, then builds the result. Blobs that claim to be images
1330
- * but aren't (or whose real format is not accepted) are dropped. Throws
1331
- * `no-content` when nothing survives.
1332
- */
1333
- async function finalizePaste(entries, source, options) {
1334
- const items = [];
1335
- const images = [];
1336
- const files = [];
1337
- let text = null;
1338
- let html = null;
1339
- for (const entry of entries) {
1340
- let { type, data } = entry;
1341
- if (typeof data === "string") {
1342
- if (type === "text/plain") text = data;
1343
- else if (type === "text/html") html = data;
1344
- } else if (type.startsWith("image/")) {
1345
- const actual = await sniffImageType(data);
1346
- if (actual === null || !isAccepted(actual, options)) continue;
1347
- if (actual !== type) {
1348
- data = retype(entry, data, actual);
1349
- type = actual;
1350
- }
1351
- images.push(data);
1352
- }
1353
- if (entry.file) files.push(data);
1354
- items.push({
1355
- type,
1356
- data
1357
- });
1358
- }
1359
- if (items.length === 0) throw copyFailure("no-content", "The content holds nothing that matches `accept`.");
1360
- return {
1361
- source,
1362
- items,
1363
- text,
1364
- html,
1365
- images,
1366
- files
1367
- };
1368
- }
1369
- //#endregion
1370
- //#region src/core/paste-adapter.ts
1371
- function defaultEnvironment$1() {
1372
- return typeof window === "undefined" ? void 0 : window;
1373
- }
1374
- const canRead = (clipboard) => typeof clipboard.read === "function";
1375
- const canReadText = (clipboard) => typeof clipboard.readText === "function";
1376
- async function readPlainText(clipboard, options) {
1377
- let text;
1378
- try {
1379
- text = await clipboard.readText();
1380
- } catch (cause) {
1381
- throw new CopyFailure(toCopyError(cause, "read"));
1382
- }
1383
- const entries = text.length > 0 ? [{
1384
- type: "text/plain",
1385
- data: text,
1386
- file: false
1387
- }] : [];
1388
- enforcePasteLimits(entries, options);
1389
- return finalizePaste(entries, "clipboard", options);
1390
- }
1391
- async function readRich(clipboard, options, signal) {
1392
- let items;
1393
- try {
1394
- items = await clipboard.read();
1395
- } catch (cause) {
1396
- throw new CopyFailure(toCopyError(cause, "read"));
1397
- }
1398
- return finalizePaste(await collectClipboardItems(items, options, signal), "clipboard", options);
1399
- }
1400
- function readFromClipboard(env, options, signal) {
1401
- if (!env) throw copyFailure("unsupported", "No browser environment: the clipboard only exists in the browser.");
1402
- if (env.isSecureContext === false) throw copyFailure("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
1403
- const clipboard = env.navigator?.clipboard;
1404
- if (!clipboard) throw copyFailure("unsupported", "navigator.clipboard is not available in this browser.");
1405
- const plainOnly = options.accept.every((pattern) => pattern === "text/plain");
1406
- const acceptsPlain = options.accept.some((pattern) => matchesMimePattern("text/plain", pattern));
1407
- if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options, signal);
1408
- if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);
1409
- throw canReadText(clipboard) ? copyFailure("unsupported-format", "Reading non-text clipboard content requires navigator.clipboard.read().") : copyFailure("unsupported", "This browser cannot read the clipboard.");
1410
- }
1411
- /** The default paste adapter: async Clipboard API with feature detection and honest errors. */
1412
- function createBrowserPasteAdapter(options = {}) {
1413
- const getEnvironment = options.getEnvironment ?? defaultEnvironment$1;
1414
- return { read: (resolved, context) => {
1415
- try {
1416
- return readFromClipboard(getEnvironment(), resolved, context?.signal);
1417
- } catch (cause) {
1418
- return Promise.reject(cause);
1419
- }
1420
- } };
1421
- }
1422
- //#endregion
1423
- //#region src/core/paste-machine.ts
1424
- const PASTE_IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
1425
- const PASTE_READING_STATE = /* @__PURE__ */ Object.freeze({ status: "reading" });
1426
- const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
1427
- status: "ignored",
1428
- reason: "in-flight"
1429
- });
1430
- const IGNORED_NO_CONTENT = /* @__PURE__ */ Object.freeze({
1431
- status: "ignored",
1432
- reason: "no-accepted-content"
1433
- });
1434
- const IGNORED_NOTHING = /* @__PURE__ */ Object.freeze({
1435
- status: "ignored",
1436
- reason: "nothing-to-retry"
1437
- });
1438
- const IGNORED_NOT_RETRYABLE = /* @__PURE__ */ Object.freeze({
1439
- status: "ignored",
1440
- reason: "not-retryable"
1441
- });
1442
- const IGNORED_CANCELLED = /* @__PURE__ */ Object.freeze({
1443
- status: "ignored",
1444
- reason: "cancelled"
1445
- });
1446
- function resolveResetDelay(value) {
1447
- if (value === void 0 || value === false || value === Infinity || Number.isNaN(value)) return null;
1448
- return Math.max(0, value);
1449
- }
1450
- /** Pure helper: can `retry()` do anything from this state? */
1451
- function canRetryPasteState(state, maxRetries) {
1452
- return state.status === "error" && state.source === "clipboard" && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
1453
- }
1454
- let defaultAdapter;
1455
- const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserPasteAdapter());
1456
- /** Framework-agnostic paste state machine. */
1457
- function createPasteMachine(options = {}) {
1458
- const read = typeof options === "function" ? options : () => options;
1459
- const listeners = /* @__PURE__ */ new Set();
1460
- let state = PASTE_IDLE_STATE;
1461
- let generation = 0;
1462
- let resetTimer;
1463
- const operations = createOperations();
1464
- const now = () => (read().now ?? Date.now)();
1465
- const setState = (next) => {
1466
- if (next === state) return;
1467
- state = next;
1468
- for (const listener of Array.from(listeners)) listener();
1469
- };
1470
- const clearResetTimer = () => {
1471
- if (resetTimer !== void 0) {
1472
- clearTimeout(resetTimer);
1473
- resetTimer = void 0;
1474
- }
1475
- };
1476
- const scheduleReset = (readState) => {
1477
- clearResetTimer();
1478
- const delay = resolveResetDelay(read().resetAfterMs);
1479
- if (delay === null) return;
1480
- const remaining = Math.max(0, delay - (now() - readState.at));
1481
- resetTimer = setTimeout(() => {
1482
- resetTimer = void 0;
1483
- setState(PASTE_IDLE_STATE);
1484
- }, remaining);
1485
- };
1486
- const settleError = (error, source, retryCount) => {
1487
- setState({
1488
- status: "error",
1489
- error,
1490
- source,
1491
- retryCount
1492
- });
1493
- invoke(read().onError, error);
1494
- };
1495
- /** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */
1496
- const run = (produce, source, retryCount) => {
1497
- clearResetTimer();
1498
- const current = ++generation;
1499
- const superseded = operations.abort();
1500
- const context = operations.start();
1501
- setState(PASTE_READING_STATE);
1502
- if (superseded) invoke(read().onCancel, "superseded");
1503
- let pending;
1504
- try {
1505
- pending = produce(context);
1506
- } catch (cause) {
1507
- pending = Promise.reject(cause);
1508
- }
1509
- return pending.then(completePasteResult).then((result) => {
1510
- operations.end(context);
1511
- if (current === generation) {
1512
- const readState = {
1513
- status: "read",
1514
- result,
1515
- at: now()
1516
- };
1517
- setState(readState);
1518
- scheduleReset(readState);
1519
- invoke(read().onPaste, result);
1520
- }
1521
- return {
1522
- status: "read",
1523
- result
1524
- };
1525
- }, (cause) => {
1526
- operations.end(context);
1527
- if (context.signal.aborted) return IGNORED_CANCELLED;
1528
- const error = toCopyError(cause, "read");
1529
- settleError(error, source, retryCount);
1530
- return {
1531
- status: "error",
1532
- error
1533
- };
1534
- });
1535
- };
1536
- const readClipboard = (retryCount) => run((context) => (read().adapter ?? getDefaultAdapter()).read(resolvePasteReadOptions(read()), context), "clipboard", retryCount);
1537
- const paste = () => state.status === "reading" ? Promise.resolve(IGNORED_IN_FLIGHT) : readClipboard(0);
1538
- const retry = () => {
1539
- if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
1540
- if (state.source !== "clipboard" || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
1541
- if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
1542
- const error = createCopyError("max-retries-exceeded", `Paste failed after ${String(state.retryCount)} retries.`, state.error);
1543
- settleError(error, "clipboard", state.retryCount);
1544
- return Promise.resolve({
1545
- status: "error",
1546
- error
1547
- });
1548
- }
1549
- return readClipboard(state.retryCount + 1);
1550
- };
1551
- /** Shared by paste and drop events: their `DataTransfer` has the same shape and lifetime. */
1552
- const transfer = (data, event, source) => {
1553
- const current = read();
1554
- if (source === "drop" && current.preventDefault !== false) event.preventDefault();
1555
- if (!data) return Promise.resolve(IGNORED_NO_CONTENT);
1556
- let resolved;
1557
- try {
1558
- resolved = resolvePasteReadOptions(current);
1559
- } catch (cause) {
1560
- const error = toCopyError(cause, "read");
1561
- ++generation;
1562
- const superseded = operations.abort();
1563
- clearResetTimer();
1564
- settleError(error, source, 0);
1565
- if (superseded) invoke(current.onCancel, "superseded");
1566
- return Promise.resolve({
1567
- status: "error",
1568
- error
1569
- });
1570
- }
1571
- const entries = snapshotDataTransfer(data, resolved);
1572
- if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);
1573
- if (source === "event" && current.preventDefault !== false) event.preventDefault();
1574
- return run(() => {
1575
- enforcePasteLimits(entries, resolved);
1576
- return finalizePaste(entries, source, resolved);
1577
- }, source, 0);
1578
- };
1579
- const pasteEvent = (event) => transfer(event.clipboardData, event, "event");
1580
- const dropEvent = (event) => transfer(event.dataTransfer, event, "drop");
1581
- const reset = () => {
1582
- ++generation;
1583
- const cancelled = operations.abort();
1584
- clearResetTimer();
1585
- const wasIdle = state.status === "idle";
1586
- setState(PASTE_IDLE_STATE);
1587
- if (cancelled) invoke(read().onCancel, "reset");
1588
- if (!wasIdle) invoke(read().onReset);
1589
- };
1590
- const connect = () => {
1591
- if (state.status === "read") scheduleReset(state);
1592
- return () => {
1593
- ++generation;
1594
- const cancelled = operations.abort();
1595
- clearResetTimer();
1596
- if (state.status === "reading") setState(PASTE_IDLE_STATE);
1597
- if (cancelled) invoke(read().onCancel, "disconnect");
1598
- };
1599
- };
1600
- return {
1601
- getSnapshot: () => state,
1602
- subscribe: (listener) => {
1603
- listeners.add(listener);
1604
- return () => {
1605
- listeners.delete(listener);
1606
- };
1607
- },
1608
- paste,
1609
- pasteEvent,
1610
- dropEvent,
1611
- retry,
1612
- reset,
1613
- connect
1614
- };
1615
- }
1616
- //#endregion
1617
12
  //#region src/react/CopyGroup.tsx
1618
13
  const CopyGroupContext = /* @__PURE__ */ (0, react.createContext)(null);
1619
14
  /**
@@ -1622,7 +17,7 @@ const CopyGroupContext = /* @__PURE__ */ (0, react.createContext)(null);
1622
17
  * Opt a single field out with `copyOptions={{ coordinator: null }}`. Groups nest; the nearest wins.
1623
18
  */
1624
19
  function CopyGroup({ children, coordinator }) {
1625
- const [owned] = (0, react.useState)(createCopyCoordinator);
20
+ const [owned] = (0, react.useState)(require_core.createCopyCoordinator);
1626
21
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopyGroupContext.Provider, {
1627
22
  value: coordinator ?? owned,
1628
23
  children
@@ -1651,7 +46,7 @@ function composeEventHandlers(theirs, ours) {
1651
46
  }
1652
47
  //#endregion
1653
48
  //#region src/react/useCopy.ts
1654
- const getServerSnapshot$2 = () => IDLE_STATE;
49
+ const getServerSnapshot$2 = () => require_core.IDLE_STATE;
1655
50
  /** An explicit `coordinator` (including `null`) wins over the surrounding `<CopyGroup>`. */
1656
51
  function withGroup(options, group) {
1657
52
  return options.coordinator !== void 0 || group === null ? options : {
@@ -1669,10 +64,10 @@ function useCopy(options = {}) {
1669
64
  useIsomorphicLayoutEffect(() => {
1670
65
  optionsRef.current = effective;
1671
66
  });
1672
- const [machine] = (0, react.useState)(() => createCopyMachine(() => optionsRef.current));
67
+ const [machine] = (0, react.useState)(() => require_core.createCopyMachine(() => optionsRef.current));
1673
68
  (0, react.useEffect)(() => machine.connect(), [machine]);
1674
69
  const state = (0, react.useSyncExternalStore)(machine.subscribe, machine.getSnapshot, getServerSnapshot$2);
1675
- const canRetry = canRetryState(state, effective.maxRetries);
70
+ const canRetry = require_core.canRetryState(state, effective.maxRetries);
1676
71
  return (0, react.useMemo)(() => ({
1677
72
  state,
1678
73
  status: state.status,
@@ -1712,7 +107,7 @@ function useCopyInterceptor(options) {
1712
107
  const enabled = options.enabled !== false;
1713
108
  (0, react.useEffect)(() => {
1714
109
  if (!node || !enabled) return void 0;
1715
- return registerCopyInterceptor(node, () => optionsRef.current);
110
+ return require_core.registerCopyInterceptor(node, () => optionsRef.current);
1716
111
  }, [node, enabled]);
1717
112
  return { ref: setNode };
1718
113
  }
@@ -1945,7 +340,7 @@ function TriggerLabel({ status, labels }) {
1945
340
  //#region src/react/CopyField.tsx
1946
341
  const defaultCopyFieldMessages = {
1947
342
  copied: "Copied to clipboard",
1948
- error: describeCopyError,
343
+ error: require_errors.describeCopyError,
1949
344
  triggerLabel: (label) => `Copy ${label}`
1950
345
  };
1951
346
  const CopyFieldContext = /* @__PURE__ */ (0, react.createContext)(null);
@@ -2100,7 +495,7 @@ const CopyField = {
2100
495
  };
2101
496
  //#endregion
2102
497
  //#region src/react/usePaste.ts
2103
- const getServerSnapshot = () => PASTE_IDLE_STATE;
498
+ const getServerSnapshot = () => require_core.PASTE_IDLE_STATE;
2104
499
  const DRAG_END_EVENTS = ["drop", "dragend"];
2105
500
  /** A text field or editable region nested inside the drop target, which should keep its native drop. */
2106
501
  const isNestedEditable = (event) => {
@@ -2124,7 +519,7 @@ function usePaste(options = {}) {
2124
519
  useIsomorphicLayoutEffect(() => {
2125
520
  optionsRef.current = options;
2126
521
  });
2127
- const [machine] = (0, react.useState)(() => createPasteMachine(() => optionsRef.current));
522
+ const [machine] = (0, react.useState)(() => require_core.createPasteMachine(() => optionsRef.current));
2128
523
  (0, react.useEffect)(() => machine.connect(), [machine]);
2129
524
  const listenOnDocument = options.listenOnDocument === true;
2130
525
  (0, react.useEffect)(() => {
@@ -2138,7 +533,7 @@ function usePaste(options = {}) {
2138
533
  };
2139
534
  }, [listenOnDocument, machine]);
2140
535
  const state = (0, react.useSyncExternalStore)(machine.subscribe, machine.getSnapshot, getServerSnapshot);
2141
- const canRetry = canRetryPasteState(state, options.maxRetries);
536
+ const canRetry = require_core.canRetryPasteState(state, options.maxRetries);
2142
537
  const targetProps = (0, react.useMemo)(() => ({ onPaste: (event) => {
2143
538
  machine.pasteEvent(event);
2144
539
  } }), [machine]);
@@ -2151,7 +546,7 @@ function usePaste(options = {}) {
2151
546
  const dropTargetProps = (0, react.useMemo)(() => {
2152
547
  const accepts = (data) => {
2153
548
  try {
2154
- return canAcceptDrag(data, resolvePasteReadOptions(optionsRef.current));
549
+ return require_paste_reader.canAcceptDrag(data, require_paste_reader.resolvePasteReadOptions(optionsRef.current));
2155
550
  } catch {
2156
551
  return true;
2157
552
  }
@@ -2261,7 +656,7 @@ function usePasteDisplayStatus(status, options = {}) {
2261
656
  const defaultPasteFieldMessages = {
2262
657
  pasted: "Pasted from clipboard",
2263
658
  dropped: "Dropped content added",
2264
- error: describePasteError,
659
+ error: require_errors.describePasteError,
2265
660
  triggerLabel: (label) => `Paste ${label}`,
2266
661
  zoneLabel: (label) => `Paste area for ${label}`
2267
662
  };
@@ -2550,7 +945,7 @@ function useDragCopy(options) {
2550
945
  const enabled = options.enabled !== false;
2551
946
  const onDragStart = (0, react.useCallback)((event) => {
2552
947
  const { onDrag, onError, source, effectAllowed } = optionsRef.current;
2553
- const outcome = applyDragCopy(event, effectAllowed !== void 0 ? {
948
+ const outcome = require_core.applyDragCopy(event, effectAllowed !== void 0 ? {
2554
949
  source,
2555
950
  effectAllowed
2556
951
  } : { source });
@@ -2559,8 +954,8 @@ function useDragCopy(options) {
2559
954
  outcome
2560
955
  };
2561
956
  setState(next);
2562
- if (outcome.status === "failed") invoke(onError, outcome.error);
2563
- invoke(onDrag, next);
957
+ if (outcome.status === "failed") require_core.invoke(onError, outcome.error);
958
+ require_core.invoke(onDrag, next);
2564
959
  }, []);
2565
960
  (0, react.useEffect)(() => {
2566
961
  if (!node || !enabled) return void 0;
@@ -2572,7 +967,7 @@ function useDragCopy(options) {
2572
967
  source,
2573
968
  effectAllowed
2574
969
  } : { source };
2575
- const outcome = applyDragCopy({
970
+ const outcome = require_core.applyDragCopy({
2576
971
  type: event.type,
2577
972
  dataTransfer: event.dataTransfer,
2578
973
  get defaultPrevented() {
@@ -2587,8 +982,8 @@ function useDragCopy(options) {
2587
982
  outcome
2588
983
  };
2589
984
  setState(next);
2590
- if (outcome.status === "failed") invoke(onError, outcome.error);
2591
- invoke(onDrag, next);
985
+ if (outcome.status === "failed") require_core.invoke(onError, outcome.error);
986
+ require_core.invoke(onDrag, next);
2592
987
  }
2593
988
  function handleDragEnd() {
2594
989
  const opts = optionsRef.current;
@@ -2597,7 +992,7 @@ function useDragCopy(options) {
2597
992
  status: "done",
2598
993
  outcome: prev.outcome
2599
994
  };
2600
- invoke(opts.onDrag, next);
995
+ require_core.invoke(opts.onDrag, next);
2601
996
  return next;
2602
997
  });
2603
998
  }
@@ -2623,399 +1018,6 @@ function useDragCopy(options) {
2623
1018
  };
2624
1019
  }
2625
1020
  //#endregion
2626
- //#region src/link/url.ts
2627
- /** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */
2628
- const DEFAULT_LINK_PROTOCOLS = /* @__PURE__ */ Object.freeze([
2629
- "https:",
2630
- "http:",
2631
- "mailto:",
2632
- "tel:"
2633
- ]);
2634
- /**
2635
- * Query parameters that only track where a click came from: the defaults of
2636
- * {@link cleanLinkUrl}. `utm_` matches every parameter starting with it.
2637
- */
2638
- const TRACKING_PARAMETERS = /* @__PURE__ */ Object.freeze([
2639
- "utm_",
2640
- "fbclid",
2641
- "gclid",
2642
- "gclsrc",
2643
- "dclid",
2644
- "gbraid",
2645
- "wbraid",
2646
- "msclkid",
2647
- "yclid",
2648
- "twclid",
2649
- "ttclid",
2650
- "li_fat_id",
2651
- "igshid",
2652
- "igsh",
2653
- "mc_cid",
2654
- "mc_eid",
2655
- "_hsenc",
2656
- "_hsmi",
2657
- "mkt_tok",
2658
- "oly_anon_id",
2659
- "oly_enc_id",
2660
- "vero_id",
2661
- "wickedid",
2662
- "_gl"
2663
- ]);
2664
- const invalid$2 = (message) => copyFailure("invalid-payload", message);
2665
- function baseUrl(base) {
2666
- if (base !== void 0) {
2667
- if (typeof base === "string" || base instanceof URL) return String(base);
2668
- throw invalid$2("`base` must be a string or a URL.");
2669
- }
2670
- return typeof location === "undefined" ? void 0 : location.href;
2671
- }
2672
- function protocolSet(protocols) {
2673
- const list = protocols ?? DEFAULT_LINK_PROTOCOLS;
2674
- const valid = (protocol) => typeof protocol === "string" && /^[a-z][a-z\d+.-]*:$/i.test(protocol);
2675
- if (!Array.isArray(list) || list.length === 0 || !list.every(valid)) throw invalid$2("`protocols` must be a non-empty list of schemes with their colon, like \"https:\".");
2676
- return new Set(list.map((protocol) => protocol.toLowerCase()));
2677
- }
2678
- function matcher(params) {
2679
- const list = params ?? TRACKING_PARAMETERS;
2680
- if (!Array.isArray(list) || !list.every((param) => typeof param === "string" || param instanceof RegExp)) throw invalid$2("`clean.params` must be a list of strings and regular expressions.");
2681
- return (name) => {
2682
- const lower = name.toLowerCase();
2683
- return list.some((param) => {
2684
- if (typeof param !== "string") return new RegExp(param.source, param.flags.replace(/[gy]/g, "")).test(name);
2685
- const wanted = param.toLowerCase();
2686
- return wanted.endsWith("_") ? lower.startsWith(wanted) : lower === wanted;
2687
- });
2688
- };
2689
- }
2690
- /** The cleaning step `clean` asks for, or `null`. Throws for an invalid option. */
2691
- function cleaner(option) {
2692
- const cleaning = option ?? false;
2693
- if (cleaning === false) return null;
2694
- if (cleaning !== true && (typeof cleaning !== "object" || cleaning === null)) throw invalid$2("`clean` must be a boolean or an options object.");
2695
- const settings = cleaning === true ? {} : cleaning;
2696
- const tracking = matcher(settings.params);
2697
- const keep = settings.keep ?? [];
2698
- if (!Array.isArray(keep) || !keep.every((name) => typeof name === "string")) throw invalid$2("`clean.keep` must be a list of strings.");
2699
- const kept = new Set(keep.map((name) => name.toLowerCase()));
2700
- return (url) => {
2701
- for (const name of [...new Set(url.searchParams.keys())]) if (tracking(name) && !kept.has(name.toLowerCase())) url.searchParams.delete(name);
2702
- };
2703
- }
2704
- /**
2705
- * Validates `options` once (throwing a typed `invalid-payload` error for invalid
2706
- * ones) and returns a resolver that throws only for invalid links.
2707
- * @internal
2708
- */
2709
- function linkUrlResolver(options = {}) {
2710
- const protocols = protocolSet(options.protocols);
2711
- const base = baseUrl(options.base);
2712
- const clean = cleaner(options.clean);
2713
- return (input) => {
2714
- if (typeof input !== "string" && !(input instanceof URL)) throw invalid$2("A link must be a string or a URL.");
2715
- const raw = String(input).trim();
2716
- if (raw === "") throw invalid$2("A link must not be empty.");
2717
- let url;
2718
- try {
2719
- url = new URL(raw, base);
2720
- } catch (cause) {
2721
- throw copyFailure("invalid-payload", `Not a valid link: ${JSON.stringify(raw.slice(0, 200))}.`, cause);
2722
- }
2723
- if (!protocols.has(url.protocol)) throw invalid$2(`Links with the scheme "${url.protocol}" are not allowed (allowed: ${[...protocols].join(", ")}).`);
2724
- url.username = "";
2725
- url.password = "";
2726
- clean?.(url);
2727
- return url.href;
2728
- };
2729
- }
2730
- /**
2731
- * The link as an absolute, safe URL string, or a typed `invalid-payload` error:
2732
- * relative links are resolved, the scheme must be allowed, user names and
2733
- * passwords are always removed, and tracking parameters optionally.
2734
- */
2735
- function resolveLinkUrl(input, options = {}) {
2736
- return linkUrlResolver(options)(input);
2737
- }
2738
- const invalid$1 = (message) => copyFailure("invalid-payload", message);
2739
- /**
2740
- * Characters a title never keeps: controls, bidi overrides and isolates (which can
2741
- * make a title read differently), and zero-width characters.
2742
- */
2743
- const HIDDEN = /[\0-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u061C\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g;
2744
- /** A title as one clean line: hidden characters removed, whitespace collapsed, length capped. */
2745
- function cleanTitle(title, maxLength) {
2746
- const clean = title.replace(HIDDEN, "").replace(/\s+/g, " ").trim();
2747
- if (clean.length <= maxLength) return clean;
2748
- return `${Array.from(clean).slice(0, maxLength - 1).join("").trimEnd()}\u2026`;
2749
- }
2750
- function maxTitle(value) {
2751
- if (value === void 0) return 300;
2752
- if (Number.isInteger(value) && value >= 1) return value;
2753
- throw invalid$1(`\`maxTitleLength\` must be a positive integer (received ${String(value)}).`);
2754
- }
2755
- function isAnchor(source) {
2756
- return typeof source === "object" && source !== null && source.nodeName === "A" && typeof source.href === "string";
2757
- }
2758
- /**
2759
- * Validates a link and its title: see {@link resolveLinkUrl} for the URL rules.
2760
- * An `<a>` element gives its `href` and its text (or `title` attribute).
2761
- */
2762
- function resolveLink(source, options = {}) {
2763
- let url;
2764
- let title;
2765
- if (typeof source === "string" || source instanceof URL) url = source;
2766
- else if (isAnchor(source)) {
2767
- url = source.getAttribute("href") ?? "";
2768
- title = source.textContent.trim() !== "" ? source.textContent : source.getAttribute("title") ?? void 0;
2769
- if (url !== "" && options.base === void 0) url = source.href;
2770
- } else if (typeof source === "object" && source !== null && "url" in source) {
2771
- url = source.url;
2772
- title = source.title;
2773
- } else throw invalid$1("A link must be a URL, a { url, title } object or an <a> element.");
2774
- if (title !== void 0 && typeof title !== "string") throw invalid$1("A link title must be a string.");
2775
- const href = resolveLinkUrl(url, options);
2776
- const clean = title === void 0 ? "" : cleanTitle(title, maxTitle(options.maxTitleLength));
2777
- return {
2778
- url: href,
2779
- title: clean === "" ? href : clean,
2780
- titled: clean !== ""
2781
- };
2782
- }
2783
- const escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2784
- /** `[title](url)`, safe in every CommonMark renderer: brackets and backslashes escaped, parentheses and spaces encoded. */
2785
- function markdownLink(link) {
2786
- return `[${link.title.replace(/[\\[\]]/g, "\\$&")}](${link.url.replace(/[()<> ]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)})`;
2787
- }
2788
- function plainText(link, format) {
2789
- switch (format) {
2790
- case "url": return link.url;
2791
- case "title": return link.title;
2792
- case "title-and-url": return link.titled ? `${link.title}\n${link.url}` : link.url;
2793
- case "markdown": return markdownLink(link);
2794
- default: throw invalid$1(`\`text\` must be "url", "title", "title-and-url" or "markdown" (received ${JSON.stringify(format)}).`);
2795
- }
2796
- }
2797
- function linkPayload(source, options = {}) {
2798
- const target = options.target ?? "clipboard";
2799
- if (target !== "drag" && target !== "clipboard") throw invalid$1("`target` must be \"clipboard\" or \"drag\".");
2800
- const link = resolveLink(source, options);
2801
- const text = plainText(link, options.text ?? "url");
2802
- const html = `<a href="${escapeHtml(link.url)}">${escapeHtml(link.title)}</a>`;
2803
- if (target === "clipboard") return {
2804
- kind: "html",
2805
- html,
2806
- text
2807
- };
2808
- return {
2809
- kind: "multi",
2810
- items: [
2811
- {
2812
- mimeType: "text/plain",
2813
- data: text
2814
- },
2815
- {
2816
- mimeType: "text/html",
2817
- data: html
2818
- },
2819
- {
2820
- mimeType: "text/uri-list",
2821
- data: link.url,
2822
- optional: true
2823
- },
2824
- {
2825
- mimeType: "text/x-moz-url",
2826
- data: `${link.url}\n${link.title}`,
2827
- optional: true
2828
- }
2829
- ]
2830
- };
2831
- }
2832
- //#endregion
2833
- //#region src/share/share.ts
2834
- /** Phones and tablets: a touch screen is the main input and nothing hovers. */
2835
- const TOUCH_FIRST = "(hover: none) and (pointer: coarse)";
2836
- const defaultEnvironment = () => typeof window === "undefined" ? void 0 : window;
2837
- const invalid = (message) => createCopyError("invalid-payload", message);
2838
- /** Validates and cleans what to share, or returns the typed error for invalid input. */
2839
- function resolveContent(content, options) {
2840
- const value = content;
2841
- if (typeof value !== "object" || value === null) return invalid("Share content must be an object with a url, text or files.");
2842
- const { url, title, text, files } = value;
2843
- let href = null;
2844
- if (url !== void 0 && url !== null) try {
2845
- href = linkUrlResolver(options)(url);
2846
- } catch (error) {
2847
- return toCopyError(error);
2848
- }
2849
- if (title !== void 0 && typeof title !== "string") return invalid("`title` must be a string.");
2850
- if (text !== void 0 && typeof text !== "string") return invalid("`text` must be a string.");
2851
- const list = files ?? [];
2852
- if (!Array.isArray(list) || !list.every((file) => typeof File !== "undefined" && file instanceof File)) return invalid("`files` must be a list of File objects.");
2853
- const cleanName = title === void 0 ? "" : cleanTitle(title, 300);
2854
- const message = text === void 0 || text.trim() === "" ? null : text;
2855
- if (href === null && message === null && list.length === 0) return invalid("There is nothing to share: give a url, text or files.");
2856
- return {
2857
- url: href,
2858
- title: cleanName === "" ? null : cleanName,
2859
- text: message,
2860
- files: list
2861
- };
2862
- }
2863
- /** The `ShareData` the browser receives: only the fields that are set. */
2864
- function shareData(content) {
2865
- return {
2866
- ...content.url === null ? {} : { url: content.url },
2867
- ...content.title === null ? {} : { title: content.title },
2868
- ...content.text === null ? {} : { text: content.text },
2869
- ...content.files.length === 0 ? {} : { files: [...content.files] }
2870
- };
2871
- }
2872
- /** Whether this browser can open its share sheet for `data`. */
2873
- function canShareNatively(environment, data) {
2874
- const nav = environment?.navigator;
2875
- if (typeof nav?.share !== "function") return false;
2876
- if (data === null) return true;
2877
- return typeof nav.canShare === "function" ? nav.canShare(data) : data.files === void 0;
2878
- }
2879
- function isTouchFirst(environment) {
2880
- return typeof environment?.matchMedia === "function" && environment.matchMedia("(hover: none) and (pointer: coarse)").matches;
2881
- }
2882
- function resolveMode(mode) {
2883
- if (mode === void 0) return "auto";
2884
- return mode === "auto" || mode === "native" || mode === "copy" ? mode : invalid("`mode` must be \"auto\", \"native\" or \"copy\".");
2885
- }
2886
- /**
2887
- * How {@link shareOrCopy} would share right now: `"native"` (the share sheet) or
2888
- * `"copy"`. Use it to label the button ("Share…" or "Copy link"). Pass the
2889
- * content when it has files, since not every share sheet takes them.
2890
- */
2891
- function shareMethod(options = {}, content) {
2892
- const mode = resolveMode(options.mode);
2893
- if (typeof mode !== "string" || mode === "copy") return "copy";
2894
- const environment = options.environment ?? defaultEnvironment();
2895
- if (mode === "auto" && !isTouchFirst(environment)) return "copy";
2896
- const resolved = content === void 0 ? null : resolveContent(content, {});
2897
- const data = resolved === null ? null : "type" in resolved ? void 0 : shareData(resolved);
2898
- return data !== void 0 && canShareNatively(environment, data) ? "native" : "copy";
2899
- }
2900
- /** The default copy: a titled link when there is a URL, otherwise the text (one of them is always set here). */
2901
- function defaultCopy(content) {
2902
- if (content.url !== null) return linkPayload({
2903
- url: content.url,
2904
- ...content.title === null ? {} : { title: content.title }
2905
- });
2906
- return content.text;
2907
- }
2908
- async function copyContent(content, reason, options) {
2909
- if (options.copy === void 0 && content.url === null && content.text === null) return {
2910
- status: "error",
2911
- method: "copy",
2912
- error: createCopyError("unsupported-format", "Files can only be shared through a share sheet, and this browser has none for them.")
2913
- };
2914
- let payload;
2915
- try {
2916
- payload = normalizePayload((options.copy ?? defaultCopy)(content));
2917
- } catch (error) {
2918
- return {
2919
- status: "error",
2920
- method: "copy",
2921
- error: toCopyError(error)
2922
- };
2923
- }
2924
- const problem = validatePayload(payload);
2925
- if (problem !== null) return {
2926
- status: "error",
2927
- method: "copy",
2928
- error: problem
2929
- };
2930
- if (options.signal?.aborted === true) return {
2931
- status: "error",
2932
- method: "copy",
2933
- error: createCopyError("aborted", "The share was aborted.")
2934
- };
2935
- try {
2936
- await (options.adapter ?? createBrowserClipboardAdapter()).write(payload, options.signal === void 0 ? void 0 : { signal: options.signal });
2937
- } catch (error) {
2938
- return {
2939
- status: "error",
2940
- method: "copy",
2941
- error: toCopyError(error)
2942
- };
2943
- }
2944
- return {
2945
- status: "copied",
2946
- method: "copy",
2947
- reason,
2948
- payload,
2949
- content
2950
- };
2951
- }
2952
- /**
2953
- * Shares through the device's share sheet where people expect one, and copies a
2954
- * titled link everywhere else. Call it directly in a click handler: the share
2955
- * sheet needs the user's gesture.
2956
- *
2957
- * It never rejects. It resolves to `shared`, `copied` (with why), `cancelled`
2958
- * (the user closed the share sheet: nothing to report) or `error` with a typed
2959
- * {@link CopyError}.
2960
- *
2961
- * @example
2962
- * button.addEventListener('click', async () => {
2963
- * const outcome = await shareOrCopy({ url: location.href, title: document.title });
2964
- * if (outcome.status === 'copied') toast('Link copied');
2965
- * });
2966
- */
2967
- async function shareOrCopy(content, options = {}) {
2968
- const mode = resolveMode(options.mode);
2969
- if (typeof mode !== "string") return {
2970
- status: "error",
2971
- method: "copy",
2972
- error: mode
2973
- };
2974
- const resolved = resolveContent(content, options);
2975
- if ("type" in resolved) return {
2976
- status: "error",
2977
- method: "copy",
2978
- error: resolved
2979
- };
2980
- const environment = options.environment ?? defaultEnvironment();
2981
- if (mode === "copy" || mode === "auto" && !isTouchFirst(environment)) return copyContent(resolved, "preferred", options);
2982
- const data = shareData(resolved);
2983
- if (!canShareNatively(environment, data)) return copyContent(resolved, "unsupported", options);
2984
- try {
2985
- await (environment?.navigator?.share)(data);
2986
- return {
2987
- status: "shared",
2988
- method: "native",
2989
- content: resolved
2990
- };
2991
- } catch (error) {
2992
- if (readName(error) === "AbortError") return {
2993
- status: "cancelled",
2994
- method: "native"
2995
- };
2996
- if (options.fallback === false) return {
2997
- status: "error",
2998
- method: "native",
2999
- error: shareError(error)
3000
- };
3001
- return copyContent(resolved, "fallback", options);
3002
- }
3003
- }
3004
- function readName(error) {
3005
- const name = typeof error === "object" && error !== null ? error.name : void 0;
3006
- return typeof name === "string" ? name : void 0;
3007
- }
3008
- /** Classifies a share sheet failure. */
3009
- function shareError(cause) {
3010
- switch (readName(cause)) {
3011
- case "NotAllowedError": return createCopyError("permission-denied", "The share sheet was blocked: it needs a click, and an iframe needs the web-share permission.", cause);
3012
- case "InvalidStateError": return createCopyError("unknown", "Another share sheet is already open.", cause);
3013
- case "DataError":
3014
- case "TypeError": return createCopyError("unsupported-format", "The share sheet rejected this content.", cause);
3015
- default: return toCopyError(cause);
3016
- }
3017
- }
3018
- //#endregion
3019
1021
  //#region src/react/useShare.ts
3020
1022
  const IDLE = {
3021
1023
  status: "idle",
@@ -3027,7 +1029,7 @@ const IGNORED = /* @__PURE__ */ Object.freeze({
3027
1029
  });
3028
1030
  function resetDelay(value) {
3029
1031
  if (value === false || value === Infinity) return null;
3030
- return value === void 0 || Number.isNaN(value) ? DEFAULT_RESET_AFTER_MS : Math.max(0, value);
1032
+ return value === void 0 || Number.isNaN(value) ? require_core.DEFAULT_RESET_AFTER_MS : Math.max(0, value);
3031
1033
  }
3032
1034
  const statusOf = (outcome) => outcome.status === "cancelled" ? "idle" : outcome.status;
3033
1035
  /**
@@ -3061,13 +1063,13 @@ function useShare(options = {}) {
3061
1063
  }, []);
3062
1064
  const subscribe = (0, react.useCallback)((onChange) => {
3063
1065
  if (typeof window === "undefined" || typeof window.matchMedia !== "function") return () => void 0;
3064
- const list = window.matchMedia(TOUCH_FIRST);
1066
+ const list = window.matchMedia(require_share.TOUCH_FIRST);
3065
1067
  list.addEventListener("change", onChange);
3066
1068
  return () => {
3067
1069
  list.removeEventListener("change", onChange);
3068
1070
  };
3069
1071
  }, []);
3070
- const method = (0, react.useSyncExternalStore)(subscribe, () => shareMethod(optionsRef.current), () => "copy");
1072
+ const method = (0, react.useSyncExternalStore)(subscribe, () => require_share.shareMethod(optionsRef.current), () => "copy");
3071
1073
  const share = (0, react.useCallback)(async (content) => {
3072
1074
  if (inFlight.current) return IGNORED;
3073
1075
  inFlight.current = true;
@@ -3077,7 +1079,7 @@ function useShare(options = {}) {
3077
1079
  status: "sharing",
3078
1080
  outcome: null
3079
1081
  });
3080
- const outcome = await shareOrCopy(content, optionsRef.current);
1082
+ const outcome = await require_share.shareOrCopy(content, optionsRef.current);
3081
1083
  inFlight.current = false;
3082
1084
  if (!mounted.current || current !== generation.current) return outcome;
3083
1085
  setState({
@@ -3111,60 +1113,60 @@ function useShare(options = {}) {
3111
1113
  ]);
3112
1114
  }
3113
1115
  //#endregion
3114
- exports.CopyFailure = CopyFailure;
1116
+ exports.CopyFailure = require_errors.CopyFailure;
3115
1117
  exports.CopyField = CopyField;
3116
1118
  exports.CopyGroup = CopyGroup;
3117
- exports.DEFAULT_INTERCEPTED_EVENTS = DEFAULT_INTERCEPTED_EVENTS;
3118
- exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES;
1119
+ exports.DEFAULT_INTERCEPTED_EVENTS = require_core.DEFAULT_INTERCEPTED_EVENTS;
1120
+ exports.DEFAULT_MAX_RETRIES = require_core.DEFAULT_MAX_RETRIES;
3119
1121
  exports.DEFAULT_MIN_PENDING_MS = DEFAULT_MIN_PENDING_MS;
3120
- exports.DEFAULT_PASTE_ACCEPT = DEFAULT_PASTE_ACCEPT;
3121
- exports.DEFAULT_PASTE_MAX_BYTES = DEFAULT_PASTE_MAX_BYTES;
3122
- exports.DEFAULT_PASTE_MAX_ITEMS = DEFAULT_PASTE_MAX_ITEMS;
1122
+ exports.DEFAULT_PASTE_ACCEPT = require_paste_reader.DEFAULT_PASTE_ACCEPT;
1123
+ exports.DEFAULT_PASTE_MAX_BYTES = require_paste_reader.DEFAULT_PASTE_MAX_BYTES;
1124
+ exports.DEFAULT_PASTE_MAX_ITEMS = require_paste_reader.DEFAULT_PASTE_MAX_ITEMS;
3123
1125
  exports.DEFAULT_PASTE_MIN_PENDING_MS = DEFAULT_PASTE_MIN_PENDING_MS;
3124
1126
  exports.DEFAULT_PASTE_PENDING_DELAY_MS = DEFAULT_PASTE_PENDING_DELAY_MS;
3125
1127
  exports.DEFAULT_PENDING_DELAY_MS = DEFAULT_PENDING_DELAY_MS;
3126
- exports.DEFAULT_RESET_AFTER_MS = DEFAULT_RESET_AFTER_MS;
3127
- exports.IDLE_STATE = IDLE_STATE;
3128
- exports.IMAGE_MIME_TYPE = IMAGE_MIME_TYPE;
1128
+ exports.DEFAULT_RESET_AFTER_MS = require_core.DEFAULT_RESET_AFTER_MS;
1129
+ exports.IDLE_STATE = require_core.IDLE_STATE;
1130
+ exports.IMAGE_MIME_TYPE = require_payload.IMAGE_MIME_TYPE;
3129
1131
  exports.LiveRegion = LiveRegion;
3130
- exports.PASTE_IDLE_STATE = PASTE_IDLE_STATE;
1132
+ exports.PASTE_IDLE_STATE = require_core.PASTE_IDLE_STATE;
3131
1133
  exports.PasteField = PasteField;
3132
- exports.SVG_MIME_TYPE = SVG_MIME_TYPE;
3133
- exports.WEB_CUSTOM_FORMAT_PREFIX = WEB_CUSTOM_FORMAT_PREFIX;
3134
- exports.applyDragCopy = applyDragCopy;
3135
- exports.canAcceptDrag = canAcceptDrag;
3136
- exports.canRetryPasteState = canRetryPasteState;
3137
- exports.canRetryState = canRetryState;
3138
- exports.copyFailure = copyFailure;
3139
- exports.createBrowserClipboardAdapter = createBrowserClipboardAdapter;
3140
- exports.createBrowserPasteAdapter = createBrowserPasteAdapter;
3141
- exports.createCopyCoordinator = createCopyCoordinator;
3142
- exports.createCopyError = createCopyError;
3143
- exports.createCopyMachine = createCopyMachine;
3144
- exports.createPasteMachine = createPasteMachine;
1134
+ exports.SVG_MIME_TYPE = require_mime.SVG_MIME_TYPE;
1135
+ exports.WEB_CUSTOM_FORMAT_PREFIX = require_mime.WEB_CUSTOM_FORMAT_PREFIX;
1136
+ exports.applyDragCopy = require_core.applyDragCopy;
1137
+ exports.canAcceptDrag = require_paste_reader.canAcceptDrag;
1138
+ exports.canRetryPasteState = require_core.canRetryPasteState;
1139
+ exports.canRetryState = require_core.canRetryState;
1140
+ exports.copyFailure = require_errors.copyFailure;
1141
+ exports.createBrowserClipboardAdapter = require_clipboard_adapter.createBrowserClipboardAdapter;
1142
+ exports.createBrowserPasteAdapter = require_core.createBrowserPasteAdapter;
1143
+ exports.createCopyCoordinator = require_core.createCopyCoordinator;
1144
+ exports.createCopyError = require_errors.createCopyError;
1145
+ exports.createCopyMachine = require_core.createCopyMachine;
1146
+ exports.createPasteMachine = require_core.createPasteMachine;
3145
1147
  exports.defaultCopyFieldMessages = defaultCopyFieldMessages;
3146
1148
  exports.defaultPasteFieldMessages = defaultPasteFieldMessages;
3147
- exports.describeCopyError = describeCopyError;
3148
- exports.describePasteError = describePasteError;
3149
- exports.interceptCopyEvent = interceptCopyEvent;
3150
- exports.isBlob = isBlob;
3151
- exports.isCopyFailure = isCopyFailure;
3152
- exports.isRetryableError = isRetryableError;
3153
- exports.isTextualMimeType = isTextualMimeType;
3154
- exports.isWebCustomFormat = isWebCustomFormat;
3155
- exports.matchesMimePattern = matchesMimePattern;
3156
- exports.normalizeClipboardType = normalizeClipboardType;
3157
- exports.normalizeMimeType = normalizeMimeType;
3158
- exports.normalizePayload = normalizePayload;
3159
- exports.readCopySelection = readCopySelection;
3160
- exports.registerCopyInterceptor = registerCopyInterceptor;
3161
- exports.registerDragCopy = registerDragCopy;
3162
- exports.resolveMaxRetries = resolveMaxRetries;
3163
- exports.resolvePasteReadOptions = resolvePasteReadOptions;
3164
- exports.serializeJson = serializeJson;
3165
- exports.sniffImageBytes = sniffImageBytes;
3166
- exports.sniffImageType = sniffImageType;
3167
- exports.toCopyError = toCopyError;
1149
+ exports.describeCopyError = require_errors.describeCopyError;
1150
+ exports.describePasteError = require_errors.describePasteError;
1151
+ exports.interceptCopyEvent = require_core.interceptCopyEvent;
1152
+ exports.isBlob = require_payload.isBlob;
1153
+ exports.isCopyFailure = require_errors.isCopyFailure;
1154
+ exports.isRetryableError = require_errors.isRetryableError;
1155
+ exports.isTextualMimeType = require_mime.isTextualMimeType;
1156
+ exports.isWebCustomFormat = require_mime.isWebCustomFormat;
1157
+ exports.matchesMimePattern = require_mime.matchesMimePattern;
1158
+ exports.normalizeClipboardType = require_mime.normalizeClipboardType;
1159
+ exports.normalizeMimeType = require_mime.normalizeMimeType;
1160
+ exports.normalizePayload = require_payload.normalizePayload;
1161
+ exports.readCopySelection = require_core.readCopySelection;
1162
+ exports.registerCopyInterceptor = require_core.registerCopyInterceptor;
1163
+ exports.registerDragCopy = require_core.registerDragCopy;
1164
+ exports.resolveMaxRetries = require_core.resolveMaxRetries;
1165
+ exports.resolvePasteReadOptions = require_paste_reader.resolvePasteReadOptions;
1166
+ exports.serializeJson = require_payload.serializeJson;
1167
+ exports.sniffImageBytes = require_mime.sniffImageBytes;
1168
+ exports.sniffImageType = require_mime.sniffImageType;
1169
+ exports.toCopyError = require_errors.toCopyError;
3168
1170
  exports.useCopy = useCopy;
3169
1171
  exports.useCopyField = useCopyField;
3170
1172
  exports.useCopyGroup = useCopyGroup;
@@ -3176,7 +1178,7 @@ exports.usePasteDisplayStatus = usePasteDisplayStatus;
3176
1178
  exports.usePasteField = usePasteField;
3177
1179
  exports.useRevealOnInteraction = useRevealOnInteraction;
3178
1180
  exports.useShare = useShare;
3179
- exports.validatePayload = validatePayload;
1181
+ exports.validatePayload = require_payload.validatePayload;
3180
1182
  exports.visuallyHiddenStyle = visuallyHiddenStyle;
3181
1183
 
3182
1184
  //# sourceMappingURL=index.cjs.map