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