react-smart-copy 1.1.1 → 1.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.d.ts CHANGED
@@ -67,15 +67,34 @@ export declare function describeCopyError(error: CopyError): string;
67
67
  /** Default English, user-facing sentence for a paste error. Replace for i18n. */
68
68
  export declare function describePasteError(error: CopyError): string;
69
69
  //#endregion
70
+ //#region src/core/machine-shared.d.ts
71
+ /**
72
+ * Internals shared by the copy and paste state machines. Kept in one module so
73
+ * apps that use both don't ship two copies.
74
+ */
75
+ export declare const DEFAULT_MAX_RETRIES = 3;
76
+ /**
77
+ * Passed to adapters and lazy sources as their last argument. `signal` aborts
78
+ * when the operation is superseded, `reset()`, or its host unmounts, so
79
+ * expensive work (rasterising, decoding) can stop early.
80
+ */
81
+ interface OperationContext {
82
+ readonly signal: AbortSignal;
83
+ }
84
+ export declare function resolveMaxRetries(value: number | undefined): number;
85
+ //#endregion
70
86
  //#region src/core/payload.d.ts
71
87
  /** The only image MIME type with reliable cross-browser clipboard write support. */
72
88
  export declare const IMAGE_MIME_TYPE = "image/png";
73
89
  /**
74
90
  * An image as a Blob, a promise of one, or a function producing one.
75
91
  * Prefer the function form: it is invoked synchronously inside the user
76
- * gesture, which Safari requires for async image generation.
92
+ * gesture, which Safari requires for async image generation. The browser
93
+ * adapter always passes an `OperationContext`: stop work once
94
+ * `context.signal` aborts (reset, superseded, unmount). Optional in the type
95
+ * so adapters that call sources themselves keep compiling.
77
96
  */
78
- export type BlobSource = Blob | PromiseLike<Blob> | (() => Blob | PromiseLike<Blob>);
97
+ export type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);
79
98
  export interface TextPayload {
80
99
  readonly kind: 'text';
81
100
  readonly value: string;
@@ -171,10 +190,11 @@ export interface ClipboardEnvironment {
171
190
  *
172
191
  * Contract: start the platform write synchronously (before any `await`) so the
173
192
  * browser still sees the user gesture, and reject with a `CopyFailure` when you
174
- * can classify the error.
193
+ * can classify the error. `context.signal` aborts when the copy is reset or its
194
+ * host unmounts; honour it to stop expensive work early.
175
195
  */
176
196
  export interface ClipboardAdapter {
177
- write(payload: CopyPayload): Promise<void>;
197
+ write(payload: CopyPayload, context?: OperationContext): Promise<void>;
178
198
  }
179
199
  export interface BrowserClipboardAdapterOptions {
180
200
  /** Defaults to `window`, read lazily at copy time (SSR-safe). */
@@ -212,7 +232,6 @@ export declare function createCopyCoordinator(): CopyCoordinator;
212
232
  //#endregion
213
233
  //#region src/core/copy-machine.d.ts
214
234
  export declare const DEFAULT_RESET_AFTER_MS = 2000;
215
- export declare const DEFAULT_MAX_RETRIES = 3;
216
235
  export interface IdleState {
217
236
  readonly status: 'idle';
218
237
  }
@@ -236,7 +255,11 @@ export interface ErrorState {
236
255
  }
237
256
  export type CopyState = IdleState | CopyingState | CopiedState | ErrorState;
238
257
  export type CopyStatus = CopyState['status'];
239
- export type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable';
258
+ /**
259
+ * `cancelled`: the copy was reset or its host unmounted before it finished,
260
+ * so its work was aborted. Nothing to report to the user.
261
+ */
262
+ export type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';
240
263
  /** What `copy()`/`retry()` resolve to. They never reject. */
241
264
  export type CopyOutcome = {
242
265
  readonly status: 'copied';
@@ -275,16 +298,17 @@ export interface CopyMachine {
275
298
  readonly subscribe: (listener: () => void) => () => void;
276
299
  readonly copy: (source: CopySource) => Promise<CopyOutcome>;
277
300
  readonly retry: () => Promise<CopyOutcome>;
301
+ /** Back to `idle`. Discards any in-flight result and aborts its `signal`. */
278
302
  readonly reset: () => void;
279
303
  /**
280
304
  * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned
281
- * cleanup clears timers, drops in-flight results and unsticks `copying`.
305
+ * cleanup clears timers, drops in-flight results, aborts in-flight work and
306
+ * unsticks `copying`.
282
307
  * Safe to call repeatedly (React StrictMode).
283
308
  */
284
309
  readonly connect: () => () => void;
285
310
  }
286
311
  export declare const IDLE_STATE: IdleState;
287
- export declare function resolveMaxRetries(value: number | undefined): number;
288
312
  /** Pure helper: can `retry()` do anything from this state? */
289
313
  export declare function canRetryState(state: CopyState, maxRetries?: number): boolean;
290
314
  /** Framework-agnostic copy state machine. */
@@ -374,9 +398,11 @@ interface PasteEnvironment {
374
398
  *
375
399
  * Contract: call the platform API synchronously (before any `await`) so the
376
400
  * browser still sees the user gesture, and reject with a `CopyFailure`.
401
+ * `context.signal` aborts when the read is superseded, reset, or its host
402
+ * unmounts; honour it to stop decoding early.
377
403
  */
378
404
  interface PasteAdapter {
379
- read(options: ResolvedPasteReadOptions): Promise<PasteResult>;
405
+ read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteResult>;
380
406
  }
381
407
  interface BrowserPasteAdapterOptions {
382
408
  /** Defaults to `window`, read lazily at paste time (SSR-safe). */
@@ -401,11 +427,19 @@ export interface PasteReadState {
401
427
  export interface PasteErrorState {
402
428
  readonly status: 'error';
403
429
  readonly error: CopyError;
430
+ /** Where the failed read came from. Only `'clipboard'` reads can be retried. */
431
+ readonly source: PasteSource;
432
+ /** `retry()` calls made since the last fresh `paste()`. */
433
+ readonly retryCount: number;
404
434
  }
405
435
  export type PasteState = PasteIdleState | PasteReadingState | PasteReadState | PasteErrorState;
406
436
  export type PasteStatus = PasteState['status'];
407
- export type PasteIgnoredReason = 'in-flight' | 'no-accepted-content';
408
- /** What `paste()` / `pasteEvent()` resolve to. They never reject. */
437
+ /**
438
+ * `cancelled`: the read was superseded, reset, or its host unmounted before it
439
+ * finished, so its work was aborted. Nothing to report to the user.
440
+ */
441
+ export type PasteIgnoredReason = 'in-flight' | 'no-accepted-content' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';
442
+ /** What `paste()` / `pasteEvent()` / `retry()` resolve to. They never reject. */
409
443
  export type PasteOutcome = {
410
444
  readonly status: 'read';
411
445
  readonly result: PasteResult;
@@ -431,6 +465,11 @@ export interface PasteMachineOptions extends PasteReadOptions {
431
465
  * accepted content, so the browser doesn't also insert it. Default `true`.
432
466
  */
433
467
  readonly preventDefault?: boolean;
468
+ /**
469
+ * Max `retry()` calls after a failed clipboard read. Default 3. `0`
470
+ * disables retry; `Infinity` allows unlimited retries.
471
+ */
472
+ readonly maxRetries?: number;
434
473
  readonly onPaste?: (result: PasteResult) => void;
435
474
  readonly onError?: (error: CopyError) => void;
436
475
  /** Clock injection for tests and deterministic environments. */
@@ -452,18 +491,27 @@ export interface PasteMachine {
452
491
  * accepted content are ignored and left untouched for the browser.
453
492
  */
454
493
  readonly pasteEvent: (event: PasteEventLike) => Promise<PasteOutcome>;
455
- /** Back to `idle`, discarding any in-flight result. */
494
+ /**
495
+ * Re-reads the clipboard after a retryable failure (e.g. permission denied,
496
+ * page not focused), up to `maxRetries`. Call it from a user gesture.
497
+ * Paste-event failures can't be retried: their data is gone after dispatch.
498
+ */
499
+ readonly retry: () => Promise<PasteOutcome>;
500
+ /** Back to `idle`. Discards any in-flight result and aborts its `signal`. */
456
501
  readonly reset: () => void;
457
502
  /**
458
503
  * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned
459
- * cleanup clears timers, drops in-flight results and unsticks `reading`.
504
+ * cleanup clears timers, drops in-flight results, aborts in-flight work and
505
+ * unsticks `reading`.
460
506
  * Safe to call repeatedly (React StrictMode).
461
507
  */
462
508
  readonly connect: () => () => void;
463
509
  }
464
510
  export declare const PASTE_IDLE_STATE: PasteIdleState;
511
+ /** Pure helper: can `retry()` do anything from this state? */
512
+ export declare function canRetryPasteState(state: PasteState, maxRetries?: number): boolean;
465
513
  /** Framework-agnostic paste state machine. */
466
514
  export declare function createPasteMachine(options?: PasteMachineOptionsSource): PasteMachine;
467
515
  //#endregion
468
- export type { BrowserPasteAdapterOptions, ClipboardItemLike, DataTransferLike, PasteAccept, PasteAcceptShorthand, PasteAdapter, PasteClipboardLike, PasteEnvironment, PasteItem, PasteLimits, PasteReadOptions, PasteResult, PasteSource, ResolvedPasteReadOptions };
516
+ export type { BrowserPasteAdapterOptions, ClipboardItemLike, DataTransferLike, OperationContext, PasteAccept, PasteAcceptShorthand, PasteAdapter, PasteClipboardLike, PasteEnvironment, PasteItem, PasteLimits, PasteReadOptions, PasteResult, PasteSource, ResolvedPasteReadOptions };
469
517
  //# sourceMappingURL=core.d.ts.map
package/dist/core.js CHANGED
@@ -263,20 +263,21 @@ function writeText(clipboard, text) {
263
263
  if (typeof clipboard.writeText !== "function") throw fail("unsupported", "navigator.clipboard.writeText() is not available.");
264
264
  return clipboard.writeText(text);
265
265
  }
266
- async function resolveImageBlob(source) {
266
+ async function resolveImageBlob(source, context) {
267
267
  let blob;
268
268
  try {
269
- blob = await (typeof source === "function" ? source() : source);
269
+ blob = await (typeof source === "function" ? source(context ?? { signal: new AbortController().signal }) : source);
270
270
  } catch (cause) {
271
+ if (context?.signal.aborted) throw fail("aborted", "The image copy was cancelled.", cause);
271
272
  throw fail("blob-generation-failed", "The image source threw or rejected while producing a Blob.", cause);
272
273
  }
273
274
  if (!isBlob(blob)) throw fail("blob-generation-failed", "The image source did not produce a Blob.");
274
275
  if (blob.type !== "image/png") throw fail("unsupported-format", `Only ${IMAGE_MIME_TYPE} can be written to the clipboard (received "${blob.type || "unknown"}"). Convert with canvas.toBlob(cb, "${IMAGE_MIME_TYPE}").`);
275
276
  return blob;
276
277
  }
277
- async function writeImage(rich, source) {
278
+ async function writeImage(rich, source, context) {
278
279
  if (!isTypeSupported(rich.Item, "image/png")) throw fail("unsupported-format", `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);
279
- const blob = resolveImageBlob(source);
280
+ const blob = resolveImageBlob(source, context);
280
281
  blob.catch(noop);
281
282
  try {
282
283
  await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);
@@ -285,7 +286,7 @@ async function writeImage(rich, source) {
285
286
  }
286
287
  await blob;
287
288
  }
288
- async function writeToClipboard(payload, env, degradeHtmlToText) {
289
+ async function writeToClipboard(payload, env, degradeHtmlToText, context) {
289
290
  if (!env) throw fail("unsupported", "No browser environment: the clipboard only exists in the browser.");
290
291
  if (env.isSecureContext === false) throw fail("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
291
292
  const clipboard = env.navigator?.clipboard;
@@ -307,7 +308,7 @@ async function writeToClipboard(payload, env, degradeHtmlToText) {
307
308
  case "image": {
308
309
  const rich = getRichClipboard(env, clipboard);
309
310
  if (!rich) throw fail("unsupported-format", "Image copy requires ClipboardItem and navigator.clipboard.write().");
310
- return writeImage(rich, payload.blob);
311
+ return writeImage(rich, payload.blob, context);
311
312
  }
312
313
  case "multi": {
313
314
  const rich = getRichClipboard(env, clipboard);
@@ -325,7 +326,7 @@ async function writeToClipboard(payload, env, degradeHtmlToText) {
325
326
  function createBrowserClipboardAdapter(options = {}) {
326
327
  const getEnvironment = options.getEnvironment ?? defaultEnvironment$1;
327
328
  const degradeHtmlToText = options.degradeHtmlToText ?? true;
328
- return { write: (payload) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText) };
329
+ return { write: (payload, context) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText, context) };
329
330
  }
330
331
  //#endregion
331
332
  //#region src/core/copy-coordinator.ts
@@ -344,27 +345,72 @@ function createCopyCoordinator() {
344
345
  };
345
346
  }
346
347
  //#endregion
348
+ //#region src/core/machine-shared.ts
349
+ /**
350
+ * Internals shared by the copy and paste state machines. Kept in one module so
351
+ * apps that use both don't ship two copies.
352
+ */
353
+ const DEFAULT_MAX_RETRIES = 3;
354
+ function resolveMaxRetries(value) {
355
+ if (value === Infinity) return Infinity;
356
+ if (value === void 0 || !Number.isFinite(value)) return 3;
357
+ return Math.max(0, Math.floor(value));
358
+ }
359
+ function reportCallbackError(error) {
360
+ const scope = globalThis;
361
+ if (typeof scope.reportError === "function") scope.reportError(error);
362
+ else setTimeout(() => {
363
+ throw error;
364
+ }, 0);
365
+ }
366
+ /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
367
+ function invoke(fn, ...args) {
368
+ if (!fn) return;
369
+ try {
370
+ fn(...args);
371
+ } catch (error) {
372
+ reportCallbackError(error);
373
+ }
374
+ }
375
+ /** One cancellable operation at a time. Signals only fire while their operation is unfinished. */
376
+ function createOperations() {
377
+ let controller;
378
+ const abort = () => {
379
+ controller?.abort();
380
+ controller = void 0;
381
+ };
382
+ return {
383
+ start: () => {
384
+ abort();
385
+ controller = new AbortController();
386
+ return { signal: controller.signal };
387
+ },
388
+ end: (context) => {
389
+ if (controller?.signal === context.signal) controller = void 0;
390
+ },
391
+ abort
392
+ };
393
+ }
394
+ //#endregion
347
395
  //#region src/core/copy-machine.ts
348
396
  const DEFAULT_RESET_AFTER_MS = 2e3;
349
- const DEFAULT_MAX_RETRIES = 3;
350
397
  const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
351
398
  const IGNORED_IN_FLIGHT$1 = /* @__PURE__ */ Object.freeze({
352
399
  status: "ignored",
353
400
  reason: "in-flight"
354
401
  });
355
- const IGNORED_NOTHING = /* @__PURE__ */ Object.freeze({
402
+ const IGNORED_NOTHING$1 = /* @__PURE__ */ Object.freeze({
356
403
  status: "ignored",
357
404
  reason: "nothing-to-retry"
358
405
  });
359
- const IGNORED_NOT_RETRYABLE = /* @__PURE__ */ Object.freeze({
406
+ const IGNORED_NOT_RETRYABLE$1 = /* @__PURE__ */ Object.freeze({
360
407
  status: "ignored",
361
408
  reason: "not-retryable"
362
409
  });
363
- function resolveMaxRetries(value) {
364
- if (value === Infinity) return Infinity;
365
- if (value === void 0 || !Number.isFinite(value)) return 3;
366
- return Math.max(0, Math.floor(value));
367
- }
410
+ const IGNORED_CANCELLED$1 = /* @__PURE__ */ Object.freeze({
411
+ status: "ignored",
412
+ reason: "cancelled"
413
+ });
368
414
  function resolveResetDelay$1(value) {
369
415
  if (value === false || value === Infinity) return null;
370
416
  if (value === void 0 || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;
@@ -374,22 +420,6 @@ function resolveResetDelay$1(value) {
374
420
  function canRetryState(state, maxRetries) {
375
421
  return state.status === "error" && state.payload !== null && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
376
422
  }
377
- function reportCallbackError$1(error) {
378
- const scope = globalThis;
379
- if (typeof scope.reportError === "function") scope.reportError(error);
380
- else setTimeout(() => {
381
- throw error;
382
- }, 0);
383
- }
384
- /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
385
- function invoke$1(fn, ...args) {
386
- if (!fn) return;
387
- try {
388
- fn(...args);
389
- } catch (error) {
390
- reportCallbackError$1(error);
391
- }
392
- }
393
423
  let defaultAdapter$1;
394
424
  const getDefaultAdapter$1 = () => defaultAdapter$1 ?? (defaultAdapter$1 = createBrowserClipboardAdapter());
395
425
  /** Framework-agnostic copy state machine. */
@@ -399,6 +429,7 @@ function createCopyMachine(options = {}) {
399
429
  let state = IDLE_STATE;
400
430
  let generation = 0;
401
431
  let resetTimer;
432
+ const operations = createOperations();
402
433
  const now = () => (read().now ?? Date.now)();
403
434
  let joined = null;
404
435
  const member = { release: () => {
@@ -444,7 +475,7 @@ function createCopyMachine(options = {}) {
444
475
  error,
445
476
  retryCount
446
477
  });
447
- invoke$1(read().onError, error, payload);
478
+ invoke(read().onError, error, payload);
448
479
  };
449
480
  const run = (source, retryCount) => {
450
481
  clearResetTimer();
@@ -483,13 +514,15 @@ function createCopyMachine(options = {}) {
483
514
  payload,
484
515
  retryCount
485
516
  });
517
+ const context = operations.start();
486
518
  let pending;
487
519
  try {
488
- pending = (read().adapter ?? getDefaultAdapter$1()).write(payload);
520
+ pending = (read().adapter ?? getDefaultAdapter$1()).write(payload, context);
489
521
  } catch (cause) {
490
522
  pending = Promise.reject(cause);
491
523
  }
492
524
  return pending.then(() => {
525
+ operations.end(context);
493
526
  if (current === generation) {
494
527
  const copied = {
495
528
  status: "copied",
@@ -499,15 +532,17 @@ function createCopyMachine(options = {}) {
499
532
  setState(copied);
500
533
  joinCoordinator();
501
534
  scheduleReset(copied);
502
- invoke$1(read().onCopy, payload);
535
+ invoke(read().onCopy, payload);
503
536
  }
504
537
  return {
505
538
  status: "copied",
506
539
  payload
507
540
  };
508
541
  }, (cause) => {
542
+ operations.end(context);
543
+ if (context.signal.aborted) return IGNORED_CANCELLED$1;
509
544
  const error = toCopyError(cause);
510
- if (current === generation) settleError(error, payload, retryCount);
545
+ settleError(error, payload, retryCount);
511
546
  return {
512
547
  status: "error",
513
548
  error
@@ -516,8 +551,8 @@ function createCopyMachine(options = {}) {
516
551
  };
517
552
  const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT$1) : run(source, 0);
518
553
  const retry = () => {
519
- if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
520
- if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
554
+ if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING$1);
555
+ if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE$1);
521
556
  if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
522
557
  const error = createCopyError("max-retries-exceeded", `Copy failed after ${String(state.retryCount)} retries.`, state.error);
523
558
  settleError(error, state.payload, state.retryCount);
@@ -530,6 +565,7 @@ function createCopyMachine(options = {}) {
530
565
  };
531
566
  const reset = () => {
532
567
  ++generation;
568
+ operations.abort();
533
569
  clearResetTimer();
534
570
  setState(IDLE_STATE);
535
571
  };
@@ -537,6 +573,7 @@ function createCopyMachine(options = {}) {
537
573
  if (state.status === "copied") scheduleReset(state);
538
574
  return () => {
539
575
  ++generation;
576
+ operations.abort();
540
577
  clearResetTimer();
541
578
  if (state.status === "copying") setState(IDLE_STATE);
542
579
  };
@@ -650,7 +687,7 @@ function snapshotDataTransfer(data, options) {
650
687
  * Reads the accepted types from `navigator.clipboard.read()` items, enforcing
651
688
  * the limits *before* decoding any text so an oversized paste is never buffered twice.
652
689
  */
653
- async function collectClipboardItems(items, options) {
690
+ async function collectClipboardItems(items, options, signal) {
654
691
  const budget = createBudget(options);
655
692
  const entries = [];
656
693
  const seen = /* @__PURE__ */ new Set();
@@ -664,6 +701,7 @@ async function collectClipboardItems(items, options) {
664
701
  } catch {
665
702
  continue;
666
703
  }
704
+ if (signal?.aborted) throw copyFailure("aborted", "The paste was cancelled.");
667
705
  if (blob.size === 0) continue;
668
706
  budget.charge(blob.size);
669
707
  entries.push({
@@ -747,32 +785,32 @@ async function readPlainText(clipboard, options) {
747
785
  enforcePasteLimits(entries, options);
748
786
  return finalizePaste(entries, "clipboard", options);
749
787
  }
750
- async function readRich(clipboard, options) {
788
+ async function readRich(clipboard, options, signal) {
751
789
  let items;
752
790
  try {
753
791
  items = await clipboard.read();
754
792
  } catch (cause) {
755
793
  throw new CopyFailure(toCopyError(cause, "read"));
756
794
  }
757
- return finalizePaste(await collectClipboardItems(items, options), "clipboard", options);
795
+ return finalizePaste(await collectClipboardItems(items, options, signal), "clipboard", options);
758
796
  }
759
- function readFromClipboard(env, options) {
797
+ function readFromClipboard(env, options, signal) {
760
798
  if (!env) throw copyFailure("unsupported", "No browser environment: the clipboard only exists in the browser.");
761
799
  if (env.isSecureContext === false) throw copyFailure("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
762
800
  const clipboard = env.navigator?.clipboard;
763
801
  if (!clipboard) throw copyFailure("unsupported", "navigator.clipboard is not available in this browser.");
764
802
  const plainOnly = options.accept.every((pattern) => pattern === "text/plain");
765
803
  const acceptsPlain = options.accept.some((pattern) => matchesMimePattern("text/plain", pattern));
766
- if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options);
804
+ if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options, signal);
767
805
  if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);
768
806
  throw canReadText(clipboard) ? copyFailure("unsupported-format", "Reading non-text clipboard content requires navigator.clipboard.read().") : copyFailure("unsupported", "This browser cannot read the clipboard.");
769
807
  }
770
808
  /** The default paste adapter: async Clipboard API with feature detection and honest errors. */
771
809
  function createBrowserPasteAdapter(options = {}) {
772
810
  const getEnvironment = options.getEnvironment ?? defaultEnvironment;
773
- return { read: (resolved) => {
811
+ return { read: (resolved, context) => {
774
812
  try {
775
- return readFromClipboard(getEnvironment(), resolved);
813
+ return readFromClipboard(getEnvironment(), resolved, context?.signal);
776
814
  } catch (cause) {
777
815
  return Promise.reject(cause);
778
816
  }
@@ -790,25 +828,25 @@ const IGNORED_NO_CONTENT = /* @__PURE__ */ Object.freeze({
790
828
  status: "ignored",
791
829
  reason: "no-accepted-content"
792
830
  });
831
+ const IGNORED_NOTHING = /* @__PURE__ */ Object.freeze({
832
+ status: "ignored",
833
+ reason: "nothing-to-retry"
834
+ });
835
+ const IGNORED_NOT_RETRYABLE = /* @__PURE__ */ Object.freeze({
836
+ status: "ignored",
837
+ reason: "not-retryable"
838
+ });
839
+ const IGNORED_CANCELLED = /* @__PURE__ */ Object.freeze({
840
+ status: "ignored",
841
+ reason: "cancelled"
842
+ });
793
843
  function resolveResetDelay(value) {
794
844
  if (value === void 0 || value === false || value === Infinity || Number.isNaN(value)) return null;
795
845
  return Math.max(0, value);
796
846
  }
797
- function reportCallbackError(error) {
798
- const scope = globalThis;
799
- if (typeof scope.reportError === "function") scope.reportError(error);
800
- else setTimeout(() => {
801
- throw error;
802
- }, 0);
803
- }
804
- /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
805
- function invoke(fn, ...args) {
806
- if (!fn) return;
807
- try {
808
- fn(...args);
809
- } catch (error) {
810
- reportCallbackError(error);
811
- }
847
+ /** Pure helper: can `retry()` do anything from this state? */
848
+ function canRetryPasteState(state, maxRetries) {
849
+ return state.status === "error" && state.source === "clipboard" && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
812
850
  }
813
851
  let defaultAdapter;
814
852
  const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserPasteAdapter());
@@ -819,6 +857,7 @@ function createPasteMachine(options = {}) {
819
857
  let state = PASTE_IDLE_STATE;
820
858
  let generation = 0;
821
859
  let resetTimer;
860
+ const operations = createOperations();
822
861
  const now = () => (read().now ?? Date.now)();
823
862
  const setState = (next) => {
824
863
  if (next === state) return;
@@ -841,18 +880,29 @@ function createPasteMachine(options = {}) {
841
880
  setState(PASTE_IDLE_STATE);
842
881
  }, remaining);
843
882
  };
883
+ const settleError = (error, source, retryCount) => {
884
+ setState({
885
+ status: "error",
886
+ error,
887
+ source,
888
+ retryCount
889
+ });
890
+ invoke(read().onError, error);
891
+ };
844
892
  /** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */
845
- const run = (produce) => {
893
+ const run = (produce, source, retryCount) => {
846
894
  clearResetTimer();
847
895
  const current = ++generation;
896
+ const context = operations.start();
848
897
  setState(PASTE_READING_STATE);
849
898
  let pending;
850
899
  try {
851
- pending = produce();
900
+ pending = produce(context);
852
901
  } catch (cause) {
853
902
  pending = Promise.reject(cause);
854
903
  }
855
904
  return pending.then((result) => {
905
+ operations.end(context);
856
906
  if (current === generation) {
857
907
  const readState = {
858
908
  status: "read",
@@ -868,26 +918,30 @@ function createPasteMachine(options = {}) {
868
918
  result
869
919
  };
870
920
  }, (cause) => {
921
+ operations.end(context);
922
+ if (context.signal.aborted) return IGNORED_CANCELLED;
871
923
  const error = toCopyError(cause, "read");
872
- if (current === generation) {
873
- setState({
874
- status: "error",
875
- error
876
- });
877
- invoke(read().onError, error);
878
- }
924
+ settleError(error, source, retryCount);
879
925
  return {
880
926
  status: "error",
881
927
  error
882
928
  };
883
929
  });
884
930
  };
885
- const paste = () => {
886
- if (state.status === "reading") return Promise.resolve(IGNORED_IN_FLIGHT);
887
- return run(() => {
888
- const resolved = resolvePasteReadOptions(read());
889
- return (read().adapter ?? getDefaultAdapter()).read(resolved);
890
- });
931
+ const readClipboard = (retryCount) => run((context) => (read().adapter ?? getDefaultAdapter()).read(resolvePasteReadOptions(read()), context), "clipboard", retryCount);
932
+ const paste = () => state.status === "reading" ? Promise.resolve(IGNORED_IN_FLIGHT) : readClipboard(0);
933
+ const retry = () => {
934
+ if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
935
+ if (state.source !== "clipboard" || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
936
+ if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
937
+ const error = createCopyError("max-retries-exceeded", `Paste failed after ${String(state.retryCount)} retries.`, state.error);
938
+ settleError(error, "clipboard", state.retryCount);
939
+ return Promise.resolve({
940
+ status: "error",
941
+ error
942
+ });
943
+ }
944
+ return readClipboard(state.retryCount + 1);
891
945
  };
892
946
  const pasteEvent = (event) => {
893
947
  const data = event.clipboardData;
@@ -899,12 +953,9 @@ function createPasteMachine(options = {}) {
899
953
  } catch (cause) {
900
954
  const error = toCopyError(cause, "read");
901
955
  ++generation;
956
+ operations.abort();
902
957
  clearResetTimer();
903
- setState({
904
- status: "error",
905
- error
906
- });
907
- invoke(current.onError, error);
958
+ settleError(error, "event", 0);
908
959
  return Promise.resolve({
909
960
  status: "error",
910
961
  error
@@ -916,10 +967,11 @@ function createPasteMachine(options = {}) {
916
967
  return run(() => {
917
968
  enforcePasteLimits(entries, resolved);
918
969
  return finalizePaste(entries, "event", resolved);
919
- });
970
+ }, "event", 0);
920
971
  };
921
972
  const reset = () => {
922
973
  ++generation;
974
+ operations.abort();
923
975
  clearResetTimer();
924
976
  setState(PASTE_IDLE_STATE);
925
977
  };
@@ -927,6 +979,7 @@ function createPasteMachine(options = {}) {
927
979
  if (state.status === "read") scheduleReset(state);
928
980
  return () => {
929
981
  ++generation;
982
+ operations.abort();
930
983
  clearResetTimer();
931
984
  if (state.status === "reading") setState(PASTE_IDLE_STATE);
932
985
  };
@@ -941,11 +994,12 @@ function createPasteMachine(options = {}) {
941
994
  },
942
995
  paste,
943
996
  pasteEvent,
997
+ retry,
944
998
  reset,
945
999
  connect
946
1000
  };
947
1001
  }
948
1002
  //#endregion
949
- 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 };
1003
+ 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, canRetryPasteState, canRetryState, copyFailure, createBrowserClipboardAdapter, createBrowserPasteAdapter, createCopyCoordinator, createCopyError, createCopyMachine, createPasteMachine, describeCopyError, describePasteError, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, matchesMimePattern, normalizeMimeType, normalizePayload, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, validatePayload };
950
1004
 
951
1005
  //# sourceMappingURL=core.js.map