react-smart-copy 1.27.1 → 1.29.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.
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-q_pp9q_x.cjs → clipboard-adapter-DYo79Fdq.cjs} +45 -6
  7. package/dist/chunks/clipboard-adapter-DYo79Fdq.cjs.map +1 -0
  8. package/dist/chunks/{clipboard-adapter-B-9XTqUp.js → clipboard-adapter-XS23N-Gg.js} +45 -6
  9. package/dist/chunks/clipboard-adapter-XS23N-Gg.js.map +1 -0
  10. package/dist/chunks/{copy-interceptor-BClcHS_P.d.cts → copy-interceptor-7NVPsNOK.d.cts} +2 -2
  11. package/dist/chunks/{copy-interceptor-D8c9EDnO.d.ts → copy-interceptor-CjF0OD8t.d.ts} +2 -2
  12. package/dist/chunks/{core-BrmkVinL.js → core-BRqanpvy.js} +60 -40
  13. package/dist/chunks/core-BRqanpvy.js.map +1 -0
  14. package/dist/chunks/{core-Bi4HUuRs.cjs → core-pOm_foSY.cjs} +59 -39
  15. package/dist/chunks/core-pOm_foSY.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-K1GpVQdH.cjs → share-0QnaCaoQ.cjs} +2 -2
  25. package/dist/chunks/{share-K1GpVQdH.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-CW1SnFz5.js → share-BwgSAtH6.js} +2 -2
  28. package/dist/chunks/{share-CW1SnFz5.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 +8 -8
  61. package/dist/chunks/clipboard-adapter-B-9XTqUp.js.map +0 -1
  62. package/dist/chunks/clipboard-adapter-q_pp9q_x.cjs.map +0 -1
  63. package/dist/chunks/core-Bi4HUuRs.cjs.map +0 -1
  64. package/dist/chunks/core-BrmkVinL.js.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.6 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
@@ -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,10 +207,36 @@ 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
  }
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
+ }
204
240
  /** The default adapter: async Clipboard API with feature detection and honest errors. */
205
241
  function createBrowserClipboardAdapter(options = {}) {
206
242
  const getEnvironment = options.getEnvironment ?? defaultEnvironment;
@@ -208,7 +244,10 @@ function createBrowserClipboardAdapter(options = {}) {
208
244
  degradeHtmlToText: options.degradeHtmlToText ?? true,
209
245
  legacyFallback: options.legacyFallback ?? true
210
246
  };
211
- 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
+ };
212
251
  }
213
252
  //#endregion
214
253
  Object.defineProperty(exports, "createBrowserClipboardAdapter", {
@@ -218,4 +257,4 @@ Object.defineProperty(exports, "createBrowserClipboardAdapter", {
218
257
  }
219
258
  });
220
259
 
221
- //# sourceMappingURL=clipboard-adapter-q_pp9q_x.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,IAAI,IAAI,kBAAkB,SAAS,QAAQ,MAAM,EAAE,eAAe,KAAK,CAAC;CACxE,IAAI,O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AAM;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"}
@@ -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,10 +207,36 @@ 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
  }
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
+ }
204
240
  /** The default adapter: async Clipboard API with feature detection and honest errors. */
205
241
  function createBrowserClipboardAdapter(options = {}) {
206
242
  const getEnvironment = options.getEnvironment ?? defaultEnvironment;
@@ -208,9 +244,12 @@ function createBrowserClipboardAdapter(options = {}) {
208
244
  degradeHtmlToText: options.degradeHtmlToText ?? true,
209
245
  legacyFallback: options.legacyFallback ?? true
210
246
  };
211
- 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
+ };
212
251
  }
213
252
  //#endregion
214
253
  export { createBrowserClipboardAdapter as t };
215
254
 
216
- //# sourceMappingURL=clipboard-adapter-B-9XTqUp.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,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,UA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AW;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-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
@@ -138,4 +138,4 @@ interface CopyInterceptorOptions extends CopyInterceptOptions {
138
138
  declare function registerCopyInterceptor(root: Element, options: CopyInterceptorOptions | (() => CopyInterceptorOptions)): () => void;
139
139
  //#endregion
140
140
  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
141
+ //# sourceMappingURL=copy-interceptor-7NVPsNOK.d.cts.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-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
@@ -138,4 +138,4 @@ interface CopyInterceptorOptions extends CopyInterceptOptions {
138
138
  declare function registerCopyInterceptor(root: Element, options: CopyInterceptorOptions | (() => CopyInterceptorOptions)): () => void;
139
139
  //#endregion
140
140
  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
141
+ //# sourceMappingURL=copy-interceptor-CjF0OD8t.d.ts.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-B-9XTqUp.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);
@@ -1115,4 +1135,4 @@ function createPasteMachine(options = {}) {
1115
1135
  //#endregion
1116
1136
  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
1137
 
1118
- //# sourceMappingURL=core-BrmkVinL.js.map
1138
+ //# sourceMappingURL=core-BRqanpvy.js.map