react-smart-copy 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -16,6 +16,7 @@ const RETRYABLE_ERRORS = /* @__PURE__ */ new Set([
16
16
  "permission-denied",
17
17
  "not-focused",
18
18
  "blob-generation-failed",
19
+ "timeout",
19
20
  "unknown"
20
21
  ]);
21
22
  /** Whether retrying the same payload could plausibly succeed. */
@@ -39,25 +40,35 @@ var CopyFailure = class extends Error {
39
40
  function isCopyFailure(value) {
40
41
  return typeof value === "object" && value !== null && value[COPY_FAILURE_BRAND] === true;
41
42
  }
43
+ /** Shorthand for throwing a classified failure. */
44
+ function copyFailure(type, message, cause) {
45
+ return new CopyFailure(createCopyError(type, message, cause));
46
+ }
42
47
  function readString(value, key) {
43
48
  if (typeof value !== "object" || value === null) return void 0;
44
49
  const field = value[key];
45
50
  return typeof field === "string" ? field : void 0;
46
51
  }
47
- /** Classifies anything thrown by the platform or an adapter into a {@link CopyError}. */
48
- function toCopyError(cause) {
52
+ /**
53
+ * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.
54
+ * `operation` only tailors the developer-facing message.
55
+ */
56
+ function toCopyError(cause, operation = "write") {
49
57
  if (isCopyFailure(cause)) return cause.copyError;
50
58
  const name = readString(cause, "name");
51
59
  const message = readString(cause, "message") ?? "";
60
+ const verb = operation === "read" ? "read" : "write";
52
61
  switch (name) {
53
- case "NotAllowedError": return /focus/i.test(message) ? createCopyError("not-focused", "The document was not focused when the copy was attempted.", cause) : createCopyError("permission-denied", "Clipboard write permission was denied.", cause);
62
+ 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);
54
63
  case "SecurityError": return createCopyError("insecure-context", "The clipboard is blocked in this context.", cause);
55
64
  case "NotSupportedError":
56
65
  case "DataError": return createCopyError("unsupported-format", "The browser rejected this clipboard format.", cause);
57
- default: return createCopyError("unknown", message || "The copy failed for an unknown reason.", cause);
66
+ case "AbortError": return createCopyError("aborted", `The clipboard ${verb} was aborted.`, cause);
67
+ case "TimeoutError": return createCopyError("timeout", `The clipboard ${verb} timed out.`, cause);
68
+ default: return createCopyError("unknown", message || `The clipboard ${verb} failed for an unknown reason.`, cause);
58
69
  }
59
70
  }
60
- const DEFAULT_DESCRIPTIONS = {
71
+ const COPY_DESCRIPTIONS = {
61
72
  unsupported: "Copying isn't supported in this browser.",
62
73
  "insecure-context": "Copying requires a secure (HTTPS) connection.",
63
74
  "permission-denied": "Clipboard access was blocked. Allow it and try again.",
@@ -66,11 +77,34 @@ const DEFAULT_DESCRIPTIONS = {
66
77
  "unsupported-format": "This content can't be copied in this browser.",
67
78
  "blob-generation-failed": "The image couldn't be prepared for copying.",
68
79
  "max-retries-exceeded": "Copying failed after several attempts.",
80
+ "no-content": "There is nothing to copy.",
81
+ "too-large": "This content is too large to copy.",
82
+ timeout: "Copying took too long. Try again.",
83
+ aborted: "Copying was cancelled.",
69
84
  unknown: "Couldn't copy to the clipboard. Try again."
70
85
  };
71
- /** Default English, user-facing sentence for an error. Replace for i18n. */
86
+ const PASTE_DESCRIPTIONS = {
87
+ unsupported: "Pasting isn't supported in this browser.",
88
+ "insecure-context": "Pasting requires a secure (HTTPS) connection.",
89
+ "permission-denied": "Clipboard access was blocked. Allow it and try again.",
90
+ "not-focused": "The page lost focus while pasting. Try again.",
91
+ "invalid-payload": "The clipboard content couldn't be read.",
92
+ "unsupported-format": "This clipboard content isn't supported here.",
93
+ "blob-generation-failed": "The pasted image couldn't be read.",
94
+ "max-retries-exceeded": "Pasting failed after several attempts.",
95
+ "no-content": "The clipboard doesn't contain anything that can be pasted here.",
96
+ "too-large": "The clipboard content is too large to paste.",
97
+ timeout: "Pasting took too long. Try again.",
98
+ aborted: "Pasting was cancelled.",
99
+ unknown: "Couldn't read the clipboard. Try again."
100
+ };
101
+ /** Default English, user-facing sentence for a copy error. Replace for i18n. */
72
102
  function describeCopyError(error) {
73
- return DEFAULT_DESCRIPTIONS[error.type];
103
+ return COPY_DESCRIPTIONS[error.type];
104
+ }
105
+ /** Default English, user-facing sentence for a paste error. Replace for i18n. */
106
+ function describePasteError(error) {
107
+ return PASTE_DESCRIPTIONS[error.type];
74
108
  }
75
109
  //#endregion
76
110
  //#region src/core/payload.ts
@@ -139,10 +173,82 @@ function serializeJson(payload) {
139
173
  return text;
140
174
  }
141
175
  //#endregion
176
+ //#region src/core/mime.ts
177
+ /**
178
+ * MIME helpers shared by paste and capture. Everything that comes from the
179
+ * clipboard is untrusted input, so types are normalised and validated before
180
+ * they are compared, and image types are confirmed from the bytes themselves.
181
+ */
182
+ /** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */
183
+ const MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
184
+ /** SVG is XML that can carry scripts; it is never matched by a wildcard. */
185
+ const SVG_MIME_TYPE = "image/svg+xml";
186
+ /** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */
187
+ function normalizeMimeType(value) {
188
+ const separator = value.indexOf(";");
189
+ const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();
190
+ return MIME_SHAPE.test(base) ? base : null;
191
+ }
192
+ /**
193
+ * Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\/*`)?
194
+ * Wildcards never match `image/svg+xml`: accepting SVG must be explicit.
195
+ */
196
+ function matchesMimePattern(mimeType, pattern) {
197
+ if (pattern === mimeType) return true;
198
+ if (mimeType === "image/svg+xml") return false;
199
+ if (pattern === "*/*") return true;
200
+ return pattern.endsWith("/*") && mimeType.startsWith(pattern.slice(0, -1));
201
+ }
202
+ /** Types whose clipboard data is text and is therefore surfaced as a `string`. */
203
+ function isTextualMimeType(mimeType) {
204
+ return mimeType.startsWith("text/") || mimeType === "image/svg+xml" || mimeType === "application/json" || mimeType === "application/xml";
205
+ }
206
+ const SNIFF_BYTES = 16;
207
+ function startsWith(bytes, signature, offset = 0) {
208
+ return signature.every((byte, index) => bytes[offset + index] === byte);
209
+ }
210
+ const ascii = (text) => Array.from(text, (char) => char.charCodeAt(0));
211
+ const PNG = [
212
+ 137,
213
+ 80,
214
+ 78,
215
+ 71,
216
+ 13,
217
+ 10,
218
+ 26,
219
+ 10
220
+ ];
221
+ const JPEG = [
222
+ 255,
223
+ 216,
224
+ 255
225
+ ];
226
+ const GIF = ascii("GIF8");
227
+ const RIFF = ascii("RIFF");
228
+ const WEBP = ascii("WEBP");
229
+ const BMP = ascii("BM");
230
+ const FTYP_AVIF = ascii("ftypavif");
231
+ const FTYP_AVIS = ascii("ftypavis");
232
+ /** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */
233
+ function sniffImageBytes(bytes) {
234
+ if (startsWith(bytes, PNG)) return "image/png";
235
+ if (startsWith(bytes, JPEG)) return "image/jpeg";
236
+ if (startsWith(bytes, GIF)) return "image/gif";
237
+ if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return "image/webp";
238
+ if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return "image/avif";
239
+ if (startsWith(bytes, BMP)) return "image/bmp";
240
+ return null;
241
+ }
242
+ /** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */
243
+ async function sniffImageType(blob) {
244
+ const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();
245
+ return sniffImageBytes(new Uint8Array(head));
246
+ }
247
+ //#endregion
142
248
  //#region src/core/clipboard-adapter.ts
143
249
  const fail = (type, message, cause) => new CopyFailure(createCopyError(type, message, cause));
144
250
  const noop = () => void 0;
145
- function defaultEnvironment() {
251
+ function defaultEnvironment$1() {
146
252
  return typeof window === "undefined" ? void 0 : window;
147
253
  }
148
254
  function getRichClipboard(env, clipboard) {
@@ -180,6 +286,7 @@ async function writeImage(rich, source) {
180
286
  } catch (error) {
181
287
  throw await blob.then(noop, (inner) => inner) ?? error;
182
288
  }
289
+ await blob;
183
290
  }
184
291
  async function writeToClipboard(payload, env, degradeHtmlToText) {
185
292
  if (!env) throw fail("unsupported", "No browser environment: the clipboard only exists in the browser.");
@@ -219,16 +326,32 @@ async function writeToClipboard(payload, env, degradeHtmlToText) {
219
326
  }
220
327
  /** The default adapter: async Clipboard API with feature detection and honest errors. */
221
328
  function createBrowserClipboardAdapter(options = {}) {
222
- const getEnvironment = options.getEnvironment ?? defaultEnvironment;
329
+ const getEnvironment = options.getEnvironment ?? defaultEnvironment$1;
223
330
  const degradeHtmlToText = options.degradeHtmlToText ?? true;
224
331
  return { write: (payload) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText) };
225
332
  }
226
333
  //#endregion
334
+ //#region src/core/copy-coordinator.ts
335
+ function createCopyCoordinator() {
336
+ let active = null;
337
+ return {
338
+ activate: (member) => {
339
+ const previous = active;
340
+ active = member;
341
+ if (previous !== null && previous !== member) previous.release();
342
+ },
343
+ deactivate: (member) => {
344
+ if (active === member) active = null;
345
+ },
346
+ getActive: () => active
347
+ };
348
+ }
349
+ //#endregion
227
350
  //#region src/core/copy-machine.ts
228
351
  const DEFAULT_RESET_AFTER_MS = 2e3;
229
352
  const DEFAULT_MAX_RETRIES = 3;
230
353
  const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
231
- const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
354
+ const IGNORED_IN_FLIGHT$1 = /* @__PURE__ */ Object.freeze({
232
355
  status: "ignored",
233
356
  reason: "in-flight"
234
357
  });
@@ -245,7 +368,7 @@ function resolveMaxRetries(value) {
245
368
  if (value === void 0 || !Number.isFinite(value)) return 3;
246
369
  return Math.max(0, Math.floor(value));
247
370
  }
248
- function resolveResetDelay(value) {
371
+ function resolveResetDelay$1(value) {
249
372
  if (value === false || value === Infinity) return null;
250
373
  if (value === void 0 || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;
251
374
  return Math.max(0, value);
@@ -254,7 +377,7 @@ function resolveResetDelay(value) {
254
377
  function canRetryState(state, maxRetries) {
255
378
  return state.status === "error" && state.payload !== null && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
256
379
  }
257
- function reportCallbackError(error) {
380
+ function reportCallbackError$1(error) {
258
381
  const scope = globalThis;
259
382
  if (typeof scope.reportError === "function") scope.reportError(error);
260
383
  else setTimeout(() => {
@@ -262,16 +385,16 @@ function reportCallbackError(error) {
262
385
  }, 0);
263
386
  }
264
387
  /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
265
- function invoke(fn, ...args) {
388
+ function invoke$1(fn, ...args) {
266
389
  if (!fn) return;
267
390
  try {
268
391
  fn(...args);
269
392
  } catch (error) {
270
- reportCallbackError(error);
393
+ reportCallbackError$1(error);
271
394
  }
272
395
  }
273
- let defaultAdapter;
274
- const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserClipboardAdapter());
396
+ let defaultAdapter$1;
397
+ const getDefaultAdapter$1 = () => defaultAdapter$1 ?? (defaultAdapter$1 = createBrowserClipboardAdapter());
275
398
  /** Framework-agnostic copy state machine. */
276
399
  function createCopyMachine(options = {}) {
277
400
  const read = typeof options === "function" ? options : () => options;
@@ -280,11 +403,27 @@ function createCopyMachine(options = {}) {
280
403
  let generation = 0;
281
404
  let resetTimer;
282
405
  const now = () => (read().now ?? Date.now)();
406
+ let joined = null;
407
+ const member = { release: () => {
408
+ if (state.status === "copied") {
409
+ clearResetTimer();
410
+ setState(IDLE_STATE);
411
+ }
412
+ } };
283
413
  const setState = (next) => {
284
414
  if (next === state) return;
415
+ const previous = state;
285
416
  state = next;
417
+ if (previous.status === "copied" && next.status !== "copied" && joined) {
418
+ joined.deactivate(member);
419
+ joined = null;
420
+ }
286
421
  for (const listener of Array.from(listeners)) listener();
287
422
  };
423
+ const joinCoordinator = () => {
424
+ joined = read().coordinator ?? null;
425
+ joined?.activate(member);
426
+ };
288
427
  const clearResetTimer = () => {
289
428
  if (resetTimer !== void 0) {
290
429
  clearTimeout(resetTimer);
@@ -293,12 +432,12 @@ function createCopyMachine(options = {}) {
293
432
  };
294
433
  const scheduleReset = (copied) => {
295
434
  clearResetTimer();
296
- const delay = resolveResetDelay(read().resetAfterMs);
435
+ const delay = resolveResetDelay$1(read().resetAfterMs);
297
436
  if (delay === null) return;
298
437
  const remaining = Math.max(0, delay - (now() - copied.at));
299
438
  resetTimer = setTimeout(() => {
300
439
  resetTimer = void 0;
301
- if (state === copied) setState(IDLE_STATE);
440
+ setState(IDLE_STATE);
302
441
  }, remaining);
303
442
  };
304
443
  const settleError = (error, payload, retryCount) => {
@@ -308,14 +447,24 @@ function createCopyMachine(options = {}) {
308
447
  error,
309
448
  retryCount
310
449
  });
311
- invoke(read().onError, error, payload);
450
+ invoke$1(read().onError, error, payload);
312
451
  };
313
452
  const run = (source, retryCount) => {
314
453
  clearResetTimer();
315
454
  const current = ++generation;
316
455
  let payload;
317
456
  try {
318
- payload = normalizePayload(typeof source === "function" ? source() : source);
457
+ const resolved = typeof source === "function" ? source() : source;
458
+ const resolvedUnknown = resolved;
459
+ if (resolvedUnknown !== null && typeof resolvedUnknown === "object" && typeof resolvedUnknown.then === "function") {
460
+ 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().");
461
+ settleError(error, null, retryCount);
462
+ return Promise.resolve({
463
+ status: "error",
464
+ error
465
+ });
466
+ }
467
+ payload = normalizePayload(resolved);
319
468
  } catch (cause) {
320
469
  const error = createCopyError("invalid-payload", "The copy source function threw.", cause);
321
470
  settleError(error, null, retryCount);
@@ -339,7 +488,7 @@ function createCopyMachine(options = {}) {
339
488
  });
340
489
  let pending;
341
490
  try {
342
- pending = (read().adapter ?? getDefaultAdapter()).write(payload);
491
+ pending = (read().adapter ?? getDefaultAdapter$1()).write(payload);
343
492
  } catch (cause) {
344
493
  pending = Promise.reject(cause);
345
494
  }
@@ -351,8 +500,9 @@ function createCopyMachine(options = {}) {
351
500
  at: now()
352
501
  };
353
502
  setState(copied);
503
+ joinCoordinator();
354
504
  scheduleReset(copied);
355
- invoke(read().onCopy, payload);
505
+ invoke$1(read().onCopy, payload);
356
506
  }
357
507
  return {
358
508
  status: "copied",
@@ -367,7 +517,7 @@ function createCopyMachine(options = {}) {
367
517
  };
368
518
  });
369
519
  };
370
- const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT) : run(source, 0);
520
+ const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT$1) : run(source, 0);
371
521
  const retry = () => {
372
522
  if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
373
523
  if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
@@ -409,6 +559,415 @@ function createCopyMachine(options = {}) {
409
559
  };
410
560
  }
411
561
  //#endregion
562
+ //#region src/core/paste-reader.ts
563
+ const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
564
+ const DEFAULT_PASTE_MAX_BYTES = 33554432;
565
+ const DEFAULT_PASTE_MAX_ITEMS = 32;
566
+ const SHORTHANDS = /* @__PURE__ */ new Map([
567
+ ["text", "text/plain"],
568
+ ["html", "text/html"],
569
+ ["image", "image/*"],
570
+ ["any", "*/*"]
571
+ ]);
572
+ const TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
573
+ function resolvePattern(entry) {
574
+ if (typeof entry !== "string") return null;
575
+ const shorthand = SHORTHANDS.get(entry);
576
+ if (shorthand !== void 0) return shorthand;
577
+ if (entry === "*/*") return entry;
578
+ if (entry.endsWith("/*")) {
579
+ const type = entry.slice(0, -2).toLowerCase();
580
+ return TYPE_TOKEN.test(type) ? `${type}/*` : null;
581
+ }
582
+ return normalizeMimeType(entry);
583
+ }
584
+ function resolveLimit(value, fallback, name) {
585
+ if (value === void 0) return fallback;
586
+ if (value === Infinity || Number.isInteger(value) && value > 0) return value;
587
+ throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
588
+ }
589
+ /** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
590
+ function resolvePasteReadOptions(options = {}) {
591
+ const accept = [];
592
+ for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {
593
+ const pattern = resolvePattern(entry);
594
+ if (pattern === null) throw copyFailure("invalid-payload", `Invalid \`accept\` entry: ${JSON.stringify(entry)}.`);
595
+ if (!accept.includes(pattern)) accept.push(pattern);
596
+ }
597
+ if (accept.length === 0) throw copyFailure("invalid-payload", "`accept` must list at least one type.");
598
+ return {
599
+ accept,
600
+ maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, "maxBytes"),
601
+ maxItems: resolveLimit(options.maxItems, 32, "maxItems")
602
+ };
603
+ }
604
+ /** Whether a normalised MIME type is allowed by the resolved `accept` list. */
605
+ function isAccepted(mimeType, options) {
606
+ return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));
607
+ }
608
+ function createBudget(options) {
609
+ let bytes = 0;
610
+ let items = 0;
611
+ return { charge: (size) => {
612
+ items += 1;
613
+ bytes += size;
614
+ if (items > options.maxItems) throw copyFailure("too-large", `The paste has more than ${String(options.maxItems)} accepted items.`);
615
+ if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
616
+ } };
617
+ }
618
+ const sizeOf = (data) => typeof data === "string" ? data.length : data.size;
619
+ /** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
620
+ function enforcePasteLimits(entries, options) {
621
+ const budget = createBudget(options);
622
+ for (const entry of entries) budget.charge(sizeOf(entry.data));
623
+ }
624
+ /**
625
+ * Synchronously copies the accepted parts of a paste event's `DataTransfer`.
626
+ * It must run during the event: browsers empty the object afterwards.
627
+ */
628
+ function snapshotDataTransfer(data, options) {
629
+ const entries = [];
630
+ const seen = /* @__PURE__ */ new Set();
631
+ for (const raw of Array.from(data.types)) {
632
+ const type = normalizeMimeType(raw);
633
+ if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;
634
+ seen.add(type);
635
+ const text = data.getData(raw);
636
+ if (text.length > 0) entries.push({
637
+ type,
638
+ data: text,
639
+ file: false
640
+ });
641
+ }
642
+ for (const file of Array.from(data.files ?? [])) {
643
+ const type = normalizeMimeType(file.type) ?? "application/octet-stream";
644
+ if (isAccepted(type, options)) entries.push({
645
+ type,
646
+ data: file,
647
+ file: true
648
+ });
649
+ }
650
+ return entries;
651
+ }
652
+ /**
653
+ * Reads the accepted types from `navigator.clipboard.read()` items, enforcing
654
+ * the limits *before* decoding any text so an oversized paste is never buffered twice.
655
+ */
656
+ async function collectClipboardItems(items, options) {
657
+ const budget = createBudget(options);
658
+ const entries = [];
659
+ const seen = /* @__PURE__ */ new Set();
660
+ for (const item of items) for (const raw of item.types) {
661
+ const type = normalizeMimeType(raw);
662
+ if (type === null || seen.has(type) || !isAccepted(type, options)) continue;
663
+ seen.add(type);
664
+ let blob;
665
+ try {
666
+ blob = await item.getType(raw);
667
+ } catch {
668
+ continue;
669
+ }
670
+ if (blob.size === 0) continue;
671
+ budget.charge(blob.size);
672
+ entries.push({
673
+ type,
674
+ data: isTextualMimeType(type) ? await blob.text() : blob,
675
+ file: false
676
+ });
677
+ }
678
+ return entries;
679
+ }
680
+ function retype(entry, data, type) {
681
+ if (entry.file) {
682
+ const file = data;
683
+ return new File([file], file.name, {
684
+ type,
685
+ lastModified: file.lastModified
686
+ });
687
+ }
688
+ return data.slice(0, data.size, type);
689
+ }
690
+ /**
691
+ * Verifies image bytes, then builds the result. Blobs that claim to be images
692
+ * but aren't (or whose real format is not accepted) are dropped. Throws
693
+ * `no-content` when nothing survives.
694
+ */
695
+ async function finalizePaste(entries, source, options) {
696
+ const items = [];
697
+ const images = [];
698
+ const files = [];
699
+ let text = null;
700
+ let html = null;
701
+ for (const entry of entries) {
702
+ let { type, data } = entry;
703
+ if (typeof data === "string") {
704
+ if (type === "text/plain") text = data;
705
+ else if (type === "text/html") html = data;
706
+ } else if (type.startsWith("image/")) {
707
+ const actual = await sniffImageType(data);
708
+ if (actual === null || !isAccepted(actual, options)) continue;
709
+ if (actual !== type) {
710
+ data = retype(entry, data, actual);
711
+ type = actual;
712
+ }
713
+ images.push(data);
714
+ }
715
+ if (entry.file) files.push(data);
716
+ items.push({
717
+ type,
718
+ data
719
+ });
720
+ }
721
+ if (items.length === 0) throw copyFailure("no-content", "The clipboard holds nothing that matches `accept`.");
722
+ return {
723
+ source,
724
+ items,
725
+ text,
726
+ html,
727
+ images,
728
+ files
729
+ };
730
+ }
731
+ //#endregion
732
+ //#region src/core/paste-adapter.ts
733
+ function defaultEnvironment() {
734
+ return typeof window === "undefined" ? void 0 : window;
735
+ }
736
+ const canRead = (clipboard) => typeof clipboard.read === "function";
737
+ const canReadText = (clipboard) => typeof clipboard.readText === "function";
738
+ async function readPlainText(clipboard, options) {
739
+ let text;
740
+ try {
741
+ text = await clipboard.readText();
742
+ } catch (cause) {
743
+ throw new CopyFailure(toCopyError(cause, "read"));
744
+ }
745
+ const entries = text.length > 0 ? [{
746
+ type: "text/plain",
747
+ data: text,
748
+ file: false
749
+ }] : [];
750
+ enforcePasteLimits(entries, options);
751
+ return finalizePaste(entries, "clipboard", options);
752
+ }
753
+ async function readRich(clipboard, options) {
754
+ let items;
755
+ try {
756
+ items = await clipboard.read();
757
+ } catch (cause) {
758
+ throw new CopyFailure(toCopyError(cause, "read"));
759
+ }
760
+ return finalizePaste(await collectClipboardItems(items, options), "clipboard", options);
761
+ }
762
+ function readFromClipboard(env, options) {
763
+ if (!env) throw copyFailure("unsupported", "No browser environment: the clipboard only exists in the browser.");
764
+ if (env.isSecureContext === false) throw copyFailure("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
765
+ const clipboard = env.navigator?.clipboard;
766
+ if (!clipboard) throw copyFailure("unsupported", "navigator.clipboard is not available in this browser.");
767
+ const plainOnly = options.accept.every((pattern) => pattern === "text/plain");
768
+ const acceptsPlain = options.accept.some((pattern) => matchesMimePattern("text/plain", pattern));
769
+ if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options);
770
+ if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);
771
+ throw canReadText(clipboard) ? copyFailure("unsupported-format", "Reading non-text clipboard content requires navigator.clipboard.read().") : copyFailure("unsupported", "This browser cannot read the clipboard.");
772
+ }
773
+ /** The default paste adapter: async Clipboard API with feature detection and honest errors. */
774
+ function createBrowserPasteAdapter(options = {}) {
775
+ const getEnvironment = options.getEnvironment ?? defaultEnvironment;
776
+ return { read: (resolved) => {
777
+ try {
778
+ return readFromClipboard(getEnvironment(), resolved);
779
+ } catch (cause) {
780
+ return Promise.reject(cause);
781
+ }
782
+ } };
783
+ }
784
+ //#endregion
785
+ //#region src/core/paste-machine.ts
786
+ const PASTE_IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
787
+ const PASTE_READING_STATE = /* @__PURE__ */ Object.freeze({ status: "reading" });
788
+ const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
789
+ status: "ignored",
790
+ reason: "in-flight"
791
+ });
792
+ const IGNORED_NO_CONTENT = /* @__PURE__ */ Object.freeze({
793
+ status: "ignored",
794
+ reason: "no-accepted-content"
795
+ });
796
+ function resolveResetDelay(value) {
797
+ if (value === void 0 || value === false || value === Infinity || Number.isNaN(value)) return null;
798
+ return Math.max(0, value);
799
+ }
800
+ function reportCallbackError(error) {
801
+ const scope = globalThis;
802
+ if (typeof scope.reportError === "function") scope.reportError(error);
803
+ else setTimeout(() => {
804
+ throw error;
805
+ }, 0);
806
+ }
807
+ /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
808
+ function invoke(fn, ...args) {
809
+ if (!fn) return;
810
+ try {
811
+ fn(...args);
812
+ } catch (error) {
813
+ reportCallbackError(error);
814
+ }
815
+ }
816
+ let defaultAdapter;
817
+ const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserPasteAdapter());
818
+ /** Framework-agnostic paste state machine. */
819
+ function createPasteMachine(options = {}) {
820
+ const read = typeof options === "function" ? options : () => options;
821
+ const listeners = /* @__PURE__ */ new Set();
822
+ let state = PASTE_IDLE_STATE;
823
+ let generation = 0;
824
+ let resetTimer;
825
+ const now = () => (read().now ?? Date.now)();
826
+ const setState = (next) => {
827
+ if (next === state) return;
828
+ state = next;
829
+ for (const listener of Array.from(listeners)) listener();
830
+ };
831
+ const clearResetTimer = () => {
832
+ if (resetTimer !== void 0) {
833
+ clearTimeout(resetTimer);
834
+ resetTimer = void 0;
835
+ }
836
+ };
837
+ const scheduleReset = (readState) => {
838
+ clearResetTimer();
839
+ const delay = resolveResetDelay(read().resetAfterMs);
840
+ if (delay === null) return;
841
+ const remaining = Math.max(0, delay - (now() - readState.at));
842
+ resetTimer = setTimeout(() => {
843
+ resetTimer = void 0;
844
+ setState(PASTE_IDLE_STATE);
845
+ }, remaining);
846
+ };
847
+ /** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */
848
+ const run = (produce) => {
849
+ clearResetTimer();
850
+ const current = ++generation;
851
+ setState(PASTE_READING_STATE);
852
+ let pending;
853
+ try {
854
+ pending = produce();
855
+ } catch (cause) {
856
+ pending = Promise.reject(cause);
857
+ }
858
+ return pending.then((result) => {
859
+ if (current === generation) {
860
+ const readState = {
861
+ status: "read",
862
+ result,
863
+ at: now()
864
+ };
865
+ setState(readState);
866
+ scheduleReset(readState);
867
+ invoke(read().onPaste, result);
868
+ }
869
+ return {
870
+ status: "read",
871
+ result
872
+ };
873
+ }, (cause) => {
874
+ const error = toCopyError(cause, "read");
875
+ if (current === generation) {
876
+ setState({
877
+ status: "error",
878
+ error
879
+ });
880
+ invoke(read().onError, error);
881
+ }
882
+ return {
883
+ status: "error",
884
+ error
885
+ };
886
+ });
887
+ };
888
+ const paste = () => {
889
+ if (state.status === "reading") return Promise.resolve(IGNORED_IN_FLIGHT);
890
+ return run(() => {
891
+ const resolved = resolvePasteReadOptions(read());
892
+ return (read().adapter ?? getDefaultAdapter()).read(resolved);
893
+ });
894
+ };
895
+ const pasteEvent = (event) => {
896
+ const data = event.clipboardData;
897
+ if (!data) return Promise.resolve(IGNORED_NO_CONTENT);
898
+ const current = read();
899
+ let resolved;
900
+ try {
901
+ resolved = resolvePasteReadOptions(current);
902
+ } catch (cause) {
903
+ const error = toCopyError(cause, "read");
904
+ ++generation;
905
+ clearResetTimer();
906
+ setState({
907
+ status: "error",
908
+ error
909
+ });
910
+ invoke(current.onError, error);
911
+ return Promise.resolve({
912
+ status: "error",
913
+ error
914
+ });
915
+ }
916
+ const entries = snapshotDataTransfer(data, resolved);
917
+ if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);
918
+ if (current.preventDefault !== false) event.preventDefault();
919
+ return run(() => {
920
+ enforcePasteLimits(entries, resolved);
921
+ return finalizePaste(entries, "event", resolved);
922
+ });
923
+ };
924
+ const reset = () => {
925
+ ++generation;
926
+ clearResetTimer();
927
+ setState(PASTE_IDLE_STATE);
928
+ };
929
+ const connect = () => {
930
+ if (state.status === "read") scheduleReset(state);
931
+ return () => {
932
+ ++generation;
933
+ clearResetTimer();
934
+ if (state.status === "reading") setState(PASTE_IDLE_STATE);
935
+ };
936
+ };
937
+ return {
938
+ getSnapshot: () => state,
939
+ subscribe: (listener) => {
940
+ listeners.add(listener);
941
+ return () => {
942
+ listeners.delete(listener);
943
+ };
944
+ },
945
+ paste,
946
+ pasteEvent,
947
+ reset,
948
+ connect
949
+ };
950
+ }
951
+ //#endregion
952
+ //#region src/react/CopyGroup.tsx
953
+ const CopyGroupContext = /* @__PURE__ */ createContext(null);
954
+ /**
955
+ * Every `useCopy` / `<CopyField.Root>` inside behaves like one clipboard:
956
+ * a new successful copy returns the previously "Copied" one to idle.
957
+ * Opt a single field out with `copyOptions={{ coordinator: null }}`. Groups nest; the nearest wins.
958
+ */
959
+ function CopyGroup({ children, coordinator }) {
960
+ const [owned] = useState(createCopyCoordinator);
961
+ return /* @__PURE__ */ jsx(CopyGroupContext.Provider, {
962
+ value: coordinator ?? owned,
963
+ children
964
+ });
965
+ }
966
+ /** The nearest `<CopyGroup>`'s coordinator, or `null` outside any group. */
967
+ function useCopyGroup() {
968
+ return useContext(CopyGroupContext);
969
+ }
970
+ //#endregion
412
971
  //#region src/react/utils.ts
413
972
  /** `useLayoutEffect` in the browser, `useEffect` on the server (no SSR warning). */
414
973
  const useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
@@ -427,19 +986,27 @@ function composeEventHandlers(theirs, ours) {
427
986
  }
428
987
  //#endregion
429
988
  //#region src/react/useCopy.ts
430
- const getServerSnapshot$1 = () => IDLE_STATE;
989
+ const getServerSnapshot$2 = () => IDLE_STATE;
990
+ /** An explicit `coordinator` (including `null`) wins over the surrounding `<CopyGroup>`. */
991
+ function withGroup(options, group) {
992
+ return options.coordinator !== void 0 || group === null ? options : {
993
+ ...options,
994
+ coordinator: group
995
+ };
996
+ }
431
997
  /**
432
998
  * Copy state machine bound to a component. Options may change on every render
433
999
  * (inline callbacks are fine); the latest ones are always used.
434
1000
  */
435
1001
  function useCopy(options = {}) {
436
- const optionsRef = useRef(options);
1002
+ const effective = withGroup(options, useCopyGroup());
1003
+ const optionsRef = useRef(effective);
437
1004
  useIsomorphicLayoutEffect(() => {
438
- optionsRef.current = options;
1005
+ optionsRef.current = effective;
439
1006
  });
440
1007
  const [machine] = useState(() => createCopyMachine(() => optionsRef.current));
441
1008
  useEffect(() => machine.connect(), [machine]);
442
- const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot$1);
1009
+ const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot$2);
443
1010
  const canRetry = canRetryState(state, options.maxRetries);
444
1011
  return useMemo(() => ({
445
1012
  state,
@@ -457,22 +1024,29 @@ function useCopy(options = {}) {
457
1024
  }
458
1025
  //#endregion
459
1026
  //#region src/react/useMediaQuery.ts
460
- const getServerSnapshot = () => false;
461
- function getMediaQueryList(query) {
462
- return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(query) : null;
463
- }
1027
+ const getServerSnapshot$1 = () => false;
464
1028
  /** SSR-safe media query subscription. Server and hydration render `false`. */
465
1029
  function useMediaQuery(query) {
1030
+ const listRef = useRef(null);
1031
+ const queryRef = useRef("");
1032
+ const getList = useCallback(() => {
1033
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return null;
1034
+ if (listRef.current === null || queryRef.current !== query) {
1035
+ listRef.current = window.matchMedia(query);
1036
+ queryRef.current = query;
1037
+ }
1038
+ return listRef.current;
1039
+ }, [query]);
466
1040
  const subscribe = useCallback((onChange) => {
467
- const list = getMediaQueryList(query);
1041
+ const list = getList();
468
1042
  if (!list) return () => void 0;
469
1043
  list.addEventListener("change", onChange);
470
1044
  return () => {
471
1045
  list.removeEventListener("change", onChange);
472
1046
  };
473
- }, [query]);
474
- const getSnapshot = useCallback(() => getMediaQueryList(query)?.matches ?? false, [query]);
475
- return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
1047
+ }, [getList]);
1048
+ const getSnapshot = useCallback(() => getList()?.matches ?? false, [getList]);
1049
+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot$1);
476
1050
  }
477
1051
  //#endregion
478
1052
  //#region src/react/useRevealOnInteraction.ts
@@ -557,7 +1131,9 @@ function useDisplayStatus(status, options = {}) {
557
1131
  const pendingDelayMs = Math.max(0, options.pendingDelayMs ?? 150);
558
1132
  const minPendingMs = Math.max(0, options.minPendingMs ?? 400);
559
1133
  const [settled, setSettled] = useState(status === "copying" ? "idle" : status);
560
- if (status !== "copying" && status !== settled) setSettled(status);
1134
+ useIsomorphicLayoutEffect(() => {
1135
+ if (status !== "copying") setSettled(status);
1136
+ }, [status]);
561
1137
  const [pendingShownAt, setPendingShownAt] = useState(null);
562
1138
  useEffect(() => {
563
1139
  if (status !== "copying") return void 0;
@@ -602,18 +1178,43 @@ const visuallyHiddenStyle = {
602
1178
  /**
603
1179
  * Always-mounted announcer. Screen readers ignore regions that are inserted
604
1180
  * together with their content, so this must render before the first message.
1181
+ *
1182
+ * **Mount safety**: the live region is intentionally empty on mount. We write
1183
+ * the message into the DOM imperatively (via a ref) only after the element has
1184
+ * been live for at least one browser paint. This prevents SSR hydration and
1185
+ * strict-mode double-mount from producing a spurious announcement on some
1186
+ * screen readers (JAWS / NVDA observe the initial DOM during hydration and
1187
+ * re-read regions that already have text content).
1188
+ *
1189
+ * **WCAG 4.1.3 / ARIA spec**: we use `role="status"` with explicit `aria-live`
1190
+ * rather than `role="alert"`. `role="alert"` interrupts any sentence being
1191
+ * spoken even in polite mode, which is inappropriate for copy feedback.
1192
+ * `role="status"` + `aria-live` is correct for both politeness levels.
605
1193
  */
606
1194
  function LiveRegion({ message, politeness = "polite", visuallyHidden = true, style, ...rest }) {
1195
+ const spanRef = useRef(null);
1196
+ const mountedRef = useRef(false);
1197
+ useEffect(() => {
1198
+ mountedRef.current = true;
1199
+ }, []);
1200
+ useEffect(() => {
1201
+ const span = spanRef.current;
1202
+ /* c8 ignore next -- spanRef.current is always set by mount; guard for unmounted edge case */
1203
+ if (!span) return;
1204
+ /* c8 ignore next -- jsdom effects run synchronously so mountedRef.current is always true here; this guard only fires in real browsers during the initial paint */
1205
+ if (!mountedRef.current) return;
1206
+ span.textContent = message;
1207
+ }, [message]);
607
1208
  return /* @__PURE__ */ jsx("span", {
608
1209
  ...rest,
609
- role: politeness === "assertive" ? "alert" : "status",
1210
+ ref: spanRef,
1211
+ role: "status",
610
1212
  "aria-live": politeness,
611
1213
  "aria-atomic": "true",
612
1214
  style: visuallyHidden ? {
613
1215
  ...visuallyHiddenStyle,
614
1216
  ...style
615
- } : style,
616
- children: message
1217
+ } : style
617
1218
  });
618
1219
  }
619
1220
  //#endregion
@@ -630,10 +1231,23 @@ function useCopyField() {
630
1231
  if (!context) throw new Error("useCopyField() must be used inside <CopyField.Root>.");
631
1232
  return context;
632
1233
  }
1234
+ /** Maps non-text payload kinds to a human-readable description for screen readers. */
1235
+ const KIND_LABELS = /* @__PURE__ */ Object.freeze({
1236
+ html: "Rich text",
1237
+ image: "Image",
1238
+ json: "JSON data",
1239
+ multi: "Mixed content"
1240
+ });
1241
+ /**
1242
+ * Returns the value's text representation when it is plain text, or a
1243
+ * descriptive fallback for non-text payloads so screen-reader users understand
1244
+ * what will be copied (A1: `CopyField.Value` must never be silent).
1245
+ */
633
1246
  function getDisplayValue(value) {
634
1247
  if (typeof value === "string") return value;
635
- if (typeof value === "object" && value.kind === "text") return value.value;
636
- return null;
1248
+ if (typeof value === "function") return null;
1249
+ if (value.kind === "text") return value.value;
1250
+ return KIND_LABELS[value.kind] ?? null;
637
1251
  }
638
1252
  const Root = /* @__PURE__ */ forwardRef(function CopyFieldRoot({ value, label, copyOptions, messages: messageOverrides, alwaysVisible = false, announce = true, pendingDelayMs, minPendingMs, children, onPointerEnter, onPointerLeave, onPointerDown, onFocus, onBlur, ...rest }, forwardedRef) {
639
1253
  const copyState = useCopy(copyOptions);
@@ -772,11 +1386,13 @@ const CopyField = {
772
1386
  revealed: field.revealed,
773
1387
  canRetry: field.canRetry
774
1388
  };
1389
+ const computedAriaLabel = ariaLabel ?? field.messages.triggerLabel(field.label);
1390
+ const safeAriaLabel = computedAriaLabel.length > 0 ? computedAriaLabel : `Copy ${field.label}`;
775
1391
  return /* @__PURE__ */ jsx("button", {
776
1392
  ...rest,
777
1393
  ref,
778
1394
  type: "button",
779
- "aria-label": ariaLabel ?? field.messages.triggerLabel(field.label),
1395
+ "aria-label": safeAriaLabel,
780
1396
  "data-state": field.status,
781
1397
  "data-display-state": field.displayStatus,
782
1398
  "data-revealed": field.revealed ? "" : void 0,
@@ -788,6 +1404,53 @@ const CopyField = {
788
1404
  })
789
1405
  };
790
1406
  //#endregion
791
- export { CopyFailure, CopyField, DEFAULT_MAX_RETRIES, DEFAULT_MIN_PENDING_MS, DEFAULT_PENDING_DELAY_MS, DEFAULT_RESET_AFTER_MS, IDLE_STATE, IMAGE_MIME_TYPE, LiveRegion, canRetryState, createBrowserClipboardAdapter, createCopyError, createCopyMachine, defaultCopyFieldMessages, describeCopyError, isBlob, isCopyFailure, isRetryableError, normalizePayload, resolveMaxRetries, serializeJson, toCopyError, useCopy, useCopyField, useDisplayStatus, useRevealOnInteraction, validatePayload, visuallyHiddenStyle };
1407
+ //#region src/react/usePaste.ts
1408
+ const getServerSnapshot = () => PASTE_IDLE_STATE;
1409
+ /**
1410
+ * Paste state machine bound to a component. Supports a "Paste" button
1411
+ * (`paste()`, may prompt for permission) and keyboard paste (`targetProps`
1412
+ * or `listenOnDocument`, no prompt). Options may change on every render.
1413
+ *
1414
+ * Everything in the result is untrusted user input.
1415
+ */
1416
+ function usePaste(options = {}) {
1417
+ const optionsRef = useRef(options);
1418
+ useIsomorphicLayoutEffect(() => {
1419
+ optionsRef.current = options;
1420
+ });
1421
+ const [machine] = useState(() => createPasteMachine(() => optionsRef.current));
1422
+ useEffect(() => machine.connect(), [machine]);
1423
+ const listenOnDocument = options.listenOnDocument === true;
1424
+ useEffect(() => {
1425
+ if (!listenOnDocument) return void 0;
1426
+ const onPaste = (event) => {
1427
+ if (!event.defaultPrevented) machine.pasteEvent(event);
1428
+ };
1429
+ document.addEventListener("paste", onPaste);
1430
+ return () => {
1431
+ document.removeEventListener("paste", onPaste);
1432
+ };
1433
+ }, [listenOnDocument, machine]);
1434
+ const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot);
1435
+ const targetProps = useMemo(() => ({ onPaste: (event) => {
1436
+ machine.pasteEvent(event);
1437
+ } }), [machine]);
1438
+ return useMemo(() => ({
1439
+ state,
1440
+ status: state.status,
1441
+ result: state.status === "read" ? state.result : null,
1442
+ error: state.status === "error" ? state.error : null,
1443
+ paste: machine.paste,
1444
+ pasteEvent: machine.pasteEvent,
1445
+ reset: machine.reset,
1446
+ targetProps
1447
+ }), [
1448
+ state,
1449
+ machine,
1450
+ targetProps
1451
+ ]);
1452
+ }
1453
+ //#endregion
1454
+ export { CopyFailure, CopyField, CopyGroup, DEFAULT_MAX_RETRIES, DEFAULT_MIN_PENDING_MS, DEFAULT_PASTE_ACCEPT, DEFAULT_PASTE_MAX_BYTES, DEFAULT_PASTE_MAX_ITEMS, DEFAULT_PENDING_DELAY_MS, DEFAULT_RESET_AFTER_MS, IDLE_STATE, IMAGE_MIME_TYPE, LiveRegion, PASTE_IDLE_STATE, SVG_MIME_TYPE, canRetryState, copyFailure, createBrowserClipboardAdapter, createBrowserPasteAdapter, createCopyCoordinator, createCopyError, createCopyMachine, createPasteMachine, defaultCopyFieldMessages, describeCopyError, describePasteError, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, matchesMimePattern, normalizeMimeType, normalizePayload, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, useCopy, useCopyField, useCopyGroup, useDisplayStatus, usePaste, useRevealOnInteraction, validatePayload, visuallyHiddenStyle };
792
1455
 
793
1456
  //# sourceMappingURL=index.js.map