react-smart-copy 1.17.2 → 1.19.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 (154) hide show
  1. package/README.md +86 -5
  2. package/dist/capture.cjs +30 -153
  3. package/dist/capture.cjs.map +1 -1
  4. package/dist/capture.d.cts +2 -25
  5. package/dist/capture.d.ts +2 -25
  6. package/dist/capture.js +5 -128
  7. package/dist/capture.js.map +1 -1
  8. package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs +102 -0
  9. package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs.map +1 -0
  10. package/dist/chunks/clipboard-adapter-CtH4VELE.d.cts +43 -0
  11. package/dist/chunks/clipboard-adapter-DEXkXxwV.js +97 -0
  12. package/dist/chunks/clipboard-adapter-DEXkXxwV.js.map +1 -0
  13. package/dist/chunks/clipboard-adapter-Ds0irroN.d.ts +43 -0
  14. package/dist/chunks/contrast-C6CVklEI.cjs +842 -0
  15. package/dist/chunks/contrast-C6CVklEI.cjs.map +1 -0
  16. package/dist/chunks/contrast-DpK2JIVu.js +789 -0
  17. package/dist/chunks/contrast-DpK2JIVu.js.map +1 -0
  18. package/dist/chunks/copy-interceptor-C6NABy1l.d.ts +141 -0
  19. package/dist/chunks/copy-interceptor-CZWzGOkL.d.cts +141 -0
  20. package/dist/chunks/core-Cp2HSpaz.js +1035 -0
  21. package/dist/chunks/core-Cp2HSpaz.js.map +1 -0
  22. package/dist/chunks/core-DYf_Lhbe.cjs +1142 -0
  23. package/dist/chunks/core-DYf_Lhbe.cjs.map +1 -0
  24. package/dist/chunks/deadline-C29AlS_Q.js +46 -0
  25. package/dist/chunks/deadline-C29AlS_Q.js.map +1 -0
  26. package/dist/chunks/deadline-DkiB8ZHE.cjs +51 -0
  27. package/dist/chunks/deadline-DkiB8ZHE.cjs.map +1 -0
  28. package/dist/chunks/errors-9h8sdFFX.js +120 -0
  29. package/dist/chunks/errors-9h8sdFFX.js.map +1 -0
  30. package/dist/chunks/errors-BwOF6T_M.cjs +167 -0
  31. package/dist/chunks/errors-BwOF6T_M.cjs.map +1 -0
  32. package/dist/chunks/index-mr7sSAgP.d.ts +426 -0
  33. package/dist/chunks/index-vz0iW5V2.d.cts +426 -0
  34. package/dist/chunks/inert-html-D75NyVvT.js +34 -0
  35. package/dist/chunks/inert-html-D75NyVvT.js.map +1 -0
  36. package/dist/chunks/inert-html-DyxjWDok.cjs +39 -0
  37. package/dist/chunks/inert-html-DyxjWDok.cjs.map +1 -0
  38. package/dist/chunks/mime--LB7kdqG.cjs +153 -0
  39. package/dist/chunks/mime--LB7kdqG.cjs.map +1 -0
  40. package/dist/chunks/mime-aa-HA2dm.js +100 -0
  41. package/dist/chunks/mime-aa-HA2dm.js.map +1 -0
  42. package/dist/chunks/paste-adapter--SPL4PRE.d.cts +35 -0
  43. package/dist/chunks/paste-adapter-uahXnTYk.d.ts +35 -0
  44. package/dist/chunks/paste-reader-Bo01IMC_.cjs +289 -0
  45. package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +1 -0
  46. package/dist/chunks/paste-reader-D9i7yMXF.js +224 -0
  47. package/dist/chunks/paste-reader-D9i7yMXF.js.map +1 -0
  48. package/dist/chunks/paste-reader-DcXnRWQr.d.cts +96 -0
  49. package/dist/chunks/paste-reader-DcXnRWQr.d.ts +96 -0
  50. package/dist/chunks/payload-CUymxwim.cjs +100 -0
  51. package/dist/chunks/payload-CUymxwim.cjs.map +1 -0
  52. package/dist/chunks/payload-CcwKJ_bU.d.cts +162 -0
  53. package/dist/chunks/payload-Cl_8hCI5.d.ts +162 -0
  54. package/dist/chunks/payload-DGw-JOo7.js +71 -0
  55. package/dist/chunks/payload-DGw-JOo7.js.map +1 -0
  56. package/dist/chunks/payload-DI5AorDz.js +103 -0
  57. package/dist/chunks/payload-DI5AorDz.js.map +1 -0
  58. package/dist/chunks/payload-J6GjHuh3.cjs +132 -0
  59. package/dist/chunks/payload-J6GjHuh3.cjs.map +1 -0
  60. package/dist/chunks/share-Bop47Znn.js +208 -0
  61. package/dist/chunks/share-Bop47Znn.js.map +1 -0
  62. package/dist/chunks/share-C0esXvRK.d.cts +115 -0
  63. package/dist/chunks/share-ayDz974N.cjs +231 -0
  64. package/dist/chunks/share-ayDz974N.cjs.map +1 -0
  65. package/dist/chunks/share-e7FenIr2.d.ts +115 -0
  66. package/dist/chunks/text-field-Ba8W3v4R.cjs +77 -0
  67. package/dist/chunks/text-field-Ba8W3v4R.cjs.map +1 -0
  68. package/dist/chunks/text-field-C0SGmvvR.d.cts +18 -0
  69. package/dist/chunks/text-field-C0SGmvvR.d.ts +18 -0
  70. package/dist/chunks/text-field-DUvrMMaK.js +66 -0
  71. package/dist/chunks/text-field-DUvrMMaK.js.map +1 -0
  72. package/dist/chunks/url-B9jdFGQy.cjs +86 -0
  73. package/dist/chunks/url-B9jdFGQy.cjs.map +1 -0
  74. package/dist/chunks/url-BcMYVCXQ.js +135 -0
  75. package/dist/chunks/url-BcMYVCXQ.js.map +1 -0
  76. package/dist/chunks/url-D4PGsRm8.cjs +164 -0
  77. package/dist/chunks/url-D4PGsRm8.cjs.map +1 -0
  78. package/dist/chunks/url-DWdElCT3.d.cts +43 -0
  79. package/dist/chunks/url-DWdElCT3.d.ts +43 -0
  80. package/dist/chunks/url-vJaFPbNL.js +57 -0
  81. package/dist/chunks/url-vJaFPbNL.js.map +1 -0
  82. package/dist/code.cjs +22 -113
  83. package/dist/code.cjs.map +1 -1
  84. package/dist/code.d.cts +4 -28
  85. package/dist/code.d.ts +4 -28
  86. package/dist/code.js +5 -96
  87. package/dist/code.js.map +1 -1
  88. package/dist/color.cjs +21 -893
  89. package/dist/color.cjs.map +1 -1
  90. package/dist/color.d.cts +4 -28
  91. package/dist/color.d.ts +4 -28
  92. package/dist/color.js +4 -876
  93. package/dist/color.js.map +1 -1
  94. package/dist/core.cjs +52 -1659
  95. package/dist/core.d.cts +8 -878
  96. package/dist/core.d.ts +8 -878
  97. package/dist/core.js +7 -1614
  98. package/dist/image.cjs +23 -94
  99. package/dist/image.cjs.map +1 -1
  100. package/dist/image.d.cts +1 -0
  101. package/dist/image.d.ts +1 -0
  102. package/dist/image.js +3 -74
  103. package/dist/image.js.map +1 -1
  104. package/dist/index.cjs +74 -2072
  105. package/dist/index.cjs.map +1 -1
  106. package/dist/index.d.cts +8 -978
  107. package/dist/index.d.ts +8 -978
  108. package/dist/index.js +7 -2005
  109. package/dist/index.js.map +1 -1
  110. package/dist/link.cjs +26 -339
  111. package/dist/link.cjs.map +1 -1
  112. package/dist/link.d.cts +5 -83
  113. package/dist/link.d.ts +5 -83
  114. package/dist/link.js +7 -320
  115. package/dist/link.js.map +1 -1
  116. package/dist/markdown.cjs +19 -159
  117. package/dist/markdown.cjs.map +1 -1
  118. package/dist/markdown.d.cts +3 -16
  119. package/dist/markdown.d.ts +3 -16
  120. package/dist/markdown.js +6 -146
  121. package/dist/markdown.js.map +1 -1
  122. package/dist/rich.cjs +1123 -940
  123. package/dist/rich.cjs.map +1 -1
  124. package/dist/rich.d.cts +101 -91
  125. package/dist/rich.d.ts +101 -91
  126. package/dist/rich.js +1099 -919
  127. package/dist/rich.js.map +1 -1
  128. package/dist/share.cjs +5 -640
  129. package/dist/share.d.cts +3 -248
  130. package/dist/share.d.ts +3 -248
  131. package/dist/share.js +1 -637
  132. package/dist/structured.cjs +13 -95
  133. package/dist/structured.cjs.map +1 -1
  134. package/dist/structured.d.cts +2 -11
  135. package/dist/structured.d.ts +2 -11
  136. package/dist/structured.js +4 -86
  137. package/dist/structured.js.map +1 -1
  138. package/dist/table.cjs +13 -40
  139. package/dist/table.cjs.map +1 -1
  140. package/dist/table.d.cts +2 -12
  141. package/dist/table.d.ts +2 -12
  142. package/dist/table.js +4 -31
  143. package/dist/table.js.map +1 -1
  144. package/dist/testing.cjs +10 -43
  145. package/dist/testing.cjs.map +1 -1
  146. package/dist/testing.d.cts +6 -181
  147. package/dist/testing.d.ts +6 -181
  148. package/dist/testing.js +3 -36
  149. package/dist/testing.js.map +1 -1
  150. package/package.json +37 -5
  151. package/dist/core.cjs.map +0 -1
  152. package/dist/core.js.map +0 -1
  153. package/dist/share.cjs.map +0 -1
  154. package/dist/share.js.map +0 -1
@@ -0,0 +1,86 @@
1
+
2
+ //#region src/markdown/url.ts
3
+ /**
4
+ * URL safety for pasted links and images. Only absolute URLs with an allowed
5
+ * scheme survive; everything else (`javascript:`, `data:`, `vbscript:`,
6
+ * relative links without a base, malformed URLs) is dropped and the visible
7
+ * text is kept. Parsing uses the WHATWG URL parser, the same one the browser
8
+ * uses when the link is clicked, so tricks like `java\tscript:` are seen as
9
+ * `javascript:`.
10
+ */
11
+ const DEFAULT_LINK_PROTOCOLS = [
12
+ "http:",
13
+ "https:",
14
+ "mailto:"
15
+ ];
16
+ const DEFAULT_IMAGE_PROTOCOLS = ["https:", "http:"];
17
+ function parse(raw, base) {
18
+ try {
19
+ return new URL(raw.trim(), base);
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+ /**
25
+ * Click-tracking redirects that pasted links often carry: Google (Docs,
26
+ * Search, Gmail) and Outlook Safe Links. Unwrapped only to an http(s) target.
27
+ */
28
+ function unwrapRedirect(url) {
29
+ const host = url.hostname.toLowerCase();
30
+ const param = /(^|\.)google\.[a-z.]+$/.test(host) && url.pathname === "/url" ? url.searchParams.get("q") ?? url.searchParams.get("url") : host.endsWith(".safelinks.protection.outlook.com") ? url.searchParams.get("url") : null;
31
+ if (param === null) return url;
32
+ const target = parse(param, void 0);
33
+ return target !== null && (target.protocol === "https:" || target.protocol === "http:") ? target : url;
34
+ }
35
+ /** The normalised URL, or `null` when it is not absolute or its scheme is not allowed. */
36
+ function safeUrl(raw, protocols, base) {
37
+ const parsed = parse(raw, base);
38
+ if (parsed === null) return null;
39
+ const url = unwrapRedirect(parsed);
40
+ return protocols.includes(url.protocol) ? url.href : null;
41
+ }
42
+ /** `href` comes from the URL serialiser, which already percent-encodes every non-ASCII character. */
43
+ const percent = (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`;
44
+ /**
45
+ * A Markdown link destination. ASCII whitespace, `<`, `>` and controls are
46
+ * percent-encoded (opaque URLs such as `mailto:` keep them otherwise),
47
+ * backslashes too so they can't act as escapes, and parentheses are kept
48
+ * exact by using the `<…>` form.
49
+ */
50
+ function linkDestination(href) {
51
+ const encoded = href.replace(/[ <>\\\u0000-\u001f\u007f]/g, percent);
52
+ return /[()]/.test(encoded) ? `<${encoded}>` : encoded;
53
+ }
54
+ //#endregion
55
+ Object.defineProperty(exports, "DEFAULT_IMAGE_PROTOCOLS", {
56
+ enumerable: true,
57
+ get: function() {
58
+ return DEFAULT_IMAGE_PROTOCOLS;
59
+ }
60
+ });
61
+ Object.defineProperty(exports, "DEFAULT_LINK_PROTOCOLS", {
62
+ enumerable: true,
63
+ get: function() {
64
+ return DEFAULT_LINK_PROTOCOLS;
65
+ }
66
+ });
67
+ Object.defineProperty(exports, "linkDestination", {
68
+ enumerable: true,
69
+ get: function() {
70
+ return linkDestination;
71
+ }
72
+ });
73
+ Object.defineProperty(exports, "safeUrl", {
74
+ enumerable: true,
75
+ get: function() {
76
+ return safeUrl;
77
+ }
78
+ });
79
+ Object.defineProperty(exports, "unwrapRedirect", {
80
+ enumerable: true,
81
+ get: function() {
82
+ return unwrapRedirect;
83
+ }
84
+ });
85
+
86
+ //# sourceMappingURL=url-B9jdFGQy.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url-B9jdFGQy.cjs","names":[],"sources":["../../src/markdown/url.ts"],"sourcesContent":["/**\n * URL safety for pasted links and images. Only absolute URLs with an allowed\n * scheme survive; everything else (`javascript:`, `data:`, `vbscript:`,\n * relative links without a base, malformed URLs) is dropped and the visible\n * text is kept. Parsing uses the WHATWG URL parser, the same one the browser\n * uses when the link is clicked, so tricks like `java\\tscript:` are seen as\n * `javascript:`.\n */\n\nexport const DEFAULT_LINK_PROTOCOLS: readonly string[] = ['http:', 'https:', 'mailto:'];\nexport const DEFAULT_IMAGE_PROTOCOLS: readonly string[] = ['https:', 'http:'];\n\nfunction parse(raw: string, base: string | undefined): URL | null {\n try {\n return new URL(raw.trim(), base);\n } catch {\n return null;\n }\n}\n\n/**\n * Click-tracking redirects that pasted links often carry: Google (Docs,\n * Search, Gmail) and Outlook Safe Links. Unwrapped only to an http(s) target.\n */\nexport function unwrapRedirect(url: URL): URL {\n const host = url.hostname.toLowerCase();\n const param =\n /(^|\\.)google\\.[a-z.]+$/.test(host) && url.pathname === '/url'\n ? (url.searchParams.get('q') ?? url.searchParams.get('url'))\n : host.endsWith('.safelinks.protection.outlook.com')\n ? url.searchParams.get('url')\n : null;\n if (param === null) return url;\n const target = parse(param, undefined);\n return target !== null && (target.protocol === 'https:' || target.protocol === 'http:') ? target : url;\n}\n\n/** The normalised URL, or `null` when it is not absolute or its scheme is not allowed. */\nexport function safeUrl(raw: string, protocols: readonly string[], base: string | undefined): string | null {\n const parsed = parse(raw, base);\n if (parsed === null) return null;\n const url = unwrapRedirect(parsed);\n return protocols.includes(url.protocol) ? url.href : null;\n}\n\n/** `href` comes from the URL serialiser, which already percent-encodes every non-ASCII character. */\nconst percent = (char: string): string => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`;\n\n/**\n * A Markdown link destination. ASCII whitespace, `<`, `>` and controls are\n * percent-encoded (opaque URLs such as `mailto:` keep them otherwise),\n * backslashes too so they can't act as escapes, and parentheses are kept\n * exact by using the `<…>` form.\n */\nexport function linkDestination(href: string): string {\n // eslint-disable-next-line no-control-regex -- control characters are exactly what must be encoded\n const encoded = href.replace(/[ <>\\\\\\u0000-\\u001f\\u007f]/g, percent);\n return /[()]/.test(encoded) ? `<${encoded}>` : encoded;\n}\n"],"mappings":";;;;;;;;;;AASA,MAAa,yBAA4C;CAAC;CAAS;CAAU;AAAS;AACtF,MAAa,0BAA6C,CAAC,UAAU,OAAO;AAE5E,SAAS,MAAM,KAAa,MAAsC;CAChE,IAAI;EACF,OAAO,IAAI,IAAI,IAAI,KAAK,GAAG,IAAI;CACjC,QAAQ;EACN,OAAO;CACT;AACF;;;;;AAMA,SAAgB,eAAe,KAAe;CAC5C,MAAM,OAAO,IAAI,SAAS,YAAY;CACtC,MAAM,QACJ,yBAAyB,KAAK,IAAI,KAAK,IAAI,aAAa,SACnD,IAAI,aAAa,IAAI,GAAG,KAAK,IAAI,aAAa,IAAI,KAAK,IACxD,KAAK,SAAS,mCAAmC,IAC/C,IAAI,aAAa,IAAI,KAAK,IAC1B;CACR,IAAI,UAAU,MAAM,OAAO;CAC3B,MAAM,SAAS,MAAM,OAAO,KAAA,CAAS;CACrC,OAAO,WAAW,SAAS,OAAO,aAAa,YAAY,OAAO,aAAa,WAAW,SAAS;AACrG;;AAGA,SAAgB,QAAQ,KAAa,WAA8B,MAAyC;CAC1G,MAAM,SAAS,MAAM,KAAK,IAAI;CAC9B,IAAI,WAAW,MAAM,OAAO;CAC5B,MAAM,MAAM,eAAe,MAAM;CACjC,OAAO,UAAU,SAAS,IAAI,QAAQ,IAAI,IAAI,OAAO;AACvD;;AAGA,MAAM,WAAW,SAAyB,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS,GAAG,GAAG;;;;;;;AAQ3G,SAAgB,gBAAgB,MAAsB;CAEpD,MAAM,UAAU,KAAK,QAAQ,+BAA+B,OAAO;CACnE,OAAO,OAAO,KAAK,OAAO,IAAI,IAAI,QAAQ,KAAK;AACjD"}
@@ -0,0 +1,135 @@
1
+
2
+ import { n as copyFailure } from "./errors-9h8sdFFX.js";
3
+ //#region src/link/url.ts
4
+ /** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */
5
+ const DEFAULT_LINK_PROTOCOLS = /* @__PURE__ */ Object.freeze([
6
+ "https:",
7
+ "http:",
8
+ "mailto:",
9
+ "tel:"
10
+ ]);
11
+ /**
12
+ * Query parameters that only track where a click came from: the defaults of
13
+ * {@link cleanLinkUrl}. `utm_` matches every parameter starting with it.
14
+ */
15
+ const TRACKING_PARAMETERS = /* @__PURE__ */ Object.freeze([
16
+ "utm_",
17
+ "fbclid",
18
+ "gclid",
19
+ "gclsrc",
20
+ "dclid",
21
+ "gbraid",
22
+ "wbraid",
23
+ "msclkid",
24
+ "yclid",
25
+ "twclid",
26
+ "ttclid",
27
+ "li_fat_id",
28
+ "igshid",
29
+ "igsh",
30
+ "mc_cid",
31
+ "mc_eid",
32
+ "_hsenc",
33
+ "_hsmi",
34
+ "mkt_tok",
35
+ "oly_anon_id",
36
+ "oly_enc_id",
37
+ "vero_id",
38
+ "wickedid",
39
+ "_gl"
40
+ ]);
41
+ const invalid = (message) => copyFailure("invalid-payload", message);
42
+ function baseUrl(base) {
43
+ if (base !== void 0) {
44
+ if (typeof base === "string" || base instanceof URL) return String(base);
45
+ throw invalid("`base` must be a string or a URL.");
46
+ }
47
+ return typeof location === "undefined" ? void 0 : location.href;
48
+ }
49
+ function protocolSet(protocols) {
50
+ const list = protocols ?? DEFAULT_LINK_PROTOCOLS;
51
+ const valid = (protocol) => typeof protocol === "string" && /^[a-z][a-z\d+.-]*:$/i.test(protocol);
52
+ if (!Array.isArray(list) || list.length === 0 || !list.every(valid)) throw invalid("`protocols` must be a non-empty list of schemes with their colon, like \"https:\".");
53
+ return new Set(list.map((protocol) => protocol.toLowerCase()));
54
+ }
55
+ function matcher(params) {
56
+ const list = params ?? TRACKING_PARAMETERS;
57
+ if (!Array.isArray(list) || !list.every((param) => typeof param === "string" || param instanceof RegExp)) throw invalid("`clean.params` must be a list of strings and regular expressions.");
58
+ return (name) => {
59
+ const lower = name.toLowerCase();
60
+ return list.some((param) => {
61
+ if (typeof param !== "string") return new RegExp(param.source, param.flags.replace(/[gy]/g, "")).test(name);
62
+ const wanted = param.toLowerCase();
63
+ return wanted.endsWith("_") ? lower.startsWith(wanted) : lower === wanted;
64
+ });
65
+ };
66
+ }
67
+ /** The cleaning step `clean` asks for, or `null`. Throws for an invalid option. */
68
+ function cleaner(option) {
69
+ const cleaning = option ?? false;
70
+ if (cleaning === false) return null;
71
+ if (cleaning !== true && (typeof cleaning !== "object" || cleaning === null)) throw invalid("`clean` must be a boolean or an options object.");
72
+ const settings = cleaning === true ? {} : cleaning;
73
+ const tracking = matcher(settings.params);
74
+ const keep = settings.keep ?? [];
75
+ if (!Array.isArray(keep) || !keep.every((name) => typeof name === "string")) throw invalid("`clean.keep` must be a list of strings.");
76
+ const kept = new Set(keep.map((name) => name.toLowerCase()));
77
+ return (url) => {
78
+ for (const name of [...new Set(url.searchParams.keys())]) if (tracking(name) && !kept.has(name.toLowerCase())) url.searchParams.delete(name);
79
+ };
80
+ }
81
+ /**
82
+ * Validates `options` once (throwing a typed `invalid-payload` error for invalid
83
+ * ones) and returns a resolver that throws only for invalid links.
84
+ * @internal
85
+ */
86
+ function linkUrlResolver(options = {}) {
87
+ const protocols = protocolSet(options.protocols);
88
+ const base = baseUrl(options.base);
89
+ const clean = cleaner(options.clean);
90
+ return (input) => {
91
+ if (typeof input !== "string" && !(input instanceof URL)) throw invalid("A link must be a string or a URL.");
92
+ const raw = String(input).trim();
93
+ if (raw === "") throw invalid("A link must not be empty.");
94
+ let url;
95
+ try {
96
+ url = new URL(raw, base);
97
+ } catch (cause) {
98
+ throw copyFailure("invalid-payload", `Not a valid link: ${JSON.stringify(raw.slice(0, 200))}.`, cause);
99
+ }
100
+ if (!protocols.has(url.protocol)) throw invalid(`Links with the scheme "${url.protocol}" are not allowed (allowed: ${[...protocols].join(", ")}).`);
101
+ url.username = "";
102
+ url.password = "";
103
+ clean?.(url);
104
+ return url.href;
105
+ };
106
+ }
107
+ /**
108
+ * The link as an absolute, safe URL string, or a typed `invalid-payload` error:
109
+ * relative links are resolved, the scheme must be allowed, user names and
110
+ * passwords are always removed, and tracking parameters optionally.
111
+ */
112
+ function resolveLinkUrl(input, options = {}) {
113
+ return linkUrlResolver(options)(input);
114
+ }
115
+ /**
116
+ * Removes tracking parameters (`utm_*`, `fbclid`, `gclid`, ...) from a link, keeping
117
+ * everything else, including the fragment. Also validates it like every link here.
118
+ *
119
+ * @example
120
+ * cleanLinkUrl('https://shop.example/p/42?utm_source=news&color=red'); // 'https://shop.example/p/42?color=red'
121
+ */
122
+ function cleanLinkUrl(url, options = {}) {
123
+ const { params, keep, ...rest } = options;
124
+ return resolveLinkUrl(url, {
125
+ ...rest,
126
+ clean: {
127
+ ...params === void 0 ? {} : { params },
128
+ ...keep === void 0 ? {} : { keep }
129
+ }
130
+ });
131
+ }
132
+ //#endregion
133
+ export { resolveLinkUrl as a, linkUrlResolver as i, TRACKING_PARAMETERS as n, cleanLinkUrl as r, DEFAULT_LINK_PROTOCOLS as t };
134
+
135
+ //# sourceMappingURL=url-BcMYVCXQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url-BcMYVCXQ.js","names":[],"sources":["../../src/link/url.ts"],"sourcesContent":["import { copyFailure } from '../core/errors';\n\n/** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */\nexport const DEFAULT_LINK_PROTOCOLS: readonly string[] = /* @__PURE__ */ Object.freeze(['https:', 'http:', 'mailto:', 'tel:']);\n\n/**\n * Query parameters that only track where a click came from: the defaults of\n * {@link cleanLinkUrl}. `utm_` matches every parameter starting with it.\n */\nexport const TRACKING_PARAMETERS: readonly string[] = /* @__PURE__ */ Object.freeze([\n 'utm_',\n 'fbclid',\n 'gclid',\n 'gclsrc',\n 'dclid',\n 'gbraid',\n 'wbraid',\n 'msclkid',\n 'yclid',\n 'twclid',\n 'ttclid',\n 'li_fat_id',\n 'igshid',\n 'igsh',\n 'mc_cid',\n 'mc_eid',\n '_hsenc',\n '_hsmi',\n 'mkt_tok',\n 'oly_anon_id',\n 'oly_enc_id',\n 'vero_id',\n 'wickedid',\n '_gl',\n]);\n\nexport interface CleanLinkOptions {\n /**\n * Parameters to remove: exact names, names ending in `_` (a prefix, like\n * `utm_`), or regular expressions tested against the name. Default {@link TRACKING_PARAMETERS}.\n */\n readonly params?: readonly (string | RegExp)[];\n /** Parameters never removed, even when `params` matches them. */\n readonly keep?: readonly string[];\n}\n\nexport interface LinkUrlOptions {\n /** Resolves relative links. Default: the page's address in a browser; required elsewhere for relative links. */\n readonly base?: string | URL;\n /** Allowed schemes, with the colon. Default {@link DEFAULT_LINK_PROTOCOLS}. */\n readonly protocols?: readonly string[];\n /** Remove tracking parameters: `true` for {@link TRACKING_PARAMETERS}, or your own list. Default `false`. */\n readonly clean?: boolean | CleanLinkOptions;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nfunction baseUrl(base: LinkUrlOptions['base']): string | undefined {\n if (base !== undefined) {\n if (typeof base === 'string' || base instanceof URL) return String(base);\n throw invalid('`base` must be a string or a URL.');\n }\n return typeof location === 'undefined' ? undefined : location.href;\n}\n\nfunction protocolSet(protocols: LinkUrlOptions['protocols']): ReadonlySet<string> {\n const list: unknown = protocols ?? DEFAULT_LINK_PROTOCOLS;\n const valid = (protocol: unknown): protocol is string => typeof protocol === 'string' && /^[a-z][a-z\\d+.-]*:$/i.test(protocol);\n if (!Array.isArray(list) || list.length === 0 || !(list as readonly unknown[]).every(valid)) {\n throw invalid('`protocols` must be a non-empty list of schemes with their colon, like \"https:\".');\n }\n return new Set((list as readonly string[]).map((protocol) => protocol.toLowerCase()));\n}\n\nfunction matcher(params: CleanLinkOptions['params']): (name: string) => boolean {\n const list = params ?? TRACKING_PARAMETERS;\n if (!Array.isArray(list) || !list.every((param) => typeof param === 'string' || param instanceof RegExp)) {\n throw invalid('`clean.params` must be a list of strings and regular expressions.');\n }\n return (name) => {\n const lower = name.toLowerCase();\n return list.some((param) => {\n if (typeof param !== 'string') return new RegExp(param.source, param.flags.replace(/[gy]/g, '')).test(name);\n const wanted = param.toLowerCase();\n return wanted.endsWith('_') ? lower.startsWith(wanted) : lower === wanted;\n });\n };\n}\n\n/** The cleaning step `clean` asks for, or `null`. Throws for an invalid option. */\nfunction cleaner(option: LinkUrlOptions['clean']): ((url: URL) => void) | null {\n const cleaning: unknown = option ?? false; // Plain-JS callers can pass anything.\n if (cleaning === false) return null;\n if (cleaning !== true && (typeof cleaning !== 'object' || cleaning === null)) throw invalid('`clean` must be a boolean or an options object.');\n const settings: CleanLinkOptions = cleaning === true ? {} : cleaning;\n const tracking = matcher(settings.params);\n const keep = settings.keep ?? [];\n if (!Array.isArray(keep) || !keep.every((name: unknown) => typeof name === 'string')) throw invalid('`clean.keep` must be a list of strings.');\n const kept = new Set(keep.map((name) => name.toLowerCase()));\n return (url) => {\n for (const name of [...new Set(url.searchParams.keys())]) {\n if (tracking(name) && !kept.has(name.toLowerCase())) url.searchParams.delete(name);\n }\n };\n}\n\n/**\n * Validates `options` once (throwing a typed `invalid-payload` error for invalid\n * ones) and returns a resolver that throws only for invalid links.\n * @internal\n */\nexport function linkUrlResolver(options: LinkUrlOptions = {}): (input: string | URL) => string {\n const protocols = protocolSet(options.protocols);\n const base = baseUrl(options.base);\n const clean = cleaner(options.clean);\n return (input) => {\n if (typeof input !== 'string' && !(input instanceof URL)) throw invalid('A link must be a string or a URL.');\n const raw = String(input).trim();\n if (raw === '') throw invalid('A link must not be empty.');\n let url: URL;\n try {\n url = new URL(raw, base);\n } catch (cause) {\n throw copyFailure('invalid-payload', `Not a valid link: ${JSON.stringify(raw.slice(0, 200))}.`, cause);\n }\n if (!protocols.has(url.protocol)) {\n throw invalid(`Links with the scheme \"${url.protocol}\" are not allowed (allowed: ${[...protocols].join(', ')}).`);\n }\n // Never copy or paste credentials embedded in a link.\n url.username = '';\n url.password = '';\n clean?.(url);\n return url.href;\n };\n}\n\n/**\n * The link as an absolute, safe URL string, or a typed `invalid-payload` error:\n * relative links are resolved, the scheme must be allowed, user names and\n * passwords are always removed, and tracking parameters optionally.\n */\nexport function resolveLinkUrl(input: string | URL, options: LinkUrlOptions = {}): string {\n return linkUrlResolver(options)(input);\n}\n\n/**\n * Removes tracking parameters (`utm_*`, `fbclid`, `gclid`, ...) from a link, keeping\n * everything else, including the fragment. Also validates it like every link here.\n *\n * @example\n * cleanLinkUrl('https://shop.example/p/42?utm_source=news&color=red'); // 'https://shop.example/p/42?color=red'\n */\nexport function cleanLinkUrl(url: string | URL, options: CleanLinkOptions & Omit<LinkUrlOptions, 'clean'> = {}): string {\n const { params, keep, ...rest } = options;\n return resolveLinkUrl(url, { ...rest, clean: { ...(params === undefined ? {} : { params }), ...(keep === undefined ? {} : { keep }) } });\n}\n"],"mappings":";;;;AAGA,MAAa,yBAA4D,uBAAO,OAAO;CAAC;CAAU;CAAS;CAAW;AAAM,CAAC;;;;;AAM7H,MAAa,sBAAyD,uBAAO,OAAO;CAClF;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAqBD,MAAM,WAAW,YAAoB,YAAY,mBAAmB,OAAO;AAE3E,SAAS,QAAQ,MAAkD;CACjE,IAAI,SAAS,KAAA,GAAW;EACtB,IAAI,OAAO,SAAS,YAAY,gBAAgB,KAAK,OAAO,OAAO,IAAI;EACvE,MAAM,QAAQ,mCAAmC;CACnD;CACA,OAAO,OAAO,aAAa,cAAc,KAAA,IAAY,SAAS;AAChE;AAEA,SAAS,YAAY,WAA6D;CAChF,MAAM,OAAgB,aAAa;CACnC,MAAM,SAAS,aAA0C,OAAO,aAAa,YAAY,uBAAuB,KAAK,QAAQ;CAC7H,IAAI,CAAC,MAAM,QAAQ,IAAI,KAAK,KAAK,WAAW,KAAK,CAAE,KAA4B,MAAM,KAAK,GACxF,MAAM,QAAQ,oFAAkF;CAElG,OAAO,IAAI,IAAK,KAA2B,KAAK,aAAa,SAAS,YAAY,CAAC,CAAC;AACtF;AAEA,SAAS,QAAQ,QAA+D;CAC9E,MAAM,OAAO,UAAU;CACvB,IAAI,CAAC,MAAM,QAAQ,IAAI,KAAK,CAAC,KAAK,OAAO,UAAU,OAAO,UAAU,YAAY,iBAAiB,MAAM,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O,UAAU,YAAY,EAAE,iBAAiB,MAAM,MAAM,QAAQ,mCAAmC;EAC3G,MAAM,MAAM,OAAO,KAAK,CAAC,CAAC,KAAK;EAC/B,IAAI,QAAQ,IAAI,MAAM,QAAQ,2BAA2B;EACzD,IAAI;EACJ,IAAI;GACF,MAAM,IAAI,IAAI,KAAK,IAAI;EACzB,SAAS,OAAO;GACd,MAAM,YAAY,mBAAmB,qBAAqB,KAAK,UAAU,IAAI,MAAM,GAAG,GAAG,CAAC,EAAE,IAAI,KAAK;EACvG;EACA,IAAI,CAAC,UAAU,IAAI,IAAI,QAAQ,GAC7B,MAAM,QAAQ,0BAA0B,IAAI,SAAS,8BAA8B,CAAC,GAAG,SAAS,CAAC,CAAC,KAAK,IAAI,EAAE,GAAG;EAGlH,IAAI,WAAW;EACf,IAAI,WAAW;EACf,QAAQ,GAAG;EACX,OAAO,IAAI;CACb;AACF;;;;;;AAOA,SAAgB,eAAe,OAAqB,UAA0B,CAAC,GAAW;CACxF,OAAO,gBAAgB,OAAO,CAAC,CAAC,KAAK;AACvC;;;;;;;;AASA,SAAgB,aAAa,KAAmB,UAA4D,CAAC,GAAW;CACtH,MAAM,EAAE,QAAQ,MAAM,GAAG,SAAS;CAClC,OAAO,eAAe,KAAK;EAAE,GAAG;EAAM,OAAO;GAAE,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO;GAAI,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,KAAK;EAAG;CAAE,CAAC;AACzI"}
@@ -0,0 +1,164 @@
1
+
2
+ const require_errors = require("./errors-BwOF6T_M.cjs");
3
+ //#region src/link/url.ts
4
+ /** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */
5
+ const DEFAULT_LINK_PROTOCOLS = /* @__PURE__ */ Object.freeze([
6
+ "https:",
7
+ "http:",
8
+ "mailto:",
9
+ "tel:"
10
+ ]);
11
+ /**
12
+ * Query parameters that only track where a click came from: the defaults of
13
+ * {@link cleanLinkUrl}. `utm_` matches every parameter starting with it.
14
+ */
15
+ const TRACKING_PARAMETERS = /* @__PURE__ */ Object.freeze([
16
+ "utm_",
17
+ "fbclid",
18
+ "gclid",
19
+ "gclsrc",
20
+ "dclid",
21
+ "gbraid",
22
+ "wbraid",
23
+ "msclkid",
24
+ "yclid",
25
+ "twclid",
26
+ "ttclid",
27
+ "li_fat_id",
28
+ "igshid",
29
+ "igsh",
30
+ "mc_cid",
31
+ "mc_eid",
32
+ "_hsenc",
33
+ "_hsmi",
34
+ "mkt_tok",
35
+ "oly_anon_id",
36
+ "oly_enc_id",
37
+ "vero_id",
38
+ "wickedid",
39
+ "_gl"
40
+ ]);
41
+ const invalid = (message) => require_errors.copyFailure("invalid-payload", message);
42
+ function baseUrl(base) {
43
+ if (base !== void 0) {
44
+ if (typeof base === "string" || base instanceof URL) return String(base);
45
+ throw invalid("`base` must be a string or a URL.");
46
+ }
47
+ return typeof location === "undefined" ? void 0 : location.href;
48
+ }
49
+ function protocolSet(protocols) {
50
+ const list = protocols ?? DEFAULT_LINK_PROTOCOLS;
51
+ const valid = (protocol) => typeof protocol === "string" && /^[a-z][a-z\d+.-]*:$/i.test(protocol);
52
+ if (!Array.isArray(list) || list.length === 0 || !list.every(valid)) throw invalid("`protocols` must be a non-empty list of schemes with their colon, like \"https:\".");
53
+ return new Set(list.map((protocol) => protocol.toLowerCase()));
54
+ }
55
+ function matcher(params) {
56
+ const list = params ?? TRACKING_PARAMETERS;
57
+ if (!Array.isArray(list) || !list.every((param) => typeof param === "string" || param instanceof RegExp)) throw invalid("`clean.params` must be a list of strings and regular expressions.");
58
+ return (name) => {
59
+ const lower = name.toLowerCase();
60
+ return list.some((param) => {
61
+ if (typeof param !== "string") return new RegExp(param.source, param.flags.replace(/[gy]/g, "")).test(name);
62
+ const wanted = param.toLowerCase();
63
+ return wanted.endsWith("_") ? lower.startsWith(wanted) : lower === wanted;
64
+ });
65
+ };
66
+ }
67
+ /** The cleaning step `clean` asks for, or `null`. Throws for an invalid option. */
68
+ function cleaner(option) {
69
+ const cleaning = option ?? false;
70
+ if (cleaning === false) return null;
71
+ if (cleaning !== true && (typeof cleaning !== "object" || cleaning === null)) throw invalid("`clean` must be a boolean or an options object.");
72
+ const settings = cleaning === true ? {} : cleaning;
73
+ const tracking = matcher(settings.params);
74
+ const keep = settings.keep ?? [];
75
+ if (!Array.isArray(keep) || !keep.every((name) => typeof name === "string")) throw invalid("`clean.keep` must be a list of strings.");
76
+ const kept = new Set(keep.map((name) => name.toLowerCase()));
77
+ return (url) => {
78
+ for (const name of [...new Set(url.searchParams.keys())]) if (tracking(name) && !kept.has(name.toLowerCase())) url.searchParams.delete(name);
79
+ };
80
+ }
81
+ /**
82
+ * Validates `options` once (throwing a typed `invalid-payload` error for invalid
83
+ * ones) and returns a resolver that throws only for invalid links.
84
+ * @internal
85
+ */
86
+ function linkUrlResolver(options = {}) {
87
+ const protocols = protocolSet(options.protocols);
88
+ const base = baseUrl(options.base);
89
+ const clean = cleaner(options.clean);
90
+ return (input) => {
91
+ if (typeof input !== "string" && !(input instanceof URL)) throw invalid("A link must be a string or a URL.");
92
+ const raw = String(input).trim();
93
+ if (raw === "") throw invalid("A link must not be empty.");
94
+ let url;
95
+ try {
96
+ url = new URL(raw, base);
97
+ } catch (cause) {
98
+ throw require_errors.copyFailure("invalid-payload", `Not a valid link: ${JSON.stringify(raw.slice(0, 200))}.`, cause);
99
+ }
100
+ if (!protocols.has(url.protocol)) throw invalid(`Links with the scheme "${url.protocol}" are not allowed (allowed: ${[...protocols].join(", ")}).`);
101
+ url.username = "";
102
+ url.password = "";
103
+ clean?.(url);
104
+ return url.href;
105
+ };
106
+ }
107
+ /**
108
+ * The link as an absolute, safe URL string, or a typed `invalid-payload` error:
109
+ * relative links are resolved, the scheme must be allowed, user names and
110
+ * passwords are always removed, and tracking parameters optionally.
111
+ */
112
+ function resolveLinkUrl(input, options = {}) {
113
+ return linkUrlResolver(options)(input);
114
+ }
115
+ /**
116
+ * Removes tracking parameters (`utm_*`, `fbclid`, `gclid`, ...) from a link, keeping
117
+ * everything else, including the fragment. Also validates it like every link here.
118
+ *
119
+ * @example
120
+ * cleanLinkUrl('https://shop.example/p/42?utm_source=news&color=red'); // 'https://shop.example/p/42?color=red'
121
+ */
122
+ function cleanLinkUrl(url, options = {}) {
123
+ const { params, keep, ...rest } = options;
124
+ return resolveLinkUrl(url, {
125
+ ...rest,
126
+ clean: {
127
+ ...params === void 0 ? {} : { params },
128
+ ...keep === void 0 ? {} : { keep }
129
+ }
130
+ });
131
+ }
132
+ //#endregion
133
+ Object.defineProperty(exports, "DEFAULT_LINK_PROTOCOLS", {
134
+ enumerable: true,
135
+ get: function() {
136
+ return DEFAULT_LINK_PROTOCOLS;
137
+ }
138
+ });
139
+ Object.defineProperty(exports, "TRACKING_PARAMETERS", {
140
+ enumerable: true,
141
+ get: function() {
142
+ return TRACKING_PARAMETERS;
143
+ }
144
+ });
145
+ Object.defineProperty(exports, "cleanLinkUrl", {
146
+ enumerable: true,
147
+ get: function() {
148
+ return cleanLinkUrl;
149
+ }
150
+ });
151
+ Object.defineProperty(exports, "linkUrlResolver", {
152
+ enumerable: true,
153
+ get: function() {
154
+ return linkUrlResolver;
155
+ }
156
+ });
157
+ Object.defineProperty(exports, "resolveLinkUrl", {
158
+ enumerable: true,
159
+ get: function() {
160
+ return resolveLinkUrl;
161
+ }
162
+ });
163
+
164
+ //# sourceMappingURL=url-D4PGsRm8.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url-D4PGsRm8.cjs","names":["copyFailure"],"sources":["../../src/link/url.ts"],"sourcesContent":["import { copyFailure } from '../core/errors';\n\n/** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */\nexport const DEFAULT_LINK_PROTOCOLS: readonly string[] = /* @__PURE__ */ Object.freeze(['https:', 'http:', 'mailto:', 'tel:']);\n\n/**\n * Query parameters that only track where a click came from: the defaults of\n * {@link cleanLinkUrl}. `utm_` matches every parameter starting with it.\n */\nexport const TRACKING_PARAMETERS: readonly string[] = /* @__PURE__ */ Object.freeze([\n 'utm_',\n 'fbclid',\n 'gclid',\n 'gclsrc',\n 'dclid',\n 'gbraid',\n 'wbraid',\n 'msclkid',\n 'yclid',\n 'twclid',\n 'ttclid',\n 'li_fat_id',\n 'igshid',\n 'igsh',\n 'mc_cid',\n 'mc_eid',\n '_hsenc',\n '_hsmi',\n 'mkt_tok',\n 'oly_anon_id',\n 'oly_enc_id',\n 'vero_id',\n 'wickedid',\n '_gl',\n]);\n\nexport interface CleanLinkOptions {\n /**\n * Parameters to remove: exact names, names ending in `_` (a prefix, like\n * `utm_`), or regular expressions tested against the name. Default {@link TRACKING_PARAMETERS}.\n */\n readonly params?: readonly (string | RegExp)[];\n /** Parameters never removed, even when `params` matches them. */\n readonly keep?: readonly string[];\n}\n\nexport interface LinkUrlOptions {\n /** Resolves relative links. Default: the page's address in a browser; required elsewhere for relative links. */\n readonly base?: string | URL;\n /** Allowed schemes, with the colon. Default {@link DEFAULT_LINK_PROTOCOLS}. */\n readonly protocols?: readonly string[];\n /** Remove tracking parameters: `true` for {@link TRACKING_PARAMETERS}, or your own list. Default `false`. */\n readonly clean?: boolean | CleanLinkOptions;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nfunction baseUrl(base: LinkUrlOptions['base']): string | undefined {\n if (base !== undefined) {\n if (typeof base === 'string' || base instanceof URL) return String(base);\n throw invalid('`base` must be a string or a URL.');\n }\n return typeof location === 'undefined' ? undefined : location.href;\n}\n\nfunction protocolSet(protocols: LinkUrlOptions['protocols']): ReadonlySet<string> {\n const list: unknown = protocols ?? DEFAULT_LINK_PROTOCOLS;\n const valid = (protocol: unknown): protocol is string => typeof protocol === 'string' && /^[a-z][a-z\\d+.-]*:$/i.test(protocol);\n if (!Array.isArray(list) || list.length === 0 || !(list as readonly unknown[]).every(valid)) {\n throw invalid('`protocols` must be a non-empty list of schemes with their colon, like \"https:\".');\n }\n return new Set((list as readonly string[]).map((protocol) => protocol.toLowerCase()));\n}\n\nfunction matcher(params: CleanLinkOptions['params']): (name: string) => boolean {\n const list = params ?? TRACKING_PARAMETERS;\n if (!Array.isArray(list) || !list.every((param) => typeof param === 'string' || param instanceof RegExp)) {\n throw invalid('`clean.params` must be a list of strings and regular expressions.');\n }\n return (name) => {\n const lower = name.toLowerCase();\n return list.some((param) => {\n if (typeof param !== 'string') return new RegExp(param.source, param.flags.replace(/[gy]/g, '')).test(name);\n const wanted = param.toLowerCase();\n return wanted.endsWith('_') ? lower.startsWith(wanted) : lower === wanted;\n });\n };\n}\n\n/** The cleaning step `clean` asks for, or `null`. Throws for an invalid option. */\nfunction cleaner(option: LinkUrlOptions['clean']): ((url: URL) => void) | null {\n const cleaning: unknown = option ?? false; // Plain-JS callers can pass anything.\n if (cleaning === false) return null;\n if (cleaning !== true && (typeof cleaning !== 'object' || cleaning === null)) throw invalid('`clean` must be a boolean or an options object.');\n const settings: CleanLinkOptions = cleaning === true ? {} : cleaning;\n const tracking = matcher(settings.params);\n const keep = settings.keep ?? [];\n if (!Array.isArray(keep) || !keep.every((name: unknown) => typeof name === 'string')) throw invalid('`clean.keep` must be a list of strings.');\n const kept = new Set(keep.map((name) => name.toLowerCase()));\n return (url) => {\n for (const name of [...new Set(url.searchParams.keys())]) {\n if (tracking(name) && !kept.has(name.toLowerCase())) url.searchParams.delete(name);\n }\n };\n}\n\n/**\n * Validates `options` once (throwing a typed `invalid-payload` error for invalid\n * ones) and returns a resolver that throws only for invalid links.\n * @internal\n */\nexport function linkUrlResolver(options: LinkUrlOptions = {}): (input: string | URL) => string {\n const protocols = protocolSet(options.protocols);\n const base = baseUrl(options.base);\n const clean = cleaner(options.clean);\n return (input) => {\n if (typeof input !== 'string' && !(input instanceof URL)) throw invalid('A link must be a string or a URL.');\n const raw = String(input).trim();\n if (raw === '') throw invalid('A link must not be empty.');\n let url: URL;\n try {\n url = new URL(raw, base);\n } catch (cause) {\n throw copyFailure('invalid-payload', `Not a valid link: ${JSON.stringify(raw.slice(0, 200))}.`, cause);\n }\n if (!protocols.has(url.protocol)) {\n throw invalid(`Links with the scheme \"${url.protocol}\" are not allowed (allowed: ${[...protocols].join(', ')}).`);\n }\n // Never copy or paste credentials embedded in a link.\n url.username = '';\n url.password = '';\n clean?.(url);\n return url.href;\n };\n}\n\n/**\n * The link as an absolute, safe URL string, or a typed `invalid-payload` error:\n * relative links are resolved, the scheme must be allowed, user names and\n * passwords are always removed, and tracking parameters optionally.\n */\nexport function resolveLinkUrl(input: string | URL, options: LinkUrlOptions = {}): string {\n return linkUrlResolver(options)(input);\n}\n\n/**\n * Removes tracking parameters (`utm_*`, `fbclid`, `gclid`, ...) from a link, keeping\n * everything else, including the fragment. Also validates it like every link here.\n *\n * @example\n * cleanLinkUrl('https://shop.example/p/42?utm_source=news&color=red'); // 'https://shop.example/p/42?color=red'\n */\nexport function cleanLinkUrl(url: string | URL, options: CleanLinkOptions & Omit<LinkUrlOptions, 'clean'> = {}): string {\n const { params, keep, ...rest } = options;\n return resolveLinkUrl(url, { ...rest, clean: { ...(params === undefined ? {} : { params }), ...(keep === undefined ? {} : { keep }) } });\n}\n"],"mappings":";;;;AAGA,MAAa,yBAA4D,uBAAO,OAAO;CAAC;CAAU;CAAS;CAAW;AAAM,CAAC;;;;;AAM7H,MAAa,sBAAyD,uBAAO,OAAO;CAClF;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAqBD,MAAM,WAAW,YAAoBA,eAAAA,YAAY,mBAAmB,OAAO;AAE3E,SAAS,QAAQ,MAAkD;CACjE,IAAI,SAAS,KAAA,GAAW;EACtB,IAAI,OAAO,SAAS,YAAY,gBAAgB,KAAK,OAAO,OAAO,IAAI;EACvE,MAAM,QAAQ,mCAAmC;CACnD;CACA,OAAO,OAAO,aAAa,cAAc,KAAA,IAAY,SAAS;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OAAO,eAAe,KAAK;EAAE,GAAG;EAAM,OAAO;GAAE,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO;GAAI,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,KAAK;EAAG;CAAE,CAAC;AACzI"}
@@ -0,0 +1,43 @@
1
+
2
+ //#region src/link/url.d.ts
3
+ /** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */
4
+ declare const DEFAULT_LINK_PROTOCOLS: readonly string[];
5
+ /**
6
+ * Query parameters that only track where a click came from: the defaults of
7
+ * {@link cleanLinkUrl}. `utm_` matches every parameter starting with it.
8
+ */
9
+ declare const TRACKING_PARAMETERS: readonly string[];
10
+ interface CleanLinkOptions {
11
+ /**
12
+ * Parameters to remove: exact names, names ending in `_` (a prefix, like
13
+ * `utm_`), or regular expressions tested against the name. Default {@link TRACKING_PARAMETERS}.
14
+ */
15
+ readonly params?: readonly (string | RegExp)[];
16
+ /** Parameters never removed, even when `params` matches them. */
17
+ readonly keep?: readonly string[];
18
+ }
19
+ interface LinkUrlOptions {
20
+ /** Resolves relative links. Default: the page's address in a browser; required elsewhere for relative links. */
21
+ readonly base?: string | URL;
22
+ /** Allowed schemes, with the colon. Default {@link DEFAULT_LINK_PROTOCOLS}. */
23
+ readonly protocols?: readonly string[];
24
+ /** Remove tracking parameters: `true` for {@link TRACKING_PARAMETERS}, or your own list. Default `false`. */
25
+ readonly clean?: boolean | CleanLinkOptions;
26
+ }
27
+ /**
28
+ * The link as an absolute, safe URL string, or a typed `invalid-payload` error:
29
+ * relative links are resolved, the scheme must be allowed, user names and
30
+ * passwords are always removed, and tracking parameters optionally.
31
+ */
32
+ declare function resolveLinkUrl(input: string | URL, options?: LinkUrlOptions): string;
33
+ /**
34
+ * Removes tracking parameters (`utm_*`, `fbclid`, `gclid`, ...) from a link, keeping
35
+ * everything else, including the fragment. Also validates it like every link here.
36
+ *
37
+ * @example
38
+ * cleanLinkUrl('https://shop.example/p/42?utm_source=news&color=red'); // 'https://shop.example/p/42?color=red'
39
+ */
40
+ declare function cleanLinkUrl(url: string | URL, options?: CleanLinkOptions & Omit<LinkUrlOptions, 'clean'>): string;
41
+ //#endregion
42
+ export { cleanLinkUrl as a, TRACKING_PARAMETERS as i, DEFAULT_LINK_PROTOCOLS as n, resolveLinkUrl as o, LinkUrlOptions as r, CleanLinkOptions as t };
43
+ //# sourceMappingURL=url-DWdElCT3.d.cts.map
@@ -0,0 +1,43 @@
1
+
2
+ //#region src/link/url.d.ts
3
+ /** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */
4
+ declare const DEFAULT_LINK_PROTOCOLS: readonly string[];
5
+ /**
6
+ * Query parameters that only track where a click came from: the defaults of
7
+ * {@link cleanLinkUrl}. `utm_` matches every parameter starting with it.
8
+ */
9
+ declare const TRACKING_PARAMETERS: readonly string[];
10
+ interface CleanLinkOptions {
11
+ /**
12
+ * Parameters to remove: exact names, names ending in `_` (a prefix, like
13
+ * `utm_`), or regular expressions tested against the name. Default {@link TRACKING_PARAMETERS}.
14
+ */
15
+ readonly params?: readonly (string | RegExp)[];
16
+ /** Parameters never removed, even when `params` matches them. */
17
+ readonly keep?: readonly string[];
18
+ }
19
+ interface LinkUrlOptions {
20
+ /** Resolves relative links. Default: the page's address in a browser; required elsewhere for relative links. */
21
+ readonly base?: string | URL;
22
+ /** Allowed schemes, with the colon. Default {@link DEFAULT_LINK_PROTOCOLS}. */
23
+ readonly protocols?: readonly string[];
24
+ /** Remove tracking parameters: `true` for {@link TRACKING_PARAMETERS}, or your own list. Default `false`. */
25
+ readonly clean?: boolean | CleanLinkOptions;
26
+ }
27
+ /**
28
+ * The link as an absolute, safe URL string, or a typed `invalid-payload` error:
29
+ * relative links are resolved, the scheme must be allowed, user names and
30
+ * passwords are always removed, and tracking parameters optionally.
31
+ */
32
+ declare function resolveLinkUrl(input: string | URL, options?: LinkUrlOptions): string;
33
+ /**
34
+ * Removes tracking parameters (`utm_*`, `fbclid`, `gclid`, ...) from a link, keeping
35
+ * everything else, including the fragment. Also validates it like every link here.
36
+ *
37
+ * @example
38
+ * cleanLinkUrl('https://shop.example/p/42?utm_source=news&color=red'); // 'https://shop.example/p/42?color=red'
39
+ */
40
+ declare function cleanLinkUrl(url: string | URL, options?: CleanLinkOptions & Omit<LinkUrlOptions, 'clean'>): string;
41
+ //#endregion
42
+ export { cleanLinkUrl as a, TRACKING_PARAMETERS as i, DEFAULT_LINK_PROTOCOLS as n, resolveLinkUrl as o, LinkUrlOptions as r, CleanLinkOptions as t };
43
+ //# sourceMappingURL=url-DWdElCT3.d.ts.map
@@ -0,0 +1,57 @@
1
+
2
+ //#region src/markdown/url.ts
3
+ /**
4
+ * URL safety for pasted links and images. Only absolute URLs with an allowed
5
+ * scheme survive; everything else (`javascript:`, `data:`, `vbscript:`,
6
+ * relative links without a base, malformed URLs) is dropped and the visible
7
+ * text is kept. Parsing uses the WHATWG URL parser, the same one the browser
8
+ * uses when the link is clicked, so tricks like `java\tscript:` are seen as
9
+ * `javascript:`.
10
+ */
11
+ const DEFAULT_LINK_PROTOCOLS = [
12
+ "http:",
13
+ "https:",
14
+ "mailto:"
15
+ ];
16
+ const DEFAULT_IMAGE_PROTOCOLS = ["https:", "http:"];
17
+ function parse(raw, base) {
18
+ try {
19
+ return new URL(raw.trim(), base);
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+ /**
25
+ * Click-tracking redirects that pasted links often carry: Google (Docs,
26
+ * Search, Gmail) and Outlook Safe Links. Unwrapped only to an http(s) target.
27
+ */
28
+ function unwrapRedirect(url) {
29
+ const host = url.hostname.toLowerCase();
30
+ const param = /(^|\.)google\.[a-z.]+$/.test(host) && url.pathname === "/url" ? url.searchParams.get("q") ?? url.searchParams.get("url") : host.endsWith(".safelinks.protection.outlook.com") ? url.searchParams.get("url") : null;
31
+ if (param === null) return url;
32
+ const target = parse(param, void 0);
33
+ return target !== null && (target.protocol === "https:" || target.protocol === "http:") ? target : url;
34
+ }
35
+ /** The normalised URL, or `null` when it is not absolute or its scheme is not allowed. */
36
+ function safeUrl(raw, protocols, base) {
37
+ const parsed = parse(raw, base);
38
+ if (parsed === null) return null;
39
+ const url = unwrapRedirect(parsed);
40
+ return protocols.includes(url.protocol) ? url.href : null;
41
+ }
42
+ /** `href` comes from the URL serialiser, which already percent-encodes every non-ASCII character. */
43
+ const percent = (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`;
44
+ /**
45
+ * A Markdown link destination. ASCII whitespace, `<`, `>` and controls are
46
+ * percent-encoded (opaque URLs such as `mailto:` keep them otherwise),
47
+ * backslashes too so they can't act as escapes, and parentheses are kept
48
+ * exact by using the `<…>` form.
49
+ */
50
+ function linkDestination(href) {
51
+ const encoded = href.replace(/[ <>\\\u0000-\u001f\u007f]/g, percent);
52
+ return /[()]/.test(encoded) ? `<${encoded}>` : encoded;
53
+ }
54
+ //#endregion
55
+ export { unwrapRedirect as a, safeUrl as i, DEFAULT_LINK_PROTOCOLS as n, linkDestination as r, DEFAULT_IMAGE_PROTOCOLS as t };
56
+
57
+ //# sourceMappingURL=url-vJaFPbNL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url-vJaFPbNL.js","names":[],"sources":["../../src/markdown/url.ts"],"sourcesContent":["/**\n * URL safety for pasted links and images. Only absolute URLs with an allowed\n * scheme survive; everything else (`javascript:`, `data:`, `vbscript:`,\n * relative links without a base, malformed URLs) is dropped and the visible\n * text is kept. Parsing uses the WHATWG URL parser, the same one the browser\n * uses when the link is clicked, so tricks like `java\\tscript:` are seen as\n * `javascript:`.\n */\n\nexport const DEFAULT_LINK_PROTOCOLS: readonly string[] = ['http:', 'https:', 'mailto:'];\nexport const DEFAULT_IMAGE_PROTOCOLS: readonly string[] = ['https:', 'http:'];\n\nfunction parse(raw: string, base: string | undefined): URL | null {\n try {\n return new URL(raw.trim(), base);\n } catch {\n return null;\n }\n}\n\n/**\n * Click-tracking redirects that pasted links often carry: Google (Docs,\n * Search, Gmail) and Outlook Safe Links. Unwrapped only to an http(s) target.\n */\nexport function unwrapRedirect(url: URL): URL {\n const host = url.hostname.toLowerCase();\n const param =\n /(^|\\.)google\\.[a-z.]+$/.test(host) && url.pathname === '/url'\n ? (url.searchParams.get('q') ?? url.searchParams.get('url'))\n : host.endsWith('.safelinks.protection.outlook.com')\n ? url.searchParams.get('url')\n : null;\n if (param === null) return url;\n const target = parse(param, undefined);\n return target !== null && (target.protocol === 'https:' || target.protocol === 'http:') ? target : url;\n}\n\n/** The normalised URL, or `null` when it is not absolute or its scheme is not allowed. */\nexport function safeUrl(raw: string, protocols: readonly string[], base: string | undefined): string | null {\n const parsed = parse(raw, base);\n if (parsed === null) return null;\n const url = unwrapRedirect(parsed);\n return protocols.includes(url.protocol) ? url.href : null;\n}\n\n/** `href` comes from the URL serialiser, which already percent-encodes every non-ASCII character. */\nconst percent = (char: string): string => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`;\n\n/**\n * A Markdown link destination. ASCII whitespace, `<`, `>` and controls are\n * percent-encoded (opaque URLs such as `mailto:` keep them otherwise),\n * backslashes too so they can't act as escapes, and parentheses are kept\n * exact by using the `<…>` form.\n */\nexport function linkDestination(href: string): string {\n // eslint-disable-next-line no-control-regex -- control characters are exactly what must be encoded\n const encoded = href.replace(/[ <>\\\\\\u0000-\\u001f\\u007f]/g, percent);\n return /[()]/.test(encoded) ? `<${encoded}>` : encoded;\n}\n"],"mappings":";;;;;;;;;;AASA,MAAa,yBAA4C;CAAC;CAAS;CAAU;AAAS;AACtF,MAAa,0BAA6C,CAAC,UAAU,OAAO;AAE5E,SAAS,MAAM,KAAa,MAAsC;CAChE,IAAI;EACF,OAAO,IAAI,IAAI,IAAI,KAAK,GAAG,IAAI;CACjC,QAAQ;EACN,OAAO;CACT;AACF;;;;;AAMA,SAAgB,eAAe,KAAe;CAC5C,MAAM,OAAO,IAAI,SAAS,YAAY;CACtC,MAAM,QACJ,yBAAyB,KAAK,IAAI,KAAK,IAAI,aAAa,SACnD,IAAI,aAAa,IAAI,GAAG,KAAK,IAAI,aAAa,IAAI,KAAK,IACxD,KAAK,SAAS,mCAAmC,IAC/C,IAAI,aAAa,IAAI,KAAK,IAC1B;CACR,IAAI,UAAU,MAAM,OAAO;CAC3B,MAAM,SAAS,MAAM,OAAO,KAAA,CAAS;CACrC,OAAO,WAAW,SAAS,OAAO,aAAa,YAAY,OAAO,aAAa,WAAW,SAAS;AACrG;;AAGA,SAAgB,QAAQ,KAAa,WAA8B,MAAyC;CAC1G,MAAM,SAAS,MAAM,KAAK,IAAI;CAC9B,IAAI,WAAW,MAAM,OAAO;CAC5B,MAAM,MAAM,eAAe,MAAM;CACjC,OAAO,UAAU,SAAS,IAAI,QAAQ,IAAI,IAAI,OAAO;AACvD;;AAGA,MAAM,WAAW,SAAyB,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS,GAAG,GAAG;;;;;;;AAQ3G,SAAgB,gBAAgB,MAAsB;CAEpD,MAAM,UAAU,KAAK,QAAQ,+BAA+B,OAAO;CACnE,OAAO,OAAO,KAAK,OAAO,IAAI,IAAI,QAAQ,KAAK;AACjD"}