@capacms/sdk 1.0.0-next.10 → 1.0.0-next.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +170 -0
- package/README.md +368 -5
- package/bin/capa-check-bundle.js +80 -0
- package/bin/capa.js +3 -3
- package/bin/graphql-project.js +1 -1
- package/dist/client.d.ts +84 -4
- package/dist/client.js +23 -5
- package/dist/esm/image/index.d.ts +69 -2
- package/dist/esm/image/index.js +108 -5
- package/dist/esm/image/shared-params.generated.d.ts +126 -2
- package/dist/esm/image/shared-params.generated.js +224 -5
- package/dist/esm/overlay/index.d.ts +4 -1
- package/dist/esm/overlay/index.js +382 -30
- package/dist/esm/overlay/live-fields.d.ts +133 -0
- package/dist/esm/overlay/live-fields.js +478 -0
- package/dist/esm/overlay/markdown.d.ts +38 -0
- package/dist/esm/overlay/markdown.js +536 -0
- package/dist/esm/overlay/protocol.d.ts +51 -5
- package/dist/esm/overlay/protocol.js +79 -9
- package/dist/image/index.d.ts +69 -2
- package/dist/image/index.js +109 -4
- package/dist/image/shared-params.generated.d.ts +126 -2
- package/dist/image/shared-params.generated.js +235 -6
- package/dist/index.d.ts +1 -1
- package/dist/next/attrs.d.ts +42 -1
- package/dist/next/attrs.js +42 -3
- package/dist/next/client.d.ts +48 -1
- package/dist/next/client.js +33 -2
- package/dist/next/entry-fields.d.ts +43 -2
- package/dist/next/graphql/request.d.ts +4 -0
- package/dist/next/graphql/request.js +4 -0
- package/dist/next/graphql/tree.js +9 -0
- package/dist/next/index.d.ts +4 -4
- package/dist/next/index.js +3 -1
- package/dist/nextjs/index.d.ts +91 -7
- package/dist/nextjs/index.js +230 -17
- package/dist/nextjs/write-key-guard.d.ts +117 -0
- package/dist/nextjs/write-key-guard.js +285 -0
- package/dist/overlay/index.d.ts +4 -1
- package/dist/overlay/index.js +399 -29
- package/dist/overlay/live-fields.d.ts +133 -0
- package/dist/overlay/live-fields.js +493 -0
- package/dist/overlay/markdown.d.ts +38 -0
- package/dist/overlay/markdown.js +539 -0
- package/dist/overlay/protocol.d.ts +51 -5
- package/dist/overlay/protocol.js +82 -9
- package/dist/server/browser.d.ts +1 -0
- package/dist/server/browser.js +20 -0
- package/dist/server/client.d.ts +268 -0
- package/dist/server/client.js +335 -0
- package/dist/server/errors.d.ts +60 -0
- package/dist/server/errors.js +120 -0
- package/dist/server/index.d.ts +14 -0
- package/dist/server/index.js +32 -0
- package/dist/server/key-format.d.ts +41 -0
- package/dist/server/key-format.js +91 -0
- package/dist/server/transport.d.ts +47 -0
- package/dist/server/transport.js +114 -0
- package/dist/webhooks.d.ts +8 -0
- package/package.json +18 -4
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* The `fields` message: unsaved rich text, images, toggles and dates, as an
|
|
4
|
+
* editor changes them, for the overlay to show before the save. Pure: no DOM,
|
|
5
|
+
* no globals, so it is tested under plain `node --test`. The overlay
|
|
6
|
+
* (`./index.ts`) does the DOM half. Its one import, `./markdown.js`, is pure
|
|
7
|
+
* too.
|
|
8
|
+
*
|
|
9
|
+
* admin -> site fields { entryId, fields: [{ field, kind, value, saved }] }
|
|
10
|
+
*
|
|
11
|
+
* kind "html" value, saved: the HTML field's HTML, as the editor stores it
|
|
12
|
+
* kind "markdown" value, saved: a Rich Text field's value: markdown source,
|
|
13
|
+
* or the HTML Capa's rich text editor writes into it
|
|
14
|
+
* kind "image" value, saved: { url, alt } | null
|
|
15
|
+
* kind "boolean" value, saved: "true" | "false"
|
|
16
|
+
* kind "date" value, saved: "YYYY-MM-DD" | ""
|
|
17
|
+
*
|
|
18
|
+
* Sent only to an overlay whose `ready` lists "fields" (`SITE_FEATURES`), and
|
|
19
|
+
* only where the project has the feature on, so an older overlay never gets
|
|
20
|
+
* one; it would drop an unknown type anyway.
|
|
21
|
+
*
|
|
22
|
+
* THE RULE IS THE TEXT PATCH'S: change only what the page drew from the saved
|
|
23
|
+
* value, exactly, so whatever the site does to a value on its own (a
|
|
24
|
+
* sanitizer, a date format, a resized image URL, markup around it) is either
|
|
25
|
+
* reproduced or left alone until the save re-renders it.
|
|
26
|
+
*
|
|
27
|
+
* html an element whose content IS the saved HTML (compared after the
|
|
28
|
+
* sanitizer below, whitespace aside) gets the new HTML, sanitized,
|
|
29
|
+
* built node by node, never through `innerHTML`.
|
|
30
|
+
* markdown the page shows the site's own rendering of the saved markdown,
|
|
31
|
+
* which nothing here can reproduce, so the element is found by
|
|
32
|
+
* its tag alone: the element `capaAttrs` tagged with the field
|
|
33
|
+
* gets the new value rendered (`richTextHtml`), then put through
|
|
34
|
+
* the same sanitizer as html. A page that tags no element for the
|
|
35
|
+
* field is left as it is.
|
|
36
|
+
* image an `<img>` or `<source>` whose `src` or `srcset` holds the saved
|
|
37
|
+
* image's URL gets the new one in its place, so the site's resize
|
|
38
|
+
* parameters stay; its `alt` follows while it reads the saved alt.
|
|
39
|
+
* boolean an element tagged `data-capa-shown-when` is shown while the value
|
|
40
|
+
* is that, and hidden otherwise; text that reads "true" or "false"
|
|
41
|
+
* follows as text.
|
|
42
|
+
* date text the site formatted from the saved day with a format this
|
|
43
|
+
* module can reproduce (`findDateFormat`) gets the new day in the
|
|
44
|
+
* same format, and a `<time datetime>` follows.
|
|
45
|
+
*/
|
|
46
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
47
|
+
exports.FIELDS_MAX_LENGTH = exports.FIELDS_MAX_FIELDS = void 0;
|
|
48
|
+
exports.acceptLiveFields = acceptLiveFields;
|
|
49
|
+
exports.parseHtml = parseHtml;
|
|
50
|
+
exports.safeHref = safeHref;
|
|
51
|
+
exports.safeImageUrl = safeImageUrl;
|
|
52
|
+
exports.sanitizeHtml = sanitizeHtml;
|
|
53
|
+
exports.canonicalHtml = canonicalHtml;
|
|
54
|
+
exports.preparedHtml = preparedHtml;
|
|
55
|
+
exports.richTextHtml = richTextHtml;
|
|
56
|
+
exports.swapImageUrl = swapImageUrl;
|
|
57
|
+
exports.formatDateAs = formatDateAs;
|
|
58
|
+
exports.findDateFormat = findDateFormat;
|
|
59
|
+
exports.swapDatetime = swapDatetime;
|
|
60
|
+
const markdown_js_1 = require("./markdown.js");
|
|
61
|
+
/** A `fields` message past these is refused whole, like a `patch`. */
|
|
62
|
+
exports.FIELDS_MAX_FIELDS = 500;
|
|
63
|
+
exports.FIELDS_MAX_LENGTH = 100_000;
|
|
64
|
+
const DATE_VALUE = /^(\d{4}-\d{2}-\d{2})?$/;
|
|
65
|
+
function image(raw) {
|
|
66
|
+
if (raw === null)
|
|
67
|
+
return null;
|
|
68
|
+
if (typeof raw !== "object" || Array.isArray(raw))
|
|
69
|
+
return undefined;
|
|
70
|
+
const m = raw;
|
|
71
|
+
if (typeof m.url !== "string" || m.url === "" || m.url.length > 4096)
|
|
72
|
+
return undefined;
|
|
73
|
+
if (typeof m.alt !== "string" || m.alt.length > exports.FIELDS_MAX_LENGTH)
|
|
74
|
+
return undefined;
|
|
75
|
+
return { url: m.url, alt: m.alt };
|
|
76
|
+
}
|
|
77
|
+
/** The fields of a `fields` message, checked, or null to refuse the message whole. */
|
|
78
|
+
function acceptLiveFields(raw) {
|
|
79
|
+
if (!Array.isArray(raw) || raw.length > exports.FIELDS_MAX_FIELDS)
|
|
80
|
+
return null;
|
|
81
|
+
const out = [];
|
|
82
|
+
for (const item of raw) {
|
|
83
|
+
if (typeof item !== "object" || item === null)
|
|
84
|
+
return null;
|
|
85
|
+
const f = item;
|
|
86
|
+
if (typeof f.field !== "string" || f.field === "")
|
|
87
|
+
return null;
|
|
88
|
+
switch (f.kind) {
|
|
89
|
+
case "html":
|
|
90
|
+
case "markdown":
|
|
91
|
+
if (typeof f.value !== "string" || typeof f.saved !== "string")
|
|
92
|
+
return null;
|
|
93
|
+
if (f.value.length > exports.FIELDS_MAX_LENGTH || f.saved.length > exports.FIELDS_MAX_LENGTH)
|
|
94
|
+
return null;
|
|
95
|
+
out.push({ field: f.field, kind: f.kind, value: f.value, saved: f.saved });
|
|
96
|
+
break;
|
|
97
|
+
case "boolean":
|
|
98
|
+
if ((f.value !== "true" && f.value !== "false") || (f.saved !== "true" && f.saved !== "false"))
|
|
99
|
+
return null;
|
|
100
|
+
out.push({ field: f.field, kind: "boolean", value: f.value, saved: f.saved });
|
|
101
|
+
break;
|
|
102
|
+
case "date":
|
|
103
|
+
if (typeof f.value !== "string" || typeof f.saved !== "string")
|
|
104
|
+
return null;
|
|
105
|
+
if (!DATE_VALUE.test(f.value) || !DATE_VALUE.test(f.saved))
|
|
106
|
+
return null;
|
|
107
|
+
out.push({ field: f.field, kind: "date", value: f.value, saved: f.saved });
|
|
108
|
+
break;
|
|
109
|
+
case "image": {
|
|
110
|
+
const value = image(f.value);
|
|
111
|
+
const saved = image(f.saved);
|
|
112
|
+
if (value === undefined || saved === undefined)
|
|
113
|
+
return null;
|
|
114
|
+
out.push({ field: f.field, kind: "image", value, saved });
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
default:
|
|
118
|
+
// A kind this overlay does not know: a newer admin. Skip it, keep the rest.
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
const VOID = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);
|
|
125
|
+
const RAW_TEXT = new Set(["script", "style", "textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript"]);
|
|
126
|
+
const MAX_DEPTH = 64;
|
|
127
|
+
const ENTITIES = {
|
|
128
|
+
amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", copy: "©", reg: "®",
|
|
129
|
+
trade: "™", hellip: "…", mdash: "—", ndash: "–", lsquo: "‘", rsquo: "’",
|
|
130
|
+
ldquo: "“", rdquo: "”", bull: "•", middot: "·", euro: "€", pound: "£",
|
|
131
|
+
yen: "¥", cent: "¢", deg: "°", times: "×", divide: "÷", laquo: "«", raquo: "»",
|
|
132
|
+
};
|
|
133
|
+
function decodeEntities(text) {
|
|
134
|
+
return text.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]{2,8});/gi, (whole, entity) => {
|
|
135
|
+
if (entity[0] === "#") {
|
|
136
|
+
const code = entity[1] === "x" || entity[1] === "X" ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10);
|
|
137
|
+
return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole;
|
|
138
|
+
}
|
|
139
|
+
return ENTITIES[entity.toLowerCase()] ?? whole;
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
const TAG_OPEN = /<([a-zA-Z][a-zA-Z0-9-]*)/y;
|
|
143
|
+
const TAG_CLOSE = /<\/([a-zA-Z][a-zA-Z0-9-]*)\s*>/y;
|
|
144
|
+
const ATTRIBUTE = /\s+([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/y;
|
|
145
|
+
const TAG_END = /\s*(\/?)>/y;
|
|
146
|
+
/**
|
|
147
|
+
* The HTML as a tree, or null when it is not markup this module reads with
|
|
148
|
+
* confidence (an unclosed tag or comment, nesting deeper than 64). Strict on
|
|
149
|
+
* purpose: rich text from Capa's editor is well formed, and a value that is
|
|
150
|
+
* not is left for the save to show.
|
|
151
|
+
*/
|
|
152
|
+
function parseHtml(html) {
|
|
153
|
+
const root = { tag: "#root", attrs: [], children: [] };
|
|
154
|
+
const stack = [root];
|
|
155
|
+
let i = 0;
|
|
156
|
+
const text = (value) => {
|
|
157
|
+
if (value !== "")
|
|
158
|
+
stack[stack.length - 1].children.push(decodeEntities(value));
|
|
159
|
+
};
|
|
160
|
+
while (i < html.length) {
|
|
161
|
+
const lt = html.indexOf("<", i);
|
|
162
|
+
if (lt === -1) {
|
|
163
|
+
text(html.slice(i));
|
|
164
|
+
break;
|
|
165
|
+
}
|
|
166
|
+
text(html.slice(i, lt));
|
|
167
|
+
i = lt;
|
|
168
|
+
if (html.startsWith("<!--", i)) {
|
|
169
|
+
const end = html.indexOf("-->", i + 4);
|
|
170
|
+
if (end === -1)
|
|
171
|
+
return null;
|
|
172
|
+
i = end + 3;
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
TAG_CLOSE.lastIndex = i;
|
|
176
|
+
const close = TAG_CLOSE.exec(html);
|
|
177
|
+
if (close) {
|
|
178
|
+
const tag = close[1].toLowerCase();
|
|
179
|
+
const at = stack.map((e) => e.tag).lastIndexOf(tag);
|
|
180
|
+
if (at > 0)
|
|
181
|
+
stack.length = at;
|
|
182
|
+
i = TAG_CLOSE.lastIndex;
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
TAG_OPEN.lastIndex = i;
|
|
186
|
+
const open = TAG_OPEN.exec(html);
|
|
187
|
+
if (!open) {
|
|
188
|
+
text("<");
|
|
189
|
+
i += 1;
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
const tag = open[1].toLowerCase();
|
|
193
|
+
let at = TAG_OPEN.lastIndex;
|
|
194
|
+
const attrs = [];
|
|
195
|
+
for (;;) {
|
|
196
|
+
ATTRIBUTE.lastIndex = at;
|
|
197
|
+
const a = ATTRIBUTE.exec(html);
|
|
198
|
+
if (!a)
|
|
199
|
+
break;
|
|
200
|
+
attrs.push([a[1].toLowerCase(), decodeEntities(a[2] ?? a[3] ?? a[4] ?? "")]);
|
|
201
|
+
at = ATTRIBUTE.lastIndex;
|
|
202
|
+
}
|
|
203
|
+
TAG_END.lastIndex = at;
|
|
204
|
+
const end = TAG_END.exec(html);
|
|
205
|
+
if (!end)
|
|
206
|
+
return null;
|
|
207
|
+
i = TAG_END.lastIndex;
|
|
208
|
+
const element = { tag, attrs, children: [] };
|
|
209
|
+
stack[stack.length - 1].children.push(element);
|
|
210
|
+
if (RAW_TEXT.has(tag)) {
|
|
211
|
+
// Its content is not markup, and nothing that comes in one is kept.
|
|
212
|
+
const closeAt = html.toLowerCase().indexOf(`</${tag}`, i);
|
|
213
|
+
if (closeAt === -1)
|
|
214
|
+
return null;
|
|
215
|
+
const gt = html.indexOf(">", closeAt);
|
|
216
|
+
if (gt === -1)
|
|
217
|
+
return null;
|
|
218
|
+
i = gt + 1;
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (VOID.has(tag) || end[1] === "/")
|
|
222
|
+
continue;
|
|
223
|
+
if (stack.length > MAX_DEPTH)
|
|
224
|
+
return null;
|
|
225
|
+
stack.push(element);
|
|
226
|
+
}
|
|
227
|
+
return root.children;
|
|
228
|
+
}
|
|
229
|
+
/** Elements whose content is kept, without the element, when they are not allowed. Everything else not allowed goes with its content. */
|
|
230
|
+
const DROPPED_WHOLE = new Set([
|
|
231
|
+
"script", "style", "iframe", "object", "embed", "template", "noscript", "svg", "math", "form", "input",
|
|
232
|
+
"button", "textarea", "select", "option", "title", "head", "link", "meta", "base", "frame", "frameset",
|
|
233
|
+
"noembed", "noframes", "xmp", "video", "audio", "canvas", "applet", "dialog", "portal",
|
|
234
|
+
]);
|
|
235
|
+
/** What the editors' rich text is made of (Quill's output, and markdown's rules), and the attributes each keeps. */
|
|
236
|
+
const ALLOWED = {
|
|
237
|
+
p: [], br: [], hr: [], h1: [], h2: [], h3: [], h4: [], h5: [], h6: [], blockquote: [], pre: ["data-language"],
|
|
238
|
+
ol: [], ul: [], li: ["data-list"], strong: [], b: [], em: [], i: [], u: [], s: [], strike: [], del: [],
|
|
239
|
+
sub: [], sup: [], code: [], span: [], a: ["href", "target", "rel"], img: ["src", "alt", "width", "height"],
|
|
240
|
+
};
|
|
241
|
+
const QUILL_CLASS = /^ql-[a-z0-9-]{1,40}$/;
|
|
242
|
+
const COLOUR = /^(#[0-9a-f]{3,8}|rgba?\(\s*[\d.]+%?\s*,\s*[\d.]+%?\s*,\s*[\d.]+%?\s*(,\s*[\d.]+\s*)?\)|[a-z]{3,20})$/i;
|
|
243
|
+
/** A link target the page may follow: http(s), mailto, tel, or a path or fragment on the site. */
|
|
244
|
+
function safeHref(href) {
|
|
245
|
+
const value = href.trim();
|
|
246
|
+
if (value === "")
|
|
247
|
+
return false;
|
|
248
|
+
if (/^(\/(?!\/)|#|\?|\.\.?\/)/.test(value))
|
|
249
|
+
return true;
|
|
250
|
+
const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(value);
|
|
251
|
+
if (!scheme)
|
|
252
|
+
return !/[\s\\]/.test(value) && !value.startsWith("//");
|
|
253
|
+
return ["http", "https", "mailto", "tel"].includes(scheme[1].toLowerCase());
|
|
254
|
+
}
|
|
255
|
+
/** An image address the page may load: an absolute http(s) URL. */
|
|
256
|
+
function safeImageUrl(url) {
|
|
257
|
+
return /^https?:\/\/[^\s"'<>\\]+$/i.test(url.trim());
|
|
258
|
+
}
|
|
259
|
+
function keptStyle(style) {
|
|
260
|
+
const kept = [];
|
|
261
|
+
for (const part of style.split(";")) {
|
|
262
|
+
const colon = part.indexOf(":");
|
|
263
|
+
if (colon === -1)
|
|
264
|
+
continue;
|
|
265
|
+
const name = part.slice(0, colon).trim().toLowerCase();
|
|
266
|
+
const value = part.slice(colon + 1).trim();
|
|
267
|
+
if ((name === "color" || name === "background-color") && COLOUR.test(value))
|
|
268
|
+
kept.push(`${name}: ${value}`);
|
|
269
|
+
}
|
|
270
|
+
return kept.length > 0 ? kept.join("; ") : null;
|
|
271
|
+
}
|
|
272
|
+
function keptAttrs(tag, attrs) {
|
|
273
|
+
const own = ALLOWED[tag] ?? [];
|
|
274
|
+
const out = [];
|
|
275
|
+
for (const [name, value] of attrs) {
|
|
276
|
+
if (name === "class") {
|
|
277
|
+
const classes = value.split(/\s+/).filter((c) => QUILL_CLASS.test(c));
|
|
278
|
+
if (classes.length > 0)
|
|
279
|
+
out.push(["class", classes.join(" ")]);
|
|
280
|
+
}
|
|
281
|
+
else if (name === "style") {
|
|
282
|
+
const style = keptStyle(value);
|
|
283
|
+
if (style)
|
|
284
|
+
out.push(["style", style]);
|
|
285
|
+
}
|
|
286
|
+
else if (own.includes(name)) {
|
|
287
|
+
if (name === "href" && !safeHref(value))
|
|
288
|
+
continue;
|
|
289
|
+
if (name === "src" && !safeImageUrl(value))
|
|
290
|
+
continue;
|
|
291
|
+
if (name === "target" && value !== "_blank" && value !== "_self")
|
|
292
|
+
continue;
|
|
293
|
+
if ((name === "width" || name === "height") && !/^\d{1,5}$/.test(value))
|
|
294
|
+
continue;
|
|
295
|
+
out.push([name, value]);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (tag === "a" && out.some(([n, v]) => n === "target" && v === "_blank") && !out.some(([n]) => n === "rel")) {
|
|
299
|
+
out.push(["rel", "noopener noreferrer"]);
|
|
300
|
+
}
|
|
301
|
+
return out;
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Rich text cut down to what the editor makes: its blocks, its inline marks,
|
|
305
|
+
* links that go somewhere safe, http(s) images, Quill's `ql-` classes, and a
|
|
306
|
+
* colour. Scripts, frames, forms, embeds and every event handler are gone,
|
|
307
|
+
* with their content; any other element is unwrapped to its content.
|
|
308
|
+
*/
|
|
309
|
+
function sanitizeHtml(nodes, depth = 0) {
|
|
310
|
+
const out = [];
|
|
311
|
+
if (depth > MAX_DEPTH)
|
|
312
|
+
return out;
|
|
313
|
+
for (const node of nodes) {
|
|
314
|
+
if (typeof node === "string") {
|
|
315
|
+
out.push(node);
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
if (DROPPED_WHOLE.has(node.tag))
|
|
319
|
+
continue;
|
|
320
|
+
const children = VOID.has(node.tag) ? [] : sanitizeHtml(node.children, depth + 1);
|
|
321
|
+
if (!(node.tag in ALLOWED)) {
|
|
322
|
+
out.push(...children);
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
if (node.tag === "img" && !node.attrs.some(([n, v]) => n === "src" && safeImageUrl(v)))
|
|
326
|
+
continue;
|
|
327
|
+
out.push({ tag: node.tag, attrs: keptAttrs(node.tag, node.attrs), children });
|
|
328
|
+
}
|
|
329
|
+
return out;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* One string per tree, for "does this element show exactly the saved rich
|
|
333
|
+
* text": attributes sorted, text with its runs of whitespace as one space,
|
|
334
|
+
* and text that is only whitespace left out, since a template's indentation
|
|
335
|
+
* between blocks is not content.
|
|
336
|
+
*/
|
|
337
|
+
function canonicalHtml(nodes) {
|
|
338
|
+
let out = "";
|
|
339
|
+
for (const node of nodes) {
|
|
340
|
+
if (typeof node === "string") {
|
|
341
|
+
const text = node.replace(/\s+/g, " ");
|
|
342
|
+
if (text.trim() !== "")
|
|
343
|
+
out += JSON.stringify(text);
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
const attrs = [...node.attrs].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
347
|
+
out += `<${node.tag}${attrs.map(([n, v]) => ` ${n}=${JSON.stringify(v)}`).join("")}>${canonicalHtml(node.children)}</${node.tag}>`;
|
|
348
|
+
}
|
|
349
|
+
return out;
|
|
350
|
+
}
|
|
351
|
+
/** The saved or new rich text, parsed and sanitized, with its canonical form. Null for HTML `parseHtml` refuses. */
|
|
352
|
+
function preparedHtml(html) {
|
|
353
|
+
const parsed = parseHtml(html);
|
|
354
|
+
if (parsed === null)
|
|
355
|
+
return null;
|
|
356
|
+
const nodes = sanitizeHtml(parsed);
|
|
357
|
+
return { nodes, canonical: canonicalHtml(nodes) };
|
|
358
|
+
}
|
|
359
|
+
// -------------------------------------------------------------- markdown ---
|
|
360
|
+
/** An element tag at the start: `<p>`, `<div class="x">`, `<h1>`, `<!-- -->`. The admin's own rule (`markdown-field.ts`). */
|
|
361
|
+
const LEADING_TAG = /^<(?:[a-z][a-z0-9-]*(?:\s[^>]*)?\/?|!--[\s\S]*?--)>/i;
|
|
362
|
+
/**
|
|
363
|
+
* A Rich Text value as HTML for the sanitizer, the way the admin's editor
|
|
364
|
+
* reads it: HTML the editor wrote stays as it is, and markdown source is
|
|
365
|
+
* rendered (`renderMarkdown`). Never written to a page as it is: the overlay
|
|
366
|
+
* puts it through `preparedHtml` first.
|
|
367
|
+
*/
|
|
368
|
+
function richTextHtml(value) {
|
|
369
|
+
if (value === "")
|
|
370
|
+
return "";
|
|
371
|
+
return LEADING_TAG.test(value.trim()) ? value : (0, markdown_js_1.renderMarkdown)(value);
|
|
372
|
+
}
|
|
373
|
+
// ----------------------------------------------------------------- image ---
|
|
374
|
+
function pathOf(url) {
|
|
375
|
+
try {
|
|
376
|
+
const u = new URL(url);
|
|
377
|
+
return u.pathname.length > 1 ? { origin: u.origin, path: u.pathname } : null;
|
|
378
|
+
}
|
|
379
|
+
catch {
|
|
380
|
+
return null;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* An `src` or `srcset` with the saved image swapped for the new one, or null
|
|
385
|
+
* when it does not hold the saved image. The saved URL is looked for as it
|
|
386
|
+
* is and URL-encoded (`/_next/image?url=...`), then, when both images are on
|
|
387
|
+
* the same host, by path alone, so an image service on another host that
|
|
388
|
+
* keeps the file's path (`https://img.example/t/a.jpg?w=800`) is followed.
|
|
389
|
+
* Whatever the site added around it, a width or a format, stays.
|
|
390
|
+
*/
|
|
391
|
+
function swapImageUrl(attr, saved, value) {
|
|
392
|
+
if (!saved || !value || !safeImageUrl(value))
|
|
393
|
+
return null;
|
|
394
|
+
const pairs = [
|
|
395
|
+
[saved, value],
|
|
396
|
+
[encodeURIComponent(saved), encodeURIComponent(value)],
|
|
397
|
+
];
|
|
398
|
+
const from = pathOf(saved);
|
|
399
|
+
const to = pathOf(value);
|
|
400
|
+
if (from && to && from.origin === to.origin) {
|
|
401
|
+
pairs.push([from.path, to.path], [encodeURIComponent(from.path), encodeURIComponent(to.path)]);
|
|
402
|
+
}
|
|
403
|
+
for (const [a, b] of pairs) {
|
|
404
|
+
if (a.length > 1 && attr.includes(a))
|
|
405
|
+
return attr.split(a).join(b);
|
|
406
|
+
}
|
|
407
|
+
return null;
|
|
408
|
+
}
|
|
409
|
+
// ------------------------------------------------------------------ date ---
|
|
410
|
+
/** The formats a site is likely to print a day in, by id. */
|
|
411
|
+
const DATE_OPTIONS = {
|
|
412
|
+
full: { dateStyle: "full" },
|
|
413
|
+
long: { dateStyle: "long" },
|
|
414
|
+
medium: { dateStyle: "medium" },
|
|
415
|
+
short: { dateStyle: "short" },
|
|
416
|
+
dmy: { year: "numeric", month: "long", day: "numeric" },
|
|
417
|
+
dmyShort: { year: "numeric", month: "short", day: "numeric" },
|
|
418
|
+
dm: { month: "long", day: "numeric" },
|
|
419
|
+
dmShort: { month: "short", day: "numeric" },
|
|
420
|
+
numeric: { year: "numeric", month: "2-digit", day: "2-digit" },
|
|
421
|
+
weekday: { weekday: "long", year: "numeric", month: "long", day: "numeric" },
|
|
422
|
+
weekdayShort: { weekday: "short", month: "short", day: "numeric" },
|
|
423
|
+
my: { month: "long", year: "numeric" },
|
|
424
|
+
};
|
|
425
|
+
function dayOf(value) {
|
|
426
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
427
|
+
if (!m)
|
|
428
|
+
return null;
|
|
429
|
+
const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
|
|
430
|
+
return Number.isNaN(d.getTime()) ? null : d;
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* A day as a format prints it. `raw` is the stored day (`2026-11-01`), `iso`
|
|
434
|
+
* the instant the API sends (`2026-11-01T00:00:00.000Z`), and
|
|
435
|
+
* `intl:<locale>:<id>` an `Intl.DateTimeFormat` in UTC, which is the day as
|
|
436
|
+
* stored: a calendar day is kept at midnight UTC. "" for an empty day.
|
|
437
|
+
*/
|
|
438
|
+
function formatDateAs(format, value) {
|
|
439
|
+
if (value === "")
|
|
440
|
+
return "";
|
|
441
|
+
const day = dayOf(value);
|
|
442
|
+
if (!day)
|
|
443
|
+
return null;
|
|
444
|
+
if (format === "raw")
|
|
445
|
+
return value;
|
|
446
|
+
if (format === "iso")
|
|
447
|
+
return day.toISOString();
|
|
448
|
+
const m = /^intl:([^:]*):(\w+)$/.exec(format);
|
|
449
|
+
if (!m || !DATE_OPTIONS[m[2]])
|
|
450
|
+
return null;
|
|
451
|
+
try {
|
|
452
|
+
return new Intl.DateTimeFormat(m[1] || undefined, { ...DATE_OPTIONS[m[2]], timeZone: "UTC" }).format(day);
|
|
453
|
+
}
|
|
454
|
+
catch {
|
|
455
|
+
return null;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* The format the site printed the saved day in, when `text` is exactly the
|
|
460
|
+
* saved day in one of them (`formatDateAs`), trying the page's locales in
|
|
461
|
+
* order. Null when none reproduces it, and the text is left for the save.
|
|
462
|
+
*/
|
|
463
|
+
function findDateFormat(text, saved, locales) {
|
|
464
|
+
const wanted = text.trim();
|
|
465
|
+
if (wanted === "" || !dayOf(saved))
|
|
466
|
+
return null;
|
|
467
|
+
const formats = ["raw", "iso"];
|
|
468
|
+
const seen = new Set();
|
|
469
|
+
for (const locale of locales) {
|
|
470
|
+
const key = locale ?? "";
|
|
471
|
+
if (seen.has(key))
|
|
472
|
+
continue;
|
|
473
|
+
seen.add(key);
|
|
474
|
+
for (const id of Object.keys(DATE_OPTIONS))
|
|
475
|
+
formats.push(`intl:${key}:${id}`);
|
|
476
|
+
}
|
|
477
|
+
for (const format of formats) {
|
|
478
|
+
if (formatDateAs(format, saved) === wanted)
|
|
479
|
+
return format;
|
|
480
|
+
}
|
|
481
|
+
return null;
|
|
482
|
+
}
|
|
483
|
+
/** A `<time datetime>` with the saved day, in the same shape, or null when it is not the saved day. */
|
|
484
|
+
function swapDatetime(datetime, saved, value) {
|
|
485
|
+
const day = dayOf(saved);
|
|
486
|
+
if (!day)
|
|
487
|
+
return null;
|
|
488
|
+
if (datetime === saved)
|
|
489
|
+
return value;
|
|
490
|
+
if (datetime === day.toISOString())
|
|
491
|
+
return value === "" ? "" : (dayOf(value)?.toISOString() ?? null);
|
|
492
|
+
return null;
|
|
493
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small markdown renderer, for live preview of Rich Text before the save
|
|
3
|
+
* (`./live-fields.ts`, kind "markdown"). Pure: no DOM, no globals, no
|
|
4
|
+
* imports, so it is tested under plain `node --test`.
|
|
5
|
+
*
|
|
6
|
+
* WHY ITS OWN. The package ships with no runtime dependencies, and the overlay
|
|
7
|
+
* adds nothing to a bundle that does not call it. A full CommonMark renderer
|
|
8
|
+
* would be the biggest thing in the overlay, for a view that lasts only until
|
|
9
|
+
* the save, when the site renders the field itself.
|
|
10
|
+
*
|
|
11
|
+
* WHAT IT READS. The blocks and marks a Rich Text field is written with:
|
|
12
|
+
*
|
|
13
|
+
* # to ###### headings, and setext (=== and --- under a line)
|
|
14
|
+
* paragraphs, with a hard break for two trailing spaces or a backslash
|
|
15
|
+
* **strong**, __strong__, *em*, _em_, ***both***, ~~strike~~
|
|
16
|
+
* [links](url "title"), [reference][links], <autolinks>, bare https:// URLs
|
|
17
|
+
* 
|
|
18
|
+
* - * + bullet and 1. 1) ordered lists, nested, tight or loose
|
|
19
|
+
* `code`, ``` and ~~~ fences, and four-space indented code
|
|
20
|
+
* > blockquotes, nested
|
|
21
|
+
* --- *** ___ rules
|
|
22
|
+
* \ escapes, and HTML written into the markdown, passed through
|
|
23
|
+
*
|
|
24
|
+
* NOT SAFE ON ITS OWN, ON PURPOSE. It writes what the markdown says, raw HTML
|
|
25
|
+
* and `javascript:` links included. The overlay puts the result through the
|
|
26
|
+
* same parser and sanitizer as an HTML field (`preparedHtml`), which is what
|
|
27
|
+
* keeps scripts, handlers and unsafe links off the page. Text it writes is
|
|
28
|
+
* escaped, so only markup the source wrote reaches that sanitizer as markup.
|
|
29
|
+
*
|
|
30
|
+
* BOUNDED. Every scan is capped, so a 100,000-character value renders in
|
|
31
|
+
* linear time, and nesting stops at 32 levels.
|
|
32
|
+
*/
|
|
33
|
+
/**
|
|
34
|
+
* Markdown as HTML, for the overlay's sanitizer: never written to a page as
|
|
35
|
+
* it is. Link reference definitions (`[label]: url`) are read first and give
|
|
36
|
+
* no output of their own.
|
|
37
|
+
*/
|
|
38
|
+
export declare function renderMarkdown(source: string): string;
|