react-smart-copy 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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,7 +447,7 @@ 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();
@@ -339,7 +478,7 @@ function createCopyMachine(options = {}) {
339
478
  });
340
479
  let pending;
341
480
  try {
342
- pending = (read().adapter ?? getDefaultAdapter()).write(payload);
481
+ pending = (read().adapter ?? getDefaultAdapter$1()).write(payload);
343
482
  } catch (cause) {
344
483
  pending = Promise.reject(cause);
345
484
  }
@@ -351,8 +490,9 @@ function createCopyMachine(options = {}) {
351
490
  at: now()
352
491
  };
353
492
  setState(copied);
493
+ joinCoordinator();
354
494
  scheduleReset(copied);
355
- invoke(read().onCopy, payload);
495
+ invoke$1(read().onCopy, payload);
356
496
  }
357
497
  return {
358
498
  status: "copied",
@@ -367,7 +507,7 @@ function createCopyMachine(options = {}) {
367
507
  };
368
508
  });
369
509
  };
370
- const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT) : run(source, 0);
510
+ const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT$1) : run(source, 0);
371
511
  const retry = () => {
372
512
  if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
373
513
  if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
@@ -409,6 +549,406 @@ function createCopyMachine(options = {}) {
409
549
  };
410
550
  }
411
551
  //#endregion
552
+ //#region src/core/paste-reader.ts
553
+ const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
554
+ const DEFAULT_PASTE_MAX_BYTES = 33554432;
555
+ const DEFAULT_PASTE_MAX_ITEMS = 32;
556
+ const SHORTHANDS = /* @__PURE__ */ new Map([
557
+ ["text", "text/plain"],
558
+ ["html", "text/html"],
559
+ ["image", "image/*"],
560
+ ["any", "*/*"]
561
+ ]);
562
+ const TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
563
+ function resolvePattern(entry) {
564
+ if (typeof entry !== "string") return null;
565
+ const shorthand = SHORTHANDS.get(entry);
566
+ if (shorthand !== void 0) return shorthand;
567
+ if (entry === "*/*") return entry;
568
+ if (entry.endsWith("/*")) {
569
+ const type = entry.slice(0, -2).toLowerCase();
570
+ return TYPE_TOKEN.test(type) ? `${type}/*` : null;
571
+ }
572
+ return normalizeMimeType(entry);
573
+ }
574
+ function resolveLimit(value, fallback, name) {
575
+ if (value === void 0) return fallback;
576
+ if (value === Infinity || Number.isInteger(value) && value > 0) return value;
577
+ throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
578
+ }
579
+ /** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
580
+ function resolvePasteReadOptions(options = {}) {
581
+ const accept = [];
582
+ for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {
583
+ const pattern = resolvePattern(entry);
584
+ if (pattern === null) throw copyFailure("invalid-payload", `Invalid \`accept\` entry: ${JSON.stringify(entry)}.`);
585
+ if (!accept.includes(pattern)) accept.push(pattern);
586
+ }
587
+ if (accept.length === 0) throw copyFailure("invalid-payload", "`accept` must list at least one type.");
588
+ return {
589
+ accept,
590
+ maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, "maxBytes"),
591
+ maxItems: resolveLimit(options.maxItems, 32, "maxItems")
592
+ };
593
+ }
594
+ /** Whether a normalised MIME type is allowed by the resolved `accept` list. */
595
+ function isAccepted(mimeType, options) {
596
+ return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));
597
+ }
598
+ function createBudget(options) {
599
+ let bytes = 0;
600
+ let items = 0;
601
+ return { charge: (size) => {
602
+ items += 1;
603
+ bytes += size;
604
+ if (items > options.maxItems) throw copyFailure("too-large", `The paste has more than ${String(options.maxItems)} accepted items.`);
605
+ if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
606
+ } };
607
+ }
608
+ const sizeOf = (data) => typeof data === "string" ? data.length : data.size;
609
+ /** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
610
+ function enforcePasteLimits(entries, options) {
611
+ const budget = createBudget(options);
612
+ for (const entry of entries) budget.charge(sizeOf(entry.data));
613
+ }
614
+ /**
615
+ * Synchronously copies the accepted parts of a paste event's `DataTransfer`.
616
+ * It must run during the event: browsers empty the object afterwards.
617
+ */
618
+ function snapshotDataTransfer(data, options) {
619
+ const entries = [];
620
+ const seen = /* @__PURE__ */ new Set();
621
+ for (const raw of Array.from(data.types)) {
622
+ const type = normalizeMimeType(raw);
623
+ if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;
624
+ seen.add(type);
625
+ const text = data.getData(raw);
626
+ if (text.length > 0) entries.push({
627
+ type,
628
+ data: text,
629
+ file: false
630
+ });
631
+ }
632
+ for (const file of Array.from(data.files ?? [])) {
633
+ const type = normalizeMimeType(file.type) ?? "application/octet-stream";
634
+ if (isAccepted(type, options)) entries.push({
635
+ type,
636
+ data: file,
637
+ file: true
638
+ });
639
+ }
640
+ return entries;
641
+ }
642
+ /**
643
+ * Reads the accepted types from `navigator.clipboard.read()` items, enforcing
644
+ * the limits *before* decoding any text so an oversized paste is never buffered twice.
645
+ */
646
+ async function collectClipboardItems(items, options) {
647
+ const budget = createBudget(options);
648
+ const entries = [];
649
+ const seen = /* @__PURE__ */ new Set();
650
+ for (const item of items) for (const raw of item.types) {
651
+ const type = normalizeMimeType(raw);
652
+ if (type === null || seen.has(type) || !isAccepted(type, options)) continue;
653
+ seen.add(type);
654
+ let blob;
655
+ try {
656
+ blob = await item.getType(raw);
657
+ } catch {
658
+ continue;
659
+ }
660
+ if (blob.size === 0) continue;
661
+ budget.charge(blob.size);
662
+ entries.push({
663
+ type,
664
+ data: isTextualMimeType(type) ? await blob.text() : blob,
665
+ file: false
666
+ });
667
+ }
668
+ return entries;
669
+ }
670
+ function retype(entry, data, type) {
671
+ if (entry.file) {
672
+ const file = data;
673
+ return new File([file], file.name, {
674
+ type,
675
+ lastModified: file.lastModified
676
+ });
677
+ }
678
+ return data.slice(0, data.size, type);
679
+ }
680
+ /**
681
+ * Verifies image bytes, then builds the result. Blobs that claim to be images
682
+ * but aren't (or whose real format is not accepted) are dropped. Throws
683
+ * `no-content` when nothing survives.
684
+ */
685
+ async function finalizePaste(entries, source, options) {
686
+ const items = [];
687
+ const images = [];
688
+ const files = [];
689
+ let text = null;
690
+ let html = null;
691
+ for (const entry of entries) {
692
+ let { type, data } = entry;
693
+ if (typeof data === "string") {
694
+ if (type === "text/plain") text = data;
695
+ else if (type === "text/html") html = data;
696
+ } else if (type.startsWith("image/")) {
697
+ const actual = await sniffImageType(data);
698
+ if (actual === null || !isAccepted(actual, options)) continue;
699
+ if (actual !== type) {
700
+ data = retype(entry, data, actual);
701
+ type = actual;
702
+ }
703
+ images.push(data);
704
+ }
705
+ if (entry.file) files.push(data);
706
+ items.push({
707
+ type,
708
+ data
709
+ });
710
+ }
711
+ if (items.length === 0) throw copyFailure("no-content", "The clipboard holds nothing that matches `accept`.");
712
+ return {
713
+ source,
714
+ items,
715
+ text,
716
+ html,
717
+ images,
718
+ files
719
+ };
720
+ }
721
+ //#endregion
722
+ //#region src/core/paste-adapter.ts
723
+ function defaultEnvironment() {
724
+ return typeof window === "undefined" ? void 0 : window;
725
+ }
726
+ const canRead = (clipboard) => typeof clipboard.read === "function";
727
+ const canReadText = (clipboard) => typeof clipboard.readText === "function";
728
+ async function readPlainText(clipboard, options) {
729
+ let text;
730
+ try {
731
+ text = await clipboard.readText();
732
+ } catch (cause) {
733
+ throw new CopyFailure(toCopyError(cause, "read"));
734
+ }
735
+ const entries = text.length > 0 ? [{
736
+ type: "text/plain",
737
+ data: text,
738
+ file: false
739
+ }] : [];
740
+ enforcePasteLimits(entries, options);
741
+ return finalizePaste(entries, "clipboard", options);
742
+ }
743
+ async function readRich(clipboard, options) {
744
+ let items;
745
+ try {
746
+ items = await clipboard.read();
747
+ } catch (cause) {
748
+ throw new CopyFailure(toCopyError(cause, "read"));
749
+ }
750
+ return finalizePaste(await collectClipboardItems(items, options), "clipboard", options);
751
+ }
752
+ function readFromClipboard(env, options) {
753
+ if (!env) throw copyFailure("unsupported", "No browser environment: the clipboard only exists in the browser.");
754
+ if (env.isSecureContext === false) throw copyFailure("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
755
+ const clipboard = env.navigator?.clipboard;
756
+ if (!clipboard) throw copyFailure("unsupported", "navigator.clipboard is not available in this browser.");
757
+ const plainOnly = options.accept.every((pattern) => pattern === "text/plain");
758
+ const acceptsPlain = options.accept.some((pattern) => matchesMimePattern("text/plain", pattern));
759
+ if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options);
760
+ if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);
761
+ throw canReadText(clipboard) ? copyFailure("unsupported-format", "Reading non-text clipboard content requires navigator.clipboard.read().") : copyFailure("unsupported", "This browser cannot read the clipboard.");
762
+ }
763
+ /** The default paste adapter: async Clipboard API with feature detection and honest errors. */
764
+ function createBrowserPasteAdapter(options = {}) {
765
+ const getEnvironment = options.getEnvironment ?? defaultEnvironment;
766
+ return { read: (resolved) => {
767
+ try {
768
+ return readFromClipboard(getEnvironment(), resolved);
769
+ } catch (cause) {
770
+ return Promise.reject(cause);
771
+ }
772
+ } };
773
+ }
774
+ //#endregion
775
+ //#region src/core/paste-machine.ts
776
+ const PASTE_IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
777
+ const PASTE_READING_STATE = /* @__PURE__ */ Object.freeze({ status: "reading" });
778
+ const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
779
+ status: "ignored",
780
+ reason: "in-flight"
781
+ });
782
+ const IGNORED_NO_CONTENT = /* @__PURE__ */ Object.freeze({
783
+ status: "ignored",
784
+ reason: "no-accepted-content"
785
+ });
786
+ function resolveResetDelay(value) {
787
+ if (value === void 0 || value === false || value === Infinity || Number.isNaN(value)) return null;
788
+ return Math.max(0, value);
789
+ }
790
+ function reportCallbackError(error) {
791
+ const scope = globalThis;
792
+ if (typeof scope.reportError === "function") scope.reportError(error);
793
+ else setTimeout(() => {
794
+ throw error;
795
+ }, 0);
796
+ }
797
+ /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
798
+ function invoke(fn, ...args) {
799
+ if (!fn) return;
800
+ try {
801
+ fn(...args);
802
+ } catch (error) {
803
+ reportCallbackError(error);
804
+ }
805
+ }
806
+ let defaultAdapter;
807
+ const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserPasteAdapter());
808
+ /** Framework-agnostic paste state machine. */
809
+ function createPasteMachine(options = {}) {
810
+ const read = typeof options === "function" ? options : () => options;
811
+ const listeners = /* @__PURE__ */ new Set();
812
+ let state = PASTE_IDLE_STATE;
813
+ let generation = 0;
814
+ let resetTimer;
815
+ const now = () => (read().now ?? Date.now)();
816
+ const setState = (next) => {
817
+ if (next === state) return;
818
+ state = next;
819
+ for (const listener of Array.from(listeners)) listener();
820
+ };
821
+ const clearResetTimer = () => {
822
+ if (resetTimer !== void 0) {
823
+ clearTimeout(resetTimer);
824
+ resetTimer = void 0;
825
+ }
826
+ };
827
+ const scheduleReset = (readState) => {
828
+ clearResetTimer();
829
+ const delay = resolveResetDelay(read().resetAfterMs);
830
+ if (delay === null) return;
831
+ const remaining = Math.max(0, delay - (now() - readState.at));
832
+ resetTimer = setTimeout(() => {
833
+ resetTimer = void 0;
834
+ setState(PASTE_IDLE_STATE);
835
+ }, remaining);
836
+ };
837
+ /** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */
838
+ const run = (produce) => {
839
+ clearResetTimer();
840
+ const current = ++generation;
841
+ setState(PASTE_READING_STATE);
842
+ let pending;
843
+ try {
844
+ pending = produce();
845
+ } catch (cause) {
846
+ pending = Promise.reject(cause);
847
+ }
848
+ return pending.then((result) => {
849
+ if (current === generation) {
850
+ const readState = {
851
+ status: "read",
852
+ result,
853
+ at: now()
854
+ };
855
+ setState(readState);
856
+ scheduleReset(readState);
857
+ invoke(read().onPaste, result);
858
+ }
859
+ return {
860
+ status: "read",
861
+ result
862
+ };
863
+ }, (cause) => {
864
+ const error = toCopyError(cause, "read");
865
+ if (current === generation) {
866
+ setState({
867
+ status: "error",
868
+ error
869
+ });
870
+ invoke(read().onError, error);
871
+ }
872
+ return {
873
+ status: "error",
874
+ error
875
+ };
876
+ });
877
+ };
878
+ const paste = () => {
879
+ if (state.status === "reading") return Promise.resolve(IGNORED_IN_FLIGHT);
880
+ return run(() => {
881
+ const resolved = resolvePasteReadOptions(read());
882
+ return (read().adapter ?? getDefaultAdapter()).read(resolved);
883
+ });
884
+ };
885
+ const pasteEvent = (event) => {
886
+ const data = event.clipboardData;
887
+ if (!data) return Promise.resolve(IGNORED_NO_CONTENT);
888
+ const current = read();
889
+ let resolved;
890
+ try {
891
+ resolved = resolvePasteReadOptions(current);
892
+ } catch (cause) {
893
+ return run(() => {
894
+ throw cause;
895
+ });
896
+ }
897
+ const entries = snapshotDataTransfer(data, resolved);
898
+ if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);
899
+ if (current.preventDefault !== false) event.preventDefault();
900
+ return run(() => {
901
+ enforcePasteLimits(entries, resolved);
902
+ return finalizePaste(entries, "event", resolved);
903
+ });
904
+ };
905
+ const reset = () => {
906
+ ++generation;
907
+ clearResetTimer();
908
+ setState(PASTE_IDLE_STATE);
909
+ };
910
+ const connect = () => {
911
+ if (state.status === "read") scheduleReset(state);
912
+ return () => {
913
+ ++generation;
914
+ clearResetTimer();
915
+ if (state.status === "reading") setState(PASTE_IDLE_STATE);
916
+ };
917
+ };
918
+ return {
919
+ getSnapshot: () => state,
920
+ subscribe: (listener) => {
921
+ listeners.add(listener);
922
+ return () => {
923
+ listeners.delete(listener);
924
+ };
925
+ },
926
+ paste,
927
+ pasteEvent,
928
+ reset,
929
+ connect
930
+ };
931
+ }
932
+ //#endregion
933
+ //#region src/react/CopyGroup.tsx
934
+ const CopyGroupContext = /* @__PURE__ */ createContext(null);
935
+ /**
936
+ * Every `useCopy` / `<CopyField.Root>` inside behaves like one clipboard:
937
+ * a new successful copy returns the previously "Copied" one to idle.
938
+ * Opt a single field out with `copyOptions={{ coordinator: null }}`. Groups nest; the nearest wins.
939
+ */
940
+ function CopyGroup({ children, coordinator }) {
941
+ const [owned] = useState(createCopyCoordinator);
942
+ return /* @__PURE__ */ jsx(CopyGroupContext.Provider, {
943
+ value: coordinator ?? owned,
944
+ children
945
+ });
946
+ }
947
+ /** The nearest `<CopyGroup>`'s coordinator, or `null` outside any group. */
948
+ function useCopyGroup() {
949
+ return useContext(CopyGroupContext);
950
+ }
951
+ //#endregion
412
952
  //#region src/react/utils.ts
413
953
  /** `useLayoutEffect` in the browser, `useEffect` on the server (no SSR warning). */
414
954
  const useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
@@ -427,19 +967,27 @@ function composeEventHandlers(theirs, ours) {
427
967
  }
428
968
  //#endregion
429
969
  //#region src/react/useCopy.ts
430
- const getServerSnapshot$1 = () => IDLE_STATE;
970
+ const getServerSnapshot$2 = () => IDLE_STATE;
971
+ /** An explicit `coordinator` (including `null`) wins over the surrounding `<CopyGroup>`. */
972
+ function withGroup(options, group) {
973
+ return options.coordinator !== void 0 || group === null ? options : {
974
+ ...options,
975
+ coordinator: group
976
+ };
977
+ }
431
978
  /**
432
979
  * Copy state machine bound to a component. Options may change on every render
433
980
  * (inline callbacks are fine); the latest ones are always used.
434
981
  */
435
982
  function useCopy(options = {}) {
436
- const optionsRef = useRef(options);
983
+ const effective = withGroup(options, useCopyGroup());
984
+ const optionsRef = useRef(effective);
437
985
  useIsomorphicLayoutEffect(() => {
438
- optionsRef.current = options;
986
+ optionsRef.current = effective;
439
987
  });
440
988
  const [machine] = useState(() => createCopyMachine(() => optionsRef.current));
441
989
  useEffect(() => machine.connect(), [machine]);
442
- const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot$1);
990
+ const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot$2);
443
991
  const canRetry = canRetryState(state, options.maxRetries);
444
992
  return useMemo(() => ({
445
993
  state,
@@ -457,7 +1005,7 @@ function useCopy(options = {}) {
457
1005
  }
458
1006
  //#endregion
459
1007
  //#region src/react/useMediaQuery.ts
460
- const getServerSnapshot = () => false;
1008
+ const getServerSnapshot$1 = () => false;
461
1009
  function getMediaQueryList(query) {
462
1010
  return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(query) : null;
463
1011
  }
@@ -472,7 +1020,7 @@ function useMediaQuery(query) {
472
1020
  };
473
1021
  }, [query]);
474
1022
  const getSnapshot = useCallback(() => getMediaQueryList(query)?.matches ?? false, [query]);
475
- return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
1023
+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot$1);
476
1024
  }
477
1025
  //#endregion
478
1026
  //#region src/react/useRevealOnInteraction.ts
@@ -557,7 +1105,9 @@ function useDisplayStatus(status, options = {}) {
557
1105
  const pendingDelayMs = Math.max(0, options.pendingDelayMs ?? 150);
558
1106
  const minPendingMs = Math.max(0, options.minPendingMs ?? 400);
559
1107
  const [settled, setSettled] = useState(status === "copying" ? "idle" : status);
560
- if (status !== "copying" && status !== settled) setSettled(status);
1108
+ useIsomorphicLayoutEffect(() => {
1109
+ if (status !== "copying") setSettled(status);
1110
+ }, [status]);
561
1111
  const [pendingShownAt, setPendingShownAt] = useState(null);
562
1112
  useEffect(() => {
563
1113
  if (status !== "copying") return void 0;
@@ -788,6 +1338,53 @@ const CopyField = {
788
1338
  })
789
1339
  };
790
1340
  //#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 };
1341
+ //#region src/react/usePaste.ts
1342
+ const getServerSnapshot = () => PASTE_IDLE_STATE;
1343
+ /**
1344
+ * Paste state machine bound to a component. Supports a "Paste" button
1345
+ * (`paste()`, may prompt for permission) and keyboard paste (`targetProps`
1346
+ * or `listenOnDocument`, no prompt). Options may change on every render.
1347
+ *
1348
+ * Everything in the result is untrusted user input.
1349
+ */
1350
+ function usePaste(options = {}) {
1351
+ const optionsRef = useRef(options);
1352
+ useIsomorphicLayoutEffect(() => {
1353
+ optionsRef.current = options;
1354
+ });
1355
+ const [machine] = useState(() => createPasteMachine(() => optionsRef.current));
1356
+ useEffect(() => machine.connect(), [machine]);
1357
+ const listenOnDocument = options.listenOnDocument === true;
1358
+ useEffect(() => {
1359
+ if (!listenOnDocument) return void 0;
1360
+ const onPaste = (event) => {
1361
+ if (!event.defaultPrevented) machine.pasteEvent(event);
1362
+ };
1363
+ document.addEventListener("paste", onPaste);
1364
+ return () => {
1365
+ document.removeEventListener("paste", onPaste);
1366
+ };
1367
+ }, [listenOnDocument, machine]);
1368
+ const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot);
1369
+ const targetProps = useMemo(() => ({ onPaste: (event) => {
1370
+ machine.pasteEvent(event);
1371
+ } }), [machine]);
1372
+ return useMemo(() => ({
1373
+ state,
1374
+ status: state.status,
1375
+ result: state.status === "read" ? state.result : null,
1376
+ error: state.status === "error" ? state.error : null,
1377
+ paste: machine.paste,
1378
+ pasteEvent: machine.pasteEvent,
1379
+ reset: machine.reset,
1380
+ targetProps
1381
+ }), [
1382
+ state,
1383
+ machine,
1384
+ targetProps
1385
+ ]);
1386
+ }
1387
+ //#endregion
1388
+ 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
1389
 
793
1390
  //# sourceMappingURL=index.js.map