react-smart-copy 1.16.0 → 1.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["invalid","defaultEnvironment","IGNORED_IN_FLIGHT","IGNORED_NOTHING","IGNORED_NOT_RETRYABLE","IGNORED_CANCELLED","resolveResetDelay","defaultAdapter","getDefaultAdapter","nonEmpty","invalid","unsupported","invalid","defaultEnvironment","useState","useContext","useEffect","useLayoutEffect","getServerSnapshot","useRef","useState","useSyncExternalStore","useMemo","useRef","useState","getServerSnapshot","useRef","useCallback","useSyncExternalStore","useState","useRef","useMemo","useState","useRef","useContext","Root","useId","useMemo","useCallback","Label","DEFAULT_TRIGGER_TEXT","Trigger","useRef","useState","useSyncExternalStore","useMemo","useState","useContext","useId","useMemo","useCallback","useState","useRef","useState","useCallback","invalid","invalid","useRef","useState","useCallback","useSyncExternalStore","useMemo"],"sources":["../src/core/errors.ts","../src/core/payload.ts","../src/core/mime.ts","../src/core/clipboard-adapter.ts","../src/core/copy-coordinator.ts","../src/core/machine-shared.ts","../src/core/source-error.ts","../src/core/copy-machine.ts","../src/core/copy-interceptor.ts","../src/core/drag-copy.ts","../src/core/paste-reader.ts","../src/core/paste-adapter.ts","../src/core/paste-machine.ts","../src/react/CopyGroup.tsx","../src/react/utils.ts","../src/react/useCopy.ts","../src/react/useCopyInterceptor.ts","../src/react/useMediaQuery.ts","../src/react/useRevealOnInteraction.ts","../src/react/useDisplayStatus.ts","../src/react/LiveRegion.tsx","../src/react/TriggerLabel.tsx","../src/react/CopyField.tsx","../src/react/usePaste.ts","../src/react/usePasteDisplayStatus.ts","../src/react/PasteField.tsx","../src/react/useDragCopy.ts","../src/link/url.ts","../src/link/payload.ts","../src/share/share.ts","../src/react/useShare.ts"],"sourcesContent":["import type { PasteSource } from './paste-reader';\n\n/**\n * Every way a clipboard operation can fail, as a closed union.\n *\n * `CopyError.message` is developer-facing (logs, telemetry). For user-facing\n * text use {@link describeCopyError} / {@link describePasteError}, or map\n * `type` through your own i18n layer.\n */\nexport type CopyErrorType =\n /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */\n | 'unsupported'\n /** Page is not served over HTTPS/localhost. Not retryable. */\n | 'insecure-context'\n /** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */\n | 'permission-denied'\n /** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */\n | 'not-focused'\n /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */\n | 'invalid-payload'\n /** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */\n | 'unsupported-format'\n /** A lazy image source (or capture) threw, rejected or did not produce a Blob. */\n | 'blob-generation-failed'\n /** `retry()` was called after `maxRetries` was reached. Terminal. */\n | 'max-retries-exceeded'\n /** Paste: the clipboard held nothing matching `accept`. */\n | 'no-content'\n /** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */\n | 'too-large'\n /** An operation did not settle within its deadline. Retryable. */\n | 'timeout'\n /** The caller aborted the operation through an `AbortSignal`. Not retryable. */\n | 'aborted'\n /** Anything the platform threw that we could not classify. */\n | 'unknown';\n\n/** Which clipboard direction failed; only changes developer-facing messages. */\nexport type ClipboardOperation = 'write' | 'read';\n\nexport interface CopyError {\n readonly type: CopyErrorType;\n readonly message: string;\n readonly cause?: unknown;\n}\n\nexport function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError {\n return cause === undefined ? { type, message } : { type, message, cause };\n}\n\nconst RETRYABLE_ERRORS: ReadonlySet<CopyErrorType> = /* @__PURE__ */ new Set<CopyErrorType>([\n 'permission-denied',\n 'not-focused',\n 'blob-generation-failed',\n 'timeout',\n 'unknown',\n]);\n\n/** Whether retrying the same payload could plausibly succeed. */\nexport function isRetryableError(error: CopyError): boolean {\n return RETRYABLE_ERRORS.has(error.type);\n}\n\n/**\n * Branded (not `instanceof`) so failures stay recognisable even when the core\n * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.\n */\nconst COPY_FAILURE_BRAND = Symbol.for('react-smart-copy.CopyFailure');\n\n/** Error thrown by adapters to carry a fully classified {@link CopyError}. */\nexport class CopyFailure extends Error {\n readonly copyError: CopyError;\n readonly [COPY_FAILURE_BRAND] = true;\n\n constructor(copyError: CopyError) {\n super(copyError.message);\n this.name = 'CopyFailure';\n this.copyError = copyError;\n }\n}\n\nexport function isCopyFailure(value: unknown): value is CopyFailure {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[COPY_FAILURE_BRAND] === true\n );\n}\n\n/** Shorthand for throwing a classified failure. */\nexport function copyFailure(type: CopyErrorType, message: string, cause?: unknown): CopyFailure {\n return new CopyFailure(createCopyError(type, message, cause));\n}\n\nfunction readString(value: unknown, key: string): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const field = (value as Record<string, unknown>)[key];\n return typeof field === 'string' ? field : undefined;\n}\n\n/**\n * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.\n * `operation` only tailors the developer-facing message.\n */\nexport function toCopyError(cause: unknown, operation: ClipboardOperation = 'write'): CopyError {\n if (isCopyFailure(cause)) return cause.copyError;\n\n const name = readString(cause, 'name');\n const message = readString(cause, 'message') ?? '';\n const verb = operation === 'read' ? 'read' : 'write';\n\n switch (name) {\n case 'NotAllowedError':\n return /focus/i.test(message)\n ? createCopyError('not-focused', `The document was not focused during the clipboard ${verb}.`, cause)\n : createCopyError('permission-denied', `Clipboard ${verb} permission was denied.`, cause);\n case 'SecurityError':\n return createCopyError('insecure-context', 'The clipboard is blocked in this context.', cause);\n case 'NotSupportedError':\n case 'DataError':\n return createCopyError('unsupported-format', 'The browser rejected this clipboard format.', cause);\n case 'AbortError':\n return createCopyError('aborted', `The clipboard ${verb} was aborted.`, cause);\n case 'TimeoutError':\n return createCopyError('timeout', `The clipboard ${verb} timed out.`, cause);\n default:\n return createCopyError('unknown', message || `The clipboard ${verb} failed for an unknown reason.`, cause);\n }\n}\n\nconst COPY_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Copying isn't supported in this browser.\",\n 'insecure-context': 'Copying requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while copying. Try again.',\n 'invalid-payload': 'There is nothing to copy.',\n 'unsupported-format': \"This content can't be copied in this browser.\",\n 'blob-generation-failed': \"The image couldn't be prepared for copying.\",\n 'max-retries-exceeded': 'Copying failed after several attempts.',\n 'no-content': 'There is nothing to copy.',\n 'too-large': 'This content is too large to copy.',\n timeout: 'Copying took too long. Try again.',\n aborted: 'Copying was cancelled.',\n unknown: \"Couldn't copy to the clipboard. Try again.\",\n};\n\nconst PASTE_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Pasting isn't supported in this browser.\",\n 'insecure-context': 'Pasting requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while pasting. Try again.',\n 'invalid-payload': \"The clipboard content couldn't be read.\",\n 'unsupported-format': \"This clipboard content isn't supported here.\",\n 'blob-generation-failed': \"The pasted image couldn't be read.\",\n 'max-retries-exceeded': 'Pasting failed after several attempts.',\n 'no-content': \"The clipboard doesn't contain anything that can be pasted here.\",\n 'too-large': 'The clipboard content is too large to paste.',\n timeout: 'Pasting took too long. Try again.',\n aborted: 'Pasting was cancelled.',\n unknown: \"Couldn't read the clipboard. Try again.\",\n};\n\n/** Default English, user-facing sentence for a copy error. Replace for i18n. */\nexport function describeCopyError(error: CopyError): string {\n return COPY_DESCRIPTIONS[error.type];\n}\n\n/** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */\nconst DROP_DESCRIPTIONS: Readonly<Partial<Record<CopyErrorType, string>>> = {\n 'invalid-payload': \"The dropped content couldn't be read.\",\n 'no-content': 'Nothing that was dropped can be used here.',\n 'too-large': 'The dropped content is too large.',\n unknown: \"Couldn't read the dropped content. Try again.\",\n};\n\n/**\n * Default English, user-facing sentence for a paste error. Pass the error\n * state's `source` to word drag-and-drop failures as drops. Replace for i18n.\n */\nexport function describePasteError(error: CopyError, source?: PasteSource): string {\n return (source === 'drop' ? DROP_DESCRIPTIONS[error.type] : undefined) ?? PASTE_DESCRIPTIONS[error.type];\n}\n","import { CopyFailure, createCopyError, type CopyError } from './errors';\nimport type { OperationContext } from './machine-shared';\n\n/** The only image MIME type with reliable cross-browser clipboard write support. */\nexport const IMAGE_MIME_TYPE = 'image/png';\n\n/**\n * An image as a Blob, a promise of one, or a function producing one.\n * Prefer the function form: it is invoked synchronously inside the user\n * gesture, which Safari requires for async image generation. The browser\n * adapter always passes an `OperationContext`: stop work once\n * `context.signal` aborts (reset, superseded, unmount). Optional in the type\n * so adapters that call sources themselves keep compiling.\n */\nexport type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);\n\nexport interface TextPayload {\n readonly kind: 'text';\n readonly value: string;\n}\n\nexport interface HtmlPayload {\n readonly kind: 'html';\n readonly html: string;\n /** Required plain-text fallback for targets that don't understand HTML. */\n readonly text: string;\n}\n\nexport interface ImagePayload {\n readonly kind: 'image';\n readonly blob: BlobSource;\n}\n\nexport interface JsonPayload {\n readonly kind: 'json';\n readonly value: unknown;\n /** `true` = 2-space indent, a number = that indent, falsy = compact. */\n readonly pretty?: boolean | number;\n}\n\nexport interface MultiPayloadItem {\n /**\n * The MIME type, or a web custom format (`web application/vnd.acme+json`).\n * Web custom formats are only written by the async Clipboard API; copy and drag\n * events skip them.\n */\n readonly mimeType: string;\n readonly data: string | Blob;\n /**\n * Skip this item, instead of failing the copy, when the browser cannot write its type.\n * An optional item is only written when `ClipboardItem.supports()` confirms the type.\n * At least one item must be written.\n */\n readonly optional?: boolean;\n}\n\nexport interface MultiPayload {\n readonly kind: 'multi';\n readonly items: readonly MultiPayloadItem[];\n}\n\nexport type CopyPayload = TextPayload | HtmlPayload | ImagePayload | JsonPayload | MultiPayload;\nexport type CopyPayloadKind = CopyPayload['kind'];\n\n/** A payload, or a bare string as shorthand for `{ kind: 'text' }`. */\nexport type CopyInput = string | CopyPayload;\n\n/**\n * What `copy()` accepts. The function form is resolved synchronously at copy\n * time, so it always reads the latest value without re-rendering.\n */\nexport type CopySource = CopyInput | (() => CopyInput);\n\nexport function normalizePayload(input: CopyInput): CopyPayload {\n return typeof input === 'string' ? { kind: 'text', value: input } : input;\n}\n\nexport function isBlob(value: unknown): value is Blob {\n if (typeof Blob !== 'undefined' && value instanceof Blob) return true;\n const tag = Object.prototype.toString.call(value);\n return tag === '[object Blob]' || tag === '[object File]';\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' || typeof value === 'function') &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\nconst invalid = (message: string): CopyError => createCopyError('invalid-payload', message);\n\n/**\n * Structural validation. Typed callers can't produce most of these states,\n * but plain-JS callers and runtime data can, so the check is always on.\n */\nexport function validatePayload(payload: unknown): CopyError | null {\n if (typeof payload !== 'object' || payload === null) {\n return invalid('Copy input must be a string or a payload object.');\n }\n const candidate = payload as Record<string, unknown>;\n\n switch (candidate['kind']) {\n case 'text':\n return typeof candidate['value'] === 'string' && candidate['value'].length > 0\n ? null\n : invalid('Text payload must be a non-empty string.');\n case 'html':\n if (typeof candidate['html'] !== 'string' || candidate['html'].length === 0) {\n return invalid('HTML payload requires a non-empty `html` string.');\n }\n return typeof candidate['text'] === 'string' && candidate['text'].length > 0\n ? null\n : invalid('HTML payload requires a non-empty plain-text `text` fallback.');\n case 'image': {\n const source = candidate['blob'];\n return isBlob(source) || typeof source === 'function' || isThenable(source)\n ? null\n : invalid('Image payload requires a Blob, a Promise<Blob> or a function returning one.');\n }\n case 'json':\n return candidate['value'] === undefined ? invalid('JSON payload value is undefined.') : null;\n case 'multi': {\n const items = candidate['items'];\n if (!Array.isArray(items) || items.length === 0) {\n return invalid('Multi payload requires at least one item.');\n }\n const seen = new Set<string>();\n for (const item of items as unknown[]) {\n const entry = (typeof item === 'object' && item !== null ? item : {}) as Record<string, unknown>;\n const mimeType = entry['mimeType'];\n const data = entry['data'];\n if (typeof mimeType !== 'string' || mimeType.length === 0) {\n return invalid('Every multi item needs a non-empty `mimeType`.');\n }\n if (seen.has(mimeType)) return invalid(`Duplicate MIME type \"${mimeType}\" in multi payload.`);\n seen.add(mimeType);\n if (typeof data !== 'string' && !isBlob(data)) {\n return invalid(`Multi item \"${mimeType}\" must contain a string or a Blob.`);\n }\n }\n return null;\n }\n default:\n return invalid(`Unknown payload kind: ${String(candidate['kind'])}.`);\n }\n}\n\n/** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */\nexport function serializeJson(payload: JsonPayload): string {\n const indent =\n payload.pretty === true ? 2 : typeof payload.pretty === 'number' ? payload.pretty : undefined;\n // Typed as `string` by lib.d.ts, but returns undefined for functions, symbols and undefined.\n let text: unknown;\n try {\n text = JSON.stringify(payload.value, null, indent);\n } catch (cause) {\n throw new CopyFailure(\n createCopyError('invalid-payload', 'JSON payload could not be serialised (circular reference or BigInt?).', cause),\n );\n }\n if (typeof text !== 'string') {\n throw new CopyFailure(\n createCopyError('invalid-payload', 'JSON payload serialised to nothing (functions, symbols and undefined are not JSON).'),\n );\n }\n return text;\n}\n","/**\n * MIME helpers shared by paste and capture. Everything that comes from the\n * clipboard is untrusted input, so types are normalised and validated before\n * they are compared, and image types are confirmed from the bytes themselves.\n */\n\n/** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */\nconst MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\n/** SVG is XML that can carry scripts; it is never matched by a wildcard. */\nexport const SVG_MIME_TYPE = 'image/svg+xml';\n\n/** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */\nexport function normalizeMimeType(value: string): string | null {\n const separator = value.indexOf(';');\n const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();\n return MIME_SHAPE.test(base) ? base : null;\n}\n\n/** Prefix of the async Clipboard API's web custom formats (`web application/vnd.acme+json`). */\nexport const WEB_CUSTOM_FORMAT_PREFIX = 'web ';\n\n/** Whether a clipboard type is a web custom format (`web type/subtype`). */\nexport function isWebCustomFormat(type: string): boolean {\n return type.slice(0, 4).toLowerCase() === WEB_CUSTOM_FORMAT_PREFIX;\n}\n\n/**\n * Like {@link normalizeMimeType}, but also accepts web custom formats\n * (`web type/subtype`), returned as `web ` + the normalised MIME type.\n */\nexport function normalizeClipboardType(value: string): string | null {\n if (!isWebCustomFormat(value)) return normalizeMimeType(value);\n const inner = normalizeMimeType(value.slice(4));\n return inner === null ? null : WEB_CUSTOM_FORMAT_PREFIX + inner;\n}\n\n/**\n * Types a wildcard never matches, so accepting them must be explicit:\n * `image/svg+xml` (scriptable XML), web custom formats and structured `+json` types\n * (application-specific data that only the app that defined them should read).\n */\nfunction requiresExactMatch(mimeType: string): boolean {\n return mimeType === SVG_MIME_TYPE || isWebCustomFormat(mimeType) || mimeType.endsWith('+json');\n}\n\n/**\n * Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\\/*`)?\n * Wildcards never match `image/svg+xml`, web custom formats or `+json` types: those must be listed exactly.\n */\nexport function matchesMimePattern(mimeType: string, pattern: string): boolean {\n if (pattern === mimeType) return true;\n if (requiresExactMatch(mimeType)) return false;\n if (pattern === '*/*') return true;\n return pattern.endsWith('/*') && mimeType.startsWith(pattern.slice(0, -1));\n}\n\n/** Types whose clipboard data is text and is therefore surfaced as a `string`. */\nexport function isTextualMimeType(mimeType: string): boolean {\n const type = isWebCustomFormat(mimeType) ? mimeType.slice(4) : mimeType;\n return (\n type.startsWith('text/') ||\n type === SVG_MIME_TYPE ||\n type === 'application/json' ||\n type === 'application/xml' ||\n type.endsWith('+json')\n );\n}\n\n/** Raster image formats recognised from their leading bytes. */\nexport type RasterImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/bmp' | 'image/avif';\n\nconst SNIFF_BYTES = 16;\n\nfunction startsWith(bytes: Uint8Array, signature: readonly number[], offset = 0): boolean {\n return signature.every((byte, index) => bytes[offset + index] === byte);\n}\n\nconst ascii = (text: string): number[] => Array.from(text, (char) => char.charCodeAt(0));\n\nconst PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\nconst JPEG = [0xff, 0xd8, 0xff];\nconst GIF = ascii('GIF8');\nconst RIFF = ascii('RIFF');\nconst WEBP = ascii('WEBP');\nconst BMP = ascii('BM');\nconst FTYP_AVIF = ascii('ftypavif');\nconst FTYP_AVIS = ascii('ftypavis');\n\n/** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */\nexport function sniffImageBytes(bytes: Uint8Array): RasterImageMimeType | null {\n if (startsWith(bytes, PNG)) return 'image/png';\n if (startsWith(bytes, JPEG)) return 'image/jpeg';\n if (startsWith(bytes, GIF)) return 'image/gif';\n if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return 'image/webp';\n if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return 'image/avif';\n if (startsWith(bytes, BMP)) return 'image/bmp';\n return null;\n}\n\n/** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */\nexport async function sniffImageType(blob: Blob): Promise<RasterImageMimeType | null> {\n const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();\n return sniffImageBytes(new Uint8Array(head));\n}\n","import { CopyFailure, createCopyError, type CopyErrorType } from './errors';\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 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\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\nfunction writeText(clipboard: ClipboardLike, text: string): Promise<void> {\n if (typeof clipboard.writeText !== 'function') {\n throw fail('unsupported', 'navigator.clipboard.writeText() is not available.');\n }\n return clipboard.writeText(text);\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 degradeHtmlToText: boolean,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!env) throw fail('unsupported', 'No browser environment: the clipboard only exists in the browser.');\n if (env.isSecureContext === false) {\n throw fail('insecure-context', 'The Clipboard API requires a secure context (HTTPS or localhost).');\n }\n const clipboard = env.navigator?.clipboard;\n if (!clipboard) throw fail('unsupported', 'navigator.clipboard is not available in this browser.');\n\n switch (payload.kind) {\n case 'text':\n return writeText(clipboard, payload.value);\n\n case 'json':\n return writeText(clipboard, serializeJson(payload));\n\n case 'html': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich || !isTypeSupported(rich.Item, 'text/html')) {\n if (degradeHtmlToText) return writeText(clipboard, payload.text);\n throw fail('unsupported-format', 'Rich HTML copy requires ClipboardItem and navigator.clipboard.write().');\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) throw fail('unsupported-format', 'Multi-format copy requires ClipboardItem and navigator.clipboard.write().');\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 degradeHtmlToText = options.degradeHtmlToText ?? true;\n return {\n write: (payload, context) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText, context),\n };\n}\n","/**\n * A copy machine as seen by a coordinator. `release()` returns it from\n * `copied` to `idle`; it is a no-op in any other state.\n */\nexport interface CopyCoordinatorMember {\n readonly release: () => void;\n}\n\n/**\n * Makes a set of copy machines behave like one clipboard: when a member\n * succeeds, the member that previously showed \"Copied\" goes back to idle,\n * because the clipboard no longer holds its value.\n *\n * Failed copies never release anyone (the clipboard still holds the previous value).\n */\nexport interface CopyCoordinator {\n /** A member just reached `copied`. Releases the previous one. */\n readonly activate: (member: CopyCoordinatorMember) => void;\n /** A member left `copied` on its own (auto-reset, reset, unmount). */\n readonly deactivate: (member: CopyCoordinatorMember) => void;\n /** The member currently showing `copied`, if any. */\n readonly getActive: () => CopyCoordinatorMember | null;\n}\n\nexport function createCopyCoordinator(): CopyCoordinator {\n let active: CopyCoordinatorMember | null = null;\n return {\n activate: (member) => {\n const previous = active;\n active = member;\n if (previous !== null && previous !== member) previous.release();\n },\n deactivate: (member) => {\n if (active === member) active = null;\n },\n getActive: () => active,\n };\n}\n","/**\n * Internals shared by the copy and paste state machines. Kept in one module so\n * apps that use both don't ship two copies.\n */\n\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * Passed to adapters and lazy sources as their last argument. `signal` aborts\n * when the operation is superseded, `reset()`, or its host unmounts, so\n * expensive work (rasterising, decoding) can stop early.\n */\nexport interface OperationContext {\n readonly signal: AbortSignal;\n}\n\nexport function resolveMaxRetries(value: number | undefined): number {\n if (value === Infinity) return Infinity;\n if (value === undefined || !Number.isFinite(value)) return DEFAULT_MAX_RETRIES;\n return Math.max(0, Math.floor(value));\n}\n\nfunction reportCallbackError(error: unknown): void {\n const scope = globalThis as { reportError?: (error: unknown) => void };\n if (typeof scope.reportError === 'function') {\n scope.reportError(error);\n } else {\n setTimeout(() => {\n throw error;\n }, 0);\n }\n}\n\n/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */\nexport function invoke<Args extends unknown[]>(fn: ((...args: Args) => void) | undefined, ...args: Args): void {\n if (!fn) return;\n try {\n fn(...args);\n } catch (error) {\n reportCallbackError(error);\n }\n}\n\nexport interface Operations {\n /** Aborts the operation in flight (if any) and starts a new one. */\n readonly start: () => OperationContext;\n /** Marks `context` finished, so a later `abort()` never fires its signal. */\n readonly end: (context: OperationContext) => void;\n /** Cancels the operation in flight, if any. Returns whether one was cancelled. */\n readonly abort: () => boolean;\n}\n\n/** One cancellable operation at a time. Signals only fire while their operation is unfinished. */\nexport function createOperations(): Operations {\n let controller: AbortController | undefined;\n const abort = (): boolean => {\n if (!controller) return false;\n controller.abort();\n controller = undefined;\n return true;\n };\n return {\n start: () => {\n abort();\n controller = new AbortController();\n return { signal: controller.signal };\n },\n end: (context) => {\n if (controller?.signal === context.signal) controller = undefined;\n },\n abort,\n };\n}\n","import { createCopyError, isCopyFailure, type CopyError } from './errors';\n\n/**\n * The error for a user-supplied source (copy source, drag source, copy transform)\n * that threw. A thrown `CopyFailure` keeps its classification, so a helper such as\n * `tablePayload()` can report `too-large` instead of a generic `invalid-payload`.\n * Internal: not part of the public API.\n */\nexport function sourceError(cause: unknown, message: string): CopyError {\n return isCopyFailure(cause) ? cause.copyError : createCopyError('invalid-payload', message, cause);\n}\n","import { createBrowserClipboardAdapter, type ClipboardAdapter } from './clipboard-adapter';\nimport type { CopyCoordinator, CopyCoordinatorMember } from './copy-coordinator';\nimport { createCopyError, isRetryableError, toCopyError, type CopyError } from './errors';\nimport { createOperations, invoke, resolveMaxRetries } from './machine-shared';\nimport { normalizePayload, validatePayload, type CopyPayload, type CopySource } from './payload';\nimport { sourceError } from './source-error';\n\nexport { DEFAULT_MAX_RETRIES, resolveMaxRetries } from './machine-shared';\n\nexport const DEFAULT_RESET_AFTER_MS = 2000;\n\nexport interface IdleState {\n readonly status: 'idle';\n}\nexport interface CopyingState {\n readonly status: 'copying';\n readonly payload: CopyPayload;\n readonly retryCount: number;\n}\nexport interface CopiedState {\n readonly status: 'copied';\n readonly payload: CopyPayload;\n /** Epoch ms when the write resolved. */\n readonly at: number;\n}\nexport interface ErrorState {\n readonly status: 'error';\n /** `null` when the input itself could not be resolved. */\n readonly payload: CopyPayload | null;\n readonly error: CopyError;\n readonly retryCount: number;\n}\n\nexport type CopyState = IdleState | CopyingState | CopiedState | ErrorState;\nexport type CopyStatus = CopyState['status'];\n\n/**\n * `cancelled`: the copy was reset or its host unmounted before it finished,\n * so its work was aborted. Nothing to report to the user.\n */\nexport type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';\n\n/**\n * Why an in-flight copy was cancelled: `reset` (`reset()` was called) or\n * `disconnect` (its host disconnected, e.g. the React component unmounted).\n */\nexport type CopyCancelReason = 'reset' | 'disconnect';\n\n/** What `copy()`/`retry()` resolve to. They never reject. */\nexport type CopyOutcome =\n | { readonly status: 'copied'; readonly payload: CopyPayload }\n | { readonly status: 'error'; readonly error: CopyError }\n | { readonly status: 'ignored'; readonly reason: CopyIgnoredReason };\n\nexport interface CopyMachineOptions {\n /** Defaults to the browser Clipboard API adapter. */\n readonly adapter?: ClipboardAdapter;\n /** Time in `copied` before returning to `idle`. `false`/`Infinity` disables. Default 2000. */\n readonly resetAfterMs?: number | false;\n /**\n * Max `retry()` calls after the first failure. Default 3. `0` disables\n * retry; `Infinity` allows unlimited retries.\n */\n readonly maxRetries?: number;\n /**\n * Share \"Copied\" with other machines: only one member of a coordinator\n * shows `copied` at a time. `null` explicitly opts out (e.g. of a React `<CopyGroup>`).\n */\n readonly coordinator?: CopyCoordinator | null;\n readonly onCopy?: (payload: CopyPayload) => void;\n readonly onError?: (error: CopyError, payload: CopyPayload | null) => void;\n /**\n * `reset()` moved the machine back to `idle` from any other state. Not\n * called for the automatic return after `resetAfterMs`, for a `<CopyGroup>`\n * handing \"Copied\" to another member, or when already `idle`.\n */\n readonly onReset?: () => void;\n /**\n * A copy in flight was cancelled before it settled: its `signal` aborted\n * and its result will not reach state or `onCopy` / `onError`. Fires\n * before `onReset` when `reset()` cancels a copy.\n */\n readonly onCancel?: (reason: CopyCancelReason) => void;\n /** Clock injection for tests and deterministic environments. */\n readonly now?: () => number;\n}\n\n/** Options object, or a getter so hosts (like React) can supply the latest options. */\nexport type CopyMachineOptionsSource = CopyMachineOptions | (() => CopyMachineOptions);\n\nexport interface CopyMachine {\n readonly getSnapshot: () => CopyState;\n readonly subscribe: (listener: () => void) => () => void;\n readonly copy: (source: CopySource) => Promise<CopyOutcome>;\n readonly retry: () => Promise<CopyOutcome>;\n /** Back to `idle`. Discards any in-flight result and aborts its `signal`. */\n readonly reset: () => void;\n /**\n * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned\n * cleanup clears timers, drops in-flight results, aborts in-flight work and\n * unsticks `copying`.\n * Safe to call repeatedly (React StrictMode).\n */\n readonly connect: () => () => void;\n}\n\nexport const IDLE_STATE: IdleState = /* @__PURE__ */ Object.freeze({ status: 'idle' });\n\nconst IGNORED_IN_FLIGHT: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'in-flight' });\nconst IGNORED_NOTHING: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'nothing-to-retry' });\nconst IGNORED_NOT_RETRYABLE: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'not-retryable' });\nconst IGNORED_CANCELLED: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'cancelled' });\n\nfunction resolveResetDelay(value: number | false | undefined): number | null {\n if (value === false || value === Infinity) return null;\n if (value === undefined || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;\n return Math.max(0, value);\n}\n\n/** Pure helper: can `retry()` do anything from this state? */\nexport function canRetryState(state: CopyState, maxRetries?: number): boolean {\n return (\n state.status === 'error' &&\n state.payload !== null &&\n isRetryableError(state.error) &&\n state.retryCount < resolveMaxRetries(maxRetries)\n );\n}\n\nlet defaultAdapter: ClipboardAdapter | undefined;\nconst getDefaultAdapter = (): ClipboardAdapter => (defaultAdapter ??= createBrowserClipboardAdapter());\n\n/** Framework-agnostic copy state machine. */\nexport function createCopyMachine(options: CopyMachineOptionsSource = {}): CopyMachine {\n const read = typeof options === 'function' ? options : (): CopyMachineOptions => options;\n const listeners = new Set<() => void>();\n let state: CopyState = IDLE_STATE;\n let generation = 0;\n let resetTimer: ReturnType<typeof setTimeout> | undefined;\n const operations = createOperations();\n\n const now = (): number => (read().now ?? Date.now)();\n\n // The coordinator that saw this machine's last `copied`, so leaving it is reported to the same one.\n let joined: CopyCoordinator | null = null;\n\n const member: CopyCoordinatorMember = {\n release: () => {\n if (state.status === 'copied') {\n clearResetTimer();\n setState(IDLE_STATE);\n }\n },\n };\n\n const setState = (next: CopyState): void => {\n if (next === state) return;\n const previous = state;\n state = next;\n if (previous.status === 'copied' && next.status !== 'copied' && joined) {\n joined.deactivate(member);\n joined = null;\n }\n for (const listener of Array.from(listeners)) listener();\n };\n\n const joinCoordinator = (): void => {\n joined = read().coordinator ?? null;\n joined?.activate(member);\n };\n\n const clearResetTimer = (): void => {\n if (resetTimer !== undefined) {\n clearTimeout(resetTimer);\n resetTimer = undefined;\n }\n };\n\n const scheduleReset = (copied: CopiedState): void => {\n clearResetTimer();\n const delay = resolveResetDelay(read().resetAfterMs);\n if (delay === null) return;\n const remaining = Math.max(0, delay - (now() - copied.at));\n // Invariant: every transition out of `copied` clears this timer, so it only ever fires while still in `copied`.\n resetTimer = setTimeout(() => {\n resetTimer = undefined;\n setState(IDLE_STATE);\n }, remaining);\n };\n\n const settleError = (error: CopyError, payload: CopyPayload | null, retryCount: number): void => {\n setState({ status: 'error', payload, error, retryCount });\n invoke(read().onError, error, payload);\n };\n\n const run = (source: CopySource, retryCount: number): Promise<CopyOutcome> => {\n clearResetTimer();\n const current = ++generation;\n\n let payload: CopyPayload;\n try {\n const resolved = typeof source === 'function' ? source() : source;\n // T1: the source function must be synchronous — async sources break the\n // browser's transient user-activation window. Detect and reject a Promise\n // return rather than letting it propagate as a malformed payload (a\n // thenable is not a valid CopyInput, so validatePayload would catch it,\n // but a clear error message is more useful).\n // Cast to `unknown` first so the thenable check compiles without the\n // \"no overlap\" lint error (the TS type already narrows `resolved` to\n // `CopyInput`, which excludes thenables, but JS callers can still pass one).\n const resolvedUnknown: unknown = resolved;\n if (\n resolvedUnknown !== null &&\n typeof resolvedUnknown === 'object' &&\n typeof (resolvedUnknown as { then?: unknown }).then === 'function'\n ) {\n const error = createCopyError(\n 'invalid-payload',\n 'The copy source function must be synchronous. ' +\n 'Returning a Promise breaks the user-gesture window required for clipboard writes. ' +\n 'Generate your content before calling copy().',\n );\n settleError(error, null, retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n payload = normalizePayload(resolved);\n } catch (cause) {\n const error = sourceError(cause, 'The copy source function threw.');\n settleError(error, null, retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n\n const invalid = validatePayload(payload);\n if (invalid) {\n settleError(invalid, payload, retryCount);\n return Promise.resolve({ status: 'error', error: invalid });\n }\n\n setState({ status: 'copying', payload, retryCount });\n const context = operations.start();\n\n // The adapter is called synchronously: no await may precede it, or the\n // browser loses the transient user activation and rejects the write.\n let pending: Promise<void>;\n try {\n pending = (read().adapter ?? getDefaultAdapter()).write(payload, context);\n } catch (cause) {\n // Keep the raw reason: toCopyError() classifies it (DOMException names, CopyFailure brand).\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n pending = Promise.reject(cause);\n }\n\n return pending.then(\n (): CopyOutcome => {\n operations.end(context);\n if (current === generation) {\n const copied: CopiedState = { status: 'copied', payload, at: now() };\n setState(copied);\n joinCoordinator();\n scheduleReset(copied);\n invoke(read().onCopy, payload);\n }\n return { status: 'copied', payload };\n },\n (cause: unknown): CopyOutcome => {\n operations.end(context);\n // Work we aborted ourselves (reset, unmount) is not a failure to report.\n // Invariant: superseding an in-flight copy always aborts it, so past\n // this line the copy is still the current one.\n if (context.signal.aborted) return IGNORED_CANCELLED;\n const error = toCopyError(cause);\n settleError(error, payload, retryCount);\n return { status: 'error', error };\n },\n );\n };\n\n const copy = (source: CopySource): Promise<CopyOutcome> =>\n state.status === 'copying' ? Promise.resolve(IGNORED_IN_FLIGHT) : run(source, 0);\n\n const retry = (): Promise<CopyOutcome> => {\n if (state.status !== 'error') return Promise.resolve(IGNORED_NOTHING);\n if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);\n\n if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {\n const error = createCopyError(\n 'max-retries-exceeded',\n `Copy failed after ${String(state.retryCount)} retries.`,\n state.error,\n );\n settleError(error, state.payload, state.retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n return run(state.payload, state.retryCount + 1);\n };\n\n const reset = (): void => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n const wasIdle = state.status === 'idle';\n setState(IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'reset');\n if (!wasIdle) invoke(read().onReset);\n };\n\n const connect = (): (() => void) => {\n if (state.status === 'copied') scheduleReset(state);\n return () => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n if (state.status === 'copying') setState(IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'disconnect');\n };\n };\n\n return {\n getSnapshot: () => state,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n copy,\n retry,\n reset,\n connect,\n };\n}\n","import { createCopyError, type CopyError } from './errors';\nimport { invoke } from './machine-shared';\nimport { isWebCustomFormat } from './mime';\nimport type { HtmlPayload, JsonPayload, TextPayload } from './payload';\nimport { sourceError } from './source-error';\n\n/**\n * Native copy interception: rewrite, redact or block what lands on the\n * clipboard when the user copies (Ctrl/Cmd+C, context menu) or cuts inside a\n * scope.\n *\n * Writes go through `event.clipboardData` synchronously, so no permission\n * prompt, no secure-context requirement, and it works in every browser. The\n * price is that only strings can be written, which the types enforce.\n *\n * Not a security boundary: users can still screenshot, use dev tools or\n * disable script. Treat redaction as a guard against accidents.\n */\n\nexport type InterceptedCopyKind = 'copy' | 'cut';\n\nexport const DEFAULT_INTERCEPTED_EVENTS: readonly InterceptedCopyKind[] = ['copy', 'cut'];\n\n/** The writable slice of `DataTransfer` during a `copy`/`cut` event. */\nexport interface ClipboardDataLike {\n setData(format: string, data: string): void;\n clearData?(format?: string): void;\n}\n\n/** Structural `ClipboardEvent`: DOM and React clipboard events both satisfy it. */\nexport interface CopyEventLike {\n readonly type: string;\n readonly target: EventTarget | null;\n readonly clipboardData: ClipboardDataLike | null;\n readonly defaultPrevented: boolean;\n preventDefault(): void;\n}\n\n/** What the user selected when they copied. */\nexport interface CopySelection {\n readonly kind: InterceptedCopyKind;\n /** What the browser would put on the clipboard as `text/plain`. */\n readonly text: string;\n /** Serialised HTML of the selection; `null` inside text inputs. */\n readonly html: string | null;\n /** A detached clone of the selected nodes, safe to mutate; `null` inside text inputs. */\n readonly fragment: DocumentFragment | null;\n /** The `<input>`/`<textarea>` the selection lives in, if any. */\n readonly field: HTMLInputElement | HTMLTextAreaElement | null;\n /** Whether a `cut` would remove the selection (form field or contenteditable). */\n readonly editable: boolean;\n}\n\n/**\n * A multi payload whose items are all strings; the only kind `setData` accepts.\n * Web custom formats (`web …`) are skipped: only the async Clipboard API writes them.\n */\nexport interface SyncMultiPayload {\n readonly kind: 'multi';\n readonly items: readonly { readonly mimeType: string; readonly data: string; readonly optional?: boolean }[];\n}\n\n/** Payloads writable synchronously during a copy event. Images need the async clipboard. */\nexport type SyncCopyPayload = TextPayload | HtmlPayload | JsonPayload | SyncMultiPayload;\n\n/**\n * What a transform returns:\n * - a string or payload: write that instead of the selection\n * - `false`: block the copy (nothing reaches the clipboard; a cut deletes nothing)\n * - `null` / `undefined`: leave the browser's default copy untouched\n *\n * Must be synchronous: the clipboard closes when the event handler returns.\n */\nexport type CopyInterceptDecision = string | SyncCopyPayload | false | null | undefined;\n\nexport type CopyInterceptTransform = (selection: CopySelection) => CopyInterceptDecision;\n\n/**\n * When the transform throws or returns something unwritable:\n * - `'block'` (default): nothing is copied. Safe for redaction.\n * - `'native'`: the browser's default copy proceeds unmodified.\n */\nexport type CopyInterceptFailureMode = 'block' | 'native';\n\nexport interface CopyInterceptOptions {\n readonly transform: CopyInterceptTransform;\n readonly failureMode?: CopyInterceptFailureMode;\n}\n\nexport type CopyInterceptPassReason =\n /** Not a `copy`/`cut` event. */\n | 'unsupported-event'\n /** Another handler already called `preventDefault()`. */\n | 'already-handled'\n /** Nothing readable was selected. */\n | 'no-selection'\n /** The transform returned `null`/`undefined`. */\n | 'declined';\n\nexport type CopyInterceptOutcome =\n | {\n readonly status: 'passed';\n readonly reason: CopyInterceptPassReason;\n readonly selection: CopySelection | null;\n }\n | {\n readonly status: 'written';\n readonly selection: CopySelection;\n readonly payload: SyncCopyPayload;\n /** For an editable `cut`: whether the selection was removed. Always `false` for `copy`. */\n readonly deleted: boolean;\n }\n | { readonly status: 'blocked'; readonly selection: CopySelection }\n | {\n readonly status: 'failed';\n readonly selection: CopySelection;\n readonly error: CopyError;\n /** What actually happened to the copy. */\n readonly fallback: CopyInterceptFailureMode;\n };\n\n/* ─────────────────────────────────────────────────────── selection reading */\n\ntype TextField = HTMLInputElement | HTMLTextAreaElement;\n\nfunction isNode(value: unknown): value is Node {\n return typeof value === 'object' && value !== null && typeof (value as Node).nodeType === 'number';\n}\n\ninterface FieldSelection {\n readonly field: TextField;\n readonly start: number;\n readonly end: number;\n}\n\nfunction readTextField(target: EventTarget | null): FieldSelection | null {\n if (!isNode(target) || target.nodeType !== 1) return null;\n const tag = (target as Element).tagName;\n if (tag !== 'INPUT' && tag !== 'TEXTAREA') return null;\n const field = target as TextField;\n try {\n // `null` (or a throw, in older engines) for input types without text selection.\n const { selectionStart: start, selectionEnd: end } = field;\n return typeof start === 'number' && typeof end === 'number' ? { field, start, end } : null;\n } catch {\n return null;\n }\n}\n\nfunction documentOf(target: EventTarget | null): Document | null {\n if (isNode(target)) return target.nodeType === 9 ? (target as Document) : target.ownerDocument;\n return typeof document === 'undefined' ? null : document;\n}\n\nfunction isEditableNode(node: Node): boolean {\n const element = node.nodeType === 1 ? (node as HTMLElement) : node.parentElement;\n return element?.isContentEditable === true;\n}\n\ninterface SelectedRanges {\n readonly selection: Selection;\n readonly ranges: readonly Range[];\n}\n\nfunction selectedRanges(doc: Document | null): SelectedRanges | null {\n const selection = doc?.getSelection();\n if (!selection || selection.isCollapsed) return null;\n const ranges: Range[] = [];\n for (let index = 0; index < selection.rangeCount; index += 1) ranges.push(selection.getRangeAt(index));\n return { selection, ranges };\n}\n\ninterface ReadSelection {\n readonly selection: CopySelection;\n readonly doc: Document;\n}\n\nfunction readSelection(event: CopyEventLike): ReadSelection | null {\n const kind: InterceptedCopyKind = event.type === 'cut' ? 'cut' : 'copy';\n const fieldSelection = readTextField(event.target);\n if (fieldSelection) {\n const { field, start, end } = fieldSelection;\n const text = field.value.slice(Math.min(start, end), Math.max(start, end));\n if (text.length === 0) return null;\n const editable = !field.readOnly && !field.disabled;\n return { selection: { kind, text, html: null, fragment: null, field, editable }, doc: field.ownerDocument };\n }\n\n const doc = documentOf(event.target);\n const selected = selectedRanges(doc);\n const first = selected?.ranges[0];\n if (!doc || !selected || !first) return null;\n // `Selection#toString` follows the rendered layout, like the browser's own copy;\n // `Range#toString` would leak source whitespace and hidden text.\n const text = selected.selection.toString();\n if (text.length === 0) return null;\n\n const container = doc.createElement('div');\n for (const range of selected.ranges) container.appendChild(range.cloneContents());\n const html = container.innerHTML;\n const fragment = doc.createDocumentFragment();\n while (container.firstChild) fragment.appendChild(container.firstChild);\n\n const editable = isEditableNode(first.startContainer);\n return { selection: { kind, text, html, fragment, field: null, editable }, doc };\n}\n\n/** Reads the selection behind a copy event, or `null` if nothing readable is selected. */\nexport function readCopySelection(event: CopyEventLike): CopySelection | null {\n const read = readSelection(event);\n return read ? read.selection : null;\n}\n\n/* ─────────────────────────────────────────────────────────────── writing */\n\ntype Entries = readonly (readonly [mimeType: string, data: string])[];\n\ntype Prepared =\n | { readonly ok: true; readonly payload: SyncCopyPayload; readonly entries: Entries }\n | { readonly ok: false; readonly error: CopyError };\n\nconst nonEmpty = (value: unknown): value is string => typeof value === 'string' && value.length > 0;\nconst invalid = (message: string, cause?: unknown): Prepared => ({\n ok: false,\n error: createCopyError('invalid-payload', message, cause),\n});\nconst unsupported = (message: string): Prepared => ({ ok: false, error: createCopyError('unsupported-format', message) });\n\n/**\n * Validates a decision and turns it into `[mimeType, data]` pairs. Kept\n * self-contained (no shared validator) so the interceptor stays small; the\n * checks still run for plain-JS callers the types can't protect.\n */\nfunction prepare(decision: string | SyncCopyPayload): Prepared {\n const candidate: unknown = typeof decision === 'string' ? { kind: 'text', value: decision } : decision;\n if (typeof candidate !== 'object' || candidate === null) {\n return invalid('Copy transforms must return a string, a payload, false, or nothing.');\n }\n if (typeof (candidate as { then?: unknown }).then === 'function') {\n return invalid('Copy transforms must be synchronous; the clipboard closes when the event ends.');\n }\n const payload = candidate as SyncCopyPayload;\n const fields = candidate as Record<string, unknown>;\n const ok = (entries: Entries): Prepared => ({ ok: true, payload, entries });\n\n switch (fields['kind']) {\n case 'text':\n return nonEmpty(fields['value']) ? ok([['text/plain', fields['value']]]) : invalid('Text payload must be a non-empty string.');\n case 'html':\n return nonEmpty(fields['html']) && nonEmpty(fields['text'])\n ? ok([['text/html', fields['html']], ['text/plain', fields['text']]])\n : invalid('HTML payload requires non-empty `html` and plain-text `text`.');\n case 'json': {\n const pretty = fields['pretty'];\n const indent = pretty === true ? 2 : typeof pretty === 'number' ? pretty : undefined;\n // Typed as `string`, but `undefined` for functions, symbols and undefined.\n let json: unknown;\n try {\n json = JSON.stringify(fields['value'], null, indent);\n } catch (cause) {\n return invalid('JSON payload could not be serialised (circular reference or BigInt?).', cause);\n }\n return typeof json === 'string' ? ok([['text/plain', json]]) : invalid('JSON payload serialised to nothing.');\n }\n case 'multi': {\n const items = fields['items'];\n if (!Array.isArray(items) || items.length === 0) return invalid('Multi payload requires at least one item.');\n const entries: (readonly [string, string])[] = [];\n for (const item of items as unknown[]) {\n const { mimeType, data } = (item ?? {}) as { mimeType?: unknown; data?: unknown };\n if (!nonEmpty(mimeType) || entries.some(([seen]) => seen === mimeType)) {\n return invalid('Every multi item needs a unique, non-empty `mimeType`.');\n }\n if (typeof data !== 'string') return unsupported(`Multi item \"${mimeType}\" must be a string during a copy event.`);\n entries.push([mimeType, data]);\n }\n const writable = entries.filter(([mimeType]) => !isWebCustomFormat(mimeType));\n return writable.length > 0\n ? ok(writable)\n : unsupported('Web custom formats need the async Clipboard API (useCopy).');\n }\n default:\n return unsupported(`\"${String(fields['kind'])}\" payloads cannot be written during a copy event; use useCopy() for images.`);\n }\n}\n\n/** Deletes the selection the way a native cut would (keeps undo history, fires `input`). */\nfunction deleteSelection(doc: Document): boolean {\n const legacy = doc as unknown as { execCommand?: (command: string) => boolean };\n try {\n return legacy.execCommand?.('delete') === true;\n } catch {\n return false;\n }\n}\n\n/**\n * Applies a transform to one `copy`/`cut` event. Use directly from an\n * `onCopy` handler, or let {@link registerCopyInterceptor} scope it.\n */\nexport function interceptCopyEvent(event: CopyEventLike, options: CopyInterceptOptions): CopyInterceptOutcome {\n if (event.type !== 'copy' && event.type !== 'cut') {\n return { status: 'passed', reason: 'unsupported-event', selection: null };\n }\n if (event.defaultPrevented) return { status: 'passed', reason: 'already-handled', selection: null };\n\n const read = readSelection(event);\n if (!read) return { status: 'passed', reason: 'no-selection', selection: null };\n const { selection, doc } = read;\n\n const fail = (error: CopyError): CopyInterceptOutcome => {\n const fallback = options.failureMode ?? 'block';\n if (fallback === 'block') event.preventDefault();\n return { status: 'failed', selection, error, fallback };\n };\n\n let decision: CopyInterceptDecision;\n try {\n decision = options.transform(selection);\n } catch (cause) {\n return fail(sourceError(cause, 'The copy transform threw.'));\n }\n\n if (decision === null || decision === undefined) return { status: 'passed', reason: 'declined', selection };\n if (decision === false) {\n event.preventDefault();\n return { status: 'blocked', selection };\n }\n\n const prepared = prepare(decision);\n if (!prepared.ok) return fail(prepared.error);\n\n const data = event.clipboardData;\n if (!data) return fail(createCopyError('unsupported', 'This browser exposes no clipboardData on copy events.'));\n\n // From here the browser's default is gone: a failure can only end in `block`.\n event.preventDefault();\n try {\n for (const [mimeType, value] of prepared.entries) data.setData(mimeType, value);\n } catch (cause) {\n try {\n data.clearData?.();\n } catch {\n // Best effort: a half-written clipboard is still better reported than hidden.\n }\n const error = createCopyError('unknown', 'The browser rejected the clipboard write.', cause);\n return { status: 'failed', selection, error, fallback: 'block' };\n }\n\n const deleted = selection.kind === 'cut' && selection.editable && deleteSelection(doc);\n return { status: 'written', selection, payload: prepared.payload, deleted };\n}\n\n/* ────────────────────────────────────────────────────────────── scoping */\n\nexport interface CopyInterceptorOptions extends CopyInterceptOptions {\n /**\n * When one selection touches several scopes, exactly one handles it: the\n * highest `priority`, then the innermost, then the first in the document.\n * The winner sees the *whole* selection. Give redaction scopes a higher\n * priority so text copied across them is always masked. Default `0`.\n */\n readonly priority?: number;\n /** Which events to intercept. Default: both `copy` and `cut`. */\n readonly events?: readonly InterceptedCopyKind[];\n /** Every outcome for selections inside this scope, including `passed`. */\n readonly onIntercept?: (outcome: CopyInterceptOutcome) => void;\n /** Called when the transform failed; the outcome's `fallback` says what happened to the copy. */\n readonly onError?: (error: CopyError) => void;\n}\n\ninterface Scope {\n readonly root: Element;\n readonly read: () => CopyInterceptorOptions;\n}\n\ninterface Registry {\n readonly scopes: Set<Scope>;\n readonly listener: (event: Event) => void;\n}\n\nconst registries = /* @__PURE__ */ new WeakMap<Document, Registry>();\n\nfunction touches(root: Element, event: CopyEventLike): boolean {\n const fieldSelection = readTextField(event.target);\n if (fieldSelection) return root.contains(fieldSelection.field);\n const selected = selectedRanges(root.ownerDocument);\n return selected !== null && selected.ranges.some((range) => range.intersectsNode(root));\n}\n\nconst priorityOf = (scope: Scope): number => scope.read().priority ?? 0;\n\n/**\n * Highest `priority` first; then the innermost scope; then document order;\n * then registration order (same root). A total order, so the result never\n * depends on effect timing.\n */\nfunction compareScopes(a: Scope, b: Scope): number {\n const byPriority = priorityOf(b) - priorityOf(a);\n if (byPriority !== 0) return byPriority;\n const position = a.root.compareDocumentPosition(b.root);\n if (position === 0) return 0;\n if (position & 16) return 1; // b is inside a: b first\n if (position & 8) return -1; // b contains a: a first\n return position & 4 ? -1 : 1; // b follows a: a first\n}\n\nfunction dispatch(registry: Registry, event: CopyEventLike): void {\n if (event.defaultPrevented) return;\n const kind = event.type as InterceptedCopyKind;\n const candidates = [...registry.scopes].filter(\n (scope) => (scope.read().events ?? DEFAULT_INTERCEPTED_EVENTS).includes(kind) && touches(scope.root, event),\n );\n const [scope] = candidates.sort(compareScopes);\n if (!scope) return;\n\n const options = scope.read();\n const outcome = interceptCopyEvent(event, options);\n invoke(options.onIntercept, outcome);\n if (outcome.status === 'failed') invoke(options.onError, outcome.error);\n}\n\n/**\n * Intercepts native copies and cuts whose selection touches `root`. Returns\n * an unsubscribe function. Pass a getter to always read the latest options.\n *\n * One listener per document serves every scope, so overlapping scopes\n * resolve deterministically (see `priority`) regardless of registration order.\n * Handlers that call `preventDefault()` first (e.g. a React `onCopy`) win.\n */\nexport function registerCopyInterceptor(\n root: Element,\n options: CopyInterceptorOptions | (() => CopyInterceptorOptions),\n): () => void {\n const doc = root.ownerDocument;\n let registry = registries.get(doc);\n if (!registry) {\n const scopes = new Set<Scope>();\n const created: Registry = {\n scopes,\n listener: (event) => {\n dispatch(created, event as unknown as CopyEventLike);\n },\n };\n registry = created;\n registries.set(doc, created);\n doc.addEventListener('copy', created.listener);\n doc.addEventListener('cut', created.listener);\n }\n\n const scope: Scope = { root, read: typeof options === 'function' ? options : () => options };\n registry.scopes.add(scope);\n const active = registry;\n\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n active.scopes.delete(scope);\n if (active.scopes.size === 0) {\n doc.removeEventListener('copy', active.listener);\n doc.removeEventListener('cut', active.listener);\n registries.delete(doc);\n }\n };\n}\n","/**\n * Drag-to-copy: populate `DataTransfer` when the user starts dragging an\n * element, so whatever they drop it into receives structured data — plain text,\n * HTML, JSON, or multiple MIME types — instead of the browser's default\n * text-extraction of the dragged DOM.\n *\n * No Clipboard API, no permission prompt, works in every browser that supports\n * HTML5 drag-and-drop (all modern browsers and IE11+).\n */\n\nimport { invoke } from './machine-shared';\nimport { createCopyError, type CopyError } from './errors';\nimport { isWebCustomFormat } from './mime';\nimport type { HtmlPayload, JsonPayload, TextPayload } from './payload';\nimport { sourceError } from './source-error';\n\n/* ─────────────────────────────────────────────────────────────────── types */\n\n/**\n * The `effectAllowed` a drag operation advertises. Controls which cursor the\n * browser shows and which `dropEffect` the drop target may request.\n *\n * - `'copy'` (default): dragging produces a copy of the data.\n * - `'move'`: dragging removes the source after a drop (the app must do this).\n * - `'link'`: dragging creates a link/reference.\n * - `'copyMove'` / `'copyLink'` / `'linkMove'` / `'all'`: combinations.\n * - `'none'`: the drag is not droppable anywhere.\n * - `'uninitialized'`: browser default (same as `'all'` in most cases).\n */\nexport type DragEffectAllowed =\n | 'copy'\n | 'move'\n | 'link'\n | 'copyMove'\n | 'copyLink'\n | 'linkMove'\n | 'all'\n | 'none'\n | 'uninitialized';\n\n/** What is put into `DataTransfer` when a drag starts. */\nexport interface DragCopyItem {\n /** Web custom formats (`web …`) are skipped: only the async Clipboard API writes them. */\n readonly mimeType: string;\n readonly data: string;\n /** Accepted for parity with `MultiPayloadItem`; every non-web item can be written to a drag. */\n readonly optional?: boolean;\n}\n\n/**\n * A multi-format drag payload — strings only (DataTransfer only accepts strings).\n * Mirrors `SyncCopyPayload` from copy-interceptor but scoped to drag.\n */\nexport type DragCopyPayload = TextPayload | HtmlPayload | JsonPayload | DragMultiPayload;\n\nexport interface DragMultiPayload {\n readonly kind: 'multi';\n readonly items: readonly DragCopyItem[];\n}\n\n/**\n * What the source getter returns:\n * - a string: written as `text/plain`.\n * - a `DragCopyPayload`: written according to its `kind`.\n * - `false`: cancels the drag (`preventDefault()` on `dragstart`).\n * - `null` / `undefined`: leaves the browser's default drag data untouched.\n */\nexport type DragCopyDecision = string | DragCopyPayload | false | null | undefined;\n\n/** Called once when the user begins dragging the element. Must be synchronous. */\nexport type DragCopySource = (event: DragStartEventLike) => DragCopyDecision;\n\n/** Structural `DragEvent`: DOM and React drag events both satisfy it. */\nexport interface DragStartEventLike {\n readonly type: string;\n readonly dataTransfer: DataTransferLike | null;\n readonly defaultPrevented: boolean;\n preventDefault(): void;\n}\n\n/** The writable face of `DataTransfer`. */\nexport interface DataTransferLike {\n effectAllowed: string;\n setData(format: string, data: string): void;\n clearData?(format?: string): void;\n}\n\nexport type DragCopyStatus =\n /** No drag has started yet, or it was cancelled / never had source data. */\n | 'idle'\n /** The element is being dragged and data is on the DataTransfer. */\n | 'dragging'\n /** The drag ended (dropped or abandoned). */\n | 'done';\n\nexport type DragCopyPassReason =\n /** Source returned `null`/`undefined`. */\n | 'declined'\n /** `DataTransfer` is not present on this event. */\n | 'no-transfer'\n /** Source returned `false`. */\n | 'cancelled';\n\nexport type DragCopyOutcome =\n | { readonly status: 'written'; readonly payload: DragCopyPayload }\n | { readonly status: 'passed'; readonly reason: DragCopyPassReason }\n | { readonly status: 'failed'; readonly error: CopyError };\n\nexport interface DragCopyState {\n readonly status: DragCopyStatus;\n /** The last `dragstart` outcome; `null` before the first drag. */\n readonly outcome: DragCopyOutcome | null;\n}\n\nexport interface DragCopyOptions {\n /**\n * Returns the data to put in the drag. Called synchronously on `dragstart`.\n * Return a string (shorthand for `{ kind: 'text' }`), a payload object,\n * `false` to cancel the drag, or `null`/`undefined` to pass through.\n */\n readonly source: DragCopySource;\n /**\n * `effectAllowed` advertised on the drag. Default `'copy'`.\n * Setting `'move'` signals to drop targets that the source will be removed.\n */\n readonly effectAllowed?: DragEffectAllowed;\n /**\n * Called each time a drag starts or ends, with the latest outcome and status.\n * Stable across re-renders when written as a class method or via `useRef`.\n */\n readonly onDrag?: (state: DragCopyState) => void;\n /** Called when preparing the drag payload fails. */\n readonly onError?: (error: CopyError) => void;\n}\n\n/* ─────────────────────────────────────────────────────────── validation */\n\nconst nonEmpty = (value: unknown): value is string =>\n typeof value === 'string' && value.length > 0;\n\ntype PrepareFail = { readonly ok: false; readonly error: CopyError };\ntype PrepareOk = { readonly ok: true; readonly payload: DragCopyPayload; readonly items: readonly DragCopyItem[] };\ntype Prepared = PrepareOk | PrepareFail;\n\nconst invalid = (message: string, cause?: unknown): PrepareFail => ({\n ok: false,\n error: createCopyError('invalid-payload', message, cause),\n});\n\nconst unsupported = (message: string): PrepareFail => ({\n ok: false,\n error: createCopyError('unsupported-format', message),\n});\n\nfunction prepareDragDecision(decision: string | DragCopyPayload): Prepared {\n const candidate: unknown =\n typeof decision === 'string' ? { kind: 'text', value: decision } : decision;\n\n if (typeof candidate !== 'object' || candidate === null) {\n return invalid('Drag source must return a string, a payload, false, or nothing.');\n }\n if (typeof (candidate as { then?: unknown }).then === 'function') {\n return invalid('Drag sources must be synchronous; DataTransfer closes when dragstart returns.');\n }\n\n const payload = candidate as DragCopyPayload;\n const fields = candidate as Record<string, unknown>;\n const ok = (items: readonly DragCopyItem[]): PrepareOk => ({ ok: true, payload, items });\n\n switch (fields['kind']) {\n case 'text':\n return nonEmpty(fields['value'])\n ? ok([{ mimeType: 'text/plain', data: fields['value'] }])\n : invalid('Text payload must be a non-empty string.');\n\n case 'html':\n return nonEmpty(fields['html']) && nonEmpty(fields['text'])\n ? ok([\n { mimeType: 'text/html', data: fields['html'] },\n { mimeType: 'text/plain', data: fields['text'] },\n ])\n : invalid('HTML payload requires non-empty `html` and `text`.');\n\n case 'json': {\n const pretty = fields['pretty'];\n const indent =\n pretty === true ? 2 : typeof pretty === 'number' ? pretty : undefined;\n let json: unknown;\n try {\n json = JSON.stringify(fields['value'], null, indent);\n } catch (cause) {\n return invalid(\n 'JSON payload could not be serialised (circular reference or BigInt?).',\n cause,\n );\n }\n return typeof json === 'string'\n ? ok([{ mimeType: 'text/plain', data: json }])\n : invalid('JSON payload serialised to nothing.');\n }\n\n case 'multi': {\n const items = fields['items'];\n if (!Array.isArray(items) || items.length === 0) {\n return invalid('Multi payload requires at least one item.');\n }\n const out: DragCopyItem[] = [];\n for (const item of items as unknown[]) {\n const { mimeType, data } = (item ?? {}) as {\n mimeType?: unknown;\n data?: unknown;\n };\n if (!nonEmpty(mimeType) || out.some((i) => i.mimeType === mimeType)) {\n return invalid('Every multi item needs a unique, non-empty `mimeType`.');\n }\n if (typeof data !== 'string') {\n return unsupported(\n `Multi item \"${mimeType}\" must be a string; DataTransfer does not accept Blobs.`,\n );\n }\n out.push({ mimeType, data });\n }\n const writable = out.filter((item) => !isWebCustomFormat(item.mimeType));\n return writable.length > 0\n ? ok(writable)\n : unsupported('Web custom formats need the async Clipboard API (useCopy).');\n }\n\n default:\n return unsupported(\n `\"${String(fields['kind'])}\" payloads cannot be used for drag-copy; use useCopy() for images.`,\n );\n }\n}\n\n/* ─────────────────────────────────────────────────────── applyDragCopy */\n\n/**\n * Populates a `dragstart` event's `DataTransfer` with the given payload.\n * Use this from a raw `dragstart` handler or a React `onDragStart` prop.\n * Returns the outcome so you can inspect what happened.\n */\nexport function applyDragCopy(\n event: DragStartEventLike,\n options: DragCopyOptions,\n): DragCopyOutcome {\n if (event.defaultPrevented) {\n return { status: 'passed', reason: 'declined' };\n }\n\n let decision: DragCopyDecision;\n try {\n decision = options.source(event);\n } catch (cause) {\n const error = sourceError(cause, 'The drag source threw.');\n return { status: 'failed', error };\n }\n\n if (decision === null || decision === undefined) {\n return { status: 'passed', reason: 'declined' };\n }\n\n if (decision === false) {\n event.preventDefault();\n return { status: 'passed', reason: 'cancelled' };\n }\n\n const transfer = event.dataTransfer;\n if (!transfer) {\n return { status: 'passed', reason: 'no-transfer' };\n }\n\n const prepared = prepareDragDecision(decision);\n if (!prepared.ok) {\n return { status: 'failed', error: prepared.error };\n }\n\n try {\n transfer.effectAllowed = options.effectAllowed ?? 'copy';\n for (const { mimeType, data } of prepared.items) {\n transfer.setData(mimeType, data);\n }\n } catch (cause) {\n try {\n transfer.clearData?.();\n } catch {\n // Best effort: report the original error, not a clearData failure.\n }\n const error = createCopyError(\n 'unknown',\n 'The browser rejected the DataTransfer write.',\n cause,\n );\n return { status: 'failed', error };\n }\n\n return { status: 'written', payload: prepared.payload };\n}\n\n/* ─────────────────────────────────────────────────── registerDragCopy */\n\nexport interface RegisterDragCopyResult {\n /** Unsubscribes all listeners. Idempotent. */\n readonly unsubscribe: () => void;\n}\n\n/**\n * Attaches `dragstart` and `dragend` listeners to `element`, calling\n * `applyDragCopy` on every drag start. Returns an object with an\n * `unsubscribe` function.\n *\n * Pass an options getter so the latest options are always used without\n * re-registering — safe to pass an inline object from a React render.\n *\n * ```ts\n * const { unsubscribe } = registerDragCopy(el, () => ({\n * source: () => `${title}\\n${url}`,\n * }));\n * ```\n */\nexport function registerDragCopy(\n element: HTMLElement,\n options: DragCopyOptions | (() => DragCopyOptions),\n): RegisterDragCopyResult {\n const read = typeof options === 'function' ? options : (): DragCopyOptions => options;\n\n let unsubscribed = false;\n let currentOutcome: DragCopyOutcome | null = null;\n\n function onDragStart(raw: Event): void {\n const event = raw as DragEvent;\n const opts = read();\n\n const outcome = applyDragCopy(\n {\n type: event.type,\n dataTransfer: event.dataTransfer,\n get defaultPrevented() {\n return event.defaultPrevented;\n },\n preventDefault: () => { event.preventDefault(); },\n },\n opts,\n );\n\n currentOutcome = outcome;\n\n const state: DragCopyState = { status: 'dragging', outcome };\n if (outcome.status === 'failed') invoke(opts.onError, outcome.error);\n invoke(opts.onDrag, state);\n }\n\n function onDragEnd(): void {\n const opts = read();\n const state: DragCopyState = { status: 'done', outcome: currentOutcome };\n invoke(opts.onDrag, state);\n currentOutcome = null;\n }\n\n element.setAttribute('draggable', 'true');\n element.addEventListener('dragstart', onDragStart);\n element.addEventListener('dragend', onDragEnd);\n\n return {\n unsubscribe(): void {\n if (unsubscribed) return;\n unsubscribed = true;\n element.removeEventListener('dragstart', onDragStart);\n element.removeEventListener('dragend', onDragEnd);\n element.removeAttribute('draggable');\n },\n };\n}\n","import { copyFailure } from './errors';\nimport { isTextualMimeType, matchesMimePattern, normalizeClipboardType, normalizeMimeType, sniffImageType } from './mime';\n\n/* ------------------------------------------------------------------ Types */\n\n/** Friendly names for the common cases. */\nexport type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';\n\n/**\n * What a paste may contain, in any order: a shorthand, an exact MIME type\n * (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a\n * wildcard (`'image/*'`, `'*\\/*'`). `image/svg+xml` (scriptable XML), web custom\n * formats and `+json` types are only accepted when listed exactly.\n */\nexport type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;\n\nexport interface PasteLimits {\n /**\n * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as\n * they would be encoded, matching `Blob.size`, so every paste path counts the same way.\n * Default 32 MiB.\n */\n readonly maxBytes?: number;\n /** Max number of accepted items (types + files). Default 32. */\n readonly maxItems?: number;\n}\n\nexport interface PasteReadOptions extends PasteLimits {\n /** Default `['text']` (plain text only): the safest choice. */\n readonly accept?: readonly PasteAccept[];\n}\n\n/** Validated, normalised options that adapters receive. */\nexport interface ResolvedPasteReadOptions {\n /** Normalised patterns: `type/subtype`, `type/*` or `*\\/*`. */\n readonly accept: readonly string[];\n readonly maxBytes: number;\n readonly maxItems: number;\n}\n\n/** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */\nexport type PasteSource = 'clipboard' | 'event' | 'drop';\n\n/** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */\nexport interface PasteItem {\n readonly type: string;\n readonly data: string | Blob;\n}\n\n/**\n * Everything the paste produced. Treat all of it as untrusted user input:\n * in particular never inject `html` into the DOM without sanitising it.\n */\nexport interface PasteResult {\n readonly source: PasteSource;\n /** Every accepted entry, in clipboard order. */\n readonly items: readonly PasteItem[];\n /** `text/plain`, when accepted and present. */\n readonly text: string | null;\n /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */\n readonly html: string | null;\n /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */\n readonly images: readonly Blob[];\n /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */\n readonly files: readonly File[];\n /**\n * The entries of `files` that are also in `images`: verified image files, keeping their\n * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.\n */\n readonly imageFiles: readonly File[];\n}\n\n/** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */\nexport type PasteReadResult = Omit<PasteResult, 'imageFiles'>;\n\n/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */\nexport function completePasteResult(result: PasteReadResult): PasteResult {\n const images = new Set<Blob>(result.images);\n return { ...result, imageFiles: result.files.filter((file) => images.has(file)) };\n}\n\n/* -------------------------------------------------------- Option handling */\n\nexport const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[] = /* @__PURE__ */ Object.freeze(['text'] as const);\nexport const DEFAULT_PASTE_MAX_BYTES = 32 * 1024 * 1024;\nexport const DEFAULT_PASTE_MAX_ITEMS = 32;\n\nconst SHORTHANDS: ReadonlyMap<string, string> = /* @__PURE__ */ new Map([\n ['text', 'text/plain'],\n ['html', 'text/html'],\n ['image', 'image/*'],\n ['any', '*/*'],\n]);\n\nconst TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\nfunction resolvePattern(entry: unknown): string | null {\n if (typeof entry !== 'string') return null;\n const shorthand = SHORTHANDS.get(entry);\n if (shorthand !== undefined) return shorthand;\n if (entry === '*/*') return entry;\n if (entry.endsWith('/*')) {\n const type = entry.slice(0, -2).toLowerCase();\n return TYPE_TOKEN.test(type) ? `${type}/*` : null;\n }\n return normalizeClipboardType(entry);\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\n/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */\nexport function resolvePasteReadOptions(options: PasteReadOptions = {}): ResolvedPasteReadOptions {\n const accept: string[] = [];\n for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {\n const pattern = resolvePattern(entry);\n if (pattern === null) throw copyFailure('invalid-payload', `Invalid \\`accept\\` entry: ${JSON.stringify(entry)}.`);\n if (!accept.includes(pattern)) accept.push(pattern);\n }\n if (accept.length === 0) throw copyFailure('invalid-payload', '`accept` must list at least one type.');\n return {\n accept,\n maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, 'maxBytes'),\n maxItems: resolveLimit(options.maxItems, DEFAULT_PASTE_MAX_ITEMS, 'maxItems'),\n };\n}\n\n/** Whether a normalised MIME type is allowed by the resolved `accept` list. */\nexport function isAccepted(mimeType: string, options: ResolvedPasteReadOptions): boolean {\n return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));\n}\n\n/* -------------------------------------------------------------- Entries */\n\n/** An accepted, not-yet-verified entry. */\nexport interface PasteEntry {\n readonly type: string;\n readonly data: string | Blob;\n /** Came from `DataTransfer.files`, i.e. `data` is a `File`. */\n readonly file: boolean;\n}\n\ninterface Budget {\n readonly charge: (size: number) => void;\n}\n\nfunction createBudget(options: ResolvedPasteReadOptions): Budget {\n let bytes = 0;\n let items = 0;\n return {\n charge: (size) => {\n items += 1;\n bytes += size;\n if (items > options.maxItems) {\n throw copyFailure('too-large', `The paste has more than ${String(options.maxItems)} accepted items.`);\n }\n if (bytes > options.maxBytes) {\n throw copyFailure('too-large', `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);\n }\n },\n };\n}\n\n/**\n * UTF-8 byte length of a string, without allocating an encoded copy.\n * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.\n */\nexport function utf8ByteLength(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i += 1) {\n const unit = text.charCodeAt(i);\n if (unit < 0x80) bytes += 1;\n else if (unit < 0x800) bytes += 2;\n else if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n bytes += 4;\n i += 1;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */\nconst sizeOf = (data: string | Blob): number => (typeof data === 'string' ? utf8ByteLength(data) : data.size);\n\n/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */\nexport function enforcePasteLimits(entries: readonly PasteEntry[], options: ResolvedPasteReadOptions): void {\n const budget = createBudget(options);\n for (const entry of entries) budget.charge(sizeOf(entry.data));\n}\n\n/** Structural view of a `DataTransferItem`: only what is readable while dragging. */\nexport interface DataTransferItemLike {\n /** `'string'` or `'file'`. */\n readonly kind: string;\n readonly type: string;\n}\n\n/** Structural view of `DataTransfer` (paste and drop events). */\nexport interface DataTransferLike {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n readonly files?: ArrayLike<File> | null;\n readonly items?: ArrayLike<DataTransferItemLike> | null;\n}\n\n/**\n * Whether a drag in progress could drop anything `accept`s. Uses only what\n * browsers expose before the drop (item kinds and types, never the data).\n * A file whose type is not known yet (some browsers hide it while dragging)\n * counts as a maybe: the drop itself is checked against `accept`.\n */\nexport function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean {\n // Without an item list, a file is only known as the type \"Files\": treat it as an untyped file.\n const items = data.items ?? Array.from(data.types, (type) => (type === 'Files' ? { kind: 'file', type: '' } : { kind: 'string', type }));\n return Array.from(items).some(({ kind, type: raw }) => {\n const file = kind === 'file';\n const type = normalizeClipboardType(raw);\n if (type === null) return file;\n return (file || isTextualMimeType(type)) && isAccepted(type, options);\n });\n}\n\n/**\n * Synchronously copies the accepted parts of a paste event's `DataTransfer`.\n * It must run during the event: browsers empty the object afterwards.\n */\nexport function snapshotDataTransfer(data: DataTransferLike, options: ResolvedPasteReadOptions): PasteEntry[] {\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const raw of Array.from(data.types)) {\n const type = normalizeClipboardType(raw);\n // Binary types are delivered through `files`; `getData` only returns strings.\n if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n const text = data.getData(raw);\n if (text.length > 0) entries.push({ type, data: text, file: false });\n }\n\n for (const file of Array.from(data.files ?? [])) {\n const type = normalizeMimeType(file.type) ?? 'application/octet-stream';\n if (isAccepted(type, options)) entries.push({ type, data: file, file: true });\n }\n\n return entries;\n}\n\n/** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */\nexport interface ClipboardItemLike {\n readonly types: readonly string[];\n getType(type: string): Promise<Blob>;\n}\n\n/**\n * Reads the accepted types from `navigator.clipboard.read()` items, enforcing\n * the limits *before* decoding any text so an oversized paste is never buffered twice.\n */\nexport async function collectClipboardItems(\n items: readonly ClipboardItemLike[],\n options: ResolvedPasteReadOptions,\n signal?: AbortSignal,\n): Promise<PasteEntry[]> {\n const budget = createBudget(options);\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const item of items) {\n for (const raw of item.types) {\n const type = normalizeClipboardType(raw);\n if (type === null || seen.has(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n\n let blob: Blob;\n try {\n blob = await item.getType(raw);\n } catch {\n // Chromium lists some types it then refuses to hand over; skip them, don't fail the paste.\n continue;\n }\n // Cancelled (reset, superseded, unmounted) while waiting: don't decode the rest.\n if (signal?.aborted) throw copyFailure('aborted', 'The paste was cancelled.');\n if (blob.size === 0) continue;\n budget.charge(blob.size);\n entries.push({ type, data: isTextualMimeType(type) ? await blob.text() : blob, file: false });\n }\n }\n return entries;\n}\n\n/* ------------------------------------------------------------ Finalising */\n\nfunction retype(entry: PasteEntry, data: Blob, type: string): Blob {\n if (entry.file) {\n const file = data as File;\n return new File([file], file.name, { type, lastModified: file.lastModified });\n }\n return data.slice(0, data.size, type);\n}\n\n/**\n * Verifies image bytes, then builds the result. Blobs that claim to be images\n * but aren't (or whose real format is not accepted) are dropped. Throws\n * `no-content` when nothing survives.\n */\nexport async function finalizePaste(\n entries: readonly PasteEntry[],\n source: PasteSource,\n options: ResolvedPasteReadOptions,\n): Promise<PasteReadResult> {\n const items: PasteItem[] = [];\n const images: Blob[] = [];\n const files: File[] = [];\n let text: string | null = null;\n let html: string | null = null;\n\n for (const entry of entries) {\n let { type, data } = entry;\n\n if (typeof data === 'string') {\n // Types are de-duplicated upstream, so each of these is seen at most once.\n if (type === 'text/plain') text = data;\n else if (type === 'text/html') html = data;\n } else if (type.startsWith('image/')) {\n const actual = await sniffImageType(data);\n if (actual === null || !isAccepted(actual, options)) continue;\n if (actual !== type) {\n data = retype(entry, data, actual);\n type = actual;\n }\n images.push(data);\n }\n\n if (entry.file) files.push(data as File);\n items.push({ type, data });\n }\n\n if (items.length === 0) {\n throw copyFailure('no-content', 'The content holds nothing that matches `accept`.');\n }\n return { source, items, text, html, images, files };\n}\n","import { CopyFailure, copyFailure, toCopyError } from './errors';\nimport type { OperationContext } from './machine-shared';\nimport { matchesMimePattern } from './mime';\nimport {\n collectClipboardItems,\n enforcePasteLimits,\n finalizePaste,\n type ClipboardItemLike,\n type PasteEntry,\n type PasteReadResult,\n type ResolvedPasteReadOptions,\n} from './paste-reader';\n\n/** Minimal structural view of `navigator.clipboard` for reading. */\nexport interface PasteClipboardLike {\n read?(): Promise<readonly ClipboardItemLike[]>;\n readText?(): Promise<string>;\n}\n\nexport interface PasteEnvironment {\n readonly isSecureContext?: boolean;\n readonly navigator?: { readonly clipboard?: PasteClipboardLike | undefined } | undefined;\n}\n\n/**\n * Reads the system clipboard. Implement it for Electron, a native bridge or tests.\n *\n * Contract: call the platform API synchronously (before any `await`) so the\n * browser still sees the user gesture, and reject with a `CopyFailure`.\n * `context.signal` aborts when the read is superseded, reset, or its host\n * unmounts; honour it to stop decoding early.\n */\nexport interface PasteAdapter {\n read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteReadResult>;\n}\n\nexport interface BrowserPasteAdapterOptions {\n /** Defaults to `window`, read lazily at paste time (SSR-safe). */\n readonly getEnvironment?: () => PasteEnvironment | undefined;\n}\n\nfunction defaultEnvironment(): PasteEnvironment | undefined {\n return typeof window === 'undefined' ? undefined : window;\n}\n\ntype ClipboardWithRead = PasteClipboardLike & Required<Pick<PasteClipboardLike, 'read'>>;\ntype ClipboardWithReadText = PasteClipboardLike & Required<Pick<PasteClipboardLike, 'readText'>>;\n\nconst canRead = (clipboard: PasteClipboardLike): clipboard is ClipboardWithRead => typeof clipboard.read === 'function';\nconst canReadText = (clipboard: PasteClipboardLike): clipboard is ClipboardWithReadText =>\n typeof clipboard.readText === 'function';\n\nasync function readPlainText(clipboard: ClipboardWithReadText, options: ResolvedPasteReadOptions): Promise<PasteReadResult> {\n let text: string;\n try {\n text = await clipboard.readText();\n } catch (cause) {\n throw new CopyFailure(toCopyError(cause, 'read'));\n }\n const entries: PasteEntry[] = text.length > 0 ? [{ type: 'text/plain', data: text, file: false }] : [];\n enforcePasteLimits(entries, options);\n return finalizePaste(entries, 'clipboard', options);\n}\n\nasync function readRich(\n clipboard: ClipboardWithRead,\n options: ResolvedPasteReadOptions,\n signal: AbortSignal | undefined,\n): Promise<PasteReadResult> {\n let items: readonly ClipboardItemLike[];\n try {\n items = await clipboard.read();\n } catch (cause) {\n throw new CopyFailure(toCopyError(cause, 'read'));\n }\n const entries = await collectClipboardItems(items, options, signal);\n return finalizePaste(entries, 'clipboard', options);\n}\n\nfunction readFromClipboard(\n env: PasteEnvironment | undefined,\n options: ResolvedPasteReadOptions,\n signal: AbortSignal | undefined,\n): Promise<PasteReadResult> {\n if (!env) throw copyFailure('unsupported', 'No browser environment: the clipboard only exists in the browser.');\n if (env.isSecureContext === false) {\n throw copyFailure('insecure-context', 'The Clipboard API requires a secure context (HTTPS or localhost).');\n }\n const clipboard = env.navigator?.clipboard;\n if (!clipboard) throw copyFailure('unsupported', 'navigator.clipboard is not available in this browser.');\n\n const plainOnly = options.accept.every((pattern) => pattern === 'text/plain');\n const acceptsPlain = options.accept.some((pattern) => matchesMimePattern('text/plain', pattern));\n\n // readText() has the widest support and the narrowest permission prompt: prefer it for plain text.\n if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options, signal);\n if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);\n throw canReadText(clipboard)\n ? copyFailure('unsupported-format', 'Reading non-text clipboard content requires navigator.clipboard.read().')\n : copyFailure('unsupported', 'This browser cannot read the clipboard.');\n}\n\n/** The default paste adapter: async Clipboard API with feature detection and honest errors. */\nexport function createBrowserPasteAdapter(options: BrowserPasteAdapterOptions = {}): PasteAdapter {\n const getEnvironment = options.getEnvironment ?? defaultEnvironment;\n return {\n read: (resolved, context) => {\n try {\n return readFromClipboard(getEnvironment(), resolved, context?.signal);\n } catch (cause) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- always a CopyFailure\n return Promise.reject(cause);\n }\n },\n };\n}\n","import { createCopyError, isRetryableError, toCopyError, type CopyError } from './errors';\nimport { createOperations, invoke, resolveMaxRetries, type OperationContext } from './machine-shared';\nimport { createBrowserPasteAdapter, type PasteAdapter } from './paste-adapter';\nimport {\n completePasteResult,\n enforcePasteLimits,\n finalizePaste,\n resolvePasteReadOptions,\n snapshotDataTransfer,\n type DataTransferLike,\n type PasteReadOptions,\n type PasteReadResult,\n type PasteResult,\n type PasteSource,\n} from './paste-reader';\n\n/* ------------------------------------------------------------------ State */\n\nexport interface PasteIdleState {\n readonly status: 'idle';\n}\nexport interface PasteReadingState {\n readonly status: 'reading';\n}\nexport interface PasteReadState {\n readonly status: 'read';\n readonly result: PasteResult;\n /** Epoch ms when the read resolved. */\n readonly at: number;\n}\nexport interface PasteErrorState {\n readonly status: 'error';\n readonly error: CopyError;\n /** Where the failed read came from. Only `'clipboard'` reads can be retried. */\n readonly source: PasteSource;\n /** `retry()` calls made since the last fresh `paste()`. */\n readonly retryCount: number;\n}\n\nexport type PasteState = PasteIdleState | PasteReadingState | PasteReadState | PasteErrorState;\nexport type PasteStatus = PasteState['status'];\n\n/**\n * `cancelled`: the read was superseded, reset, or its host unmounted before it\n * finished, so its work was aborted. Nothing to report to the user.\n */\nexport type PasteIgnoredReason = 'in-flight' | 'no-accepted-content' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';\n\n/**\n * Why an in-flight read was cancelled: `reset` (`reset()` was called),\n * `disconnect` (its host disconnected, e.g. the React component unmounted) or\n * `superseded` (a paste or drop event arrived while a read was pending).\n */\nexport type PasteCancelReason = 'reset' | 'disconnect' | 'superseded';\n\n/** What `paste()` / `pasteEvent()` / `dropEvent()` / `retry()` resolve to. They never reject. */\nexport type PasteOutcome =\n | { readonly status: 'read'; readonly result: PasteResult }\n | { readonly status: 'error'; readonly error: CopyError }\n | { readonly status: 'ignored'; readonly reason: PasteIgnoredReason };\n\n/** Structural view of a DOM / React `paste` event. */\nexport interface PasteEventLike {\n readonly clipboardData: DataTransferLike | null | undefined;\n preventDefault(): void;\n}\n\n/** Structural view of a DOM / React `drop` event. */\nexport interface PasteDropEventLike {\n readonly dataTransfer: DataTransferLike | null | undefined;\n preventDefault(): void;\n}\n\n/* ---------------------------------------------------------------- Options */\n\nexport interface PasteMachineOptions extends PasteReadOptions {\n /** Defaults to the browser Clipboard API adapter. */\n readonly adapter?: PasteAdapter;\n /** Return from `read` to `idle` after this many ms. `false` / `Infinity` / omitted = keep the result. */\n readonly resetAfterMs?: number | false;\n /**\n * Paste events: call `event.preventDefault()` when the event carried accepted\n * content, so the browser doesn't also insert it. Drop events: always call it,\n * so the browser doesn't open the dropped file. Default `true`.\n */\n readonly preventDefault?: boolean;\n /**\n * Max `retry()` calls after a failed clipboard read. Default 3. `0`\n * disables retry; `Infinity` allows unlimited retries.\n */\n readonly maxRetries?: number;\n readonly onPaste?: (result: PasteResult) => void;\n readonly onError?: (error: CopyError) => void;\n /**\n * `reset()` moved the machine back to `idle` from any other state. Not\n * called for the automatic return after `resetAfterMs`, or when already `idle`.\n */\n readonly onReset?: () => void;\n /**\n * A read in flight was cancelled before it settled: its `signal` aborted\n * and its result will not reach state or `onPaste` / `onError`. Fires\n * before `onReset` when `reset()` cancels a read.\n */\n readonly onCancel?: (reason: PasteCancelReason) => void;\n /** Clock injection for tests and deterministic environments. */\n readonly now?: () => number;\n}\n\n/** Options object, or a getter so hosts (like React) can supply the latest options. */\nexport type PasteMachineOptionsSource = PasteMachineOptions | (() => PasteMachineOptions);\n\nexport interface PasteMachine {\n readonly getSnapshot: () => PasteState;\n readonly subscribe: (listener: () => void) => () => void;\n /**\n * Reads the system clipboard via the adapter. Call it from a user gesture\n * (click, keypress). May show a permission prompt. Ignored while `reading`.\n */\n readonly paste: () => Promise<PasteOutcome>;\n /**\n * Handles a `paste` event (Ctrl/⌘+V). No permission prompt: the data is\n * already in the event. Supersedes any read in flight. Events without\n * accepted content are ignored and left untouched for the browser.\n */\n readonly pasteEvent: (event: PasteEventLike) => Promise<PasteOutcome>;\n /**\n * Handles a drag-and-drop `drop` event exactly like a paste event: same\n * `accept`, limits and image checks, `result.source === 'drop'`. Always calls\n * `event.preventDefault()` (unless `preventDefault: false`), so a rejected\n * file is not opened by the browser in place of the page.\n */\n readonly dropEvent: (event: PasteDropEventLike) => Promise<PasteOutcome>;\n /**\n * Re-reads the clipboard after a retryable failure (e.g. permission denied,\n * page not focused), up to `maxRetries`. Call it from a user gesture.\n * Paste-event failures can't be retried: their data is gone after dispatch.\n */\n readonly retry: () => Promise<PasteOutcome>;\n /** Back to `idle`. Discards any in-flight result and aborts its `signal`. */\n readonly reset: () => void;\n /**\n * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned\n * cleanup clears timers, drops in-flight results, aborts in-flight work and\n * unsticks `reading`.\n * Safe to call repeatedly (React StrictMode).\n */\n readonly connect: () => () => void;\n}\n\nexport const PASTE_IDLE_STATE: PasteIdleState = /* @__PURE__ */ Object.freeze({ status: 'idle' });\nconst PASTE_READING_STATE: PasteReadingState = /* @__PURE__ */ Object.freeze({ status: 'reading' });\nconst IGNORED_IN_FLIGHT: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'in-flight' });\nconst IGNORED_NO_CONTENT: PasteOutcome = /* @__PURE__ */ Object.freeze({\n status: 'ignored',\n reason: 'no-accepted-content',\n});\nconst IGNORED_NOTHING: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'nothing-to-retry' });\nconst IGNORED_NOT_RETRYABLE: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'not-retryable' });\nconst IGNORED_CANCELLED: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'cancelled' });\n\nfunction resolveResetDelay(value: number | false | undefined): number | null {\n if (value === undefined || value === false || value === Infinity || Number.isNaN(value)) return null;\n return Math.max(0, value);\n}\n\n/** Pure helper: can `retry()` do anything from this state? */\nexport function canRetryPasteState(state: PasteState, maxRetries?: number): boolean {\n return (\n state.status === 'error' &&\n state.source === 'clipboard' &&\n isRetryableError(state.error) &&\n state.retryCount < resolveMaxRetries(maxRetries)\n );\n}\n\nlet defaultAdapter: PasteAdapter | undefined;\nconst getDefaultAdapter = (): PasteAdapter => (defaultAdapter ??= createBrowserPasteAdapter());\n\n/** Framework-agnostic paste state machine. */\nexport function createPasteMachine(options: PasteMachineOptionsSource = {}): PasteMachine {\n const read = typeof options === 'function' ? options : (): PasteMachineOptions => options;\n const listeners = new Set<() => void>();\n let state: PasteState = PASTE_IDLE_STATE;\n let generation = 0;\n let resetTimer: ReturnType<typeof setTimeout> | undefined;\n const operations = createOperations();\n\n const now = (): number => (read().now ?? Date.now)();\n\n const setState = (next: PasteState): void => {\n if (next === state) return;\n state = next;\n for (const listener of Array.from(listeners)) listener();\n };\n\n const clearResetTimer = (): void => {\n if (resetTimer !== undefined) {\n clearTimeout(resetTimer);\n resetTimer = undefined;\n }\n };\n\n const scheduleReset = (readState: PasteReadState): void => {\n clearResetTimer();\n const delay = resolveResetDelay(read().resetAfterMs);\n if (delay === null) return;\n const remaining = Math.max(0, delay - (now() - readState.at));\n // Invariant: every transition out of `read` clears this timer, so it only ever fires while still in `readState`.\n resetTimer = setTimeout(() => {\n resetTimer = undefined;\n setState(PASTE_IDLE_STATE);\n }, remaining);\n };\n\n const settleError = (error: CopyError, source: PasteSource, retryCount: number): void => {\n setState({ status: 'error', error, source, retryCount });\n invoke(read().onError, error);\n };\n\n /** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */\n const run = (\n produce: (context: OperationContext) => Promise<PasteReadResult>,\n source: PasteSource,\n retryCount: number,\n ): Promise<PasteOutcome> => {\n clearResetTimer();\n const current = ++generation;\n const superseded = operations.abort();\n const context = operations.start();\n setState(PASTE_READING_STATE);\n if (superseded) invoke(read().onCancel, 'superseded');\n\n let pending: Promise<PasteReadResult>;\n try {\n pending = produce(context);\n } catch (cause) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified below\n pending = Promise.reject(cause);\n }\n\n // Completing inside the chain routes a malformed adapter result to the error path,\n // so `paste()` still never rejects and the machine never stays stuck in `reading`.\n return pending.then(completePasteResult).then(\n (result): PasteOutcome => {\n operations.end(context);\n if (current === generation) {\n const readState: PasteReadState = { status: 'read', result, at: now() };\n setState(readState);\n scheduleReset(readState);\n invoke(read().onPaste, result);\n }\n return { status: 'read', result };\n },\n (cause: unknown): PasteOutcome => {\n operations.end(context);\n // Work we aborted ourselves (superseded, reset, unmount) is not a failure to report.\n // Invariant: superseding an in-flight read always aborts it, so past\n // this line the read is still the current one.\n if (context.signal.aborted) return IGNORED_CANCELLED;\n const error = toCopyError(cause, 'read');\n settleError(error, source, retryCount);\n return { status: 'error', error };\n },\n );\n };\n\n const readClipboard = (retryCount: number): Promise<PasteOutcome> =>\n run(\n (context) => (read().adapter ?? getDefaultAdapter()).read(resolvePasteReadOptions(read()), context),\n 'clipboard',\n retryCount,\n );\n\n const paste = (): Promise<PasteOutcome> =>\n state.status === 'reading' ? Promise.resolve(IGNORED_IN_FLIGHT) : readClipboard(0);\n\n const retry = (): Promise<PasteOutcome> => {\n if (state.status !== 'error') return Promise.resolve(IGNORED_NOTHING);\n if (state.source !== 'clipboard' || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);\n if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {\n const error = createCopyError(\n 'max-retries-exceeded',\n `Paste failed after ${String(state.retryCount)} retries.`,\n state.error,\n );\n settleError(error, 'clipboard', state.retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n return readClipboard(state.retryCount + 1);\n };\n\n /** Shared by paste and drop events: their `DataTransfer` has the same shape and lifetime. */\n const transfer = (\n data: DataTransferLike | null | undefined,\n event: { preventDefault(): void },\n source: 'event' | 'drop',\n ): Promise<PasteOutcome> => {\n const current = read();\n // An unhandled drop makes the browser open the file in place of the page, so drops are always claimed.\n if (source === 'drop' && current.preventDefault !== false) event.preventDefault();\n if (!data) return Promise.resolve(IGNORED_NO_CONTENT);\n\n let resolved: ReturnType<typeof resolvePasteReadOptions>;\n try {\n resolved = resolvePasteReadOptions(current);\n } catch (cause) {\n // Transition straight to `error` without a ghost `reading` frame.\n // `run()` would momentarily set state to `reading` before resolving the\n // error, which observers would see as a spurious state transition.\n const error = toCopyError(cause, 'read');\n ++generation;\n const superseded = operations.abort();\n clearResetTimer();\n settleError(error, source, 0);\n if (superseded) invoke(current.onCancel, 'superseded');\n return Promise.resolve({ status: 'error', error });\n }\n\n // DataTransfer is only readable during dispatch: snapshot before anything async.\n const entries = snapshotDataTransfer(data, resolved);\n if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);\n if (source === 'event' && current.preventDefault !== false) event.preventDefault();\n\n return run(\n () => {\n enforcePasteLimits(entries, resolved);\n return finalizePaste(entries, source, resolved);\n },\n source,\n 0,\n );\n };\n\n const pasteEvent = (event: PasteEventLike): Promise<PasteOutcome> => transfer(event.clipboardData, event, 'event');\n const dropEvent = (event: PasteDropEventLike): Promise<PasteOutcome> => transfer(event.dataTransfer, event, 'drop');\n\n const reset = (): void => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n const wasIdle = state.status === 'idle';\n setState(PASTE_IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'reset');\n if (!wasIdle) invoke(read().onReset);\n };\n\n const connect = (): (() => void) => {\n if (state.status === 'read') scheduleReset(state);\n return () => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n if (state.status === 'reading') setState(PASTE_IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'disconnect');\n };\n };\n\n return {\n getSnapshot: () => state,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n paste,\n pasteEvent,\n dropEvent,\n retry,\n reset,\n connect,\n };\n}\n","import { createContext, useContext, useState, type ReactNode } from 'react';\nimport { createCopyCoordinator, type CopyCoordinator } from '../core/copy-coordinator';\n\nconst CopyGroupContext = /* @__PURE__ */ createContext<CopyCoordinator | null>(null);\n\nexport interface CopyGroupProps {\n readonly children?: ReactNode;\n /**\n * Share a coordinator with code outside this tree (another root, a vanilla\n * `createCopyMachine`). Defaults to one owned by this group.\n */\n readonly coordinator?: CopyCoordinator;\n}\n\n/**\n * Every `useCopy` / `<CopyField.Root>` inside behaves like one clipboard:\n * a new successful copy returns the previously \"Copied\" one to idle.\n * Opt a single field out with `copyOptions={{ coordinator: null }}`. Groups nest; the nearest wins.\n */\nexport function CopyGroup({ children, coordinator }: CopyGroupProps) {\n const [owned] = useState(createCopyCoordinator);\n return <CopyGroupContext.Provider value={coordinator ?? owned}>{children}</CopyGroupContext.Provider>;\n}\n\n/** The nearest `<CopyGroup>`'s coordinator, or `null` outside any group. */\nexport function useCopyGroup(): CopyCoordinator | null {\n return useContext(CopyGroupContext);\n}\n","import { useEffect, useLayoutEffect, type Ref, type RefCallback } from 'react';\n\n/** `useLayoutEffect` in the browser, `useEffect` on the server (no SSR warning). */\nexport const useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;\n\nexport function mergeRefs<T>(...refs: ReadonlyArray<Ref<T> | undefined>): RefCallback<T> {\n return (node) => {\n for (const ref of refs) {\n if (typeof ref === 'function') ref(node);\n else if (ref) (ref as { current: T | null }).current = node;\n }\n };\n}\n\n/** Runs the consumer's handler first; ours is skipped if they call `preventDefault()`. */\nexport function composeEventHandlers<E extends { readonly defaultPrevented: boolean }>(\n theirs: ((event: E) => void) | undefined,\n ours: (event: E) => void,\n): (event: E) => void {\n return (event) => {\n theirs?.(event);\n if (!event.defaultPrevented) ours(event);\n };\n}\n","import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport {\n IDLE_STATE,\n canRetryState,\n createCopyMachine,\n type CopyMachine,\n type CopyMachineOptions,\n type CopyState,\n type CopyStatus,\n} from '../core/copy-machine';\nimport type { CopyCoordinator } from '../core/copy-coordinator';\nimport type { CopyError } from '../core/errors';\nimport { useCopyGroup } from './CopyGroup';\nimport { useIsomorphicLayoutEffect } from './utils';\n\nexport type UseCopyOptions = CopyMachineOptions;\n\nexport interface UseCopyResult {\n /** Full discriminated state; narrow on `state.status`. */\n readonly state: CopyState;\n readonly status: CopyStatus;\n readonly error: CopyError | null;\n /** Whether `retry()` can do anything right now. */\n readonly canRetry: boolean;\n /** Stable identity. Never rejects; resolves to a `CopyOutcome`. */\n readonly copy: CopyMachine['copy'];\n /** Stable identity. Re-attempts the last failed payload, up to `maxRetries`. */\n readonly retry: CopyMachine['retry'];\n /** Stable identity. Back to `idle`, discarding and aborting any in-flight copy. */\n readonly reset: CopyMachine['reset'];\n}\n\nconst getServerSnapshot = (): CopyState => IDLE_STATE;\n\n/** An explicit `coordinator` (including `null`) wins over the surrounding `<CopyGroup>`. */\nfunction withGroup(options: UseCopyOptions, group: CopyCoordinator | null): UseCopyOptions {\n return options.coordinator !== undefined || group === null ? options : { ...options, coordinator: group };\n}\n\n/**\n * Copy state machine bound to a component. Options may change on every render\n * (inline callbacks are fine); the latest ones are always used.\n */\nexport function useCopy(options: UseCopyOptions = {}): UseCopyResult {\n const effective = withGroup(options, useCopyGroup());\n const optionsRef = useRef(effective);\n useIsomorphicLayoutEffect(() => {\n optionsRef.current = effective;\n });\n\n const [machine] = useState(() => createCopyMachine(() => optionsRef.current));\n useEffect(() => machine.connect(), [machine]);\n\n const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot);\n const canRetry = canRetryState(state, effective.maxRetries);\n\n return useMemo(\n () => ({\n state,\n status: state.status,\n error: state.status === 'error' ? state.error : null,\n canRetry,\n copy: machine.copy,\n retry: machine.retry,\n reset: machine.reset,\n }),\n [state, canRetry, machine],\n );\n}\n","import { useEffect, useRef, useState, type RefCallback } from 'react';\nimport { registerCopyInterceptor, type CopyInterceptorOptions } from '../core/copy-interceptor';\nimport { useIsomorphicLayoutEffect } from './utils';\n\nexport interface UseCopyInterceptorOptions extends CopyInterceptorOptions {\n /** Set `false` to stop intercepting without unmounting. Default `true`. */\n readonly enabled?: boolean;\n}\n\nexport interface UseCopyInterceptorResult<T extends Element> {\n /** Attach to the element whose content you want to control. */\n readonly ref: RefCallback<T>;\n}\n\n/**\n * Rewrites, redacts or blocks native copies (Ctrl/Cmd+C, context menu) and\n * cuts whose selection touches the referenced element.\n *\n * ```tsx\n * const { ref } = useCopyInterceptor<HTMLElement>({\n * transform: ({ text }) => `${text}\\n\\nSource: ${location.href}`,\n * });\n * return <article ref={ref}>…</article>;\n * ```\n *\n * The transform runs synchronously inside the event and always sees the\n * latest props; changing it never re-subscribes. SSR-safe.\n */\nexport function useCopyInterceptor<T extends Element = HTMLElement>(\n options: UseCopyInterceptorOptions,\n): UseCopyInterceptorResult<T> {\n const optionsRef = useRef(options);\n useIsomorphicLayoutEffect(() => {\n optionsRef.current = options;\n });\n\n const [node, setNode] = useState<T | null>(null);\n const enabled = options.enabled !== false;\n\n useEffect(() => {\n if (!node || !enabled) return undefined;\n return registerCopyInterceptor(node, () => optionsRef.current);\n }, [node, enabled]);\n\n return { ref: setNode };\n}\n","import { useCallback, useRef, useSyncExternalStore } from 'react';\n\nconst getServerSnapshot = (): boolean => false;\n\n/** SSR-safe media query subscription. Server and hydration render `false`. */\nexport function useMediaQuery(query: string): boolean {\n // Cache the MediaQueryList so `subscribe` always attaches to the same\n // object. We call `matchMedia()` once per query string (per mount / query\n // change) and hold the reference for the duration. The `.matches` accessor\n // on the real MediaQueryList is live, so `getSnapshot` reads the current\n // value without re-calling `matchMedia()` on every render.\n const listRef = useRef<MediaQueryList | null>(null);\n const queryRef = useRef<string>('');\n\n const getList = useCallback((): MediaQueryList | null => {\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return null;\n // Invalidate the cache when the query string changes.\n if (listRef.current === null || queryRef.current !== query) {\n listRef.current = window.matchMedia(query);\n queryRef.current = query;\n }\n return listRef.current;\n }, [query]);\n\n const subscribe = useCallback(\n (onChange: () => void) => {\n const list = getList();\n if (!list) return () => undefined;\n list.addEventListener('change', onChange);\n return () => {\n list.removeEventListener('change', onChange);\n };\n },\n [getList],\n );\n\n const getSnapshot = useCallback(() => getList()?.matches ?? false, [getList]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n","import {\n useEffect,\n useMemo,\n useRef,\n useState,\n type FocusEventHandler,\n type PointerEventHandler,\n type RefCallback,\n} from 'react';\nimport { useMediaQuery } from './useMediaQuery';\n\n/** Why the target is currently revealed, in priority order. */\nexport type RevealReason = 'forced' | 'focus' | 'hover' | 'touch' | 'no-hover-device';\n\nexport interface UseRevealOnInteractionOptions {\n /** Always reveal (e.g. a \"show actions\" user setting). */\n readonly alwaysVisible?: boolean;\n}\n\nexport interface RevealTargetProps<T extends HTMLElement> {\n readonly ref: RefCallback<T>;\n readonly onPointerEnter: PointerEventHandler<T>;\n readonly onPointerLeave: PointerEventHandler<T>;\n readonly onPointerDown: PointerEventHandler<T>;\n readonly onFocus: FocusEventHandler<T>;\n readonly onBlur: FocusEventHandler<T>;\n}\n\nexport interface UseRevealOnInteractionResult<T extends HTMLElement> {\n readonly visible: boolean;\n readonly reason: RevealReason | null;\n /** Spread onto the container that owns the hidden actions. */\n readonly targetProps: RevealTargetProps<T>;\n}\n\nfunction isFocusVisible(element: EventTarget): boolean {\n if (!(element instanceof Element)) return true;\n try {\n return element.matches(':focus-visible');\n } catch {\n return true; // Engines without :focus-visible: reveal on any focus, the accessible default.\n }\n}\n\n/**\n * Reveals secondary actions on hover, keyboard focus and touch, and always on\n * devices that cannot hover. Hover and focus are tracked independently, so a\n * touchscreen laptop never gets stuck in a \"touch only\" mode.\n *\n * Keep the actions in the DOM and in the tab order; hide them visually with\n * CSS keyed off `visible` (or `data-revealed`), never with `display: none`.\n */\nexport function useRevealOnInteraction<T extends HTMLElement = HTMLElement>(\n options: UseRevealOnInteractionOptions = {},\n): UseRevealOnInteractionResult<T> {\n const [hovered, setHovered] = useState(false);\n const [focused, setFocused] = useState(false);\n const [touched, setTouched] = useState(false);\n const cannotHover = useMediaQuery('(hover: none)');\n const nodeRef = useRef<T | null>(null);\n\n // A touch reveal lasts until the user touches somewhere else.\n useEffect(() => {\n if (!touched) return undefined;\n const dismiss = (event: PointerEvent): void => {\n const node = nodeRef.current;\n if (node && event.target instanceof Node && node.contains(event.target)) return;\n setTouched(false);\n };\n document.addEventListener('pointerdown', dismiss, true);\n return () => {\n document.removeEventListener('pointerdown', dismiss, true);\n };\n }, [touched]);\n\n const targetProps = useMemo<RevealTargetProps<T>>(\n () => ({\n ref: (node) => {\n nodeRef.current = node;\n },\n onPointerEnter: (event) => {\n if (event.pointerType !== 'touch') setHovered(true);\n },\n onPointerLeave: (event) => {\n if (event.pointerType !== 'touch') setHovered(false);\n },\n onPointerDown: (event) => {\n if (event.pointerType === 'touch') setTouched(true);\n },\n onFocus: (event) => {\n // Mouse clicks focus buttons too; only keyboard-style focus should pin the reveal.\n setFocused(isFocusVisible(event.target));\n },\n onBlur: (event) => {\n const next = event.relatedTarget;\n if (next instanceof Node && event.currentTarget.contains(next)) return;\n setFocused(false);\n },\n }),\n [],\n );\n\n const reason: RevealReason | null = options.alwaysVisible\n ? 'forced'\n : focused\n ? 'focus'\n : hovered\n ? 'hover'\n : touched\n ? 'touch'\n : cannotHover\n ? 'no-hover-device'\n : null;\n\n return { visible: reason !== null, reason, targetProps };\n}\n","import { useEffect, useState } from 'react';\nimport type { CopyStatus } from '../core/copy-machine';\nimport { useIsomorphicLayoutEffect } from './utils';\n\nexport const DEFAULT_PENDING_DELAY_MS = 150;\nexport const DEFAULT_MIN_PENDING_MS = 400;\n\nexport interface UseDisplayStatusOptions {\n /** Only show `copying` if the copy takes longer than this. Default 150 ms. */\n readonly pendingDelayMs?: number;\n /** Once `copying` is shown, keep it visible at least this long. Default 400 ms. */\n readonly minPendingMs?: number;\n}\n\ntype SettledStatus = Exclude<CopyStatus, 'copying'>;\n\n/**\n * Presentation-only view of a copy status that never flickers.\n *\n * The real `status` is honest and can be `copying` for a single frame (text\n * copies take ~1-5 ms). Rendering that directly flashes a \"Copying…\" label.\n * This hook keeps showing the previous state during fast copies, and when a\n * copy is genuinely slow it shows `copying` for a minimum time instead of a blink.\n *\n * It never changes the state machine: use `status` for logic, this for pixels.\n */\nexport function useDisplayStatus(status: CopyStatus, options: UseDisplayStatusOptions = {}): CopyStatus {\n const pendingDelayMs = Math.max(0, options.pendingDelayMs ?? DEFAULT_PENDING_DELAY_MS);\n const minPendingMs = Math.max(0, options.minPendingMs ?? DEFAULT_MIN_PENDING_MS);\n\n // Last non-copying status, shown while a fast copy is in flight. It is only read\n // while `copying`, so it is synced in a layout effect: never with a render-phase\n // setState, which on React 18 corrupts `useSyncExternalStore`'s snapshot tracking\n // and left CopyField stuck on \"Copied\" after a fast copy.\n const [settled, setSettled] = useState<SettledStatus>(status === 'copying' ? 'idle' : status);\n useIsomorphicLayoutEffect(() => {\n if (status !== 'copying') setSettled(status);\n }, [status]);\n\n // When the pending indicator became visible, or null while it is hidden.\n const [pendingShownAt, setPendingShownAt] = useState<number | null>(null);\n\n useEffect(() => {\n if (status !== 'copying') return undefined;\n const timer = setTimeout(() => {\n setPendingShownAt(Date.now());\n }, pendingDelayMs);\n return () => {\n clearTimeout(timer);\n };\n }, [status, pendingDelayMs]);\n\n useEffect(() => {\n if (status === 'copying' || pendingShownAt === null) return undefined;\n const remaining = Math.max(0, minPendingMs - (Date.now() - pendingShownAt));\n const timer = setTimeout(() => {\n setPendingShownAt(null);\n }, remaining);\n return () => {\n clearTimeout(timer);\n };\n }, [status, pendingShownAt, minPendingMs]);\n\n if (pendingShownAt !== null) return 'copying';\n return status === 'copying' ? settled : status;\n}\n","import { useEffect, useRef, type CSSProperties, type HTMLAttributes } from 'react';\n\n/** Hides content visually while keeping it available to assistive technology. */\nexport const visuallyHiddenStyle: CSSProperties = {\n position: 'absolute',\n width: 1,\n height: 1,\n padding: 0,\n margin: -1,\n overflow: 'hidden',\n clip: 'rect(0, 0, 0, 0)',\n whiteSpace: 'nowrap',\n border: 0,\n};\n\nexport interface LiveRegionProps\n extends Omit<HTMLAttributes<HTMLSpanElement>, 'children' | 'role' | 'aria-live' | 'aria-atomic'> {\n /** Changing this text is what triggers the announcement. Empty string = silent. */\n readonly message: string;\n readonly politeness?: 'polite' | 'assertive';\n readonly visuallyHidden?: boolean;\n}\n\n/**\n * Always-mounted announcer. Screen readers ignore regions that are inserted\n * together with their content, so this must render before the first message.\n *\n * **Mount safety**: the live region is intentionally empty on mount. We write\n * the message into the DOM imperatively (via a ref) only after the element has\n * been live for at least one browser paint. This prevents SSR hydration and\n * strict-mode double-mount from producing a spurious announcement on some\n * screen readers (JAWS / NVDA observe the initial DOM during hydration and\n * re-read regions that already have text content).\n *\n * **WCAG 4.1.3 / ARIA spec**: we use `role=\"status\"` with explicit `aria-live`\n * rather than `role=\"alert\"`. `role=\"alert\"` interrupts any sentence being\n * spoken even in polite mode, which is inappropriate for copy feedback.\n * `role=\"status\"` + `aria-live` is correct for both politeness levels.\n */\nexport function LiveRegion({\n message,\n politeness = 'polite',\n visuallyHidden = true,\n style,\n ...rest\n}: LiveRegionProps) {\n const spanRef = useRef<HTMLSpanElement>(null);\n const mountedRef = useRef(false);\n\n useEffect(() => {\n mountedRef.current = true;\n }, []);\n\n useEffect(() => {\n const span = spanRef.current;\n /* c8 ignore next -- spanRef.current is always set by mount; guard for unmounted edge case */\n if (!span) return;\n // Delay the first write by one tick so the live region is registered with\n // the AT before any content lands in it. Subsequent updates are immediate.\n /* c8 ignore next -- jsdom effects run synchronously so mountedRef.current is always true here; this guard only fires in real browsers during the initial paint */\n if (!mountedRef.current) return;\n span.textContent = message;\n }, [message]);\n\n return (\n <span\n {...rest}\n ref={spanRef}\n role=\"status\"\n aria-live={politeness}\n aria-atomic=\"true\"\n style={visuallyHidden ? { ...visuallyHiddenStyle, ...style } : style}\n />\n );\n}\n","import { useMediaQuery } from './useMediaQuery';\n\n/**\n * Default trigger label shared by `CopyField` and `PasteField`: every state's\n * text is stacked in one grid cell, so the button is always as wide as its\n * longest label and never resizes (no layout shift). Only the active label is\n * visible and exposed to assistive tech; the crossfade is skipped when the\n * user prefers reduced motion.\n */\nexport function TriggerLabel<S extends string>({\n status,\n labels,\n}: {\n readonly status: S;\n readonly labels: Readonly<Record<S, string>>;\n}) {\n const reduceMotion = useMediaQuery('(prefers-reduced-motion: reduce)');\n return (\n <span style={{ display: 'inline-grid' }}>\n {(Object.keys(labels) as S[]).map((candidate) => {\n const active = candidate === status;\n return (\n <span\n key={candidate}\n data-trigger-label={candidate}\n data-active={active ? '' : undefined}\n aria-hidden={!active || undefined}\n style={{\n gridArea: '1 / 1',\n opacity: active ? 1 : 0,\n visibility: active ? 'visible' : 'hidden',\n ...(reduceMotion ? {} : { transition: 'opacity 150ms ease, visibility 150ms' }),\n }}\n >\n {labels[candidate]}\n </span>\n );\n })}\n </span>\n );\n}\n","import {\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useId,\n useMemo,\n type ButtonHTMLAttributes,\n type HTMLAttributes,\n type ReactNode,\n} from 'react';\nimport type { CopyOutcome, CopyState, CopyStatus } from '../core/copy-machine';\nimport { describeCopyError, type CopyError } from '../core/errors';\nimport type { CopySource } from '../core/payload';\nimport { LiveRegion } from './LiveRegion';\nimport { TriggerLabel } from './TriggerLabel';\nimport { useDisplayStatus, type UseDisplayStatusOptions } from './useDisplayStatus';\nimport { useCopy, type UseCopyOptions, type UseCopyResult } from './useCopy';\nimport { useRevealOnInteraction, type RevealReason } from './useRevealOnInteraction';\nimport { composeEventHandlers, mergeRefs } from './utils';\n\nexport interface CopyFieldMessages {\n /** Announced to screen readers on success. */\n readonly copied: string;\n /** Announced on failure. Defaults to {@link describeCopyError}. */\n readonly error: (error: CopyError) => string;\n /**\n * Accessible name of the trigger button. Receives the field's `label` prop.\n * The returned string must not be empty.\n */\n readonly triggerLabel: (label: string) => string;\n}\n\nexport const defaultCopyFieldMessages: CopyFieldMessages = {\n copied: 'Copied to clipboard',\n error: describeCopyError,\n triggerLabel: (label) => `Copy ${label}`,\n};\n\nexport interface CopyFieldContextValue extends UseCopyResult {\n readonly label: string;\n readonly labelId: string;\n readonly valueId: string;\n readonly revealed: boolean;\n readonly revealReason: RevealReason | null;\n readonly messages: CopyFieldMessages;\n /** Text shown by `<CopyField.Value>` when the value is plain text; otherwise `null`. */\n readonly displayValue: string | null;\n /** Flicker-free status for rendering. Use `status` for logic, this for pixels. */\n readonly displayStatus: CopyStatus;\n /** Copies the field's current value. */\n readonly copyValue: () => Promise<CopyOutcome>;\n}\n\nconst CopyFieldContext = /* @__PURE__ */ createContext<CopyFieldContextValue | null>(null);\n\n/** Access field state to build custom parts. Must be used inside `<CopyField.Root>`. */\nexport function useCopyField(): CopyFieldContextValue {\n const context = useContext(CopyFieldContext);\n if (!context) throw new Error('useCopyField() must be used inside <CopyField.Root>.');\n return context;\n}\n\n/** Maps non-text payload kinds to a human-readable description for screen readers. */\nconst KIND_LABELS: Readonly<Record<string, string>> = /* @__PURE__ */ Object.freeze(\n Object.assign(Object.create(null) as Record<string, string>, {\n html: 'Rich text',\n image: 'Image',\n json: 'JSON data',\n multi: 'Mixed content',\n }),\n);\n\n/**\n * Returns the value's text representation when it is plain text, or a\n * descriptive fallback for non-text payloads so screen-reader users understand\n * what will be copied (A1: `CopyField.Value` must never be silent).\n */\nfunction getDisplayValue(value: CopySource): string | null {\n if (typeof value === 'string') return value;\n if (typeof value === 'function') return null; // dynamic: no stable preview\n if (value.kind === 'text') return value.value;\n return KIND_LABELS[value.kind] ?? null;\n}\n\n/* ------------------------------------------------------------------ Root */\n\nexport interface CopyFieldRootProps\n extends Omit<HTMLAttributes<HTMLDivElement>, 'onCopy' | 'onError'>,\n UseDisplayStatusOptions {\n /** What to copy. Pass a function to read the latest value at click time. */\n readonly value: CopySource;\n /** Human label, used for the trigger's accessible name (\"Copy Email\"). */\n readonly label: string;\n readonly copyOptions?: UseCopyOptions;\n readonly messages?: Partial<CopyFieldMessages>;\n /** Skip hover/focus reveal and always show the trigger. */\n readonly alwaysVisible?: boolean;\n /** Render the built-in live region. Disable if your app has a global announcer. Default `true`. */\n readonly announce?: boolean;\n}\n\nconst Root = /* @__PURE__ */ forwardRef<HTMLDivElement, CopyFieldRootProps>(function CopyFieldRoot(\n {\n value,\n label,\n copyOptions,\n messages: messageOverrides,\n alwaysVisible = false,\n announce = true,\n pendingDelayMs,\n minPendingMs,\n children,\n onPointerEnter,\n onPointerLeave,\n onPointerDown,\n onFocus,\n onBlur,\n ...rest\n },\n forwardedRef,\n) {\n const copyState = useCopy(copyOptions);\n const displayStatus = useDisplayStatus(copyState.status, {\n ...(pendingDelayMs === undefined ? {} : { pendingDelayMs }),\n ...(minPendingMs === undefined ? {} : { minPendingMs }),\n });\n const reveal = useRevealOnInteraction<HTMLDivElement>({ alwaysVisible });\n const baseId = useId();\n const labelId = `${baseId}-label`;\n const valueId = `${baseId}-value`;\n\n const messages = useMemo<CopyFieldMessages>(\n () => ({ ...defaultCopyFieldMessages, ...messageOverrides }),\n [messageOverrides],\n );\n\n const { copy } = copyState;\n const copyValue = useCallback(() => copy(value), [copy, value]);\n const { targetProps } = reveal;\n const ref = useMemo(() => mergeRefs(targetProps.ref, forwardedRef), [targetProps.ref, forwardedRef]);\n\n const context = useMemo<CopyFieldContextValue>(\n () => ({\n ...copyState,\n label,\n labelId,\n valueId,\n revealed: reveal.visible,\n revealReason: reveal.reason,\n messages,\n displayValue: getDisplayValue(value),\n displayStatus,\n copyValue,\n }),\n [copyState, label, labelId, valueId, reveal.visible, reveal.reason, messages, value, displayStatus, copyValue],\n );\n\n const { state } = copyState;\n const announcement =\n state.status === 'copied' ? messages.copied : state.status === 'error' ? messages.error(state.error) : '';\n\n return (\n <CopyFieldContext.Provider value={context}>\n <div\n {...rest}\n ref={ref}\n data-state={state.status}\n data-display-state={displayStatus}\n data-revealed={reveal.visible ? '' : undefined}\n onPointerEnter={composeEventHandlers(onPointerEnter, targetProps.onPointerEnter)}\n onPointerLeave={composeEventHandlers(onPointerLeave, targetProps.onPointerLeave)}\n onPointerDown={composeEventHandlers(onPointerDown, targetProps.onPointerDown)}\n onFocus={composeEventHandlers(onFocus, targetProps.onFocus)}\n onBlur={composeEventHandlers(onBlur, targetProps.onBlur)}\n >\n {children}\n {announce ? <LiveRegion message={announcement} /> : null}\n </div>\n </CopyFieldContext.Provider>\n );\n});\n\n/* ----------------------------------------------------------- Label/Value */\n\nexport type CopyFieldLabelProps = HTMLAttributes<HTMLSpanElement>;\n\nconst Label = /* @__PURE__ */ forwardRef<HTMLSpanElement, CopyFieldLabelProps>(function CopyFieldLabel(\n { children, ...rest },\n ref,\n) {\n const field = useCopyField();\n return (\n <span {...rest} ref={ref} id={field.labelId}>\n {children ?? field.label}\n </span>\n );\n});\n\nexport type CopyFieldValueProps = HTMLAttributes<HTMLSpanElement>;\n\nconst Value = /* @__PURE__ */ forwardRef<HTMLSpanElement, CopyFieldValueProps>(function CopyFieldValue(\n { children, ...rest },\n ref,\n) {\n const field = useCopyField();\n return (\n <span {...rest} ref={ref} id={field.valueId}>\n {children ?? field.displayValue}\n </span>\n );\n});\n\n/* --------------------------------------------------------------- Trigger */\n\nexport interface CopyFieldTriggerRenderProps {\n /** The real state. Use for logic. */\n readonly status: CopyStatus;\n /** Flicker-free state. Use for what you render. */\n readonly displayStatus: CopyStatus;\n readonly state: CopyState;\n readonly revealed: boolean;\n readonly canRetry: boolean;\n}\n\nexport interface CopyFieldTriggerProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'type'> {\n /** Static content, or a render function receiving the live state (icons, labels, spinners). */\n readonly children?: ReactNode | ((props: CopyFieldTriggerRenderProps) => ReactNode);\n}\n\nconst DEFAULT_TRIGGER_TEXT: Readonly<Record<CopyStatus, string>> = {\n idle: 'Copy',\n copying: 'Copying…',\n copied: 'Copied',\n error: 'Retry',\n};\n\nconst Trigger = /* @__PURE__ */ forwardRef<HTMLButtonElement, CopyFieldTriggerProps>(function CopyFieldTrigger(\n { children, onClick, 'aria-label': ariaLabel, ...rest },\n ref,\n) {\n const field = useCopyField();\n const renderProps: CopyFieldTriggerRenderProps = {\n status: field.status,\n displayStatus: field.displayStatus,\n state: field.state,\n revealed: field.revealed,\n canRetry: field.canRetry,\n };\n\n // Guard: `triggerLabel` must return a non-empty string; \"Copy undefined\" is\n // not a valid accessible name (happens when the consumer omits `label`).\n const safeAriaLabel =\n (ariaLabel ?? field.messages.triggerLabel(field.label)) || defaultCopyFieldMessages.triggerLabel(field.label);\n\n return (\n <button\n {...rest}\n ref={ref}\n // Never `disabled` while copying: disabling a focused button drops keyboard focus.\n type=\"button\"\n aria-label={safeAriaLabel}\n aria-busy={field.status === 'copying' ? true : undefined}\n data-state={field.status}\n data-display-state={field.displayStatus}\n data-revealed={field.revealed ? '' : undefined}\n onClick={composeEventHandlers(onClick, () => {\n void field.copyValue();\n })}\n >\n {typeof children === 'function'\n ? children(renderProps)\n : (children ?? <TriggerLabel status={field.displayStatus} labels={DEFAULT_TRIGGER_TEXT} />)}\n </button>\n );\n});\n\n/**\n * Headless compound component for a labelled, copyable value.\n *\n * Styling hooks on Root and Trigger:\n * - `data-display-state=\"idle|copying|copied|error\"`: flicker-free, style with this\n * - `data-state`: the real, instantaneous state, for logic and tests\n * - `data-revealed`: present while the trigger should be visible\n */\nexport const CopyField = { Root, Label, Value, Trigger } as const;\n","import {\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n type ClipboardEventHandler,\n type DragEventHandler,\n} from 'react';\nimport type { CopyError } from '../core/errors';\nimport {\n PASTE_IDLE_STATE,\n canRetryPasteState,\n createPasteMachine,\n type PasteMachine,\n type PasteMachineOptions,\n type PasteState,\n type PasteStatus,\n} from '../core/paste-machine';\nimport { canAcceptDrag, resolvePasteReadOptions, type DataTransferLike, type PasteResult } from '../core/paste-reader';\nimport { useIsomorphicLayoutEffect } from './utils';\n\nexport interface UsePasteOptions extends PasteMachineOptions {\n /**\n * Also handle Ctrl/⌘+V anywhere on the page (chat-style \"paste a screenshot\").\n * Events an element already handled (`defaultPrevented`) are skipped. Default `false`.\n */\n readonly listenOnDocument?: boolean;\n}\n\nexport interface PasteTargetProps<T extends Element> {\n readonly onPaste: ClipboardEventHandler<T>;\n}\n\nexport interface PasteDropTargetProps<T extends Element> {\n readonly onDragEnter: DragEventHandler<T>;\n readonly onDragOver: DragEventHandler<T>;\n readonly onDragLeave: DragEventHandler<T>;\n readonly onDrop: DragEventHandler<T>;\n}\n\nexport interface UsePasteResult<T extends Element = HTMLElement> {\n /** Full discriminated state; narrow on `state.status`. */\n readonly state: PasteState;\n readonly status: PasteStatus;\n /** The latest result while `status === 'read'`, otherwise `null`. */\n readonly result: PasteResult | null;\n readonly error: CopyError | null;\n /** Whether `retry()` can do anything right now. */\n readonly canRetry: boolean;\n /** Stable identity. Reads the clipboard from a user gesture. Never rejects. */\n readonly paste: PasteMachine['paste'];\n /** Stable identity. Handles a paste event you received yourself. Never rejects. */\n readonly pasteEvent: PasteMachine['pasteEvent'];\n /** Stable identity. Handles a drop event you received yourself. Never rejects. */\n readonly dropEvent: PasteMachine['dropEvent'];\n /** Stable identity. Re-reads the clipboard after a retryable failure, up to `maxRetries`. */\n readonly retry: PasteMachine['retry'];\n /** Stable identity. Back to `idle`, discarding and aborting any in-flight read. */\n readonly reset: PasteMachine['reset'];\n /** Spread onto an element (drop zone, textarea, editor) to accept Ctrl/⌘+V there. */\n readonly targetProps: PasteTargetProps<T>;\n /**\n * Spread onto one element to accept drag-and-drop there, through the same\n * `accept` and limits as paste. Only drags carrying accepted types show the\n * drop cursor. Separate from `targetProps` so text fields keep native drops.\n */\n readonly dropTargetProps: PasteDropTargetProps<T>;\n /** An accepted drag is over the `dropTargetProps` element. Style the drop zone with it. */\n readonly isDragOver: boolean;\n}\n\nconst getServerSnapshot = (): PasteState => PASTE_IDLE_STATE;\n\nconst DRAG_END_EVENTS = ['drop', 'dragend'] as const;\n\n/** A text field or editable region nested inside the drop target, which should keep its native drop. */\nconst isNestedEditable = (event: { readonly target: EventTarget; readonly currentTarget: EventTarget }): boolean => {\n const { target, currentTarget } = event;\n if (target === currentTarget || !(target instanceof HTMLElement)) return false;\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') return true;\n // Inside an editable drop target every child is editable too: those drops are still ours to check.\n return target.isContentEditable && !(currentTarget instanceof HTMLElement && currentTarget.isContentEditable);\n};\n\n/** The drop effect the drag source allows, preferring copy: an effect it disallows cancels the drop. */\nconst dropEffectFor = (allowed: string): DataTransfer['dropEffect'] =>\n /^(all|uninitialized|copy)/.test(allowed) ? 'copy' : /move/i.test(allowed) ? 'move' : allowed === 'link' ? 'link' : 'none';\n\n/**\n * Paste state machine bound to a component. Supports a \"Paste\" button\n * (`paste()`, may prompt for permission), keyboard paste (`targetProps` or\n * `listenOnDocument`, no prompt) and drag-and-drop (`dropTargetProps`).\n * Options may change on every render.\n *\n * Everything in the result is untrusted user input.\n */\nexport function usePaste<T extends Element = HTMLElement>(options: UsePasteOptions = {}): UsePasteResult<T> {\n const optionsRef = useRef(options);\n useIsomorphicLayoutEffect(() => {\n optionsRef.current = options;\n });\n\n const [machine] = useState(() => createPasteMachine(() => optionsRef.current));\n useEffect(() => machine.connect(), [machine]);\n\n const listenOnDocument = options.listenOnDocument === true;\n useEffect(() => {\n if (!listenOnDocument) return undefined;\n const onPaste = (event: ClipboardEvent): void => {\n if (!event.defaultPrevented) void machine.pasteEvent(event);\n };\n document.addEventListener('paste', onPaste);\n return () => {\n document.removeEventListener('paste', onPaste);\n };\n }, [listenOnDocument, machine]);\n\n const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot);\n const canRetry = canRetryPasteState(state, options.maxRetries);\n\n const targetProps = useMemo<PasteTargetProps<T>>(\n () => ({\n onPaste: (event) => {\n void machine.pasteEvent(event);\n },\n }),\n [machine],\n );\n\n const [isDragOver, setIsDragOver] = useState(false);\n // dragenter/dragleave also fire for every child crossed; count them so moving inside doesn't flicker.\n const dragDepth = useRef(0);\n const [endDrag] = useState(() => (): void => {\n dragDepth.current = 0;\n setIsDragOver(false);\n });\n const dropTargetProps = useMemo<PasteDropTargetProps<T>>(() => {\n const accepts = (data: DataTransferLike): boolean => {\n try {\n return canAcceptDrag(data, resolvePasteReadOptions(optionsRef.current));\n } catch {\n return true; // Invalid options: let the drop through so it reports `invalid-payload`.\n }\n };\n return {\n onDragEnter: (event) => {\n dragDepth.current += 1;\n if (accepts(event.dataTransfer)) setIsDragOver(true);\n },\n onDragOver: (event) => {\n if (isNestedEditable(event)) return; // A field inside the target keeps its native drop.\n // Always claimed: otherwise a rejected file would be opened in place of the page.\n // `dropEffect: 'none'` then cancels the drop instead.\n event.preventDefault();\n event.dataTransfer.dropEffect = accepts(event.dataTransfer)\n ? dropEffectFor(event.dataTransfer.effectAllowed)\n : 'none';\n },\n onDragLeave: (event) => {\n const next = event.relatedTarget;\n dragDepth.current -= 1;\n // `relatedTarget` (where supported) catches a count left high by a child removed mid-drag.\n if (dragDepth.current <= 0 || (next instanceof Node && !event.currentTarget.contains(next))) endDrag();\n },\n onDrop: (event) => {\n endDrag();\n if (!isNestedEditable(event)) void machine.dropEvent(event);\n },\n };\n }, [machine, endDrag]);\n\n // A drop handled elsewhere (a consumer `onDrop` that took over, a child that\n // stopped propagation) or a cancelled drag never reaches `onDrop` / `onDragLeave`.\n useEffect(() => {\n if (!isDragOver) return undefined;\n for (const type of DRAG_END_EVENTS) window.addEventListener(type, endDrag, true);\n return () => {\n for (const type of DRAG_END_EVENTS) window.removeEventListener(type, endDrag, true);\n };\n }, [isDragOver, endDrag]);\n\n return useMemo(\n () => ({\n state,\n status: state.status,\n result: state.status === 'read' ? state.result : null,\n error: state.status === 'error' ? state.error : null,\n canRetry,\n paste: machine.paste,\n pasteEvent: machine.pasteEvent,\n dropEvent: machine.dropEvent,\n retry: machine.retry,\n reset: machine.reset,\n targetProps,\n dropTargetProps,\n isDragOver,\n }),\n [state, canRetry, machine, targetProps, dropTargetProps, isDragOver],\n );\n}\n","import { useEffect, useState } from 'react';\nimport type { PasteStatus } from '../core/paste-machine';\nimport { useIsomorphicLayoutEffect } from './utils';\n\nexport const DEFAULT_PASTE_PENDING_DELAY_MS = 150;\nexport const DEFAULT_PASTE_MIN_PENDING_MS = 400;\n\nexport interface UsePasteDisplayStatusOptions {\n /** Only show `reading` if the paste takes longer than this. Default 150 ms. */\n readonly pendingDelayMs?: number;\n /** Once `reading` is shown, keep it visible at least this long. Default 400 ms. */\n readonly minPendingMs?: number;\n}\n\ntype SettledPasteStatus = Exclude<PasteStatus, 'reading'>;\n\n/**\n * Presentation-only view of a paste status that never flickers.\n *\n * The real `status` is honest and can be `reading` for a single render frame\n * (plain-text reads take ~1-5 ms). Rendering that directly flashes a \"Reading…\"\n * label. This hook keeps showing the previous settled status during fast pastes,\n * and when a paste is genuinely slow it shows `reading` for a minimum time\n * instead of a blink.\n *\n * It never changes the state machine: use `status` for logic, this for pixels.\n */\nexport function usePasteDisplayStatus(status: PasteStatus, options: UsePasteDisplayStatusOptions = {}): PasteStatus {\n const pendingDelayMs = Math.max(0, options.pendingDelayMs ?? DEFAULT_PASTE_PENDING_DELAY_MS);\n const minPendingMs = Math.max(0, options.minPendingMs ?? DEFAULT_PASTE_MIN_PENDING_MS);\n\n // Last non-reading status, shown while a fast paste is in flight. Only read\n // while `reading`, so synced in a layout effect to avoid useSyncExternalStore\n // snapshot-tracking corruption on React 18.\n const [settled, setSettled] = useState<SettledPasteStatus>(status === 'reading' ? 'idle' : status);\n useIsomorphicLayoutEffect(() => {\n if (status !== 'reading') setSettled(status);\n }, [status]);\n\n // When the pending indicator became visible, or null while it is hidden.\n const [pendingShownAt, setPendingShownAt] = useState<number | null>(null);\n\n useEffect(() => {\n if (status !== 'reading') return undefined;\n const timer = setTimeout(() => {\n setPendingShownAt(Date.now());\n }, pendingDelayMs);\n return () => {\n clearTimeout(timer);\n };\n }, [status, pendingDelayMs]);\n\n useEffect(() => {\n if (status === 'reading' || pendingShownAt === null) return undefined;\n const remaining = Math.max(0, minPendingMs - (Date.now() - pendingShownAt));\n const timer = setTimeout(() => {\n setPendingShownAt(null);\n }, remaining);\n return () => {\n clearTimeout(timer);\n };\n }, [status, pendingShownAt, minPendingMs]);\n\n if (pendingShownAt !== null) return 'reading';\n return status === 'reading' ? settled : status;\n}\n","import {\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useEffect,\n useId,\n useMemo,\n useState,\n type ButtonHTMLAttributes,\n type DragEventHandler,\n type HTMLAttributes,\n type ReactNode,\n} from 'react';\nimport type { PasteOutcome, PasteState, PasteStatus } from '../core/paste-machine';\nimport { describePasteError, type CopyError } from '../core/errors';\nimport type { PasteResult, PasteSource } from '../core/paste-reader';\nimport { LiveRegion } from './LiveRegion';\nimport { TriggerLabel } from './TriggerLabel';\nimport { usePasteDisplayStatus, type UsePasteDisplayStatusOptions } from './usePasteDisplayStatus';\nimport { usePaste, type PasteDropTargetProps, type UsePasteOptions, type UsePasteResult } from './usePaste';\nimport { useRevealOnInteraction, type RevealReason } from './useRevealOnInteraction';\nimport { composeEventHandlers, mergeRefs } from './utils';\n\n/* ---------------------------------------------------------------- Messages */\n\nexport interface PasteFieldMessages {\n /** Announced to screen readers on successful paste. */\n readonly pasted: string | ((result: PasteResult) => string);\n /**\n * Announced to screen readers when content is dropped onto the zone. When\n * you override `pasted` but not this, your `pasted` message is used for drops too.\n */\n readonly dropped?: string | ((result: PasteResult) => string);\n /** Announced on failure. Defaults to {@link describePasteError}. `source` tells drops from pastes. */\n readonly error: (error: CopyError, source?: PasteSource) => string;\n /**\n * Accessible name of the trigger button. Receives the field's `label` prop.\n * The returned string must not be empty.\n */\n readonly triggerLabel: (label: string) => string;\n /**\n * Accessible name of the drop zone / paste target area.\n * Receives the field's `label` prop.\n */\n readonly zoneLabel: (label: string) => string;\n}\n\nexport const defaultPasteFieldMessages: PasteFieldMessages = {\n pasted: 'Pasted from clipboard',\n dropped: 'Dropped content added',\n error: describePasteError,\n triggerLabel: (label) => `Paste ${label}`,\n zoneLabel: (label) => `Paste area for ${label}`,\n};\n\n/* ----------------------------------------------------------------- Context */\n\nexport interface PasteFieldContextValue extends UsePasteResult {\n readonly label: string;\n readonly labelId: string;\n readonly zoneId: string;\n readonly revealed: boolean;\n readonly revealReason: RevealReason | null;\n readonly messages: PasteFieldMessages;\n /** Flicker-free status for rendering. Use `status` for logic, this for pixels. */\n readonly displayStatus: PasteStatus;\n /** Triggers a programmatic paste (via Clipboard API, may prompt for permission). */\n readonly doPaste: () => Promise<PasteOutcome>;\n}\n\nconst PasteFieldContext = /* @__PURE__ */ createContext<PasteFieldContextValue | null>(null);\n\n/** Access field state to build custom parts. Must be used inside `<PasteField.Root>`. */\nexport function usePasteField(): PasteFieldContextValue {\n const context = useContext(PasteFieldContext);\n if (!context) throw new Error('usePasteField() must be used inside <PasteField.Root>.');\n return context;\n}\n\n/* -------------------------------------------------------------------- Root */\n\nexport interface PasteFieldRootProps\n extends Omit<HTMLAttributes<HTMLDivElement>, 'onPaste' | 'onError'>,\n UsePasteDisplayStatusOptions {\n /** Human label — used for the trigger's and zone's accessible names. */\n readonly label: string;\n readonly pasteOptions?: UsePasteOptions;\n readonly messages?: Partial<PasteFieldMessages>;\n /** Skip hover/focus reveal and always show the trigger. */\n readonly alwaysVisible?: boolean;\n /** Render the built-in live region. Disable if your app has a global announcer. Default `true`. */\n readonly announce?: boolean;\n}\n\nconst Root = /* @__PURE__ */ forwardRef<HTMLDivElement, PasteFieldRootProps>(function PasteFieldRoot(\n {\n label,\n pasteOptions,\n messages: messageOverrides,\n alwaysVisible = false,\n announce = true,\n pendingDelayMs,\n minPendingMs,\n children,\n onPointerEnter,\n onPointerLeave,\n onPointerDown,\n onFocus,\n onBlur,\n ...rest\n },\n forwardedRef,\n) {\n const pasteState = usePaste(pasteOptions);\n const displayStatus = usePasteDisplayStatus(pasteState.status, {\n ...(pendingDelayMs === undefined ? {} : { pendingDelayMs }),\n ...(minPendingMs === undefined ? {} : { minPendingMs }),\n });\n const reveal = useRevealOnInteraction<HTMLDivElement>({ alwaysVisible });\n const baseId = useId();\n const labelId = `${baseId}-label`;\n const zoneId = `${baseId}-zone`;\n\n const messages = useMemo<PasteFieldMessages>(\n () => ({\n ...defaultPasteFieldMessages,\n // A translated `pasted` beats the English default `dropped`.\n ...(messageOverrides?.pasted === undefined ? {} : { dropped: messageOverrides.pasted }),\n ...messageOverrides,\n }),\n [messageOverrides],\n );\n\n const { paste: machinePaste } = pasteState;\n const doPaste = useCallback(() => machinePaste(), [machinePaste]);\n const { targetProps } = reveal;\n const ref = useMemo(() => mergeRefs(targetProps.ref, forwardedRef), [targetProps.ref, forwardedRef]);\n\n const context = useMemo<PasteFieldContextValue>(\n () => ({\n ...pasteState,\n label,\n labelId,\n zoneId,\n revealed: reveal.visible,\n revealReason: reveal.reason,\n messages,\n displayStatus,\n doPaste,\n }),\n [pasteState, label, labelId, zoneId, reveal.visible, reveal.reason, messages, displayStatus, doPaste],\n );\n\n const { state } = pasteState;\n\n let announcement = '';\n if (state.status === 'read') {\n const message = (state.result.source === 'drop' ? messages.dropped : undefined) ?? messages.pasted;\n announcement = typeof message === 'function' ? message(state.result) : message;\n } else if (state.status === 'error') {\n announcement = messages.error(state.error, state.source);\n }\n\n return (\n <PasteFieldContext.Provider value={context}>\n <div\n {...rest}\n ref={ref}\n data-state={state.status}\n data-display-state={displayStatus}\n data-revealed={reveal.visible ? '' : undefined}\n onPointerEnter={composeEventHandlers(onPointerEnter, targetProps.onPointerEnter)}\n onPointerLeave={composeEventHandlers(onPointerLeave, targetProps.onPointerLeave)}\n onPointerDown={composeEventHandlers(onPointerDown, targetProps.onPointerDown)}\n onFocus={composeEventHandlers(onFocus, targetProps.onFocus)}\n onBlur={composeEventHandlers(onBlur, targetProps.onBlur)}\n >\n {children}\n {announce ? <LiveRegion message={announcement} /> : null}\n </div>\n </PasteFieldContext.Provider>\n );\n});\n\n/* ------------------------------------------------------------ Label/Status */\n\nexport type PasteFieldLabelProps = HTMLAttributes<HTMLSpanElement>;\n\nconst Label = /* @__PURE__ */ forwardRef<HTMLSpanElement, PasteFieldLabelProps>(function PasteFieldLabel(\n { children, ...rest },\n ref,\n) {\n const field = usePasteField();\n return (\n <span {...rest} ref={ref} id={field.labelId}>\n {children ?? field.label}\n </span>\n );\n});\n\nexport interface PasteFieldStatusProps extends HTMLAttributes<HTMLSpanElement> {\n /** Map each paste status to a label. Defaults to English strings. */\n readonly labels?: Partial<Readonly<Record<PasteStatus, string>>>;\n}\n\nconst DEFAULT_STATUS_LABELS: Readonly<Record<PasteStatus, string>> = {\n idle: 'Ready',\n reading: 'Reading…',\n read: 'Pasted',\n error: 'Error',\n};\n\nconst Status = /* @__PURE__ */ forwardRef<HTMLSpanElement, PasteFieldStatusProps>(function PasteFieldStatus(\n { children, labels, ...rest },\n ref,\n) {\n const field = usePasteField();\n const resolved = labels ? { ...DEFAULT_STATUS_LABELS, ...labels } : DEFAULT_STATUS_LABELS;\n return (\n <span {...rest} ref={ref} data-state={field.status} data-display-state={field.displayStatus}>\n {children ?? resolved[field.displayStatus]}\n </span>\n );\n});\n\n/* ------------------------------------------------------------------- Zone */\n\nexport interface PasteFieldZoneProps extends HTMLAttributes<HTMLDivElement> {\n /** When true, the zone is always focusable (tabIndex=0). Default true. */\n readonly focusable?: boolean;\n /**\n * Accept drag-and-drop, through the same `accept` and limits as paste.\n * `data-drag-over` is present while an accepted drag is over the zone. Default true.\n */\n readonly droppable?: boolean;\n}\n\n/**\n * A focusable paste target. Accepts keyboard paste (Ctrl/⌘+V) without a\n * permission prompt and, unless `droppable={false}`, drag-and-drop. Renders\n * `data-zone` and `data-drag-over` for styling.\n *\n * Accessible name: `aria-label` prop, else `messages.zoneLabel(label)`\n * (\"Paste area for Notes\"). Pass `aria-labelledby` explicitly to name it from\n * another element instead.\n */\nconst Zone = /* @__PURE__ */ forwardRef<HTMLDivElement, PasteFieldZoneProps>(function PasteFieldZone(\n {\n children,\n focusable = true,\n droppable = true,\n onPaste,\n onDragEnter,\n onDragOver,\n onDragLeave,\n onDrop,\n 'aria-label': ariaLabel,\n tabIndex,\n ...rest\n },\n ref,\n) {\n const field = usePasteField();\n const { targetProps, dropTargetProps } = field;\n const drop: Record<keyof PasteDropTargetProps<HTMLDivElement>, DragEventHandler<HTMLDivElement> | undefined> = {\n onDragEnter,\n onDragOver,\n onDragLeave,\n onDrop,\n };\n if (droppable) {\n for (const key of Object.keys(dropTargetProps) as (keyof typeof dropTargetProps)[]) {\n drop[key] = composeEventHandlers(drop[key], dropTargetProps[key]);\n }\n }\n\n // Guard: a custom `zoneLabel` returning '' must not leave the region unnamed.\n const safeAriaLabel =\n (ariaLabel ?? field.messages.zoneLabel(field.label)) || defaultPasteFieldMessages.zoneLabel(field.label);\n\n return (\n <div\n // Default shortcut hint; a consumer value in `rest` overrides it.\n aria-keyshortcuts=\"Control+V Meta+V\"\n {...rest}\n ref={ref}\n id={field.zoneId}\n role=\"region\"\n aria-label={safeAriaLabel}\n data-zone=\"\"\n data-state={field.status}\n data-display-state={field.displayStatus}\n data-drag-over={droppable && field.isDragOver ? '' : undefined}\n tabIndex={tabIndex ?? (focusable ? 0 : undefined)}\n onPaste={composeEventHandlers(onPaste, targetProps.onPaste)}\n {...drop}\n >\n {children}\n </div>\n );\n});\n\n/* ----------------------------------------------------------------- Trigger */\n\nexport interface PasteFieldTriggerRenderProps {\n /** The real state. Use for logic. */\n readonly status: PasteStatus;\n /** Flicker-free state. Use for what you render. */\n readonly displayStatus: PasteStatus;\n readonly state: PasteState;\n readonly revealed: boolean;\n /** Whether `retry()` could help after the current error. */\n readonly canRetry: boolean;\n}\n\nexport interface PasteFieldTriggerProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'type'> {\n /** Static content, or a render function receiving the live state. */\n readonly children?: ReactNode | ((props: PasteFieldTriggerRenderProps) => ReactNode);\n}\n\nconst DEFAULT_TRIGGER_TEXT: Readonly<Record<PasteStatus, string>> = {\n idle: 'Paste',\n reading: 'Pasting…',\n read: 'Pasted',\n error: 'Retry',\n};\n\nconst Trigger = /* @__PURE__ */ forwardRef<HTMLButtonElement, PasteFieldTriggerProps>(function PasteFieldTrigger(\n { children, onClick, 'aria-label': ariaLabel, ...rest },\n ref,\n) {\n const field = usePasteField();\n const renderProps: PasteFieldTriggerRenderProps = {\n status: field.status,\n displayStatus: field.displayStatus,\n state: field.state,\n revealed: field.revealed,\n canRetry: field.canRetry,\n };\n\n const safeAriaLabel =\n (ariaLabel ?? field.messages.triggerLabel(field.label)) || defaultPasteFieldMessages.triggerLabel(field.label);\n\n return (\n <button\n {...rest}\n ref={ref}\n type=\"button\"\n aria-label={safeAriaLabel}\n aria-busy={field.status === 'reading' ? true : undefined}\n data-state={field.status}\n data-display-state={field.displayStatus}\n data-revealed={field.revealed ? '' : undefined}\n onClick={composeEventHandlers(onClick, () => {\n void field.doPaste();\n })}\n >\n {typeof children === 'function'\n ? children(renderProps)\n : (children ?? <TriggerLabel status={field.displayStatus} labels={DEFAULT_TRIGGER_TEXT} />)}\n </button>\n );\n});\n\n/* ----------------------------------------------------------------- Preview */\n\nexport interface PasteFieldPreviewRenderProps {\n readonly result: PasteResult;\n /**\n * Object URLs for `result.images`, in order, revoked automatically. Empty on\n * the server and for the first render after a paste, until they are created.\n */\n readonly imageUrls: readonly string[];\n}\n\nexport interface PasteFieldPreviewProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {\n /** Custom rendering of the latest result. Replaces the default text / image / file preview. */\n readonly children?: (props: PasteFieldPreviewRenderProps) => ReactNode;\n /** Shown while there is no pasted result (idle, reading, error). */\n readonly placeholder?: ReactNode;\n /** Pasted text longer than this is cut and ends with \"…\". Default 2000. */\n readonly maxTextLength?: number;\n /** Alt text for each pasted image. Default \"Pasted image 1 of 2\". */\n readonly imageAlt?: (index: number, total: number) => string;\n}\n\nconst NO_URLS: readonly string[] = [];\n\n/**\n * Object URLs for blobs, revoked when the blobs change or the component\n * unmounts. URLs are only returned for the blobs they were made from, so they\n * never pair with the wrong result.\n */\nfunction useObjectUrls(blobs: readonly Blob[] | undefined): readonly string[] {\n const [entry, setEntry] = useState<{ readonly blobs?: readonly Blob[]; readonly urls: readonly string[] }>({\n urls: NO_URLS,\n });\n useEffect(() => {\n if (!blobs?.length || typeof URL.createObjectURL !== 'function') return undefined;\n const urls = blobs.map((blob) => URL.createObjectURL(blob));\n setEntry({ blobs, urls });\n return () => {\n for (const url of urls) URL.revokeObjectURL(url);\n };\n }, [blobs]);\n return entry.blobs === blobs ? entry.urls : NO_URLS;\n}\n\nconst defaultImageAlt = (index: number, total: number): string => `Pasted image ${String(index + 1)} of ${String(total)}`;\n\n/**\n * Shows what was pasted: text (never HTML, which is untrusted), image\n * thumbnails and file names. Renders `placeholder` until there is a result.\n * Pass a function child to render the result yourself.\n */\nconst Preview = /* @__PURE__ */ forwardRef<HTMLDivElement, PasteFieldPreviewProps>(function PasteFieldPreview(\n { children, placeholder = null, maxTextLength = 2000, imageAlt = defaultImageAlt, ...rest },\n ref,\n) {\n const { result, status } = usePasteField();\n const imageUrls = useObjectUrls(result?.images);\n\n let content: ReactNode = placeholder;\n if (result) {\n if (children) {\n content = children({ result, imageUrls });\n } else {\n const { text } = result;\n const files = result.files.filter((file) => !file.type.startsWith('image/'));\n content = (\n <>\n {text ? (\n <pre data-preview-text=\"\">{text.length > maxTextLength ? `${text.slice(0, maxTextLength)}…` : text}</pre>\n ) : null}\n {imageUrls.map((url, index) => (\n <img key={url} data-preview-image=\"\" src={url} alt={imageAlt(index, imageUrls.length)} />\n ))}\n {files.length > 0 ? (\n <ul data-preview-files=\"\">\n {files.map((file, index) => (\n <li key={`${String(index)}-${file.name}`}>{file.name}</li>\n ))}\n </ul>\n ) : null}\n </>\n );\n }\n }\n\n return (\n <div {...rest} ref={ref} data-preview=\"\" data-state={status} data-empty={result ? undefined : ''}>\n {content}\n </div>\n );\n});\n\n/**\n * Headless compound component for a labelled, paste-ready field.\n *\n * Styling hooks on Root, Zone and Trigger:\n * - `data-display-state=\"idle|reading|read|error\"`: flicker-free, style with this\n * - `data-state`: the real, instantaneous state, for logic and tests\n * - `data-revealed`: present while the trigger should be visible\n *\n * @example\n * ```tsx\n * <PasteField.Root label=\"Notes\">\n * <PasteField.Label />\n * <PasteField.Zone />\n * <PasteField.Trigger />\n * <PasteField.Preview placeholder=\"Nothing pasted yet\" />\n * </PasteField.Root>\n * ```\n */\nexport const PasteField = { Root, Label, Status, Zone, Trigger, Preview } as const;\n","import { useCallback, useEffect, useRef, useState, type RefCallback } from 'react';\nimport {\n applyDragCopy,\n type DragCopyOptions,\n type DragCopyOutcome,\n type DragCopyState,\n type DragCopyStatus,\n type DragStartEventLike,\n} from '../core/drag-copy';\nimport { useIsomorphicLayoutEffect } from './utils';\nimport { invoke } from '../core/machine-shared';\n\nexport interface UseDragCopyOptions extends Omit<DragCopyOptions, 'onDrag'> {\n /**\n * Set `false` to disable drag without unmounting. Removes the `draggable`\n * attribute and listener while `false`. Default `true`.\n */\n readonly enabled?: boolean;\n /** Called each time a drag starts or ends. */\n readonly onDrag?: (state: DragCopyState) => void;\n}\n\nexport interface UseDragCopyResult<T extends HTMLElement = HTMLElement> {\n /**\n * Attach to any element you want to make draggable. The hook sets\n * `draggable=\"true\"` automatically while `enabled` is `true`.\n */\n readonly ref: RefCallback<T>;\n /** `'idle' | 'dragging' | 'done'` — the current drag status. */\n readonly status: DragCopyStatus;\n /** The last `dragstart` outcome; `null` before the first drag. */\n readonly outcome: DragCopyOutcome | null;\n /**\n * For use in React's `onDragStart` prop if you need to wire it imperatively\n * (e.g. inside a render-prop component). The `ref` alone is sufficient for\n * native HTML elements: the hook attaches its own listener.\n */\n readonly onDragStart: (event: DragStartEventLike) => void;\n}\n\n/**\n * Makes an element draggable and populates its `DataTransfer` with your data.\n *\n * ```tsx\n * const { ref } = useDragCopy({\n * source: () => ({ kind: 'html', html: '<b>Hello</b>', text: 'Hello' }),\n * });\n * return <div ref={ref}>Drag me</div>;\n * ```\n *\n * - No Clipboard API needed — works in every browser supporting HTML5 drag-and-drop.\n * - The `source` callback always reads the latest props/state, never stale closures.\n * - `enabled={false}` removes `draggable` and the listener without unmounting.\n * - SSR-safe: no DOM access during server rendering.\n */\nexport function useDragCopy<T extends HTMLElement = HTMLElement>(\n options: UseDragCopyOptions,\n): UseDragCopyResult<T> {\n const optionsRef = useRef(options);\n useIsomorphicLayoutEffect(() => {\n optionsRef.current = options;\n });\n\n const [node, setNode] = useState<HTMLElement | null>(null);\n const [state, setState] = useState<DragCopyState>({ status: 'idle', outcome: null });\n\n const enabled = options.enabled !== false;\n\n // Stable handler for the React onDragStart prop path.\n const onDragStart = useCallback((event: DragStartEventLike): void => {\n const { onDrag, onError, source, effectAllowed } = optionsRef.current;\n const coreOpts: DragCopyOptions = effectAllowed !== undefined\n ? { source, effectAllowed }\n : { source };\n const outcome = applyDragCopy(event, coreOpts);\n const next: DragCopyState = { status: 'dragging', outcome };\n setState(next);\n if (outcome.status === 'failed') invoke(onError, outcome.error);\n invoke(onDrag, next);\n }, []);\n\n useEffect(() => {\n if (!node || !enabled) return undefined;\n\n node.setAttribute('draggable', 'true');\n\n function handleDragStart(raw: Event): void {\n const event = raw as DragEvent;\n const { onDrag, onError, source, effectAllowed } = optionsRef.current;\n const coreOpts: DragCopyOptions = effectAllowed !== undefined\n ? { source, effectAllowed }\n : { source };\n const outcome = applyDragCopy(\n {\n type: event.type,\n dataTransfer: event.dataTransfer,\n get defaultPrevented() {\n return event.defaultPrevented;\n },\n preventDefault: () => { event.preventDefault(); },\n },\n coreOpts,\n );\n const next: DragCopyState = { status: 'dragging', outcome };\n setState(next);\n if (outcome.status === 'failed') invoke(onError, outcome.error);\n invoke(onDrag, next);\n }\n\n function handleDragEnd(): void {\n const opts = optionsRef.current;\n setState((prev) => {\n const next: DragCopyState = { status: 'done', outcome: prev.outcome };\n invoke(opts.onDrag, next);\n return next;\n });\n }\n\n node.addEventListener('dragstart', handleDragStart);\n node.addEventListener('dragend', handleDragEnd);\n\n return () => {\n node.removeEventListener('dragstart', handleDragStart);\n node.removeEventListener('dragend', handleDragEnd);\n node.removeAttribute('draggable');\n };\n }, [node, enabled]);\n\n // Reset to idle when disabled so status accurately reflects the element's state.\n useEffect(() => {\n if (!enabled) setState({ status: 'idle', outcome: null });\n }, [enabled]);\n\n return {\n ref: setNode,\n status: state.status,\n outcome: state.outcome,\n onDragStart,\n };\n}\n","import { copyFailure } from '../core/errors';\n\n/** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */\nexport const DEFAULT_LINK_PROTOCOLS: readonly string[] = /* @__PURE__ */ Object.freeze(['https:', 'http:', 'mailto:', 'tel:']);\n\n/**\n * Query parameters that only track where a click came from: the defaults of\n * {@link cleanLinkUrl}. `utm_` matches every parameter starting with it.\n */\nexport const TRACKING_PARAMETERS: readonly string[] = /* @__PURE__ */ Object.freeze([\n 'utm_',\n 'fbclid',\n 'gclid',\n 'gclsrc',\n 'dclid',\n 'gbraid',\n 'wbraid',\n 'msclkid',\n 'yclid',\n 'twclid',\n 'ttclid',\n 'li_fat_id',\n 'igshid',\n 'igsh',\n 'mc_cid',\n 'mc_eid',\n '_hsenc',\n '_hsmi',\n 'mkt_tok',\n 'oly_anon_id',\n 'oly_enc_id',\n 'vero_id',\n 'wickedid',\n '_gl',\n]);\n\nexport interface CleanLinkOptions {\n /**\n * Parameters to remove: exact names, names ending in `_` (a prefix, like\n * `utm_`), or regular expressions tested against the name. Default {@link TRACKING_PARAMETERS}.\n */\n readonly params?: readonly (string | RegExp)[];\n /** Parameters never removed, even when `params` matches them. */\n readonly keep?: readonly string[];\n}\n\nexport interface LinkUrlOptions {\n /** Resolves relative links. Default: the page's address in a browser; required elsewhere for relative links. */\n readonly base?: string | URL;\n /** Allowed schemes, with the colon. Default {@link DEFAULT_LINK_PROTOCOLS}. */\n readonly protocols?: readonly string[];\n /** Remove tracking parameters: `true` for {@link TRACKING_PARAMETERS}, or your own list. Default `false`. */\n readonly clean?: boolean | CleanLinkOptions;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nfunction baseUrl(base: LinkUrlOptions['base']): string | undefined {\n if (base !== undefined) {\n if (typeof base === 'string' || base instanceof URL) return String(base);\n throw invalid('`base` must be a string or a URL.');\n }\n return typeof location === 'undefined' ? undefined : location.href;\n}\n\nfunction protocolSet(protocols: LinkUrlOptions['protocols']): ReadonlySet<string> {\n const list: unknown = protocols ?? DEFAULT_LINK_PROTOCOLS;\n const valid = (protocol: unknown): protocol is string => typeof protocol === 'string' && /^[a-z][a-z\\d+.-]*:$/i.test(protocol);\n if (!Array.isArray(list) || list.length === 0 || !(list as readonly unknown[]).every(valid)) {\n throw invalid('`protocols` must be a non-empty list of schemes with their colon, like \"https:\".');\n }\n return new Set((list as readonly string[]).map((protocol) => protocol.toLowerCase()));\n}\n\nfunction matcher(params: CleanLinkOptions['params']): (name: string) => boolean {\n const list = params ?? TRACKING_PARAMETERS;\n if (!Array.isArray(list) || !list.every((param) => typeof param === 'string' || param instanceof RegExp)) {\n throw invalid('`clean.params` must be a list of strings and regular expressions.');\n }\n return (name) => {\n const lower = name.toLowerCase();\n return list.some((param) => {\n if (typeof param !== 'string') return new RegExp(param.source, param.flags.replace(/[gy]/g, '')).test(name);\n const wanted = param.toLowerCase();\n return wanted.endsWith('_') ? lower.startsWith(wanted) : lower === wanted;\n });\n };\n}\n\n/** The cleaning step `clean` asks for, or `null`. Throws for an invalid option. */\nfunction cleaner(option: LinkUrlOptions['clean']): ((url: URL) => void) | null {\n const cleaning: unknown = option ?? false; // Plain-JS callers can pass anything.\n if (cleaning === false) return null;\n if (cleaning !== true && (typeof cleaning !== 'object' || cleaning === null)) throw invalid('`clean` must be a boolean or an options object.');\n const settings: CleanLinkOptions = cleaning === true ? {} : cleaning;\n const tracking = matcher(settings.params);\n const keep = settings.keep ?? [];\n if (!Array.isArray(keep) || !keep.every((name: unknown) => typeof name === 'string')) throw invalid('`clean.keep` must be a list of strings.');\n const kept = new Set(keep.map((name) => name.toLowerCase()));\n return (url) => {\n for (const name of [...new Set(url.searchParams.keys())]) {\n if (tracking(name) && !kept.has(name.toLowerCase())) url.searchParams.delete(name);\n }\n };\n}\n\n/**\n * Validates `options` once (throwing a typed `invalid-payload` error for invalid\n * ones) and returns a resolver that throws only for invalid links.\n * @internal\n */\nexport function linkUrlResolver(options: LinkUrlOptions = {}): (input: string | URL) => string {\n const protocols = protocolSet(options.protocols);\n const base = baseUrl(options.base);\n const clean = cleaner(options.clean);\n return (input) => {\n if (typeof input !== 'string' && !(input instanceof URL)) throw invalid('A link must be a string or a URL.');\n const raw = String(input).trim();\n if (raw === '') throw invalid('A link must not be empty.');\n let url: URL;\n try {\n url = new URL(raw, base);\n } catch (cause) {\n throw copyFailure('invalid-payload', `Not a valid link: ${JSON.stringify(raw.slice(0, 200))}.`, cause);\n }\n if (!protocols.has(url.protocol)) {\n throw invalid(`Links with the scheme \"${url.protocol}\" are not allowed (allowed: ${[...protocols].join(', ')}).`);\n }\n // Never copy or paste credentials embedded in a link.\n url.username = '';\n url.password = '';\n clean?.(url);\n return url.href;\n };\n}\n\n/**\n * The link as an absolute, safe URL string, or a typed `invalid-payload` error:\n * relative links are resolved, the scheme must be allowed, user names and\n * passwords are always removed, and tracking parameters optionally.\n */\nexport function resolveLinkUrl(input: string | URL, options: LinkUrlOptions = {}): string {\n return linkUrlResolver(options)(input);\n}\n\n/**\n * Removes tracking parameters (`utm_*`, `fbclid`, `gclid`, ...) from a link, keeping\n * everything else, including the fragment. Also validates it like every link here.\n *\n * @example\n * cleanLinkUrl('https://shop.example/p/42?utm_source=news&color=red'); // 'https://shop.example/p/42?color=red'\n */\nexport function cleanLinkUrl(url: string | URL, options: CleanLinkOptions & Omit<LinkUrlOptions, 'clean'> = {}): string {\n const { params, keep, ...rest } = options;\n return resolveLinkUrl(url, { ...rest, clean: { ...(params === undefined ? {} : { params }), ...(keep === undefined ? {} : { keep }) } });\n}\n","import { copyFailure } from '../core/errors';\nimport type { HtmlPayload, MultiPayload } from '../core/payload';\nimport { resolveLinkUrl, type LinkUrlOptions } from './url';\n\n/** A link with an optional title. */\nexport interface Link {\n readonly url: string | URL;\n /** What the link says when pasted into a document or chat. Default: the URL. */\n readonly title?: string;\n}\n\n/** A link: a URL, a `{ url, title }` object, or an `<a>` element (its `href` and text). */\nexport type LinkSource = string | URL | Link | HTMLAnchorElement;\n\n/** A validated link: an absolute, safe URL and a clean title. */\nexport interface ResolvedLink {\n readonly url: string;\n /** Never empty: the URL when there is no title. */\n readonly title: string;\n /** Whether `title` came from the input (`false`: it is the URL). */\n readonly titled: boolean;\n}\n\n/**\n * What the plain-text flavour holds (editors, terminals and address bars paste it):\n * `'url'` (the default), `'title'`, `'title-and-url'` (the title, then the URL on\n * the next line) or `'markdown'` (`[Title](URL)`).\n */\nexport type LinkTextFormat = 'url' | 'title' | 'title-and-url' | 'markdown';\n\nexport interface LinkPayloadOptions extends LinkUrlOptions {\n /** Default `'url'`. */\n readonly text?: LinkTextFormat;\n /** Longest title kept, in characters; longer ones end in an ellipsis. Default {@link DEFAULT_LINK_TITLE_LENGTH}. */\n readonly maxTitleLength?: number;\n}\n\nexport interface LinkDragPayloadOptions extends LinkPayloadOptions {\n /**\n * `'drag'`: a multi-format payload that also carries `text/uri-list` and\n * Firefox's `text/x-moz-url`, for `useDragCopy` and `useCopyInterceptor` (a link\n * dropped on the tab bar opens). Clipboard writes skip those two where the\n * browser can't write them.\n */\n readonly target: 'drag';\n}\n\nexport const DEFAULT_LINK_TITLE_LENGTH = 300;\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\n/**\n * Characters a title never keeps: controls, bidi overrides and isolates (which can\n * make a title read differently), and zero-width characters.\n */\n// eslint-disable-next-line no-control-regex -- matching control characters is the point\nconst HIDDEN = /[\\0-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f-\\x9f\\u061C\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u2066-\\u2069\\uFEFF]/g;\n\n/** A title as one clean line: hidden characters removed, whitespace collapsed, length capped. */\nexport function cleanTitle(title: string, maxLength: number): string {\n const clean = title.replace(HIDDEN, '').replace(/\\s+/g, ' ').trim();\n if (clean.length <= maxLength) return clean;\n // Cut on a code point boundary and mark the cut.\n return `${Array.from(clean).slice(0, maxLength - 1).join('').trimEnd()}\\u2026`;\n}\n\nfunction maxTitle(value: number | undefined): number {\n if (value === undefined) return DEFAULT_LINK_TITLE_LENGTH;\n if (Number.isInteger(value) && value >= 1) return value;\n throw invalid(`\\`maxTitleLength\\` must be a positive integer (received ${String(value)}).`);\n}\n\nfunction isAnchor(source: unknown): source is HTMLAnchorElement {\n return typeof source === 'object' && source !== null && (source as { nodeName?: unknown }).nodeName === 'A' && typeof (source as { href?: unknown }).href === 'string';\n}\n\n/**\n * Validates a link and its title: see {@link resolveLinkUrl} for the URL rules.\n * An `<a>` element gives its `href` and its text (or `title` attribute).\n */\nexport function resolveLink(source: LinkSource, options: LinkPayloadOptions = {}): ResolvedLink {\n let url: string | URL;\n let title: unknown;\n if (typeof source === 'string' || source instanceof URL) {\n url = source;\n } else if (isAnchor(source)) {\n url = source.getAttribute('href') ?? '';\n title = source.textContent.trim() !== '' ? source.textContent : (source.getAttribute('title') ?? undefined);\n if (url !== '' && options.base === undefined) url = source.href; // Resolved against the anchor's own document.\n } else if (typeof (source as unknown) === 'object' && (source as unknown) !== null && 'url' in source) {\n url = source.url;\n title = source.title;\n } else {\n throw invalid('A link must be a URL, a { url, title } object or an <a> element.');\n }\n if (title !== undefined && typeof title !== 'string') throw invalid('A link title must be a string.');\n const href = resolveLinkUrl(url, options);\n const clean = title === undefined ? '' : cleanTitle(title, maxTitle(options.maxTitleLength));\n return { url: href, title: clean === '' ? href : clean, titled: clean !== '' };\n}\n\nexport const escapeHtml = (text: string): string =>\n text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\n\n/** `[title](url)`, safe in every CommonMark renderer: brackets and backslashes escaped, parentheses and spaces encoded. */\nexport function markdownLink(link: ResolvedLink): string {\n const label = link.title.replace(/[\\\\[\\]]/g, '\\\\$&');\n const target = link.url.replace(/[()<> ]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);\n return `[${label}](${target})`;\n}\n\nfunction plainText(link: ResolvedLink, format: LinkTextFormat): string {\n switch (format) {\n case 'url':\n return link.url;\n case 'title':\n return link.title;\n case 'title-and-url':\n return link.titled ? `${link.title}\\n${link.url}` : link.url;\n case 'markdown':\n return markdownLink(link);\n default:\n throw invalid(`\\`text\\` must be \"url\", \"title\", \"title-and-url\" or \"markdown\" (received ${JSON.stringify(format)}).`);\n }\n}\n\n/**\n * A copy payload for a link: an HTML anchor, so Slack, Google Docs, Notion,\n * Teams, Word and mail paste a titled link, and plain text (the URL by default)\n * for editors and address bars. The URL is validated (allowed schemes only,\n * credentials removed, optionally cleaned of tracking) and the title is cleaned\n * of hidden characters; both are escaped.\n *\n * @example\n * copy(() => linkPayload({ url: location.href, title: document.title }, { clean: true }));\n * useDragCopy({ payload: () => linkPayload(anchor, { target: 'drag' }) });\n */\nexport function linkPayload(source: LinkSource, options: LinkDragPayloadOptions): MultiPayload;\nexport function linkPayload(source: LinkSource, options?: LinkPayloadOptions): HtmlPayload;\nexport function linkPayload(source: LinkSource, options: LinkPayloadOptions & { readonly target?: 'drag' | 'clipboard' } = {}): HtmlPayload | MultiPayload {\n const target: unknown = options.target ?? 'clipboard'; // Plain-JS callers can pass anything.\n if (target !== 'drag' && target !== 'clipboard') throw invalid('`target` must be \"clipboard\" or \"drag\".');\n const link = resolveLink(source, options);\n const text = plainText(link, options.text ?? 'url');\n const html = `<a href=\"${escapeHtml(link.url)}\">${escapeHtml(link.title)}</a>`;\n if (target === 'clipboard') return { kind: 'html', html, text };\n return {\n kind: 'multi',\n items: [\n { mimeType: 'text/plain', data: text },\n { mimeType: 'text/html', data: html },\n { mimeType: 'text/uri-list', data: link.url, optional: true },\n // Firefox's titled-link format: the URL, a line break, the title.\n { mimeType: 'text/x-moz-url', data: `${link.url}\\n${link.title}`, optional: true },\n ],\n };\n}\n","import { createBrowserClipboardAdapter, type ClipboardAdapter } from '../core/clipboard-adapter';\nimport { createCopyError, describeCopyError, toCopyError, type CopyError, type CopyErrorType } from '../core/errors';\nimport { normalizePayload, validatePayload, type CopyInput, type CopyPayload } from '../core/payload';\nimport { cleanTitle, DEFAULT_LINK_TITLE_LENGTH, linkPayload } from '../link/payload';\nimport { linkUrlResolver, type LinkUrlOptions } from '../link/url';\n\n/** What to share: a link, a message, files, or any mix of them. */\nexport interface ShareContent {\n /** Validated like every link in this package: allowed schemes only, credentials removed. */\n readonly url?: string | URL;\n readonly title?: string;\n /** A message to share alongside (or instead of) the link. */\n readonly text?: string;\n /** Files for the share sheet, where the browser can share them (`navigator.canShare({ files })`). Never copied. */\n readonly files?: readonly File[];\n}\n\n/** The content after validation: what the share sheet or the clipboard receives. */\nexport interface ResolvedShare {\n readonly url: string | null;\n /** Cleaned of hidden characters; `null` when there is none. */\n readonly title: string | null;\n readonly text: string | null;\n readonly files: readonly File[];\n}\n\n/**\n * How to share:\n * - `auto` (default): the share sheet on phones and tablets, where people expect it; copy elsewhere.\n * - `native`: the share sheet wherever the browser has one (also desktop Safari, Edge and Chrome on Windows and macOS).\n * - `copy`: always copy.\n */\nexport type ShareMode = 'auto' | 'native' | 'copy';\n\nexport type ShareMethod = 'native' | 'copy';\n\n/** Structural view of what sharing needs from the browser; `window` by default. */\nexport interface ShareEnvironment {\n readonly navigator?: {\n readonly share?: (data: ShareData) => Promise<void>;\n readonly canShare?: (data: ShareData) => boolean;\n };\n readonly matchMedia?: (query: string) => { readonly matches: boolean };\n}\n\nexport interface ShareOptions extends LinkUrlOptions {\n /** Default `\"auto\"`. */\n readonly mode?: ShareMode;\n /** When the share sheet fails for a reason other than the user closing it, copy instead. Default `true`. */\n readonly fallback?: boolean;\n /**\n * What to copy. Default: a titled link (`linkPayload`) when there is a URL,\n * otherwise the text. Return a string or any copy payload.\n */\n readonly copy?: (content: ResolvedShare) => CopyInput;\n /** Default: the browser Clipboard API, as `useCopy` uses. */\n readonly adapter?: ClipboardAdapter;\n /** Default: `window`. For tests, webviews and other hosts. */\n readonly environment?: ShareEnvironment;\n /** Aborting it stops a copy in progress; the share sheet itself can only be closed by the user. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Why the content was copied rather than shared: `preferred` (the mode chose\n * copy, as on desktop in `auto`), `unsupported` (no share sheet, or it can't\n * take this content) or `fallback` (the share sheet failed).\n */\nexport type CopyReason = 'preferred' | 'unsupported' | 'fallback';\n\n/** What `shareOrCopy` resolves to. It never rejects. */\nexport type ShareOutcome =\n | { readonly status: 'shared'; readonly method: 'native'; readonly content: ResolvedShare }\n | { readonly status: 'copied'; readonly method: 'copy'; readonly reason: CopyReason; readonly payload: CopyPayload; readonly content: ResolvedShare }\n /** The user closed the share sheet. Nothing to report. */\n | { readonly status: 'cancelled'; readonly method: 'native' }\n | { readonly status: 'error'; readonly method: ShareMethod; readonly error: CopyError };\n\n/** Phones and tablets: a touch screen is the main input and nothing hovers. */\nexport const TOUCH_FIRST = '(hover: none) and (pointer: coarse)';\n\nconst defaultEnvironment = (): ShareEnvironment | undefined => (typeof window === 'undefined' ? undefined : window);\n\nconst invalid = (message: string): CopyError => createCopyError('invalid-payload', message);\n\n/** Validates and cleans what to share, or returns the typed error for invalid input. */\nfunction resolveContent(content: ShareContent, options: LinkUrlOptions): ResolvedShare | CopyError {\n const value: unknown = content;\n if (typeof value !== 'object' || value === null) return invalid('Share content must be an object with a url, text or files.');\n const { url, title, text, files } = value as Record<string, unknown>;\n let href: string | null = null;\n if (url !== undefined && url !== null) {\n try {\n href = linkUrlResolver(options)(url as string | URL);\n } catch (error) {\n return toCopyError(error);\n }\n }\n if (title !== undefined && typeof title !== 'string') return invalid('`title` must be a string.');\n if (text !== undefined && typeof text !== 'string') return invalid('`text` must be a string.');\n const list: unknown = files ?? [];\n if (!Array.isArray(list) || !list.every((file: unknown) => typeof File !== 'undefined' && file instanceof File)) {\n return invalid('`files` must be a list of File objects.');\n }\n const cleanName = title === undefined ? '' : cleanTitle(title, DEFAULT_LINK_TITLE_LENGTH);\n const message = text === undefined || text.trim() === '' ? null : text;\n if (href === null && message === null && list.length === 0) return invalid('There is nothing to share: give a url, text or files.');\n return { url: href, title: cleanName === '' ? null : cleanName, text: message, files: list as File[] };\n}\n\n/** The `ShareData` the browser receives: only the fields that are set. */\nfunction shareData(content: ResolvedShare): ShareData {\n return {\n ...(content.url === null ? {} : { url: content.url }),\n ...(content.title === null ? {} : { title: content.title }),\n ...(content.text === null ? {} : { text: content.text }),\n ...(content.files.length === 0 ? {} : { files: [...content.files] }),\n };\n}\n\n/** Whether this browser can open its share sheet for `data`. */\nfunction canShareNatively(environment: ShareEnvironment | undefined, data: ShareData | null): boolean {\n const nav = environment?.navigator;\n if (typeof nav?.share !== 'function') return false;\n if (data === null) return true;\n // Without canShare (older Safari), only links and text can be shared.\n return typeof nav.canShare === 'function' ? nav.canShare(data) : data.files === undefined;\n}\n\nfunction isTouchFirst(environment: ShareEnvironment | undefined): boolean {\n return typeof environment?.matchMedia === 'function' && environment.matchMedia(TOUCH_FIRST).matches;\n}\n\nfunction resolveMode(mode: unknown): ShareMode | CopyError {\n if (mode === undefined) return 'auto';\n return mode === 'auto' || mode === 'native' || mode === 'copy' ? mode : invalid('`mode` must be \"auto\", \"native\" or \"copy\".');\n}\n\n/**\n * How {@link shareOrCopy} would share right now: `\"native\"` (the share sheet) or\n * `\"copy\"`. Use it to label the button (\"Share…\" or \"Copy link\"). Pass the\n * content when it has files, since not every share sheet takes them.\n */\nexport function shareMethod(options: Pick<ShareOptions, 'mode' | 'environment'> = {}, content?: ShareContent): ShareMethod {\n const mode = resolveMode(options.mode);\n if (typeof mode !== 'string' || mode === 'copy') return 'copy';\n const environment = options.environment ?? defaultEnvironment();\n if (mode === 'auto' && !isTouchFirst(environment)) return 'copy';\n const resolved = content === undefined ? null : resolveContent(content, {});\n const data = resolved === null ? null : 'type' in resolved ? undefined : shareData(resolved);\n return data !== undefined && canShareNatively(environment, data) ? 'native' : 'copy';\n}\n\n/** The default copy: a titled link when there is a URL, otherwise the text (one of them is always set here). */\nfunction defaultCopy(content: ResolvedShare): CopyInput {\n if (content.url !== null) return linkPayload({ url: content.url, ...(content.title === null ? {} : { title: content.title }) });\n return content.text as string;\n}\n\nasync function copyContent(content: ResolvedShare, reason: CopyReason, options: ShareOptions): Promise<ShareOutcome> {\n if (options.copy === undefined && content.url === null && content.text === null) {\n return { status: 'error', method: 'copy', error: createCopyError('unsupported-format', 'Files can only be shared through a share sheet, and this browser has none for them.') };\n }\n let payload: CopyPayload;\n try {\n payload = normalizePayload((options.copy ?? defaultCopy)(content));\n } catch (error) {\n return { status: 'error', method: 'copy', error: toCopyError(error) };\n }\n const problem = validatePayload(payload);\n if (problem !== null) return { status: 'error', method: 'copy', error: problem };\n if (options.signal?.aborted === true) return { status: 'error', method: 'copy', error: createCopyError('aborted', 'The share was aborted.') };\n try {\n await (options.adapter ?? createBrowserClipboardAdapter()).write(payload, options.signal === undefined ? undefined : { signal: options.signal });\n } catch (error) {\n return { status: 'error', method: 'copy', error: toCopyError(error) };\n }\n return { status: 'copied', method: 'copy', reason, payload, content };\n}\n\n/**\n * Shares through the device's share sheet where people expect one, and copies a\n * titled link everywhere else. Call it directly in a click handler: the share\n * sheet needs the user's gesture.\n *\n * It never rejects. It resolves to `shared`, `copied` (with why), `cancelled`\n * (the user closed the share sheet: nothing to report) or `error` with a typed\n * {@link CopyError}.\n *\n * @example\n * button.addEventListener('click', async () => {\n * const outcome = await shareOrCopy({ url: location.href, title: document.title });\n * if (outcome.status === 'copied') toast('Link copied');\n * });\n */\nexport async function shareOrCopy(content: ShareContent, options: ShareOptions = {}): Promise<ShareOutcome> {\n const mode = resolveMode(options.mode);\n if (typeof mode !== 'string') return { status: 'error', method: 'copy', error: mode };\n const resolved = resolveContent(content, options);\n if ('type' in resolved) return { status: 'error', method: 'copy', error: resolved };\n const environment = options.environment ?? defaultEnvironment();\n if (mode === 'copy' || (mode === 'auto' && !isTouchFirst(environment))) return copyContent(resolved, 'preferred', options);\n const data = shareData(resolved);\n if (!canShareNatively(environment, data)) return copyContent(resolved, 'unsupported', options);\n try {\n // Called before any await: the share sheet needs the click's user activation.\n await (environment?.navigator?.share as (data: ShareData) => Promise<void>)(data);\n return { status: 'shared', method: 'native', content: resolved };\n } catch (error) {\n if (readName(error) === 'AbortError') return { status: 'cancelled', method: 'native' };\n if (options.fallback === false) return { status: 'error', method: 'native', error: shareError(error) };\n return copyContent(resolved, 'fallback', options);\n }\n}\n\nfunction readName(error: unknown): string | undefined {\n const name: unknown = typeof error === 'object' && error !== null ? (error as { name?: unknown }).name : undefined;\n return typeof name === 'string' ? name : undefined;\n}\n\n/** Classifies a share sheet failure. */\nfunction shareError(cause: unknown): CopyError {\n switch (readName(cause)) {\n case 'NotAllowedError':\n return createCopyError('permission-denied', 'The share sheet was blocked: it needs a click, and an iframe needs the web-share permission.', cause);\n case 'InvalidStateError':\n return createCopyError('unknown', 'Another share sheet is already open.', cause);\n case 'DataError':\n case 'TypeError':\n return createCopyError('unsupported-format', 'The share sheet rejected this content.', cause);\n default:\n return toCopyError(cause);\n }\n}\n\nconst SHARE_DESCRIPTIONS: Partial<Readonly<Record<CopyErrorType, string>>> = {\n 'permission-denied': \"Sharing isn't allowed here.\",\n 'unsupported-format': \"This can't be shared from this browser.\",\n timeout: 'Sharing took too long. Try again.',\n};\n\n/**\n * Default English, user-facing sentence for a failed share: a share sheet\n * failure is described as sharing, a failed copy as copying. Replace for i18n.\n */\nexport function describeShareError(error: CopyError, method: ShareMethod): string {\n if (method === 'copy') return describeCopyError(error);\n return SHARE_DESCRIPTIONS[error.type] ?? \"Couldn't share. Try again.\";\n}\n","import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { DEFAULT_RESET_AFTER_MS } from '../core/copy-machine';\nimport type { CopyError } from '../core/errors';\nimport { useIsomorphicLayoutEffect } from './utils';\nimport { shareMethod, shareOrCopy, TOUCH_FIRST, type ShareContent, type ShareMethod, type ShareOptions, type ShareOutcome } from '../share/share';\n\n/** `sharing` lasts while the share sheet is open or the copy is being written. */\nexport type ShareStatus = 'idle' | 'sharing' | 'shared' | 'copied' | 'error';\n\nexport interface UseShareOptions extends ShareOptions {\n /** Time in `shared` or `copied` before returning to `idle`. `false` keeps it. Default 2000. */\n readonly resetAfterMs?: number | false;\n /** Called with every settled outcome, including `cancelled`. */\n readonly onShare?: (outcome: ShareOutcome) => void;\n}\n\n/** What `share()` resolves to: the outcome, or `ignored` while a share is already open. */\nexport type UseShareOutcome = ShareOutcome | { readonly status: 'ignored'; readonly reason: 'in-flight' };\n\nexport interface UseShareResult {\n readonly status: ShareStatus;\n readonly error: CopyError | null;\n /** The last settled outcome; `null` before the first and after `reset()`. */\n readonly outcome: ShareOutcome | null;\n /**\n * How `share()` will share: `\"native\"` (the share sheet) or `\"copy\"`. Label the\n * button with it (\"Share…\" or \"Copy link\"). `\"copy\"` during server rendering\n * and hydration, then updated in the browser, also when the device changes.\n */\n readonly method: ShareMethod;\n /** Stable identity. Call it in a click handler. Never rejects. */\n readonly share: (content: ShareContent) => Promise<UseShareOutcome>;\n /** Stable identity. Back to `idle`; the result of a share still open is ignored. */\n readonly reset: () => void;\n}\n\ninterface State {\n readonly status: ShareStatus;\n readonly outcome: ShareOutcome | null;\n}\n\nconst IDLE: State = { status: 'idle', outcome: null };\nconst IGNORED: UseShareOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'in-flight' });\n\nfunction resetDelay(value: number | false | undefined): number | null {\n if (value === false || value === Infinity) return null;\n return value === undefined || Number.isNaN(value) ? DEFAULT_RESET_AFTER_MS : Math.max(0, value);\n}\n\nconst statusOf = (outcome: ShareOutcome): ShareStatus => (outcome.status === 'cancelled' ? 'idle' : outcome.status);\n\n/**\n * Share with the device's share sheet on phones and tablets, and copy a titled\n * link everywhere else, with honest state for the button. Options may change on\n * every render; the latest ones are always used.\n *\n * @example\n * const { share, status, method } = useShare();\n * <button onClick={() => share({ url, title })}>\n * {status === 'copied' ? 'Link copied' : method === 'native' ? 'Share…' : 'Copy link'}\n * </button>\n */\nexport function useShare(options: UseShareOptions = {}): UseShareResult {\n const optionsRef = useRef(options);\n useIsomorphicLayoutEffect(() => {\n optionsRef.current = options;\n });\n\n const [state, setState] = useState<State>(IDLE);\n const mounted = useRef(false);\n const inFlight = useRef(false);\n const generation = useRef(0);\n const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n generation.current += 1;\n clearTimeout(timer.current);\n };\n }, []);\n\n const subscribe = useCallback((onChange: () => void) => {\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return () => undefined;\n const list = window.matchMedia(TOUCH_FIRST);\n list.addEventListener('change', onChange);\n return () => {\n list.removeEventListener('change', onChange);\n };\n }, []);\n const method = useSyncExternalStore(\n subscribe,\n () => shareMethod(optionsRef.current),\n (): ShareMethod => 'copy',\n );\n\n const share = useCallback(async (content: ShareContent): Promise<UseShareOutcome> => {\n if (inFlight.current) return IGNORED;\n inFlight.current = true;\n const current = (generation.current += 1);\n clearTimeout(timer.current);\n setState({ status: 'sharing', outcome: null });\n // No await before this call: the share sheet needs the click's user activation.\n const outcome = await shareOrCopy(content, optionsRef.current);\n inFlight.current = false;\n if (!mounted.current || current !== generation.current) return outcome;\n setState({ status: statusOf(outcome), outcome });\n const delay = resetDelay(optionsRef.current.resetAfterMs);\n if ((outcome.status === 'shared' || outcome.status === 'copied') && delay !== null) {\n timer.current = setTimeout(() => {\n setState(IDLE);\n }, delay);\n }\n optionsRef.current.onShare?.(outcome);\n return outcome;\n }, []);\n\n const reset = useCallback(() => {\n generation.current += 1;\n clearTimeout(timer.current);\n setState(IDLE);\n }, []);\n\n return useMemo(\n () => ({\n status: state.status,\n error: state.outcome?.status === 'error' ? state.outcome.error : null,\n outcome: state.outcome,\n method,\n share,\n reset,\n }),\n [state, method, share, reset],\n );\n}\n"],"mappings":";;;;;AA8CA,SAAgB,gBAAgB,MAAqB,SAAiB,OAA4B;CAChG,OAAO,UAAU,KAAA,IAAY;EAAE;EAAM;CAAQ,IAAI;EAAE;EAAM;EAAS;CAAM;AAC1E;AAEA,MAAM,mCAA+D,IAAI,IAAmB;CAC1F;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,iBAAiB,OAA2B;CAC1D,OAAO,iBAAiB,IAAI,MAAM,IAAI;AACxC;;;;;AAMA,MAAM,qBAAqB,OAAO,IAAI,8BAA8B;;AAGpE,IAAa,cAAb,cAAiC,MAAM;CAIrC,YAAY,WAAsB;EAChC,MAAM,UAAU,OAAO;EAHzB,KAAU,sBAAsB;EAI9B,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF;AAEA,SAAgB,cAAc,OAAsC;CAClE,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAuC,wBAAwB;AAEpE;;AAGA,SAAgB,YAAY,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A;EAAC;EAAO;EAAQ;EAAO;CAAK,CAC9B;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["invalid","defaultEnvironment","IGNORED_IN_FLIGHT","IGNORED_NOTHING","IGNORED_NOT_RETRYABLE","IGNORED_CANCELLED","resolveResetDelay","defaultAdapter","getDefaultAdapter","nonEmpty","invalid","unsupported","invalid","defaultEnvironment","useState","useContext","useEffect","useLayoutEffect","getServerSnapshot","useRef","useState","useSyncExternalStore","useMemo","useRef","useState","getServerSnapshot","useRef","useCallback","useSyncExternalStore","useState","useRef","useMemo","useState","useRef","useContext","Root","useId","useMemo","useCallback","Label","DEFAULT_TRIGGER_TEXT","Trigger","useRef","useState","useSyncExternalStore","useMemo","useState","useContext","useId","useMemo","useCallback","useState","useRef","useState","useCallback","invalid","invalid","useRef","useState","useCallback","useSyncExternalStore","useMemo"],"sources":["../src/core/errors.ts","../src/core/payload.ts","../src/core/mime.ts","../src/core/clipboard-adapter.ts","../src/core/copy-coordinator.ts","../src/core/machine-shared.ts","../src/core/source-error.ts","../src/core/copy-machine.ts","../src/core/copy-interceptor.ts","../src/core/drag-copy.ts","../src/core/paste-reader.ts","../src/core/paste-adapter.ts","../src/core/paste-machine.ts","../src/react/CopyGroup.tsx","../src/react/utils.ts","../src/react/useCopy.ts","../src/react/useCopyInterceptor.ts","../src/react/useMediaQuery.ts","../src/react/useRevealOnInteraction.ts","../src/react/useDisplayStatus.ts","../src/react/LiveRegion.tsx","../src/react/TriggerLabel.tsx","../src/react/CopyField.tsx","../src/react/usePaste.ts","../src/react/usePasteDisplayStatus.ts","../src/react/PasteField.tsx","../src/react/useDragCopy.ts","../src/link/url.ts","../src/link/payload.ts","../src/share/share.ts","../src/react/useShare.ts"],"sourcesContent":["import type { PasteSource } from './paste-reader';\n\n/**\n * Every way a clipboard operation can fail, as a closed union.\n *\n * `CopyError.message` is developer-facing (logs, telemetry). For user-facing\n * text use {@link describeCopyError} / {@link describePasteError}, or map\n * `type` through your own i18n layer.\n */\nexport type CopyErrorType =\n /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */\n | 'unsupported'\n /** Page is not served over HTTPS/localhost. Not retryable. */\n | 'insecure-context'\n /** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */\n | 'permission-denied'\n /** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */\n | 'not-focused'\n /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */\n | 'invalid-payload'\n /** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */\n | 'unsupported-format'\n /** A lazy image source (or capture) threw, rejected or did not produce a Blob. */\n | 'blob-generation-failed'\n /** `retry()` was called after `maxRetries` was reached. Terminal. */\n | 'max-retries-exceeded'\n /** Paste: the clipboard held nothing matching `accept`. */\n | 'no-content'\n /** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */\n | 'too-large'\n /** An operation did not settle within its deadline. Retryable. */\n | 'timeout'\n /** The caller aborted the operation through an `AbortSignal`. Not retryable. */\n | 'aborted'\n /** Anything the platform threw that we could not classify. */\n | 'unknown';\n\n/** Which clipboard direction failed; only changes developer-facing messages. */\nexport type ClipboardOperation = 'write' | 'read';\n\nexport interface CopyError {\n readonly type: CopyErrorType;\n readonly message: string;\n readonly cause?: unknown;\n}\n\nexport function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError {\n return cause === undefined ? { type, message } : { type, message, cause };\n}\n\nconst RETRYABLE_ERRORS: ReadonlySet<CopyErrorType> = /* @__PURE__ */ new Set<CopyErrorType>([\n 'permission-denied',\n 'not-focused',\n 'blob-generation-failed',\n 'timeout',\n 'unknown',\n]);\n\n/** Whether retrying the same payload could plausibly succeed. */\nexport function isRetryableError(error: CopyError): boolean {\n return RETRYABLE_ERRORS.has(error.type);\n}\n\n/**\n * Branded (not `instanceof`) so failures stay recognisable even when the core\n * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.\n */\nconst COPY_FAILURE_BRAND = Symbol.for('react-smart-copy.CopyFailure');\n\n/** Error thrown by adapters to carry a fully classified {@link CopyError}. */\nexport class CopyFailure extends Error {\n readonly copyError: CopyError;\n readonly [COPY_FAILURE_BRAND] = true;\n\n constructor(copyError: CopyError) {\n super(copyError.message);\n this.name = 'CopyFailure';\n this.copyError = copyError;\n }\n}\n\nexport function isCopyFailure(value: unknown): value is CopyFailure {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[COPY_FAILURE_BRAND] === true\n );\n}\n\n/** Shorthand for throwing a classified failure. */\nexport function copyFailure(type: CopyErrorType, message: string, cause?: unknown): CopyFailure {\n return new CopyFailure(createCopyError(type, message, cause));\n}\n\nfunction readString(value: unknown, key: string): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const field = (value as Record<string, unknown>)[key];\n return typeof field === 'string' ? field : undefined;\n}\n\n/**\n * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.\n * `operation` only tailors the developer-facing message.\n */\nexport function toCopyError(cause: unknown, operation: ClipboardOperation = 'write'): CopyError {\n if (isCopyFailure(cause)) return cause.copyError;\n\n const name = readString(cause, 'name');\n const message = readString(cause, 'message') ?? '';\n const verb = operation === 'read' ? 'read' : 'write';\n\n switch (name) {\n case 'NotAllowedError':\n return /focus/i.test(message)\n ? createCopyError('not-focused', `The document was not focused during the clipboard ${verb}.`, cause)\n : createCopyError('permission-denied', `Clipboard ${verb} permission was denied.`, cause);\n case 'SecurityError':\n return createCopyError('insecure-context', 'The clipboard is blocked in this context.', cause);\n case 'NotSupportedError':\n case 'DataError':\n return createCopyError('unsupported-format', 'The browser rejected this clipboard format.', cause);\n case 'AbortError':\n return createCopyError('aborted', `The clipboard ${verb} was aborted.`, cause);\n case 'TimeoutError':\n return createCopyError('timeout', `The clipboard ${verb} timed out.`, cause);\n default:\n return createCopyError('unknown', message || `The clipboard ${verb} failed for an unknown reason.`, cause);\n }\n}\n\nconst COPY_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Copying isn't supported in this browser.\",\n 'insecure-context': 'Copying requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while copying. Try again.',\n 'invalid-payload': 'There is nothing to copy.',\n 'unsupported-format': \"This content can't be copied in this browser.\",\n 'blob-generation-failed': \"The image couldn't be prepared for copying.\",\n 'max-retries-exceeded': 'Copying failed after several attempts.',\n 'no-content': 'There is nothing to copy.',\n 'too-large': 'This content is too large to copy.',\n timeout: 'Copying took too long. Try again.',\n aborted: 'Copying was cancelled.',\n unknown: \"Couldn't copy to the clipboard. Try again.\",\n};\n\nconst PASTE_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Pasting isn't supported in this browser.\",\n 'insecure-context': 'Pasting requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while pasting. Try again.',\n 'invalid-payload': \"The clipboard content couldn't be read.\",\n 'unsupported-format': \"This clipboard content isn't supported here.\",\n 'blob-generation-failed': \"The pasted image couldn't be read.\",\n 'max-retries-exceeded': 'Pasting failed after several attempts.',\n 'no-content': \"The clipboard doesn't contain anything that can be pasted here.\",\n 'too-large': 'The clipboard content is too large to paste.',\n timeout: 'Pasting took too long. Try again.',\n aborted: 'Pasting was cancelled.',\n unknown: \"Couldn't read the clipboard. Try again.\",\n};\n\n/** Default English, user-facing sentence for a copy error. Replace for i18n. */\nexport function describeCopyError(error: CopyError): string {\n return COPY_DESCRIPTIONS[error.type];\n}\n\n/** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */\nconst DROP_DESCRIPTIONS: Readonly<Partial<Record<CopyErrorType, string>>> = {\n 'invalid-payload': \"The dropped content couldn't be read.\",\n 'no-content': 'Nothing that was dropped can be used here.',\n 'too-large': 'The dropped content is too large.',\n unknown: \"Couldn't read the dropped content. Try again.\",\n};\n\n/**\n * Default English, user-facing sentence for a paste error. Pass the error\n * state's `source` to word drag-and-drop failures as drops. Replace for i18n.\n */\nexport function describePasteError(error: CopyError, source?: PasteSource): string {\n return (source === 'drop' ? DROP_DESCRIPTIONS[error.type] : undefined) ?? PASTE_DESCRIPTIONS[error.type];\n}\n","import { CopyFailure, createCopyError, type CopyError } from './errors';\nimport type { OperationContext } from './machine-shared';\n\n/** The only image MIME type with reliable cross-browser clipboard write support. */\nexport const IMAGE_MIME_TYPE = 'image/png';\n\n/**\n * An image as a Blob, a promise of one, or a function producing one.\n * Prefer the function form: it is invoked synchronously inside the user\n * gesture, which Safari requires for async image generation. The browser\n * adapter always passes an `OperationContext`: stop work once\n * `context.signal` aborts (reset, superseded, unmount). Optional in the type\n * so adapters that call sources themselves keep compiling.\n */\nexport type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);\n\nexport interface TextPayload {\n readonly kind: 'text';\n readonly value: string;\n}\n\nexport interface HtmlPayload {\n readonly kind: 'html';\n readonly html: string;\n /** Required plain-text fallback for targets that don't understand HTML. */\n readonly text: string;\n}\n\nexport interface ImagePayload {\n readonly kind: 'image';\n readonly blob: BlobSource;\n}\n\nexport interface JsonPayload {\n readonly kind: 'json';\n readonly value: unknown;\n /** `true` = 2-space indent, a number = that indent, falsy = compact. */\n readonly pretty?: boolean | number;\n}\n\nexport interface MultiPayloadItem {\n /**\n * The MIME type, or a web custom format (`web application/vnd.acme+json`).\n * Web custom formats are only written by the async Clipboard API; copy and drag\n * events skip them.\n */\n readonly mimeType: string;\n readonly data: string | Blob;\n /**\n * Skip this item, instead of failing the copy, when the browser cannot write its type.\n * An optional item is only written when `ClipboardItem.supports()` confirms the type.\n * At least one item must be written.\n */\n readonly optional?: boolean;\n}\n\nexport interface MultiPayload {\n readonly kind: 'multi';\n readonly items: readonly MultiPayloadItem[];\n}\n\nexport type CopyPayload = TextPayload | HtmlPayload | ImagePayload | JsonPayload | MultiPayload;\nexport type CopyPayloadKind = CopyPayload['kind'];\n\n/** A payload, or a bare string as shorthand for `{ kind: 'text' }`. */\nexport type CopyInput = string | CopyPayload;\n\n/**\n * What `copy()` accepts. The function form is resolved synchronously at copy\n * time, so it always reads the latest value without re-rendering.\n */\nexport type CopySource = CopyInput | (() => CopyInput);\n\nexport function normalizePayload(input: CopyInput): CopyPayload {\n return typeof input === 'string' ? { kind: 'text', value: input } : input;\n}\n\nexport function isBlob(value: unknown): value is Blob {\n if (typeof Blob !== 'undefined' && value instanceof Blob) return true;\n const tag = Object.prototype.toString.call(value);\n return tag === '[object Blob]' || tag === '[object File]';\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' || typeof value === 'function') &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\nconst invalid = (message: string): CopyError => createCopyError('invalid-payload', message);\n\n/**\n * Structural validation. Typed callers can't produce most of these states,\n * but plain-JS callers and runtime data can, so the check is always on.\n */\nexport function validatePayload(payload: unknown): CopyError | null {\n if (typeof payload !== 'object' || payload === null) {\n return invalid('Copy input must be a string or a payload object.');\n }\n const candidate = payload as Record<string, unknown>;\n\n switch (candidate['kind']) {\n case 'text':\n return typeof candidate['value'] === 'string' && candidate['value'].length > 0\n ? null\n : invalid('Text payload must be a non-empty string.');\n case 'html':\n if (typeof candidate['html'] !== 'string' || candidate['html'].length === 0) {\n return invalid('HTML payload requires a non-empty `html` string.');\n }\n return typeof candidate['text'] === 'string' && candidate['text'].length > 0\n ? null\n : invalid('HTML payload requires a non-empty plain-text `text` fallback.');\n case 'image': {\n const source = candidate['blob'];\n return isBlob(source) || typeof source === 'function' || isThenable(source)\n ? null\n : invalid('Image payload requires a Blob, a Promise<Blob> or a function returning one.');\n }\n case 'json':\n return candidate['value'] === undefined ? invalid('JSON payload value is undefined.') : null;\n case 'multi': {\n const items = candidate['items'];\n if (!Array.isArray(items) || items.length === 0) {\n return invalid('Multi payload requires at least one item.');\n }\n const seen = new Set<string>();\n for (const item of items as unknown[]) {\n const entry = (typeof item === 'object' && item !== null ? item : {}) as Record<string, unknown>;\n const mimeType = entry['mimeType'];\n const data = entry['data'];\n if (typeof mimeType !== 'string' || mimeType.length === 0) {\n return invalid('Every multi item needs a non-empty `mimeType`.');\n }\n if (seen.has(mimeType)) return invalid(`Duplicate MIME type \"${mimeType}\" in multi payload.`);\n seen.add(mimeType);\n if (typeof data !== 'string' && !isBlob(data)) {\n return invalid(`Multi item \"${mimeType}\" must contain a string or a Blob.`);\n }\n }\n return null;\n }\n default:\n return invalid(`Unknown payload kind: ${String(candidate['kind'])}.`);\n }\n}\n\n/** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */\nexport function serializeJson(payload: JsonPayload): string {\n const indent =\n payload.pretty === true ? 2 : typeof payload.pretty === 'number' ? payload.pretty : undefined;\n // Typed as `string` by lib.d.ts, but returns undefined for functions, symbols and undefined.\n let text: unknown;\n try {\n text = JSON.stringify(payload.value, null, indent);\n } catch (cause) {\n throw new CopyFailure(\n createCopyError('invalid-payload', 'JSON payload could not be serialised (circular reference or BigInt?).', cause),\n );\n }\n if (typeof text !== 'string') {\n throw new CopyFailure(\n createCopyError('invalid-payload', 'JSON payload serialised to nothing (functions, symbols and undefined are not JSON).'),\n );\n }\n return text;\n}\n","/**\n * MIME helpers shared by paste and capture. Everything that comes from the\n * clipboard is untrusted input, so types are normalised and validated before\n * they are compared, and image types are confirmed from the bytes themselves.\n */\n\n/** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */\nconst MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\n/** SVG is XML that can carry scripts; it is never matched by a wildcard. */\nexport const SVG_MIME_TYPE = 'image/svg+xml';\n\n/** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */\nexport function normalizeMimeType(value: string): string | null {\n const separator = value.indexOf(';');\n const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();\n return MIME_SHAPE.test(base) ? base : null;\n}\n\n/** Prefix of the async Clipboard API's web custom formats (`web application/vnd.acme+json`). */\nexport const WEB_CUSTOM_FORMAT_PREFIX = 'web ';\n\n/** Whether a clipboard type is a web custom format (`web type/subtype`). */\nexport function isWebCustomFormat(type: string): boolean {\n return type.slice(0, 4).toLowerCase() === WEB_CUSTOM_FORMAT_PREFIX;\n}\n\n/**\n * Like {@link normalizeMimeType}, but also accepts web custom formats\n * (`web type/subtype`), returned as `web ` + the normalised MIME type.\n */\nexport function normalizeClipboardType(value: string): string | null {\n if (!isWebCustomFormat(value)) return normalizeMimeType(value);\n const inner = normalizeMimeType(value.slice(4));\n return inner === null ? null : WEB_CUSTOM_FORMAT_PREFIX + inner;\n}\n\n/**\n * Types a wildcard never matches, so accepting them must be explicit:\n * `image/svg+xml` (scriptable XML), web custom formats and structured `+json` types\n * (application-specific data that only the app that defined them should read).\n */\nfunction requiresExactMatch(mimeType: string): boolean {\n return mimeType === SVG_MIME_TYPE || isWebCustomFormat(mimeType) || mimeType.endsWith('+json');\n}\n\n/**\n * Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\\/*`)?\n * Wildcards never match `image/svg+xml`, web custom formats or `+json` types: those must be listed exactly.\n */\nexport function matchesMimePattern(mimeType: string, pattern: string): boolean {\n if (pattern === mimeType) return true;\n if (requiresExactMatch(mimeType)) return false;\n if (pattern === '*/*') return true;\n return pattern.endsWith('/*') && mimeType.startsWith(pattern.slice(0, -1));\n}\n\n/** Types whose clipboard data is text and is therefore surfaced as a `string`. */\nexport function isTextualMimeType(mimeType: string): boolean {\n const type = isWebCustomFormat(mimeType) ? mimeType.slice(4) : mimeType;\n return (\n type.startsWith('text/') ||\n type === SVG_MIME_TYPE ||\n type === 'application/json' ||\n type === 'application/xml' ||\n type.endsWith('+json')\n );\n}\n\n/** Raster image formats recognised from their leading bytes. */\nexport type RasterImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/bmp' | 'image/avif';\n\nconst SNIFF_BYTES = 16;\n\nfunction startsWith(bytes: Uint8Array, signature: readonly number[], offset = 0): boolean {\n return signature.every((byte, index) => bytes[offset + index] === byte);\n}\n\nconst ascii = (text: string): number[] => Array.from(text, (char) => char.charCodeAt(0));\n\nconst PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\nconst JPEG = [0xff, 0xd8, 0xff];\nconst GIF = ascii('GIF8');\nconst RIFF = ascii('RIFF');\nconst WEBP = ascii('WEBP');\nconst BMP = ascii('BM');\nconst FTYP_AVIF = ascii('ftypavif');\nconst FTYP_AVIS = ascii('ftypavis');\n\n/** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */\nexport function sniffImageBytes(bytes: Uint8Array): RasterImageMimeType | null {\n if (startsWith(bytes, PNG)) return 'image/png';\n if (startsWith(bytes, JPEG)) return 'image/jpeg';\n if (startsWith(bytes, GIF)) return 'image/gif';\n if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return 'image/webp';\n if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return 'image/avif';\n if (startsWith(bytes, BMP)) return 'image/bmp';\n return null;\n}\n\n/** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */\nexport async function sniffImageType(blob: Blob): Promise<RasterImageMimeType | null> {\n const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();\n return sniffImageBytes(new Uint8Array(head));\n}\n","import { CopyFailure, createCopyError, type CopyErrorType } from './errors';\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 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\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\nfunction writeText(clipboard: ClipboardLike, text: string): Promise<void> {\n if (typeof clipboard.writeText !== 'function') {\n throw fail('unsupported', 'navigator.clipboard.writeText() is not available.');\n }\n return clipboard.writeText(text);\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 degradeHtmlToText: boolean,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!env) throw fail('unsupported', 'No browser environment: the clipboard only exists in the browser.');\n if (env.isSecureContext === false) {\n throw fail('insecure-context', 'The Clipboard API requires a secure context (HTTPS or localhost).');\n }\n const clipboard = env.navigator?.clipboard;\n if (!clipboard) throw fail('unsupported', 'navigator.clipboard is not available in this browser.');\n\n switch (payload.kind) {\n case 'text':\n return writeText(clipboard, payload.value);\n\n case 'json':\n return writeText(clipboard, serializeJson(payload));\n\n case 'html': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich || !isTypeSupported(rich.Item, 'text/html')) {\n if (degradeHtmlToText) return writeText(clipboard, payload.text);\n throw fail('unsupported-format', 'Rich HTML copy requires ClipboardItem and navigator.clipboard.write().');\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) throw fail('unsupported-format', 'Multi-format copy requires ClipboardItem and navigator.clipboard.write().');\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 degradeHtmlToText = options.degradeHtmlToText ?? true;\n return {\n write: (payload, context) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText, context),\n };\n}\n","/**\n * A copy machine as seen by a coordinator. `release()` returns it from\n * `copied` to `idle`; it is a no-op in any other state.\n */\nexport interface CopyCoordinatorMember {\n readonly release: () => void;\n}\n\n/**\n * Makes a set of copy machines behave like one clipboard: when a member\n * succeeds, the member that previously showed \"Copied\" goes back to idle,\n * because the clipboard no longer holds its value.\n *\n * Failed copies never release anyone (the clipboard still holds the previous value).\n */\nexport interface CopyCoordinator {\n /** A member just reached `copied`. Releases the previous one. */\n readonly activate: (member: CopyCoordinatorMember) => void;\n /** A member left `copied` on its own (auto-reset, reset, unmount). */\n readonly deactivate: (member: CopyCoordinatorMember) => void;\n /** The member currently showing `copied`, if any. */\n readonly getActive: () => CopyCoordinatorMember | null;\n}\n\nexport function createCopyCoordinator(): CopyCoordinator {\n let active: CopyCoordinatorMember | null = null;\n return {\n activate: (member) => {\n const previous = active;\n active = member;\n if (previous !== null && previous !== member) previous.release();\n },\n deactivate: (member) => {\n if (active === member) active = null;\n },\n getActive: () => active,\n };\n}\n","/**\n * Internals shared by the copy and paste state machines. Kept in one module so\n * apps that use both don't ship two copies.\n */\n\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * Passed to adapters and lazy sources as their last argument. `signal` aborts\n * when the operation is superseded, `reset()`, or its host unmounts, so\n * expensive work (rasterising, decoding) can stop early.\n */\nexport interface OperationContext {\n readonly signal: AbortSignal;\n}\n\nexport function resolveMaxRetries(value: number | undefined): number {\n if (value === Infinity) return Infinity;\n if (value === undefined || !Number.isFinite(value)) return DEFAULT_MAX_RETRIES;\n return Math.max(0, Math.floor(value));\n}\n\nfunction reportCallbackError(error: unknown): void {\n const scope = globalThis as { reportError?: (error: unknown) => void };\n if (typeof scope.reportError === 'function') {\n scope.reportError(error);\n } else {\n setTimeout(() => {\n throw error;\n }, 0);\n }\n}\n\n/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */\nexport function invoke<Args extends unknown[]>(fn: ((...args: Args) => void) | undefined, ...args: Args): void {\n if (!fn) return;\n try {\n fn(...args);\n } catch (error) {\n reportCallbackError(error);\n }\n}\n\nexport interface Operations {\n /** Aborts the operation in flight (if any) and starts a new one. */\n readonly start: () => OperationContext;\n /** Marks `context` finished, so a later `abort()` never fires its signal. */\n readonly end: (context: OperationContext) => void;\n /** Cancels the operation in flight, if any. Returns whether one was cancelled. */\n readonly abort: () => boolean;\n}\n\n/** One cancellable operation at a time. Signals only fire while their operation is unfinished. */\nexport function createOperations(): Operations {\n let controller: AbortController | undefined;\n const abort = (): boolean => {\n if (!controller) return false;\n controller.abort();\n controller = undefined;\n return true;\n };\n return {\n start: () => {\n abort();\n controller = new AbortController();\n return { signal: controller.signal };\n },\n end: (context) => {\n if (controller?.signal === context.signal) controller = undefined;\n },\n abort,\n };\n}\n","import { createCopyError, isCopyFailure, type CopyError } from './errors';\n\n/**\n * The error for a user-supplied source (copy source, drag source, copy transform)\n * that threw. A thrown `CopyFailure` keeps its classification, so a helper such as\n * `tablePayload()` can report `too-large` instead of a generic `invalid-payload`.\n * Internal: not part of the public API.\n */\nexport function sourceError(cause: unknown, message: string): CopyError {\n return isCopyFailure(cause) ? cause.copyError : createCopyError('invalid-payload', message, cause);\n}\n","import { createBrowserClipboardAdapter, type ClipboardAdapter } from './clipboard-adapter';\nimport type { CopyCoordinator, CopyCoordinatorMember } from './copy-coordinator';\nimport { createCopyError, isRetryableError, toCopyError, type CopyError } from './errors';\nimport { createOperations, invoke, resolveMaxRetries } from './machine-shared';\nimport { normalizePayload, validatePayload, type CopyPayload, type CopySource } from './payload';\nimport { sourceError } from './source-error';\n\nexport { DEFAULT_MAX_RETRIES, resolveMaxRetries } from './machine-shared';\n\nexport const DEFAULT_RESET_AFTER_MS = 2000;\n\nexport interface IdleState {\n readonly status: 'idle';\n}\nexport interface CopyingState {\n readonly status: 'copying';\n readonly payload: CopyPayload;\n readonly retryCount: number;\n}\nexport interface CopiedState {\n readonly status: 'copied';\n readonly payload: CopyPayload;\n /** Epoch ms when the write resolved. */\n readonly at: number;\n}\nexport interface ErrorState {\n readonly status: 'error';\n /** `null` when the input itself could not be resolved. */\n readonly payload: CopyPayload | null;\n readonly error: CopyError;\n readonly retryCount: number;\n}\n\nexport type CopyState = IdleState | CopyingState | CopiedState | ErrorState;\nexport type CopyStatus = CopyState['status'];\n\n/**\n * `cancelled`: the copy was reset or its host unmounted before it finished,\n * so its work was aborted. Nothing to report to the user.\n */\nexport type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';\n\n/**\n * Why an in-flight copy was cancelled: `reset` (`reset()` was called) or\n * `disconnect` (its host disconnected, e.g. the React component unmounted).\n */\nexport type CopyCancelReason = 'reset' | 'disconnect';\n\n/** What `copy()`/`retry()` resolve to. They never reject. */\nexport type CopyOutcome =\n | { readonly status: 'copied'; readonly payload: CopyPayload }\n | { readonly status: 'error'; readonly error: CopyError }\n | { readonly status: 'ignored'; readonly reason: CopyIgnoredReason };\n\nexport interface CopyMachineOptions {\n /** Defaults to the browser Clipboard API adapter. */\n readonly adapter?: ClipboardAdapter;\n /** Time in `copied` before returning to `idle`. `false`/`Infinity` disables. Default 2000. */\n readonly resetAfterMs?: number | false;\n /**\n * Max `retry()` calls after the first failure. Default 3. `0` disables\n * retry; `Infinity` allows unlimited retries.\n */\n readonly maxRetries?: number;\n /**\n * Share \"Copied\" with other machines: only one member of a coordinator\n * shows `copied` at a time. `null` explicitly opts out (e.g. of a React `<CopyGroup>`).\n */\n readonly coordinator?: CopyCoordinator | null;\n readonly onCopy?: (payload: CopyPayload) => void;\n readonly onError?: (error: CopyError, payload: CopyPayload | null) => void;\n /**\n * `reset()` moved the machine back to `idle` from any other state. Not\n * called for the automatic return after `resetAfterMs`, for a `<CopyGroup>`\n * handing \"Copied\" to another member, or when already `idle`.\n */\n readonly onReset?: () => void;\n /**\n * A copy in flight was cancelled before it settled: its `signal` aborted\n * and its result will not reach state or `onCopy` / `onError`. Fires\n * before `onReset` when `reset()` cancels a copy.\n */\n readonly onCancel?: (reason: CopyCancelReason) => void;\n /** Clock injection for tests and deterministic environments. */\n readonly now?: () => number;\n}\n\n/** Options object, or a getter so hosts (like React) can supply the latest options. */\nexport type CopyMachineOptionsSource = CopyMachineOptions | (() => CopyMachineOptions);\n\nexport interface CopyMachine {\n readonly getSnapshot: () => CopyState;\n readonly subscribe: (listener: () => void) => () => void;\n readonly copy: (source: CopySource) => Promise<CopyOutcome>;\n readonly retry: () => Promise<CopyOutcome>;\n /** Back to `idle`. Discards any in-flight result and aborts its `signal`. */\n readonly reset: () => void;\n /**\n * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned\n * cleanup clears timers, drops in-flight results, aborts in-flight work and\n * unsticks `copying`.\n * Safe to call repeatedly (React StrictMode).\n */\n readonly connect: () => () => void;\n}\n\nexport const IDLE_STATE: IdleState = /* @__PURE__ */ Object.freeze({ status: 'idle' });\n\nconst IGNORED_IN_FLIGHT: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'in-flight' });\nconst IGNORED_NOTHING: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'nothing-to-retry' });\nconst IGNORED_NOT_RETRYABLE: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'not-retryable' });\nconst IGNORED_CANCELLED: CopyOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'cancelled' });\n\nfunction resolveResetDelay(value: number | false | undefined): number | null {\n if (value === false || value === Infinity) return null;\n if (value === undefined || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;\n return Math.max(0, value);\n}\n\n/** Pure helper: can `retry()` do anything from this state? */\nexport function canRetryState(state: CopyState, maxRetries?: number): boolean {\n return (\n state.status === 'error' &&\n state.payload !== null &&\n isRetryableError(state.error) &&\n state.retryCount < resolveMaxRetries(maxRetries)\n );\n}\n\nlet defaultAdapter: ClipboardAdapter | undefined;\nconst getDefaultAdapter = (): ClipboardAdapter => (defaultAdapter ??= createBrowserClipboardAdapter());\n\n/** Framework-agnostic copy state machine. */\nexport function createCopyMachine(options: CopyMachineOptionsSource = {}): CopyMachine {\n const read = typeof options === 'function' ? options : (): CopyMachineOptions => options;\n const listeners = new Set<() => void>();\n let state: CopyState = IDLE_STATE;\n let generation = 0;\n let resetTimer: ReturnType<typeof setTimeout> | undefined;\n const operations = createOperations();\n\n const now = (): number => (read().now ?? Date.now)();\n\n // The coordinator that saw this machine's last `copied`, so leaving it is reported to the same one.\n let joined: CopyCoordinator | null = null;\n\n const member: CopyCoordinatorMember = {\n release: () => {\n if (state.status === 'copied') {\n clearResetTimer();\n setState(IDLE_STATE);\n }\n },\n };\n\n const setState = (next: CopyState): void => {\n if (next === state) return;\n const previous = state;\n state = next;\n if (previous.status === 'copied' && next.status !== 'copied' && joined) {\n joined.deactivate(member);\n joined = null;\n }\n for (const listener of Array.from(listeners)) listener();\n };\n\n const joinCoordinator = (): void => {\n joined = read().coordinator ?? null;\n joined?.activate(member);\n };\n\n const clearResetTimer = (): void => {\n if (resetTimer !== undefined) {\n clearTimeout(resetTimer);\n resetTimer = undefined;\n }\n };\n\n const scheduleReset = (copied: CopiedState): void => {\n clearResetTimer();\n const delay = resolveResetDelay(read().resetAfterMs);\n if (delay === null) return;\n const remaining = Math.max(0, delay - (now() - copied.at));\n // Invariant: every transition out of `copied` clears this timer, so it only ever fires while still in `copied`.\n resetTimer = setTimeout(() => {\n resetTimer = undefined;\n setState(IDLE_STATE);\n }, remaining);\n };\n\n const settleError = (error: CopyError, payload: CopyPayload | null, retryCount: number): void => {\n setState({ status: 'error', payload, error, retryCount });\n invoke(read().onError, error, payload);\n };\n\n const run = (source: CopySource, retryCount: number): Promise<CopyOutcome> => {\n clearResetTimer();\n const current = ++generation;\n\n let payload: CopyPayload;\n try {\n const resolved = typeof source === 'function' ? source() : source;\n // T1: the source function must be synchronous — async sources break the\n // browser's transient user-activation window. Detect and reject a Promise\n // return rather than letting it propagate as a malformed payload (a\n // thenable is not a valid CopyInput, so validatePayload would catch it,\n // but a clear error message is more useful).\n // Cast to `unknown` first so the thenable check compiles without the\n // \"no overlap\" lint error (the TS type already narrows `resolved` to\n // `CopyInput`, which excludes thenables, but JS callers can still pass one).\n const resolvedUnknown: unknown = resolved;\n if (\n resolvedUnknown !== null &&\n typeof resolvedUnknown === 'object' &&\n typeof (resolvedUnknown as { then?: unknown }).then === 'function'\n ) {\n const error = createCopyError(\n 'invalid-payload',\n 'The copy source function must be synchronous. ' +\n 'Returning a Promise breaks the user-gesture window required for clipboard writes. ' +\n 'Generate your content before calling copy().',\n );\n settleError(error, null, retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n payload = normalizePayload(resolved);\n } catch (cause) {\n const error = sourceError(cause, 'The copy source function threw.');\n settleError(error, null, retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n\n const invalid = validatePayload(payload);\n if (invalid) {\n settleError(invalid, payload, retryCount);\n return Promise.resolve({ status: 'error', error: invalid });\n }\n\n setState({ status: 'copying', payload, retryCount });\n const context = operations.start();\n\n // The adapter is called synchronously: no await may precede it, or the\n // browser loses the transient user activation and rejects the write.\n let pending: Promise<void>;\n try {\n pending = (read().adapter ?? getDefaultAdapter()).write(payload, context);\n } catch (cause) {\n // Keep the raw reason: toCopyError() classifies it (DOMException names, CopyFailure brand).\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified by toCopyError()\n pending = Promise.reject(cause);\n }\n\n return pending.then(\n (): CopyOutcome => {\n operations.end(context);\n if (current === generation) {\n const copied: CopiedState = { status: 'copied', payload, at: now() };\n setState(copied);\n joinCoordinator();\n scheduleReset(copied);\n invoke(read().onCopy, payload);\n }\n return { status: 'copied', payload };\n },\n (cause: unknown): CopyOutcome => {\n operations.end(context);\n // Work we aborted ourselves (reset, unmount) is not a failure to report.\n // Invariant: superseding an in-flight copy always aborts it, so past\n // this line the copy is still the current one.\n if (context.signal.aborted) return IGNORED_CANCELLED;\n const error = toCopyError(cause);\n settleError(error, payload, retryCount);\n return { status: 'error', error };\n },\n );\n };\n\n const copy = (source: CopySource): Promise<CopyOutcome> =>\n state.status === 'copying' ? Promise.resolve(IGNORED_IN_FLIGHT) : run(source, 0);\n\n const retry = (): Promise<CopyOutcome> => {\n if (state.status !== 'error') return Promise.resolve(IGNORED_NOTHING);\n if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);\n\n if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {\n const error = createCopyError(\n 'max-retries-exceeded',\n `Copy failed after ${String(state.retryCount)} retries.`,\n state.error,\n );\n settleError(error, state.payload, state.retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n return run(state.payload, state.retryCount + 1);\n };\n\n const reset = (): void => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n const wasIdle = state.status === 'idle';\n setState(IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'reset');\n if (!wasIdle) invoke(read().onReset);\n };\n\n const connect = (): (() => void) => {\n if (state.status === 'copied') scheduleReset(state);\n return () => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n if (state.status === 'copying') setState(IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'disconnect');\n };\n };\n\n return {\n getSnapshot: () => state,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n copy,\n retry,\n reset,\n connect,\n };\n}\n","import { createCopyError, type CopyError } from './errors';\nimport { invoke } from './machine-shared';\nimport { isWebCustomFormat } from './mime';\nimport type { HtmlPayload, JsonPayload, TextPayload } from './payload';\nimport { sourceError } from './source-error';\n\n/**\n * Native copy interception: rewrite, redact or block what lands on the\n * clipboard when the user copies (Ctrl/Cmd+C, context menu) or cuts inside a\n * scope.\n *\n * Writes go through `event.clipboardData` synchronously, so no permission\n * prompt, no secure-context requirement, and it works in every browser. The\n * price is that only strings can be written, which the types enforce.\n *\n * Not a security boundary: users can still screenshot, use dev tools or\n * disable script. Treat redaction as a guard against accidents.\n */\n\nexport type InterceptedCopyKind = 'copy' | 'cut';\n\nexport const DEFAULT_INTERCEPTED_EVENTS: readonly InterceptedCopyKind[] = ['copy', 'cut'];\n\n/** The writable slice of `DataTransfer` during a `copy`/`cut` event. */\nexport interface ClipboardDataLike {\n setData(format: string, data: string): void;\n clearData?(format?: string): void;\n}\n\n/** Structural `ClipboardEvent`: DOM and React clipboard events both satisfy it. */\nexport interface CopyEventLike {\n readonly type: string;\n readonly target: EventTarget | null;\n readonly clipboardData: ClipboardDataLike | null;\n readonly defaultPrevented: boolean;\n preventDefault(): void;\n}\n\n/** What the user selected when they copied. */\nexport interface CopySelection {\n readonly kind: InterceptedCopyKind;\n /** What the browser would put on the clipboard as `text/plain`. */\n readonly text: string;\n /** Serialised HTML of the selection; `null` inside text inputs. */\n readonly html: string | null;\n /** A detached clone of the selected nodes, safe to mutate; `null` inside text inputs. */\n readonly fragment: DocumentFragment | null;\n /** The `<input>`/`<textarea>` the selection lives in, if any. */\n readonly field: HTMLInputElement | HTMLTextAreaElement | null;\n /** Whether a `cut` would remove the selection (form field or contenteditable). */\n readonly editable: boolean;\n}\n\n/**\n * A multi payload whose items are all strings; the only kind `setData` accepts.\n * Web custom formats (`web …`) are skipped: only the async Clipboard API writes them.\n */\nexport interface SyncMultiPayload {\n readonly kind: 'multi';\n readonly items: readonly { readonly mimeType: string; readonly data: string; readonly optional?: boolean }[];\n}\n\n/** Payloads writable synchronously during a copy event. Images need the async clipboard. */\nexport type SyncCopyPayload = TextPayload | HtmlPayload | JsonPayload | SyncMultiPayload;\n\n/**\n * What a transform returns:\n * - a string or payload: write that instead of the selection\n * - `false`: block the copy (nothing reaches the clipboard; a cut deletes nothing)\n * - `null` / `undefined`: leave the browser's default copy untouched\n *\n * Must be synchronous: the clipboard closes when the event handler returns.\n */\nexport type CopyInterceptDecision = string | SyncCopyPayload | false | null | undefined;\n\nexport type CopyInterceptTransform = (selection: CopySelection) => CopyInterceptDecision;\n\n/**\n * When the transform throws or returns something unwritable:\n * - `'block'` (default): nothing is copied. Safe for redaction.\n * - `'native'`: the browser's default copy proceeds unmodified.\n */\nexport type CopyInterceptFailureMode = 'block' | 'native';\n\nexport interface CopyInterceptOptions {\n readonly transform: CopyInterceptTransform;\n readonly failureMode?: CopyInterceptFailureMode;\n}\n\nexport type CopyInterceptPassReason =\n /** Not a `copy`/`cut` event. */\n | 'unsupported-event'\n /** Another handler already called `preventDefault()`. */\n | 'already-handled'\n /** Nothing readable was selected. */\n | 'no-selection'\n /** The transform returned `null`/`undefined`. */\n | 'declined';\n\nexport type CopyInterceptOutcome =\n | {\n readonly status: 'passed';\n readonly reason: CopyInterceptPassReason;\n readonly selection: CopySelection | null;\n }\n | {\n readonly status: 'written';\n readonly selection: CopySelection;\n readonly payload: SyncCopyPayload;\n /** For an editable `cut`: whether the selection was removed. Always `false` for `copy`. */\n readonly deleted: boolean;\n }\n | { readonly status: 'blocked'; readonly selection: CopySelection }\n | {\n readonly status: 'failed';\n readonly selection: CopySelection;\n readonly error: CopyError;\n /** What actually happened to the copy. */\n readonly fallback: CopyInterceptFailureMode;\n };\n\n/* ─────────────────────────────────────────────────────── selection reading */\n\ntype TextField = HTMLInputElement | HTMLTextAreaElement;\n\nfunction isNode(value: unknown): value is Node {\n return typeof value === 'object' && value !== null && typeof (value as Node).nodeType === 'number';\n}\n\ninterface FieldSelection {\n readonly field: TextField;\n readonly start: number;\n readonly end: number;\n}\n\nfunction readTextField(target: EventTarget | null): FieldSelection | null {\n if (!isNode(target) || target.nodeType !== 1) return null;\n const tag = (target as Element).tagName;\n if (tag !== 'INPUT' && tag !== 'TEXTAREA') return null;\n const field = target as TextField;\n try {\n // `null` (or a throw, in older engines) for input types without text selection.\n const { selectionStart: start, selectionEnd: end } = field;\n return typeof start === 'number' && typeof end === 'number' ? { field, start, end } : null;\n } catch {\n return null;\n }\n}\n\nfunction documentOf(target: EventTarget | null): Document | null {\n if (isNode(target)) return target.nodeType === 9 ? (target as Document) : target.ownerDocument;\n return typeof document === 'undefined' ? null : document;\n}\n\nfunction isEditableNode(node: Node): boolean {\n const element = node.nodeType === 1 ? (node as HTMLElement) : node.parentElement;\n return element?.isContentEditable === true;\n}\n\ninterface SelectedRanges {\n readonly selection: Selection;\n readonly ranges: readonly Range[];\n}\n\nfunction selectedRanges(doc: Document | null): SelectedRanges | null {\n const selection = doc?.getSelection();\n if (!selection || selection.isCollapsed) return null;\n const ranges: Range[] = [];\n for (let index = 0; index < selection.rangeCount; index += 1) ranges.push(selection.getRangeAt(index));\n return { selection, ranges };\n}\n\ninterface ReadSelection {\n readonly selection: CopySelection;\n readonly doc: Document;\n}\n\nfunction readSelection(event: CopyEventLike): ReadSelection | null {\n const kind: InterceptedCopyKind = event.type === 'cut' ? 'cut' : 'copy';\n const fieldSelection = readTextField(event.target);\n if (fieldSelection) {\n const { field, start, end } = fieldSelection;\n const text = field.value.slice(Math.min(start, end), Math.max(start, end));\n if (text.length === 0) return null;\n const editable = !field.readOnly && !field.disabled;\n return { selection: { kind, text, html: null, fragment: null, field, editable }, doc: field.ownerDocument };\n }\n\n const doc = documentOf(event.target);\n const selected = selectedRanges(doc);\n const first = selected?.ranges[0];\n if (!doc || !selected || !first) return null;\n // `Selection#toString` follows the rendered layout, like the browser's own copy;\n // `Range#toString` would leak source whitespace and hidden text.\n const text = selected.selection.toString();\n if (text.length === 0) return null;\n\n const container = doc.createElement('div');\n for (const range of selected.ranges) container.appendChild(range.cloneContents());\n const html = container.innerHTML;\n const fragment = doc.createDocumentFragment();\n while (container.firstChild) fragment.appendChild(container.firstChild);\n\n const editable = isEditableNode(first.startContainer);\n return { selection: { kind, text, html, fragment, field: null, editable }, doc };\n}\n\n/** Reads the selection behind a copy event, or `null` if nothing readable is selected. */\nexport function readCopySelection(event: CopyEventLike): CopySelection | null {\n const read = readSelection(event);\n return read ? read.selection : null;\n}\n\n/* ─────────────────────────────────────────────────────────────── writing */\n\ntype Entries = readonly (readonly [mimeType: string, data: string])[];\n\ntype Prepared =\n | { readonly ok: true; readonly payload: SyncCopyPayload; readonly entries: Entries }\n | { readonly ok: false; readonly error: CopyError };\n\nconst nonEmpty = (value: unknown): value is string => typeof value === 'string' && value.length > 0;\nconst invalid = (message: string, cause?: unknown): Prepared => ({\n ok: false,\n error: createCopyError('invalid-payload', message, cause),\n});\nconst unsupported = (message: string): Prepared => ({ ok: false, error: createCopyError('unsupported-format', message) });\n\n/**\n * Validates a decision and turns it into `[mimeType, data]` pairs. Kept\n * self-contained (no shared validator) so the interceptor stays small; the\n * checks still run for plain-JS callers the types can't protect.\n */\nfunction prepare(decision: string | SyncCopyPayload): Prepared {\n const candidate: unknown = typeof decision === 'string' ? { kind: 'text', value: decision } : decision;\n if (typeof candidate !== 'object' || candidate === null) {\n return invalid('Copy transforms must return a string, a payload, false, or nothing.');\n }\n if (typeof (candidate as { then?: unknown }).then === 'function') {\n return invalid('Copy transforms must be synchronous; the clipboard closes when the event ends.');\n }\n const payload = candidate as SyncCopyPayload;\n const fields = candidate as Record<string, unknown>;\n const ok = (entries: Entries): Prepared => ({ ok: true, payload, entries });\n\n switch (fields['kind']) {\n case 'text':\n return nonEmpty(fields['value']) ? ok([['text/plain', fields['value']]]) : invalid('Text payload must be a non-empty string.');\n case 'html':\n return nonEmpty(fields['html']) && nonEmpty(fields['text'])\n ? ok([['text/html', fields['html']], ['text/plain', fields['text']]])\n : invalid('HTML payload requires non-empty `html` and plain-text `text`.');\n case 'json': {\n const pretty = fields['pretty'];\n const indent = pretty === true ? 2 : typeof pretty === 'number' ? pretty : undefined;\n // Typed as `string`, but `undefined` for functions, symbols and undefined.\n let json: unknown;\n try {\n json = JSON.stringify(fields['value'], null, indent);\n } catch (cause) {\n return invalid('JSON payload could not be serialised (circular reference or BigInt?).', cause);\n }\n return typeof json === 'string' ? ok([['text/plain', json]]) : invalid('JSON payload serialised to nothing.');\n }\n case 'multi': {\n const items = fields['items'];\n if (!Array.isArray(items) || items.length === 0) return invalid('Multi payload requires at least one item.');\n const entries: (readonly [string, string])[] = [];\n for (const item of items as unknown[]) {\n const { mimeType, data } = (item ?? {}) as { mimeType?: unknown; data?: unknown };\n if (!nonEmpty(mimeType) || entries.some(([seen]) => seen === mimeType)) {\n return invalid('Every multi item needs a unique, non-empty `mimeType`.');\n }\n if (typeof data !== 'string') return unsupported(`Multi item \"${mimeType}\" must be a string during a copy event.`);\n entries.push([mimeType, data]);\n }\n const writable = entries.filter(([mimeType]) => !isWebCustomFormat(mimeType));\n return writable.length > 0\n ? ok(writable)\n : unsupported('Web custom formats need the async Clipboard API (useCopy).');\n }\n default:\n return unsupported(`\"${String(fields['kind'])}\" payloads cannot be written during a copy event; use useCopy() for images.`);\n }\n}\n\n/** Deletes the selection the way a native cut would (keeps undo history, fires `input`). */\nfunction deleteSelection(doc: Document): boolean {\n const legacy = doc as unknown as { execCommand?: (command: string) => boolean };\n try {\n return legacy.execCommand?.('delete') === true;\n } catch {\n return false;\n }\n}\n\n/**\n * Applies a transform to one `copy`/`cut` event. Use directly from an\n * `onCopy` handler, or let {@link registerCopyInterceptor} scope it.\n */\nexport function interceptCopyEvent(event: CopyEventLike, options: CopyInterceptOptions): CopyInterceptOutcome {\n if (event.type !== 'copy' && event.type !== 'cut') {\n return { status: 'passed', reason: 'unsupported-event', selection: null };\n }\n if (event.defaultPrevented) return { status: 'passed', reason: 'already-handled', selection: null };\n\n const read = readSelection(event);\n if (!read) return { status: 'passed', reason: 'no-selection', selection: null };\n const { selection, doc } = read;\n\n const fail = (error: CopyError): CopyInterceptOutcome => {\n const fallback = options.failureMode ?? 'block';\n if (fallback === 'block') event.preventDefault();\n return { status: 'failed', selection, error, fallback };\n };\n\n let decision: CopyInterceptDecision;\n try {\n decision = options.transform(selection);\n } catch (cause) {\n return fail(sourceError(cause, 'The copy transform threw.'));\n }\n\n if (decision === null || decision === undefined) return { status: 'passed', reason: 'declined', selection };\n if (decision === false) {\n event.preventDefault();\n return { status: 'blocked', selection };\n }\n\n const prepared = prepare(decision);\n if (!prepared.ok) return fail(prepared.error);\n\n const data = event.clipboardData;\n if (!data) return fail(createCopyError('unsupported', 'This browser exposes no clipboardData on copy events.'));\n\n // From here the browser's default is gone: a failure can only end in `block`.\n event.preventDefault();\n try {\n for (const [mimeType, value] of prepared.entries) data.setData(mimeType, value);\n } catch (cause) {\n try {\n data.clearData?.();\n } catch {\n // Best effort: a half-written clipboard is still better reported than hidden.\n }\n const error = createCopyError('unknown', 'The browser rejected the clipboard write.', cause);\n return { status: 'failed', selection, error, fallback: 'block' };\n }\n\n const deleted = selection.kind === 'cut' && selection.editable && deleteSelection(doc);\n return { status: 'written', selection, payload: prepared.payload, deleted };\n}\n\n/* ────────────────────────────────────────────────────────────── scoping */\n\nexport interface CopyInterceptorOptions extends CopyInterceptOptions {\n /**\n * When one selection touches several scopes, exactly one handles it: the\n * highest `priority`, then the innermost, then the first in the document.\n * The winner sees the *whole* selection. Give redaction scopes a higher\n * priority so text copied across them is always masked. Default `0`.\n */\n readonly priority?: number;\n /** Which events to intercept. Default: both `copy` and `cut`. */\n readonly events?: readonly InterceptedCopyKind[];\n /** Every outcome for selections inside this scope, including `passed`. */\n readonly onIntercept?: (outcome: CopyInterceptOutcome) => void;\n /** Called when the transform failed; the outcome's `fallback` says what happened to the copy. */\n readonly onError?: (error: CopyError) => void;\n}\n\ninterface Scope {\n readonly root: Element;\n readonly read: () => CopyInterceptorOptions;\n}\n\ninterface Registry {\n readonly scopes: Set<Scope>;\n readonly listener: (event: Event) => void;\n}\n\nconst registries = /* @__PURE__ */ new WeakMap<Document, Registry>();\n\nfunction touches(root: Element, event: CopyEventLike): boolean {\n const fieldSelection = readTextField(event.target);\n if (fieldSelection) return root.contains(fieldSelection.field);\n const selected = selectedRanges(root.ownerDocument);\n return selected !== null && selected.ranges.some((range) => range.intersectsNode(root));\n}\n\nconst priorityOf = (scope: Scope): number => scope.read().priority ?? 0;\n\n/**\n * Highest `priority` first; then the innermost scope; then document order;\n * then registration order (same root). A total order, so the result never\n * depends on effect timing.\n */\nfunction compareScopes(a: Scope, b: Scope): number {\n const byPriority = priorityOf(b) - priorityOf(a);\n if (byPriority !== 0) return byPriority;\n const position = a.root.compareDocumentPosition(b.root);\n if (position === 0) return 0;\n if (position & 16) return 1; // b is inside a: b first\n if (position & 8) return -1; // b contains a: a first\n return position & 4 ? -1 : 1; // b follows a: a first\n}\n\nfunction dispatch(registry: Registry, event: CopyEventLike): void {\n if (event.defaultPrevented) return;\n const kind = event.type as InterceptedCopyKind;\n const candidates = [...registry.scopes].filter(\n (scope) => (scope.read().events ?? DEFAULT_INTERCEPTED_EVENTS).includes(kind) && touches(scope.root, event),\n );\n const [scope] = candidates.sort(compareScopes);\n if (!scope) return;\n\n const options = scope.read();\n const outcome = interceptCopyEvent(event, options);\n invoke(options.onIntercept, outcome);\n if (outcome.status === 'failed') invoke(options.onError, outcome.error);\n}\n\n/**\n * Intercepts native copies and cuts whose selection touches `root`. Returns\n * an unsubscribe function. Pass a getter to always read the latest options.\n *\n * One listener per document serves every scope, so overlapping scopes\n * resolve deterministically (see `priority`) regardless of registration order.\n * Handlers that call `preventDefault()` first (e.g. a React `onCopy`) win.\n */\nexport function registerCopyInterceptor(\n root: Element,\n options: CopyInterceptorOptions | (() => CopyInterceptorOptions),\n): () => void {\n const doc = root.ownerDocument;\n let registry = registries.get(doc);\n if (!registry) {\n const scopes = new Set<Scope>();\n const created: Registry = {\n scopes,\n listener: (event) => {\n dispatch(created, event as unknown as CopyEventLike);\n },\n };\n registry = created;\n registries.set(doc, created);\n doc.addEventListener('copy', created.listener);\n doc.addEventListener('cut', created.listener);\n }\n\n const scope: Scope = { root, read: typeof options === 'function' ? options : () => options };\n registry.scopes.add(scope);\n const active = registry;\n\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n active.scopes.delete(scope);\n if (active.scopes.size === 0) {\n doc.removeEventListener('copy', active.listener);\n doc.removeEventListener('cut', active.listener);\n registries.delete(doc);\n }\n };\n}\n","/**\n * Drag-to-copy: populate `DataTransfer` when the user starts dragging an\n * element, so whatever they drop it into receives structured data — plain text,\n * HTML, JSON, or multiple MIME types — instead of the browser's default\n * text-extraction of the dragged DOM.\n *\n * No Clipboard API, no permission prompt, works in every browser that supports\n * HTML5 drag-and-drop (all modern browsers and IE11+).\n */\n\nimport { invoke } from './machine-shared';\nimport { createCopyError, type CopyError } from './errors';\nimport { isWebCustomFormat } from './mime';\nimport type { HtmlPayload, JsonPayload, TextPayload } from './payload';\nimport { sourceError } from './source-error';\n\n/* ─────────────────────────────────────────────────────────────────── types */\n\n/**\n * The `effectAllowed` a drag operation advertises. Controls which cursor the\n * browser shows and which `dropEffect` the drop target may request.\n *\n * - `'copy'` (default): dragging produces a copy of the data.\n * - `'move'`: dragging removes the source after a drop (the app must do this).\n * - `'link'`: dragging creates a link/reference.\n * - `'copyMove'` / `'copyLink'` / `'linkMove'` / `'all'`: combinations.\n * - `'none'`: the drag is not droppable anywhere.\n * - `'uninitialized'`: browser default (same as `'all'` in most cases).\n */\nexport type DragEffectAllowed =\n | 'copy'\n | 'move'\n | 'link'\n | 'copyMove'\n | 'copyLink'\n | 'linkMove'\n | 'all'\n | 'none'\n | 'uninitialized';\n\n/** What is put into `DataTransfer` when a drag starts. */\nexport interface DragCopyItem {\n /** Web custom formats (`web …`) are skipped: only the async Clipboard API writes them. */\n readonly mimeType: string;\n readonly data: string;\n /** Accepted for parity with `MultiPayloadItem`; every non-web item can be written to a drag. */\n readonly optional?: boolean;\n}\n\n/**\n * A multi-format drag payload — strings only (DataTransfer only accepts strings).\n * Mirrors `SyncCopyPayload` from copy-interceptor but scoped to drag.\n */\nexport type DragCopyPayload = TextPayload | HtmlPayload | JsonPayload | DragMultiPayload;\n\nexport interface DragMultiPayload {\n readonly kind: 'multi';\n readonly items: readonly DragCopyItem[];\n}\n\n/**\n * What the source getter returns:\n * - a string: written as `text/plain`.\n * - a `DragCopyPayload`: written according to its `kind`.\n * - `false`: cancels the drag (`preventDefault()` on `dragstart`).\n * - `null` / `undefined`: leaves the browser's default drag data untouched.\n */\nexport type DragCopyDecision = string | DragCopyPayload | false | null | undefined;\n\n/** Called once when the user begins dragging the element. Must be synchronous. */\nexport type DragCopySource = (event: DragStartEventLike) => DragCopyDecision;\n\n/** Structural `DragEvent`: DOM and React drag events both satisfy it. */\nexport interface DragStartEventLike {\n readonly type: string;\n readonly dataTransfer: DataTransferLike | null;\n readonly defaultPrevented: boolean;\n preventDefault(): void;\n}\n\n/** The writable face of `DataTransfer`. */\nexport interface DataTransferLike {\n effectAllowed: string;\n setData(format: string, data: string): void;\n clearData?(format?: string): void;\n}\n\nexport type DragCopyStatus =\n /** No drag has started yet, or it was cancelled / never had source data. */\n | 'idle'\n /** The element is being dragged and data is on the DataTransfer. */\n | 'dragging'\n /** The drag ended (dropped or abandoned). */\n | 'done';\n\nexport type DragCopyPassReason =\n /** Source returned `null`/`undefined`. */\n | 'declined'\n /** `DataTransfer` is not present on this event. */\n | 'no-transfer'\n /** Source returned `false`. */\n | 'cancelled';\n\nexport type DragCopyOutcome =\n | { readonly status: 'written'; readonly payload: DragCopyPayload }\n | { readonly status: 'passed'; readonly reason: DragCopyPassReason }\n | { readonly status: 'failed'; readonly error: CopyError };\n\nexport interface DragCopyState {\n readonly status: DragCopyStatus;\n /** The last `dragstart` outcome; `null` before the first drag. */\n readonly outcome: DragCopyOutcome | null;\n}\n\nexport interface DragCopyOptions {\n /**\n * Returns the data to put in the drag. Called synchronously on `dragstart`.\n * Return a string (shorthand for `{ kind: 'text' }`), a payload object,\n * `false` to cancel the drag, or `null`/`undefined` to pass through.\n */\n readonly source: DragCopySource;\n /**\n * `effectAllowed` advertised on the drag. Default `'copy'`.\n * Setting `'move'` signals to drop targets that the source will be removed.\n */\n readonly effectAllowed?: DragEffectAllowed;\n /**\n * Called each time a drag starts or ends, with the latest outcome and status.\n * Stable across re-renders when written as a class method or via `useRef`.\n */\n readonly onDrag?: (state: DragCopyState) => void;\n /** Called when preparing the drag payload fails. */\n readonly onError?: (error: CopyError) => void;\n}\n\n/* ─────────────────────────────────────────────────────────── validation */\n\nconst nonEmpty = (value: unknown): value is string =>\n typeof value === 'string' && value.length > 0;\n\ntype PrepareFail = { readonly ok: false; readonly error: CopyError };\ntype PrepareOk = { readonly ok: true; readonly payload: DragCopyPayload; readonly items: readonly DragCopyItem[] };\ntype Prepared = PrepareOk | PrepareFail;\n\nconst invalid = (message: string, cause?: unknown): PrepareFail => ({\n ok: false,\n error: createCopyError('invalid-payload', message, cause),\n});\n\nconst unsupported = (message: string): PrepareFail => ({\n ok: false,\n error: createCopyError('unsupported-format', message),\n});\n\nfunction prepareDragDecision(decision: string | DragCopyPayload): Prepared {\n const candidate: unknown =\n typeof decision === 'string' ? { kind: 'text', value: decision } : decision;\n\n if (typeof candidate !== 'object' || candidate === null) {\n return invalid('Drag source must return a string, a payload, false, or nothing.');\n }\n if (typeof (candidate as { then?: unknown }).then === 'function') {\n return invalid('Drag sources must be synchronous; DataTransfer closes when dragstart returns.');\n }\n\n const payload = candidate as DragCopyPayload;\n const fields = candidate as Record<string, unknown>;\n const ok = (items: readonly DragCopyItem[]): PrepareOk => ({ ok: true, payload, items });\n\n switch (fields['kind']) {\n case 'text':\n return nonEmpty(fields['value'])\n ? ok([{ mimeType: 'text/plain', data: fields['value'] }])\n : invalid('Text payload must be a non-empty string.');\n\n case 'html':\n return nonEmpty(fields['html']) && nonEmpty(fields['text'])\n ? ok([\n { mimeType: 'text/html', data: fields['html'] },\n { mimeType: 'text/plain', data: fields['text'] },\n ])\n : invalid('HTML payload requires non-empty `html` and `text`.');\n\n case 'json': {\n const pretty = fields['pretty'];\n const indent =\n pretty === true ? 2 : typeof pretty === 'number' ? pretty : undefined;\n let json: unknown;\n try {\n json = JSON.stringify(fields['value'], null, indent);\n } catch (cause) {\n return invalid(\n 'JSON payload could not be serialised (circular reference or BigInt?).',\n cause,\n );\n }\n return typeof json === 'string'\n ? ok([{ mimeType: 'text/plain', data: json }])\n : invalid('JSON payload serialised to nothing.');\n }\n\n case 'multi': {\n const items = fields['items'];\n if (!Array.isArray(items) || items.length === 0) {\n return invalid('Multi payload requires at least one item.');\n }\n const out: DragCopyItem[] = [];\n for (const item of items as unknown[]) {\n const { mimeType, data } = (item ?? {}) as {\n mimeType?: unknown;\n data?: unknown;\n };\n if (!nonEmpty(mimeType) || out.some((i) => i.mimeType === mimeType)) {\n return invalid('Every multi item needs a unique, non-empty `mimeType`.');\n }\n if (typeof data !== 'string') {\n return unsupported(\n `Multi item \"${mimeType}\" must be a string; DataTransfer does not accept Blobs.`,\n );\n }\n out.push({ mimeType, data });\n }\n const writable = out.filter((item) => !isWebCustomFormat(item.mimeType));\n return writable.length > 0\n ? ok(writable)\n : unsupported('Web custom formats need the async Clipboard API (useCopy).');\n }\n\n default:\n return unsupported(\n `\"${String(fields['kind'])}\" payloads cannot be used for drag-copy; use useCopy() for images.`,\n );\n }\n}\n\n/* ─────────────────────────────────────────────────────── applyDragCopy */\n\n/**\n * Populates a `dragstart` event's `DataTransfer` with the given payload.\n * Use this from a raw `dragstart` handler or a React `onDragStart` prop.\n * Returns the outcome so you can inspect what happened.\n */\nexport function applyDragCopy(\n event: DragStartEventLike,\n options: DragCopyOptions,\n): DragCopyOutcome {\n if (event.defaultPrevented) {\n return { status: 'passed', reason: 'declined' };\n }\n\n let decision: DragCopyDecision;\n try {\n decision = options.source(event);\n } catch (cause) {\n const error = sourceError(cause, 'The drag source threw.');\n return { status: 'failed', error };\n }\n\n if (decision === null || decision === undefined) {\n return { status: 'passed', reason: 'declined' };\n }\n\n if (decision === false) {\n event.preventDefault();\n return { status: 'passed', reason: 'cancelled' };\n }\n\n const transfer = event.dataTransfer;\n if (!transfer) {\n return { status: 'passed', reason: 'no-transfer' };\n }\n\n const prepared = prepareDragDecision(decision);\n if (!prepared.ok) {\n return { status: 'failed', error: prepared.error };\n }\n\n try {\n transfer.effectAllowed = options.effectAllowed ?? 'copy';\n for (const { mimeType, data } of prepared.items) {\n transfer.setData(mimeType, data);\n }\n } catch (cause) {\n try {\n transfer.clearData?.();\n } catch {\n // Best effort: report the original error, not a clearData failure.\n }\n const error = createCopyError(\n 'unknown',\n 'The browser rejected the DataTransfer write.',\n cause,\n );\n return { status: 'failed', error };\n }\n\n return { status: 'written', payload: prepared.payload };\n}\n\n/* ─────────────────────────────────────────────────── registerDragCopy */\n\nexport interface RegisterDragCopyResult {\n /** Unsubscribes all listeners. Idempotent. */\n readonly unsubscribe: () => void;\n}\n\n/**\n * Attaches `dragstart` and `dragend` listeners to `element`, calling\n * `applyDragCopy` on every drag start. Returns an object with an\n * `unsubscribe` function.\n *\n * Pass an options getter so the latest options are always used without\n * re-registering — safe to pass an inline object from a React render.\n *\n * ```ts\n * const { unsubscribe } = registerDragCopy(el, () => ({\n * source: () => `${title}\\n${url}`,\n * }));\n * ```\n */\nexport function registerDragCopy(\n element: HTMLElement,\n options: DragCopyOptions | (() => DragCopyOptions),\n): RegisterDragCopyResult {\n const read = typeof options === 'function' ? options : (): DragCopyOptions => options;\n\n let unsubscribed = false;\n let currentOutcome: DragCopyOutcome | null = null;\n\n function onDragStart(raw: Event): void {\n const event = raw as DragEvent;\n const opts = read();\n\n const outcome = applyDragCopy(\n {\n type: event.type,\n dataTransfer: event.dataTransfer,\n get defaultPrevented() {\n return event.defaultPrevented;\n },\n preventDefault: () => { event.preventDefault(); },\n },\n opts,\n );\n\n currentOutcome = outcome;\n\n const state: DragCopyState = { status: 'dragging', outcome };\n if (outcome.status === 'failed') invoke(opts.onError, outcome.error);\n invoke(opts.onDrag, state);\n }\n\n function onDragEnd(): void {\n const opts = read();\n const state: DragCopyState = { status: 'done', outcome: currentOutcome };\n invoke(opts.onDrag, state);\n currentOutcome = null;\n }\n\n element.setAttribute('draggable', 'true');\n element.addEventListener('dragstart', onDragStart);\n element.addEventListener('dragend', onDragEnd);\n\n return {\n unsubscribe(): void {\n if (unsubscribed) return;\n unsubscribed = true;\n element.removeEventListener('dragstart', onDragStart);\n element.removeEventListener('dragend', onDragEnd);\n element.removeAttribute('draggable');\n },\n };\n}\n","import { copyFailure } from './errors';\nimport { isTextualMimeType, matchesMimePattern, normalizeClipboardType, normalizeMimeType, sniffImageType } from './mime';\n\n/* ------------------------------------------------------------------ Types */\n\n/** Friendly names for the common cases. */\nexport type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';\n\n/**\n * What a paste may contain, in any order: a shorthand, an exact MIME type\n * (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a\n * wildcard (`'image/*'`, `'*\\/*'`). `image/svg+xml` (scriptable XML), web custom\n * formats and `+json` types are only accepted when listed exactly.\n */\nexport type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;\n\nexport interface PasteLimits {\n /**\n * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as\n * they would be encoded, matching `Blob.size`, so every paste path counts the same way.\n * Default 32 MiB.\n */\n readonly maxBytes?: number;\n /** Max number of accepted items (types + files). Default 32. */\n readonly maxItems?: number;\n}\n\nexport interface PasteReadOptions extends PasteLimits {\n /** Default `['text']` (plain text only): the safest choice. */\n readonly accept?: readonly PasteAccept[];\n}\n\n/** Validated, normalised options that adapters receive. */\nexport interface ResolvedPasteReadOptions {\n /** Normalised patterns: `type/subtype`, `type/*` or `*\\/*`. */\n readonly accept: readonly string[];\n readonly maxBytes: number;\n readonly maxItems: number;\n}\n\n/** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */\nexport type PasteSource = 'clipboard' | 'event' | 'drop';\n\n/** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */\nexport interface PasteItem {\n readonly type: string;\n readonly data: string | Blob;\n}\n\n/**\n * Everything the paste produced. Treat all of it as untrusted user input:\n * in particular never inject `html` into the DOM without sanitising it.\n */\nexport interface PasteResult {\n readonly source: PasteSource;\n /** Every accepted entry, in clipboard order. */\n readonly items: readonly PasteItem[];\n /** `text/plain`, when accepted and present. */\n readonly text: string | null;\n /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */\n readonly html: string | null;\n /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */\n readonly images: readonly Blob[];\n /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */\n readonly files: readonly File[];\n /**\n * The entries of `files` that are also in `images`: verified image files, keeping their\n * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.\n */\n readonly imageFiles: readonly File[];\n}\n\n/** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */\nexport type PasteReadResult = Omit<PasteResult, 'imageFiles'>;\n\n/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */\nexport function completePasteResult(result: PasteReadResult): PasteResult {\n const images = new Set<Blob>(result.images);\n return { ...result, imageFiles: result.files.filter((file) => images.has(file)) };\n}\n\n/* -------------------------------------------------------- Option handling */\n\nexport const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[] = /* @__PURE__ */ Object.freeze(['text'] as const);\nexport const DEFAULT_PASTE_MAX_BYTES = 32 * 1024 * 1024;\nexport const DEFAULT_PASTE_MAX_ITEMS = 32;\n\nconst SHORTHANDS: ReadonlyMap<string, string> = /* @__PURE__ */ new Map([\n ['text', 'text/plain'],\n ['html', 'text/html'],\n ['image', 'image/*'],\n ['any', '*/*'],\n]);\n\nconst TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\nfunction resolvePattern(entry: unknown): string | null {\n if (typeof entry !== 'string') return null;\n const shorthand = SHORTHANDS.get(entry);\n if (shorthand !== undefined) return shorthand;\n if (entry === '*/*') return entry;\n if (entry.endsWith('/*')) {\n const type = entry.slice(0, -2).toLowerCase();\n return TYPE_TOKEN.test(type) ? `${type}/*` : null;\n }\n return normalizeClipboardType(entry);\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\n/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */\nexport function resolvePasteReadOptions(options: PasteReadOptions = {}): ResolvedPasteReadOptions {\n const accept: string[] = [];\n for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {\n const pattern = resolvePattern(entry);\n if (pattern === null) throw copyFailure('invalid-payload', `Invalid \\`accept\\` entry: ${JSON.stringify(entry)}.`);\n if (!accept.includes(pattern)) accept.push(pattern);\n }\n if (accept.length === 0) throw copyFailure('invalid-payload', '`accept` must list at least one type.');\n return {\n accept,\n maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, 'maxBytes'),\n maxItems: resolveLimit(options.maxItems, DEFAULT_PASTE_MAX_ITEMS, 'maxItems'),\n };\n}\n\n/** Whether a normalised MIME type is allowed by the resolved `accept` list. */\nexport function isAccepted(mimeType: string, options: ResolvedPasteReadOptions): boolean {\n return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));\n}\n\n/* -------------------------------------------------------------- Entries */\n\n/** An accepted, not-yet-verified entry. */\nexport interface PasteEntry {\n readonly type: string;\n readonly data: string | Blob;\n /** Came from `DataTransfer.files`, i.e. `data` is a `File`. */\n readonly file: boolean;\n}\n\ninterface Budget {\n readonly charge: (size: number) => void;\n}\n\nfunction createBudget(options: ResolvedPasteReadOptions): Budget {\n let bytes = 0;\n let items = 0;\n return {\n charge: (size) => {\n items += 1;\n bytes += size;\n if (items > options.maxItems) {\n throw copyFailure('too-large', `The paste has more than ${String(options.maxItems)} accepted items.`);\n }\n if (bytes > options.maxBytes) {\n throw copyFailure('too-large', `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);\n }\n },\n };\n}\n\n/**\n * UTF-8 byte length of a string, without allocating an encoded copy.\n * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.\n */\nexport function utf8ByteLength(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i += 1) {\n const unit = text.charCodeAt(i);\n if (unit < 0x80) bytes += 1;\n else if (unit < 0x800) bytes += 2;\n else if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n bytes += 4;\n i += 1;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */\nconst sizeOf = (data: string | Blob): number => (typeof data === 'string' ? utf8ByteLength(data) : data.size);\n\n/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */\nexport function enforcePasteLimits(entries: readonly PasteEntry[], options: ResolvedPasteReadOptions): void {\n const budget = createBudget(options);\n for (const entry of entries) budget.charge(sizeOf(entry.data));\n}\n\n/** Structural view of a `DataTransferItem`: only what is readable while dragging. */\nexport interface DataTransferItemLike {\n /** `'string'` or `'file'`. */\n readonly kind: string;\n readonly type: string;\n}\n\n/** Structural view of `DataTransfer` (paste and drop events). */\nexport interface DataTransferLike {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n readonly files?: ArrayLike<File> | null;\n readonly items?: ArrayLike<DataTransferItemLike> | null;\n}\n\n/**\n * Whether a drag in progress could drop anything `accept`s. Uses only what\n * browsers expose before the drop (item kinds and types, never the data).\n * A file whose type is not known yet (some browsers hide it while dragging)\n * counts as a maybe: the drop itself is checked against `accept`.\n */\nexport function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean {\n // Without an item list, a file is only known as the type \"Files\": treat it as an untyped file.\n const items = data.items ?? Array.from(data.types, (type) => (type === 'Files' ? { kind: 'file', type: '' } : { kind: 'string', type }));\n return Array.from(items).some(({ kind, type: raw }) => {\n const file = kind === 'file';\n const type = normalizeClipboardType(raw);\n if (type === null) return file;\n return (file || isTextualMimeType(type)) && isAccepted(type, options);\n });\n}\n\n/**\n * Synchronously copies the accepted parts of a paste event's `DataTransfer`.\n * It must run during the event: browsers empty the object afterwards.\n */\nexport function snapshotDataTransfer(data: DataTransferLike, options: ResolvedPasteReadOptions): PasteEntry[] {\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const raw of Array.from(data.types)) {\n const type = normalizeClipboardType(raw);\n // Binary types are delivered through `files`; `getData` only returns strings.\n if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n const text = data.getData(raw);\n if (text.length > 0) entries.push({ type, data: text, file: false });\n }\n\n for (const file of Array.from(data.files ?? [])) {\n const type = normalizeMimeType(file.type) ?? 'application/octet-stream';\n if (isAccepted(type, options)) entries.push({ type, data: file, file: true });\n }\n\n return entries;\n}\n\n/** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */\nexport interface ClipboardItemLike {\n readonly types: readonly string[];\n getType(type: string): Promise<Blob>;\n}\n\n/**\n * Reads the accepted types from `navigator.clipboard.read()` items, enforcing\n * the limits *before* decoding any text so an oversized paste is never buffered twice.\n */\nexport async function collectClipboardItems(\n items: readonly ClipboardItemLike[],\n options: ResolvedPasteReadOptions,\n signal?: AbortSignal,\n): Promise<PasteEntry[]> {\n const budget = createBudget(options);\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const item of items) {\n for (const raw of item.types) {\n const type = normalizeClipboardType(raw);\n if (type === null || seen.has(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n\n let blob: Blob;\n try {\n blob = await item.getType(raw);\n } catch {\n // Chromium lists some types it then refuses to hand over; skip them, don't fail the paste.\n continue;\n }\n // Cancelled (reset, superseded, unmounted) while waiting: don't decode the rest.\n if (signal?.aborted) throw copyFailure('aborted', 'The paste was cancelled.');\n if (blob.size === 0) continue;\n budget.charge(blob.size);\n entries.push({ type, data: isTextualMimeType(type) ? await blob.text() : blob, file: false });\n }\n }\n return entries;\n}\n\n/* ------------------------------------------------------------ Finalising */\n\nfunction retype(entry: PasteEntry, data: Blob, type: string): Blob {\n if (entry.file) {\n const file = data as File;\n return new File([file], file.name, { type, lastModified: file.lastModified });\n }\n return data.slice(0, data.size, type);\n}\n\n/**\n * Verifies image bytes, then builds the result. Blobs that claim to be images\n * but aren't (or whose real format is not accepted) are dropped. Throws\n * `no-content` when nothing survives.\n */\nexport async function finalizePaste(\n entries: readonly PasteEntry[],\n source: PasteSource,\n options: ResolvedPasteReadOptions,\n): Promise<PasteReadResult> {\n const items: PasteItem[] = [];\n const images: Blob[] = [];\n const files: File[] = [];\n let text: string | null = null;\n let html: string | null = null;\n\n for (const entry of entries) {\n let { type, data } = entry;\n\n if (typeof data === 'string') {\n // Types are de-duplicated upstream, so each of these is seen at most once.\n if (type === 'text/plain') text = data;\n else if (type === 'text/html') html = data;\n } else if (type.startsWith('image/')) {\n const actual = await sniffImageType(data);\n if (actual === null || !isAccepted(actual, options)) continue;\n if (actual !== type) {\n data = retype(entry, data, actual);\n type = actual;\n }\n images.push(data);\n }\n\n if (entry.file) files.push(data as File);\n items.push({ type, data });\n }\n\n if (items.length === 0) {\n throw copyFailure('no-content', 'The content holds nothing that matches `accept`.');\n }\n return { source, items, text, html, images, files };\n}\n","import { CopyFailure, copyFailure, toCopyError } from './errors';\nimport type { OperationContext } from './machine-shared';\nimport { matchesMimePattern } from './mime';\nimport {\n collectClipboardItems,\n enforcePasteLimits,\n finalizePaste,\n type ClipboardItemLike,\n type PasteEntry,\n type PasteReadResult,\n type ResolvedPasteReadOptions,\n} from './paste-reader';\n\n/** Minimal structural view of `navigator.clipboard` for reading. */\nexport interface PasteClipboardLike {\n read?(): Promise<readonly ClipboardItemLike[]>;\n readText?(): Promise<string>;\n}\n\nexport interface PasteEnvironment {\n readonly isSecureContext?: boolean;\n readonly navigator?: { readonly clipboard?: PasteClipboardLike | undefined } | undefined;\n}\n\n/**\n * Reads the system clipboard. Implement it for Electron, a native bridge or tests.\n *\n * Contract: call the platform API synchronously (before any `await`) so the\n * browser still sees the user gesture, and reject with a `CopyFailure`.\n * `context.signal` aborts when the read is superseded, reset, or its host\n * unmounts; honour it to stop decoding early.\n */\nexport interface PasteAdapter {\n read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteReadResult>;\n}\n\nexport interface BrowserPasteAdapterOptions {\n /** Defaults to `window`, read lazily at paste time (SSR-safe). */\n readonly getEnvironment?: () => PasteEnvironment | undefined;\n}\n\nfunction defaultEnvironment(): PasteEnvironment | undefined {\n return typeof window === 'undefined' ? undefined : window;\n}\n\ntype ClipboardWithRead = PasteClipboardLike & Required<Pick<PasteClipboardLike, 'read'>>;\ntype ClipboardWithReadText = PasteClipboardLike & Required<Pick<PasteClipboardLike, 'readText'>>;\n\nconst canRead = (clipboard: PasteClipboardLike): clipboard is ClipboardWithRead => typeof clipboard.read === 'function';\nconst canReadText = (clipboard: PasteClipboardLike): clipboard is ClipboardWithReadText =>\n typeof clipboard.readText === 'function';\n\nasync function readPlainText(clipboard: ClipboardWithReadText, options: ResolvedPasteReadOptions): Promise<PasteReadResult> {\n let text: string;\n try {\n text = await clipboard.readText();\n } catch (cause) {\n throw new CopyFailure(toCopyError(cause, 'read'));\n }\n const entries: PasteEntry[] = text.length > 0 ? [{ type: 'text/plain', data: text, file: false }] : [];\n enforcePasteLimits(entries, options);\n return finalizePaste(entries, 'clipboard', options);\n}\n\nasync function readRich(\n clipboard: ClipboardWithRead,\n options: ResolvedPasteReadOptions,\n signal: AbortSignal | undefined,\n): Promise<PasteReadResult> {\n let items: readonly ClipboardItemLike[];\n try {\n items = await clipboard.read();\n } catch (cause) {\n throw new CopyFailure(toCopyError(cause, 'read'));\n }\n const entries = await collectClipboardItems(items, options, signal);\n return finalizePaste(entries, 'clipboard', options);\n}\n\nfunction readFromClipboard(\n env: PasteEnvironment | undefined,\n options: ResolvedPasteReadOptions,\n signal: AbortSignal | undefined,\n): Promise<PasteReadResult> {\n if (!env) throw copyFailure('unsupported', 'No browser environment: the clipboard only exists in the browser.');\n if (env.isSecureContext === false) {\n throw copyFailure('insecure-context', 'The Clipboard API requires a secure context (HTTPS or localhost).');\n }\n const clipboard = env.navigator?.clipboard;\n if (!clipboard) throw copyFailure('unsupported', 'navigator.clipboard is not available in this browser.');\n\n const plainOnly = options.accept.every((pattern) => pattern === 'text/plain');\n const acceptsPlain = options.accept.some((pattern) => matchesMimePattern('text/plain', pattern));\n\n // readText() has the widest support and the narrowest permission prompt: prefer it for plain text.\n if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options, signal);\n if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);\n throw canReadText(clipboard)\n ? copyFailure('unsupported-format', 'Reading non-text clipboard content requires navigator.clipboard.read().')\n : copyFailure('unsupported', 'This browser cannot read the clipboard.');\n}\n\n/** The default paste adapter: async Clipboard API with feature detection and honest errors. */\nexport function createBrowserPasteAdapter(options: BrowserPasteAdapterOptions = {}): PasteAdapter {\n const getEnvironment = options.getEnvironment ?? defaultEnvironment;\n return {\n read: (resolved, context) => {\n try {\n return readFromClipboard(getEnvironment(), resolved, context?.signal);\n } catch (cause) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- always a CopyFailure\n return Promise.reject(cause);\n }\n },\n };\n}\n","import { createCopyError, isRetryableError, toCopyError, type CopyError } from './errors';\nimport { createOperations, invoke, resolveMaxRetries, type OperationContext } from './machine-shared';\nimport { createBrowserPasteAdapter, type PasteAdapter } from './paste-adapter';\nimport {\n completePasteResult,\n enforcePasteLimits,\n finalizePaste,\n resolvePasteReadOptions,\n snapshotDataTransfer,\n type DataTransferLike,\n type PasteReadOptions,\n type PasteReadResult,\n type PasteResult,\n type PasteSource,\n} from './paste-reader';\n\n/* ------------------------------------------------------------------ State */\n\nexport interface PasteIdleState {\n readonly status: 'idle';\n}\nexport interface PasteReadingState {\n readonly status: 'reading';\n}\nexport interface PasteReadState {\n readonly status: 'read';\n readonly result: PasteResult;\n /** Epoch ms when the read resolved. */\n readonly at: number;\n}\nexport interface PasteErrorState {\n readonly status: 'error';\n readonly error: CopyError;\n /** Where the failed read came from. Only `'clipboard'` reads can be retried. */\n readonly source: PasteSource;\n /** `retry()` calls made since the last fresh `paste()`. */\n readonly retryCount: number;\n}\n\nexport type PasteState = PasteIdleState | PasteReadingState | PasteReadState | PasteErrorState;\nexport type PasteStatus = PasteState['status'];\n\n/**\n * `cancelled`: the read was superseded, reset, or its host unmounted before it\n * finished, so its work was aborted. Nothing to report to the user.\n */\nexport type PasteIgnoredReason = 'in-flight' | 'no-accepted-content' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';\n\n/**\n * Why an in-flight read was cancelled: `reset` (`reset()` was called),\n * `disconnect` (its host disconnected, e.g. the React component unmounted) or\n * `superseded` (a paste or drop event arrived while a read was pending).\n */\nexport type PasteCancelReason = 'reset' | 'disconnect' | 'superseded';\n\n/** What `paste()` / `pasteEvent()` / `dropEvent()` / `retry()` resolve to. They never reject. */\nexport type PasteOutcome =\n | { readonly status: 'read'; readonly result: PasteResult }\n | { readonly status: 'error'; readonly error: CopyError }\n | { readonly status: 'ignored'; readonly reason: PasteIgnoredReason };\n\n/** Structural view of a DOM / React `paste` event. */\nexport interface PasteEventLike {\n readonly clipboardData: DataTransferLike | null | undefined;\n preventDefault(): void;\n}\n\n/** Structural view of a DOM / React `drop` event. */\nexport interface PasteDropEventLike {\n readonly dataTransfer: DataTransferLike | null | undefined;\n preventDefault(): void;\n}\n\n/* ---------------------------------------------------------------- Options */\n\nexport interface PasteMachineOptions extends PasteReadOptions {\n /** Defaults to the browser Clipboard API adapter. */\n readonly adapter?: PasteAdapter;\n /** Return from `read` to `idle` after this many ms. `false` / `Infinity` / omitted = keep the result. */\n readonly resetAfterMs?: number | false;\n /**\n * Paste events: call `event.preventDefault()` when the event carried accepted\n * content, so the browser doesn't also insert it. Drop events: always call it,\n * so the browser doesn't open the dropped file. Default `true`.\n */\n readonly preventDefault?: boolean;\n /**\n * Max `retry()` calls after a failed clipboard read. Default 3. `0`\n * disables retry; `Infinity` allows unlimited retries.\n */\n readonly maxRetries?: number;\n readonly onPaste?: (result: PasteResult) => void;\n readonly onError?: (error: CopyError) => void;\n /**\n * `reset()` moved the machine back to `idle` from any other state. Not\n * called for the automatic return after `resetAfterMs`, or when already `idle`.\n */\n readonly onReset?: () => void;\n /**\n * A read in flight was cancelled before it settled: its `signal` aborted\n * and its result will not reach state or `onPaste` / `onError`. Fires\n * before `onReset` when `reset()` cancels a read.\n */\n readonly onCancel?: (reason: PasteCancelReason) => void;\n /** Clock injection for tests and deterministic environments. */\n readonly now?: () => number;\n}\n\n/** Options object, or a getter so hosts (like React) can supply the latest options. */\nexport type PasteMachineOptionsSource = PasteMachineOptions | (() => PasteMachineOptions);\n\nexport interface PasteMachine {\n readonly getSnapshot: () => PasteState;\n readonly subscribe: (listener: () => void) => () => void;\n /**\n * Reads the system clipboard via the adapter. Call it from a user gesture\n * (click, keypress). May show a permission prompt. Ignored while `reading`.\n */\n readonly paste: () => Promise<PasteOutcome>;\n /**\n * Handles a `paste` event (Ctrl/⌘+V). No permission prompt: the data is\n * already in the event. Supersedes any read in flight. Events without\n * accepted content are ignored and left untouched for the browser.\n */\n readonly pasteEvent: (event: PasteEventLike) => Promise<PasteOutcome>;\n /**\n * Handles a drag-and-drop `drop` event exactly like a paste event: same\n * `accept`, limits and image checks, `result.source === 'drop'`. Always calls\n * `event.preventDefault()` (unless `preventDefault: false`), so a rejected\n * file is not opened by the browser in place of the page.\n */\n readonly dropEvent: (event: PasteDropEventLike) => Promise<PasteOutcome>;\n /**\n * Re-reads the clipboard after a retryable failure (e.g. permission denied,\n * page not focused), up to `maxRetries`. Call it from a user gesture.\n * Paste-event failures can't be retried: their data is gone after dispatch.\n */\n readonly retry: () => Promise<PasteOutcome>;\n /** Back to `idle`. Discards any in-flight result and aborts its `signal`. */\n readonly reset: () => void;\n /**\n * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned\n * cleanup clears timers, drops in-flight results, aborts in-flight work and\n * unsticks `reading`.\n * Safe to call repeatedly (React StrictMode).\n */\n readonly connect: () => () => void;\n}\n\nexport const PASTE_IDLE_STATE: PasteIdleState = /* @__PURE__ */ Object.freeze({ status: 'idle' });\nconst PASTE_READING_STATE: PasteReadingState = /* @__PURE__ */ Object.freeze({ status: 'reading' });\nconst IGNORED_IN_FLIGHT: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'in-flight' });\nconst IGNORED_NO_CONTENT: PasteOutcome = /* @__PURE__ */ Object.freeze({\n status: 'ignored',\n reason: 'no-accepted-content',\n});\nconst IGNORED_NOTHING: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'nothing-to-retry' });\nconst IGNORED_NOT_RETRYABLE: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'not-retryable' });\nconst IGNORED_CANCELLED: PasteOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'cancelled' });\n\nfunction resolveResetDelay(value: number | false | undefined): number | null {\n if (value === undefined || value === false || value === Infinity || Number.isNaN(value)) return null;\n return Math.max(0, value);\n}\n\n/** Pure helper: can `retry()` do anything from this state? */\nexport function canRetryPasteState(state: PasteState, maxRetries?: number): boolean {\n return (\n state.status === 'error' &&\n state.source === 'clipboard' &&\n isRetryableError(state.error) &&\n state.retryCount < resolveMaxRetries(maxRetries)\n );\n}\n\nlet defaultAdapter: PasteAdapter | undefined;\nconst getDefaultAdapter = (): PasteAdapter => (defaultAdapter ??= createBrowserPasteAdapter());\n\n/** Framework-agnostic paste state machine. */\nexport function createPasteMachine(options: PasteMachineOptionsSource = {}): PasteMachine {\n const read = typeof options === 'function' ? options : (): PasteMachineOptions => options;\n const listeners = new Set<() => void>();\n let state: PasteState = PASTE_IDLE_STATE;\n let generation = 0;\n let resetTimer: ReturnType<typeof setTimeout> | undefined;\n const operations = createOperations();\n\n const now = (): number => (read().now ?? Date.now)();\n\n const setState = (next: PasteState): void => {\n if (next === state) return;\n state = next;\n for (const listener of Array.from(listeners)) listener();\n };\n\n const clearResetTimer = (): void => {\n if (resetTimer !== undefined) {\n clearTimeout(resetTimer);\n resetTimer = undefined;\n }\n };\n\n const scheduleReset = (readState: PasteReadState): void => {\n clearResetTimer();\n const delay = resolveResetDelay(read().resetAfterMs);\n if (delay === null) return;\n const remaining = Math.max(0, delay - (now() - readState.at));\n // Invariant: every transition out of `read` clears this timer, so it only ever fires while still in `readState`.\n resetTimer = setTimeout(() => {\n resetTimer = undefined;\n setState(PASTE_IDLE_STATE);\n }, remaining);\n };\n\n const settleError = (error: CopyError, source: PasteSource, retryCount: number): void => {\n setState({ status: 'error', error, source, retryCount });\n invoke(read().onError, error);\n };\n\n /** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */\n const run = (\n produce: (context: OperationContext) => Promise<PasteReadResult>,\n source: PasteSource,\n retryCount: number,\n ): Promise<PasteOutcome> => {\n clearResetTimer();\n const current = ++generation;\n const superseded = operations.abort();\n const context = operations.start();\n setState(PASTE_READING_STATE);\n if (superseded) invoke(read().onCancel, 'superseded');\n\n let pending: Promise<PasteReadResult>;\n try {\n pending = produce(context);\n } catch (cause) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified below\n pending = Promise.reject(cause);\n }\n\n // Completing inside the chain routes a malformed adapter result to the error path,\n // so `paste()` still never rejects and the machine never stays stuck in `reading`.\n return pending.then(completePasteResult).then(\n (result): PasteOutcome => {\n operations.end(context);\n if (current === generation) {\n const readState: PasteReadState = { status: 'read', result, at: now() };\n setState(readState);\n scheduleReset(readState);\n invoke(read().onPaste, result);\n }\n return { status: 'read', result };\n },\n (cause: unknown): PasteOutcome => {\n operations.end(context);\n // Work we aborted ourselves (superseded, reset, unmount) is not a failure to report.\n // Invariant: superseding an in-flight read always aborts it, so past\n // this line the read is still the current one.\n if (context.signal.aborted) return IGNORED_CANCELLED;\n const error = toCopyError(cause, 'read');\n settleError(error, source, retryCount);\n return { status: 'error', error };\n },\n );\n };\n\n const readClipboard = (retryCount: number): Promise<PasteOutcome> =>\n run(\n (context) => (read().adapter ?? getDefaultAdapter()).read(resolvePasteReadOptions(read()), context),\n 'clipboard',\n retryCount,\n );\n\n const paste = (): Promise<PasteOutcome> =>\n state.status === 'reading' ? Promise.resolve(IGNORED_IN_FLIGHT) : readClipboard(0);\n\n const retry = (): Promise<PasteOutcome> => {\n if (state.status !== 'error') return Promise.resolve(IGNORED_NOTHING);\n if (state.source !== 'clipboard' || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);\n if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {\n const error = createCopyError(\n 'max-retries-exceeded',\n `Paste failed after ${String(state.retryCount)} retries.`,\n state.error,\n );\n settleError(error, 'clipboard', state.retryCount);\n return Promise.resolve({ status: 'error', error });\n }\n return readClipboard(state.retryCount + 1);\n };\n\n /** Shared by paste and drop events: their `DataTransfer` has the same shape and lifetime. */\n const transfer = (\n data: DataTransferLike | null | undefined,\n event: { preventDefault(): void },\n source: 'event' | 'drop',\n ): Promise<PasteOutcome> => {\n const current = read();\n // An unhandled drop makes the browser open the file in place of the page, so drops are always claimed.\n if (source === 'drop' && current.preventDefault !== false) event.preventDefault();\n if (!data) return Promise.resolve(IGNORED_NO_CONTENT);\n\n let resolved: ReturnType<typeof resolvePasteReadOptions>;\n try {\n resolved = resolvePasteReadOptions(current);\n } catch (cause) {\n // Transition straight to `error` without a ghost `reading` frame.\n // `run()` would momentarily set state to `reading` before resolving the\n // error, which observers would see as a spurious state transition.\n const error = toCopyError(cause, 'read');\n ++generation;\n const superseded = operations.abort();\n clearResetTimer();\n settleError(error, source, 0);\n if (superseded) invoke(current.onCancel, 'superseded');\n return Promise.resolve({ status: 'error', error });\n }\n\n // DataTransfer is only readable during dispatch: snapshot before anything async.\n const entries = snapshotDataTransfer(data, resolved);\n if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);\n if (source === 'event' && current.preventDefault !== false) event.preventDefault();\n\n return run(\n () => {\n enforcePasteLimits(entries, resolved);\n return finalizePaste(entries, source, resolved);\n },\n source,\n 0,\n );\n };\n\n const pasteEvent = (event: PasteEventLike): Promise<PasteOutcome> => transfer(event.clipboardData, event, 'event');\n const dropEvent = (event: PasteDropEventLike): Promise<PasteOutcome> => transfer(event.dataTransfer, event, 'drop');\n\n const reset = (): void => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n const wasIdle = state.status === 'idle';\n setState(PASTE_IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'reset');\n if (!wasIdle) invoke(read().onReset);\n };\n\n const connect = (): (() => void) => {\n if (state.status === 'read') scheduleReset(state);\n return () => {\n ++generation;\n const cancelled = operations.abort();\n clearResetTimer();\n if (state.status === 'reading') setState(PASTE_IDLE_STATE);\n if (cancelled) invoke(read().onCancel, 'disconnect');\n };\n };\n\n return {\n getSnapshot: () => state,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n paste,\n pasteEvent,\n dropEvent,\n retry,\n reset,\n connect,\n };\n}\n","import { createContext, useContext, useState, type ReactNode } from 'react';\nimport { createCopyCoordinator, type CopyCoordinator } from '../core/copy-coordinator';\n\nconst CopyGroupContext = /* @__PURE__ */ createContext<CopyCoordinator | null>(null);\n\nexport interface CopyGroupProps {\n readonly children?: ReactNode;\n /**\n * Share a coordinator with code outside this tree (another root, a vanilla\n * `createCopyMachine`). Defaults to one owned by this group.\n */\n readonly coordinator?: CopyCoordinator;\n}\n\n/**\n * Every `useCopy` / `<CopyField.Root>` inside behaves like one clipboard:\n * a new successful copy returns the previously \"Copied\" one to idle.\n * Opt a single field out with `copyOptions={{ coordinator: null }}`. Groups nest; the nearest wins.\n */\nexport function CopyGroup({ children, coordinator }: CopyGroupProps) {\n const [owned] = useState(createCopyCoordinator);\n return <CopyGroupContext.Provider value={coordinator ?? owned}>{children}</CopyGroupContext.Provider>;\n}\n\n/** The nearest `<CopyGroup>`'s coordinator, or `null` outside any group. */\nexport function useCopyGroup(): CopyCoordinator | null {\n return useContext(CopyGroupContext);\n}\n","import { useEffect, useLayoutEffect, type Ref, type RefCallback } from 'react';\n\n/** `useLayoutEffect` in the browser, `useEffect` on the server (no SSR warning). */\nexport const useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;\n\nexport function mergeRefs<T>(...refs: ReadonlyArray<Ref<T> | undefined>): RefCallback<T> {\n return (node) => {\n for (const ref of refs) {\n if (typeof ref === 'function') ref(node);\n else if (ref) (ref as { current: T | null }).current = node;\n }\n };\n}\n\n/** Runs the consumer's handler first; ours is skipped if they call `preventDefault()`. */\nexport function composeEventHandlers<E extends { readonly defaultPrevented: boolean }>(\n theirs: ((event: E) => void) | undefined,\n ours: (event: E) => void,\n): (event: E) => void {\n return (event) => {\n theirs?.(event);\n if (!event.defaultPrevented) ours(event);\n };\n}\n","import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport {\n IDLE_STATE,\n canRetryState,\n createCopyMachine,\n type CopyMachine,\n type CopyMachineOptions,\n type CopyState,\n type CopyStatus,\n} from '../core/copy-machine';\nimport type { CopyCoordinator } from '../core/copy-coordinator';\nimport type { CopyError } from '../core/errors';\nimport { useCopyGroup } from './CopyGroup';\nimport { useIsomorphicLayoutEffect } from './utils';\n\nexport type UseCopyOptions = CopyMachineOptions;\n\nexport interface UseCopyResult {\n /** Full discriminated state; narrow on `state.status`. */\n readonly state: CopyState;\n readonly status: CopyStatus;\n readonly error: CopyError | null;\n /** Whether `retry()` can do anything right now. */\n readonly canRetry: boolean;\n /** Stable identity. Never rejects; resolves to a `CopyOutcome`. */\n readonly copy: CopyMachine['copy'];\n /** Stable identity. Re-attempts the last failed payload, up to `maxRetries`. */\n readonly retry: CopyMachine['retry'];\n /** Stable identity. Back to `idle`, discarding and aborting any in-flight copy. */\n readonly reset: CopyMachine['reset'];\n}\n\nconst getServerSnapshot = (): CopyState => IDLE_STATE;\n\n/** An explicit `coordinator` (including `null`) wins over the surrounding `<CopyGroup>`. */\nfunction withGroup(options: UseCopyOptions, group: CopyCoordinator | null): UseCopyOptions {\n return options.coordinator !== undefined || group === null ? options : { ...options, coordinator: group };\n}\n\n/**\n * Copy state machine bound to a component. Options may change on every render\n * (inline callbacks are fine); the latest ones are always used.\n */\nexport function useCopy(options: UseCopyOptions = {}): UseCopyResult {\n const effective = withGroup(options, useCopyGroup());\n const optionsRef = useRef(effective);\n useIsomorphicLayoutEffect(() => {\n optionsRef.current = effective;\n });\n\n const [machine] = useState(() => createCopyMachine(() => optionsRef.current));\n useEffect(() => machine.connect(), [machine]);\n\n const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot);\n const canRetry = canRetryState(state, effective.maxRetries);\n\n return useMemo(\n () => ({\n state,\n status: state.status,\n error: state.status === 'error' ? state.error : null,\n canRetry,\n copy: machine.copy,\n retry: machine.retry,\n reset: machine.reset,\n }),\n [state, canRetry, machine],\n );\n}\n","import { useEffect, useRef, useState, type RefCallback } from 'react';\nimport { registerCopyInterceptor, type CopyInterceptorOptions } from '../core/copy-interceptor';\nimport { useIsomorphicLayoutEffect } from './utils';\n\nexport interface UseCopyInterceptorOptions extends CopyInterceptorOptions {\n /** Set `false` to stop intercepting without unmounting. Default `true`. */\n readonly enabled?: boolean;\n}\n\nexport interface UseCopyInterceptorResult<T extends Element> {\n /** Attach to the element whose content you want to control. */\n readonly ref: RefCallback<T>;\n}\n\n/**\n * Rewrites, redacts or blocks native copies (Ctrl/Cmd+C, context menu) and\n * cuts whose selection touches the referenced element.\n *\n * ```tsx\n * const { ref } = useCopyInterceptor<HTMLElement>({\n * transform: ({ text }) => `${text}\\n\\nSource: ${location.href}`,\n * });\n * return <article ref={ref}>…</article>;\n * ```\n *\n * The transform runs synchronously inside the event and always sees the\n * latest props; changing it never re-subscribes. SSR-safe.\n */\nexport function useCopyInterceptor<T extends Element = HTMLElement>(\n options: UseCopyInterceptorOptions,\n): UseCopyInterceptorResult<T> {\n const optionsRef = useRef(options);\n useIsomorphicLayoutEffect(() => {\n optionsRef.current = options;\n });\n\n const [node, setNode] = useState<T | null>(null);\n const enabled = options.enabled !== false;\n\n useEffect(() => {\n if (!node || !enabled) return undefined;\n return registerCopyInterceptor(node, () => optionsRef.current);\n }, [node, enabled]);\n\n return { ref: setNode };\n}\n","import { useCallback, useRef, useSyncExternalStore } from 'react';\n\nconst getServerSnapshot = (): boolean => false;\n\n/** SSR-safe media query subscription. Server and hydration render `false`. */\nexport function useMediaQuery(query: string): boolean {\n // Cache the MediaQueryList so `subscribe` always attaches to the same\n // object. We call `matchMedia()` once per query string (per mount / query\n // change) and hold the reference for the duration. The `.matches` accessor\n // on the real MediaQueryList is live, so `getSnapshot` reads the current\n // value without re-calling `matchMedia()` on every render.\n const listRef = useRef<MediaQueryList | null>(null);\n const queryRef = useRef<string>('');\n\n const getList = useCallback((): MediaQueryList | null => {\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return null;\n // Invalidate the cache when the query string changes.\n if (listRef.current === null || queryRef.current !== query) {\n listRef.current = window.matchMedia(query);\n queryRef.current = query;\n }\n return listRef.current;\n }, [query]);\n\n const subscribe = useCallback(\n (onChange: () => void) => {\n const list = getList();\n if (!list) return () => undefined;\n list.addEventListener('change', onChange);\n return () => {\n list.removeEventListener('change', onChange);\n };\n },\n [getList],\n );\n\n const getSnapshot = useCallback(() => getList()?.matches ?? false, [getList]);\n\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n","import {\n useEffect,\n useMemo,\n useRef,\n useState,\n type FocusEventHandler,\n type PointerEventHandler,\n type RefCallback,\n} from 'react';\nimport { useMediaQuery } from './useMediaQuery';\n\n/** Why the target is currently revealed, in priority order. */\nexport type RevealReason = 'forced' | 'focus' | 'hover' | 'touch' | 'no-hover-device';\n\nexport interface UseRevealOnInteractionOptions {\n /** Always reveal (e.g. a \"show actions\" user setting). */\n readonly alwaysVisible?: boolean;\n}\n\nexport interface RevealTargetProps<T extends HTMLElement> {\n readonly ref: RefCallback<T>;\n readonly onPointerEnter: PointerEventHandler<T>;\n readonly onPointerLeave: PointerEventHandler<T>;\n readonly onPointerDown: PointerEventHandler<T>;\n readonly onFocus: FocusEventHandler<T>;\n readonly onBlur: FocusEventHandler<T>;\n}\n\nexport interface UseRevealOnInteractionResult<T extends HTMLElement> {\n readonly visible: boolean;\n readonly reason: RevealReason | null;\n /** Spread onto the container that owns the hidden actions. */\n readonly targetProps: RevealTargetProps<T>;\n}\n\nfunction isFocusVisible(element: EventTarget): boolean {\n if (!(element instanceof Element)) return true;\n try {\n return element.matches(':focus-visible');\n } catch {\n return true; // Engines without :focus-visible: reveal on any focus, the accessible default.\n }\n}\n\n/**\n * Reveals secondary actions on hover, keyboard focus and touch, and always on\n * devices that cannot hover. Hover and focus are tracked independently, so a\n * touchscreen laptop never gets stuck in a \"touch only\" mode.\n *\n * Keep the actions in the DOM and in the tab order; hide them visually with\n * CSS keyed off `visible` (or `data-revealed`), never with `display: none`.\n */\nexport function useRevealOnInteraction<T extends HTMLElement = HTMLElement>(\n options: UseRevealOnInteractionOptions = {},\n): UseRevealOnInteractionResult<T> {\n const [hovered, setHovered] = useState(false);\n const [focused, setFocused] = useState(false);\n const [touched, setTouched] = useState(false);\n const cannotHover = useMediaQuery('(hover: none)');\n const nodeRef = useRef<T | null>(null);\n\n // A touch reveal lasts until the user touches somewhere else.\n useEffect(() => {\n if (!touched) return undefined;\n const dismiss = (event: PointerEvent): void => {\n const node = nodeRef.current;\n if (node && event.target instanceof Node && node.contains(event.target)) return;\n setTouched(false);\n };\n document.addEventListener('pointerdown', dismiss, true);\n return () => {\n document.removeEventListener('pointerdown', dismiss, true);\n };\n }, [touched]);\n\n const targetProps = useMemo<RevealTargetProps<T>>(\n () => ({\n ref: (node) => {\n nodeRef.current = node;\n },\n onPointerEnter: (event) => {\n if (event.pointerType !== 'touch') setHovered(true);\n },\n onPointerLeave: (event) => {\n if (event.pointerType !== 'touch') setHovered(false);\n },\n onPointerDown: (event) => {\n if (event.pointerType === 'touch') setTouched(true);\n },\n onFocus: (event) => {\n // Mouse clicks focus buttons too; only keyboard-style focus should pin the reveal.\n setFocused(isFocusVisible(event.target));\n },\n onBlur: (event) => {\n const next = event.relatedTarget;\n if (next instanceof Node && event.currentTarget.contains(next)) return;\n setFocused(false);\n },\n }),\n [],\n );\n\n const reason: RevealReason | null = options.alwaysVisible\n ? 'forced'\n : focused\n ? 'focus'\n : hovered\n ? 'hover'\n : touched\n ? 'touch'\n : cannotHover\n ? 'no-hover-device'\n : null;\n\n return { visible: reason !== null, reason, targetProps };\n}\n","import { useEffect, useState } from 'react';\nimport type { CopyStatus } from '../core/copy-machine';\nimport { useIsomorphicLayoutEffect } from './utils';\n\nexport const DEFAULT_PENDING_DELAY_MS = 150;\nexport const DEFAULT_MIN_PENDING_MS = 400;\n\nexport interface UseDisplayStatusOptions {\n /** Only show `copying` if the copy takes longer than this. Default 150 ms. */\n readonly pendingDelayMs?: number;\n /** Once `copying` is shown, keep it visible at least this long. Default 400 ms. */\n readonly minPendingMs?: number;\n}\n\ntype SettledStatus = Exclude<CopyStatus, 'copying'>;\n\n/**\n * Presentation-only view of a copy status that never flickers.\n *\n * The real `status` is honest and can be `copying` for a single frame (text\n * copies take ~1-5 ms). Rendering that directly flashes a \"Copying…\" label.\n * This hook keeps showing the previous state during fast copies, and when a\n * copy is genuinely slow it shows `copying` for a minimum time instead of a blink.\n *\n * It never changes the state machine: use `status` for logic, this for pixels.\n */\nexport function useDisplayStatus(status: CopyStatus, options: UseDisplayStatusOptions = {}): CopyStatus {\n const pendingDelayMs = Math.max(0, options.pendingDelayMs ?? DEFAULT_PENDING_DELAY_MS);\n const minPendingMs = Math.max(0, options.minPendingMs ?? DEFAULT_MIN_PENDING_MS);\n\n // Last non-copying status, shown while a fast copy is in flight. It is only read\n // while `copying`, so it is synced in a layout effect: never with a render-phase\n // setState, which on React 18 corrupts `useSyncExternalStore`'s snapshot tracking\n // and left CopyField stuck on \"Copied\" after a fast copy.\n const [settled, setSettled] = useState<SettledStatus>(status === 'copying' ? 'idle' : status);\n useIsomorphicLayoutEffect(() => {\n if (status !== 'copying') setSettled(status);\n }, [status]);\n\n // When the pending indicator became visible, or null while it is hidden.\n const [pendingShownAt, setPendingShownAt] = useState<number | null>(null);\n\n useEffect(() => {\n if (status !== 'copying') return undefined;\n const timer = setTimeout(() => {\n setPendingShownAt(Date.now());\n }, pendingDelayMs);\n return () => {\n clearTimeout(timer);\n };\n }, [status, pendingDelayMs]);\n\n useEffect(() => {\n if (status === 'copying' || pendingShownAt === null) return undefined;\n const remaining = Math.max(0, minPendingMs - (Date.now() - pendingShownAt));\n const timer = setTimeout(() => {\n setPendingShownAt(null);\n }, remaining);\n return () => {\n clearTimeout(timer);\n };\n }, [status, pendingShownAt, minPendingMs]);\n\n if (pendingShownAt !== null) return 'copying';\n return status === 'copying' ? settled : status;\n}\n","import { useEffect, useRef, type CSSProperties, type HTMLAttributes } from 'react';\n\n/** Hides content visually while keeping it available to assistive technology. */\nexport const visuallyHiddenStyle: CSSProperties = {\n position: 'absolute',\n width: 1,\n height: 1,\n padding: 0,\n margin: -1,\n overflow: 'hidden',\n clip: 'rect(0, 0, 0, 0)',\n whiteSpace: 'nowrap',\n border: 0,\n};\n\nexport interface LiveRegionProps\n extends Omit<HTMLAttributes<HTMLSpanElement>, 'children' | 'role' | 'aria-live' | 'aria-atomic'> {\n /** Changing this text is what triggers the announcement. Empty string = silent. */\n readonly message: string;\n readonly politeness?: 'polite' | 'assertive';\n readonly visuallyHidden?: boolean;\n}\n\n/**\n * Always-mounted announcer. Screen readers ignore regions that are inserted\n * together with their content, so this must render before the first message.\n *\n * **Mount safety**: the live region is intentionally empty on mount. We write\n * the message into the DOM imperatively (via a ref) only after the element has\n * been live for at least one browser paint. This prevents SSR hydration and\n * strict-mode double-mount from producing a spurious announcement on some\n * screen readers (JAWS / NVDA observe the initial DOM during hydration and\n * re-read regions that already have text content).\n *\n * **WCAG 4.1.3 / ARIA spec**: we use `role=\"status\"` with explicit `aria-live`\n * rather than `role=\"alert\"`. `role=\"alert\"` interrupts any sentence being\n * spoken even in polite mode, which is inappropriate for copy feedback.\n * `role=\"status\"` + `aria-live` is correct for both politeness levels.\n */\nexport function LiveRegion({\n message,\n politeness = 'polite',\n visuallyHidden = true,\n style,\n ...rest\n}: LiveRegionProps) {\n const spanRef = useRef<HTMLSpanElement>(null);\n const mountedRef = useRef(false);\n\n useEffect(() => {\n mountedRef.current = true;\n }, []);\n\n useEffect(() => {\n const span = spanRef.current;\n /* c8 ignore next -- spanRef.current is always set by mount; guard for unmounted edge case */\n if (!span) return;\n // Delay the first write by one tick so the live region is registered with\n // the AT before any content lands in it. Subsequent updates are immediate.\n /* c8 ignore next -- jsdom effects run synchronously so mountedRef.current is always true here; this guard only fires in real browsers during the initial paint */\n if (!mountedRef.current) return;\n span.textContent = message;\n }, [message]);\n\n return (\n <span\n {...rest}\n ref={spanRef}\n role=\"status\"\n aria-live={politeness}\n aria-atomic=\"true\"\n style={visuallyHidden ? { ...visuallyHiddenStyle, ...style } : style}\n />\n );\n}\n","import { useMediaQuery } from './useMediaQuery';\n\n/**\n * Default trigger label shared by `CopyField` and `PasteField`: every state's\n * text is stacked in one grid cell, so the button is always as wide as its\n * longest label and never resizes (no layout shift). Only the active label is\n * visible and exposed to assistive tech; the crossfade is skipped when the\n * user prefers reduced motion.\n */\nexport function TriggerLabel<S extends string>({\n status,\n labels,\n}: {\n readonly status: S;\n readonly labels: Readonly<Record<S, string>>;\n}) {\n const reduceMotion = useMediaQuery('(prefers-reduced-motion: reduce)');\n return (\n <span style={{ display: 'inline-grid' }}>\n {(Object.keys(labels) as S[]).map((candidate) => {\n const active = candidate === status;\n return (\n <span\n key={candidate}\n data-trigger-label={candidate}\n data-active={active ? '' : undefined}\n aria-hidden={!active || undefined}\n style={{\n gridArea: '1 / 1',\n opacity: active ? 1 : 0,\n visibility: active ? 'visible' : 'hidden',\n ...(reduceMotion ? {} : { transition: 'opacity 150ms ease, visibility 150ms' }),\n }}\n >\n {labels[candidate]}\n </span>\n );\n })}\n </span>\n );\n}\n","import {\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useId,\n useMemo,\n type ButtonHTMLAttributes,\n type HTMLAttributes,\n type ReactNode,\n} from 'react';\nimport type { CopyOutcome, CopyState, CopyStatus } from '../core/copy-machine';\nimport { describeCopyError, type CopyError } from '../core/errors';\nimport type { CopySource } from '../core/payload';\nimport { LiveRegion } from './LiveRegion';\nimport { TriggerLabel } from './TriggerLabel';\nimport { useDisplayStatus, type UseDisplayStatusOptions } from './useDisplayStatus';\nimport { useCopy, type UseCopyOptions, type UseCopyResult } from './useCopy';\nimport { useRevealOnInteraction, type RevealReason } from './useRevealOnInteraction';\nimport { composeEventHandlers, mergeRefs } from './utils';\n\nexport interface CopyFieldMessages {\n /** Announced to screen readers on success. */\n readonly copied: string;\n /** Announced on failure. Defaults to {@link describeCopyError}. */\n readonly error: (error: CopyError) => string;\n /**\n * Accessible name of the trigger button. Receives the field's `label` prop.\n * The returned string must not be empty.\n */\n readonly triggerLabel: (label: string) => string;\n}\n\nexport const defaultCopyFieldMessages: CopyFieldMessages = {\n copied: 'Copied to clipboard',\n error: describeCopyError,\n triggerLabel: (label) => `Copy ${label}`,\n};\n\nexport interface CopyFieldContextValue extends UseCopyResult {\n readonly label: string;\n readonly labelId: string;\n readonly valueId: string;\n readonly revealed: boolean;\n readonly revealReason: RevealReason | null;\n readonly messages: CopyFieldMessages;\n /** Text shown by `<CopyField.Value>` when the value is plain text; otherwise `null`. */\n readonly displayValue: string | null;\n /** Flicker-free status for rendering. Use `status` for logic, this for pixels. */\n readonly displayStatus: CopyStatus;\n /** Copies the field's current value. */\n readonly copyValue: () => Promise<CopyOutcome>;\n}\n\nconst CopyFieldContext = /* @__PURE__ */ createContext<CopyFieldContextValue | null>(null);\n\n/** Access field state to build custom parts. Must be used inside `<CopyField.Root>`. */\nexport function useCopyField(): CopyFieldContextValue {\n const context = useContext(CopyFieldContext);\n if (!context) throw new Error('useCopyField() must be used inside <CopyField.Root>.');\n return context;\n}\n\n/** Maps non-text payload kinds to a human-readable description for screen readers. */\nconst KIND_LABELS: Readonly<Record<string, string>> = /* @__PURE__ */ Object.freeze(\n Object.assign(Object.create(null) as Record<string, string>, {\n html: 'Rich text',\n image: 'Image',\n json: 'JSON data',\n multi: 'Mixed content',\n }),\n);\n\n/**\n * Returns the value's text representation when it is plain text, or a\n * descriptive fallback for non-text payloads so screen-reader users understand\n * what will be copied (A1: `CopyField.Value` must never be silent).\n */\nfunction getDisplayValue(value: CopySource): string | null {\n if (typeof value === 'string') return value;\n if (typeof value === 'function') return null; // dynamic: no stable preview\n if (value.kind === 'text') return value.value;\n return KIND_LABELS[value.kind] ?? null;\n}\n\n/* ------------------------------------------------------------------ Root */\n\nexport interface CopyFieldRootProps\n extends Omit<HTMLAttributes<HTMLDivElement>, 'onCopy' | 'onError'>,\n UseDisplayStatusOptions {\n /** What to copy. Pass a function to read the latest value at click time. */\n readonly value: CopySource;\n /** Human label, used for the trigger's accessible name (\"Copy Email\"). */\n readonly label: string;\n readonly copyOptions?: UseCopyOptions;\n readonly messages?: Partial<CopyFieldMessages>;\n /** Skip hover/focus reveal and always show the trigger. */\n readonly alwaysVisible?: boolean;\n /** Render the built-in live region. Disable if your app has a global announcer. Default `true`. */\n readonly announce?: boolean;\n}\n\nconst Root = /* @__PURE__ */ forwardRef<HTMLDivElement, CopyFieldRootProps>(function CopyFieldRoot(\n {\n value,\n label,\n copyOptions,\n messages: messageOverrides,\n alwaysVisible = false,\n announce = true,\n pendingDelayMs,\n minPendingMs,\n children,\n onPointerEnter,\n onPointerLeave,\n onPointerDown,\n onFocus,\n onBlur,\n ...rest\n },\n forwardedRef,\n) {\n const copyState = useCopy(copyOptions);\n const displayStatus = useDisplayStatus(copyState.status, {\n ...(pendingDelayMs === undefined ? {} : { pendingDelayMs }),\n ...(minPendingMs === undefined ? {} : { minPendingMs }),\n });\n const reveal = useRevealOnInteraction<HTMLDivElement>({ alwaysVisible });\n const baseId = useId();\n const labelId = `${baseId}-label`;\n const valueId = `${baseId}-value`;\n\n const messages = useMemo<CopyFieldMessages>(\n () => ({ ...defaultCopyFieldMessages, ...messageOverrides }),\n [messageOverrides],\n );\n\n const { copy } = copyState;\n const copyValue = useCallback(() => copy(value), [copy, value]);\n const { targetProps } = reveal;\n const ref = useMemo(() => mergeRefs(targetProps.ref, forwardedRef), [targetProps.ref, forwardedRef]);\n\n const context = useMemo<CopyFieldContextValue>(\n () => ({\n ...copyState,\n label,\n labelId,\n valueId,\n revealed: reveal.visible,\n revealReason: reveal.reason,\n messages,\n displayValue: getDisplayValue(value),\n displayStatus,\n copyValue,\n }),\n [copyState, label, labelId, valueId, reveal.visible, reveal.reason, messages, value, displayStatus, copyValue],\n );\n\n const { state } = copyState;\n const announcement =\n state.status === 'copied' ? messages.copied : state.status === 'error' ? messages.error(state.error) : '';\n\n return (\n <CopyFieldContext.Provider value={context}>\n <div\n {...rest}\n ref={ref}\n data-state={state.status}\n data-display-state={displayStatus}\n data-revealed={reveal.visible ? '' : undefined}\n onPointerEnter={composeEventHandlers(onPointerEnter, targetProps.onPointerEnter)}\n onPointerLeave={composeEventHandlers(onPointerLeave, targetProps.onPointerLeave)}\n onPointerDown={composeEventHandlers(onPointerDown, targetProps.onPointerDown)}\n onFocus={composeEventHandlers(onFocus, targetProps.onFocus)}\n onBlur={composeEventHandlers(onBlur, targetProps.onBlur)}\n >\n {children}\n {announce ? <LiveRegion message={announcement} /> : null}\n </div>\n </CopyFieldContext.Provider>\n );\n});\n\n/* ----------------------------------------------------------- Label/Value */\n\nexport type CopyFieldLabelProps = HTMLAttributes<HTMLSpanElement>;\n\nconst Label = /* @__PURE__ */ forwardRef<HTMLSpanElement, CopyFieldLabelProps>(function CopyFieldLabel(\n { children, ...rest },\n ref,\n) {\n const field = useCopyField();\n return (\n <span {...rest} ref={ref} id={field.labelId}>\n {children ?? field.label}\n </span>\n );\n});\n\nexport type CopyFieldValueProps = HTMLAttributes<HTMLSpanElement>;\n\nconst Value = /* @__PURE__ */ forwardRef<HTMLSpanElement, CopyFieldValueProps>(function CopyFieldValue(\n { children, ...rest },\n ref,\n) {\n const field = useCopyField();\n return (\n <span {...rest} ref={ref} id={field.valueId}>\n {children ?? field.displayValue}\n </span>\n );\n});\n\n/* --------------------------------------------------------------- Trigger */\n\nexport interface CopyFieldTriggerRenderProps {\n /** The real state. Use for logic. */\n readonly status: CopyStatus;\n /** Flicker-free state. Use for what you render. */\n readonly displayStatus: CopyStatus;\n readonly state: CopyState;\n readonly revealed: boolean;\n readonly canRetry: boolean;\n}\n\nexport interface CopyFieldTriggerProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'type'> {\n /** Static content, or a render function receiving the live state (icons, labels, spinners). */\n readonly children?: ReactNode | ((props: CopyFieldTriggerRenderProps) => ReactNode);\n}\n\nconst DEFAULT_TRIGGER_TEXT: Readonly<Record<CopyStatus, string>> = {\n idle: 'Copy',\n copying: 'Copying…',\n copied: 'Copied',\n error: 'Retry',\n};\n\nconst Trigger = /* @__PURE__ */ forwardRef<HTMLButtonElement, CopyFieldTriggerProps>(function CopyFieldTrigger(\n { children, onClick, 'aria-label': ariaLabel, ...rest },\n ref,\n) {\n const field = useCopyField();\n const renderProps: CopyFieldTriggerRenderProps = {\n status: field.status,\n displayStatus: field.displayStatus,\n state: field.state,\n revealed: field.revealed,\n canRetry: field.canRetry,\n };\n\n // Guard: `triggerLabel` must return a non-empty string; \"Copy undefined\" is\n // not a valid accessible name (happens when the consumer omits `label`).\n const safeAriaLabel =\n (ariaLabel ?? field.messages.triggerLabel(field.label)) || defaultCopyFieldMessages.triggerLabel(field.label);\n\n return (\n <button\n {...rest}\n ref={ref}\n // Never `disabled` while copying: disabling a focused button drops keyboard focus.\n type=\"button\"\n aria-label={safeAriaLabel}\n aria-busy={field.status === 'copying' ? true : undefined}\n data-state={field.status}\n data-display-state={field.displayStatus}\n data-revealed={field.revealed ? '' : undefined}\n onClick={composeEventHandlers(onClick, () => {\n void field.copyValue();\n })}\n >\n {typeof children === 'function'\n ? children(renderProps)\n : (children ?? <TriggerLabel status={field.displayStatus} labels={DEFAULT_TRIGGER_TEXT} />)}\n </button>\n );\n});\n\n/**\n * Headless compound component for a labelled, copyable value.\n *\n * Styling hooks on Root and Trigger:\n * - `data-display-state=\"idle|copying|copied|error\"`: flicker-free, style with this\n * - `data-state`: the real, instantaneous state, for logic and tests\n * - `data-revealed`: present while the trigger should be visible\n */\nexport const CopyField = { Root, Label, Value, Trigger } as const;\n","import {\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n type ClipboardEventHandler,\n type DragEventHandler,\n} from 'react';\nimport type { CopyError } from '../core/errors';\nimport {\n PASTE_IDLE_STATE,\n canRetryPasteState,\n createPasteMachine,\n type PasteMachine,\n type PasteMachineOptions,\n type PasteState,\n type PasteStatus,\n} from '../core/paste-machine';\nimport { canAcceptDrag, resolvePasteReadOptions, type DataTransferLike, type PasteResult } from '../core/paste-reader';\nimport { useIsomorphicLayoutEffect } from './utils';\n\nexport interface UsePasteOptions extends PasteMachineOptions {\n /**\n * Also handle Ctrl/⌘+V anywhere on the page (chat-style \"paste a screenshot\").\n * Events an element already handled (`defaultPrevented`) are skipped. Default `false`.\n */\n readonly listenOnDocument?: boolean;\n}\n\nexport interface PasteTargetProps<T extends Element> {\n readonly onPaste: ClipboardEventHandler<T>;\n}\n\nexport interface PasteDropTargetProps<T extends Element> {\n readonly onDragEnter: DragEventHandler<T>;\n readonly onDragOver: DragEventHandler<T>;\n readonly onDragLeave: DragEventHandler<T>;\n readonly onDrop: DragEventHandler<T>;\n}\n\nexport interface UsePasteResult<T extends Element = HTMLElement> {\n /** Full discriminated state; narrow on `state.status`. */\n readonly state: PasteState;\n readonly status: PasteStatus;\n /** The latest result while `status === 'read'`, otherwise `null`. */\n readonly result: PasteResult | null;\n readonly error: CopyError | null;\n /** Whether `retry()` can do anything right now. */\n readonly canRetry: boolean;\n /** Stable identity. Reads the clipboard from a user gesture. Never rejects. */\n readonly paste: PasteMachine['paste'];\n /** Stable identity. Handles a paste event you received yourself. Never rejects. */\n readonly pasteEvent: PasteMachine['pasteEvent'];\n /** Stable identity. Handles a drop event you received yourself. Never rejects. */\n readonly dropEvent: PasteMachine['dropEvent'];\n /** Stable identity. Re-reads the clipboard after a retryable failure, up to `maxRetries`. */\n readonly retry: PasteMachine['retry'];\n /** Stable identity. Back to `idle`, discarding and aborting any in-flight read. */\n readonly reset: PasteMachine['reset'];\n /** Spread onto an element (drop zone, textarea, editor) to accept Ctrl/⌘+V there. */\n readonly targetProps: PasteTargetProps<T>;\n /**\n * Spread onto one element to accept drag-and-drop there, through the same\n * `accept` and limits as paste. Only drags carrying accepted types show the\n * drop cursor. Separate from `targetProps` so text fields keep native drops.\n */\n readonly dropTargetProps: PasteDropTargetProps<T>;\n /** An accepted drag is over the `dropTargetProps` element. Style the drop zone with it. */\n readonly isDragOver: boolean;\n}\n\nconst getServerSnapshot = (): PasteState => PASTE_IDLE_STATE;\n\nconst DRAG_END_EVENTS = ['drop', 'dragend'] as const;\n\n/** A text field or editable region nested inside the drop target, which should keep its native drop. */\nconst isNestedEditable = (event: { readonly target: EventTarget; readonly currentTarget: EventTarget }): boolean => {\n const { target, currentTarget } = event;\n if (target === currentTarget || !(target instanceof HTMLElement)) return false;\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') return true;\n // Inside an editable drop target every child is editable too: those drops are still ours to check.\n return target.isContentEditable && !(currentTarget instanceof HTMLElement && currentTarget.isContentEditable);\n};\n\n/** The drop effect the drag source allows, preferring copy: an effect it disallows cancels the drop. */\nconst dropEffectFor = (allowed: string): DataTransfer['dropEffect'] =>\n /^(all|uninitialized|copy)/.test(allowed) ? 'copy' : /move/i.test(allowed) ? 'move' : allowed === 'link' ? 'link' : 'none';\n\n/**\n * Paste state machine bound to a component. Supports a \"Paste\" button\n * (`paste()`, may prompt for permission), keyboard paste (`targetProps` or\n * `listenOnDocument`, no prompt) and drag-and-drop (`dropTargetProps`).\n * Options may change on every render.\n *\n * Everything in the result is untrusted user input.\n */\nexport function usePaste<T extends Element = HTMLElement>(options: UsePasteOptions = {}): UsePasteResult<T> {\n const optionsRef = useRef(options);\n useIsomorphicLayoutEffect(() => {\n optionsRef.current = options;\n });\n\n const [machine] = useState(() => createPasteMachine(() => optionsRef.current));\n useEffect(() => machine.connect(), [machine]);\n\n const listenOnDocument = options.listenOnDocument === true;\n useEffect(() => {\n if (!listenOnDocument) return undefined;\n const onPaste = (event: ClipboardEvent): void => {\n if (!event.defaultPrevented) void machine.pasteEvent(event);\n };\n document.addEventListener('paste', onPaste);\n return () => {\n document.removeEventListener('paste', onPaste);\n };\n }, [listenOnDocument, machine]);\n\n const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot);\n const canRetry = canRetryPasteState(state, options.maxRetries);\n\n const targetProps = useMemo<PasteTargetProps<T>>(\n () => ({\n onPaste: (event) => {\n void machine.pasteEvent(event);\n },\n }),\n [machine],\n );\n\n const [isDragOver, setIsDragOver] = useState(false);\n // dragenter/dragleave also fire for every child crossed; count them so moving inside doesn't flicker.\n const dragDepth = useRef(0);\n const [endDrag] = useState(() => (): void => {\n dragDepth.current = 0;\n setIsDragOver(false);\n });\n const dropTargetProps = useMemo<PasteDropTargetProps<T>>(() => {\n const accepts = (data: DataTransferLike): boolean => {\n try {\n return canAcceptDrag(data, resolvePasteReadOptions(optionsRef.current));\n } catch {\n return true; // Invalid options: let the drop through so it reports `invalid-payload`.\n }\n };\n return {\n onDragEnter: (event) => {\n dragDepth.current += 1;\n if (accepts(event.dataTransfer)) setIsDragOver(true);\n },\n onDragOver: (event) => {\n if (isNestedEditable(event)) return; // A field inside the target keeps its native drop.\n // Always claimed: otherwise a rejected file would be opened in place of the page.\n // `dropEffect: 'none'` then cancels the drop instead.\n event.preventDefault();\n event.dataTransfer.dropEffect = accepts(event.dataTransfer)\n ? dropEffectFor(event.dataTransfer.effectAllowed)\n : 'none';\n },\n onDragLeave: (event) => {\n const next = event.relatedTarget;\n dragDepth.current -= 1;\n // `relatedTarget` (where supported) catches a count left high by a child removed mid-drag.\n if (dragDepth.current <= 0 || (next instanceof Node && !event.currentTarget.contains(next))) endDrag();\n },\n onDrop: (event) => {\n endDrag();\n if (!isNestedEditable(event)) void machine.dropEvent(event);\n },\n };\n }, [machine, endDrag]);\n\n // A drop handled elsewhere (a consumer `onDrop` that took over, a child that\n // stopped propagation) or a cancelled drag never reaches `onDrop` / `onDragLeave`.\n useEffect(() => {\n if (!isDragOver) return undefined;\n for (const type of DRAG_END_EVENTS) window.addEventListener(type, endDrag, true);\n return () => {\n for (const type of DRAG_END_EVENTS) window.removeEventListener(type, endDrag, true);\n };\n }, [isDragOver, endDrag]);\n\n return useMemo(\n () => ({\n state,\n status: state.status,\n result: state.status === 'read' ? state.result : null,\n error: state.status === 'error' ? state.error : null,\n canRetry,\n paste: machine.paste,\n pasteEvent: machine.pasteEvent,\n dropEvent: machine.dropEvent,\n retry: machine.retry,\n reset: machine.reset,\n targetProps,\n dropTargetProps,\n isDragOver,\n }),\n [state, canRetry, machine, targetProps, dropTargetProps, isDragOver],\n );\n}\n","import { useEffect, useState } from 'react';\nimport type { PasteStatus } from '../core/paste-machine';\nimport { useIsomorphicLayoutEffect } from './utils';\n\nexport const DEFAULT_PASTE_PENDING_DELAY_MS = 150;\nexport const DEFAULT_PASTE_MIN_PENDING_MS = 400;\n\nexport interface UsePasteDisplayStatusOptions {\n /** Only show `reading` if the paste takes longer than this. Default 150 ms. */\n readonly pendingDelayMs?: number;\n /** Once `reading` is shown, keep it visible at least this long. Default 400 ms. */\n readonly minPendingMs?: number;\n}\n\ntype SettledPasteStatus = Exclude<PasteStatus, 'reading'>;\n\n/**\n * Presentation-only view of a paste status that never flickers.\n *\n * The real `status` is honest and can be `reading` for a single render frame\n * (plain-text reads take ~1-5 ms). Rendering that directly flashes a \"Reading…\"\n * label. This hook keeps showing the previous settled status during fast pastes,\n * and when a paste is genuinely slow it shows `reading` for a minimum time\n * instead of a blink.\n *\n * It never changes the state machine: use `status` for logic, this for pixels.\n */\nexport function usePasteDisplayStatus(status: PasteStatus, options: UsePasteDisplayStatusOptions = {}): PasteStatus {\n const pendingDelayMs = Math.max(0, options.pendingDelayMs ?? DEFAULT_PASTE_PENDING_DELAY_MS);\n const minPendingMs = Math.max(0, options.minPendingMs ?? DEFAULT_PASTE_MIN_PENDING_MS);\n\n // Last non-reading status, shown while a fast paste is in flight. Only read\n // while `reading`, so synced in a layout effect to avoid useSyncExternalStore\n // snapshot-tracking corruption on React 18.\n const [settled, setSettled] = useState<SettledPasteStatus>(status === 'reading' ? 'idle' : status);\n useIsomorphicLayoutEffect(() => {\n if (status !== 'reading') setSettled(status);\n }, [status]);\n\n // When the pending indicator became visible, or null while it is hidden.\n const [pendingShownAt, setPendingShownAt] = useState<number | null>(null);\n\n useEffect(() => {\n if (status !== 'reading') return undefined;\n const timer = setTimeout(() => {\n setPendingShownAt(Date.now());\n }, pendingDelayMs);\n return () => {\n clearTimeout(timer);\n };\n }, [status, pendingDelayMs]);\n\n useEffect(() => {\n if (status === 'reading' || pendingShownAt === null) return undefined;\n const remaining = Math.max(0, minPendingMs - (Date.now() - pendingShownAt));\n const timer = setTimeout(() => {\n setPendingShownAt(null);\n }, remaining);\n return () => {\n clearTimeout(timer);\n };\n }, [status, pendingShownAt, minPendingMs]);\n\n if (pendingShownAt !== null) return 'reading';\n return status === 'reading' ? settled : status;\n}\n","import {\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useEffect,\n useId,\n useMemo,\n useState,\n type ButtonHTMLAttributes,\n type DragEventHandler,\n type HTMLAttributes,\n type ReactNode,\n} from 'react';\nimport type { PasteOutcome, PasteState, PasteStatus } from '../core/paste-machine';\nimport { describePasteError, type CopyError } from '../core/errors';\nimport type { PasteResult, PasteSource } from '../core/paste-reader';\nimport { LiveRegion } from './LiveRegion';\nimport { TriggerLabel } from './TriggerLabel';\nimport { usePasteDisplayStatus, type UsePasteDisplayStatusOptions } from './usePasteDisplayStatus';\nimport { usePaste, type PasteDropTargetProps, type UsePasteOptions, type UsePasteResult } from './usePaste';\nimport { useRevealOnInteraction, type RevealReason } from './useRevealOnInteraction';\nimport { composeEventHandlers, mergeRefs } from './utils';\n\n/* ---------------------------------------------------------------- Messages */\n\nexport interface PasteFieldMessages {\n /** Announced to screen readers on successful paste. */\n readonly pasted: string | ((result: PasteResult) => string);\n /**\n * Announced to screen readers when content is dropped onto the zone. When\n * you override `pasted` but not this, your `pasted` message is used for drops too.\n */\n readonly dropped?: string | ((result: PasteResult) => string);\n /** Announced on failure. Defaults to {@link describePasteError}. `source` tells drops from pastes. */\n readonly error: (error: CopyError, source?: PasteSource) => string;\n /**\n * Accessible name of the trigger button. Receives the field's `label` prop.\n * The returned string must not be empty.\n */\n readonly triggerLabel: (label: string) => string;\n /**\n * Accessible name of the drop zone / paste target area.\n * Receives the field's `label` prop.\n */\n readonly zoneLabel: (label: string) => string;\n}\n\nexport const defaultPasteFieldMessages: PasteFieldMessages = {\n pasted: 'Pasted from clipboard',\n dropped: 'Dropped content added',\n error: describePasteError,\n triggerLabel: (label) => `Paste ${label}`,\n zoneLabel: (label) => `Paste area for ${label}`,\n};\n\n/* ----------------------------------------------------------------- Context */\n\nexport interface PasteFieldContextValue extends UsePasteResult {\n readonly label: string;\n readonly labelId: string;\n readonly zoneId: string;\n readonly revealed: boolean;\n readonly revealReason: RevealReason | null;\n readonly messages: PasteFieldMessages;\n /** Flicker-free status for rendering. Use `status` for logic, this for pixels. */\n readonly displayStatus: PasteStatus;\n /** Triggers a programmatic paste (via Clipboard API, may prompt for permission). */\n readonly doPaste: () => Promise<PasteOutcome>;\n}\n\nconst PasteFieldContext = /* @__PURE__ */ createContext<PasteFieldContextValue | null>(null);\n\n/** Access field state to build custom parts. Must be used inside `<PasteField.Root>`. */\nexport function usePasteField(): PasteFieldContextValue {\n const context = useContext(PasteFieldContext);\n if (!context) throw new Error('usePasteField() must be used inside <PasteField.Root>.');\n return context;\n}\n\n/* -------------------------------------------------------------------- Root */\n\nexport interface PasteFieldRootProps\n extends Omit<HTMLAttributes<HTMLDivElement>, 'onPaste' | 'onError'>,\n UsePasteDisplayStatusOptions {\n /** Human label — used for the trigger's and zone's accessible names. */\n readonly label: string;\n readonly pasteOptions?: UsePasteOptions;\n readonly messages?: Partial<PasteFieldMessages>;\n /** Skip hover/focus reveal and always show the trigger. */\n readonly alwaysVisible?: boolean;\n /** Render the built-in live region. Disable if your app has a global announcer. Default `true`. */\n readonly announce?: boolean;\n}\n\nconst Root = /* @__PURE__ */ forwardRef<HTMLDivElement, PasteFieldRootProps>(function PasteFieldRoot(\n {\n label,\n pasteOptions,\n messages: messageOverrides,\n alwaysVisible = false,\n announce = true,\n pendingDelayMs,\n minPendingMs,\n children,\n onPointerEnter,\n onPointerLeave,\n onPointerDown,\n onFocus,\n onBlur,\n ...rest\n },\n forwardedRef,\n) {\n const pasteState = usePaste(pasteOptions);\n const displayStatus = usePasteDisplayStatus(pasteState.status, {\n ...(pendingDelayMs === undefined ? {} : { pendingDelayMs }),\n ...(minPendingMs === undefined ? {} : { minPendingMs }),\n });\n const reveal = useRevealOnInteraction<HTMLDivElement>({ alwaysVisible });\n const baseId = useId();\n const labelId = `${baseId}-label`;\n const zoneId = `${baseId}-zone`;\n\n const messages = useMemo<PasteFieldMessages>(\n () => ({\n ...defaultPasteFieldMessages,\n // A translated `pasted` beats the English default `dropped`.\n ...(messageOverrides?.pasted === undefined ? {} : { dropped: messageOverrides.pasted }),\n ...messageOverrides,\n }),\n [messageOverrides],\n );\n\n const { paste: machinePaste } = pasteState;\n const doPaste = useCallback(() => machinePaste(), [machinePaste]);\n const { targetProps } = reveal;\n const ref = useMemo(() => mergeRefs(targetProps.ref, forwardedRef), [targetProps.ref, forwardedRef]);\n\n const context = useMemo<PasteFieldContextValue>(\n () => ({\n ...pasteState,\n label,\n labelId,\n zoneId,\n revealed: reveal.visible,\n revealReason: reveal.reason,\n messages,\n displayStatus,\n doPaste,\n }),\n [pasteState, label, labelId, zoneId, reveal.visible, reveal.reason, messages, displayStatus, doPaste],\n );\n\n const { state } = pasteState;\n\n let announcement = '';\n if (state.status === 'read') {\n const message = (state.result.source === 'drop' ? messages.dropped : undefined) ?? messages.pasted;\n announcement = typeof message === 'function' ? message(state.result) : message;\n } else if (state.status === 'error') {\n announcement = messages.error(state.error, state.source);\n }\n\n return (\n <PasteFieldContext.Provider value={context}>\n <div\n {...rest}\n ref={ref}\n data-state={state.status}\n data-display-state={displayStatus}\n data-revealed={reveal.visible ? '' : undefined}\n onPointerEnter={composeEventHandlers(onPointerEnter, targetProps.onPointerEnter)}\n onPointerLeave={composeEventHandlers(onPointerLeave, targetProps.onPointerLeave)}\n onPointerDown={composeEventHandlers(onPointerDown, targetProps.onPointerDown)}\n onFocus={composeEventHandlers(onFocus, targetProps.onFocus)}\n onBlur={composeEventHandlers(onBlur, targetProps.onBlur)}\n >\n {children}\n {announce ? <LiveRegion message={announcement} /> : null}\n </div>\n </PasteFieldContext.Provider>\n );\n});\n\n/* ------------------------------------------------------------ Label/Status */\n\nexport type PasteFieldLabelProps = HTMLAttributes<HTMLSpanElement>;\n\nconst Label = /* @__PURE__ */ forwardRef<HTMLSpanElement, PasteFieldLabelProps>(function PasteFieldLabel(\n { children, ...rest },\n ref,\n) {\n const field = usePasteField();\n return (\n <span {...rest} ref={ref} id={field.labelId}>\n {children ?? field.label}\n </span>\n );\n});\n\nexport interface PasteFieldStatusProps extends HTMLAttributes<HTMLSpanElement> {\n /** Map each paste status to a label. Defaults to English strings. */\n readonly labels?: Partial<Readonly<Record<PasteStatus, string>>>;\n}\n\nconst DEFAULT_STATUS_LABELS: Readonly<Record<PasteStatus, string>> = {\n idle: 'Ready',\n reading: 'Reading…',\n read: 'Pasted',\n error: 'Error',\n};\n\nconst Status = /* @__PURE__ */ forwardRef<HTMLSpanElement, PasteFieldStatusProps>(function PasteFieldStatus(\n { children, labels, ...rest },\n ref,\n) {\n const field = usePasteField();\n const resolved = labels ? { ...DEFAULT_STATUS_LABELS, ...labels } : DEFAULT_STATUS_LABELS;\n return (\n <span {...rest} ref={ref} data-state={field.status} data-display-state={field.displayStatus}>\n {children ?? resolved[field.displayStatus]}\n </span>\n );\n});\n\n/* ------------------------------------------------------------------- Zone */\n\nexport interface PasteFieldZoneProps extends HTMLAttributes<HTMLDivElement> {\n /** When true, the zone is always focusable (tabIndex=0). Default true. */\n readonly focusable?: boolean;\n /**\n * Accept drag-and-drop, through the same `accept` and limits as paste.\n * `data-drag-over` is present while an accepted drag is over the zone. Default true.\n */\n readonly droppable?: boolean;\n}\n\n/**\n * A focusable paste target. Accepts keyboard paste (Ctrl/⌘+V) without a\n * permission prompt and, unless `droppable={false}`, drag-and-drop. Renders\n * `data-zone` and `data-drag-over` for styling.\n *\n * Accessible name: `aria-label` prop, else `messages.zoneLabel(label)`\n * (\"Paste area for Notes\"). Pass `aria-labelledby` explicitly to name it from\n * another element instead.\n */\nconst Zone = /* @__PURE__ */ forwardRef<HTMLDivElement, PasteFieldZoneProps>(function PasteFieldZone(\n {\n children,\n focusable = true,\n droppable = true,\n onPaste,\n onDragEnter,\n onDragOver,\n onDragLeave,\n onDrop,\n 'aria-label': ariaLabel,\n tabIndex,\n ...rest\n },\n ref,\n) {\n const field = usePasteField();\n const { targetProps, dropTargetProps } = field;\n const drop: Record<keyof PasteDropTargetProps<HTMLDivElement>, DragEventHandler<HTMLDivElement> | undefined> = {\n onDragEnter,\n onDragOver,\n onDragLeave,\n onDrop,\n };\n if (droppable) {\n for (const key of Object.keys(dropTargetProps) as (keyof typeof dropTargetProps)[]) {\n drop[key] = composeEventHandlers(drop[key], dropTargetProps[key]);\n }\n }\n\n // Guard: a custom `zoneLabel` returning '' must not leave the region unnamed.\n const safeAriaLabel =\n (ariaLabel ?? field.messages.zoneLabel(field.label)) || defaultPasteFieldMessages.zoneLabel(field.label);\n\n return (\n <div\n // Default shortcut hint; a consumer value in `rest` overrides it.\n aria-keyshortcuts=\"Control+V Meta+V\"\n {...rest}\n ref={ref}\n id={field.zoneId}\n role=\"region\"\n aria-label={safeAriaLabel}\n data-zone=\"\"\n data-state={field.status}\n data-display-state={field.displayStatus}\n data-drag-over={droppable && field.isDragOver ? '' : undefined}\n tabIndex={tabIndex ?? (focusable ? 0 : undefined)}\n onPaste={composeEventHandlers(onPaste, targetProps.onPaste)}\n {...drop}\n >\n {children}\n </div>\n );\n});\n\n/* ----------------------------------------------------------------- Trigger */\n\nexport interface PasteFieldTriggerRenderProps {\n /** The real state. Use for logic. */\n readonly status: PasteStatus;\n /** Flicker-free state. Use for what you render. */\n readonly displayStatus: PasteStatus;\n readonly state: PasteState;\n readonly revealed: boolean;\n /** Whether `retry()` could help after the current error. */\n readonly canRetry: boolean;\n}\n\nexport interface PasteFieldTriggerProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'type'> {\n /** Static content, or a render function receiving the live state. */\n readonly children?: ReactNode | ((props: PasteFieldTriggerRenderProps) => ReactNode);\n}\n\nconst DEFAULT_TRIGGER_TEXT: Readonly<Record<PasteStatus, string>> = {\n idle: 'Paste',\n reading: 'Pasting…',\n read: 'Pasted',\n error: 'Retry',\n};\n\nconst Trigger = /* @__PURE__ */ forwardRef<HTMLButtonElement, PasteFieldTriggerProps>(function PasteFieldTrigger(\n { children, onClick, 'aria-label': ariaLabel, ...rest },\n ref,\n) {\n const field = usePasteField();\n const renderProps: PasteFieldTriggerRenderProps = {\n status: field.status,\n displayStatus: field.displayStatus,\n state: field.state,\n revealed: field.revealed,\n canRetry: field.canRetry,\n };\n\n const safeAriaLabel =\n (ariaLabel ?? field.messages.triggerLabel(field.label)) || defaultPasteFieldMessages.triggerLabel(field.label);\n\n return (\n <button\n {...rest}\n ref={ref}\n type=\"button\"\n aria-label={safeAriaLabel}\n aria-busy={field.status === 'reading' ? true : undefined}\n data-state={field.status}\n data-display-state={field.displayStatus}\n data-revealed={field.revealed ? '' : undefined}\n onClick={composeEventHandlers(onClick, () => {\n void field.doPaste();\n })}\n >\n {typeof children === 'function'\n ? children(renderProps)\n : (children ?? <TriggerLabel status={field.displayStatus} labels={DEFAULT_TRIGGER_TEXT} />)}\n </button>\n );\n});\n\n/* ----------------------------------------------------------------- Preview */\n\nexport interface PasteFieldPreviewRenderProps {\n readonly result: PasteResult;\n /**\n * Object URLs for `result.images`, in order, revoked automatically. Empty on\n * the server and for the first render after a paste, until they are created.\n */\n readonly imageUrls: readonly string[];\n}\n\nexport interface PasteFieldPreviewProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {\n /** Custom rendering of the latest result. Replaces the default text / image / file preview. */\n readonly children?: (props: PasteFieldPreviewRenderProps) => ReactNode;\n /** Shown while there is no pasted result (idle, reading, error). */\n readonly placeholder?: ReactNode;\n /** Pasted text longer than this is cut and ends with \"…\". Default 2000. */\n readonly maxTextLength?: number;\n /** Alt text for each pasted image. Default \"Pasted image 1 of 2\". */\n readonly imageAlt?: (index: number, total: number) => string;\n}\n\nconst NO_URLS: readonly string[] = [];\n\n/**\n * Object URLs for blobs, revoked when the blobs change or the component\n * unmounts. URLs are only returned for the blobs they were made from, so they\n * never pair with the wrong result.\n */\nfunction useObjectUrls(blobs: readonly Blob[] | undefined): readonly string[] {\n const [entry, setEntry] = useState<{ readonly blobs?: readonly Blob[]; readonly urls: readonly string[] }>({\n urls: NO_URLS,\n });\n useEffect(() => {\n if (!blobs?.length || typeof URL.createObjectURL !== 'function') return undefined;\n const urls = blobs.map((blob) => URL.createObjectURL(blob));\n setEntry({ blobs, urls });\n return () => {\n for (const url of urls) URL.revokeObjectURL(url);\n };\n }, [blobs]);\n return entry.blobs === blobs ? entry.urls : NO_URLS;\n}\n\nconst defaultImageAlt = (index: number, total: number): string => `Pasted image ${String(index + 1)} of ${String(total)}`;\n\n/**\n * Shows what was pasted: text (never HTML, which is untrusted), image\n * thumbnails and file names. Renders `placeholder` until there is a result.\n * Pass a function child to render the result yourself.\n */\nconst Preview = /* @__PURE__ */ forwardRef<HTMLDivElement, PasteFieldPreviewProps>(function PasteFieldPreview(\n { children, placeholder = null, maxTextLength = 2000, imageAlt = defaultImageAlt, ...rest },\n ref,\n) {\n const { result, status } = usePasteField();\n const imageUrls = useObjectUrls(result?.images);\n\n let content: ReactNode = placeholder;\n if (result) {\n if (children) {\n content = children({ result, imageUrls });\n } else {\n const { text } = result;\n const files = result.files.filter((file) => !file.type.startsWith('image/'));\n content = (\n <>\n {text ? (\n <pre data-preview-text=\"\">{text.length > maxTextLength ? `${text.slice(0, maxTextLength)}…` : text}</pre>\n ) : null}\n {imageUrls.map((url, index) => (\n <img key={url} data-preview-image=\"\" src={url} alt={imageAlt(index, imageUrls.length)} />\n ))}\n {files.length > 0 ? (\n <ul data-preview-files=\"\">\n {files.map((file, index) => (\n <li key={`${String(index)}-${file.name}`}>{file.name}</li>\n ))}\n </ul>\n ) : null}\n </>\n );\n }\n }\n\n return (\n <div {...rest} ref={ref} data-preview=\"\" data-state={status} data-empty={result ? undefined : ''}>\n {content}\n </div>\n );\n});\n\n/**\n * Headless compound component for a labelled, paste-ready field.\n *\n * Styling hooks on Root, Zone and Trigger:\n * - `data-display-state=\"idle|reading|read|error\"`: flicker-free, style with this\n * - `data-state`: the real, instantaneous state, for logic and tests\n * - `data-revealed`: present while the trigger should be visible\n *\n * @example\n * ```tsx\n * <PasteField.Root label=\"Notes\">\n * <PasteField.Label />\n * <PasteField.Zone />\n * <PasteField.Trigger />\n * <PasteField.Preview placeholder=\"Nothing pasted yet\" />\n * </PasteField.Root>\n * ```\n */\nexport const PasteField = { Root, Label, Status, Zone, Trigger, Preview } as const;\n","import { useCallback, useEffect, useRef, useState, type RefCallback } from 'react';\nimport {\n applyDragCopy,\n type DragCopyOptions,\n type DragCopyOutcome,\n type DragCopyState,\n type DragCopyStatus,\n type DragStartEventLike,\n} from '../core/drag-copy';\nimport { useIsomorphicLayoutEffect } from './utils';\nimport { invoke } from '../core/machine-shared';\n\nexport interface UseDragCopyOptions extends Omit<DragCopyOptions, 'onDrag'> {\n /**\n * Set `false` to disable drag without unmounting. Removes the `draggable`\n * attribute and listener while `false`. Default `true`.\n */\n readonly enabled?: boolean;\n /** Called each time a drag starts or ends. */\n readonly onDrag?: (state: DragCopyState) => void;\n}\n\nexport interface UseDragCopyResult<T extends HTMLElement = HTMLElement> {\n /**\n * Attach to any element you want to make draggable. The hook sets\n * `draggable=\"true\"` automatically while `enabled` is `true`.\n */\n readonly ref: RefCallback<T>;\n /** `'idle' | 'dragging' | 'done'` — the current drag status. */\n readonly status: DragCopyStatus;\n /** The last `dragstart` outcome; `null` before the first drag. */\n readonly outcome: DragCopyOutcome | null;\n /**\n * For use in React's `onDragStart` prop if you need to wire it imperatively\n * (e.g. inside a render-prop component). The `ref` alone is sufficient for\n * native HTML elements: the hook attaches its own listener.\n */\n readonly onDragStart: (event: DragStartEventLike) => void;\n}\n\n/**\n * Makes an element draggable and populates its `DataTransfer` with your data.\n *\n * ```tsx\n * const { ref } = useDragCopy({\n * source: () => ({ kind: 'html', html: '<b>Hello</b>', text: 'Hello' }),\n * });\n * return <div ref={ref}>Drag me</div>;\n * ```\n *\n * - No Clipboard API needed — works in every browser supporting HTML5 drag-and-drop.\n * - The `source` callback always reads the latest props/state, never stale closures.\n * - `enabled={false}` removes `draggable` and the listener without unmounting.\n * - SSR-safe: no DOM access during server rendering.\n */\nexport function useDragCopy<T extends HTMLElement = HTMLElement>(\n options: UseDragCopyOptions,\n): UseDragCopyResult<T> {\n const optionsRef = useRef(options);\n useIsomorphicLayoutEffect(() => {\n optionsRef.current = options;\n });\n\n const [node, setNode] = useState<HTMLElement | null>(null);\n const [state, setState] = useState<DragCopyState>({ status: 'idle', outcome: null });\n\n const enabled = options.enabled !== false;\n\n // Stable handler for the React onDragStart prop path.\n const onDragStart = useCallback((event: DragStartEventLike): void => {\n const { onDrag, onError, source, effectAllowed } = optionsRef.current;\n const coreOpts: DragCopyOptions = effectAllowed !== undefined\n ? { source, effectAllowed }\n : { source };\n const outcome = applyDragCopy(event, coreOpts);\n const next: DragCopyState = { status: 'dragging', outcome };\n setState(next);\n if (outcome.status === 'failed') invoke(onError, outcome.error);\n invoke(onDrag, next);\n }, []);\n\n useEffect(() => {\n if (!node || !enabled) return undefined;\n\n node.setAttribute('draggable', 'true');\n\n function handleDragStart(raw: Event): void {\n const event = raw as DragEvent;\n const { onDrag, onError, source, effectAllowed } = optionsRef.current;\n const coreOpts: DragCopyOptions = effectAllowed !== undefined\n ? { source, effectAllowed }\n : { source };\n const outcome = applyDragCopy(\n {\n type: event.type,\n dataTransfer: event.dataTransfer,\n get defaultPrevented() {\n return event.defaultPrevented;\n },\n preventDefault: () => { event.preventDefault(); },\n },\n coreOpts,\n );\n const next: DragCopyState = { status: 'dragging', outcome };\n setState(next);\n if (outcome.status === 'failed') invoke(onError, outcome.error);\n invoke(onDrag, next);\n }\n\n function handleDragEnd(): void {\n const opts = optionsRef.current;\n setState((prev) => {\n const next: DragCopyState = { status: 'done', outcome: prev.outcome };\n invoke(opts.onDrag, next);\n return next;\n });\n }\n\n node.addEventListener('dragstart', handleDragStart);\n node.addEventListener('dragend', handleDragEnd);\n\n return () => {\n node.removeEventListener('dragstart', handleDragStart);\n node.removeEventListener('dragend', handleDragEnd);\n node.removeAttribute('draggable');\n };\n }, [node, enabled]);\n\n // Reset to idle when disabled so status accurately reflects the element's state.\n useEffect(() => {\n if (!enabled) setState({ status: 'idle', outcome: null });\n }, [enabled]);\n\n return {\n ref: setNode,\n status: state.status,\n outcome: state.outcome,\n onDragStart,\n };\n}\n","import { copyFailure } from '../core/errors';\n\n/** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */\nexport const DEFAULT_LINK_PROTOCOLS: readonly string[] = /* @__PURE__ */ Object.freeze(['https:', 'http:', 'mailto:', 'tel:']);\n\n/**\n * Query parameters that only track where a click came from: the defaults of\n * {@link cleanLinkUrl}. `utm_` matches every parameter starting with it.\n */\nexport const TRACKING_PARAMETERS: readonly string[] = /* @__PURE__ */ Object.freeze([\n 'utm_',\n 'fbclid',\n 'gclid',\n 'gclsrc',\n 'dclid',\n 'gbraid',\n 'wbraid',\n 'msclkid',\n 'yclid',\n 'twclid',\n 'ttclid',\n 'li_fat_id',\n 'igshid',\n 'igsh',\n 'mc_cid',\n 'mc_eid',\n '_hsenc',\n '_hsmi',\n 'mkt_tok',\n 'oly_anon_id',\n 'oly_enc_id',\n 'vero_id',\n 'wickedid',\n '_gl',\n]);\n\nexport interface CleanLinkOptions {\n /**\n * Parameters to remove: exact names, names ending in `_` (a prefix, like\n * `utm_`), or regular expressions tested against the name. Default {@link TRACKING_PARAMETERS}.\n */\n readonly params?: readonly (string | RegExp)[];\n /** Parameters never removed, even when `params` matches them. */\n readonly keep?: readonly string[];\n}\n\nexport interface LinkUrlOptions {\n /** Resolves relative links. Default: the page's address in a browser; required elsewhere for relative links. */\n readonly base?: string | URL;\n /** Allowed schemes, with the colon. Default {@link DEFAULT_LINK_PROTOCOLS}. */\n readonly protocols?: readonly string[];\n /** Remove tracking parameters: `true` for {@link TRACKING_PARAMETERS}, or your own list. Default `false`. */\n readonly clean?: boolean | CleanLinkOptions;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nfunction baseUrl(base: LinkUrlOptions['base']): string | undefined {\n if (base !== undefined) {\n if (typeof base === 'string' || base instanceof URL) return String(base);\n throw invalid('`base` must be a string or a URL.');\n }\n return typeof location === 'undefined' ? undefined : location.href;\n}\n\nfunction protocolSet(protocols: LinkUrlOptions['protocols']): ReadonlySet<string> {\n const list: unknown = protocols ?? DEFAULT_LINK_PROTOCOLS;\n const valid = (protocol: unknown): protocol is string => typeof protocol === 'string' && /^[a-z][a-z\\d+.-]*:$/i.test(protocol);\n if (!Array.isArray(list) || list.length === 0 || !(list as readonly unknown[]).every(valid)) {\n throw invalid('`protocols` must be a non-empty list of schemes with their colon, like \"https:\".');\n }\n return new Set((list as readonly string[]).map((protocol) => protocol.toLowerCase()));\n}\n\nfunction matcher(params: CleanLinkOptions['params']): (name: string) => boolean {\n const list = params ?? TRACKING_PARAMETERS;\n if (!Array.isArray(list) || !list.every((param) => typeof param === 'string' || param instanceof RegExp)) {\n throw invalid('`clean.params` must be a list of strings and regular expressions.');\n }\n return (name) => {\n const lower = name.toLowerCase();\n return list.some((param) => {\n if (typeof param !== 'string') return new RegExp(param.source, param.flags.replace(/[gy]/g, '')).test(name);\n const wanted = param.toLowerCase();\n return wanted.endsWith('_') ? lower.startsWith(wanted) : lower === wanted;\n });\n };\n}\n\n/** The cleaning step `clean` asks for, or `null`. Throws for an invalid option. */\nfunction cleaner(option: LinkUrlOptions['clean']): ((url: URL) => void) | null {\n const cleaning: unknown = option ?? false; // Plain-JS callers can pass anything.\n if (cleaning === false) return null;\n if (cleaning !== true && (typeof cleaning !== 'object' || cleaning === null)) throw invalid('`clean` must be a boolean or an options object.');\n const settings: CleanLinkOptions = cleaning === true ? {} : cleaning;\n const tracking = matcher(settings.params);\n const keep = settings.keep ?? [];\n if (!Array.isArray(keep) || !keep.every((name: unknown) => typeof name === 'string')) throw invalid('`clean.keep` must be a list of strings.');\n const kept = new Set(keep.map((name) => name.toLowerCase()));\n return (url) => {\n for (const name of [...new Set(url.searchParams.keys())]) {\n if (tracking(name) && !kept.has(name.toLowerCase())) url.searchParams.delete(name);\n }\n };\n}\n\n/**\n * Validates `options` once (throwing a typed `invalid-payload` error for invalid\n * ones) and returns a resolver that throws only for invalid links.\n * @internal\n */\nexport function linkUrlResolver(options: LinkUrlOptions = {}): (input: string | URL) => string {\n const protocols = protocolSet(options.protocols);\n const base = baseUrl(options.base);\n const clean = cleaner(options.clean);\n return (input) => {\n if (typeof input !== 'string' && !(input instanceof URL)) throw invalid('A link must be a string or a URL.');\n const raw = String(input).trim();\n if (raw === '') throw invalid('A link must not be empty.');\n let url: URL;\n try {\n url = new URL(raw, base);\n } catch (cause) {\n throw copyFailure('invalid-payload', `Not a valid link: ${JSON.stringify(raw.slice(0, 200))}.`, cause);\n }\n if (!protocols.has(url.protocol)) {\n throw invalid(`Links with the scheme \"${url.protocol}\" are not allowed (allowed: ${[...protocols].join(', ')}).`);\n }\n // Never copy or paste credentials embedded in a link.\n url.username = '';\n url.password = '';\n clean?.(url);\n return url.href;\n };\n}\n\n/**\n * The link as an absolute, safe URL string, or a typed `invalid-payload` error:\n * relative links are resolved, the scheme must be allowed, user names and\n * passwords are always removed, and tracking parameters optionally.\n */\nexport function resolveLinkUrl(input: string | URL, options: LinkUrlOptions = {}): string {\n return linkUrlResolver(options)(input);\n}\n\n/**\n * Removes tracking parameters (`utm_*`, `fbclid`, `gclid`, ...) from a link, keeping\n * everything else, including the fragment. Also validates it like every link here.\n *\n * @example\n * cleanLinkUrl('https://shop.example/p/42?utm_source=news&color=red'); // 'https://shop.example/p/42?color=red'\n */\nexport function cleanLinkUrl(url: string | URL, options: CleanLinkOptions & Omit<LinkUrlOptions, 'clean'> = {}): string {\n const { params, keep, ...rest } = options;\n return resolveLinkUrl(url, { ...rest, clean: { ...(params === undefined ? {} : { params }), ...(keep === undefined ? {} : { keep }) } });\n}\n","import { copyFailure } from '../core/errors';\nimport type { HtmlPayload, MultiPayload } from '../core/payload';\nimport { resolveLinkUrl, type LinkUrlOptions } from './url';\n\n/** A link with an optional title. */\nexport interface Link {\n readonly url: string | URL;\n /** What the link says when pasted into a document or chat. Default: the URL. */\n readonly title?: string;\n}\n\n/** A link: a URL, a `{ url, title }` object, or an `<a>` element (its `href` and text). */\nexport type LinkSource = string | URL | Link | HTMLAnchorElement;\n\n/** A validated link: an absolute, safe URL and a clean title. */\nexport interface ResolvedLink {\n readonly url: string;\n /** Never empty: the URL when there is no title. */\n readonly title: string;\n /** Whether `title` came from the input (`false`: it is the URL). */\n readonly titled: boolean;\n}\n\n/**\n * What the plain-text flavour holds (editors, terminals and address bars paste it):\n * `'url'` (the default), `'title'`, `'title-and-url'` (the title, then the URL on\n * the next line) or `'markdown'` (`[Title](URL)`).\n */\nexport type LinkTextFormat = 'url' | 'title' | 'title-and-url' | 'markdown';\n\nexport interface LinkPayloadOptions extends LinkUrlOptions {\n /** Default `'url'`. */\n readonly text?: LinkTextFormat;\n /** Longest title kept, in characters; longer ones end in an ellipsis. Default {@link DEFAULT_LINK_TITLE_LENGTH}. */\n readonly maxTitleLength?: number;\n}\n\nexport interface LinkDragPayloadOptions extends LinkPayloadOptions {\n /**\n * `'drag'`: a multi-format payload that also carries `text/uri-list` and\n * Firefox's `text/x-moz-url`, for `useDragCopy` and `useCopyInterceptor` (a link\n * dropped on the tab bar opens). Clipboard writes skip those two where the\n * browser can't write them.\n */\n readonly target: 'drag';\n}\n\nexport const DEFAULT_LINK_TITLE_LENGTH = 300;\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\n/**\n * Characters a title never keeps: controls, bidi overrides and isolates (which can\n * make a title read differently), and zero-width characters.\n */\n// eslint-disable-next-line no-control-regex -- matching control characters is the point\nconst HIDDEN = /[\\0-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f-\\x9f\\u061C\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u2066-\\u2069\\uFEFF]/g;\n\n/** A title as one clean line: hidden characters removed, whitespace collapsed, length capped. */\nexport function cleanTitle(title: string, maxLength: number): string {\n const clean = title.replace(HIDDEN, '').replace(/\\s+/g, ' ').trim();\n if (clean.length <= maxLength) return clean;\n // Cut on a code point boundary and mark the cut.\n return `${Array.from(clean).slice(0, maxLength - 1).join('').trimEnd()}\\u2026`;\n}\n\nfunction maxTitle(value: number | undefined): number {\n if (value === undefined) return DEFAULT_LINK_TITLE_LENGTH;\n if (Number.isInteger(value) && value >= 1) return value;\n throw invalid(`\\`maxTitleLength\\` must be a positive integer (received ${String(value)}).`);\n}\n\nfunction isAnchor(source: unknown): source is HTMLAnchorElement {\n return typeof source === 'object' && source !== null && (source as { nodeName?: unknown }).nodeName === 'A' && typeof (source as { href?: unknown }).href === 'string';\n}\n\n/**\n * Validates a link and its title: see {@link resolveLinkUrl} for the URL rules.\n * An `<a>` element gives its `href` and its text (or `title` attribute).\n */\nexport function resolveLink(source: LinkSource, options: LinkPayloadOptions = {}): ResolvedLink {\n let url: string | URL;\n let title: unknown;\n if (typeof source === 'string' || source instanceof URL) {\n url = source;\n } else if (isAnchor(source)) {\n url = source.getAttribute('href') ?? '';\n title = source.textContent.trim() !== '' ? source.textContent : (source.getAttribute('title') ?? undefined);\n if (url !== '' && options.base === undefined) url = source.href; // Resolved against the anchor's own document.\n } else if (typeof (source as unknown) === 'object' && (source as unknown) !== null && 'url' in source) {\n url = source.url;\n title = source.title;\n } else {\n throw invalid('A link must be a URL, a { url, title } object or an <a> element.');\n }\n if (title !== undefined && typeof title !== 'string') throw invalid('A link title must be a string.');\n const href = resolveLinkUrl(url, options);\n const clean = title === undefined ? '' : cleanTitle(title, maxTitle(options.maxTitleLength));\n return { url: href, title: clean === '' ? href : clean, titled: clean !== '' };\n}\n\nexport const escapeHtml = (text: string): string =>\n text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\n\n/** `[title](url)`, safe in every CommonMark renderer: brackets and backslashes escaped, parentheses and spaces encoded. */\nexport function markdownLink(link: ResolvedLink): string {\n const label = link.title.replace(/[\\\\[\\]]/g, '\\\\$&');\n const target = link.url.replace(/[()<> ]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);\n return `[${label}](${target})`;\n}\n\nfunction plainText(link: ResolvedLink, format: LinkTextFormat): string {\n switch (format) {\n case 'url':\n return link.url;\n case 'title':\n return link.title;\n case 'title-and-url':\n return link.titled ? `${link.title}\\n${link.url}` : link.url;\n case 'markdown':\n return markdownLink(link);\n default:\n throw invalid(`\\`text\\` must be \"url\", \"title\", \"title-and-url\" or \"markdown\" (received ${JSON.stringify(format)}).`);\n }\n}\n\n/**\n * A copy payload for a link: an HTML anchor, so Slack, Google Docs, Notion,\n * Teams, Word and mail paste a titled link, and plain text (the URL by default)\n * for editors and address bars. The URL is validated (allowed schemes only,\n * credentials removed, optionally cleaned of tracking) and the title is cleaned\n * of hidden characters; both are escaped.\n *\n * @example\n * copy(() => linkPayload({ url: location.href, title: document.title }, { clean: true }));\n * useDragCopy({ payload: () => linkPayload(anchor, { target: 'drag' }) });\n */\nexport function linkPayload(source: LinkSource, options: LinkDragPayloadOptions): MultiPayload;\nexport function linkPayload(source: LinkSource, options?: LinkPayloadOptions): HtmlPayload;\nexport function linkPayload(source: LinkSource, options: LinkPayloadOptions & { readonly target?: 'drag' | 'clipboard' } = {}): HtmlPayload | MultiPayload {\n const target: unknown = options.target ?? 'clipboard'; // Plain-JS callers can pass anything.\n if (target !== 'drag' && target !== 'clipboard') throw invalid('`target` must be \"clipboard\" or \"drag\".');\n const link = resolveLink(source, options);\n const text = plainText(link, options.text ?? 'url');\n const html = `<a href=\"${escapeHtml(link.url)}\">${escapeHtml(link.title)}</a>`;\n if (target === 'clipboard') return { kind: 'html', html, text };\n return {\n kind: 'multi',\n items: [\n { mimeType: 'text/plain', data: text },\n { mimeType: 'text/html', data: html },\n { mimeType: 'text/uri-list', data: link.url, optional: true },\n // Firefox's titled-link format: the URL, a line break, the title.\n { mimeType: 'text/x-moz-url', data: `${link.url}\\n${link.title}`, optional: true },\n ],\n };\n}\n","import { createBrowserClipboardAdapter, type ClipboardAdapter } from '../core/clipboard-adapter';\nimport { createCopyError, describeCopyError, toCopyError, type CopyError, type CopyErrorType } from '../core/errors';\nimport { normalizePayload, validatePayload, type CopyInput, type CopyPayload } from '../core/payload';\nimport { cleanTitle, DEFAULT_LINK_TITLE_LENGTH, linkPayload } from '../link/payload';\nimport { linkUrlResolver, type LinkUrlOptions } from '../link/url';\n\n/** What to share: a link, a message, files, or any mix of them. */\nexport interface ShareContent {\n /** Validated like every link in this package: allowed schemes only, credentials removed. */\n readonly url?: string | URL;\n readonly title?: string;\n /** A message to share alongside (or instead of) the link. */\n readonly text?: string;\n /** Files for the share sheet, where the browser can share them (`navigator.canShare({ files })`). Never copied. */\n readonly files?: readonly File[];\n}\n\n/** The content after validation: what the share sheet or the clipboard receives. */\nexport interface ResolvedShare {\n readonly url: string | null;\n /** Cleaned of hidden characters; `null` when there is none. */\n readonly title: string | null;\n readonly text: string | null;\n readonly files: readonly File[];\n}\n\n/**\n * How to share:\n * - `auto` (default): the share sheet on phones and tablets, where people expect it; copy elsewhere.\n * - `native`: the share sheet wherever the browser has one (also desktop Safari, Edge and Chrome on Windows and macOS).\n * - `copy`: always copy.\n */\nexport type ShareMode = 'auto' | 'native' | 'copy';\n\nexport type ShareMethod = 'native' | 'copy';\n\n/** Structural view of what sharing needs from the browser; `window` by default. */\nexport interface ShareEnvironment {\n readonly navigator?: {\n readonly share?: (data: ShareData) => Promise<void>;\n readonly canShare?: (data: ShareData) => boolean;\n };\n readonly matchMedia?: (query: string) => { readonly matches: boolean };\n}\n\nexport interface ShareOptions extends LinkUrlOptions {\n /** Default `\"auto\"`. */\n readonly mode?: ShareMode;\n /** When the share sheet fails for a reason other than the user closing it, copy instead. Default `true`. */\n readonly fallback?: boolean;\n /**\n * What to copy. Default: a titled link (`linkPayload`) when there is a URL,\n * otherwise the text. Return a string or any copy payload.\n */\n readonly copy?: (content: ResolvedShare) => CopyInput;\n /** Default: the browser Clipboard API, as `useCopy` uses. */\n readonly adapter?: ClipboardAdapter;\n /** Default: `window`. For tests, webviews and other hosts. */\n readonly environment?: ShareEnvironment;\n /** Aborting it stops a copy in progress; the share sheet itself can only be closed by the user. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Why the content was copied rather than shared: `preferred` (the mode chose\n * copy, as on desktop in `auto`), `unsupported` (no share sheet, or it can't\n * take this content) or `fallback` (the share sheet failed).\n */\nexport type CopyReason = 'preferred' | 'unsupported' | 'fallback';\n\n/** What `shareOrCopy` resolves to. It never rejects. */\nexport type ShareOutcome =\n | { readonly status: 'shared'; readonly method: 'native'; readonly content: ResolvedShare }\n | { readonly status: 'copied'; readonly method: 'copy'; readonly reason: CopyReason; readonly payload: CopyPayload; readonly content: ResolvedShare }\n /** The user closed the share sheet. Nothing to report. */\n | { readonly status: 'cancelled'; readonly method: 'native' }\n | { readonly status: 'error'; readonly method: ShareMethod; readonly error: CopyError };\n\n/** Phones and tablets: a touch screen is the main input and nothing hovers. */\nexport const TOUCH_FIRST = '(hover: none) and (pointer: coarse)';\n\nconst defaultEnvironment = (): ShareEnvironment | undefined => (typeof window === 'undefined' ? undefined : window);\n\nconst invalid = (message: string): CopyError => createCopyError('invalid-payload', message);\n\n/** Validates and cleans what to share, or returns the typed error for invalid input. */\nfunction resolveContent(content: ShareContent, options: LinkUrlOptions): ResolvedShare | CopyError {\n const value: unknown = content;\n if (typeof value !== 'object' || value === null) return invalid('Share content must be an object with a url, text or files.');\n const { url, title, text, files } = value as Record<string, unknown>;\n let href: string | null = null;\n if (url !== undefined && url !== null) {\n try {\n href = linkUrlResolver(options)(url as string | URL);\n } catch (error) {\n return toCopyError(error);\n }\n }\n if (title !== undefined && typeof title !== 'string') return invalid('`title` must be a string.');\n if (text !== undefined && typeof text !== 'string') return invalid('`text` must be a string.');\n const list: unknown = files ?? [];\n if (!Array.isArray(list) || !list.every((file: unknown) => typeof File !== 'undefined' && file instanceof File)) {\n return invalid('`files` must be a list of File objects.');\n }\n const cleanName = title === undefined ? '' : cleanTitle(title, DEFAULT_LINK_TITLE_LENGTH);\n const message = text === undefined || text.trim() === '' ? null : text;\n if (href === null && message === null && list.length === 0) return invalid('There is nothing to share: give a url, text or files.');\n return { url: href, title: cleanName === '' ? null : cleanName, text: message, files: list as File[] };\n}\n\n/** The `ShareData` the browser receives: only the fields that are set. */\nfunction shareData(content: ResolvedShare): ShareData {\n return {\n ...(content.url === null ? {} : { url: content.url }),\n ...(content.title === null ? {} : { title: content.title }),\n ...(content.text === null ? {} : { text: content.text }),\n ...(content.files.length === 0 ? {} : { files: [...content.files] }),\n };\n}\n\n/** Whether this browser can open its share sheet for `data`. */\nfunction canShareNatively(environment: ShareEnvironment | undefined, data: ShareData | null): boolean {\n const nav = environment?.navigator;\n if (typeof nav?.share !== 'function') return false;\n if (data === null) return true;\n // Without canShare (older Safari), only links and text can be shared.\n return typeof nav.canShare === 'function' ? nav.canShare(data) : data.files === undefined;\n}\n\nfunction isTouchFirst(environment: ShareEnvironment | undefined): boolean {\n return typeof environment?.matchMedia === 'function' && environment.matchMedia(TOUCH_FIRST).matches;\n}\n\nfunction resolveMode(mode: unknown): ShareMode | CopyError {\n if (mode === undefined) return 'auto';\n return mode === 'auto' || mode === 'native' || mode === 'copy' ? mode : invalid('`mode` must be \"auto\", \"native\" or \"copy\".');\n}\n\n/**\n * How {@link shareOrCopy} would share right now: `\"native\"` (the share sheet) or\n * `\"copy\"`. Use it to label the button (\"Share…\" or \"Copy link\"). Pass the\n * content when it has files, since not every share sheet takes them.\n */\nexport function shareMethod(options: Pick<ShareOptions, 'mode' | 'environment'> = {}, content?: ShareContent): ShareMethod {\n const mode = resolveMode(options.mode);\n if (typeof mode !== 'string' || mode === 'copy') return 'copy';\n const environment = options.environment ?? defaultEnvironment();\n if (mode === 'auto' && !isTouchFirst(environment)) return 'copy';\n const resolved = content === undefined ? null : resolveContent(content, {});\n const data = resolved === null ? null : 'type' in resolved ? undefined : shareData(resolved);\n return data !== undefined && canShareNatively(environment, data) ? 'native' : 'copy';\n}\n\n/** The default copy: a titled link when there is a URL, otherwise the text (one of them is always set here). */\nfunction defaultCopy(content: ResolvedShare): CopyInput {\n if (content.url !== null) return linkPayload({ url: content.url, ...(content.title === null ? {} : { title: content.title }) });\n return content.text as string;\n}\n\nasync function copyContent(content: ResolvedShare, reason: CopyReason, options: ShareOptions): Promise<ShareOutcome> {\n if (options.copy === undefined && content.url === null && content.text === null) {\n return { status: 'error', method: 'copy', error: createCopyError('unsupported-format', 'Files can only be shared through a share sheet, and this browser has none for them.') };\n }\n let payload: CopyPayload;\n try {\n payload = normalizePayload((options.copy ?? defaultCopy)(content));\n } catch (error) {\n return { status: 'error', method: 'copy', error: toCopyError(error) };\n }\n const problem = validatePayload(payload);\n if (problem !== null) return { status: 'error', method: 'copy', error: problem };\n if (options.signal?.aborted === true) return { status: 'error', method: 'copy', error: createCopyError('aborted', 'The share was aborted.') };\n try {\n await (options.adapter ?? createBrowserClipboardAdapter()).write(payload, options.signal === undefined ? undefined : { signal: options.signal });\n } catch (error) {\n return { status: 'error', method: 'copy', error: toCopyError(error) };\n }\n return { status: 'copied', method: 'copy', reason, payload, content };\n}\n\n/**\n * Shares through the device's share sheet where people expect one, and copies a\n * titled link everywhere else. Call it directly in a click handler: the share\n * sheet needs the user's gesture.\n *\n * It never rejects. It resolves to `shared`, `copied` (with why), `cancelled`\n * (the user closed the share sheet: nothing to report) or `error` with a typed\n * {@link CopyError}.\n *\n * @example\n * button.addEventListener('click', async () => {\n * const outcome = await shareOrCopy({ url: location.href, title: document.title });\n * if (outcome.status === 'copied') toast('Link copied');\n * });\n */\nexport async function shareOrCopy(content: ShareContent, options: ShareOptions = {}): Promise<ShareOutcome> {\n const mode = resolveMode(options.mode);\n if (typeof mode !== 'string') return { status: 'error', method: 'copy', error: mode };\n const resolved = resolveContent(content, options);\n if ('type' in resolved) return { status: 'error', method: 'copy', error: resolved };\n const environment = options.environment ?? defaultEnvironment();\n if (mode === 'copy' || (mode === 'auto' && !isTouchFirst(environment))) return copyContent(resolved, 'preferred', options);\n const data = shareData(resolved);\n if (!canShareNatively(environment, data)) return copyContent(resolved, 'unsupported', options);\n try {\n // Called before any await: the share sheet needs the click's user activation.\n await (environment?.navigator?.share as (data: ShareData) => Promise<void>)(data);\n return { status: 'shared', method: 'native', content: resolved };\n } catch (error) {\n if (readName(error) === 'AbortError') return { status: 'cancelled', method: 'native' };\n if (options.fallback === false) return { status: 'error', method: 'native', error: shareError(error) };\n return copyContent(resolved, 'fallback', options);\n }\n}\n\nfunction readName(error: unknown): string | undefined {\n const name: unknown = typeof error === 'object' && error !== null ? (error as { name?: unknown }).name : undefined;\n return typeof name === 'string' ? name : undefined;\n}\n\n/** Classifies a share sheet failure. */\nfunction shareError(cause: unknown): CopyError {\n switch (readName(cause)) {\n case 'NotAllowedError':\n return createCopyError('permission-denied', 'The share sheet was blocked: it needs a click, and an iframe needs the web-share permission.', cause);\n case 'InvalidStateError':\n return createCopyError('unknown', 'Another share sheet is already open.', cause);\n case 'DataError':\n case 'TypeError':\n return createCopyError('unsupported-format', 'The share sheet rejected this content.', cause);\n default:\n return toCopyError(cause);\n }\n}\n\nconst SHARE_DESCRIPTIONS: Partial<Readonly<Record<CopyErrorType, string>>> = {\n 'permission-denied': \"Sharing isn't allowed here.\",\n 'unsupported-format': \"This can't be shared from this browser.\",\n timeout: 'Sharing took too long. Try again.',\n};\n\n/**\n * Default English, user-facing sentence for a failed share: a share sheet\n * failure is described as sharing, a failed copy as copying. Replace for i18n.\n */\nexport function describeShareError(error: CopyError, method: ShareMethod): string {\n if (method === 'copy') return describeCopyError(error);\n return SHARE_DESCRIPTIONS[error.type] ?? \"Couldn't share. Try again.\";\n}\n","import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { DEFAULT_RESET_AFTER_MS } from '../core/copy-machine';\nimport type { CopyError } from '../core/errors';\nimport { useIsomorphicLayoutEffect } from './utils';\nimport { shareMethod, shareOrCopy, TOUCH_FIRST, type ShareContent, type ShareMethod, type ShareOptions, type ShareOutcome } from '../share/share';\n\n/** `sharing` lasts while the share sheet is open or the copy is being written. */\nexport type ShareStatus = 'idle' | 'sharing' | 'shared' | 'copied' | 'error';\n\nexport interface UseShareOptions extends ShareOptions {\n /** Time in `shared` or `copied` before returning to `idle`. `false` keeps it. Default 2000. */\n readonly resetAfterMs?: number | false;\n /** Called with every settled outcome, including `cancelled`. */\n readonly onShare?: (outcome: ShareOutcome) => void;\n}\n\n/** What `share()` resolves to: the outcome, or `ignored` while a share is already open. */\nexport type UseShareOutcome = ShareOutcome | { readonly status: 'ignored'; readonly reason: 'in-flight' };\n\nexport interface UseShareResult {\n readonly status: ShareStatus;\n readonly error: CopyError | null;\n /** The last settled outcome; `null` before the first and after `reset()`. */\n readonly outcome: ShareOutcome | null;\n /**\n * How `share()` will share: `\"native\"` (the share sheet) or `\"copy\"`. Label the\n * button with it (\"Share…\" or \"Copy link\"). `\"copy\"` during server rendering\n * and hydration, then updated in the browser, also when the device changes.\n */\n readonly method: ShareMethod;\n /** Stable identity. Call it in a click handler. Never rejects. */\n readonly share: (content: ShareContent) => Promise<UseShareOutcome>;\n /** Stable identity. Back to `idle`; the result of a share still open is ignored. */\n readonly reset: () => void;\n}\n\ninterface State {\n readonly status: ShareStatus;\n readonly outcome: ShareOutcome | null;\n}\n\nconst IDLE: State = { status: 'idle', outcome: null };\nconst IGNORED: UseShareOutcome = /* @__PURE__ */ Object.freeze({ status: 'ignored', reason: 'in-flight' });\n\nfunction resetDelay(value: number | false | undefined): number | null {\n if (value === false || value === Infinity) return null;\n return value === undefined || Number.isNaN(value) ? DEFAULT_RESET_AFTER_MS : Math.max(0, value);\n}\n\nconst statusOf = (outcome: ShareOutcome): ShareStatus => (outcome.status === 'cancelled' ? 'idle' : outcome.status);\n\n/**\n * Share with the device's share sheet on phones and tablets, and copy a titled\n * link everywhere else, with honest state for the button. Options may change on\n * every render; the latest ones are always used.\n *\n * @example\n * const { share, status, method } = useShare();\n * <button onClick={() => share({ url, title })}>\n * {status === 'copied' ? 'Link copied' : method === 'native' ? 'Share…' : 'Copy link'}\n * </button>\n */\nexport function useShare(options: UseShareOptions = {}): UseShareResult {\n const optionsRef = useRef(options);\n useIsomorphicLayoutEffect(() => {\n optionsRef.current = options;\n });\n\n const [state, setState] = useState<State>(IDLE);\n const mounted = useRef(false);\n const inFlight = useRef(false);\n const generation = useRef(0);\n const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n generation.current += 1;\n clearTimeout(timer.current);\n };\n }, []);\n\n const subscribe = useCallback((onChange: () => void) => {\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return () => undefined;\n const list = window.matchMedia(TOUCH_FIRST);\n list.addEventListener('change', onChange);\n return () => {\n list.removeEventListener('change', onChange);\n };\n }, []);\n const method = useSyncExternalStore(\n subscribe,\n () => shareMethod(optionsRef.current),\n (): ShareMethod => 'copy',\n );\n\n const share = useCallback(async (content: ShareContent): Promise<UseShareOutcome> => {\n if (inFlight.current) return IGNORED;\n inFlight.current = true;\n const current = (generation.current += 1);\n clearTimeout(timer.current);\n setState({ status: 'sharing', outcome: null });\n // No await before this call: the share sheet needs the click's user activation.\n const outcome = await shareOrCopy(content, optionsRef.current);\n inFlight.current = false;\n if (!mounted.current || current !== generation.current) return outcome;\n setState({ status: statusOf(outcome), outcome });\n const delay = resetDelay(optionsRef.current.resetAfterMs);\n if ((outcome.status === 'shared' || outcome.status === 'copied') && delay !== null) {\n timer.current = setTimeout(() => {\n setState(IDLE);\n }, delay);\n }\n optionsRef.current.onShare?.(outcome);\n return outcome;\n }, []);\n\n const reset = useCallback(() => {\n generation.current += 1;\n clearTimeout(timer.current);\n setState(IDLE);\n }, []);\n\n return useMemo(\n () => ({\n status: state.status,\n error: state.outcome?.status === 'error' ? state.outcome.error : null,\n outcome: state.outcome,\n method,\n share,\n reset,\n }),\n [state, method, share, reset],\n );\n}\n"],"mappings":";;;;;AA8CA,SAAgB,gBAAgB,MAAqB,SAAiB,OAA4B;CAChG,OAAO,UAAU,KAAA,IAAY;EAAE;EAAM;CAAQ,IAAI;EAAE;EAAM;EAAS;CAAM;AAC1E;AAEA,MAAM,mCAA+D,IAAI,IAAmB;CAC1F;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,iBAAiB,OAA2B;CAC1D,OAAO,iBAAiB,IAAI,MAAM,IAAI;AACxC;;;;;AAMA,MAAM,qBAAqB,OAAO,IAAI,8BAA8B;;AAGpE,IAAa,cAAb,cAAiC,MAAM;CAIrC,YAAY,WAAsB;EAChC,MAAM,UAAU,OAAO;EAHzB,KAAU,sBAAsB;EAI9B,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF;AAEA,SAAgB,cAAc,OAAsC;CAClE,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAuC,wBAAwB;AAEpE;;AAGA,SAAgB,YAAY,MAAqB,SAAiB,OAA8B;CAC9F,OAAO,IAAI,YAAY,gBAAgB,MAAM,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