@capacms/sdk 1.0.0-next.13 → 1.0.0-next.15

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.
@@ -899,12 +899,19 @@ const DRAFT_LINK_ATTRS = { path: "/", httpOnly: true, secure: true, sameSite: "l
899
899
  * when the link has already expired.
900
900
  */
901
901
  async function keepDraftLink(cookies, token, expiresAt, maxAge) {
902
- const left = Math.floor((Date.parse(expiresAt) - Date.now()) / 1000);
903
- if (!Number.isFinite(left) || left <= 0)
902
+ const age = linkAge(expiresAt, maxAge);
903
+ if (age === 0)
904
904
  return false;
905
- (await cookies()).set({ name: exports.DRAFT_LINK_COOKIE, value: token, ...DRAFT_LINK_ATTRS, maxAge: Math.min(left, maxAge) });
905
+ (await cookies()).set({ name: exports.DRAFT_LINK_COOKIE, value: token, ...DRAFT_LINK_ATTRS, maxAge: age });
906
906
  return true;
907
907
  }
908
+ /** Seconds a cookie for a link may last: to the link's expiry or `maxAge`, whichever is first. 0 once it has expired. */
909
+ function linkAge(expiresAt, maxAge) {
910
+ const left = Math.floor((Date.parse(expiresAt) - Date.now()) / 1000);
911
+ if (!Number.isFinite(left) || left <= 0)
912
+ return 0;
913
+ return Math.min(left, maxAge);
914
+ }
908
915
  /**
909
916
  * Delete the draft link's cookie `createPreviewRoute` kept, when the request
910
917
  * carries one. `createPreviewRoute` calls it on any other answer and
@@ -943,6 +950,11 @@ function routeRedirect(location, headers) {
943
950
  * Given `cookies`, the draft cookie is re-set by `frameDraftCookie`: one hour,
944
951
  * and sent inside the editor's frame.
945
952
  *
953
+ * A RELEASE PREVIEW keeps its token in `RELEASE_COOKIE` for the visit's reads.
954
+ * It and the draft cookie end when the link expires, or after `maxAge`
955
+ * seconds, whichever is first; a link already expired lands on
956
+ * `?preview=expired`.
957
+ *
946
958
  * A DRAFT LINK (Share draft in Capa) opens only given `cookies`, and never
947
959
  * turns draft mode on. The route tells Capa it narrows (`preview()` with
948
960
  * `draftLinks`), keeps the token in `DRAFT_LINK_COOKIE` until the link
@@ -986,7 +998,13 @@ function createPreviewRoute(input) {
986
998
  // Either sign is enough, so a draft link never reaches `enable()`.
987
999
  const isLink = claim !== null && (claim.draftLink === true || token.startsWith(DRAFT_LINK_PREFIX));
988
1000
  const kept = isLink && input.cookies ? await keepDraftLink(input.cookies, token, claim.expiresAt, maxAge) : false;
989
- if (!claim || (isLink && !kept)) {
1001
+ // A release preview lasts no longer than its link, the draft cookie
1002
+ // included: past it, draft mode without the release would show every
1003
+ // draft. 0 when the link has already expired. A link whose releases
1004
+ // are all gone is still a release link: its cookie stays, so Capa
1005
+ // serves the live site rather than every draft.
1006
+ const releaseAge = claim && !isLink && claim.kind === "release" ? linkAge(claim.expiresAt, maxAge) : null;
1007
+ if (!claim || (isLink && !kept) || releaseAge === 0) {
990
1008
  draft.disable?.();
991
1009
  if (input.cookies) {
992
1010
  await clearDraftCookie(input.cookies);
@@ -1005,12 +1023,13 @@ function createPreviewRoute(input) {
1005
1023
  }
1006
1024
  draft.enable?.();
1007
1025
  if (input.cookies) {
1008
- await frameDraftCookie(input.cookies, { maxAge });
1026
+ await frameDraftCookie(input.cookies, { maxAge: releaseAge ?? maxAge });
1009
1027
  await clearDraftLinkCookie(input.cookies);
1010
- // A release preview keeps its token for the reads (`Capa-Release`); any
1011
- // other preview clears one left from before, so it shows every draft.
1012
- if (claim.kind === "release" && (claim.releases?.length ?? 0) > 0) {
1013
- (await input.cookies()).set({ name: exports.RELEASE_COOKIE, value: token, ...FRAMED, maxAge });
1028
+ // A release preview keeps its token for the reads (`Capa-Release`)
1029
+ // until the link expires; any other preview clears one left from
1030
+ // before, so it shows every draft.
1031
+ if (releaseAge !== null) {
1032
+ (await input.cookies()).set({ name: exports.RELEASE_COOKIE, value: token, ...FRAMED, maxAge: releaseAge });
1014
1033
  }
1015
1034
  else {
1016
1035
  await clearReleaseCookie(input.cookies);
@@ -92,6 +92,16 @@ function timeoutOf(ms) {
92
92
  const noop = () => { };
93
93
  /** A scroller's overflow that lets a reader scroll it (not `hidden` or `clip`). */
94
94
  const SCROLLABLE = /^(auto|scroll|overlay)$/;
95
+ /**
96
+ * Smooth, or "instant" for a viewer who asked for less motion. A site's
97
+ * `prefers-reduced-motion` CSS does not reach a script that asks for
98
+ * "smooth" by name, so the overlay asks the browser itself (`motion` in
99
+ * `SITE_FEATURES` tells the admin it does).
100
+ */
101
+ function scrollBehavior() {
102
+ const reduce = typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
103
+ return reduce ? "instant" : "smooth";
104
+ }
95
105
  /**
96
106
  * Brings the highlighted element to the middle of the page, scrolling only
97
107
  * this page: its own scrollers (a drawer, a horizontal rail) and its window.
@@ -110,6 +120,7 @@ const SCROLLABLE = /^(auto|scroll|overlay)$/;
110
120
  function revealOnPage(el) {
111
121
  if (typeof el.getClientRects === "function" && el.getClientRects().length === 0)
112
122
  return;
123
+ const behavior = scrollBehavior();
113
124
  const start = el.getBoundingClientRect();
114
125
  let top = start.top;
115
126
  let left = start.left;
@@ -150,13 +161,13 @@ function revealOnPage(el) {
150
161
  // Where the element will be once this scroller has moved, for the next one out.
151
162
  top -= toTop - box.scrollTop;
152
163
  left -= toLeft - box.scrollLeft;
153
- box.scrollTo({ top: toTop, left: toLeft, behavior: "smooth" });
164
+ box.scrollTo({ top: toTop, left: toLeft, behavior });
154
165
  }
155
166
  const dy = move(top, height, 0, window.innerHeight, true);
156
167
  const dx = move(left, width, 0, window.innerWidth, false);
157
168
  if (Math.abs(dy) < 1 && Math.abs(dx) < 1)
158
169
  return;
159
- window.scrollTo({ top: window.scrollY + dy, left: (window.scrollX ?? 0) + dx, behavior: "smooth" });
170
+ window.scrollTo({ top: window.scrollY + dy, left: (window.scrollX ?? 0) + dx, behavior });
160
171
  }
161
172
  let running = null;
162
173
  /**
@@ -65,6 +65,9 @@ export declare const SITE_SOURCE = "capa";
65
65
  * What this overlay can do beyond v1, listed in its `ready`. `release`: this
66
66
  * SDK sends a release preview's token on its reads (`Capa-Release`), so the
67
67
  * admin can tell a site that shows a release from one that shows every draft.
68
+ * `motion`: a highlight scrolls the page at once, not smoothly, for a viewer
69
+ * who asked for less motion (`prefers-reduced-motion: reduce`), so the admin
70
+ * can take the page to an entry without animating it for them.
68
71
  */
69
72
  export declare const SITE_FEATURES: readonly string[];
70
73
  /** One field of a `patch`: the text being typed, and the saved value the page was rendered from. */
@@ -81,8 +81,11 @@ exports.SITE_SOURCE = "capa";
81
81
  * What this overlay can do beyond v1, listed in its `ready`. `release`: this
82
82
  * SDK sends a release preview's token on its reads (`Capa-Release`), so the
83
83
  * admin can tell a site that shows a release from one that shows every draft.
84
+ * `motion`: a highlight scrolls the page at once, not smoothly, for a viewer
85
+ * who asked for less motion (`prefers-reduced-motion: reduce`), so the admin
86
+ * can take the page to an entry without animating it for them.
84
87
  */
85
- exports.SITE_FEATURES = ["patch", "fields", "release"];
88
+ exports.SITE_FEATURES = ["patch", "fields", "release", "motion"];
86
89
  /** A `patch` past these is refused whole: no form has that many text fields, or that much text in one. */
87
90
  exports.PATCH_MAX_FIELDS = 500;
88
91
  exports.PATCH_MAX_LENGTH = 100_000;
@@ -0,0 +1,70 @@
1
+ /** What `sanitizeHtml` keeps beside its defaults. Each list adds to them; none replaces them. */
2
+ export interface SanitizeHtmlOptions {
3
+ /**
4
+ * Elements to keep beside the defaults, such as `"iframe"` or `"video"`.
5
+ * An iframe keeps `src` (http or https only), `width`, `height`, `title`,
6
+ * `allowfullscreen`, `frameborder`, `loading` and `referrerpolicy`.
7
+ * `"script"`, `"style"`, `"link"`, `"base"`, `"plaintext"`, `"object"`,
8
+ * `"embed"`, `"applet"`, `"frame"`, `"frameset"` and `"portal"` are
9
+ * refused; inline styles are an attribute (`allowedAttributes: { "*":
10
+ * ["style"] }`). Each element added weakens the defaults: `"meta"` can
11
+ * refresh to another page, and `"form"` can post to another site.
12
+ */
13
+ allowedTags?: readonly string[];
14
+ /**
15
+ * Attributes to keep beside the defaults, by element, with `"*"` for every
16
+ * element: `{ "*": ["style"], img: ["srcset", "sizes"] }`. A name may end
17
+ * in `*` (`"data-*"`). Listing `class` keeps every class on that element.
18
+ * A kept `href`, `src` or `srcset` is still checked against the schemes.
19
+ * An `on…` event handler and `srcdoc` are refused. `style` keeps any CSS
20
+ * as written, which can restyle or cover the rest of the page. An `id` or
21
+ * `name` is kept as `user-content-` and the value, and every link to `#x`
22
+ * becomes `#user-content-x`, so content cannot take an id the page relies
23
+ * on and a table of contents still works.
24
+ */
25
+ allowedAttributes?: Readonly<Record<string, readonly string[]>>;
26
+ /**
27
+ * URL schemes to accept in links beside `http`, `https`, `mailto` and
28
+ * `tel`, such as `"sms"`. Image sources stay `http` and `https`, and an
29
+ * iframe's `src` stays `http` or `https` whatever is listed. `"data"` is the
30
+ * one exception: it keeps an image whose `src` is a `data:` URL of a PNG,
31
+ * JPEG, GIF, WebP or AVIF, and nothing else (no SVG, no HTML, no `data:`
32
+ * link). `"javascript"` and `"vbscript"` are refused.
33
+ */
34
+ allowedSchemes?: readonly string[];
35
+ /**
36
+ * Keep iframes whose `src` is on one of these hosts, compared exactly
37
+ * (`"www.youtube.com"`, `"player.vimeo.com"`). Every other iframe, and one
38
+ * with a relative `src`, is dropped. Implies `"iframe"` in `allowedTags`.
39
+ */
40
+ allowedIframeHostnames?: readonly string[];
41
+ }
42
+ /** The elements kept by default: the blocks, lists, links, images, tables, code and inline formatting of rich text. */
43
+ export declare const DEFAULT_ALLOWED_TAGS: readonly string[];
44
+ /**
45
+ * The attributes kept by default, by element. Besides these, a `class` is
46
+ * kept for its `ql-` classes (the editor's alignment, indent, size and font)
47
+ * on any element, and its `language-` classes on `code` and `pre`.
48
+ */
49
+ export declare const DEFAULT_ALLOWED_ATTRIBUTES: Readonly<Record<string, readonly string[]>>;
50
+ /** The URL schemes a link may use by default. An image's `src` takes `http` and `https` only. A relative URL is always kept. */
51
+ export declare const DEFAULT_ALLOWED_SCHEMES: readonly string[];
52
+ /**
53
+ * An html field's value as HTML that is safe to render with the defaults:
54
+ * what the editor writes stays, and scripts, event handlers, `javascript:`
55
+ * links, styles, frames and anything else outside the allowlist go. Markup
56
+ * that is not closed is closed, so an unclosed `<em>` cannot run into the
57
+ * rest of the page. `null` and `undefined` (a field never filled) give `""`.
58
+ * Options extend the allowlist, and each one they add can weaken it, so add
59
+ * only what the content needs.
60
+ *
61
+ * Runs the same in a server component, in Node, on an edge runtime and in a
62
+ * browser. Needs `sanitize-html` 2.18.2 or later installed beside the SDK.
63
+ *
64
+ * ```tsx
65
+ * import { sanitizeHtml } from "@capacms/sdk/sanitize";
66
+ *
67
+ * <div dangerouslySetInnerHTML={{ __html: sanitizeHtml(entry.fields.body) }} />
68
+ * ```
69
+ */
70
+ export declare function sanitizeHtml(html: string | null | undefined, options?: SanitizeHtmlOptions): string;
@@ -0,0 +1,296 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_ALLOWED_SCHEMES = exports.DEFAULT_ALLOWED_ATTRIBUTES = exports.DEFAULT_ALLOWED_TAGS = void 0;
4
+ exports.sanitizeHtml = sanitizeHtml;
5
+ /** What a site without the peer installed is told. */
6
+ const MISSING_PEER_MESSAGE = "@capacms/sdk/sanitize needs the sanitize-html package: npm install sanitize-html";
7
+ /**
8
+ * sanitize-html's function. Only a failure to find sanitize-html itself gets
9
+ * the message: Node's "Cannot find module 'sanitize-html'", webpack's, and
10
+ * esbuild's "Dynamic require of "sanitize-html"". A module missing inside an
11
+ * installed sanitize-html, or any other error, is thrown as it was.
12
+ */
13
+ function loadSanitizeHtml() {
14
+ let loaded;
15
+ try {
16
+ loaded = require("sanitize-html");
17
+ }
18
+ catch (error) {
19
+ const first = String(error?.message ?? "").split("\n")[0];
20
+ if (/["']sanitize-html["']/.test(first))
21
+ throw new Error(MISSING_PEER_MESSAGE, { cause: error });
22
+ throw error;
23
+ }
24
+ const found = typeof loaded === "function" ? loaded : loaded?.default;
25
+ if (typeof found === "function")
26
+ return found;
27
+ throw new Error(emptyModule(loaded) ? MISSING_PEER_MESSAGE : `${MISSING_PEER_MESSAGE} (the sanitize-html that was found exports no function)`);
28
+ }
29
+ /**
30
+ * Whether a module holds nothing: what a bundler hands back for one that is
31
+ * not installed. Next's webpack and Vite 8 give `{}`; Vite 6.3 to 7.3 give
32
+ * `{ default: {} }`, marked `__esModule`. Either is not installed, not a
33
+ * broken install.
34
+ */
35
+ function emptyModule(loaded) {
36
+ if (loaded === null || typeof loaded !== "object")
37
+ return true;
38
+ const keys = Object.keys(loaded).filter((key) => key !== "__esModule");
39
+ if (keys.length === 0)
40
+ return true;
41
+ if (!keys.every((key) => key === "default"))
42
+ return false;
43
+ const inner = loaded.default;
44
+ return inner === undefined || (inner !== null && typeof inner === "object" && Object.keys(inner).length === 0);
45
+ }
46
+ const sanitize = loadSanitizeHtml();
47
+ /** The elements kept by default: the blocks, lists, links, images, tables, code and inline formatting of rich text. */
48
+ exports.DEFAULT_ALLOWED_TAGS = Object.freeze([
49
+ "h1", "h2", "h3", "h4", "h5", "h6", "p", "br", "hr", "div", "span", "blockquote", "pre", "code",
50
+ "ul", "ol", "li", "dl", "dt", "dd",
51
+ "a", "img", "figure", "figcaption",
52
+ "table", "caption", "colgroup", "col", "thead", "tbody", "tfoot", "tr", "th", "td",
53
+ "strong", "b", "em", "i", "u", "s", "strike", "del", "ins", "mark", "sub", "sup", "small",
54
+ ]);
55
+ /**
56
+ * The attributes kept by default, by element. Besides these, a `class` is
57
+ * kept for its `ql-` classes (the editor's alignment, indent, size and font)
58
+ * on any element, and its `language-` classes on `code` and `pre`.
59
+ */
60
+ exports.DEFAULT_ALLOWED_ATTRIBUTES = Object.freeze({
61
+ a: Object.freeze(["href", "title", "target", "rel"]),
62
+ img: Object.freeze(["src", "alt", "title", "width", "height"]),
63
+ blockquote: Object.freeze(["cite"]),
64
+ ol: Object.freeze(["start", "reversed", "type"]),
65
+ li: Object.freeze(["value", "data-list"]),
66
+ pre: Object.freeze(["data-language"]),
67
+ div: Object.freeze(["data-language"]),
68
+ th: Object.freeze(["colspan", "rowspan", "scope"]),
69
+ td: Object.freeze(["colspan", "rowspan"]),
70
+ col: Object.freeze(["span"]),
71
+ colgroup: Object.freeze(["span"]),
72
+ });
73
+ /** The URL schemes a link may use by default. An image's `src` takes `http` and `https` only. A relative URL is always kept. */
74
+ exports.DEFAULT_ALLOWED_SCHEMES = Object.freeze(["http", "https", "mailto", "tel"]);
75
+ /** The schemes an image or a frame loads from: never more, whatever `allowedSchemes` lists, but `data:` images below. */
76
+ const SOURCE_SCHEMES = ["http", "https"];
77
+ /** A `data:` URL an image may show when `allowedSchemes` lists `data`: these raster types, and no SVG, which can carry script. */
78
+ const DATA_IMAGE = /^data:image\/(?:png|jpeg|gif|webp|avif)[;,]/i;
79
+ /**
80
+ * Elements never kept: a script; a stylesheet, whose text sanitize-html
81
+ * writes back raw, or one loaded from anywhere; a base URL for the whole
82
+ * page; `plaintext`, after which a browser reads everything as text; and the
83
+ * elements that load a document or a plugin outside the iframe rules (`src`
84
+ * scheme and hosts).
85
+ */
86
+ const NEVER_TAGS = ["script", "style", "link", "base", "plaintext", "object", "embed", "applet", "frame", "frameset", "portal"];
87
+ /** The prefix of every `id` and `name` content keeps, so it cannot take one the page or its framework uses. */
88
+ const USER_CONTENT = "user-content-";
89
+ /** Targets that stay in this window, so the page they load gets no `window.opener` to begin with. */
90
+ const SAME_WINDOW = ["_self", "_parent", "_top"];
91
+ /** The attributes sanitize-html checks as URLs, and `srcset`, which it checks candidate by candidate. */
92
+ const URL_ATTRIBUTES = new Set([...(sanitize.defaults?.allowedSchemesAppliedToAttributes ?? ["href", "src", "cite"]), "srcset", "imagesrcset"]);
93
+ const LINK_TARGETS = ["_blank", "_self", "_parent", "_top"];
94
+ const IFRAME_ATTRIBUTES = ["src", "width", "height", "title", "allowfullscreen", "frameborder", "loading", "referrerpolicy"];
95
+ const DEFAULT_CLASSES = { "*": ["ql-*"], code: ["language-*"], pre: ["language-*"] };
96
+ /**
97
+ * Elements dropped with everything inside them when they are not kept, so a
98
+ * frame's fallback, a form's controls or an SVG's text never surface as
99
+ * loose text. The same list the live preview overlay drops, and `plaintext`.
100
+ */
101
+ const DROPPED_WHOLE = [
102
+ "script", "style", "iframe", "object", "embed", "template", "noscript", "svg", "math", "form", "input",
103
+ "button", "textarea", "select", "option", "title", "head", "link", "meta", "base", "frame", "frameset",
104
+ "noembed", "noframes", "xmp", "plaintext", "video", "audio", "canvas", "applet", "dialog", "portal",
105
+ ];
106
+ function refuse(message) {
107
+ throw new TypeError(`sanitizeHtml: ${message}`);
108
+ }
109
+ function names(value, option) {
110
+ if (value === undefined)
111
+ return [];
112
+ if (!Array.isArray(value) || !value.every((name) => typeof name === "string"))
113
+ refuse(`${option} must be an array of strings`);
114
+ return value.map((name) => name.trim().toLowerCase()).filter((name) => name !== "");
115
+ }
116
+ /**
117
+ * Whether an attribute name, or a name ending in `*`, can match an event
118
+ * handler or `srcdoc`. A pattern is safe only when the text before its `*`
119
+ * starts neither of them, so `"data-*"` is fine and `"*"`, `"o*"` and `"s*"`
120
+ * are not.
121
+ */
122
+ function unsafeAttribute(name) {
123
+ const star = name.indexOf("*");
124
+ if (star === -1)
125
+ return name.startsWith("on") || name === "srcdoc";
126
+ const prefix = name.slice(0, star);
127
+ return prefix === "" || prefix.startsWith("on") || "on".startsWith(prefix) || "srcdoc".startsWith(prefix);
128
+ }
129
+ /**
130
+ * A link's (`<a>` or `<area>`) `target`, kept when it is one of the keywords
131
+ * (unless the caller listed `target` itself, for named windows). A link that
132
+ * opens another window or tab, `_blank` or a named one, never hands it
133
+ * `window.opener`, and an `opener` token in `rel` is dropped whatever the
134
+ * target. Other links keep `rel` as written.
135
+ */
136
+ function linkTarget(anyTarget) {
137
+ return (tagName, attribs) => {
138
+ const out = { ...attribs };
139
+ if (out.target !== undefined) {
140
+ const target = out.target.trim().toLowerCase();
141
+ if (LINK_TARGETS.includes(target))
142
+ out.target = target;
143
+ else if (!anyTarget)
144
+ delete out.target;
145
+ }
146
+ const opensAnother = out.target !== undefined && !SAME_WINDOW.includes(out.target);
147
+ const written = (out.rel ?? "").split(/\s+/).filter((token) => token !== "");
148
+ if (!opensAnother && !written.some((token) => token.toLowerCase() === "opener"))
149
+ return { tagName, attribs: out };
150
+ const tokens = written.map((token) => token.toLowerCase()).filter((token) => token !== "opener");
151
+ if (opensAnother)
152
+ tokens.push("noopener", "noreferrer");
153
+ if (tokens.length > 0)
154
+ out.rel = [...new Set(tokens)].join(" ");
155
+ else
156
+ delete out.rel;
157
+ return { tagName, attribs: out };
158
+ };
159
+ }
160
+ /** A URL attribute's value as a browser's URL parser reads it: tabs and newlines gone, and C0 controls and spaces trimmed. */
161
+ function urlText(value) {
162
+ return value.replace(/[\t\n\r]/g, "").replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g, "");
163
+ }
164
+ /**
165
+ * An image keeps a `data:` URL only in `src`, only for the raster types in
166
+ * `DATA_IMAGE`, and only when `allowedSchemes` lists `data`. Any other URL
167
+ * attribute holding `data:` (a `srcset` candidate, say) is dropped.
168
+ * sanitize-html checks the scheme after this; this checks the type.
169
+ */
170
+ function imageSources(dataImages) {
171
+ return (tagName, attribs) => {
172
+ const out = { ...attribs };
173
+ for (const [name, value] of Object.entries(attribs)) {
174
+ if (!URL_ATTRIBUTES.has(name))
175
+ continue;
176
+ const url = urlText(value);
177
+ if (name === "src" ? /^data:/i.test(url) && !(dataImages && DATA_IMAGE.test(url)) : /data:/i.test(url))
178
+ delete out[name];
179
+ }
180
+ return { tagName, attribs: out };
181
+ };
182
+ }
183
+ function userContent(value) {
184
+ return value === "" || value.startsWith(USER_CONTENT) ? value : USER_CONTENT + value;
185
+ }
186
+ /**
187
+ * When `id` or `name` may be kept: each value gets the `user-content-`
188
+ * prefix, and a same-document link (`#x`) points at the prefixed id. Already
189
+ * prefixed values are left alone, so sanitizing twice changes nothing.
190
+ */
191
+ const namedProps = (tagName, attribs) => {
192
+ const out = { ...attribs };
193
+ for (const name of ["id", "name"])
194
+ if (out[name] !== undefined)
195
+ out[name] = userContent(out[name]);
196
+ for (const name of ["href", "xlink:href"]) {
197
+ const value = out[name] === undefined ? "" : urlText(out[name]);
198
+ if (value.length > 1 && value.startsWith("#"))
199
+ out[name] = `#${userContent(value.slice(1))}`;
200
+ }
201
+ return { tagName, attribs: out };
202
+ };
203
+ /** Whether an allowed attribute name, or a name ending in `*`, matches `id` or `name`. */
204
+ function namesElement(pattern) {
205
+ if (!pattern.includes("*"))
206
+ return pattern === "id" || pattern === "name";
207
+ const regex = new RegExp(`^${pattern.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`);
208
+ return regex.test("id") || regex.test("name");
209
+ }
210
+ /** An image or a frame whose source was not kept is dropped, rather than left as an empty box. */
211
+ function sourceless(frame) {
212
+ return (frame.tag === "img" || frame.tag === "iframe") && !frame.attribs.src;
213
+ }
214
+ function optionsFor(extra = {}) {
215
+ if (typeof extra !== "object" || extra === null)
216
+ refuse("options must be an object");
217
+ const hosts = names(extra.allowedIframeHostnames, "allowedIframeHostnames");
218
+ const tags = new Set([...exports.DEFAULT_ALLOWED_TAGS, ...names(extra.allowedTags, "allowedTags")]);
219
+ if (hosts.length > 0)
220
+ tags.add("iframe");
221
+ for (const tag of NEVER_TAGS) {
222
+ if (!tags.has(tag))
223
+ continue;
224
+ const instead = tag === "style" ? ' (keep inline styles with allowedAttributes: { "*": ["style"] })' : "";
225
+ refuse(`<${tag}> is never kept, so allowedTags cannot list it${instead}`);
226
+ }
227
+ const attributes = {};
228
+ for (const [tag, list] of Object.entries(exports.DEFAULT_ALLOWED_ATTRIBUTES))
229
+ attributes[tag] = [...list];
230
+ attributes.iframe = [...IFRAME_ATTRIBUTES];
231
+ const classes = { ...DEFAULT_CLASSES };
232
+ const extraAttributes = extra.allowedAttributes ?? {};
233
+ if (typeof extraAttributes !== "object" || extraAttributes === null || Array.isArray(extraAttributes)) {
234
+ refuse("allowedAttributes must be an object of arrays, by element");
235
+ }
236
+ let anyTarget = false;
237
+ let named = false;
238
+ for (const [element, list] of Object.entries(extraAttributes)) {
239
+ const tag = element.trim().toLowerCase();
240
+ for (const name of names(list, `allowedAttributes.${element}`)) {
241
+ if (unsafeAttribute(name))
242
+ refuse(`"${name}" could keep an event handler or srcdoc, so allowedAttributes cannot list it`);
243
+ if (name === "target" && (tag === "a" || tag === "area" || tag === "*"))
244
+ anyTarget = true;
245
+ if (namesElement(name))
246
+ named = true;
247
+ if (name === "class")
248
+ classes[tag] = ["*"];
249
+ else
250
+ (attributes[tag] ??= []).push(name);
251
+ }
252
+ }
253
+ const schemes = names(extra.allowedSchemes, "allowedSchemes").map((scheme) => scheme.replace(/:$/, ""));
254
+ for (const scheme of schemes) {
255
+ if (scheme === "javascript" || scheme === "vbscript")
256
+ refuse(`a ${scheme}: URL is never kept, so allowedSchemes cannot list it`);
257
+ }
258
+ const dataImages = schemes.includes("data");
259
+ const linkTargets = linkTarget(anyTarget);
260
+ const links = schemes.filter((scheme) => scheme !== "data");
261
+ return {
262
+ allowedTags: [...tags],
263
+ allowedAttributes: attributes,
264
+ allowedClasses: classes,
265
+ allowedSchemes: [...exports.DEFAULT_ALLOWED_SCHEMES, ...links],
266
+ allowedSchemesByTag: { img: dataImages ? [...SOURCE_SCHEMES, "data"] : [...SOURCE_SCHEMES], iframe: [...SOURCE_SCHEMES] },
267
+ allowedIframeHostnames: hosts.length > 0 ? hosts : undefined,
268
+ nonTextTags: DROPPED_WHOLE.filter((tag) => !tags.has(tag)),
269
+ transformTags: { a: linkTargets, area: linkTargets, img: imageSources(dataImages), ...(named ? { "*": namedProps } : {}) },
270
+ exclusiveFilter: sourceless,
271
+ };
272
+ }
273
+ /**
274
+ * An html field's value as HTML that is safe to render with the defaults:
275
+ * what the editor writes stays, and scripts, event handlers, `javascript:`
276
+ * links, styles, frames and anything else outside the allowlist go. Markup
277
+ * that is not closed is closed, so an unclosed `<em>` cannot run into the
278
+ * rest of the page. `null` and `undefined` (a field never filled) give `""`.
279
+ * Options extend the allowlist, and each one they add can weaken it, so add
280
+ * only what the content needs.
281
+ *
282
+ * Runs the same in a server component, in Node, on an edge runtime and in a
283
+ * browser. Needs `sanitize-html` 2.18.2 or later installed beside the SDK.
284
+ *
285
+ * ```tsx
286
+ * import { sanitizeHtml } from "@capacms/sdk/sanitize";
287
+ *
288
+ * <div dangerouslySetInnerHTML={{ __html: sanitizeHtml(entry.fields.body) }} />
289
+ * ```
290
+ */
291
+ function sanitizeHtml(html, options) {
292
+ const settings = optionsFor(options);
293
+ if (html == null)
294
+ return "";
295
+ return sanitize(String(html), settings);
296
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capacms/sdk",
3
- "version": "1.0.0-next.13",
3
+ "version": "1.0.0-next.15",
4
4
  "description": "The TypeScript SDK for Capa's content API: REST and GraphQL reads typed from your models, Next.js caching and live preview, and codegen.",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://docs.capacms.com/api",
@@ -51,6 +51,10 @@
51
51
  "types": "./dist/image/index.d.ts",
52
52
  "default": "./dist/image/index.js"
53
53
  },
54
+ "./sanitize": {
55
+ "types": "./dist/sanitize/index.d.ts",
56
+ "default": "./dist/sanitize/index.js"
57
+ },
54
58
  "./overlay": {
55
59
  "import": {
56
60
  "types": "./dist/esm/overlay/index.d.ts",
@@ -100,6 +104,9 @@
100
104
  "image": [
101
105
  "dist/image/index.d.ts"
102
106
  ],
107
+ "sanitize": [
108
+ "dist/sanitize/index.d.ts"
109
+ ],
103
110
  "*": [
104
111
  "dist/index.d.ts"
105
112
  ]
@@ -112,7 +119,8 @@
112
119
  },
113
120
  "peerDependencies": {
114
121
  "graphql": "^16.9.0",
115
- "react": ">=18"
122
+ "react": ">=18",
123
+ "sanitize-html": "^2.18.2"
116
124
  },
117
125
  "peerDependenciesMeta": {
118
126
  "graphql": {
@@ -120,6 +128,9 @@
120
128
  },
121
129
  "react": {
122
130
  "optional": true
131
+ },
132
+ "sanitize-html": {
133
+ "optional": true
123
134
  }
124
135
  },
125
136
  "devDependencies": {
@@ -128,11 +139,14 @@
128
139
  "@types/react": "19.0.1",
129
140
  "next": "15.5.28",
130
141
  "react": "19.2.8",
142
+ "@types/sanitize-html": "^2.16.2",
143
+ "sanitize-html": "^2.18.2",
144
+ "jsdom": "^31.0.1",
131
145
  "@capa/shared": "0.1.0"
132
146
  },
133
147
  "scripts": {
134
148
  "build": "node scripts/shared-image.js && tsc -p tsconfig.json && tsc -p tsconfig.esm.json && node scripts/esm-scope.js",
135
149
  "typecheck": "node scripts/shared-image.js && tsc -p tsconfig.json --noEmit && tsc -p tsconfig.esm.json --noEmit",
136
- "test": "pnpm run build && node --test test/comments.test.js test/codegen.test.js test/client.test.js test/next-client.test.js test/nextjs.test.js test/webhooks.test.js test/relations.test.js test/attrs.test.js test/overlay.test.js test/overlay-dom.test.js test/overlay-items.test.js test/live-fields.test.js test/markdown.test.js test/overlay-fields.test.js test/nextjs-overlay-refresh.test.js test/nextjs-overlay-bundle.test.js test/inflate.test.js test/field-names.test.js test/next-graphql.test.js test/graphql-codegen.test.js test/graphql-contract.test.js test/readme-snippets.test.js test/nextjs-app.test.js test/nextjs-preview-app.test.js test/package-json.test.js test/changelog.test.js test/published-docs.test.js test/builder-messages.test.js test/image.test.js test/nextjs-image-loader.test.js test/capa-cli-handoff.test.js test/server.test.js test/nextjs-write-key-guard.test.js && tsc -p test/types/tsconfig.consumer.json --noEmit && tsc -p test/types/tsconfig.nonstrict.json --noEmit && tsc -p test/types/tsconfig.next.json --noEmit"
150
+ "test": "pnpm run build && node --test test/comments.test.js test/codegen.test.js test/codegen-shapes.test.js test/client.test.js test/next-client.test.js test/nextjs.test.js test/webhooks.test.js test/relations.test.js test/attrs.test.js test/overlay.test.js test/overlay-dom.test.js test/overlay-items.test.js test/live-fields.test.js test/markdown.test.js test/overlay-fields.test.js test/nextjs-overlay-refresh.test.js test/nextjs-overlay-bundle.test.js test/inflate.test.js test/field-names.test.js test/next-graphql.test.js test/graphql-codegen.test.js test/graphql-contract.test.js test/readme-snippets.test.js test/nextjs-app.test.js test/nextjs-preview-app.test.js test/package-json.test.js test/changelog.test.js test/published-docs.test.js test/builder-messages.test.js test/image.test.js test/sanitize.test.js test/sanitize-browser.test.js test/sanitize-dom.test.js test/nextjs-image-loader.test.js test/capa-cli-handoff.test.js test/server.test.js test/nextjs-write-key-guard.test.js && tsc -p test/types/tsconfig.consumer.json --noEmit && tsc -p test/types/tsconfig.nonstrict.json --noEmit && tsc -p test/types/tsconfig.next.json --noEmit"
137
151
  }
138
152
  }