react-smart-copy 1.14.1 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/share.cjs ADDED
@@ -0,0 +1,641 @@
1
+ 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
+ function readString(value, key) {
35
+ if (typeof value !== "object" || value === null) return void 0;
36
+ const field = value[key];
37
+ return typeof field === "string" ? field : void 0;
38
+ }
39
+ /**
40
+ * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.
41
+ * `operation` only tailors the developer-facing message.
42
+ */
43
+ function toCopyError(cause, operation = "write") {
44
+ if (isCopyFailure(cause)) return cause.copyError;
45
+ const name = readString(cause, "name");
46
+ const message = readString(cause, "message") ?? "";
47
+ const verb = operation === "read" ? "read" : "write";
48
+ switch (name) {
49
+ case "NotAllowedError": return /focus/i.test(message) ? createCopyError("not-focused", `The document was not focused during the clipboard ${verb}.`, cause) : createCopyError("permission-denied", `Clipboard ${verb} permission was denied.`, cause);
50
+ case "SecurityError": return createCopyError("insecure-context", "The clipboard is blocked in this context.", cause);
51
+ case "NotSupportedError":
52
+ case "DataError": return createCopyError("unsupported-format", "The browser rejected this clipboard format.", cause);
53
+ case "AbortError": return createCopyError("aborted", `The clipboard ${verb} was aborted.`, cause);
54
+ case "TimeoutError": return createCopyError("timeout", `The clipboard ${verb} timed out.`, cause);
55
+ default: return createCopyError("unknown", message || `The clipboard ${verb} failed for an unknown reason.`, cause);
56
+ }
57
+ }
58
+ const COPY_DESCRIPTIONS = {
59
+ unsupported: "Copying isn't supported in this browser.",
60
+ "insecure-context": "Copying requires a secure (HTTPS) connection.",
61
+ "permission-denied": "Clipboard access was blocked. Allow it and try again.",
62
+ "not-focused": "The page lost focus while copying. Try again.",
63
+ "invalid-payload": "There is nothing to copy.",
64
+ "unsupported-format": "This content can't be copied in this browser.",
65
+ "blob-generation-failed": "The image couldn't be prepared for copying.",
66
+ "max-retries-exceeded": "Copying failed after several attempts.",
67
+ "no-content": "There is nothing to copy.",
68
+ "too-large": "This content is too large to copy.",
69
+ timeout: "Copying took too long. Try again.",
70
+ aborted: "Copying was cancelled.",
71
+ unknown: "Couldn't copy to the clipboard. Try again."
72
+ };
73
+ /** Default English, user-facing sentence for a copy error. Replace for i18n. */
74
+ function describeCopyError(error) {
75
+ return COPY_DESCRIPTIONS[error.type];
76
+ }
77
+ //#endregion
78
+ //#region src/core/payload.ts
79
+ /** The only image MIME type with reliable cross-browser clipboard write support. */
80
+ const IMAGE_MIME_TYPE = "image/png";
81
+ function normalizePayload(input) {
82
+ return typeof input === "string" ? {
83
+ kind: "text",
84
+ value: input
85
+ } : input;
86
+ }
87
+ function isBlob(value) {
88
+ if (typeof Blob !== "undefined" && value instanceof Blob) return true;
89
+ const tag = Object.prototype.toString.call(value);
90
+ return tag === "[object Blob]" || tag === "[object File]";
91
+ }
92
+ function isThenable(value) {
93
+ return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
94
+ }
95
+ const invalid$3 = (message) => createCopyError("invalid-payload", message);
96
+ /**
97
+ * Structural validation. Typed callers can't produce most of these states,
98
+ * but plain-JS callers and runtime data can, so the check is always on.
99
+ */
100
+ function validatePayload(payload) {
101
+ if (typeof payload !== "object" || payload === null) return invalid$3("Copy input must be a string or a payload object.");
102
+ const candidate = payload;
103
+ switch (candidate["kind"]) {
104
+ case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid$3("Text payload must be a non-empty string.");
105
+ case "html":
106
+ if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid$3("HTML payload requires a non-empty `html` string.");
107
+ return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid$3("HTML payload requires a non-empty plain-text `text` fallback.");
108
+ case "image": {
109
+ const source = candidate["blob"];
110
+ return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid$3("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
111
+ }
112
+ case "json": return candidate["value"] === void 0 ? invalid$3("JSON payload value is undefined.") : null;
113
+ case "multi": {
114
+ const items = candidate["items"];
115
+ if (!Array.isArray(items) || items.length === 0) return invalid$3("Multi payload requires at least one item.");
116
+ const seen = /* @__PURE__ */ new Set();
117
+ for (const item of items) {
118
+ const entry = typeof item === "object" && item !== null ? item : {};
119
+ const mimeType = entry["mimeType"];
120
+ const data = entry["data"];
121
+ if (typeof mimeType !== "string" || mimeType.length === 0) return invalid$3("Every multi item needs a non-empty `mimeType`.");
122
+ if (seen.has(mimeType)) return invalid$3(`Duplicate MIME type "${mimeType}" in multi payload.`);
123
+ seen.add(mimeType);
124
+ if (typeof data !== "string" && !isBlob(data)) return invalid$3(`Multi item "${mimeType}" must contain a string or a Blob.`);
125
+ }
126
+ return null;
127
+ }
128
+ default: return invalid$3(`Unknown payload kind: ${String(candidate["kind"])}.`);
129
+ }
130
+ }
131
+ /** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */
132
+ function serializeJson(payload) {
133
+ const indent = payload.pretty === true ? 2 : typeof payload.pretty === "number" ? payload.pretty : void 0;
134
+ let text;
135
+ try {
136
+ text = JSON.stringify(payload.value, null, indent);
137
+ } catch (cause) {
138
+ throw new CopyFailure(createCopyError("invalid-payload", "JSON payload could not be serialised (circular reference or BigInt?).", cause));
139
+ }
140
+ if (typeof text !== "string") throw new CopyFailure(createCopyError("invalid-payload", "JSON payload serialised to nothing (functions, symbols and undefined are not JSON)."));
141
+ return text;
142
+ }
143
+ //#endregion
144
+ //#region src/core/clipboard-adapter.ts
145
+ const fail = (type, message, cause) => new CopyFailure(createCopyError(type, message, cause));
146
+ const noop = () => void 0;
147
+ function defaultEnvironment$1() {
148
+ return typeof window === "undefined" ? void 0 : window;
149
+ }
150
+ function getRichClipboard(env, clipboard) {
151
+ const Item = env.ClipboardItem;
152
+ if (!Item || typeof clipboard.write !== "function") return null;
153
+ return {
154
+ Item,
155
+ write: clipboard.write.bind(clipboard)
156
+ };
157
+ }
158
+ function isTypeSupported(Item, type) {
159
+ return typeof Item.supports !== "function" || Item.supports(type);
160
+ }
161
+ function writeText(clipboard, text) {
162
+ if (typeof clipboard.writeText !== "function") throw fail("unsupported", "navigator.clipboard.writeText() is not available.");
163
+ return clipboard.writeText(text);
164
+ }
165
+ async function resolveImageBlob(source, context) {
166
+ let blob;
167
+ try {
168
+ blob = await (typeof source === "function" ? source(context ?? { signal: new AbortController().signal }) : source);
169
+ } catch (cause) {
170
+ if (context?.signal.aborted) throw fail("aborted", "The image copy was cancelled.", cause);
171
+ throw fail("blob-generation-failed", "The image source threw or rejected while producing a Blob.", cause);
172
+ }
173
+ if (!isBlob(blob)) throw fail("blob-generation-failed", "The image source did not produce a Blob.");
174
+ if (blob.type !== "image/png") throw fail("unsupported-format", `Only ${IMAGE_MIME_TYPE} can be written to the clipboard (received "${blob.type || "unknown"}"). Convert with canvas.toBlob(cb, "${IMAGE_MIME_TYPE}").`);
175
+ return blob;
176
+ }
177
+ async function writeImage(rich, source, context) {
178
+ if (!isTypeSupported(rich.Item, "image/png")) throw fail("unsupported-format", `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);
179
+ const blob = resolveImageBlob(source, context);
180
+ blob.catch(noop);
181
+ try {
182
+ await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);
183
+ } catch (error) {
184
+ throw await blob.then(noop, (inner) => inner) ?? error;
185
+ }
186
+ await blob;
187
+ }
188
+ async function writeToClipboard(payload, env, degradeHtmlToText, context) {
189
+ if (!env) throw fail("unsupported", "No browser environment: the clipboard only exists in the browser.");
190
+ if (env.isSecureContext === false) throw fail("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
191
+ const clipboard = env.navigator?.clipboard;
192
+ if (!clipboard) throw fail("unsupported", "navigator.clipboard is not available in this browser.");
193
+ switch (payload.kind) {
194
+ case "text": return writeText(clipboard, payload.value);
195
+ case "json": return writeText(clipboard, serializeJson(payload));
196
+ case "html": {
197
+ const rich = getRichClipboard(env, clipboard);
198
+ if (!rich || !isTypeSupported(rich.Item, "text/html")) {
199
+ if (degradeHtmlToText) return writeText(clipboard, payload.text);
200
+ throw fail("unsupported-format", "Rich HTML copy requires ClipboardItem and navigator.clipboard.write().");
201
+ }
202
+ return rich.write([new rich.Item({
203
+ "text/html": new Blob([payload.html], { type: "text/html" }),
204
+ "text/plain": new Blob([payload.text], { type: "text/plain" })
205
+ })]);
206
+ }
207
+ case "image": {
208
+ const rich = getRichClipboard(env, clipboard);
209
+ if (!rich) throw fail("unsupported-format", "Image copy requires ClipboardItem and navigator.clipboard.write().");
210
+ return writeImage(rich, payload.blob, context);
211
+ }
212
+ case "multi": {
213
+ const rich = getRichClipboard(env, clipboard);
214
+ if (!rich) throw fail("unsupported-format", "Multi-format copy requires ClipboardItem and navigator.clipboard.write().");
215
+ const record = Object.create(null);
216
+ let written = 0;
217
+ for (const { mimeType, data, optional } of payload.items) {
218
+ if (optional === true && !(typeof rich.Item.supports === "function" && rich.Item.supports(mimeType))) continue;
219
+ if (!isTypeSupported(rich.Item, mimeType)) throw fail("unsupported-format", `This browser cannot write "${mimeType}" to the clipboard.`);
220
+ record[mimeType] = typeof data === "string" ? new Blob([data], { type: mimeType }) : data;
221
+ written += 1;
222
+ }
223
+ if (written === 0) throw fail("unsupported-format", "This browser can write none of the payload types.");
224
+ return rich.write([new rich.Item(record)]);
225
+ }
226
+ }
227
+ }
228
+ /** The default adapter: async Clipboard API with feature detection and honest errors. */
229
+ function createBrowserClipboardAdapter(options = {}) {
230
+ const getEnvironment = options.getEnvironment ?? defaultEnvironment$1;
231
+ const degradeHtmlToText = options.degradeHtmlToText ?? true;
232
+ return { write: (payload, context) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText, context) };
233
+ }
234
+ //#endregion
235
+ //#region src/link/url.ts
236
+ /** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */
237
+ const DEFAULT_LINK_PROTOCOLS = /* @__PURE__ */ Object.freeze([
238
+ "https:",
239
+ "http:",
240
+ "mailto:",
241
+ "tel:"
242
+ ]);
243
+ /**
244
+ * Query parameters that only track where a click came from: the defaults of
245
+ * {@link cleanLinkUrl}. `utm_` matches every parameter starting with it.
246
+ */
247
+ const TRACKING_PARAMETERS = /* @__PURE__ */ Object.freeze([
248
+ "utm_",
249
+ "fbclid",
250
+ "gclid",
251
+ "gclsrc",
252
+ "dclid",
253
+ "gbraid",
254
+ "wbraid",
255
+ "msclkid",
256
+ "yclid",
257
+ "twclid",
258
+ "ttclid",
259
+ "li_fat_id",
260
+ "igshid",
261
+ "igsh",
262
+ "mc_cid",
263
+ "mc_eid",
264
+ "_hsenc",
265
+ "_hsmi",
266
+ "mkt_tok",
267
+ "oly_anon_id",
268
+ "oly_enc_id",
269
+ "vero_id",
270
+ "wickedid",
271
+ "_gl"
272
+ ]);
273
+ const invalid$2 = (message) => copyFailure("invalid-payload", message);
274
+ function baseUrl(base) {
275
+ if (base !== void 0) {
276
+ if (typeof base === "string" || base instanceof URL) return String(base);
277
+ throw invalid$2("`base` must be a string or a URL.");
278
+ }
279
+ return typeof location === "undefined" ? void 0 : location.href;
280
+ }
281
+ function protocolSet(protocols) {
282
+ const list = protocols ?? DEFAULT_LINK_PROTOCOLS;
283
+ const valid = (protocol) => typeof protocol === "string" && /^[a-z][a-z\d+.-]*:$/i.test(protocol);
284
+ if (!Array.isArray(list) || list.length === 0 || !list.every(valid)) throw invalid$2("`protocols` must be a non-empty list of schemes with their colon, like \"https:\".");
285
+ return new Set(list.map((protocol) => protocol.toLowerCase()));
286
+ }
287
+ function matcher(params) {
288
+ const list = params ?? TRACKING_PARAMETERS;
289
+ if (!Array.isArray(list) || !list.every((param) => typeof param === "string" || param instanceof RegExp)) throw invalid$2("`clean.params` must be a list of strings and regular expressions.");
290
+ return (name) => {
291
+ const lower = name.toLowerCase();
292
+ return list.some((param) => {
293
+ if (typeof param !== "string") return new RegExp(param.source, param.flags.replace(/[gy]/g, "")).test(name);
294
+ const wanted = param.toLowerCase();
295
+ return wanted.endsWith("_") ? lower.startsWith(wanted) : lower === wanted;
296
+ });
297
+ };
298
+ }
299
+ /** The cleaning step `clean` asks for, or `null`. Throws for an invalid option. */
300
+ function cleaner(option) {
301
+ const cleaning = option ?? false;
302
+ if (cleaning === false) return null;
303
+ if (cleaning !== true && (typeof cleaning !== "object" || cleaning === null)) throw invalid$2("`clean` must be a boolean or an options object.");
304
+ const settings = cleaning === true ? {} : cleaning;
305
+ const tracking = matcher(settings.params);
306
+ const keep = settings.keep ?? [];
307
+ if (!Array.isArray(keep) || !keep.every((name) => typeof name === "string")) throw invalid$2("`clean.keep` must be a list of strings.");
308
+ const kept = new Set(keep.map((name) => name.toLowerCase()));
309
+ return (url) => {
310
+ for (const name of [...new Set(url.searchParams.keys())]) if (tracking(name) && !kept.has(name.toLowerCase())) url.searchParams.delete(name);
311
+ };
312
+ }
313
+ /**
314
+ * Validates `options` once (throwing a typed `invalid-payload` error for invalid
315
+ * ones) and returns a resolver that throws only for invalid links.
316
+ * @internal
317
+ */
318
+ function linkUrlResolver(options = {}) {
319
+ const protocols = protocolSet(options.protocols);
320
+ const base = baseUrl(options.base);
321
+ const clean = cleaner(options.clean);
322
+ return (input) => {
323
+ if (typeof input !== "string" && !(input instanceof URL)) throw invalid$2("A link must be a string or a URL.");
324
+ const raw = String(input).trim();
325
+ if (raw === "") throw invalid$2("A link must not be empty.");
326
+ let url;
327
+ try {
328
+ url = new URL(raw, base);
329
+ } catch (cause) {
330
+ throw copyFailure("invalid-payload", `Not a valid link: ${JSON.stringify(raw.slice(0, 200))}.`, cause);
331
+ }
332
+ if (!protocols.has(url.protocol)) throw invalid$2(`Links with the scheme "${url.protocol}" are not allowed (allowed: ${[...protocols].join(", ")}).`);
333
+ url.username = "";
334
+ url.password = "";
335
+ clean?.(url);
336
+ return url.href;
337
+ };
338
+ }
339
+ /**
340
+ * The link as an absolute, safe URL string, or a typed `invalid-payload` error:
341
+ * relative links are resolved, the scheme must be allowed, user names and
342
+ * passwords are always removed, and tracking parameters optionally.
343
+ */
344
+ function resolveLinkUrl(input, options = {}) {
345
+ return linkUrlResolver(options)(input);
346
+ }
347
+ const invalid$1 = (message) => copyFailure("invalid-payload", message);
348
+ /**
349
+ * Characters a title never keeps: controls, bidi overrides and isolates (which can
350
+ * make a title read differently), and zero-width characters.
351
+ */
352
+ const HIDDEN = /[\0-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u061C\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g;
353
+ /** A title as one clean line: hidden characters removed, whitespace collapsed, length capped. */
354
+ function cleanTitle(title, maxLength) {
355
+ const clean = title.replace(HIDDEN, "").replace(/\s+/g, " ").trim();
356
+ if (clean.length <= maxLength) return clean;
357
+ return `${Array.from(clean).slice(0, maxLength - 1).join("").trimEnd()}\u2026`;
358
+ }
359
+ function maxTitle(value) {
360
+ if (value === void 0) return 300;
361
+ if (Number.isInteger(value) && value >= 1) return value;
362
+ throw invalid$1(`\`maxTitleLength\` must be a positive integer (received ${String(value)}).`);
363
+ }
364
+ function isAnchor(source) {
365
+ return typeof source === "object" && source !== null && source.nodeName === "A" && typeof source.href === "string";
366
+ }
367
+ /**
368
+ * Validates a link and its title: see {@link resolveLinkUrl} for the URL rules.
369
+ * An `<a>` element gives its `href` and its text (or `title` attribute).
370
+ */
371
+ function resolveLink(source, options = {}) {
372
+ let url;
373
+ let title;
374
+ if (typeof source === "string" || source instanceof URL) url = source;
375
+ else if (isAnchor(source)) {
376
+ url = source.getAttribute("href") ?? "";
377
+ title = source.textContent.trim() !== "" ? source.textContent : source.getAttribute("title") ?? void 0;
378
+ if (url !== "" && options.base === void 0) url = source.href;
379
+ } else if (typeof source === "object" && source !== null && "url" in source) {
380
+ url = source.url;
381
+ title = source.title;
382
+ } else throw invalid$1("A link must be a URL, a { url, title } object or an <a> element.");
383
+ if (title !== void 0 && typeof title !== "string") throw invalid$1("A link title must be a string.");
384
+ const href = resolveLinkUrl(url, options);
385
+ const clean = title === void 0 ? "" : cleanTitle(title, maxTitle(options.maxTitleLength));
386
+ return {
387
+ url: href,
388
+ title: clean === "" ? href : clean,
389
+ titled: clean !== ""
390
+ };
391
+ }
392
+ const escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
393
+ /** `[title](url)`, safe in every CommonMark renderer: brackets and backslashes escaped, parentheses and spaces encoded. */
394
+ function markdownLink(link) {
395
+ return `[${link.title.replace(/[\\[\]]/g, "\\$&")}](${link.url.replace(/[()<> ]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)})`;
396
+ }
397
+ function plainText(link, format) {
398
+ switch (format) {
399
+ case "url": return link.url;
400
+ case "title": return link.title;
401
+ case "title-and-url": return link.titled ? `${link.title}\n${link.url}` : link.url;
402
+ case "markdown": return markdownLink(link);
403
+ default: throw invalid$1(`\`text\` must be "url", "title", "title-and-url" or "markdown" (received ${JSON.stringify(format)}).`);
404
+ }
405
+ }
406
+ function linkPayload(source, options = {}) {
407
+ const target = options.target ?? "clipboard";
408
+ if (target !== "drag" && target !== "clipboard") throw invalid$1("`target` must be \"clipboard\" or \"drag\".");
409
+ const link = resolveLink(source, options);
410
+ const text = plainText(link, options.text ?? "url");
411
+ const html = `<a href="${escapeHtml(link.url)}">${escapeHtml(link.title)}</a>`;
412
+ if (target === "clipboard") return {
413
+ kind: "html",
414
+ html,
415
+ text
416
+ };
417
+ return {
418
+ kind: "multi",
419
+ items: [
420
+ {
421
+ mimeType: "text/plain",
422
+ data: text
423
+ },
424
+ {
425
+ mimeType: "text/html",
426
+ data: html
427
+ },
428
+ {
429
+ mimeType: "text/uri-list",
430
+ data: link.url,
431
+ optional: true
432
+ },
433
+ {
434
+ mimeType: "text/x-moz-url",
435
+ data: `${link.url}\n${link.title}`,
436
+ optional: true
437
+ }
438
+ ]
439
+ };
440
+ }
441
+ const defaultEnvironment = () => typeof window === "undefined" ? void 0 : window;
442
+ const invalid = (message) => createCopyError("invalid-payload", message);
443
+ /** Validates and cleans what to share, or returns the typed error for invalid input. */
444
+ function resolveContent(content, options) {
445
+ const value = content;
446
+ if (typeof value !== "object" || value === null) return invalid("Share content must be an object with a url, text or files.");
447
+ const { url, title, text, files } = value;
448
+ let href = null;
449
+ if (url !== void 0 && url !== null) try {
450
+ href = linkUrlResolver(options)(url);
451
+ } catch (error) {
452
+ return toCopyError(error);
453
+ }
454
+ if (title !== void 0 && typeof title !== "string") return invalid("`title` must be a string.");
455
+ if (text !== void 0 && typeof text !== "string") return invalid("`text` must be a string.");
456
+ const list = files ?? [];
457
+ if (!Array.isArray(list) || !list.every((file) => typeof File !== "undefined" && file instanceof File)) return invalid("`files` must be a list of File objects.");
458
+ const cleanName = title === void 0 ? "" : cleanTitle(title, 300);
459
+ const message = text === void 0 || text.trim() === "" ? null : text;
460
+ if (href === null && message === null && list.length === 0) return invalid("There is nothing to share: give a url, text or files.");
461
+ return {
462
+ url: href,
463
+ title: cleanName === "" ? null : cleanName,
464
+ text: message,
465
+ files: list
466
+ };
467
+ }
468
+ /** The `ShareData` the browser receives: only the fields that are set. */
469
+ function shareData(content) {
470
+ return {
471
+ ...content.url === null ? {} : { url: content.url },
472
+ ...content.title === null ? {} : { title: content.title },
473
+ ...content.text === null ? {} : { text: content.text },
474
+ ...content.files.length === 0 ? {} : { files: [...content.files] }
475
+ };
476
+ }
477
+ /** Whether this browser can open its share sheet for `data`. */
478
+ function canShareNatively(environment, data) {
479
+ const nav = environment?.navigator;
480
+ if (typeof nav?.share !== "function") return false;
481
+ if (data === null) return true;
482
+ return typeof nav.canShare === "function" ? nav.canShare(data) : data.files === void 0;
483
+ }
484
+ function isTouchFirst(environment) {
485
+ return typeof environment?.matchMedia === "function" && environment.matchMedia("(hover: none) and (pointer: coarse)").matches;
486
+ }
487
+ function resolveMode(mode) {
488
+ if (mode === void 0) return "auto";
489
+ return mode === "auto" || mode === "native" || mode === "copy" ? mode : invalid("`mode` must be \"auto\", \"native\" or \"copy\".");
490
+ }
491
+ /**
492
+ * How {@link shareOrCopy} would share right now: `"native"` (the share sheet) or
493
+ * `"copy"`. Use it to label the button ("Share…" or "Copy link"). Pass the
494
+ * content when it has files, since not every share sheet takes them.
495
+ */
496
+ function shareMethod(options = {}, content) {
497
+ const mode = resolveMode(options.mode);
498
+ if (typeof mode !== "string" || mode === "copy") return "copy";
499
+ const environment = options.environment ?? defaultEnvironment();
500
+ if (mode === "auto" && !isTouchFirst(environment)) return "copy";
501
+ const resolved = content === void 0 ? null : resolveContent(content, {});
502
+ const data = resolved === null ? null : "type" in resolved ? void 0 : shareData(resolved);
503
+ return data !== void 0 && canShareNatively(environment, data) ? "native" : "copy";
504
+ }
505
+ /** The default copy: a titled link when there is a URL, otherwise the text (one of them is always set here). */
506
+ function defaultCopy(content) {
507
+ if (content.url !== null) return linkPayload({
508
+ url: content.url,
509
+ ...content.title === null ? {} : { title: content.title }
510
+ });
511
+ return content.text;
512
+ }
513
+ async function copyContent(content, reason, options) {
514
+ if (options.copy === void 0 && content.url === null && content.text === null) return {
515
+ status: "error",
516
+ method: "copy",
517
+ error: createCopyError("unsupported-format", "Files can only be shared through a share sheet, and this browser has none for them.")
518
+ };
519
+ let payload;
520
+ try {
521
+ payload = normalizePayload((options.copy ?? defaultCopy)(content));
522
+ } catch (error) {
523
+ return {
524
+ status: "error",
525
+ method: "copy",
526
+ error: toCopyError(error)
527
+ };
528
+ }
529
+ const problem = validatePayload(payload);
530
+ if (problem !== null) return {
531
+ status: "error",
532
+ method: "copy",
533
+ error: problem
534
+ };
535
+ if (options.signal?.aborted === true) return {
536
+ status: "error",
537
+ method: "copy",
538
+ error: createCopyError("aborted", "The share was aborted.")
539
+ };
540
+ try {
541
+ await (options.adapter ?? createBrowserClipboardAdapter()).write(payload, options.signal === void 0 ? void 0 : { signal: options.signal });
542
+ } catch (error) {
543
+ return {
544
+ status: "error",
545
+ method: "copy",
546
+ error: toCopyError(error)
547
+ };
548
+ }
549
+ return {
550
+ status: "copied",
551
+ method: "copy",
552
+ reason,
553
+ payload,
554
+ content
555
+ };
556
+ }
557
+ /**
558
+ * Shares through the device's share sheet where people expect one, and copies a
559
+ * titled link everywhere else. Call it directly in a click handler: the share
560
+ * sheet needs the user's gesture.
561
+ *
562
+ * It never rejects. It resolves to `shared`, `copied` (with why), `cancelled`
563
+ * (the user closed the share sheet: nothing to report) or `error` with a typed
564
+ * {@link CopyError}.
565
+ *
566
+ * @example
567
+ * button.addEventListener('click', async () => {
568
+ * const outcome = await shareOrCopy({ url: location.href, title: document.title });
569
+ * if (outcome.status === 'copied') toast('Link copied');
570
+ * });
571
+ */
572
+ async function shareOrCopy(content, options = {}) {
573
+ const mode = resolveMode(options.mode);
574
+ if (typeof mode !== "string") return {
575
+ status: "error",
576
+ method: "copy",
577
+ error: mode
578
+ };
579
+ const resolved = resolveContent(content, options);
580
+ if ("type" in resolved) return {
581
+ status: "error",
582
+ method: "copy",
583
+ error: resolved
584
+ };
585
+ const environment = options.environment ?? defaultEnvironment();
586
+ if (mode === "copy" || mode === "auto" && !isTouchFirst(environment)) return copyContent(resolved, "preferred", options);
587
+ const data = shareData(resolved);
588
+ if (!canShareNatively(environment, data)) return copyContent(resolved, "unsupported", options);
589
+ try {
590
+ await (environment?.navigator?.share)(data);
591
+ return {
592
+ status: "shared",
593
+ method: "native",
594
+ content: resolved
595
+ };
596
+ } catch (error) {
597
+ if (readName(error) === "AbortError") return {
598
+ status: "cancelled",
599
+ method: "native"
600
+ };
601
+ if (options.fallback === false) return {
602
+ status: "error",
603
+ method: "native",
604
+ error: shareError(error)
605
+ };
606
+ return copyContent(resolved, "fallback", options);
607
+ }
608
+ }
609
+ function readName(error) {
610
+ const name = typeof error === "object" && error !== null ? error.name : void 0;
611
+ return typeof name === "string" ? name : void 0;
612
+ }
613
+ /** Classifies a share sheet failure. */
614
+ function shareError(cause) {
615
+ switch (readName(cause)) {
616
+ case "NotAllowedError": return createCopyError("permission-denied", "The share sheet was blocked: it needs a click, and an iframe needs the web-share permission.", cause);
617
+ case "InvalidStateError": return createCopyError("unknown", "Another share sheet is already open.", cause);
618
+ case "DataError":
619
+ case "TypeError": return createCopyError("unsupported-format", "The share sheet rejected this content.", cause);
620
+ default: return toCopyError(cause);
621
+ }
622
+ }
623
+ const SHARE_DESCRIPTIONS = {
624
+ "permission-denied": "Sharing isn't allowed here.",
625
+ "unsupported-format": "This can't be shared from this browser.",
626
+ timeout: "Sharing took too long. Try again."
627
+ };
628
+ /**
629
+ * Default English, user-facing sentence for a failed share: a share sheet
630
+ * failure is described as sharing, a failed copy as copying. Replace for i18n.
631
+ */
632
+ function describeShareError(error, method) {
633
+ if (method === "copy") return describeCopyError(error);
634
+ return SHARE_DESCRIPTIONS[error.type] ?? "Couldn't share. Try again.";
635
+ }
636
+ //#endregion
637
+ exports.describeShareError = describeShareError;
638
+ exports.shareMethod = shareMethod;
639
+ exports.shareOrCopy = shareOrCopy;
640
+
641
+ //# sourceMappingURL=share.cjs.map