react-smart-copy 1.27.1 → 1.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -143,6 +143,16 @@ async function writeToClipboard(payload, env, settings, context) {
143
143
  if (entries && legacyCopy(env.document, entries)) return;
144
144
  throw failure;
145
145
  };
146
+ /**
147
+ * A write the browser refused with `NotAllowedError`, most often a permissions policy: a
148
+ * Microsoft Teams tab, a SharePoint web part or a Storybook canvas is an iframe without
149
+ * `allow="clipboard-write"`. The copy command is not gated by that policy, so it is tried while
150
+ * the user's gesture is still fresh; when it cannot help, the browser's own error stands.
151
+ */
152
+ const orLegacy = (write) => write.catch((cause) => {
153
+ if (cause?.name !== "NotAllowedError" || context?.signal.aborted === true) throw cause;
154
+ legacy(cause);
155
+ });
146
156
  if (env.isSecureContext === false) {
147
157
  legacy(fail("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost)."));
148
158
  return;
@@ -156,7 +166,7 @@ async function writeToClipboard(payload, env, settings, context) {
156
166
  case "text":
157
167
  case "json": {
158
168
  const text = payload.kind === "text" ? payload.value : require_payload.serializeJson(payload);
159
- if (typeof clipboard.writeText === "function") return clipboard.writeText(text);
169
+ if (typeof clipboard.writeText === "function") return orLegacy(clipboard.writeText(text));
160
170
  legacy(fail("unsupported", "navigator.clipboard.writeText() is not available."));
161
171
  return;
162
172
  }
@@ -172,10 +182,10 @@ async function writeToClipboard(payload, env, settings, context) {
172
182
  throw failure;
173
183
  }
174
184
  }
175
- return rich.write([new rich.Item({
185
+ return orLegacy(rich.write([new rich.Item({
176
186
  "text/html": new Blob([payload.html], { type: "text/html" }),
177
187
  "text/plain": new Blob([payload.text], { type: "text/plain" })
178
- })]);
188
+ })]));
179
189
  }
180
190
  case "image": {
181
191
  const rich = getRichClipboard(env, clipboard);
@@ -197,7 +207,7 @@ async function writeToClipboard(payload, env, settings, context) {
197
207
  written += 1;
198
208
  }
199
209
  if (written === 0) throw fail("unsupported-format", "This browser can write none of the payload types.");
200
- return rich.write([new rich.Item(record)]);
210
+ return orLegacy(rich.write([new rich.Item(record)]));
201
211
  }
202
212
  }
203
213
  }
@@ -218,4 +228,4 @@ Object.defineProperty(exports, "createBrowserClipboardAdapter", {
218
228
  }
219
229
  });
220
230
 
221
- //# sourceMappingURL=clipboard-adapter-q_pp9q_x.cjs.map
231
+ //# sourceMappingURL=clipboard-adapter-CfI4O02E.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"clipboard-adapter-q_pp9q_x.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\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: CopyFailure): 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 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 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 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 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 rich.write([new rich.Item(record)]);\n }\n }\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 };\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,IAAI,IAAI,kBAAkB,SAAS,QAAQ,MA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 {"version":3,"file":"clipboard-adapter-CfI4O02E.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\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/** 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 };\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;CAC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5G,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,EAC5F;AACF"}
@@ -143,6 +143,16 @@ async function writeToClipboard(payload, env, settings, context) {
143
143
  if (entries && legacyCopy(env.document, entries)) return;
144
144
  throw failure;
145
145
  };
146
+ /**
147
+ * A write the browser refused with `NotAllowedError`, most often a permissions policy: a
148
+ * Microsoft Teams tab, a SharePoint web part or a Storybook canvas is an iframe without
149
+ * `allow="clipboard-write"`. The copy command is not gated by that policy, so it is tried while
150
+ * the user's gesture is still fresh; when it cannot help, the browser's own error stands.
151
+ */
152
+ const orLegacy = (write) => write.catch((cause) => {
153
+ if (cause?.name !== "NotAllowedError" || context?.signal.aborted === true) throw cause;
154
+ legacy(cause);
155
+ });
146
156
  if (env.isSecureContext === false) {
147
157
  legacy(fail("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost)."));
148
158
  return;
@@ -156,7 +166,7 @@ async function writeToClipboard(payload, env, settings, context) {
156
166
  case "text":
157
167
  case "json": {
158
168
  const text = payload.kind === "text" ? payload.value : serializeJson(payload);
159
- if (typeof clipboard.writeText === "function") return clipboard.writeText(text);
169
+ if (typeof clipboard.writeText === "function") return orLegacy(clipboard.writeText(text));
160
170
  legacy(fail("unsupported", "navigator.clipboard.writeText() is not available."));
161
171
  return;
162
172
  }
@@ -172,10 +182,10 @@ async function writeToClipboard(payload, env, settings, context) {
172
182
  throw failure;
173
183
  }
174
184
  }
175
- return rich.write([new rich.Item({
185
+ return orLegacy(rich.write([new rich.Item({
176
186
  "text/html": new Blob([payload.html], { type: "text/html" }),
177
187
  "text/plain": new Blob([payload.text], { type: "text/plain" })
178
- })]);
188
+ })]));
179
189
  }
180
190
  case "image": {
181
191
  const rich = getRichClipboard(env, clipboard);
@@ -197,7 +207,7 @@ async function writeToClipboard(payload, env, settings, context) {
197
207
  written += 1;
198
208
  }
199
209
  if (written === 0) throw fail("unsupported-format", "This browser can write none of the payload types.");
200
- return rich.write([new rich.Item(record)]);
210
+ return orLegacy(rich.write([new rich.Item(record)]));
201
211
  }
202
212
  }
203
213
  }
@@ -213,4 +223,4 @@ function createBrowserClipboardAdapter(options = {}) {
213
223
  //#endregion
214
224
  export { createBrowserClipboardAdapter as t };
215
225
 
216
- //# sourceMappingURL=clipboard-adapter-B-9XTqUp.js.map
226
+ //# sourceMappingURL=clipboard-adapter-DX5yd8_6.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"clipboard-adapter-B-9XTqUp.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\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: CopyFailure): 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 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 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 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 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 rich.write([new rich.Item(record)]);\n }\n }\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 };\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,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,CAAC,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,IAAI,IAAI,kBAA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/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\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/** 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 };\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,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,CAAC,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,IAAI,IAAI,kBAAkB,SAAS,QAAQ,MAAM,EAAE,eAAe,KAAK,CAAC;CACxE,IAAI,OAAO,QAA8B,kBAAkB,GAAG,KAAK;AACrE;;;;;AAMA,SAAgB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@@ -2,7 +2,7 @@
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
3
  import { a as validatePayload, 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-B-9XTqUp.js";
5
+ import { t as createBrowserClipboardAdapter } from "./clipboard-adapter-DX5yd8_6.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() {
@@ -1115,4 +1115,4 @@ function createPasteMachine(options = {}) {
1115
1115
  //#endregion
1116
1116
  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
1117
 
1118
- //# sourceMappingURL=core-BrmkVinL.js.map
1118
+ //# sourceMappingURL=core-BE0SO57n.js.map