react-smart-copy 1.23.0 → 1.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +130 -1806
  2. package/dist/capture.cjs +3 -3
  3. package/dist/capture.d.cts +1 -1
  4. package/dist/capture.d.ts +1 -1
  5. package/dist/capture.js +3 -3
  6. package/dist/chunks/{clipboard-adapter-CtH4VELE.d.cts → clipboard-adapter-CfaIbZpv.d.cts} +2 -2
  7. package/dist/chunks/{clipboard-adapter-Ds0irroN.d.ts → clipboard-adapter-Chm6zq60.d.ts} +2 -2
  8. package/dist/chunks/{clipboard-adapter-DEXkXxwV.js → clipboard-adapter-CmKDTFdO.js} +3 -3
  9. package/dist/chunks/{clipboard-adapter-DEXkXxwV.js.map → clipboard-adapter-CmKDTFdO.js.map} +1 -1
  10. package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs → clipboard-adapter-UIFc_Qso.cjs} +3 -3
  11. package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs.map → clipboard-adapter-UIFc_Qso.cjs.map} +1 -1
  12. package/dist/chunks/{contrast-C6CVklEI.cjs → contrast-C9d8QuaF.cjs} +2 -2
  13. package/dist/chunks/{contrast-C6CVklEI.cjs.map → contrast-C9d8QuaF.cjs.map} +1 -1
  14. package/dist/chunks/{contrast-DpK2JIVu.js → contrast-DUaZq5SA.js} +2 -2
  15. package/dist/chunks/{contrast-DpK2JIVu.js.map → contrast-DUaZq5SA.js.map} +1 -1
  16. package/dist/chunks/{copy-interceptor-CZWzGOkL.d.cts → copy-interceptor-BClcHS_P.d.cts} +2 -2
  17. package/dist/chunks/{copy-interceptor-C6NABy1l.d.ts → copy-interceptor-D8c9EDnO.d.ts} +2 -2
  18. package/dist/chunks/{core-Cp2HSpaz.js → core-BH2uIumi.js} +5 -5
  19. package/dist/chunks/{core-Cp2HSpaz.js.map → core-BH2uIumi.js.map} +1 -1
  20. package/dist/chunks/{core-DYf_Lhbe.cjs → core-DmncxMt3.cjs} +5 -5
  21. package/dist/chunks/{core-DYf_Lhbe.cjs.map → core-DmncxMt3.cjs.map} +1 -1
  22. package/dist/chunks/{deadline-C29AlS_Q.js → deadline-CbwnZ3Oq.js} +2 -2
  23. package/dist/chunks/{deadline-C29AlS_Q.js.map → deadline-CbwnZ3Oq.js.map} +1 -1
  24. package/dist/chunks/{deadline-DkiB8ZHE.cjs → deadline-j2hD7JKz.cjs} +2 -2
  25. package/dist/chunks/{deadline-DkiB8ZHE.cjs.map → deadline-j2hD7JKz.cjs.map} +1 -1
  26. package/dist/chunks/{errors-9h8sdFFX.js → errors-CT-FfUtU.js} +2 -2
  27. package/dist/chunks/errors-CT-FfUtU.js.map +1 -0
  28. package/dist/chunks/{errors-BwOF6T_M.cjs → errors-DFmEAC4E.cjs} +2 -2
  29. package/dist/chunks/errors-DFmEAC4E.cjs.map +1 -0
  30. package/dist/chunks/{field-BHo5y-t_.js → field-CK3NxfkM.js} +43 -14
  31. package/dist/chunks/field-CK3NxfkM.js.map +1 -0
  32. package/dist/chunks/{field-Bytz2WfN.cjs → field-CNEcZqa9.cjs} +43 -14
  33. package/dist/chunks/field-CNEcZqa9.cjs.map +1 -0
  34. package/dist/chunks/{index-vz0iW5V2.d.cts → index-CqYzvxSN.d.cts} +4 -4
  35. package/dist/chunks/{index-mr7sSAgP.d.ts → index-Q_QeSwGr.d.ts} +4 -4
  36. package/dist/chunks/{paste-adapter--SPL4PRE.d.cts → paste-adapter-B6eucH3E.d.cts} +2 -2
  37. package/dist/chunks/{paste-adapter-uahXnTYk.d.ts → paste-adapter-CfIDT3mp.d.ts} +2 -2
  38. package/dist/chunks/{paste-reader-Bo01IMC_.cjs → paste-reader-BWQaYNaV.cjs} +2 -2
  39. package/dist/chunks/paste-reader-BWQaYNaV.cjs.map +1 -0
  40. package/dist/chunks/{paste-reader-D9i7yMXF.js → paste-reader-D6uOTDBM.js} +2 -2
  41. package/dist/chunks/paste-reader-D6uOTDBM.js.map +1 -0
  42. package/dist/chunks/{payload-DI5AorDz.js → payload-BWQ6sPtS.js} +3 -3
  43. package/dist/chunks/{payload-DI5AorDz.js.map → payload-BWQ6sPtS.js.map} +1 -1
  44. package/dist/chunks/{payload-DGw-JOo7.js → payload-BrQWGwyx.js} +2 -2
  45. package/dist/chunks/{payload-DGw-JOo7.js.map → payload-BrQWGwyx.js.map} +1 -1
  46. package/dist/chunks/{payload-Cl_8hCI5.d.ts → payload-CcvSx_Hq.d.ts} +4 -2
  47. package/dist/chunks/{payload-CcwKJ_bU.d.cts → payload-qkAWVXWA.d.cts} +4 -2
  48. package/dist/chunks/{payload-CUymxwim.cjs → payload-sBxkG7jH.cjs} +2 -2
  49. package/dist/chunks/{payload-CUymxwim.cjs.map → payload-sBxkG7jH.cjs.map} +1 -1
  50. package/dist/chunks/{payload-J6GjHuh3.cjs → payload-tTK6REua.cjs} +3 -3
  51. package/dist/chunks/{payload-J6GjHuh3.cjs.map → payload-tTK6REua.cjs.map} +1 -1
  52. package/dist/chunks/{share-Bop47Znn.js → share-CU91L4EK.js} +6 -6
  53. package/dist/chunks/{share-Bop47Znn.js.map → share-CU91L4EK.js.map} +1 -1
  54. package/dist/chunks/{share-e7FenIr2.d.ts → share-DVR_DhHc.d.ts} +3 -3
  55. package/dist/chunks/{share-C0esXvRK.d.cts → share-hIwth7Dh.d.cts} +3 -3
  56. package/dist/chunks/{share-ayDz974N.cjs → share-nx7M4Z0t.cjs} +6 -6
  57. package/dist/chunks/{share-ayDz974N.cjs.map → share-nx7M4Z0t.cjs.map} +1 -1
  58. package/dist/chunks/{url-D4PGsRm8.cjs → url-BrhVUwn7.cjs} +2 -2
  59. package/dist/chunks/{url-D4PGsRm8.cjs.map → url-BrhVUwn7.cjs.map} +1 -1
  60. package/dist/chunks/{url-BcMYVCXQ.js → url-COID0BLY.js} +2 -2
  61. package/dist/chunks/{url-BcMYVCXQ.js.map → url-COID0BLY.js.map} +1 -1
  62. package/dist/code.cjs +1 -1
  63. package/dist/code.cjs.map +1 -1
  64. package/dist/code.d.cts +1 -1
  65. package/dist/code.d.ts +1 -1
  66. package/dist/code.js +1 -1
  67. package/dist/code.js.map +1 -1
  68. package/dist/color.cjs +2 -2
  69. package/dist/color.d.cts +1 -1
  70. package/dist/color.d.ts +1 -1
  71. package/dist/color.js +2 -2
  72. package/dist/core.cjs +5 -5
  73. package/dist/core.d.cts +5 -5
  74. package/dist/core.d.ts +5 -5
  75. package/dist/core.js +5 -5
  76. package/dist/email.cjs +357 -0
  77. package/dist/email.cjs.map +1 -0
  78. package/dist/email.d.cts +163 -0
  79. package/dist/email.d.ts +163 -0
  80. package/dist/email.js +351 -0
  81. package/dist/email.js.map +1 -0
  82. package/dist/files.cjs +1 -1
  83. package/dist/files.cjs.map +1 -1
  84. package/dist/files.d.cts +3 -59
  85. package/dist/files.d.ts +3 -59
  86. package/dist/files.js +1 -1
  87. package/dist/files.js.map +1 -1
  88. package/dist/image.cjs +2 -2
  89. package/dist/image.cjs.map +1 -1
  90. package/dist/image.js +2 -2
  91. package/dist/image.js.map +1 -1
  92. package/dist/index.cjs +7 -7
  93. package/dist/index.cjs.map +1 -1
  94. package/dist/index.d.cts +43 -19
  95. package/dist/index.d.ts +43 -19
  96. package/dist/index.js +7 -7
  97. package/dist/index.js.map +1 -1
  98. package/dist/link.cjs +3 -3
  99. package/dist/link.d.cts +1 -1
  100. package/dist/link.d.ts +1 -1
  101. package/dist/link.js +3 -3
  102. package/dist/markdown.cjs +1 -1
  103. package/dist/markdown.cjs.map +1 -1
  104. package/dist/markdown.js +1 -1
  105. package/dist/markdown.js.map +1 -1
  106. package/dist/number.cjs +1 -1
  107. package/dist/number.d.cts +1 -1
  108. package/dist/number.d.ts +1 -1
  109. package/dist/number.js +1 -1
  110. package/dist/otp.cjs +1 -1
  111. package/dist/otp.js +1 -1
  112. package/dist/rich.cjs +3 -3
  113. package/dist/rich.cjs.map +1 -1
  114. package/dist/rich.d.cts +2 -2
  115. package/dist/rich.d.ts +2 -2
  116. package/dist/rich.js +3 -3
  117. package/dist/rich.js.map +1 -1
  118. package/dist/secrets.cjs +1 -1
  119. package/dist/secrets.cjs.map +1 -1
  120. package/dist/secrets.d.cts +1 -1
  121. package/dist/secrets.d.ts +1 -1
  122. package/dist/secrets.js +1 -1
  123. package/dist/secrets.js.map +1 -1
  124. package/dist/share.cjs +1 -1
  125. package/dist/share.d.cts +1 -1
  126. package/dist/share.d.ts +1 -1
  127. package/dist/share.js +1 -1
  128. package/dist/structured.cjs +2 -2
  129. package/dist/structured.cjs.map +1 -1
  130. package/dist/structured.js +2 -2
  131. package/dist/structured.js.map +1 -1
  132. package/dist/table.cjs +1 -1
  133. package/dist/table.cjs.map +1 -1
  134. package/dist/table.d.cts +1 -1
  135. package/dist/table.d.ts +1 -1
  136. package/dist/table.js +1 -1
  137. package/dist/table.js.map +1 -1
  138. package/dist/testing.cjs +2 -2
  139. package/dist/testing.d.cts +3 -3
  140. package/dist/testing.d.ts +3 -3
  141. package/dist/testing.js +2 -2
  142. package/package.json +35 -6
  143. package/dist/chunks/errors-9h8sdFFX.js.map +0 -1
  144. package/dist/chunks/errors-BwOF6T_M.cjs.map +0 -1
  145. package/dist/chunks/field-BHo5y-t_.js.map +0 -1
  146. package/dist/chunks/field-Bytz2WfN.cjs.map +0 -1
  147. package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +0 -1
  148. package/dist/chunks/paste-reader-D9i7yMXF.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"core-DYf_Lhbe.cjs","names":["isCopyFailure","createCopyError","IGNORED_IN_FLIGHT","IGNORED_NOTHING","IGNORED_NOT_RETRYABLE","IGNORED_CANCELLED","resolveResetDelay","isRetryableError","defaultAdapter","getDefaultAdapter","createBrowserClipboardAdapter","createCopyError","normalizePayload","validatePayload","toCopyError","nonEmpty","invalid","createCopyError","unsupported","isWebCustomFormat","createCopyError","isWebCustomFormat","CopyFailure","toCopyError","finalizePaste","collectClipboardItems","copyFailure","matchesMimePattern","isRetryableError","completePasteResult","toCopyError","resolvePasteReadOptions","createCopyError","snapshotDataTransfer","finalizePaste"],"sources":["../../src/core/copy-coordinator.ts","../../src/core/machine-shared.ts","../../src/core/source-error.ts","../../src/core/copy-machine.ts","../../src/core/copy-interceptor.ts","../../src/core/drag-copy.ts","../../src/core/paste-adapter.ts","../../src/core/paste-machine.ts"],"sourcesContent":["/**\n * A copy machine as seen by a coordinator. `release()` returns it from\n * `copied` to `idle`; it is a no-op in any other state.\n */\nexport interface CopyCoordinatorMember {\n readonly release: () => void;\n}\n\n/**\n * Makes a set of copy machines behave like one clipboard: when a member\n * succeeds, the member that previously showed \"Copied\" goes back to idle,\n * because the clipboard no longer holds its value.\n *\n * Failed copies never release anyone (the clipboard still holds the previous value).\n */\nexport interface CopyCoordinator {\n /** A member just reached `copied`. Releases the previous one. */\n readonly activate: (member: CopyCoordinatorMember) => void;\n /** A member left `copied` on its own (auto-reset, reset, unmount). */\n readonly deactivate: (member: CopyCoordinatorMember) => void;\n /** The member currently showing `copied`, if any. */\n readonly getActive: () => CopyCoordinatorMember | null;\n}\n\nexport function createCopyCoordinator(): CopyCoordinator {\n let active: CopyCoordinatorMember | null = null;\n return {\n activate: (member) => {\n const previous = active;\n active = member;\n if (previous !== null && previous !== member) previous.release();\n },\n deactivate: (member) => {\n if (active === member) active = null;\n },\n getActive: () => active,\n };\n}\n","/**\n * Internals shared by the copy and paste state machines. Kept in one module so\n * apps that use both don't ship two copies.\n */\n\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * Passed to adapters and lazy sources as their last argument. `signal` aborts\n * when the operation is superseded, `reset()`, or its host unmounts, so\n * expensive work (rasterising, decoding) can stop early.\n */\nexport interface OperationContext {\n readonly signal: AbortSignal;\n}\n\nexport function resolveMaxRetries(value: number | undefined): number {\n if (value === Infinity) return Infinity;\n if (value === undefined || !Number.isFinite(value)) return DEFAULT_MAX_RETRIES;\n return Math.max(0, Math.floor(value));\n}\n\nfunction reportCallbackError(error: unknown): void {\n const scope = globalThis as { reportError?: (error: unknown) => void };\n if (typeof scope.reportError === 'function') {\n scope.reportError(error);\n } else {\n setTimeout(() => {\n throw error;\n }, 0);\n }\n}\n\n/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */\nexport function invoke<Args extends unknown[]>(fn: ((...args: Args) => void) | undefined, ...args: Args): void {\n if (!fn) return;\n try {\n fn(...args);\n } catch (error) {\n reportCallbackError(error);\n }\n}\n\nexport interface Operations {\n /** Aborts the operation in flight (if any) and starts a new one. */\n readonly start: () => OperationContext;\n /** Marks `context` finished, so a later `abort()` never fires its signal. */\n readonly end: (context: OperationContext) => void;\n /** Cancels the operation in flight, if any. Returns whether one was cancelled. */\n readonly abort: () => boolean;\n}\n\n/** One cancellable operation at a time. Signals only fire while their operation is unfinished. */\nexport function createOperations(): Operations {\n let controller: AbortController | undefined;\n const abort = (): boolean => {\n if (!controller) return false;\n controller.abort();\n controller = undefined;\n return true;\n };\n return {\n start: () => {\n abort();\n controller = new AbortController();\n return { signal: controller.signal };\n },\n end: (context) => {\n if (controller?.signal === context.signal) controller = undefined;\n },\n abort,\n };\n}\n","import { createCopyError, isCopyFailure, type CopyError } from './errors';\n\n/**\n * The error for a user-supplied source (copy source, drag source, copy transform)\n * that threw. A thrown `CopyFailure` keeps its classification, so a helper such as\n * `tablePayload()` can report `too-large` instead of a generic `invalid-payload`.\n * Internal: not part of the public API.\n */\nexport function sourceError(cause: unknown, message: string): CopyError {\n return isCopyFailure(cause) ? cause.copyError : createCopyError('invalid-payload', message, cause);\n}\n","import { createBrowserClipboardAdapter, type ClipboardAdapter } from './clipboard-adapter';\nimport type { CopyCoordinator, CopyCoordinatorMember } from './copy-coordinator';\nimport { createCopyError, isRetryableError, toCopyError, type CopyError } from './errors';\nimport { createOperations, invoke, resolveMaxRetries } from './machine-shared';\nimport { normalizePayload, validatePayload, type CopyPayload, type CopySource } from './payload';\nimport { sourceError } from './source-error';\n\nexport { DEFAULT_MAX_RETRIES, resolveMaxRetries } from './machine-shared';\n\nexport const DEFAULT_RESET_AFTER_MS = 2000;\n\nexport interface IdleState {\n readonly status: 'idle';\n}\nexport interface CopyingState {\n readonly status: 'copying';\n readonly payload: CopyPayload;\n readonly retryCount: number;\n}\nexport interface CopiedState {\n readonly status: 'copied';\n readonly payload: CopyPayload;\n /** Epoch ms when the write resolved. */\n readonly at: number;\n}\nexport interface ErrorState {\n readonly status: 'error';\n /** `null` when the input itself could not be resolved. */\n readonly payload: CopyPayload | null;\n readonly error: CopyError;\n readonly retryCount: number;\n}\n\nexport type CopyState = IdleState | CopyingState | CopiedState | ErrorState;\nexport type CopyStatus = CopyState['status'];\n\n/**\n * `cancelled`: the copy was reset or its host unmounted before it finished,\n * so its work was aborted. Nothing to report to the user.\n */\nexport type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';\n\n/**\n * Why an in-flight copy was cancelled: `reset` (`reset()` was called) or\n * `disconnect` (its host disconnected, e.g. the React component unmounted).\n */\nexport type CopyCancelReason = 'reset' | 'disconnect';\n\n/** What `copy()`/`retry()` resolve to. They never reject. */\nexport type CopyOutcome =\n | { readonly status: 'copied'; readonly payload: CopyPayload }\n | { readonly status: 'error'; readonly error: CopyError }\n | { readonly status: 'ignored'; readonly reason: CopyIgnoredReason };\n\nexport interface CopyMachineOptions {\n /** Defaults to the browser Clipboard API adapter. */\n readonly adapter?: ClipboardAdapter;\n /** Time in `copied` before returning to `idle`. `false`/`Infinity` disables. Default 2000. */\n readonly resetAfterMs?: number | false;\n /**\n * Max `retry()` calls after the first failure. Default 3. `0` disables\n * retry; `Infinity` allows unlimited retries.\n */\n readonly maxRetries?: number;\n /**\n * Share \"Copied\" with other machines: only one member of a coordinator\n * shows `copied` at a time. `null` explicitly opts out (e.g. of a React `<CopyGroup>`).\n */\n readonly coordinator?: CopyCoordinator | null;\n readonly onCopy?: (payload: CopyPayload) => void;\n readonly onError?: (error: CopyError, payload: CopyPayload | null) => void;\n /**\n * `reset()` moved the machine back to `idle` from any other state. Not\n * called for the automatic return after `resetAfterMs`, for a `<CopyGroup>`\n * handing \"Copied\" to another member, or when already `idle`.\n */\n readonly onReset?: () => void;\n /**\n * A copy in flight was cancelled before it settled: its `signal` aborted\n * and its result will not reach state or `onCopy` / `onError`. Fires\n * before `onReset` when `reset()` cancels a copy.\n */\n readonly onCancel?: (reason: CopyCancelReason) => void;\n /** Clock injection for tests and deterministic environments. */\n readonly now?: () => number;\n}\n\n/** Options object, or a getter so hosts (like React) can supply the latest options. */\nexport type CopyMachineOptionsSource = CopyMachineOptions | (() => CopyMachineOptions);\n\nexport interface CopyMachine {\n readonly getSnapshot: () => CopyState;\n readonly subscribe: (listener: () => void) => () => void;\n readonly copy: (source: CopySource) => Promise<CopyOutcome>;\n readonly retry: () => Promise<CopyOutcome>;\n /** Back to `idle`. Discards any in-flight result and aborts its `signal`. */\n readonly reset: () => void;\n /**\n * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned\n * cleanup clears timers, drops in-flight results, aborts in-flight work and\n * unsticks `copying`.\n * Safe to call repeatedly (React StrictMode).\n */\n readonly connect: () => () => void;\n}\n\nexport const IDLE_STATE: IdleState = /* @__PURE__ */ Object.freeze({ status: 'idle' });\n\nconst IGNORED_IN_FLIGHT: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'in-flight' });\nconst IGNORED_NOTHING: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'nothing-to-retry' });\nconst IGNORED_NOT_RETRYABLE: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'not-retryable' });\nconst IGNORED_CANCELLED: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'cancelled' });\n\nfunction resolveResetDelay(value: number | false | undefined): number | null {\n if (value === false || value === Infinity) return null;\n if (value === undefined || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;\n return Math.max(0, value);\n}\n\n/** Pure helper: can `retry()` do anything from this state? */\nexport function canRetryState(state: CopyState, maxRetries?: number): boolean {\n return (\n state.status === 'error' &&\n state.payload !== null &&\n isRetryableError(state.error) &&\n state.retryCount < resolveMaxRetries(maxRetries)\n );\n}\n\nlet defaultAdapter: ClipboardAdapter | undefined;\nconst getDefaultAdapter = (): ClipboardAdapter => (defaultAdapter ??= createBrowserClipboardAdapter());\n\n/** Framework-agnostic copy state machine. */\nexport function createCopyMachine(options: CopyMachineOptionsSource = {}): CopyMachine {\n const read = typeof options === 'function' ? options : (): CopyMachineOptions => options;\n const listeners = new Set<() => void>();\n let state: CopyState = IDLE_STATE;\n let generation = 0;\n let resetTimer: ReturnType<typeof setTimeout> | undefined;\n const operations = createOperations();\n\n const now = (): number => (read().now ?? Date.now)();\n\n // The coordinator that saw this machine's last `copied`, so leaving it is reported to the same one.\n let joined: CopyCoordinator | null = null;\n\n const member: CopyCoordinatorMember = {\n release: () => {\n if (state.status === 'copied') {\n clearResetTimer();\n setState(IDLE_STATE);\n }\n },\n };\n\n const setState = (next: CopyState): void => {\n if (next === state) return;\n const previous = state;\n state = next;\n if (previous.status === 'copied' && next.status !== 'copied' && joined) {\n joined.deactivate(member);\n joined = null;\n }\n for (const listener of Array.from(listeners)) listener();\n };\n\n const joinCoordinator = (): void => {\n joined = read().coordinator ?? null;\n joined?.activate(member);\n };\n\n const clearResetTimer = (): void => {\n if (resetTimer !== undefined) {\n clearTimeout(resetTimer);\n resetTimer = undefined;\n }\n };\n\n const scheduleReset = (copied: CopiedState): void => {\n clearResetTimer();\n const delay = resolveResetDelay(read().resetAfterMs);\n if (delay === null) return;\n const remaining = Math.max(0, delay - (now() - copied.at));\n // Invariant: every transition out of `copied` clears this timer, so it only ever fires while still in `copied`.\n resetTimer = setTimeout(() => {\n resetTimer = undefined;\n setState(IDLE_STATE);\n }, remaining);\n };\n\n const settleError = (error: CopyError, payload: CopyPayload | null, retryCount: number): void => {\n setState({ status: 'error', payload, error, retryCount });\n invoke(read().onError, error, payload);\n };\n\n const run = (source: CopySource, retryCount: number): Promise<CopyOutcome> => {\n clearResetTimer();\n const current = ++generation;\n\n let payload: CopyPayload;\n try {\n const resolved = typeof source === 'function' ? source() : source;\n // T1: the source function must be synchronous — async sources break the\n // browser's transient user-activation window. Detect and reject a Promise\n // return rather than letting it propagate as a malformed payload (a\n // thenable is not a valid CopyInput, so validatePayload would catch it,\n // but a clear error message is more useful).\n // Cast to `unknown` first so the thenable check compiles without the\n // \"no overlap\" lint error (the TS type already narrows `resolved` to\n // `CopyInput`, which excludes thenables, but JS callers can still pass one).\n const resolvedUnknown: unknown = resolved;\n if (\n resolvedUnknown !== null &&\n typeof resolvedUnknown === 'object' &&\n typeof (resolvedUnknown as { then?: unknown }).then === 'function'\n ) {\n const error = createCopyError(\n 'invalid-payload',\n 'The copy source function must be synchronous. ' +\n 'Returning a Promise breaks the user-gesture window required for clipboard writes. ' +\n 'Generate your content before calling copy().',\n );\n settleError(error, null, retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n payload = normalizePayload(resolved);\n } catch (cause) {\n const error = sourceError(cause, 'The copy source function threw.');\n settleError(error, null, retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n\n const invalid = validatePayload(payload);\n if (invalid) {\n settleError(invalid, payload, retryCount);\n return Promise.resolve({ status: 'error', error: invalid });\n }\n\n setState({ status: 'copying', payload, retryCount });\n const context = operations.start();\n\n // The adapter is called synchronously: no await may precede it, or the\n // browser loses the transient user activation and rejects the write.\n let pending: Promise<void>;\n try {\n pending = (read().adapter ?? getDefaultAdapter()).write(payload, context);\n } catch (cause) {\n // Keep the raw reason: toCopyError() classifies it (DOMException names, CopyFailure brand).\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified by toCopyError()\n pending = Promise.reject(cause);\n }\n\n return pending.then(\n (): CopyOutcome => {\n operations.end(context);\n if (current === generation) {\n const copied: CopiedState = { status: 'copied', payload, at: now() };\n setState(copied);\n joinCoordinator();\n scheduleReset(copied);\n invoke(read().onCopy, payload);\n }\n return { status: 'copied', payload };\n },\n (cause: unknown): CopyOutcome => {\n operations.end(context);\n // Work we aborted ourselves (reset, unmount) is not a failure to report.\n // Invariant: superseding an in-flight copy always aborts it, so past\n // this line the copy is still the current one.\n if (context.signal.aborted) return IGNORED_CANCELLED;\n const error = toCopyError(cause);\n settleError(error, payload, retryCount);\n return { status: 'error', error };\n },\n );\n };\n\n const copy = (source: CopySource): Promise<CopyOutcome> =>\n state.status === 'copying' ? Promise.resolve(IGNORED_IN_FLIGHT) : run(source, 0);\n\n const retry = (): Promise<CopyOutcome> => {\n if (state.status !== 'error') return Promise.resolve(IGNORED_NOTHING);\n if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);\n\n if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {\n const error = createCopyError(\n 'max-retries-exceeded',\n `Copy failed after ${String(state.retryCount)} retries.`,\n state.error,\n );\n settleError(error, state.payload, state.retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n return run(state.payload, state.retryCount + 1);\n };\n\n const reset = (): void => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n const wasIdle = state.status === 'idle';\n setState(IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'reset');\n if (!wasIdle) invoke(read().onReset);\n };\n\n const connect = (): (() => void) => {\n if (state.status === 'copied') scheduleReset(state);\n return () => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n if (state.status === 'copying') setState(IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'disconnect');\n };\n };\n\n return {\n getSnapshot: () => state,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n copy,\n retry,\n reset,\n connect,\n };\n}\n","import { createCopyError, type CopyError } from './errors';\nimport { invoke } from './machine-shared';\nimport { isWebCustomFormat } from './mime';\nimport type { HtmlPayload, JsonPayload, TextPayload } from './payload';\nimport { sourceError } from './source-error';\n\n/**\n * Native copy interception: rewrite, redact or block what lands on the\n * clipboard when the user copies (Ctrl/Cmd+C, context menu) or cuts inside a\n * scope.\n *\n * Writes go through `event.clipboardData` synchronously, so no permission\n * prompt, no secure-context requirement, and it works in every browser. The\n * price is that only strings can be written, which the types enforce.\n *\n * Not a security boundary: users can still screenshot, use dev tools or\n * disable script. Treat redaction as a guard against accidents.\n */\n\nexport type InterceptedCopyKind = 'copy' | 'cut';\n\nexport const DEFAULT_INTERCEPTED_EVENTS: readonly InterceptedCopyKind[] = ['copy', 'cut'];\n\n/** The writable slice of `DataTransfer` during a `copy`/`cut` event. */\nexport interface ClipboardDataLike {\n setData(format: string, data: string): void;\n clearData?(format?: string): void;\n}\n\n/** Structural `ClipboardEvent`: DOM and React clipboard events both satisfy it. */\nexport interface CopyEventLike {\n readonly type: string;\n readonly target: EventTarget | null;\n readonly clipboardData: ClipboardDataLike | null;\n readonly defaultPrevented: boolean;\n preventDefault(): void;\n}\n\n/** What the user selected when they copied. */\nexport interface CopySelection {\n readonly kind: InterceptedCopyKind;\n /** What the browser would put on the clipboard as `text/plain`. */\n readonly text: string;\n /** Serialised HTML of the selection; `null` inside text inputs. */\n readonly html: string | null;\n /** A detached clone of the selected nodes, safe to mutate; `null` inside text inputs. */\n readonly fragment: DocumentFragment | null;\n /** The `<input>`/`<textarea>` the selection lives in, if any. */\n readonly field: HTMLInputElement | HTMLTextAreaElement | null;\n /** Whether a `cut` would remove the selection (form field or contenteditable). */\n readonly editable: boolean;\n}\n\n/**\n * A multi payload whose items are all strings; the only kind `setData` accepts.\n * Web custom formats (`web …`) are skipped: only the async Clipboard API writes them.\n */\nexport interface SyncMultiPayload {\n readonly kind: 'multi';\n readonly items: readonly { readonly mimeType: string; readonly data: string; readonly optional?: boolean }[];\n}\n\n/** Payloads writable synchronously during a copy event. Images need the async clipboard. */\nexport type SyncCopyPayload = TextPayload | HtmlPayload | JsonPayload | SyncMultiPayload;\n\n/**\n * What a transform returns:\n * - a string or payload: write that instead of the selection\n * - `false`: block the copy (nothing reaches the clipboard; a cut deletes nothing)\n * - `null` / `undefined`: leave the browser's default copy untouched\n *\n * Must be synchronous: the clipboard closes when the event handler returns.\n */\nexport type CopyInterceptDecision = string | SyncCopyPayload | false | null | undefined;\n\nexport type CopyInterceptTransform = (selection: CopySelection) => CopyInterceptDecision;\n\n/**\n * When the transform throws or returns something unwritable:\n * - `'block'` (default): nothing is copied. Safe for redaction.\n * - `'native'`: the browser's default copy proceeds unmodified.\n */\nexport type CopyInterceptFailureMode = 'block' | 'native';\n\nexport interface CopyInterceptOptions {\n readonly transform: CopyInterceptTransform;\n readonly failureMode?: CopyInterceptFailureMode;\n}\n\nexport type CopyInterceptPassReason =\n /** Not a `copy`/`cut` event. */\n | 'unsupported-event'\n /** Another handler already called `preventDefault()`. */\n | 'already-handled'\n /** Nothing readable was selected. */\n | 'no-selection'\n /** The transform returned `null`/`undefined`. */\n | 'declined';\n\nexport type CopyInterceptOutcome =\n | {\n readonly status: 'passed';\n readonly reason: CopyInterceptPassReason;\n readonly selection: CopySelection | null;\n }\n | {\n readonly status: 'written';\n readonly selection: CopySelection;\n readonly payload: SyncCopyPayload;\n /** For an editable `cut`: whether the selection was removed. Always `false` for `copy`. */\n readonly deleted: boolean;\n }\n | { readonly status: 'blocked'; readonly selection: CopySelection }\n | {\n readonly status: 'failed';\n readonly selection: CopySelection;\n readonly error: CopyError;\n /** What actually happened to the copy. */\n readonly fallback: CopyInterceptFailureMode;\n };\n\n/* ─────────────────────────────────────────────────────── selection reading */\n\ntype TextField = HTMLInputElement | HTMLTextAreaElement;\n\nfunction isNode(value: unknown): value is Node {\n return typeof value === 'object' && value !== null && typeof (value as Node).nodeType === 'number';\n}\n\ninterface FieldSelection {\n readonly field: TextField;\n readonly start: number;\n readonly end: number;\n}\n\nfunction readTextField(target: EventTarget | null): FieldSelection | null {\n if (!isNode(target) || target.nodeType !== 1) return null;\n const tag = (target as Element).tagName;\n if (tag !== 'INPUT' && tag !== 'TEXTAREA') return null;\n const field = target as TextField;\n try {\n // `null` (or a throw, in older engines) for input types without text selection.\n const { selectionStart: start, selectionEnd: end } = field;\n return typeof start === 'number' && typeof end === 'number' ? { field, start, end } : null;\n } catch {\n return null;\n }\n}\n\nfunction documentOf(target: EventTarget | null): Document | null {\n if (isNode(target)) return target.nodeType === 9 ? (target as Document) : target.ownerDocument;\n return typeof document === 'undefined' ? null : document;\n}\n\nfunction isEditableNode(node: Node): boolean {\n const element = node.nodeType === 1 ? (node as HTMLElement) : node.parentElement;\n return element?.isContentEditable === true;\n}\n\ninterface SelectedRanges {\n readonly selection: Selection;\n readonly ranges: readonly Range[];\n}\n\nfunction selectedRanges(doc: Document | null): SelectedRanges | null {\n const selection = doc?.getSelection();\n if (!selection || selection.isCollapsed) return null;\n const ranges: Range[] = [];\n for (let index = 0; index < selection.rangeCount; index += 1) ranges.push(selection.getRangeAt(index));\n return { selection, ranges };\n}\n\ninterface ReadSelection {\n readonly selection: CopySelection;\n readonly doc: Document;\n}\n\nfunction readSelection(event: CopyEventLike): ReadSelection | null {\n const kind: InterceptedCopyKind = event.type === 'cut' ? 'cut' : 'copy';\n const fieldSelection = readTextField(event.target);\n if (fieldSelection) {\n const { field, start, end } = fieldSelection;\n const text = field.value.slice(Math.min(start, end), Math.max(start, end));\n if (text.length === 0) return null;\n const editable = !field.readOnly && !field.disabled;\n return { selection: { kind, text, html: null, fragment: null, field, editable }, doc: field.ownerDocument };\n }\n\n const doc = documentOf(event.target);\n const selected = selectedRanges(doc);\n const first = selected?.ranges[0];\n if (!doc || !selected || !first) return null;\n // `Selection#toString` follows the rendered layout, like the browser's own copy;\n // `Range#toString` would leak source whitespace and hidden text.\n const text = selected.selection.toString();\n if (text.length === 0) return null;\n\n const container = doc.createElement('div');\n for (const range of selected.ranges) container.appendChild(range.cloneContents());\n const html = container.innerHTML;\n const fragment = doc.createDocumentFragment();\n while (container.firstChild) fragment.appendChild(container.firstChild);\n\n const editable = isEditableNode(first.startContainer);\n return { selection: { kind, text, html, fragment, field: null, editable }, doc };\n}\n\n/** Reads the selection behind a copy event, or `null` if nothing readable is selected. */\nexport function readCopySelection(event: CopyEventLike): CopySelection | null {\n const read = readSelection(event);\n return read ? read.selection : null;\n}\n\n/* ─────────────────────────────────────────────────────────────── writing */\n\ntype Entries = readonly (readonly [mimeType: string, data: string])[];\n\ntype Prepared =\n | { readonly ok: true; readonly payload: SyncCopyPayload; readonly entries: Entries }\n | { readonly ok: false; readonly error: CopyError };\n\nconst nonEmpty = (value: unknown): value is string => typeof value === 'string' && value.length > 0;\nconst invalid = (message: string, cause?: unknown): Prepared => ({\n ok: false,\n error: createCopyError('invalid-payload', message, cause),\n});\nconst unsupported = (message: string): Prepared => ({ ok: false, error: createCopyError('unsupported-format', message) });\n\n/**\n * Validates a decision and turns it into `[mimeType, data]` pairs. Kept\n * self-contained (no shared validator) so the interceptor stays small; the\n * checks still run for plain-JS callers the types can't protect.\n */\nfunction prepare(decision: string | SyncCopyPayload): Prepared {\n const candidate: unknown = typeof decision === 'string' ? { kind: 'text', value: decision } : decision;\n if (typeof candidate !== 'object' || candidate === null) {\n return invalid('Copy transforms must return a string, a payload, false, or nothing.');\n }\n if (typeof (candidate as { then?: unknown }).then === 'function') {\n return invalid('Copy transforms must be synchronous; the clipboard closes when the event ends.');\n }\n const payload = candidate as SyncCopyPayload;\n const fields = candidate as Record<string, unknown>;\n const ok = (entries: Entries): Prepared => ({ ok: true, payload, entries });\n\n switch (fields['kind']) {\n case 'text':\n return nonEmpty(fields['value']) ? ok([['text/plain', fields['value']]]) : invalid('Text payload must be a non-empty string.');\n case 'html':\n return nonEmpty(fields['html']) && nonEmpty(fields['text'])\n ? ok([['text/html', fields['html']], ['text/plain', fields['text']]])\n : invalid('HTML payload requires non-empty `html` and plain-text `text`.');\n case 'json': {\n const pretty = fields['pretty'];\n const indent = pretty === true ? 2 : typeof pretty === 'number' ? pretty : undefined;\n // Typed as `string`, but `undefined` for functions, symbols and undefined.\n let json: unknown;\n try {\n json = JSON.stringify(fields['value'], null, indent);\n } catch (cause) {\n return invalid('JSON payload could not be serialised (circular reference or BigInt?).', cause);\n }\n return typeof json === 'string' ? ok([['text/plain', json]]) : invalid('JSON payload serialised to nothing.');\n }\n case 'multi': {\n const items = fields['items'];\n if (!Array.isArray(items) || items.length === 0) return invalid('Multi payload requires at least one item.');\n const entries: (readonly [string, string])[] = [];\n for (const item of items as unknown[]) {\n const { mimeType, data } = (item ?? {}) as { mimeType?: unknown; data?: unknown };\n if (!nonEmpty(mimeType) || entries.some(([seen]) => seen === mimeType)) {\n return invalid('Every multi item needs a unique, non-empty `mimeType`.');\n }\n if (typeof data !== 'string') return unsupported(`Multi item \"${mimeType}\" must be a string during a copy event.`);\n entries.push([mimeType, data]);\n }\n const writable = entries.filter(([mimeType]) => !isWebCustomFormat(mimeType));\n return writable.length > 0\n ? ok(writable)\n : unsupported('Web custom formats need the async Clipboard API (useCopy).');\n }\n default:\n return unsupported(`\"${String(fields['kind'])}\" payloads cannot be written during a copy event; use useCopy() for images.`);\n }\n}\n\n/** Deletes the selection the way a native cut would (keeps undo history, fires `input`). */\nfunction deleteSelection(doc: Document): boolean {\n const legacy = doc as unknown as { execCommand?: (command: string) => boolean };\n try {\n return legacy.execCommand?.('delete') === true;\n } catch {\n return false;\n }\n}\n\n/**\n * Applies a transform to one `copy`/`cut` event. Use directly from an\n * `onCopy` handler, or let {@link registerCopyInterceptor} scope it.\n */\nexport function interceptCopyEvent(event: CopyEventLike, options: CopyInterceptOptions): CopyInterceptOutcome {\n if (event.type !== 'copy' && event.type !== 'cut') {\n return { status: 'passed', reason: 'unsupported-event', selection: null };\n }\n if (event.defaultPrevented) return { status: 'passed', reason: 'already-handled', selection: null };\n\n const read = readSelection(event);\n if (!read) return { status: 'passed', reason: 'no-selection', selection: null };\n const { selection, doc } = read;\n\n const fail = (error: CopyError): CopyInterceptOutcome => {\n const fallback = options.failureMode ?? 'block';\n if (fallback === 'block') event.preventDefault();\n return { status: 'failed', selection, error, fallback };\n };\n\n let decision: CopyInterceptDecision;\n try {\n decision = options.transform(selection);\n } catch (cause) {\n return fail(sourceError(cause, 'The copy transform threw.'));\n }\n\n if (decision === null || decision === undefined) return { status: 'passed', reason: 'declined', selection };\n if (decision === false) {\n event.preventDefault();\n return { status: 'blocked', selection };\n }\n\n const prepared = prepare(decision);\n if (!prepared.ok) return fail(prepared.error);\n\n const data = event.clipboardData;\n if (!data) return fail(createCopyError('unsupported', 'This browser exposes no clipboardData on copy events.'));\n\n // From here the browser's default is gone: a failure can only end in `block`.\n event.preventDefault();\n try {\n for (const [mimeType, value] of prepared.entries) data.setData(mimeType, value);\n } catch (cause) {\n try {\n data.clearData?.();\n } catch {\n // Best effort: a half-written clipboard is still better reported than hidden.\n }\n const error = createCopyError('unknown', 'The browser rejected the clipboard write.', cause);\n return { status: 'failed', selection, error, fallback: 'block' };\n }\n\n const deleted = selection.kind === 'cut' && selection.editable && deleteSelection(doc);\n return { status: 'written', selection, payload: prepared.payload, deleted };\n}\n\n/* ────────────────────────────────────────────────────────────── scoping */\n\nexport interface CopyInterceptorOptions extends CopyInterceptOptions {\n /**\n * When one selection touches several scopes, exactly one handles it: the\n * highest `priority`, then the innermost, then the first in the document.\n * The winner sees the *whole* selection. Give redaction scopes a higher\n * priority so text copied across them is always masked. Default `0`.\n */\n readonly priority?: number;\n /** Which events to intercept. Default: both `copy` and `cut`. */\n readonly events?: readonly InterceptedCopyKind[];\n /** Every outcome for selections inside this scope, including `passed`. */\n readonly onIntercept?: (outcome: CopyInterceptOutcome) => void;\n /** Called when the transform failed; the outcome's `fallback` says what happened to the copy. */\n readonly onError?: (error: CopyError) => void;\n}\n\ninterface Scope {\n readonly root: Element;\n readonly read: () => CopyInterceptorOptions;\n}\n\ninterface Registry {\n readonly scopes: Set<Scope>;\n readonly listener: (event: Event) => void;\n}\n\nconst registries = /* @__PURE__ */ new WeakMap<Document, Registry>();\n\nfunction touches(root: Element, event: CopyEventLike): boolean {\n const fieldSelection = readTextField(event.target);\n if (fieldSelection) return root.contains(fieldSelection.field);\n const selected = selectedRanges(root.ownerDocument);\n return selected !== null && selected.ranges.some((range) => range.intersectsNode(root));\n}\n\nconst priorityOf = (scope: Scope): number => scope.read().priority ?? 0;\n\n/**\n * Highest `priority` first; then the innermost scope; then document order;\n * then registration order (same root). A total order, so the result never\n * depends on effect timing.\n */\nfunction compareScopes(a: Scope, b: Scope): number {\n const byPriority = priorityOf(b) - priorityOf(a);\n if (byPriority !== 0) return byPriority;\n const position = a.root.compareDocumentPosition(b.root);\n if (position === 0) return 0;\n if (position & 16) return 1; // b is inside a: b first\n if (position & 8) return -1; // b contains a: a first\n return position & 4 ? -1 : 1; // b follows a: a first\n}\n\nfunction dispatch(registry: Registry, event: CopyEventLike): void {\n if (event.defaultPrevented) return;\n const kind = event.type as InterceptedCopyKind;\n const candidates = [...registry.scopes].filter(\n (scope) => (scope.read().events ?? DEFAULT_INTERCEPTED_EVENTS).includes(kind) && touches(scope.root, event),\n );\n const [scope] = candidates.sort(compareScopes);\n if (!scope) return;\n\n const options = scope.read();\n const outcome = interceptCopyEvent(event, options);\n invoke(options.onIntercept, outcome);\n if (outcome.status === 'failed') invoke(options.onError, outcome.error);\n}\n\n/**\n * Intercepts native copies and cuts whose selection touches `root`. Returns\n * an unsubscribe function. Pass a getter to always read the latest options.\n *\n * One listener per document serves every scope, so overlapping scopes\n * resolve deterministically (see `priority`) regardless of registration order.\n * Handlers that call `preventDefault()` first (e.g. a React `onCopy`) win.\n */\nexport function registerCopyInterceptor(\n root: Element,\n options: CopyInterceptorOptions | (() => CopyInterceptorOptions),\n): () => void {\n const doc = root.ownerDocument;\n let registry = registries.get(doc);\n if (!registry) {\n const scopes = new Set<Scope>();\n const created: Registry = {\n scopes,\n listener: (event) => {\n dispatch(created, event as unknown as CopyEventLike);\n },\n };\n registry = created;\n registries.set(doc, created);\n doc.addEventListener('copy', created.listener);\n doc.addEventListener('cut', created.listener);\n }\n\n const scope: Scope = { root, read: typeof options === 'function' ? options : () => options };\n registry.scopes.add(scope);\n const active = registry;\n\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n active.scopes.delete(scope);\n if (active.scopes.size === 0) {\n doc.removeEventListener('copy', active.listener);\n doc.removeEventListener('cut', active.listener);\n registries.delete(doc);\n }\n };\n}\n","/**\n * Drag-to-copy: populate `DataTransfer` when the user starts dragging an\n * element, so whatever they drop it into receives structured data — plain text,\n * HTML, JSON, or multiple MIME types — instead of the browser's default\n * text-extraction of the dragged DOM.\n *\n * No Clipboard API, no permission prompt, works in every browser that supports\n * HTML5 drag-and-drop (all modern browsers and IE11+).\n */\n\nimport { invoke } from './machine-shared';\nimport { createCopyError, type CopyError } from './errors';\nimport { isWebCustomFormat } from './mime';\nimport type { HtmlPayload, JsonPayload, TextPayload } from './payload';\nimport { sourceError } from './source-error';\n\n/* ─────────────────────────────────────────────────────────────────── types */\n\n/**\n * The `effectAllowed` a drag operation advertises. Controls which cursor the\n * browser shows and which `dropEffect` the drop target may request.\n *\n * - `'copy'` (default): dragging produces a copy of the data.\n * - `'move'`: dragging removes the source after a drop (the app must do this).\n * - `'link'`: dragging creates a link/reference.\n * - `'copyMove'` / `'copyLink'` / `'linkMove'` / `'all'`: combinations.\n * - `'none'`: the drag is not droppable anywhere.\n * - `'uninitialized'`: browser default (same as `'all'` in most cases).\n */\nexport type DragEffectAllowed =\n | 'copy'\n | 'move'\n | 'link'\n | 'copyMove'\n | 'copyLink'\n | 'linkMove'\n | 'all'\n | 'none'\n | 'uninitialized';\n\n/** What is put into `DataTransfer` when a drag starts. */\nexport interface DragCopyItem {\n /** Web custom formats (`web …`) are skipped: only the async Clipboard API writes them. */\n readonly mimeType: string;\n readonly data: string;\n /** Accepted for parity with `MultiPayloadItem`; every non-web item can be written to a drag. */\n readonly optional?: boolean;\n}\n\n/**\n * A multi-format drag payload — strings only (DataTransfer only accepts strings).\n * Mirrors `SyncCopyPayload` from copy-interceptor but scoped to drag.\n */\nexport type DragCopyPayload = TextPayload | HtmlPayload | JsonPayload | DragMultiPayload;\n\nexport interface DragMultiPayload {\n readonly kind: 'multi';\n readonly items: readonly DragCopyItem[];\n}\n\n/**\n * What the source getter returns:\n * - a string: written as `text/plain`.\n * - a `DragCopyPayload`: written according to its `kind`.\n * - `false`: cancels the drag (`preventDefault()` on `dragstart`).\n * - `null` / `undefined`: leaves the browser's default drag data untouched.\n */\nexport type DragCopyDecision = string | DragCopyPayload | false | null | undefined;\n\n/** Called once when the user begins dragging the element. Must be synchronous. */\nexport type DragCopySource = (event: DragStartEventLike) => DragCopyDecision;\n\n/** Structural `DragEvent`: DOM and React drag events both satisfy it. */\nexport interface DragStartEventLike {\n readonly type: string;\n readonly dataTransfer: DataTransferLike | null;\n readonly defaultPrevented: boolean;\n preventDefault(): void;\n}\n\n/** The writable face of `DataTransfer`. */\nexport interface DataTransferLike {\n effectAllowed: string;\n setData(format: string, data: string): void;\n clearData?(format?: string): void;\n}\n\nexport type DragCopyStatus =\n /** No drag has started yet, or it was cancelled / never had source data. */\n | 'idle'\n /** The element is being dragged and data is on the DataTransfer. */\n | 'dragging'\n /** The drag ended (dropped or abandoned). */\n | 'done';\n\nexport type DragCopyPassReason =\n /** Source returned `null`/`undefined`. */\n | 'declined'\n /** `DataTransfer` is not present on this event. */\n | 'no-transfer'\n /** Source returned `false`. */\n | 'cancelled';\n\nexport type DragCopyOutcome =\n | { readonly status: 'written'; readonly payload: DragCopyPayload }\n | { readonly status: 'passed'; readonly reason: DragCopyPassReason }\n | { readonly status: 'failed'; readonly error: CopyError };\n\nexport interface DragCopyState {\n readonly status: DragCopyStatus;\n /** The last `dragstart` outcome; `null` before the first drag. */\n readonly outcome: DragCopyOutcome | null;\n}\n\nexport interface DragCopyOptions {\n /**\n * Returns the data to put in the drag. Called synchronously on `dragstart`.\n * Return a string (shorthand for `{ kind: 'text' }`), a payload object,\n * `false` to cancel the drag, or `null`/`undefined` to pass through.\n */\n readonly source: DragCopySource;\n /**\n * `effectAllowed` advertised on the drag. Default `'copy'`.\n * Setting `'move'` signals to drop targets that the source will be removed.\n */\n readonly effectAllowed?: DragEffectAllowed;\n /**\n * Called each time a drag starts or ends, with the latest outcome and status.\n * Stable across re-renders when written as a class method or via `useRef`.\n */\n readonly onDrag?: (state: DragCopyState) => void;\n /** Called when preparing the drag payload fails. */\n readonly onError?: (error: CopyError) => void;\n}\n\n/* ─────────────────────────────────────────────────────────── validation */\n\nconst nonEmpty = (value: unknown): value is string =>\n typeof value === 'string' && value.length > 0;\n\ntype PrepareFail = { readonly ok: false; readonly error: CopyError };\ntype PrepareOk = { readonly ok: true; readonly payload: DragCopyPayload; readonly items: readonly DragCopyItem[] };\ntype Prepared = PrepareOk | PrepareFail;\n\nconst invalid = (message: string, cause?: unknown): PrepareFail => ({\n ok: false,\n error: createCopyError('invalid-payload', message, cause),\n});\n\nconst unsupported = (message: string): PrepareFail => ({\n ok: false,\n error: createCopyError('unsupported-format', message),\n});\n\nfunction prepareDragDecision(decision: string | DragCopyPayload): Prepared {\n const candidate: unknown =\n typeof decision === 'string' ? { kind: 'text', value: decision } : decision;\n\n if (typeof candidate !== 'object' || candidate === null) {\n return invalid('Drag source must return a string, a payload, false, or nothing.');\n }\n if (typeof (candidate as { then?: unknown }).then === 'function') {\n return invalid('Drag sources must be synchronous; DataTransfer closes when dragstart returns.');\n }\n\n const payload = candidate as DragCopyPayload;\n const fields = candidate as Record<string, unknown>;\n const ok = (items: readonly DragCopyItem[]): PrepareOk => ({ ok: true, payload, items });\n\n switch (fields['kind']) {\n case 'text':\n return nonEmpty(fields['value'])\n ? ok([{ mimeType: 'text/plain', data: fields['value'] }])\n : invalid('Text payload must be a non-empty string.');\n\n case 'html':\n return nonEmpty(fields['html']) && nonEmpty(fields['text'])\n ? ok([\n { mimeType: 'text/html', data: fields['html'] },\n { mimeType: 'text/plain', data: fields['text'] },\n ])\n : invalid('HTML payload requires non-empty `html` and `text`.');\n\n case 'json': {\n const pretty = fields['pretty'];\n const indent =\n pretty === true ? 2 : typeof pretty === 'number' ? pretty : undefined;\n let json: unknown;\n try {\n json = JSON.stringify(fields['value'], null, indent);\n } catch (cause) {\n return invalid(\n 'JSON payload could not be serialised (circular reference or BigInt?).',\n cause,\n );\n }\n return typeof json === 'string'\n ? ok([{ mimeType: 'text/plain', data: json }])\n : invalid('JSON payload serialised to nothing.');\n }\n\n case 'multi': {\n const items = fields['items'];\n if (!Array.isArray(items) || items.length === 0) {\n return invalid('Multi payload requires at least one item.');\n }\n const out: DragCopyItem[] = [];\n for (const item of items as unknown[]) {\n const { mimeType, data } = (item ?? {}) as {\n mimeType?: unknown;\n data?: unknown;\n };\n if (!nonEmpty(mimeType) || out.some((i) => i.mimeType === mimeType)) {\n return invalid('Every multi item needs a unique, non-empty `mimeType`.');\n }\n if (typeof data !== 'string') {\n return unsupported(\n `Multi item \"${mimeType}\" must be a string; DataTransfer does not accept Blobs.`,\n );\n }\n out.push({ mimeType, data });\n }\n const writable = out.filter((item) => !isWebCustomFormat(item.mimeType));\n return writable.length > 0\n ? ok(writable)\n : unsupported('Web custom formats need the async Clipboard API (useCopy).');\n }\n\n default:\n return unsupported(\n `\"${String(fields['kind'])}\" payloads cannot be used for drag-copy; use useCopy() for images.`,\n );\n }\n}\n\n/* ─────────────────────────────────────────────────────── applyDragCopy */\n\n/**\n * Populates a `dragstart` event's `DataTransfer` with the given payload.\n * Use this from a raw `dragstart` handler or a React `onDragStart` prop.\n * Returns the outcome so you can inspect what happened.\n */\nexport function applyDragCopy(\n event: DragStartEventLike,\n options: DragCopyOptions,\n): DragCopyOutcome {\n if (event.defaultPrevented) {\n return { status: 'passed', reason: 'declined' };\n }\n\n let decision: DragCopyDecision;\n try {\n decision = options.source(event);\n } catch (cause) {\n const error = sourceError(cause, 'The drag source threw.');\n return { status: 'failed', error };\n }\n\n if (decision === null || decision === undefined) {\n return { status: 'passed', reason: 'declined' };\n }\n\n if (decision === false) {\n event.preventDefault();\n return { status: 'passed', reason: 'cancelled' };\n }\n\n const transfer = event.dataTransfer;\n if (!transfer) {\n return { status: 'passed', reason: 'no-transfer' };\n }\n\n const prepared = prepareDragDecision(decision);\n if (!prepared.ok) {\n return { status: 'failed', error: prepared.error };\n }\n\n try {\n transfer.effectAllowed = options.effectAllowed ?? 'copy';\n for (const { mimeType, data } of prepared.items) {\n transfer.setData(mimeType, data);\n }\n } catch (cause) {\n try {\n transfer.clearData?.();\n } catch {\n // Best effort: report the original error, not a clearData failure.\n }\n const error = createCopyError(\n 'unknown',\n 'The browser rejected the DataTransfer write.',\n cause,\n );\n return { status: 'failed', error };\n }\n\n return { status: 'written', payload: prepared.payload };\n}\n\n/* ─────────────────────────────────────────────────── registerDragCopy */\n\nexport interface RegisterDragCopyResult {\n /** Unsubscribes all listeners. Idempotent. */\n readonly unsubscribe: () => void;\n}\n\n/**\n * Attaches `dragstart` and `dragend` listeners to `element`, calling\n * `applyDragCopy` on every drag start. Returns an object with an\n * `unsubscribe` function.\n *\n * Pass an options getter so the latest options are always used without\n * re-registering — safe to pass an inline object from a React render.\n *\n * ```ts\n * const { unsubscribe } = registerDragCopy(el, () => ({\n * source: () => `${title}\\n${url}`,\n * }));\n * ```\n */\nexport function registerDragCopy(\n element: HTMLElement,\n options: DragCopyOptions | (() => DragCopyOptions),\n): RegisterDragCopyResult {\n const read = typeof options === 'function' ? options : (): DragCopyOptions => options;\n\n let unsubscribed = false;\n let currentOutcome: DragCopyOutcome | null = null;\n\n function onDragStart(raw: Event): void {\n const event = raw as DragEvent;\n const opts = read();\n\n const outcome = applyDragCopy(\n {\n type: event.type,\n dataTransfer: event.dataTransfer,\n get defaultPrevented() {\n return event.defaultPrevented;\n },\n preventDefault: () => { event.preventDefault(); },\n },\n opts,\n );\n\n currentOutcome = outcome;\n\n const state: DragCopyState = { status: 'dragging', outcome };\n if (outcome.status === 'failed') invoke(opts.onError, outcome.error);\n invoke(opts.onDrag, state);\n }\n\n function onDragEnd(): void {\n const opts = read();\n const state: DragCopyState = { status: 'done', outcome: currentOutcome };\n invoke(opts.onDrag, state);\n currentOutcome = null;\n }\n\n element.setAttribute('draggable', 'true');\n element.addEventListener('dragstart', onDragStart);\n element.addEventListener('dragend', onDragEnd);\n\n return {\n unsubscribe(): void {\n if (unsubscribed) return;\n unsubscribed = true;\n element.removeEventListener('dragstart', onDragStart);\n element.removeEventListener('dragend', onDragEnd);\n element.removeAttribute('draggable');\n },\n };\n}\n","import { CopyFailure, copyFailure, toCopyError } from './errors';\nimport type { OperationContext } from './machine-shared';\nimport { matchesMimePattern } from './mime';\nimport {\n collectClipboardItems,\n enforcePasteLimits,\n finalizePaste,\n type ClipboardItemLike,\n type PasteEntry,\n type PasteReadResult,\n type ResolvedPasteReadOptions,\n} from './paste-reader';\n\n/** Minimal structural view of `navigator.clipboard` for reading. */\nexport interface PasteClipboardLike {\n read?(): Promise<readonly ClipboardItemLike[]>;\n readText?(): Promise<string>;\n}\n\nexport interface PasteEnvironment {\n readonly isSecureContext?: boolean;\n readonly navigator?: { readonly clipboard?: PasteClipboardLike | undefined } | undefined;\n}\n\n/**\n * Reads the system clipboard. Implement it for Electron, a native bridge or tests.\n *\n * Contract: call the platform API synchronously (before any `await`) so the\n * browser still sees the user gesture, and reject with a `CopyFailure`.\n * `context.signal` aborts when the read is superseded, reset, or its host\n * unmounts; honour it to stop decoding early.\n */\nexport interface PasteAdapter {\n read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteReadResult>;\n}\n\nexport interface BrowserPasteAdapterOptions {\n /** Defaults to `window`, read lazily at paste time (SSR-safe). */\n readonly getEnvironment?: () => PasteEnvironment | undefined;\n}\n\nfunction defaultEnvironment(): PasteEnvironment | undefined {\n return typeof window === 'undefined' ? undefined : window;\n}\n\ntype ClipboardWithRead = PasteClipboardLike & Required<Pick<PasteClipboardLike, 'read'>>;\ntype ClipboardWithReadText = PasteClipboardLike & Required<Pick<PasteClipboardLike, 'readText'>>;\n\nconst canRead = (clipboard: PasteClipboardLike): clipboard is ClipboardWithRead => typeof clipboard.read === 'function';\nconst canReadText = (clipboard: PasteClipboardLike): clipboard is ClipboardWithReadText =>\n typeof clipboard.readText === 'function';\n\nasync function readPlainText(clipboard: ClipboardWithReadText, options: ResolvedPasteReadOptions): Promise<PasteReadResult> {\n let text: string;\n try {\n text = await clipboard.readText();\n } catch (cause) {\n throw new CopyFailure(toCopyError(cause, 'read'));\n }\n const entries: PasteEntry[] = text.length > 0 ? [{ type: 'text/plain', data: text, file: false }] : [];\n enforcePasteLimits(entries, options);\n return finalizePaste(entries, 'clipboard', options);\n}\n\nasync function readRich(\n clipboard: ClipboardWithRead,\n options: ResolvedPasteReadOptions,\n signal: AbortSignal | undefined,\n): Promise<PasteReadResult> {\n let items: readonly ClipboardItemLike[];\n try {\n items = await clipboard.read();\n } catch (cause) {\n throw new CopyFailure(toCopyError(cause, 'read'));\n }\n const entries = await collectClipboardItems(items, options, signal);\n return finalizePaste(entries, 'clipboard', options);\n}\n\nfunction readFromClipboard(\n env: PasteEnvironment | undefined,\n options: ResolvedPasteReadOptions,\n signal: AbortSignal | undefined,\n): Promise<PasteReadResult> {\n if (!env) throw copyFailure('unsupported', 'No browser environment: the clipboard only exists in the browser.');\n if (env.isSecureContext === false) {\n throw copyFailure('insecure-context', 'The Clipboard API requires a secure context (HTTPS or localhost).');\n }\n const clipboard = env.navigator?.clipboard;\n if (!clipboard) throw copyFailure('unsupported', 'navigator.clipboard is not available in this browser.');\n\n const plainOnly = options.accept.every((pattern) => pattern === 'text/plain');\n const acceptsPlain = options.accept.some((pattern) => matchesMimePattern('text/plain', pattern));\n\n // readText() has the widest support and the narrowest permission prompt: prefer it for plain text.\n if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options, signal);\n if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);\n throw canReadText(clipboard)\n ? copyFailure('unsupported-format', 'Reading non-text clipboard content requires navigator.clipboard.read().')\n : copyFailure('unsupported', 'This browser cannot read the clipboard.');\n}\n\n/** The default paste adapter: async Clipboard API with feature detection and honest errors. */\nexport function createBrowserPasteAdapter(options: BrowserPasteAdapterOptions = {}): PasteAdapter {\n const getEnvironment = options.getEnvironment ?? defaultEnvironment;\n return {\n read: (resolved, context) => {\n try {\n return readFromClipboard(getEnvironment(), resolved, context?.signal);\n } catch (cause) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- always a CopyFailure\n return Promise.reject(cause);\n }\n },\n };\n}\n","import { createCopyError, isRetryableError, toCopyError, type CopyError } from './errors';\nimport { createOperations, invoke, resolveMaxRetries, type OperationContext } from './machine-shared';\nimport { createBrowserPasteAdapter, type PasteAdapter } from './paste-adapter';\nimport {\n completePasteResult,\n enforcePasteLimits,\n finalizePaste,\n resolvePasteReadOptions,\n snapshotDataTransfer,\n type DataTransferLike,\n type PasteReadOptions,\n type PasteReadResult,\n type PasteResult,\n type PasteSource,\n} from './paste-reader';\n\n/* ------------------------------------------------------------------ State */\n\nexport interface PasteIdleState {\n readonly status: 'idle';\n}\nexport interface PasteReadingState {\n readonly status: 'reading';\n}\nexport interface PasteReadState {\n readonly status: 'read';\n readonly result: PasteResult;\n /** Epoch ms when the read resolved. */\n readonly at: number;\n}\nexport interface PasteErrorState {\n readonly status: 'error';\n readonly error: CopyError;\n /** Where the failed read came from. Only `'clipboard'` reads can be retried. */\n readonly source: PasteSource;\n /** `retry()` calls made since the last fresh `paste()`. */\n readonly retryCount: number;\n}\n\nexport type PasteState = PasteIdleState | PasteReadingState | PasteReadState | PasteErrorState;\nexport type PasteStatus = PasteState['status'];\n\n/**\n * `cancelled`: the read was superseded, reset, or its host unmounted before it\n * finished, so its work was aborted. Nothing to report to the user.\n */\nexport type PasteIgnoredReason = 'in-flight' | 'no-accepted-content' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';\n\n/**\n * Why an in-flight read was cancelled: `reset` (`reset()` was called),\n * `disconnect` (its host disconnected, e.g. the React component unmounted) or\n * `superseded` (a paste or drop event arrived while a read was pending).\n */\nexport type PasteCancelReason = 'reset' | 'disconnect' | 'superseded';\n\n/** What `paste()` / `pasteEvent()` / `dropEvent()` / `retry()` resolve to. They never reject. */\nexport type PasteOutcome =\n | { readonly status: 'read'; readonly result: PasteResult }\n | { readonly status: 'error'; readonly error: CopyError }\n | { readonly status: 'ignored'; readonly reason: PasteIgnoredReason };\n\n/** Structural view of a DOM / React `paste` event. */\nexport interface PasteEventLike {\n readonly clipboardData: DataTransferLike | null | undefined;\n preventDefault(): void;\n}\n\n/** Structural view of a DOM / React `drop` event. */\nexport interface PasteDropEventLike {\n readonly dataTransfer: DataTransferLike | null | undefined;\n preventDefault(): void;\n}\n\n/* ---------------------------------------------------------------- Options */\n\nexport interface PasteMachineOptions extends PasteReadOptions {\n /** Defaults to the browser Clipboard API adapter. */\n readonly adapter?: PasteAdapter;\n /** Return from `read` to `idle` after this many ms. `false` / `Infinity` / omitted = keep the result. */\n readonly resetAfterMs?: number | false;\n /**\n * Paste events: call `event.preventDefault()` when the event carried accepted\n * content, so the browser doesn't also insert it. Drop events: always call it,\n * so the browser doesn't open the dropped file. Default `true`.\n */\n readonly preventDefault?: boolean;\n /**\n * Max `retry()` calls after a failed clipboard read. Default 3. `0`\n * disables retry; `Infinity` allows unlimited retries.\n */\n readonly maxRetries?: number;\n readonly onPaste?: (result: PasteResult) => void;\n readonly onError?: (error: CopyError) => void;\n /**\n * `reset()` moved the machine back to `idle` from any other state. Not\n * called for the automatic return after `resetAfterMs`, or when already `idle`.\n */\n readonly onReset?: () => void;\n /**\n * A read in flight was cancelled before it settled: its `signal` aborted\n * and its result will not reach state or `onPaste` / `onError`. Fires\n * before `onReset` when `reset()` cancels a read.\n */\n readonly onCancel?: (reason: PasteCancelReason) => void;\n /** Clock injection for tests and deterministic environments. */\n readonly now?: () => number;\n}\n\n/** Options object, or a getter so hosts (like React) can supply the latest options. */\nexport type PasteMachineOptionsSource = PasteMachineOptions | (() => PasteMachineOptions);\n\nexport interface PasteMachine {\n readonly getSnapshot: () => PasteState;\n readonly subscribe: (listener: () => void) => () => void;\n /**\n * Reads the system clipboard via the adapter. Call it from a user gesture\n * (click, keypress). May show a permission prompt. Ignored while `reading`.\n */\n readonly paste: () => Promise<PasteOutcome>;\n /**\n * Handles a `paste` event (Ctrl/⌘+V). No permission prompt: the data is\n * already in the event. Supersedes any read in flight. Events without\n * accepted content are ignored and left untouched for the browser.\n */\n readonly pasteEvent: (event: PasteEventLike) => Promise<PasteOutcome>;\n /**\n * Handles a drag-and-drop `drop` event exactly like a paste event: same\n * `accept`, limits and image checks, `result.source === 'drop'`. Always calls\n * `event.preventDefault()` (unless `preventDefault: false`), so a rejected\n * file is not opened by the browser in place of the page.\n */\n readonly dropEvent: (event: PasteDropEventLike) => Promise<PasteOutcome>;\n /**\n * Re-reads the clipboard after a retryable failure (e.g. permission denied,\n * page not focused), up to `maxRetries`. Call it from a user gesture.\n * Paste-event failures can't be retried: their data is gone after dispatch.\n */\n readonly retry: () => Promise<PasteOutcome>;\n /** Back to `idle`. Discards any in-flight result and aborts its `signal`. */\n readonly reset: () => void;\n /**\n * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned\n * cleanup clears timers, drops in-flight results, aborts in-flight work and\n * unsticks `reading`.\n * Safe to call repeatedly (React StrictMode).\n */\n readonly connect: () => () => void;\n}\n\nexport const PASTE_IDLE_STATE: PasteIdleState = /* @__PURE__ */ Object.freeze({ status: 'idle' });\nconst PASTE_READING_STATE: PasteReadingState = /* @__PURE__ */ Object.freeze({ status: 'reading' });\nconst IGNORED_IN_FLIGHT: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'in-flight' });\nconst IGNORED_NO_CONTENT: PasteOutcome = /* @__PURE__ */ Object.freeze({\n status: 'ignored',\n reason: 'no-accepted-content',\n});\nconst IGNORED_NOTHING: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'nothing-to-retry' });\nconst IGNORED_NOT_RETRYABLE: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'not-retryable' });\nconst IGNORED_CANCELLED: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'cancelled' });\n\nfunction resolveResetDelay(value: number | false | undefined): number | null {\n if (value === undefined || value === false || value === Infinity || Number.isNaN(value)) return null;\n return Math.max(0, value);\n}\n\n/** Pure helper: can `retry()` do anything from this state? */\nexport function canRetryPasteState(state: PasteState, maxRetries?: number): boolean {\n return (\n state.status === 'error' &&\n state.source === 'clipboard' &&\n isRetryableError(state.error) &&\n state.retryCount < resolveMaxRetries(maxRetries)\n );\n}\n\nlet defaultAdapter: PasteAdapter | undefined;\nconst getDefaultAdapter = (): PasteAdapter => (defaultAdapter ??= createBrowserPasteAdapter());\n\n/** Framework-agnostic paste state machine. */\nexport function createPasteMachine(options: PasteMachineOptionsSource = {}): PasteMachine {\n const read = typeof options === 'function' ? options : (): PasteMachineOptions => options;\n const listeners = new Set<() => void>();\n let state: PasteState = PASTE_IDLE_STATE;\n let generation = 0;\n let resetTimer: ReturnType<typeof setTimeout> | undefined;\n const operations = createOperations();\n\n const now = (): number => (read().now ?? Date.now)();\n\n const setState = (next: PasteState): void => {\n if (next === state) return;\n state = next;\n for (const listener of Array.from(listeners)) listener();\n };\n\n const clearResetTimer = (): void => {\n if (resetTimer !== undefined) {\n clearTimeout(resetTimer);\n resetTimer = undefined;\n }\n };\n\n const scheduleReset = (readState: PasteReadState): void => {\n clearResetTimer();\n const delay = resolveResetDelay(read().resetAfterMs);\n if (delay === null) return;\n const remaining = Math.max(0, delay - (now() - readState.at));\n // Invariant: every transition out of `read` clears this timer, so it only ever fires while still in `readState`.\n resetTimer = setTimeout(() => {\n resetTimer = undefined;\n setState(PASTE_IDLE_STATE);\n }, remaining);\n };\n\n const settleError = (error: CopyError, source: PasteSource, retryCount: number): void => {\n setState({ status: 'error', error, source, retryCount });\n invoke(read().onError, error);\n };\n\n /** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */\n const run = (\n produce: (context: OperationContext) => Promise<PasteReadResult>,\n source: PasteSource,\n retryCount: number,\n ): Promise<PasteOutcome> => {\n clearResetTimer();\n const current = ++generation;\n const superseded = operations.abort();\n const context = operations.start();\n setState(PASTE_READING_STATE);\n if (superseded) invoke(read().onCancel, 'superseded');\n\n let pending: Promise<PasteReadResult>;\n try {\n pending = produce(context);\n } catch (cause) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified below\n pending = Promise.reject(cause);\n }\n\n // Completing inside the chain routes a malformed adapter result to the error path,\n // so `paste()` still never rejects and the machine never stays stuck in `reading`.\n return pending.then(completePasteResult).then(\n (result): PasteOutcome => {\n operations.end(context);\n if (current === generation) {\n const readState: PasteReadState = { status: 'read', result, at: now() };\n setState(readState);\n scheduleReset(readState);\n invoke(read().onPaste, result);\n }\n return { status: 'read', result };\n },\n (cause: unknown): PasteOutcome => {\n operations.end(context);\n // Work we aborted ourselves (superseded, reset, unmount) is not a failure to report.\n // Invariant: superseding an in-flight read always aborts it, so past\n // this line the read is still the current one.\n if (context.signal.aborted) return IGNORED_CANCELLED;\n const error = toCopyError(cause, 'read');\n settleError(error, source, retryCount);\n return { status: 'error', error };\n },\n );\n };\n\n const readClipboard = (retryCount: number): Promise<PasteOutcome> =>\n run(\n (context) => (read().adapter ?? getDefaultAdapter()).read(resolvePasteReadOptions(read()), context),\n 'clipboard',\n retryCount,\n );\n\n const paste = (): Promise<PasteOutcome> =>\n state.status === 'reading' ? Promise.resolve(IGNORED_IN_FLIGHT) : readClipboard(0);\n\n const retry = (): Promise<PasteOutcome> => {\n if (state.status !== 'error') return Promise.resolve(IGNORED_NOTHING);\n if (state.source !== 'clipboard' || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);\n if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {\n const error = createCopyError(\n 'max-retries-exceeded',\n `Paste failed after ${String(state.retryCount)} retries.`,\n state.error,\n );\n settleError(error, 'clipboard', state.retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n return readClipboard(state.retryCount + 1);\n };\n\n /** Shared by paste and drop events: their `DataTransfer` has the same shape and lifetime. */\n const transfer = (\n data: DataTransferLike | null | undefined,\n event: { preventDefault(): void },\n source: 'event' | 'drop',\n ): Promise<PasteOutcome> => {\n const current = read();\n // An unhandled drop makes the browser open the file in place of the page, so drops are always claimed.\n if (source === 'drop' && current.preventDefault !== false) event.preventDefault();\n if (!data) return Promise.resolve(IGNORED_NO_CONTENT);\n\n let resolved: ReturnType<typeof resolvePasteReadOptions>;\n try {\n resolved = resolvePasteReadOptions(current);\n } catch (cause) {\n // Transition straight to `error` without a ghost `reading` frame.\n // `run()` would momentarily set state to `reading` before resolving the\n // error, which observers would see as a spurious state transition.\n const error = toCopyError(cause, 'read');\n ++generation;\n const superseded = operations.abort();\n clearResetTimer();\n settleError(error, source, 0);\n if (superseded) invoke(current.onCancel, 'superseded');\n return Promise.resolve({ status: 'error', error });\n }\n\n // DataTransfer is only readable during dispatch: snapshot before anything async.\n const entries = snapshotDataTransfer(data, resolved);\n if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);\n if (source === 'event' && current.preventDefault !== false) event.preventDefault();\n\n return run(\n () => {\n enforcePasteLimits(entries, resolved);\n return finalizePaste(entries, source, resolved);\n },\n source,\n 0,\n );\n };\n\n const pasteEvent = (event: PasteEventLike): Promise<PasteOutcome> => transfer(event.clipboardData, event, 'event');\n const dropEvent = (event: PasteDropEventLike): Promise<PasteOutcome> => transfer(event.dataTransfer, event, 'drop');\n\n const reset = (): void => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n const wasIdle = state.status === 'idle';\n setState(PASTE_IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'reset');\n if (!wasIdle) invoke(read().onReset);\n };\n\n const connect = (): (() => void) => {\n if (state.status === 'read') scheduleReset(state);\n return () => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n if (state.status === 'reading') setState(PASTE_IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'disconnect');\n };\n };\n\n return {\n getSnapshot: () => state,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n paste,\n pasteEvent,\n dropEvent,\n retry,\n reset,\n connect,\n };\n}\n"],"mappings":";;;;;;;AAwBA,SAAgB,wBAAyC;CACvD,IAAI,SAAuC;CAC3C,OAAO;EACL,WAAW,WAAW;GACpB,MAAM,WAAW;GACjB,SAAS;GACT,IAAI,aAAa,QAAQ,aAAa,QAAQ,SAAS,QAAQ;EACjE;EACA,aAAa,WAAW;GACtB,IAAI,WAAW,QAAQ,SAAS;EAClC;EACA,iBAAiB;CACnB;AACF;;;;;;;AChCA,MAAa,sBAAsB;AAWnC,SAAgB,kBAAkB,OAAmC;CACnE,IAAI,UAAU,UAAU,OAAO;CAC/B,IAAI,UAAU,KAAA,KAAa,CAAC,OAAO,SAAS,KAAK,GAAG,OAAA;CACpD,OAAO,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC;AACtC;AAEA,SAAS,oBAAoB,OAAsB;CACjD,MAAM,QAAQ;CACd,IAAI,OAAO,MAAM,gBAAgB,YAC/B,MAAM,YAAY,KAAK;MAEvB,iBAAiB;EACf,MAAM;CACR,GAAG,CAAC;AAER;;AAGA,SAAgB,OAA+B,IAA2C,GAAG,MAAkB;CAC7G,IAAI,CAAC,IAAI;CACT,IAAI;EACF,GAAG,GAAG,IAAI;CACZ,SAAS,OAAO;EACd,oBAAoB,KAAK;CAC3B;AACF;;AAYA,SAAgB,mBAA+B;CAC7C,IAAI;CACJ,MAAM,cAAuB;EAC3B,IAAI,CAAC,YAAY,OAAO;EACxB,WAAW,MAAM;EACjB,aAAa,KAAA;EACb,OAAO;CACT;CACA,OAAO;EACL,aAAa;GACX,MAAM;GACN,aAAa,IAAI,gBAAgB;GACjC,OAAO,EAAE,QAAQ,WAAW,OAAO;EACrC;EACA,MAAM,YAAY;GAChB,IAAI,YAAY,WAAW,QAAQ,QAAQ,aAAa,KAAA;EAC1D;EACA;CACF;AACF;;;;;;;;;AChEA,SAAgB,YAAY,OAAgB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AS,gBAAgB;GACzD,IAAI,WAAW,OAAO,KAAK,CAAC,CAAC,UAAU,YAAY;EACrD;CACF;CAEA,OAAO;EACL,mBAAmB;EACnB,YAAY,aAAa;GACvB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"core-DmncxMt3.cjs","names":["isCopyFailure","createCopyError","IGNORED_IN_FLIGHT","IGNORED_NOTHING","IGNORED_NOT_RETRYABLE","IGNORED_CANCELLED","resolveResetDelay","isRetryableError","defaultAdapter","getDefaultAdapter","createBrowserClipboardAdapter","createCopyError","normalizePayload","validatePayload","toCopyError","nonEmpty","invalid","createCopyError","unsupported","isWebCustomFormat","createCopyError","isWebCustomFormat","CopyFailure","toCopyError","finalizePaste","collectClipboardItems","copyFailure","matchesMimePattern","isRetryableError","completePasteResult","toCopyError","resolvePasteReadOptions","createCopyError","snapshotDataTransfer","finalizePaste"],"sources":["../../src/core/copy-coordinator.ts","../../src/core/machine-shared.ts","../../src/core/source-error.ts","../../src/core/copy-machine.ts","../../src/core/copy-interceptor.ts","../../src/core/drag-copy.ts","../../src/core/paste-adapter.ts","../../src/core/paste-machine.ts"],"sourcesContent":["/**\n * A copy machine as seen by a coordinator. `release()` returns it from\n * `copied` to `idle`; it is a no-op in any other state.\n */\nexport interface CopyCoordinatorMember {\n readonly release: () => void;\n}\n\n/**\n * Makes a set of copy machines behave like one clipboard: when a member\n * succeeds, the member that previously showed \"Copied\" goes back to idle,\n * because the clipboard no longer holds its value.\n *\n * Failed copies never release anyone (the clipboard still holds the previous value).\n */\nexport interface CopyCoordinator {\n /** A member just reached `copied`. Releases the previous one. */\n readonly activate: (member: CopyCoordinatorMember) => void;\n /** A member left `copied` on its own (auto-reset, reset, unmount). */\n readonly deactivate: (member: CopyCoordinatorMember) => void;\n /** The member currently showing `copied`, if any. */\n readonly getActive: () => CopyCoordinatorMember | null;\n}\n\nexport function createCopyCoordinator(): CopyCoordinator {\n let active: CopyCoordinatorMember | null = null;\n return {\n activate: (member) => {\n const previous = active;\n active = member;\n if (previous !== null && previous !== member) previous.release();\n },\n deactivate: (member) => {\n if (active === member) active = null;\n },\n getActive: () => active,\n };\n}\n","/**\n * Internals shared by the copy and paste state machines. Kept in one module so\n * apps that use both don't ship two copies.\n */\n\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * Passed to adapters and lazy sources as their last argument. `signal` aborts\n * when the operation is superseded, `reset()`, or its host unmounts, so\n * expensive work (rasterising, decoding) can stop early.\n */\nexport interface OperationContext {\n readonly signal: AbortSignal;\n}\n\nexport function resolveMaxRetries(value: number | undefined): number {\n if (value === Infinity) return Infinity;\n if (value === undefined || !Number.isFinite(value)) return DEFAULT_MAX_RETRIES;\n return Math.max(0, Math.floor(value));\n}\n\nfunction reportCallbackError(error: unknown): void {\n const scope = globalThis as { reportError?: (error: unknown) => void };\n if (typeof scope.reportError === 'function') {\n scope.reportError(error);\n } else {\n setTimeout(() => {\n throw error;\n }, 0);\n }\n}\n\n/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */\nexport function invoke<Args extends unknown[]>(fn: ((...args: Args) => void) | undefined, ...args: Args): void {\n if (!fn) return;\n try {\n fn(...args);\n } catch (error) {\n reportCallbackError(error);\n }\n}\n\nexport interface Operations {\n /** Aborts the operation in flight (if any) and starts a new one. */\n readonly start: () => OperationContext;\n /** Marks `context` finished, so a later `abort()` never fires its signal. */\n readonly end: (context: OperationContext) => void;\n /** Cancels the operation in flight, if any. Returns whether one was cancelled. */\n readonly abort: () => boolean;\n}\n\n/** One cancellable operation at a time. Signals only fire while their operation is unfinished. */\nexport function createOperations(): Operations {\n let controller: AbortController | undefined;\n const abort = (): boolean => {\n if (!controller) return false;\n controller.abort();\n controller = undefined;\n return true;\n };\n return {\n start: () => {\n abort();\n controller = new AbortController();\n return { signal: controller.signal };\n },\n end: (context) => {\n if (controller?.signal === context.signal) controller = undefined;\n },\n abort,\n };\n}\n","import { createCopyError, isCopyFailure, type CopyError } from './errors';\n\n/**\n * The error for a user-supplied source (copy source, drag source, copy transform)\n * that threw. A thrown `CopyFailure` keeps its classification, so a helper such as\n * `tablePayload()` can report `too-large` instead of a generic `invalid-payload`.\n * Internal: not part of the public API.\n */\nexport function sourceError(cause: unknown, message: string): CopyError {\n return isCopyFailure(cause) ? cause.copyError : createCopyError('invalid-payload', message, cause);\n}\n","import { createBrowserClipboardAdapter, type ClipboardAdapter } from './clipboard-adapter';\nimport type { CopyCoordinator, CopyCoordinatorMember } from './copy-coordinator';\nimport { createCopyError, isRetryableError, toCopyError, type CopyError } from './errors';\nimport { createOperations, invoke, resolveMaxRetries } from './machine-shared';\nimport { normalizePayload, validatePayload, type CopyPayload, type CopySource } from './payload';\nimport { sourceError } from './source-error';\n\nexport { DEFAULT_MAX_RETRIES, resolveMaxRetries } from './machine-shared';\n\nexport const DEFAULT_RESET_AFTER_MS = 2000;\n\nexport interface IdleState {\n readonly status: 'idle';\n}\nexport interface CopyingState {\n readonly status: 'copying';\n readonly payload: CopyPayload;\n readonly retryCount: number;\n}\nexport interface CopiedState {\n readonly status: 'copied';\n readonly payload: CopyPayload;\n /** Epoch ms when the write resolved. */\n readonly at: number;\n}\nexport interface ErrorState {\n readonly status: 'error';\n /** `null` when the input itself could not be resolved. */\n readonly payload: CopyPayload | null;\n readonly error: CopyError;\n readonly retryCount: number;\n}\n\nexport type CopyState = IdleState | CopyingState | CopiedState | ErrorState;\nexport type CopyStatus = CopyState['status'];\n\n/**\n * `cancelled`: the copy was reset or its host unmounted before it finished,\n * so its work was aborted. Nothing to report to the user.\n */\nexport type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';\n\n/**\n * Why an in-flight copy was cancelled: `reset` (`reset()` was called) or\n * `disconnect` (its host disconnected, e.g. the React component unmounted).\n */\nexport type CopyCancelReason = 'reset' | 'disconnect';\n\n/** What `copy()`/`retry()` resolve to. They never reject. */\nexport type CopyOutcome =\n | { readonly status: 'copied'; readonly payload: CopyPayload }\n | { readonly status: 'error'; readonly error: CopyError }\n | { readonly status: 'ignored'; readonly reason: CopyIgnoredReason };\n\nexport interface CopyMachineOptions {\n /** Defaults to the browser Clipboard API adapter. */\n readonly adapter?: ClipboardAdapter;\n /** Time in `copied` before returning to `idle`. `false`/`Infinity` disables. Default 2000. */\n readonly resetAfterMs?: number | false;\n /**\n * Max `retry()` calls after the first failure. Default 3. `0` disables\n * retry; `Infinity` allows unlimited retries.\n */\n readonly maxRetries?: number;\n /**\n * Share \"Copied\" with other machines: only one member of a coordinator\n * shows `copied` at a time. `null` explicitly opts out (e.g. of a React `<CopyGroup>`).\n */\n readonly coordinator?: CopyCoordinator | null;\n readonly onCopy?: (payload: CopyPayload) => void;\n readonly onError?: (error: CopyError, payload: CopyPayload | null) => void;\n /**\n * `reset()` moved the machine back to `idle` from any other state. Not\n * called for the automatic return after `resetAfterMs`, for a `<CopyGroup>`\n * handing \"Copied\" to another member, or when already `idle`.\n */\n readonly onReset?: () => void;\n /**\n * A copy in flight was cancelled before it settled: its `signal` aborted\n * and its result will not reach state or `onCopy` / `onError`. Fires\n * before `onReset` when `reset()` cancels a copy.\n */\n readonly onCancel?: (reason: CopyCancelReason) => void;\n /** Clock injection for tests and deterministic environments. */\n readonly now?: () => number;\n}\n\n/** Options object, or a getter so hosts (like React) can supply the latest options. */\nexport type CopyMachineOptionsSource = CopyMachineOptions | (() => CopyMachineOptions);\n\nexport interface CopyMachine {\n readonly getSnapshot: () => CopyState;\n readonly subscribe: (listener: () => void) => () => void;\n readonly copy: (source: CopySource) => Promise<CopyOutcome>;\n readonly retry: () => Promise<CopyOutcome>;\n /** Back to `idle`. Discards any in-flight result and aborts its `signal`. */\n readonly reset: () => void;\n /**\n * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned\n * cleanup clears timers, drops in-flight results, aborts in-flight work and\n * unsticks `copying`.\n * Safe to call repeatedly (React StrictMode).\n */\n readonly connect: () => () => void;\n}\n\nexport const IDLE_STATE: IdleState = /* @__PURE__ */ Object.freeze({ status: 'idle' });\n\nconst IGNORED_IN_FLIGHT: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'in-flight' });\nconst IGNORED_NOTHING: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'nothing-to-retry' });\nconst IGNORED_NOT_RETRYABLE: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'not-retryable' });\nconst IGNORED_CANCELLED: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'cancelled' });\n\nfunction resolveResetDelay(value: number | false | undefined): number | null {\n if (value === false || value === Infinity) return null;\n if (value === undefined || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;\n return Math.max(0, value);\n}\n\n/** Pure helper: can `retry()` do anything from this state? */\nexport function canRetryState(state: CopyState, maxRetries?: number): boolean {\n return (\n state.status === 'error' &&\n state.payload !== null &&\n isRetryableError(state.error) &&\n state.retryCount < resolveMaxRetries(maxRetries)\n );\n}\n\nlet defaultAdapter: ClipboardAdapter | undefined;\nconst getDefaultAdapter = (): ClipboardAdapter => (defaultAdapter ??= createBrowserClipboardAdapter());\n\n/** Framework-agnostic copy state machine. */\nexport function createCopyMachine(options: CopyMachineOptionsSource = {}): CopyMachine {\n const read = typeof options === 'function' ? options : (): CopyMachineOptions => options;\n const listeners = new Set<() => void>();\n let state: CopyState = IDLE_STATE;\n let generation = 0;\n let resetTimer: ReturnType<typeof setTimeout> | undefined;\n const operations = createOperations();\n\n const now = (): number => (read().now ?? Date.now)();\n\n // The coordinator that saw this machine's last `copied`, so leaving it is reported to the same one.\n let joined: CopyCoordinator | null = null;\n\n const member: CopyCoordinatorMember = {\n release: () => {\n if (state.status === 'copied') {\n clearResetTimer();\n setState(IDLE_STATE);\n }\n },\n };\n\n const setState = (next: CopyState): void => {\n if (next === state) return;\n const previous = state;\n state = next;\n if (previous.status === 'copied' && next.status !== 'copied' && joined) {\n joined.deactivate(member);\n joined = null;\n }\n for (const listener of Array.from(listeners)) listener();\n };\n\n const joinCoordinator = (): void => {\n joined = read().coordinator ?? null;\n joined?.activate(member);\n };\n\n const clearResetTimer = (): void => {\n if (resetTimer !== undefined) {\n clearTimeout(resetTimer);\n resetTimer = undefined;\n }\n };\n\n const scheduleReset = (copied: CopiedState): void => {\n clearResetTimer();\n const delay = resolveResetDelay(read().resetAfterMs);\n if (delay === null) return;\n const remaining = Math.max(0, delay - (now() - copied.at));\n // Invariant: every transition out of `copied` clears this timer, so it only ever fires while still in `copied`.\n resetTimer = setTimeout(() => {\n resetTimer = undefined;\n setState(IDLE_STATE);\n }, remaining);\n };\n\n const settleError = (error: CopyError, payload: CopyPayload | null, retryCount: number): void => {\n setState({ status: 'error', payload, error, retryCount });\n invoke(read().onError, error, payload);\n };\n\n const run = (source: CopySource, retryCount: number): Promise<CopyOutcome> => {\n clearResetTimer();\n const current = ++generation;\n\n let payload: CopyPayload;\n try {\n const resolved = typeof source === 'function' ? source() : source;\n // T1: the source function must be synchronous — async sources break the\n // browser's transient user-activation window. Detect and reject a Promise\n // return rather than letting it propagate as a malformed payload (a\n // thenable is not a valid CopyInput, so validatePayload would catch it,\n // but a clear error message is more useful).\n // Cast to `unknown` first so the thenable check compiles without the\n // \"no overlap\" lint error (the TS type already narrows `resolved` to\n // `CopyInput`, which excludes thenables, but JS callers can still pass one).\n const resolvedUnknown: unknown = resolved;\n if (\n resolvedUnknown !== null &&\n typeof resolvedUnknown === 'object' &&\n typeof (resolvedUnknown as { then?: unknown }).then === 'function'\n ) {\n const error = createCopyError(\n 'invalid-payload',\n 'The copy source function must be synchronous. ' +\n 'Returning a Promise breaks the user-gesture window required for clipboard writes. ' +\n 'Generate your content before calling copy().',\n );\n settleError(error, null, retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n payload = normalizePayload(resolved);\n } catch (cause) {\n const error = sourceError(cause, 'The copy source function threw.');\n settleError(error, null, retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n\n const invalid = validatePayload(payload);\n if (invalid) {\n settleError(invalid, payload, retryCount);\n return Promise.resolve({ status: 'error', error: invalid });\n }\n\n setState({ status: 'copying', payload, retryCount });\n const context = operations.start();\n\n // The adapter is called synchronously: no await may precede it, or the\n // browser loses the transient user activation and rejects the write.\n let pending: Promise<void>;\n try {\n pending = (read().adapter ?? getDefaultAdapter()).write(payload, context);\n } catch (cause) {\n // Keep the raw reason: toCopyError() classifies it (DOMException names, CopyFailure brand).\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified by toCopyError()\n pending = Promise.reject(cause);\n }\n\n return pending.then(\n (): CopyOutcome => {\n operations.end(context);\n if (current === generation) {\n const copied: CopiedState = { status: 'copied', payload, at: now() };\n setState(copied);\n joinCoordinator();\n scheduleReset(copied);\n invoke(read().onCopy, payload);\n }\n return { status: 'copied', payload };\n },\n (cause: unknown): CopyOutcome => {\n operations.end(context);\n // Work we aborted ourselves (reset, unmount) is not a failure to report.\n // Invariant: superseding an in-flight copy always aborts it, so past\n // this line the copy is still the current one.\n if (context.signal.aborted) return IGNORED_CANCELLED;\n const error = toCopyError(cause);\n settleError(error, payload, retryCount);\n return { status: 'error', error };\n },\n );\n };\n\n const copy = (source: CopySource): Promise<CopyOutcome> =>\n state.status === 'copying' ? Promise.resolve(IGNORED_IN_FLIGHT) : run(source, 0);\n\n const retry = (): Promise<CopyOutcome> => {\n if (state.status !== 'error') return Promise.resolve(IGNORED_NOTHING);\n if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);\n\n if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {\n const error = createCopyError(\n 'max-retries-exceeded',\n `Copy failed after ${String(state.retryCount)} retries.`,\n state.error,\n );\n settleError(error, state.payload, state.retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n return run(state.payload, state.retryCount + 1);\n };\n\n const reset = (): void => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n const wasIdle = state.status === 'idle';\n setState(IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'reset');\n if (!wasIdle) invoke(read().onReset);\n };\n\n const connect = (): (() => void) => {\n if (state.status === 'copied') scheduleReset(state);\n return () => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n if (state.status === 'copying') setState(IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'disconnect');\n };\n };\n\n return {\n getSnapshot: () => state,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n copy,\n retry,\n reset,\n connect,\n };\n}\n","import { createCopyError, type CopyError } from './errors';\nimport { invoke } from './machine-shared';\nimport { isWebCustomFormat } from './mime';\nimport type { HtmlPayload, JsonPayload, TextPayload } from './payload';\nimport { sourceError } from './source-error';\n\n/**\n * Native copy interception: rewrite, redact or block what lands on the\n * clipboard when the user copies (Ctrl/Cmd+C, context menu) or cuts inside a\n * scope.\n *\n * Writes go through `event.clipboardData` synchronously, so no permission\n * prompt, no secure-context requirement, and it works in every browser. The\n * price is that only strings can be written, which the types enforce.\n *\n * Not a security boundary: users can still screenshot, use dev tools or\n * disable script. Treat redaction as a guard against accidents.\n */\n\nexport type InterceptedCopyKind = 'copy' | 'cut';\n\nexport const DEFAULT_INTERCEPTED_EVENTS: readonly InterceptedCopyKind[] = ['copy', 'cut'];\n\n/** The writable slice of `DataTransfer` during a `copy`/`cut` event. */\nexport interface ClipboardDataLike {\n setData(format: string, data: string): void;\n clearData?(format?: string): void;\n}\n\n/** Structural `ClipboardEvent`: DOM and React clipboard events both satisfy it. */\nexport interface CopyEventLike {\n readonly type: string;\n readonly target: EventTarget | null;\n readonly clipboardData: ClipboardDataLike | null;\n readonly defaultPrevented: boolean;\n preventDefault(): void;\n}\n\n/** What the user selected when they copied. */\nexport interface CopySelection {\n readonly kind: InterceptedCopyKind;\n /** What the browser would put on the clipboard as `text/plain`. */\n readonly text: string;\n /** Serialised HTML of the selection; `null` inside text inputs. */\n readonly html: string | null;\n /** A detached clone of the selected nodes, safe to mutate; `null` inside text inputs. */\n readonly fragment: DocumentFragment | null;\n /** The `<input>`/`<textarea>` the selection lives in, if any. */\n readonly field: HTMLInputElement | HTMLTextAreaElement | null;\n /** Whether a `cut` would remove the selection (form field or contenteditable). */\n readonly editable: boolean;\n}\n\n/**\n * A multi payload whose items are all strings; the only kind `setData` accepts.\n * Web custom formats (`web …`) are skipped: only the async Clipboard API writes them.\n */\nexport interface SyncMultiPayload {\n readonly kind: 'multi';\n readonly items: readonly { readonly mimeType: string; readonly data: string; readonly optional?: boolean }[];\n}\n\n/** Payloads writable synchronously during a copy event. Images need the async clipboard. */\nexport type SyncCopyPayload = TextPayload | HtmlPayload | JsonPayload | SyncMultiPayload;\n\n/**\n * What a transform returns:\n * - a string or payload: write that instead of the selection\n * - `false`: block the copy (nothing reaches the clipboard; a cut deletes nothing)\n * - `null` / `undefined`: leave the browser's default copy untouched\n *\n * Must be synchronous: the clipboard closes when the event handler returns.\n */\nexport type CopyInterceptDecision = string | SyncCopyPayload | false | null | undefined;\n\nexport type CopyInterceptTransform = (selection: CopySelection) => CopyInterceptDecision;\n\n/**\n * When the transform throws or returns something unwritable:\n * - `'block'` (default): nothing is copied. Safe for redaction.\n * - `'native'`: the browser's default copy proceeds unmodified.\n */\nexport type CopyInterceptFailureMode = 'block' | 'native';\n\nexport interface CopyInterceptOptions {\n readonly transform: CopyInterceptTransform;\n readonly failureMode?: CopyInterceptFailureMode;\n}\n\nexport type CopyInterceptPassReason =\n /** Not a `copy`/`cut` event. */\n | 'unsupported-event'\n /** Another handler already called `preventDefault()`. */\n | 'already-handled'\n /** Nothing readable was selected. */\n | 'no-selection'\n /** The transform returned `null`/`undefined`. */\n | 'declined';\n\nexport type CopyInterceptOutcome =\n | {\n readonly status: 'passed';\n readonly reason: CopyInterceptPassReason;\n readonly selection: CopySelection | null;\n }\n | {\n readonly status: 'written';\n readonly selection: CopySelection;\n readonly payload: SyncCopyPayload;\n /** For an editable `cut`: whether the selection was removed. Always `false` for `copy`. */\n readonly deleted: boolean;\n }\n | { readonly status: 'blocked'; readonly selection: CopySelection }\n | {\n readonly status: 'failed';\n readonly selection: CopySelection;\n readonly error: CopyError;\n /** What actually happened to the copy. */\n readonly fallback: CopyInterceptFailureMode;\n };\n\n/* ─────────────────────────────────────────────────────── selection reading */\n\ntype TextField = HTMLInputElement | HTMLTextAreaElement;\n\nfunction isNode(value: unknown): value is Node {\n return typeof value === 'object' && value !== null && typeof (value as Node).nodeType === 'number';\n}\n\ninterface FieldSelection {\n readonly field: TextField;\n readonly start: number;\n readonly end: number;\n}\n\nfunction readTextField(target: EventTarget | null): FieldSelection | null {\n if (!isNode(target) || target.nodeType !== 1) return null;\n const tag = (target as Element).tagName;\n if (tag !== 'INPUT' && tag !== 'TEXTAREA') return null;\n const field = target as TextField;\n try {\n // `null` (or a throw, in older engines) for input types without text selection.\n const { selectionStart: start, selectionEnd: end } = field;\n return typeof start === 'number' && typeof end === 'number' ? { field, start, end } : null;\n } catch {\n return null;\n }\n}\n\nfunction documentOf(target: EventTarget | null): Document | null {\n if (isNode(target)) return target.nodeType === 9 ? (target as Document) : target.ownerDocument;\n return typeof document === 'undefined' ? null : document;\n}\n\nfunction isEditableNode(node: Node): boolean {\n const element = node.nodeType === 1 ? (node as HTMLElement) : node.parentElement;\n return element?.isContentEditable === true;\n}\n\ninterface SelectedRanges {\n readonly selection: Selection;\n readonly ranges: readonly Range[];\n}\n\nfunction selectedRanges(doc: Document | null): SelectedRanges | null {\n const selection = doc?.getSelection();\n if (!selection || selection.isCollapsed) return null;\n const ranges: Range[] = [];\n for (let index = 0; index < selection.rangeCount; index += 1) ranges.push(selection.getRangeAt(index));\n return { selection, ranges };\n}\n\ninterface ReadSelection {\n readonly selection: CopySelection;\n readonly doc: Document;\n}\n\nfunction readSelection(event: CopyEventLike): ReadSelection | null {\n const kind: InterceptedCopyKind = event.type === 'cut' ? 'cut' : 'copy';\n const fieldSelection = readTextField(event.target);\n if (fieldSelection) {\n const { field, start, end } = fieldSelection;\n const text = field.value.slice(Math.min(start, end), Math.max(start, end));\n if (text.length === 0) return null;\n const editable = !field.readOnly && !field.disabled;\n return { selection: { kind, text, html: null, fragment: null, field, editable }, doc: field.ownerDocument };\n }\n\n const doc = documentOf(event.target);\n const selected = selectedRanges(doc);\n const first = selected?.ranges[0];\n if (!doc || !selected || !first) return null;\n // `Selection#toString` follows the rendered layout, like the browser's own copy;\n // `Range#toString` would leak source whitespace and hidden text.\n const text = selected.selection.toString();\n if (text.length === 0) return null;\n\n const container = doc.createElement('div');\n for (const range of selected.ranges) container.appendChild(range.cloneContents());\n const html = container.innerHTML;\n const fragment = doc.createDocumentFragment();\n while (container.firstChild) fragment.appendChild(container.firstChild);\n\n const editable = isEditableNode(first.startContainer);\n return { selection: { kind, text, html, fragment, field: null, editable }, doc };\n}\n\n/** Reads the selection behind a copy event, or `null` if nothing readable is selected. */\nexport function readCopySelection(event: CopyEventLike): CopySelection | null {\n const read = readSelection(event);\n return read ? read.selection : null;\n}\n\n/* ─────────────────────────────────────────────────────────────── writing */\n\ntype Entries = readonly (readonly [mimeType: string, data: string])[];\n\ntype Prepared =\n | { readonly ok: true; readonly payload: SyncCopyPayload; readonly entries: Entries }\n | { readonly ok: false; readonly error: CopyError };\n\nconst nonEmpty = (value: unknown): value is string => typeof value === 'string' && value.length > 0;\nconst invalid = (message: string, cause?: unknown): Prepared => ({\n ok: false,\n error: createCopyError('invalid-payload', message, cause),\n});\nconst unsupported = (message: string): Prepared => ({ ok: false, error: createCopyError('unsupported-format', message) });\n\n/**\n * Validates a decision and turns it into `[mimeType, data]` pairs. Kept\n * self-contained (no shared validator) so the interceptor stays small; the\n * checks still run for plain-JS callers the types can't protect.\n */\nfunction prepare(decision: string | SyncCopyPayload): Prepared {\n const candidate: unknown = typeof decision === 'string' ? { kind: 'text', value: decision } : decision;\n if (typeof candidate !== 'object' || candidate === null) {\n return invalid('Copy transforms must return a string, a payload, false, or nothing.');\n }\n if (typeof (candidate as { then?: unknown }).then === 'function') {\n return invalid('Copy transforms must be synchronous; the clipboard closes when the event ends.');\n }\n const payload = candidate as SyncCopyPayload;\n const fields = candidate as Record<string, unknown>;\n const ok = (entries: Entries): Prepared => ({ ok: true, payload, entries });\n\n switch (fields['kind']) {\n case 'text':\n return nonEmpty(fields['value']) ? ok([['text/plain', fields['value']]]) : invalid('Text payload must be a non-empty string.');\n case 'html':\n return nonEmpty(fields['html']) && nonEmpty(fields['text'])\n ? ok([['text/html', fields['html']], ['text/plain', fields['text']]])\n : invalid('HTML payload requires non-empty `html` and plain-text `text`.');\n case 'json': {\n const pretty = fields['pretty'];\n const indent = pretty === true ? 2 : typeof pretty === 'number' ? pretty : undefined;\n // Typed as `string`, but `undefined` for functions, symbols and undefined.\n let json: unknown;\n try {\n json = JSON.stringify(fields['value'], null, indent);\n } catch (cause) {\n return invalid('JSON payload could not be serialised (circular reference or BigInt?).', cause);\n }\n return typeof json === 'string' ? ok([['text/plain', json]]) : invalid('JSON payload serialised to nothing.');\n }\n case 'multi': {\n const items = fields['items'];\n if (!Array.isArray(items) || items.length === 0) return invalid('Multi payload requires at least one item.');\n const entries: (readonly [string, string])[] = [];\n for (const item of items as unknown[]) {\n const { mimeType, data } = (item ?? {}) as { mimeType?: unknown; data?: unknown };\n if (!nonEmpty(mimeType) || entries.some(([seen]) => seen === mimeType)) {\n return invalid('Every multi item needs a unique, non-empty `mimeType`.');\n }\n if (typeof data !== 'string') return unsupported(`Multi item \"${mimeType}\" must be a string during a copy event.`);\n entries.push([mimeType, data]);\n }\n const writable = entries.filter(([mimeType]) => !isWebCustomFormat(mimeType));\n return writable.length > 0\n ? ok(writable)\n : unsupported('Web custom formats need the async Clipboard API (useCopy).');\n }\n default:\n return unsupported(`\"${String(fields['kind'])}\" payloads cannot be written during a copy event; use useCopy() for images.`);\n }\n}\n\n/** Deletes the selection the way a native cut would (keeps undo history, fires `input`). */\nfunction deleteSelection(doc: Document): boolean {\n const legacy = doc as unknown as { execCommand?: (command: string) => boolean };\n try {\n return legacy.execCommand?.('delete') === true;\n } catch {\n return false;\n }\n}\n\n/**\n * Applies a transform to one `copy`/`cut` event. Use directly from an\n * `onCopy` handler, or let {@link registerCopyInterceptor} scope it.\n */\nexport function interceptCopyEvent(event: CopyEventLike, options: CopyInterceptOptions): CopyInterceptOutcome {\n if (event.type !== 'copy' && event.type !== 'cut') {\n return { status: 'passed', reason: 'unsupported-event', selection: null };\n }\n if (event.defaultPrevented) return { status: 'passed', reason: 'already-handled', selection: null };\n\n const read = readSelection(event);\n if (!read) return { status: 'passed', reason: 'no-selection', selection: null };\n const { selection, doc } = read;\n\n const fail = (error: CopyError): CopyInterceptOutcome => {\n const fallback = options.failureMode ?? 'block';\n if (fallback === 'block') event.preventDefault();\n return { status: 'failed', selection, error, fallback };\n };\n\n let decision: CopyInterceptDecision;\n try {\n decision = options.transform(selection);\n } catch (cause) {\n return fail(sourceError(cause, 'The copy transform threw.'));\n }\n\n if (decision === null || decision === undefined) return { status: 'passed', reason: 'declined', selection };\n if (decision === false) {\n event.preventDefault();\n return { status: 'blocked', selection };\n }\n\n const prepared = prepare(decision);\n if (!prepared.ok) return fail(prepared.error);\n\n const data = event.clipboardData;\n if (!data) return fail(createCopyError('unsupported', 'This browser exposes no clipboardData on copy events.'));\n\n // From here the browser's default is gone: a failure can only end in `block`.\n event.preventDefault();\n try {\n for (const [mimeType, value] of prepared.entries) data.setData(mimeType, value);\n } catch (cause) {\n try {\n data.clearData?.();\n } catch {\n // Best effort: a half-written clipboard is still better reported than hidden.\n }\n const error = createCopyError('unknown', 'The browser rejected the clipboard write.', cause);\n return { status: 'failed', selection, error, fallback: 'block' };\n }\n\n const deleted = selection.kind === 'cut' && selection.editable && deleteSelection(doc);\n return { status: 'written', selection, payload: prepared.payload, deleted };\n}\n\n/* ────────────────────────────────────────────────────────────── scoping */\n\nexport interface CopyInterceptorOptions extends CopyInterceptOptions {\n /**\n * When one selection touches several scopes, exactly one handles it: the\n * highest `priority`, then the innermost, then the first in the document.\n * The winner sees the *whole* selection. Give redaction scopes a higher\n * priority so text copied across them is always masked. Default `0`.\n */\n readonly priority?: number;\n /** Which events to intercept. Default: both `copy` and `cut`. */\n readonly events?: readonly InterceptedCopyKind[];\n /** Every outcome for selections inside this scope, including `passed`. */\n readonly onIntercept?: (outcome: CopyInterceptOutcome) => void;\n /** Called when the transform failed; the outcome's `fallback` says what happened to the copy. */\n readonly onError?: (error: CopyError) => void;\n}\n\ninterface Scope {\n readonly root: Element;\n readonly read: () => CopyInterceptorOptions;\n}\n\ninterface Registry {\n readonly scopes: Set<Scope>;\n readonly listener: (event: Event) => void;\n}\n\nconst registries = /* @__PURE__ */ new WeakMap<Document, Registry>();\n\nfunction touches(root: Element, event: CopyEventLike): boolean {\n const fieldSelection = readTextField(event.target);\n if (fieldSelection) return root.contains(fieldSelection.field);\n const selected = selectedRanges(root.ownerDocument);\n return selected !== null && selected.ranges.some((range) => range.intersectsNode(root));\n}\n\nconst priorityOf = (scope: Scope): number => scope.read().priority ?? 0;\n\n/**\n * Highest `priority` first; then the innermost scope; then document order;\n * then registration order (same root). A total order, so the result never\n * depends on effect timing.\n */\nfunction compareScopes(a: Scope, b: Scope): number {\n const byPriority = priorityOf(b) - priorityOf(a);\n if (byPriority !== 0) return byPriority;\n const position = a.root.compareDocumentPosition(b.root);\n if (position === 0) return 0;\n if (position & 16) return 1; // b is inside a: b first\n if (position & 8) return -1; // b contains a: a first\n return position & 4 ? -1 : 1; // b follows a: a first\n}\n\nfunction dispatch(registry: Registry, event: CopyEventLike): void {\n if (event.defaultPrevented) return;\n const kind = event.type as InterceptedCopyKind;\n const candidates = [...registry.scopes].filter(\n (scope) => (scope.read().events ?? DEFAULT_INTERCEPTED_EVENTS).includes(kind) && touches(scope.root, event),\n );\n const [scope] = candidates.sort(compareScopes);\n if (!scope) return;\n\n const options = scope.read();\n const outcome = interceptCopyEvent(event, options);\n invoke(options.onIntercept, outcome);\n if (outcome.status === 'failed') invoke(options.onError, outcome.error);\n}\n\n/**\n * Intercepts native copies and cuts whose selection touches `root`. Returns\n * an unsubscribe function. Pass a getter to always read the latest options.\n *\n * One listener per document serves every scope, so overlapping scopes\n * resolve deterministically (see `priority`) regardless of registration order.\n * Handlers that call `preventDefault()` first (e.g. a React `onCopy`) win.\n */\nexport function registerCopyInterceptor(\n root: Element,\n options: CopyInterceptorOptions | (() => CopyInterceptorOptions),\n): () => void {\n const doc = root.ownerDocument;\n let registry = registries.get(doc);\n if (!registry) {\n const scopes = new Set<Scope>();\n const created: Registry = {\n scopes,\n listener: (event) => {\n dispatch(created, event as unknown as CopyEventLike);\n },\n };\n registry = created;\n registries.set(doc, created);\n doc.addEventListener('copy', created.listener);\n doc.addEventListener('cut', created.listener);\n }\n\n const scope: Scope = { root, read: typeof options === 'function' ? options : () => options };\n registry.scopes.add(scope);\n const active = registry;\n\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n active.scopes.delete(scope);\n if (active.scopes.size === 0) {\n doc.removeEventListener('copy', active.listener);\n doc.removeEventListener('cut', active.listener);\n registries.delete(doc);\n }\n };\n}\n","/**\n * Drag-to-copy: populate `DataTransfer` when the user starts dragging an\n * element, so whatever they drop it into receives structured data — plain text,\n * HTML, JSON, or multiple MIME types — instead of the browser's default\n * text-extraction of the dragged DOM.\n *\n * No Clipboard API, no permission prompt, works in every browser that supports\n * HTML5 drag-and-drop (all modern browsers and IE11+).\n */\n\nimport { invoke } from './machine-shared';\nimport { createCopyError, type CopyError } from './errors';\nimport { isWebCustomFormat } from './mime';\nimport type { HtmlPayload, JsonPayload, TextPayload } from './payload';\nimport { sourceError } from './source-error';\n\n/* ─────────────────────────────────────────────────────────────────── types */\n\n/**\n * The `effectAllowed` a drag operation advertises. Controls which cursor the\n * browser shows and which `dropEffect` the drop target may request.\n *\n * - `'copy'` (default): dragging produces a copy of the data.\n * - `'move'`: dragging removes the source after a drop (the app must do this).\n * - `'link'`: dragging creates a link/reference.\n * - `'copyMove'` / `'copyLink'` / `'linkMove'` / `'all'`: combinations.\n * - `'none'`: the drag is not droppable anywhere.\n * - `'uninitialized'`: browser default (same as `'all'` in most cases).\n */\nexport type DragEffectAllowed =\n | 'copy'\n | 'move'\n | 'link'\n | 'copyMove'\n | 'copyLink'\n | 'linkMove'\n | 'all'\n | 'none'\n | 'uninitialized';\n\n/** What is put into `DataTransfer` when a drag starts. */\nexport interface DragCopyItem {\n /** Web custom formats (`web …`) are skipped: only the async Clipboard API writes them. */\n readonly mimeType: string;\n readonly data: string;\n /** Accepted for parity with `MultiPayloadItem`; every non-web item can be written to a drag. */\n readonly optional?: boolean;\n}\n\n/**\n * A multi-format drag payload — strings only (DataTransfer only accepts strings).\n * Mirrors `SyncCopyPayload` from copy-interceptor but scoped to drag.\n */\nexport type DragCopyPayload = TextPayload | HtmlPayload | JsonPayload | DragMultiPayload;\n\nexport interface DragMultiPayload {\n readonly kind: 'multi';\n readonly items: readonly DragCopyItem[];\n}\n\n/**\n * What the source getter returns:\n * - a string: written as `text/plain`.\n * - a `DragCopyPayload`: written according to its `kind`.\n * - `false`: cancels the drag (`preventDefault()` on `dragstart`).\n * - `null` / `undefined`: leaves the browser's default drag data untouched.\n */\nexport type DragCopyDecision = string | DragCopyPayload | false | null | undefined;\n\n/** Called once when the user begins dragging the element. Must be synchronous. */\nexport type DragCopySource = (event: DragStartEventLike) => DragCopyDecision;\n\n/** Structural `DragEvent`: DOM and React drag events both satisfy it. */\nexport interface DragStartEventLike {\n readonly type: string;\n readonly dataTransfer: DataTransferLike | null;\n readonly defaultPrevented: boolean;\n preventDefault(): void;\n}\n\n/** The writable face of `DataTransfer`. */\nexport interface DataTransferLike {\n effectAllowed: string;\n setData(format: string, data: string): void;\n clearData?(format?: string): void;\n}\n\nexport type DragCopyStatus =\n /** No drag has started yet, or it was cancelled / never had source data. */\n | 'idle'\n /** The element is being dragged and data is on the DataTransfer. */\n | 'dragging'\n /** The drag ended (dropped or abandoned). */\n | 'done';\n\nexport type DragCopyPassReason =\n /** Source returned `null`/`undefined`. */\n | 'declined'\n /** `DataTransfer` is not present on this event. */\n | 'no-transfer'\n /** Source returned `false`. */\n | 'cancelled';\n\nexport type DragCopyOutcome =\n | { readonly status: 'written'; readonly payload: DragCopyPayload }\n | { readonly status: 'passed'; readonly reason: DragCopyPassReason }\n | { readonly status: 'failed'; readonly error: CopyError };\n\nexport interface DragCopyState {\n readonly status: DragCopyStatus;\n /** The last `dragstart` outcome; `null` before the first drag. */\n readonly outcome: DragCopyOutcome | null;\n}\n\nexport interface DragCopyOptions {\n /**\n * Returns the data to put in the drag. Called synchronously on `dragstart`.\n * Return a string (shorthand for `{ kind: 'text' }`), a payload object,\n * `false` to cancel the drag, or `null`/`undefined` to pass through.\n */\n readonly source: DragCopySource;\n /**\n * `effectAllowed` advertised on the drag. Default `'copy'`.\n * Setting `'move'` signals to drop targets that the source will be removed.\n */\n readonly effectAllowed?: DragEffectAllowed;\n /**\n * Called each time a drag starts or ends, with the latest outcome and status.\n * Stable across re-renders when written as a class method or via `useRef`.\n */\n readonly onDrag?: (state: DragCopyState) => void;\n /** Called when preparing the drag payload fails. */\n readonly onError?: (error: CopyError) => void;\n}\n\n/* ─────────────────────────────────────────────────────────── validation */\n\nconst nonEmpty = (value: unknown): value is string =>\n typeof value === 'string' && value.length > 0;\n\ntype PrepareFail = { readonly ok: false; readonly error: CopyError };\ntype PrepareOk = { readonly ok: true; readonly payload: DragCopyPayload; readonly items: readonly DragCopyItem[] };\ntype Prepared = PrepareOk | PrepareFail;\n\nconst invalid = (message: string, cause?: unknown): PrepareFail => ({\n ok: false,\n error: createCopyError('invalid-payload', message, cause),\n});\n\nconst unsupported = (message: string): PrepareFail => ({\n ok: false,\n error: createCopyError('unsupported-format', message),\n});\n\nfunction prepareDragDecision(decision: string | DragCopyPayload): Prepared {\n const candidate: unknown =\n typeof decision === 'string' ? { kind: 'text', value: decision } : decision;\n\n if (typeof candidate !== 'object' || candidate === null) {\n return invalid('Drag source must return a string, a payload, false, or nothing.');\n }\n if (typeof (candidate as { then?: unknown }).then === 'function') {\n return invalid('Drag sources must be synchronous; DataTransfer closes when dragstart returns.');\n }\n\n const payload = candidate as DragCopyPayload;\n const fields = candidate as Record<string, unknown>;\n const ok = (items: readonly DragCopyItem[]): PrepareOk => ({ ok: true, payload, items });\n\n switch (fields['kind']) {\n case 'text':\n return nonEmpty(fields['value'])\n ? ok([{ mimeType: 'text/plain', data: fields['value'] }])\n : invalid('Text payload must be a non-empty string.');\n\n case 'html':\n return nonEmpty(fields['html']) && nonEmpty(fields['text'])\n ? ok([\n { mimeType: 'text/html', data: fields['html'] },\n { mimeType: 'text/plain', data: fields['text'] },\n ])\n : invalid('HTML payload requires non-empty `html` and `text`.');\n\n case 'json': {\n const pretty = fields['pretty'];\n const indent =\n pretty === true ? 2 : typeof pretty === 'number' ? pretty : undefined;\n let json: unknown;\n try {\n json = JSON.stringify(fields['value'], null, indent);\n } catch (cause) {\n return invalid(\n 'JSON payload could not be serialised (circular reference or BigInt?).',\n cause,\n );\n }\n return typeof json === 'string'\n ? ok([{ mimeType: 'text/plain', data: json }])\n : invalid('JSON payload serialised to nothing.');\n }\n\n case 'multi': {\n const items = fields['items'];\n if (!Array.isArray(items) || items.length === 0) {\n return invalid('Multi payload requires at least one item.');\n }\n const out: DragCopyItem[] = [];\n for (const item of items as unknown[]) {\n const { mimeType, data } = (item ?? {}) as {\n mimeType?: unknown;\n data?: unknown;\n };\n if (!nonEmpty(mimeType) || out.some((i) => i.mimeType === mimeType)) {\n return invalid('Every multi item needs a unique, non-empty `mimeType`.');\n }\n if (typeof data !== 'string') {\n return unsupported(\n `Multi item \"${mimeType}\" must be a string; DataTransfer does not accept Blobs.`,\n );\n }\n out.push({ mimeType, data });\n }\n const writable = out.filter((item) => !isWebCustomFormat(item.mimeType));\n return writable.length > 0\n ? ok(writable)\n : unsupported('Web custom formats need the async Clipboard API (useCopy).');\n }\n\n default:\n return unsupported(\n `\"${String(fields['kind'])}\" payloads cannot be used for drag-copy; use useCopy() for images.`,\n );\n }\n}\n\n/* ─────────────────────────────────────────────────────── applyDragCopy */\n\n/**\n * Populates a `dragstart` event's `DataTransfer` with the given payload.\n * Use this from a raw `dragstart` handler or a React `onDragStart` prop.\n * Returns the outcome so you can inspect what happened.\n */\nexport function applyDragCopy(\n event: DragStartEventLike,\n options: DragCopyOptions,\n): DragCopyOutcome {\n if (event.defaultPrevented) {\n return { status: 'passed', reason: 'declined' };\n }\n\n let decision: DragCopyDecision;\n try {\n decision = options.source(event);\n } catch (cause) {\n const error = sourceError(cause, 'The drag source threw.');\n return { status: 'failed', error };\n }\n\n if (decision === null || decision === undefined) {\n return { status: 'passed', reason: 'declined' };\n }\n\n if (decision === false) {\n event.preventDefault();\n return { status: 'passed', reason: 'cancelled' };\n }\n\n const transfer = event.dataTransfer;\n if (!transfer) {\n return { status: 'passed', reason: 'no-transfer' };\n }\n\n const prepared = prepareDragDecision(decision);\n if (!prepared.ok) {\n return { status: 'failed', error: prepared.error };\n }\n\n try {\n transfer.effectAllowed = options.effectAllowed ?? 'copy';\n for (const { mimeType, data } of prepared.items) {\n transfer.setData(mimeType, data);\n }\n } catch (cause) {\n try {\n transfer.clearData?.();\n } catch {\n // Best effort: report the original error, not a clearData failure.\n }\n const error = createCopyError(\n 'unknown',\n 'The browser rejected the DataTransfer write.',\n cause,\n );\n return { status: 'failed', error };\n }\n\n return { status: 'written', payload: prepared.payload };\n}\n\n/* ─────────────────────────────────────────────────── registerDragCopy */\n\nexport interface RegisterDragCopyResult {\n /** Unsubscribes all listeners. Idempotent. */\n readonly unsubscribe: () => void;\n}\n\n/**\n * Attaches `dragstart` and `dragend` listeners to `element`, calling\n * `applyDragCopy` on every drag start. Returns an object with an\n * `unsubscribe` function.\n *\n * Pass an options getter so the latest options are always used without\n * re-registering — safe to pass an inline object from a React render.\n *\n * ```ts\n * const { unsubscribe } = registerDragCopy(el, () => ({\n * source: () => `${title}\\n${url}`,\n * }));\n * ```\n */\nexport function registerDragCopy(\n element: HTMLElement,\n options: DragCopyOptions | (() => DragCopyOptions),\n): RegisterDragCopyResult {\n const read = typeof options === 'function' ? options : (): DragCopyOptions => options;\n\n let unsubscribed = false;\n let currentOutcome: DragCopyOutcome | null = null;\n\n function onDragStart(raw: Event): void {\n const event = raw as DragEvent;\n const opts = read();\n\n const outcome = applyDragCopy(\n {\n type: event.type,\n dataTransfer: event.dataTransfer,\n get defaultPrevented() {\n return event.defaultPrevented;\n },\n preventDefault: () => { event.preventDefault(); },\n },\n opts,\n );\n\n currentOutcome = outcome;\n\n const state: DragCopyState = { status: 'dragging', outcome };\n if (outcome.status === 'failed') invoke(opts.onError, outcome.error);\n invoke(opts.onDrag, state);\n }\n\n function onDragEnd(): void {\n const opts = read();\n const state: DragCopyState = { status: 'done', outcome: currentOutcome };\n invoke(opts.onDrag, state);\n currentOutcome = null;\n }\n\n element.setAttribute('draggable', 'true');\n element.addEventListener('dragstart', onDragStart);\n element.addEventListener('dragend', onDragEnd);\n\n return {\n unsubscribe(): void {\n if (unsubscribed) return;\n unsubscribed = true;\n element.removeEventListener('dragstart', onDragStart);\n element.removeEventListener('dragend', onDragEnd);\n element.removeAttribute('draggable');\n },\n };\n}\n","import { CopyFailure, copyFailure, toCopyError } from './errors';\nimport type { OperationContext } from './machine-shared';\nimport { matchesMimePattern } from './mime';\nimport {\n collectClipboardItems,\n enforcePasteLimits,\n finalizePaste,\n type ClipboardItemLike,\n type PasteEntry,\n type PasteReadResult,\n type ResolvedPasteReadOptions,\n} from './paste-reader';\n\n/** Minimal structural view of `navigator.clipboard` for reading. */\nexport interface PasteClipboardLike {\n read?(): Promise<readonly ClipboardItemLike[]>;\n readText?(): Promise<string>;\n}\n\nexport interface PasteEnvironment {\n readonly isSecureContext?: boolean;\n readonly navigator?: { readonly clipboard?: PasteClipboardLike | undefined } | undefined;\n}\n\n/**\n * Reads the system clipboard. Implement it for Electron, a native bridge or tests.\n *\n * Contract: call the platform API synchronously (before any `await`) so the\n * browser still sees the user gesture, and reject with a `CopyFailure`.\n * `context.signal` aborts when the read is superseded, reset, or its host\n * unmounts; honour it to stop decoding early.\n */\nexport interface PasteAdapter {\n read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteReadResult>;\n}\n\nexport interface BrowserPasteAdapterOptions {\n /** Defaults to `window`, read lazily at paste time (SSR-safe). */\n readonly getEnvironment?: () => PasteEnvironment | undefined;\n}\n\nfunction defaultEnvironment(): PasteEnvironment | undefined {\n return typeof window === 'undefined' ? undefined : window;\n}\n\ntype ClipboardWithRead = PasteClipboardLike & Required<Pick<PasteClipboardLike, 'read'>>;\ntype ClipboardWithReadText = PasteClipboardLike & Required<Pick<PasteClipboardLike, 'readText'>>;\n\nconst canRead = (clipboard: PasteClipboardLike): clipboard is ClipboardWithRead => typeof clipboard.read === 'function';\nconst canReadText = (clipboard: PasteClipboardLike): clipboard is ClipboardWithReadText =>\n typeof clipboard.readText === 'function';\n\nasync function readPlainText(clipboard: ClipboardWithReadText, options: ResolvedPasteReadOptions): Promise<PasteReadResult> {\n let text: string;\n try {\n text = await clipboard.readText();\n } catch (cause) {\n throw new CopyFailure(toCopyError(cause, 'read'));\n }\n const entries: PasteEntry[] = text.length > 0 ? [{ type: 'text/plain', data: text, file: false }] : [];\n enforcePasteLimits(entries, options);\n return finalizePaste(entries, 'clipboard', options);\n}\n\nasync function readRich(\n clipboard: ClipboardWithRead,\n options: ResolvedPasteReadOptions,\n signal: AbortSignal | undefined,\n): Promise<PasteReadResult> {\n let items: readonly ClipboardItemLike[];\n try {\n items = await clipboard.read();\n } catch (cause) {\n throw new CopyFailure(toCopyError(cause, 'read'));\n }\n const entries = await collectClipboardItems(items, options, signal);\n return finalizePaste(entries, 'clipboard', options);\n}\n\nfunction readFromClipboard(\n env: PasteEnvironment | undefined,\n options: ResolvedPasteReadOptions,\n signal: AbortSignal | undefined,\n): Promise<PasteReadResult> {\n if (!env) throw copyFailure('unsupported', 'No browser environment: the clipboard only exists in the browser.');\n if (env.isSecureContext === false) {\n throw copyFailure('insecure-context', 'The Clipboard API requires a secure context (HTTPS or localhost).');\n }\n const clipboard = env.navigator?.clipboard;\n if (!clipboard) throw copyFailure('unsupported', 'navigator.clipboard is not available in this browser.');\n\n const plainOnly = options.accept.every((pattern) => pattern === 'text/plain');\n const acceptsPlain = options.accept.some((pattern) => matchesMimePattern('text/plain', pattern));\n\n // readText() has the widest support and the narrowest permission prompt: prefer it for plain text.\n if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options, signal);\n if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);\n throw canReadText(clipboard)\n ? copyFailure('unsupported-format', 'Reading non-text clipboard content requires navigator.clipboard.read().')\n : copyFailure('unsupported', 'This browser cannot read the clipboard.');\n}\n\n/** The default paste adapter: async Clipboard API with feature detection and honest errors. */\nexport function createBrowserPasteAdapter(options: BrowserPasteAdapterOptions = {}): PasteAdapter {\n const getEnvironment = options.getEnvironment ?? defaultEnvironment;\n return {\n read: (resolved, context) => {\n try {\n return readFromClipboard(getEnvironment(), resolved, context?.signal);\n } catch (cause) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- always a CopyFailure\n return Promise.reject(cause);\n }\n },\n };\n}\n","import { createCopyError, isRetryableError, toCopyError, type CopyError } from './errors';\nimport { createOperations, invoke, resolveMaxRetries, type OperationContext } from './machine-shared';\nimport { createBrowserPasteAdapter, type PasteAdapter } from './paste-adapter';\nimport {\n completePasteResult,\n enforcePasteLimits,\n finalizePaste,\n resolvePasteReadOptions,\n snapshotDataTransfer,\n type DataTransferLike,\n type PasteReadOptions,\n type PasteReadResult,\n type PasteResult,\n type PasteSource,\n} from './paste-reader';\n\n/* ------------------------------------------------------------------ State */\n\nexport interface PasteIdleState {\n readonly status: 'idle';\n}\nexport interface PasteReadingState {\n readonly status: 'reading';\n}\nexport interface PasteReadState {\n readonly status: 'read';\n readonly result: PasteResult;\n /** Epoch ms when the read resolved. */\n readonly at: number;\n}\nexport interface PasteErrorState {\n readonly status: 'error';\n readonly error: CopyError;\n /** Where the failed read came from. Only `'clipboard'` reads can be retried. */\n readonly source: PasteSource;\n /** `retry()` calls made since the last fresh `paste()`. */\n readonly retryCount: number;\n}\n\nexport type PasteState = PasteIdleState | PasteReadingState | PasteReadState | PasteErrorState;\nexport type PasteStatus = PasteState['status'];\n\n/**\n * `cancelled`: the read was superseded, reset, or its host unmounted before it\n * finished, so its work was aborted. Nothing to report to the user.\n */\nexport type PasteIgnoredReason = 'in-flight' | 'no-accepted-content' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';\n\n/**\n * Why an in-flight read was cancelled: `reset` (`reset()` was called),\n * `disconnect` (its host disconnected, e.g. the React component unmounted) or\n * `superseded` (a paste or drop event arrived while a read was pending).\n */\nexport type PasteCancelReason = 'reset' | 'disconnect' | 'superseded';\n\n/** What `paste()` / `pasteEvent()` / `dropEvent()` / `retry()` resolve to. They never reject. */\nexport type PasteOutcome =\n | { readonly status: 'read'; readonly result: PasteResult }\n | { readonly status: 'error'; readonly error: CopyError }\n | { readonly status: 'ignored'; readonly reason: PasteIgnoredReason };\n\n/** Structural view of a DOM / React `paste` event. */\nexport interface PasteEventLike {\n readonly clipboardData: DataTransferLike | null | undefined;\n preventDefault(): void;\n}\n\n/** Structural view of a DOM / React `drop` event. */\nexport interface PasteDropEventLike {\n readonly dataTransfer: DataTransferLike | null | undefined;\n preventDefault(): void;\n}\n\n/* ---------------------------------------------------------------- Options */\n\nexport interface PasteMachineOptions extends PasteReadOptions {\n /** Defaults to the browser Clipboard API adapter. */\n readonly adapter?: PasteAdapter;\n /** Return from `read` to `idle` after this many ms. `false` / `Infinity` / omitted = keep the result. */\n readonly resetAfterMs?: number | false;\n /**\n * Paste events: call `event.preventDefault()` when the event carried accepted\n * content, so the browser doesn't also insert it. Drop events: always call it,\n * so the browser doesn't open the dropped file. Default `true`.\n */\n readonly preventDefault?: boolean;\n /**\n * Max `retry()` calls after a failed clipboard read. Default 3. `0`\n * disables retry; `Infinity` allows unlimited retries.\n */\n readonly maxRetries?: number;\n readonly onPaste?: (result: PasteResult) => void;\n readonly onError?: (error: CopyError) => void;\n /**\n * `reset()` moved the machine back to `idle` from any other state. Not\n * called for the automatic return after `resetAfterMs`, or when already `idle`.\n */\n readonly onReset?: () => void;\n /**\n * A read in flight was cancelled before it settled: its `signal` aborted\n * and its result will not reach state or `onPaste` / `onError`. Fires\n * before `onReset` when `reset()` cancels a read.\n */\n readonly onCancel?: (reason: PasteCancelReason) => void;\n /** Clock injection for tests and deterministic environments. */\n readonly now?: () => number;\n}\n\n/** Options object, or a getter so hosts (like React) can supply the latest options. */\nexport type PasteMachineOptionsSource = PasteMachineOptions | (() => PasteMachineOptions);\n\nexport interface PasteMachine {\n readonly getSnapshot: () => PasteState;\n readonly subscribe: (listener: () => void) => () => void;\n /**\n * Reads the system clipboard via the adapter. Call it from a user gesture\n * (click, keypress). May show a permission prompt. Ignored while `reading`.\n */\n readonly paste: () => Promise<PasteOutcome>;\n /**\n * Handles a `paste` event (Ctrl/⌘+V). No permission prompt: the data is\n * already in the event. Supersedes any read in flight. Events without\n * accepted content are ignored and left untouched for the browser.\n */\n readonly pasteEvent: (event: PasteEventLike) => Promise<PasteOutcome>;\n /**\n * Handles a drag-and-drop `drop` event exactly like a paste event: same\n * `accept`, limits and image checks, `result.source === 'drop'`. Always calls\n * `event.preventDefault()` (unless `preventDefault: false`), so a rejected\n * file is not opened by the browser in place of the page.\n */\n readonly dropEvent: (event: PasteDropEventLike) => Promise<PasteOutcome>;\n /**\n * Re-reads the clipboard after a retryable failure (e.g. permission denied,\n * page not focused), up to `maxRetries`. Call it from a user gesture.\n * Paste-event failures can't be retried: their data is gone after dispatch.\n */\n readonly retry: () => Promise<PasteOutcome>;\n /** Back to `idle`. Discards any in-flight result and aborts its `signal`. */\n readonly reset: () => void;\n /**\n * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned\n * cleanup clears timers, drops in-flight results, aborts in-flight work and\n * unsticks `reading`.\n * Safe to call repeatedly (React StrictMode).\n */\n readonly connect: () => () => void;\n}\n\nexport const PASTE_IDLE_STATE: PasteIdleState = /* @__PURE__ */ Object.freeze({ status: 'idle' });\nconst PASTE_READING_STATE: PasteReadingState = /* @__PURE__ */ Object.freeze({ status: 'reading' });\nconst IGNORED_IN_FLIGHT: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'in-flight' });\nconst IGNORED_NO_CONTENT: PasteOutcome = /* @__PURE__ */ Object.freeze({\n status: 'ignored',\n reason: 'no-accepted-content',\n});\nconst IGNORED_NOTHING: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'nothing-to-retry' });\nconst IGNORED_NOT_RETRYABLE: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'not-retryable' });\nconst IGNORED_CANCELLED: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'cancelled' });\n\nfunction resolveResetDelay(value: number | false | undefined): number | null {\n if (value === undefined || value === false || value === Infinity || Number.isNaN(value)) return null;\n return Math.max(0, value);\n}\n\n/** Pure helper: can `retry()` do anything from this state? */\nexport function canRetryPasteState(state: PasteState, maxRetries?: number): boolean {\n return (\n state.status === 'error' &&\n state.source === 'clipboard' &&\n isRetryableError(state.error) &&\n state.retryCount < resolveMaxRetries(maxRetries)\n );\n}\n\nlet defaultAdapter: PasteAdapter | undefined;\nconst getDefaultAdapter = (): PasteAdapter => (defaultAdapter ??= createBrowserPasteAdapter());\n\n/** Framework-agnostic paste state machine. */\nexport function createPasteMachine(options: PasteMachineOptionsSource = {}): PasteMachine {\n const read = typeof options === 'function' ? options : (): PasteMachineOptions => options;\n const listeners = new Set<() => void>();\n let state: PasteState = PASTE_IDLE_STATE;\n let generation = 0;\n let resetTimer: ReturnType<typeof setTimeout> | undefined;\n const operations = createOperations();\n\n const now = (): number => (read().now ?? Date.now)();\n\n const setState = (next: PasteState): void => {\n if (next === state) return;\n state = next;\n for (const listener of Array.from(listeners)) listener();\n };\n\n const clearResetTimer = (): void => {\n if (resetTimer !== undefined) {\n clearTimeout(resetTimer);\n resetTimer = undefined;\n }\n };\n\n const scheduleReset = (readState: PasteReadState): void => {\n clearResetTimer();\n const delay = resolveResetDelay(read().resetAfterMs);\n if (delay === null) return;\n const remaining = Math.max(0, delay - (now() - readState.at));\n // Invariant: every transition out of `read` clears this timer, so it only ever fires while still in `readState`.\n resetTimer = setTimeout(() => {\n resetTimer = undefined;\n setState(PASTE_IDLE_STATE);\n }, remaining);\n };\n\n const settleError = (error: CopyError, source: PasteSource, retryCount: number): void => {\n setState({ status: 'error', error, source, retryCount });\n invoke(read().onError, error);\n };\n\n /** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */\n const run = (\n produce: (context: OperationContext) => Promise<PasteReadResult>,\n source: PasteSource,\n retryCount: number,\n ): Promise<PasteOutcome> => {\n clearResetTimer();\n const current = ++generation;\n const superseded = operations.abort();\n const context = operations.start();\n setState(PASTE_READING_STATE);\n if (superseded) invoke(read().onCancel, 'superseded');\n\n let pending: Promise<PasteReadResult>;\n try {\n pending = produce(context);\n } catch (cause) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified below\n pending = Promise.reject(cause);\n }\n\n // Completing inside the chain routes a malformed adapter result to the error path,\n // so `paste()` still never rejects and the machine never stays stuck in `reading`.\n return pending.then(completePasteResult).then(\n (result): PasteOutcome => {\n operations.end(context);\n if (current === generation) {\n const readState: PasteReadState = { status: 'read', result, at: now() };\n setState(readState);\n scheduleReset(readState);\n invoke(read().onPaste, result);\n }\n return { status: 'read', result };\n },\n (cause: unknown): PasteOutcome => {\n operations.end(context);\n // Work we aborted ourselves (superseded, reset, unmount) is not a failure to report.\n // Invariant: superseding an in-flight read always aborts it, so past\n // this line the read is still the current one.\n if (context.signal.aborted) return IGNORED_CANCELLED;\n const error = toCopyError(cause, 'read');\n settleError(error, source, retryCount);\n return { status: 'error', error };\n },\n );\n };\n\n const readClipboard = (retryCount: number): Promise<PasteOutcome> =>\n run(\n (context) => (read().adapter ?? getDefaultAdapter()).read(resolvePasteReadOptions(read()), context),\n 'clipboard',\n retryCount,\n );\n\n const paste = (): Promise<PasteOutcome> =>\n state.status === 'reading' ? Promise.resolve(IGNORED_IN_FLIGHT) : readClipboard(0);\n\n const retry = (): Promise<PasteOutcome> => {\n if (state.status !== 'error') return Promise.resolve(IGNORED_NOTHING);\n if (state.source !== 'clipboard' || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);\n if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {\n const error = createCopyError(\n 'max-retries-exceeded',\n `Paste failed after ${String(state.retryCount)} retries.`,\n state.error,\n );\n settleError(error, 'clipboard', state.retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n return readClipboard(state.retryCount + 1);\n };\n\n /** Shared by paste and drop events: their `DataTransfer` has the same shape and lifetime. */\n const transfer = (\n data: DataTransferLike | null | undefined,\n event: { preventDefault(): void },\n source: 'event' | 'drop',\n ): Promise<PasteOutcome> => {\n const current = read();\n // An unhandled drop makes the browser open the file in place of the page, so drops are always claimed.\n if (source === 'drop' && current.preventDefault !== false) event.preventDefault();\n if (!data) return Promise.resolve(IGNORED_NO_CONTENT);\n\n let resolved: ReturnType<typeof resolvePasteReadOptions>;\n try {\n resolved = resolvePasteReadOptions(current);\n } catch (cause) {\n // Transition straight to `error` without a ghost `reading` frame.\n // `run()` would momentarily set state to `reading` before resolving the\n // error, which observers would see as a spurious state transition.\n const error = toCopyError(cause, 'read');\n ++generation;\n const superseded = operations.abort();\n clearResetTimer();\n settleError(error, source, 0);\n if (superseded) invoke(current.onCancel, 'superseded');\n return Promise.resolve({ status: 'error', error });\n }\n\n // DataTransfer is only readable during dispatch: snapshot before anything async.\n const entries = snapshotDataTransfer(data, resolved);\n if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);\n if (source === 'event' && current.preventDefault !== false) event.preventDefault();\n\n return run(\n () => {\n enforcePasteLimits(entries, resolved);\n return finalizePaste(entries, source, resolved);\n },\n source,\n 0,\n );\n };\n\n const pasteEvent = (event: PasteEventLike): Promise<PasteOutcome> => transfer(event.clipboardData, event, 'event');\n const dropEvent = (event: PasteDropEventLike): Promise<PasteOutcome> => transfer(event.dataTransfer, event, 'drop');\n\n const reset = (): void => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n const wasIdle = state.status === 'idle';\n setState(PASTE_IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'reset');\n if (!wasIdle) invoke(read().onReset);\n };\n\n const connect = (): (() => void) => {\n if (state.status === 'read') scheduleReset(state);\n return () => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n if (state.status === 'reading') setState(PASTE_IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'disconnect');\n };\n };\n\n return {\n getSnapshot: () => state,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n paste,\n pasteEvent,\n dropEvent,\n retry,\n reset,\n connect,\n };\n}\n"],"mappings":";;;;;;;AAwBA,SAAgB,wBAAyC;CACvD,IAAI,SAAuC;CAC3C,OAAO;EACL,WAAW,WAAW;GACpB,MAAM,WAAW;GACjB,SAAS;GACT,IAAI,aAAa,QAAQ,aAAa,QAAQ,SAAS,QAAQ;EACjE;EACA,aAAa,WAAW;GACtB,IAAI,WAAW,QAAQ,SAAS;EAClC;EACA,iBAAiB;CACnB;AACF;;;;;;;AChCA,MAAa,sBAAsB;AAWnC,SAAgB,kBAAkB,OAAmC;CACnE,IAAI,UAAU,UAAU,OAAO;CAC/B,IAAI,UAAU,KAAA,KAAa,CAAC,OAAO,SAAS,KAAK,GAAG,OAAA;CACpD,OAAO,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC;AACtC;AAEA,SAAS,oBAAoB,OAAsB;CACjD,MAAM,QAAQ;CACd,IAAI,OAAO,MAAM,gBAAgB,YAC/B,MAAM,YAAY,KAAK;MAEvB,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,QAAQ,QAAQ;EAChD,GACA,QACA,CACF;CACF;CAEA,MAAM,cAAc,UAAiD,SAAS,MAAM,eAAe,OAAO,OAAO;CACjH,MAAM,aAAa,UAAqD,SAAS,MAAM,cAAc,OAAO,MAAM;CAElH,MAAM,cAAoB;EACxB,EAAE;EACF,MAAM,YAAY,WAAW,MAAM;EACnC,gBAAgB;EAChB,MAAM,UAAU,MAAM,WAAW;EACjC,SAAS,gBAAgB;EACzB,IAAI,WAAW,OAAO,KAAK,CAAC,CAAC,UAAU,OAAO;EAC9C,IAAI,CAAC,SAAS,OAAO,KAAK,CAAC,CAAC,OAAO;CACrC;CAEA,MAAM,gBAA8B;EAClC,IAAI,MAAM,WAAW,QAAQ,cAAc,KAAK;EAChD,aAAa;GACX,EAAE;GACF,MAAM,YAAY,WAAW,MAAM;GACnC,gBAAgB;GAChB,IAAI,MAAM,WAAW,WAAW,SAAS,gBAAgB;GACzD,IAAI,WAAW,OAAO,KAAK,CAAC,CAAC,UAAU,YAAY;EACrD;CACF;CAEA,OAAO;EACL,mBAAmB;EACnB,YAAY,aAAa;GACvB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { n as copyFailure } from "./errors-9h8sdFFX.js";
2
+ import { n as copyFailure } from "./errors-CT-FfUtU.js";
3
3
  //#region src/capture/deadline.ts
4
4
  /**
5
5
  * Runs `task` with a timeout and an optional caller `AbortSignal`. The task
@@ -43,4 +43,4 @@ function withDeadline(task, options) {
43
43
  //#endregion
44
44
  export { withDeadline as t };
45
45
 
46
- //# sourceMappingURL=deadline-C29AlS_Q.js.map
46
+ //# sourceMappingURL=deadline-CbwnZ3Oq.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"deadline-C29AlS_Q.js","names":[],"sources":["../../src/capture/deadline.ts"],"sourcesContent":["import { copyFailure, type CopyFailure } from '../core/errors';\n\nexport interface DeadlineOptions {\n readonly timeoutMs: number;\n readonly signal?: AbortSignal | undefined;\n /** Used in messages: \"<label> timed out\". */\n readonly label: string;\n}\n\n/**\n * Runs `task` with a timeout and an optional caller `AbortSignal`. The task\n * receives a signal that fires on either, so cooperative work can stop early.\n * Rejects with classified `timeout` / `aborted` failures.\n */\nexport function withDeadline<T>(task: (signal: AbortSignal) => PromiseLike<T> | T, options: DeadlineOptions): Promise<T> {\n const { timeoutMs, label } = options;\n const external = options.signal;\n if (external?.aborted) {\n return Promise.reject(copyFailure('aborted', `${label} was aborted.`, external.reason));\n }\n\n const controller = new AbortController();\n return new Promise<T>((resolve, reject) => {\n const finish = (abort: boolean): void => {\n clearTimeout(timer);\n external?.removeEventListener('abort', onAbort);\n // Always signal downstream cooperative work to stop — whether we timed\n // out, were aborted, or resolved successfully. Without this, a task\n // that started a long operation keeps that operation alive after we've\n // already resolved, leaking resources until GC.\n /* c8 ignore next -- abort=false path is never used; kept for future API flexibility */\n if (abort) controller.abort();\n };\n const fail = (failure: CopyFailure): void => {\n finish(true);\n reject(failure);\n };\n const onAbort = (): void => {\n fail(copyFailure('aborted', `${label} was aborted.`, (external as AbortSignal).reason));\n };\n const timer =\n timeoutMs === Infinity\n ? undefined\n : setTimeout(() => {\n fail(copyFailure('timeout', `${label} timed out after ${String(timeoutMs)} ms.`));\n }, timeoutMs);\n external?.addEventListener('abort', onAbort, { once: true });\n\n new Promise<T>((run) => {\n run(task(controller.signal));\n }).then(\n (value) => {\n finish(true);\n resolve(value);\n },\n (cause: unknown) => {\n finish(true);\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified by the caller\n reject(cause);\n },\n );\n });\n}\n"],"mappings":";;;;;;;;AAcA,SAAgB,aAAgB,MAAmD,SAAsC;CACvH,MAAM,EAAE,WAAW,UAAU;CAC7B,MAAM,WAAW,QAAQ;CACzB,IAAI,UAAU,SACZ,OAAO,QAAQ,OAAO,YAAY,WAAW,GAAG,MAAM,gBAAgB,SAAS,MAAM,CAAC;CAGxF,MAAM,aAAa,IAAI,gBAAgB;CACvC,OAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,UAAU,UAAyB;GACvC,aAAa,KAAK;GAClB,UAAU,oBAAoB,SAAS,OAAO;;GAM9C,IAAI,OAAO,WAAW,MAAM;EAC9B;EACA,MAAM,QAAQ,YAA+B;GAC3C,OAAO,IAAI;GACX,OAAO,OAAO;EAChB;EACA,MAAM,gBAAsB;GAC1B,KAAK,YAAY,WAAW,GAAG,MAAM,gBAAiB,SAAyB,MAAM,CAAC;EACxF;EACA,MAAM,QACJ,cAAc,WACV,KAAA,IACA,iBAAiB;GACf,KAAK,YAAY,WAAW,GAAG,MAAM,mBAAmB,OAAO,SAAS,EAAE,KAAK,CAAC;EAClF,GAAG,SAAS;EAClB,UAAU,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAE3D,IAAI,SAAY,QAAQ;GACtB,IAAI,KAAK,WAAW,MAAM,CAAC;EAC7B,CAAC,CAAC,CAAC,MACA,UAAU;GACT,OAAO,IAAI;GACX,QAAQ,KAAK;EACf,IACC,UAAmB;GAClB,OAAO,IAAI;GAEX,OAAO,KAAK;EACd,CACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"deadline-CbwnZ3Oq.js","names":[],"sources":["../../src/capture/deadline.ts"],"sourcesContent":["import { copyFailure, type CopyFailure } from '../core/errors';\n\nexport interface DeadlineOptions {\n readonly timeoutMs: number;\n readonly signal?: AbortSignal | undefined;\n /** Used in messages: \"<label> timed out\". */\n readonly label: string;\n}\n\n/**\n * Runs `task` with a timeout and an optional caller `AbortSignal`. The task\n * receives a signal that fires on either, so cooperative work can stop early.\n * Rejects with classified `timeout` / `aborted` failures.\n */\nexport function withDeadline<T>(task: (signal: AbortSignal) => PromiseLike<T> | T, options: DeadlineOptions): Promise<T> {\n const { timeoutMs, label } = options;\n const external = options.signal;\n if (external?.aborted) {\n return Promise.reject(copyFailure('aborted', `${label} was aborted.`, external.reason));\n }\n\n const controller = new AbortController();\n return new Promise<T>((resolve, reject) => {\n const finish = (abort: boolean): void => {\n clearTimeout(timer);\n external?.removeEventListener('abort', onAbort);\n // Always signal downstream cooperative work to stop — whether we timed\n // out, were aborted, or resolved successfully. Without this, a task\n // that started a long operation keeps that operation alive after we've\n // already resolved, leaking resources until GC.\n /* c8 ignore next -- abort=false path is never used; kept for future API flexibility */\n if (abort) controller.abort();\n };\n const fail = (failure: CopyFailure): void => {\n finish(true);\n reject(failure);\n };\n const onAbort = (): void => {\n fail(copyFailure('aborted', `${label} was aborted.`, (external as AbortSignal).reason));\n };\n const timer =\n timeoutMs === Infinity\n ? undefined\n : setTimeout(() => {\n fail(copyFailure('timeout', `${label} timed out after ${String(timeoutMs)} ms.`));\n }, timeoutMs);\n external?.addEventListener('abort', onAbort, { once: true });\n\n new Promise<T>((run) => {\n run(task(controller.signal));\n }).then(\n (value) => {\n finish(true);\n resolve(value);\n },\n (cause: unknown) => {\n finish(true);\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified by the caller\n reject(cause);\n },\n );\n });\n}\n"],"mappings":";;;;;;;;AAcA,SAAgB,aAAgB,MAAmD,SAAsC;CACvH,MAAM,EAAE,WAAW,UAAU;CAC7B,MAAM,WAAW,QAAQ;CACzB,IAAI,UAAU,SACZ,OAAO,QAAQ,OAAO,YAAY,WAAW,GAAG,MAAM,gBAAgB,SAAS,MAAM,CAAC;CAGxF,MAAM,aAAa,IAAI,gBAAgB;CACvC,OAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,UAAU,UAAyB;GACvC,aAAa,KAAK;GAClB,UAAU,oBAAoB,SAAS,OAAO;;GAM9C,IAAI,OAAO,WAAW,MAAM;EAC9B;EACA,MAAM,QAAQ,YAA+B;GAC3C,OAAO,IAAI;GACX,OAAO,OAAO;EAChB;EACA,MAAM,gBAAsB;GAC1B,KAAK,YAAY,WAAW,GAAG,MAAM,gBAAiB,SAAyB,MAAM,CAAC;EACxF;EACA,MAAM,QACJ,cAAc,WACV,KAAA,IACA,iBAAiB;GACf,KAAK,YAAY,WAAW,GAAG,MAAM,mBAAmB,OAAO,SAAS,EAAE,KAAK,CAAC;EAClF,GAAG,SAAS;EAClB,UAAU,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAE3D,IAAI,SAAY,QAAQ;GACtB,IAAI,KAAK,WAAW,MAAM,CAAC;EAC7B,CAAC,CAAC,CAAC,MACA,UAAU;GACT,OAAO,IAAI;GACX,QAAQ,KAAK;EACf,IACC,UAAmB;GAClB,OAAO,IAAI;GAEX,OAAO,KAAK;EACd,CACF;CACF,CAAC;AACH"}
@@ -1,5 +1,5 @@
1
1
 
2
- const require_errors = require("./errors-BwOF6T_M.cjs");
2
+ const require_errors = require("./errors-DFmEAC4E.cjs");
3
3
  //#region src/capture/deadline.ts
4
4
  /**
5
5
  * Runs `task` with a timeout and an optional caller `AbortSignal`. The task
@@ -48,4 +48,4 @@ Object.defineProperty(exports, "withDeadline", {
48
48
  }
49
49
  });
50
50
 
51
- //# sourceMappingURL=deadline-DkiB8ZHE.cjs.map
51
+ //# sourceMappingURL=deadline-j2hD7JKz.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"deadline-DkiB8ZHE.cjs","names":["copyFailure"],"sources":["../../src/capture/deadline.ts"],"sourcesContent":["import { copyFailure, type CopyFailure } from '../core/errors';\n\nexport interface DeadlineOptions {\n readonly timeoutMs: number;\n readonly signal?: AbortSignal | undefined;\n /** Used in messages: \"<label> timed out\". */\n readonly label: string;\n}\n\n/**\n * Runs `task` with a timeout and an optional caller `AbortSignal`. The task\n * receives a signal that fires on either, so cooperative work can stop early.\n * Rejects with classified `timeout` / `aborted` failures.\n */\nexport function withDeadline<T>(task: (signal: AbortSignal) => PromiseLike<T> | T, options: DeadlineOptions): Promise<T> {\n const { timeoutMs, label } = options;\n const external = options.signal;\n if (external?.aborted) {\n return Promise.reject(copyFailure('aborted', `${label} was aborted.`, external.reason));\n }\n\n const controller = new AbortController();\n return new Promise<T>((resolve, reject) => {\n const finish = (abort: boolean): void => {\n clearTimeout(timer);\n external?.removeEventListener('abort', onAbort);\n // Always signal downstream cooperative work to stop — whether we timed\n // out, were aborted, or resolved successfully. Without this, a task\n // that started a long operation keeps that operation alive after we've\n // already resolved, leaking resources until GC.\n /* c8 ignore next -- abort=false path is never used; kept for future API flexibility */\n if (abort) controller.abort();\n };\n const fail = (failure: CopyFailure): void => {\n finish(true);\n reject(failure);\n };\n const onAbort = (): void => {\n fail(copyFailure('aborted', `${label} was aborted.`, (external as AbortSignal).reason));\n };\n const timer =\n timeoutMs === Infinity\n ? undefined\n : setTimeout(() => {\n fail(copyFailure('timeout', `${label} timed out after ${String(timeoutMs)} ms.`));\n }, timeoutMs);\n external?.addEventListener('abort', onAbort, { once: true });\n\n new Promise<T>((run) => {\n run(task(controller.signal));\n }).then(\n (value) => {\n finish(true);\n resolve(value);\n },\n (cause: unknown) => {\n finish(true);\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified by the caller\n reject(cause);\n },\n );\n });\n}\n"],"mappings":";;;;;;;;AAcA,SAAgB,aAAgB,MAAmD,SAAsC;CACvH,MAAM,EAAE,WAAW,UAAU;CAC7B,MAAM,WAAW,QAAQ;CACzB,IAAI,UAAU,SACZ,OAAO,QAAQ,OAAOA,eAAAA,YAAY,WAAW,GAAG,MAAM,gBAAgB,SAAS,MAAM,CAAC;CAGxF,MAAM,aAAa,IAAI,gBAAgB;CACvC,OAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,UAAU,UAAyB;GACvC,aAAa,KAAK;GAClB,UAAU,oBAAoB,SAAS,OAAO;;GAM9C,IAAI,OAAO,WAAW,MAAM;EAC9B;EACA,MAAM,QAAQ,YAA+B;GAC3C,OAAO,IAAI;GACX,OAAO,OAAO;EAChB;EACA,MAAM,gBAAsB;GAC1B,KAAKA,eAAAA,YAAY,WAAW,GAAG,MAAM,gBAAiB,SAAyB,MAAM,CAAC;EACxF;EACA,MAAM,QACJ,cAAc,WACV,KAAA,IACA,iBAAiB;GACf,KAAKA,eAAAA,YAAY,WAAW,GAAG,MAAM,mBAAmB,OAAO,SAAS,EAAE,KAAK,CAAC;EAClF,GAAG,SAAS;EAClB,UAAU,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAE3D,IAAI,SAAY,QAAQ;GACtB,IAAI,KAAK,WAAW,MAAM,CAAC;EAC7B,CAAC,CAAC,CAAC,MACA,UAAU;GACT,OAAO,IAAI;GACX,QAAQ,KAAK;EACf,IACC,UAAmB;GAClB,OAAO,IAAI;GAEX,OAAO,KAAK;EACd,CACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"deadline-j2hD7JKz.cjs","names":["copyFailure"],"sources":["../../src/capture/deadline.ts"],"sourcesContent":["import { copyFailure, type CopyFailure } from '../core/errors';\n\nexport interface DeadlineOptions {\n readonly timeoutMs: number;\n readonly signal?: AbortSignal | undefined;\n /** Used in messages: \"<label> timed out\". */\n readonly label: string;\n}\n\n/**\n * Runs `task` with a timeout and an optional caller `AbortSignal`. The task\n * receives a signal that fires on either, so cooperative work can stop early.\n * Rejects with classified `timeout` / `aborted` failures.\n */\nexport function withDeadline<T>(task: (signal: AbortSignal) => PromiseLike<T> | T, options: DeadlineOptions): Promise<T> {\n const { timeoutMs, label } = options;\n const external = options.signal;\n if (external?.aborted) {\n return Promise.reject(copyFailure('aborted', `${label} was aborted.`, external.reason));\n }\n\n const controller = new AbortController();\n return new Promise<T>((resolve, reject) => {\n const finish = (abort: boolean): void => {\n clearTimeout(timer);\n external?.removeEventListener('abort', onAbort);\n // Always signal downstream cooperative work to stop — whether we timed\n // out, were aborted, or resolved successfully. Without this, a task\n // that started a long operation keeps that operation alive after we've\n // already resolved, leaking resources until GC.\n /* c8 ignore next -- abort=false path is never used; kept for future API flexibility */\n if (abort) controller.abort();\n };\n const fail = (failure: CopyFailure): void => {\n finish(true);\n reject(failure);\n };\n const onAbort = (): void => {\n fail(copyFailure('aborted', `${label} was aborted.`, (external as AbortSignal).reason));\n };\n const timer =\n timeoutMs === Infinity\n ? undefined\n : setTimeout(() => {\n fail(copyFailure('timeout', `${label} timed out after ${String(timeoutMs)} ms.`));\n }, timeoutMs);\n external?.addEventListener('abort', onAbort, { once: true });\n\n new Promise<T>((run) => {\n run(task(controller.signal));\n }).then(\n (value) => {\n finish(true);\n resolve(value);\n },\n (cause: unknown) => {\n finish(true);\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified by the caller\n reject(cause);\n },\n );\n });\n}\n"],"mappings":";;;;;;;;AAcA,SAAgB,aAAgB,MAAmD,SAAsC;CACvH,MAAM,EAAE,WAAW,UAAU;CAC7B,MAAM,WAAW,QAAQ;CACzB,IAAI,UAAU,SACZ,OAAO,QAAQ,OAAOA,eAAAA,YAAY,WAAW,GAAG,MAAM,gBAAgB,SAAS,MAAM,CAAC;CAGxF,MAAM,aAAa,IAAI,gBAAgB;CACvC,OAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,UAAU,UAAyB;GACvC,aAAa,KAAK;GAClB,UAAU,oBAAoB,SAAS,OAAO;;GAM9C,IAAI,OAAO,WAAW,MAAM;EAC9B;EACA,MAAM,QAAQ,YAA+B;GAC3C,OAAO,IAAI;GACX,OAAO,OAAO;EAChB;EACA,MAAM,gBAAsB;GAC1B,KAAKA,eAAAA,YAAY,WAAW,GAAG,MAAM,gBAAiB,SAAyB,MAAM,CAAC;EACxF;EACA,MAAM,QACJ,cAAc,WACV,KAAA,IACA,iBAAiB;GACf,KAAKA,eAAAA,YAAY,WAAW,GAAG,MAAM,mBAAmB,OAAO,SAAS,EAAE,KAAK,CAAC;EAClF,GAAG,SAAS;EAClB,UAAU,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAE3D,IAAI,SAAY,QAAQ;GACtB,IAAI,KAAK,WAAW,MAAM,CAAC;EAC7B,CAAC,CAAC,CAAC,MACA,UAAU;GACT,OAAO,IAAI;GACX,QAAQ,KAAK;EACf,IACC,UAAmB;GAClB,OAAO,IAAI;GAEX,OAAO,KAAK;EACd,CACF;CACF,CAAC;AACH"}
@@ -30,9 +30,9 @@ const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
30
30
  var CopyFailure = class extends Error {
31
31
  constructor(copyError) {
32
32
  super(copyError.message);
33
- this[COPY_FAILURE_BRAND] = true;
34
33
  this.name = "CopyFailure";
35
34
  this.copyError = copyError;
35
+ this[COPY_FAILURE_BRAND] = true;
36
36
  }
37
37
  };
38
38
  function isCopyFailure(value) {
@@ -117,4 +117,4 @@ function describePasteError(error, source) {
117
117
  //#endregion
118
118
  export { describePasteError as a, toCopyError as c, describeCopyError as i, copyFailure as n, isCopyFailure as o, createCopyError as r, isRetryableError as s, CopyFailure as t };
119
119
 
120
- //# sourceMappingURL=errors-9h8sdFFX.js.map
120
+ //# sourceMappingURL=errors-CT-FfUtU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-CT-FfUtU.js","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["import type { PasteSource } from './paste-reader';\n\n/**\n * Every way a clipboard operation can fail, as a closed union.\n *\n * `CopyError.message` is developer-facing (logs, telemetry). For user-facing\n * text use {@link describeCopyError} / {@link describePasteError}, or map\n * `type` through your own i18n layer.\n */\nexport type CopyErrorType =\n /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */\n | 'unsupported'\n /** Page is not served over HTTPS/localhost. Not retryable. */\n | 'insecure-context'\n /** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */\n | 'permission-denied'\n /** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */\n | 'not-focused'\n /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */\n | 'invalid-payload'\n /** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */\n | 'unsupported-format'\n /** A lazy image source (or capture) threw, rejected or did not produce a Blob. */\n | 'blob-generation-failed'\n /** `retry()` was called after `maxRetries` was reached. Terminal. */\n | 'max-retries-exceeded'\n /** Paste: the clipboard held nothing matching `accept`. */\n | 'no-content'\n /** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */\n | 'too-large'\n /** An operation did not settle within its deadline. Retryable. */\n | 'timeout'\n /** The caller aborted the operation through an `AbortSignal`. Not retryable. */\n | 'aborted'\n /** Anything the platform threw that we could not classify. */\n | 'unknown';\n\n/** Which clipboard direction failed; only changes developer-facing messages. */\nexport type ClipboardOperation = 'write' | 'read';\n\nexport interface CopyError {\n readonly type: CopyErrorType;\n readonly message: string;\n readonly cause?: unknown;\n}\n\nexport function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError {\n return cause === undefined ? { type, message } : { type, message, cause };\n}\n\nconst RETRYABLE_ERRORS: ReadonlySet<CopyErrorType> = /* @__PURE__ */ new Set<CopyErrorType>([\n 'permission-denied',\n 'not-focused',\n 'blob-generation-failed',\n 'timeout',\n 'unknown',\n]);\n\n/** Whether retrying the same payload could plausibly succeed. */\nexport function isRetryableError(error: CopyError): boolean {\n return RETRYABLE_ERRORS.has(error.type);\n}\n\n/**\n * Branded (not `instanceof`) so failures stay recognisable even when the core\n * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.\n */\nconst COPY_FAILURE_BRAND: unique symbol = Symbol.for('react-smart-copy.CopyFailure');\n\n// The brand is declared here and set in the constructor: a class can't declare a symbol-named\n// property in a way its declaration file can be written from this file alone.\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -- the constructor sets the brand\nexport interface CopyFailure {\n readonly [COPY_FAILURE_BRAND]: true;\n}\n\n/** Error thrown by adapters to carry a fully classified {@link CopyError}. */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -- see the interface above\nexport class CopyFailure extends Error {\n readonly copyError: CopyError;\n\n constructor(copyError: CopyError) {\n super(copyError.message);\n this.name = 'CopyFailure';\n this.copyError = copyError;\n // An own, enumerable property, as a class field would be.\n (this as { [COPY_FAILURE_BRAND]: true })[COPY_FAILURE_BRAND] = true;\n }\n}\n\nexport function isCopyFailure(value: unknown): value is CopyFailure {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[COPY_FAILURE_BRAND] === true\n );\n}\n\n/** Shorthand for throwing a classified failure. */\nexport function copyFailure(type: CopyErrorType, message: string, cause?: unknown): CopyFailure {\n return new CopyFailure(createCopyError(type, message, cause));\n}\n\nfunction readString(value: unknown, key: string): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const field = (value as Record<string, unknown>)[key];\n return typeof field === 'string' ? field : undefined;\n}\n\n/**\n * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.\n * `operation` only tailors the developer-facing message.\n */\nexport function toCopyError(cause: unknown, operation: ClipboardOperation = 'write'): CopyError {\n if (isCopyFailure(cause)) return cause.copyError;\n\n const name = readString(cause, 'name');\n const message = readString(cause, 'message') ?? '';\n const verb = operation === 'read' ? 'read' : 'write';\n\n switch (name) {\n case 'NotAllowedError':\n return /focus/i.test(message)\n ? createCopyError('not-focused', `The document was not focused during the clipboard ${verb}.`, cause)\n : createCopyError('permission-denied', `Clipboard ${verb} permission was denied.`, cause);\n case 'SecurityError':\n return createCopyError('insecure-context', 'The clipboard is blocked in this context.', cause);\n case 'NotSupportedError':\n case 'DataError':\n return createCopyError('unsupported-format', 'The browser rejected this clipboard format.', cause);\n case 'AbortError':\n return createCopyError('aborted', `The clipboard ${verb} was aborted.`, cause);\n case 'TimeoutError':\n return createCopyError('timeout', `The clipboard ${verb} timed out.`, cause);\n default:\n return createCopyError('unknown', message || `The clipboard ${verb} failed for an unknown reason.`, cause);\n }\n}\n\nconst COPY_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Copying isn't supported in this browser.\",\n 'insecure-context': 'Copying requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while copying. Try again.',\n 'invalid-payload': 'There is nothing to copy.',\n 'unsupported-format': \"This content can't be copied in this browser.\",\n 'blob-generation-failed': \"The image couldn't be prepared for copying.\",\n 'max-retries-exceeded': 'Copying failed after several attempts.',\n 'no-content': 'There is nothing to copy.',\n 'too-large': 'This content is too large to copy.',\n timeout: 'Copying took too long. Try again.',\n aborted: 'Copying was cancelled.',\n unknown: \"Couldn't copy to the clipboard. Try again.\",\n};\n\nconst PASTE_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Pasting isn't supported in this browser.\",\n 'insecure-context': 'Pasting requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while pasting. Try again.',\n 'invalid-payload': \"The clipboard content couldn't be read.\",\n 'unsupported-format': \"This clipboard content isn't supported here.\",\n 'blob-generation-failed': \"The pasted image couldn't be read.\",\n 'max-retries-exceeded': 'Pasting failed after several attempts.',\n 'no-content': \"The clipboard doesn't contain anything that can be pasted here.\",\n 'too-large': 'The clipboard content is too large to paste.',\n timeout: 'Pasting took too long. Try again.',\n aborted: 'Pasting was cancelled.',\n unknown: \"Couldn't read the clipboard. Try again.\",\n};\n\n/** Default English, user-facing sentence for a copy error. Replace for i18n. */\nexport function describeCopyError(error: CopyError): string {\n return COPY_DESCRIPTIONS[error.type];\n}\n\n/** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */\nconst DROP_DESCRIPTIONS: Readonly<Partial<Record<CopyErrorType, string>>> = {\n 'invalid-payload': \"The dropped content couldn't be read.\",\n 'no-content': 'Nothing that was dropped can be used here.',\n 'too-large': 'The dropped content is too large.',\n unknown: \"Couldn't read the dropped content. Try again.\",\n};\n\n/**\n * Default English, user-facing sentence for a paste error. Pass the error\n * state's `source` to word drag-and-drop failures as drops. Replace for i18n.\n */\nexport function describePasteError(error: CopyError, source?: PasteSource): string {\n return (source === 'drop' ? DROP_DESCRIPTIONS[error.type] : undefined) ?? PAST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C5F,KAAK,iBACH,OAAO,gBAAgB,oBAAoB,6CAA6C,KAAK;EAC/F,KAAK;EACL,KAAK,aACH,OAAO,gBAAgB,sBAAsB,+CAA+C,KAAK;EACnG,KAAK,cACH,OAAO,gBAAgB,WAAW,iBAAiB,KAAK,gBAAgB,KAAK;EAC/E,KAAK,gBACH,OAAO,gBAAgB,WAAW,iBAAiB,KAAK,cAAc,KAAK;EAC7E,SACE,OAAO,gBAAgB,WAAW,WAAW,iBAAiB,KAAK,iCAAiC,KAAK;CAC7G;AACF;AAEA,MAAM,oBAA6D;CACjE,aAAa;CACb,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,mBAAmB;CACnB,sBAAsB;CACtB,0BAA0B;CAC1B,wBAAwB;CACxB,cAAc;CACd,aAAa;CACb,SAAS;CACT,SAAS;CACT,SAAS;AACX;AAEA,MAAM,qBAA8D;CAClE,aAAa;CACb,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,mBAAmB;CACnB,sBAAsB;CACtB,0BAA0B;CAC1B,wBAAwB;CACxB,cAAc;CACd,aAAa;CACb,SAAS;CACT,SAAS;CACT,SAAS;AACX;;AAGA,SAAgB,kBAAkB,OAA0B;CAC1D,OAAO,kBAAkB,MAAM;AACjC;;AAGA,MAAM,oBAAsE;CAC1E,mBAAmB;CACnB,cAAc;CACd,aAAa;CACb,SAAS;AACX;;;;;AAMA,SAAgB,mBAAmB,OAAkB,QAA8B;CACjF,QAAQ,WAAW,SAAS,kBAAkB,MAAM,QAAQ,KAAA,MAAc,mBAAmB,MAAM;AACrG"}
@@ -30,9 +30,9 @@ const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
30
30
  var CopyFailure = class extends Error {
31
31
  constructor(copyError) {
32
32
  super(copyError.message);
33
- this[COPY_FAILURE_BRAND] = true;
34
33
  this.name = "CopyFailure";
35
34
  this.copyError = copyError;
35
+ this[COPY_FAILURE_BRAND] = true;
36
36
  }
37
37
  };
38
38
  function isCopyFailure(value) {
@@ -164,4 +164,4 @@ Object.defineProperty(exports, "toCopyError", {
164
164
  }
165
165
  });
166
166
 
167
- //# sourceMappingURL=errors-BwOF6T_M.cjs.map
167
+ //# sourceMappingURL=errors-DFmEAC4E.cjs.map