react-smart-copy 1.26.0 → 1.26.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/capture.cjs +4 -4
- package/dist/capture.cjs.map +1 -1
- package/dist/capture.js +4 -4
- package/dist/capture.js.map +1 -1
- package/dist/chunks/{clipboard-adapter-UIFc_Qso.cjs → clipboard-adapter-Bpuf5GmB.cjs} +3 -3
- package/dist/chunks/{clipboard-adapter-UIFc_Qso.cjs.map → clipboard-adapter-Bpuf5GmB.cjs.map} +1 -1
- package/dist/chunks/{clipboard-adapter-CmKDTFdO.js → clipboard-adapter-DyCmyZV9.js} +3 -3
- package/dist/chunks/{clipboard-adapter-CmKDTFdO.js.map → clipboard-adapter-DyCmyZV9.js.map} +1 -1
- package/dist/chunks/{contrast-C9d8QuaF.cjs → contrast-BatHkv8j.cjs} +2 -2
- package/dist/chunks/{contrast-C9d8QuaF.cjs.map → contrast-BatHkv8j.cjs.map} +1 -1
- package/dist/chunks/{contrast-DUaZq5SA.js → contrast-DnCunIr1.js} +2 -2
- package/dist/chunks/{contrast-DUaZq5SA.js.map → contrast-DnCunIr1.js.map} +1 -1
- package/dist/chunks/{core-D3GCO3yT.js → core-88XdCKaH.js} +5 -5
- package/dist/chunks/{core-D3GCO3yT.js.map → core-88XdCKaH.js.map} +1 -1
- package/dist/chunks/{core-t59Z4gdy.cjs → core-DF6jiigD.cjs} +5 -5
- package/dist/chunks/{core-t59Z4gdy.cjs.map → core-DF6jiigD.cjs.map} +1 -1
- package/dist/chunks/{deadline-j2hD7JKz.cjs → deadline-Cz6l-PDR.cjs} +14 -2
- package/dist/chunks/deadline-Cz6l-PDR.cjs.map +1 -0
- package/dist/chunks/{deadline-CbwnZ3Oq.js → deadline-DTAkra5B.js} +9 -3
- package/dist/chunks/deadline-DTAkra5B.js.map +1 -0
- package/dist/chunks/{errors-DFmEAC4E.cjs → errors-CF2EQNbc.cjs} +14 -2
- package/dist/chunks/errors-CF2EQNbc.cjs.map +1 -0
- package/dist/chunks/{errors-CT-FfUtU.js → errors-CGcMvbhJ.js} +9 -3
- package/dist/chunks/errors-CGcMvbhJ.js.map +1 -0
- package/dist/chunks/{field-B6SRWRbI.cjs → field-C8A5Yxln.cjs} +3 -3
- package/dist/chunks/{field-B6SRWRbI.cjs.map → field-C8A5Yxln.cjs.map} +1 -1
- package/dist/chunks/{field-DsRKkbav.js → field-CDCN9x0L.js} +3 -3
- package/dist/chunks/{field-DsRKkbav.js.map → field-CDCN9x0L.js.map} +1 -1
- package/dist/chunks/{limits-BP9R5wnr.js → limits-DvJZJn0V.js} +2 -2
- package/dist/chunks/{limits-BP9R5wnr.js.map → limits-DvJZJn0V.js.map} +1 -1
- package/dist/chunks/{limits-9wi1f6xT.cjs → limits-Vy-Xv26D.cjs} +2 -2
- package/dist/chunks/{limits-9wi1f6xT.cjs.map → limits-Vy-Xv26D.cjs.map} +1 -1
- package/dist/chunks/{paste-reader-BWQaYNaV.cjs → paste-reader-BL51Jt1y.cjs} +2 -2
- package/dist/chunks/{paste-reader-BWQaYNaV.cjs.map → paste-reader-BL51Jt1y.cjs.map} +1 -1
- package/dist/chunks/{paste-reader-D6uOTDBM.js → paste-reader-BpXOH_Px.js} +2 -2
- package/dist/chunks/{paste-reader-D6uOTDBM.js.map → paste-reader-BpXOH_Px.js.map} +1 -1
- package/dist/chunks/{payload-BrQWGwyx.js → payload-5uJedhwz.js} +2 -2
- package/dist/chunks/{payload-BrQWGwyx.js.map → payload-5uJedhwz.js.map} +1 -1
- package/dist/chunks/{payload-BWQ6sPtS.js → payload-DZnXoBmF.js} +3 -3
- package/dist/chunks/{payload-BWQ6sPtS.js.map → payload-DZnXoBmF.js.map} +1 -1
- package/dist/chunks/{payload-sBxkG7jH.cjs → payload-DjSSLonm.cjs} +2 -2
- package/dist/chunks/{payload-sBxkG7jH.cjs.map → payload-DjSSLonm.cjs.map} +1 -1
- package/dist/chunks/{payload-tTK6REua.cjs → payload-DzHhs6Ey.cjs} +3 -3
- package/dist/chunks/{payload-tTK6REua.cjs.map → payload-DzHhs6Ey.cjs.map} +1 -1
- package/dist/chunks/{share-nx7M4Z0t.cjs → share-Bk6MPmJg.cjs} +6 -6
- package/dist/chunks/{share-nx7M4Z0t.cjs.map → share-Bk6MPmJg.cjs.map} +1 -1
- package/dist/chunks/{share-CU91L4EK.js → share-tdlNQeje.js} +6 -6
- package/dist/chunks/{share-CU91L4EK.js.map → share-tdlNQeje.js.map} +1 -1
- package/dist/chunks/{url-BrhVUwn7.cjs → url-CL4YTCvM.cjs} +2 -2
- package/dist/chunks/{url-BrhVUwn7.cjs.map → url-CL4YTCvM.cjs.map} +1 -1
- package/dist/chunks/{url-COID0BLY.js → url-zB_krkuF.js} +2 -2
- package/dist/chunks/{url-COID0BLY.js.map → url-zB_krkuF.js.map} +1 -1
- package/dist/code.cjs +2 -2
- package/dist/code.js +2 -2
- package/dist/color.cjs +2 -2
- package/dist/color.js +2 -2
- package/dist/core.cjs +5 -5
- package/dist/core.js +5 -5
- package/dist/email.cjs +2 -2
- package/dist/email.js +2 -2
- package/dist/files.cjs +1 -1
- package/dist/files.js +1 -1
- package/dist/image.cjs +3 -3
- package/dist/image.cjs.map +1 -1
- package/dist/image.js +3 -3
- package/dist/image.js.map +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.js +7 -7
- package/dist/link.cjs +3 -3
- package/dist/link.js +3 -3
- package/dist/markdown.cjs +1 -1
- package/dist/markdown.js +1 -1
- package/dist/number.cjs +2 -2
- package/dist/number.js +2 -2
- package/dist/otp.cjs +1 -1
- package/dist/otp.js +1 -1
- package/dist/rich.cjs +3 -3
- package/dist/rich.js +3 -3
- package/dist/secrets.cjs +1 -1
- package/dist/secrets.js +1 -1
- package/dist/share.cjs +1 -1
- package/dist/share.js +1 -1
- package/dist/structured.cjs +2 -2
- package/dist/structured.js +2 -2
- package/dist/table.cjs +1 -1
- package/dist/table.js +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/deadline-CbwnZ3Oq.js.map +0 -1
- package/dist/chunks/deadline-j2hD7JKz.cjs.map +0 -1
- package/dist/chunks/errors-CT-FfUtU.js.map +0 -1
- package/dist/chunks/errors-DFmEAC4E.cjs.map +0 -1
package/dist/capture.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
-
const require_errors = require("./chunks/errors-
|
|
4
|
-
const require_payload = require("./chunks/payload-
|
|
3
|
+
const require_errors = require("./chunks/errors-CF2EQNbc.cjs");
|
|
4
|
+
const require_payload = require("./chunks/payload-DjSSLonm.cjs");
|
|
5
5
|
const require_mime = require("./chunks/mime--LB7kdqG.cjs");
|
|
6
|
-
const require_deadline = require("./chunks/deadline-
|
|
6
|
+
const require_deadline = require("./chunks/deadline-Cz6l-PDR.cjs");
|
|
7
7
|
//#region src/capture/environment.ts
|
|
8
8
|
function loadImage(url) {
|
|
9
9
|
return new Promise((resolve, reject) => {
|
|
@@ -119,7 +119,7 @@ function assertPixelBudget(width, height, maxPixels) {
|
|
|
119
119
|
//#region src/capture/render.ts
|
|
120
120
|
/** Maps anything unexpected to `blob-generation-failed`, keeping already-classified failures. */
|
|
121
121
|
function classifyCaptureError(cause, label) {
|
|
122
|
-
return require_errors.isCopyFailure(cause) ? cause :
|
|
122
|
+
return require_errors.isCopyFailure(cause) ? cause : require_deadline.blobFailure(label, cause);
|
|
123
123
|
}
|
|
124
124
|
/**
|
|
125
125
|
* Decodes an image Blob and re-encodes it as PNG at `target` (or its natural
|
package/dist/capture.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"capture.cjs","names":["copyFailure","copyFailure","isCopyFailure","copyFailure","withDeadline","sniffImageType","IMAGE_MIME_TYPE","copyFailure","SVG_MIME_TYPE","copyFailure","isBlob","withDeadline"],"sources":["../src/capture/environment.ts","../src/capture/options.ts","../src/capture/render.ts","../src/capture/svg.ts","../src/capture/element.ts"],"sourcesContent":["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","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":";;;;;;;AAgCA,SAAS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,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"}
|
|
1
|
+
{"version":3,"file":"capture.cjs","names":["copyFailure","copyFailure","isCopyFailure","blobFailure","withDeadline","sniffImageType","copyFailure","IMAGE_MIME_TYPE","copyFailure","SVG_MIME_TYPE","copyFailure","isBlob","withDeadline"],"sources":["../src/capture/environment.ts","../src/capture/options.ts","../src/capture/render.ts","../src/capture/svg.ts","../src/capture/element.ts"],"sourcesContent":["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","import { blobFailure } from '../core/blob-failure';\nimport { 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 : blobFailure(label, 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":";;;;;;;AAgCA,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,OAAOA,eAAAA,YAAY,0BAA0B,iCAAiC,CAAC;EACjF;EACA,MAAM,MAAM;CACd,CAAC;AACH;AAEA,SAAS,UAAU,OAAqB,QAAkC;CACxE,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,SAAS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AQ,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"}
|
package/dist/capture.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
|
|
2
|
-
import { n as copyFailure, o as isCopyFailure } from "./chunks/errors-
|
|
3
|
-
import { n as isBlob, t as IMAGE_MIME_TYPE } from "./chunks/payload-
|
|
2
|
+
import { n as copyFailure, o as isCopyFailure } from "./chunks/errors-CGcMvbhJ.js";
|
|
3
|
+
import { n as isBlob, t as IMAGE_MIME_TYPE } from "./chunks/payload-5uJedhwz.js";
|
|
4
4
|
import { l as sniffImageType, t as SVG_MIME_TYPE } from "./chunks/mime-aa-HA2dm.js";
|
|
5
|
-
import { t as withDeadline } from "./chunks/deadline-
|
|
5
|
+
import { n as blobFailure, t as withDeadline } from "./chunks/deadline-DTAkra5B.js";
|
|
6
6
|
//#region src/capture/environment.ts
|
|
7
7
|
function loadImage(url) {
|
|
8
8
|
return new Promise((resolve, reject) => {
|
|
@@ -118,7 +118,7 @@ function assertPixelBudget(width, height, maxPixels) {
|
|
|
118
118
|
//#region src/capture/render.ts
|
|
119
119
|
/** Maps anything unexpected to `blob-generation-failed`, keeping already-classified failures. */
|
|
120
120
|
function classifyCaptureError(cause, label) {
|
|
121
|
-
return isCopyFailure(cause) ? cause :
|
|
121
|
+
return isCopyFailure(cause) ? cause : blobFailure(label, cause);
|
|
122
122
|
}
|
|
123
123
|
/**
|
|
124
124
|
* Decodes an image Blob and re-encodes it as PNG at `target` (or its natural
|
package/dist/capture.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"capture.js","names":[],"sources":["../src/capture/environment.ts","../src/capture/options.ts","../src/capture/render.ts","../src/capture/svg.ts","../src/capture/element.ts"],"sourcesContent":["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","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":";;;;;;AAgCA,SAAS,UAAU,KA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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"}
|
|
1
|
+
{"version":3,"file":"capture.js","names":[],"sources":["../src/capture/environment.ts","../src/capture/options.ts","../src/capture/render.ts","../src/capture/svg.ts","../src/capture/element.ts"],"sourcesContent":["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","import { blobFailure } from '../core/blob-failure';\nimport { 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 : blobFailure(label, 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":";;;;;;AAgCA,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,SAAS,SAAS,WAAW;EACtC,MAAM,SAAS,SAAS,cAAc,QAAQ;EAC9C,OAAO,QAAQ,OAAO;EACtB,OAAO,SAAS,OAAO;EACvB,MAAM,UAAU,OAAO,WAAW,IAAI;EACtC,IAAI,CAAC,SAAS;GACZ,OAAO,YAAY,eAAe,uCAAuC,CAAC;GAC1E;EACF;EACA,IAAI,OAAO,eAAe,MAAM;GAC9B,QAAQ,YAAY,OAAO;GAC3B,QAAQ,SAAS,GAAG,GAAG,OAAO,OAAO,OAAO,MAAM;EACpD;EACA,QAAQ,UAAU,MAAM,QAA6B,GAAG,GAAG,OAAO,OAAO,OAA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AM,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"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
const require_errors = require("./errors-
|
|
3
|
-
const require_payload = require("./payload-
|
|
2
|
+
const require_errors = require("./errors-CF2EQNbc.cjs");
|
|
3
|
+
const require_payload = require("./payload-DjSSLonm.cjs");
|
|
4
4
|
//#region src/core/clipboard-adapter.ts
|
|
5
5
|
const fail = (type, message, cause) => new require_errors.CopyFailure(require_errors.createCopyError(type, message, cause));
|
|
6
6
|
const noop = () => void 0;
|
|
@@ -99,4 +99,4 @@ Object.defineProperty(exports, "createBrowserClipboardAdapter", {
|
|
|
99
99
|
}
|
|
100
100
|
});
|
|
101
101
|
|
|
102
|
-
//# sourceMappingURL=clipboard-adapter-
|
|
102
|
+
//# sourceMappingURL=clipboard-adapter-Bpuf5GmB.cjs.map
|
package/dist/chunks/{clipboard-adapter-UIFc_Qso.cjs.map → clipboard-adapter-Bpuf5GmB.cjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard-adapter-UIFc_Qso.cjs","names":["CopyFailure","createCopyError","isBlob","IMAGE_MIME_TYPE","serializeJson"],"sources":["../../src/core/clipboard-adapter.ts"],"sourcesContent":["import { CopyFailure, createCopyError, type CopyErrorType } from './errors';\nimport type { OperationContext } from './machine-shared';\nimport { IMAGE_MIME_TYPE, isBlob, serializeJson, type BlobSource, type CopyPayload } from './payload';\n\n/** Minimal structural view of `navigator.clipboard`, so fakes and polyfills fit. */\nexport interface ClipboardLike {\n writeText?(text: string): Promise<void>;\n write?(items: readonly unknown[]): Promise<void>;\n}\n\nexport type ClipboardItemData = Blob | PromiseLike<Blob>;\n\nexport interface ClipboardItemConstructorLike {\n new (items: Record<string, ClipboardItemData>): unknown;\n supports?(type: string): boolean;\n}\n\nexport interface ClipboardEnvironment {\n readonly isSecureContext?: boolean;\n readonly navigator?: { readonly clipboard?: ClipboardLike | undefined } | undefined;\n readonly ClipboardItem?: ClipboardItemConstructorLike | undefined;\n}\n\n/**\n * The only thing the state machine needs. Implement it to target Electron,\n * a native bridge, a test double, or anything else.\n *\n * Contract: start the platform write synchronously (before any `await`) so the\n * browser still sees the user gesture, and reject with a `CopyFailure` when you\n * can classify the error. `context.signal` aborts when the copy is reset or its\n * host unmounts; honour it to stop expensive work early.\n */\nexport interface ClipboardAdapter {\n write(payload: CopyPayload, context?: OperationContext): Promise<void>;\n}\n\nexport interface BrowserClipboardAdapterOptions {\n /** Defaults to `window`, read lazily at copy time (SSR-safe). */\n readonly getEnvironment?: () => ClipboardEnvironment | undefined;\n /** When rich HTML copy is unavailable, fall back to its plain text. Default `true`. */\n readonly degradeHtmlToText?: boolean;\n}\n\ninterface RichClipboard {\n readonly Item: ClipboardItemConstructorLike;\n readonly write: (items: readonly unknown[]) => Promise<void>;\n}\n\nconst fail = (type: CopyErrorType, message: string, cause?: unknown): CopyFailure =>\n new CopyFailure(createCopyError(type, message, cause));\n\nconst noop = (): void => undefined;\n\nfunction defaultEnvironment(): ClipboardEnvironment | undefined {\n return typeof window === 'undefined' ? undefined : window;\n}\n\nfunction getRichClipboard(env: ClipboardEnvironment, clipboard: ClipboardLike): RichClipboard | null {\n const Item = env.ClipboardItem;\n if (!Item || typeof clipboard.write !== 'function') return null;\n return { Item, write: clipboard.write.bind(clipboard) };\n}\n\nfunction isTypeSupported(Item: ClipboardItemConstructorLike, type: string): boolean {\n return typeof Item.supports !== 'function' || Item.supports(type);\n}\n\nfunction writeText(clipboard: ClipboardLike, text: string): Promise<void> {\n if (typeof clipboard.writeText !== 'function') {\n throw fail('unsupported', 'navigator.clipboard.writeText() is not available.');\n }\n return clipboard.writeText(text);\n}\n\nasync function resolveImageBlob(source: BlobSource, context: OperationContext | undefined): Promise<Blob> {\n let blob: unknown;\n try {\n // Invoked before the first await, i.e. synchronously inside the gesture.\n blob = await (typeof source === 'function' ? source(context ?? { signal: new AbortController().signal }) : source);\n } catch (cause) {\n if (context?.signal.aborted) throw fail('aborted', 'The image copy was cancelled.', cause);\n throw fail('blob-generation-failed', 'The image source threw or rejected while producing a Blob.', cause);\n }\n if (!isBlob(blob)) throw fail('blob-generation-failed', 'The image source did not produce a Blob.');\n if (blob.type !== IMAGE_MIME_TYPE) {\n throw fail(\n 'unsupported-format',\n `Only ${IMAGE_MIME_TYPE} can be written to the clipboard (received \"${blob.type || 'unknown'}\"). ` +\n `Convert with canvas.toBlob(cb, \"${IMAGE_MIME_TYPE}\").`,\n );\n }\n return blob;\n}\n\nasync function writeImage(\n rich: RichClipboard,\n source: BlobSource,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!isTypeSupported(rich.Item, IMAGE_MIME_TYPE)) {\n throw fail('unsupported-format', `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);\n }\n // Hand ClipboardItem a *promise* so Safari keeps the gesture while the blob is produced.\n const blob = resolveImageBlob(source, context);\n blob.catch(noop); // Never an unhandled rejection, whichever side fails first.\n try {\n await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);\n } catch (error) {\n // Browsers replace our classified reason with a generic DOMException. Prefer ours.\n const reason = await blob.then(noop, (inner: unknown) => inner);\n throw reason ?? error;\n }\n // Conforming browsers have consumed `blob` by now. Lax polyfills/webviews may resolve\n // without reading it: never report an image that failed to generate as copied.\n await blob;\n}\n\nasync function writeToClipboard(\n payload: CopyPayload,\n env: ClipboardEnvironment | undefined,\n degradeHtmlToText: boolean,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!env) throw fail('unsupported', 'No browser environment: the clipboard only exists in the browser.');\n if (env.isSecureContext === false) {\n throw fail('insecure-context', 'The Clipboard API requires a secure context (HTTPS or localhost).');\n }\n const clipboard = env.navigator?.clipboard;\n if (!clipboard) throw fail('unsupported', 'navigator.clipboard is not available in this browser.');\n\n switch (payload.kind) {\n case 'text':\n return writeText(clipboard, payload.value);\n\n case 'json':\n return writeText(clipboard, serializeJson(payload));\n\n case 'html': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich || !isTypeSupported(rich.Item, 'text/html')) {\n if (degradeHtmlToText) return writeText(clipboard, payload.text);\n throw fail('unsupported-format', 'Rich HTML copy requires ClipboardItem and navigator.clipboard.write().');\n }\n return rich.write([\n new rich.Item({\n 'text/html': new Blob([payload.html], { type: 'text/html' }),\n 'text/plain': new Blob([payload.text], { type: 'text/plain' }),\n }),\n ]);\n }\n\n case 'image': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich) throw fail('unsupported-format', 'Image copy requires ClipboardItem and navigator.clipboard.write().');\n return writeImage(rich, payload.blob, context);\n }\n\n case 'multi': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich) throw fail('unsupported-format', 'Multi-format copy requires ClipboardItem and navigator.clipboard.write().');\n const record: Record<string, ClipboardItemData> = Object.create(null) as Record<string, ClipboardItemData>;\n let written = 0;\n for (const { mimeType, data, optional } of payload.items) {\n // Optional items need positive confirmation: an unknown type can make the whole write reject.\n if (optional === true && !(typeof rich.Item.supports === 'function' && rich.Item.supports(mimeType))) continue;\n if (!isTypeSupported(rich.Item, mimeType)) {\n throw fail('unsupported-format', `This browser cannot write \"${mimeType}\" to the clipboard.`);\n }\n record[mimeType] = typeof data === 'string' ? new Blob([data], { type: mimeType }) : data;\n written += 1;\n }\n if (written === 0) throw fail('unsupported-format', 'This browser can write none of the payload types.');\n return rich.write([new rich.Item(record)]);\n }\n }\n}\n\n/** The default adapter: async Clipboard API with feature detection and honest errors. */\nexport function createBrowserClipboardAdapter(options: BrowserClipboardAdapterOptions = {}): ClipboardAdapter {\n const getEnvironment = options.getEnvironment ?? defaultEnvironment;\n const degradeHtmlToText = options.degradeHtmlToText ?? true;\n return {\n write: (payload, context) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText, context),\n };\n}\n"],"mappings":";;;;AAgDA,MAAM,QAAQ,MAAqB,SAAiB,UAClD,IAAIA,eAAAA,YAAYC,eAAAA,gBAAgB,MAAM,SAAS,KAAK,CAAC;AAEvD,MAAM,aAAmB,KAAA;AAEzB,SAAS,qBAAuD;CAC9D,OAAO,OAAO,WAAW,cAAc,KAAA,IAAY;AACrD;AAEA,SAAS,iBAAiB,KAA2B,WAAgD;CACnG,MAAM,OAAO,IAAI;CACjB,IAAI,CAAC,QAAQ,OAAO,UAAU,UAAU,YAAY,OAAO;CAC3D,OAAO;EAAE;EAAM,OAAO,UAAU,MAAM,KAAK,SAAS;CAAE;AACxD;AAEA,SAAS,gBAAgB,MAAoC,MAAuB;CAClF,OAAO,OAAO,KAAK,aAAa,cAAc,KAAK,SAAS,IAAI;AAClE;AAEA,SAAS,UAA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AAK,CAAC,IAAI,GAAG,EAAE,MAAM,SAAS,CAAC,IAAI;IACrF,WAAW;GACb;GACA,IAAI,YAAY,GAAG,MAAM,KAAK,sBAAsB,mDAAmD;GACvG,OAAO,KAAK,MAAM,CAAC,IAAI,KAAK,KAAK,MAAM,CAAC,CAAC;EAC3C;CACF;AACF;;AAGA,SAAgB,8BAA8B,UAA0C,CAAC,GAAqB;CAC5G,MAAM,iBAAiB,QAAQ,kBAAkB;CACjD,MAAM,oBAAoB,QAAQ,qBAAqB;CACvD,OAAO,EACL,QAAQ,SAAS,YAAY,iBAAiB,SAAS,eAAe,GAAG,mBAAmB,OAAO,EACrG;AACF"}
|
|
1
|
+
{"version":3,"file":"clipboard-adapter-Bpuf5GmB.cjs","names":["CopyFailure","createCopyError","isBlob","IMAGE_MIME_TYPE","serializeJson"],"sources":["../../src/core/clipboard-adapter.ts"],"sourcesContent":["import { CopyFailure, createCopyError, type CopyErrorType } from './errors';\nimport type { OperationContext } from './machine-shared';\nimport { IMAGE_MIME_TYPE, isBlob, serializeJson, type BlobSource, type CopyPayload } from './payload';\n\n/** Minimal structural view of `navigator.clipboard`, so fakes and polyfills fit. */\nexport interface ClipboardLike {\n writeText?(text: string): Promise<void>;\n write?(items: readonly unknown[]): Promise<void>;\n}\n\nexport type ClipboardItemData = Blob | PromiseLike<Blob>;\n\nexport interface ClipboardItemConstructorLike {\n new (items: Record<string, ClipboardItemData>): unknown;\n supports?(type: string): boolean;\n}\n\nexport interface ClipboardEnvironment {\n readonly isSecureContext?: boolean;\n readonly navigator?: { readonly clipboard?: ClipboardLike | undefined } | undefined;\n readonly ClipboardItem?: ClipboardItemConstructorLike | undefined;\n}\n\n/**\n * The only thing the state machine needs. Implement it to target Electron,\n * a native bridge, a test double, or anything else.\n *\n * Contract: start the platform write synchronously (before any `await`) so the\n * browser still sees the user gesture, and reject with a `CopyFailure` when you\n * can classify the error. `context.signal` aborts when the copy is reset or its\n * host unmounts; honour it to stop expensive work early.\n */\nexport interface ClipboardAdapter {\n write(payload: CopyPayload, context?: OperationContext): Promise<void>;\n}\n\nexport interface BrowserClipboardAdapterOptions {\n /** Defaults to `window`, read lazily at copy time (SSR-safe). */\n readonly getEnvironment?: () => ClipboardEnvironment | undefined;\n /** When rich HTML copy is unavailable, fall back to its plain text. Default `true`. */\n readonly degradeHtmlToText?: boolean;\n}\n\ninterface RichClipboard {\n readonly Item: ClipboardItemConstructorLike;\n readonly write: (items: readonly unknown[]) => Promise<void>;\n}\n\nconst fail = (type: CopyErrorType, message: string, cause?: unknown): CopyFailure =>\n new CopyFailure(createCopyError(type, message, cause));\n\nconst noop = (): void => undefined;\n\nfunction defaultEnvironment(): ClipboardEnvironment | undefined {\n return typeof window === 'undefined' ? undefined : window;\n}\n\nfunction getRichClipboard(env: ClipboardEnvironment, clipboard: ClipboardLike): RichClipboard | null {\n const Item = env.ClipboardItem;\n if (!Item || typeof clipboard.write !== 'function') return null;\n return { Item, write: clipboard.write.bind(clipboard) };\n}\n\nfunction isTypeSupported(Item: ClipboardItemConstructorLike, type: string): boolean {\n return typeof Item.supports !== 'function' || Item.supports(type);\n}\n\nfunction writeText(clipboard: ClipboardLike, text: string): Promise<void> {\n if (typeof clipboard.writeText !== 'function') {\n throw fail('unsupported', 'navigator.clipboard.writeText() is not available.');\n }\n return clipboard.writeText(text);\n}\n\nasync function resolveImageBlob(source: BlobSource, context: OperationContext | undefined): Promise<Blob> {\n let blob: unknown;\n try {\n // Invoked before the first await, i.e. synchronously inside the gesture.\n blob = await (typeof source === 'function' ? source(context ?? { signal: new AbortController().signal }) : source);\n } catch (cause) {\n if (context?.signal.aborted) throw fail('aborted', 'The image copy was cancelled.', cause);\n throw fail('blob-generation-failed', 'The image source threw or rejected while producing a Blob.', cause);\n }\n if (!isBlob(blob)) throw fail('blob-generation-failed', 'The image source did not produce a Blob.');\n if (blob.type !== IMAGE_MIME_TYPE) {\n throw fail(\n 'unsupported-format',\n `Only ${IMAGE_MIME_TYPE} can be written to the clipboard (received \"${blob.type || 'unknown'}\"). ` +\n `Convert with canvas.toBlob(cb, \"${IMAGE_MIME_TYPE}\").`,\n );\n }\n return blob;\n}\n\nasync function writeImage(\n rich: RichClipboard,\n source: BlobSource,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!isTypeSupported(rich.Item, IMAGE_MIME_TYPE)) {\n throw fail('unsupported-format', `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);\n }\n // Hand ClipboardItem a *promise* so Safari keeps the gesture while the blob is produced.\n const blob = resolveImageBlob(source, context);\n blob.catch(noop); // Never an unhandled rejection, whichever side fails first.\n try {\n await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);\n } catch (error) {\n // Browsers replace our classified reason with a generic DOMException. Prefer ours.\n const reason = await blob.then(noop, (inner: unknown) => inner);\n throw reason ?? error;\n }\n // Conforming browsers have consumed `blob` by now. Lax polyfills/webviews may resolve\n // without reading it: never report an image that failed to generate as copied.\n await blob;\n}\n\nasync function writeToClipboard(\n payload: CopyPayload,\n env: ClipboardEnvironment | undefined,\n degradeHtmlToText: boolean,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!env) throw fail('unsupported', 'No browser environment: the clipboard only exists in the browser.');\n if (env.isSecureContext === false) {\n throw fail('insecure-context', 'The Clipboard API requires a secure context (HTTPS or localhost).');\n }\n const clipboard = env.navigator?.clipboard;\n if (!clipboard) throw fail('unsupported', 'navigator.clipboard is not available in this browser.');\n\n switch (payload.kind) {\n case 'text':\n return writeText(clipboard, payload.value);\n\n case 'json':\n return writeText(clipboard, serializeJson(payload));\n\n case 'html': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich || !isTypeSupported(rich.Item, 'text/html')) {\n if (degradeHtmlToText) return writeText(clipboard, payload.text);\n throw fail('unsupported-format', 'Rich HTML copy requires ClipboardItem and navigator.clipboard.write().');\n }\n return rich.write([\n new rich.Item({\n 'text/html': new Blob([payload.html], { type: 'text/html' }),\n 'text/plain': new Blob([payload.text], { type: 'text/plain' }),\n }),\n ]);\n }\n\n case 'image': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich) throw fail('unsupported-format', 'Image copy requires ClipboardItem and navigator.clipboard.write().');\n return writeImage(rich, payload.blob, context);\n }\n\n case 'multi': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich) throw fail('unsupported-format', 'Multi-format copy requires ClipboardItem and navigator.clipboard.write().');\n const record: Record<string, ClipboardItemData> = Object.create(null) as Record<string, ClipboardItemData>;\n let written = 0;\n for (const { mimeType, data, optional } of payload.items) {\n // Optional items need positive confirmation: an unknown type can make the whole write reject.\n if (optional === true && !(typeof rich.Item.supports === 'function' && rich.Item.supports(mimeType))) continue;\n if (!isTypeSupported(rich.Item, mimeType)) {\n throw fail('unsupported-format', `This browser cannot write \"${mimeType}\" to the clipboard.`);\n }\n record[mimeType] = typeof data === 'string' ? new Blob([data], { type: mimeType }) : data;\n written += 1;\n }\n if (written === 0) throw fail('unsupported-format', 'This browser can write none of the payload types.');\n return rich.write([new rich.Item(record)]);\n }\n }\n}\n\n/** The default adapter: async Clipboard API with feature detection and honest errors. */\nexport function createBrowserClipboardAdapter(options: BrowserClipboardAdapterOptions = {}): ClipboardAdapter {\n const getEnvironment = options.getEnvironment ?? defaultEnvironment;\n const degradeHtmlToText = options.degradeHtmlToText ?? true;\n return {\n write: (payload, context) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText, context),\n };\n}\n"],"mappings":";;;;AAgDA,MAAM,QAAQ,MAAqB,SAAiB,UAClD,IAAIA,eAAAA,YAAYC,eAAAA,gBAAgB,MAAM,SAAS,KAAK,CAAC;AAEvD,MAAM,aAAmB,KAAA;AAEzB,SAAS,qBAAuD;CAC9D,OAAO,OAAO,WAAW,cAAc,KAAA,IAAY;AACrD;AAEA,SAAS,iBAAiB,KAA2B,WAAgD;CACnG,MAAM,OAAO,IAAI;CACjB,IAAI,CAAC,QAAQ,OAAO,UAAU,UAAU,YAAY,OAAO;CAC3D,OAAO;EAAE;EAAM,OAAO,UAA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AI;IACtG,IAAI,CAAC,gBAAgB,KAAK,MAAM,QAAQ,GACtC,MAAM,KAAK,sBAAsB,8BAA8B,SAAS,oBAAoB;IAE9F,OAAO,YAAY,OAAO,SAAS,WAAW,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,MAAM,SAAS,CAAC,IAAI;IACrF,WAAW;GACb;GACA,IAAI,YAAY,GAAG,MAAM,KAAK,sBAAsB,mDAAmD;GACvG,OAAO,KAAK,MAAM,CAAC,IAAI,KAAK,KAAK,MAAM,CAAC,CAAC;EAC3C;CACF;AACF;;AAGA,SAAgB,8BAA8B,UAA0C,CAAC,GAAqB;CAC5G,MAAM,iBAAiB,QAAQ,kBAAkB;CACjD,MAAM,oBAAoB,QAAQ,qBAAqB;CACvD,OAAO,EACL,QAAQ,SAAS,YAAY,iBAAiB,SAAS,eAAe,GAAG,mBAAmB,OAAO,EACrG;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import { r as createCopyError, t as CopyFailure } from "./errors-
|
|
3
|
-
import { i as serializeJson, n as isBlob, t as IMAGE_MIME_TYPE } from "./payload-
|
|
2
|
+
import { r as createCopyError, t as CopyFailure } from "./errors-CGcMvbhJ.js";
|
|
3
|
+
import { i as serializeJson, n as isBlob, t as IMAGE_MIME_TYPE } from "./payload-5uJedhwz.js";
|
|
4
4
|
//#region src/core/clipboard-adapter.ts
|
|
5
5
|
const fail = (type, message, cause) => new CopyFailure(createCopyError(type, message, cause));
|
|
6
6
|
const noop = () => void 0;
|
|
@@ -94,4 +94,4 @@ function createBrowserClipboardAdapter(options = {}) {
|
|
|
94
94
|
//#endregion
|
|
95
95
|
export { createBrowserClipboardAdapter as t };
|
|
96
96
|
|
|
97
|
-
//# sourceMappingURL=clipboard-adapter-
|
|
97
|
+
//# sourceMappingURL=clipboard-adapter-DyCmyZV9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard-adapter-CmKDTFdO.js","names":[],"sources":["../../src/core/clipboard-adapter.ts"],"sourcesContent":["import { CopyFailure, createCopyError, type CopyErrorType } from './errors';\nimport type { OperationContext } from './machine-shared';\nimport { IMAGE_MIME_TYPE, isBlob, serializeJson, type BlobSource, type CopyPayload } from './payload';\n\n/** Minimal structural view of `navigator.clipboard`, so fakes and polyfills fit. */\nexport interface ClipboardLike {\n writeText?(text: string): Promise<void>;\n write?(items: readonly unknown[]): Promise<void>;\n}\n\nexport type ClipboardItemData = Blob | PromiseLike<Blob>;\n\nexport interface ClipboardItemConstructorLike {\n new (items: Record<string, ClipboardItemData>): unknown;\n supports?(type: string): boolean;\n}\n\nexport interface ClipboardEnvironment {\n readonly isSecureContext?: boolean;\n readonly navigator?: { readonly clipboard?: ClipboardLike | undefined } | undefined;\n readonly ClipboardItem?: ClipboardItemConstructorLike | undefined;\n}\n\n/**\n * The only thing the state machine needs. Implement it to target Electron,\n * a native bridge, a test double, or anything else.\n *\n * Contract: start the platform write synchronously (before any `await`) so the\n * browser still sees the user gesture, and reject with a `CopyFailure` when you\n * can classify the error. `context.signal` aborts when the copy is reset or its\n * host unmounts; honour it to stop expensive work early.\n */\nexport interface ClipboardAdapter {\n write(payload: CopyPayload, context?: OperationContext): Promise<void>;\n}\n\nexport interface BrowserClipboardAdapterOptions {\n /** Defaults to `window`, read lazily at copy time (SSR-safe). */\n readonly getEnvironment?: () => ClipboardEnvironment | undefined;\n /** When rich HTML copy is unavailable, fall back to its plain text. Default `true`. */\n readonly degradeHtmlToText?: boolean;\n}\n\ninterface RichClipboard {\n readonly Item: ClipboardItemConstructorLike;\n readonly write: (items: readonly unknown[]) => Promise<void>;\n}\n\nconst fail = (type: CopyErrorType, message: string, cause?: unknown): CopyFailure =>\n new CopyFailure(createCopyError(type, message, cause));\n\nconst noop = (): void => undefined;\n\nfunction defaultEnvironment(): ClipboardEnvironment | undefined {\n return typeof window === 'undefined' ? undefined : window;\n}\n\nfunction getRichClipboard(env: ClipboardEnvironment, clipboard: ClipboardLike): RichClipboard | null {\n const Item = env.ClipboardItem;\n if (!Item || typeof clipboard.write !== 'function') return null;\n return { Item, write: clipboard.write.bind(clipboard) };\n}\n\nfunction isTypeSupported(Item: ClipboardItemConstructorLike, type: string): boolean {\n return typeof Item.supports !== 'function' || Item.supports(type);\n}\n\nfunction writeText(clipboard: ClipboardLike, text: string): Promise<void> {\n if (typeof clipboard.writeText !== 'function') {\n throw fail('unsupported', 'navigator.clipboard.writeText() is not available.');\n }\n return clipboard.writeText(text);\n}\n\nasync function resolveImageBlob(source: BlobSource, context: OperationContext | undefined): Promise<Blob> {\n let blob: unknown;\n try {\n // Invoked before the first await, i.e. synchronously inside the gesture.\n blob = await (typeof source === 'function' ? source(context ?? { signal: new AbortController().signal }) : source);\n } catch (cause) {\n if (context?.signal.aborted) throw fail('aborted', 'The image copy was cancelled.', cause);\n throw fail('blob-generation-failed', 'The image source threw or rejected while producing a Blob.', cause);\n }\n if (!isBlob(blob)) throw fail('blob-generation-failed', 'The image source did not produce a Blob.');\n if (blob.type !== IMAGE_MIME_TYPE) {\n throw fail(\n 'unsupported-format',\n `Only ${IMAGE_MIME_TYPE} can be written to the clipboard (received \"${blob.type || 'unknown'}\"). ` +\n `Convert with canvas.toBlob(cb, \"${IMAGE_MIME_TYPE}\").`,\n );\n }\n return blob;\n}\n\nasync function writeImage(\n rich: RichClipboard,\n source: BlobSource,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!isTypeSupported(rich.Item, IMAGE_MIME_TYPE)) {\n throw fail('unsupported-format', `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);\n }\n // Hand ClipboardItem a *promise* so Safari keeps the gesture while the blob is produced.\n const blob = resolveImageBlob(source, context);\n blob.catch(noop); // Never an unhandled rejection, whichever side fails first.\n try {\n await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);\n } catch (error) {\n // Browsers replace our classified reason with a generic DOMException. Prefer ours.\n const reason = await blob.then(noop, (inner: unknown) => inner);\n throw reason ?? error;\n }\n // Conforming browsers have consumed `blob` by now. Lax polyfills/webviews may resolve\n // without reading it: never report an image that failed to generate as copied.\n await blob;\n}\n\nasync function writeToClipboard(\n payload: CopyPayload,\n env: ClipboardEnvironment | undefined,\n degradeHtmlToText: boolean,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!env) throw fail('unsupported', 'No browser environment: the clipboard only exists in the browser.');\n if (env.isSecureContext === false) {\n throw fail('insecure-context', 'The Clipboard API requires a secure context (HTTPS or localhost).');\n }\n const clipboard = env.navigator?.clipboard;\n if (!clipboard) throw fail('unsupported', 'navigator.clipboard is not available in this browser.');\n\n switch (payload.kind) {\n case 'text':\n return writeText(clipboard, payload.value);\n\n case 'json':\n return writeText(clipboard, serializeJson(payload));\n\n case 'html': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich || !isTypeSupported(rich.Item, 'text/html')) {\n if (degradeHtmlToText) return writeText(clipboard, payload.text);\n throw fail('unsupported-format', 'Rich HTML copy requires ClipboardItem and navigator.clipboard.write().');\n }\n return rich.write([\n new rich.Item({\n 'text/html': new Blob([payload.html], { type: 'text/html' }),\n 'text/plain': new Blob([payload.text], { type: 'text/plain' }),\n }),\n ]);\n }\n\n case 'image': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich) throw fail('unsupported-format', 'Image copy requires ClipboardItem and navigator.clipboard.write().');\n return writeImage(rich, payload.blob, context);\n }\n\n case 'multi': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich) throw fail('unsupported-format', 'Multi-format copy requires ClipboardItem and navigator.clipboard.write().');\n const record: Record<string, ClipboardItemData> = Object.create(null) as Record<string, ClipboardItemData>;\n let written = 0;\n for (const { mimeType, data, optional } of payload.items) {\n // Optional items need positive confirmation: an unknown type can make the whole write reject.\n if (optional === true && !(typeof rich.Item.supports === 'function' && rich.Item.supports(mimeType))) continue;\n if (!isTypeSupported(rich.Item, mimeType)) {\n throw fail('unsupported-format', `This browser cannot write \"${mimeType}\" to the clipboard.`);\n }\n record[mimeType] = typeof data === 'string' ? new Blob([data], { type: mimeType }) : data;\n written += 1;\n }\n if (written === 0) throw fail('unsupported-format', 'This browser can write none of the payload types.');\n return rich.write([new rich.Item(record)]);\n }\n }\n}\n\n/** The default adapter: async Clipboard API with feature detection and honest errors. */\nexport function createBrowserClipboardAdapter(options: BrowserClipboardAdapterOptions = {}): ClipboardAdapter {\n const getEnvironment = options.getEnvironment ?? defaultEnvironment;\n const degradeHtmlToText = options.degradeHtmlToText ?? true;\n return {\n write: (payload, context) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText, context),\n };\n}\n"],"mappings":";;;;AAgDA,MAAM,QAAQ,MAAqB,SAAiB,UAClD,IAAI,YAAY,gBAAgB,MAAM,SAAS,KAAK,CAAC;AAEvD,MAAM,aAAmB,KAAA;AAEzB,SAAS,qBAAuD;CAC9D,OAAO,OAAO,WAAW,cAAc,KAAA,IAAY;AACrD;AAEA,SAAS,iBAAiB,KAA2B,WAAgD;CACnG,MAAM,OAAO,IAAI;CACjB,IAAI,CAAC,QAAQ,OAAO,UAAU,UAAU,YAAY,OAAO;CAC3D,OAAO;EAAE;EAAM,OAAO,UAAU,MAAM,KAAK,SAAS;CAAE;AACxD;AAEA,SAAS,gBAAgB,MAAoC,MAAuB;CAClF,OAAO,OAAO,KAAK,aAAa,cAAc,KAAK,SAAS,IAAI;AAClE;AAEA,SAAS,UAAU,WAA0B,MAA6B;CACxE,IAAI,OAAO,UAAU,cAAc,YACjC,MAAM,KAAK,eAAe,mDAAmD;CAE/E,OAAO,UAAU,UAAU,IAAI;AACjC;AAEA,eAAe,iBAAiB,QAAoB,SAAsD;CACxG,IAAI;CACJ,IAAI;EAEF,OAAO,OAAO,OAAO,WAAW,aAAa,OAAO,WAAW,EAAE,QAAQ,IAAI,gBAAgB,CAAC,CAAC,OAAO,CAAC,IAAI;CAC7G,SAAS,OAAO;EACd,IAAI,SAAS,OAAO,SAAS,MAAM,KAAK,WAAW,iCAAiC,KAAK;EACzF,MAAM,KAAK,0BAA0B,8DAA8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myZV9.js","names":[],"sources":["../../src/core/clipboard-adapter.ts"],"sourcesContent":["import { CopyFailure, createCopyError, type CopyErrorType } from './errors';\nimport type { OperationContext } from './machine-shared';\nimport { IMAGE_MIME_TYPE, isBlob, serializeJson, type BlobSource, type CopyPayload } from './payload';\n\n/** Minimal structural view of `navigator.clipboard`, so fakes and polyfills fit. */\nexport interface ClipboardLike {\n writeText?(text: string): Promise<void>;\n write?(items: readonly unknown[]): Promise<void>;\n}\n\nexport type ClipboardItemData = Blob | PromiseLike<Blob>;\n\nexport interface ClipboardItemConstructorLike {\n new (items: Record<string, ClipboardItemData>): unknown;\n supports?(type: string): boolean;\n}\n\nexport interface ClipboardEnvironment {\n readonly isSecureContext?: boolean;\n readonly navigator?: { readonly clipboard?: ClipboardLike | undefined } | undefined;\n readonly ClipboardItem?: ClipboardItemConstructorLike | undefined;\n}\n\n/**\n * The only thing the state machine needs. Implement it to target Electron,\n * a native bridge, a test double, or anything else.\n *\n * Contract: start the platform write synchronously (before any `await`) so the\n * browser still sees the user gesture, and reject with a `CopyFailure` when you\n * can classify the error. `context.signal` aborts when the copy is reset or its\n * host unmounts; honour it to stop expensive work early.\n */\nexport interface ClipboardAdapter {\n write(payload: CopyPayload, context?: OperationContext): Promise<void>;\n}\n\nexport interface BrowserClipboardAdapterOptions {\n /** Defaults to `window`, read lazily at copy time (SSR-safe). */\n readonly getEnvironment?: () => ClipboardEnvironment | undefined;\n /** When rich HTML copy is unavailable, fall back to its plain text. Default `true`. */\n readonly degradeHtmlToText?: boolean;\n}\n\ninterface RichClipboard {\n readonly Item: ClipboardItemConstructorLike;\n readonly write: (items: readonly unknown[]) => Promise<void>;\n}\n\nconst fail = (type: CopyErrorType, message: string, cause?: unknown): CopyFailure =>\n new CopyFailure(createCopyError(type, message, cause));\n\nconst noop = (): void => undefined;\n\nfunction defaultEnvironment(): ClipboardEnvironment | undefined {\n return typeof window === 'undefined' ? undefined : window;\n}\n\nfunction getRichClipboard(env: ClipboardEnvironment, clipboard: ClipboardLike): RichClipboard | null {\n const Item = env.ClipboardItem;\n if (!Item || typeof clipboard.write !== 'function') return null;\n return { Item, write: clipboard.write.bind(clipboard) };\n}\n\nfunction isTypeSupported(Item: ClipboardItemConstructorLike, type: string): boolean {\n return typeof Item.supports !== 'function' || Item.supports(type);\n}\n\nfunction writeText(clipboard: ClipboardLike, text: string): Promise<void> {\n if (typeof clipboard.writeText !== 'function') {\n throw fail('unsupported', 'navigator.clipboard.writeText() is not available.');\n }\n return clipboard.writeText(text);\n}\n\nasync function resolveImageBlob(source: BlobSource, context: OperationContext | undefined): Promise<Blob> {\n let blob: unknown;\n try {\n // Invoked before the first await, i.e. synchronously inside the gesture.\n blob = await (typeof source === 'function' ? source(context ?? { signal: new AbortController().signal }) : source);\n } catch (cause) {\n if (context?.signal.aborted) throw fail('aborted', 'The image copy was cancelled.', cause);\n throw fail('blob-generation-failed', 'The image source threw or rejected while producing a Blob.', cause);\n }\n if (!isBlob(blob)) throw fail('blob-generation-failed', 'The image source did not produce a Blob.');\n if (blob.type !== IMAGE_MIME_TYPE) {\n throw fail(\n 'unsupported-format',\n `Only ${IMAGE_MIME_TYPE} can be written to the clipboard (received \"${blob.type || 'unknown'}\"). ` +\n `Convert with canvas.toBlob(cb, \"${IMAGE_MIME_TYPE}\").`,\n );\n }\n return blob;\n}\n\nasync function writeImage(\n rich: RichClipboard,\n source: BlobSource,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!isTypeSupported(rich.Item, IMAGE_MIME_TYPE)) {\n throw fail('unsupported-format', `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);\n }\n // Hand ClipboardItem a *promise* so Safari keeps the gesture while the blob is produced.\n const blob = resolveImageBlob(source, context);\n blob.catch(noop); // Never an unhandled rejection, whichever side fails first.\n try {\n await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);\n } catch (error) {\n // Browsers replace our classified reason with a generic DOMException. Prefer ours.\n const reason = await blob.then(noop, (inner: unknown) => inner);\n throw reason ?? error;\n }\n // Conforming browsers have consumed `blob` by now. Lax polyfills/webviews may resolve\n // without reading it: never report an image that failed to generate as copied.\n await blob;\n}\n\nasync function writeToClipboard(\n payload: CopyPayload,\n env: ClipboardEnvironment | undefined,\n degradeHtmlToText: boolean,\n context: OperationContext | undefined,\n): Promise<void> {\n if (!env) throw fail('unsupported', 'No browser environment: the clipboard only exists in the browser.');\n if (env.isSecureContext === false) {\n throw fail('insecure-context', 'The Clipboard API requires a secure context (HTTPS or localhost).');\n }\n const clipboard = env.navigator?.clipboard;\n if (!clipboard) throw fail('unsupported', 'navigator.clipboard is not available in this browser.');\n\n switch (payload.kind) {\n case 'text':\n return writeText(clipboard, payload.value);\n\n case 'json':\n return writeText(clipboard, serializeJson(payload));\n\n case 'html': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich || !isTypeSupported(rich.Item, 'text/html')) {\n if (degradeHtmlToText) return writeText(clipboard, payload.text);\n throw fail('unsupported-format', 'Rich HTML copy requires ClipboardItem and navigator.clipboard.write().');\n }\n return rich.write([\n new rich.Item({\n 'text/html': new Blob([payload.html], { type: 'text/html' }),\n 'text/plain': new Blob([payload.text], { type: 'text/plain' }),\n }),\n ]);\n }\n\n case 'image': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich) throw fail('unsupported-format', 'Image copy requires ClipboardItem and navigator.clipboard.write().');\n return writeImage(rich, payload.blob, context);\n }\n\n case 'multi': {\n const rich = getRichClipboard(env, clipboard);\n if (!rich) throw fail('unsupported-format', 'Multi-format copy requires ClipboardItem and navigator.clipboard.write().');\n const record: Record<string, ClipboardItemData> = Object.create(null) as Record<string, ClipboardItemData>;\n let written = 0;\n for (const { mimeType, data, optional } of payload.items) {\n // Optional items need positive confirmation: an unknown type can make the whole write reject.\n if (optional === true && !(typeof rich.Item.supports === 'function' && rich.Item.supports(mimeType))) continue;\n if (!isTypeSupported(rich.Item, mimeType)) {\n throw fail('unsupported-format', `This browser cannot write \"${mimeType}\" to the clipboard.`);\n }\n record[mimeType] = typeof data === 'string' ? new Blob([data], { type: mimeType }) : data;\n written += 1;\n }\n if (written === 0) throw fail('unsupported-format', 'This browser can write none of the payload types.');\n return rich.write([new rich.Item(record)]);\n }\n }\n}\n\n/** The default adapter: async Clipboard API with feature detection and honest errors. */\nexport function createBrowserClipboardAdapter(options: BrowserClipboardAdapterOptions = {}): ClipboardAdapter {\n const getEnvironment = options.getEnvironment ?? defaultEnvironment;\n const degradeHtmlToText = options.degradeHtmlToText ?? true;\n return {\n write: (payload, context) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText, context),\n };\n}\n"],"mappings":";;;;AAgDA,MAAM,QAAQ,MAAqB,SAAiB,UAClD,IAAI,YAAY,gBAAgB,MAAM,SAAS,KAAK,CAAC;AAEvD,MAAM,aAAmB,KAAA;AAEzB,SAAS,qBAAuD;CAC9D,OAAO,OAAO,WAAW,cAAc,KAAA,IAAY;AACrD;AAEA,SAAS,iBAAiB,KAA2B,WAAgD;CACnG,MAAM,OAAO,IAAI;CACjB,IAAI,CAAC,QAAQ,OAAO,UAAU,UAAU,YAAY,OAAO;CAC3D,OAAO;EAAE;EAAM,OAAO,UAAU,MAAM,KAAK,SAAS;CAAE;AACxD;AAEA,SAAS,gBAAgB,MAAoC,MAAuB;CAClF,OAAO,OAAO,KAAK,aAAa,cAAc,KAAK,SAAS,IAAI;AAClE;AAEA,SAAS,UAAU,WAA0B,MAA6B;CACxE,IAAI,OAAO,UAAU,cAAc,YACjC,MAAM,KAAK,eAAe,mDAAmD;CAE/E,OAAO,UAAU,UAAU,IAAI;AACjC;AAEA,eAAe,iBAAiB,QAAoB,SAAsD;CACxG,IAAI;CACJ,IAAI;EAEF,OAAO,OAAO,OAAO,WAAW,aAAa,OAAO,WAAW,EAAE,QAAQ,IAAI,gBAAgB,CAAC,CAAC,OAAO,CAAC,IAAI;CAC7G,SAAS,OAAO;EACd,IAAI,SAAS,OAAO,SAAS,MAAM,KAAK,WAAW,iCAAiC,KAAK;EACzF,MAAM,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5 @@
|
|
|
1
1
|
|
|
2
|
-
const require_errors = require("./errors-
|
|
2
|
+
const require_errors = require("./errors-CF2EQNbc.cjs");
|
|
3
3
|
//#region src/color/convert.ts
|
|
4
4
|
const color = (r, g, b, alpha = 1) => Object.freeze({
|
|
5
5
|
r,
|
|
@@ -839,4 +839,4 @@ Object.defineProperty(exports, "toGamut", {
|
|
|
839
839
|
}
|
|
840
840
|
});
|
|
841
841
|
|
|
842
|
-
//# sourceMappingURL=contrast-
|
|
842
|
+
//# sourceMappingURL=contrast-BatHkv8j.cjs.map
|