react-smart-copy 1.28.0 → 1.29.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 (64) hide show
  1. package/README.md +3 -3
  2. package/dist/capture.d.cts +1 -1
  3. package/dist/capture.d.ts +1 -1
  4. package/dist/chunks/{clipboard-adapter-CUvmAcRE.d.cts → clipboard-adapter-B55TgPYd.d.ts} +8 -2
  5. package/dist/chunks/{clipboard-adapter-CdOzN135.d.ts → clipboard-adapter-C1_Mvpcc.d.cts} +8 -2
  6. package/dist/chunks/{clipboard-adapter-CfI4O02E.cjs → clipboard-adapter-DYo79Fdq.cjs} +31 -2
  7. package/dist/chunks/clipboard-adapter-DYo79Fdq.cjs.map +1 -0
  8. package/dist/chunks/{clipboard-adapter-DX5yd8_6.js → clipboard-adapter-XS23N-Gg.js} +31 -2
  9. package/dist/chunks/clipboard-adapter-XS23N-Gg.js.map +1 -0
  10. package/dist/chunks/{copy-interceptor-BClcHS_P.d.cts → copy-interceptor-Bet296gH.d.ts} +4 -2
  11. package/dist/chunks/{copy-interceptor-D8c9EDnO.d.ts → copy-interceptor-C0AD6C4O.d.cts} +4 -2
  12. package/dist/chunks/{core-BE0SO57n.js → core-B8_wVOSU.js} +115 -50
  13. package/dist/chunks/core-B8_wVOSU.js.map +1 -0
  14. package/dist/chunks/{core-BdHzkkQ-.cjs → core-BR8Jgea1.cjs} +114 -49
  15. package/dist/chunks/core-BR8Jgea1.cjs.map +1 -0
  16. package/dist/chunks/{index-U91G1nS9.d.ts → index-DjqQGsNs.d.ts} +6 -5
  17. package/dist/chunks/{index-Ct2V52et.d.cts → index-uHZHddq0.d.cts} +6 -5
  18. package/dist/chunks/{paste-adapter-CfIDT3mp.d.ts → paste-adapter-D6OGeYxr.d.ts} +2 -2
  19. package/dist/chunks/{paste-adapter-B6eucH3E.d.cts → paste-adapter-DlwtI3qZ.d.cts} +2 -2
  20. package/dist/chunks/payload-5uJedhwz.js.map +1 -1
  21. package/dist/chunks/{payload-qkAWVXWA.d.cts → payload-BKDabKYy.d.cts} +15 -5
  22. package/dist/chunks/{payload-CcvSx_Hq.d.ts → payload-D7CJ6e2W.d.ts} +15 -5
  23. package/dist/chunks/payload-DjSSLonm.cjs.map +1 -1
  24. package/dist/chunks/{share-BqXjYbND.cjs → share-0QnaCaoQ.cjs} +2 -2
  25. package/dist/chunks/{share-BqXjYbND.cjs.map → share-0QnaCaoQ.cjs.map} +1 -1
  26. package/dist/chunks/{share-DQFF73gt.d.cts → share-BueRwILH.d.cts} +3 -3
  27. package/dist/chunks/{share-BFVyOA7b.js → share-BwgSAtH6.js} +2 -2
  28. package/dist/chunks/{share-BFVyOA7b.js.map → share-BwgSAtH6.js.map} +1 -1
  29. package/dist/chunks/{share-DMqvWz32.d.ts → share-DDIsWxbC.d.ts} +3 -3
  30. package/dist/code.d.cts +1 -1
  31. package/dist/code.d.ts +1 -1
  32. package/dist/color.d.cts +1 -1
  33. package/dist/color.d.ts +1 -1
  34. package/dist/core.cjs +2 -2
  35. package/dist/core.d.cts +6 -6
  36. package/dist/core.d.ts +6 -6
  37. package/dist/core.js +2 -2
  38. package/dist/email.d.cts +1 -1
  39. package/dist/email.d.ts +1 -1
  40. package/dist/index.cjs +3 -3
  41. package/dist/index.d.cts +7 -7
  42. package/dist/index.d.ts +7 -7
  43. package/dist/index.js +3 -3
  44. package/dist/link.d.cts +1 -1
  45. package/dist/link.d.ts +1 -1
  46. package/dist/number.d.cts +1 -1
  47. package/dist/number.d.ts +1 -1
  48. package/dist/rich.d.cts +2 -2
  49. package/dist/rich.d.ts +2 -2
  50. package/dist/secrets.d.cts +1 -1
  51. package/dist/secrets.d.ts +1 -1
  52. package/dist/share.cjs +1 -1
  53. package/dist/share.d.cts +1 -1
  54. package/dist/share.d.ts +1 -1
  55. package/dist/share.js +1 -1
  56. package/dist/table.d.cts +1 -1
  57. package/dist/table.d.ts +1 -1
  58. package/dist/testing.d.cts +3 -3
  59. package/dist/testing.d.ts +3 -3
  60. package/package.json +9 -9
  61. package/dist/chunks/clipboard-adapter-CfI4O02E.cjs.map +0 -1
  62. package/dist/chunks/clipboard-adapter-DX5yd8_6.js.map +0 -1
  63. package/dist/chunks/core-BE0SO57n.js.map +0 -1
  64. package/dist/chunks/core-BdHzkkQ-.cjs.map +0 -1
package/README.md CHANGED
@@ -23,7 +23,7 @@ Phone +91 98xxx xxxxx [Copy]
23
23
  ID PLT-29018 [Copy]
24
24
  ```
25
25
 
26
- - **Small.** About 4.2 kB for `useCopy` (min + brotli), zero runtime dependencies, and every
26
+ - **Small.** About 4.4 kB for `useCopy` (min + brotli), zero runtime dependencies, and every
27
27
  module is a separate entry point that shares one copy of the core.
28
28
  - **Honest.** Every failure is a typed, classified error. Nothing silently does nothing.
29
29
  - **Accessible.** Real buttons, accessible names, polite announcements, reduced motion, and
@@ -138,8 +138,8 @@ Sizes are minified and brotli-compressed, for everything the entry point exports
138
138
 
139
139
  | Entry point | What it is for | Size |
140
140
  | --- | --- | --- |
141
- | [`react-smart-copy`](https://suprabhat02.github.io/react-smart-copy/start/introduction/) | React hooks and components: `useCopy`, `usePaste`, `CopyField`, `PasteField`, `CopyGroup`, `useCopyInterceptor`, `useDragCopy`, `useShare`, `useOtpField`, `useClipboardPermission` | from 4.2 kB |
142
- | [`/core`](https://suprabhat02.github.io/react-smart-copy/guides/without-react/) | The framework-agnostic machines and adapters | 9.3 kB |
141
+ | [`react-smart-copy`](https://suprabhat02.github.io/react-smart-copy/start/introduction/) | React hooks and components: `useCopy`, `usePaste`, `CopyField`, `PasteField`, `CopyGroup`, `useCopyInterceptor`, `useDragCopy`, `useShare`, `useOtpField`, `useClipboardPermission` | from 4.4 kB |
142
+ | [`/core`](https://suprabhat02.github.io/react-smart-copy/guides/without-react/) | The framework-agnostic machines and adapters | 9.8 kB |
143
143
  | [`/capture`](https://suprabhat02.github.io/react-smart-copy/copy/capture/) | Copy an `<svg>` or a piece of your UI as a PNG | 3.4 kB |
144
144
  | [`/table`](https://suprabhat02.github.io/react-smart-copy/modules/tables/) | Ranges that paste into Excel and Google Sheets as cells, and back as typed records | 5.6 kB |
145
145
  | [`/structured`](https://suprabhat02.github.io/react-smart-copy/modules/structured/) | Your own typed, versioned, validated objects on the clipboard | 3.5 kB |
@@ -1,5 +1,5 @@
1
1
 
2
- import { c as ImagePayload, k as OperationContext } from "./chunks/payload-qkAWVXWA.cjs";
2
+ import { j as OperationContext, u as ImagePayload } from "./chunks/payload-BKDabKYy.cjs";
3
3
  //#region src/capture/environment.d.ts
4
4
  /** A decoded image, ready to be drawn. `source` is platform-specific (an `HTMLImageElement` in browsers). */
5
5
  interface DecodedImage {
package/dist/capture.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- import { c as ImagePayload, k as OperationContext } from "./chunks/payload-CcvSx_Hq.js";
2
+ import { j as OperationContext, u as ImagePayload } from "./chunks/payload-D7CJ6e2W.js";
3
3
  //#region src/capture/environment.d.ts
4
4
  /** A decoded image, ready to be drawn. `source` is platform-specific (an `HTMLImageElement` in browsers). */
5
5
  interface DecodedImage {
@@ -1,5 +1,5 @@
1
1
 
2
- import { k as OperationContext, r as CopyPayload } from "./payload-qkAWVXWA.cjs";
2
+ import { i as CopyPayload, j as OperationContext } from "./payload-D7CJ6e2W.js";
3
3
  //#region src/core/clipboard-adapter.d.ts
4
4
  /** Minimal structural view of `navigator.clipboard`, so fakes and polyfills fit. */
5
5
  interface ClipboardLike {
@@ -31,6 +31,12 @@ interface ClipboardEnvironment {
31
31
  */
32
32
  interface ClipboardAdapter {
33
33
  write(payload: CopyPayload, context?: OperationContext): Promise<void>;
34
+ /**
35
+ * Optional: write text that is still being produced (an async copy source), starting the
36
+ * platform write now so the user's gesture is kept. Without it, the machine waits for the
37
+ * text and calls `write`, which suits clipboards with no gesture rules (Electron, tests).
38
+ */
39
+ writeDeferred?(text: Promise<string>, context?: OperationContext): Promise<void>;
34
40
  }
35
41
  interface BrowserClipboardAdapterOptions {
36
42
  /** Defaults to `window`, read lazily at copy time (SSR-safe). */
@@ -49,4 +55,4 @@ interface BrowserClipboardAdapterOptions {
49
55
  declare function createBrowserClipboardAdapter(options?: BrowserClipboardAdapterOptions): ClipboardAdapter;
50
56
  //#endregion
51
57
  export { ClipboardItemData as a, ClipboardItemConstructorLike as i, ClipboardAdapter as n, ClipboardLike as o, ClipboardEnvironment as r, createBrowserClipboardAdapter as s, BrowserClipboardAdapterOptions as t };
52
- //# sourceMappingURL=clipboard-adapter-CUvmAcRE.d.cts.map
58
+ //# sourceMappingURL=clipboard-adapter-B55TgPYd.d.ts.map
@@ -1,5 +1,5 @@
1
1
 
2
- import { k as OperationContext, r as CopyPayload } from "./payload-CcvSx_Hq.js";
2
+ import { i as CopyPayload, j as OperationContext } from "./payload-BKDabKYy.cjs";
3
3
  //#region src/core/clipboard-adapter.d.ts
4
4
  /** Minimal structural view of `navigator.clipboard`, so fakes and polyfills fit. */
5
5
  interface ClipboardLike {
@@ -31,6 +31,12 @@ interface ClipboardEnvironment {
31
31
  */
32
32
  interface ClipboardAdapter {
33
33
  write(payload: CopyPayload, context?: OperationContext): Promise<void>;
34
+ /**
35
+ * Optional: write text that is still being produced (an async copy source), starting the
36
+ * platform write now so the user's gesture is kept. Without it, the machine waits for the
37
+ * text and calls `write`, which suits clipboards with no gesture rules (Electron, tests).
38
+ */
39
+ writeDeferred?(text: Promise<string>, context?: OperationContext): Promise<void>;
34
40
  }
35
41
  interface BrowserClipboardAdapterOptions {
36
42
  /** Defaults to `window`, read lazily at copy time (SSR-safe). */
@@ -49,4 +55,4 @@ interface BrowserClipboardAdapterOptions {
49
55
  declare function createBrowserClipboardAdapter(options?: BrowserClipboardAdapterOptions): ClipboardAdapter;
50
56
  //#endregion
51
57
  export { ClipboardItemData as a, ClipboardItemConstructorLike as i, ClipboardAdapter as n, ClipboardLike as o, ClipboardEnvironment as r, createBrowserClipboardAdapter as s, BrowserClipboardAdapterOptions as t };
52
- //# sourceMappingURL=clipboard-adapter-CdOzN135.d.ts.map
58
+ //# sourceMappingURL=clipboard-adapter-C1_Mvpcc.d.cts.map
@@ -211,6 +211,32 @@ async function writeToClipboard(payload, env, settings, context) {
211
211
  }
212
212
  }
213
213
  }
214
+ /**
215
+ * Text that is still being produced. Where `ClipboardItem` exists, the write starts now with a
216
+ * *promise* of the text, so Safari keeps the user's gesture while it arrives. Elsewhere (and
217
+ * when that write is refused), the text is awaited and written as usual: Chromium and Firefox
218
+ * keep the gesture for several seconds, and the copy-command fallbacks still apply.
219
+ */
220
+ async function writeDeferredText(text, env, settings, context) {
221
+ text.catch(noop);
222
+ const afterwards = async () => writeToClipboard({
223
+ kind: "text",
224
+ value: await text
225
+ }, env, settings, context);
226
+ const clipboard = env?.isSecureContext === false ? void 0 : env?.navigator?.clipboard;
227
+ const rich = env && clipboard ? getRichClipboard(env, clipboard) : null;
228
+ if (!rich || !isTypeSupported(rich.Item, "text/plain")) return afterwards();
229
+ const blob = text.then((value) => new Blob([value], { type: "text/plain" }));
230
+ blob.catch(noop);
231
+ try {
232
+ await rich.write([new rich.Item({ "text/plain": blob })]);
233
+ } catch (error) {
234
+ const reason = await text.then(noop, (inner) => inner);
235
+ if (reason === void 0 && error?.name === "NotAllowedError") return afterwards();
236
+ throw reason ?? error;
237
+ }
238
+ await text;
239
+ }
214
240
  /** The default adapter: async Clipboard API with feature detection and honest errors. */
215
241
  function createBrowserClipboardAdapter(options = {}) {
216
242
  const getEnvironment = options.getEnvironment ?? defaultEnvironment;
@@ -218,7 +244,10 @@ function createBrowserClipboardAdapter(options = {}) {
218
244
  degradeHtmlToText: options.degradeHtmlToText ?? true,
219
245
  legacyFallback: options.legacyFallback ?? true
220
246
  };
221
- return { write: (payload, context) => writeToClipboard(payload, getEnvironment(), settings, context) };
247
+ return {
248
+ write: (payload, context) => writeToClipboard(payload, getEnvironment(), settings, context),
249
+ writeDeferred: (text, context) => writeDeferredText(text, getEnvironment(), settings, context)
250
+ };
222
251
  }
223
252
  //#endregion
224
253
  Object.defineProperty(exports, "createBrowserClipboardAdapter", {
@@ -228,4 +257,4 @@ Object.defineProperty(exports, "createBrowserClipboardAdapter", {
228
257
  }
229
258
  });
230
259
 
231
- //# sourceMappingURL=clipboard-adapter-CfI4O02E.cjs.map
260
+ //# sourceMappingURL=clipboard-adapter-DYo79Fdq.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clipboard-adapter-DYo79Fdq.cjs","names":["serializeJson","isWebCustomFormat","CopyFailure","createCopyError","isBlob","IMAGE_MIME_TYPE","serializeJson"],"sources":["../../src/core/legacy-copy.ts","../../src/core/clipboard-adapter.ts"],"sourcesContent":["/**\n * The copy that works where the async Clipboard API does not: plain HTTP pages (intranets,\n * internal tools on an IP address) and webviews without `navigator.clipboard`.\n *\n * `document.execCommand('copy')` fires a `copy` event whose `clipboardData` takes any text\n * format, so the payload is written exactly, as text and HTML alike. Nothing is shown and\n * nothing moves: the selection the command needs is made on a node outside the layout, and\n * the user's own selection and focus are put back before the function returns. It runs\n * synchronously, inside the user's gesture. Internal: not part of the public API.\n */\nimport { isWebCustomFormat } from './mime';\nimport { serializeJson, type CopyPayload } from './payload';\n\n/** Each format and its text, in the order written. */\nexport type LegacyEntries = readonly (readonly [format: string, data: string])[];\n\n/** What can travel through a copy event: every text format, no images, no blobs, no web custom formats. */\nexport function legacyEntries(payload: CopyPayload): LegacyEntries | null {\n switch (payload.kind) {\n case 'text':\n return [['text/plain', payload.value]];\n case 'json':\n return [['text/plain', serializeJson(payload)]];\n case 'html':\n return [\n ['text/html', payload.html],\n ['text/plain', payload.text],\n ];\n case 'image':\n return null;\n case 'multi': {\n const entries: (readonly [string, string])[] = [];\n for (const { mimeType, data, optional } of payload.items) {\n if (typeof data === 'string' && !isWebCustomFormat(mimeType)) entries.push([mimeType, data]);\n // A required format that a copy event cannot carry: the copy would be incomplete.\n else if (optional !== true) return null;\n }\n return entries.length > 0 ? entries : null;\n }\n }\n}\n\ntype SavedFocus = readonly [element: HTMLElement, range: readonly [number, number, 'forward' | 'backward' | 'none'] | null];\n\nfunction saveFocus(doc: Document): SavedFocus | null {\n const element = doc.activeElement as (HTMLElement & Partial<HTMLInputElement>) | null;\n if (!element || element === doc.body) return null;\n try {\n const { selectionStart: start, selectionEnd: end, selectionDirection: direction } = element;\n return [element, typeof start === 'number' && typeof end === 'number' ? [start, end, direction ?? 'none'] : null];\n } catch {\n // Older engines throw for inputs without a selection API (email, number).\n return [element, null];\n }\n}\n\nfunction restoreFocus(doc: Document, saved: SavedFocus | null): void {\n if (!saved?.[0].isConnected) return;\n const [element, range] = saved;\n if (doc.activeElement !== element) element.focus({ preventScroll: true });\n if (range) (element as HTMLInputElement).setSelectionRange(...range);\n}\n\n/**\n * Writes `entries` through `execCommand('copy')`. Returns whether the browser took them;\n * `false` leaves the clipboard as it was (the caller reports its own, classified error).\n */\nexport function legacyCopy(doc: Document, entries: LegacyEntries): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/no-deprecated -- missing in some webviews; the only copy without the async API\n if (typeof doc.execCommand !== 'function' || !doc.body) return false;\n // Set by the listener: an object, so the check after `execCommand` reads its latest value.\n const seen = { written: false };\n const onCopy = (event: Event): void => {\n const data = (event as ClipboardEvent).clipboardData;\n if (!data) return;\n event.preventDefault();\n // This copy carries an exact payload: page copy handlers and interceptors must not rewrite it.\n event.stopImmediatePropagation();\n try {\n for (const [format, value] of entries) data.setData(format, value);\n seen.written = true;\n } catch {\n // A format the browser refuses: the copy is reported as failed, not thrown into the page.\n }\n };\n\n // Saved first: in some engines reading or moving the selection already moves focus.\n const focus = saveFocus(doc);\n const selection = doc.getSelection();\n const ranges: Range[] = [];\n if (selection) for (let index = 0; index < selection.rangeCount; index += 1) ranges.push(selection.getRangeAt(index));\n\n // The copy command is only enabled over a selection, so select something nobody can see.\n const holder = doc.createElement('span');\n // One character enables the command; the payload itself goes through the event.\n // (The full text here cost 100 ms of layout for a megabyte.)\n holder.textContent = '\\u00a0';\n holder.setAttribute('aria-hidden', 'true');\n // CSSOM, not a style attribute: allowed under a strict Content Security Policy.\n holder.style.cssText = 'position:fixed;top:0;left:0;clip-path:inset(50%);white-space:pre;user-select:text;-webkit-user-select:text';\n\n doc.addEventListener('copy', onCopy, true);\n doc.body.append(holder);\n try {\n if (selection) {\n const range = doc.createRange();\n range.selectNodeContents(holder);\n selection.removeAllRanges();\n selection.addRange(range);\n }\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the only copy without the async API\n doc.execCommand('copy');\n } catch {\n // Reported through `written`, which the listener never set.\n } finally {\n doc.removeEventListener('copy', onCopy, true);\n holder.remove();\n if (selection) {\n selection.removeAllRanges();\n for (const range of ranges) selection.addRange(range);\n }\n restoreFocus(doc, focus);\n }\n return seen.written;\n}\n","import { CopyFailure, createCopyError, type CopyErrorType } from './errors';\nimport { legacyCopy, legacyEntries } from './legacy-copy';\nimport type { OperationContext } from './machine-shared';\nimport { IMAGE_MIME_TYPE, isBlob, serializeJson, type BlobSource, type CopyPayload } from './payload';\n\n/** Minimal structural view of `navigator.clipboard`, so fakes and polyfills fit. */\nexport interface ClipboardLike {\n writeText?(text: string): Promise<void>;\n write?(items: readonly unknown[]): Promise<void>;\n}\n\nexport type ClipboardItemData = Blob | PromiseLike<Blob>;\n\nexport interface ClipboardItemConstructorLike {\n new (items: Record<string, ClipboardItemData>): unknown;\n supports?(type: string): boolean;\n}\n\nexport interface ClipboardEnvironment {\n readonly isSecureContext?: boolean;\n /** For the `execCommand('copy')` fallback; `window` has it. */\n readonly document?: Document | undefined;\n readonly navigator?: { readonly clipboard?: ClipboardLike | undefined } | undefined;\n readonly ClipboardItem?: ClipboardItemConstructorLike | undefined;\n}\n\n/**\n * The only thing the state machine needs. Implement it to target Electron,\n * a native bridge, a test double, or anything else.\n *\n * Contract: start the platform write synchronously (before any `await`) so the\n * browser still sees the user gesture, and reject with a `CopyFailure` when you\n * can classify the error. `context.signal` aborts when the copy is reset or its\n * host unmounts; honour it to stop expensive work early.\n */\nexport interface ClipboardAdapter {\n write(payload: CopyPayload, context?: OperationContext): Promise<void>;\n /**\n * Optional: write text that is still being produced (an async copy source), starting the\n * platform write now so the user's gesture is kept. Without it, the machine waits for the\n * text and calls `write`, which suits clipboards with no gesture rules (Electron, tests).\n */\n writeDeferred?(text: Promise<string>, context?: OperationContext): Promise<void>;\n}\n\nexport interface BrowserClipboardAdapterOptions {\n /** Defaults to `window`, read lazily at copy time (SSR-safe). */\n readonly getEnvironment?: () => ClipboardEnvironment | undefined;\n /** When rich HTML copy is unavailable, fall back to its plain text. Default `true`. */\n readonly degradeHtmlToText?: boolean;\n /**\n * When the async Clipboard API is unavailable (a plain-HTTP page, a webview without\n * `navigator.clipboard`, no `ClipboardItem` for HTML), copy text, HTML and JSON through the\n * browser's `copy` command instead, as `react-copy-to-clipboard` does. Images still need the\n * async API. Default `true`; `false` reports `insecure-context` / `unsupported` instead.\n */\n readonly legacyFallback?: boolean;\n}\n\ninterface RichClipboard {\n readonly Item: ClipboardItemConstructorLike;\n readonly write: (items: readonly unknown[]) => Promise<void>;\n}\n\nconst fail = (type: CopyErrorType, message: string, cause?: unknown): CopyFailure =>\n new CopyFailure(createCopyError(type, message, cause));\n\nconst noop = (): void => undefined;\n\nfunction defaultEnvironment(): ClipboardEnvironment | undefined {\n return typeof window === 'undefined' ? undefined : window;\n}\n\nfunction getRichClipboard(env: ClipboardEnvironment, clipboard: ClipboardLike): RichClipboard | null {\n const Item = env.ClipboardItem;\n if (!Item || typeof clipboard.write !== 'function') return null;\n return { Item, write: clipboard.write.bind(clipboard) };\n}\n\nfunction isTypeSupported(Item: ClipboardItemConstructorLike, type: string): boolean {\n return typeof Item.supports !== 'function' || Item.supports(type);\n}\n\nasync function resolveImageBlob(source: BlobSource, context: OperationContext | undefined): Promise<Blob> {\n let blob: unknown;\n try {\n // Invoked before the first await, i.e. synchronously inside the gesture.\n blob = await (typeof source === 'function' ? source(context ?? { signal: new AbortController().signal }) : source);\n } catch (cause) {\n if (context?.signal.aborted) throw fail('aborted', 'The image copy was cancelled.', cause);\n throw fail('blob-generation-failed', 'The image source threw or rejected while producing a Blob.', cause);\n }\n if (!isBlob(blob)) throw fail('blob-generation-failed', 'The image source did not produce a Blob.');\n if (blob.type !== IMAGE_MIME_TYPE) {\n throw fail(\n 'unsupported-format',\n `Only ${IMAGE_MIME_TYPE} can be written to the clipboard (received \"${blob.type || 'unknown'}\"). ` +\n `Convert with canvas.toBlob(cb, \"${IMAGE_MIME_TYPE}\").`,\n );\n }\n return blob;\n}\n\nasync function writeImage(\n rich: RichClipboard,\n source: BlobSource,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!isTypeSupported(rich.Item, IMAGE_MIME_TYPE)) {\n throw fail('unsupported-format', `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);\n }\n // Hand ClipboardItem a *promise* so Safari keeps the gesture while the blob is produced.\n const blob = resolveImageBlob(source, context);\n blob.catch(noop); // Never an unhandled rejection, whichever side fails first.\n try {\n await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);\n } catch (error) {\n // Browsers replace our classified reason with a generic DOMException. Prefer ours.\n const reason = await blob.then(noop, (inner: unknown) => inner);\n throw reason ?? error;\n }\n // Conforming browsers have consumed `blob` by now. Lax polyfills/webviews may resolve\n // without reading it: never report an image that failed to generate as copied.\n await blob;\n}\n\nasync function writeToClipboard(\n payload: CopyPayload,\n env: ClipboardEnvironment | undefined,\n settings: Required<Omit<BrowserClipboardAdapterOptions, 'getEnvironment'>>,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!env) throw fail('unsupported', 'No browser environment: the clipboard only exists in the browser.');\n /** Without the async API: the copy command if it can carry this payload, else `failure`. */\n const legacy = (failure: unknown): void => {\n const entries = settings.legacyFallback && env.document ? legacyEntries(payload) : null;\n if (entries && legacyCopy(env.document as Document, entries)) return;\n throw failure;\n };\n /**\n * A write the browser refused with `NotAllowedError`, most often a permissions policy: a\n * Microsoft Teams tab, a SharePoint web part or a Storybook canvas is an iframe without\n * `allow=\"clipboard-write\"`. The copy command is not gated by that policy, so it is tried while\n * the user's gesture is still fresh; when it cannot help, the browser's own error stands.\n */\n const orLegacy = (write: Promise<void>): Promise<void> =>\n write.catch((cause: unknown) => {\n if ((cause as { name?: unknown } | null)?.name !== 'NotAllowedError' || context?.signal.aborted === true) throw cause;\n legacy(cause);\n });\n if (env.isSecureContext === false) {\n legacy(fail('insecure-context', 'The Clipboard API requires a secure context (HTTPS or localhost).'));\n return;\n }\n const clipboard = env.navigator?.clipboard;\n if (!clipboard) {\n legacy(fail('unsupported', 'navigator.clipboard is not available in this browser.'));\n return;\n }\n\n switch (payload.kind) {\n case 'text':\n case 'json': {\n const text = payload.kind === 'text' ? payload.value : serializeJson(payload);\n if (typeof clipboard.writeText === 'function') return orLegacy(clipboard.writeText(text));\n legacy(fail('unsupported', 'navigator.clipboard.writeText() is not available.'));\n return;\n }\n\n case 'html': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich || !isTypeSupported(rich.Item, 'text/html')) {\n const failure = fail('unsupported-format', 'Rich HTML copy requires ClipboardItem and navigator.clipboard.write().');\n try {\n legacy(failure);\n return;\n } catch {\n if (settings.degradeHtmlToText && typeof clipboard.writeText === 'function') return clipboard.writeText(payload.text);\n throw failure;\n }\n }\n return orLegacy(\n rich.write([\n new rich.Item({\n 'text/html': new Blob([payload.html], { type: 'text/html' }),\n 'text/plain': new Blob([payload.text], { type: 'text/plain' }),\n }),\n ]),\n );\n }\n\n case 'image': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich) throw fail('unsupported-format', 'Image copy requires ClipboardItem and navigator.clipboard.write().');\n return writeImage(rich, payload.blob, context);\n }\n\n case 'multi': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich) {\n legacy(fail('unsupported-format', 'Multi-format copy requires ClipboardItem and navigator.clipboard.write().'));\n return;\n }\n const record: Record<string, ClipboardItemData> = Object.create(null) as Record<string, ClipboardItemData>;\n let written = 0;\n for (const { mimeType, data, optional } of payload.items) {\n // Optional items need positive confirmation: an unknown type can make the whole write reject.\n if (optional === true && !(typeof rich.Item.supports === 'function' && rich.Item.supports(mimeType))) continue;\n if (!isTypeSupported(rich.Item, mimeType)) {\n throw fail('unsupported-format', `This browser cannot write \"${mimeType}\" to the clipboard.`);\n }\n record[mimeType] = typeof data === 'string' ? new Blob([data], { type: mimeType }) : data;\n written += 1;\n }\n if (written === 0) throw fail('unsupported-format', 'This browser can write none of the payload types.');\n return orLegacy(rich.write([new rich.Item(record)]));\n }\n }\n}\n\n/**\n * Text that is still being produced. Where `ClipboardItem` exists, the write starts now with a\n * *promise* of the text, so Safari keeps the user's gesture while it arrives. Elsewhere (and\n * when that write is refused), the text is awaited and written as usual: Chromium and Firefox\n * keep the gesture for several seconds, and the copy-command fallbacks still apply.\n */\nasync function writeDeferredText(\n text: Promise<string>,\n env: ClipboardEnvironment | undefined,\n settings: Required<Omit<BrowserClipboardAdapterOptions, 'getEnvironment'>>,\n context: OperationContext | undefined,\n): Promise<void> {\n text.catch(noop); // Never an unhandled rejection, whichever side fails first.\n const afterwards = async (): Promise<void> => writeToClipboard({ kind: 'text', value: await text }, env, settings, context);\n const clipboard = env?.isSecureContext === false ? undefined : env?.navigator?.clipboard;\n const rich = env && clipboard ? getRichClipboard(env, clipboard) : null;\n if (!rich || !isTypeSupported(rich.Item, 'text/plain')) return afterwards();\n const blob = text.then((value) => new Blob([value], { type: 'text/plain' }));\n blob.catch(noop);\n try {\n await rich.write([new rich.Item({ 'text/plain': blob })]);\n } catch (error) {\n // The source's own failure explains more than the browser's generic one.\n const reason = await text.then(noop, (inner: unknown) => inner);\n // Refused (an embedded iframe): the plain write and its copy-command fallback.\n if (reason === undefined && (error as { name?: unknown } | null)?.name === 'NotAllowedError') return afterwards();\n throw reason ?? error;\n }\n // As for images: never report text that failed to arrive as copied.\n await text;\n}\n\n/** The default adapter: async Clipboard API with feature detection and honest errors. */\nexport function createBrowserClipboardAdapter(options: BrowserClipboardAdapterOptions = {}): ClipboardAdapter {\n const getEnvironment = options.getEnvironment ?? defaultEnvironment;\n const settings = { degradeHtmlToText: options.degradeHtmlToText ?? true, legacyFallback: options.legacyFallback ?? true };\n return {\n write: (payload, context) => writeToClipboard(payload, getEnvironment(), settings, context),\n writeDeferred: (text, context) => writeDeferredText(text, getEnvironment(), settings, context),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,SAAgB,cAAc,SAA4C;CACxE,QAAQ,QAAQ,MAAhB;EACE,KAAK,QACH,OAAO,CAAC,CAAC,cAAc,QAAQ,KAAK,CAAC;EACvC,KAAK,QACH,OAAO,CAAC,CAAC,cAAcA,gBAAAA,cAAc,OAAO,CAAC,CAAC;EAChD,KAAK,QACH,OAAO,CACL,CAAC,aAAa,QAAQ,IAAI,GAC1B,CAAC,cAAc,QAAQ,IAAI,CAC7B;EACF,KAAK,SACH,OAAO;EACT,KAAK,SAAS;GACZ,MAAM,UAAyC,CAAC;GAChD,KAAK,MAAM,EAAE,UAAU,MAAM,cAAc,QAAQ,OACjD,IAAI,OAAO,SAAS,YAAY,CAACC,aAAAA,kBAAkB,QAAQ,GAAG,QAAQ,KAAK,CAAC,UAAU,IAAI,CAAC;QAEtF,IAAI,aAAa,MAAM,OAAO;GAErC,OAAO,QAAQ,SAAS,IAAI,UAAU;EACxC;CACF;AACF;AAIA,SAAS,UAAU,KAAkC;CACnD,MAAM,UAAU,IAAI;CACpB,IAAI,CAAC,WAAW,YAAY,IAAI,MAAM,OAAO;CAC7C,IAAI;EACF,MAAM,EAAE,gBAAgB,OAAO,cAAc,KAAK,oBAAoB,cAAc;EACpF,OAAO,CAAC,SAAS,OAAO,UAAU,YAAY,OAAO,QAAQ,WAAW;GAAC;GAAO;GAAK,aAAa;EAAM,IAAI,IAAI;CAClH,QAAQ;EAEN,OAAO,CAAC,SAAS,IAAI;CACvB;AACF;AAEA,SAAS,aAAa,KAAe,OAAgC;CACnE,IAAI,CAAC,QAAQ,EAAE,CAAC,aAAa;CAC7B,MAAM,CAAC,SAAS,SAAS;CACzB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,KAAK,MAAM,IAAI;CACf,MAAM,aAAa,YAA2B,iBAAiB;EAAE,MAAM;EAAQ,OAAO,MAAM;CAAK,GAAG,KAAK,UAAU,OAAO;CAC1H,MAAM,YAAY,KAAK,oBAAoB,QAAQ,KAAA,IAAY,KAAK,WAAW;CAC/E,MAAM,OAAO,OAAO,YAAY,iBAAiB,KAAK,SAAS,IAAI;CACnE,IAAI,CAAC,QAAQ,CAAC,gBAAgB,KAAK,MAAM,YAAY,GAAG,OAAO,WAAW;CAC1E,MAAM,OAAO,KAAK,MAAM,UAAU,IAAI,KAAK,CAAC,KAAK,GAAG,EAAE,MAAM,aAAa,CAAC,CAAC;CAC3E,KAAK,MAAM,IAAI;CACf,IAAI;EACF,MAAM,KAAK,MAAM,CAAC,IAAI,KAAK,KAAK,EAAE,cAAc,KAAK,CAAC,CAAC,CAAC;CAC1D,SAAS,OAAO;EAEd,MAAM,SAAS,MAAM,KAAK,KAAK,OAAO,UAAmB,KAAK;EAE9D,IAAI,WAAW,KAAA,KAAc,OAAqC,SAAS,mBAAmB,OAAO,WAAW;EAChH,MAAM,UAAU;CAClB;CAEA,MAAM;AACR;;AAGA,SAAgB,8BAA8B,UAA0C,CAAC,GAAqB;CAC5G,MAAM,iBAAiB,QAAQ,kBAAkB;CACjD,MAAM,WAAW;EAAE,mBAAmB,QAAQ,qBAAqB;EAAM,gBAAgB,QAAQ,kBAAkB;CAAK;CACxH,OAAO;EACL,QAAQ,SAAS,YAAY,iBAAiB,SAAS,eAAe,GAAG,UAAU,OAAO;EAC1F,gBAAgB,MAAM,YAAY,kBAAkB,MAAM,eAAe,GAAG,UAAU,OAAO;CAC/F;AACF"}
@@ -211,6 +211,32 @@ async function writeToClipboard(payload, env, settings, context) {
211
211
  }
212
212
  }
213
213
  }
214
+ /**
215
+ * Text that is still being produced. Where `ClipboardItem` exists, the write starts now with a
216
+ * *promise* of the text, so Safari keeps the user's gesture while it arrives. Elsewhere (and
217
+ * when that write is refused), the text is awaited and written as usual: Chromium and Firefox
218
+ * keep the gesture for several seconds, and the copy-command fallbacks still apply.
219
+ */
220
+ async function writeDeferredText(text, env, settings, context) {
221
+ text.catch(noop);
222
+ const afterwards = async () => writeToClipboard({
223
+ kind: "text",
224
+ value: await text
225
+ }, env, settings, context);
226
+ const clipboard = env?.isSecureContext === false ? void 0 : env?.navigator?.clipboard;
227
+ const rich = env && clipboard ? getRichClipboard(env, clipboard) : null;
228
+ if (!rich || !isTypeSupported(rich.Item, "text/plain")) return afterwards();
229
+ const blob = text.then((value) => new Blob([value], { type: "text/plain" }));
230
+ blob.catch(noop);
231
+ try {
232
+ await rich.write([new rich.Item({ "text/plain": blob })]);
233
+ } catch (error) {
234
+ const reason = await text.then(noop, (inner) => inner);
235
+ if (reason === void 0 && error?.name === "NotAllowedError") return afterwards();
236
+ throw reason ?? error;
237
+ }
238
+ await text;
239
+ }
214
240
  /** The default adapter: async Clipboard API with feature detection and honest errors. */
215
241
  function createBrowserClipboardAdapter(options = {}) {
216
242
  const getEnvironment = options.getEnvironment ?? defaultEnvironment;
@@ -218,9 +244,12 @@ function createBrowserClipboardAdapter(options = {}) {
218
244
  degradeHtmlToText: options.degradeHtmlToText ?? true,
219
245
  legacyFallback: options.legacyFallback ?? true
220
246
  };
221
- return { write: (payload, context) => writeToClipboard(payload, getEnvironment(), settings, context) };
247
+ return {
248
+ write: (payload, context) => writeToClipboard(payload, getEnvironment(), settings, context),
249
+ writeDeferred: (text, context) => writeDeferredText(text, getEnvironment(), settings, context)
250
+ };
222
251
  }
223
252
  //#endregion
224
253
  export { createBrowserClipboardAdapter as t };
225
254
 
226
- //# sourceMappingURL=clipboard-adapter-DX5yd8_6.js.map
255
+ //# sourceMappingURL=clipboard-adapter-XS23N-Gg.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clipboard-adapter-XS23N-Gg.js","names":[],"sources":["../../src/core/legacy-copy.ts","../../src/core/clipboard-adapter.ts"],"sourcesContent":["/**\n * The copy that works where the async Clipboard API does not: plain HTTP pages (intranets,\n * internal tools on an IP address) and webviews without `navigator.clipboard`.\n *\n * `document.execCommand('copy')` fires a `copy` event whose `clipboardData` takes any text\n * format, so the payload is written exactly, as text and HTML alike. Nothing is shown and\n * nothing moves: the selection the command needs is made on a node outside the layout, and\n * the user's own selection and focus are put back before the function returns. It runs\n * synchronously, inside the user's gesture. Internal: not part of the public API.\n */\nimport { isWebCustomFormat } from './mime';\nimport { serializeJson, type CopyPayload } from './payload';\n\n/** Each format and its text, in the order written. */\nexport type LegacyEntries = readonly (readonly [format: string, data: string])[];\n\n/** What can travel through a copy event: every text format, no images, no blobs, no web custom formats. */\nexport function legacyEntries(payload: CopyPayload): LegacyEntries | null {\n switch (payload.kind) {\n case 'text':\n return [['text/plain', payload.value]];\n case 'json':\n return [['text/plain', serializeJson(payload)]];\n case 'html':\n return [\n ['text/html', payload.html],\n ['text/plain', payload.text],\n ];\n case 'image':\n return null;\n case 'multi': {\n const entries: (readonly [string, string])[] = [];\n for (const { mimeType, data, optional } of payload.items) {\n if (typeof data === 'string' && !isWebCustomFormat(mimeType)) entries.push([mimeType, data]);\n // A required format that a copy event cannot carry: the copy would be incomplete.\n else if (optional !== true) return null;\n }\n return entries.length > 0 ? entries : null;\n }\n }\n}\n\ntype SavedFocus = readonly [element: HTMLElement, range: readonly [number, number, 'forward' | 'backward' | 'none'] | null];\n\nfunction saveFocus(doc: Document): SavedFocus | null {\n const element = doc.activeElement as (HTMLElement & Partial<HTMLInputElement>) | null;\n if (!element || element === doc.body) return null;\n try {\n const { selectionStart: start, selectionEnd: end, selectionDirection: direction } = element;\n return [element, typeof start === 'number' && typeof end === 'number' ? [start, end, direction ?? 'none'] : null];\n } catch {\n // Older engines throw for inputs without a selection API (email, number).\n return [element, null];\n }\n}\n\nfunction restoreFocus(doc: Document, saved: SavedFocus | null): void {\n if (!saved?.[0].isConnected) return;\n const [element, range] = saved;\n if (doc.activeElement !== element) element.focus({ preventScroll: true });\n if (range) (element as HTMLInputElement).setSelectionRange(...range);\n}\n\n/**\n * Writes `entries` through `execCommand('copy')`. Returns whether the browser took them;\n * `false` leaves the clipboard as it was (the caller reports its own, classified error).\n */\nexport function legacyCopy(doc: Document, entries: LegacyEntries): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/no-deprecated -- missing in some webviews; the only copy without the async API\n if (typeof doc.execCommand !== 'function' || !doc.body) return false;\n // Set by the listener: an object, so the check after `execCommand` reads its latest value.\n const seen = { written: false };\n const onCopy = (event: Event): void => {\n const data = (event as ClipboardEvent).clipboardData;\n if (!data) return;\n event.preventDefault();\n // This copy carries an exact payload: page copy handlers and interceptors must not rewrite it.\n event.stopImmediatePropagation();\n try {\n for (const [format, value] of entries) data.setData(format, value);\n seen.written = true;\n } catch {\n // A format the browser refuses: the copy is reported as failed, not thrown into the page.\n }\n };\n\n // Saved first: in some engines reading or moving the selection already moves focus.\n const focus = saveFocus(doc);\n const selection = doc.getSelection();\n const ranges: Range[] = [];\n if (selection) for (let index = 0; index < selection.rangeCount; index += 1) ranges.push(selection.getRangeAt(index));\n\n // The copy command is only enabled over a selection, so select something nobody can see.\n const holder = doc.createElement('span');\n // One character enables the command; the payload itself goes through the event.\n // (The full text here cost 100 ms of layout for a megabyte.)\n holder.textContent = '\\u00a0';\n holder.setAttribute('aria-hidden', 'true');\n // CSSOM, not a style attribute: allowed under a strict Content Security Policy.\n holder.style.cssText = 'position:fixed;top:0;left:0;clip-path:inset(50%);white-space:pre;user-select:text;-webkit-user-select:text';\n\n doc.addEventListener('copy', onCopy, true);\n doc.body.append(holder);\n try {\n if (selection) {\n const range = doc.createRange();\n range.selectNodeContents(holder);\n selection.removeAllRanges();\n selection.addRange(range);\n }\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the only copy without the async API\n doc.execCommand('copy');\n } catch {\n // Reported through `written`, which the listener never set.\n } finally {\n doc.removeEventListener('copy', onCopy, true);\n holder.remove();\n if (selection) {\n selection.removeAllRanges();\n for (const range of ranges) selection.addRange(range);\n }\n restoreFocus(doc, focus);\n }\n return seen.written;\n}\n","import { CopyFailure, createCopyError, type CopyErrorType } from './errors';\nimport { legacyCopy, legacyEntries } from './legacy-copy';\nimport type { OperationContext } from './machine-shared';\nimport { IMAGE_MIME_TYPE, isBlob, serializeJson, type BlobSource, type CopyPayload } from './payload';\n\n/** Minimal structural view of `navigator.clipboard`, so fakes and polyfills fit. */\nexport interface ClipboardLike {\n writeText?(text: string): Promise<void>;\n write?(items: readonly unknown[]): Promise<void>;\n}\n\nexport type ClipboardItemData = Blob | PromiseLike<Blob>;\n\nexport interface ClipboardItemConstructorLike {\n new (items: Record<string, ClipboardItemData>): unknown;\n supports?(type: string): boolean;\n}\n\nexport interface ClipboardEnvironment {\n readonly isSecureContext?: boolean;\n /** For the `execCommand('copy')` fallback; `window` has it. */\n readonly document?: Document | undefined;\n readonly navigator?: { readonly clipboard?: ClipboardLike | undefined } | undefined;\n readonly ClipboardItem?: ClipboardItemConstructorLike | undefined;\n}\n\n/**\n * The only thing the state machine needs. Implement it to target Electron,\n * a native bridge, a test double, or anything else.\n *\n * Contract: start the platform write synchronously (before any `await`) so the\n * browser still sees the user gesture, and reject with a `CopyFailure` when you\n * can classify the error. `context.signal` aborts when the copy is reset or its\n * host unmounts; honour it to stop expensive work early.\n */\nexport interface ClipboardAdapter {\n write(payload: CopyPayload, context?: OperationContext): Promise<void>;\n /**\n * Optional: write text that is still being produced (an async copy source), starting the\n * platform write now so the user's gesture is kept. Without it, the machine waits for the\n * text and calls `write`, which suits clipboards with no gesture rules (Electron, tests).\n */\n writeDeferred?(text: Promise<string>, context?: OperationContext): Promise<void>;\n}\n\nexport interface BrowserClipboardAdapterOptions {\n /** Defaults to `window`, read lazily at copy time (SSR-safe). */\n readonly getEnvironment?: () => ClipboardEnvironment | undefined;\n /** When rich HTML copy is unavailable, fall back to its plain text. Default `true`. */\n readonly degradeHtmlToText?: boolean;\n /**\n * When the async Clipboard API is unavailable (a plain-HTTP page, a webview without\n * `navigator.clipboard`, no `ClipboardItem` for HTML), copy text, HTML and JSON through the\n * browser's `copy` command instead, as `react-copy-to-clipboard` does. Images still need the\n * async API. Default `true`; `false` reports `insecure-context` / `unsupported` instead.\n */\n readonly legacyFallback?: boolean;\n}\n\ninterface RichClipboard {\n readonly Item: ClipboardItemConstructorLike;\n readonly write: (items: readonly unknown[]) => Promise<void>;\n}\n\nconst fail = (type: CopyErrorType, message: string, cause?: unknown): CopyFailure =>\n new CopyFailure(createCopyError(type, message, cause));\n\nconst noop = (): void => undefined;\n\nfunction defaultEnvironment(): ClipboardEnvironment | undefined {\n return typeof window === 'undefined' ? undefined : window;\n}\n\nfunction getRichClipboard(env: ClipboardEnvironment, clipboard: ClipboardLike): RichClipboard | null {\n const Item = env.ClipboardItem;\n if (!Item || typeof clipboard.write !== 'function') return null;\n return { Item, write: clipboard.write.bind(clipboard) };\n}\n\nfunction isTypeSupported(Item: ClipboardItemConstructorLike, type: string): boolean {\n return typeof Item.supports !== 'function' || Item.supports(type);\n}\n\nasync function resolveImageBlob(source: BlobSource, context: OperationContext | undefined): Promise<Blob> {\n let blob: unknown;\n try {\n // Invoked before the first await, i.e. synchronously inside the gesture.\n blob = await (typeof source === 'function' ? source(context ?? { signal: new AbortController().signal }) : source);\n } catch (cause) {\n if (context?.signal.aborted) throw fail('aborted', 'The image copy was cancelled.', cause);\n throw fail('blob-generation-failed', 'The image source threw or rejected while producing a Blob.', cause);\n }\n if (!isBlob(blob)) throw fail('blob-generation-failed', 'The image source did not produce a Blob.');\n if (blob.type !== IMAGE_MIME_TYPE) {\n throw fail(\n 'unsupported-format',\n `Only ${IMAGE_MIME_TYPE} can be written to the clipboard (received \"${blob.type || 'unknown'}\"). ` +\n `Convert with canvas.toBlob(cb, \"${IMAGE_MIME_TYPE}\").`,\n );\n }\n return blob;\n}\n\nasync function writeImage(\n rich: RichClipboard,\n source: BlobSource,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!isTypeSupported(rich.Item, IMAGE_MIME_TYPE)) {\n throw fail('unsupported-format', `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);\n }\n // Hand ClipboardItem a *promise* so Safari keeps the gesture while the blob is produced.\n const blob = resolveImageBlob(source, context);\n blob.catch(noop); // Never an unhandled rejection, whichever side fails first.\n try {\n await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);\n } catch (error) {\n // Browsers replace our classified reason with a generic DOMException. Prefer ours.\n const reason = await blob.then(noop, (inner: unknown) => inner);\n throw reason ?? error;\n }\n // Conforming browsers have consumed `blob` by now. Lax polyfills/webviews may resolve\n // without reading it: never report an image that failed to generate as copied.\n await blob;\n}\n\nasync function writeToClipboard(\n payload: CopyPayload,\n env: ClipboardEnvironment | undefined,\n settings: Required<Omit<BrowserClipboardAdapterOptions, 'getEnvironment'>>,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!env) throw fail('unsupported', 'No browser environment: the clipboard only exists in the browser.');\n /** Without the async API: the copy command if it can carry this payload, else `failure`. */\n const legacy = (failure: unknown): void => {\n const entries = settings.legacyFallback && env.document ? legacyEntries(payload) : null;\n if (entries && legacyCopy(env.document as Document, entries)) return;\n throw failure;\n };\n /**\n * A write the browser refused with `NotAllowedError`, most often a permissions policy: a\n * Microsoft Teams tab, a SharePoint web part or a Storybook canvas is an iframe without\n * `allow=\"clipboard-write\"`. The copy command is not gated by that policy, so it is tried while\n * the user's gesture is still fresh; when it cannot help, the browser's own error stands.\n */\n const orLegacy = (write: Promise<void>): Promise<void> =>\n write.catch((cause: unknown) => {\n if ((cause as { name?: unknown } | null)?.name !== 'NotAllowedError' || context?.signal.aborted === true) throw cause;\n legacy(cause);\n });\n if (env.isSecureContext === false) {\n legacy(fail('insecure-context', 'The Clipboard API requires a secure context (HTTPS or localhost).'));\n return;\n }\n const clipboard = env.navigator?.clipboard;\n if (!clipboard) {\n legacy(fail('unsupported', 'navigator.clipboard is not available in this browser.'));\n return;\n }\n\n switch (payload.kind) {\n case 'text':\n case 'json': {\n const text = payload.kind === 'text' ? payload.value : serializeJson(payload);\n if (typeof clipboard.writeText === 'function') return orLegacy(clipboard.writeText(text));\n legacy(fail('unsupported', 'navigator.clipboard.writeText() is not available.'));\n return;\n }\n\n case 'html': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich || !isTypeSupported(rich.Item, 'text/html')) {\n const failure = fail('unsupported-format', 'Rich HTML copy requires ClipboardItem and navigator.clipboard.write().');\n try {\n legacy(failure);\n return;\n } catch {\n if (settings.degradeHtmlToText && typeof clipboard.writeText === 'function') return clipboard.writeText(payload.text);\n throw failure;\n }\n }\n return orLegacy(\n rich.write([\n new rich.Item({\n 'text/html': new Blob([payload.html], { type: 'text/html' }),\n 'text/plain': new Blob([payload.text], { type: 'text/plain' }),\n }),\n ]),\n );\n }\n\n case 'image': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich) throw fail('unsupported-format', 'Image copy requires ClipboardItem and navigator.clipboard.write().');\n return writeImage(rich, payload.blob, context);\n }\n\n case 'multi': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich) {\n legacy(fail('unsupported-format', 'Multi-format copy requires ClipboardItem and navigator.clipboard.write().'));\n return;\n }\n const record: Record<string, ClipboardItemData> = Object.create(null) as Record<string, ClipboardItemData>;\n let written = 0;\n for (const { mimeType, data, optional } of payload.items) {\n // Optional items need positive confirmation: an unknown type can make the whole write reject.\n if (optional === true && !(typeof rich.Item.supports === 'function' && rich.Item.supports(mimeType))) continue;\n if (!isTypeSupported(rich.Item, mimeType)) {\n throw fail('unsupported-format', `This browser cannot write \"${mimeType}\" to the clipboard.`);\n }\n record[mimeType] = typeof data === 'string' ? new Blob([data], { type: mimeType }) : data;\n written += 1;\n }\n if (written === 0) throw fail('unsupported-format', 'This browser can write none of the payload types.');\n return orLegacy(rich.write([new rich.Item(record)]));\n }\n }\n}\n\n/**\n * Text that is still being produced. Where `ClipboardItem` exists, the write starts now with a\n * *promise* of the text, so Safari keeps the user's gesture while it arrives. Elsewhere (and\n * when that write is refused), the text is awaited and written as usual: Chromium and Firefox\n * keep the gesture for several seconds, and the copy-command fallbacks still apply.\n */\nasync function writeDeferredText(\n text: Promise<string>,\n env: ClipboardEnvironment | undefined,\n settings: Required<Omit<BrowserClipboardAdapterOptions, 'getEnvironment'>>,\n context: OperationContext | undefined,\n): Promise<void> {\n text.catch(noop); // Never an unhandled rejection, whichever side fails first.\n const afterwards = async (): Promise<void> => writeToClipboard({ kind: 'text', value: await text }, env, settings, context);\n const clipboard = env?.isSecureContext === false ? undefined : env?.navigator?.clipboard;\n const rich = env && clipboard ? getRichClipboard(env, clipboard) : null;\n if (!rich || !isTypeSupported(rich.Item, 'text/plain')) return afterwards();\n const blob = text.then((value) => new Blob([value], { type: 'text/plain' }));\n blob.catch(noop);\n try {\n await rich.write([new rich.Item({ 'text/plain': blob })]);\n } catch (error) {\n // The source's own failure explains more than the browser's generic one.\n const reason = await text.then(noop, (inner: unknown) => inner);\n // Refused (an embedded iframe): the plain write and its copy-command fallback.\n if (reason === undefined && (error as { name?: unknown } | null)?.name === 'NotAllowedError') return afterwards();\n throw reason ?? error;\n }\n // As for images: never report text that failed to arrive as copied.\n await text;\n}\n\n/** The default adapter: async Clipboard API with feature detection and honest errors. */\nexport function createBrowserClipboardAdapter(options: BrowserClipboardAdapterOptions = {}): ClipboardAdapter {\n const getEnvironment = options.getEnvironment ?? defaultEnvironment;\n const settings = { degradeHtmlToText: options.degradeHtmlToText ?? true, legacyFallback: options.legacyFallback ?? true };\n return {\n write: (payload, context) => writeToClipboard(payload, getEnvironment(), settings, context),\n writeDeferred: (text, context) => writeDeferredText(text, getEnvironment(), settings, context),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,SAAgB,cAAc,SAA4C;CACxE,QAAQ,QAAQ,MAAhB;EACE,KAAK,QACH,OAAO,CAAC,CAAC,cAAc,QAAQ,KAAK,CAAC;EACvC,KAAK,QACH,OAAO,CAAC,CAAC,cAAc,cAAc,OAAO,CAAC,CAAC;EAChD,KAAK,QACH,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cAAc,KAAK,CAAC,CAAC,CAAC;CAC1D,SAAS,OAAO;EAEd,MAAM,SAAS,MAAM,KAAK,KAAK,OAAO,UAAmB,KAAK;EAE9D,IAAI,WAAW,KAAA,KAAc,OAAqC,SAAS,mBAAmB,OAAO,WAAW;EAChH,MAAM,UAAU;CAClB;CAEA,MAAM;AACR;;AAGA,SAAgB,8BAA8B,UAA0C,CAAC,GAAqB;CAC5G,MAAM,iBAAiB,QAAQ,kBAAkB;CACjD,MAAM,WAAW;EAAE,mBAAmB,QAAQ,qBAAqB;EAAM,gBAAgB,QAAQ,kBAAkB;CAAK;CACxH,OAAO;EACL,QAAQ,SAAS,YAAY,iBAAiB,SAAS,eAAe,GAAG,UAAU,OAAO;EAC1F,gBAAgB,MAAM,YAAY,kBAAkB,MAAM,eAAe,GAAG,UAAU,OAAO;CAC/F;AACF"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { f as TextPayload, l as JsonPayload, o as HtmlPayload, v as CopyError } from "./payload-qkAWVXWA.cjs";
2
+ import { b as CopyError, c as HtmlPayload, d as JsonPayload, m as TextPayload } from "./payload-D7CJ6e2W.js";
3
3
  //#region src/core/copy-interceptor.d.ts
4
4
  /**
5
5
  * Native copy interception: rewrite, redact or block what lands on the
@@ -24,6 +24,8 @@ interface ClipboardDataLike {
24
24
  interface CopyEventLike {
25
25
  readonly type: string;
26
26
  readonly target: EventTarget | null;
27
+ /** The event's path through shadow roots; the first entry is the real target inside a web component. */
28
+ composedPath?(): EventTarget[];
27
29
  readonly clipboardData: ClipboardDataLike | null;
28
30
  readonly defaultPrevented: boolean;
29
31
  preventDefault(): void;
@@ -138,4 +140,4 @@ interface CopyInterceptorOptions extends CopyInterceptOptions {
138
140
  declare function registerCopyInterceptor(root: Element, options: CopyInterceptorOptions | (() => CopyInterceptorOptions)): () => void;
139
141
  //#endregion
140
142
  export { registerCopyInterceptor as _, CopyInterceptOptions as a, CopyInterceptTransform as c, DEFAULT_INTERCEPTED_EVENTS as d, InterceptedCopyKind as f, readCopySelection as g, interceptCopyEvent as h, CopyInterceptFailureMode as i, CopyInterceptorOptions as l, SyncMultiPayload as m, CopyEventLike as n, CopyInterceptOutcome as o, SyncCopyPayload as p, CopyInterceptDecision as r, CopyInterceptPassReason as s, ClipboardDataLike as t, CopySelection as u };
141
- //# sourceMappingURL=copy-interceptor-BClcHS_P.d.cts.map
143
+ //# sourceMappingURL=copy-interceptor-Bet296gH.d.ts.map
@@ -1,5 +1,5 @@
1
1
 
2
- import { f as TextPayload, l as JsonPayload, o as HtmlPayload, v as CopyError } from "./payload-CcvSx_Hq.js";
2
+ import { b as CopyError, c as HtmlPayload, d as JsonPayload, m as TextPayload } from "./payload-BKDabKYy.cjs";
3
3
  //#region src/core/copy-interceptor.d.ts
4
4
  /**
5
5
  * Native copy interception: rewrite, redact or block what lands on the
@@ -24,6 +24,8 @@ interface ClipboardDataLike {
24
24
  interface CopyEventLike {
25
25
  readonly type: string;
26
26
  readonly target: EventTarget | null;
27
+ /** The event's path through shadow roots; the first entry is the real target inside a web component. */
28
+ composedPath?(): EventTarget[];
27
29
  readonly clipboardData: ClipboardDataLike | null;
28
30
  readonly defaultPrevented: boolean;
29
31
  preventDefault(): void;
@@ -138,4 +140,4 @@ interface CopyInterceptorOptions extends CopyInterceptOptions {
138
140
  declare function registerCopyInterceptor(root: Element, options: CopyInterceptorOptions | (() => CopyInterceptorOptions)): () => void;
139
141
  //#endregion
140
142
  export { registerCopyInterceptor as _, CopyInterceptOptions as a, CopyInterceptTransform as c, DEFAULT_INTERCEPTED_EVENTS as d, InterceptedCopyKind as f, readCopySelection as g, interceptCopyEvent as h, CopyInterceptFailureMode as i, CopyInterceptorOptions as l, SyncMultiPayload as m, CopyEventLike as n, CopyInterceptOutcome as o, SyncCopyPayload as p, CopyInterceptDecision as r, CopyInterceptPassReason as s, ClipboardDataLike as t, CopySelection as u };
141
- //# sourceMappingURL=copy-interceptor-D8c9EDnO.d.ts.map
143
+ //# sourceMappingURL=copy-interceptor-C0AD6C4O.d.cts.map
@@ -1,8 +1,8 @@
1
1
 
2
2
  import { c as toCopyError, n as copyFailure, o as isCopyFailure, r as createCopyError, s as isRetryableError, t as CopyFailure } from "./errors-CGcMvbhJ.js";
3
- import { a as validatePayload, r as normalizePayload } from "./payload-5uJedhwz.js";
3
+ import { a as validatePayload, i as serializeJson, r as normalizePayload } from "./payload-5uJedhwz.js";
4
4
  import { a as matchesMimePattern, i as isWebCustomFormat } from "./mime-aa-HA2dm.js";
5
- import { t as createBrowserClipboardAdapter } from "./clipboard-adapter-DX5yd8_6.js";
5
+ import { t as createBrowserClipboardAdapter } from "./clipboard-adapter-XS23N-Gg.js";
6
6
  import { a as collectClipboardItems, c as finalizePaste, l as resolvePasteReadOptions, o as completePasteResult, s as enforcePasteLimits, u as snapshotDataTransfer } from "./paste-reader-BpXOH_Px.js";
7
7
  //#region src/core/copy-coordinator.ts
8
8
  function createCopyCoordinator() {
@@ -82,6 +82,10 @@ function sourceError(cause, message) {
82
82
  //#endregion
83
83
  //#region src/core/copy-machine.ts
84
84
  const DEFAULT_RESET_AFTER_MS = 2e3;
85
+ const noop = () => void 0;
86
+ function isThenable(value) {
87
+ return typeof value === "object" && value !== null && typeof value.then === "function";
88
+ }
85
89
  const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
86
90
  const IGNORED_IN_FLIGHT$1 = /* @__PURE__ */ Object.freeze({
87
91
  status: "ignored",
@@ -168,63 +172,79 @@ function createCopyMachine(options = {}) {
168
172
  const run = (source, retryCount) => {
169
173
  clearResetTimer();
170
174
  const current = ++generation;
171
- let payload;
172
- try {
173
- const resolved = typeof source === "function" ? source() : source;
174
- const resolvedUnknown = resolved;
175
- if (resolvedUnknown !== null && typeof resolvedUnknown === "object" && typeof resolvedUnknown.then === "function") {
176
- const error = createCopyError("invalid-payload", "The copy source function must be synchronous. Returning a Promise breaks the user-gesture window required for clipboard writes. Generate your content before calling copy().");
177
- settleError(error, null, retryCount);
178
- return Promise.resolve({
179
- status: "error",
180
- error
181
- });
182
- }
183
- payload = normalizePayload(resolved);
184
- } catch (cause) {
185
- const error = sourceError(cause, "The copy source function threw.");
186
- settleError(error, null, retryCount);
175
+ const context = operations.start();
176
+ const fail = (error, payload) => {
177
+ operations.end(context);
178
+ settleError(error, payload, retryCount);
187
179
  return Promise.resolve({
188
180
  status: "error",
189
181
  error
190
182
  });
191
- }
192
- const invalid = validatePayload(payload);
193
- if (invalid) {
194
- settleError(invalid, payload, retryCount);
195
- return Promise.resolve({
196
- status: "error",
197
- error: invalid
198
- });
199
- }
200
- setState({
201
- status: "copying",
202
- payload,
203
- retryCount
204
- });
205
- const context = operations.start();
206
- let pending;
183
+ };
184
+ let resolved;
207
185
  try {
208
- pending = (read().adapter ?? getDefaultAdapter$1()).write(payload, context);
186
+ resolved = typeof source === "function" ? source(context) : source;
209
187
  } catch (cause) {
210
- pending = Promise.reject(cause);
188
+ return fail(sourceError(cause, "The copy source function threw."), null);
189
+ }
190
+ const adapter = read().adapter ?? getDefaultAdapter$1();
191
+ let payload = null;
192
+ let pending;
193
+ if (isThenable(resolved)) {
194
+ const arrived = Promise.resolve(resolved).then((input) => {
195
+ if (context.signal.aborted) throw copyFailure("aborted", "Copying was cancelled.");
196
+ const made = normalizePayload(input);
197
+ if (made.kind !== "text" && made.kind !== "json") throw copyFailure("invalid-payload", "An async copy source must resolve to text or JSON.");
198
+ const invalid = validatePayload(made);
199
+ if (invalid) throw new CopyFailure(invalid);
200
+ payload = made;
201
+ return made.kind === "text" ? made.value : serializeJson(made);
202
+ }, (cause) => {
203
+ throw new CopyFailure(sourceError(cause, "The copy source rejected."));
204
+ });
205
+ setState({
206
+ status: "copying",
207
+ payload: null,
208
+ retryCount
209
+ });
210
+ try {
211
+ pending = (adapter.writeDeferred ? adapter.writeDeferred(arrived, context) : arrived.then(() => adapter.write(payload, context))).then(() => arrived).then(noop);
212
+ } catch (cause) {
213
+ arrived.catch(noop);
214
+ pending = Promise.reject(cause);
215
+ }
216
+ } else {
217
+ payload = normalizePayload(resolved);
218
+ const invalid = validatePayload(payload);
219
+ if (invalid) return fail(invalid, payload);
220
+ setState({
221
+ status: "copying",
222
+ payload,
223
+ retryCount
224
+ });
225
+ try {
226
+ pending = adapter.write(payload, context);
227
+ } catch (cause) {
228
+ pending = Promise.reject(cause);
229
+ }
211
230
  }
212
231
  return pending.then(() => {
213
232
  operations.end(context);
233
+ const done = payload;
214
234
  if (current === generation) {
215
235
  const copied = {
216
236
  status: "copied",
217
- payload,
237
+ payload: done,
218
238
  at: now()
219
239
  };
220
240
  setState(copied);
221
241
  joinCoordinator();
222
242
  scheduleReset(copied);
223
- invoke(read().onCopy, payload);
243
+ invoke(read().onCopy, done);
224
244
  }
225
245
  return {
226
246
  status: "copied",
227
- payload
247
+ payload: done
228
248
  };
229
249
  }, (cause) => {
230
250
  operations.end(context);
@@ -290,6 +310,18 @@ const DEFAULT_INTERCEPTED_EVENTS = ["copy", "cut"];
290
310
  function isNode(value) {
291
311
  return typeof value === "object" && value !== null && typeof value.nodeType === "number";
292
312
  }
313
+ /**
314
+ * The element the event really started at. A copy inside a web component is retargeted to
315
+ * its host by the time a document listener sees it; the composed path still starts inside.
316
+ */
317
+ function deepTarget(event) {
318
+ return event.composedPath?.()[0] ?? event.target;
319
+ }
320
+ /** `root.contains(node)`, also through the shadow roots of web components inside `root`. */
321
+ function containsDeep(root, node) {
322
+ for (let current = node; current; current = current.parentNode ?? current.host ?? null) if (current === root) return true;
323
+ return false;
324
+ }
293
325
  function readTextField(target) {
294
326
  if (!isNode(target) || target.nodeType !== 1) return null;
295
327
  const tag = target.tagName;
@@ -313,19 +345,49 @@ function documentOf(target) {
313
345
  function isEditableNode(node) {
314
346
  return (node.nodeType === 1 ? node : node.parentElement)?.isContentEditable === true;
315
347
  }
348
+ /** An open shadow root at a rescoped boundary: the host the selection was folded onto. */
349
+ function hostRootAt(container, offset) {
350
+ return container.childNodes[offset]?.shadowRoot ?? null;
351
+ }
352
+ /**
353
+ * The selected ranges, inside web components too. Chromium and Firefox already report a
354
+ * selection inside a shadow root as is; Safari folds it onto the component's host, and
355
+ * `getComposedRanges` is the only way to see inside. Open shadow roots are revealed one level
356
+ * at a time from the folded boundaries. A selection that crosses a shadow boundary cannot be
357
+ * one `Range` and keeps the folded range.
358
+ */
316
359
  function selectedRanges(doc) {
317
360
  const selection = doc?.getSelection();
318
- if (!selection || selection.isCollapsed) return null;
361
+ if (!selection) return null;
319
362
  const ranges = [];
320
363
  for (let index = 0; index < selection.rangeCount; index += 1) ranges.push(selection.getRangeAt(index));
321
- return {
364
+ const found = ranges.length === 1 ? composedRange(selection, doc) : null;
365
+ const result = found ? [found] : ranges;
366
+ return result.some((range) => !range.collapsed) ? {
322
367
  selection,
323
- ranges
324
- };
368
+ ranges: result
369
+ } : null;
370
+ }
371
+ function composedRange(selection, doc) {
372
+ const composed = selection;
373
+ if (typeof composed.getComposedRanges !== "function") return null;
374
+ const roots = [];
375
+ let found;
376
+ for (let depth = 0; depth < 8; depth += 1) {
377
+ found = composed.getComposedRanges({ shadowRoots: roots })[0];
378
+ const next = found && (hostRootAt(found.startContainer, found.startOffset) ?? hostRootAt(found.endContainer, found.endOffset - 1));
379
+ if (!next || roots.includes(next)) break;
380
+ roots.push(next);
381
+ }
382
+ if (!found || roots.length === 0 || found.startContainer.getRootNode() !== found.endContainer.getRootNode()) return null;
383
+ const inside = doc.createRange();
384
+ inside.setStart(found.startContainer, found.startOffset);
385
+ inside.setEnd(found.endContainer, found.endOffset);
386
+ return inside;
325
387
  }
326
388
  function readSelection(event) {
327
389
  const kind = event.type === "cut" ? "cut" : "copy";
328
- const fieldSelection = readTextField(event.target);
390
+ const fieldSelection = readTextField(deepTarget(event));
329
391
  if (fieldSelection) {
330
392
  const { field, start, end } = fieldSelection;
331
393
  const text = field.value.slice(Math.min(start, end), Math.max(start, end));
@@ -515,8 +577,8 @@ function interceptCopyEvent(event, options) {
515
577
  }
516
578
  const registries = /* @__PURE__ */ new WeakMap();
517
579
  function touches(root, event) {
518
- const fieldSelection = readTextField(event.target);
519
- if (fieldSelection) return root.contains(fieldSelection.field);
580
+ const fieldSelection = readTextField(deepTarget(event));
581
+ if (fieldSelection) return containsDeep(root, fieldSelection.field);
520
582
  const selected = selectedRanges(root.ownerDocument);
521
583
  return selected !== null && selected.ranges.some((range) => selectsContentOf(range, root));
522
584
  }
@@ -530,14 +592,17 @@ const EMBEDDED_CONTENT = "img,svg,video,audio,canvas,iframe,object,embed,input,t
530
592
  * redaction scope can never be skipped when part of it is copied.
531
593
  */
532
594
  function selectsContentOf(range, root) {
595
+ const tree = range.startContainer.getRootNode();
596
+ if (tree.host && tree !== root.getRootNode()) return containsDeep(root, tree.host) && hasContent(range);
533
597
  if (!range.intersectsNode(root)) return false;
534
598
  const clip = root.ownerDocument.createRange();
535
599
  clip.selectNodeContents(root);
536
600
  if (range.compareBoundaryPoints(0, clip) > 0) clip.setStart(range.startContainer, range.startOffset);
537
601
  if (range.compareBoundaryPoints(2, clip) < 0) clip.setEnd(range.endContainer, range.endOffset);
538
- if (clip.collapsed) return false;
539
- if (clip.toString().trim() !== "") return true;
540
- return clip.cloneContents().querySelector(EMBEDDED_CONTENT) !== null;
602
+ return !clip.collapsed && hasContent(clip);
603
+ }
604
+ function hasContent(range) {
605
+ return range.toString().trim() !== "" || range.cloneContents().querySelector(EMBEDDED_CONTENT) !== null;
541
606
  }
542
607
  const priorityOf = (scope) => scope.read().priority ?? 0;
543
608
  /**
@@ -1115,4 +1180,4 @@ function createPasteMachine(options = {}) {
1115
1180
  //#endregion
1116
1181
  export { DEFAULT_MAX_RETRIES as _, readClipboardPermission as a, createCopyCoordinator as b, registerDragCopy as c, readCopySelection as d, registerCopyInterceptor as f, createCopyMachine as g, canRetryState as h, createBrowserPasteAdapter as i, DEFAULT_INTERCEPTED_EVENTS as l, IDLE_STATE as m, canRetryPasteState as n, watchClipboardPermission as o, DEFAULT_RESET_AFTER_MS as p, createPasteMachine as r, applyDragCopy as s, PASTE_IDLE_STATE as t, interceptCopyEvent as u, invoke as v, resolveMaxRetries as y };
1117
1182
 
1118
- //# sourceMappingURL=core-BE0SO57n.js.map
1183
+ //# sourceMappingURL=core-B8_wVOSU.js.map