react-smart-copy 1.26.0 → 1.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +6 -3
  2. package/dist/capture.cjs +4 -4
  3. package/dist/capture.cjs.map +1 -1
  4. package/dist/capture.js +4 -4
  5. package/dist/capture.js.map +1 -1
  6. package/dist/chunks/clipboard-adapter-0haPt4jJ.js +217 -0
  7. package/dist/chunks/clipboard-adapter-0haPt4jJ.js.map +1 -0
  8. package/dist/chunks/clipboard-adapter-5bmjKbyK.cjs +222 -0
  9. package/dist/chunks/clipboard-adapter-5bmjKbyK.cjs.map +1 -0
  10. package/dist/chunks/{clipboard-adapter-CfaIbZpv.d.cts → clipboard-adapter-CUvmAcRE.d.cts} +10 -1
  11. package/dist/chunks/{clipboard-adapter-Chm6zq60.d.ts → clipboard-adapter-CdOzN135.d.ts} +10 -1
  12. package/dist/chunks/{contrast-C9d8QuaF.cjs → contrast-BatHkv8j.cjs} +2 -2
  13. package/dist/chunks/{contrast-C9d8QuaF.cjs.map → contrast-BatHkv8j.cjs.map} +1 -1
  14. package/dist/chunks/{contrast-DUaZq5SA.js → contrast-DnCunIr1.js} +2 -2
  15. package/dist/chunks/{contrast-DUaZq5SA.js.map → contrast-DnCunIr1.js.map} +1 -1
  16. package/dist/chunks/{core-t59Z4gdy.cjs → core-BRMlZOtj.cjs} +5 -5
  17. package/dist/chunks/{core-t59Z4gdy.cjs.map → core-BRMlZOtj.cjs.map} +1 -1
  18. package/dist/chunks/{core-D3GCO3yT.js → core-CnAFS4Wh.js} +5 -5
  19. package/dist/chunks/{core-D3GCO3yT.js.map → core-CnAFS4Wh.js.map} +1 -1
  20. package/dist/chunks/{deadline-j2hD7JKz.cjs → deadline-Cz6l-PDR.cjs} +14 -2
  21. package/dist/chunks/deadline-Cz6l-PDR.cjs.map +1 -0
  22. package/dist/chunks/{deadline-CbwnZ3Oq.js → deadline-DTAkra5B.js} +9 -3
  23. package/dist/chunks/deadline-DTAkra5B.js.map +1 -0
  24. package/dist/chunks/{errors-DFmEAC4E.cjs → errors-CF2EQNbc.cjs} +14 -2
  25. package/dist/chunks/errors-CF2EQNbc.cjs.map +1 -0
  26. package/dist/chunks/{errors-CT-FfUtU.js → errors-CGcMvbhJ.js} +9 -3
  27. package/dist/chunks/errors-CGcMvbhJ.js.map +1 -0
  28. package/dist/chunks/{field-B6SRWRbI.cjs → field-C8A5Yxln.cjs} +3 -3
  29. package/dist/chunks/{field-B6SRWRbI.cjs.map → field-C8A5Yxln.cjs.map} +1 -1
  30. package/dist/chunks/{field-DsRKkbav.js → field-CDCN9x0L.js} +3 -3
  31. package/dist/chunks/{field-DsRKkbav.js.map → field-CDCN9x0L.js.map} +1 -1
  32. package/dist/chunks/{index-CZ6HpdKm.d.cts → index-Ct2V52et.d.cts} +2 -2
  33. package/dist/chunks/{index-BidyqUMa.d.ts → index-U91G1nS9.d.ts} +2 -2
  34. package/dist/chunks/{limits-BP9R5wnr.js → limits-DvJZJn0V.js} +2 -2
  35. package/dist/chunks/{limits-BP9R5wnr.js.map → limits-DvJZJn0V.js.map} +1 -1
  36. package/dist/chunks/{limits-9wi1f6xT.cjs → limits-Vy-Xv26D.cjs} +2 -2
  37. package/dist/chunks/{limits-9wi1f6xT.cjs.map → limits-Vy-Xv26D.cjs.map} +1 -1
  38. package/dist/chunks/{paste-reader-BWQaYNaV.cjs → paste-reader-BL51Jt1y.cjs} +2 -2
  39. package/dist/chunks/{paste-reader-BWQaYNaV.cjs.map → paste-reader-BL51Jt1y.cjs.map} +1 -1
  40. package/dist/chunks/{paste-reader-D6uOTDBM.js → paste-reader-BpXOH_Px.js} +2 -2
  41. package/dist/chunks/{paste-reader-D6uOTDBM.js.map → paste-reader-BpXOH_Px.js.map} +1 -1
  42. package/dist/chunks/{payload-BrQWGwyx.js → payload-5uJedhwz.js} +2 -2
  43. package/dist/chunks/{payload-BrQWGwyx.js.map → payload-5uJedhwz.js.map} +1 -1
  44. package/dist/chunks/{payload-BWQ6sPtS.js → payload-DZnXoBmF.js} +3 -3
  45. package/dist/chunks/{payload-BWQ6sPtS.js.map → payload-DZnXoBmF.js.map} +1 -1
  46. package/dist/chunks/{payload-sBxkG7jH.cjs → payload-DjSSLonm.cjs} +2 -2
  47. package/dist/chunks/{payload-sBxkG7jH.cjs.map → payload-DjSSLonm.cjs.map} +1 -1
  48. package/dist/chunks/{payload-tTK6REua.cjs → payload-DzHhs6Ey.cjs} +3 -3
  49. package/dist/chunks/{payload-tTK6REua.cjs.map → payload-DzHhs6Ey.cjs.map} +1 -1
  50. package/dist/chunks/{share-nx7M4Z0t.cjs → share-Bu5u2ItX.cjs} +6 -6
  51. package/dist/chunks/{share-nx7M4Z0t.cjs.map → share-Bu5u2ItX.cjs.map} +1 -1
  52. package/dist/chunks/{share-CU91L4EK.js → share-CL72PUqq.js} +6 -6
  53. package/dist/chunks/{share-CU91L4EK.js.map → share-CL72PUqq.js.map} +1 -1
  54. package/dist/chunks/{share-DVR_DhHc.d.ts → share-DMqvWz32.d.ts} +2 -2
  55. package/dist/chunks/{share-hIwth7Dh.d.cts → share-DQFF73gt.d.cts} +2 -2
  56. package/dist/chunks/{url-BrhVUwn7.cjs → url-CL4YTCvM.cjs} +2 -2
  57. package/dist/chunks/{url-BrhVUwn7.cjs.map → url-CL4YTCvM.cjs.map} +1 -1
  58. package/dist/chunks/{url-COID0BLY.js → url-zB_krkuF.js} +2 -2
  59. package/dist/chunks/{url-COID0BLY.js.map → url-zB_krkuF.js.map} +1 -1
  60. package/dist/code.cjs +2 -2
  61. package/dist/code.js +2 -2
  62. package/dist/color.cjs +2 -2
  63. package/dist/color.js +2 -2
  64. package/dist/core.cjs +5 -5
  65. package/dist/core.d.cts +2 -2
  66. package/dist/core.d.ts +2 -2
  67. package/dist/core.js +5 -5
  68. package/dist/email.cjs +2 -2
  69. package/dist/email.js +2 -2
  70. package/dist/files.cjs +1 -1
  71. package/dist/files.js +1 -1
  72. package/dist/image.cjs +3 -3
  73. package/dist/image.cjs.map +1 -1
  74. package/dist/image.js +3 -3
  75. package/dist/image.js.map +1 -1
  76. package/dist/index.cjs +7 -7
  77. package/dist/index.d.cts +3 -3
  78. package/dist/index.d.ts +3 -3
  79. package/dist/index.js +7 -7
  80. package/dist/link.cjs +3 -3
  81. package/dist/link.js +3 -3
  82. package/dist/markdown.cjs +1 -1
  83. package/dist/markdown.js +1 -1
  84. package/dist/number.cjs +2 -2
  85. package/dist/number.js +2 -2
  86. package/dist/otp.cjs +1 -1
  87. package/dist/otp.js +1 -1
  88. package/dist/rich.cjs +3 -3
  89. package/dist/rich.js +3 -3
  90. package/dist/secrets.cjs +1 -1
  91. package/dist/secrets.js +1 -1
  92. package/dist/share.cjs +1 -1
  93. package/dist/share.d.cts +1 -1
  94. package/dist/share.d.ts +1 -1
  95. package/dist/share.js +1 -1
  96. package/dist/structured.cjs +2 -2
  97. package/dist/structured.js +2 -2
  98. package/dist/table.cjs +1 -1
  99. package/dist/table.js +1 -1
  100. package/dist/testing.cjs +2 -2
  101. package/dist/testing.d.cts +1 -1
  102. package/dist/testing.d.ts +1 -1
  103. package/dist/testing.js +2 -2
  104. package/package.json +8 -8
  105. package/dist/chunks/clipboard-adapter-CmKDTFdO.js +0 -97
  106. package/dist/chunks/clipboard-adapter-CmKDTFdO.js.map +0 -1
  107. package/dist/chunks/clipboard-adapter-UIFc_Qso.cjs +0 -102
  108. package/dist/chunks/clipboard-adapter-UIFc_Qso.cjs.map +0 -1
  109. package/dist/chunks/deadline-CbwnZ3Oq.js.map +0 -1
  110. package/dist/chunks/deadline-j2hD7JKz.cjs.map +0 -1
  111. package/dist/chunks/errors-CT-FfUtU.js.map +0 -1
  112. package/dist/chunks/errors-DFmEAC4E.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"limits-BP9R5wnr.js","names":[],"sources":["../../src/core/limits.ts"],"sourcesContent":["import { copyFailure } from './errors';\n\n/**\n * A limit option read: `fallback` when it was not given, otherwise a positive whole number\n * or `Infinity`. Every `max*` option of the library is checked by this one rule.\n *\n * @throws {CopyFailure} `invalid-payload` for zero, a negative or fractional number, or `NaN`.\n */\nexport function positiveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,cAAc,OAA2B,UAAkB,MAAsB;CAC/F,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,UAAU,YAAa,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAI,OAAO;CACzE,MAAM,YAAY,mBAAmB,KAAK,KAAK,sDAAsD,OAAO,KAAK,EAAE,GAAG;AACxH"}
1
+ {"version":3,"file":"limits-DvJZJn0V.js","names":[],"sources":["../../src/core/limits.ts"],"sourcesContent":["import { copyFailure } from './errors';\n\n/**\n * A limit option read: `fallback` when it was not given, otherwise a positive whole number\n * or `Infinity`. Every `max*` option of the library is checked by this one rule.\n *\n * @throws {CopyFailure} `invalid-payload` for zero, a negative or fractional number, or `NaN`.\n */\nexport function positiveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,cAAc,OAA2B,UAAkB,MAAsB;CAC/F,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,UAAU,YAAa,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAI,OAAO;CACzE,MAAM,YAAY,mBAAmB,KAAK,KAAK,sDAAsD,OAAO,KAAK,EAAE,GAAG;AACxH"}
@@ -1,5 +1,5 @@
1
1
 
2
- const require_errors = require("./errors-DFmEAC4E.cjs");
2
+ const require_errors = require("./errors-CF2EQNbc.cjs");
3
3
  //#region src/core/limits.ts
4
4
  /**
5
5
  * A limit option read: `fallback` when it was not given, otherwise a positive whole number
@@ -20,4 +20,4 @@ Object.defineProperty(exports, "positiveLimit", {
20
20
  }
21
21
  });
22
22
 
23
- //# sourceMappingURL=limits-9wi1f6xT.cjs.map
23
+ //# sourceMappingURL=limits-Vy-Xv26D.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"limits-9wi1f6xT.cjs","names":["copyFailure"],"sources":["../../src/core/limits.ts"],"sourcesContent":["import { copyFailure } from './errors';\n\n/**\n * A limit option read: `fallback` when it was not given, otherwise a positive whole number\n * or `Infinity`. Every `max*` option of the library is checked by this one rule.\n *\n * @throws {CopyFailure} `invalid-payload` for zero, a negative or fractional number, or `NaN`.\n */\nexport function positiveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,cAAc,OAA2B,UAAkB,MAAsB;CAC/F,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,UAAU,YAAa,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAI,OAAO;CACzE,MAAMA,eAAAA,YAAY,mBAAmB,KAAK,KAAK,sDAAsD,OAAO,KAAK,EAAE,GAAG;AACxH"}
1
+ {"version":3,"file":"limits-Vy-Xv26D.cjs","names":["copyFailure"],"sources":["../../src/core/limits.ts"],"sourcesContent":["import { copyFailure } from './errors';\n\n/**\n * A limit option read: `fallback` when it was not given, otherwise a positive whole number\n * or `Infinity`. Every `max*` option of the library is checked by this one rule.\n *\n * @throws {CopyFailure} `invalid-payload` for zero, a negative or fractional number, or `NaN`.\n */\nexport function positiveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,cAAc,OAA2B,UAAkB,MAAsB;CAC/F,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,UAAU,YAAa,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAI,OAAO;CACzE,MAAMA,eAAAA,YAAY,mBAAmB,KAAK,KAAK,sDAAsD,OAAO,KAAK,EAAE,GAAG;AACxH"}
@@ -1,5 +1,5 @@
1
1
 
2
- const require_errors = require("./errors-DFmEAC4E.cjs");
2
+ const require_errors = require("./errors-CF2EQNbc.cjs");
3
3
  const require_mime = require("./mime--LB7kdqG.cjs");
4
4
  //#region src/core/paste-reader.ts
5
5
  /** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
@@ -286,4 +286,4 @@ Object.defineProperty(exports, "utf8ByteLength", {
286
286
  }
287
287
  });
288
288
 
289
- //# sourceMappingURL=paste-reader-BWQaYNaV.cjs.map
289
+ //# sourceMappingURL=paste-reader-BL51Jt1y.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"paste-reader-BWQaYNaV.cjs","names":["normalizeClipboardType","copyFailure","matchesMimePattern","isTextualMimeType","normalizeMimeType","sniffImageType"],"sources":["../../src/core/paste-reader.ts"],"sourcesContent":["import { copyFailure } from './errors';\nimport { isTextualMimeType, matchesMimePattern, normalizeClipboardType, normalizeMimeType, sniffImageType } from './mime';\n\n/* ------------------------------------------------------------------ Types */\n\n/** Friendly names for the common cases. */\nexport type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';\n\n/**\n * What a paste may contain, in any order: a shorthand, an exact MIME type\n * (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a\n * wildcard (`'image/*'`, `'*\\/*'`). `image/svg+xml` (scriptable XML), web custom\n * formats and `+json` types are only accepted when listed exactly.\n */\nexport type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;\n\nexport interface PasteLimits {\n /**\n * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as\n * they would be encoded, matching `Blob.size`, so every paste path counts the same way.\n * Default 32 MiB.\n */\n readonly maxBytes?: number;\n /** Max number of accepted items (types + files). Default 32. */\n readonly maxItems?: number;\n}\n\nexport interface PasteReadOptions extends PasteLimits {\n /** Default `['text']` (plain text only): the safest choice. */\n readonly accept?: readonly PasteAccept[];\n}\n\n/** Validated, normalised options that adapters receive. */\nexport interface ResolvedPasteReadOptions {\n /** Normalised patterns: `type/subtype`, `type/*` or `*\\/*`. */\n readonly accept: readonly string[];\n readonly maxBytes: number;\n readonly maxItems: number;\n}\n\n/** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */\nexport type PasteSource = 'clipboard' | 'event' | 'drop';\n\n/** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */\nexport interface PasteItem {\n readonly type: string;\n readonly data: string | Blob;\n}\n\n/**\n * Everything the paste produced. Treat all of it as untrusted user input:\n * in particular never inject `html` into the DOM without sanitising it.\n */\nexport interface PasteResult {\n readonly source: PasteSource;\n /** Every accepted entry, in clipboard order. */\n readonly items: readonly PasteItem[];\n /** `text/plain`, when accepted and present. */\n readonly text: string | null;\n /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */\n readonly html: string | null;\n /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */\n readonly images: readonly Blob[];\n /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */\n readonly files: readonly File[];\n /**\n * The entries of `files` that are also in `images`: verified image files, keeping their\n * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.\n */\n readonly imageFiles: readonly File[];\n}\n\n/** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */\nexport type PasteReadResult = Omit<PasteResult, 'imageFiles'>;\n\n/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */\nexport function completePasteResult(result: PasteReadResult): PasteResult {\n const images = new Set<Blob>(result.images);\n return { ...result, imageFiles: result.files.filter((file) => images.has(file)) };\n}\n\n/* -------------------------------------------------------- Option handling */\n\nexport const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[] = /* @__PURE__ */ Object.freeze(['text'] as const);\nexport const DEFAULT_PASTE_MAX_BYTES: number = 32 * 1024 * 1024;\nexport const DEFAULT_PASTE_MAX_ITEMS = 32;\n\nconst SHORTHANDS: ReadonlyMap<string, string> = /* @__PURE__ */ new Map([\n ['text', 'text/plain'],\n ['html', 'text/html'],\n ['image', 'image/*'],\n ['any', '*/*'],\n]);\n\nconst TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\nfunction resolvePattern(entry: unknown): string | null {\n if (typeof entry !== 'string') return null;\n const shorthand = SHORTHANDS.get(entry);\n if (shorthand !== undefined) return shorthand;\n if (entry === '*/*') return entry;\n if (entry.endsWith('/*')) {\n const type = entry.slice(0, -2).toLowerCase();\n return TYPE_TOKEN.test(type) ? `${type}/*` : null;\n }\n return normalizeClipboardType(entry);\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\n/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */\nexport function resolvePasteReadOptions(options: PasteReadOptions = {}): ResolvedPasteReadOptions {\n const accept: string[] = [];\n for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {\n const pattern = resolvePattern(entry);\n if (pattern === null) throw copyFailure('invalid-payload', `Invalid \\`accept\\` entry: ${JSON.stringify(entry)}.`);\n if (!accept.includes(pattern)) accept.push(pattern);\n }\n if (accept.length === 0) throw copyFailure('invalid-payload', '`accept` must list at least one type.');\n return {\n accept,\n maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, 'maxBytes'),\n maxItems: resolveLimit(options.maxItems, DEFAULT_PASTE_MAX_ITEMS, 'maxItems'),\n };\n}\n\n/** Whether a normalised MIME type is allowed by the resolved `accept` list. */\nexport function isAccepted(mimeType: string, options: ResolvedPasteReadOptions): boolean {\n return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));\n}\n\n/* -------------------------------------------------------------- Entries */\n\n/** An accepted, not-yet-verified entry. */\nexport interface PasteEntry {\n readonly type: string;\n readonly data: string | Blob;\n /** Came from `DataTransfer.files`, i.e. `data` is a `File`. */\n readonly file: boolean;\n}\n\ninterface Budget {\n readonly charge: (size: number) => void;\n}\n\nfunction createBudget(options: ResolvedPasteReadOptions): Budget {\n let bytes = 0;\n let items = 0;\n return {\n charge: (size) => {\n items += 1;\n bytes += size;\n if (items > options.maxItems) {\n throw copyFailure('too-large', `The paste has more than ${String(options.maxItems)} accepted items.`);\n }\n if (bytes > options.maxBytes) {\n throw copyFailure('too-large', `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);\n }\n },\n };\n}\n\n/**\n * UTF-8 byte length of a string, without allocating an encoded copy.\n * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.\n */\nexport function utf8ByteLength(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i += 1) {\n const unit = text.charCodeAt(i);\n if (unit < 0x80) bytes += 1;\n else if (unit < 0x800) bytes += 2;\n else if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n bytes += 4;\n i += 1;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */\nconst sizeOf = (data: string | Blob): number => (typeof data === 'string' ? utf8ByteLength(data) : data.size);\n\n/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */\nexport function enforcePasteLimits(entries: readonly PasteEntry[], options: ResolvedPasteReadOptions): void {\n const budget = createBudget(options);\n for (const entry of entries) budget.charge(sizeOf(entry.data));\n}\n\n/** Structural view of a `DataTransferItem`: only what is readable while dragging. */\nexport interface DataTransferItemLike {\n /** `'string'` or `'file'`. */\n readonly kind: string;\n readonly type: string;\n}\n\n/** Structural view of `DataTransfer` (paste and drop events). */\nexport interface DataTransferLike {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n readonly files?: ArrayLike<File> | null;\n readonly items?: ArrayLike<DataTransferItemLike> | null;\n}\n\n/**\n * Whether a drag in progress could drop anything `accept`s. Uses only what\n * browsers expose before the drop (item kinds and types, never the data).\n * A file whose type is not known yet (some browsers hide it while dragging)\n * counts as a maybe: the drop itself is checked against `accept`.\n */\nexport function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean {\n // Without an item list, a file is only known as the type \"Files\": treat it as an untyped file.\n const items = data.items ?? Array.from(data.types, (type) => (type === 'Files' ? { kind: 'file', type: '' } : { kind: 'string', type }));\n return Array.from(items).some(({ kind, type: raw }) => {\n const file = kind === 'file';\n const type = normalizeClipboardType(raw);\n if (type === null) return file;\n return (file || isTextualMimeType(type)) && isAccepted(type, options);\n });\n}\n\n/**\n * Synchronously copies the accepted parts of a paste event's `DataTransfer`.\n * It must run during the event: browsers empty the object afterwards.\n */\nexport function snapshotDataTransfer(data: DataTransferLike, options: ResolvedPasteReadOptions): PasteEntry[] {\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const raw of Array.from(data.types)) {\n const type = normalizeClipboardType(raw);\n // Binary types are delivered through `files`; `getData` only returns strings.\n if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n const text = data.getData(raw);\n if (text.length > 0) entries.push({ type, data: text, file: false });\n }\n\n for (const file of Array.from(data.files ?? [])) {\n const type = normalizeMimeType(file.type) ?? 'application/octet-stream';\n if (isAccepted(type, options)) entries.push({ type, data: file, file: true });\n }\n\n return entries;\n}\n\n/** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */\nexport interface ClipboardItemLike {\n readonly types: readonly string[];\n getType(type: string): Promise<Blob>;\n}\n\n/**\n * Reads the accepted types from `navigator.clipboard.read()` items, enforcing\n * the limits *before* decoding any text so an oversized paste is never buffered twice.\n */\nexport async function collectClipboardItems(\n items: readonly ClipboardItemLike[],\n options: ResolvedPasteReadOptions,\n signal?: AbortSignal,\n): Promise<PasteEntry[]> {\n const budget = createBudget(options);\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const item of items) {\n for (const raw of item.types) {\n const type = normalizeClipboardType(raw);\n if (type === null || seen.has(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n\n let blob: Blob;\n try {\n blob = await item.getType(raw);\n } catch {\n // Chromium lists some types it then refuses to hand over; skip them, don't fail the paste.\n continue;\n }\n // Cancelled (reset, superseded, unmounted) while waiting: don't decode the rest.\n if (signal?.aborted) throw copyFailure('aborted', 'The paste was cancelled.');\n if (blob.size === 0) continue;\n budget.charge(blob.size);\n entries.push({ type, data: isTextualMimeType(type) ? await blob.text() : blob, file: false });\n }\n }\n return entries;\n}\n\n/* ------------------------------------------------------------ Finalising */\n\nfunction retype(entry: PasteEntry, data: Blob, type: string): Blob {\n if (entry.file) {\n const file = data as File;\n return new File([file], file.name, { type, lastModified: file.lastModified });\n }\n return data.slice(0, data.size, type);\n}\n\n/**\n * Verifies image bytes, then builds the result. Blobs that claim to be images\n * but aren't (or whose real format is not accepted) are dropped. Throws\n * `no-content` when nothing survives.\n */\nexport async function finalizePaste(\n entries: readonly PasteEntry[],\n source: PasteSource,\n options: ResolvedPasteReadOptions,\n): Promise<PasteReadResult> {\n const items: PasteItem[] = [];\n const images: Blob[] = [];\n const files: File[] = [];\n let text: string | null = null;\n let html: string | null = null;\n\n for (const entry of entries) {\n let { type, data } = entry;\n\n if (typeof data === 'string') {\n // Types are de-duplicated upstream, so each of these is seen at most once.\n if (type === 'text/plain') text = data;\n else if (type === 'text/html') html = data;\n } else if (type.startsWith('image/')) {\n const actual = await sniffImageType(data);\n if (actual === null || !isAccepted(actual, options)) continue;\n if (actual !== type) {\n data = retype(entry, data, actual);\n type = actual;\n }\n images.push(data);\n }\n\n if (entry.file) files.push(data as File);\n items.push({ type, data });\n }\n\n if (items.length === 0) {\n throw copyFailure('no-content', 'The content holds nothing that matches `accept`.');\n }\n return { source, items, text, html, images, files };\n}\n"],"mappings":";;;;;AA4EA,SAAgB,oBAAoB,QAAsC;CACxE,MAAM,SAAS,IAAI,IAAU,OAAO,MAAM;CAC1C,OAAO;EAAE,GAAG;EAAQ,YAAY,OAAO,MAAM,QAAQ,SAAS,OAAO,IAAI,IAAI,CAAC;CAAE;AAClF;AAIA,MAAa,uBAA+D,uBAAO,OAAO,CAAC,MAAM,CAAU;AAC3G,MAAa,0BAAkC;AAC/C,MAAa,0BAA0B;AAEvC,MAAM,6BAA0D,IAAI,IAAI;CACtE,CAAC,QAAQ,YAAY;CACrB,CAAC,QAAQ,WAAW;CACpB,CAAC,SAAS,SAAS;CACnB,CAAC,OAAO,KAAK;AACf,CAAC;AAED,MAAM,aAAa;AAEnB,SAAS,eAAe,OAA+B;CACrD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,MAAM,YAAY,WAAW,IAAI,KAAK;CACtC,IAAI,cAAc,KAAA,GAAW,OAAO;CACpC,IAAI,UAAU,OAAO,OAAO;CAC5B,IAAI,MAAM,SAAS,IAAI,GAAG;EACxB,MAAM,OAAO,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,YAAY;EAC5C,OAAO,WAAW,KAAK,IAAI,IAAI,GAAG,KAAK,MAAM;CAC/C;CACA,OAAOA,aAAAA,uBAAuB,KAAK;AACrC;AAEA,SAAS,aAAa,OAA2B,UAAkB,MAAsB;CACvF,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,UAAU,YAAa,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAI,OAAO;CACzE,MAAMC,eAAAA,YAAY,mBAAmB,KAAK,KAAK,sDAAsD,OAAO,KAAK,EAAE,GAAG;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gB,CAAC;CACvB,IAAI,OAAsB;CAC1B,IAAI,OAAsB;CAE1B,KAAK,MAAM,SAAS,SAAS;EAC3B,IAAI,EAAE,MAAM,SAAS;EAErB,IAAI,OAAO,SAAS,UAAU;GAE5B,IAAI,SAAS,cAAc,OAAO;QAC7B,IAAI,SAAS,aAAa,OAAO;EACxC,OAAO,IAAI,KAAK,WAAW,QAAQ,GAAG;GACpC,MAAM,SAAS,MAAME,aAAAA,eAAe,IAAI;GACxC,IAAI,WAAW,QAAQ,CAAC,WAAW,QAAQ,OAAO,GAAG;GACrD,IAAI,WAAW,MAAM;IACnB,OAAO,OAAO,OAAO,MAAM,MAAM;IACjC,OAAO;GACT;GACA,OAAO,KAAK,IAAI;EAClB;EAEA,IAAI,MAAM,MAAM,MAAM,KAAK,IAAY;EACvC,MAAM,KAAK;GAAE;GAAM;EAAK,CAAC;CAC3B;CAEA,IAAI,MAAM,WAAW,GACnB,MAAMJ,eAAAA,YAAY,cAAc,kDAAkD;CAEpF,OAAO;EAAE;EAAQ;EAAO;EAAM;EAAM;EAAQ;CAAM;AACpD"}
1
+ {"version":3,"file":"paste-reader-BL51Jt1y.cjs","names":["normalizeClipboardType","copyFailure","matchesMimePattern","isTextualMimeType","normalizeMimeType","sniffImageType"],"sources":["../../src/core/paste-reader.ts"],"sourcesContent":["import { copyFailure } from './errors';\nimport { isTextualMimeType, matchesMimePattern, normalizeClipboardType, normalizeMimeType, sniffImageType } from './mime';\n\n/* ------------------------------------------------------------------ Types */\n\n/** Friendly names for the common cases. */\nexport type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';\n\n/**\n * What a paste may contain, in any order: a shorthand, an exact MIME type\n * (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a\n * wildcard (`'image/*'`, `'*\\/*'`). `image/svg+xml` (scriptable XML), web custom\n * formats and `+json` types are only accepted when listed exactly.\n */\nexport type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;\n\nexport interface PasteLimits {\n /**\n * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as\n * they would be encoded, matching `Blob.size`, so every paste path counts the same way.\n * Default 32 MiB.\n */\n readonly maxBytes?: number;\n /** Max number of accepted items (types + files). Default 32. */\n readonly maxItems?: number;\n}\n\nexport interface PasteReadOptions extends PasteLimits {\n /** Default `['text']` (plain text only): the safest choice. */\n readonly accept?: readonly PasteAccept[];\n}\n\n/** Validated, normalised options that adapters receive. */\nexport interface ResolvedPasteReadOptions {\n /** Normalised patterns: `type/subtype`, `type/*` or `*\\/*`. */\n readonly accept: readonly string[];\n readonly maxBytes: number;\n readonly maxItems: number;\n}\n\n/** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */\nexport type PasteSource = 'clipboard' | 'event' | 'drop';\n\n/** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */\nexport interface PasteItem {\n readonly type: string;\n readonly data: string | Blob;\n}\n\n/**\n * Everything the paste produced. Treat all of it as untrusted user input:\n * in particular never inject `html` into the DOM without sanitising it.\n */\nexport interface PasteResult {\n readonly source: PasteSource;\n /** Every accepted entry, in clipboard order. */\n readonly items: readonly PasteItem[];\n /** `text/plain`, when accepted and present. */\n readonly text: string | null;\n /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */\n readonly html: string | null;\n /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */\n readonly images: readonly Blob[];\n /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */\n readonly files: readonly File[];\n /**\n * The entries of `files` that are also in `images`: verified image files, keeping their\n * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.\n */\n readonly imageFiles: readonly File[];\n}\n\n/** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */\nexport type PasteReadResult = Omit<PasteResult, 'imageFiles'>;\n\n/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */\nexport function completePasteResult(result: PasteReadResult): PasteResult {\n const images = new Set<Blob>(result.images);\n return { ...result, imageFiles: result.files.filter((file) => images.has(file)) };\n}\n\n/* -------------------------------------------------------- Option handling */\n\nexport const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[] = /* @__PURE__ */ Object.freeze(['text'] as const);\nexport const DEFAULT_PASTE_MAX_BYTES: number = 32 * 1024 * 1024;\nexport const DEFAULT_PASTE_MAX_ITEMS = 32;\n\nconst SHORTHANDS: ReadonlyMap<string, string> = /* @__PURE__ */ new Map([\n ['text', 'text/plain'],\n ['html', 'text/html'],\n ['image', 'image/*'],\n ['any', '*/*'],\n]);\n\nconst TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\nfunction resolvePattern(entry: unknown): string | null {\n if (typeof entry !== 'string') return null;\n const shorthand = SHORTHANDS.get(entry);\n if (shorthand !== undefined) return shorthand;\n if (entry === '*/*') return entry;\n if (entry.endsWith('/*')) {\n const type = entry.slice(0, -2).toLowerCase();\n return TYPE_TOKEN.test(type) ? `${type}/*` : null;\n }\n return normalizeClipboardType(entry);\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\n/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */\nexport function resolvePasteReadOptions(options: PasteReadOptions = {}): ResolvedPasteReadOptions {\n const accept: string[] = [];\n for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {\n const pattern = resolvePattern(entry);\n if (pattern === null) throw copyFailure('invalid-payload', `Invalid \\`accept\\` entry: ${JSON.stringify(entry)}.`);\n if (!accept.includes(pattern)) accept.push(pattern);\n }\n if (accept.length === 0) throw copyFailure('invalid-payload', '`accept` must list at least one type.');\n return {\n accept,\n maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, 'maxBytes'),\n maxItems: resolveLimit(options.maxItems, DEFAULT_PASTE_MAX_ITEMS, 'maxItems'),\n };\n}\n\n/** Whether a normalised MIME type is allowed by the resolved `accept` list. */\nexport function isAccepted(mimeType: string, options: ResolvedPasteReadOptions): boolean {\n return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));\n}\n\n/* -------------------------------------------------------------- Entries */\n\n/** An accepted, not-yet-verified entry. */\nexport interface PasteEntry {\n readonly type: string;\n readonly data: string | Blob;\n /** Came from `DataTransfer.files`, i.e. `data` is a `File`. */\n readonly file: boolean;\n}\n\ninterface Budget {\n readonly charge: (size: number) => void;\n}\n\nfunction createBudget(options: ResolvedPasteReadOptions): Budget {\n let bytes = 0;\n let items = 0;\n return {\n charge: (size) => {\n items += 1;\n bytes += size;\n if (items > options.maxItems) {\n throw copyFailure('too-large', `The paste has more than ${String(options.maxItems)} accepted items.`);\n }\n if (bytes > options.maxBytes) {\n throw copyFailure('too-large', `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);\n }\n },\n };\n}\n\n/**\n * UTF-8 byte length of a string, without allocating an encoded copy.\n * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.\n */\nexport function utf8ByteLength(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i += 1) {\n const unit = text.charCodeAt(i);\n if (unit < 0x80) bytes += 1;\n else if (unit < 0x800) bytes += 2;\n else if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n bytes += 4;\n i += 1;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */\nconst sizeOf = (data: string | Blob): number => (typeof data === 'string' ? utf8ByteLength(data) : data.size);\n\n/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */\nexport function enforcePasteLimits(entries: readonly PasteEntry[], options: ResolvedPasteReadOptions): void {\n const budget = createBudget(options);\n for (const entry of entries) budget.charge(sizeOf(entry.data));\n}\n\n/** Structural view of a `DataTransferItem`: only what is readable while dragging. */\nexport interface DataTransferItemLike {\n /** `'string'` or `'file'`. */\n readonly kind: string;\n readonly type: string;\n}\n\n/** Structural view of `DataTransfer` (paste and drop events). */\nexport interface DataTransferLike {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n readonly files?: ArrayLike<File> | null;\n readonly items?: ArrayLike<DataTransferItemLike> | null;\n}\n\n/**\n * Whether a drag in progress could drop anything `accept`s. Uses only what\n * browsers expose before the drop (item kinds and types, never the data).\n * A file whose type is not known yet (some browsers hide it while dragging)\n * counts as a maybe: the drop itself is checked against `accept`.\n */\nexport function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean {\n // Without an item list, a file is only known as the type \"Files\": treat it as an untyped file.\n const items = data.items ?? Array.from(data.types, (type) => (type === 'Files' ? { kind: 'file', type: '' } : { kind: 'string', type }));\n return Array.from(items).some(({ kind, type: raw }) => {\n const file = kind === 'file';\n const type = normalizeClipboardType(raw);\n if (type === null) return file;\n return (file || isTextualMimeType(type)) && isAccepted(type, options);\n });\n}\n\n/**\n * Synchronously copies the accepted parts of a paste event's `DataTransfer`.\n * It must run during the event: browsers empty the object afterwards.\n */\nexport function snapshotDataTransfer(data: DataTransferLike, options: ResolvedPasteReadOptions): PasteEntry[] {\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const raw of Array.from(data.types)) {\n const type = normalizeClipboardType(raw);\n // Binary types are delivered through `files`; `getData` only returns strings.\n if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n const text = data.getData(raw);\n if (text.length > 0) entries.push({ type, data: text, file: false });\n }\n\n for (const file of Array.from(data.files ?? [])) {\n const type = normalizeMimeType(file.type) ?? 'application/octet-stream';\n if (isAccepted(type, options)) entries.push({ type, data: file, file: true });\n }\n\n return entries;\n}\n\n/** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */\nexport interface ClipboardItemLike {\n readonly types: readonly string[];\n getType(type: string): Promise<Blob>;\n}\n\n/**\n * Reads the accepted types from `navigator.clipboard.read()` items, enforcing\n * the limits *before* decoding any text so an oversized paste is never buffered twice.\n */\nexport async function collectClipboardItems(\n items: readonly ClipboardItemLike[],\n options: ResolvedPasteReadOptions,\n signal?: AbortSignal,\n): Promise<PasteEntry[]> {\n const budget = createBudget(options);\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const item of items) {\n for (const raw of item.types) {\n const type = normalizeClipboardType(raw);\n if (type === null || seen.has(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n\n let blob: Blob;\n try {\n blob = await item.getType(raw);\n } catch {\n // Chromium lists some types it then refuses to hand over; skip them, don't fail the paste.\n continue;\n }\n // Cancelled (reset, superseded, unmounted) while waiting: don't decode the rest.\n if (signal?.aborted) throw copyFailure('aborted', 'The paste was cancelled.');\n if (blob.size === 0) continue;\n budget.charge(blob.size);\n entries.push({ type, data: isTextualMimeType(type) ? await blob.text() : blob, file: false });\n }\n }\n return entries;\n}\n\n/* ------------------------------------------------------------ Finalising */\n\nfunction retype(entry: PasteEntry, data: Blob, type: string): Blob {\n if (entry.file) {\n const file = data as File;\n return new File([file], file.name, { type, lastModified: file.lastModified });\n }\n return data.slice(0, data.size, type);\n}\n\n/**\n * Verifies image bytes, then builds the result. Blobs that claim to be images\n * but aren't (or whose real format is not accepted) are dropped. Throws\n * `no-content` when nothing survives.\n */\nexport async function finalizePaste(\n entries: readonly PasteEntry[],\n source: PasteSource,\n options: ResolvedPasteReadOptions,\n): Promise<PasteReadResult> {\n const items: PasteItem[] = [];\n const images: Blob[] = [];\n const files: File[] = [];\n let text: string | null = null;\n let html: string | null = null;\n\n for (const entry of entries) {\n let { type, data } = entry;\n\n if (typeof data === 'string') {\n // Types are de-duplicated upstream, so each of these is seen at most once.\n if (type === 'text/plain') text = data;\n else if (type === 'text/html') html = data;\n } else if (type.startsWith('image/')) {\n const actual = await sniffImageType(data);\n if (actual === null || !isAccepted(actual, options)) continue;\n if (actual !== type) {\n data = retype(entry, data, actual);\n type = actual;\n }\n images.push(data);\n }\n\n if (entry.file) files.push(data as File);\n items.push({ type, data });\n }\n\n if (items.length === 0) {\n throw copyFailure('no-content', 'The content holds nothing that matches `accept`.');\n }\n return { source, items, text, html, images, files };\n}\n"],"mappings":";;;;;AA4EA,SAAgB,oBAAoB,QAAsC;CACxE,MAAM,SAAS,IAAI,IAAU,OAAO,MAAM;CAC1C,OAAO;EAAE,GAAG;EAAQ,YAAY,OAAO,MAAM,QAAQ,SAAS,OAAO,IAAI,IAAI,CAAC;CAAE;AAClF;AAIA,MAAa,uBAA+D,uBAAO,OAAO,CAAC,MAAM,CAAU;AAC3G,MAAa,0BAAkC;AAC/C,MAAa,0BAA0B;AAEvC,MAAM,6BAA0D,IAAI,IAAI;CACtE,CAAC,QAAQ,YAAY;CACrB,CAAC,QAAQ,WAAW;CACpB,CAAC,SAAS,SAAS;CACnB,CAAC,OAAO,KAAK;AACf,CAAC;AAED,MAAM,aAAa;AAEnB,SAAS,eAAe,OAA+B;CACrD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,MAAM,YAAY,WAAW,IAAI,KAAK;CACtC,IAAI,cAAc,KAAA,GAAW,OAAO;CACpC,IAAI,UAAU,OAAO,OAAO;CAC5B,IAAI,MAAM,SAAS,IAAI,GAAG;EACxB,MAAM,OAAO,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,YAAY;EAC5C,OAAO,WAAW,KAAK,IAAI,IAAI,GAAG,KAAK,MAAM;CAC/C;CACA,OAAOA,aAAAA,uBAAuB,KAAK;AACrC;AAEA,SAAS,aAAa,OAA2B,UAAkB,MAAsB;CACvF,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,UAAU,YAAa,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAI,OAAO;CACzE,MAAMC,eAAAA,YAAY,mBAAmB,KAAK,KAAK,sDAAsD,OAAO,KAAK,EAAE,GAAG;AACxH;;AAG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ACvB,IAAI,OAAsB;CAC1B,IAAI,OAAsB;CAE1B,KAAK,MAAM,SAAS,SAAS;EAC3B,IAAI,EAAE,MAAM,SAAS;EAErB,IAAI,OAAO,SAAS,UAAU;GAE5B,IAAI,SAAS,cAAc,OAAO;QAC7B,IAAI,SAAS,aAAa,OAAO;EACxC,OAAO,IAAI,KAAK,WAAW,QAAQ,GAAG;GACpC,MAAM,SAAS,MAAME,aAAAA,eAAe,IAAI;GACxC,IAAI,WAAW,QAAQ,CAAC,WAAW,QAAQ,OAAO,GAAG;GACrD,IAAI,WAAW,MAAM;IACnB,OAAO,OAAO,OAAO,MAAM,MAAM;IACjC,OAAO;GACT;GACA,OAAO,KAAK,IAAI;EAClB;EAEA,IAAI,MAAM,MAAM,MAAM,KAAK,IAAY;EACvC,MAAM,KAAK;GAAE;GAAM;EAAK,CAAC;CAC3B;CAEA,IAAI,MAAM,WAAW,GACnB,MAAMJ,eAAAA,YAAY,cAAc,kDAAkD;CAEpF,OAAO;EAAE;EAAQ;EAAO;EAAM;EAAM;EAAQ;CAAM;AACpD"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { n as copyFailure } from "./errors-CT-FfUtU.js";
2
+ import { n as copyFailure } from "./errors-CGcMvbhJ.js";
3
3
  import { a as matchesMimePattern, l as sniffImageType, o as normalizeClipboardType, r as isTextualMimeType, s as normalizeMimeType } from "./mime-aa-HA2dm.js";
4
4
  //#region src/core/paste-reader.ts
5
5
  /** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
@@ -221,4 +221,4 @@ async function finalizePaste(entries, source, options) {
221
221
  //#endregion
222
222
  export { collectClipboardItems as a, finalizePaste as c, utf8ByteLength as d, canAcceptDrag as i, resolvePasteReadOptions as l, DEFAULT_PASTE_MAX_BYTES as n, completePasteResult as o, DEFAULT_PASTE_MAX_ITEMS as r, enforcePasteLimits as s, DEFAULT_PASTE_ACCEPT as t, snapshotDataTransfer as u };
223
223
 
224
- //# sourceMappingURL=paste-reader-D6uOTDBM.js.map
224
+ //# sourceMappingURL=paste-reader-BpXOH_Px.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"paste-reader-D6uOTDBM.js","names":[],"sources":["../../src/core/paste-reader.ts"],"sourcesContent":["import { copyFailure } from './errors';\nimport { isTextualMimeType, matchesMimePattern, normalizeClipboardType, normalizeMimeType, sniffImageType } from './mime';\n\n/* ------------------------------------------------------------------ Types */\n\n/** Friendly names for the common cases. */\nexport type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';\n\n/**\n * What a paste may contain, in any order: a shorthand, an exact MIME type\n * (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a\n * wildcard (`'image/*'`, `'*\\/*'`). `image/svg+xml` (scriptable XML), web custom\n * formats and `+json` types are only accepted when listed exactly.\n */\nexport type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;\n\nexport interface PasteLimits {\n /**\n * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as\n * they would be encoded, matching `Blob.size`, so every paste path counts the same way.\n * Default 32 MiB.\n */\n readonly maxBytes?: number;\n /** Max number of accepted items (types + files). Default 32. */\n readonly maxItems?: number;\n}\n\nexport interface PasteReadOptions extends PasteLimits {\n /** Default `['text']` (plain text only): the safest choice. */\n readonly accept?: readonly PasteAccept[];\n}\n\n/** Validated, normalised options that adapters receive. */\nexport interface ResolvedPasteReadOptions {\n /** Normalised patterns: `type/subtype`, `type/*` or `*\\/*`. */\n readonly accept: readonly string[];\n readonly maxBytes: number;\n readonly maxItems: number;\n}\n\n/** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */\nexport type PasteSource = 'clipboard' | 'event' | 'drop';\n\n/** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */\nexport interface PasteItem {\n readonly type: string;\n readonly data: string | Blob;\n}\n\n/**\n * Everything the paste produced. Treat all of it as untrusted user input:\n * in particular never inject `html` into the DOM without sanitising it.\n */\nexport interface PasteResult {\n readonly source: PasteSource;\n /** Every accepted entry, in clipboard order. */\n readonly items: readonly PasteItem[];\n /** `text/plain`, when accepted and present. */\n readonly text: string | null;\n /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */\n readonly html: string | null;\n /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */\n readonly images: readonly Blob[];\n /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */\n readonly files: readonly File[];\n /**\n * The entries of `files` that are also in `images`: verified image files, keeping their\n * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.\n */\n readonly imageFiles: readonly File[];\n}\n\n/** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */\nexport type PasteReadResult = Omit<PasteResult, 'imageFiles'>;\n\n/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */\nexport function completePasteResult(result: PasteReadResult): PasteResult {\n const images = new Set<Blob>(result.images);\n return { ...result, imageFiles: result.files.filter((file) => images.has(file)) };\n}\n\n/* -------------------------------------------------------- Option handling */\n\nexport const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[] = /* @__PURE__ */ Object.freeze(['text'] as const);\nexport const DEFAULT_PASTE_MAX_BYTES: number = 32 * 1024 * 1024;\nexport const DEFAULT_PASTE_MAX_ITEMS = 32;\n\nconst SHORTHANDS: ReadonlyMap<string, string> = /* @__PURE__ */ new Map([\n ['text', 'text/plain'],\n ['html', 'text/html'],\n ['image', 'image/*'],\n ['any', '*/*'],\n]);\n\nconst TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\nfunction resolvePattern(entry: unknown): string | null {\n if (typeof entry !== 'string') return null;\n const shorthand = SHORTHANDS.get(entry);\n if (shorthand !== undefined) return shorthand;\n if (entry === '*/*') return entry;\n if (entry.endsWith('/*')) {\n const type = entry.slice(0, -2).toLowerCase();\n return TYPE_TOKEN.test(type) ? `${type}/*` : null;\n }\n return normalizeClipboardType(entry);\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\n/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */\nexport function resolvePasteReadOptions(options: PasteReadOptions = {}): ResolvedPasteReadOptions {\n const accept: string[] = [];\n for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {\n const pattern = resolvePattern(entry);\n if (pattern === null) throw copyFailure('invalid-payload', `Invalid \\`accept\\` entry: ${JSON.stringify(entry)}.`);\n if (!accept.includes(pattern)) accept.push(pattern);\n }\n if (accept.length === 0) throw copyFailure('invalid-payload', '`accept` must list at least one type.');\n return {\n accept,\n maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, 'maxBytes'),\n maxItems: resolveLimit(options.maxItems, DEFAULT_PASTE_MAX_ITEMS, 'maxItems'),\n };\n}\n\n/** Whether a normalised MIME type is allowed by the resolved `accept` list. */\nexport function isAccepted(mimeType: string, options: ResolvedPasteReadOptions): boolean {\n return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));\n}\n\n/* -------------------------------------------------------------- Entries */\n\n/** An accepted, not-yet-verified entry. */\nexport interface PasteEntry {\n readonly type: string;\n readonly data: string | Blob;\n /** Came from `DataTransfer.files`, i.e. `data` is a `File`. */\n readonly file: boolean;\n}\n\ninterface Budget {\n readonly charge: (size: number) => void;\n}\n\nfunction createBudget(options: ResolvedPasteReadOptions): Budget {\n let bytes = 0;\n let items = 0;\n return {\n charge: (size) => {\n items += 1;\n bytes += size;\n if (items > options.maxItems) {\n throw copyFailure('too-large', `The paste has more than ${String(options.maxItems)} accepted items.`);\n }\n if (bytes > options.maxBytes) {\n throw copyFailure('too-large', `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);\n }\n },\n };\n}\n\n/**\n * UTF-8 byte length of a string, without allocating an encoded copy.\n * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.\n */\nexport function utf8ByteLength(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i += 1) {\n const unit = text.charCodeAt(i);\n if (unit < 0x80) bytes += 1;\n else if (unit < 0x800) bytes += 2;\n else if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n bytes += 4;\n i += 1;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */\nconst sizeOf = (data: string | Blob): number => (typeof data === 'string' ? utf8ByteLength(data) : data.size);\n\n/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */\nexport function enforcePasteLimits(entries: readonly PasteEntry[], options: ResolvedPasteReadOptions): void {\n const budget = createBudget(options);\n for (const entry of entries) budget.charge(sizeOf(entry.data));\n}\n\n/** Structural view of a `DataTransferItem`: only what is readable while dragging. */\nexport interface DataTransferItemLike {\n /** `'string'` or `'file'`. */\n readonly kind: string;\n readonly type: string;\n}\n\n/** Structural view of `DataTransfer` (paste and drop events). */\nexport interface DataTransferLike {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n readonly files?: ArrayLike<File> | null;\n readonly items?: ArrayLike<DataTransferItemLike> | null;\n}\n\n/**\n * Whether a drag in progress could drop anything `accept`s. Uses only what\n * browsers expose before the drop (item kinds and types, never the data).\n * A file whose type is not known yet (some browsers hide it while dragging)\n * counts as a maybe: the drop itself is checked against `accept`.\n */\nexport function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean {\n // Without an item list, a file is only known as the type \"Files\": treat it as an untyped file.\n const items = data.items ?? Array.from(data.types, (type) => (type === 'Files' ? { kind: 'file', type: '' } : { kind: 'string', type }));\n return Array.from(items).some(({ kind, type: raw }) => {\n const file = kind === 'file';\n const type = normalizeClipboardType(raw);\n if (type === null) return file;\n return (file || isTextualMimeType(type)) && isAccepted(type, options);\n });\n}\n\n/**\n * Synchronously copies the accepted parts of a paste event's `DataTransfer`.\n * It must run during the event: browsers empty the object afterwards.\n */\nexport function snapshotDataTransfer(data: DataTransferLike, options: ResolvedPasteReadOptions): PasteEntry[] {\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const raw of Array.from(data.types)) {\n const type = normalizeClipboardType(raw);\n // Binary types are delivered through `files`; `getData` only returns strings.\n if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n const text = data.getData(raw);\n if (text.length > 0) entries.push({ type, data: text, file: false });\n }\n\n for (const file of Array.from(data.files ?? [])) {\n const type = normalizeMimeType(file.type) ?? 'application/octet-stream';\n if (isAccepted(type, options)) entries.push({ type, data: file, file: true });\n }\n\n return entries;\n}\n\n/** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */\nexport interface ClipboardItemLike {\n readonly types: readonly string[];\n getType(type: string): Promise<Blob>;\n}\n\n/**\n * Reads the accepted types from `navigator.clipboard.read()` items, enforcing\n * the limits *before* decoding any text so an oversized paste is never buffered twice.\n */\nexport async function collectClipboardItems(\n items: readonly ClipboardItemLike[],\n options: ResolvedPasteReadOptions,\n signal?: AbortSignal,\n): Promise<PasteEntry[]> {\n const budget = createBudget(options);\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const item of items) {\n for (const raw of item.types) {\n const type = normalizeClipboardType(raw);\n if (type === null || seen.has(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n\n let blob: Blob;\n try {\n blob = await item.getType(raw);\n } catch {\n // Chromium lists some types it then refuses to hand over; skip them, don't fail the paste.\n continue;\n }\n // Cancelled (reset, superseded, unmounted) while waiting: don't decode the rest.\n if (signal?.aborted) throw copyFailure('aborted', 'The paste was cancelled.');\n if (blob.size === 0) continue;\n budget.charge(blob.size);\n entries.push({ type, data: isTextualMimeType(type) ? await blob.text() : blob, file: false });\n }\n }\n return entries;\n}\n\n/* ------------------------------------------------------------ Finalising */\n\nfunction retype(entry: PasteEntry, data: Blob, type: string): Blob {\n if (entry.file) {\n const file = data as File;\n return new File([file], file.name, { type, lastModified: file.lastModified });\n }\n return data.slice(0, data.size, type);\n}\n\n/**\n * Verifies image bytes, then builds the result. Blobs that claim to be images\n * but aren't (or whose real format is not accepted) are dropped. Throws\n * `no-content` when nothing survives.\n */\nexport async function finalizePaste(\n entries: readonly PasteEntry[],\n source: PasteSource,\n options: ResolvedPasteReadOptions,\n): Promise<PasteReadResult> {\n const items: PasteItem[] = [];\n const images: Blob[] = [];\n const files: File[] = [];\n let text: string | null = null;\n let html: string | null = null;\n\n for (const entry of entries) {\n let { type, data } = entry;\n\n if (typeof data === 'string') {\n // Types are de-duplicated upstream, so each of these is seen at most once.\n if (type === 'text/plain') text = data;\n else if (type === 'text/html') html = data;\n } else if (type.startsWith('image/')) {\n const actual = await sniffImageType(data);\n if (actual === null || !isAccepted(actual, options)) continue;\n if (actual !== type) {\n data = retype(entry, data, actual);\n type = actual;\n }\n images.push(data);\n }\n\n if (entry.file) files.push(data as File);\n items.push({ type, data });\n }\n\n if (items.length === 0) {\n throw copyFailure('no-content', 'The content holds nothing that matches `accept`.');\n }\n return { source, items, text, html, images, files };\n}\n"],"mappings":";;;;;AA4EA,SAAgB,oBAAoB,QAAsC;CACxE,MAAM,SAAS,IAAI,IAAU,OAAO,MAAM;CAC1C,OAAO;EAAE,GAAG;EAAQ,YAAY,OAAO,MAAM,QAAQ,SAAS,OAAO,IAAI,IAAI,CAAC;CAAE;AAClF;AAIA,MAAa,uBAA+D,uBAAO,OAAO,CAAC,MAAM,CAAU;AAC3G,MAAa,0BAAkC;AAC/C,MAAa,0BAA0B;AAEvC,MAAM,6BAA0D,IAAI,IAAI;CACtE,CAAC,QAAQ,YAAY;CACrB,CAAC,QAAQ,WAAW;CACpB,CAAC,SAAS,SAAS;CACnB,CAAC,OAAO,KAAK;AACf,CAAC;AAED,MAAM,aAAa;AAEnB,SAAS,eAAe,OAA+B;CACrD,IAAI,OA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AAI,IAAI,MAAM,KAAK,KAAK,IAAI;GAAM,MAAM;EAAM,CAAC;CAC9F;CAEF,OAAO;AACT;AAIA,SAAS,OAAO,OAAmB,MAAY,MAAoB;CACjE,IAAI,MAAM,MAAM;EACd,MAAM,OAAO;EACb,OAAO,IAAI,KAAK,CAAC,IAAI,GAAG,KAAK,MAAM;GAAE;GAAM,cAAc,KAAK;EAAa,CAAC;CAC9E;CACA,OAAO,KAAK,MAAM,GAAG,KAAK,MAAM,IAAI;AACtC;;;;;;AAOA,eAAsB,cACpB,SACA,QACA,SAC0B;CAC1B,MAAM,QAAqB,CAAC;CAC5B,MAAM,SAAiB,CAAC;CACxB,MAAM,QAAgB,CAAC;CACvB,IAAI,OAAsB;CAC1B,IAAI,OAAsB;CAE1B,KAAK,MAAM,SAAS,SAAS;EAC3B,IAAI,EAAE,MAAM,SAAS;EAErB,IAAI,OAAO,SAAS,UAAU;GAE5B,IAAI,SAAS,cAAc,OAAO;QAC7B,IAAI,SAAS,aAAa,OAAO;EACxC,OAAO,IAAI,KAAK,WAAW,QAAQ,GAAG;GACpC,MAAM,SAAS,MAAM,eAAe,IAAI;GACxC,IAAI,WAAW,QAAQ,CAAC,WAAW,QAAQ,OAAO,GAAG;GACrD,IAAI,WAAW,MAAM;IACnB,OAAO,OAAO,OAAO,MAAM,MAAM;IACjC,OAAO;GACT;GACA,OAAO,KAAK,IAAI;EAClB;EAEA,IAAI,MAAM,MAAM,MAAM,KAAK,IAAY;EACvC,MAAM,KAAK;GAAE;GAAM;EAAK,CAAC;CAC3B;CAEA,IAAI,MAAM,WAAW,GACnB,MAAM,YAAY,cAAc,kDAAkD;CAEpF,OAAO;EAAE;EAAQ;EAAO;EAAM;EAAM;EAAQ;CAAM;AACpD"}
1
+ {"version":3,"file":"paste-reader-BpXOH_Px.js","names":[],"sources":["../../src/core/paste-reader.ts"],"sourcesContent":["import { copyFailure } from './errors';\nimport { isTextualMimeType, matchesMimePattern, normalizeClipboardType, normalizeMimeType, sniffImageType } from './mime';\n\n/* ------------------------------------------------------------------ Types */\n\n/** Friendly names for the common cases. */\nexport type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';\n\n/**\n * What a paste may contain, in any order: a shorthand, an exact MIME type\n * (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a\n * wildcard (`'image/*'`, `'*\\/*'`). `image/svg+xml` (scriptable XML), web custom\n * formats and `+json` types are only accepted when listed exactly.\n */\nexport type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;\n\nexport interface PasteLimits {\n /**\n * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as\n * they would be encoded, matching `Blob.size`, so every paste path counts the same way.\n * Default 32 MiB.\n */\n readonly maxBytes?: number;\n /** Max number of accepted items (types + files). Default 32. */\n readonly maxItems?: number;\n}\n\nexport interface PasteReadOptions extends PasteLimits {\n /** Default `['text']` (plain text only): the safest choice. */\n readonly accept?: readonly PasteAccept[];\n}\n\n/** Validated, normalised options that adapters receive. */\nexport interface ResolvedPasteReadOptions {\n /** Normalised patterns: `type/subtype`, `type/*` or `*\\/*`. */\n readonly accept: readonly string[];\n readonly maxBytes: number;\n readonly maxItems: number;\n}\n\n/** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */\nexport type PasteSource = 'clipboard' | 'event' | 'drop';\n\n/** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */\nexport interface PasteItem {\n readonly type: string;\n readonly data: string | Blob;\n}\n\n/**\n * Everything the paste produced. Treat all of it as untrusted user input:\n * in particular never inject `html` into the DOM without sanitising it.\n */\nexport interface PasteResult {\n readonly source: PasteSource;\n /** Every accepted entry, in clipboard order. */\n readonly items: readonly PasteItem[];\n /** `text/plain`, when accepted and present. */\n readonly text: string | null;\n /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */\n readonly html: string | null;\n /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */\n readonly images: readonly Blob[];\n /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */\n readonly files: readonly File[];\n /**\n * The entries of `files` that are also in `images`: verified image files, keeping their\n * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.\n */\n readonly imageFiles: readonly File[];\n}\n\n/** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */\nexport type PasteReadResult = Omit<PasteResult, 'imageFiles'>;\n\n/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */\nexport function completePasteResult(result: PasteReadResult): PasteResult {\n const images = new Set<Blob>(result.images);\n return { ...result, imageFiles: result.files.filter((file) => images.has(file)) };\n}\n\n/* -------------------------------------------------------- Option handling */\n\nexport const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[] = /* @__PURE__ */ Object.freeze(['text'] as const);\nexport const DEFAULT_PASTE_MAX_BYTES: number = 32 * 1024 * 1024;\nexport const DEFAULT_PASTE_MAX_ITEMS = 32;\n\nconst SHORTHANDS: ReadonlyMap<string, string> = /* @__PURE__ */ new Map([\n ['text', 'text/plain'],\n ['html', 'text/html'],\n ['image', 'image/*'],\n ['any', '*/*'],\n]);\n\nconst TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\nfunction resolvePattern(entry: unknown): string | null {\n if (typeof entry !== 'string') return null;\n const shorthand = SHORTHANDS.get(entry);\n if (shorthand !== undefined) return shorthand;\n if (entry === '*/*') return entry;\n if (entry.endsWith('/*')) {\n const type = entry.slice(0, -2).toLowerCase();\n return TYPE_TOKEN.test(type) ? `${type}/*` : null;\n }\n return normalizeClipboardType(entry);\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\n/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */\nexport function resolvePasteReadOptions(options: PasteReadOptions = {}): ResolvedPasteReadOptions {\n const accept: string[] = [];\n for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {\n const pattern = resolvePattern(entry);\n if (pattern === null) throw copyFailure('invalid-payload', `Invalid \\`accept\\` entry: ${JSON.stringify(entry)}.`);\n if (!accept.includes(pattern)) accept.push(pattern);\n }\n if (accept.length === 0) throw copyFailure('invalid-payload', '`accept` must list at least one type.');\n return {\n accept,\n maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, 'maxBytes'),\n maxItems: resolveLimit(options.maxItems, DEFAULT_PASTE_MAX_ITEMS, 'maxItems'),\n };\n}\n\n/** Whether a normalised MIME type is allowed by the resolved `accept` list. */\nexport function isAccepted(mimeType: string, options: ResolvedPasteReadOptions): boolean {\n return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));\n}\n\n/* -------------------------------------------------------------- Entries */\n\n/** An accepted, not-yet-verified entry. */\nexport interface PasteEntry {\n readonly type: string;\n readonly data: string | Blob;\n /** Came from `DataTransfer.files`, i.e. `data` is a `File`. */\n readonly file: boolean;\n}\n\ninterface Budget {\n readonly charge: (size: number) => void;\n}\n\nfunction createBudget(options: ResolvedPasteReadOptions): Budget {\n let bytes = 0;\n let items = 0;\n return {\n charge: (size) => {\n items += 1;\n bytes += size;\n if (items > options.maxItems) {\n throw copyFailure('too-large', `The paste has more than ${String(options.maxItems)} accepted items.`);\n }\n if (bytes > options.maxBytes) {\n throw copyFailure('too-large', `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);\n }\n },\n };\n}\n\n/**\n * UTF-8 byte length of a string, without allocating an encoded copy.\n * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.\n */\nexport function utf8ByteLength(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i += 1) {\n const unit = text.charCodeAt(i);\n if (unit < 0x80) bytes += 1;\n else if (unit < 0x800) bytes += 2;\n else if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n bytes += 4;\n i += 1;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */\nconst sizeOf = (data: string | Blob): number => (typeof data === 'string' ? utf8ByteLength(data) : data.size);\n\n/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */\nexport function enforcePasteLimits(entries: readonly PasteEntry[], options: ResolvedPasteReadOptions): void {\n const budget = createBudget(options);\n for (const entry of entries) budget.charge(sizeOf(entry.data));\n}\n\n/** Structural view of a `DataTransferItem`: only what is readable while dragging. */\nexport interface DataTransferItemLike {\n /** `'string'` or `'file'`. */\n readonly kind: string;\n readonly type: string;\n}\n\n/** Structural view of `DataTransfer` (paste and drop events). */\nexport interface DataTransferLike {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n readonly files?: ArrayLike<File> | null;\n readonly items?: ArrayLike<DataTransferItemLike> | null;\n}\n\n/**\n * Whether a drag in progress could drop anything `accept`s. Uses only what\n * browsers expose before the drop (item kinds and types, never the data).\n * A file whose type is not known yet (some browsers hide it while dragging)\n * counts as a maybe: the drop itself is checked against `accept`.\n */\nexport function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean {\n // Without an item list, a file is only known as the type \"Files\": treat it as an untyped file.\n const items = data.items ?? Array.from(data.types, (type) => (type === 'Files' ? { kind: 'file', type: '' } : { kind: 'string', type }));\n return Array.from(items).some(({ kind, type: raw }) => {\n const file = kind === 'file';\n const type = normalizeClipboardType(raw);\n if (type === null) return file;\n return (file || isTextualMimeType(type)) && isAccepted(type, options);\n });\n}\n\n/**\n * Synchronously copies the accepted parts of a paste event's `DataTransfer`.\n * It must run during the event: browsers empty the object afterwards.\n */\nexport function snapshotDataTransfer(data: DataTransferLike, options: ResolvedPasteReadOptions): PasteEntry[] {\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const raw of Array.from(data.types)) {\n const type = normalizeClipboardType(raw);\n // Binary types are delivered through `files`; `getData` only returns strings.\n if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n const text = data.getData(raw);\n if (text.length > 0) entries.push({ type, data: text, file: false });\n }\n\n for (const file of Array.from(data.files ?? [])) {\n const type = normalizeMimeType(file.type) ?? 'application/octet-stream';\n if (isAccepted(type, options)) entries.push({ type, data: file, file: true });\n }\n\n return entries;\n}\n\n/** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */\nexport interface ClipboardItemLike {\n readonly types: readonly string[];\n getType(type: string): Promise<Blob>;\n}\n\n/**\n * Reads the accepted types from `navigator.clipboard.read()` items, enforcing\n * the limits *before* decoding any text so an oversized paste is never buffered twice.\n */\nexport async function collectClipboardItems(\n items: readonly ClipboardItemLike[],\n options: ResolvedPasteReadOptions,\n signal?: AbortSignal,\n): Promise<PasteEntry[]> {\n const budget = createBudget(options);\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const item of items) {\n for (const raw of item.types) {\n const type = normalizeClipboardType(raw);\n if (type === null || seen.has(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n\n let blob: Blob;\n try {\n blob = await item.getType(raw);\n } catch {\n // Chromium lists some types it then refuses to hand over; skip them, don't fail the paste.\n continue;\n }\n // Cancelled (reset, superseded, unmounted) while waiting: don't decode the rest.\n if (signal?.aborted) throw copyFailure('aborted', 'The paste was cancelled.');\n if (blob.size === 0) continue;\n budget.charge(blob.size);\n entries.push({ type, data: isTextualMimeType(type) ? await blob.text() : blob, file: false });\n }\n }\n return entries;\n}\n\n/* ------------------------------------------------------------ Finalising */\n\nfunction retype(entry: PasteEntry, data: Blob, type: string): Blob {\n if (entry.file) {\n const file = data as File;\n return new File([file], file.name, { type, lastModified: file.lastModified });\n }\n return data.slice(0, data.size, type);\n}\n\n/**\n * Verifies image bytes, then builds the result. Blobs that claim to be images\n * but aren't (or whose real format is not accepted) are dropped. Throws\n * `no-content` when nothing survives.\n */\nexport async function finalizePaste(\n entries: readonly PasteEntry[],\n source: PasteSource,\n options: ResolvedPasteReadOptions,\n): Promise<PasteReadResult> {\n const items: PasteItem[] = [];\n const images: Blob[] = [];\n const files: File[] = [];\n let text: string | null = null;\n let html: string | null = null;\n\n for (const entry of entries) {\n let { type, data } = entry;\n\n if (typeof data === 'string') {\n // Types are de-duplicated upstream, so each of these is seen at most once.\n if (type === 'text/plain') text = data;\n else if (type === 'text/html') html = data;\n } else if (type.startsWith('image/')) {\n const actual = await sniffImageType(data);\n if (actual === null || !isAccepted(actual, options)) continue;\n if (actual !== type) {\n data = retype(entry, data, actual);\n type = actual;\n }\n images.push(data);\n }\n\n if (entry.file) files.push(data as File);\n items.push({ type, data });\n }\n\n if (items.length === 0) {\n throw copyFailure('no-content', 'The content holds nothing that matches `accept`.');\n }\n return { source, items, text, html, images, files };\n}\n"],"mappings":";;;;;AA4EA,SAAgB,oBAAoB,QAAsC;CACxE,MAAM,SAAS,IAAI,IAAU,OAAO,MAAM;CAC1C,OAAO;EAAE,GAAG;EAAQ,YAAY,OAAO,MAAM,QAAQ,SAAS,OAAO,IAAI,IAAI,CAAC;CAAE;AAClF;AAIA,MAAa,uBAA+D,uBAAO,OAAO,CAAC,MAAM,CAAU;AAC3G,MAAa,0BAAkC;AAC/C,MAAa,0BAA0B;AAEvC,MAAM,6BAA0D,IAAI,IAAI;CACtE,CAAC,QAAQ,YAAY;CACrB,CAAC,QAAQ,WAAW;CACpB,CAAC,SAAS,SAAS;CACnB,CAAC,OAAO,KAAK;AACf,CAAC;AAED,MAAM,aAAa;AAEnB,SAAS,eAAe,OAA+B;CACrD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,MAAM,YAAY,WAAW,IAAI,KAAK;CACtC,IAAI,cAAc,KAAA,GAAW,OAAO;CACpC,IAAI,UAAU,OAAO,OAAO;CAC5B,IAAI,MAAM,SAAS,IAAI,GAAG;EACxB,MAAM,OAAO,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC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;GAAE;GAAM,cAAc,KAAK;EAAa,CAAC;CAC9E;CACA,OAAO,KAAK,MAAM,GAAG,KAAK,MAAM,IAAI;AACtC;;;;;;AAOA,eAAsB,cACpB,SACA,QACA,SAC0B;CAC1B,MAAM,QAAqB,CAAC;CAC5B,MAAM,SAAiB,CAAC;CACxB,MAAM,QAAgB,CAAC;CACvB,IAAI,OAAsB;CAC1B,IAAI,OAAsB;CAE1B,KAAK,MAAM,SAAS,SAAS;EAC3B,IAAI,EAAE,MAAM,SAAS;EAErB,IAAI,OAAO,SAAS,UAAU;GAE5B,IAAI,SAAS,cAAc,OAAO;QAC7B,IAAI,SAAS,aAAa,OAAO;EACxC,OAAO,IAAI,KAAK,WAAW,QAAQ,GAAG;GACpC,MAAM,SAAS,MAAM,eAAe,IAAI;GACxC,IAAI,WAAW,QAAQ,CAAC,WAAW,QAAQ,OAAO,GAAG;GACrD,IAAI,WAAW,MAAM;IACnB,OAAO,OAAO,OAAO,MAAM,MAAM;IACjC,OAAO;GACT;GACA,OAAO,KAAK,IAAI;EAClB;EAEA,IAAI,MAAM,MAAM,MAAM,KAAK,IAAY;EACvC,MAAM,KAAK;GAAE;GAAM;EAAK,CAAC;CAC3B;CAEA,IAAI,MAAM,WAAW,GACnB,MAAM,YAAY,cAAc,kDAAkD;CAEpF,OAAO;EAAE;EAAQ;EAAO;EAAM;EAAM;EAAQ;CAAM;AACpD"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { r as createCopyError, t as CopyFailure } from "./errors-CT-FfUtU.js";
2
+ import { r as createCopyError, t as CopyFailure } from "./errors-CGcMvbhJ.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-BrQWGwyx.js.map
71
+ //# sourceMappingURL=payload-5uJedhwz.js.map
@@ -1 +1 @@
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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,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,IAAI,YACR,gBAAgB,mBAAmB,yEAAyE,KAAK,CACnH;CACF;CACA,IAAI,OAAO,SAAS,UAClB,MAAM,IAAI,YACR,gBAAgB,mBAAmB,qFAAqF,CAC1H;CAEF,OAAO;AACT"}
1
+ {"version":3,"file":"payload-5uJedhwz.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;AAC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AAW,MAAM;IACvB,MAAM,OAAO,MAAM;IACnB,IAAI,OAAO,aAAa,YAAY,SAAS,WAAW,GACtD,OAAO,QAAQ,gDAAgD;IAEjE,IAAI,KAAK,IAAI,QAAQ,GAAG,OAAO,QAAQ,wBAAwB,SAAS,oBAAoB;IAC5F,KAAK,IAAI,QAAQ;IACjB,IAAI,OAAO,SAAS,YAAY,CAAC,OAAO,IAAI,GAC1C,OAAO,QAAQ,eAAe,SAAS,mCAAmC;GAE9E;GACA,OAAO;EACT;EACA,SACE,OAAO,QAAQ,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,IAAI,YACR,gBAAgB,mBAAmB,yEAAyE,KAAK,CACnH;CACF;CACA,IAAI,OAAO,SAAS,UAClB,MAAM,IAAI,YACR,gBAAgB,mBAAmB,qFAAqF,CAC1H;CAEF,OAAO;AACT"}
@@ -1,6 +1,6 @@
1
1
 
2
- import { n as copyFailure } from "./errors-CT-FfUtU.js";
3
- import { a as resolveLinkUrl } from "./url-COID0BLY.js";
2
+ import { n as copyFailure } from "./errors-CGcMvbhJ.js";
3
+ import { a as resolveLinkUrl } from "./url-zB_krkuF.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-BWQ6sPtS.js.map
103
+ //# sourceMappingURL=payload-DZnXoBmF.js.map
@@ -1 +1 @@
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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\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,YAAoB,YAAY,mBAAmB,OAAO;;;;;AAO3E,MAAM,SAAS;;AAGf,SAAgB,WAAW,OAAe,WAA2B;CACnE,MAAM,QAAQ,MAAM,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK;CAClE,IAAI,MAAM,UAAU,WAAW,OAAO;CAEtC,OAAO,GAAG,MAAM,KAAK,KAAK,CAAC,CAAC,MAAM,GAAG,YAAY,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,QAAQ,EAAE;AACzE;AAEA,SAAS,SAAS,OAAmC;CACnD,IAAI,UAAU,KAAA,GAAW,OAAA;CACzB,IAAI,OAAO,UAAU,KAAK,KAAK,SAAS,GAAG,OAAO;CAClD,MAAM,QAAQ,2DAA2D,OAAO,KAAK,EAAE,GAAG;AAC5F;AAEA,SAAS,SAAS,QAA8C;CAC9D,OAAO,OAAO,WAAW,YAAY,WAAW,QAAS,OAAkC,aAAa,OAAO,OAAQ,OAA8B,SAAS;AAChK;;;;;AAMA,SAAgB,YAAY,QAAoB,UAA8B,CAAC,GAAiB;CAC9F,IAAI;CACJ,IAAI;CACJ,IAAI,OAAO,WAAW,YAAY,kBAAkB,KAClD,MAAM;MACD,IAAI,SAAS,MAAM,GAAG;EAC3B,MAAM,OAAO,aAAa,MAAM,KAAK;EACrC,QAAQ,OAAO,YAAY,KAAK,MAAM,KAAK,OAAO,cAAe,OAAO,aAAa,OAAO,KAAK,KAAA;EACjG,IAAI,QAAQ,MAAM,QAAQ,SAAS,KA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AAM,QAAQ,6CAAyC;CACxG,MAAM,OAAO,YAAY,QAAQ,OAAO;CACxC,MAAM,OAAO,UAAU,MAAM,QAAQ,QAAQ,KAAK;CAClD,MAAM,OAAO,YAAY,WAAW,KAAK,GAAG,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
+ {"version":3,"file":"payload-DZnXoBmF.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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\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,YAAoB,YAAY,mBAAmB,OAAO;;;;;AAO3E,MAAM,SAAS;;AAGf,SAAgB,WAAW,OAAe,WAA2B;CACnE,MAAM,QAAQ,MAAM,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK;CAClE,IAAI,MAAM,UAAU,WAAW,OAAO;CAEtC,OAAO,GAAG,MAAM,KAAK,KAAK,CAAC,CAAC,MAAM,GAAG,YAAY,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,QAAQ,EAAE;AACzE;AAEA,SAAS,SAAS,OAAmC;CACnD,IAAI,UAAU,KAAA,GAAW,OAAA;CACzB,IAAI,OAAO,UAAU,KAAK,KAAK,SAAS,GAAG,OAAO;CAClD,MAAM,QAAQ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AC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,GAC5E,EAAE;AAC9B;AAEA,SAAS,UAAU,MAAoB,QAAgC;CACrE,QAAQ,QAAR;EACE,KAAK,OACH,OAAO,KAAK;EACd,KAAK,SACH,OAAO,KAAK;EACd,KAAK,iBACH,OAAO,KAAK,SAAS,GAAG,KAAK,MAAM,IAAI,KAAK,QAAQ,KAAK;EAC3D,KAAK,YACH,OAAO,aAAa,IAAI;EAC1B,SACE,MAAM,QAAQ,4EAA4E,KAAK,UAAU,MAAM,EAAE,GAAG;CACxH;AACF;AAeA,SAAgB,YAAY,QAAoB,UAA2E,CAAC,GAA+B;CACzJ,MAAM,SAAkB,QAAQ,UAAU;CAC1C,IAAI,WAAW,UAAU,WAAW,aAAa,MAAM,QAAQ,6CAAyC;CACxG,MAAM,OAAO,YAAY,QAAQ,OAAO;CACxC,MAAM,OAAO,UAAU,MAAM,QAAQ,QAAQ,KAAK;CAClD,MAAM,OAAO,YAAY,WAAW,KAAK,GAAG,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
- const require_errors = require("./errors-DFmEAC4E.cjs");
2
+ const require_errors = require("./errors-CF2EQNbc.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-sBxkG7jH.cjs.map
100
+ //# sourceMappingURL=payload-DjSSLonm.cjs.map
@@ -1 +1 @@
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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S,mCAAmC;GAE9E;GACA,OAAO;EACT;EACA,SACE,OAAO,QAAQ,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
+ {"version":3,"file":"payload-DjSSLonm.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,M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AAO,IAAI,IAAY;GAC7B,KAAK,MAAM,QAAQ,OAAoB;IACrC,MAAM,QAAS,OAAO,SAAS,YAAY,SAAS,OAAO,OAAO,CAAC;IACnE,MAAM,WAAW,MAAM;IACvB,MAAM,OAAO,MAAM;IACnB,IAAI,OAAO,aAAa,YAAY,SAAS,WAAW,GACtD,OAAO,QAAQ,gDAAgD;IAEjE,IAAI,KAAK,IAAI,QAAQ,GAAG,OAAO,QAAQ,wBAAwB,SAAS,oBAAoB;IAC5F,KAAK,IAAI,QAAQ;IACjB,IAAI,OAAO,SAAS,YAAY,CAAC,OAAO,IAAI,GAC1C,OAAO,QAAQ,eAAe,SAAS,mCAAmC;GAE9E;GACA,OAAO;EACT;EACA,SACE,OAAO,QAAQ,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-DFmEAC4E.cjs");
3
- const require_url = require("./url-BrhVUwn7.cjs");
2
+ const require_errors = require("./errors-CF2EQNbc.cjs");
3
+ const require_url = require("./url-CL4YTCvM.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-tTK6REua.cjs.map
132
+ //# sourceMappingURL=payload-DzHhs6Ey.cjs.map
@@ -1 +1 @@
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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\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,eAAAA,YAAY,mBAAmB,OAAO;;;;;AAO3E,MAAM,SAAS;;AAGf,SAAgB,WAAW,OAAe,WAA2B;CACnE,MAAM,QAAQ,MAAM,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK;CAClE,IAAI,MAAM,UAAU,WAAW,OAAO;CAEtC,OAAO,GAAG,MAAM,KAAK,KAAK,CAAC,CAAC,MAAM,GAAG,YAAY,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,QAAQ,EAAE;AACzE;AAEA,SAAS,SAAS,OAAmC;CACnD,IAAI,UAAU,KAAA,GAAW,OAAA;CACzB,IAAI,OAAO,UAAU,KAAK,KAAK,SAAS,GAAG,OAAO;CAClD,MAAM,QAAQ,2DAA2D,OAAO,KAAK,EAAE,GAAG;AAC5F;AAEA,SAAS,SAAS,QAA8C;CAC9D,OAAO,OAAO,WAAW,YAAY,WAAW,QAAS,OAAkC,aAAa,OAAO,OAAQ,OAA8B,SAAS;AAChK;;;;;AAMA,SAAgB,YAAY,QAAoB,UAA8B,CAAC,GAAiB;CAC9F,IAAI;CACJ,IAAI;CACJ,IAAI,OAAO,WAAW,YAAY,kBAAkB,KAClD,MAAM;MACD,IAAI,SAAS,MAAM,GAAG;EAC3B,MAAM,OAAO,aAAa,MAAM,KAAK;EACrC,QAAQ,OAAO,YA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SAAgB,YAAY,QAAoB,UAA2E,CAAC,GAA+B;CACzJ,MAAM,SAAkB,QAAQ,UAAU;CAC1C,IAAI,WAAW,UAAU,WAAW,aAAa,MAAM,QAAQ,6CAAyC;CACxG,MAAM,OAAO,YAAY,QAAQ,OAAO;CACxC,MAAM,OAAO,UAAU,MAAM,QAAQ,QAAQ,KAAK;CAClD,MAAM,OAAO,YAAY,WAAW,KAAK,GAAG,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
+ {"version":3,"file":"payload-DzHhs6Ey.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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\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,eAAAA,YAAY,mBAAmB,OAAO;;;;;AAO3E,MAAM,SAAS;;AAGf,SAAgB,WAAW,OAAe,WAA2B;CACnE,MAAM,QAAQ,MAAM,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK;CAClE,IAAI,MAAM,UAAU,WAAW,OAAO;CAEtC,OAAO,GAAG,MAAM,KAAK,KAAK,CAAC,CAAC,MAAM,GAAG,YAAY,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,QAAQ,E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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");
2
+ const require_errors = require("./errors-CF2EQNbc.cjs");
3
+ const require_payload = require("./payload-DjSSLonm.cjs");
4
+ const require_clipboard_adapter = require("./clipboard-adapter-5bmjKbyK.cjs");
5
+ const require_url = require("./url-CL4YTCvM.cjs");
6
+ const require_payload$1 = require("./payload-DzHhs6Ey.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-nx7M4Z0t.cjs.map
231
+ //# sourceMappingURL=share-Bu5u2ItX.cjs.map