@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.
Files changed (60) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +368 -5
  3. package/bin/capa-check-bundle.js +80 -0
  4. package/bin/capa.js +3 -3
  5. package/bin/graphql-project.js +1 -1
  6. package/dist/client.d.ts +84 -4
  7. package/dist/client.js +23 -5
  8. package/dist/esm/image/index.d.ts +69 -2
  9. package/dist/esm/image/index.js +108 -5
  10. package/dist/esm/image/shared-params.generated.d.ts +126 -2
  11. package/dist/esm/image/shared-params.generated.js +224 -5
  12. package/dist/esm/overlay/index.d.ts +4 -1
  13. package/dist/esm/overlay/index.js +382 -30
  14. package/dist/esm/overlay/live-fields.d.ts +133 -0
  15. package/dist/esm/overlay/live-fields.js +478 -0
  16. package/dist/esm/overlay/markdown.d.ts +38 -0
  17. package/dist/esm/overlay/markdown.js +536 -0
  18. package/dist/esm/overlay/protocol.d.ts +51 -5
  19. package/dist/esm/overlay/protocol.js +79 -9
  20. package/dist/image/index.d.ts +69 -2
  21. package/dist/image/index.js +109 -4
  22. package/dist/image/shared-params.generated.d.ts +126 -2
  23. package/dist/image/shared-params.generated.js +235 -6
  24. package/dist/index.d.ts +1 -1
  25. package/dist/next/attrs.d.ts +42 -1
  26. package/dist/next/attrs.js +42 -3
  27. package/dist/next/client.d.ts +48 -1
  28. package/dist/next/client.js +33 -2
  29. package/dist/next/entry-fields.d.ts +43 -2
  30. package/dist/next/graphql/request.d.ts +4 -0
  31. package/dist/next/graphql/request.js +4 -0
  32. package/dist/next/graphql/tree.js +9 -0
  33. package/dist/next/index.d.ts +4 -4
  34. package/dist/next/index.js +3 -1
  35. package/dist/nextjs/index.d.ts +91 -7
  36. package/dist/nextjs/index.js +230 -17
  37. package/dist/nextjs/write-key-guard.d.ts +117 -0
  38. package/dist/nextjs/write-key-guard.js +285 -0
  39. package/dist/overlay/index.d.ts +4 -1
  40. package/dist/overlay/index.js +399 -29
  41. package/dist/overlay/live-fields.d.ts +133 -0
  42. package/dist/overlay/live-fields.js +493 -0
  43. package/dist/overlay/markdown.d.ts +38 -0
  44. package/dist/overlay/markdown.js +539 -0
  45. package/dist/overlay/protocol.d.ts +51 -5
  46. package/dist/overlay/protocol.js +82 -9
  47. package/dist/server/browser.d.ts +1 -0
  48. package/dist/server/browser.js +20 -0
  49. package/dist/server/client.d.ts +268 -0
  50. package/dist/server/client.js +335 -0
  51. package/dist/server/errors.d.ts +60 -0
  52. package/dist/server/errors.js +120 -0
  53. package/dist/server/index.d.ts +14 -0
  54. package/dist/server/index.js +32 -0
  55. package/dist/server/key-format.d.ts +41 -0
  56. package/dist/server/key-format.js +91 -0
  57. package/dist/server/transport.d.ts +47 -0
  58. package/dist/server/transport.js +114 -0
  59. package/dist/webhooks.d.ts +8 -0
  60. package/package.json +18 -4
@@ -0,0 +1,536 @@
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
+ * ![images](url)
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
+ const MAX_DEPTH = 32;
34
+ /** The longest emphasis, link text and link a scan looks across. */
35
+ const MAX_SPAN = 1000;
36
+ const ESCAPABLE = /[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/;
37
+ /** Text as HTML: `&` that starts no entity, `<`, `>` and `"` escaped. */
38
+ function escapeText(text) {
39
+ return text
40
+ .replace(/&(?!#\d{1,7};|#x[0-9a-f]{1,6};|[a-z][a-z0-9]{1,31};)/gi, "&amp;")
41
+ .replace(/</g, "&lt;")
42
+ .replace(/>/g, "&gt;")
43
+ .replace(/"/g, "&quot;");
44
+ }
45
+ /** Code as HTML: every `&` escaped, since code shows entities as written. */
46
+ function escapeCode(text) {
47
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
48
+ }
49
+ function unescapeMarkdown(text) {
50
+ return text.replace(/\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g, "$1");
51
+ }
52
+ /** A link destination as an attribute value. */
53
+ function urlAttr(url) {
54
+ return escapeText(unescapeMarkdown(url).replace(/ /g, "%20"));
55
+ }
56
+ function normalLabel(label) {
57
+ return label.trim().replace(/\s+/g, " ").toLowerCase();
58
+ }
59
+ // --------------------------------------------------------------- inline ---
60
+ const RAW_TAG = /<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s+[a-zA-Z_:][a-zA-Z0-9_.:-]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*\/?>/y;
61
+ const AUTOLINK = /<([a-zA-Z][a-zA-Z0-9+.-]{1,31}:[^\s<>]*)>/y;
62
+ const EMAIL = /<([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/y;
63
+ const BARE_URL = /https?:\/\/[^\s<]*[^\s<?!.,:;*_~)'"]/y;
64
+ const REF_LABEL = /\[((?:[^\[\]\\]|\\.){0,999})\]/y;
65
+ /**
66
+ * A link's `(destination "title")` starting at `at`, or null. Scanned by hand
67
+ * rather than by one regular expression, so a long run of spaces or brackets
68
+ * costs one pass.
69
+ */
70
+ function destination(src, at) {
71
+ if (src[at] !== "(")
72
+ return null;
73
+ const end = Math.min(src.length, at + MAX_SPAN);
74
+ let i = at + 1;
75
+ const skipSpace = () => {
76
+ while (i < end && /\s/.test(src[i]))
77
+ i++;
78
+ };
79
+ skipSpace();
80
+ let url;
81
+ if (src[i] === "<") {
82
+ const inside = src.slice(i + 1, end);
83
+ const close = inside.indexOf(">");
84
+ if (close === -1)
85
+ return null;
86
+ url = inside.slice(0, close);
87
+ if (/[<\n]/.test(url))
88
+ return null;
89
+ i += close + 2;
90
+ }
91
+ else {
92
+ const from = i;
93
+ let parens = 0;
94
+ while (i < end) {
95
+ const c = src[i];
96
+ if (c === "\\") {
97
+ i += 2;
98
+ continue;
99
+ }
100
+ if (/\s/.test(c))
101
+ break;
102
+ if (c === "(")
103
+ parens++;
104
+ else if (c === ")") {
105
+ if (parens === 0)
106
+ break;
107
+ parens--;
108
+ }
109
+ i++;
110
+ }
111
+ if (parens !== 0 || i >= end)
112
+ return null;
113
+ url = src.slice(from, i);
114
+ }
115
+ const beforeTitle = i;
116
+ skipSpace();
117
+ const quote = src[i];
118
+ if (i > beforeTitle && (quote === '"' || quote === "'" || quote === "(")) {
119
+ const closer = quote === "(" ? ")" : quote;
120
+ i++;
121
+ while (i < end && src[i] !== closer)
122
+ i += src[i] === "\\" ? 2 : 1;
123
+ if (i >= end)
124
+ return null;
125
+ i++;
126
+ skipSpace();
127
+ }
128
+ return src[i] === ")" ? { url, end: i + 1 } : null;
129
+ }
130
+ /** Where the `]` that closes the `[` at `open` is, or -1. */
131
+ function closingBracket(src, open) {
132
+ let depth = 0;
133
+ const end = Math.min(src.length, open + MAX_SPAN);
134
+ for (let i = open; i < end; i++) {
135
+ const c = src[i];
136
+ if (c === "\\")
137
+ i++;
138
+ else if (c === "[")
139
+ depth++;
140
+ else if (c === "]" && --depth === 0)
141
+ return i;
142
+ }
143
+ return -1;
144
+ }
145
+ /** Every run of backticks, by length, so a code span finds its end in one pass. */
146
+ function backtickRuns(src) {
147
+ const runs = new Map();
148
+ for (const m of src.matchAll(/`+/g)) {
149
+ const list = runs.get(m[0].length);
150
+ if (list)
151
+ list.push(m.index ?? 0);
152
+ else
153
+ runs.set(m[0].length, [m.index ?? 0]);
154
+ }
155
+ return runs;
156
+ }
157
+ const EMPHASIS = [
158
+ [new RegExp(`\\*\\*\\*(?=\\S)([\\s\\S]{0,${MAX_SPAN}}?\\S)\\*\\*\\*`, "g"), "<strong><em>$1</em></strong>"],
159
+ [new RegExp(`\\*\\*(?=\\S)([\\s\\S]{0,${MAX_SPAN}}?\\S)\\*\\*`, "g"), "<strong>$1</strong>"],
160
+ [new RegExp(`(^|[^\\p{L}\\p{N}_])__(?=\\S)([\\s\\S]{0,${MAX_SPAN}}?\\S)__(?![\\p{L}\\p{N}_])`, "gu"), "$1<strong>$2</strong>"],
161
+ [new RegExp(`\\*(?=[^\\s*])([\\s\\S]{0,${MAX_SPAN}}?[^\\s*])\\*`, "g"), "<em>$1</em>"],
162
+ [new RegExp(`(^|[^\\p{L}\\p{N}_])_(?=[^\\s_])([\\s\\S]{0,${MAX_SPAN}}?[^\\s_])_(?![\\p{L}\\p{N}_])`, "gu"), "$1<em>$2</em>"],
163
+ [new RegExp(`~~(?=\\S)([\\s\\S]{0,${MAX_SPAN}}?\\S)~~`, "g"), "<del>$1</del>"],
164
+ ];
165
+ /**
166
+ * One paragraph's or heading's text as HTML. Code spans, links, images,
167
+ * autolinks, raw tags and escapes are set aside first, so the emphasis marks
168
+ * are read only in plain text.
169
+ */
170
+ function inline(src, refs, inLink = false) {
171
+ const held = [];
172
+ const hold = (html) => `\u0000${held.push(html) - 1}\u0000`;
173
+ const runs = backtickRuns(src);
174
+ const nextRun = new Map();
175
+ /** The next `-->`: -2 not looked for yet, -1 there is none. */
176
+ let commentEnd = -2;
177
+ let text = "";
178
+ let i = 0;
179
+ const sticky = (re) => {
180
+ re.lastIndex = i;
181
+ return re.exec(src);
182
+ };
183
+ while (i < src.length) {
184
+ const c = src[i];
185
+ if (c === "\\") {
186
+ const next = src[i + 1];
187
+ if (next === "\n") {
188
+ text += hold("<br>") + "\n";
189
+ i += 2;
190
+ continue;
191
+ }
192
+ if (next !== undefined && ESCAPABLE.test(next)) {
193
+ text += hold(escapeText(next));
194
+ i += 2;
195
+ continue;
196
+ }
197
+ }
198
+ else if (c === "`") {
199
+ let n = 1;
200
+ while (src[i + n] === "`")
201
+ n++;
202
+ const list = runs.get(n) ?? [];
203
+ let k = nextRun.get(n) ?? 0;
204
+ while (k < list.length && list[k] <= i)
205
+ k++;
206
+ nextRun.set(n, k);
207
+ if (k < list.length) {
208
+ let code = src.slice(i + n, list[k]).replace(/\n/g, " ");
209
+ if (code.length > 2 && code.startsWith(" ") && code.endsWith(" ") && code.trim() !== "")
210
+ code = code.slice(1, -1);
211
+ text += hold(`<code>${escapeCode(code)}</code>`);
212
+ i = list[k] + n;
213
+ continue;
214
+ }
215
+ text += src.slice(i, i + n);
216
+ i += n;
217
+ continue;
218
+ }
219
+ else if (c === "<") {
220
+ const auto = sticky(AUTOLINK);
221
+ if (auto && !inLink) {
222
+ text += hold(`<a href="${escapeText(auto[1])}">${escapeText(auto[1])}</a>`);
223
+ i = AUTOLINK.lastIndex;
224
+ continue;
225
+ }
226
+ const email = sticky(EMAIL);
227
+ if (email && !inLink) {
228
+ text += hold(`<a href="mailto:${escapeText(email[1])}">${escapeText(email[1])}</a>`);
229
+ i = EMAIL.lastIndex;
230
+ continue;
231
+ }
232
+ if (src.startsWith("<!--", i)) {
233
+ if (commentEnd !== -1 && commentEnd < i + 4)
234
+ commentEnd = src.indexOf("-->", i + 4);
235
+ if (commentEnd !== -1) {
236
+ text += hold(src.slice(i, commentEnd + 3));
237
+ i = commentEnd + 3;
238
+ continue;
239
+ }
240
+ }
241
+ const raw = sticky(RAW_TAG);
242
+ if (raw) {
243
+ // Markup the source wrote. The sanitizer decides what of it stays.
244
+ text += hold(raw[0]);
245
+ i += raw[0].length;
246
+ continue;
247
+ }
248
+ }
249
+ else if (c === "h" && !inLink && !/[\p{L}\p{N}]/u.test(src[i - 1] ?? "")) {
250
+ const url = sticky(BARE_URL);
251
+ if (url) {
252
+ text += hold(`<a href="${escapeText(url[0])}">${escapeText(url[0])}</a>`);
253
+ i = BARE_URL.lastIndex;
254
+ continue;
255
+ }
256
+ }
257
+ else if (c === "[" || (c === "!" && src[i + 1] === "[")) {
258
+ const image = c === "!";
259
+ const open = image ? i + 1 : i;
260
+ const close = image || !inLink ? closingBracket(src, open) : -1;
261
+ if (close !== -1) {
262
+ const label = src.slice(open + 1, close);
263
+ let url = null;
264
+ let end = close + 1;
265
+ const dest = destination(src, end);
266
+ if (dest) {
267
+ url = dest.url;
268
+ end = dest.end;
269
+ }
270
+ else {
271
+ REF_LABEL.lastIndex = end;
272
+ const ref = REF_LABEL.exec(src);
273
+ const key = ref ? normalLabel(ref[1] === "" ? label : ref[1]) : normalLabel(label);
274
+ if (refs.has(key)) {
275
+ url = refs.get(key) ?? "";
276
+ if (ref)
277
+ end = REF_LABEL.lastIndex;
278
+ }
279
+ }
280
+ if (url !== null) {
281
+ text += hold(image
282
+ ? `<img src="${urlAttr(url)}" alt="${escapeText(unescapeMarkdown(label).replace(/[*_`~[\]]/g, ""))}">`
283
+ : `<a href="${urlAttr(url)}">${inline(label, refs, true)}</a>`);
284
+ i = end;
285
+ continue;
286
+ }
287
+ }
288
+ }
289
+ text += c;
290
+ i += 1;
291
+ }
292
+ let html = escapeText(text.replace(/[ \t]+$/, ""));
293
+ for (const [re, to] of EMPHASIS)
294
+ html = html.replace(re, to);
295
+ html = html.replace(/ {2,}\n/g, "<br>\n");
296
+ return html.replace(/\u0000(\d+)\u0000/g, (_, n) => held[Number(n)] ?? "");
297
+ }
298
+ // ---------------------------------------------------------------- blocks ---
299
+ const BLANK = /^\s*$/;
300
+ const ATX = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
301
+ const RULE = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/;
302
+ const SETEXT = /^ {0,3}(=+|-+)[ \t]*$/;
303
+ const FENCE = /^( {0,3})(`{3,}|~{3,})(.*)$/;
304
+ const QUOTE = /^ {0,3}> ?(.*)$/;
305
+ const LIST_ITEM = /^( {0,3})([-+*]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/;
306
+ const HTML_OPEN = /^ {0,3}<(?:(!--)|\/?([a-zA-Z][a-zA-Z0-9-]*)(?=[\s/>]|$))/;
307
+ const HTML_TAG_LINE = new RegExp(`^ {0,3}${RAW_TAG.source}\\s*$`);
308
+ /** Tags that start an HTML block wherever they are, as in CommonMark. Any other tag only when it is alone on its line. */
309
+ const BLOCK_TAGS = new Set([
310
+ "address", "article", "aside", "audio", "blockquote", "canvas", "dd", "details", "dialog", "div", "dl", "dt",
311
+ "embed", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header",
312
+ "hr", "iframe", "li", "main", "math", "nav", "noscript", "object", "ol", "p", "pre", "script", "section",
313
+ "style", "summary", "svg", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "tr", "ul",
314
+ "video",
315
+ ]);
316
+ const INDENTED = /^ {4}/;
317
+ const DEFINITION = /^ {0,3}\[((?:[^\[\]\\]|\\.){1,999})\]:[ \t]*(?:<([^<>\n]*)>|(\S+))(?:[ \t]+(?:"[^"\n]*"|'[^'\n]*'|\([^()\n]*\)))?[ \t]*$/;
318
+ function indentOf(line) {
319
+ return /^ */.exec(line)?.[0].length ?? 0;
320
+ }
321
+ /** Does an HTML block start on this line? Inside a paragraph, only a comment or a block tag starts one. */
322
+ function htmlBlock(line, inParagraph) {
323
+ const m = HTML_OPEN.exec(line);
324
+ if (!m)
325
+ return false;
326
+ if (m[1] !== undefined || BLOCK_TAGS.has((m[2] ?? "").toLowerCase()))
327
+ return true;
328
+ return !inParagraph && HTML_TAG_LINE.test(line);
329
+ }
330
+ /** A line that ends a paragraph: a heading, fence, rule, quote, list or HTML block starts here. */
331
+ function interrupts(line) {
332
+ if (ATX.test(line) || FENCE.test(line) || RULE.test(line) || QUOTE.test(line) || htmlBlock(line, true))
333
+ return true;
334
+ const item = LIST_ITEM.exec(line);
335
+ // An empty item, or a numbered one not at 1, does not end a paragraph.
336
+ return item !== null && item[4] !== undefined && item[4].trim() !== "" && (!/\d/.test(item[2]) || /^1[.)]$/.test(item[2]));
337
+ }
338
+ /** The kind of list a marker starts: a different bullet or delimiter starts a new list. */
339
+ function listKind(marker) {
340
+ return /\d/.test(marker) ? `ol${marker.slice(-1)}` : `ul${marker}`;
341
+ }
342
+ function list(lines, start, refs, depth) {
343
+ const first = LIST_ITEM.exec(lines[start]);
344
+ const kind = listKind(first[2]);
345
+ const items = [];
346
+ let loose = false;
347
+ let i = start;
348
+ while (i < lines.length) {
349
+ const m = LIST_ITEM.exec(lines[i]);
350
+ if (!m || listKind(m[2]) !== kind || RULE.test(lines[i]))
351
+ break;
352
+ const spaces = m[3] ?? " ";
353
+ const offset = m[1].length + m[2].length + (spaces.length > 4 ? 1 : spaces.length);
354
+ const item = [spaces.length > 4 ? `${spaces.slice(1)}${m[4] ?? ""}` : (m[4] ?? "")];
355
+ i++;
356
+ while (i < lines.length) {
357
+ const line = lines[i];
358
+ if (BLANK.test(line)) {
359
+ item.push("");
360
+ i++;
361
+ continue;
362
+ }
363
+ if (indentOf(line) >= offset) {
364
+ item.push(line.slice(offset));
365
+ i++;
366
+ continue;
367
+ }
368
+ // Not indented: a new item, another block, or a lazy line of the paragraph.
369
+ if (item[item.length - 1] === "" || LIST_ITEM.test(line) || interrupts(line))
370
+ break;
371
+ item.push(line);
372
+ i++;
373
+ }
374
+ let trailing = 0;
375
+ while (item.length > 1 && item[item.length - 1] === "") {
376
+ item.pop();
377
+ trailing++;
378
+ }
379
+ // A blank line between items, or between two blocks of one item, makes the list loose.
380
+ const next = i < lines.length ? LIST_ITEM.exec(lines[i]) : null;
381
+ if (trailing > 0 && next && listKind(next[2]) === kind)
382
+ loose = true;
383
+ // From the second line: an item that starts on the line after its marker is not loose for that.
384
+ for (let k = 2; k < item.length; k++) {
385
+ if (item[k - 1] === "" && item[k] !== "" && !/^\s/.test(item[k]) && !LIST_ITEM.test(item[k]))
386
+ loose = true;
387
+ }
388
+ items.push(item);
389
+ if (trailing > 0 && !(next && listKind(next[2]) === kind))
390
+ break;
391
+ }
392
+ const tag = kind.startsWith("ol") ? "ol" : "ul";
393
+ const number = Number(/\d+/.exec(first[2])?.[0] ?? "1");
394
+ const open = tag === "ol" && number !== 1 ? `<ol start="${number}">` : `<${tag}>`;
395
+ const body = items.map((item) => `<li>${blocks(item, refs, depth + 1, !loose)}</li>`).join("\n");
396
+ return { html: `${open}\n${body}\n</${tag}>`, next: i };
397
+ }
398
+ /** Lines of markdown as HTML blocks. `tight`: a tight list item's paragraphs, without `<p>`. */
399
+ function blocks(lines, refs, depth, tight = false) {
400
+ const out = [];
401
+ if (depth > MAX_DEPTH) {
402
+ const text = lines.join("\n").trim();
403
+ return text === "" ? "" : `<p>${escapeText(text)}</p>`;
404
+ }
405
+ let i = 0;
406
+ while (i < lines.length) {
407
+ const line = lines[i];
408
+ if (BLANK.test(line)) {
409
+ i++;
410
+ continue;
411
+ }
412
+ const fence = FENCE.exec(line);
413
+ if (fence && !(fence[2][0] === "`" && fence[3].includes("`"))) {
414
+ const indent = fence[1].length;
415
+ const marker = fence[2];
416
+ const code = [];
417
+ i++;
418
+ while (i < lines.length) {
419
+ const closing = /^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(lines[i]);
420
+ if (closing && closing[1][0] === marker[0] && closing[1].length >= marker.length) {
421
+ i++;
422
+ break;
423
+ }
424
+ code.push(lines[i].replace(new RegExp(`^ {0,${indent}}`), ""));
425
+ i++;
426
+ }
427
+ out.push(`<pre><code>${escapeCode(code.length > 0 ? `${code.join("\n")}\n` : "")}</code></pre>`);
428
+ continue;
429
+ }
430
+ const atx = ATX.exec(line);
431
+ if (atx) {
432
+ const level = atx[1].length;
433
+ out.push(`<h${level}>${inline((atx[2] ?? "").trim(), refs)}</h${level}>`);
434
+ i++;
435
+ continue;
436
+ }
437
+ if (RULE.test(line)) {
438
+ out.push("<hr>");
439
+ i++;
440
+ continue;
441
+ }
442
+ if (QUOTE.test(line)) {
443
+ const inner = [];
444
+ while (i < lines.length) {
445
+ const q = QUOTE.exec(lines[i]);
446
+ if (q)
447
+ inner.push(q[1]);
448
+ else if (!BLANK.test(lines[i]) && inner.length > 0 && !BLANK.test(inner[inner.length - 1]) && !interrupts(lines[i])) {
449
+ inner.push(lines[i]);
450
+ }
451
+ else
452
+ break;
453
+ i++;
454
+ }
455
+ out.push(`<blockquote>\n${blocks(inner, refs, depth + 1)}\n</blockquote>`);
456
+ continue;
457
+ }
458
+ if (LIST_ITEM.test(line)) {
459
+ const made = list(lines, i, refs, depth);
460
+ out.push(made.html);
461
+ i = made.next;
462
+ continue;
463
+ }
464
+ if (htmlBlock(line, false)) {
465
+ const html = [];
466
+ while (i < lines.length && !BLANK.test(lines[i]))
467
+ html.push(lines[i++]);
468
+ out.push(html.join("\n"));
469
+ continue;
470
+ }
471
+ if (INDENTED.test(line)) {
472
+ const code = [];
473
+ while (i < lines.length && (INDENTED.test(lines[i]) || BLANK.test(lines[i])))
474
+ code.push(lines[i++].slice(4));
475
+ while (code.length > 0 && BLANK.test(code[code.length - 1]))
476
+ code.pop();
477
+ out.push(`<pre><code>${escapeCode(`${code.join("\n")}\n`)}</code></pre>`);
478
+ continue;
479
+ }
480
+ // A paragraph, or a setext heading when a line of = or - follows it.
481
+ const para = [line.replace(/^\s+/, "")];
482
+ i++;
483
+ let heading = 0;
484
+ while (i < lines.length && !BLANK.test(lines[i])) {
485
+ const under = SETEXT.exec(lines[i]);
486
+ if (under) {
487
+ heading = under[1][0] === "=" ? 1 : 2;
488
+ i++;
489
+ break;
490
+ }
491
+ if (interrupts(lines[i]))
492
+ break;
493
+ para.push(lines[i].replace(/^\s+/, ""));
494
+ i++;
495
+ }
496
+ const text = inline(para.join("\n"), refs);
497
+ out.push(heading > 0 ? `<h${heading}>${text}</h${heading}>` : tight ? text : `<p>${text}</p>`);
498
+ }
499
+ return out.join("\n");
500
+ }
501
+ /**
502
+ * Markdown as HTML, for the overlay's sanitizer: never written to a page as
503
+ * it is. Link reference definitions (`[label]: url`) are read first and give
504
+ * no output of their own.
505
+ */
506
+ export function renderMarkdown(source) {
507
+ const lines = source.replace(/\u0000/g, "�").replace(/\r\n?/g, "\n").replace(/\t/g, " ").split("\n");
508
+ const refs = new Map();
509
+ let fence = null;
510
+ let prev = "";
511
+ for (let i = 0; i < lines.length; i++) {
512
+ const line = lines[i];
513
+ const found = FENCE.exec(line);
514
+ const f = found && !(found[2][0] === "`" && found[3].includes("`")) ? found : null;
515
+ if (fence) {
516
+ if (f && f[2][0] === fence[0] && f[2].length >= fence.length && f[3].trim() === "")
517
+ fence = null;
518
+ }
519
+ else if (f) {
520
+ fence = f[2];
521
+ }
522
+ else {
523
+ const def = DEFINITION.exec(line);
524
+ if (def && (i === 0 || BLANK.test(prev) || DEFINITION.test(prev))) {
525
+ const key = normalLabel(def[1]);
526
+ if (key !== "" && !refs.has(key))
527
+ refs.set(key, def[2] ?? def[3] ?? "");
528
+ prev = line;
529
+ lines[i] = "";
530
+ continue;
531
+ }
532
+ }
533
+ prev = line;
534
+ }
535
+ return blocks(lines, refs, 0);
536
+ }
@@ -1,23 +1,33 @@
1
1
  /**
2
2
  * The live preview protocol, site side. Pure: no DOM, no globals, so it can be
3
- * tested under plain `node --test`.
3
+ * tested under plain `node --test`. Its one import, `./live-fields.js`, is
4
+ * pure too.
4
5
  *
5
6
  * The Capa admin frames the site and the two talk over `postMessage`. Every
6
7
  * message is a plain object `{ source, v: 1, type, ...fields }`:
7
8
  *
8
9
  * admin -> site (source "capa-admin")
9
10
  * hello {} sent on the frame's load
10
- * highlight { entryId, field: string | null } entryId "" clears
11
+ * highlight { entryId, field: string | null, item? }
12
+ * entryId "" clears. `item`: one item
13
+ * of a list field (`data-capa-item`)
11
14
  * outline { on: boolean } outline every tagged element
12
15
  * refresh {} re-render the draft
13
16
  * patch { entryId, fields: [{ field, value, saved }] }
14
17
  * unsaved text, as the editor types it
18
+ * fields { entryId, fields: [{ field, kind, value, saved }] }
19
+ * unsaved HTML and Rich Text, images,
20
+ * toggles and dates (`./live-fields.ts`).
21
+ * Sent only to an overlay whose ready
22
+ * lists "fields". A kind it does not
23
+ * know is skipped, the rest kept
15
24
  *
16
25
  * site -> admin (source "capa")
17
26
  * ready { path, entries, features } after hello, and after every navigation.
18
27
  * `features`: what this overlay can do
19
28
  * beyond v1 (`SITE_FEATURES`)
20
- * select { entryId, field } a tagged element was clicked
29
+ * select { entryId, field, item? } a tagged element was clicked. `item`:
30
+ * its `data-capa-item`, when it has one
21
31
  * hover { entryId, field } | { entryId: "", field: null }
22
32
  * visible { entryId, field } the tagged element at the centre of the
23
33
  * viewport changed (throttled, on scroll)
@@ -29,6 +39,15 @@
29
39
  * same kind of addition: an admin sends `patch` only to an overlay whose
30
40
  * `ready` lists "patch", and an older admin never reads `features`.
31
41
  *
42
+ * `item` is the same kind of addition, on two messages v1 already has. The
43
+ * site tags one item of a list (`capaAttrs(entry, "faqs", { item: 2 })`), a
44
+ * click reports it, and the editor opens that item rather than the top of
45
+ * the list. The editor sends it with a highlight only where the project has
46
+ * it on (`CAPA_PREVIEW_TARGETS`), and an overlay that does not read it
47
+ * outlines the whole field, as before. An item that is not a well-formed
48
+ * path (`isItemPath`) is dropped and the message kept: the field is still
49
+ * right.
50
+ *
32
51
  * A PATCH IS TEXT ONLY, and only where the page shows the field verbatim. The
33
52
  * overlay changes a tagged element's text while it reads exactly `saved` (the
34
53
  * value the page was rendered from) or what this page last patched it to, so
@@ -38,10 +57,15 @@
38
57
  * The admin keeps its own copy of these shapes (`apps/admin`, no dependency on
39
58
  * this package). If you change one side, change the other.
40
59
  */
60
+ import { type LiveField } from "./live-fields.js";
41
61
  export declare const PROTOCOL_VERSION = 1;
42
62
  export declare const ADMIN_SOURCE = "capa-admin";
43
63
  export declare const SITE_SOURCE = "capa";
44
- /** What this overlay can do beyond v1, listed in its `ready`. */
64
+ /**
65
+ * What this overlay can do beyond v1, listed in its `ready`. `release`: this
66
+ * SDK sends a release preview's token on its reads (`Capa-Release`), so the
67
+ * admin can tell a site that shows a release from one that shows every draft.
68
+ */
45
69
  export declare const SITE_FEATURES: readonly string[];
46
70
  /** One field of a `patch`: the text being typed, and the saved value the page was rendered from. */
47
71
  export interface PatchField {
@@ -52,6 +76,8 @@ export interface PatchField {
52
76
  /** A `patch` past these is refused whole: no form has that many text fields, or that much text in one. */
53
77
  export declare const PATCH_MAX_FIELDS = 500;
54
78
  export declare const PATCH_MAX_LENGTH = 100000;
79
+ /** Whether a value is an item path an overlay sends and an editor reads. */
80
+ export declare function isItemPath(value: unknown): value is string;
55
81
  export type AdminMessage = {
56
82
  source: typeof ADMIN_SOURCE;
57
83
  v: 1;
@@ -62,6 +88,7 @@ export type AdminMessage = {
62
88
  type: "highlight";
63
89
  entryId: string;
64
90
  field: string | null;
91
+ item?: string;
65
92
  } | {
66
93
  source: typeof ADMIN_SOURCE;
67
94
  v: 1;
@@ -77,6 +104,12 @@ export type AdminMessage = {
77
104
  type: "patch";
78
105
  entryId: string;
79
106
  fields: PatchField[];
107
+ } | {
108
+ source: typeof ADMIN_SOURCE;
109
+ v: 1;
110
+ type: "fields";
111
+ entryId: string;
112
+ fields: LiveField[];
80
113
  };
81
114
  export type SiteMessage = {
82
115
  source: typeof SITE_SOURCE;
@@ -91,6 +124,7 @@ export type SiteMessage = {
91
124
  type: "select";
92
125
  entryId: string;
93
126
  field: string;
127
+ item?: string;
94
128
  } | {
95
129
  source: typeof SITE_SOURCE;
96
130
  v: 1;
@@ -153,7 +187,19 @@ export declare function textAround(current: string): {
153
187
  trail: string;
154
188
  };
155
189
  export declare function readyMessage(path: string, entries: string[], features?: readonly string[]): SiteMessage;
156
- export declare function selectMessage(entryId: string, field: string): SiteMessage;
190
+ /** A click on a tagged element, with its list item when it names a well-formed one. */
191
+ export declare function selectMessage(entryId: string, field: string, item?: string | null): SiteMessage;
192
+ /**
193
+ * Whether an element's `data-capa-item` is the item asked for, or inside it:
194
+ * `2.question` is in item `2`. Pure, so the overlay's matching is tested
195
+ * without a DOM.
196
+ */
197
+ export declare function itemMatches(tagged: string | null | undefined, wanted: string): boolean;
198
+ /**
199
+ * The label the overlay draws for an item: "faqs › item 3" for an index,
200
+ * which counts from one as an editor does, "faqs › question" for a key.
201
+ */
202
+ export declare function itemLabel(field: string, item: string | null | undefined): string;
157
203
  export declare function hoverMessage(entryId: string, field: string | null): SiteMessage;
158
204
  export declare function visibleMessage(entryId: string, field: string): SiteMessage;
159
205
  /** The part of a tagged element `pickCentred` reads, so a test can hand in literals. */