react-smart-copy 1.17.2 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/README.md +9 -3
  2. package/dist/capture.cjs +30 -153
  3. package/dist/capture.cjs.map +1 -1
  4. package/dist/capture.d.cts +2 -25
  5. package/dist/capture.d.ts +2 -25
  6. package/dist/capture.js +5 -128
  7. package/dist/capture.js.map +1 -1
  8. package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs +102 -0
  9. package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs.map +1 -0
  10. package/dist/chunks/clipboard-adapter-CtH4VELE.d.cts +43 -0
  11. package/dist/chunks/clipboard-adapter-DEXkXxwV.js +97 -0
  12. package/dist/chunks/clipboard-adapter-DEXkXxwV.js.map +1 -0
  13. package/dist/chunks/clipboard-adapter-Ds0irroN.d.ts +43 -0
  14. package/dist/chunks/contrast-C6CVklEI.cjs +842 -0
  15. package/dist/chunks/contrast-C6CVklEI.cjs.map +1 -0
  16. package/dist/chunks/contrast-DpK2JIVu.js +789 -0
  17. package/dist/chunks/contrast-DpK2JIVu.js.map +1 -0
  18. package/dist/chunks/copy-interceptor-C6NABy1l.d.ts +141 -0
  19. package/dist/chunks/copy-interceptor-CZWzGOkL.d.cts +141 -0
  20. package/dist/chunks/core-Cp2HSpaz.js +1035 -0
  21. package/dist/chunks/core-Cp2HSpaz.js.map +1 -0
  22. package/dist/chunks/core-DYf_Lhbe.cjs +1142 -0
  23. package/dist/chunks/core-DYf_Lhbe.cjs.map +1 -0
  24. package/dist/chunks/deadline-C29AlS_Q.js +46 -0
  25. package/dist/chunks/deadline-C29AlS_Q.js.map +1 -0
  26. package/dist/chunks/deadline-DkiB8ZHE.cjs +51 -0
  27. package/dist/chunks/deadline-DkiB8ZHE.cjs.map +1 -0
  28. package/dist/chunks/errors-9h8sdFFX.js +120 -0
  29. package/dist/chunks/errors-9h8sdFFX.js.map +1 -0
  30. package/dist/chunks/errors-BwOF6T_M.cjs +167 -0
  31. package/dist/chunks/errors-BwOF6T_M.cjs.map +1 -0
  32. package/dist/chunks/index-mr7sSAgP.d.ts +426 -0
  33. package/dist/chunks/index-vz0iW5V2.d.cts +426 -0
  34. package/dist/chunks/mime--LB7kdqG.cjs +153 -0
  35. package/dist/chunks/mime--LB7kdqG.cjs.map +1 -0
  36. package/dist/chunks/mime-aa-HA2dm.js +100 -0
  37. package/dist/chunks/mime-aa-HA2dm.js.map +1 -0
  38. package/dist/chunks/paste-adapter--SPL4PRE.d.cts +35 -0
  39. package/dist/chunks/paste-adapter-uahXnTYk.d.ts +35 -0
  40. package/dist/chunks/paste-reader-Bo01IMC_.cjs +289 -0
  41. package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +1 -0
  42. package/dist/chunks/paste-reader-D9i7yMXF.js +224 -0
  43. package/dist/chunks/paste-reader-D9i7yMXF.js.map +1 -0
  44. package/dist/chunks/paste-reader-DcXnRWQr.d.cts +96 -0
  45. package/dist/chunks/paste-reader-DcXnRWQr.d.ts +96 -0
  46. package/dist/chunks/payload-CUymxwim.cjs +100 -0
  47. package/dist/chunks/payload-CUymxwim.cjs.map +1 -0
  48. package/dist/chunks/payload-CcwKJ_bU.d.cts +162 -0
  49. package/dist/chunks/payload-Cl_8hCI5.d.ts +162 -0
  50. package/dist/chunks/payload-DGw-JOo7.js +71 -0
  51. package/dist/chunks/payload-DGw-JOo7.js.map +1 -0
  52. package/dist/chunks/payload-DI5AorDz.js +103 -0
  53. package/dist/chunks/payload-DI5AorDz.js.map +1 -0
  54. package/dist/chunks/payload-J6GjHuh3.cjs +132 -0
  55. package/dist/chunks/payload-J6GjHuh3.cjs.map +1 -0
  56. package/dist/chunks/share-Bop47Znn.js +208 -0
  57. package/dist/chunks/share-Bop47Znn.js.map +1 -0
  58. package/dist/chunks/share-C0esXvRK.d.cts +115 -0
  59. package/dist/chunks/share-ayDz974N.cjs +231 -0
  60. package/dist/chunks/share-ayDz974N.cjs.map +1 -0
  61. package/dist/chunks/share-e7FenIr2.d.ts +115 -0
  62. package/dist/chunks/text-field-Ba8W3v4R.cjs +77 -0
  63. package/dist/chunks/text-field-Ba8W3v4R.cjs.map +1 -0
  64. package/dist/chunks/text-field-C0SGmvvR.d.cts +18 -0
  65. package/dist/chunks/text-field-C0SGmvvR.d.ts +18 -0
  66. package/dist/chunks/text-field-DUvrMMaK.js +66 -0
  67. package/dist/chunks/text-field-DUvrMMaK.js.map +1 -0
  68. package/dist/chunks/url-BcMYVCXQ.js +135 -0
  69. package/dist/chunks/url-BcMYVCXQ.js.map +1 -0
  70. package/dist/chunks/url-D4PGsRm8.cjs +164 -0
  71. package/dist/chunks/url-D4PGsRm8.cjs.map +1 -0
  72. package/dist/chunks/url-DWdElCT3.d.cts +43 -0
  73. package/dist/chunks/url-DWdElCT3.d.ts +43 -0
  74. package/dist/code.cjs +20 -112
  75. package/dist/code.cjs.map +1 -1
  76. package/dist/code.d.cts +4 -28
  77. package/dist/code.d.ts +4 -28
  78. package/dist/code.js +3 -95
  79. package/dist/code.js.map +1 -1
  80. package/dist/color.cjs +21 -893
  81. package/dist/color.cjs.map +1 -1
  82. package/dist/color.d.cts +4 -28
  83. package/dist/color.d.ts +4 -28
  84. package/dist/color.js +4 -876
  85. package/dist/color.js.map +1 -1
  86. package/dist/core.cjs +52 -1659
  87. package/dist/core.d.cts +8 -878
  88. package/dist/core.d.ts +8 -878
  89. package/dist/core.js +7 -1614
  90. package/dist/image.cjs +23 -94
  91. package/dist/image.cjs.map +1 -1
  92. package/dist/image.d.cts +1 -0
  93. package/dist/image.d.ts +1 -0
  94. package/dist/image.js +3 -74
  95. package/dist/image.js.map +1 -1
  96. package/dist/index.cjs +74 -2072
  97. package/dist/index.cjs.map +1 -1
  98. package/dist/index.d.cts +8 -978
  99. package/dist/index.d.ts +8 -978
  100. package/dist/index.js +7 -2005
  101. package/dist/index.js.map +1 -1
  102. package/dist/link.cjs +24 -338
  103. package/dist/link.cjs.map +1 -1
  104. package/dist/link.d.cts +5 -83
  105. package/dist/link.d.ts +5 -83
  106. package/dist/link.js +5 -319
  107. package/dist/link.js.map +1 -1
  108. package/dist/markdown.cjs +8 -97
  109. package/dist/markdown.cjs.map +1 -1
  110. package/dist/markdown.d.cts +3 -16
  111. package/dist/markdown.d.ts +3 -16
  112. package/dist/markdown.js +3 -92
  113. package/dist/markdown.js.map +1 -1
  114. package/dist/rich.cjs +26 -934
  115. package/dist/rich.cjs.map +1 -1
  116. package/dist/rich.d.cts +4 -90
  117. package/dist/rich.d.ts +4 -90
  118. package/dist/rich.js +4 -912
  119. package/dist/rich.js.map +1 -1
  120. package/dist/share.cjs +5 -640
  121. package/dist/share.d.cts +3 -248
  122. package/dist/share.d.ts +3 -248
  123. package/dist/share.js +1 -637
  124. package/dist/structured.cjs +13 -95
  125. package/dist/structured.cjs.map +1 -1
  126. package/dist/structured.d.cts +2 -11
  127. package/dist/structured.d.ts +2 -11
  128. package/dist/structured.js +4 -86
  129. package/dist/structured.js.map +1 -1
  130. package/dist/table.cjs +11 -39
  131. package/dist/table.cjs.map +1 -1
  132. package/dist/table.d.cts +2 -12
  133. package/dist/table.d.ts +2 -12
  134. package/dist/table.js +2 -30
  135. package/dist/table.js.map +1 -1
  136. package/dist/testing.cjs +10 -43
  137. package/dist/testing.cjs.map +1 -1
  138. package/dist/testing.d.cts +6 -181
  139. package/dist/testing.d.ts +6 -181
  140. package/dist/testing.js +3 -36
  141. package/dist/testing.js.map +1 -1
  142. package/package.json +20 -2
  143. package/dist/core.cjs.map +0 -1
  144. package/dist/core.js.map +0 -1
  145. package/dist/share.cjs.map +0 -1
  146. package/dist/share.js.map +0 -1
package/README.md CHANGED
@@ -1447,7 +1447,13 @@ The React entry ships with `"use client"`, so import it directly from Server Com
1447
1447
  Nothing touches `window` during render: the server and the first client render are both
1448
1448
  `idle` and not revealed, so there are no hydration mismatches.
1449
1449
 
1450
- `react-smart-copy/core` is framework-agnostic and safe to import anywhere.
1450
+ `react-smart-copy/core` is framework-agnostic and safe to import anywhere, and so is every other
1451
+ entry point (`/table`, `/markdown`, `/rich`, ...): only the main entry imports React, and the build
1452
+ checks that no other entry reaches it.
1453
+
1454
+ All entry points share one copy of the core. Using several of them loads it once, and a
1455
+ `CopyFailure` from any of them is an `instanceof` the one exported by `react-smart-copy` and
1456
+ `react-smart-copy/core`.
1451
1457
 
1452
1458
  ## Without React
1453
1459
 
@@ -1590,7 +1596,7 @@ embedded webviews. Where a capability is missing you get a typed error, never a
1590
1596
  - ~~**1.15** `react-smart-copy/share` — the share sheet on phones, a copied titled link everywhere else, with honest outcomes~~ shipped
1591
1597
  - ~~**1.16** `react-smart-copy/color` — copy and paste colours in every CSS format, CSS gamut mapping, WCAG contrast~~ shipped
1592
1598
  - ~~**1.17** `react-smart-copy/rich` — styled content that pastes as it looks in mail, Docs, Word and Slack, for buttons and Ctrl/⌘+C~~ shipped
1593
- - **1.18** One shared copy of the core across entry points: smaller bundles when you use several modules, and one `CopyFailure` class
1599
+ - ~~**1.18** One shared copy of the core across entry points: smaller bundles when you use several modules, and one `CopyFailure` class~~ shipped
1594
1600
  - **1.19** `react-smart-copy/rich`, paste side: paste from Word, Google Docs and web pages into rich-text editors as clean, safe HTML
1595
1601
 
1596
1602
  Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://suprabhat02.github.io/react-smart-copy/#releases).
@@ -1615,7 +1621,7 @@ is parsed inertly, URLs are scheme-checked, hidden characters are reported, and
1615
1621
  metadata is verified as removed. Report vulnerabilities privately as described in
1616
1622
  [SECURITY.md](./SECURITY.md). Releases carry npm provenance (`npm audit signatures`
1617
1623
  verifies them), and CodeQL and the OpenSSF Scorecard run on every change. Each GitHub release
1618
- (from 1.17.2 on) also holds the exact tarball npm serves, with a Sigstore attestation that it was
1624
+ (from 1.15.0 on) also holds the exact tarball npm serves, with a Sigstore attestation that it was
1619
1625
  built by this repository's release workflow:
1620
1626
 
1621
1627
  ```bash
package/dist/capture.cjs CHANGED
@@ -1,37 +1,9 @@
1
+
1
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region src/core/errors.ts
3
- function createCopyError(type, message, cause) {
4
- return cause === void 0 ? {
5
- type,
6
- message
7
- } : {
8
- type,
9
- message,
10
- cause
11
- };
12
- }
13
- /**
14
- * Branded (not `instanceof`) so failures stay recognisable even when the core
15
- * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
16
- */
17
- const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
18
- /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
19
- var CopyFailure = class extends Error {
20
- constructor(copyError) {
21
- super(copyError.message);
22
- this[COPY_FAILURE_BRAND] = true;
23
- this.name = "CopyFailure";
24
- this.copyError = copyError;
25
- }
26
- };
27
- function isCopyFailure(value) {
28
- return typeof value === "object" && value !== null && value[COPY_FAILURE_BRAND] === true;
29
- }
30
- /** Shorthand for throwing a classified failure. */
31
- function copyFailure(type, message, cause) {
32
- return new CopyFailure(createCopyError(type, message, cause));
33
- }
34
- //#endregion
3
+ const require_errors = require("./chunks/errors-BwOF6T_M.cjs");
4
+ const require_payload = require("./chunks/payload-CUymxwim.cjs");
5
+ const require_mime = require("./chunks/mime--LB7kdqG.cjs");
6
+ const require_deadline = require("./chunks/deadline-DkiB8ZHE.cjs");
35
7
  //#region src/capture/environment.ts
36
8
  function loadImage(url) {
37
9
  return new Promise((resolve, reject) => {
@@ -45,7 +17,7 @@ function loadImage(url) {
45
17
  });
46
18
  };
47
19
  image.onerror = () => {
48
- reject(copyFailure("blob-generation-failed", "The image could not be decoded."));
20
+ reject(require_errors.copyFailure("blob-generation-failed", "The image could not be decoded."));
49
21
  };
50
22
  image.src = url;
51
23
  });
@@ -57,7 +29,7 @@ function encodePng(image, target) {
57
29
  canvas.height = target.height;
58
30
  const context = canvas.getContext("2d");
59
31
  if (!context) {
60
- reject(copyFailure("unsupported", "Canvas 2D rendering is not available."));
32
+ reject(require_errors.copyFailure("unsupported", "Canvas 2D rendering is not available."));
61
33
  return;
62
34
  }
63
35
  if (target.background !== null) {
@@ -67,7 +39,7 @@ function encodePng(image, target) {
67
39
  context.drawImage(image.source, 0, 0, target.width, target.height);
68
40
  canvas.toBlob((blob) => {
69
41
  if (blob) resolve(blob);
70
- else reject(copyFailure("blob-generation-failed", "canvas.toBlob() produced nothing (canvas too large?)."));
42
+ else reject(require_errors.copyFailure("blob-generation-failed", "canvas.toBlob() produced nothing (canvas too large?)."));
71
43
  }, "image/png");
72
44
  });
73
45
  }
@@ -86,7 +58,7 @@ function getDefaultCaptureEnvironment() {
86
58
  }
87
59
  function resolveCaptureEnvironment(environment) {
88
60
  const resolved = environment ?? getDefaultCaptureEnvironment();
89
- if (!resolved) throw copyFailure("unsupported", "Image capture needs a browser environment (document, Image, canvas).");
61
+ if (!resolved) throw require_errors.copyFailure("unsupported", "Image capture needs a browser environment (document, Image, canvas).");
90
62
  return resolved;
91
63
  }
92
64
  //#endregion
@@ -96,7 +68,7 @@ const MAX_CAPTURE_SCALE = 10;
96
68
  /** 4096 × 4096: the canvas area limit of Safari/iOS, the strictest mainstream engine. */
97
69
  const DEFAULT_MAX_PIXELS = 16777216;
98
70
  const DEFAULT_CAPTURE_TIMEOUT_MS = 15e3;
99
- const invalid = (message) => copyFailure("invalid-payload", message);
71
+ const invalid = (message) => require_errors.copyFailure("invalid-payload", message);
100
72
  const isPositiveFinite = (value) => Number.isFinite(value) && value > 0;
101
73
  function resolveRenderSettings(options) {
102
74
  const scale = options.scale ?? 2;
@@ -141,108 +113,13 @@ function toPixelSize(size, settings) {
141
113
  };
142
114
  }
143
115
  function assertPixelBudget(width, height, maxPixels) {
144
- if (width * height > maxPixels) throw copyFailure("too-large", `A ${String(width)}×${String(height)} image exceeds the ${String(maxPixels)}-pixel limit. Lower \`scale\` or raise \`maxPixels\`.`);
145
- }
146
- //#endregion
147
- //#region src/core/mime.ts
148
- /** SVG is XML that can carry scripts; it is never matched by a wildcard. */
149
- const SVG_MIME_TYPE = "image/svg+xml";
150
- const SNIFF_BYTES = 16;
151
- function startsWith(bytes, signature, offset = 0) {
152
- return signature.every((byte, index) => bytes[offset + index] === byte);
153
- }
154
- const ascii = (text) => Array.from(text, (char) => char.charCodeAt(0));
155
- const PNG = [
156
- 137,
157
- 80,
158
- 78,
159
- 71,
160
- 13,
161
- 10,
162
- 26,
163
- 10
164
- ];
165
- const JPEG = [
166
- 255,
167
- 216,
168
- 255
169
- ];
170
- const GIF = ascii("GIF8");
171
- const RIFF = ascii("RIFF");
172
- const WEBP = ascii("WEBP");
173
- const BMP = ascii("BM");
174
- const FTYP_AVIF = ascii("ftypavif");
175
- const FTYP_AVIS = ascii("ftypavis");
176
- /** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */
177
- function sniffImageBytes(bytes) {
178
- if (startsWith(bytes, PNG)) return "image/png";
179
- if (startsWith(bytes, JPEG)) return "image/jpeg";
180
- if (startsWith(bytes, GIF)) return "image/gif";
181
- if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return "image/webp";
182
- if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return "image/avif";
183
- if (startsWith(bytes, BMP)) return "image/bmp";
184
- return null;
185
- }
186
- /** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */
187
- async function sniffImageType(blob) {
188
- const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();
189
- return sniffImageBytes(new Uint8Array(head));
190
- }
191
- //#endregion
192
- //#region src/core/payload.ts
193
- /** The only image MIME type with reliable cross-browser clipboard write support. */
194
- const IMAGE_MIME_TYPE = "image/png";
195
- function isBlob(value) {
196
- if (typeof Blob !== "undefined" && value instanceof Blob) return true;
197
- const tag = Object.prototype.toString.call(value);
198
- return tag === "[object Blob]" || tag === "[object File]";
199
- }
200
- //#endregion
201
- //#region src/capture/deadline.ts
202
- /**
203
- * Runs `task` with a timeout and an optional caller `AbortSignal`. The task
204
- * receives a signal that fires on either, so cooperative work can stop early.
205
- * Rejects with classified `timeout` / `aborted` failures.
206
- */
207
- function withDeadline(task, options) {
208
- const { timeoutMs, label } = options;
209
- const external = options.signal;
210
- if (external?.aborted) return Promise.reject(copyFailure("aborted", `${label} was aborted.`, external.reason));
211
- const controller = new AbortController();
212
- return new Promise((resolve, reject) => {
213
- const finish = (abort) => {
214
- clearTimeout(timer);
215
- external?.removeEventListener("abort", onAbort);
216
- /* c8 ignore next -- abort=false path is never used; kept for future API flexibility */
217
- if (abort) controller.abort();
218
- };
219
- const fail = (failure) => {
220
- finish(true);
221
- reject(failure);
222
- };
223
- const onAbort = () => {
224
- fail(copyFailure("aborted", `${label} was aborted.`, external.reason));
225
- };
226
- const timer = timeoutMs === Infinity ? void 0 : setTimeout(() => {
227
- fail(copyFailure("timeout", `${label} timed out after ${String(timeoutMs)} ms.`));
228
- }, timeoutMs);
229
- external?.addEventListener("abort", onAbort, { once: true });
230
- new Promise((run) => {
231
- run(task(controller.signal));
232
- }).then((value) => {
233
- finish(true);
234
- resolve(value);
235
- }, (cause) => {
236
- finish(true);
237
- reject(cause);
238
- });
239
- });
116
+ if (width * height > maxPixels) throw require_errors.copyFailure("too-large", `A ${String(width)}×${String(height)} image exceeds the ${String(maxPixels)}-pixel limit. Lower \`scale\` or raise \`maxPixels\`.`);
240
117
  }
241
118
  //#endregion
242
119
  //#region src/capture/render.ts
243
120
  /** Maps anything unexpected to `blob-generation-failed`, keeping already-classified failures. */
244
121
  function classifyCaptureError(cause, label) {
245
- return isCopyFailure(cause) ? cause : copyFailure("blob-generation-failed", `${label} failed.`, cause);
122
+ return require_errors.isCopyFailure(cause) ? cause : require_errors.copyFailure("blob-generation-failed", `${label} failed.`, cause);
246
123
  }
247
124
  /**
248
125
  * Decodes an image Blob and re-encodes it as PNG at `target` (or its natural
@@ -251,7 +128,7 @@ function classifyCaptureError(cause, label) {
251
128
  async function drawBlobToPng(blob, target, settings, environment, signal, label) {
252
129
  const url = environment.createObjectURL(blob);
253
130
  try {
254
- return await withDeadline(async () => {
131
+ return await require_deadline.withDeadline(async () => {
255
132
  const image = await environment.loadImage(url);
256
133
  const size = target ?? {
257
134
  width: image.width,
@@ -288,13 +165,13 @@ async function readPngSize(blob) {
288
165
  * typed `image/png`, within the pixel budget. Other raster formats are re-encoded.
289
166
  */
290
167
  async function ensurePng(blob, settings, environment, signal, label) {
291
- const actual = await sniffImageType(blob);
292
- if (actual === null) throw copyFailure("blob-generation-failed", `${label} did not produce an image.`);
168
+ const actual = await require_mime.sniffImageType(blob);
169
+ if (actual === null) throw require_errors.copyFailure("blob-generation-failed", `${label} did not produce an image.`);
293
170
  if (actual !== "image/png") return drawBlobToPng(blob, null, settings, environment(), signal, label);
294
171
  const size = await readPngSize(blob);
295
- if (size === null) throw copyFailure("blob-generation-failed", `${label} produced a truncated PNG.`);
172
+ if (size === null) throw require_errors.copyFailure("blob-generation-failed", `${label} produced a truncated PNG.`);
296
173
  assertPixelBudget(size.width, size.height, settings.maxPixels);
297
- return blob.type === "image/png" ? blob : blob.slice(0, blob.size, IMAGE_MIME_TYPE);
174
+ return blob.type === "image/png" ? blob : blob.slice(0, blob.size, require_payload.IMAGE_MIME_TYPE);
298
175
  }
299
176
  //#endregion
300
177
  //#region src/capture/svg.ts
@@ -359,7 +236,7 @@ function readSvgSize(markup) {
359
236
  /** Adds the SVG namespace when missing; `<img>` refuses to decode SVG without it. */
360
237
  function ensureSvgNamespace(markup) {
361
238
  const tag = findRootTag(markup);
362
- if (tag === null) throw copyFailure("invalid-payload", "The markup has no <svg> root element.");
239
+ if (tag === null) throw require_errors.copyFailure("invalid-payload", "The markup has no <svg> root element.");
363
240
  if (readAttribute(tag, "xmlns") !== null) return markup;
364
241
  return markup.replace(SVG_OPEN, `<svg xmlns="${SVG_NAMESPACE}"`);
365
242
  }
@@ -380,7 +257,7 @@ async function svgToPngBlob(source, options = {}) {
380
257
  let markup;
381
258
  if (typeof source === "string") markup = source;
382
259
  else {
383
- if (!isSvgElement(source)) throw copyFailure("invalid-payload", `Expected an <svg> element, got <${source.localName}>.`);
260
+ if (!isSvgElement(source)) throw require_errors.copyFailure("invalid-payload", `Expected an <svg> element, got <${source.localName}>.`);
384
261
  const rect = source.getBoundingClientRect();
385
262
  if (rect.width > 0 && rect.height > 0) intrinsic = {
386
263
  width: rect.width,
@@ -388,10 +265,10 @@ async function svgToPngBlob(source, options = {}) {
388
265
  };
389
266
  markup = environment.serializeSvg(source);
390
267
  }
391
- if (markup.length > maxLength) throw copyFailure("too-large", `The SVG markup exceeds ${String(maxLength)} characters.`);
268
+ if (markup.length > maxLength) throw require_errors.copyFailure("too-large", `The SVG markup exceeds ${String(maxLength)} characters.`);
392
269
  const prepared = ensureSvgNamespace(markup);
393
270
  const target = toPixelSize(resolveSize(intrinsic ?? readSvgSize(prepared), options.width, options.height), settings);
394
- return drawBlobToPng(new Blob([prepared], { type: SVG_MIME_TYPE }), target, settings, environment, options.signal, "SVG rasterisation");
271
+ return drawBlobToPng(new Blob([prepared], { type: require_mime.SVG_MIME_TYPE }), target, settings, environment, options.signal, "SVG rasterisation");
395
272
  }
396
273
  //#endregion
397
274
  //#region src/capture/element.ts
@@ -402,7 +279,7 @@ function decodeBase64(payload, type) {
402
279
  try {
403
280
  binary = atob(payload);
404
281
  } catch (cause) {
405
- throw copyFailure("blob-generation-failed", "The rasteriser returned malformed base64.", cause);
282
+ throw require_errors.copyFailure("blob-generation-failed", "The rasteriser returned malformed base64.", cause);
406
283
  }
407
284
  const bytes = new Uint8Array(binary.length);
408
285
  for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
@@ -412,18 +289,18 @@ function canvasToBlob(canvas) {
412
289
  return new Promise((resolve, reject) => {
413
290
  canvas.toBlob((blob) => {
414
291
  if (blob) resolve(blob);
415
- else reject(copyFailure("blob-generation-failed", "canvas.toBlob() produced nothing."));
292
+ else reject(require_errors.copyFailure("blob-generation-failed", "canvas.toBlob() produced nothing."));
416
293
  }, "image/png");
417
294
  });
418
295
  }
419
296
  const isCanvasLike = (value) => typeof value === "object" && value !== null && typeof value.toBlob === "function";
420
297
  async function toPng(output, options, settings, size, signal) {
421
298
  const environment = () => resolveCaptureEnvironment(options.environment);
422
- if (isBlob(output)) return ensurePng(output, settings, environment, signal, LABEL);
299
+ if (require_payload.isBlob(output)) return ensurePng(output, settings, environment, signal, LABEL);
423
300
  if (isCanvasLike(output)) return ensurePng(await canvasToBlob(output), settings, environment, signal, LABEL);
424
- if (typeof output !== "string") throw copyFailure("blob-generation-failed", "The rasteriser must return a Blob, a canvas or a data:image URL.");
301
+ if (typeof output !== "string") throw require_errors.copyFailure("blob-generation-failed", "The rasteriser must return a Blob, a canvas or a data:image URL.");
425
302
  const match = DATA_URL.exec(output);
426
- if (match === null) throw copyFailure("blob-generation-failed", "The rasteriser returned a string that is not a data:image URL.");
303
+ if (match === null) throw require_errors.copyFailure("blob-generation-failed", "The rasteriser returned a string that is not a data:image URL.");
427
304
  const type = String(match[1]).toLowerCase();
428
305
  const base64 = match[3] !== void 0;
429
306
  const body = output.slice(match[0].length);
@@ -434,7 +311,7 @@ async function toPng(output, options, settings, size, signal) {
434
311
  signal,
435
312
  environment: environment()
436
313
  });
437
- if (!base64) throw copyFailure("blob-generation-failed", "Raster data URLs must be base64-encoded.");
314
+ if (!base64) throw require_errors.copyFailure("blob-generation-failed", "Raster data URLs must be base64-encoded.");
438
315
  return ensurePng(decodeBase64(body, type), settings, environment, signal, LABEL);
439
316
  }
440
317
  /**
@@ -444,11 +321,11 @@ async function toPng(output, options, settings, size, signal) {
444
321
  * `timeout`, `aborted`, `blob-generation-failed`).
445
322
  */
446
323
  async function captureElement(node, options = {}) {
447
- if (!node) throw copyFailure("invalid-payload", "There is no element to capture (is the ref attached yet?).");
324
+ if (!node) throw require_errors.copyFailure("invalid-payload", "There is no element to capture (is the ref attached yet?).");
448
325
  const { rasterize } = options;
449
326
  if (!rasterize) {
450
327
  if (node.localName === "svg") return svgToPngBlob(node, options);
451
- throw copyFailure("unsupported", "Capturing HTML needs a `rasterize` function, e.g. `domToBlob` from modern-screenshot. Only <svg> works without one.");
328
+ throw require_errors.copyFailure("unsupported", "Capturing HTML needs a `rasterize` function, e.g. `domToBlob` from modern-screenshot. Only <svg> works without one.");
452
329
  }
453
330
  const settings = resolveRenderSettings(options);
454
331
  const rect = node.getBoundingClientRect();
@@ -458,7 +335,7 @@ async function captureElement(node, options = {}) {
458
335
  } : null, options.width, options.height);
459
336
  toPixelSize(size, settings);
460
337
  try {
461
- return await withDeadline(async (signal) => {
338
+ return await require_deadline.withDeadline(async (signal) => {
462
339
  return toPng(await rasterize(node, {
463
340
  scale: settings.scale,
464
341
  width: size.width,
@@ -1 +1 @@
1
- {"version":3,"file":"capture.cjs","names":[],"sources":["../src/core/errors.ts","../src/capture/environment.ts","../src/capture/options.ts","../src/core/mime.ts","../src/core/payload.ts","../src/capture/deadline.ts","../src/capture/render.ts","../src/capture/svg.ts","../src/capture/element.ts"],"sourcesContent":["import type { PasteSource } from './paste-reader';\n\n/**\n * Every way a clipboard operation can fail, as a closed union.\n *\n * `CopyError.message` is developer-facing (logs, telemetry). For user-facing\n * text use {@link describeCopyError} / {@link describePasteError}, or map\n * `type` through your own i18n layer.\n */\nexport type CopyErrorType =\n /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */\n | 'unsupported'\n /** Page is not served over HTTPS/localhost. Not retryable. */\n | 'insecure-context'\n /** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */\n | 'permission-denied'\n /** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */\n | 'not-focused'\n /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */\n | 'invalid-payload'\n /** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */\n | 'unsupported-format'\n /** A lazy image source (or capture) threw, rejected or did not produce a Blob. */\n | 'blob-generation-failed'\n /** `retry()` was called after `maxRetries` was reached. Terminal. */\n | 'max-retries-exceeded'\n /** Paste: the clipboard held nothing matching `accept`. */\n | 'no-content'\n /** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */\n | 'too-large'\n /** An operation did not settle within its deadline. Retryable. */\n | 'timeout'\n /** The caller aborted the operation through an `AbortSignal`. Not retryable. */\n | 'aborted'\n /** Anything the platform threw that we could not classify. */\n | 'unknown';\n\n/** Which clipboard direction failed; only changes developer-facing messages. */\nexport type ClipboardOperation = 'write' | 'read';\n\nexport interface CopyError {\n readonly type: CopyErrorType;\n readonly message: string;\n readonly cause?: unknown;\n}\n\nexport function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError {\n return cause === undefined ? { type, message } : { type, message, cause };\n}\n\nconst RETRYABLE_ERRORS: ReadonlySet<CopyErrorType> = /* @__PURE__ */ new Set<CopyErrorType>([\n 'permission-denied',\n 'not-focused',\n 'blob-generation-failed',\n 'timeout',\n 'unknown',\n]);\n\n/** Whether retrying the same payload could plausibly succeed. */\nexport function isRetryableError(error: CopyError): boolean {\n return RETRYABLE_ERRORS.has(error.type);\n}\n\n/**\n * Branded (not `instanceof`) so failures stay recognisable even when the core\n * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.\n */\nconst COPY_FAILURE_BRAND = Symbol.for('react-smart-copy.CopyFailure');\n\n/** Error thrown by adapters to carry a fully classified {@link CopyError}. */\nexport class CopyFailure extends Error {\n readonly copyError: CopyError;\n readonly [COPY_FAILURE_BRAND] = true;\n\n constructor(copyError: CopyError) {\n super(copyError.message);\n this.name = 'CopyFailure';\n this.copyError = copyError;\n }\n}\n\nexport function isCopyFailure(value: unknown): value is CopyFailure {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[COPY_FAILURE_BRAND] === true\n );\n}\n\n/** Shorthand for throwing a classified failure. */\nexport function copyFailure(type: CopyErrorType, message: string, cause?: unknown): CopyFailure {\n return new CopyFailure(createCopyError(type, message, cause));\n}\n\nfunction readString(value: unknown, key: string): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const field = (value as Record<string, unknown>)[key];\n return typeof field === 'string' ? field : undefined;\n}\n\n/**\n * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.\n * `operation` only tailors the developer-facing message.\n */\nexport function toCopyError(cause: unknown, operation: ClipboardOperation = 'write'): CopyError {\n if (isCopyFailure(cause)) return cause.copyError;\n\n const name = readString(cause, 'name');\n const message = readString(cause, 'message') ?? '';\n const verb = operation === 'read' ? 'read' : 'write';\n\n switch (name) {\n case 'NotAllowedError':\n return /focus/i.test(message)\n ? createCopyError('not-focused', `The document was not focused during the clipboard ${verb}.`, cause)\n : createCopyError('permission-denied', `Clipboard ${verb} permission was denied.`, cause);\n case 'SecurityError':\n return createCopyError('insecure-context', 'The clipboard is blocked in this context.', cause);\n case 'NotSupportedError':\n case 'DataError':\n return createCopyError('unsupported-format', 'The browser rejected this clipboard format.', cause);\n case 'AbortError':\n return createCopyError('aborted', `The clipboard ${verb} was aborted.`, cause);\n case 'TimeoutError':\n return createCopyError('timeout', `The clipboard ${verb} timed out.`, cause);\n default:\n return createCopyError('unknown', message || `The clipboard ${verb} failed for an unknown reason.`, cause);\n }\n}\n\nconst COPY_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Copying isn't supported in this browser.\",\n 'insecure-context': 'Copying requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while copying. Try again.',\n 'invalid-payload': 'There is nothing to copy.',\n 'unsupported-format': \"This content can't be copied in this browser.\",\n 'blob-generation-failed': \"The image couldn't be prepared for copying.\",\n 'max-retries-exceeded': 'Copying failed after several attempts.',\n 'no-content': 'There is nothing to copy.',\n 'too-large': 'This content is too large to copy.',\n timeout: 'Copying took too long. Try again.',\n aborted: 'Copying was cancelled.',\n unknown: \"Couldn't copy to the clipboard. Try again.\",\n};\n\nconst PASTE_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Pasting isn't supported in this browser.\",\n 'insecure-context': 'Pasting requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while pasting. Try again.',\n 'invalid-payload': \"The clipboard content couldn't be read.\",\n 'unsupported-format': \"This clipboard content isn't supported here.\",\n 'blob-generation-failed': \"The pasted image couldn't be read.\",\n 'max-retries-exceeded': 'Pasting failed after several attempts.',\n 'no-content': \"The clipboard doesn't contain anything that can be pasted here.\",\n 'too-large': 'The clipboard content is too large to paste.',\n timeout: 'Pasting took too long. Try again.',\n aborted: 'Pasting was cancelled.',\n unknown: \"Couldn't read the clipboard. Try again.\",\n};\n\n/** Default English, user-facing sentence for a copy error. Replace for i18n. */\nexport function describeCopyError(error: CopyError): string {\n return COPY_DESCRIPTIONS[error.type];\n}\n\n/** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */\nconst DROP_DESCRIPTIONS: Readonly<Partial<Record<CopyErrorType, string>>> = {\n 'invalid-payload': \"The dropped content couldn't be read.\",\n 'no-content': 'Nothing that was dropped can be used here.',\n 'too-large': 'The dropped content is too large.',\n unknown: \"Couldn't read the dropped content. Try again.\",\n};\n\n/**\n * Default English, user-facing sentence for a paste error. Pass the error\n * state's `source` to word drag-and-drop failures as drops. Replace for i18n.\n */\nexport function describePasteError(error: CopyError, source?: PasteSource): string {\n return (source === 'drop' ? DROP_DESCRIPTIONS[error.type] : undefined) ?? PASTE_DESCRIPTIONS[error.type];\n}\n","import { copyFailure } from '../core/errors';\n\n/** A decoded image, ready to be drawn. `source` is platform-specific (an `HTMLImageElement` in browsers). */\nexport interface DecodedImage {\n readonly source: unknown;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface PngTarget {\n /** Integer pixel size of the output. */\n readonly width: number;\n readonly height: number;\n /** CSS colour painted under the image, or `null` for transparency. */\n readonly background: string | null;\n}\n\n/**\n * Everything capture needs from the platform. The default uses the DOM;\n * inject your own for workers (OffscreenCanvas), native shells or tests.\n */\nexport interface CaptureEnvironment {\n readonly createObjectURL: (blob: Blob) => string;\n readonly revokeObjectURL: (url: string) => void;\n /** Serialises an `<svg>` element to markup. */\n readonly serializeSvg: (node: Element) => string;\n /** Decodes an image from a `blob:` or `data:` URL. */\n readonly loadImage: (url: string) => Promise<DecodedImage>;\n /** Draws the image scaled to `target` and encodes it as PNG. */\n readonly encodePng: (image: DecodedImage, target: PngTarget) => Promise<Blob>;\n}\n\nfunction loadImage(url: string): Promise<DecodedImage> {\n return new Promise((resolve, reject) => {\n const image = new Image();\n image.decoding = 'async';\n image.onload = () => {\n resolve({ source: image, width: image.naturalWidth, height: image.naturalHeight });\n };\n image.onerror = () => {\n reject(copyFailure('blob-generation-failed', 'The image could not be decoded.'));\n };\n image.src = url;\n });\n}\n\nfunction encodePng(image: DecodedImage, target: PngTarget): Promise<Blob> {\n return new Promise((resolve, reject) => {\n const canvas = document.createElement('canvas');\n canvas.width = target.width;\n canvas.height = target.height;\n const context = canvas.getContext('2d');\n if (!context) {\n reject(copyFailure('unsupported', 'Canvas 2D rendering is not available.'));\n return;\n }\n if (target.background !== null) {\n context.fillStyle = target.background;\n context.fillRect(0, 0, target.width, target.height);\n }\n context.drawImage(image.source as CanvasImageSource, 0, 0, target.width, target.height);\n // Throws SecurityError synchronously for tainted canvases; the executor turns that into a rejection.\n canvas.toBlob((blob) => {\n if (blob) resolve(blob);\n else reject(copyFailure('blob-generation-failed', 'canvas.toBlob() produced nothing (canvas too large?).'));\n }, 'image/png');\n });\n}\n\n/** The DOM-backed environment, or `null` outside a browser. */\nexport function getDefaultCaptureEnvironment(): CaptureEnvironment | null {\n if (\n typeof document === 'undefined' ||\n typeof Image !== 'function' ||\n typeof XMLSerializer !== 'function' ||\n typeof URL.createObjectURL !== 'function'\n ) {\n return null;\n }\n return {\n createObjectURL: (blob) => URL.createObjectURL(blob),\n revokeObjectURL: (url) => {\n URL.revokeObjectURL(url);\n },\n serializeSvg: (node) => new XMLSerializer().serializeToString(node),\n loadImage,\n encodePng,\n };\n}\n\nexport function resolveCaptureEnvironment(environment: CaptureEnvironment | undefined): CaptureEnvironment {\n const resolved = environment ?? getDefaultCaptureEnvironment();\n if (!resolved) {\n throw copyFailure('unsupported', 'Image capture needs a browser environment (document, Image, canvas).');\n }\n return resolved;\n}\n","import { copyFailure } from '../core/errors';\nimport type { CaptureEnvironment } from './environment';\n\nexport const DEFAULT_CAPTURE_SCALE = 2;\nexport const MAX_CAPTURE_SCALE = 10;\n/** 4096 × 4096: the canvas area limit of Safari/iOS, the strictest mainstream engine. */\nexport const DEFAULT_MAX_PIXELS = 16_777_216;\nexport const DEFAULT_CAPTURE_TIMEOUT_MS = 15_000;\n\nexport interface RenderOptions {\n /** Output width in CSS px (before `scale`). Omit to use the intrinsic size; set one side to keep the aspect ratio. */\n readonly width?: number;\n /** Output height in CSS px (before `scale`). */\n readonly height?: number;\n /** Pixel density multiplier, e.g. `window.devicePixelRatio`. Default 2 (crisp on HiDPI). Max 10. */\n readonly scale?: number;\n /** CSS colour under the image. Default `null` (transparent). */\n readonly background?: string | null;\n /** Refuse outputs larger than this many pixels (memory / DoS guard). Default 16 777 216. */\n readonly maxPixels?: number;\n /** Give up after this long. Default 15 000 ms. `Infinity` disables. */\n readonly timeoutMs?: number;\n /** Cancel the capture. */\n readonly signal?: AbortSignal;\n /** Platform hooks. Defaults to the DOM. */\n readonly environment?: CaptureEnvironment;\n}\n\nexport interface RenderSettings {\n readonly scale: number;\n readonly background: string | null;\n readonly maxPixels: number;\n readonly timeoutMs: number;\n}\n\nexport interface Size {\n readonly width: number;\n readonly height: number;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nconst isPositiveFinite = (value: number): boolean => Number.isFinite(value) && value > 0;\n\nexport function resolveRenderSettings(options: RenderOptions): RenderSettings {\n const scale = options.scale ?? DEFAULT_CAPTURE_SCALE;\n if (!isPositiveFinite(scale) || scale > MAX_CAPTURE_SCALE) {\n throw invalid(`\\`scale\\` must be > 0 and <= ${String(MAX_CAPTURE_SCALE)} (received ${String(scale)}).`);\n }\n const maxPixels = options.maxPixels ?? DEFAULT_MAX_PIXELS;\n if (!Number.isInteger(maxPixels) || maxPixels <= 0) {\n throw invalid(`\\`maxPixels\\` must be a positive integer (received ${String(maxPixels)}).`);\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_CAPTURE_TIMEOUT_MS;\n if (timeoutMs !== Infinity && !isPositiveFinite(timeoutMs)) {\n throw invalid(`\\`timeoutMs\\` must be > 0 or Infinity (received ${String(timeoutMs)}).`);\n }\n return { scale, background: options.background ?? null, maxPixels, timeoutMs };\n}\n\n/** Combines explicit `width`/`height` with an intrinsic size, keeping the aspect ratio when only one is set. */\nexport function resolveSize(intrinsic: Size | null, width: number | undefined, height: number | undefined): Size {\n for (const [name, value] of [\n ['width', width],\n ['height', height],\n ] as const) {\n if (value !== undefined && !isPositiveFinite(value)) {\n throw invalid(`\\`${name}\\` must be a positive number (received ${String(value)}).`);\n }\n }\n if (width !== undefined && height !== undefined) return { width, height };\n if (intrinsic === null) {\n throw invalid('The size to render is unknown: pass `width` and `height`, or give the source a size.');\n }\n if (width !== undefined) return { width, height: (width * intrinsic.height) / intrinsic.width };\n if (height !== undefined) return { width: (height * intrinsic.width) / intrinsic.height, height };\n return intrinsic;\n}\n\n/** Integer pixel size after scaling. Throws `too-large` past `maxPixels`. */\nexport function toPixelSize(size: Size, settings: Pick<RenderSettings, 'scale' | 'maxPixels'>): Size {\n const width = Math.max(1, Math.round(size.width * settings.scale));\n const height = Math.max(1, Math.round(size.height * settings.scale));\n assertPixelBudget(width, height, settings.maxPixels);\n return { width, height };\n}\n\nexport function assertPixelBudget(width: number, height: number, maxPixels: number): void {\n if (width * height > maxPixels) {\n throw copyFailure(\n 'too-large',\n `A ${String(width)}×${String(height)} image exceeds the ${String(maxPixels)}-pixel limit. Lower \\`scale\\` or raise \\`maxPixels\\`.`,\n );\n }\n}\n","/**\n * MIME helpers shared by paste and capture. Everything that comes from the\n * clipboard is untrusted input, so types are normalised and validated before\n * they are compared, and image types are confirmed from the bytes themselves.\n */\n\n/** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */\nconst MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\n/** SVG is XML that can carry scripts; it is never matched by a wildcard. */\nexport const SVG_MIME_TYPE = 'image/svg+xml';\n\n/** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */\nexport function normalizeMimeType(value: string): string | null {\n const separator = value.indexOf(';');\n const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();\n return MIME_SHAPE.test(base) ? base : null;\n}\n\n/** Prefix of the async Clipboard API's web custom formats (`web application/vnd.acme+json`). */\nexport const WEB_CUSTOM_FORMAT_PREFIX = 'web ';\n\n/** Whether a clipboard type is a web custom format (`web type/subtype`). */\nexport function isWebCustomFormat(type: string): boolean {\n return type.slice(0, 4).toLowerCase() === WEB_CUSTOM_FORMAT_PREFIX;\n}\n\n/**\n * Like {@link normalizeMimeType}, but also accepts web custom formats\n * (`web type/subtype`), returned as `web ` + the normalised MIME type.\n */\nexport function normalizeClipboardType(value: string): string | null {\n if (!isWebCustomFormat(value)) return normalizeMimeType(value);\n const inner = normalizeMimeType(value.slice(4));\n return inner === null ? null : WEB_CUSTOM_FORMAT_PREFIX + inner;\n}\n\n/**\n * Types a wildcard never matches, so accepting them must be explicit:\n * `image/svg+xml` (scriptable XML), web custom formats and structured `+json` types\n * (application-specific data that only the app that defined them should read).\n */\nfunction requiresExactMatch(mimeType: string): boolean {\n return mimeType === SVG_MIME_TYPE || isWebCustomFormat(mimeType) || mimeType.endsWith('+json');\n}\n\n/**\n * Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\\/*`)?\n * Wildcards never match `image/svg+xml`, web custom formats or `+json` types: those must be listed exactly.\n */\nexport function matchesMimePattern(mimeType: string, pattern: string): boolean {\n if (pattern === mimeType) return true;\n if (requiresExactMatch(mimeType)) return false;\n if (pattern === '*/*') return true;\n return pattern.endsWith('/*') && mimeType.startsWith(pattern.slice(0, -1));\n}\n\n/** Types whose clipboard data is text and is therefore surfaced as a `string`. */\nexport function isTextualMimeType(mimeType: string): boolean {\n const type = isWebCustomFormat(mimeType) ? mimeType.slice(4) : mimeType;\n return (\n type.startsWith('text/') ||\n type === SVG_MIME_TYPE ||\n type === 'application/json' ||\n type === 'application/xml' ||\n type.endsWith('+json')\n );\n}\n\n/** Raster image formats recognised from their leading bytes. */\nexport type RasterImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/bmp' | 'image/avif';\n\nconst SNIFF_BYTES = 16;\n\nfunction startsWith(bytes: Uint8Array, signature: readonly number[], offset = 0): boolean {\n return signature.every((byte, index) => bytes[offset + index] === byte);\n}\n\nconst ascii = (text: string): number[] => Array.from(text, (char) => char.charCodeAt(0));\n\nconst PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\nconst JPEG = [0xff, 0xd8, 0xff];\nconst GIF = ascii('GIF8');\nconst RIFF = ascii('RIFF');\nconst WEBP = ascii('WEBP');\nconst BMP = ascii('BM');\nconst FTYP_AVIF = ascii('ftypavif');\nconst FTYP_AVIS = ascii('ftypavis');\n\n/** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */\nexport function sniffImageBytes(bytes: Uint8Array): RasterImageMimeType | null {\n if (startsWith(bytes, PNG)) return 'image/png';\n if (startsWith(bytes, JPEG)) return 'image/jpeg';\n if (startsWith(bytes, GIF)) return 'image/gif';\n if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return 'image/webp';\n if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return 'image/avif';\n if (startsWith(bytes, BMP)) return 'image/bmp';\n return null;\n}\n\n/** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */\nexport async function sniffImageType(blob: Blob): Promise<RasterImageMimeType | null> {\n const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();\n return sniffImageBytes(new Uint8Array(head));\n}\n","import { CopyFailure, createCopyError, type CopyError } from './errors';\nimport type { OperationContext } from './machine-shared';\n\n/** The only image MIME type with reliable cross-browser clipboard write support. */\nexport const IMAGE_MIME_TYPE = 'image/png';\n\n/**\n * An image as a Blob, a promise of one, or a function producing one.\n * Prefer the function form: it is invoked synchronously inside the user\n * gesture, which Safari requires for async image generation. The browser\n * adapter always passes an `OperationContext`: stop work once\n * `context.signal` aborts (reset, superseded, unmount). Optional in the type\n * so adapters that call sources themselves keep compiling.\n */\nexport type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);\n\nexport interface TextPayload {\n readonly kind: 'text';\n readonly value: string;\n}\n\nexport interface HtmlPayload {\n readonly kind: 'html';\n readonly html: string;\n /** Required plain-text fallback for targets that don't understand HTML. */\n readonly text: string;\n}\n\nexport interface ImagePayload {\n readonly kind: 'image';\n readonly blob: BlobSource;\n}\n\nexport interface JsonPayload {\n readonly kind: 'json';\n readonly value: unknown;\n /** `true` = 2-space indent, a number = that indent, falsy = compact. */\n readonly pretty?: boolean | number;\n}\n\nexport interface MultiPayloadItem {\n /**\n * The MIME type, or a web custom format (`web application/vnd.acme+json`).\n * Web custom formats are only written by the async Clipboard API; copy and drag\n * events skip them.\n */\n readonly mimeType: string;\n readonly data: string | Blob;\n /**\n * Skip this item, instead of failing the copy, when the browser cannot write its type.\n * An optional item is only written when `ClipboardItem.supports()` confirms the type.\n * At least one item must be written.\n */\n readonly optional?: boolean;\n}\n\nexport interface MultiPayload {\n readonly kind: 'multi';\n readonly items: readonly MultiPayloadItem[];\n}\n\nexport type CopyPayload = TextPayload | HtmlPayload | ImagePayload | JsonPayload | MultiPayload;\nexport type CopyPayloadKind = CopyPayload['kind'];\n\n/** A payload, or a bare string as shorthand for `{ kind: 'text' }`. */\nexport type CopyInput = string | CopyPayload;\n\n/**\n * What `copy()` accepts. The function form is resolved synchronously at copy\n * time, so it always reads the latest value without re-rendering.\n */\nexport type CopySource = CopyInput | (() => CopyInput);\n\nexport function normalizePayload(input: CopyInput): CopyPayload {\n return typeof input === 'string' ? { kind: 'text', value: input } : input;\n}\n\nexport function isBlob(value: unknown): value is Blob {\n if (typeof Blob !== 'undefined' && value instanceof Blob) return true;\n const tag = Object.prototype.toString.call(value);\n return tag === '[object Blob]' || tag === '[object File]';\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' || typeof value === 'function') &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\nconst invalid = (message: string): CopyError => createCopyError('invalid-payload', message);\n\n/**\n * Structural validation. Typed callers can't produce most of these states,\n * but plain-JS callers and runtime data can, so the check is always on.\n */\nexport function validatePayload(payload: unknown): CopyError | null {\n if (typeof payload !== 'object' || payload === null) {\n return invalid('Copy input must be a string or a payload object.');\n }\n const candidate = payload as Record<string, unknown>;\n\n switch (candidate['kind']) {\n case 'text':\n return typeof candidate['value'] === 'string' && candidate['value'].length > 0\n ? null\n : invalid('Text payload must be a non-empty string.');\n case 'html':\n if (typeof candidate['html'] !== 'string' || candidate['html'].length === 0) {\n return invalid('HTML payload requires a non-empty `html` string.');\n }\n return typeof candidate['text'] === 'string' && candidate['text'].length > 0\n ? null\n : invalid('HTML payload requires a non-empty plain-text `text` fallback.');\n case 'image': {\n const source = candidate['blob'];\n return isBlob(source) || typeof source === 'function' || isThenable(source)\n ? null\n : invalid('Image payload requires a Blob, a Promise<Blob> or a function returning one.');\n }\n case 'json':\n return candidate['value'] === undefined ? invalid('JSON payload value is undefined.') : null;\n case 'multi': {\n const items = candidate['items'];\n if (!Array.isArray(items) || items.length === 0) {\n return invalid('Multi payload requires at least one item.');\n }\n const seen = new Set<string>();\n for (const item of items as unknown[]) {\n const entry = (typeof item === 'object' && item !== null ? item : {}) as Record<string, unknown>;\n const mimeType = entry['mimeType'];\n const data = entry['data'];\n if (typeof mimeType !== 'string' || mimeType.length === 0) {\n return invalid('Every multi item needs a non-empty `mimeType`.');\n }\n if (seen.has(mimeType)) return invalid(`Duplicate MIME type \"${mimeType}\" in multi payload.`);\n seen.add(mimeType);\n if (typeof data !== 'string' && !isBlob(data)) {\n return invalid(`Multi item \"${mimeType}\" must contain a string or a Blob.`);\n }\n }\n return null;\n }\n default:\n return invalid(`Unknown payload kind: ${String(candidate['kind'])}.`);\n }\n}\n\n/** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */\nexport function serializeJson(payload: JsonPayload): string {\n const indent =\n payload.pretty === true ? 2 : typeof payload.pretty === 'number' ? payload.pretty : undefined;\n // Typed as `string` by lib.d.ts, but returns undefined for functions, symbols and undefined.\n let text: unknown;\n try {\n text = JSON.stringify(payload.value, null, indent);\n } catch (cause) {\n throw new CopyFailure(\n createCopyError('invalid-payload', 'JSON payload could not be serialised (circular reference or BigInt?).', cause),\n );\n }\n if (typeof text !== 'string') {\n throw new CopyFailure(\n createCopyError('invalid-payload', 'JSON payload serialised to nothing (functions, symbols and undefined are not JSON).'),\n );\n }\n return text;\n}\n","import { copyFailure, type CopyFailure } from '../core/errors';\n\nexport interface DeadlineOptions {\n readonly timeoutMs: number;\n readonly signal?: AbortSignal | undefined;\n /** Used in messages: \"<label> timed out\". */\n readonly label: string;\n}\n\n/**\n * Runs `task` with a timeout and an optional caller `AbortSignal`. The task\n * receives a signal that fires on either, so cooperative work can stop early.\n * Rejects with classified `timeout` / `aborted` failures.\n */\nexport function withDeadline<T>(task: (signal: AbortSignal) => PromiseLike<T> | T, options: DeadlineOptions): Promise<T> {\n const { timeoutMs, label } = options;\n const external = options.signal;\n if (external?.aborted) {\n return Promise.reject(copyFailure('aborted', `${label} was aborted.`, external.reason));\n }\n\n const controller = new AbortController();\n return new Promise<T>((resolve, reject) => {\n const finish = (abort: boolean): void => {\n clearTimeout(timer);\n external?.removeEventListener('abort', onAbort);\n // Always signal downstream cooperative work to stop — whether we timed\n // out, were aborted, or resolved successfully. Without this, a task\n // that started a long operation keeps that operation alive after we've\n // already resolved, leaking resources until GC.\n /* c8 ignore next -- abort=false path is never used; kept for future API flexibility */\n if (abort) controller.abort();\n };\n const fail = (failure: CopyFailure): void => {\n finish(true);\n reject(failure);\n };\n const onAbort = (): void => {\n fail(copyFailure('aborted', `${label} was aborted.`, (external as AbortSignal).reason));\n };\n const timer =\n timeoutMs === Infinity\n ? undefined\n : setTimeout(() => {\n fail(copyFailure('timeout', `${label} timed out after ${String(timeoutMs)} ms.`));\n }, timeoutMs);\n external?.addEventListener('abort', onAbort, { once: true });\n\n new Promise<T>((run) => {\n run(task(controller.signal));\n }).then(\n (value) => {\n finish(true);\n resolve(value);\n },\n (cause: unknown) => {\n finish(true);\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified by the caller\n reject(cause);\n },\n );\n });\n}\n","import { copyFailure, isCopyFailure } from '../core/errors';\nimport { IMAGE_MIME_TYPE } from '../core/payload';\nimport { sniffImageType } from '../core/mime';\nimport { withDeadline } from './deadline';\nimport type { CaptureEnvironment } from './environment';\nimport { assertPixelBudget, type RenderSettings, type Size } from './options';\n\n/** Maps anything unexpected to `blob-generation-failed`, keeping already-classified failures. */\nexport function classifyCaptureError(cause: unknown, label: string): unknown {\n return isCopyFailure(cause) ? cause : copyFailure('blob-generation-failed', `${label} failed.`, cause);\n}\n\n/**\n * Decodes an image Blob and re-encodes it as PNG at `target` (or its natural\n * size), within the deadline. The object URL is always revoked.\n */\nexport async function drawBlobToPng(\n blob: Blob,\n target: Size | null,\n settings: RenderSettings,\n environment: CaptureEnvironment,\n signal: AbortSignal | undefined,\n label: string,\n): Promise<Blob> {\n const url = environment.createObjectURL(blob);\n try {\n return await withDeadline(\n async () => {\n const image = await environment.loadImage(url);\n const size = target ?? { width: image.width, height: image.height };\n assertPixelBudget(size.width, size.height, settings.maxPixels);\n return environment.encodePng(image, { ...size, background: settings.background });\n },\n { timeoutMs: settings.timeoutMs, signal, label },\n );\n } catch (cause) {\n throw classifyCaptureError(cause, label);\n } finally {\n environment.revokeObjectURL(url);\n }\n}\n\n/** Width and height from a PNG's IHDR chunk, read from the first 24 bytes only. */\nexport async function readPngSize(blob: Blob): Promise<Size | null> {\n const bytes = new Uint8Array(await blob.slice(0, 24).arrayBuffer());\n if (bytes.length < 24) return null;\n const view = new DataView(bytes.buffer);\n return { width: view.getUint32(16), height: view.getUint32(20) };\n}\n\n/**\n * Guarantees the clipboard-safe result: a real PNG (verified by its bytes),\n * typed `image/png`, within the pixel budget. Other raster formats are re-encoded.\n */\nexport async function ensurePng(\n blob: Blob,\n settings: RenderSettings,\n environment: () => CaptureEnvironment,\n signal: AbortSignal | undefined,\n label: string,\n): Promise<Blob> {\n const actual = await sniffImageType(blob);\n if (actual === null) {\n throw copyFailure('blob-generation-failed', `${label} did not produce an image.`);\n }\n if (actual !== IMAGE_MIME_TYPE) {\n return drawBlobToPng(blob, null, settings, environment(), signal, label);\n }\n const size = await readPngSize(blob);\n if (size === null) throw copyFailure('blob-generation-failed', `${label} produced a truncated PNG.`);\n assertPixelBudget(size.width, size.height, settings.maxPixels);\n return blob.type === IMAGE_MIME_TYPE ? blob : blob.slice(0, blob.size, IMAGE_MIME_TYPE);\n}\n","import { copyFailure } from '../core/errors';\nimport { SVG_MIME_TYPE } from '../core/mime';\nimport { resolveCaptureEnvironment } from './environment';\nimport { drawBlobToPng } from './render';\nimport { resolveRenderSettings, resolveSize, toPixelSize, type RenderOptions, type Size } from './options';\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n/** Refuse absurd markup before handing it to the image decoder. 10 M characters. */\nexport const DEFAULT_MAX_SVG_LENGTH = 10_000_000;\n\nexport interface SvgToPngOptions extends RenderOptions {\n /** Max markup length in characters. Default 10 000 000. */\n readonly maxLength?: number;\n}\n\n// Both patterns are linear-time: untrusted markup must not be able to trigger catastrophic backtracking.\nconst SVG_OPEN = /<svg\\b/i;\nconst LENGTH = /^(\\d+(?:\\.\\d+)?|\\.\\d+)(?:px)?$/i;\n\n/** The first `<svg …>` tag, found with two linear scans. */\nfunction findRootTag(markup: string): string | null {\n const start = markup.search(SVG_OPEN);\n if (start === -1) return null;\n const end = markup.indexOf('>', start);\n return end === -1 ? null : markup.slice(start, end + 1);\n}\n\n// Pre-compiled attribute patterns for the three attributes we ever read.\n// Compiling at module load time and with fixed literal names eliminates any\n// risk of ReDoS from runtime-constructed RegExps.\nconst ATTR_PATTERNS: Readonly<Record<string, RegExp>> = /* @__PURE__ */ Object.freeze({\n width: /\\swidth\\s*=\\s*([\"'])(.*?)\\1/i,\n height: /\\sheight\\s*=\\s*([\"'])(.*?)\\1/i,\n viewBox: /\\sviewBox\\s*=\\s*([\"'])(.*?)\\1/i,\n xmlns: /\\sxmlns\\s*=\\s*([\"'])(.*?)\\1/i,\n});\n\nfunction readAttribute(tag: string, name: keyof typeof ATTR_PATTERNS): string | null {\n const pattern = ATTR_PATTERNS[name];\n /* c8 ignore next -- TypeScript enforces name is a key of ATTR_PATTERNS; guard is for JS callers only */\n if (!pattern) return null;\n const match = pattern.exec(tag);\n return match === null ? null : String(match[2]);\n}\n\nfunction parseLength(value: string | null): number | null {\n if (value === null) return null;\n const match = LENGTH.exec(value.trim());\n const number = match ? Number(match[1]) : NaN;\n return number > 0 ? number : null;\n}\n\n/** Intrinsic size from the root tag: `width`/`height` in px, else the `viewBox`. */\nexport function readSvgSize(markup: string): Size | null {\n const tag = findRootTag(markup);\n if (tag === null) return null;\n const width = parseLength(readAttribute(tag, 'width'));\n const height = parseLength(readAttribute(tag, 'height'));\n if (width !== null && height !== null) return { width, height };\n\n const raw = readAttribute(tag, 'viewBox');\n const viewBox = raw != null ? raw.trim().split(/[\\s,]+/).map(Number) : [];\n const [, , boxWidth = NaN, boxHeight = NaN] = viewBox;\n if (viewBox.length !== 4 || !(boxWidth > 0) || !(boxHeight > 0)) return null;\n if (width !== null) return { width, height: (width * boxHeight) / boxWidth };\n if (height !== null) return { width: (height * boxWidth) / boxHeight, height };\n return { width: boxWidth, height: boxHeight };\n}\n\n/** Adds the SVG namespace when missing; `<img>` refuses to decode SVG without it. */\nexport function ensureSvgNamespace(markup: string): string {\n const tag = findRootTag(markup);\n if (tag === null) throw copyFailure('invalid-payload', 'The markup has no <svg> root element.');\n if (readAttribute(tag, 'xmlns') !== null) return markup;\n return markup.replace(SVG_OPEN, `<svg xmlns=\"${SVG_NAMESPACE}\"`);\n}\n\nconst isSvgElement = (value: Element): boolean => value.localName === 'svg';\n\n/**\n * Rasterises SVG (an `<svg>` element or markup) to a PNG Blob, ready for\n * `copy({ kind: 'image', blob })`.\n *\n * Security: the SVG is decoded as an *image*, where browsers disable scripts,\n * event handlers and external resource loading, and it is never inserted into\n * the document. Size is capped in characters and pixels.\n */\nexport async function svgToPngBlob(source: Element | string, options: SvgToPngOptions = {}): Promise<Blob> {\n const environment = resolveCaptureEnvironment(options.environment);\n const settings = resolveRenderSettings(options);\n const maxLength = options.maxLength ?? DEFAULT_MAX_SVG_LENGTH;\n\n let intrinsic: Size | null = null;\n let markup: string;\n if (typeof source === 'string') {\n markup = source;\n } else {\n if (!isSvgElement(source)) throw copyFailure('invalid-payload', `Expected an <svg> element, got <${source.localName}>.`);\n const rect = source.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) intrinsic = { width: rect.width, height: rect.height };\n markup = environment.serializeSvg(source);\n }\n\n if (markup.length > maxLength) {\n throw copyFailure('too-large', `The SVG markup exceeds ${String(maxLength)} characters.`);\n }\n const prepared = ensureSvgNamespace(markup);\n const size = resolveSize(intrinsic ?? readSvgSize(prepared), options.width, options.height);\n const target = toPixelSize(size, settings);\n\n const blob = new Blob([prepared], { type: SVG_MIME_TYPE });\n return drawBlobToPng(blob, target, settings, environment, options.signal, 'SVG rasterisation');\n}\n","import { copyFailure } from '../core/errors';\nimport type { OperationContext } from '../core/machine-shared';\nimport { SVG_MIME_TYPE } from '../core/mime';\nimport { isBlob, type ImagePayload } from '../core/payload';\nimport { withDeadline } from './deadline';\nimport { resolveCaptureEnvironment, type CaptureEnvironment } from './environment';\nimport {\n resolveRenderSettings,\n resolveSize,\n toPixelSize,\n type RenderOptions,\n type RenderSettings,\n type Size,\n} from './options';\nimport { classifyCaptureError, ensurePng } from './render';\nimport { svgToPngBlob } from './svg';\n\n/** Anything with `canvas.toBlob()`: `HTMLCanvasElement`, or a compatible object. */\nexport interface CanvasLike {\n toBlob(callback: (blob: Blob | null) => void, type?: string, quality?: number): void;\n}\n\n/**\n * What a rasteriser may return: a Blob (any raster format), a canvas, or a\n * base64 `data:image/…` URL. Network URLs are refused (never fetched).\n */\nexport type RasterizeOutput = Blob | CanvasLike | string;\n\nexport interface RasterizeContext {\n /** Pixel density to render at. */\n readonly scale: number;\n /** CSS size of the element (or the requested size). */\n readonly width: number;\n readonly height: number;\n readonly backgroundColor: string | null;\n /** Fires on timeout or caller abort: stop work early if you can. */\n readonly signal: AbortSignal;\n}\n\n/**\n * Turns a DOM node into pixels. Bring your own engine, e.g.\n * `(node, { scale }) => domToBlob(node, { scale })` from `modern-screenshot`.\n */\nexport type Rasterizer = (node: Element, context: RasterizeContext) => PromiseLike<RasterizeOutput> | RasterizeOutput;\n\nexport interface CaptureElementOptions extends RenderOptions {\n /** Required for HTML elements. `<svg>` elements are rasterised natively when omitted. */\n readonly rasterize?: Rasterizer;\n}\n\nconst LABEL = 'Element capture';\nconst DATA_URL = /^data:(image\\/[a-z0-9.+-]+)((?:;[a-z0-9-]+=[a-z0-9.+-]+)*)(;base64)?,/i;\n\nfunction decodeBase64(payload: string, type: string): Blob {\n let binary: string;\n try {\n binary = atob(payload);\n } catch (cause) {\n throw copyFailure('blob-generation-failed', 'The rasteriser returned malformed base64.', cause);\n }\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);\n return new Blob([bytes], { type });\n}\n\nfunction canvasToBlob(canvas: CanvasLike): Promise<Blob> {\n return new Promise((resolve, reject) => {\n canvas.toBlob((blob) => {\n if (blob) resolve(blob);\n else reject(copyFailure('blob-generation-failed', 'canvas.toBlob() produced nothing.'));\n }, 'image/png');\n });\n}\n\nconst isCanvasLike = (value: unknown): value is CanvasLike =>\n typeof value === 'object' && value !== null && typeof (value as { toBlob?: unknown }).toBlob === 'function';\n\nasync function toPng(\n output: unknown,\n options: CaptureElementOptions,\n settings: RenderSettings,\n size: Size,\n signal: AbortSignal,\n): Promise<Blob> {\n const environment = (): CaptureEnvironment => resolveCaptureEnvironment(options.environment);\n\n if (isBlob(output)) return ensurePng(output, settings, environment, signal, LABEL);\n if (isCanvasLike(output)) return ensurePng(await canvasToBlob(output), settings, environment, signal, LABEL);\n if (typeof output !== 'string') {\n throw copyFailure('blob-generation-failed', 'The rasteriser must return a Blob, a canvas or a data:image URL.');\n }\n\n const match = DATA_URL.exec(output);\n if (match === null) {\n throw copyFailure('blob-generation-failed', 'The rasteriser returned a string that is not a data:image URL.');\n }\n const type = String(match[1]).toLowerCase();\n const base64 = match[3] !== undefined;\n const body = output.slice(match[0].length);\n\n if (type === SVG_MIME_TYPE) {\n // e.g. modern-screenshot's domToSvg: rasterise it natively at the element's size.\n const markup = base64 ? await decodeBase64(body, type).text() : decodeURIComponent(body);\n return svgToPngBlob(markup, {\n ...settings,\n width: size.width,\n height: size.height,\n signal,\n environment: environment(),\n });\n }\n if (!base64) throw copyFailure('blob-generation-failed', 'Raster data URLs must be base64-encoded.');\n return ensurePng(decodeBase64(body, type), settings, environment, signal, LABEL);\n}\n\n/**\n * Captures an element as a PNG Blob, ready for `copy({ kind: 'image', blob })`.\n * Output is verified to be a real PNG within `maxPixels`, or a classified\n * `CopyFailure` is thrown (`invalid-payload`, `unsupported`, `too-large`,\n * `timeout`, `aborted`, `blob-generation-failed`).\n */\nexport async function captureElement(node: Element | null | undefined, options: CaptureElementOptions = {}): Promise<Blob> {\n if (!node) throw copyFailure('invalid-payload', 'There is no element to capture (is the ref attached yet?).');\n\n const { rasterize } = options;\n if (!rasterize) {\n if (node.localName === 'svg') return svgToPngBlob(node, options);\n throw copyFailure(\n 'unsupported',\n 'Capturing HTML needs a `rasterize` function, e.g. `domToBlob` from modern-screenshot. Only <svg> works without one.',\n );\n }\n\n const settings = resolveRenderSettings(options);\n const rect = node.getBoundingClientRect();\n const intrinsic = rect.width > 0 && rect.height > 0 ? { width: rect.width, height: rect.height } : null;\n const size = resolveSize(intrinsic, options.width, options.height);\n toPixelSize(size, settings); // Refuse before rendering anything.\n\n try {\n return await withDeadline(\n async (signal) => {\n const output = await rasterize(node, {\n scale: settings.scale,\n width: size.width,\n height: size.height,\n backgroundColor: settings.background,\n signal,\n });\n return toPng(output, options, settings, size, signal);\n },\n { timeoutMs: settings.timeoutMs, signal: options.signal, label: LABEL },\n );\n } catch (cause) {\n throw classifyCaptureError(cause, LABEL);\n }\n}\n\n/**\n * A lazy `BlobSource` for `copy()`. Resolving the element at click time and\n * starting inside the gesture keeps Safari happy. Rasterising stops when the\n * copy is reset or its component unmounts, or when `options.signal` aborts.\n *\n * @example copy({ kind: 'image', blob: captureSource(() => cardRef.current, { rasterize }) })\n */\nexport function captureSource(\n getNode: () => Element | null | undefined,\n options: CaptureElementOptions = {},\n): (context?: OperationContext) => Promise<Blob> {\n return (context) => {\n const a = options.signal;\n const b = context?.signal;\n if (!a || !b) {\n const signal = a ?? b;\n return captureElement(getNode(), signal ? { ...options, signal } : options);\n }\n const any = (AbortSignal as { any?: (signals: AbortSignal[]) => AbortSignal }).any;\n if (typeof any === 'function') return captureElement(getNode(), { ...options, signal: any([a, b]) });\n\n // Older browsers: forward both, and detach once settled so a long-lived\n // caller signal doesn't accumulate a listener per copy.\n const controller = new AbortController();\n const onAbortA = (): void => {\n controller.abort(a.reason);\n };\n const onAbortB = (): void => {\n controller.abort(b.reason);\n };\n if (a.aborted) onAbortA();\n else if (b.aborted) onAbortB();\n a.addEventListener('abort', onAbortA);\n b.addEventListener('abort', onAbortB);\n return captureElement(getNode(), { ...options, signal: controller.signal }).finally(() => {\n a.removeEventListener('abort', onAbortA);\n b.removeEventListener('abort', onAbortB);\n });\n };\n}\n\n/** Shorthand for `{ kind: 'image', blob: captureSource(getNode, options) }`. */\nexport function captureImage(\n getNode: () => Element | null | undefined,\n options: CaptureElementOptions = {},\n): ImagePayload {\n return { kind: 'image', blob: captureSource(getNode, options) };\n}\n"],"mappings":";;AA8CA,SAAgB,gBAAgB,MAAqB,SAAiB,OAA4B;CAChG,OAAO,UAAU,KAAA,IAAY;EAAE;EAAM;CAAQ,IAAI;EAAE;EAAM;EAAS;CAAM;AAC1E;;;;;AAmBA,MAAM,qBAAqB,OAAO,IAAI,8BAA8B;;AAGpE,IAAa,cAAb,cAAiC,MAAM;CAIrC,YAAY,WAAsB;EAChC,MAAM,UAAU,OAAO;EAHzB,KAAU,sBAAsB;EAI9B,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF;AAEA,SAAgB,cAAc,OAAsC;CAClE,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAuC,wBAAwB;AAEpE;;AAGA,SAAgB,YAAY,MAAqB,SAAiB,OAA8B;CAC9F,OAAO,IAAI,YAAY,gBAAgB,MAAM,SAAS,KAAK,CAAC;AAC9D;;;AC5DA,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,WA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AAM,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
+ {"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,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;I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M;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,3 +1,5 @@
1
+
2
+ import { c as ImagePayload, k as OperationContext } from "./chunks/payload-CcwKJ_bU.cjs";
1
3
  //#region src/capture/environment.d.ts
2
4
  /** A decoded image, ready to be drawn. `source` is platform-specific (an `HTMLImageElement` in browsers). */
3
5
  interface DecodedImage {
@@ -80,31 +82,6 @@ export declare function ensureSvgNamespace(markup: string): string;
80
82
  */
81
83
  export declare function svgToPngBlob(source: Element | string, options?: SvgToPngOptions): Promise<Blob>;
82
84
  //#endregion
83
- //#region src/core/machine-shared.d.ts
84
- /**
85
- * Passed to adapters and lazy sources as their last argument. `signal` aborts
86
- * when the operation is superseded, `reset()`, or its host unmounts, so
87
- * expensive work (rasterising, decoding) can stop early.
88
- */
89
- interface OperationContext {
90
- readonly signal: AbortSignal;
91
- }
92
- //#endregion
93
- //#region src/core/payload.d.ts
94
- /**
95
- * An image as a Blob, a promise of one, or a function producing one.
96
- * Prefer the function form: it is invoked synchronously inside the user
97
- * gesture, which Safari requires for async image generation. The browser
98
- * adapter always passes an `OperationContext`: stop work once
99
- * `context.signal` aborts (reset, superseded, unmount). Optional in the type
100
- * so adapters that call sources themselves keep compiling.
101
- */
102
- type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);
103
- interface ImagePayload {
104
- readonly kind: 'image';
105
- readonly blob: BlobSource;
106
- }
107
- //#endregion
108
85
  //#region src/capture/element.d.ts
109
86
  /** Anything with `canvas.toBlob()`: `HTMLCanvasElement`, or a compatible object. */
110
87
  interface CanvasLike {