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/core.cjs CHANGED
@@ -14,6 +14,7 @@ const RETRYABLE_ERRORS = /* @__PURE__ */ new Set([
14
14
  "permission-denied",
15
15
  "not-focused",
16
16
  "blob-generation-failed",
17
+ "timeout",
17
18
  "unknown"
18
19
  ]);
19
20
  /** Whether retrying the same payload could plausibly succeed. */
@@ -37,25 +38,35 @@ var CopyFailure = class extends Error {
37
38
  function isCopyFailure(value) {
38
39
  return typeof value === "object" && value !== null && value[COPY_FAILURE_BRAND] === true;
39
40
  }
41
+ /** Shorthand for throwing a classified failure. */
42
+ function copyFailure(type, message, cause) {
43
+ return new CopyFailure(createCopyError(type, message, cause));
44
+ }
40
45
  function readString(value, key) {
41
46
  if (typeof value !== "object" || value === null) return void 0;
42
47
  const field = value[key];
43
48
  return typeof field === "string" ? field : void 0;
44
49
  }
45
- /** Classifies anything thrown by the platform or an adapter into a {@link CopyError}. */
46
- function toCopyError(cause) {
50
+ /**
51
+ * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.
52
+ * `operation` only tailors the developer-facing message.
53
+ */
54
+ function toCopyError(cause, operation = "write") {
47
55
  if (isCopyFailure(cause)) return cause.copyError;
48
56
  const name = readString(cause, "name");
49
57
  const message = readString(cause, "message") ?? "";
58
+ const verb = operation === "read" ? "read" : "write";
50
59
  switch (name) {
51
- 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);
60
+ 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);
52
61
  case "SecurityError": return createCopyError("insecure-context", "The clipboard is blocked in this context.", cause);
53
62
  case "NotSupportedError":
54
63
  case "DataError": return createCopyError("unsupported-format", "The browser rejected this clipboard format.", cause);
55
- default: return createCopyError("unknown", message || "The copy failed for an unknown reason.", cause);
64
+ case "AbortError": return createCopyError("aborted", `The clipboard ${verb} was aborted.`, cause);
65
+ case "TimeoutError": return createCopyError("timeout", `The clipboard ${verb} timed out.`, cause);
66
+ default: return createCopyError("unknown", message || `The clipboard ${verb} failed for an unknown reason.`, cause);
56
67
  }
57
68
  }
58
- const DEFAULT_DESCRIPTIONS = {
69
+ const COPY_DESCRIPTIONS = {
59
70
  unsupported: "Copying isn't supported in this browser.",
60
71
  "insecure-context": "Copying requires a secure (HTTPS) connection.",
61
72
  "permission-denied": "Clipboard access was blocked. Allow it and try again.",
@@ -64,11 +75,34 @@ const DEFAULT_DESCRIPTIONS = {
64
75
  "unsupported-format": "This content can't be copied in this browser.",
65
76
  "blob-generation-failed": "The image couldn't be prepared for copying.",
66
77
  "max-retries-exceeded": "Copying failed after several attempts.",
78
+ "no-content": "There is nothing to copy.",
79
+ "too-large": "This content is too large to copy.",
80
+ timeout: "Copying took too long. Try again.",
81
+ aborted: "Copying was cancelled.",
67
82
  unknown: "Couldn't copy to the clipboard. Try again."
68
83
  };
69
- /** Default English, user-facing sentence for an error. Replace for i18n. */
84
+ const PASTE_DESCRIPTIONS = {
85
+ unsupported: "Pasting isn't supported in this browser.",
86
+ "insecure-context": "Pasting requires a secure (HTTPS) connection.",
87
+ "permission-denied": "Clipboard access was blocked. Allow it and try again.",
88
+ "not-focused": "The page lost focus while pasting. Try again.",
89
+ "invalid-payload": "The clipboard content couldn't be read.",
90
+ "unsupported-format": "This clipboard content isn't supported here.",
91
+ "blob-generation-failed": "The pasted image couldn't be read.",
92
+ "max-retries-exceeded": "Pasting failed after several attempts.",
93
+ "no-content": "The clipboard doesn't contain anything that can be pasted here.",
94
+ "too-large": "The clipboard content is too large to paste.",
95
+ timeout: "Pasting took too long. Try again.",
96
+ aborted: "Pasting was cancelled.",
97
+ unknown: "Couldn't read the clipboard. Try again."
98
+ };
99
+ /** Default English, user-facing sentence for a copy error. Replace for i18n. */
70
100
  function describeCopyError(error) {
71
- return DEFAULT_DESCRIPTIONS[error.type];
101
+ return COPY_DESCRIPTIONS[error.type];
102
+ }
103
+ /** Default English, user-facing sentence for a paste error. Replace for i18n. */
104
+ function describePasteError(error) {
105
+ return PASTE_DESCRIPTIONS[error.type];
72
106
  }
73
107
  //#endregion
74
108
  //#region src/core/payload.ts
@@ -137,10 +171,82 @@ function serializeJson(payload) {
137
171
  return text;
138
172
  }
139
173
  //#endregion
174
+ //#region src/core/mime.ts
175
+ /**
176
+ * MIME helpers shared by paste and capture. Everything that comes from the
177
+ * clipboard is untrusted input, so types are normalised and validated before
178
+ * they are compared, and image types are confirmed from the bytes themselves.
179
+ */
180
+ /** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */
181
+ const MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
182
+ /** SVG is XML that can carry scripts; it is never matched by a wildcard. */
183
+ const SVG_MIME_TYPE = "image/svg+xml";
184
+ /** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */
185
+ function normalizeMimeType(value) {
186
+ const separator = value.indexOf(";");
187
+ const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();
188
+ return MIME_SHAPE.test(base) ? base : null;
189
+ }
190
+ /**
191
+ * Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\/*`)?
192
+ * Wildcards never match `image/svg+xml`: accepting SVG must be explicit.
193
+ */
194
+ function matchesMimePattern(mimeType, pattern) {
195
+ if (pattern === mimeType) return true;
196
+ if (mimeType === "image/svg+xml") return false;
197
+ if (pattern === "*/*") return true;
198
+ return pattern.endsWith("/*") && mimeType.startsWith(pattern.slice(0, -1));
199
+ }
200
+ /** Types whose clipboard data is text and is therefore surfaced as a `string`. */
201
+ function isTextualMimeType(mimeType) {
202
+ return mimeType.startsWith("text/") || mimeType === "image/svg+xml" || mimeType === "application/json" || mimeType === "application/xml";
203
+ }
204
+ const SNIFF_BYTES = 16;
205
+ function startsWith(bytes, signature, offset = 0) {
206
+ return signature.every((byte, index) => bytes[offset + index] === byte);
207
+ }
208
+ const ascii = (text) => Array.from(text, (char) => char.charCodeAt(0));
209
+ const PNG = [
210
+ 137,
211
+ 80,
212
+ 78,
213
+ 71,
214
+ 13,
215
+ 10,
216
+ 26,
217
+ 10
218
+ ];
219
+ const JPEG = [
220
+ 255,
221
+ 216,
222
+ 255
223
+ ];
224
+ const GIF = ascii("GIF8");
225
+ const RIFF = ascii("RIFF");
226
+ const WEBP = ascii("WEBP");
227
+ const BMP = ascii("BM");
228
+ const FTYP_AVIF = ascii("ftypavif");
229
+ const FTYP_AVIS = ascii("ftypavis");
230
+ /** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */
231
+ function sniffImageBytes(bytes) {
232
+ if (startsWith(bytes, PNG)) return "image/png";
233
+ if (startsWith(bytes, JPEG)) return "image/jpeg";
234
+ if (startsWith(bytes, GIF)) return "image/gif";
235
+ if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return "image/webp";
236
+ if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return "image/avif";
237
+ if (startsWith(bytes, BMP)) return "image/bmp";
238
+ return null;
239
+ }
240
+ /** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */
241
+ async function sniffImageType(blob) {
242
+ const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();
243
+ return sniffImageBytes(new Uint8Array(head));
244
+ }
245
+ //#endregion
140
246
  //#region src/core/clipboard-adapter.ts
141
247
  const fail = (type, message, cause) => new CopyFailure(createCopyError(type, message, cause));
142
248
  const noop = () => void 0;
143
- function defaultEnvironment() {
249
+ function defaultEnvironment$1() {
144
250
  return typeof window === "undefined" ? void 0 : window;
145
251
  }
146
252
  function getRichClipboard(env, clipboard) {
@@ -178,6 +284,7 @@ async function writeImage(rich, source) {
178
284
  } catch (error) {
179
285
  throw await blob.then(noop, (inner) => inner) ?? error;
180
286
  }
287
+ await blob;
181
288
  }
182
289
  async function writeToClipboard(payload, env, degradeHtmlToText) {
183
290
  if (!env) throw fail("unsupported", "No browser environment: the clipboard only exists in the browser.");
@@ -217,16 +324,32 @@ async function writeToClipboard(payload, env, degradeHtmlToText) {
217
324
  }
218
325
  /** The default adapter: async Clipboard API with feature detection and honest errors. */
219
326
  function createBrowserClipboardAdapter(options = {}) {
220
- const getEnvironment = options.getEnvironment ?? defaultEnvironment;
327
+ const getEnvironment = options.getEnvironment ?? defaultEnvironment$1;
221
328
  const degradeHtmlToText = options.degradeHtmlToText ?? true;
222
329
  return { write: (payload) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText) };
223
330
  }
224
331
  //#endregion
332
+ //#region src/core/copy-coordinator.ts
333
+ function createCopyCoordinator() {
334
+ let active = null;
335
+ return {
336
+ activate: (member) => {
337
+ const previous = active;
338
+ active = member;
339
+ if (previous !== null && previous !== member) previous.release();
340
+ },
341
+ deactivate: (member) => {
342
+ if (active === member) active = null;
343
+ },
344
+ getActive: () => active
345
+ };
346
+ }
347
+ //#endregion
225
348
  //#region src/core/copy-machine.ts
226
349
  const DEFAULT_RESET_AFTER_MS = 2e3;
227
350
  const DEFAULT_MAX_RETRIES = 3;
228
351
  const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
229
- const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
352
+ const IGNORED_IN_FLIGHT$1 = /* @__PURE__ */ Object.freeze({
230
353
  status: "ignored",
231
354
  reason: "in-flight"
232
355
  });
@@ -243,7 +366,7 @@ function resolveMaxRetries(value) {
243
366
  if (value === void 0 || !Number.isFinite(value)) return 3;
244
367
  return Math.max(0, Math.floor(value));
245
368
  }
246
- function resolveResetDelay(value) {
369
+ function resolveResetDelay$1(value) {
247
370
  if (value === false || value === Infinity) return null;
248
371
  if (value === void 0 || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;
249
372
  return Math.max(0, value);
@@ -252,7 +375,7 @@ function resolveResetDelay(value) {
252
375
  function canRetryState(state, maxRetries) {
253
376
  return state.status === "error" && state.payload !== null && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
254
377
  }
255
- function reportCallbackError(error) {
378
+ function reportCallbackError$1(error) {
256
379
  const scope = globalThis;
257
380
  if (typeof scope.reportError === "function") scope.reportError(error);
258
381
  else setTimeout(() => {
@@ -260,16 +383,16 @@ function reportCallbackError(error) {
260
383
  }, 0);
261
384
  }
262
385
  /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
263
- function invoke(fn, ...args) {
386
+ function invoke$1(fn, ...args) {
264
387
  if (!fn) return;
265
388
  try {
266
389
  fn(...args);
267
390
  } catch (error) {
268
- reportCallbackError(error);
391
+ reportCallbackError$1(error);
269
392
  }
270
393
  }
271
- let defaultAdapter;
272
- const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserClipboardAdapter());
394
+ let defaultAdapter$1;
395
+ const getDefaultAdapter$1 = () => defaultAdapter$1 ?? (defaultAdapter$1 = createBrowserClipboardAdapter());
273
396
  /** Framework-agnostic copy state machine. */
274
397
  function createCopyMachine(options = {}) {
275
398
  const read = typeof options === "function" ? options : () => options;
@@ -278,11 +401,27 @@ function createCopyMachine(options = {}) {
278
401
  let generation = 0;
279
402
  let resetTimer;
280
403
  const now = () => (read().now ?? Date.now)();
404
+ let joined = null;
405
+ const member = { release: () => {
406
+ if (state.status === "copied") {
407
+ clearResetTimer();
408
+ setState(IDLE_STATE);
409
+ }
410
+ } };
281
411
  const setState = (next) => {
282
412
  if (next === state) return;
413
+ const previous = state;
283
414
  state = next;
415
+ if (previous.status === "copied" && next.status !== "copied" && joined) {
416
+ joined.deactivate(member);
417
+ joined = null;
418
+ }
284
419
  for (const listener of Array.from(listeners)) listener();
285
420
  };
421
+ const joinCoordinator = () => {
422
+ joined = read().coordinator ?? null;
423
+ joined?.activate(member);
424
+ };
286
425
  const clearResetTimer = () => {
287
426
  if (resetTimer !== void 0) {
288
427
  clearTimeout(resetTimer);
@@ -291,12 +430,12 @@ function createCopyMachine(options = {}) {
291
430
  };
292
431
  const scheduleReset = (copied) => {
293
432
  clearResetTimer();
294
- const delay = resolveResetDelay(read().resetAfterMs);
433
+ const delay = resolveResetDelay$1(read().resetAfterMs);
295
434
  if (delay === null) return;
296
435
  const remaining = Math.max(0, delay - (now() - copied.at));
297
436
  resetTimer = setTimeout(() => {
298
437
  resetTimer = void 0;
299
- if (state === copied) setState(IDLE_STATE);
438
+ setState(IDLE_STATE);
300
439
  }, remaining);
301
440
  };
302
441
  const settleError = (error, payload, retryCount) => {
@@ -306,7 +445,7 @@ function createCopyMachine(options = {}) {
306
445
  error,
307
446
  retryCount
308
447
  });
309
- invoke(read().onError, error, payload);
448
+ invoke$1(read().onError, error, payload);
310
449
  };
311
450
  const run = (source, retryCount) => {
312
451
  clearResetTimer();
@@ -337,7 +476,7 @@ function createCopyMachine(options = {}) {
337
476
  });
338
477
  let pending;
339
478
  try {
340
- pending = (read().adapter ?? getDefaultAdapter()).write(payload);
479
+ pending = (read().adapter ?? getDefaultAdapter$1()).write(payload);
341
480
  } catch (cause) {
342
481
  pending = Promise.reject(cause);
343
482
  }
@@ -349,8 +488,9 @@ function createCopyMachine(options = {}) {
349
488
  at: now()
350
489
  };
351
490
  setState(copied);
491
+ joinCoordinator();
352
492
  scheduleReset(copied);
353
- invoke(read().onCopy, payload);
493
+ invoke$1(read().onCopy, payload);
354
494
  }
355
495
  return {
356
496
  status: "copied",
@@ -365,7 +505,7 @@ function createCopyMachine(options = {}) {
365
505
  };
366
506
  });
367
507
  };
368
- const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT) : run(source, 0);
508
+ const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT$1) : run(source, 0);
369
509
  const retry = () => {
370
510
  if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
371
511
  if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
@@ -407,22 +547,419 @@ function createCopyMachine(options = {}) {
407
547
  };
408
548
  }
409
549
  //#endregion
550
+ //#region src/core/paste-reader.ts
551
+ const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
552
+ const DEFAULT_PASTE_MAX_BYTES = 33554432;
553
+ const DEFAULT_PASTE_MAX_ITEMS = 32;
554
+ const SHORTHANDS = /* @__PURE__ */ new Map([
555
+ ["text", "text/plain"],
556
+ ["html", "text/html"],
557
+ ["image", "image/*"],
558
+ ["any", "*/*"]
559
+ ]);
560
+ const TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
561
+ function resolvePattern(entry) {
562
+ if (typeof entry !== "string") return null;
563
+ const shorthand = SHORTHANDS.get(entry);
564
+ if (shorthand !== void 0) return shorthand;
565
+ if (entry === "*/*") return entry;
566
+ if (entry.endsWith("/*")) {
567
+ const type = entry.slice(0, -2).toLowerCase();
568
+ return TYPE_TOKEN.test(type) ? `${type}/*` : null;
569
+ }
570
+ return normalizeMimeType(entry);
571
+ }
572
+ function resolveLimit(value, fallback, name) {
573
+ if (value === void 0) return fallback;
574
+ if (value === Infinity || Number.isInteger(value) && value > 0) return value;
575
+ throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
576
+ }
577
+ /** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
578
+ function resolvePasteReadOptions(options = {}) {
579
+ const accept = [];
580
+ for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {
581
+ const pattern = resolvePattern(entry);
582
+ if (pattern === null) throw copyFailure("invalid-payload", `Invalid \`accept\` entry: ${JSON.stringify(entry)}.`);
583
+ if (!accept.includes(pattern)) accept.push(pattern);
584
+ }
585
+ if (accept.length === 0) throw copyFailure("invalid-payload", "`accept` must list at least one type.");
586
+ return {
587
+ accept,
588
+ maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, "maxBytes"),
589
+ maxItems: resolveLimit(options.maxItems, 32, "maxItems")
590
+ };
591
+ }
592
+ /** Whether a normalised MIME type is allowed by the resolved `accept` list. */
593
+ function isAccepted(mimeType, options) {
594
+ return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));
595
+ }
596
+ function createBudget(options) {
597
+ let bytes = 0;
598
+ let items = 0;
599
+ return { charge: (size) => {
600
+ items += 1;
601
+ bytes += size;
602
+ if (items > options.maxItems) throw copyFailure("too-large", `The paste has more than ${String(options.maxItems)} accepted items.`);
603
+ if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
604
+ } };
605
+ }
606
+ const sizeOf = (data) => typeof data === "string" ? data.length : data.size;
607
+ /** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
608
+ function enforcePasteLimits(entries, options) {
609
+ const budget = createBudget(options);
610
+ for (const entry of entries) budget.charge(sizeOf(entry.data));
611
+ }
612
+ /**
613
+ * Synchronously copies the accepted parts of a paste event's `DataTransfer`.
614
+ * It must run during the event: browsers empty the object afterwards.
615
+ */
616
+ function snapshotDataTransfer(data, options) {
617
+ const entries = [];
618
+ const seen = /* @__PURE__ */ new Set();
619
+ for (const raw of Array.from(data.types)) {
620
+ const type = normalizeMimeType(raw);
621
+ if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;
622
+ seen.add(type);
623
+ const text = data.getData(raw);
624
+ if (text.length > 0) entries.push({
625
+ type,
626
+ data: text,
627
+ file: false
628
+ });
629
+ }
630
+ for (const file of Array.from(data.files ?? [])) {
631
+ const type = normalizeMimeType(file.type) ?? "application/octet-stream";
632
+ if (isAccepted(type, options)) entries.push({
633
+ type,
634
+ data: file,
635
+ file: true
636
+ });
637
+ }
638
+ return entries;
639
+ }
640
+ /**
641
+ * Reads the accepted types from `navigator.clipboard.read()` items, enforcing
642
+ * the limits *before* decoding any text so an oversized paste is never buffered twice.
643
+ */
644
+ async function collectClipboardItems(items, options) {
645
+ const budget = createBudget(options);
646
+ const entries = [];
647
+ const seen = /* @__PURE__ */ new Set();
648
+ for (const item of items) for (const raw of item.types) {
649
+ const type = normalizeMimeType(raw);
650
+ if (type === null || seen.has(type) || !isAccepted(type, options)) continue;
651
+ seen.add(type);
652
+ let blob;
653
+ try {
654
+ blob = await item.getType(raw);
655
+ } catch {
656
+ continue;
657
+ }
658
+ if (blob.size === 0) continue;
659
+ budget.charge(blob.size);
660
+ entries.push({
661
+ type,
662
+ data: isTextualMimeType(type) ? await blob.text() : blob,
663
+ file: false
664
+ });
665
+ }
666
+ return entries;
667
+ }
668
+ function retype(entry, data, type) {
669
+ if (entry.file) {
670
+ const file = data;
671
+ return new File([file], file.name, {
672
+ type,
673
+ lastModified: file.lastModified
674
+ });
675
+ }
676
+ return data.slice(0, data.size, type);
677
+ }
678
+ /**
679
+ * Verifies image bytes, then builds the result. Blobs that claim to be images
680
+ * but aren't (or whose real format is not accepted) are dropped. Throws
681
+ * `no-content` when nothing survives.
682
+ */
683
+ async function finalizePaste(entries, source, options) {
684
+ const items = [];
685
+ const images = [];
686
+ const files = [];
687
+ let text = null;
688
+ let html = null;
689
+ for (const entry of entries) {
690
+ let { type, data } = entry;
691
+ if (typeof data === "string") {
692
+ if (type === "text/plain") text = data;
693
+ else if (type === "text/html") html = data;
694
+ } else if (type.startsWith("image/")) {
695
+ const actual = await sniffImageType(data);
696
+ if (actual === null || !isAccepted(actual, options)) continue;
697
+ if (actual !== type) {
698
+ data = retype(entry, data, actual);
699
+ type = actual;
700
+ }
701
+ images.push(data);
702
+ }
703
+ if (entry.file) files.push(data);
704
+ items.push({
705
+ type,
706
+ data
707
+ });
708
+ }
709
+ if (items.length === 0) throw copyFailure("no-content", "The clipboard holds nothing that matches `accept`.");
710
+ return {
711
+ source,
712
+ items,
713
+ text,
714
+ html,
715
+ images,
716
+ files
717
+ };
718
+ }
719
+ //#endregion
720
+ //#region src/core/paste-adapter.ts
721
+ function defaultEnvironment() {
722
+ return typeof window === "undefined" ? void 0 : window;
723
+ }
724
+ const canRead = (clipboard) => typeof clipboard.read === "function";
725
+ const canReadText = (clipboard) => typeof clipboard.readText === "function";
726
+ async function readPlainText(clipboard, options) {
727
+ let text;
728
+ try {
729
+ text = await clipboard.readText();
730
+ } catch (cause) {
731
+ throw new CopyFailure(toCopyError(cause, "read"));
732
+ }
733
+ const entries = text.length > 0 ? [{
734
+ type: "text/plain",
735
+ data: text,
736
+ file: false
737
+ }] : [];
738
+ enforcePasteLimits(entries, options);
739
+ return finalizePaste(entries, "clipboard", options);
740
+ }
741
+ async function readRich(clipboard, options) {
742
+ let items;
743
+ try {
744
+ items = await clipboard.read();
745
+ } catch (cause) {
746
+ throw new CopyFailure(toCopyError(cause, "read"));
747
+ }
748
+ return finalizePaste(await collectClipboardItems(items, options), "clipboard", options);
749
+ }
750
+ function readFromClipboard(env, options) {
751
+ if (!env) throw copyFailure("unsupported", "No browser environment: the clipboard only exists in the browser.");
752
+ if (env.isSecureContext === false) throw copyFailure("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
753
+ const clipboard = env.navigator?.clipboard;
754
+ if (!clipboard) throw copyFailure("unsupported", "navigator.clipboard is not available in this browser.");
755
+ const plainOnly = options.accept.every((pattern) => pattern === "text/plain");
756
+ const acceptsPlain = options.accept.some((pattern) => matchesMimePattern("text/plain", pattern));
757
+ if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options);
758
+ if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);
759
+ throw canReadText(clipboard) ? copyFailure("unsupported-format", "Reading non-text clipboard content requires navigator.clipboard.read().") : copyFailure("unsupported", "This browser cannot read the clipboard.");
760
+ }
761
+ /** The default paste adapter: async Clipboard API with feature detection and honest errors. */
762
+ function createBrowserPasteAdapter(options = {}) {
763
+ const getEnvironment = options.getEnvironment ?? defaultEnvironment;
764
+ return { read: (resolved) => {
765
+ try {
766
+ return readFromClipboard(getEnvironment(), resolved);
767
+ } catch (cause) {
768
+ return Promise.reject(cause);
769
+ }
770
+ } };
771
+ }
772
+ //#endregion
773
+ //#region src/core/paste-machine.ts
774
+ const PASTE_IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
775
+ const PASTE_READING_STATE = /* @__PURE__ */ Object.freeze({ status: "reading" });
776
+ const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
777
+ status: "ignored",
778
+ reason: "in-flight"
779
+ });
780
+ const IGNORED_NO_CONTENT = /* @__PURE__ */ Object.freeze({
781
+ status: "ignored",
782
+ reason: "no-accepted-content"
783
+ });
784
+ function resolveResetDelay(value) {
785
+ if (value === void 0 || value === false || value === Infinity || Number.isNaN(value)) return null;
786
+ return Math.max(0, value);
787
+ }
788
+ function reportCallbackError(error) {
789
+ const scope = globalThis;
790
+ if (typeof scope.reportError === "function") scope.reportError(error);
791
+ else setTimeout(() => {
792
+ throw error;
793
+ }, 0);
794
+ }
795
+ /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
796
+ function invoke(fn, ...args) {
797
+ if (!fn) return;
798
+ try {
799
+ fn(...args);
800
+ } catch (error) {
801
+ reportCallbackError(error);
802
+ }
803
+ }
804
+ let defaultAdapter;
805
+ const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserPasteAdapter());
806
+ /** Framework-agnostic paste state machine. */
807
+ function createPasteMachine(options = {}) {
808
+ const read = typeof options === "function" ? options : () => options;
809
+ const listeners = /* @__PURE__ */ new Set();
810
+ let state = PASTE_IDLE_STATE;
811
+ let generation = 0;
812
+ let resetTimer;
813
+ const now = () => (read().now ?? Date.now)();
814
+ const setState = (next) => {
815
+ if (next === state) return;
816
+ state = next;
817
+ for (const listener of Array.from(listeners)) listener();
818
+ };
819
+ const clearResetTimer = () => {
820
+ if (resetTimer !== void 0) {
821
+ clearTimeout(resetTimer);
822
+ resetTimer = void 0;
823
+ }
824
+ };
825
+ const scheduleReset = (readState) => {
826
+ clearResetTimer();
827
+ const delay = resolveResetDelay(read().resetAfterMs);
828
+ if (delay === null) return;
829
+ const remaining = Math.max(0, delay - (now() - readState.at));
830
+ resetTimer = setTimeout(() => {
831
+ resetTimer = void 0;
832
+ setState(PASTE_IDLE_STATE);
833
+ }, remaining);
834
+ };
835
+ /** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */
836
+ const run = (produce) => {
837
+ clearResetTimer();
838
+ const current = ++generation;
839
+ setState(PASTE_READING_STATE);
840
+ let pending;
841
+ try {
842
+ pending = produce();
843
+ } catch (cause) {
844
+ pending = Promise.reject(cause);
845
+ }
846
+ return pending.then((result) => {
847
+ if (current === generation) {
848
+ const readState = {
849
+ status: "read",
850
+ result,
851
+ at: now()
852
+ };
853
+ setState(readState);
854
+ scheduleReset(readState);
855
+ invoke(read().onPaste, result);
856
+ }
857
+ return {
858
+ status: "read",
859
+ result
860
+ };
861
+ }, (cause) => {
862
+ const error = toCopyError(cause, "read");
863
+ if (current === generation) {
864
+ setState({
865
+ status: "error",
866
+ error
867
+ });
868
+ invoke(read().onError, error);
869
+ }
870
+ return {
871
+ status: "error",
872
+ error
873
+ };
874
+ });
875
+ };
876
+ const paste = () => {
877
+ if (state.status === "reading") return Promise.resolve(IGNORED_IN_FLIGHT);
878
+ return run(() => {
879
+ const resolved = resolvePasteReadOptions(read());
880
+ return (read().adapter ?? getDefaultAdapter()).read(resolved);
881
+ });
882
+ };
883
+ const pasteEvent = (event) => {
884
+ const data = event.clipboardData;
885
+ if (!data) return Promise.resolve(IGNORED_NO_CONTENT);
886
+ const current = read();
887
+ let resolved;
888
+ try {
889
+ resolved = resolvePasteReadOptions(current);
890
+ } catch (cause) {
891
+ return run(() => {
892
+ throw cause;
893
+ });
894
+ }
895
+ const entries = snapshotDataTransfer(data, resolved);
896
+ if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);
897
+ if (current.preventDefault !== false) event.preventDefault();
898
+ return run(() => {
899
+ enforcePasteLimits(entries, resolved);
900
+ return finalizePaste(entries, "event", resolved);
901
+ });
902
+ };
903
+ const reset = () => {
904
+ ++generation;
905
+ clearResetTimer();
906
+ setState(PASTE_IDLE_STATE);
907
+ };
908
+ const connect = () => {
909
+ if (state.status === "read") scheduleReset(state);
910
+ return () => {
911
+ ++generation;
912
+ clearResetTimer();
913
+ if (state.status === "reading") setState(PASTE_IDLE_STATE);
914
+ };
915
+ };
916
+ return {
917
+ getSnapshot: () => state,
918
+ subscribe: (listener) => {
919
+ listeners.add(listener);
920
+ return () => {
921
+ listeners.delete(listener);
922
+ };
923
+ },
924
+ paste,
925
+ pasteEvent,
926
+ reset,
927
+ connect
928
+ };
929
+ }
930
+ //#endregion
410
931
  exports.CopyFailure = CopyFailure;
411
932
  exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES;
933
+ exports.DEFAULT_PASTE_ACCEPT = DEFAULT_PASTE_ACCEPT;
934
+ exports.DEFAULT_PASTE_MAX_BYTES = DEFAULT_PASTE_MAX_BYTES;
935
+ exports.DEFAULT_PASTE_MAX_ITEMS = DEFAULT_PASTE_MAX_ITEMS;
412
936
  exports.DEFAULT_RESET_AFTER_MS = DEFAULT_RESET_AFTER_MS;
413
937
  exports.IDLE_STATE = IDLE_STATE;
414
938
  exports.IMAGE_MIME_TYPE = IMAGE_MIME_TYPE;
939
+ exports.PASTE_IDLE_STATE = PASTE_IDLE_STATE;
940
+ exports.SVG_MIME_TYPE = SVG_MIME_TYPE;
415
941
  exports.canRetryState = canRetryState;
942
+ exports.copyFailure = copyFailure;
416
943
  exports.createBrowserClipboardAdapter = createBrowserClipboardAdapter;
944
+ exports.createBrowserPasteAdapter = createBrowserPasteAdapter;
945
+ exports.createCopyCoordinator = createCopyCoordinator;
417
946
  exports.createCopyError = createCopyError;
418
947
  exports.createCopyMachine = createCopyMachine;
948
+ exports.createPasteMachine = createPasteMachine;
419
949
  exports.describeCopyError = describeCopyError;
950
+ exports.describePasteError = describePasteError;
420
951
  exports.isBlob = isBlob;
421
952
  exports.isCopyFailure = isCopyFailure;
422
953
  exports.isRetryableError = isRetryableError;
954
+ exports.isTextualMimeType = isTextualMimeType;
955
+ exports.matchesMimePattern = matchesMimePattern;
956
+ exports.normalizeMimeType = normalizeMimeType;
423
957
  exports.normalizePayload = normalizePayload;
424
958
  exports.resolveMaxRetries = resolveMaxRetries;
959
+ exports.resolvePasteReadOptions = resolvePasteReadOptions;
425
960
  exports.serializeJson = serializeJson;
961
+ exports.sniffImageBytes = sniffImageBytes;
962
+ exports.sniffImageType = sniffImageType;
426
963
  exports.toCopyError = toCopyError;
427
964
  exports.validatePayload = validatePayload;
428
965