react-smart-copy 1.17.1 → 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 +22 -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 -109
  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 +4 -93
  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 -91
  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 +5 -73
  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
@@ -0,0 +1,224 @@
1
+
2
+ import { n as copyFailure } from "./errors-9h8sdFFX.js";
3
+ import { a as matchesMimePattern, l as sniffImageType, o as normalizeClipboardType, r as isTextualMimeType, s as normalizeMimeType } from "./mime-aa-HA2dm.js";
4
+ //#region src/core/paste-reader.ts
5
+ /** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
6
+ function completePasteResult(result) {
7
+ const images = new Set(result.images);
8
+ return {
9
+ ...result,
10
+ imageFiles: result.files.filter((file) => images.has(file))
11
+ };
12
+ }
13
+ const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
14
+ const DEFAULT_PASTE_MAX_BYTES = 33554432;
15
+ const DEFAULT_PASTE_MAX_ITEMS = 32;
16
+ const SHORTHANDS = /* @__PURE__ */ new Map([
17
+ ["text", "text/plain"],
18
+ ["html", "text/html"],
19
+ ["image", "image/*"],
20
+ ["any", "*/*"]
21
+ ]);
22
+ const TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
23
+ function resolvePattern(entry) {
24
+ if (typeof entry !== "string") return null;
25
+ const shorthand = SHORTHANDS.get(entry);
26
+ if (shorthand !== void 0) return shorthand;
27
+ if (entry === "*/*") return entry;
28
+ if (entry.endsWith("/*")) {
29
+ const type = entry.slice(0, -2).toLowerCase();
30
+ return TYPE_TOKEN.test(type) ? `${type}/*` : null;
31
+ }
32
+ return normalizeClipboardType(entry);
33
+ }
34
+ function resolveLimit(value, fallback, name) {
35
+ if (value === void 0) return fallback;
36
+ if (value === Infinity || Number.isInteger(value) && value > 0) return value;
37
+ throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
38
+ }
39
+ /** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
40
+ function resolvePasteReadOptions(options = {}) {
41
+ const accept = [];
42
+ for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {
43
+ const pattern = resolvePattern(entry);
44
+ if (pattern === null) throw copyFailure("invalid-payload", `Invalid \`accept\` entry: ${JSON.stringify(entry)}.`);
45
+ if (!accept.includes(pattern)) accept.push(pattern);
46
+ }
47
+ if (accept.length === 0) throw copyFailure("invalid-payload", "`accept` must list at least one type.");
48
+ return {
49
+ accept,
50
+ maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, "maxBytes"),
51
+ maxItems: resolveLimit(options.maxItems, 32, "maxItems")
52
+ };
53
+ }
54
+ /** Whether a normalised MIME type is allowed by the resolved `accept` list. */
55
+ function isAccepted(mimeType, options) {
56
+ return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));
57
+ }
58
+ function createBudget(options) {
59
+ let bytes = 0;
60
+ let items = 0;
61
+ return { charge: (size) => {
62
+ items += 1;
63
+ bytes += size;
64
+ if (items > options.maxItems) throw copyFailure("too-large", `The paste has more than ${String(options.maxItems)} accepted items.`);
65
+ if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
66
+ } };
67
+ }
68
+ /**
69
+ * UTF-8 byte length of a string, without allocating an encoded copy.
70
+ * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.
71
+ */
72
+ function utf8ByteLength(text) {
73
+ let bytes = 0;
74
+ for (let i = 0; i < text.length; i += 1) {
75
+ const unit = text.charCodeAt(i);
76
+ if (unit < 128) bytes += 1;
77
+ else if (unit < 2048) bytes += 2;
78
+ else if (unit >= 55296 && unit <= 56319 && i + 1 < text.length && (text.charCodeAt(i + 1) & 64512) === 56320) {
79
+ bytes += 4;
80
+ i += 1;
81
+ } else bytes += 3;
82
+ }
83
+ return bytes;
84
+ }
85
+ /** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */
86
+ const sizeOf = (data) => typeof data === "string" ? utf8ByteLength(data) : data.size;
87
+ /** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
88
+ function enforcePasteLimits(entries, options) {
89
+ const budget = createBudget(options);
90
+ for (const entry of entries) budget.charge(sizeOf(entry.data));
91
+ }
92
+ /**
93
+ * Whether a drag in progress could drop anything `accept`s. Uses only what
94
+ * browsers expose before the drop (item kinds and types, never the data).
95
+ * A file whose type is not known yet (some browsers hide it while dragging)
96
+ * counts as a maybe: the drop itself is checked against `accept`.
97
+ */
98
+ function canAcceptDrag(data, options) {
99
+ const items = data.items ?? Array.from(data.types, (type) => type === "Files" ? {
100
+ kind: "file",
101
+ type: ""
102
+ } : {
103
+ kind: "string",
104
+ type
105
+ });
106
+ return Array.from(items).some(({ kind, type: raw }) => {
107
+ const file = kind === "file";
108
+ const type = normalizeClipboardType(raw);
109
+ if (type === null) return file;
110
+ return (file || isTextualMimeType(type)) && isAccepted(type, options);
111
+ });
112
+ }
113
+ /**
114
+ * Synchronously copies the accepted parts of a paste event's `DataTransfer`.
115
+ * It must run during the event: browsers empty the object afterwards.
116
+ */
117
+ function snapshotDataTransfer(data, options) {
118
+ const entries = [];
119
+ const seen = /* @__PURE__ */ new Set();
120
+ for (const raw of Array.from(data.types)) {
121
+ const type = normalizeClipboardType(raw);
122
+ if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;
123
+ seen.add(type);
124
+ const text = data.getData(raw);
125
+ if (text.length > 0) entries.push({
126
+ type,
127
+ data: text,
128
+ file: false
129
+ });
130
+ }
131
+ for (const file of Array.from(data.files ?? [])) {
132
+ const type = normalizeMimeType(file.type) ?? "application/octet-stream";
133
+ if (isAccepted(type, options)) entries.push({
134
+ type,
135
+ data: file,
136
+ file: true
137
+ });
138
+ }
139
+ return entries;
140
+ }
141
+ /**
142
+ * Reads the accepted types from `navigator.clipboard.read()` items, enforcing
143
+ * the limits *before* decoding any text so an oversized paste is never buffered twice.
144
+ */
145
+ async function collectClipboardItems(items, options, signal) {
146
+ const budget = createBudget(options);
147
+ const entries = [];
148
+ const seen = /* @__PURE__ */ new Set();
149
+ for (const item of items) for (const raw of item.types) {
150
+ const type = normalizeClipboardType(raw);
151
+ if (type === null || seen.has(type) || !isAccepted(type, options)) continue;
152
+ seen.add(type);
153
+ let blob;
154
+ try {
155
+ blob = await item.getType(raw);
156
+ } catch {
157
+ continue;
158
+ }
159
+ if (signal?.aborted) throw copyFailure("aborted", "The paste was cancelled.");
160
+ if (blob.size === 0) continue;
161
+ budget.charge(blob.size);
162
+ entries.push({
163
+ type,
164
+ data: isTextualMimeType(type) ? await blob.text() : blob,
165
+ file: false
166
+ });
167
+ }
168
+ return entries;
169
+ }
170
+ function retype(entry, data, type) {
171
+ if (entry.file) {
172
+ const file = data;
173
+ return new File([file], file.name, {
174
+ type,
175
+ lastModified: file.lastModified
176
+ });
177
+ }
178
+ return data.slice(0, data.size, type);
179
+ }
180
+ /**
181
+ * Verifies image bytes, then builds the result. Blobs that claim to be images
182
+ * but aren't (or whose real format is not accepted) are dropped. Throws
183
+ * `no-content` when nothing survives.
184
+ */
185
+ async function finalizePaste(entries, source, options) {
186
+ const items = [];
187
+ const images = [];
188
+ const files = [];
189
+ let text = null;
190
+ let html = null;
191
+ for (const entry of entries) {
192
+ let { type, data } = entry;
193
+ if (typeof data === "string") {
194
+ if (type === "text/plain") text = data;
195
+ else if (type === "text/html") html = data;
196
+ } else if (type.startsWith("image/")) {
197
+ const actual = await sniffImageType(data);
198
+ if (actual === null || !isAccepted(actual, options)) continue;
199
+ if (actual !== type) {
200
+ data = retype(entry, data, actual);
201
+ type = actual;
202
+ }
203
+ images.push(data);
204
+ }
205
+ if (entry.file) files.push(data);
206
+ items.push({
207
+ type,
208
+ data
209
+ });
210
+ }
211
+ if (items.length === 0) throw copyFailure("no-content", "The content holds nothing that matches `accept`.");
212
+ return {
213
+ source,
214
+ items,
215
+ text,
216
+ html,
217
+ images,
218
+ files
219
+ };
220
+ }
221
+ //#endregion
222
+ export { collectClipboardItems as a, finalizePaste as c, utf8ByteLength as d, canAcceptDrag as i, resolvePasteReadOptions as l, DEFAULT_PASTE_MAX_BYTES as n, completePasteResult as o, DEFAULT_PASTE_MAX_ITEMS as r, enforcePasteLimits as s, DEFAULT_PASTE_ACCEPT as t, snapshotDataTransfer as u };
223
+
224
+ //# sourceMappingURL=paste-reader-D9i7yMXF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paste-reader-D9i7yMXF.js","names":[],"sources":["../../src/core/paste-reader.ts"],"sourcesContent":["import { copyFailure } from './errors';\nimport { isTextualMimeType, matchesMimePattern, normalizeClipboardType, normalizeMimeType, sniffImageType } from './mime';\n\n/* ------------------------------------------------------------------ Types */\n\n/** Friendly names for the common cases. */\nexport type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';\n\n/**\n * What a paste may contain, in any order: a shorthand, an exact MIME type\n * (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a\n * wildcard (`'image/*'`, `'*\\/*'`). `image/svg+xml` (scriptable XML), web custom\n * formats and `+json` types are only accepted when listed exactly.\n */\nexport type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;\n\nexport interface PasteLimits {\n /**\n * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as\n * they would be encoded, matching `Blob.size`, so every paste path counts the same way.\n * Default 32 MiB.\n */\n readonly maxBytes?: number;\n /** Max number of accepted items (types + files). Default 32. */\n readonly maxItems?: number;\n}\n\nexport interface PasteReadOptions extends PasteLimits {\n /** Default `['text']` (plain text only): the safest choice. */\n readonly accept?: readonly PasteAccept[];\n}\n\n/** Validated, normalised options that adapters receive. */\nexport interface ResolvedPasteReadOptions {\n /** Normalised patterns: `type/subtype`, `type/*` or `*\\/*`. */\n readonly accept: readonly string[];\n readonly maxBytes: number;\n readonly maxItems: number;\n}\n\n/** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */\nexport type PasteSource = 'clipboard' | 'event' | 'drop';\n\n/** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */\nexport interface PasteItem {\n readonly type: string;\n readonly data: string | Blob;\n}\n\n/**\n * Everything the paste produced. Treat all of it as untrusted user input:\n * in particular never inject `html` into the DOM without sanitising it.\n */\nexport interface PasteResult {\n readonly source: PasteSource;\n /** Every accepted entry, in clipboard order. */\n readonly items: readonly PasteItem[];\n /** `text/plain`, when accepted and present. */\n readonly text: string | null;\n /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */\n readonly html: string | null;\n /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */\n readonly images: readonly Blob[];\n /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */\n readonly files: readonly File[];\n /**\n * The entries of `files` that are also in `images`: verified image files, keeping their\n * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.\n */\n readonly imageFiles: readonly File[];\n}\n\n/** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */\nexport type PasteReadResult = Omit<PasteResult, 'imageFiles'>;\n\n/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */\nexport function completePasteResult(result: PasteReadResult): PasteResult {\n const images = new Set<Blob>(result.images);\n return { ...result, imageFiles: result.files.filter((file) => images.has(file)) };\n}\n\n/* -------------------------------------------------------- Option handling */\n\nexport const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[] = /* @__PURE__ */ Object.freeze(['text'] as const);\nexport const DEFAULT_PASTE_MAX_BYTES = 32 * 1024 * 1024;\nexport const DEFAULT_PASTE_MAX_ITEMS = 32;\n\nconst SHORTHANDS: ReadonlyMap<string, string> = /* @__PURE__ */ new Map([\n ['text', 'text/plain'],\n ['html', 'text/html'],\n ['image', 'image/*'],\n ['any', '*/*'],\n]);\n\nconst TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\nfunction resolvePattern(entry: unknown): string | null {\n if (typeof entry !== 'string') return null;\n const shorthand = SHORTHANDS.get(entry);\n if (shorthand !== undefined) return shorthand;\n if (entry === '*/*') return entry;\n if (entry.endsWith('/*')) {\n const type = entry.slice(0, -2).toLowerCase();\n return TYPE_TOKEN.test(type) ? `${type}/*` : null;\n }\n return normalizeClipboardType(entry);\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\n/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */\nexport function resolvePasteReadOptions(options: PasteReadOptions = {}): ResolvedPasteReadOptions {\n const accept: string[] = [];\n for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {\n const pattern = resolvePattern(entry);\n if (pattern === null) throw copyFailure('invalid-payload', `Invalid \\`accept\\` entry: ${JSON.stringify(entry)}.`);\n if (!accept.includes(pattern)) accept.push(pattern);\n }\n if (accept.length === 0) throw copyFailure('invalid-payload', '`accept` must list at least one type.');\n return {\n accept,\n maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, 'maxBytes'),\n maxItems: resolveLimit(options.maxItems, DEFAULT_PASTE_MAX_ITEMS, 'maxItems'),\n };\n}\n\n/** Whether a normalised MIME type is allowed by the resolved `accept` list. */\nexport function isAccepted(mimeType: string, options: ResolvedPasteReadOptions): boolean {\n return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));\n}\n\n/* -------------------------------------------------------------- Entries */\n\n/** An accepted, not-yet-verified entry. */\nexport interface PasteEntry {\n readonly type: string;\n readonly data: string | Blob;\n /** Came from `DataTransfer.files`, i.e. `data` is a `File`. */\n readonly file: boolean;\n}\n\ninterface Budget {\n readonly charge: (size: number) => void;\n}\n\nfunction createBudget(options: ResolvedPasteReadOptions): Budget {\n let bytes = 0;\n let items = 0;\n return {\n charge: (size) => {\n items += 1;\n bytes += size;\n if (items > options.maxItems) {\n throw copyFailure('too-large', `The paste has more than ${String(options.maxItems)} accepted items.`);\n }\n if (bytes > options.maxBytes) {\n throw copyFailure('too-large', `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);\n }\n },\n };\n}\n\n/**\n * UTF-8 byte length of a string, without allocating an encoded copy.\n * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.\n */\nexport function utf8ByteLength(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i += 1) {\n const unit = text.charCodeAt(i);\n if (unit < 0x80) bytes += 1;\n else if (unit < 0x800) bytes += 2;\n else if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n bytes += 4;\n i += 1;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */\nconst sizeOf = (data: string | Blob): number => (typeof data === 'string' ? utf8ByteLength(data) : data.size);\n\n/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */\nexport function enforcePasteLimits(entries: readonly PasteEntry[], options: ResolvedPasteReadOptions): void {\n const budget = createBudget(options);\n for (const entry of entries) budget.charge(sizeOf(entry.data));\n}\n\n/** Structural view of a `DataTransferItem`: only what is readable while dragging. */\nexport interface DataTransferItemLike {\n /** `'string'` or `'file'`. */\n readonly kind: string;\n readonly type: string;\n}\n\n/** Structural view of `DataTransfer` (paste and drop events). */\nexport interface DataTransferLike {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n readonly files?: ArrayLike<File> | null;\n readonly items?: ArrayLike<DataTransferItemLike> | null;\n}\n\n/**\n * Whether a drag in progress could drop anything `accept`s. Uses only what\n * browsers expose before the drop (item kinds and types, never the data).\n * A file whose type is not known yet (some browsers hide it while dragging)\n * counts as a maybe: the drop itself is checked against `accept`.\n */\nexport function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean {\n // Without an item list, a file is only known as the type \"Files\": treat it as an untyped file.\n const items = data.items ?? Array.from(data.types, (type) => (type === 'Files' ? { kind: 'file', type: '' } : { kind: 'string', type }));\n return Array.from(items).some(({ kind, type: raw }) => {\n const file = kind === 'file';\n const type = normalizeClipboardType(raw);\n if (type === null) return file;\n return (file || isTextualMimeType(type)) && isAccepted(type, options);\n });\n}\n\n/**\n * Synchronously copies the accepted parts of a paste event's `DataTransfer`.\n * It must run during the event: browsers empty the object afterwards.\n */\nexport function snapshotDataTransfer(data: DataTransferLike, options: ResolvedPasteReadOptions): PasteEntry[] {\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const raw of Array.from(data.types)) {\n const type = normalizeClipboardType(raw);\n // Binary types are delivered through `files`; `getData` only returns strings.\n if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n const text = data.getData(raw);\n if (text.length > 0) entries.push({ type, data: text, file: false });\n }\n\n for (const file of Array.from(data.files ?? [])) {\n const type = normalizeMimeType(file.type) ?? 'application/octet-stream';\n if (isAccepted(type, options)) entries.push({ type, data: file, file: true });\n }\n\n return entries;\n}\n\n/** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */\nexport interface ClipboardItemLike {\n readonly types: readonly string[];\n getType(type: string): Promise<Blob>;\n}\n\n/**\n * Reads the accepted types from `navigator.clipboard.read()` items, enforcing\n * the limits *before* decoding any text so an oversized paste is never buffered twice.\n */\nexport async function collectClipboardItems(\n items: readonly ClipboardItemLike[],\n options: ResolvedPasteReadOptions,\n signal?: AbortSignal,\n): Promise<PasteEntry[]> {\n const budget = createBudget(options);\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const item of items) {\n for (const raw of item.types) {\n const type = normalizeClipboardType(raw);\n if (type === null || seen.has(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n\n let blob: Blob;\n try {\n blob = await item.getType(raw);\n } catch {\n // Chromium lists some types it then refuses to hand over; skip them, don't fail the paste.\n continue;\n }\n // Cancelled (reset, superseded, unmounted) while waiting: don't decode the rest.\n if (signal?.aborted) throw copyFailure('aborted', 'The paste was cancelled.');\n if (blob.size === 0) continue;\n budget.charge(blob.size);\n entries.push({ type, data: isTextualMimeType(type) ? await blob.text() : blob, file: false });\n }\n }\n return entries;\n}\n\n/* ------------------------------------------------------------ Finalising */\n\nfunction retype(entry: PasteEntry, data: Blob, type: string): Blob {\n if (entry.file) {\n const file = data as File;\n return new File([file], file.name, { type, lastModified: file.lastModified });\n }\n return data.slice(0, data.size, type);\n}\n\n/**\n * Verifies image bytes, then builds the result. Blobs that claim to be images\n * but aren't (or whose real format is not accepted) are dropped. Throws\n * `no-content` when nothing survives.\n */\nexport async function finalizePaste(\n entries: readonly PasteEntry[],\n source: PasteSource,\n options: ResolvedPasteReadOptions,\n): Promise<PasteReadResult> {\n const items: PasteItem[] = [];\n const images: Blob[] = [];\n const files: File[] = [];\n let text: string | null = null;\n let html: string | null = null;\n\n for (const entry of entries) {\n let { type, data } = entry;\n\n if (typeof data === 'string') {\n // Types are de-duplicated upstream, so each of these is seen at most once.\n if (type === 'text/plain') text = data;\n else if (type === 'text/html') html = data;\n } else if (type.startsWith('image/')) {\n const actual = await sniffImageType(data);\n if (actual === null || !isAccepted(actual, options)) continue;\n if (actual !== type) {\n data = retype(entry, data, actual);\n type = actual;\n }\n images.push(data);\n }\n\n if (entry.file) files.push(data as File);\n items.push({ type, data });\n }\n\n if (items.length === 0) {\n throw copyFailure('no-content', 'The content holds nothing that matches `accept`.');\n }\n return { source, items, text, html, images, files };\n}\n"],"mappings":";;;;;AA4EA,SAAgB,oBAAoB,QAAsC;CACxE,MAAM,SAAS,IAAI,IAAU,OAAO,MAAM;CAC1C,OAAO;EAAE,GAAG;EAAQ,YAAY,OAAO,MAAM,QAAQ,SAAS,OAAO,IAAI,IAAI,CAAC;CAAE;AAClF;AAIA,MAAa,uBAA+D,uBAAO,OAAO,CAAC,MAAM,CAAU;AAC3G,MAAa,0BAA0B;AACvC,MAAa,0BAA0B;AAEvC,MAAM,6BAA0D,IAAI,IAAI;CACtE,CAAC,QAAQ,YAAY;CACrB,CAAC,QAAQ,WAAW;CACpB,CAAC,SAAS,SAAS;CACnB,CAAC,OAAO,KAAK;AACf,CAAC;AAED,MAAM,aAAa;AAEnB,SAAS,eAAe,OAA+B;CACrD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,MAAM,YAAY,WAAW,IAAI,KAAK;CACtC,IAAI,cAAc,KAAA,GAAW,OAAO;CACpC,IAAI,UAAU,OAAO,OAAO;CAC5B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AI,MAAM,MAAM;EACd,MAAM,OAAO;EACb,OAAO,IAAI,KAAK,CAAC,IAAI,GAAG,KAAK,MAAM;GAAE;GAAM,cAAc,KAAK;EAAa,CAAC;CAC9E;CACA,OAAO,KAAK,MAAM,GAAG,KAAK,MAAM,IAAI;AACtC;;;;;;AAOA,eAAsB,cACpB,SACA,QACA,SAC0B;CAC1B,MAAM,QAAqB,CAAC;CAC5B,MAAM,SAAiB,CAAC;CACxB,MAAM,QAAgB,CAAC;CACvB,IAAI,OAAsB;CAC1B,IAAI,OAAsB;CAE1B,KAAK,MAAM,SAAS,SAAS;EAC3B,IAAI,EAAE,MAAM,SAAS;EAErB,IAAI,OAAO,SAAS,UAAU;GAE5B,IAAI,SAAS,cAAc,OAAO;QAC7B,IAAI,SAAS,aAAa,OAAO;EACxC,OAAO,IAAI,KAAK,WAAW,QAAQ,GAAG;GACpC,MAAM,SAAS,MAAM,eAAe,IAAI;GACxC,IAAI,WAAW,QAAQ,CAAC,WAAW,QAAQ,OAAO,GAAG;GACrD,IAAI,WAAW,MAAM;IACnB,OAAO,OAAO,OAAO,MAAM,MAAM;IACjC,OAAO;GACT;GACA,OAAO,KAAK,IAAI;EAClB;EAEA,IAAI,MAAM,MAAM,MAAM,KAAK,IAAY;EACvC,MAAM,KAAK;GAAE;GAAM;EAAK,CAAC;CAC3B;CAEA,IAAI,MAAM,WAAW,GACnB,MAAM,YAAY,cAAc,kDAAkD;CAEpF,OAAO;EAAE;EAAQ;EAAO;EAAM;EAAM;EAAQ;CAAM;AACpD"}
@@ -0,0 +1,96 @@
1
+
2
+ //#region src/core/paste-reader.d.ts
3
+ /** Friendly names for the common cases. */
4
+ type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';
5
+ /**
6
+ * What a paste may contain, in any order: a shorthand, an exact MIME type
7
+ * (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a
8
+ * wildcard (`'image/*'`, `'*\/*'`). `image/svg+xml` (scriptable XML), web custom
9
+ * formats and `+json` types are only accepted when listed exactly.
10
+ */
11
+ type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;
12
+ interface PasteLimits {
13
+ /**
14
+ * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as
15
+ * they would be encoded, matching `Blob.size`, so every paste path counts the same way.
16
+ * Default 32 MiB.
17
+ */
18
+ readonly maxBytes?: number;
19
+ /** Max number of accepted items (types + files). Default 32. */
20
+ readonly maxItems?: number;
21
+ }
22
+ interface PasteReadOptions extends PasteLimits {
23
+ /** Default `['text']` (plain text only): the safest choice. */
24
+ readonly accept?: readonly PasteAccept[];
25
+ }
26
+ /** Validated, normalised options that adapters receive. */
27
+ interface ResolvedPasteReadOptions {
28
+ /** Normalised patterns: `type/subtype`, `type/*` or `*\/*`. */
29
+ readonly accept: readonly string[];
30
+ readonly maxBytes: number;
31
+ readonly maxItems: number;
32
+ }
33
+ /** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */
34
+ type PasteSource = 'clipboard' | 'event' | 'drop';
35
+ /** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */
36
+ interface PasteItem {
37
+ readonly type: string;
38
+ readonly data: string | Blob;
39
+ }
40
+ /**
41
+ * Everything the paste produced. Treat all of it as untrusted user input:
42
+ * in particular never inject `html` into the DOM without sanitising it.
43
+ */
44
+ interface PasteResult {
45
+ readonly source: PasteSource;
46
+ /** Every accepted entry, in clipboard order. */
47
+ readonly items: readonly PasteItem[];
48
+ /** `text/plain`, when accepted and present. */
49
+ readonly text: string | null;
50
+ /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */
51
+ readonly html: string | null;
52
+ /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */
53
+ readonly images: readonly Blob[];
54
+ /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */
55
+ readonly files: readonly File[];
56
+ /**
57
+ * The entries of `files` that are also in `images`: verified image files, keeping their
58
+ * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.
59
+ */
60
+ readonly imageFiles: readonly File[];
61
+ }
62
+ /** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */
63
+ type PasteReadResult = Omit<PasteResult, 'imageFiles'>;
64
+ declare const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[];
65
+ declare const DEFAULT_PASTE_MAX_BYTES: number;
66
+ declare const DEFAULT_PASTE_MAX_ITEMS = 32;
67
+ /** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
68
+ declare function resolvePasteReadOptions(options?: PasteReadOptions): ResolvedPasteReadOptions;
69
+ /** Structural view of a `DataTransferItem`: only what is readable while dragging. */
70
+ interface DataTransferItemLike {
71
+ /** `'string'` or `'file'`. */
72
+ readonly kind: string;
73
+ readonly type: string;
74
+ }
75
+ /** Structural view of `DataTransfer` (paste and drop events). */
76
+ interface DataTransferLike {
77
+ readonly types: ArrayLike<string>;
78
+ getData(format: string): string;
79
+ readonly files?: ArrayLike<File> | null;
80
+ readonly items?: ArrayLike<DataTransferItemLike> | null;
81
+ }
82
+ /**
83
+ * Whether a drag in progress could drop anything `accept`s. Uses only what
84
+ * browsers expose before the drop (item kinds and types, never the data).
85
+ * A file whose type is not known yet (some browsers hide it while dragging)
86
+ * counts as a maybe: the drop itself is checked against `accept`.
87
+ */
88
+ declare function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean;
89
+ /** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */
90
+ interface ClipboardItemLike {
91
+ readonly types: readonly string[];
92
+ getType(type: string): Promise<Blob>;
93
+ }
94
+ //#endregion
95
+ export { resolvePasteReadOptions as _, DataTransferItemLike as a, PasteAcceptShorthand as c, PasteReadOptions as d, PasteReadResult as f, canAcceptDrag as g, ResolvedPasteReadOptions as h, DEFAULT_PASTE_MAX_ITEMS as i, PasteItem as l, PasteSource as m, DEFAULT_PASTE_ACCEPT as n, DataTransferLike as o, PasteResult as p, DEFAULT_PASTE_MAX_BYTES as r, PasteAccept as s, ClipboardItemLike as t, PasteLimits as u };
96
+ //# sourceMappingURL=paste-reader-DcXnRWQr.d.cts.map
@@ -0,0 +1,96 @@
1
+
2
+ //#region src/core/paste-reader.d.ts
3
+ /** Friendly names for the common cases. */
4
+ type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';
5
+ /**
6
+ * What a paste may contain, in any order: a shorthand, an exact MIME type
7
+ * (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a
8
+ * wildcard (`'image/*'`, `'*\/*'`). `image/svg+xml` (scriptable XML), web custom
9
+ * formats and `+json` types are only accepted when listed exactly.
10
+ */
11
+ type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;
12
+ interface PasteLimits {
13
+ /**
14
+ * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as
15
+ * they would be encoded, matching `Blob.size`, so every paste path counts the same way.
16
+ * Default 32 MiB.
17
+ */
18
+ readonly maxBytes?: number;
19
+ /** Max number of accepted items (types + files). Default 32. */
20
+ readonly maxItems?: number;
21
+ }
22
+ interface PasteReadOptions extends PasteLimits {
23
+ /** Default `['text']` (plain text only): the safest choice. */
24
+ readonly accept?: readonly PasteAccept[];
25
+ }
26
+ /** Validated, normalised options that adapters receive. */
27
+ interface ResolvedPasteReadOptions {
28
+ /** Normalised patterns: `type/subtype`, `type/*` or `*\/*`. */
29
+ readonly accept: readonly string[];
30
+ readonly maxBytes: number;
31
+ readonly maxItems: number;
32
+ }
33
+ /** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */
34
+ type PasteSource = 'clipboard' | 'event' | 'drop';
35
+ /** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */
36
+ interface PasteItem {
37
+ readonly type: string;
38
+ readonly data: string | Blob;
39
+ }
40
+ /**
41
+ * Everything the paste produced. Treat all of it as untrusted user input:
42
+ * in particular never inject `html` into the DOM without sanitising it.
43
+ */
44
+ interface PasteResult {
45
+ readonly source: PasteSource;
46
+ /** Every accepted entry, in clipboard order. */
47
+ readonly items: readonly PasteItem[];
48
+ /** `text/plain`, when accepted and present. */
49
+ readonly text: string | null;
50
+ /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */
51
+ readonly html: string | null;
52
+ /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */
53
+ readonly images: readonly Blob[];
54
+ /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */
55
+ readonly files: readonly File[];
56
+ /**
57
+ * The entries of `files` that are also in `images`: verified image files, keeping their
58
+ * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.
59
+ */
60
+ readonly imageFiles: readonly File[];
61
+ }
62
+ /** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */
63
+ type PasteReadResult = Omit<PasteResult, 'imageFiles'>;
64
+ declare const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[];
65
+ declare const DEFAULT_PASTE_MAX_BYTES: number;
66
+ declare const DEFAULT_PASTE_MAX_ITEMS = 32;
67
+ /** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
68
+ declare function resolvePasteReadOptions(options?: PasteReadOptions): ResolvedPasteReadOptions;
69
+ /** Structural view of a `DataTransferItem`: only what is readable while dragging. */
70
+ interface DataTransferItemLike {
71
+ /** `'string'` or `'file'`. */
72
+ readonly kind: string;
73
+ readonly type: string;
74
+ }
75
+ /** Structural view of `DataTransfer` (paste and drop events). */
76
+ interface DataTransferLike {
77
+ readonly types: ArrayLike<string>;
78
+ getData(format: string): string;
79
+ readonly files?: ArrayLike<File> | null;
80
+ readonly items?: ArrayLike<DataTransferItemLike> | null;
81
+ }
82
+ /**
83
+ * Whether a drag in progress could drop anything `accept`s. Uses only what
84
+ * browsers expose before the drop (item kinds and types, never the data).
85
+ * A file whose type is not known yet (some browsers hide it while dragging)
86
+ * counts as a maybe: the drop itself is checked against `accept`.
87
+ */
88
+ declare function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean;
89
+ /** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */
90
+ interface ClipboardItemLike {
91
+ readonly types: readonly string[];
92
+ getType(type: string): Promise<Blob>;
93
+ }
94
+ //#endregion
95
+ export { resolvePasteReadOptions as _, DataTransferItemLike as a, PasteAcceptShorthand as c, PasteReadOptions as d, PasteReadResult as f, canAcceptDrag as g, ResolvedPasteReadOptions as h, DEFAULT_PASTE_MAX_ITEMS as i, PasteItem as l, PasteSource as m, DEFAULT_PASTE_ACCEPT as n, DataTransferLike as o, PasteResult as p, DEFAULT_PASTE_MAX_BYTES as r, PasteAccept as s, ClipboardItemLike as t, PasteLimits as u };
96
+ //# sourceMappingURL=paste-reader-DcXnRWQr.d.ts.map
@@ -0,0 +1,100 @@
1
+
2
+ const require_errors = require("./errors-BwOF6T_M.cjs");
3
+ //#region src/core/payload.ts
4
+ /** The only image MIME type with reliable cross-browser clipboard write support. */
5
+ const IMAGE_MIME_TYPE = "image/png";
6
+ function normalizePayload(input) {
7
+ return typeof input === "string" ? {
8
+ kind: "text",
9
+ value: input
10
+ } : input;
11
+ }
12
+ function isBlob(value) {
13
+ if (typeof Blob !== "undefined" && value instanceof Blob) return true;
14
+ const tag = Object.prototype.toString.call(value);
15
+ return tag === "[object Blob]" || tag === "[object File]";
16
+ }
17
+ function isThenable(value) {
18
+ return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
19
+ }
20
+ const invalid = (message) => require_errors.createCopyError("invalid-payload", message);
21
+ /**
22
+ * Structural validation. Typed callers can't produce most of these states,
23
+ * but plain-JS callers and runtime data can, so the check is always on.
24
+ */
25
+ function validatePayload(payload) {
26
+ if (typeof payload !== "object" || payload === null) return invalid("Copy input must be a string or a payload object.");
27
+ const candidate = payload;
28
+ switch (candidate["kind"]) {
29
+ case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid("Text payload must be a non-empty string.");
30
+ case "html":
31
+ if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid("HTML payload requires a non-empty `html` string.");
32
+ return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid("HTML payload requires a non-empty plain-text `text` fallback.");
33
+ case "image": {
34
+ const source = candidate["blob"];
35
+ return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
36
+ }
37
+ case "json": return candidate["value"] === void 0 ? invalid("JSON payload value is undefined.") : null;
38
+ case "multi": {
39
+ const items = candidate["items"];
40
+ if (!Array.isArray(items) || items.length === 0) return invalid("Multi payload requires at least one item.");
41
+ const seen = /* @__PURE__ */ new Set();
42
+ for (const item of items) {
43
+ const entry = typeof item === "object" && item !== null ? item : {};
44
+ const mimeType = entry["mimeType"];
45
+ const data = entry["data"];
46
+ if (typeof mimeType !== "string" || mimeType.length === 0) return invalid("Every multi item needs a non-empty `mimeType`.");
47
+ if (seen.has(mimeType)) return invalid(`Duplicate MIME type "${mimeType}" in multi payload.`);
48
+ seen.add(mimeType);
49
+ if (typeof data !== "string" && !isBlob(data)) return invalid(`Multi item "${mimeType}" must contain a string or a Blob.`);
50
+ }
51
+ return null;
52
+ }
53
+ default: return invalid(`Unknown payload kind: ${String(candidate["kind"])}.`);
54
+ }
55
+ }
56
+ /** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */
57
+ function serializeJson(payload) {
58
+ const indent = payload.pretty === true ? 2 : typeof payload.pretty === "number" ? payload.pretty : void 0;
59
+ let text;
60
+ try {
61
+ text = JSON.stringify(payload.value, null, indent);
62
+ } catch (cause) {
63
+ throw new require_errors.CopyFailure(require_errors.createCopyError("invalid-payload", "JSON payload could not be serialised (circular reference or BigInt?).", cause));
64
+ }
65
+ if (typeof text !== "string") throw new require_errors.CopyFailure(require_errors.createCopyError("invalid-payload", "JSON payload serialised to nothing (functions, symbols and undefined are not JSON)."));
66
+ return text;
67
+ }
68
+ //#endregion
69
+ Object.defineProperty(exports, "IMAGE_MIME_TYPE", {
70
+ enumerable: true,
71
+ get: function() {
72
+ return IMAGE_MIME_TYPE;
73
+ }
74
+ });
75
+ Object.defineProperty(exports, "isBlob", {
76
+ enumerable: true,
77
+ get: function() {
78
+ return isBlob;
79
+ }
80
+ });
81
+ Object.defineProperty(exports, "normalizePayload", {
82
+ enumerable: true,
83
+ get: function() {
84
+ return normalizePayload;
85
+ }
86
+ });
87
+ Object.defineProperty(exports, "serializeJson", {
88
+ enumerable: true,
89
+ get: function() {
90
+ return serializeJson;
91
+ }
92
+ });
93
+ Object.defineProperty(exports, "validatePayload", {
94
+ enumerable: true,
95
+ get: function() {
96
+ return validatePayload;
97
+ }
98
+ });
99
+
100
+ //# sourceMappingURL=payload-CUymxwim.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payload-CUymxwim.cjs","names":["createCopyError","CopyFailure"],"sources":["../../src/core/payload.ts"],"sourcesContent":["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"],"mappings":";;;;AAIA,MAAa,kBAAkB;AAqE/B,SAAgB,iBAAiB,OAA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