react-smart-copy 1.1.1 → 1.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.
package/README.md CHANGED
@@ -281,6 +281,19 @@ keeps working. Events with accepted content are `preventDefault()`-ed (opt out w
281
281
  States: `idle` → `reading` → `read` | `error`. `paste()` is ignored while reading; a keyboard
282
282
  paste supersedes an in-flight read. Results persist until `reset()` unless you set `resetAfterMs`.
283
283
 
284
+ **Retry.** After a retryable failure of the Paste button (permission denied, page not focused),
285
+ `retry()` reads the clipboard again, up to `maxRetries` (default 3), and `canRetry` tells you
286
+ whether it can help. Call it from a click, like `paste()`. Keyboard-paste failures can't be
287
+ retried: the event's data is gone once it has been handled, so ask the user to paste again.
288
+
289
+ ```tsx
290
+ const { paste, retry, canRetry, error } = usePaste({ accept: ["image"] });
291
+ // ...
292
+ {error && (canRetry
293
+ ? <button onClick={() => void retry()}>Allow clipboard access and try again</button>
294
+ : <p role="alert">{describePasteError(error)}</p>)}
295
+ ```
296
+
284
297
  ## States
285
298
 
286
299
  ```ts
@@ -304,8 +317,8 @@ type CopyState =
304
317
  | `copying` | write rejects | `error` |
305
318
  | `error` (retryable, under the cap) | `retry()` | `copying` with the same payload, `retryCount + 1` |
306
319
  | `error` (cap reached) | `retry()` | `error` with `max-retries-exceeded` |
307
- | any | `reset()` | `idle`; an in-flight result is discarded |
308
- | any | unmount | timers cleared; in-flight result and callbacks dropped |
320
+ | any | `reset()` | `idle`; in-flight work is aborted and its result discarded |
321
+ | any | unmount | timers cleared; in-flight work aborted, its result and callbacks dropped |
309
322
 
310
323
  ## Errors
311
324
 
@@ -322,7 +335,7 @@ type CopyState =
322
335
  | `no-content` | Paste: nothing on the clipboard matches `accept` | No |
323
336
  | `too-large` | Over `maxBytes`, `maxItems`, `maxPixels` or `maxLength` | No |
324
337
  | `timeout` | Capture did not finish within `timeoutMs` | Yes |
325
- | `aborted` | Your `AbortSignal` fired | No |
338
+ | `aborted` | Your `AbortSignal` fired, or the operation was reset, superseded or unmounted | No |
326
339
  | `unknown` | Anything unclassified | Yes |
327
340
 
328
341
  `error.message` is for developers. For users, call `describeCopyError(error)` /
@@ -341,6 +354,22 @@ useCopy({
341
354
  });
342
355
  ```
343
356
 
357
+ ## Cancellation
358
+
359
+ Every copy and paste gets an `AbortSignal`. It fires when the operation is superseded, when you
360
+ call `reset()`, or when the component unmounts. The state machine already ignores late results;
361
+ the signal lets the *work* stop too, so a slow screenshot or a large clipboard decode doesn't keep
362
+ running (and holding memory) after nobody needs it.
363
+
364
+ - **Image sources** receive it: `copy({ kind: "image", blob: (context) => render(context?.signal) })`
365
+ - **`captureSource` / `captureImage`** wire it up for you, combined with any `signal` you pass
366
+ - **Custom adapters** receive it as their last argument: `write(payload, { signal })`, `read(options, { signal })`
367
+
368
+ The signal never fires after an operation has finished. If a cancelled operation fails anyway,
369
+ the promise you awaited resolves `{ status: "ignored", reason: "cancelled" }` rather than an
370
+ error, and `onError` is not called, so you never toast a failure for work the user walked away
371
+ from. Adapters and sources written before 1.2 keep working: the argument is optional.
372
+
344
373
  ## CopyField API
345
374
 
346
375
  | Part | Renders | Notes |
@@ -380,13 +409,13 @@ export function NotesPasteField() {
380
409
  return (
381
410
  <PasteField.Root
382
411
  label="Notes"
383
- pasteOptions={{ accept: ["text"] }}
384
- onPaste={(result) => setNotes(result.text ?? "")}
412
+ pasteOptions={{ accept: ["text", "image"], onPaste: (result) => setNotes(result.text ?? "") }}
385
413
  >
386
414
  <PasteField.Label />
387
415
  <PasteField.Status /> {/* "Ready" → "Reading…" → "Pasted" → "Error" */}
388
- <PasteField.Zone /> {/* focusable drop target; accepts Ctrl/⌘+V */}
416
+ <PasteField.Zone /> {/* focusable paste target; accepts Ctrl/⌘+V */}
389
417
  <PasteField.Trigger /> {/* "Paste" → "Pasting…" → "Pasted" → "Retry" */}
418
+ <PasteField.Preview placeholder="Nothing pasted yet" /> {/* text, thumbnails, file names */}
390
419
  </PasteField.Root>
391
420
  );
392
421
  }
@@ -398,7 +427,8 @@ export function NotesPasteField() {
398
427
  | `PasteField.Label` | `span` | Defaults to `label` |
399
428
  | `PasteField.Status` | `span` | Text label per status. Defaults: `idle → "Ready"`, `reading → "Reading…"`, `read → "Pasted"`, `error → "Error"`. Custom `labels` prop |
400
429
  | `PasteField.Zone` | `div role="region"` | Focusable paste target (`tabIndex=0`); handles Ctrl/⌘+V itself. Named "Paste area for {label}" via `aria-label` (override with `aria-label`, `aria-labelledby` or `messages.zoneLabel`). Sets `aria-keyshortcuts="Control+V Meta+V"`. `focusable={false}` removes tabIndex |
401
- | `PasteField.Trigger` | `button type="button"` | Children can be a node or `({ status, displayStatus, state, revealed }) => node`. `aria-busy` while reading; never `disabled`, so focus stays put |
430
+ | `PasteField.Trigger` | `button type="button"` | Children can be a node or `({ status, displayStatus, state, revealed, canRetry }) => node`. `aria-busy` while reading; never `disabled`, so focus stays put |
431
+ | `PasteField.Preview` | `div` | What was pasted: text (truncated at `maxTextLength`, default 2000), image thumbnails (`imageAlt` for alt text) and non-image file names. **Never renders pasted HTML.** Shows `placeholder` until there is a result. Object URLs are revoked on change and unmount. Pass `({ result, imageUrls }) => node` to render it yourself |
402
432
  | `usePasteField()` | — | Full context, for building your own parts inside `PasteField.Root` |
403
433
 
404
434
  Styling hooks on Root, Zone and Trigger: `data-display-state="idle | reading | read | error"`
@@ -459,10 +489,11 @@ import {
459
489
  } from "react-smart-copy/core";
460
490
 
461
491
  const electronAdapter: ClipboardAdapter = {
462
- write: async (payload) => {
492
+ write: async (payload, context) => {
463
493
  if (payload.kind !== "text")
464
494
  throw new CopyFailure(createCopyError("unsupported-format", "Text only"));
465
495
  window.electron.clipboard.writeText(payload.value);
496
+ // context?.signal aborts on reset / unmount: check it before any slow follow-up work.
466
497
  },
467
498
  };
468
499
  ```
@@ -481,13 +512,18 @@ embedded webviews. Where a capability is missing you get a typed error, never a
481
512
  ## Roadmap
482
513
 
483
514
  - ~~**0.2** `usePaste`, `<CopyGroup>`, SVG/DOM capture~~ shipped
484
- - **1.0** Frozen API, comprehensive SSR/security/a11y audit (in progress)
515
+ - ~~**1.0** Frozen API, SSR / security / accessibility audit~~ shipped
516
+ - ~~**1.1** `PasteField`~~ shipped
517
+ - ~~**1.2** Paste `retry()`, cancellation with `AbortSignal`, `PasteField.Preview`~~ shipped
518
+ - **Next** Consistent `maxBytes` accounting across paste paths, `onReset` / `onRelease` telemetry callbacks
519
+
520
+ Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://suprabhat02.github.io/react-smart-copy/#releases).
485
521
 
486
522
  ## Development
487
523
 
488
524
  ```bash
489
525
  npm install
490
- npm run verify # lint, types, 300+ tests, build, publint + attw, size budgets
526
+ npm run verify # lint, types, 398 tests at 100% coverage, build, publint + attw, size budgets
491
527
  npm run changeset # describe your change for the changelog
492
528
  npm run site:preview # docs site at http://localhost:3000
493
529
  ```
package/dist/capture.cjs CHANGED
@@ -477,12 +477,46 @@ async function captureElement(node, options = {}) {
477
477
  }
478
478
  /**
479
479
  * A lazy `BlobSource` for `copy()`. Resolving the element at click time and
480
- * starting inside the gesture keeps Safari happy.
480
+ * starting inside the gesture keeps Safari happy. Rasterising stops when the
481
+ * copy is reset or its component unmounts, or when `options.signal` aborts.
481
482
  *
482
483
  * @example copy({ kind: 'image', blob: captureSource(() => cardRef.current, { rasterize }) })
483
484
  */
484
485
  function captureSource(getNode, options = {}) {
485
- return () => captureElement(getNode(), options);
486
+ return (context) => {
487
+ const a = options.signal;
488
+ const b = context?.signal;
489
+ if (!a || !b) {
490
+ const signal = a ?? b;
491
+ return captureElement(getNode(), signal ? {
492
+ ...options,
493
+ signal
494
+ } : options);
495
+ }
496
+ const any = AbortSignal.any;
497
+ if (typeof any === "function") return captureElement(getNode(), {
498
+ ...options,
499
+ signal: any([a, b])
500
+ });
501
+ const controller = new AbortController();
502
+ const onAbortA = () => {
503
+ controller.abort(a.reason);
504
+ };
505
+ const onAbortB = () => {
506
+ controller.abort(b.reason);
507
+ };
508
+ if (a.aborted) onAbortA();
509
+ else if (b.aborted) onAbortB();
510
+ a.addEventListener("abort", onAbortA);
511
+ b.addEventListener("abort", onAbortB);
512
+ return captureElement(getNode(), {
513
+ ...options,
514
+ signal: controller.signal
515
+ }).finally(() => {
516
+ a.removeEventListener("abort", onAbortA);
517
+ b.removeEventListener("abort", onAbortB);
518
+ });
519
+ };
486
520
  }
487
521
  /** Shorthand for `{ kind: 'image', blob: captureSource(getNode, options) }`. */
488
522
  function captureImage(getNode, options = {}) {
@@ -1 +1 @@
1
- {"version":3,"file":"capture.cjs","names":[],"sources":["../src/core/errors.ts","../src/capture/environment.ts","../src/capture/options.ts","../src/core/mime.ts","../src/core/payload.ts","../src/capture/deadline.ts","../src/capture/render.ts","../src/capture/svg.ts","../src/capture/element.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 } from '../core/errors';\n\n/** A decoded image, ready to be drawn. `source` is platform-specific (an `HTMLImageElement` in browsers). */\nexport interface DecodedImage {\n readonly source: unknown;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface PngTarget {\n /** Integer pixel size of the output. */\n readonly width: number;\n readonly height: number;\n /** CSS colour painted under the image, or `null` for transparency. */\n readonly background: string | null;\n}\n\n/**\n * Everything capture needs from the platform. The default uses the DOM;\n * inject your own for workers (OffscreenCanvas), native shells or tests.\n */\nexport interface CaptureEnvironment {\n readonly createObjectURL: (blob: Blob) => string;\n readonly revokeObjectURL: (url: string) => void;\n /** Serialises an `<svg>` element to markup. */\n readonly serializeSvg: (node: Element) => string;\n /** Decodes an image from a `blob:` or `data:` URL. */\n readonly loadImage: (url: string) => Promise<DecodedImage>;\n /** Draws the image scaled to `target` and encodes it as PNG. */\n readonly encodePng: (image: DecodedImage, target: PngTarget) => Promise<Blob>;\n}\n\nfunction loadImage(url: string): Promise<DecodedImage> {\n return new Promise((resolve, reject) => {\n const image = new Image();\n image.decoding = 'async';\n image.onload = () => {\n resolve({ source: image, width: image.naturalWidth, height: image.naturalHeight });\n };\n image.onerror = () => {\n reject(copyFailure('blob-generation-failed', 'The image could not be decoded.'));\n };\n image.src = url;\n });\n}\n\nfunction encodePng(image: DecodedImage, target: PngTarget): Promise<Blob> {\n return new Promise((resolve, reject) => {\n const canvas = document.createElement('canvas');\n canvas.width = target.width;\n canvas.height = target.height;\n const context = canvas.getContext('2d');\n if (!context) {\n reject(copyFailure('unsupported', 'Canvas 2D rendering is not available.'));\n return;\n }\n if (target.background !== null) {\n context.fillStyle = target.background;\n context.fillRect(0, 0, target.width, target.height);\n }\n context.drawImage(image.source as CanvasImageSource, 0, 0, target.width, target.height);\n // Throws SecurityError synchronously for tainted canvases; the executor turns that into a rejection.\n canvas.toBlob((blob) => {\n if (blob) resolve(blob);\n else reject(copyFailure('blob-generation-failed', 'canvas.toBlob() produced nothing (canvas too large?).'));\n }, 'image/png');\n });\n}\n\n/** The DOM-backed environment, or `null` outside a browser. */\nexport function getDefaultCaptureEnvironment(): CaptureEnvironment | null {\n if (\n typeof document === 'undefined' ||\n typeof Image !== 'function' ||\n typeof XMLSerializer !== 'function' ||\n typeof URL.createObjectURL !== 'function'\n ) {\n return null;\n }\n return {\n createObjectURL: (blob) => URL.createObjectURL(blob),\n revokeObjectURL: (url) => {\n URL.revokeObjectURL(url);\n },\n serializeSvg: (node) => new XMLSerializer().serializeToString(node),\n loadImage,\n encodePng,\n };\n}\n\nexport function resolveCaptureEnvironment(environment: CaptureEnvironment | undefined): CaptureEnvironment {\n const resolved = environment ?? getDefaultCaptureEnvironment();\n if (!resolved) {\n throw copyFailure('unsupported', 'Image capture needs a browser environment (document, Image, canvas).');\n }\n return resolved;\n}\n","import { copyFailure } from '../core/errors';\nimport type { CaptureEnvironment } from './environment';\n\nexport const DEFAULT_CAPTURE_SCALE = 2;\nexport const MAX_CAPTURE_SCALE = 10;\n/** 4096 × 4096: the canvas area limit of Safari/iOS, the strictest mainstream engine. */\nexport const DEFAULT_MAX_PIXELS = 16_777_216;\nexport const DEFAULT_CAPTURE_TIMEOUT_MS = 15_000;\n\nexport interface RenderOptions {\n /** Output width in CSS px (before `scale`). Omit to use the intrinsic size; set one side to keep the aspect ratio. */\n readonly width?: number;\n /** Output height in CSS px (before `scale`). */\n readonly height?: number;\n /** Pixel density multiplier, e.g. `window.devicePixelRatio`. Default 2 (crisp on HiDPI). Max 10. */\n readonly scale?: number;\n /** CSS colour under the image. Default `null` (transparent). */\n readonly background?: string | null;\n /** Refuse outputs larger than this many pixels (memory / DoS guard). Default 16 777 216. */\n readonly maxPixels?: number;\n /** Give up after this long. Default 15 000 ms. `Infinity` disables. */\n readonly timeoutMs?: number;\n /** Cancel the capture. */\n readonly signal?: AbortSignal;\n /** Platform hooks. Defaults to the DOM. */\n readonly environment?: CaptureEnvironment;\n}\n\nexport interface RenderSettings {\n readonly scale: number;\n readonly background: string | null;\n readonly maxPixels: number;\n readonly timeoutMs: number;\n}\n\nexport interface Size {\n readonly width: number;\n readonly height: number;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nconst isPositiveFinite = (value: number): boolean => Number.isFinite(value) && value > 0;\n\nexport function resolveRenderSettings(options: RenderOptions): RenderSettings {\n const scale = options.scale ?? DEFAULT_CAPTURE_SCALE;\n if (!isPositiveFinite(scale) || scale > MAX_CAPTURE_SCALE) {\n throw invalid(`\\`scale\\` must be > 0 and <= ${String(MAX_CAPTURE_SCALE)} (received ${String(scale)}).`);\n }\n const maxPixels = options.maxPixels ?? DEFAULT_MAX_PIXELS;\n if (!Number.isInteger(maxPixels) || maxPixels <= 0) {\n throw invalid(`\\`maxPixels\\` must be a positive integer (received ${String(maxPixels)}).`);\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_CAPTURE_TIMEOUT_MS;\n if (timeoutMs !== Infinity && !isPositiveFinite(timeoutMs)) {\n throw invalid(`\\`timeoutMs\\` must be > 0 or Infinity (received ${String(timeoutMs)}).`);\n }\n return { scale, background: options.background ?? null, maxPixels, timeoutMs };\n}\n\n/** Combines explicit `width`/`height` with an intrinsic size, keeping the aspect ratio when only one is set. */\nexport function resolveSize(intrinsic: Size | null, width: number | undefined, height: number | undefined): Size {\n for (const [name, value] of [\n ['width', width],\n ['height', height],\n ] as const) {\n if (value !== undefined && !isPositiveFinite(value)) {\n throw invalid(`\\`${name}\\` must be a positive number (received ${String(value)}).`);\n }\n }\n if (width !== undefined && height !== undefined) return { width, height };\n if (intrinsic === null) {\n throw invalid('The size to render is unknown: pass `width` and `height`, or give the source a size.');\n }\n if (width !== undefined) return { width, height: (width * intrinsic.height) / intrinsic.width };\n if (height !== undefined) return { width: (height * intrinsic.width) / intrinsic.height, height };\n return intrinsic;\n}\n\n/** Integer pixel size after scaling. Throws `too-large` past `maxPixels`. */\nexport function toPixelSize(size: Size, settings: Pick<RenderSettings, 'scale' | 'maxPixels'>): Size {\n const width = Math.max(1, Math.round(size.width * settings.scale));\n const height = Math.max(1, Math.round(size.height * settings.scale));\n assertPixelBudget(width, height, settings.maxPixels);\n return { width, height };\n}\n\nexport function assertPixelBudget(width: number, height: number, maxPixels: number): void {\n if (width * height > maxPixels) {\n throw copyFailure(\n 'too-large',\n `A ${String(width)}×${String(height)} image exceeds the ${String(maxPixels)}-pixel limit. Lower \\`scale\\` or raise \\`maxPixels\\`.`,\n );\n }\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 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, type CopyFailure } from '../core/errors';\n\nexport interface DeadlineOptions {\n readonly timeoutMs: number;\n readonly signal?: AbortSignal | undefined;\n /** Used in messages: \"<label> timed out\". */\n readonly label: string;\n}\n\n/**\n * Runs `task` with a timeout and an optional caller `AbortSignal`. The task\n * receives a signal that fires on either, so cooperative work can stop early.\n * Rejects with classified `timeout` / `aborted` failures.\n */\nexport function withDeadline<T>(task: (signal: AbortSignal) => PromiseLike<T> | T, options: DeadlineOptions): Promise<T> {\n const { timeoutMs, label } = options;\n const external = options.signal;\n if (external?.aborted) {\n return Promise.reject(copyFailure('aborted', `${label} was aborted.`, external.reason));\n }\n\n const controller = new AbortController();\n return new Promise<T>((resolve, reject) => {\n const finish = (abort: boolean): void => {\n clearTimeout(timer);\n external?.removeEventListener('abort', onAbort);\n // Always signal downstream cooperative work to stop — whether we timed\n // out, were aborted, or resolved successfully. Without this, a task\n // that started a long operation keeps that operation alive after we've\n // already resolved, leaking resources until GC.\n /* c8 ignore next -- abort=false path is never used; kept for future API flexibility */\n if (abort) controller.abort();\n };\n const fail = (failure: CopyFailure): void => {\n finish(true);\n reject(failure);\n };\n const onAbort = (): void => {\n fail(copyFailure('aborted', `${label} was aborted.`, (external as AbortSignal).reason));\n };\n const timer =\n timeoutMs === Infinity\n ? undefined\n : setTimeout(() => {\n fail(copyFailure('timeout', `${label} timed out after ${String(timeoutMs)} ms.`));\n }, timeoutMs);\n external?.addEventListener('abort', onAbort, { once: true });\n\n new Promise<T>((run) => {\n run(task(controller.signal));\n }).then(\n (value) => {\n finish(true);\n resolve(value);\n },\n (cause: unknown) => {\n finish(true);\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified by the caller\n reject(cause);\n },\n );\n });\n}\n","import { copyFailure, isCopyFailure } from '../core/errors';\nimport { IMAGE_MIME_TYPE } from '../core/payload';\nimport { sniffImageType } from '../core/mime';\nimport { withDeadline } from './deadline';\nimport type { CaptureEnvironment } from './environment';\nimport { assertPixelBudget, type RenderSettings, type Size } from './options';\n\n/** Maps anything unexpected to `blob-generation-failed`, keeping already-classified failures. */\nexport function classifyCaptureError(cause: unknown, label: string): unknown {\n return isCopyFailure(cause) ? cause : copyFailure('blob-generation-failed', `${label} failed.`, cause);\n}\n\n/**\n * Decodes an image Blob and re-encodes it as PNG at `target` (or its natural\n * size), within the deadline. The object URL is always revoked.\n */\nexport async function drawBlobToPng(\n blob: Blob,\n target: Size | null,\n settings: RenderSettings,\n environment: CaptureEnvironment,\n signal: AbortSignal | undefined,\n label: string,\n): Promise<Blob> {\n const url = environment.createObjectURL(blob);\n try {\n return await withDeadline(\n async () => {\n const image = await environment.loadImage(url);\n const size = target ?? { width: image.width, height: image.height };\n assertPixelBudget(size.width, size.height, settings.maxPixels);\n return environment.encodePng(image, { ...size, background: settings.background });\n },\n { timeoutMs: settings.timeoutMs, signal, label },\n );\n } catch (cause) {\n throw classifyCaptureError(cause, label);\n } finally {\n environment.revokeObjectURL(url);\n }\n}\n\n/** Width and height from a PNG's IHDR chunk, read from the first 24 bytes only. */\nexport async function readPngSize(blob: Blob): Promise<Size | null> {\n const bytes = new Uint8Array(await blob.slice(0, 24).arrayBuffer());\n if (bytes.length < 24) return null;\n const view = new DataView(bytes.buffer);\n return { width: view.getUint32(16), height: view.getUint32(20) };\n}\n\n/**\n * Guarantees the clipboard-safe result: a real PNG (verified by its bytes),\n * typed `image/png`, within the pixel budget. Other raster formats are re-encoded.\n */\nexport async function ensurePng(\n blob: Blob,\n settings: RenderSettings,\n environment: () => CaptureEnvironment,\n signal: AbortSignal | undefined,\n label: string,\n): Promise<Blob> {\n const actual = await sniffImageType(blob);\n if (actual === null) {\n throw copyFailure('blob-generation-failed', `${label} did not produce an image.`);\n }\n if (actual !== IMAGE_MIME_TYPE) {\n return drawBlobToPng(blob, null, settings, environment(), signal, label);\n }\n const size = await readPngSize(blob);\n if (size === null) throw copyFailure('blob-generation-failed', `${label} produced a truncated PNG.`);\n assertPixelBudget(size.width, size.height, settings.maxPixels);\n return blob.type === IMAGE_MIME_TYPE ? blob : blob.slice(0, blob.size, IMAGE_MIME_TYPE);\n}\n","import { copyFailure } from '../core/errors';\nimport { SVG_MIME_TYPE } from '../core/mime';\nimport { resolveCaptureEnvironment } from './environment';\nimport { drawBlobToPng } from './render';\nimport { resolveRenderSettings, resolveSize, toPixelSize, type RenderOptions, type Size } from './options';\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n/** Refuse absurd markup before handing it to the image decoder. 10 M characters. */\nexport const DEFAULT_MAX_SVG_LENGTH = 10_000_000;\n\nexport interface SvgToPngOptions extends RenderOptions {\n /** Max markup length in characters. Default 10 000 000. */\n readonly maxLength?: number;\n}\n\n// Both patterns are linear-time: untrusted markup must not be able to trigger catastrophic backtracking.\nconst SVG_OPEN = /<svg\\b/i;\nconst LENGTH = /^(\\d+(?:\\.\\d+)?|\\.\\d+)(?:px)?$/i;\n\n/** The first `<svg …>` tag, found with two linear scans. */\nfunction findRootTag(markup: string): string | null {\n const start = markup.search(SVG_OPEN);\n if (start === -1) return null;\n const end = markup.indexOf('>', start);\n return end === -1 ? null : markup.slice(start, end + 1);\n}\n\n// Pre-compiled attribute patterns for the three attributes we ever read.\n// Compiling at module load time and with fixed literal names eliminates any\n// risk of ReDoS from runtime-constructed RegExps.\nconst ATTR_PATTERNS: Readonly<Record<string, RegExp>> = /* @__PURE__ */ Object.freeze({\n width: /\\swidth\\s*=\\s*([\"'])(.*?)\\1/i,\n height: /\\sheight\\s*=\\s*([\"'])(.*?)\\1/i,\n viewBox: /\\sviewBox\\s*=\\s*([\"'])(.*?)\\1/i,\n xmlns: /\\sxmlns\\s*=\\s*([\"'])(.*?)\\1/i,\n});\n\nfunction readAttribute(tag: string, name: keyof typeof ATTR_PATTERNS): string | null {\n const pattern = ATTR_PATTERNS[name];\n /* c8 ignore next -- TypeScript enforces name is a key of ATTR_PATTERNS; guard is for JS callers only */\n if (!pattern) return null;\n const match = pattern.exec(tag);\n return match === null ? null : String(match[2]);\n}\n\nfunction parseLength(value: string | null): number | null {\n if (value === null) return null;\n const match = LENGTH.exec(value.trim());\n const number = match ? Number(match[1]) : NaN;\n return number > 0 ? number : null;\n}\n\n/** Intrinsic size from the root tag: `width`/`height` in px, else the `viewBox`. */\nexport function readSvgSize(markup: string): Size | null {\n const tag = findRootTag(markup);\n if (tag === null) return null;\n const width = parseLength(readAttribute(tag, 'width'));\n const height = parseLength(readAttribute(tag, 'height'));\n if (width !== null && height !== null) return { width, height };\n\n const raw = readAttribute(tag, 'viewBox');\n const viewBox = raw != null ? raw.trim().split(/[\\s,]+/).map(Number) : [];\n const [, , boxWidth = NaN, boxHeight = NaN] = viewBox;\n if (viewBox.length !== 4 || !(boxWidth > 0) || !(boxHeight > 0)) return null;\n if (width !== null) return { width, height: (width * boxHeight) / boxWidth };\n if (height !== null) return { width: (height * boxWidth) / boxHeight, height };\n return { width: boxWidth, height: boxHeight };\n}\n\n/** Adds the SVG namespace when missing; `<img>` refuses to decode SVG without it. */\nexport function ensureSvgNamespace(markup: string): string {\n const tag = findRootTag(markup);\n if (tag === null) throw copyFailure('invalid-payload', 'The markup has no <svg> root element.');\n if (readAttribute(tag, 'xmlns') !== null) return markup;\n return markup.replace(SVG_OPEN, `<svg xmlns=\"${SVG_NAMESPACE}\"`);\n}\n\nconst isSvgElement = (value: Element): boolean => value.localName === 'svg';\n\n/**\n * Rasterises SVG (an `<svg>` element or markup) to a PNG Blob, ready for\n * `copy({ kind: 'image', blob })`.\n *\n * Security: the SVG is decoded as an *image*, where browsers disable scripts,\n * event handlers and external resource loading, and it is never inserted into\n * the document. Size is capped in characters and pixels.\n */\nexport async function svgToPngBlob(source: Element | string, options: SvgToPngOptions = {}): Promise<Blob> {\n const environment = resolveCaptureEnvironment(options.environment);\n const settings = resolveRenderSettings(options);\n const maxLength = options.maxLength ?? DEFAULT_MAX_SVG_LENGTH;\n\n let intrinsic: Size | null = null;\n let markup: string;\n if (typeof source === 'string') {\n markup = source;\n } else {\n if (!isSvgElement(source)) throw copyFailure('invalid-payload', `Expected an <svg> element, got <${source.localName}>.`);\n const rect = source.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) intrinsic = { width: rect.width, height: rect.height };\n markup = environment.serializeSvg(source);\n }\n\n if (markup.length > maxLength) {\n throw copyFailure('too-large', `The SVG markup exceeds ${String(maxLength)} characters.`);\n }\n const prepared = ensureSvgNamespace(markup);\n const size = resolveSize(intrinsic ?? readSvgSize(prepared), options.width, options.height);\n const target = toPixelSize(size, settings);\n\n const blob = new Blob([prepared], { type: SVG_MIME_TYPE });\n return drawBlobToPng(blob, target, settings, environment, options.signal, 'SVG rasterisation');\n}\n","import { copyFailure } from '../core/errors';\nimport { SVG_MIME_TYPE } from '../core/mime';\nimport { isBlob, type ImagePayload } from '../core/payload';\nimport { withDeadline } from './deadline';\nimport { resolveCaptureEnvironment, type CaptureEnvironment } from './environment';\nimport {\n resolveRenderSettings,\n resolveSize,\n toPixelSize,\n type RenderOptions,\n type RenderSettings,\n type Size,\n} from './options';\nimport { classifyCaptureError, ensurePng } from './render';\nimport { svgToPngBlob } from './svg';\n\n/** Anything with `canvas.toBlob()`: `HTMLCanvasElement`, or a compatible object. */\nexport interface CanvasLike {\n toBlob(callback: (blob: Blob | null) => void, type?: string, quality?: number): void;\n}\n\n/**\n * What a rasteriser may return: a Blob (any raster format), a canvas, or a\n * base64 `data:image/…` URL. Network URLs are refused (never fetched).\n */\nexport type RasterizeOutput = Blob | CanvasLike | string;\n\nexport interface RasterizeContext {\n /** Pixel density to render at. */\n readonly scale: number;\n /** CSS size of the element (or the requested size). */\n readonly width: number;\n readonly height: number;\n readonly backgroundColor: string | null;\n /** Fires on timeout or caller abort: stop work early if you can. */\n readonly signal: AbortSignal;\n}\n\n/**\n * Turns a DOM node into pixels. Bring your own engine, e.g.\n * `(node, { scale }) => domToBlob(node, { scale })` from `modern-screenshot`.\n */\nexport type Rasterizer = (node: Element, context: RasterizeContext) => PromiseLike<RasterizeOutput> | RasterizeOutput;\n\nexport interface CaptureElementOptions extends RenderOptions {\n /** Required for HTML elements. `<svg>` elements are rasterised natively when omitted. */\n readonly rasterize?: Rasterizer;\n}\n\nconst LABEL = 'Element capture';\nconst DATA_URL = /^data:(image\\/[a-z0-9.+-]+)((?:;[a-z0-9-]+=[a-z0-9.+-]+)*)(;base64)?,/i;\n\nfunction decodeBase64(payload: string, type: string): Blob {\n let binary: string;\n try {\n binary = atob(payload);\n } catch (cause) {\n throw copyFailure('blob-generation-failed', 'The rasteriser returned malformed base64.', cause);\n }\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);\n return new Blob([bytes], { type });\n}\n\nfunction canvasToBlob(canvas: CanvasLike): Promise<Blob> {\n return new Promise((resolve, reject) => {\n canvas.toBlob((blob) => {\n if (blob) resolve(blob);\n else reject(copyFailure('blob-generation-failed', 'canvas.toBlob() produced nothing.'));\n }, 'image/png');\n });\n}\n\nconst isCanvasLike = (value: unknown): value is CanvasLike =>\n typeof value === 'object' && value !== null && typeof (value as { toBlob?: unknown }).toBlob === 'function';\n\nasync function toPng(\n output: unknown,\n options: CaptureElementOptions,\n settings: RenderSettings,\n size: Size,\n signal: AbortSignal,\n): Promise<Blob> {\n const environment = (): CaptureEnvironment => resolveCaptureEnvironment(options.environment);\n\n if (isBlob(output)) return ensurePng(output, settings, environment, signal, LABEL);\n if (isCanvasLike(output)) return ensurePng(await canvasToBlob(output), settings, environment, signal, LABEL);\n if (typeof output !== 'string') {\n throw copyFailure('blob-generation-failed', 'The rasteriser must return a Blob, a canvas or a data:image URL.');\n }\n\n const match = DATA_URL.exec(output);\n if (match === null) {\n throw copyFailure('blob-generation-failed', 'The rasteriser returned a string that is not a data:image URL.');\n }\n const type = String(match[1]).toLowerCase();\n const base64 = match[3] !== undefined;\n const body = output.slice(match[0].length);\n\n if (type === SVG_MIME_TYPE) {\n // e.g. modern-screenshot's domToSvg: rasterise it natively at the element's size.\n const markup = base64 ? await decodeBase64(body, type).text() : decodeURIComponent(body);\n return svgToPngBlob(markup, {\n ...settings,\n width: size.width,\n height: size.height,\n signal,\n environment: environment(),\n });\n }\n if (!base64) throw copyFailure('blob-generation-failed', 'Raster data URLs must be base64-encoded.');\n return ensurePng(decodeBase64(body, type), settings, environment, signal, LABEL);\n}\n\n/**\n * Captures an element as a PNG Blob, ready for `copy({ kind: 'image', blob })`.\n * Output is verified to be a real PNG within `maxPixels`, or a classified\n * `CopyFailure` is thrown (`invalid-payload`, `unsupported`, `too-large`,\n * `timeout`, `aborted`, `blob-generation-failed`).\n */\nexport async function captureElement(node: Element | null | undefined, options: CaptureElementOptions = {}): Promise<Blob> {\n if (!node) throw copyFailure('invalid-payload', 'There is no element to capture (is the ref attached yet?).');\n\n const { rasterize } = options;\n if (!rasterize) {\n if (node.localName === 'svg') return svgToPngBlob(node, options);\n throw copyFailure(\n 'unsupported',\n 'Capturing HTML needs a `rasterize` function, e.g. `domToBlob` from modern-screenshot. Only <svg> works without one.',\n );\n }\n\n const settings = resolveRenderSettings(options);\n const rect = node.getBoundingClientRect();\n const intrinsic = rect.width > 0 && rect.height > 0 ? { width: rect.width, height: rect.height } : null;\n const size = resolveSize(intrinsic, options.width, options.height);\n toPixelSize(size, settings); // Refuse before rendering anything.\n\n try {\n return await withDeadline(\n async (signal) => {\n const output = await rasterize(node, {\n scale: settings.scale,\n width: size.width,\n height: size.height,\n backgroundColor: settings.background,\n signal,\n });\n return toPng(output, options, settings, size, signal);\n },\n { timeoutMs: settings.timeoutMs, signal: options.signal, label: LABEL },\n );\n } catch (cause) {\n throw classifyCaptureError(cause, LABEL);\n }\n}\n\n/**\n * A lazy `BlobSource` for `copy()`. Resolving the element at click time and\n * starting inside the gesture keeps Safari happy.\n *\n * @example copy({ kind: 'image', blob: captureSource(() => cardRef.current, { rasterize }) })\n */\nexport function captureSource(\n getNode: () => Element | null | undefined,\n options: CaptureElementOptions = {},\n): () => Promise<Blob> {\n return () => captureElement(getNode(), options);\n}\n\n/** Shorthand for `{ kind: 'image', blob: captureSource(getNode, options) }`. */\nexport function captureImage(\n getNode: () => Element | null | undefined,\n options: CaptureElementOptions = {},\n): ImagePayload {\n return { kind: 'image', blob: captureSource(getNode, options) };\n}\n"],"mappings":";;AA4CA,SAAgB,gBAAgB,MAAqB,SAAiB,OAA4B;CAChG,OAAO,UAAU,KAAA,IAAY;EAAE;EAAM;CAAQ,IAAI;EAAE;EAAM;EAAS;CAAM;AAC1E;;;;;AAmBA,MAAM,qBAAqB,OAAO,IAAI,8BAA8B;;AAGpE,IAAa,cAAb,cAAiC,MAAM;CAIrC,YAAY,WAAsB;EAChC,MAAM,UAAU,OAAO;EAHzB,KAAU,sBAAsB;EAI9B,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF;AAEA,SAAgB,cAAc,OAAsC;CAClE,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAuC,wBAAwB;AAEpE;;AAGA,SAAgB,YAAY,MAAqB,SAAiB,OAA8B;CAC9F,OAAO,IAAI,YAAY,gBAAgB,MAAM,SAAS,KAAK,CAAC;AAC9D;;;AC1DA,SAAS,UAAU,KAAoC;CACrD,OAAO,IAAI,SAAS,SAAS,WAAW;EAC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AM,QAAQ;CAE1B,IAAI;EACF,OAAO,MAAM,aACX,OAAO,WAAW;GAQhB,OAAO,MAAM,MAPQ,UAAU,MAAM;IACnC,OAAO,SAAS;IAChB,OAAO,KAAK;IACZ,QAAQ,KAAK;IACb,iBAAiB,SAAS;IAC1B;GACF,CAAC,GACoB,SAAS,UAAU,MAAM,MAAM;EACtD,GACA;GAAE,WAAW,SAAS;GAAW,QAAQ,QAAQ;GAAQ,OAAO;EAAM,CACxE;CACF,SAAS,OAAO;EACd,MAAM,qBAAqB,OAAO,KAAK;CACzC;AACF;;;;;;;AAQA,SAAgB,cACd,SACA,UAAiC,CAAC,GACb;CACrB,aAAa,eAAe,QAAQ,GAAG,OAAO;AAChD;;AAGA,SAAgB,aACd,SACA,UAAiC,CAAC,GACpB;CACd,OAAO;EAAE,MAAM;EAAS,MAAM,cAAc,SAAS,OAAO;CAAE;AAChE"}
1
+ {"version":3,"file":"capture.cjs","names":[],"sources":["../src/core/errors.ts","../src/capture/environment.ts","../src/capture/options.ts","../src/core/mime.ts","../src/core/payload.ts","../src/capture/deadline.ts","../src/capture/render.ts","../src/capture/svg.ts","../src/capture/element.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 } from '../core/errors';\n\n/** A decoded image, ready to be drawn. `source` is platform-specific (an `HTMLImageElement` in browsers). */\nexport interface DecodedImage {\n readonly source: unknown;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface PngTarget {\n /** Integer pixel size of the output. */\n readonly width: number;\n readonly height: number;\n /** CSS colour painted under the image, or `null` for transparency. */\n readonly background: string | null;\n}\n\n/**\n * Everything capture needs from the platform. The default uses the DOM;\n * inject your own for workers (OffscreenCanvas), native shells or tests.\n */\nexport interface CaptureEnvironment {\n readonly createObjectURL: (blob: Blob) => string;\n readonly revokeObjectURL: (url: string) => void;\n /** Serialises an `<svg>` element to markup. */\n readonly serializeSvg: (node: Element) => string;\n /** Decodes an image from a `blob:` or `data:` URL. */\n readonly loadImage: (url: string) => Promise<DecodedImage>;\n /** Draws the image scaled to `target` and encodes it as PNG. */\n readonly encodePng: (image: DecodedImage, target: PngTarget) => Promise<Blob>;\n}\n\nfunction loadImage(url: string): Promise<DecodedImage> {\n return new Promise((resolve, reject) => {\n const image = new Image();\n image.decoding = 'async';\n image.onload = () => {\n resolve({ source: image, width: image.naturalWidth, height: image.naturalHeight });\n };\n image.onerror = () => {\n reject(copyFailure('blob-generation-failed', 'The image could not be decoded.'));\n };\n image.src = url;\n });\n}\n\nfunction encodePng(image: DecodedImage, target: PngTarget): Promise<Blob> {\n return new Promise((resolve, reject) => {\n const canvas = document.createElement('canvas');\n canvas.width = target.width;\n canvas.height = target.height;\n const context = canvas.getContext('2d');\n if (!context) {\n reject(copyFailure('unsupported', 'Canvas 2D rendering is not available.'));\n return;\n }\n if (target.background !== null) {\n context.fillStyle = target.background;\n context.fillRect(0, 0, target.width, target.height);\n }\n context.drawImage(image.source as CanvasImageSource, 0, 0, target.width, target.height);\n // Throws SecurityError synchronously for tainted canvases; the executor turns that into a rejection.\n canvas.toBlob((blob) => {\n if (blob) resolve(blob);\n else reject(copyFailure('blob-generation-failed', 'canvas.toBlob() produced nothing (canvas too large?).'));\n }, 'image/png');\n });\n}\n\n/** The DOM-backed environment, or `null` outside a browser. */\nexport function getDefaultCaptureEnvironment(): CaptureEnvironment | null {\n if (\n typeof document === 'undefined' ||\n typeof Image !== 'function' ||\n typeof XMLSerializer !== 'function' ||\n typeof URL.createObjectURL !== 'function'\n ) {\n return null;\n }\n return {\n createObjectURL: (blob) => URL.createObjectURL(blob),\n revokeObjectURL: (url) => {\n URL.revokeObjectURL(url);\n },\n serializeSvg: (node) => new XMLSerializer().serializeToString(node),\n loadImage,\n encodePng,\n };\n}\n\nexport function resolveCaptureEnvironment(environment: CaptureEnvironment | undefined): CaptureEnvironment {\n const resolved = environment ?? getDefaultCaptureEnvironment();\n if (!resolved) {\n throw copyFailure('unsupported', 'Image capture needs a browser environment (document, Image, canvas).');\n }\n return resolved;\n}\n","import { copyFailure } from '../core/errors';\nimport type { CaptureEnvironment } from './environment';\n\nexport const DEFAULT_CAPTURE_SCALE = 2;\nexport const MAX_CAPTURE_SCALE = 10;\n/** 4096 × 4096: the canvas area limit of Safari/iOS, the strictest mainstream engine. */\nexport const DEFAULT_MAX_PIXELS = 16_777_216;\nexport const DEFAULT_CAPTURE_TIMEOUT_MS = 15_000;\n\nexport interface RenderOptions {\n /** Output width in CSS px (before `scale`). Omit to use the intrinsic size; set one side to keep the aspect ratio. */\n readonly width?: number;\n /** Output height in CSS px (before `scale`). */\n readonly height?: number;\n /** Pixel density multiplier, e.g. `window.devicePixelRatio`. Default 2 (crisp on HiDPI). Max 10. */\n readonly scale?: number;\n /** CSS colour under the image. Default `null` (transparent). */\n readonly background?: string | null;\n /** Refuse outputs larger than this many pixels (memory / DoS guard). Default 16 777 216. */\n readonly maxPixels?: number;\n /** Give up after this long. Default 15 000 ms. `Infinity` disables. */\n readonly timeoutMs?: number;\n /** Cancel the capture. */\n readonly signal?: AbortSignal;\n /** Platform hooks. Defaults to the DOM. */\n readonly environment?: CaptureEnvironment;\n}\n\nexport interface RenderSettings {\n readonly scale: number;\n readonly background: string | null;\n readonly maxPixels: number;\n readonly timeoutMs: number;\n}\n\nexport interface Size {\n readonly width: number;\n readonly height: number;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nconst isPositiveFinite = (value: number): boolean => Number.isFinite(value) && value > 0;\n\nexport function resolveRenderSettings(options: RenderOptions): RenderSettings {\n const scale = options.scale ?? DEFAULT_CAPTURE_SCALE;\n if (!isPositiveFinite(scale) || scale > MAX_CAPTURE_SCALE) {\n throw invalid(`\\`scale\\` must be > 0 and <= ${String(MAX_CAPTURE_SCALE)} (received ${String(scale)}).`);\n }\n const maxPixels = options.maxPixels ?? DEFAULT_MAX_PIXELS;\n if (!Number.isInteger(maxPixels) || maxPixels <= 0) {\n throw invalid(`\\`maxPixels\\` must be a positive integer (received ${String(maxPixels)}).`);\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_CAPTURE_TIMEOUT_MS;\n if (timeoutMs !== Infinity && !isPositiveFinite(timeoutMs)) {\n throw invalid(`\\`timeoutMs\\` must be > 0 or Infinity (received ${String(timeoutMs)}).`);\n }\n return { scale, background: options.background ?? null, maxPixels, timeoutMs };\n}\n\n/** Combines explicit `width`/`height` with an intrinsic size, keeping the aspect ratio when only one is set. */\nexport function resolveSize(intrinsic: Size | null, width: number | undefined, height: number | undefined): Size {\n for (const [name, value] of [\n ['width', width],\n ['height', height],\n ] as const) {\n if (value !== undefined && !isPositiveFinite(value)) {\n throw invalid(`\\`${name}\\` must be a positive number (received ${String(value)}).`);\n }\n }\n if (width !== undefined && height !== undefined) return { width, height };\n if (intrinsic === null) {\n throw invalid('The size to render is unknown: pass `width` and `height`, or give the source a size.');\n }\n if (width !== undefined) return { width, height: (width * intrinsic.height) / intrinsic.width };\n if (height !== undefined) return { width: (height * intrinsic.width) / intrinsic.height, height };\n return intrinsic;\n}\n\n/** Integer pixel size after scaling. Throws `too-large` past `maxPixels`. */\nexport function toPixelSize(size: Size, settings: Pick<RenderSettings, 'scale' | 'maxPixels'>): Size {\n const width = Math.max(1, Math.round(size.width * settings.scale));\n const height = Math.max(1, Math.round(size.height * settings.scale));\n assertPixelBudget(width, height, settings.maxPixels);\n return { width, height };\n}\n\nexport function assertPixelBudget(width: number, height: number, maxPixels: number): void {\n if (width * height > maxPixels) {\n throw copyFailure(\n 'too-large',\n `A ${String(width)}×${String(height)} image exceeds the ${String(maxPixels)}-pixel limit. Lower \\`scale\\` or raise \\`maxPixels\\`.`,\n );\n }\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 CopyError } from './errors';\nimport type { OperationContext } from './machine-shared';\n\n/** The only image MIME type with reliable cross-browser clipboard write support. */\nexport const IMAGE_MIME_TYPE = 'image/png';\n\n/**\n * An image as a Blob, a promise of one, or a function producing one.\n * Prefer the function form: it is invoked synchronously inside the user\n * gesture, which Safari requires for async image generation. The browser\n * adapter always passes an `OperationContext`: stop work once\n * `context.signal` aborts (reset, superseded, unmount). Optional in the type\n * so adapters that call sources themselves keep compiling.\n */\nexport type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);\n\nexport interface TextPayload {\n readonly kind: 'text';\n readonly value: string;\n}\n\nexport interface HtmlPayload {\n readonly kind: 'html';\n readonly html: string;\n /** Required plain-text fallback for targets that don't understand HTML. */\n readonly text: string;\n}\n\nexport interface ImagePayload {\n readonly kind: 'image';\n readonly blob: BlobSource;\n}\n\nexport interface JsonPayload {\n readonly kind: 'json';\n readonly value: unknown;\n /** `true` = 2-space indent, a number = that indent, falsy = compact. */\n readonly pretty?: boolean | number;\n}\n\nexport interface MultiPayloadItem {\n 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, type CopyFailure } from '../core/errors';\n\nexport interface DeadlineOptions {\n readonly timeoutMs: number;\n readonly signal?: AbortSignal | undefined;\n /** Used in messages: \"<label> timed out\". */\n readonly label: string;\n}\n\n/**\n * Runs `task` with a timeout and an optional caller `AbortSignal`. The task\n * receives a signal that fires on either, so cooperative work can stop early.\n * Rejects with classified `timeout` / `aborted` failures.\n */\nexport function withDeadline<T>(task: (signal: AbortSignal) => PromiseLike<T> | T, options: DeadlineOptions): Promise<T> {\n const { timeoutMs, label } = options;\n const external = options.signal;\n if (external?.aborted) {\n return Promise.reject(copyFailure('aborted', `${label} was aborted.`, external.reason));\n }\n\n const controller = new AbortController();\n return new Promise<T>((resolve, reject) => {\n const finish = (abort: boolean): void => {\n clearTimeout(timer);\n external?.removeEventListener('abort', onAbort);\n // Always signal downstream cooperative work to stop — whether we timed\n // out, were aborted, or resolved successfully. Without this, a task\n // that started a long operation keeps that operation alive after we've\n // already resolved, leaking resources until GC.\n /* c8 ignore next -- abort=false path is never used; kept for future API flexibility */\n if (abort) controller.abort();\n };\n const fail = (failure: CopyFailure): void => {\n finish(true);\n reject(failure);\n };\n const onAbort = (): void => {\n fail(copyFailure('aborted', `${label} was aborted.`, (external as AbortSignal).reason));\n };\n const timer =\n timeoutMs === Infinity\n ? undefined\n : setTimeout(() => {\n fail(copyFailure('timeout', `${label} timed out after ${String(timeoutMs)} ms.`));\n }, timeoutMs);\n external?.addEventListener('abort', onAbort, { once: true });\n\n new Promise<T>((run) => {\n run(task(controller.signal));\n }).then(\n (value) => {\n finish(true);\n resolve(value);\n },\n (cause: unknown) => {\n finish(true);\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified by the caller\n reject(cause);\n },\n );\n });\n}\n","import { copyFailure, isCopyFailure } from '../core/errors';\nimport { IMAGE_MIME_TYPE } from '../core/payload';\nimport { sniffImageType } from '../core/mime';\nimport { withDeadline } from './deadline';\nimport type { CaptureEnvironment } from './environment';\nimport { assertPixelBudget, type RenderSettings, type Size } from './options';\n\n/** Maps anything unexpected to `blob-generation-failed`, keeping already-classified failures. */\nexport function classifyCaptureError(cause: unknown, label: string): unknown {\n return isCopyFailure(cause) ? cause : copyFailure('blob-generation-failed', `${label} failed.`, cause);\n}\n\n/**\n * Decodes an image Blob and re-encodes it as PNG at `target` (or its natural\n * size), within the deadline. The object URL is always revoked.\n */\nexport async function drawBlobToPng(\n blob: Blob,\n target: Size | null,\n settings: RenderSettings,\n environment: CaptureEnvironment,\n signal: AbortSignal | undefined,\n label: string,\n): Promise<Blob> {\n const url = environment.createObjectURL(blob);\n try {\n return await withDeadline(\n async () => {\n const image = await environment.loadImage(url);\n const size = target ?? { width: image.width, height: image.height };\n assertPixelBudget(size.width, size.height, settings.maxPixels);\n return environment.encodePng(image, { ...size, background: settings.background });\n },\n { timeoutMs: settings.timeoutMs, signal, label },\n );\n } catch (cause) {\n throw classifyCaptureError(cause, label);\n } finally {\n environment.revokeObjectURL(url);\n }\n}\n\n/** Width and height from a PNG's IHDR chunk, read from the first 24 bytes only. */\nexport async function readPngSize(blob: Blob): Promise<Size | null> {\n const bytes = new Uint8Array(await blob.slice(0, 24).arrayBuffer());\n if (bytes.length < 24) return null;\n const view = new DataView(bytes.buffer);\n return { width: view.getUint32(16), height: view.getUint32(20) };\n}\n\n/**\n * Guarantees the clipboard-safe result: a real PNG (verified by its bytes),\n * typed `image/png`, within the pixel budget. Other raster formats are re-encoded.\n */\nexport async function ensurePng(\n blob: Blob,\n settings: RenderSettings,\n environment: () => CaptureEnvironment,\n signal: AbortSignal | undefined,\n label: string,\n): Promise<Blob> {\n const actual = await sniffImageType(blob);\n if (actual === null) {\n throw copyFailure('blob-generation-failed', `${label} did not produce an image.`);\n }\n if (actual !== IMAGE_MIME_TYPE) {\n return drawBlobToPng(blob, null, settings, environment(), signal, label);\n }\n const size = await readPngSize(blob);\n if (size === null) throw copyFailure('blob-generation-failed', `${label} produced a truncated PNG.`);\n assertPixelBudget(size.width, size.height, settings.maxPixels);\n return blob.type === IMAGE_MIME_TYPE ? blob : blob.slice(0, blob.size, IMAGE_MIME_TYPE);\n}\n","import { copyFailure } from '../core/errors';\nimport { SVG_MIME_TYPE } from '../core/mime';\nimport { resolveCaptureEnvironment } from './environment';\nimport { drawBlobToPng } from './render';\nimport { resolveRenderSettings, resolveSize, toPixelSize, type RenderOptions, type Size } from './options';\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n/** Refuse absurd markup before handing it to the image decoder. 10 M characters. */\nexport const DEFAULT_MAX_SVG_LENGTH = 10_000_000;\n\nexport interface SvgToPngOptions extends RenderOptions {\n /** Max markup length in characters. Default 10 000 000. */\n readonly maxLength?: number;\n}\n\n// Both patterns are linear-time: untrusted markup must not be able to trigger catastrophic backtracking.\nconst SVG_OPEN = /<svg\\b/i;\nconst LENGTH = /^(\\d+(?:\\.\\d+)?|\\.\\d+)(?:px)?$/i;\n\n/** The first `<svg …>` tag, found with two linear scans. */\nfunction findRootTag(markup: string): string | null {\n const start = markup.search(SVG_OPEN);\n if (start === -1) return null;\n const end = markup.indexOf('>', start);\n return end === -1 ? null : markup.slice(start, end + 1);\n}\n\n// Pre-compiled attribute patterns for the three attributes we ever read.\n// Compiling at module load time and with fixed literal names eliminates any\n// risk of ReDoS from runtime-constructed RegExps.\nconst ATTR_PATTERNS: Readonly<Record<string, RegExp>> = /* @__PURE__ */ Object.freeze({\n width: /\\swidth\\s*=\\s*([\"'])(.*?)\\1/i,\n height: /\\sheight\\s*=\\s*([\"'])(.*?)\\1/i,\n viewBox: /\\sviewBox\\s*=\\s*([\"'])(.*?)\\1/i,\n xmlns: /\\sxmlns\\s*=\\s*([\"'])(.*?)\\1/i,\n});\n\nfunction readAttribute(tag: string, name: keyof typeof ATTR_PATTERNS): string | null {\n const pattern = ATTR_PATTERNS[name];\n /* c8 ignore next -- TypeScript enforces name is a key of ATTR_PATTERNS; guard is for JS callers only */\n if (!pattern) return null;\n const match = pattern.exec(tag);\n return match === null ? null : String(match[2]);\n}\n\nfunction parseLength(value: string | null): number | null {\n if (value === null) return null;\n const match = LENGTH.exec(value.trim());\n const number = match ? Number(match[1]) : NaN;\n return number > 0 ? number : null;\n}\n\n/** Intrinsic size from the root tag: `width`/`height` in px, else the `viewBox`. */\nexport function readSvgSize(markup: string): Size | null {\n const tag = findRootTag(markup);\n if (tag === null) return null;\n const width = parseLength(readAttribute(tag, 'width'));\n const height = parseLength(readAttribute(tag, 'height'));\n if (width !== null && height !== null) return { width, height };\n\n const raw = readAttribute(tag, 'viewBox');\n const viewBox = raw != null ? raw.trim().split(/[\\s,]+/).map(Number) : [];\n const [, , boxWidth = NaN, boxHeight = NaN] = viewBox;\n if (viewBox.length !== 4 || !(boxWidth > 0) || !(boxHeight > 0)) return null;\n if (width !== null) return { width, height: (width * boxHeight) / boxWidth };\n if (height !== null) return { width: (height * boxWidth) / boxHeight, height };\n return { width: boxWidth, height: boxHeight };\n}\n\n/** Adds the SVG namespace when missing; `<img>` refuses to decode SVG without it. */\nexport function ensureSvgNamespace(markup: string): string {\n const tag = findRootTag(markup);\n if (tag === null) throw copyFailure('invalid-payload', 'The markup has no <svg> root element.');\n if (readAttribute(tag, 'xmlns') !== null) return markup;\n return markup.replace(SVG_OPEN, `<svg xmlns=\"${SVG_NAMESPACE}\"`);\n}\n\nconst isSvgElement = (value: Element): boolean => value.localName === 'svg';\n\n/**\n * Rasterises SVG (an `<svg>` element or markup) to a PNG Blob, ready for\n * `copy({ kind: 'image', blob })`.\n *\n * Security: the SVG is decoded as an *image*, where browsers disable scripts,\n * event handlers and external resource loading, and it is never inserted into\n * the document. Size is capped in characters and pixels.\n */\nexport async function svgToPngBlob(source: Element | string, options: SvgToPngOptions = {}): Promise<Blob> {\n const environment = resolveCaptureEnvironment(options.environment);\n const settings = resolveRenderSettings(options);\n const maxLength = options.maxLength ?? DEFAULT_MAX_SVG_LENGTH;\n\n let intrinsic: Size | null = null;\n let markup: string;\n if (typeof source === 'string') {\n markup = source;\n } else {\n if (!isSvgElement(source)) throw copyFailure('invalid-payload', `Expected an <svg> element, got <${source.localName}>.`);\n const rect = source.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) intrinsic = { width: rect.width, height: rect.height };\n markup = environment.serializeSvg(source);\n }\n\n if (markup.length > maxLength) {\n throw copyFailure('too-large', `The SVG markup exceeds ${String(maxLength)} characters.`);\n }\n const prepared = ensureSvgNamespace(markup);\n const size = resolveSize(intrinsic ?? readSvgSize(prepared), options.width, options.height);\n const target = toPixelSize(size, settings);\n\n const blob = new Blob([prepared], { type: SVG_MIME_TYPE });\n return drawBlobToPng(blob, target, settings, environment, options.signal, 'SVG rasterisation');\n}\n","import { copyFailure } from '../core/errors';\nimport type { OperationContext } from '../core/machine-shared';\nimport { SVG_MIME_TYPE } from '../core/mime';\nimport { isBlob, type ImagePayload } from '../core/payload';\nimport { withDeadline } from './deadline';\nimport { resolveCaptureEnvironment, type CaptureEnvironment } from './environment';\nimport {\n resolveRenderSettings,\n resolveSize,\n toPixelSize,\n type RenderOptions,\n type RenderSettings,\n type Size,\n} from './options';\nimport { classifyCaptureError, ensurePng } from './render';\nimport { svgToPngBlob } from './svg';\n\n/** Anything with `canvas.toBlob()`: `HTMLCanvasElement`, or a compatible object. */\nexport interface CanvasLike {\n toBlob(callback: (blob: Blob | null) => void, type?: string, quality?: number): void;\n}\n\n/**\n * What a rasteriser may return: a Blob (any raster format), a canvas, or a\n * base64 `data:image/…` URL. Network URLs are refused (never fetched).\n */\nexport type RasterizeOutput = Blob | CanvasLike | string;\n\nexport interface RasterizeContext {\n /** Pixel density to render at. */\n readonly scale: number;\n /** CSS size of the element (or the requested size). */\n readonly width: number;\n readonly height: number;\n readonly backgroundColor: string | null;\n /** Fires on timeout or caller abort: stop work early if you can. */\n readonly signal: AbortSignal;\n}\n\n/**\n * Turns a DOM node into pixels. Bring your own engine, e.g.\n * `(node, { scale }) => domToBlob(node, { scale })` from `modern-screenshot`.\n */\nexport type Rasterizer = (node: Element, context: RasterizeContext) => PromiseLike<RasterizeOutput> | RasterizeOutput;\n\nexport interface CaptureElementOptions extends RenderOptions {\n /** Required for HTML elements. `<svg>` elements are rasterised natively when omitted. */\n readonly rasterize?: Rasterizer;\n}\n\nconst LABEL = 'Element capture';\nconst DATA_URL = /^data:(image\\/[a-z0-9.+-]+)((?:;[a-z0-9-]+=[a-z0-9.+-]+)*)(;base64)?,/i;\n\nfunction decodeBase64(payload: string, type: string): Blob {\n let binary: string;\n try {\n binary = atob(payload);\n } catch (cause) {\n throw copyFailure('blob-generation-failed', 'The rasteriser returned malformed base64.', cause);\n }\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);\n return new Blob([bytes], { type });\n}\n\nfunction canvasToBlob(canvas: CanvasLike): Promise<Blob> {\n return new Promise((resolve, reject) => {\n canvas.toBlob((blob) => {\n if (blob) resolve(blob);\n else reject(copyFailure('blob-generation-failed', 'canvas.toBlob() produced nothing.'));\n }, 'image/png');\n });\n}\n\nconst isCanvasLike = (value: unknown): value is CanvasLike =>\n typeof value === 'object' && value !== null && typeof (value as { toBlob?: unknown }).toBlob === 'function';\n\nasync function toPng(\n output: unknown,\n options: CaptureElementOptions,\n settings: RenderSettings,\n size: Size,\n signal: AbortSignal,\n): Promise<Blob> {\n const environment = (): CaptureEnvironment => resolveCaptureEnvironment(options.environment);\n\n if (isBlob(output)) return ensurePng(output, settings, environment, signal, LABEL);\n if (isCanvasLike(output)) return ensurePng(await canvasToBlob(output), settings, environment, signal, LABEL);\n if (typeof output !== 'string') {\n throw copyFailure('blob-generation-failed', 'The rasteriser must return a Blob, a canvas or a data:image URL.');\n }\n\n const match = DATA_URL.exec(output);\n if (match === null) {\n throw copyFailure('blob-generation-failed', 'The rasteriser returned a string that is not a data:image URL.');\n }\n const type = String(match[1]).toLowerCase();\n const base64 = match[3] !== undefined;\n const body = output.slice(match[0].length);\n\n if (type === SVG_MIME_TYPE) {\n // e.g. modern-screenshot's domToSvg: rasterise it natively at the element's size.\n const markup = base64 ? await decodeBase64(body, type).text() : decodeURIComponent(body);\n return svgToPngBlob(markup, {\n ...settings,\n width: size.width,\n height: size.height,\n signal,\n environment: environment(),\n });\n }\n if (!base64) throw copyFailure('blob-generation-failed', 'Raster data URLs must be base64-encoded.');\n return ensurePng(decodeBase64(body, type), settings, environment, signal, LABEL);\n}\n\n/**\n * Captures an element as a PNG Blob, ready for `copy({ kind: 'image', blob })`.\n * Output is verified to be a real PNG within `maxPixels`, or a classified\n * `CopyFailure` is thrown (`invalid-payload`, `unsupported`, `too-large`,\n * `timeout`, `aborted`, `blob-generation-failed`).\n */\nexport async function captureElement(node: Element | null | undefined, options: CaptureElementOptions = {}): Promise<Blob> {\n if (!node) throw copyFailure('invalid-payload', 'There is no element to capture (is the ref attached yet?).');\n\n const { rasterize } = options;\n if (!rasterize) {\n if (node.localName === 'svg') return svgToPngBlob(node, options);\n throw copyFailure(\n 'unsupported',\n 'Capturing HTML needs a `rasterize` function, e.g. `domToBlob` from modern-screenshot. Only <svg> works without one.',\n );\n }\n\n const settings = resolveRenderSettings(options);\n const rect = node.getBoundingClientRect();\n const intrinsic = rect.width > 0 && rect.height > 0 ? { width: rect.width, height: rect.height } : null;\n const size = resolveSize(intrinsic, options.width, options.height);\n toPixelSize(size, settings); // Refuse before rendering anything.\n\n try {\n return await withDeadline(\n async (signal) => {\n const output = await rasterize(node, {\n scale: settings.scale,\n width: size.width,\n height: size.height,\n backgroundColor: settings.background,\n signal,\n });\n return toPng(output, options, settings, size, signal);\n },\n { timeoutMs: settings.timeoutMs, signal: options.signal, label: LABEL },\n );\n } catch (cause) {\n throw classifyCaptureError(cause, LABEL);\n }\n}\n\n/**\n * A lazy `BlobSource` for `copy()`. Resolving the element at click time and\n * starting inside the gesture keeps Safari happy. Rasterising stops when the\n * copy is reset or its component unmounts, or when `options.signal` aborts.\n *\n * @example copy({ kind: 'image', blob: captureSource(() => cardRef.current, { rasterize }) })\n */\nexport function captureSource(\n getNode: () => Element | null | undefined,\n options: CaptureElementOptions = {},\n): (context?: OperationContext) => Promise<Blob> {\n return (context) => {\n const a = options.signal;\n const b = context?.signal;\n if (!a || !b) {\n const signal = a ?? b;\n return captureElement(getNode(), signal ? { ...options, signal } : options);\n }\n const any = (AbortSignal as { any?: (signals: AbortSignal[]) => AbortSignal }).any;\n if (typeof any === 'function') return captureElement(getNode(), { ...options, signal: any([a, b]) });\n\n // Older browsers: forward both, and detach once settled so a long-lived\n // caller signal doesn't accumulate a listener per copy.\n const controller = new AbortController();\n const onAbortA = (): void => {\n controller.abort(a.reason);\n };\n const onAbortB = (): void => {\n controller.abort(b.reason);\n };\n if (a.aborted) onAbortA();\n else if (b.aborted) onAbortB();\n a.addEventListener('abort', onAbortA);\n b.addEventListener('abort', onAbortB);\n return captureElement(getNode(), { ...options, signal: controller.signal }).finally(() => {\n a.removeEventListener('abort', onAbortA);\n b.removeEventListener('abort', onAbortB);\n });\n };\n}\n\n/** Shorthand for `{ kind: 'image', blob: captureSource(getNode, options) }`. */\nexport function captureImage(\n getNode: () => Element | null | undefined,\n options: CaptureElementOptions = {},\n): ImagePayload {\n return { kind: 'image', blob: captureSource(getNode, options) };\n}\n"],"mappings":";;AA4CA,SAAgB,gBAAgB,MAAqB,SAAiB,OAA4B;CAChG,OAAO,UAAU,KAAA,IAAY;EAAE;EAAM;CAAQ,IAAI;EAAE;EAAM;EAAS;CAAM;AAC1E;;;;;AAmBA,MAAM,qBAAqB,OAAO,IAAI,8BAA8B;;AAGpE,IAAa,cAAb,cAAiC,MAAM;CAIrC,YAAY,WAAsB;EAChC,MAAM,UAAU,OAAO;EAHzB,KAAU,sBAAsB;EAI9B,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF;AAEA,SAAgB,cAAc,OAAsC;CAClE,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAuC,wBAAwB;AAEpE;;AAGA,SAAgB,YAAY,MAAqB,SAAiB,OAA8B;CAC9F,OAAO,IAAI,YAAY,gBAAgB,MAAM,SAAS,KAAK,CAAC;AAC9D;;;AC1DA,SAAS,UAAU,KAAoC;CACrD,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,QAAQ,IAAI,MAAM;EACxB,MAAM,WAAW;EACjB,MAAM,eAAe;GACnB,QAAQ;IAAE,QAAQ;IAAO,OAAO,MAAM;IAAc,QAAQ,MAAM;GAAc,CAAC;EACnF;EACA,MAAM,gBAAgB;GACpB,OAAO,YAAY,0BAA0B,iCAAiC,CAAC;EACjF;EACA,MAAM,MAAM;CACd,CAAC;AACH;AAEA,SAAS,UAAU,OAAqB,QAAkC;CACxE,OAAO,IAAI,S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,SAAS,OAAO;EACd,MAAM,qBAAqB,OAAO,KAAK;CACzC;AACF;;;;;;;;AASA,SAAgB,cACd,SACA,UAAiC,CAAC,GACa;CAC/C,QAAQ,YAAY;EAClB,MAAM,IAAI,QAAQ;EAClB,MAAM,IAAI,SAAS;EACnB,IAAI,CAAC,KAAK,CAAC,GAAG;GACZ,MAAM,SAAS,KAAK;GACpB,OAAO,eAAe,QAAQ,GAAG,SAAS;IAAE,GAAG;IAAS;GAAO,IAAI,OAAO;EAC5E;EACA,MAAM,MAAO,YAAkE;EAC/E,IAAI,OAAO,QAAQ,YAAY,OAAO,eAAe,QAAQ,GAAG;GAAE,GAAG;GAAS,QAAQ,IAAI,CAAC,GAAG,CAAC,CAAC;EAAE,CAAC;EAInG,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,iBAAuB;GAC3B,WAAW,MAAM,EAAE,MAAM;EAC3B;EACA,MAAM,iBAAuB;GAC3B,WAAW,MAAM,EAAE,MAAM;EAC3B;EACA,IAAI,EAAE,SAAS,SAAS;OACnB,IAAI,EAAE,SAAS,SAAS;EAC7B,EAAE,iBAAiB,SAAS,QAAQ;EACpC,EAAE,iBAAiB,SAAS,QAAQ;EACpC,OAAO,eAAe,QAAQ,GAAG;GAAE,GAAG;GAAS,QAAQ,WAAW;EAAO,CAAC,CAAC,CAAC,cAAc;GACxF,EAAE,oBAAoB,SAAS,QAAQ;GACvC,EAAE,oBAAoB,SAAS,QAAQ;EACzC,CAAC;CACH;AACF;;AAGA,SAAgB,aACd,SACA,UAAiC,CAAC,GACpB;CACd,OAAO;EAAE,MAAM;EAAS,MAAM,cAAc,SAAS,OAAO;CAAE;AAChE"}
@@ -80,13 +80,26 @@ export declare function ensureSvgNamespace(markup: string): string;
80
80
  */
81
81
  export declare function svgToPngBlob(source: Element | string, options?: SvgToPngOptions): Promise<Blob>;
82
82
  //#endregion
83
+ //#region src/core/machine-shared.d.ts
84
+ /**
85
+ * Passed to adapters and lazy sources as their last argument. `signal` aborts
86
+ * when the operation is superseded, `reset()`, or its host unmounts, so
87
+ * expensive work (rasterising, decoding) can stop early.
88
+ */
89
+ interface OperationContext {
90
+ readonly signal: AbortSignal;
91
+ }
92
+ //#endregion
83
93
  //#region src/core/payload.d.ts
84
94
  /**
85
95
  * An image as a Blob, a promise of one, or a function producing one.
86
96
  * Prefer the function form: it is invoked synchronously inside the user
87
- * gesture, which Safari requires for async image generation.
97
+ * gesture, which Safari requires for async image generation. The browser
98
+ * adapter always passes an `OperationContext`: stop work once
99
+ * `context.signal` aborts (reset, superseded, unmount). Optional in the type
100
+ * so adapters that call sources themselves keep compiling.
88
101
  */
89
- type BlobSource = Blob | PromiseLike<Blob> | (() => Blob | PromiseLike<Blob>);
102
+ type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);
90
103
  interface ImagePayload {
91
104
  readonly kind: 'image';
92
105
  readonly blob: BlobSource;
@@ -130,11 +143,12 @@ interface CaptureElementOptions extends RenderOptions {
130
143
  export declare function captureElement(node: Element | null | undefined, options?: CaptureElementOptions): Promise<Blob>;
131
144
  /**
132
145
  * A lazy `BlobSource` for `copy()`. Resolving the element at click time and
133
- * starting inside the gesture keeps Safari happy.
146
+ * starting inside the gesture keeps Safari happy. Rasterising stops when the
147
+ * copy is reset or its component unmounts, or when `options.signal` aborts.
134
148
  *
135
149
  * @example copy({ kind: 'image', blob: captureSource(() => cardRef.current, { rasterize }) })
136
150
  */
137
- export declare function captureSource(getNode: () => Element | null | undefined, options?: CaptureElementOptions): () => Promise<Blob>;
151
+ export declare function captureSource(getNode: () => Element | null | undefined, options?: CaptureElementOptions): (context?: OperationContext) => Promise<Blob>;
138
152
  /** Shorthand for `{ kind: 'image', blob: captureSource(getNode, options) }`. */
139
153
  export declare function captureImage(getNode: () => Element | null | undefined, options?: CaptureElementOptions): ImagePayload;
140
154
  //#endregion
package/dist/capture.d.ts CHANGED
@@ -80,13 +80,26 @@ export declare function ensureSvgNamespace(markup: string): string;
80
80
  */
81
81
  export declare function svgToPngBlob(source: Element | string, options?: SvgToPngOptions): Promise<Blob>;
82
82
  //#endregion
83
+ //#region src/core/machine-shared.d.ts
84
+ /**
85
+ * Passed to adapters and lazy sources as their last argument. `signal` aborts
86
+ * when the operation is superseded, `reset()`, or its host unmounts, so
87
+ * expensive work (rasterising, decoding) can stop early.
88
+ */
89
+ interface OperationContext {
90
+ readonly signal: AbortSignal;
91
+ }
92
+ //#endregion
83
93
  //#region src/core/payload.d.ts
84
94
  /**
85
95
  * An image as a Blob, a promise of one, or a function producing one.
86
96
  * Prefer the function form: it is invoked synchronously inside the user
87
- * gesture, which Safari requires for async image generation.
97
+ * gesture, which Safari requires for async image generation. The browser
98
+ * adapter always passes an `OperationContext`: stop work once
99
+ * `context.signal` aborts (reset, superseded, unmount). Optional in the type
100
+ * so adapters that call sources themselves keep compiling.
88
101
  */
89
- type BlobSource = Blob | PromiseLike<Blob> | (() => Blob | PromiseLike<Blob>);
102
+ type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);
90
103
  interface ImagePayload {
91
104
  readonly kind: 'image';
92
105
  readonly blob: BlobSource;
@@ -130,11 +143,12 @@ interface CaptureElementOptions extends RenderOptions {
130
143
  export declare function captureElement(node: Element | null | undefined, options?: CaptureElementOptions): Promise<Blob>;
131
144
  /**
132
145
  * A lazy `BlobSource` for `copy()`. Resolving the element at click time and
133
- * starting inside the gesture keeps Safari happy.
146
+ * starting inside the gesture keeps Safari happy. Rasterising stops when the
147
+ * copy is reset or its component unmounts, or when `options.signal` aborts.
134
148
  *
135
149
  * @example copy({ kind: 'image', blob: captureSource(() => cardRef.current, { rasterize }) })
136
150
  */
137
- export declare function captureSource(getNode: () => Element | null | undefined, options?: CaptureElementOptions): () => Promise<Blob>;
151
+ export declare function captureSource(getNode: () => Element | null | undefined, options?: CaptureElementOptions): (context?: OperationContext) => Promise<Blob>;
138
152
  /** Shorthand for `{ kind: 'image', blob: captureSource(getNode, options) }`. */
139
153
  export declare function captureImage(getNode: () => Element | null | undefined, options?: CaptureElementOptions): ImagePayload;
140
154
  //#endregion
package/dist/capture.js CHANGED
@@ -476,12 +476,46 @@ async function captureElement(node, options = {}) {
476
476
  }
477
477
  /**
478
478
  * A lazy `BlobSource` for `copy()`. Resolving the element at click time and
479
- * starting inside the gesture keeps Safari happy.
479
+ * starting inside the gesture keeps Safari happy. Rasterising stops when the
480
+ * copy is reset or its component unmounts, or when `options.signal` aborts.
480
481
  *
481
482
  * @example copy({ kind: 'image', blob: captureSource(() => cardRef.current, { rasterize }) })
482
483
  */
483
484
  function captureSource(getNode, options = {}) {
484
- return () => captureElement(getNode(), options);
485
+ return (context) => {
486
+ const a = options.signal;
487
+ const b = context?.signal;
488
+ if (!a || !b) {
489
+ const signal = a ?? b;
490
+ return captureElement(getNode(), signal ? {
491
+ ...options,
492
+ signal
493
+ } : options);
494
+ }
495
+ const any = AbortSignal.any;
496
+ if (typeof any === "function") return captureElement(getNode(), {
497
+ ...options,
498
+ signal: any([a, b])
499
+ });
500
+ const controller = new AbortController();
501
+ const onAbortA = () => {
502
+ controller.abort(a.reason);
503
+ };
504
+ const onAbortB = () => {
505
+ controller.abort(b.reason);
506
+ };
507
+ if (a.aborted) onAbortA();
508
+ else if (b.aborted) onAbortB();
509
+ a.addEventListener("abort", onAbortA);
510
+ b.addEventListener("abort", onAbortB);
511
+ return captureElement(getNode(), {
512
+ ...options,
513
+ signal: controller.signal
514
+ }).finally(() => {
515
+ a.removeEventListener("abort", onAbortA);
516
+ b.removeEventListener("abort", onAbortB);
517
+ });
518
+ };
485
519
  }
486
520
  /** Shorthand for `{ kind: 'image', blob: captureSource(getNode, options) }`. */
487
521
  function captureImage(getNode, options = {}) {