react-smart-copy 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["useEffect","useLayoutEffect","getServerSnapshot","useRef","useState","useSyncExternalStore","useMemo","useCallback","useSyncExternalStore","useState","useRef","useMemo","useState","useContext","useId","useMemo","useCallback"],"sources":["../src/core/errors.ts","../src/core/payload.ts","../src/core/clipboard-adapter.ts","../src/core/copy-machine.ts","../src/react/utils.ts","../src/react/useCopy.ts","../src/react/useMediaQuery.ts","../src/react/useRevealOnInteraction.ts","../src/react/useDisplayStatus.ts","../src/react/LiveRegion.tsx","../src/react/CopyField.tsx"],"sourcesContent":["/**\n * Every way a copy can fail, as a closed union.\n *\n * `CopyError.message` is developer-facing (logs, telemetry). For user-facing\n * text use {@link describeCopyError} or map `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 write. Also what Safari reports for a missing user gesture. */\n | 'permission-denied'\n /** The document lost focus mid-copy (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 write this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */\n | 'unsupported-format'\n /** A lazy image source 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 /** Anything the platform threw that we could not classify. */\n | 'unknown';\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 '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\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/** Classifies anything thrown by the platform or an adapter into a {@link CopyError}. */\nexport function toCopyError(cause: unknown): CopyError {\n if (isCopyFailure(cause)) return cause.copyError;\n\n const name = readString(cause, 'name');\n const message = readString(cause, 'message') ?? '';\n\n switch (name) {\n case 'NotAllowedError':\n return /focus/i.test(message)\n ? createCopyError('not-focused', 'The document was not focused when the copy was attempted.', cause)\n : createCopyError('permission-denied', 'Clipboard write 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 default:\n return createCopyError('unknown', message || 'The copy failed for an unknown reason.', cause);\n }\n}\n\nconst DEFAULT_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 unknown: \"Couldn't copy to the clipboard. Try again.\",\n};\n\n/** Default English, user-facing sentence for an error. Replace for i18n. */\nexport function describeCopyError(error: CopyError): string {\n return DEFAULT_DESCRIPTIONS[error.type];\n}\n","import { CopyFailure, createCopyError, type CopyError } from './errors';\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.\n */\nexport type BlobSource = Blob | PromiseLike<Blob> | (() => 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 readonly mimeType: string;\n readonly data: string | Blob;\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","import { CopyFailure, createCopyError, type CopyErrorType } from './errors';\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.\n */\nexport interface ClipboardAdapter {\n write(payload: CopyPayload): 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): 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() : source);\n } catch (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(rich: RichClipboard, source: BlobSource): 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);\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}\n\nasync function writeToClipboard(\n payload: CopyPayload,\n env: ClipboardEnvironment | undefined,\n degradeHtmlToText: boolean,\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);\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> = {};\n for (const { mimeType, data } of payload.items) {\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 }\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) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText),\n };\n}\n","import { createBrowserClipboardAdapter, type ClipboardAdapter } from './clipboard-adapter';\nimport { createCopyError, isRetryableError, toCopyError, type CopyError } from './errors';\nimport { normalizePayload, validatePayload, type CopyPayload, type CopySource } from './payload';\n\nexport const DEFAULT_RESET_AFTER_MS = 2000;\nexport const DEFAULT_MAX_RETRIES = 3;\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\nexport type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable';\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 /** Max `retry()` calls after the first failure. Default 3. */\n readonly maxRetries?: number;\n readonly onCopy?: (payload: CopyPayload) => void;\n readonly onError?: (error: CopyError, payload: CopyPayload | null) => 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 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 and 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' });\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 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\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. */\nfunction 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\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\n const now = (): number => (read().now ?? Date.now)();\n\n const setState = (next: CopyState): 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 = (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 resetTimer = setTimeout(() => {\n resetTimer = undefined;\n if (state === copied) 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 payload = normalizePayload(typeof source === 'function' ? source() : source);\n } catch (cause) {\n const error = createCopyError('invalid-payload', 'The copy source function threw.', cause);\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\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);\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 if (current === generation) {\n const copied: CopiedState = { status: 'copied', payload, at: now() };\n setState(copied);\n scheduleReset(copied);\n invoke(read().onCopy, payload);\n }\n return { status: 'copied', payload };\n },\n (cause: unknown): CopyOutcome => {\n const error = toCopyError(cause);\n if (current === generation) 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 clearResetTimer();\n setState(IDLE_STATE);\n };\n\n const connect = (): (() => void) => {\n if (state.status === 'copied') scheduleReset(state);\n return () => {\n ++generation;\n clearResetTimer();\n if (state.status === 'copying') setState(IDLE_STATE);\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 { 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 { CopyError } from '../core/errors';\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 any in-flight result. */\n readonly reset: CopyMachine['reset'];\n}\n\nconst getServerSnapshot = (): CopyState => IDLE_STATE;\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 optionsRef = useRef(options);\n useIsomorphicLayoutEffect(() => {\n optionsRef.current = options;\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, options.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 { useCallback, useSyncExternalStore } from 'react';\n\nconst getServerSnapshot = (): boolean => false;\n\nfunction getMediaQueryList(query: string): MediaQueryList | null {\n return typeof window !== 'undefined' && typeof window.matchMedia === 'function'\n ? window.matchMedia(query)\n : null;\n}\n\n/** SSR-safe media query subscription. Server and hydration render `false`. */\nexport function useMediaQuery(query: string): boolean {\n const subscribe = useCallback(\n (onChange: () => void) => {\n const list = getMediaQueryList(query);\n if (!list) return () => undefined;\n list.addEventListener('change', onChange);\n return () => {\n list.removeEventListener('change', onChange);\n };\n },\n [query],\n );\n const getSnapshot = useCallback(() => getMediaQueryList(query)?.matches ?? false, [query]);\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';\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.\n const [settled, setSettled] = useState<SettledStatus>(status === 'copying' ? 'idle' : status);\n if (status !== 'copying' && status !== settled) setSettled(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 type { CSSProperties, 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 */\nexport function LiveRegion({\n message,\n politeness = 'polite',\n visuallyHidden = true,\n style,\n ...rest\n}: LiveRegionProps) {\n return (\n <span\n {...rest}\n role={politeness === 'assertive' ? 'alert' : 'status'}\n aria-live={politeness}\n aria-atomic=\"true\"\n style={visuallyHidden ? { ...visuallyHiddenStyle, ...style } : style}\n >\n {message}\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 { useDisplayStatus, type UseDisplayStatusOptions } from './useDisplayStatus';\nimport { useMediaQuery } from './useMediaQuery';\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 /** Accessible name of the trigger. */\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\nfunction getDisplayValue(value: CopySource): string | null {\n if (typeof value === 'string') return value;\n if (typeof value === 'object' && value.kind === 'text') return value.value;\n return 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_STATUSES: readonly CopyStatus[] = ['idle', 'copying', 'copied', 'error'];\n\n/**\n * Default label: every state's text is stacked in the same grid cell, so the\n * button is always as wide as its longest label and never resizes (no layout\n * shift). Only the active one is visible; the others crossfade out.\n */\nfunction DefaultTriggerLabel({ status }: { readonly status: CopyStatus }) {\n const reduceMotion = useMediaQuery('(prefers-reduced-motion: reduce)');\n return (\n <span style={{ display: 'inline-grid' }}>\n {TRIGGER_STATUSES.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 : true}\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 {DEFAULT_TRIGGER_TEXT[candidate]}\n </span>\n );\n })}\n </span>\n );\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 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={ariaLabel ?? field.messages.triggerLabel(field.label)}\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 ?? <DefaultTriggerLabel status={field.displayStatus} />)}\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"],"mappings":";;;;;AAgCA,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;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;AAEA,SAAS,WAAW,OAAgB,KAAiC;CACnE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO,KAAA;CACxD,MAAM,QAAS,MAAkC;CACjD,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;;AAGA,SAAgB,YAAY,OAA2B;CACrD,IAAI,cAAc,KAAK,GAAG,OAAO,MAAM;CAEvC,MAAM,OAAO,WAAW,OAAO,MAAM;CACrC,MAAM,UAAU,WAAW,OAAO,SAAS,KAAK;CAEhD,QAAQ,MAAR;EACE,KAAK,mBACH,OAAO,SAAS,KAAK,OAAO,IACxB,gBAAgB,eAAe,6D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AAY,SAAS,YAAY;KACjC,GAAI,eAAe,CAAC,IAAI,EAAE,YAAY,uCAAuC;IAC/E;IAEC,UAAA,qBAAqB;GAClB,GAZC,SAYD;EAEV,CAAC;CACG,CAAA;AAEV;;;;;;;;;AA4CA,MAAa,YAAY;CAAE;CAAM;CAAO;CAAO,0BA1Cf,GAAA,MAAA,WAAA,CAAqD,SAAS,iBAC5F,EAAE,UAAU,SAAS,cAAc,WAAW,GAAG,QACjD,KACA;EACA,MAAM,QAAQ,aAAa;EAC3B,MAAM,cAA2C;GAC/C,QAAQ,MAAM;GACd,eAAe,MAAM;GACrB,OAAO,MAAM;GACb,UAAU,MAAM;GAChB,UAAU,MAAM;EAClB;EAEA,OACE,iBAAA,GAAA,kBAAA,IAAA,CAAC,UAAD;GACE,GAAI;GACC;GAEL,MAAK;GACL,cAAY,aAAa,MAAM,SAAS,aAAa,MAAM,KAAK;GAChE,cAAY,MAAM;GAClB,sBAAoB,MAAM;GAC1B,iBAAe,MAAM,WAAW,KAAK,KAAA;GACrC,SAAS,qBAAqB,eAAe;IAC3C,MAAW,UAAU;GACvB,CAAC;GAEA,UAAA,OAAO,aAAa,aACjB,SAAS,WAAW,IACnB,YAAY,iBAAA,GAAA,kBAAA,IAAA,CAAC,qBAAD,EAAqB,QAAQ,MAAM,cAAgB,CAAA;EAC9D,CAAA;CAEZ,CAU+C;AAAQ"}
1
+ {"version":3,"file":"index.cjs","names":["defaultEnvironment","IGNORED_IN_FLIGHT","resolveResetDelay","reportCallbackError","invoke","defaultAdapter","getDefaultAdapter","useState","useContext","useEffect","useLayoutEffect","getServerSnapshot","useRef","useState","useSyncExternalStore","useMemo","getServerSnapshot","useCallback","useSyncExternalStore","useState","useRef","useMemo","useState","useContext","useId","useMemo","useCallback","useRef","useState","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/copy-machine.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/useMediaQuery.ts","../src/react/useRevealOnInteraction.ts","../src/react/useDisplayStatus.ts","../src/react/LiveRegion.tsx","../src/react/CopyField.tsx","../src/react/usePaste.ts"],"sourcesContent":["/**\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/** Default English, user-facing sentence for a paste error. Replace for i18n. */\nexport function describePasteError(error: CopyError): string {\n return PASTE_DESCRIPTIONS[error.type];\n}\n","import { CopyFailure, createCopyError, type CopyError } from './errors';\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.\n */\nexport type BlobSource = Blob | PromiseLike<Blob> | (() => 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 readonly mimeType: string;\n readonly data: string | Blob;\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/**\n * Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\\/*`)?\n * Wildcards never match `image/svg+xml`: accepting SVG must be explicit.\n */\nexport function matchesMimePattern(mimeType: string, pattern: string): boolean {\n if (pattern === mimeType) return true;\n if (mimeType === SVG_MIME_TYPE) 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 return (\n mimeType.startsWith('text/') ||\n mimeType === SVG_MIME_TYPE ||\n mimeType === 'application/json' ||\n mimeType === 'application/xml'\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 { 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.\n */\nexport interface ClipboardAdapter {\n write(payload: CopyPayload): 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): 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() : source);\n } catch (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(rich: RichClipboard, source: BlobSource): 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);\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): 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);\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> = {};\n for (const { mimeType, data } of payload.items) {\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 }\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) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText),\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","import { createBrowserClipboardAdapter, type ClipboardAdapter } from './clipboard-adapter';\nimport type { CopyCoordinator, CopyCoordinatorMember } from './copy-coordinator';\nimport { createCopyError, isRetryableError, toCopyError, type CopyError } from './errors';\nimport { normalizePayload, validatePayload, type CopyPayload, type CopySource } from './payload';\n\nexport const DEFAULT_RESET_AFTER_MS = 2000;\nexport const DEFAULT_MAX_RETRIES = 3;\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\nexport type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable';\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 /** Max `retry()` calls after the first failure. Default 3. */\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 /** 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 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 and 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' });\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 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\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. */\nfunction 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\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\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 payload = normalizePayload(typeof source === 'function' ? source() : source);\n } catch (cause) {\n const error = createCopyError('invalid-payload', 'The copy source function threw.', cause);\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\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);\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 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 const error = toCopyError(cause);\n if (current === generation) 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 clearResetTimer();\n setState(IDLE_STATE);\n };\n\n const connect = (): (() => void) => {\n if (state.status === 'copied') scheduleReset(state);\n return () => {\n ++generation;\n clearResetTimer();\n if (state.status === 'copying') setState(IDLE_STATE);\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 { copyFailure } from './errors';\nimport { isTextualMimeType, matchesMimePattern, 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'`) or a wildcard (`'image/*'`, `'*\\/*'`).\n * `image/svg+xml` is only accepted when listed exactly (it is scriptable XML).\n */\nexport type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;\n\nexport interface PasteLimits {\n /** Total size cap across all accepted items. Strings count UTF-16 code units. Default 32 MiB. */\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. */\nexport type PasteSource = 'clipboard' | 'event';\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\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 normalizeMimeType(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\nconst sizeOf = (data: string | Blob): number => (typeof data === 'string' ? data.length : 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 `DataTransfer` (paste events). */\nexport interface DataTransferLike {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n readonly files?: ArrayLike<File> | null;\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 = normalizeMimeType(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): 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 = normalizeMimeType(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 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<PasteResult> {\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 clipboard holds nothing that matches `accept`.');\n }\n return { source, items, text, html, images, files };\n}\n","import { CopyFailure, copyFailure, toCopyError } from './errors';\nimport { matchesMimePattern } from './mime';\nimport {\n collectClipboardItems,\n enforcePasteLimits,\n finalizePaste,\n type ClipboardItemLike,\n type PasteEntry,\n type PasteResult,\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 */\nexport interface PasteAdapter {\n read(options: ResolvedPasteReadOptions): Promise<PasteResult>;\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<PasteResult> {\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(clipboard: ClipboardWithRead, options: ResolvedPasteReadOptions): Promise<PasteResult> {\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);\n return finalizePaste(entries, 'clipboard', options);\n}\n\nfunction readFromClipboard(env: PasteEnvironment | undefined, options: ResolvedPasteReadOptions): Promise<PasteResult> {\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);\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) => {\n try {\n return readFromClipboard(getEnvironment(), resolved);\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 { toCopyError, type CopyError } from './errors';\nimport { createBrowserPasteAdapter, type PasteAdapter } from './paste-adapter';\nimport {\n enforcePasteLimits,\n finalizePaste,\n resolvePasteReadOptions,\n snapshotDataTransfer,\n type DataTransferLike,\n type PasteReadOptions,\n type PasteResult,\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}\n\nexport type PasteState = PasteIdleState | PasteReadingState | PasteReadState | PasteErrorState;\nexport type PasteStatus = PasteState['status'];\n\nexport type PasteIgnoredReason = 'in-flight' | 'no-accepted-content';\n\n/** What `paste()` / `pasteEvent()` 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/* ---------------------------------------------------------------- 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 only: call `event.preventDefault()` when the event carried\n * accepted content, so the browser doesn't also insert it. Default `true`.\n */\n readonly preventDefault?: boolean;\n readonly onPaste?: (result: PasteResult) => void;\n readonly onError?: (error: CopyError) => 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 /** Back to `idle`, discarding any in-flight result. */\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 and 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});\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\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. */\nfunction 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\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\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 /** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */\n const run = (produce: () => Promise<PasteResult>): Promise<PasteOutcome> => {\n clearResetTimer();\n const current = ++generation;\n setState(PASTE_READING_STATE);\n\n let pending: Promise<PasteResult>;\n try {\n pending = produce();\n } catch (cause) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified below\n pending = Promise.reject(cause);\n }\n\n return pending.then(\n (result): PasteOutcome => {\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 const error = toCopyError(cause, 'read');\n if (current === generation) {\n setState({ status: 'error', error });\n invoke(read().onError, error);\n }\n return { status: 'error', error };\n },\n );\n };\n\n const paste = (): Promise<PasteOutcome> => {\n if (state.status === 'reading') return Promise.resolve(IGNORED_IN_FLIGHT);\n return run(() => {\n const resolved = resolvePasteReadOptions(read());\n return (read().adapter ?? getDefaultAdapter()).read(resolved);\n });\n };\n\n const pasteEvent = (event: PasteEventLike): Promise<PasteOutcome> => {\n const data = event.clipboardData;\n if (!data) return Promise.resolve(IGNORED_NO_CONTENT);\n\n const current = read();\n let resolved: ReturnType<typeof resolvePasteReadOptions>;\n try {\n resolved = resolvePasteReadOptions(current);\n } catch (cause) {\n return run(() => {\n throw cause;\n });\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 (current.preventDefault !== false) event.preventDefault();\n\n return run(() => {\n enforcePasteLimits(entries, resolved);\n return finalizePaste(entries, 'event', resolved);\n });\n };\n\n const reset = (): void => {\n ++generation;\n clearResetTimer();\n setState(PASTE_IDLE_STATE);\n };\n\n const connect = (): (() => void) => {\n if (state.status === 'read') scheduleReset(state);\n return () => {\n ++generation;\n clearResetTimer();\n if (state.status === 'reading') setState(PASTE_IDLE_STATE);\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 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 any in-flight result. */\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, options.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 { useCallback, useSyncExternalStore } from 'react';\n\nconst getServerSnapshot = (): boolean => false;\n\nfunction getMediaQueryList(query: string): MediaQueryList | null {\n return typeof window !== 'undefined' && typeof window.matchMedia === 'function'\n ? window.matchMedia(query)\n : null;\n}\n\n/** SSR-safe media query subscription. Server and hydration render `false`. */\nexport function useMediaQuery(query: string): boolean {\n const subscribe = useCallback(\n (onChange: () => void) => {\n const list = getMediaQueryList(query);\n if (!list) return () => undefined;\n list.addEventListener('change', onChange);\n return () => {\n list.removeEventListener('change', onChange);\n };\n },\n [query],\n );\n const getSnapshot = useCallback(() => getMediaQueryList(query)?.matches ?? false, [query]);\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 type { CSSProperties, 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 */\nexport function LiveRegion({\n message,\n politeness = 'polite',\n visuallyHidden = true,\n style,\n ...rest\n}: LiveRegionProps) {\n return (\n <span\n {...rest}\n role={politeness === 'assertive' ? 'alert' : 'status'}\n aria-live={politeness}\n aria-atomic=\"true\"\n style={visuallyHidden ? { ...visuallyHiddenStyle, ...style } : style}\n >\n {message}\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 { useDisplayStatus, type UseDisplayStatusOptions } from './useDisplayStatus';\nimport { useMediaQuery } from './useMediaQuery';\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 /** Accessible name of the trigger. */\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\nfunction getDisplayValue(value: CopySource): string | null {\n if (typeof value === 'string') return value;\n if (typeof value === 'object' && value.kind === 'text') return value.value;\n return 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_STATUSES: readonly CopyStatus[] = ['idle', 'copying', 'copied', 'error'];\n\n/**\n * Default label: every state's text is stacked in the same grid cell, so the\n * button is always as wide as its longest label and never resizes (no layout\n * shift). Only the active one is visible; the others crossfade out.\n */\nfunction DefaultTriggerLabel({ status }: { readonly status: CopyStatus }) {\n const reduceMotion = useMediaQuery('(prefers-reduced-motion: reduce)');\n return (\n <span style={{ display: 'inline-grid' }}>\n {TRIGGER_STATUSES.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 : true}\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 {DEFAULT_TRIGGER_TEXT[candidate]}\n </span>\n );\n })}\n </span>\n );\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 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={ariaLabel ?? field.messages.triggerLabel(field.label)}\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 ?? <DefaultTriggerLabel status={field.displayStatus} />)}\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 { useEffect, useMemo, useRef, useState, useSyncExternalStore, type ClipboardEventHandler } from 'react';\nimport type { CopyError } from '../core/errors';\nimport {\n PASTE_IDLE_STATE,\n createPasteMachine,\n type PasteMachine,\n type PasteMachineOptions,\n type PasteState,\n type PasteStatus,\n} from '../core/paste-machine';\nimport 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 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 /** 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. Back to `idle`, discarding any in-flight result. */\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\nconst getServerSnapshot = (): PasteState => PASTE_IDLE_STATE;\n\n/**\n * Paste state machine bound to a component. Supports a \"Paste\" button\n * (`paste()`, may prompt for permission) and keyboard paste (`targetProps`\n * or `listenOnDocument`, no prompt). 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\n const targetProps = useMemo<PasteTargetProps<T>>(\n () => ({\n onPaste: (event) => {\n void machine.pasteEvent(event);\n },\n }),\n [machine],\n );\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 paste: machine.paste,\n pasteEvent: machine.pasteEvent,\n reset: machine.reset,\n targetProps,\n }),\n [state, machine, targetProps],\n );\n}\n"],"mappings":";;;;;AA4CA,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,Y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