react-smart-copy 1.23.0 → 1.24.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +130 -1806
- package/dist/capture.cjs +3 -3
- package/dist/capture.d.cts +1 -1
- package/dist/capture.d.ts +1 -1
- package/dist/capture.js +3 -3
- package/dist/chunks/{clipboard-adapter-CtH4VELE.d.cts → clipboard-adapter-CfaIbZpv.d.cts} +2 -2
- package/dist/chunks/{clipboard-adapter-Ds0irroN.d.ts → clipboard-adapter-Chm6zq60.d.ts} +2 -2
- package/dist/chunks/{clipboard-adapter-DEXkXxwV.js → clipboard-adapter-CmKDTFdO.js} +3 -3
- package/dist/chunks/{clipboard-adapter-DEXkXxwV.js.map → clipboard-adapter-CmKDTFdO.js.map} +1 -1
- package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs → clipboard-adapter-UIFc_Qso.cjs} +3 -3
- package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs.map → clipboard-adapter-UIFc_Qso.cjs.map} +1 -1
- package/dist/chunks/{contrast-C6CVklEI.cjs → contrast-C9d8QuaF.cjs} +2 -2
- package/dist/chunks/{contrast-C6CVklEI.cjs.map → contrast-C9d8QuaF.cjs.map} +1 -1
- package/dist/chunks/{contrast-DpK2JIVu.js → contrast-DUaZq5SA.js} +2 -2
- package/dist/chunks/{contrast-DpK2JIVu.js.map → contrast-DUaZq5SA.js.map} +1 -1
- package/dist/chunks/{copy-interceptor-CZWzGOkL.d.cts → copy-interceptor-BClcHS_P.d.cts} +2 -2
- package/dist/chunks/{copy-interceptor-C6NABy1l.d.ts → copy-interceptor-D8c9EDnO.d.ts} +2 -2
- package/dist/chunks/{core-Cp2HSpaz.js → core-BH2uIumi.js} +5 -5
- package/dist/chunks/{core-Cp2HSpaz.js.map → core-BH2uIumi.js.map} +1 -1
- package/dist/chunks/{core-DYf_Lhbe.cjs → core-DmncxMt3.cjs} +5 -5
- package/dist/chunks/{core-DYf_Lhbe.cjs.map → core-DmncxMt3.cjs.map} +1 -1
- package/dist/chunks/{deadline-C29AlS_Q.js → deadline-CbwnZ3Oq.js} +2 -2
- package/dist/chunks/{deadline-C29AlS_Q.js.map → deadline-CbwnZ3Oq.js.map} +1 -1
- package/dist/chunks/{deadline-DkiB8ZHE.cjs → deadline-j2hD7JKz.cjs} +2 -2
- package/dist/chunks/{deadline-DkiB8ZHE.cjs.map → deadline-j2hD7JKz.cjs.map} +1 -1
- package/dist/chunks/{errors-9h8sdFFX.js → errors-CT-FfUtU.js} +2 -2
- package/dist/chunks/errors-CT-FfUtU.js.map +1 -0
- package/dist/chunks/{errors-BwOF6T_M.cjs → errors-DFmEAC4E.cjs} +2 -2
- package/dist/chunks/errors-DFmEAC4E.cjs.map +1 -0
- package/dist/chunks/{field-BHo5y-t_.js → field-CK3NxfkM.js} +43 -14
- package/dist/chunks/field-CK3NxfkM.js.map +1 -0
- package/dist/chunks/{field-Bytz2WfN.cjs → field-CNEcZqa9.cjs} +43 -14
- package/dist/chunks/field-CNEcZqa9.cjs.map +1 -0
- package/dist/chunks/{index-vz0iW5V2.d.cts → index-CqYzvxSN.d.cts} +4 -4
- package/dist/chunks/{index-mr7sSAgP.d.ts → index-Q_QeSwGr.d.ts} +4 -4
- package/dist/chunks/{paste-adapter--SPL4PRE.d.cts → paste-adapter-B6eucH3E.d.cts} +2 -2
- package/dist/chunks/{paste-adapter-uahXnTYk.d.ts → paste-adapter-CfIDT3mp.d.ts} +2 -2
- package/dist/chunks/{paste-reader-Bo01IMC_.cjs → paste-reader-BWQaYNaV.cjs} +2 -2
- package/dist/chunks/paste-reader-BWQaYNaV.cjs.map +1 -0
- package/dist/chunks/{paste-reader-D9i7yMXF.js → paste-reader-D6uOTDBM.js} +2 -2
- package/dist/chunks/paste-reader-D6uOTDBM.js.map +1 -0
- package/dist/chunks/{payload-DI5AorDz.js → payload-BWQ6sPtS.js} +3 -3
- package/dist/chunks/{payload-DI5AorDz.js.map → payload-BWQ6sPtS.js.map} +1 -1
- package/dist/chunks/{payload-DGw-JOo7.js → payload-BrQWGwyx.js} +2 -2
- package/dist/chunks/{payload-DGw-JOo7.js.map → payload-BrQWGwyx.js.map} +1 -1
- package/dist/chunks/{payload-Cl_8hCI5.d.ts → payload-CcvSx_Hq.d.ts} +4 -2
- package/dist/chunks/{payload-CcwKJ_bU.d.cts → payload-qkAWVXWA.d.cts} +4 -2
- package/dist/chunks/{payload-CUymxwim.cjs → payload-sBxkG7jH.cjs} +2 -2
- package/dist/chunks/{payload-CUymxwim.cjs.map → payload-sBxkG7jH.cjs.map} +1 -1
- package/dist/chunks/{payload-J6GjHuh3.cjs → payload-tTK6REua.cjs} +3 -3
- package/dist/chunks/{payload-J6GjHuh3.cjs.map → payload-tTK6REua.cjs.map} +1 -1
- package/dist/chunks/{share-Bop47Znn.js → share-CU91L4EK.js} +6 -6
- package/dist/chunks/{share-Bop47Znn.js.map → share-CU91L4EK.js.map} +1 -1
- package/dist/chunks/{share-e7FenIr2.d.ts → share-DVR_DhHc.d.ts} +3 -3
- package/dist/chunks/{share-C0esXvRK.d.cts → share-hIwth7Dh.d.cts} +3 -3
- package/dist/chunks/{share-ayDz974N.cjs → share-nx7M4Z0t.cjs} +6 -6
- package/dist/chunks/{share-ayDz974N.cjs.map → share-nx7M4Z0t.cjs.map} +1 -1
- package/dist/chunks/{url-D4PGsRm8.cjs → url-BrhVUwn7.cjs} +2 -2
- package/dist/chunks/{url-D4PGsRm8.cjs.map → url-BrhVUwn7.cjs.map} +1 -1
- package/dist/chunks/{url-BcMYVCXQ.js → url-COID0BLY.js} +2 -2
- package/dist/chunks/{url-BcMYVCXQ.js.map → url-COID0BLY.js.map} +1 -1
- package/dist/code.cjs +1 -1
- package/dist/code.cjs.map +1 -1
- package/dist/code.d.cts +1 -1
- package/dist/code.d.ts +1 -1
- package/dist/code.js +1 -1
- package/dist/code.js.map +1 -1
- package/dist/color.cjs +2 -2
- package/dist/color.d.cts +1 -1
- package/dist/color.d.ts +1 -1
- package/dist/color.js +2 -2
- package/dist/core.cjs +5 -5
- package/dist/core.d.cts +5 -5
- package/dist/core.d.ts +5 -5
- package/dist/core.js +5 -5
- package/dist/email.cjs +357 -0
- package/dist/email.cjs.map +1 -0
- package/dist/email.d.cts +163 -0
- package/dist/email.d.ts +163 -0
- package/dist/email.js +351 -0
- package/dist/email.js.map +1 -0
- package/dist/files.cjs +1 -1
- package/dist/files.cjs.map +1 -1
- package/dist/files.d.cts +3 -59
- package/dist/files.d.ts +3 -59
- package/dist/files.js +1 -1
- package/dist/files.js.map +1 -1
- package/dist/image.cjs +2 -2
- package/dist/image.cjs.map +1 -1
- package/dist/image.js +2 -2
- package/dist/image.js.map +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +43 -19
- package/dist/index.d.ts +43 -19
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/link.cjs +3 -3
- package/dist/link.d.cts +1 -1
- package/dist/link.d.ts +1 -1
- package/dist/link.js +3 -3
- package/dist/markdown.cjs +1 -1
- package/dist/markdown.cjs.map +1 -1
- package/dist/markdown.js +1 -1
- package/dist/markdown.js.map +1 -1
- package/dist/number.cjs +1 -1
- package/dist/number.d.cts +1 -1
- package/dist/number.d.ts +1 -1
- package/dist/number.js +1 -1
- package/dist/otp.cjs +1 -1
- package/dist/otp.js +1 -1
- package/dist/rich.cjs +3 -3
- package/dist/rich.cjs.map +1 -1
- package/dist/rich.d.cts +2 -2
- package/dist/rich.d.ts +2 -2
- package/dist/rich.js +3 -3
- package/dist/rich.js.map +1 -1
- package/dist/secrets.cjs +1 -1
- package/dist/secrets.cjs.map +1 -1
- package/dist/secrets.d.cts +1 -1
- package/dist/secrets.d.ts +1 -1
- package/dist/secrets.js +1 -1
- package/dist/secrets.js.map +1 -1
- package/dist/share.cjs +1 -1
- package/dist/share.d.cts +1 -1
- package/dist/share.d.ts +1 -1
- package/dist/share.js +1 -1
- package/dist/structured.cjs +2 -2
- package/dist/structured.cjs.map +1 -1
- package/dist/structured.js +2 -2
- package/dist/structured.js.map +1 -1
- package/dist/table.cjs +1 -1
- package/dist/table.cjs.map +1 -1
- package/dist/table.d.cts +1 -1
- package/dist/table.d.ts +1 -1
- package/dist/table.js +1 -1
- package/dist/table.js.map +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +3 -3
- package/dist/testing.d.ts +3 -3
- package/dist/testing.js +2 -2
- package/package.json +35 -6
- package/dist/chunks/errors-9h8sdFFX.js.map +0 -1
- package/dist/chunks/errors-BwOF6T_M.cjs.map +0 -1
- package/dist/chunks/field-BHo5y-t_.js.map +0 -1
- package/dist/chunks/field-Bytz2WfN.cjs.map +0 -1
- package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +0 -1
- package/dist/chunks/paste-reader-D9i7yMXF.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import { n as copyFailure } from "./errors-
|
|
3
|
-
import { a as resolveLinkUrl } from "./url-
|
|
2
|
+
import { n as copyFailure } from "./errors-CT-FfUtU.js";
|
|
3
|
+
import { a as resolveLinkUrl } from "./url-COID0BLY.js";
|
|
4
4
|
//#region src/link/payload.ts
|
|
5
5
|
const DEFAULT_LINK_TITLE_LENGTH = 300;
|
|
6
6
|
const invalid = (message) => copyFailure("invalid-payload", message);
|
|
@@ -100,4 +100,4 @@ function linkPayload(source, options = {}) {
|
|
|
100
100
|
//#endregion
|
|
101
101
|
export { resolveLink as a, markdownLink as i, cleanTitle as n, linkPayload as r, DEFAULT_LINK_TITLE_LENGTH as t };
|
|
102
102
|
|
|
103
|
-
//# sourceMappingURL=payload-
|
|
103
|
+
//# sourceMappingURL=payload-BWQ6sPtS.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payload-
|
|
1
|
+
{"version":3,"file":"payload-BWQ6sPtS.js","names":[],"sources":["../../src/link/payload.ts"],"sourcesContent":["import { copyFailure } from '../core/errors';\nimport type { HtmlPayload, MultiPayload } from '../core/payload';\nimport { resolveLinkUrl, type LinkUrlOptions } from './url';\n\n/** A link with an optional title. */\nexport interface Link {\n readonly url: string | URL;\n /** What the link says when pasted into a document or chat. Default: the URL. */\n readonly title?: string;\n}\n\n/** A link: a URL, a `{ url, title }` object, or an `<a>` element (its `href` and text). */\nexport type LinkSource = string | URL | Link | HTMLAnchorElement;\n\n/** A validated link: an absolute, safe URL and a clean title. */\nexport interface ResolvedLink {\n readonly url: string;\n /** Never empty: the URL when there is no title. */\n readonly title: string;\n /** Whether `title` came from the input (`false`: it is the URL). */\n readonly titled: boolean;\n}\n\n/**\n * What the plain-text flavour holds (editors, terminals and address bars paste it):\n * `'url'` (the default), `'title'`, `'title-and-url'` (the title, then the URL on\n * the next line) or `'markdown'` (`[Title](URL)`).\n */\nexport type LinkTextFormat = 'url' | 'title' | 'title-and-url' | 'markdown';\n\nexport interface LinkPayloadOptions extends LinkUrlOptions {\n /** Default `'url'`. */\n readonly text?: LinkTextFormat;\n /** Longest title kept, in characters; longer ones end in an ellipsis. Default {@link DEFAULT_LINK_TITLE_LENGTH}. */\n readonly maxTitleLength?: number;\n}\n\nexport interface LinkDragPayloadOptions extends LinkPayloadOptions {\n /**\n * `'drag'`: a multi-format payload that also carries `text/uri-list` and\n * Firefox's `text/x-moz-url`, for `useDragCopy` and `useCopyInterceptor` (a link\n * dropped on the tab bar opens). Clipboard writes skip those two where the\n * browser can't write them.\n */\n readonly target: 'drag';\n}\n\nexport const DEFAULT_LINK_TITLE_LENGTH = 300;\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\n/**\n * Characters a title never keeps: controls, bidi overrides and isolates (which can\n * make a title read differently), and zero-width characters.\n */\n// eslint-disable-next-line no-control-regex -- matching control characters is the point\nconst HIDDEN = /[\\0-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f-\\x9f\\u061C\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u2066-\\u2069\\uFEFF]/g;\n\n/** A title as one clean line: hidden characters removed, whitespace collapsed, length capped. */\nexport function cleanTitle(title: string, maxLength: number): string {\n const clean = title.replace(HIDDEN, '').replace(/\\s+/g, ' ').trim();\n if (clean.length <= maxLength) return clean;\n // Cut on a code point boundary and mark the cut.\n return `${Array.from(clean).slice(0, maxLength - 1).join('').trimEnd()}\\u2026`;\n}\n\nfunction maxTitle(value: number | undefined): number {\n if (value === undefined) return DEFAULT_LINK_TITLE_LENGTH;\n if (Number.isInteger(value) && value >= 1) return value;\n throw invalid(`\\`maxTitleLength\\` must be a positive integer (received ${String(value)}).`);\n}\n\nfunction isAnchor(source: unknown): source is HTMLAnchorElement {\n return typeof source === 'object' && source !== null && (source as { nodeName?: unknown }).nodeName === 'A' && typeof (source as { href?: unknown }).href === 'string';\n}\n\n/**\n * Validates a link and its title: see {@link resolveLinkUrl} for the URL rules.\n * An `<a>` element gives its `href` and its text (or `title` attribute).\n */\nexport function resolveLink(source: LinkSource, options: LinkPayloadOptions = {}): ResolvedLink {\n let url: string | URL;\n let title: unknown;\n if (typeof source === 'string' || source instanceof URL) {\n url = source;\n } else if (isAnchor(source)) {\n url = source.getAttribute('href') ?? '';\n title = source.textContent.trim() !== '' ? source.textContent : (source.getAttribute('title') ?? undefined);\n if (url !== '' && options.base === undefined) url = source.href; // Resolved against the anchor's own document.\n } else if (typeof (source as unknown) === 'object' && (source as unknown) !== null && 'url' in source) {\n url = source.url;\n title = source.title;\n } else {\n throw invalid('A link must be a URL, a { url, title } object or an <a> element.');\n }\n if (title !== undefined && typeof title !== 'string') throw invalid('A link title must be a string.');\n const href = resolveLinkUrl(url, options);\n const clean = title === undefined ? '' : cleanTitle(title, maxTitle(options.maxTitleLength));\n return { url: href, title: clean === '' ? href : clean, titled: clean !== '' };\n}\n\nexport const escapeHtml = (text: string): string =>\n text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"').replace(/'/g, ''');\n\n/** `[title](url)`, safe in every CommonMark renderer: brackets and backslashes escaped, parentheses and spaces encoded. */\nexport function markdownLink(link: ResolvedLink): string {\n const label = link.title.replace(/[\\\\[\\]]/g, '\\\\$&');\n const target = link.url.replace(/[()<> ]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);\n return `[${label}](${target})`;\n}\n\nfunction plainText(link: ResolvedLink, format: LinkTextFormat): string {\n switch (format) {\n case 'url':\n return link.url;\n case 'title':\n return link.title;\n case 'title-and-url':\n return link.titled ? `${link.title}\\n${link.url}` : link.url;\n case 'markdown':\n return markdownLink(link);\n default:\n throw invalid(`\\`text\\` must be \"url\", \"title\", \"title-and-url\" or \"markdown\" (received ${JSON.stringify(format)}).`);\n }\n}\n\n/**\n * A copy payload for a link: an HTML anchor, so Slack, Google Docs, Notion,\n * Teams, Word and mail paste a titled link, and plain text (the URL by default)\n * for editors and address bars. The URL is validated (allowed schemes only,\n * credentials removed, optionally cleaned of tracking) and the title is cleaned\n * of hidden characters; both are escaped.\n *\n * @example\n * copy(() => linkPayload({ url: location.href, title: document.title }, { clean: true }));\n * useDragCopy({ payload: () => linkPayload(anchor, { target: 'drag' }) });\n */\nexport function linkPayload(source: LinkSource, options: LinkDragPayloadOptions): MultiPayload;\nexport function linkPayload(source: LinkSource, options?: LinkPayloadOptions): HtmlPayload;\nexport function linkPayload(source: LinkSource, options: LinkPayloadOptions & { readonly target?: 'drag' | 'clipboard' } = {}): HtmlPayload | MultiPayload {\n const target: unknown = options.target ?? 'clipboard'; // Plain-JS callers can pass anything.\n if (target !== 'drag' && target !== 'clipboard') throw invalid('`target` must be \"clipboard\" or \"drag\".');\n const link = resolveLink(source, options);\n const text = plainText(link, options.text ?? 'url');\n const html = `<a href=\"${escapeHtml(link.url)}\">${escapeHtml(link.title)}</a>`;\n if (target === 'clipboard') return { kind: 'html', html, text };\n return {\n kind: 'multi',\n items: [\n { mimeType: 'text/plain', data: text },\n { mimeType: 'text/html', data: html },\n { mimeType: 'text/uri-list', data: link.url, optional: true },\n // Firefox's titled-link format: the URL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G,EAAE,IAAI,WAAW,KAAK,KAAK,EAAE;CACzE,IAAI,WAAW,aAAa,OAAO;EAAE,MAAM;EAAQ;EAAM;CAAK;CAC9D,OAAO;EACL,MAAM;EACN,OAAO;GACL;IAAE,UAAU;IAAc,MAAM;GAAK;GACrC;IAAE,UAAU;IAAa,MAAM;GAAK;GACpC;IAAE,UAAU;IAAiB,MAAM,KAAK;IAAK,UAAU;GAAK;GAE5D;IAAE,UAAU;IAAkB,MAAM,GAAG,KAAK,IAAI,IAAI,KAAK;IAAS,UAAU;GAAK;EACnF;CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { r as createCopyError, t as CopyFailure } from "./errors-
|
|
2
|
+
import { r as createCopyError, t as CopyFailure } from "./errors-CT-FfUtU.js";
|
|
3
3
|
//#region src/core/payload.ts
|
|
4
4
|
/** The only image MIME type with reliable cross-browser clipboard write support. */
|
|
5
5
|
const IMAGE_MIME_TYPE = "image/png";
|
|
@@ -68,4 +68,4 @@ function serializeJson(payload) {
|
|
|
68
68
|
//#endregion
|
|
69
69
|
export { validatePayload as a, serializeJson as i, isBlob as n, normalizePayload as r, IMAGE_MIME_TYPE as t };
|
|
70
70
|
|
|
71
|
-
//# sourceMappingURL=payload-
|
|
71
|
+
//# sourceMappingURL=payload-BrQWGwyx.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payload-
|
|
1
|
+
{"version":3,"file":"payload-BrQWGwyx.js","names":[],"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+B;CAC9D,OAAO,OAAO,UAAU,WAAW;EAAE,MAAM;EAAQ,OAAO;CAAM,IAAI;AACtE;AAEA,SAAgB,OAAO,OAA+B;CACpD,IAAI,OAAO,SAAS,eAAe,iBAAiB,MAAM,OAAO;CACjE,MAAM,MAAM,OAAO,UAAU,SAAS,KAAK,KAAK;CAChD,OAAO,QAAQ,mBAAmB,QAAQ;AAC5C;AAEA,SAAS,WAAW,OAA+C;CACjE,QACG,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,UAAU,QACV,OAAQ,MAA6B,SAAS;AAElD;AAEA,MAAM,WAAW,YAA+B,gBAAgB,mBAAmB,OAAO;;;;;AAM1F,SAAgB,gBAAgB,SAAoC;CAClE,IAAI,OAAO,YAAY,YAAY,YAAY,MAC7C,OAAO,QAAQ,kDAAkD;CAEnE,MAAM,YAAY;CAElB,QAAQ,UAAU,SAAlB;EACE,KAAK,QACH,OAAO,OAAO,UAAU,aAAa,YAAY,UAAU,QAAQ,CAAC,SAAS,IACzE,OACA,QAAQ,0CAA0C;EACxD,KAAK;GACH,IAAI,OAAO,UAAU,YAAY,YAAY,UAAU,OAAO,CAAC,WAAW,GACxE,OAAO,QAAQ,kDAAkD;GAEnE,OAAO,OAAO,UAAU,YAAY,YAAY,UAAU,OAAO,CAAC,SAAS,IACvE,OACA,QAAQ,+DA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T"}
|
|
@@ -66,10 +66,12 @@ declare function isRetryableError(error: CopyError): boolean;
|
|
|
66
66
|
* is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
|
|
67
67
|
*/
|
|
68
68
|
declare const COPY_FAILURE_BRAND: unique symbol;
|
|
69
|
+
interface CopyFailure {
|
|
70
|
+
readonly [COPY_FAILURE_BRAND]: true;
|
|
71
|
+
}
|
|
69
72
|
/** Error thrown by adapters to carry a fully classified {@link CopyError}. */
|
|
70
73
|
declare class CopyFailure extends Error {
|
|
71
74
|
readonly copyError: CopyError;
|
|
72
|
-
readonly [COPY_FAILURE_BRAND] = true;
|
|
73
75
|
constructor(copyError: CopyError);
|
|
74
76
|
}
|
|
75
77
|
declare function isCopyFailure(value: unknown): value is CopyFailure;
|
|
@@ -159,4 +161,4 @@ declare function validatePayload(payload: unknown): CopyError | null;
|
|
|
159
161
|
declare function serializeJson(payload: JsonPayload): string;
|
|
160
162
|
//#endregion
|
|
161
163
|
export { resolveMaxRetries as A, describeCopyError as C, toCopyError as D, isRetryableError as E, DEFAULT_MAX_RETRIES as O, createCopyError as S, isCopyFailure as T, ClipboardOperation as _, CopySource as a, CopyFailure as b, ImagePayload as c, MultiPayloadItem as d, TextPayload as f, validatePayload as g, serializeJson as h, CopyPayloadKind as i, OperationContext as k, JsonPayload as l, normalizePayload as m, CopyInput as n, HtmlPayload as o, isBlob as p, CopyPayload as r, IMAGE_MIME_TYPE as s, BlobSource as t, MultiPayload as u, CopyError as v, describePasteError as w, copyFailure as x, CopyErrorType as y };
|
|
162
|
-
//# sourceMappingURL=payload-
|
|
164
|
+
//# sourceMappingURL=payload-CcvSx_Hq.d.ts.map
|
|
@@ -66,10 +66,12 @@ declare function isRetryableError(error: CopyError): boolean;
|
|
|
66
66
|
* is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
|
|
67
67
|
*/
|
|
68
68
|
declare const COPY_FAILURE_BRAND: unique symbol;
|
|
69
|
+
interface CopyFailure {
|
|
70
|
+
readonly [COPY_FAILURE_BRAND]: true;
|
|
71
|
+
}
|
|
69
72
|
/** Error thrown by adapters to carry a fully classified {@link CopyError}. */
|
|
70
73
|
declare class CopyFailure extends Error {
|
|
71
74
|
readonly copyError: CopyError;
|
|
72
|
-
readonly [COPY_FAILURE_BRAND] = true;
|
|
73
75
|
constructor(copyError: CopyError);
|
|
74
76
|
}
|
|
75
77
|
declare function isCopyFailure(value: unknown): value is CopyFailure;
|
|
@@ -159,4 +161,4 @@ declare function validatePayload(payload: unknown): CopyError | null;
|
|
|
159
161
|
declare function serializeJson(payload: JsonPayload): string;
|
|
160
162
|
//#endregion
|
|
161
163
|
export { resolveMaxRetries as A, describeCopyError as C, toCopyError as D, isRetryableError as E, DEFAULT_MAX_RETRIES as O, createCopyError as S, isCopyFailure as T, ClipboardOperation as _, CopySource as a, CopyFailure as b, ImagePayload as c, MultiPayloadItem as d, TextPayload as f, validatePayload as g, serializeJson as h, CopyPayloadKind as i, OperationContext as k, JsonPayload as l, normalizePayload as m, CopyInput as n, HtmlPayload as o, isBlob as p, CopyPayload as r, IMAGE_MIME_TYPE as s, BlobSource as t, MultiPayload as u, CopyError as v, describePasteError as w, copyFailure as x, CopyErrorType as y };
|
|
162
|
-
//# sourceMappingURL=payload-
|
|
164
|
+
//# sourceMappingURL=payload-qkAWVXWA.d.cts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
const require_errors = require("./errors-
|
|
2
|
+
const require_errors = require("./errors-DFmEAC4E.cjs");
|
|
3
3
|
//#region src/core/payload.ts
|
|
4
4
|
/** The only image MIME type with reliable cross-browser clipboard write support. */
|
|
5
5
|
const IMAGE_MIME_TYPE = "image/png";
|
|
@@ -97,4 +97,4 @@ Object.defineProperty(exports, "validatePayload", {
|
|
|
97
97
|
}
|
|
98
98
|
});
|
|
99
99
|
|
|
100
|
-
//# sourceMappingURL=payload-
|
|
100
|
+
//# sourceMappingURL=payload-sBxkG7jH.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payload-
|
|
1
|
+
{"version":3,"file":"payload-sBxkG7jH.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+B;CAC9D,OAAO,OAAO,UAAU,WAAW;EAAE,MAAM;EAAQ,OAAO;CAAM,IAAI;AACtE;AAEA,SAAgB,OAAO,OAA+B;CACpD,IAAI,OAAO,SAAS,eAAe,iBAAiB,MAAM,OAAO;CACjE,MAAM,MAAM,OAAO,UAAU,SAAS,KAAK,KAAK;CAChD,OAAO,QAAQ,mBAAmB,QAAQ;AAC5C;AAEA,SAAS,WAAW,OAA+C;CACjE,QACG,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,UAAU,QACV,OAAQ,MAA6B,SAAS;AAElD;AAEA,MAAM,WAAW,YAA+BA,eAAAA,gBAAgB,mBAAmB,OAAO;;;;;AA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Q,yBAAyB,OAAO,UAAU,OAAO,EAAE,EAAE;CACxE;AACF;;AAGA,SAAgB,cAAc,SAA8B;CAC1D,MAAM,SACJ,QAAQ,WAAW,OAAO,IAAI,OAAO,QAAQ,WAAW,WAAW,QAAQ,SAAS,KAAA;CAEtF,IAAI;CACJ,IAAI;EACF,OAAO,KAAK,UAAU,QAAQ,OAAO,MAAM,MAAM;CACnD,SAAS,OAAO;EACd,MAAM,IAAIC,eAAAA,YACRD,eAAAA,gBAAgB,mBAAmB,yEAAyE,KAAK,CACnH;CACF;CACA,IAAI,OAAO,SAAS,UAClB,MAAM,IAAIC,eAAAA,YACRD,eAAAA,gBAAgB,mBAAmB,qFAAqF,CAC1H;CAEF,OAAO;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
const require_errors = require("./errors-
|
|
3
|
-
const require_url = require("./url-
|
|
2
|
+
const require_errors = require("./errors-DFmEAC4E.cjs");
|
|
3
|
+
const require_url = require("./url-BrhVUwn7.cjs");
|
|
4
4
|
//#region src/link/payload.ts
|
|
5
5
|
const DEFAULT_LINK_TITLE_LENGTH = 300;
|
|
6
6
|
const invalid = (message) => require_errors.copyFailure("invalid-payload", message);
|
|
@@ -129,4 +129,4 @@ Object.defineProperty(exports, "resolveLink", {
|
|
|
129
129
|
}
|
|
130
130
|
});
|
|
131
131
|
|
|
132
|
-
//# sourceMappingURL=payload-
|
|
132
|
+
//# sourceMappingURL=payload-tTK6REua.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payload-
|
|
1
|
+
{"version":3,"file":"payload-tTK6REua.cjs","names":["copyFailure","resolveLinkUrl"],"sources":["../../src/link/payload.ts"],"sourcesContent":["import { copyFailure } from '../core/errors';\nimport type { HtmlPayload, MultiPayload } from '../core/payload';\nimport { resolveLinkUrl, type LinkUrlOptions } from './url';\n\n/** A link with an optional title. */\nexport interface Link {\n readonly url: string | URL;\n /** What the link says when pasted into a document or chat. Default: the URL. */\n readonly title?: string;\n}\n\n/** A link: a URL, a `{ url, title }` object, or an `<a>` element (its `href` and text). */\nexport type LinkSource = string | URL | Link | HTMLAnchorElement;\n\n/** A validated link: an absolute, safe URL and a clean title. */\nexport interface ResolvedLink {\n readonly url: string;\n /** Never empty: the URL when there is no title. */\n readonly title: string;\n /** Whether `title` came from the input (`false`: it is the URL). */\n readonly titled: boolean;\n}\n\n/**\n * What the plain-text flavour holds (editors, terminals and address bars paste it):\n * `'url'` (the default), `'title'`, `'title-and-url'` (the title, then the URL on\n * the next line) or `'markdown'` (`[Title](URL)`).\n */\nexport type LinkTextFormat = 'url' | 'title' | 'title-and-url' | 'markdown';\n\nexport interface LinkPayloadOptions extends LinkUrlOptions {\n /** Default `'url'`. */\n readonly text?: LinkTextFormat;\n /** Longest title kept, in characters; longer ones end in an ellipsis. Default {@link DEFAULT_LINK_TITLE_LENGTH}. */\n readonly maxTitleLength?: number;\n}\n\nexport interface LinkDragPayloadOptions extends LinkPayloadOptions {\n /**\n * `'drag'`: a multi-format payload that also carries `text/uri-list` and\n * Firefox's `text/x-moz-url`, for `useDragCopy` and `useCopyInterceptor` (a link\n * dropped on the tab bar opens). Clipboard writes skip those two where the\n * browser can't write them.\n */\n readonly target: 'drag';\n}\n\nexport const DEFAULT_LINK_TITLE_LENGTH = 300;\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\n/**\n * Characters a title never keeps: controls, bidi overrides and isolates (which can\n * make a title read differently), and zero-width characters.\n */\n// eslint-disable-next-line no-control-regex -- matching control characters is the point\nconst HIDDEN = /[\\0-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f-\\x9f\\u061C\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u2066-\\u2069\\uFEFF]/g;\n\n/** A title as one clean line: hidden characters removed, whitespace collapsed, length capped. */\nexport function cleanTitle(title: string, maxLength: number): string {\n const clean = title.replace(HIDDEN, '').replace(/\\s+/g, ' ').trim();\n if (clean.length <= maxLength) return clean;\n // Cut on a code point boundary and mark the cut.\n return `${Array.from(clean).slice(0, maxLength - 1).join('').trimEnd()}\\u2026`;\n}\n\nfunction maxTitle(value: number | undefined): number {\n if (value === undefined) return DEFAULT_LINK_TITLE_LENGTH;\n if (Number.isInteger(value) && value >= 1) return value;\n throw invalid(`\\`maxTitleLength\\` must be a positive integer (received ${String(value)}).`);\n}\n\nfunction isAnchor(source: unknown): source is HTMLAnchorElement {\n return typeof source === 'object' && source !== null && (source as { nodeName?: unknown }).nodeName === 'A' && typeof (source as { href?: unknown }).href === 'string';\n}\n\n/**\n * Validates a link and its title: see {@link resolveLinkUrl} for the URL rules.\n * An `<a>` element gives its `href` and its text (or `title` attribute).\n */\nexport function resolveLink(source: LinkSource, options: LinkPayloadOptions = {}): ResolvedLink {\n let url: string | URL;\n let title: unknown;\n if (typeof source === 'string' || source instanceof URL) {\n url = source;\n } else if (isAnchor(source)) {\n url = source.getAttribute('href') ?? '';\n title = source.textContent.trim() !== '' ? source.textContent : (source.getAttribute('title') ?? undefined);\n if (url !== '' && options.base === undefined) url = source.href; // Resolved against the anchor's own document.\n } else if (typeof (source as unknown) === 'object' && (source as unknown) !== null && 'url' in source) {\n url = source.url;\n title = source.title;\n } else {\n throw invalid('A link must be a URL, a { url, title } object or an <a> element.');\n }\n if (title !== undefined && typeof title !== 'string') throw invalid('A link title must be a string.');\n const href = resolveLinkUrl(url, options);\n const clean = title === undefined ? '' : cleanTitle(title, maxTitle(options.maxTitleLength));\n return { url: href, title: clean === '' ? href : clean, titled: clean !== '' };\n}\n\nexport const escapeHtml = (text: string): string =>\n text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"').replace(/'/g, ''');\n\n/** `[title](url)`, safe in every CommonMark renderer: brackets and backslashes escaped, parentheses and spaces encoded. */\nexport function markdownLink(link: ResolvedLink): string {\n const label = link.title.replace(/[\\\\[\\]]/g, '\\\\$&');\n const target = link.url.replace(/[()<> ]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);\n return `[${label}](${target})`;\n}\n\nfunction plainText(link: ResolvedLink, format: LinkTextFormat): string {\n switch (format) {\n case 'url':\n return link.url;\n case 'title':\n return link.title;\n case 'title-and-url':\n return link.titled ? `${link.title}\\n${link.url}` : link.url;\n case 'markdown':\n return markdownLink(link);\n default:\n throw invalid(`\\`text\\` must be \"url\", \"title\", \"title-and-url\" or \"markdown\" (received ${JSON.stringify(format)}).`);\n }\n}\n\n/**\n * A copy payload for a link: an HTML anchor, so Slack, Google Docs, Notion,\n * Teams, Word and mail paste a titled link, and plain text (the URL by default)\n * for editors and address bars. The URL is validated (allowed schemes only,\n * credentials removed, optionally cleaned of tracking) and the title is cleaned\n * of hidden characters; both are escaped.\n *\n * @example\n * copy(() => linkPayload({ url: location.href, title: document.title }, { clean: true }));\n * useDragCopy({ payload: () => linkPayload(anchor, { target: 'drag' }) });\n */\nexport function linkPayload(source: LinkSource, options: LinkDragPayloadOptions): MultiPayload;\nexport function linkPayload(source: LinkSource, options?: LinkPayloadOptions): HtmlPayload;\nexport function linkPayload(source: LinkSource, options: LinkPayloadOptions & { readonly target?: 'drag' | 'clipboard' } = {}): HtmlPayload | MultiPayload {\n const target: unknown = options.target ?? 'clipboard'; // Plain-JS callers can pass anything.\n if (target !== 'drag' && target !== 'clipboard') throw invalid('`target` must be \"clipboard\" or \"drag\".');\n const link = resolveLink(source, options);\n const text = plainText(link, options.text ?? 'url');\n const html = `<a href=\"${escapeHtml(link.url)}\">${escapeHtml(link.title)}</a>`;\n if (target === 'clipboard') return { kind: 'html', html, text };\n return {\n kind: 'multi',\n items: [\n { mimeType: 'text/plain', data: text },\n { mimeType: 'text/html', data: html },\n { mimeType: 'text/uri-list', data: link.url, optional: true },\n // Firefox's titled-link format: the URL, a line break, the title.\n { mimeType: 'text/x-moz-url', data: `${link.url}\\n${link.title}`, optional: true },\n ],\n };\n}\n"],"mappings":";;;;AA+CA,MAAa,4BAA4B;AAEzC,MAAM,WAAW,YAAoBA,e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M;EACN,OAAO;GACL;IAAE,UAAU;IAAc,MAAM;GAAK;GACrC;IAAE,UAAU;IAAa,MAAM;GAAK;GACpC;IAAE,UAAU;IAAiB,MAAM,KAAK;IAAK,UAAU;GAAK;GAE5D;IAAE,UAAU;IAAkB,MAAM,GAAG,KAAK,IAAI,IAAI,KAAK;IAAS,UAAU;GAAK;EACnF;CACF;AACF"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
|
|
2
|
-
import { c as toCopyError, i as describeCopyError, r as createCopyError } from "./errors-
|
|
3
|
-
import { a as validatePayload, r as normalizePayload } from "./payload-
|
|
4
|
-
import { t as createBrowserClipboardAdapter } from "./clipboard-adapter-
|
|
5
|
-
import { i as linkUrlResolver } from "./url-
|
|
6
|
-
import { n as cleanTitle, r as linkPayload } from "./payload-
|
|
2
|
+
import { c as toCopyError, i as describeCopyError, r as createCopyError } from "./errors-CT-FfUtU.js";
|
|
3
|
+
import { a as validatePayload, r as normalizePayload } from "./payload-BrQWGwyx.js";
|
|
4
|
+
import { t as createBrowserClipboardAdapter } from "./clipboard-adapter-CmKDTFdO.js";
|
|
5
|
+
import { i as linkUrlResolver } from "./url-COID0BLY.js";
|
|
6
|
+
import { n as cleanTitle, r as linkPayload } from "./payload-BWQ6sPtS.js";
|
|
7
7
|
//#region src/share/share.ts
|
|
8
8
|
/** Phones and tablets: a touch screen is the main input and nothing hovers. */
|
|
9
9
|
const TOUCH_FIRST = "(hover: none) and (pointer: coarse)";
|
|
@@ -205,4 +205,4 @@ function describeShareError(error, method) {
|
|
|
205
205
|
//#endregion
|
|
206
206
|
export { shareOrCopy as i, describeShareError as n, shareMethod as r, TOUCH_FIRST as t };
|
|
207
207
|
|
|
208
|
-
//# sourceMappingURL=share-
|
|
208
|
+
//# sourceMappingURL=share-CU91L4EK.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"share-Bop47Znn.js","names":[],"sources":["../../src/share/share.ts"],"sourcesContent":["import { createBrowserClipboardAdapter, type ClipboardAdapter } from '../core/clipboard-adapter';\nimport { createCopyError, describeCopyError, toCopyError, type CopyError, type CopyErrorType } from '../core/errors';\nimport { normalizePayload, validatePayload, type CopyInput, type CopyPayload } from '../core/payload';\nimport { cleanTitle, DEFAULT_LINK_TITLE_LENGTH, linkPayload } from '../link/payload';\nimport { linkUrlResolver, type LinkUrlOptions } from '../link/url';\n\n/** What to share: a link, a message, files, or any mix of them. */\nexport interface ShareContent {\n /** Validated like every link in this package: allowed schemes only, credentials removed. */\n readonly url?: string | URL;\n readonly title?: string;\n /** A message to share alongside (or instead of) the link. */\n readonly text?: string;\n /** Files for the share sheet, where the browser can share them (`navigator.canShare({ files })`). Never copied. */\n readonly files?: readonly File[];\n}\n\n/** The content after validation: what the share sheet or the clipboard receives. */\nexport interface ResolvedShare {\n readonly url: string | null;\n /** Cleaned of hidden characters; `null` when there is none. */\n readonly title: string | null;\n readonly text: string | null;\n readonly files: readonly File[];\n}\n\n/**\n * How to share:\n * - `auto` (default): the share sheet on phones and tablets, where people expect it; copy elsewhere.\n * - `native`: the share sheet wherever the browser has one (also desktop Safari, Edge and Chrome on Windows and macOS).\n * - `copy`: always copy.\n */\nexport type ShareMode = 'auto' | 'native' | 'copy';\n\nexport type ShareMethod = 'native' | 'copy';\n\n/** Structural view of what sharing needs from the browser; `window` by default. */\nexport interface ShareEnvironment {\n readonly navigator?: {\n readonly share?: (data: ShareData) => Promise<void>;\n readonly canShare?: (data: ShareData) => boolean;\n };\n readonly matchMedia?: (query: string) => { readonly matches: boolean };\n}\n\nexport interface ShareOptions extends LinkUrlOptions {\n /** Default `\"auto\"`. */\n readonly mode?: ShareMode;\n /** When the share sheet fails for a reason other than the user closing it, copy instead. Default `true`. */\n readonly fallback?: boolean;\n /**\n * What to copy. Default: a titled link (`linkPayload`) when there is a URL,\n * otherwise the text. Return a string or any copy payload.\n */\n readonly copy?: (content: ResolvedShare) => CopyInput;\n /** Default: the browser Clipboard API, as `useCopy` uses. */\n readonly adapter?: ClipboardAdapter;\n /** Default: `window`. For tests, webviews and other hosts. */\n readonly environment?: ShareEnvironment;\n /** Aborting it stops a copy in progress; the share sheet itself can only be closed by the user. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Why the content was copied rather than shared: `preferred` (the mode chose\n * copy, as on desktop in `auto`), `unsupported` (no share sheet, or it can't\n * take this content) or `fallback` (the share sheet failed).\n */\nexport type CopyReason = 'preferred' | 'unsupported' | 'fallback';\n\n/** What `shareOrCopy` resolves to. It never rejects. */\nexport type ShareOutcome =\n | { readonly status: 'shared'; readonly method: 'native'; readonly content: ResolvedShare }\n | { readonly status: 'copied'; readonly method: 'copy'; readonly reason: CopyReason; readonly payload: CopyPayload; readonly content: ResolvedShare }\n /** The user closed the share sheet. Nothing to report. */\n | { readonly status: 'cancelled'; readonly method: 'native' }\n | { readonly status: 'error'; readonly method: ShareMethod; readonly error: CopyError };\n\n/** Phones and tablets: a touch screen is the main input and nothing hovers. */\nexport const TOUCH_FIRST = '(hover: none) and (pointer: coarse)';\n\nconst defaultEnvironment = (): ShareEnvironment | undefined => (typeof window === 'undefined' ? undefined : window);\n\nconst invalid = (message: string): CopyError => createCopyError('invalid-payload', message);\n\n/** Validates and cleans what to share, or returns the typed error for invalid input. */\nfunction resolveContent(content: ShareContent, options: LinkUrlOptions): ResolvedShare | CopyError {\n const value: unknown = content;\n if (typeof value !== 'object' || value === null) return invalid('Share content must be an object with a url, text or files.');\n const { url, title, text, files } = value as Record<string, unknown>;\n let href: string | null = null;\n if (url !== undefined && url !== null) {\n try {\n href = linkUrlResolver(options)(url as string | URL);\n } catch (error) {\n return toCopyError(error);\n }\n }\n if (title !== undefined && typeof title !== 'string') return invalid('`title` must be a string.');\n if (text !== undefined && typeof text !== 'string') return invalid('`text` must be a string.');\n const list: unknown = files ?? [];\n if (!Array.isArray(list) || !list.every((file: unknown) => typeof File !== 'undefined' && file instanceof File)) {\n return invalid('`files` must be a list of File objects.');\n }\n const cleanName = title === undefined ? '' : cleanTitle(title, DEFAULT_LINK_TITLE_LENGTH);\n const message = text === undefined || text.trim() === '' ? null : text;\n if (href === null && message === null && list.length === 0) return invalid('There is nothing to share: give a url, text or files.');\n return { url: href, title: cleanName === '' ? null : cleanName, text: message, files: list as File[] };\n}\n\n/** The `ShareData` the browser receives: only the fields that are set. */\nfunction shareData(content: ResolvedShare): ShareData {\n return {\n ...(content.url === null ? {} : { url: content.url }),\n ...(content.title === null ? {} : { title: content.title }),\n ...(content.text === null ? {} : { text: content.text }),\n ...(content.files.length === 0 ? {} : { files: [...content.files] }),\n };\n}\n\n/** Whether this browser can open its share sheet for `data`. */\nfunction canShareNatively(environment: ShareEnvironment | undefined, data: ShareData | null): boolean {\n const nav = environment?.navigator;\n if (typeof nav?.share !== 'function') return false;\n if (data === null) return true;\n // Without canShare (older Safari), only links and text can be shared.\n return typeof nav.canShare === 'function' ? nav.canShare(data) : data.files === undefined;\n}\n\nfunction isTouchFirst(environment: ShareEnvironment | undefined): boolean {\n return typeof environment?.matchMedia === 'function' && environment.matchMedia(TOUCH_FIRST).matches;\n}\n\nfunction resolveMode(mode: unknown): ShareMode | CopyError {\n if (mode === undefined) return 'auto';\n return mode === 'auto' || mode === 'native' || mode === 'copy' ? mode : invalid('`mode` must be \"auto\", \"native\" or \"copy\".');\n}\n\n/**\n * How {@link shareOrCopy} would share right now: `\"native\"` (the share sheet) or\n * `\"copy\"`. Use it to label the button (\"Share…\" or \"Copy link\"). Pass the\n * content when it has files, since not every share sheet takes them.\n */\nexport function shareMethod(options: Pick<ShareOptions, 'mode' | 'environment'> = {}, content?: ShareContent): ShareMethod {\n const mode = resolveMode(options.mode);\n if (typeof mode !== 'string' || mode === 'copy') return 'copy';\n const environment = options.environment ?? defaultEnvironment();\n if (mode === 'auto' && !isTouchFirst(environment)) return 'copy';\n const resolved = content === undefined ? null : resolveContent(content, {});\n const data = resolved === null ? null : 'type' in resolved ? undefined : shareData(resolved);\n return data !== undefined && canShareNatively(environment, data) ? 'native' : 'copy';\n}\n\n/** The default copy: a titled link when there is a URL, otherwise the text (one of them is always set here). */\nfunction defaultCopy(content: ResolvedShare): CopyInput {\n if (content.url !== null) return linkPayload({ url: content.url, ...(content.title === null ? {} : { title: content.title }) });\n return content.text as string;\n}\n\nasync function copyContent(content: ResolvedShare, reason: CopyReason, options: ShareOptions): Promise<ShareOutcome> {\n if (options.copy === undefined && content.url === null && content.text === null) {\n return { status: 'error', method: 'copy', error: createCopyError('unsupported-format', 'Files can only be shared through a share sheet, and this browser has none for them.') };\n }\n let payload: CopyPayload;\n try {\n payload = normalizePayload((options.copy ?? defaultCopy)(content));\n } catch (error) {\n return { status: 'error', method: 'copy', error: toCopyError(error) };\n }\n const problem = validatePayload(payload);\n if (problem !== null) return { status: 'error', method: 'copy', error: problem };\n if (options.signal?.aborted === true) return { status: 'error', method: 'copy', error: createCopyError('aborted', 'The share was aborted.') };\n try {\n await (options.adapter ?? createBrowserClipboardAdapter()).write(payload, options.signal === undefined ? undefined : { signal: options.signal });\n } catch (error) {\n return { status: 'error', method: 'copy', error: toCopyError(error) };\n }\n return { status: 'copied', method: 'copy', reason, payload, content };\n}\n\n/**\n * Shares through the device's share sheet where people expect one, and copies a\n * titled link everywhere else. Call it directly in a click handler: the share\n * sheet needs the user's gesture.\n *\n * It never rejects. It resolves to `shared`, `copied` (with why), `cancelled`\n * (the user closed the share sheet: nothing to report) or `error` with a typed\n * {@link CopyError}.\n *\n * @example\n * button.addEventListener('click', async () => {\n * const outcome = await shareOrCopy({ url: location.href, title: document.title });\n * if (outcome.status === 'copied') toast('Link copied');\n * });\n */\nexport async function shareOrCopy(content: ShareContent, options: ShareOptions = {}): Promise<ShareOutcome> {\n const mode = resolveMode(options.mode);\n if (typeof mode !== 'string') return { status: 'error', method: 'copy', error: mode };\n const resolved = resolveContent(content, options);\n if ('type' in resolved) return { status: 'error', method: 'copy', error: resolved };\n const environment = options.environment ?? defaultEnvironment();\n if (mode === 'copy' || (mode === 'auto' && !isTouchFirst(environment))) return copyContent(resolved, 'preferred', options);\n const data = shareData(resolved);\n if (!canShareNatively(environment, data)) return copyContent(resolved, 'unsupported', options);\n try {\n // Called before any await: the share sheet needs the click's user activation.\n await (environment?.navigator?.share as (data: ShareData) => Promise<void>)(data);\n return { status: 'shared', method: 'native', content: resolved };\n } catch (error) {\n if (readName(error) === 'AbortError') return { status: 'cancelled', method: 'native' };\n if (options.fallback === false) return { status: 'error', method: 'native', error: shareError(error) };\n return copyContent(resolved, 'fallback', options);\n }\n}\n\nfunction readName(error: unknown): string | undefined {\n const name: unknown = typeof error === 'object' && error !== null ? (error as { name?: unknown }).name : undefined;\n return typeof name === 'string' ? name : undefined;\n}\n\n/** Classifies a share sheet failure. */\nfunction shareError(cause: unknown): CopyError {\n switch (readName(cause)) {\n case 'NotAllowedError':\n return createCopyError('permission-denied', 'The share sheet was blocked: it needs a click, and an iframe needs the web-share permission.', cause);\n case 'InvalidStateError':\n return createCopyError('unknown', 'Another share sheet is already open.', cause);\n case 'DataError':\n case 'TypeError':\n return createCopyError('unsupported-format', 'The share sheet rejected this content.', cause);\n default:\n return toCopyError(cause);\n }\n}\n\nconst SHARE_DESCRIPTIONS: Partial<Readonly<Record<CopyErrorType, string>>> = {\n 'permission-denied': \"Sharing isn't allowed here.\",\n 'unsupported-format': \"This can't be shared from this browser.\",\n timeout: 'Sharing took too long. Try again.',\n};\n\n/**\n * Default English, user-facing sentence for a failed share: a share sheet\n * failure is described as sharing, a failed copy as copying. Replace for i18n.\n */\nexport function describeShareError(error: CopyError, method: ShareMethod): string {\n if (method === 'copy') return describeCopyError(error);\n return SHARE_DESCRIPTIONS[error.type] ?? \"Couldn't share. Try again.\";\n}\n"],"mappings":";;;;;;;;AA+EA,MAAa,cAAc;AAE3B,MAAM,2BAA0D,OAAO,WAAW,cAAc,KAAA,IAAY;AAE5G,MAAM,WAAW,YAA+B,gBAAgB,mBAAmB,OAAO;;AAG1F,SAAS,eAAe,SAAuB,SAAoD;CACjG,MAAM,QAAiB;CACvB,IAAI,O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Aa,IAAI,GAAG,OAAO,YAAY,UAAU,eAAe,OAAO;CAC7F,IAAI;EAEF,OAAO,aAAa,WAAW,MAAA,CAA6C,IAAI;EAChF,OAAO;GAAE,QAAQ;GAAU,QAAQ;GAAU,SAAS;EAAS;CACjE,SAAS,OAAO;EACd,IAAI,SAAS,KAAK,MAAM,cAAc,OAAO;GAAE,QAAQ;GAAa,QAAQ;EAAS;EACrF,IAAI,QAAQ,aAAa,OAAO,OAAO;GAAE,QAAQ;GAAS,QAAQ;GAAU,OAAO,WAAW,KAAK;EAAE;EACrG,OAAO,YAAY,UAAU,YAAY,OAAO;CAClD;AACF;AAEA,SAAS,SAAS,OAAoC;CACpD,MAAM,OAAgB,OAAO,UAAU,YAAY,UAAU,OAAQ,MAA6B,OAAO,KAAA;CACzG,OAAO,OAAO,SAAS,WAAW,OAAO,KAAA;AAC3C;;AAGA,SAAS,WAAW,OAA2B;CAC7C,QAAQ,SAAS,KAAK,GAAtB;EACE,KAAK,mBACH,OAAO,gBAAgB,qBAAqB,gGAAgG,KAAK;EACnJ,KAAK,qBACH,OAAO,gBAAgB,WAAW,wCAAwC,KAAK;EACjF,KAAK;EACL,KAAK,aACH,OAAO,gBAAgB,sBAAsB,0CAA0C,KAAK;EAC9F,SACE,OAAO,YAAY,KAAK;CAC5B;AACF;AAEA,MAAM,qBAAuE;CAC3E,qBAAqB;CACrB,sBAAsB;CACtB,SAAS;AACX;;;;;AAMA,SAAgB,mBAAmB,OAAkB,QAA6B;CAChF,IAAI,WAAW,QAAQ,OAAO,kBAAkB,KAAK;CACrD,OAAO,mBAAmB,MAAM,SAAS;AAC3C"}
|
|
1
|
+
{"version":3,"file":"share-CU91L4EK.js","names":[],"sources":["../../src/share/share.ts"],"sourcesContent":["import { createBrowserClipboardAdapter, type ClipboardAdapter } from '../core/clipboard-adapter';\nimport { createCopyError, describeCopyError, toCopyError, type CopyError, type CopyErrorType } from '../core/errors';\nimport { normalizePayload, validatePayload, type CopyInput, type CopyPayload } from '../core/payload';\nimport { cleanTitle, DEFAULT_LINK_TITLE_LENGTH, linkPayload } from '../link/payload';\nimport { linkUrlResolver, type LinkUrlOptions } from '../link/url';\n\n/** What to share: a link, a message, files, or any mix of them. */\nexport interface ShareContent {\n /** Validated like every link in this package: allowed schemes only, credentials removed. */\n readonly url?: string | URL;\n readonly title?: string;\n /** A message to share alongside (or instead of) the link. */\n readonly text?: string;\n /** Files for the share sheet, where the browser can share them (`navigator.canShare({ files })`). Never copied. */\n readonly files?: readonly File[];\n}\n\n/** The content after validation: what the share sheet or the clipboard receives. */\nexport interface ResolvedShare {\n readonly url: string | null;\n /** Cleaned of hidden characters; `null` when there is none. */\n readonly title: string | null;\n readonly text: string | null;\n readonly files: readonly File[];\n}\n\n/**\n * How to share:\n * - `auto` (default): the share sheet on phones and tablets, where people expect it; copy elsewhere.\n * - `native`: the share sheet wherever the browser has one (also desktop Safari, Edge and Chrome on Windows and macOS).\n * - `copy`: always copy.\n */\nexport type ShareMode = 'auto' | 'native' | 'copy';\n\nexport type ShareMethod = 'native' | 'copy';\n\n/** Structural view of what sharing needs from the browser; `window` by default. */\nexport interface ShareEnvironment {\n readonly navigator?: {\n readonly share?: (data: ShareData) => Promise<void>;\n readonly canShare?: (data: ShareData) => boolean;\n };\n readonly matchMedia?: (query: string) => { readonly matches: boolean };\n}\n\nexport interface ShareOptions extends LinkUrlOptions {\n /** Default `\"auto\"`. */\n readonly mode?: ShareMode;\n /** When the share sheet fails for a reason other than the user closing it, copy instead. Default `true`. */\n readonly fallback?: boolean;\n /**\n * What to copy. Default: a titled link (`linkPayload`) when there is a URL,\n * otherwise the text. Return a string or any copy payload.\n */\n readonly copy?: (content: ResolvedShare) => CopyInput;\n /** Default: the browser Clipboard API, as `useCopy` uses. */\n readonly adapter?: ClipboardAdapter;\n /** Default: `window`. For tests, webviews and other hosts. */\n readonly environment?: ShareEnvironment;\n /** Aborting it stops a copy in progress; the share sheet itself can only be closed by the user. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Why the content was copied rather than shared: `preferred` (the mode chose\n * copy, as on desktop in `auto`), `unsupported` (no share sheet, or it can't\n * take this content) or `fallback` (the share sheet failed).\n */\nexport type CopyReason = 'preferred' | 'unsupported' | 'fallback';\n\n/** What `shareOrCopy` resolves to. It never rejects. */\nexport type ShareOutcome =\n | { readonly status: 'shared'; readonly method: 'native'; readonly content: ResolvedShare }\n | { readonly status: 'copied'; readonly method: 'copy'; readonly reason: CopyReason; readonly payload: CopyPayload; readonly content: ResolvedShare }\n /** The user closed the share sheet. Nothing to report. */\n | { readonly status: 'cancelled'; readonly method: 'native' }\n | { readonly status: 'error'; readonly method: ShareMethod; readonly error: CopyError };\n\n/** Phones and tablets: a touch screen is the main input and nothing hovers. */\nexport const TOUCH_FIRST = '(hover: none) and (pointer: coarse)';\n\nconst defaultEnvironment = (): ShareEnvironment | undefined => (typeof window === 'undefined' ? undefined : window);\n\nconst invalid = (message: string): CopyError => createCopyError('invalid-payload', message);\n\n/** Validates and cleans what to share, or returns the typed error for invalid input. */\nfunction resolveContent(content: ShareContent, options: LinkUrlOptions): ResolvedShare | CopyError {\n const value: unknown = content;\n if (typeof value !== 'object' || value === null) return invalid('Share content must be an object with a url, text or files.');\n const { url, title, text, files } = value as Record<string, unknown>;\n let href: string | null = null;\n if (url !== undefined && url !== null) {\n try {\n href = linkUrlResolver(options)(url as string | URL);\n } catch (error) {\n return toCopyError(error);\n }\n }\n if (title !== undefined && typeof title !== 'string') return invalid('`title` must be a string.');\n if (text !== undefined && typeof text !== 'string') return invalid('`text` must be a string.');\n const list: unknown = files ?? [];\n if (!Array.isArray(list) || !list.every((file: unknown) => typeof File !== 'undefined' && file instanceof File)) {\n return invalid('`files` must be a list of File objects.');\n }\n const cleanName = title === undefined ? '' : cleanTitle(title, DEFAULT_LINK_TITLE_LENGTH);\n const message = text === undefined || text.trim() === '' ? null : text;\n if (href === null && message === null && list.length === 0) return invalid('There is nothing to share: give a url, text or files.');\n return { url: href, title: cleanName === '' ? null : cleanName, text: message, files: list as File[] };\n}\n\n/** The `ShareData` the browser receives: only the fields that are set. */\nfunction shareData(content: ResolvedShare): ShareData {\n return {\n ...(content.url === null ? {} : { url: content.url }),\n ...(content.title === null ? {} : { title: content.title }),\n ...(content.text === null ? {} : { text: content.text }),\n ...(content.files.length === 0 ? {} : { files: [...content.files] }),\n };\n}\n\n/** Whether this browser can open its share sheet for `data`. */\nfunction canShareNatively(environment: ShareEnvironment | undefined, data: ShareData | null): boolean {\n const nav = environment?.navigator;\n if (typeof nav?.share !== 'function') return false;\n if (data === null) return true;\n // Without canShare (older Safari), only links and text can be shared.\n return typeof nav.canShare === 'function' ? nav.canShare(data) : data.files === undefined;\n}\n\nfunction isTouchFirst(environment: ShareEnvironment | undefined): boolean {\n return typeof environment?.matchMedia === 'function' && environment.matchMedia(TOUCH_FIRST).matches;\n}\n\nfunction resolveMode(mode: unknown): ShareMode | CopyError {\n if (mode === undefined) return 'auto';\n return mode === 'auto' || mode === 'native' || mode === 'copy' ? mode : invalid('`mode` must be \"auto\", \"native\" or \"copy\".');\n}\n\n/**\n * How {@link shareOrCopy} would share right now: `\"native\"` (the share sheet) or\n * `\"copy\"`. Use it to label the button (\"Share…\" or \"Copy link\"). Pass the\n * content when it has files, since not every share sheet takes them.\n */\nexport function shareMethod(options: Pick<ShareOptions, 'mode' | 'environment'> = {}, content?: ShareContent): ShareMethod {\n const mode = resolveMode(options.mode);\n if (typeof mode !== 'string' || mode === 'copy') return 'copy';\n const environment = options.environment ?? defaultEnvironment();\n if (mode === 'auto' && !isTouchFirst(environment)) return 'copy';\n const resolved = content === undefined ? null : resolveContent(content, {});\n const data = resolved === null ? null : 'type' in resolved ? undefined : shareData(resolved);\n return data !== undefined && canShareNatively(environment, data) ? 'native' : 'copy';\n}\n\n/** The default copy: a titled link when there is a URL, otherwise the text (one of them is always set here). */\nfunction defaultCopy(content: ResolvedShare): CopyInput {\n if (content.url !== null) return linkPayload({ url: content.url, ...(content.title === null ? {} : { title: content.title }) });\n return content.text as string;\n}\n\nasync function copyContent(content: ResolvedShare, reason: CopyReason, options: ShareOptions): Promise<ShareOutcome> {\n if (options.copy === undefined && content.url === null && content.text === null) {\n return { status: 'error', method: 'copy', error: createCopyError('unsupported-format', 'Files can only be shared through a share sheet, and this browser has none for them.') };\n }\n let payload: CopyPayload;\n try {\n payload = normalizePayload((options.copy ?? defaultCopy)(content));\n } catch (error) {\n return { status: 'error', method: 'copy', error: toCopyError(error) };\n }\n const problem = validatePayload(payload);\n if (problem !== null) return { status: 'error', method: 'copy', error: problem };\n if (options.signal?.aborted === true) return { status: 'error', method: 'copy', error: createCopyError('aborted', 'The share was aborted.') };\n try {\n await (options.adapter ?? createBrowserClipboardAdapter()).write(payload, options.signal === undefined ? undefined : { signal: options.signal });\n } catch (error) {\n return { status: 'error', method: 'copy', error: toCopyError(error) };\n }\n return { status: 'copied', method: 'copy', reason, payload, content };\n}\n\n/**\n * Shares through the device's share sheet where people expect one, and copies a\n * titled link everywhere else. Call it directly in a click handler: the share\n * sheet needs the user's gesture.\n *\n * It never rejects. It resolves to `shared`, `copied` (with why), `cancelled`\n * (the user closed the share sheet: nothing to report) or `error` with a typed\n * {@link CopyError}.\n *\n * @example\n * button.addEventListener('click', async () => {\n * const outcome = await shareOrCopy({ url: location.href, title: document.title });\n * if (outcome.status === 'copied') toast('Link copied');\n * });\n */\nexport async function shareOrCopy(content: ShareContent, options: ShareOptions = {}): Promise<ShareOutcome> {\n const mode = resolveMode(options.mode);\n if (typeof mode !== 'string') return { status: 'error', method: 'copy', error: mode };\n const resolved = resolveContent(content, options);\n if ('type' in resolved) return { status: 'error', method: 'copy', error: resolved };\n const environment = options.environment ?? defaultEnvironment();\n if (mode === 'copy' || (mode === 'auto' && !isTouchFirst(environment))) return copyContent(resolved, 'preferred', options);\n const data = shareData(resolved);\n if (!canShareNatively(environment, data)) return copyContent(resolved, 'unsupported', options);\n try {\n // Called before any await: the share sheet needs the click's user activation.\n await (environment?.navigator?.share as (data: ShareData) => Promise<void>)(data);\n return { status: 'shared', method: 'native', content: resolved };\n } catch (error) {\n if (readName(error) === 'AbortError') return { status: 'cancelled', method: 'native' };\n if (options.fallback === false) return { status: 'error', method: 'native', error: shareError(error) };\n return copyContent(resolved, 'fallback', options);\n }\n}\n\nfunction readName(error: unknown): string | undefined {\n const name: unknown = typeof error === 'object' && error !== null ? (error as { name?: unknown }).name : undefined;\n return typeof name === 'string' ? name : undefined;\n}\n\n/** Classifies a share sheet failure. */\nfunction shareError(cause: unknown): CopyError {\n switch (readName(cause)) {\n case 'NotAllowedError':\n return createCopyError('permission-denied', 'The share sheet was blocked: it needs a click, and an iframe needs the web-share permission.', cause);\n case 'InvalidStateError':\n return createCopyError('unknown', 'Another share sheet is already open.', cause);\n case 'DataError':\n case 'TypeError':\n return createCopyError('unsupported-format', 'The share sheet rejected this content.', cause);\n default:\n return toCopyError(cause);\n }\n}\n\nconst SHARE_DESCRIPTIONS: Partial<Readonly<Record<CopyErrorType, string>>> = {\n 'permission-denied': \"Sharing isn't allowed here.\",\n 'unsupported-format': \"This can't be shared from this browser.\",\n timeout: 'Sharing took too long. Try again.',\n};\n\n/**\n * Default English, user-facing sentence for a failed share: a share sheet\n * failure is described as sharing, a failed copy as copying. Replace for i18n.\n */\nexport function describeShareError(error: CopyError, method: ShareMethod): string {\n if (method === 'copy') return describeCopyError(error);\n return SHARE_DESCRIPTIONS[error.type] ?? \"Couldn't share. Try again.\";\n}\n"],"mappings":";;;;;;;;AA+EA,MAAa,cAAc;AAE3B,MAAM,2BAA0D,OAAO,WAAW,cAAc,KAAA,IAAY;AAE5G,MAAM,WAAW,YAA+B,gBAAgB,mBAAmB,OAAO;;AAG1F,SAAS,eAAe,SAAuB,SAAoD;CACjG,MAAM,QAAiB;CACvB,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO,QAAQ,4DAA4D;CAC5H,MAAM,EAAE,KAAK,OAAO,MAAM,UAAU;CACpC,IAAI,OAAsB;CAC1B,IAAI,QAAQ,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QAAQ;GAAU,SAAS;EAAS;CACjE,SAAS,OAAO;EACd,IAAI,SAAS,KAAK,MAAM,cAAc,OAAO;GAAE,QAAQ;GAAa,QAAQ;EAAS;EACrF,IAAI,QAAQ,aAAa,OAAO,OAAO;GAAE,QAAQ;GAAS,QAAQ;GAAU,OAAO,WAAW,KAAK;EAAE;EACrG,OAAO,YAAY,UAAU,YAAY,OAAO;CAClD;AACF;AAEA,SAAS,SAAS,OAAoC;CACpD,MAAM,OAAgB,OAAO,UAAU,YAAY,UAAU,OAAQ,MAA6B,OAAO,KAAA;CACzG,OAAO,OAAO,SAAS,WAAW,OAAO,KAAA;AAC3C;;AAGA,SAAS,WAAW,OAA2B;CAC7C,QAAQ,SAAS,KAAK,GAAtB;EACE,KAAK,mBACH,OAAO,gBAAgB,qBAAqB,gGAAgG,KAAK;EACnJ,KAAK,qBACH,OAAO,gBAAgB,WAAW,wCAAwC,KAAK;EACjF,KAAK;EACL,KAAK,aACH,OAAO,gBAAgB,sBAAsB,0CAA0C,KAAK;EAC9F,SACE,OAAO,YAAY,KAAK;CAC5B;AACF;AAEA,MAAM,qBAAuE;CAC3E,qBAAqB;CACrB,sBAAsB;CACtB,SAAS;AACX;;;;;AAMA,SAAgB,mBAAmB,OAAkB,QAA6B;CAChF,IAAI,WAAW,QAAQ,OAAO,kBAAkB,KAAK;CACrD,OAAO,mBAAmB,MAAM,SAAS;AAC3C"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import { n as CopyInput, r as CopyPayload, v as CopyError } from "./payload-
|
|
3
|
-
import { n as ClipboardAdapter } from "./clipboard-adapter-
|
|
2
|
+
import { n as CopyInput, r as CopyPayload, v as CopyError } from "./payload-CcvSx_Hq.js";
|
|
3
|
+
import { n as ClipboardAdapter } from "./clipboard-adapter-Chm6zq60.js";
|
|
4
4
|
import { r as LinkUrlOptions } from "./url-DWdElCT3.js";
|
|
5
5
|
//#region src/share/share.d.ts
|
|
6
6
|
/** What to share: a link, a message, files, or any mix of them. */
|
|
@@ -112,4 +112,4 @@ declare function shareOrCopy(content: ShareContent, options?: ShareOptions): Pro
|
|
|
112
112
|
declare function describeShareError(error: CopyError, method: ShareMethod): string;
|
|
113
113
|
//#endregion
|
|
114
114
|
export { ShareMethod as a, ShareOutcome as c, shareOrCopy as d, ShareEnvironment as i, describeShareError as l, ResolvedShare as n, ShareMode as o, ShareContent as r, ShareOptions as s, CopyReason as t, shareMethod as u };
|
|
115
|
-
//# sourceMappingURL=share-
|
|
115
|
+
//# sourceMappingURL=share-DVR_DhHc.d.ts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import { n as CopyInput, r as CopyPayload, v as CopyError } from "./payload-
|
|
3
|
-
import { n as ClipboardAdapter } from "./clipboard-adapter-
|
|
2
|
+
import { n as CopyInput, r as CopyPayload, v as CopyError } from "./payload-qkAWVXWA.cjs";
|
|
3
|
+
import { n as ClipboardAdapter } from "./clipboard-adapter-CfaIbZpv.cjs";
|
|
4
4
|
import { r as LinkUrlOptions } from "./url-DWdElCT3.cjs";
|
|
5
5
|
//#region src/share/share.d.ts
|
|
6
6
|
/** What to share: a link, a message, files, or any mix of them. */
|
|
@@ -112,4 +112,4 @@ declare function shareOrCopy(content: ShareContent, options?: ShareOptions): Pro
|
|
|
112
112
|
declare function describeShareError(error: CopyError, method: ShareMethod): string;
|
|
113
113
|
//#endregion
|
|
114
114
|
export { ShareMethod as a, ShareOutcome as c, shareOrCopy as d, ShareEnvironment as i, describeShareError as l, ResolvedShare as n, ShareMode as o, ShareContent as r, ShareOptions as s, CopyReason as t, shareMethod as u };
|
|
115
|
-
//# sourceMappingURL=share-
|
|
115
|
+
//# sourceMappingURL=share-hIwth7Dh.d.cts.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
|
|
2
|
-
const require_errors = require("./errors-
|
|
3
|
-
const require_payload = require("./payload-
|
|
4
|
-
const require_clipboard_adapter = require("./clipboard-adapter-
|
|
5
|
-
const require_url = require("./url-
|
|
6
|
-
const require_payload$1 = require("./payload-
|
|
2
|
+
const require_errors = require("./errors-DFmEAC4E.cjs");
|
|
3
|
+
const require_payload = require("./payload-sBxkG7jH.cjs");
|
|
4
|
+
const require_clipboard_adapter = require("./clipboard-adapter-UIFc_Qso.cjs");
|
|
5
|
+
const require_url = require("./url-BrhVUwn7.cjs");
|
|
6
|
+
const require_payload$1 = require("./payload-tTK6REua.cjs");
|
|
7
7
|
//#region src/share/share.ts
|
|
8
8
|
/** Phones and tablets: a touch screen is the main input and nothing hovers. */
|
|
9
9
|
const TOUCH_FIRST = "(hover: none) and (pointer: coarse)";
|
|
@@ -228,4 +228,4 @@ Object.defineProperty(exports, "shareOrCopy", {
|
|
|
228
228
|
}
|
|
229
229
|
});
|
|
230
230
|
|
|
231
|
-
//# sourceMappingURL=share-
|
|
231
|
+
//# sourceMappingURL=share-nx7M4Z0t.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"share-ayDz974N.cjs","names":["createCopyError","linkUrlResolver","toCopyError","cleanTitle","linkPayload","normalizePayload","validatePayload","createBrowserClipboardAdapter","describeCopyError"],"sources":["../../src/share/share.ts"],"sourcesContent":["import { createBrowserClipboardAdapter, type ClipboardAdapter } from '../core/clipboard-adapter';\nimport { createCopyError, describeCopyError, toCopyError, type CopyError, type CopyErrorType } from '../core/errors';\nimport { normalizePayload, validatePayload, type CopyInput, type CopyPayload } from '../core/payload';\nimport { cleanTitle, DEFAULT_LINK_TITLE_LENGTH, linkPayload } from '../link/payload';\nimport { linkUrlResolver, type LinkUrlOptions } from '../link/url';\n\n/** What to share: a link, a message, files, or any mix of them. */\nexport interface ShareContent {\n /** Validated like every link in this package: allowed schemes only, credentials removed. */\n readonly url?: string | URL;\n readonly title?: string;\n /** A message to share alongside (or instead of) the link. */\n readonly text?: string;\n /** Files for the share sheet, where the browser can share them (`navigator.canShare({ files })`). Never copied. */\n readonly files?: readonly File[];\n}\n\n/** The content after validation: what the share sheet or the clipboard receives. */\nexport interface ResolvedShare {\n readonly url: string | null;\n /** Cleaned of hidden characters; `null` when there is none. */\n readonly title: string | null;\n readonly text: string | null;\n readonly files: readonly File[];\n}\n\n/**\n * How to share:\n * - `auto` (default): the share sheet on phones and tablets, where people expect it; copy elsewhere.\n * - `native`: the share sheet wherever the browser has one (also desktop Safari, Edge and Chrome on Windows and macOS).\n * - `copy`: always copy.\n */\nexport type ShareMode = 'auto' | 'native' | 'copy';\n\nexport type ShareMethod = 'native' | 'copy';\n\n/** Structural view of what sharing needs from the browser; `window` by default. */\nexport interface ShareEnvironment {\n readonly navigator?: {\n readonly share?: (data: ShareData) => Promise<void>;\n readonly canShare?: (data: ShareData) => boolean;\n };\n readonly matchMedia?: (query: string) => { readonly matches: boolean };\n}\n\nexport interface ShareOptions extends LinkUrlOptions {\n /** Default `\"auto\"`. */\n readonly mode?: ShareMode;\n /** When the share sheet fails for a reason other than the user closing it, copy instead. Default `true`. */\n readonly fallback?: boolean;\n /**\n * What to copy. Default: a titled link (`linkPayload`) when there is a URL,\n * otherwise the text. Return a string or any copy payload.\n */\n readonly copy?: (content: ResolvedShare) => CopyInput;\n /** Default: the browser Clipboard API, as `useCopy` uses. */\n readonly adapter?: ClipboardAdapter;\n /** Default: `window`. For tests, webviews and other hosts. */\n readonly environment?: ShareEnvironment;\n /** Aborting it stops a copy in progress; the share sheet itself can only be closed by the user. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Why the content was copied rather than shared: `preferred` (the mode chose\n * copy, as on desktop in `auto`), `unsupported` (no share sheet, or it can't\n * take this content) or `fallback` (the share sheet failed).\n */\nexport type CopyReason = 'preferred' | 'unsupported' | 'fallback';\n\n/** What `shareOrCopy` resolves to. It never rejects. */\nexport type ShareOutcome =\n | { readonly status: 'shared'; readonly method: 'native'; readonly content: ResolvedShare }\n | { readonly status: 'copied'; readonly method: 'copy'; readonly reason: CopyReason; readonly payload: CopyPayload; readonly content: ResolvedShare }\n /** The user closed the share sheet. Nothing to report. */\n | { readonly status: 'cancelled'; readonly method: 'native' }\n | { readonly status: 'error'; readonly method: ShareMethod; readonly error: CopyError };\n\n/** Phones and tablets: a touch screen is the main input and nothing hovers. */\nexport const TOUCH_FIRST = '(hover: none) and (pointer: coarse)';\n\nconst defaultEnvironment = (): ShareEnvironment | undefined => (typeof window === 'undefined' ? undefined : window);\n\nconst invalid = (message: string): CopyError => createCopyError('invalid-payload', message);\n\n/** Validates and cleans what to share, or returns the typed error for invalid input. */\nfunction resolveContent(content: ShareContent, options: LinkUrlOptions): ResolvedShare | CopyError {\n const value: unknown = content;\n if (typeof value !== 'object' || value === null) return invalid('Share content must be an object with a url, text or files.');\n const { url, title, text, files } = value as Record<string, unknown>;\n let href: string | null = null;\n if (url !== undefined && url !== null) {\n try {\n href = linkUrlResolver(options)(url as string | URL);\n } catch (error) {\n return toCopyError(error);\n }\n }\n if (title !== undefined && typeof title !== 'string') return invalid('`title` must be a string.');\n if (text !== undefined && typeof text !== 'string') return invalid('`text` must be a string.');\n const list: unknown = files ?? [];\n if (!Array.isArray(list) || !list.every((file: unknown) => typeof File !== 'undefined' && file instanceof File)) {\n return invalid('`files` must be a list of File objects.');\n }\n const cleanName = title === undefined ? '' : cleanTitle(title, DEFAULT_LINK_TITLE_LENGTH);\n const message = text === undefined || text.trim() === '' ? null : text;\n if (href === null && message === null && list.length === 0) return invalid('There is nothing to share: give a url, text or files.');\n return { url: href, title: cleanName === '' ? null : cleanName, text: message, files: list as File[] };\n}\n\n/** The `ShareData` the browser receives: only the fields that are set. */\nfunction shareData(content: ResolvedShare): ShareData {\n return {\n ...(content.url === null ? {} : { url: content.url }),\n ...(content.title === null ? {} : { title: content.title }),\n ...(content.text === null ? {} : { text: content.text }),\n ...(content.files.length === 0 ? {} : { files: [...content.files] }),\n };\n}\n\n/** Whether this browser can open its share sheet for `data`. */\nfunction canShareNatively(environment: ShareEnvironment | undefined, data: ShareData | null): boolean {\n const nav = environment?.navigator;\n if (typeof nav?.share !== 'function') return false;\n if (data === null) return true;\n // Without canShare (older Safari), only links and text can be shared.\n return typeof nav.canShare === 'function' ? nav.canShare(data) : data.files === undefined;\n}\n\nfunction isTouchFirst(environment: ShareEnvironment | undefined): boolean {\n return typeof environment?.matchMedia === 'function' && environment.matchMedia(TOUCH_FIRST).matches;\n}\n\nfunction resolveMode(mode: unknown): ShareMode | CopyError {\n if (mode === undefined) return 'auto';\n return mode === 'auto' || mode === 'native' || mode === 'copy' ? mode : invalid('`mode` must be \"auto\", \"native\" or \"copy\".');\n}\n\n/**\n * How {@link shareOrCopy} would share right now: `\"native\"` (the share sheet) or\n * `\"copy\"`. Use it to label the button (\"Share…\" or \"Copy link\"). Pass the\n * content when it has files, since not every share sheet takes them.\n */\nexport function shareMethod(options: Pick<ShareOptions, 'mode' | 'environment'> = {}, content?: ShareContent): ShareMethod {\n const mode = resolveMode(options.mode);\n if (typeof mode !== 'string' || mode === 'copy') return 'copy';\n const environment = options.environment ?? defaultEnvironment();\n if (mode === 'auto' && !isTouchFirst(environment)) return 'copy';\n const resolved = content === undefined ? null : resolveContent(content, {});\n const data = resolved === null ? null : 'type' in resolved ? undefined : shareData(resolved);\n return data !== undefined && canShareNatively(environment, data) ? 'native' : 'copy';\n}\n\n/** The default copy: a titled link when there is a URL, otherwise the text (one of them is always set here). */\nfunction defaultCopy(content: ResolvedShare): CopyInput {\n if (content.url !== null) return linkPayload({ url: content.url, ...(content.title === null ? {} : { title: content.title }) });\n return content.text as string;\n}\n\nasync function copyContent(content: ResolvedShare, reason: CopyReason, options: ShareOptions): Promise<ShareOutcome> {\n if (options.copy === undefined && content.url === null && content.text === null) {\n return { status: 'error', method: 'copy', error: createCopyError('unsupported-format', 'Files can only be shared through a share sheet, and this browser has none for them.') };\n }\n let payload: CopyPayload;\n try {\n payload = normalizePayload((options.copy ?? defaultCopy)(content));\n } catch (error) {\n return { status: 'error', method: 'copy', error: toCopyError(error) };\n }\n const problem = validatePayload(payload);\n if (problem !== null) return { status: 'error', method: 'copy', error: problem };\n if (options.signal?.aborted === true) return { status: 'error', method: 'copy', error: createCopyError('aborted', 'The share was aborted.') };\n try {\n await (options.adapter ?? createBrowserClipboardAdapter()).write(payload, options.signal === undefined ? undefined : { signal: options.signal });\n } catch (error) {\n return { status: 'error', method: 'copy', error: toCopyError(error) };\n }\n return { status: 'copied', method: 'copy', reason, payload, content };\n}\n\n/**\n * Shares through the device's share sheet where people expect one, and copies a\n * titled link everywhere else. Call it directly in a click handler: the share\n * sheet needs the user's gesture.\n *\n * It never rejects. It resolves to `shared`, `copied` (with why), `cancelled`\n * (the user closed the share sheet: nothing to report) or `error` with a typed\n * {@link CopyError}.\n *\n * @example\n * button.addEventListener('click', async () => {\n * const outcome = await shareOrCopy({ url: location.href, title: document.title });\n * if (outcome.status === 'copied') toast('Link copied');\n * });\n */\nexport async function shareOrCopy(content: ShareContent, options: ShareOptions = {}): Promise<ShareOutcome> {\n const mode = resolveMode(options.mode);\n if (typeof mode !== 'string') return { status: 'error', method: 'copy', error: mode };\n const resolved = resolveContent(content, options);\n if ('type' in resolved) return { status: 'error', method: 'copy', error: resolved };\n const environment = options.environment ?? defaultEnvironment();\n if (mode === 'copy' || (mode === 'auto' && !isTouchFirst(environment))) return copyContent(resolved, 'preferred', options);\n const data = shareData(resolved);\n if (!canShareNatively(environment, data)) return copyContent(resolved, 'unsupported', options);\n try {\n // Called before any await: the share sheet needs the click's user activation.\n await (environment?.navigator?.share as (data: ShareData) => Promise<void>)(data);\n return { status: 'shared', method: 'native', content: resolved };\n } catch (error) {\n if (readName(error) === 'AbortError') return { status: 'cancelled', method: 'native' };\n if (options.fallback === false) return { status: 'error', method: 'native', error: shareError(error) };\n return copyContent(resolved, 'fallback', options);\n }\n}\n\nfunction readName(error: unknown): string | undefined {\n const name: unknown = typeof error === 'object' && error !== null ? (error as { name?: unknown }).name : undefined;\n return typeof name === 'string' ? name : undefined;\n}\n\n/** Classifies a share sheet failure. */\nfunction shareError(cause: unknown): CopyError {\n switch (readName(cause)) {\n case 'NotAllowedError':\n return createCopyError('permission-denied', 'The share sheet was blocked: it needs a click, and an iframe needs the web-share permission.', cause);\n case 'InvalidStateError':\n return createCopyError('unknown', 'Another share sheet is already open.', cause);\n case 'DataError':\n case 'TypeError':\n return createCopyError('unsupported-format', 'The share sheet rejected this content.', cause);\n default:\n return toCopyError(cause);\n }\n}\n\nconst SHARE_DESCRIPTIONS: Partial<Readonly<Record<CopyErrorType, string>>> = {\n 'permission-denied': \"Sharing isn't allowed here.\",\n 'unsupported-format': \"This can't be shared from this browser.\",\n timeout: 'Sharing took too long. Try again.',\n};\n\n/**\n * Default English, user-facing sentence for a failed share: a share sheet\n * failure is described as sharing, a failed copy as copying. Replace for i18n.\n */\nexport function describeShareError(error: CopyError, method: ShareMethod): string {\n if (method === 'copy') return describeCopyError(error);\n return SHARE_DESCRIPTIONS[error.type] ?? \"Couldn't share. Try again.\";\n}\n"],"mappings":";;;;;;;;AA+EA,MAAa,cAAc;AAE3B,MAAM,2BAA0D,OAAO,WAAW,cAAc,KAAA,IAAY;AAE5G,MAAM,WAAW,YAA+BA,eAAAA,gBAAgB,mBAAmB,OAAO;;AAG1F,SAAS,eAAe,SAAuB,SAAoD;CACjG,MAAM,QAAiB;CACvB,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO,QAAQ,4DAA4D;CAC5H,MAAM,EAAE,KAAK,OAAO,MAAM,UAAU;CACpC,IAAI,OAAsB;CAC1B,IAAI,QAAQ,KAAA,KAAa,QAAQ,MAC/B,IAAI;EACF,OAAOC,YAAAA,gBAAgB,OAAO,CAAC,CAAC,GAAmB;CACrD,SAAS,OAAO;EACd,OAAOC,eAAAA,YAAY,KAAK;CAC1B;CAEF,IAAI,UAAU,KAAA,KAAa,OAAO,UAAU,UAAU,OAAO,QAAQ,2BAA2B;CAChG,IAAI,SAAS,KAAA,KAAa,OAAO,SAAS,UAAU,OAAO,QAAQ,0BAA0B;CAC7F,MAAM,OAAgB,SAAS,CAAC;CAChC,IAAI,CAA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AU,YAAY,OAAO;CAClD;AACF;AAEA,SAAS,SAAS,OAAoC;CACpD,MAAM,OAAgB,OAAO,UAAU,YAAY,UAAU,OAAQ,MAA6B,OAAO,KAAA;CACzG,OAAO,OAAO,SAAS,WAAW,OAAO,KAAA;AAC3C;;AAGA,SAAS,WAAW,OAA2B;CAC7C,QAAQ,SAAS,KAAK,GAAtB;EACE,KAAK,mBACH,OAAOF,eAAAA,gBAAgB,qBAAqB,gGAAgG,KAAK;EACnJ,KAAK,qBACH,OAAOA,eAAAA,gBAAgB,WAAW,wCAAwC,KAAK;EACjF,KAAK;EACL,KAAK,aACH,OAAOA,eAAAA,gBAAgB,sBAAsB,0CAA0C,KAAK;EAC9F,SACE,OAAOE,eAAAA,YAAY,KAAK;CAC5B;AACF;AAEA,MAAM,qBAAuE;CAC3E,qBAAqB;CACrB,sBAAsB;CACtB,SAAS;AACX;;;;;AAMA,SAAgB,mBAAmB,OAAkB,QAA6B;CAChF,IAAI,WAAW,QAAQ,OAAOM,eAAAA,kBAAkB,KAAK;CACrD,OAAO,mBAAmB,MAAM,SAAS;AAC3C"}
|
|
1
|
+
{"version":3,"file":"share-nx7M4Z0t.cjs","names":["createCopyError","linkUrlResolver","toCopyError","cleanTitle","linkPayload","normalizePayload","validatePayload","createBrowserClipboardAdapter","describeCopyError"],"sources":["../../src/share/share.ts"],"sourcesContent":["import { createBrowserClipboardAdapter, type ClipboardAdapter } from '../core/clipboard-adapter';\nimport { createCopyError, describeCopyError, toCopyError, type CopyError, type CopyErrorType } from '../core/errors';\nimport { normalizePayload, validatePayload, type CopyInput, type CopyPayload } from '../core/payload';\nimport { cleanTitle, DEFAULT_LINK_TITLE_LENGTH, linkPayload } from '../link/payload';\nimport { linkUrlResolver, type LinkUrlOptions } from '../link/url';\n\n/** What to share: a link, a message, files, or any mix of them. */\nexport interface ShareContent {\n /** Validated like every link in this package: allowed schemes only, credentials removed. */\n readonly url?: string | URL;\n readonly title?: string;\n /** A message to share alongside (or instead of) the link. */\n readonly text?: string;\n /** Files for the share sheet, where the browser can share them (`navigator.canShare({ files })`). Never copied. */\n readonly files?: readonly File[];\n}\n\n/** The content after validation: what the share sheet or the clipboard receives. */\nexport interface ResolvedShare {\n readonly url: string | null;\n /** Cleaned of hidden characters; `null` when there is none. */\n readonly title: string | null;\n readonly text: string | null;\n readonly files: readonly File[];\n}\n\n/**\n * How to share:\n * - `auto` (default): the share sheet on phones and tablets, where people expect it; copy elsewhere.\n * - `native`: the share sheet wherever the browser has one (also desktop Safari, Edge and Chrome on Windows and macOS).\n * - `copy`: always copy.\n */\nexport type ShareMode = 'auto' | 'native' | 'copy';\n\nexport type ShareMethod = 'native' | 'copy';\n\n/** Structural view of what sharing needs from the browser; `window` by default. */\nexport interface ShareEnvironment {\n readonly navigator?: {\n readonly share?: (data: ShareData) => Promise<void>;\n readonly canShare?: (data: ShareData) => boolean;\n };\n readonly matchMedia?: (query: string) => { readonly matches: boolean };\n}\n\nexport interface ShareOptions extends LinkUrlOptions {\n /** Default `\"auto\"`. */\n readonly mode?: ShareMode;\n /** When the share sheet fails for a reason other than the user closing it, copy instead. Default `true`. */\n readonly fallback?: boolean;\n /**\n * What to copy. Default: a titled link (`linkPayload`) when there is a URL,\n * otherwise the text. Return a string or any copy payload.\n */\n readonly copy?: (content: ResolvedShare) => CopyInput;\n /** Default: the browser Clipboard API, as `useCopy` uses. */\n readonly adapter?: ClipboardAdapter;\n /** Default: `window`. For tests, webviews and other hosts. */\n readonly environment?: ShareEnvironment;\n /** Aborting it stops a copy in progress; the share sheet itself can only be closed by the user. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Why the content was copied rather than shared: `preferred` (the mode chose\n * copy, as on desktop in `auto`), `unsupported` (no share sheet, or it can't\n * take this content) or `fallback` (the share sheet failed).\n */\nexport type CopyReason = 'preferred' | 'unsupported' | 'fallback';\n\n/** What `shareOrCopy` resolves to. It never rejects. */\nexport type ShareOutcome =\n | { readonly status: 'shared'; readonly method: 'native'; readonly content: ResolvedShare }\n | { readonly status: 'copied'; readonly method: 'copy'; readonly reason: CopyReason; readonly payload: CopyPayload; readonly content: ResolvedShare }\n /** The user closed the share sheet. Nothing to report. */\n | { readonly status: 'cancelled'; readonly method: 'native' }\n | { readonly status: 'error'; readonly method: ShareMethod; readonly error: CopyError };\n\n/** Phones and tablets: a touch screen is the main input and nothing hovers. */\nexport const TOUCH_FIRST = '(hover: none) and (pointer: coarse)';\n\nconst defaultEnvironment = (): ShareEnvironment | undefined => (typeof window === 'undefined' ? undefined : window);\n\nconst invalid = (message: string): CopyError => createCopyError('invalid-payload', message);\n\n/** Validates and cleans what to share, or returns the typed error for invalid input. */\nfunction resolveContent(content: ShareContent, options: LinkUrlOptions): ResolvedShare | CopyError {\n const value: unknown = content;\n if (typeof value !== 'object' || value === null) return invalid('Share content must be an object with a url, text or files.');\n const { url, title, text, files } = value as Record<string, unknown>;\n let href: string | null = null;\n if (url !== undefined && url !== null) {\n try {\n href = linkUrlResolver(options)(url as string | URL);\n } catch (error) {\n return toCopyError(error);\n }\n }\n if (title !== undefined && typeof title !== 'string') return invalid('`title` must be a string.');\n if (text !== undefined && typeof text !== 'string') return invalid('`text` must be a string.');\n const list: unknown = files ?? [];\n if (!Array.isArray(list) || !list.every((file: unknown) => typeof File !== 'undefined' && file instanceof File)) {\n return invalid('`files` must be a list of File objects.');\n }\n const cleanName = title === undefined ? '' : cleanTitle(title, DEFAULT_LINK_TITLE_LENGTH);\n const message = text === undefined || text.trim() === '' ? null : text;\n if (href === null && message === null && list.length === 0) return invalid('There is nothing to share: give a url, text or files.');\n return { url: href, title: cleanName === '' ? null : cleanName, text: message, files: list as File[] };\n}\n\n/** The `ShareData` the browser receives: only the fields that are set. */\nfunction shareData(content: ResolvedShare): ShareData {\n return {\n ...(content.url === null ? {} : { url: content.url }),\n ...(content.title === null ? {} : { title: content.title }),\n ...(content.text === null ? {} : { text: content.text }),\n ...(content.files.length === 0 ? {} : { files: [...content.files] }),\n };\n}\n\n/** Whether this browser can open its share sheet for `data`. */\nfunction canShareNatively(environment: ShareEnvironment | undefined, data: ShareData | null): boolean {\n const nav = environment?.navigator;\n if (typeof nav?.share !== 'function') return false;\n if (data === null) return true;\n // Without canShare (older Safari), only links and text can be shared.\n return typeof nav.canShare === 'function' ? nav.canShare(data) : data.files === undefined;\n}\n\nfunction isTouchFirst(environment: ShareEnvironment | undefined): boolean {\n return typeof environment?.matchMedia === 'function' && environment.matchMedia(TOUCH_FIRST).matches;\n}\n\nfunction resolveMode(mode: unknown): ShareMode | CopyError {\n if (mode === undefined) return 'auto';\n return mode === 'auto' || mode === 'native' || mode === 'copy' ? mode : invalid('`mode` must be \"auto\", \"native\" or \"copy\".');\n}\n\n/**\n * How {@link shareOrCopy} would share right now: `\"native\"` (the share sheet) or\n * `\"copy\"`. Use it to label the button (\"Share…\" or \"Copy link\"). Pass the\n * content when it has files, since not every share sheet takes them.\n */\nexport function shareMethod(options: Pick<ShareOptions, 'mode' | 'environment'> = {}, content?: ShareContent): ShareMethod {\n const mode = resolveMode(options.mode);\n if (typeof mode !== 'string' || mode === 'copy') return 'copy';\n const environment = options.environment ?? defaultEnvironment();\n if (mode === 'auto' && !isTouchFirst(environment)) return 'copy';\n const resolved = content === undefined ? null : resolveContent(content, {});\n const data = resolved === null ? null : 'type' in resolved ? undefined : shareData(resolved);\n return data !== undefined && canShareNatively(environment, data) ? 'native' : 'copy';\n}\n\n/** The default copy: a titled link when there is a URL, otherwise the text (one of them is always set here). */\nfunction defaultCopy(content: ResolvedShare): CopyInput {\n if (content.url !== null) return linkPayload({ url: content.url, ...(content.title === null ? {} : { title: content.title }) });\n return content.text as string;\n}\n\nasync function copyContent(content: ResolvedShare, reason: CopyReason, options: ShareOptions): Promise<ShareOutcome> {\n if (options.copy === undefined && content.url === null && content.text === null) {\n return { status: 'error', method: 'copy', error: createCopyError('unsupported-format', 'Files can only be shared through a share sheet, and this browser has none for them.') };\n }\n let payload: CopyPayload;\n try {\n payload = normalizePayload((options.copy ?? defaultCopy)(content));\n } catch (error) {\n return { status: 'error', method: 'copy', error: toCopyError(error) };\n }\n const problem = validatePayload(payload);\n if (problem !== null) return { status: 'error', method: 'copy', error: problem };\n if (options.signal?.aborted === true) return { status: 'error', method: 'copy', error: createCopyError('aborted', 'The share was aborted.') };\n try {\n await (options.adapter ?? createBrowserClipboardAdapter()).write(payload, options.signal === undefined ? undefined : { signal: options.signal });\n } catch (error) {\n return { status: 'error', method: 'copy', error: toCopyError(error) };\n }\n return { status: 'copied', method: 'copy', reason, payload, content };\n}\n\n/**\n * Shares through the device's share sheet where people expect one, and copies a\n * titled link everywhere else. Call it directly in a click handler: the share\n * sheet needs the user's gesture.\n *\n * It never rejects. It resolves to `shared`, `copied` (with why), `cancelled`\n * (the user closed the share sheet: nothing to report) or `error` with a typed\n * {@link CopyError}.\n *\n * @example\n * button.addEventListener('click', async () => {\n * const outcome = await shareOrCopy({ url: location.href, title: document.title });\n * if (outcome.status === 'copied') toast('Link copied');\n * });\n */\nexport async function shareOrCopy(content: ShareContent, options: ShareOptions = {}): Promise<ShareOutcome> {\n const mode = resolveMode(options.mode);\n if (typeof mode !== 'string') return { status: 'error', method: 'copy', error: mode };\n const resolved = resolveContent(content, options);\n if ('type' in resolved) return { status: 'error', method: 'copy', error: resolved };\n const environment = options.environment ?? defaultEnvironment();\n if (mode === 'copy' || (mode === 'auto' && !isTouchFirst(environment))) return copyContent(resolved, 'preferred', options);\n const data = shareData(resolved);\n if (!canShareNatively(environment, data)) return copyContent(resolved, 'unsupported', options);\n try {\n // Called before any await: the share sheet needs the click's user activation.\n await (environment?.navigator?.share as (data: ShareData) => Promise<void>)(data);\n return { status: 'shared', method: 'native', content: resolved };\n } catch (error) {\n if (readName(error) === 'AbortError') return { status: 'cancelled', method: 'native' };\n if (options.fallback === false) return { status: 'error', method: 'native', error: shareError(error) };\n return copyContent(resolved, 'fallback', options);\n }\n}\n\nfunction readName(error: unknown): string | undefined {\n const name: unknown = typeof error === 'object' && error !== null ? (error as { name?: unknown }).name : undefined;\n return typeof name === 'string' ? name : undefined;\n}\n\n/** Classifies a share sheet failure. */\nfunction shareError(cause: unknown): CopyError {\n switch (readName(cause)) {\n case 'NotAllowedError':\n return createCopyError('permission-denied', 'The share sheet was blocked: it needs a click, and an iframe needs the web-share permission.', cause);\n case 'InvalidStateError':\n return createCopyError('unknown', 'Another share sheet is already open.', cause);\n case 'DataError':\n case 'TypeError':\n return createCopyError('unsupported-format', 'The share sheet rejected this content.', cause);\n default:\n return toCopyError(cause);\n }\n}\n\nconst SHARE_DESCRIPTIONS: Partial<Readonly<Record<CopyErrorType, string>>> = {\n 'permission-denied': \"Sharing isn't allowed here.\",\n 'unsupported-format': \"This can't be shared from this browser.\",\n timeout: 'Sharing took too long. Try again.',\n};\n\n/**\n * Default English, user-facing sentence for a failed share: a share sheet\n * failure is described as sharing, a failed copy as copying. Replace for i18n.\n */\nexport function describeShareError(error: CopyError, method: ShareMethod): string {\n if (method === 'copy') return describeCopyError(error);\n return SHARE_DESCRIPTIONS[error.type] ?? \"Couldn't share. Try again.\";\n}\n"],"mappings":";;;;;;;;AA+EA,MAAa,cAAc;AAE3B,MAAM,2BAA0D,OAAO,WAAW,cAAc,KAAA,IAAY;AAE5G,MAAM,WAAW,YAA+BA,eAAAA,gBAAgB,mBAAmB,OAAO;;AAG1F,SAAS,eAAe,SAAuB,SAAoD;CACjG,MAAM,QAAiB;CACvB,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO,QAAQ,4DAA4D;CAC5H,MAAM,EAAE,KAAK,OAAO,MAAM,UAAU;CACpC,IAAI,OAAsB;CAC1B,IAAI,QAAQ,KAAA,KAAa,QAAQ,MAC/B,IAAI;EACF,OAAOC,YAAAA,gBAAgB,OAAO,CAAC,CAAC,GAAmB;CACrD,SAAS,OAAO;EACd,OAAOC,eAAAA,YAAY,KAAK;CAC1B;CAEF,IAAI,UAAU,KAAA,KAAa,OAAO,UAAU,UAAU,OAAO,QAAQ,2BAA2B;CAChG,IAAI,SAA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QAAQ,aAAa,OAAO,OAAO;GAAE,QAAQ;GAAS,QAAQ;GAAU,OAAO,WAAW,KAAK;EAAE;EACrG,OAAO,YAAY,UAAU,YAAY,OAAO;CAClD;AACF;AAEA,SAAS,SAAS,OAAoC;CACpD,MAAM,OAAgB,OAAO,UAAU,YAAY,UAAU,OAAQ,MAA6B,OAAO,KAAA;CACzG,OAAO,OAAO,SAAS,WAAW,OAAO,KAAA;AAC3C;;AAGA,SAAS,WAAW,OAA2B;CAC7C,QAAQ,SAAS,KAAK,GAAtB;EACE,KAAK,mBACH,OAAOF,eAAAA,gBAAgB,qBAAqB,gGAAgG,KAAK;EACnJ,KAAK,qBACH,OAAOA,eAAAA,gBAAgB,WAAW,wCAAwC,KAAK;EACjF,KAAK;EACL,KAAK,aACH,OAAOA,eAAAA,gBAAgB,sBAAsB,0CAA0C,KAAK;EAC9F,SACE,OAAOE,eAAAA,YAAY,KAAK;CAC5B;AACF;AAEA,MAAM,qBAAuE;CAC3E,qBAAqB;CACrB,sBAAsB;CACtB,SAAS;AACX;;;;;AAMA,SAAgB,mBAAmB,OAAkB,QAA6B;CAChF,IAAI,WAAW,QAAQ,OAAOM,eAAAA,kBAAkB,KAAK;CACrD,OAAO,mBAAmB,MAAM,SAAS;AAC3C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
const require_errors = require("./errors-
|
|
2
|
+
const require_errors = require("./errors-DFmEAC4E.cjs");
|
|
3
3
|
//#region src/link/url.ts
|
|
4
4
|
/** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */
|
|
5
5
|
const DEFAULT_LINK_PROTOCOLS = /* @__PURE__ */ Object.freeze([
|
|
@@ -161,4 +161,4 @@ Object.defineProperty(exports, "resolveLinkUrl", {
|
|
|
161
161
|
}
|
|
162
162
|
});
|
|
163
163
|
|
|
164
|
-
//# sourceMappingURL=url-
|
|
164
|
+
//# sourceMappingURL=url-BrhVUwn7.cjs.map
|