@xharness/satori-element 0.0.0-stage → 4.0.1-alpha.2

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/lib/index.js ADDED
@@ -0,0 +1,871 @@
1
+ import { Element, escape, isElement as isElement$1, parse as parse$1, unescape } from "@xharness/cordis-element";
2
+ //#region lib/types/elements.js
3
+ /**
4
+ * Block/inline category table of the element vocabulary and the content model `normalize` enforces.
5
+ */
6
+ const inline$1 = (tier = 1, content = "phrasing", required) => ({
7
+ category: "inline",
8
+ tier,
9
+ position: "inline",
10
+ content,
11
+ ...required && { required }
12
+ });
13
+ const block = (content, parents) => ({
14
+ category: "block",
15
+ tier: 1,
16
+ position: "block",
17
+ content,
18
+ ...parents && { parents }
19
+ });
20
+ const media = {
21
+ category: "media",
22
+ tier: 1,
23
+ position: "any",
24
+ content: "empty",
25
+ required: ["src"]
26
+ };
27
+ const elementInfo = {
28
+ message: {
29
+ category: "root",
30
+ tier: 1,
31
+ position: "block",
32
+ content: "flow"
33
+ },
34
+ quote: {
35
+ category: "envelope",
36
+ tier: 1,
37
+ position: "block",
38
+ content: "empty",
39
+ parents: ["message"],
40
+ required: ["id"]
41
+ },
42
+ title: {
43
+ category: "envelope",
44
+ tier: 1,
45
+ position: "block",
46
+ content: "phrasing",
47
+ parents: ["message"]
48
+ },
49
+ text: inline$1(1, "empty"),
50
+ b: inline$1(),
51
+ i: inline$1(),
52
+ u: inline$1(),
53
+ s: inline$1(),
54
+ spoiler: inline$1(2),
55
+ code: inline$1(1, "text"),
56
+ a: inline$1(1, "phrasing", ["href"]),
57
+ at: inline$1(1, "empty"),
58
+ channel: inline$1(2, "empty", ["id"]),
59
+ emoji: inline$1(2, "empty", ["id"]),
60
+ span: inline$1(2),
61
+ br: inline$1(1, "empty"),
62
+ p: block("phrasing"),
63
+ h1: block("phrasing"),
64
+ h2: block("phrasing"),
65
+ h3: block("phrasing"),
66
+ h4: block("phrasing"),
67
+ h5: block("phrasing"),
68
+ h6: block("phrasing"),
69
+ ul: block("list"),
70
+ ol: block("list"),
71
+ li: block("flow", ["ul", "ol"]),
72
+ blockquote: block("flow"),
73
+ pre: block("text"),
74
+ hr: block("empty"),
75
+ table: block("table"),
76
+ tr: block("row", ["table"]),
77
+ th: block("flow", ["tr"]),
78
+ td: block("flow", ["tr"]),
79
+ details: block("details"),
80
+ summary: block("phrasing", ["details"]),
81
+ small: block("phrasing"),
82
+ img: media,
83
+ audio: media,
84
+ video: media,
85
+ file: media,
86
+ button: {
87
+ category: "interactive",
88
+ tier: 1,
89
+ position: "any",
90
+ content: "phrasing"
91
+ },
92
+ "button-group": {
93
+ category: "interactive",
94
+ tier: 1,
95
+ position: "block",
96
+ content: "buttons"
97
+ },
98
+ form: {
99
+ category: "control",
100
+ tier: 1,
101
+ position: "block",
102
+ content: "flow",
103
+ required: ["name"]
104
+ },
105
+ input: {
106
+ category: "control",
107
+ tier: 1,
108
+ position: "block",
109
+ content: "empty"
110
+ },
111
+ select: {
112
+ category: "control",
113
+ tier: 1,
114
+ position: "block",
115
+ content: "options"
116
+ },
117
+ option: {
118
+ category: "control",
119
+ tier: 1,
120
+ position: "block",
121
+ content: "phrasing",
122
+ parents: ["select"],
123
+ required: ["value"]
124
+ },
125
+ fallback: {
126
+ category: "alternative",
127
+ tier: 1,
128
+ position: "any",
129
+ content: "cases"
130
+ },
131
+ case: {
132
+ category: "alternative",
133
+ tier: 1,
134
+ position: "any",
135
+ content: "cases",
136
+ parents: ["fallback"]
137
+ },
138
+ markdown: {
139
+ category: "input",
140
+ tier: 1,
141
+ position: "any",
142
+ content: "text"
143
+ },
144
+ forward: {
145
+ category: "inbound",
146
+ tier: 1,
147
+ position: "any",
148
+ content: "phrasing",
149
+ required: ["id"]
150
+ },
151
+ raw: {
152
+ category: "inbound",
153
+ tier: 1,
154
+ position: "any",
155
+ content: "phrasing",
156
+ required: ["platform", "type"]
157
+ }
158
+ };
159
+ /** T3: names reserved for later versions; `normalize` rejects them in v1. */
160
+ const reservedTags = [
161
+ "math",
162
+ "time",
163
+ "sup",
164
+ "sub",
165
+ "mark",
166
+ "sticker",
167
+ "gallery",
168
+ "figure",
169
+ "columns",
170
+ "poll",
171
+ "location",
172
+ "contact",
173
+ "progress",
174
+ "countdown"
175
+ ];
176
+ /** Old Satori / HTML spellings and the v4 tag that replaces them (rejected by `normalize` with a hint). */
177
+ const tagAliases = {
178
+ strong: "b",
179
+ em: "i",
180
+ ins: "u",
181
+ del: "s",
182
+ spl: "spoiler",
183
+ sharp: "channel",
184
+ face: "emoji",
185
+ strike: "s",
186
+ image: "img"
187
+ };
188
+ /** Every tag of the vocabulary. */
189
+ const tags = Object.keys(elementInfo);
190
+ function isTag(type) {
191
+ return Object.prototype.hasOwnProperty.call(elementInfo, type);
192
+ }
193
+ function isReservedTag(type) {
194
+ return reservedTags.includes(type);
195
+ }
196
+ /** Containers whose children are blocks (bare inline runs are wrapped into `<p>`). */
197
+ function isFlowContainer(type) {
198
+ if (!isTag(type)) return false;
199
+ const { content } = elementInfo[type];
200
+ return content === "flow" || content === "details";
201
+ }
202
+ /** Containers whose children are inline (phrasing) content. */
203
+ function isPhrasingContainer(type) {
204
+ if (!isTag(type)) return false;
205
+ const { content } = elementInfo[type];
206
+ return content === "phrasing" || content === "text";
207
+ }
208
+ function isInline(type) {
209
+ return isTag(type) && elementInfo[type].position === "inline";
210
+ }
211
+ function isBlock(type) {
212
+ return isTag(type) && elementInfo[type].position === "block";
213
+ }
214
+ //#endregion
215
+ //#region lib/types/factory.js
216
+ /**
217
+ * Typed factories and the JSX runtime (`@xharness/satori-element/jsx-runtime` resolves to this package's index).
218
+ */
219
+ /** Element-like check: a `cordis-element` runtime element, or a plain `{ type, attrs, children }` object. */
220
+ function isElement(value) {
221
+ if (isElement$1(value)) return true;
222
+ if (!value || typeof value !== "object") return false;
223
+ const { type, attrs, children } = value;
224
+ return typeof type === "string" && !!attrs && typeof attrs === "object" && Array.isArray(children);
225
+ }
226
+ /** Runtime tag of a JSX fragment (`<>…</>`); flattened by the factories, `normalize` and `toText`. */
227
+ const Fragment = "";
228
+ /**
229
+ * Parse the XML-ish `Element.toString()` form back into elements (goldens, logs, tests). Not an input format for
230
+ * user content: plain strings passed to `h` / `normalize` are literal text.
231
+ */
232
+ function parse(source) {
233
+ return parse$1(source);
234
+ }
235
+ /** @internal Build a runtime element without copying children. */
236
+ function make(type, attrs, children, key) {
237
+ const el = Element(type, {});
238
+ for (const [name, value] of Object.entries(attrs)) if (value !== void 0 && value !== null) el.attrs[name] = value;
239
+ el.children = children;
240
+ if (key !== void 0) el.key = key;
241
+ return el;
242
+ }
243
+ /** Flatten children: strings and numbers become `text`, holes are skipped, fragments and arrays are spliced. */
244
+ function toChildren(child, out = []) {
245
+ if (child === null || child === void 0 || typeof child === "boolean") return out;
246
+ if (typeof child === "string" || typeof child === "number") {
247
+ const content = String(child);
248
+ if (content) out.push(make("text", { content }, []));
249
+ } else if (Array.isArray(child)) for (const item of child) toChildren(item, out);
250
+ else if (isElement(child)) if (child.type === "") toChildren(child.children, out);
251
+ else out.push(child);
252
+ else throw new TypeError(`invalid element child: ${Object.prototype.toString.call(child)}`);
253
+ return out;
254
+ }
255
+ function isAttrs(value) {
256
+ return !!value && typeof value === "object" && !Array.isArray(value) && !isElement(value);
257
+ }
258
+ /**
259
+ * Children of a `<fallback>`: every item is one candidate, kept apart as a `<case>`. A fragment or an array is one
260
+ * candidate holding all of its nodes; holes are skipped.
261
+ */
262
+ function toCases(items) {
263
+ const out = [];
264
+ for (const item of items) {
265
+ if (item === null || item === void 0 || typeof item === "boolean") continue;
266
+ if (isElement(item) && item.type === "case") out.push(item);
267
+ else out.push(make("case", {}, toChildren(item)));
268
+ }
269
+ return out;
270
+ }
271
+ function create(type, args) {
272
+ let attrs = {};
273
+ let key;
274
+ if (isAttrs(args[0])) {
275
+ const { key: k, ...rest } = args.shift();
276
+ attrs = rest;
277
+ if (k !== void 0 && k !== null) key = String(k);
278
+ }
279
+ return make(type, attrs, type === "fallback" ? toCases(args) : toChildren(args), key);
280
+ }
281
+ const h = Object.assign((type, ...args) => create(type, args), {
282
+ text: (content) => make("text", { content }, []),
283
+ markdown: (source) => make("markdown", { content: source }, [])
284
+ });
285
+ /** Automatic JSX runtime entry (`jsx`, `jsxs`, `jsxDEV`). */
286
+ function jsx(type, props, key) {
287
+ const { children, ...attrs } = props ?? {};
288
+ if (typeof type === "function") {
289
+ const nodes = toChildren(type({
290
+ ...attrs,
291
+ ...children !== void 0 && { children }
292
+ }));
293
+ return nodes.length === 1 && key === void 0 ? nodes[0] : make("", {}, nodes, key);
294
+ }
295
+ if (type === "") return make("", {}, toChildren(children), key);
296
+ if (type === "markdown" && attrs.content === void 0 && children !== void 0) {
297
+ attrs.content = [].concat(children).join("");
298
+ return make(type, attrs, [], key);
299
+ }
300
+ if (key === void 0 && attrs.key !== void 0) key = String(attrs.key);
301
+ delete attrs.key;
302
+ if (type === "fallback") return make(type, attrs, toCases(Array.isArray(children) ? children : [children]), key);
303
+ return make(type, attrs, toChildren(children), key);
304
+ }
305
+ //#endregion
306
+ //#region lib/types/normalize.js
307
+ /**
308
+ * `normalize()`: the structural contract adapters rely on.
309
+ *
310
+ * - the root is one `<message>`;
311
+ * - flow containers (`message`, `li`, `td`, `th`, `blockquote`, `details`) contain blocks: bare inline runs are
312
+ * wrapped into `<p>`, whitespace-only runs between blocks are dropped;
313
+ * - envelope elements (`quote`, `title`) only appear as direct root children, at most one each, hoisted to the
314
+ * front in the order `quote`, `title`; `summary` is hoisted to the front of its `details`;
315
+ * - `<markdown>` stays one element with its source in `content` (text children are joined into it); the IM render
316
+ * engine expands it, so the source is never parsed here;
317
+ * - a `<fallback>` may stand wherever its candidates may: each candidate becomes one `<case>` normalized as content
318
+ * of the element the `<fallback>` stands in (a fallback of phrasing content joins the surrounding inline run);
319
+ * - T3 (reserved), alias and unknown tags are rejected, as are blocks inside phrasing content and children of
320
+ * elements that take none;
321
+ * - adjacent text is merged, empty text dropped. The input is never mutated; the result is idempotent.
322
+ */
323
+ /** Thrown for content that violates the v4 structure. `path` locates the offending node (`message/ul[2]/li[0]`). */
324
+ var NormalizeError = class extends Error {
325
+ path;
326
+ name = "NormalizeError";
327
+ constructor(message, path) {
328
+ super(`${message} (at ${path})`);
329
+ this.path = path;
330
+ }
331
+ };
332
+ /** Normalize any content into one `<message>` root. */
333
+ function normalize(content) {
334
+ const nodes = toChildren(content);
335
+ if (nodes.length === 1 && nodes[0].type === "message") {
336
+ const [root] = nodes;
337
+ return make("message", root.attrs, normalizeChildren(root.children, "message"), root.key);
338
+ }
339
+ return make("message", {}, normalizeChildren(nodes, "message"), void 0);
340
+ }
341
+ /**
342
+ * Normalize content as the children of an element of tag `parent` (used for fallback output and partial trees).
343
+ * `path` is only used in error messages.
344
+ */
345
+ function normalizeChildren(content, parent, path = parent) {
346
+ const nodes = toChildren(content);
347
+ switch (elementInfo[parent].content) {
348
+ case "empty": {
349
+ const extra = nodes.find((node) => !isEmptyText(node));
350
+ if (extra) throw new NormalizeError(`<${parent}> takes no children, got <${extra.type}>`, path);
351
+ return [];
352
+ }
353
+ case "text": return normalizeText(nodes, parent, path);
354
+ case "phrasing": return normalizePhrasing(nodes, parent, path);
355
+ case "flow":
356
+ case "details": return normalizeFlow(nodes, parent, path);
357
+ case "list": return normalizeList(nodes, parent, path);
358
+ case "table": return normalizeOnly(nodes, parent, path, ["tr"]);
359
+ case "row": return normalizeOnly(nodes, parent, path, ["th", "td"]);
360
+ case "buttons": return normalizeOnly(nodes, parent, path, ["button"]);
361
+ case "options": return normalizeOnly(nodes, parent, path, ["option"]);
362
+ case "cases":
363
+ if (!nodes.length) return [];
364
+ throw new NormalizeError(`the candidates of <${parent}> are normalized as content of its parent`, path);
365
+ }
366
+ }
367
+ /** Candidates of a `<fallback>`: its `<case>` children, or each other child as a candidate of its own. */
368
+ function candidatesOf(node) {
369
+ return node.children.map((child) => child.type === "case" ? toChildren(child.children) : [child]);
370
+ }
371
+ /** Whether a `<fallback>` holds only phrasing content, so it joins an inline run instead of standing as a block. */
372
+ function isInlineFallback(node) {
373
+ return candidatesOf(node).every((candidate) => candidate.every((child) => child.type === "fallback" ? isInlineFallback(child) : isTag(child.type) && elementInfo[child.type].position === "inline"));
374
+ }
375
+ /** Normalize every candidate of a `<fallback>` as content of `parent`, the element the `<fallback>` stands in. */
376
+ function normalizeFallback(node, parent, path) {
377
+ const candidates = candidatesOf(node);
378
+ if (!candidates.length) throw new NormalizeError("<fallback> needs at least one candidate", path);
379
+ return make("fallback", {}, candidates.map((candidate, index) => make("case", {}, normalizeChildren(candidate, parent, `${path}/case[${index}]`))), node.key);
380
+ }
381
+ function isEmptyText(node) {
382
+ return node.type === "text" && !node.attrs.content;
383
+ }
384
+ function isBlankText(node) {
385
+ return node.type === "text" && typeof node.attrs.content === "string" && !node.attrs.content.trim();
386
+ }
387
+ function childPath(path, node, index) {
388
+ return `${path}/${node.type || "fragment"}[${index}]`;
389
+ }
390
+ function checkTag(node, path) {
391
+ const type = node.type;
392
+ if (isTag(type)) return type;
393
+ if (isReservedTag(type)) throw new NormalizeError(`<${type}> is reserved (T3) and not supported in v1`, path);
394
+ const alias = tagAliases[type];
395
+ if (alias) throw new NormalizeError(`unknown element <${type}>; use <${alias}>`, path);
396
+ if (type === "component") throw new NormalizeError("function components must be called while building the tree", path);
397
+ throw new NormalizeError(`unknown element <${type}>`, path);
398
+ }
399
+ function nonEmptyString(value) {
400
+ return typeof value === "string" && value.length > 0;
401
+ }
402
+ function checkAttrs(tag, attrs, path) {
403
+ for (const name of elementInfo[tag].required ?? []) if (!nonEmptyString(attrs[name])) throw new NormalizeError(`<${tag}> requires a non-empty "${name}"`, path);
404
+ if (tag === "text" && typeof attrs.content !== "string") throw new NormalizeError("<text> requires a string \"content\"", path);
405
+ if (tag === "at") {
406
+ if (![
407
+ "user",
408
+ "all",
409
+ "here",
410
+ "role"
411
+ ].includes(attrs.type)) throw new NormalizeError(`<at> type must be user | all | here | role, got ${String(attrs.type)}`, path);
412
+ if ((attrs.type === "user" || attrs.type === "role") && !nonEmptyString(attrs.id)) throw new NormalizeError(`<at type="${attrs.type}"> requires an "id"`, path);
413
+ }
414
+ if (tag === "button") {
415
+ const field = {
416
+ action: "id",
417
+ link: "href",
418
+ input: "text",
419
+ submit: "id"
420
+ }[attrs.type];
421
+ if (!field) throw new NormalizeError(`<button> type must be action | link | input | submit, got ${String(attrs.type)}`, path);
422
+ if (!nonEmptyString(attrs[field])) throw new NormalizeError(`<button type="${attrs.type}"> requires "${field}"`, path);
423
+ checkButtonStyle(attrs, path);
424
+ }
425
+ if (tag === "button-group") {
426
+ checkOneOf("button-group", "width", attrs.width, ["auto", "fill"], path);
427
+ checkOneOf("button-group", "align", attrs.align, [
428
+ "left",
429
+ "center",
430
+ "right"
431
+ ], path);
432
+ }
433
+ if (tag === "input") checkInput(attrs, path);
434
+ if (tag === "select") checkSelect(attrs, path);
435
+ if (tag === "option" && attrs.selected !== void 0 && typeof attrs.selected !== "boolean") throw new NormalizeError("<option> selected must be a boolean", path);
436
+ }
437
+ /** A `<select>`: it names a channel (`id` or `name`), and its initial value matches the arity `multiple` asks for. */
438
+ function checkSelect(attrs, path) {
439
+ for (const name of [
440
+ "placeholder",
441
+ "data",
442
+ "name"
443
+ ]) if (attrs[name] !== void 0 && !nonEmptyString(attrs[name])) throw new NormalizeError(`<select> ${name} must be a non-empty string`, path);
444
+ if (attrs.id !== void 0 && !nonEmptyString(attrs.id)) throw new NormalizeError("<select> id must be a non-empty string", path);
445
+ if (!nonEmptyString(attrs.id) && !nonEmptyString(attrs.name)) throw new NormalizeError("<select> requires an \"id\" (reports its pick) or a \"name\" (feeds its form)", path);
446
+ const value = attrs.value;
447
+ if (value === void 0) return;
448
+ if (!(attrs.multiple ? Array.isArray(value) && value.every((item) => typeof item === "string") : typeof value === "string")) throw new NormalizeError(`<select${attrs.multiple ? " multiple" : ""}> value must be ${attrs.multiple ? "string[]" : "a string"}`, path);
449
+ }
450
+ /** A control's channel, its input mode, its bounds and the value type each mode takes. */
451
+ function checkInput(attrs, path) {
452
+ checkOneOf("input", "type", attrs.type, [
453
+ "text",
454
+ "multiline",
455
+ "password",
456
+ "checkbox"
457
+ ], path);
458
+ for (const name of [
459
+ "label",
460
+ "placeholder",
461
+ "name",
462
+ "id"
463
+ ]) if (attrs[name] !== void 0 && !nonEmptyString(attrs[name])) throw new NormalizeError(`<input> ${name} must be a non-empty string`, path);
464
+ if (!nonEmptyString(attrs.name) && !nonEmptyString(attrs.id)) throw new NormalizeError("<input> requires a \"name\" (feeds its form) or an \"id\" (reports its toggle)", path);
465
+ const checkbox = attrs.type === "checkbox";
466
+ if (attrs.onChange !== void 0) {
467
+ if (!checkbox) throw new NormalizeError("<input> onChange needs type=\"checkbox\"", path);
468
+ if (!nonEmptyString(attrs.id)) throw new NormalizeError("<input type=\"checkbox\" onChange> requires an \"id\"", path);
469
+ }
470
+ if (attrs.maxLength !== void 0) {
471
+ const max = attrs.maxLength;
472
+ if (typeof max !== "number" || !Number.isInteger(max) || max <= 0) throw new NormalizeError(`<input> maxLength must be a positive integer, got ${String(max)}`, path);
473
+ }
474
+ if (attrs.value !== void 0 && typeof attrs.value !== (checkbox ? "boolean" : "string")) throw new NormalizeError(`<input${checkbox ? " type=\"checkbox\"" : ""}> value must be a ${checkbox ? "boolean" : "string"}`, path);
475
+ }
476
+ /** Reject a present attribute outside its allowed values. */
477
+ function checkOneOf(tag, name, value, allowed, path) {
478
+ if (value !== void 0 && !allowed.includes(value)) throw new NormalizeError(`<${tag}> ${name} must be ${allowed.join(" | ")}, got ${String(value)}`, path);
479
+ }
480
+ /** The optional `ButtonStyle` attributes: closed values, a positive pixel width and a complete confirmation. */
481
+ function checkButtonStyle(attrs, path) {
482
+ checkOneOf("button", "size", attrs.size, [
483
+ "tiny",
484
+ "small",
485
+ "medium",
486
+ "large"
487
+ ], path);
488
+ checkOneOf("button", "variant", attrs.variant, [
489
+ "default",
490
+ "primary",
491
+ "danger",
492
+ "text",
493
+ "primary_text",
494
+ "danger_text",
495
+ "primary_filled",
496
+ "danger_filled",
497
+ "laser"
498
+ ], path);
499
+ const width = attrs.width;
500
+ if (width !== void 0 && width !== "default" && width !== "fill" && !(typeof width === "number" && Number.isFinite(width) && width > 0)) throw new NormalizeError(`<button> width must be default | fill | a positive number of pixels, got ${String(width)}`, path);
501
+ for (const name of [
502
+ "icon",
503
+ "tip",
504
+ "disabledTip"
505
+ ]) if (attrs[name] !== void 0 && !nonEmptyString(attrs[name])) throw new NormalizeError(`<button> ${name} must be a non-empty string`, path);
506
+ const confirm = attrs.confirm;
507
+ if (confirm !== void 0 && (typeof confirm !== "object" || confirm === null || !nonEmptyString(confirm.title) || !nonEmptyString(confirm.text))) throw new NormalizeError("<button> confirm requires a non-empty \"title\" and \"text\"", path);
508
+ }
509
+ /** Normalize one element (its own tag, attributes and children); the caller checked its position. */
510
+ function normalizeElement(node, tag, path) {
511
+ checkAttrs(tag, node.attrs, path);
512
+ if (tag === "text") return make("text", node.attrs, [], node.key);
513
+ return make(tag, node.attrs, normalizeChildren(node.children, tag, path), node.key);
514
+ }
515
+ function markdownSource(node, path) {
516
+ if (typeof node.attrs.content === "string") return node.attrs.content;
517
+ const children = toChildren(node.children);
518
+ if (children.every((child) => child.type === "text")) return children.map((child) => child.attrs.content).join("");
519
+ throw new NormalizeError("<markdown> requires a \"content\" string (or text children)", path);
520
+ }
521
+ /** `<markdown>` with its source in `content`; the render engine expands it (the source is never parsed here). */
522
+ function normalizeMarkdown(node, path) {
523
+ return make("markdown", { content: markdownSource(node, path) }, [], node.key);
524
+ }
525
+ function normalizeText(nodes, parent, path) {
526
+ let content = "";
527
+ nodes.forEach((node, index) => {
528
+ if (node.type === "text" && typeof node.attrs.content === "string") content += node.attrs.content;
529
+ else if (node.type === "br") content += "\n";
530
+ else throw new NormalizeError(`<${parent}> only contains text, got <${node.type}>`, childPath(path, node, index));
531
+ });
532
+ return content ? [make("text", { content }, [])] : [];
533
+ }
534
+ function pushText(out, node) {
535
+ const content = node.attrs.content;
536
+ if (!content) return;
537
+ const last = out[out.length - 1];
538
+ if (last?.type === "text" && last.key === void 0 && node.key === void 0) out[out.length - 1] = make("text", {
539
+ ...last.attrs,
540
+ content: last.attrs.content + content
541
+ }, []);
542
+ else out.push(node);
543
+ }
544
+ function items(nodes, path) {
545
+ return nodes.map((node, index) => ({
546
+ node,
547
+ path: childPath(path, node, index)
548
+ }));
549
+ }
550
+ function normalizePhrasing(nodes, parent, path) {
551
+ return phrasing(items(nodes, path), parent);
552
+ }
553
+ function phrasing(list, parent) {
554
+ const out = [];
555
+ list.forEach(({ node, path: p }) => {
556
+ if (node.type === "markdown") {
557
+ out.push(normalizeMarkdown(node, p));
558
+ return;
559
+ }
560
+ if (node.type === "fallback") {
561
+ out.push(normalizeFallback(node, parent, p));
562
+ return;
563
+ }
564
+ const tag = checkTag(node, p);
565
+ const info = elementInfo[tag];
566
+ if (info.parents && !info.parents.includes(parent)) throw new NormalizeError(`<${tag}> is only allowed directly inside ${info.parents.map((t) => `<${t}>`).join(" or ")}`, p);
567
+ if (info.position === "block") throw new NormalizeError(`block <${tag}> inside inline content of <${parent}>`, p);
568
+ const el = normalizeElement(node, tag, p);
569
+ if (tag === "text") pushText(out, el);
570
+ else out.push(el);
571
+ });
572
+ return out;
573
+ }
574
+ function normalizeFlow(nodes, parent, path) {
575
+ const out = [];
576
+ const envelope = {};
577
+ let run = [];
578
+ const flush = () => {
579
+ if (run.length && !run.every(({ node }) => isBlankText(node) || isEmptyText(node))) {
580
+ const children = phrasing(run, "p");
581
+ if (children.length) out.push(make("p", {}, children));
582
+ }
583
+ run = [];
584
+ };
585
+ for (const { node, path: p } of items(nodes, path)) {
586
+ if (node.type === "markdown") {
587
+ flush();
588
+ out.push(normalizeMarkdown(node, p));
589
+ continue;
590
+ }
591
+ if (node.type === "fallback") {
592
+ if (isInlineFallback(node)) run.push({
593
+ node,
594
+ path: p
595
+ });
596
+ else {
597
+ flush();
598
+ out.push(normalizeFallback(node, parent, p));
599
+ }
600
+ continue;
601
+ }
602
+ const tag = checkTag(node, p);
603
+ const info = elementInfo[tag];
604
+ if (info.parents && !info.parents.includes(parent)) throw new NormalizeError(`<${tag}> is only allowed directly inside ${info.parents.map((t) => `<${t}>`).join(" or ")}`, p);
605
+ if (info.position === "inline") {
606
+ run.push({
607
+ node,
608
+ path: p
609
+ });
610
+ continue;
611
+ }
612
+ flush();
613
+ if (tag === "quote" || tag === "title" || tag === "summary") {
614
+ if (envelope[tag]) throw new NormalizeError(`at most one <${tag}> per <${parent}>`, p);
615
+ envelope[tag] = normalizeElement(node, tag, p);
616
+ continue;
617
+ }
618
+ if (tag === "message") throw new NormalizeError("<message> is only allowed as the root", p);
619
+ out.push(normalizeElement(node, tag, p));
620
+ }
621
+ flush();
622
+ return [...[
623
+ envelope.quote,
624
+ envelope.title,
625
+ envelope.summary
626
+ ].filter((x) => !!x), ...out];
627
+ }
628
+ function normalizeList(nodes, parent, path) {
629
+ const out = [];
630
+ let run = [];
631
+ let runPath = path;
632
+ const flush = () => {
633
+ if (run.length && !run.every((node) => isBlankText(node) || isEmptyText(node))) out.push(make("li", {}, normalizeChildren(run, "li", `${runPath}<li>`)));
634
+ run = [];
635
+ };
636
+ for (const { node, path: p } of items(nodes, path)) if (node.type === "li") {
637
+ flush();
638
+ out.push(normalizeElement(node, "li", p));
639
+ } else if (node.type === "fallback") {
640
+ flush();
641
+ out.push(normalizeFallback(node, parent, p));
642
+ } else {
643
+ if (!run.length) runPath = p;
644
+ run.push(node);
645
+ }
646
+ flush();
647
+ return out;
648
+ }
649
+ function normalizeOnly(nodes, parent, path, allowed) {
650
+ const out = [];
651
+ nodes.forEach((node, index) => {
652
+ const p = childPath(path, node, index);
653
+ if (isBlankText(node) || isEmptyText(node)) return;
654
+ if (node.type === "fallback") {
655
+ out.push(normalizeFallback(node, parent, p));
656
+ return;
657
+ }
658
+ const tag = checkTag(node, p);
659
+ if (!allowed.includes(tag)) throw new NormalizeError(`<${parent}> only contains ${allowed.map((t) => `<${t}>`).join(" or ")}, got <${tag}>`, p);
660
+ out.push(normalizeElement(node, tag, p));
661
+ });
662
+ return out;
663
+ }
664
+ //#endregion
665
+ //#region lib/types/variants.js
666
+ /**
667
+ * Variant detection: which `element.<tag>.<variant>` keys an element instance needs.
668
+ */
669
+ /** Declared variants per tag, in `VariantMap` order. */
670
+ const variantTable = {
671
+ at: [
672
+ "user",
673
+ "all",
674
+ "here",
675
+ "role"
676
+ ],
677
+ li: ["checked", "nested"],
678
+ pre: ["lang"],
679
+ span: ["color"],
680
+ table: ["align"],
681
+ td: ["block"],
682
+ img: ["inline"],
683
+ button: [
684
+ "action",
685
+ "link",
686
+ "input",
687
+ "submit",
688
+ "theme",
689
+ "inline"
690
+ ],
691
+ input: ["checkbox"],
692
+ select: ["multiple"]
693
+ };
694
+ /** Capability key of a tag or one of its variants: `variantKey('at', 'all')` → `'element.at.all'`. */
695
+ function variantKey(tag, variant) {
696
+ return variant ? `element.${tag}.${variant}` : `element.${tag}`;
697
+ }
698
+ function isInlinePosition(ancestors) {
699
+ const parent = ancestors?.[ancestors.length - 1];
700
+ return !!parent && isPhrasingContainer(parent.type);
701
+ }
702
+ function hasAlign(table) {
703
+ return table.children.some((row) => row.type === "tr" && row.children.some((cell) => (cell.type === "td" || cell.type === "th") && cell.attrs.align !== void 0 && cell.attrs.align !== "left"));
704
+ }
705
+ function variantsOf(el, ancestors) {
706
+ switch (el.type) {
707
+ case "at": return [el.attrs.type];
708
+ case "li": {
709
+ const out = [];
710
+ if (typeof el.attrs.checked === "boolean") out.push("checked");
711
+ if (el.children.some((child) => child.type === "ul" || child.type === "ol")) out.push("nested");
712
+ return out;
713
+ }
714
+ case "pre": return el.attrs.lang ? ["lang"] : [];
715
+ case "span": return el.attrs.color && el.attrs.color !== "default" ? ["color"] : [];
716
+ case "table": return hasAlign(el) ? ["align"] : [];
717
+ case "td": return el.children.length > 1 || el.children.some((child) => child.type !== "p") ? ["block"] : [];
718
+ case "img": return isInlinePosition(ancestors) ? ["inline"] : [];
719
+ case "input": return el.attrs.type === "checkbox" ? ["checkbox"] : [];
720
+ case "select": return el.attrs.multiple ? ["multiple"] : [];
721
+ case "button": {
722
+ const out = [el.attrs.type];
723
+ if (el.attrs.theme && el.attrs.theme !== "default") out.push("theme");
724
+ if (isInlinePosition(ancestors)) out.push("inline");
725
+ return out;
726
+ }
727
+ default: return [];
728
+ }
729
+ }
730
+ /** Capability keys an element instance needs: its tag key followed by its variant keys. */
731
+ function keysOf(el, ancestors) {
732
+ return [variantKey(el.type), ...variantsOf(el, ancestors).map((v) => variantKey(el.type, v))];
733
+ }
734
+ //#endregion
735
+ //#region lib/types/text.js
736
+ /**
737
+ * `toText()`: the plain-text projection of content (fallbacks, tests, history, agent-facing inbound text).
738
+ *
739
+ * Total: works on unnormalized trees and never throws for unknown tags (their children are projected).
740
+ * Blocks are separated by one newline; envelope `quote` is omitted, `title` is the first line; a `<fallback>` projects
741
+ * its last candidate; `<markdown>` projects its source as it is (the converter lives with the IM render engine).
742
+ */
743
+ function toText(content) {
744
+ return flow(toChildren(content));
745
+ }
746
+ function isBlockNode(node) {
747
+ const type = node.type;
748
+ if (type === "" || !isTag(type)) return false;
749
+ return elementInfo[type].position !== "inline";
750
+ }
751
+ /** Children in flow position: consecutive inline nodes form one line group, blocks stand alone. */
752
+ function flow(nodes) {
753
+ const chunks = [];
754
+ let run = [];
755
+ const flush = () => {
756
+ if (run.length) {
757
+ const text = inline(run);
758
+ if (text.trim()) chunks.push(text);
759
+ }
760
+ run = [];
761
+ };
762
+ for (const node of nodes) if (isBlockNode(node)) {
763
+ flush();
764
+ const text = blockText(node);
765
+ if (text !== void 0) chunks.push(text);
766
+ } else run.push(node);
767
+ flush();
768
+ return chunks.join("\n");
769
+ }
770
+ function inline(nodes) {
771
+ return nodes.map(inlineText).join("");
772
+ }
773
+ function children(node) {
774
+ return inline(node.children);
775
+ }
776
+ function prefixLines(text, first, rest = " ".repeat(first.length)) {
777
+ return text.split("\n").map((line, index) => (index ? rest : first) + line).join("\n");
778
+ }
779
+ function label(kind, name) {
780
+ return name ? `[${kind}: ${name}]` : `[${kind}]`;
781
+ }
782
+ function buttonText(node) {
783
+ return `[${children(node) || node.attrs.text || node.attrs.href || node.attrs.id || "button"}]`;
784
+ }
785
+ /** A control's text: a checkbox keeps its box and label, every other mode names what would be entered. */
786
+ function inputText(node) {
787
+ const { label, name, type, placeholder, value } = node.attrs;
788
+ if (type === "checkbox") return `${value ? "☑" : "☐"} ${label ?? name ?? ""}`.trimEnd();
789
+ return `[${label ?? placeholder ?? name ?? ""}]`;
790
+ }
791
+ /** A select lists what could have been chosen, so the reader sees the options a click would have offered. */
792
+ function selectText(node) {
793
+ const head = node.attrs.placeholder ?? "选择";
794
+ const labels = node.children.filter((child) => child.type === "option").map((option) => children(option) || String(option.attrs.value ?? ""));
795
+ return labels.length ? `[${head}: ${labels.join(" / ")}]` : `[${head}]`;
796
+ }
797
+ /** The last candidate of a `<fallback>`: the plainest alternative, which a text projection stands for. */
798
+ function lastCandidate(node) {
799
+ const last = node.children.at(-1);
800
+ if (!last) return [];
801
+ return last.type === "case" ? last.children : [last];
802
+ }
803
+ /** Text of a block element; `undefined` = renders nothing (envelope quote). */
804
+ function blockText(node) {
805
+ const { attrs } = node;
806
+ const kids = node.children;
807
+ switch (node.type) {
808
+ case "quote": return;
809
+ case "message": return flow(kids);
810
+ case "fallback": return flow(lastCandidate(node));
811
+ case "title": return attrs.subtitle ? `${children(node)}\n${attrs.subtitle}` : children(node);
812
+ case "pre": return inline(kids).replace(/\n$/, "");
813
+ case "hr": return "---";
814
+ case "blockquote": return prefixLines(flow(kids), "> ", "> ");
815
+ case "ul":
816
+ case "ol": {
817
+ let index = node.type === "ol" && typeof attrs.start === "number" ? attrs.start : 1;
818
+ return kids.map((item) => {
819
+ const marker = node.type === "ol" ? `${index++}. ` : "• ";
820
+ const body = item.type === "li" ? flow(item.children) : flow([item]);
821
+ return prefixLines((item.type === "li" && typeof item.attrs.checked === "boolean" ? item.attrs.checked ? "☑ " : "☐ " : "") + body, marker);
822
+ }).join("\n");
823
+ }
824
+ case "li": return prefixLines(flow(kids), "• ");
825
+ case "table": return kids.map((row) => blockText(row) ?? "").join("\n");
826
+ case "tr": return kids.map((cell) => flow(cell.children).replace(/\n/g, " ")).join(" | ");
827
+ case "th":
828
+ case "td": return flow(kids);
829
+ case "details": return flow(kids);
830
+ case "button-group": return kids.map((child) => child.type === "button" ? buttonText(child) : inlineText(child)).join(" ");
831
+ case "input": return inputText(node);
832
+ case "select": return selectText(node);
833
+ case "option": return children(node) || String(attrs.value ?? "");
834
+ case "markdown": return String(attrs.content ?? children(node));
835
+ default: {
836
+ if (!isTag(node.type)) return children(node);
837
+ const info = elementInfo[node.type];
838
+ if (info.content === "flow" || info.content === "details") return flow(kids);
839
+ return info.position === "block" ? children(node) : inlineText(node);
840
+ }
841
+ }
842
+ }
843
+ function inlineText(node) {
844
+ const { attrs } = node;
845
+ switch (node.type) {
846
+ case "text": return String(attrs.content ?? "");
847
+ case "br": return "\n";
848
+ case "at":
849
+ if (attrs.type === "all") return "@all";
850
+ if (attrs.type === "here") return "@here";
851
+ return `@${attrs.name ?? attrs.id ?? ""}`;
852
+ case "channel": return `#${attrs.name ?? attrs.id ?? ""}`;
853
+ case "emoji": return `:${attrs.name ?? attrs.id ?? ""}:`;
854
+ case "a": {
855
+ const text = children(node);
856
+ return !text || text === attrs.href ? String(attrs.href ?? "") : attrs.href ? `${text} (${attrs.href})` : text;
857
+ }
858
+ case "img": return label("image", attrs.alt);
859
+ case "audio": return label("audio", attrs.name);
860
+ case "video": return label("video", attrs.name);
861
+ case "file": return label("file", attrs.name);
862
+ case "button": return buttonText(node);
863
+ case "forward": return children(node) || "[forward]";
864
+ case "quote": return "";
865
+ case "fallback": return inline(lastCandidate(node));
866
+ case "markdown": return String(attrs.content ?? children(node));
867
+ default: return isTag(node.type) && elementInfo[node.type].position === "block" ? blockText(node) ?? "" : children(node);
868
+ }
869
+ }
870
+ //#endregion
871
+ export { Fragment, NormalizeError, h as default, h, elementInfo, escape, isBlock, isElement, isFlowContainer, isInline, isPhrasingContainer, isReservedTag, isTag, jsx, jsx as jsxDEV, jsx as jsxs, keysOf, normalize, normalizeChildren, parse, reservedTags, tagAliases, tags, toText, unescape, variantKey, variantTable, variantsOf };