@quickbuilder.io/rich-text 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -2
  3. package/adapters.d.ts +1 -0
  4. package/adapters.js +1 -0
  5. package/collaboration.d.ts +1 -0
  6. package/collaboration.js +1 -0
  7. package/commands.d.ts +1 -0
  8. package/commands.js +1 -0
  9. package/content.d.ts +1 -0
  10. package/content.js +1 -0
  11. package/contracts.d.ts +1 -0
  12. package/contracts.js +1 -0
  13. package/dist/adapters.d.mts +11 -0
  14. package/dist/adapters.d.ts +11 -0
  15. package/dist/adapters.js +564 -0
  16. package/dist/adapters.js.map +1 -0
  17. package/dist/adapters.mjs +557 -0
  18. package/dist/adapters.mjs.map +1 -0
  19. package/dist/collaboration.d.mts +29 -0
  20. package/dist/collaboration.d.ts +29 -0
  21. package/dist/collaboration.js +758 -0
  22. package/dist/collaboration.js.map +1 -0
  23. package/dist/collaboration.mjs +733 -0
  24. package/dist/collaboration.mjs.map +1 -0
  25. package/dist/commands.d.mts +8 -0
  26. package/dist/commands.d.ts +8 -0
  27. package/dist/commands.js +42 -0
  28. package/dist/commands.js.map +1 -0
  29. package/dist/commands.mjs +38 -0
  30. package/dist/commands.mjs.map +1 -0
  31. package/dist/content-types-CYHsrMrs.d.mts +27 -0
  32. package/dist/content-types-CYHsrMrs.d.ts +27 -0
  33. package/dist/content.d.mts +19 -0
  34. package/dist/content.d.ts +19 -0
  35. package/dist/content.js +785 -0
  36. package/dist/content.js.map +1 -0
  37. package/dist/content.mjs +775 -0
  38. package/dist/content.mjs.map +1 -0
  39. package/dist/contracts.d.mts +199 -0
  40. package/dist/contracts.d.ts +199 -0
  41. package/dist/contracts.js +4 -0
  42. package/dist/contracts.js.map +1 -0
  43. package/dist/contracts.mjs +3 -0
  44. package/dist/contracts.mjs.map +1 -0
  45. package/dist/extensions.d.mts +363 -0
  46. package/dist/extensions.d.ts +363 -0
  47. package/dist/extensions.js +153 -0
  48. package/dist/extensions.js.map +1 -0
  49. package/dist/extensions.mjs +142 -0
  50. package/dist/extensions.mjs.map +1 -0
  51. package/dist/history.d.mts +12 -0
  52. package/dist/history.d.ts +12 -0
  53. package/dist/history.js +464 -0
  54. package/dist/history.js.map +1 -0
  55. package/dist/history.mjs +459 -0
  56. package/dist/history.mjs.map +1 -0
  57. package/dist/index.d.mts +12 -0
  58. package/dist/index.d.ts +12 -0
  59. package/dist/index.js +1438 -0
  60. package/dist/index.js.map +1 -0
  61. package/dist/index.mjs +1372 -0
  62. package/dist/index.mjs.map +1 -0
  63. package/dist/markdown.d.mts +32 -0
  64. package/dist/markdown.d.ts +32 -0
  65. package/dist/markdown.js +739 -0
  66. package/dist/markdown.js.map +1 -0
  67. package/dist/markdown.mjs +735 -0
  68. package/dist/markdown.mjs.map +1 -0
  69. package/dist/runtime/dom.d.mts +148 -0
  70. package/dist/runtime/dom.d.ts +148 -0
  71. package/dist/runtime/dom.js +2145 -0
  72. package/dist/runtime/dom.js.map +1 -0
  73. package/dist/runtime/dom.mjs +2084 -0
  74. package/dist/runtime/dom.mjs.map +1 -0
  75. package/dist/schema.d.mts +23 -0
  76. package/dist/schema.d.ts +23 -0
  77. package/dist/schema.js +157 -0
  78. package/dist/schema.js.map +1 -0
  79. package/dist/schema.mjs +137 -0
  80. package/dist/schema.mjs.map +1 -0
  81. package/dist/serializer.d.mts +38 -0
  82. package/dist/serializer.d.ts +38 -0
  83. package/dist/serializer.js +504 -0
  84. package/dist/serializer.js.map +1 -0
  85. package/dist/serializer.mjs +491 -0
  86. package/dist/serializer.mjs.map +1 -0
  87. package/dist/svg-export-BtI8x_mG.d.mts +15 -0
  88. package/dist/svg-export-BtI8x_mG.d.ts +15 -0
  89. package/dist/transactions.d.mts +16 -0
  90. package/dist/transactions.d.ts +16 -0
  91. package/dist/transactions.js +637 -0
  92. package/dist/transactions.js.map +1 -0
  93. package/dist/transactions.mjs +631 -0
  94. package/dist/transactions.mjs.map +1 -0
  95. package/extensions.d.ts +1 -0
  96. package/extensions.js +1 -0
  97. package/history.d.ts +1 -0
  98. package/history.js +1 -0
  99. package/package.json +352 -4
  100. package/schema.d.ts +1 -0
  101. package/schema.js +1 -0
  102. package/serializer.d.ts +1 -0
  103. package/serializer.js +1 -0
  104. package/transactions.d.ts +1 -0
  105. package/transactions.js +1 -0
@@ -0,0 +1,758 @@
1
+ 'use strict';
2
+
3
+ var Y = require('yjs');
4
+
5
+ function _interopNamespace(e) {
6
+ if (e && e.__esModule) return e;
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n.default = e;
20
+ return Object.freeze(n);
21
+ }
22
+
23
+ var Y__namespace = /*#__PURE__*/_interopNamespace(Y);
24
+
25
+ // src/collaboration.ts
26
+
27
+ // src/entities.ts
28
+ var entities = {
29
+ amp: "&",
30
+ lt: "<",
31
+ gt: ">",
32
+ quot: '"',
33
+ apos: "'",
34
+ nbsp: "\xA0",
35
+ copy: "\xA9",
36
+ reg: "\xAE",
37
+ trade: "\u2122",
38
+ mdash: "\u2014",
39
+ ndash: "\u2013",
40
+ hellip: "\u2026",
41
+ lsquo: "\u2018",
42
+ rsquo: "\u2019",
43
+ ldquo: "\u201C",
44
+ rdquo: "\u201D",
45
+ bull: "\u2022",
46
+ middot: "\xB7"
47
+ };
48
+ function decodeRichTextEntities(value) {
49
+ return value.replace(
50
+ /&(#x[\da-f]+|#\d+|[a-z][a-z\d]+);/gi,
51
+ (original, entity) => {
52
+ if (!entity.startsWith("#")) {
53
+ const decoded = entities[entity];
54
+ if (decoded === void 0)
55
+ throw new Error(
56
+ `Unsupported named rich-text entity ${original}; use Unicode or a numeric entity`
57
+ );
58
+ return decoded;
59
+ }
60
+ const point = entity[1]?.toLowerCase() === "x" ? Number.parseInt(entity.slice(2), 16) : Number(entity.slice(1));
61
+ if (point < 1 || point > 1114111 || point >= 55296 && point <= 57343)
62
+ throw new Error("Invalid rich-text character entity");
63
+ return String.fromCodePoint(point);
64
+ }
65
+ );
66
+ }
67
+
68
+ // src/schema.ts
69
+ var richTextAllowedTags = [
70
+ "a",
71
+ "b",
72
+ "blockquote",
73
+ "br",
74
+ "code",
75
+ "em",
76
+ "h1",
77
+ "h2",
78
+ "h3",
79
+ "h4",
80
+ "h5",
81
+ "h6",
82
+ "hr",
83
+ "i",
84
+ "img",
85
+ "input",
86
+ "label",
87
+ "li",
88
+ "mark",
89
+ "ol",
90
+ "p",
91
+ "pre",
92
+ "qb-video",
93
+ "s",
94
+ "span",
95
+ "sub",
96
+ "sup",
97
+ "strong",
98
+ "table",
99
+ "tbody",
100
+ "td",
101
+ "tfoot",
102
+ "th",
103
+ "thead",
104
+ "tr",
105
+ "u",
106
+ "ul"
107
+ ];
108
+ var richTextVoidTags = ["br", "hr", "img", "input"];
109
+ var richTextAllowedTargets = ["_blank", "_self", "_parent", "_top"];
110
+ var richTextAlignmentTags = [
111
+ "blockquote",
112
+ "h1",
113
+ "h2",
114
+ "h3",
115
+ "h4",
116
+ "h5",
117
+ "h6",
118
+ "li",
119
+ "ol",
120
+ "p",
121
+ "pre",
122
+ "td",
123
+ "th",
124
+ "ul"
125
+ ];
126
+ var richTextAllowedAlignments = ["left", "center", "right", "justify"];
127
+ var richTextAllowedFontFamilies = [
128
+ "default",
129
+ "carlito",
130
+ "source-sans-3",
131
+ "noto-sans",
132
+ "arimo",
133
+ "tinos",
134
+ "cousine"
135
+ ];
136
+ var richTextAllowedFontSizes = [
137
+ "default",
138
+ "8",
139
+ "9",
140
+ "10",
141
+ "11",
142
+ "12",
143
+ "14",
144
+ "16",
145
+ "18",
146
+ "24",
147
+ "30",
148
+ "36",
149
+ "48",
150
+ "60",
151
+ "72",
152
+ "96"
153
+ ];
154
+ var richTextAllowedLineHeights = ["1", "1.15", "1.5", "2"];
155
+ var richTextAllowedColors = [
156
+ "default",
157
+ "gray",
158
+ "brown",
159
+ "orange",
160
+ "yellow",
161
+ "green",
162
+ "blue",
163
+ "purple",
164
+ "pink",
165
+ "red"
166
+ ];
167
+ function isRichTextAlignment(value) {
168
+ return richTextAllowedAlignments.includes(value);
169
+ }
170
+ function isRichTextFontFamily(value) {
171
+ return richTextAllowedFontFamilies.includes(value);
172
+ }
173
+ function isRichTextFontSize(value) {
174
+ return richTextAllowedFontSizes.includes(value);
175
+ }
176
+ function isRichTextLineHeight(value) {
177
+ return richTextAllowedLineHeights.includes(value);
178
+ }
179
+ function isRichTextColor(value) {
180
+ return richTextAllowedColors.includes(value);
181
+ }
182
+
183
+ // src/serializer.ts
184
+ var ACTIVE_CONTENT_TAG_PATTERN = /<\s*(script|style|iframe|object|embed|form)\b[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi;
185
+ var ACTIVE_VOID_TAG_PATTERN = /<\s*(?:script|style|iframe|object|embed|link|meta|base)\b[^>]*\/?\s*>/gi;
186
+ var RICH_TEXT_TAG_PATTERN = /<qb-video\b((?:"[^"]*"|'[^']*'|[^'">])*)>[\s\S]*?<\/qb-video>|<\/?([a-z][a-z0-9-]*)\b((?:"[^"]*"|'[^']*'|[^'">])*)>/gi;
187
+ var ATTRIBUTE_VALUE_PATTERN = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g;
188
+ var allowedTagSet = new Set(richTextAllowedTags);
189
+ var voidTagSet = new Set(richTextVoidTags);
190
+ var allowedTargetSet = new Set(richTextAllowedTargets);
191
+ var alignmentTagSet = new Set(richTextAlignmentTags);
192
+ var richTextMaximumUrlLength = 4096;
193
+ function validateRichTextVideo(src, title) {
194
+ src = src.trim();
195
+ title = title.trim();
196
+ if (!src || src.length > 2048 || !title || title.length > 200 || /[\u0000-\u0020\u007f\\]/u.test(src)) return;
197
+ const relative = /^\/(?!\/)/u.test(src);
198
+ if (!relative && !src.startsWith("https://")) return;
199
+ try {
200
+ const url = new URL(src, "https://rich-text.invalid");
201
+ if (url.protocol !== "https:" || url.username || url.password) return;
202
+ return { src, title };
203
+ } catch {
204
+ return;
205
+ }
206
+ }
207
+ function readVideoAttributes(raw) {
208
+ const attributes = readHtmlAttributes(raw);
209
+ return validateRichTextVideo(attributes.get("data-src") ?? "", attributes.get("data-title") ?? "");
210
+ }
211
+ function sanitizeRichTextMarkup(value, options = {}) {
212
+ if (options.resolveImageSource !== void 0 && typeof options.resolveImageSource !== "function")
213
+ throw new TypeError("Invalid rich text image resolver.");
214
+ if (options.allowVideos !== void 0 && typeof options.allowVideos !== "boolean")
215
+ throw new TypeError("Invalid rich text video policy.");
216
+ if (options.videoPresentation !== void 0 && !["embed", "link"].includes(options.videoPresentation))
217
+ throw new TypeError("Invalid rich text video presentation.");
218
+ if (options.allowContentIdImages !== void 0 && typeof options.allowContentIdImages !== "boolean")
219
+ throw new TypeError("Invalid rich text Content-ID image policy.");
220
+ if (options.imageCrossOrigin !== void 0 && options.imageCrossOrigin !== "anonymous" && typeof options.imageCrossOrigin !== "function")
221
+ throw new TypeError("Invalid rich text image credentials policy.");
222
+ return sanitizeMarkup(value, options);
223
+ }
224
+ function sanitizeMarkup(value, options = {}) {
225
+ return value.replace(ACTIVE_CONTENT_TAG_PATTERN, "").replace(ACTIVE_VOID_TAG_PATTERN, "").replace(RICH_TEXT_TAG_PATTERN, (match, rawVideo, rawTagName, rawAttributes) => {
226
+ if (rawVideo !== void 0) {
227
+ if (options.allowVideos === false) return "";
228
+ const video = readVideoAttributes(rawVideo);
229
+ if (!video) return "";
230
+ if (options.videoPresentation === "link") {
231
+ return withBlockIdentity("<p>", rawVideo) + `<br><a href="${escapeHtmlAttribute(video.src)}">${escapeHtmlAttribute(video.title)}</a></p>`;
232
+ }
233
+ return withBlockIdentity(`<qb-video data-src="${escapeHtmlAttribute(video.src)}" data-title="${escapeHtmlAttribute(video.title)}" contenteditable="false">`, rawVideo) + "</qb-video>";
234
+ }
235
+ const tagName = rawTagName.toLowerCase();
236
+ if (tagName === "qb-video") return "";
237
+ if (!allowedTagSet.has(tagName)) {
238
+ return "";
239
+ }
240
+ if (match.startsWith("</")) {
241
+ return voidTagSet.has(tagName) ? "" : `</${tagName}>`;
242
+ }
243
+ if (voidTagSet.has(tagName)) {
244
+ if (tagName === "img") {
245
+ return withBlockIdentity(renderSafeImageTag(rawAttributes, options), rawAttributes);
246
+ }
247
+ if (tagName === "input") {
248
+ return withBlockIdentity(renderSafeTaskCheckbox(rawAttributes), rawAttributes);
249
+ }
250
+ return withBlockIdentity(`<${tagName}>`, rawAttributes);
251
+ }
252
+ if (tagName !== "a") {
253
+ return withBlockIdentity(renderSafeRichTextTag(tagName, rawAttributes), rawAttributes);
254
+ }
255
+ return renderSafeAnchorTag(rawAttributes);
256
+ });
257
+ }
258
+ function normalizeRichTextHtml(value) {
259
+ const sanitized = sanitizeRichTextMarkup(value);
260
+ return sanitized.trim() ? sanitized : "<p></p>";
261
+ }
262
+ function withBlockIdentity(tag, rawAttributes) {
263
+ const id = readHtmlAttributes(rawAttributes).get("data-qb-block-id");
264
+ if (!tag || tag.startsWith("<span") || !id || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id)) return tag;
265
+ return tag.replace(/>$/, ` data-qb-block-id="${id}">`);
266
+ }
267
+ function renderSafeRichTextTag(tagName, rawAttributes) {
268
+ if (tagName === "span") {
269
+ return renderSafeSpanTag(rawAttributes);
270
+ }
271
+ if (tagName === "td" || tagName === "th") {
272
+ return renderSafeTableCellTag(tagName, rawAttributes);
273
+ }
274
+ if (tagName === "ul") {
275
+ const attributes2 = readHtmlAttributes(rawAttributes);
276
+ return attributes2.get("data-task-list") === "true" ? '<ul data-task-list="true">' : "<ul>";
277
+ }
278
+ if (tagName === "li") {
279
+ const attributes2 = readHtmlAttributes(rawAttributes);
280
+ const checked = attributes2.get("data-checked");
281
+ return checked === "true" || checked === "false" ? `<li data-checked="${checked}">` : "<li>";
282
+ }
283
+ if (!alignmentTagSet.has(tagName)) {
284
+ return `<${tagName}>`;
285
+ }
286
+ const attributes = readHtmlAttributes(rawAttributes);
287
+ const renderedAttributes = [];
288
+ const alignment = attributes.get("data-align");
289
+ const lineHeight = attributes.get("data-line-height");
290
+ if (isRichTextAlignment(alignment)) renderedAttributes.push(`data-align="${alignment}"`);
291
+ if (isRichTextLineHeight(lineHeight)) renderedAttributes.push(`data-line-height="${lineHeight}"`);
292
+ return renderedAttributes.length > 0 ? `<${tagName} ${renderedAttributes.join(" ")}>` : `<${tagName}>`;
293
+ }
294
+ function renderSafeSpanTag(rawAttributes) {
295
+ const attributes = readHtmlAttributes(rawAttributes);
296
+ const renderedAttributes = [];
297
+ const id = normalizeMentionAttribute(attributes.get("data-mention-id"), 128);
298
+ const label = normalizeMentionAttribute(attributes.get("data-mention-label"), 160);
299
+ const fontFamily = attributes.get("data-font-family");
300
+ const fontSize = attributes.get("data-font-size");
301
+ const textColor = attributes.get("data-text-color");
302
+ const highlightColor = attributes.get("data-highlight-color");
303
+ if (id && label) {
304
+ renderedAttributes.push(
305
+ `data-mention-id="${escapeHtmlAttribute(id)}"`,
306
+ `data-mention-label="${escapeHtmlAttribute(label)}"`
307
+ );
308
+ }
309
+ if (isRichTextFontFamily(fontFamily) && fontFamily !== "default") renderedAttributes.push(`data-font-family="${fontFamily}"`);
310
+ if (isRichTextFontSize(fontSize) && fontSize !== "default") renderedAttributes.push(`data-font-size="${fontSize}"`);
311
+ if (isRichTextColor(textColor) && textColor !== "default") renderedAttributes.push(`data-text-color="${textColor}"`);
312
+ if (isRichTextColor(highlightColor) && highlightColor !== "default") renderedAttributes.push(`data-highlight-color="${highlightColor}"`);
313
+ return renderedAttributes.length > 0 ? `<span ${renderedAttributes.join(" ")}>` : "<span>";
314
+ }
315
+ function renderSafeTableCellTag(tagName, rawAttributes) {
316
+ const attributes = readHtmlAttributes(rawAttributes);
317
+ const renderedAttributes = [];
318
+ const alignment = attributes.get("data-align");
319
+ const colSpan = normalizeTableSpan(attributes.get("colspan"));
320
+ const rowSpan = normalizeTableSpan(attributes.get("rowspan"));
321
+ const scope = attributes.get("scope");
322
+ if (isRichTextAlignment(alignment)) {
323
+ renderedAttributes.push(`data-align="${alignment}"`);
324
+ }
325
+ if (colSpan) {
326
+ renderedAttributes.push(`colspan="${colSpan}"`);
327
+ }
328
+ if (rowSpan) {
329
+ renderedAttributes.push(`rowspan="${rowSpan}"`);
330
+ }
331
+ if (tagName === "th" && scope && ["col", "row", "colgroup", "rowgroup"].includes(scope)) {
332
+ renderedAttributes.push(`scope="${scope}"`);
333
+ }
334
+ return renderedAttributes.length > 0 ? `<${tagName} ${renderedAttributes.join(" ")}>` : `<${tagName}>`;
335
+ }
336
+ function renderSafeAnchorTag(rawAttributes) {
337
+ const attributes = readHtmlAttributes(rawAttributes);
338
+ const renderedAttributes = [];
339
+ const href = attributes.get("href");
340
+ const target = attributes.get("target");
341
+ if (href && isSafeRichTextHref(href)) {
342
+ renderedAttributes.push(`href="${escapeHtmlAttribute(href)}"`);
343
+ }
344
+ if (target && allowedTargetSet.has(target)) {
345
+ renderedAttributes.push(`target="${target}"`);
346
+ if (target === "_blank") {
347
+ renderedAttributes.push('rel="noopener noreferrer"');
348
+ }
349
+ }
350
+ return renderedAttributes.length > 0 ? `<a ${renderedAttributes.join(" ")}>` : "<a>";
351
+ }
352
+ function renderSafeImageTag(rawAttributes, options) {
353
+ const attributes = readHtmlAttributes(rawAttributes);
354
+ const source = attributes.get("src");
355
+ const resolveSource = options.resolveImageSource;
356
+ if (!source || !resolveSource && !isAllowedImageSource(source, options)) return "";
357
+ const src = resolveSource ? resolveSource(source) : source;
358
+ if (src === null) return "";
359
+ if (!isAllowedImageSource(src, options)) throw new TypeError("Invalid replacement image URL.");
360
+ const renderedAttributes = [
361
+ `src="${escapeHtmlAttribute(src)}"`,
362
+ `alt="${escapeHtmlAttribute(normalizeTextAttribute(attributes.get("alt"), 512) ?? "")}"`
363
+ ];
364
+ const title = normalizeTextAttribute(attributes.get("title"), 512);
365
+ const width = normalizeImageDimension(attributes.get("width"));
366
+ const height = normalizeImageDimension(attributes.get("height"));
367
+ if (title) renderedAttributes.push(`title="${escapeHtmlAttribute(title)}"`);
368
+ if (width) renderedAttributes.push(`width="${width}"`);
369
+ if (height) renderedAttributes.push(`height="${height}"`);
370
+ const credentials = typeof options.imageCrossOrigin === "function" ? options.imageCrossOrigin(src) : options.imageCrossOrigin;
371
+ if (credentials !== void 0 && credentials !== "anonymous") throw new TypeError("Invalid resolved image credentials policy.");
372
+ if ((credentials ?? attributes.get("crossorigin")) === "anonymous") renderedAttributes.push('crossorigin="anonymous"');
373
+ renderedAttributes.push('loading="lazy"', 'decoding="async"');
374
+ return `<img ${renderedAttributes.join(" ")}>`;
375
+ }
376
+ function isAllowedImageSource(value, options) {
377
+ if (isSafeRichTextImageSrc(value)) return true;
378
+ if (!options.allowContentIdImages || value.length > richTextMaximumUrlLength || !/^cid:/iu.test(value)) return false;
379
+ try {
380
+ const identity = decodeURIComponent(value.slice(4));
381
+ return identity.length > 0 && identity.length <= 200 && !/[^\u0021-\u007e]|[<>"]/u.test(identity);
382
+ } catch {
383
+ return false;
384
+ }
385
+ }
386
+ function renderSafeTaskCheckbox(rawAttributes) {
387
+ const attributes = readHtmlAttributes(rawAttributes);
388
+ if (attributes.get("type")?.toLowerCase() !== "checkbox") return "";
389
+ const checked = attributes.get("checked") !== void 0 || /(?:^|\s)checked(?:\s|=|$)/i.test(rawAttributes);
390
+ return `<input type="checkbox"${checked ? ' checked=""' : ""} contenteditable="false">`;
391
+ }
392
+ function readHtmlAttributes(rawAttributes) {
393
+ const attributes = /* @__PURE__ */ new Map();
394
+ for (const match of rawAttributes.matchAll(ATTRIBUTE_VALUE_PATTERN)) {
395
+ const name = match[1]?.toLowerCase();
396
+ const value = match[2] ?? match[3] ?? match[4] ?? "";
397
+ if (name) {
398
+ attributes.set(name, decodeHtmlAttribute(value.trim()));
399
+ }
400
+ }
401
+ return attributes;
402
+ }
403
+ function isSafeRichTextHref(value) {
404
+ const trimmed = value.trim();
405
+ if (!trimmed || trimmed.length > richTextMaximumUrlLength || /[\u0000-\u001f\u007f]/.test(trimmed)) {
406
+ return false;
407
+ }
408
+ if (trimmed.startsWith("//")) {
409
+ return false;
410
+ }
411
+ if (/^(?:#|\/|\.\/|\.\.\/|\?)/.test(trimmed)) {
412
+ return true;
413
+ }
414
+ try {
415
+ const url = new URL(trimmed);
416
+ return ["http:", "https:", "mailto:", "tel:"].includes(url.protocol.toLowerCase());
417
+ } catch {
418
+ return false;
419
+ }
420
+ }
421
+ function isSafeRichTextImageSrc(value) {
422
+ const trimmed = value.trim();
423
+ if (!trimmed || trimmed.length > richTextMaximumUrlLength || /[\u0000-\u001f\u007f]/.test(trimmed) || trimmed.startsWith("//")) return false;
424
+ if (/^(?:\/|\.\/|\.\.\/)/.test(trimmed)) return true;
425
+ try {
426
+ const url = new URL(trimmed);
427
+ return url.protocol === "http:" || url.protocol === "https:";
428
+ } catch {
429
+ return false;
430
+ }
431
+ }
432
+ function normalizeTableSpan(value) {
433
+ if (!value || !/^\d{1,3}$/.test(value)) {
434
+ return null;
435
+ }
436
+ const numericValue = Number(value);
437
+ return numericValue >= 1 && numericValue <= 100 ? String(numericValue) : null;
438
+ }
439
+ function normalizeMentionAttribute(value, maxLength) {
440
+ const normalized = value?.trim();
441
+ if (!normalized || normalized.length > maxLength || /[<>"'`]/.test(normalized)) {
442
+ return null;
443
+ }
444
+ return normalized;
445
+ }
446
+ function normalizeTextAttribute(value, maxLength) {
447
+ const normalized = value?.trim();
448
+ if (!normalized || normalized.length > maxLength) return null;
449
+ return normalized;
450
+ }
451
+ function normalizeImageDimension(value) {
452
+ if (!value || !/^\d{1,5}$/.test(value)) return null;
453
+ const numericValue = Number(value);
454
+ return numericValue >= 1 && numericValue <= 1e4 ? String(numericValue) : null;
455
+ }
456
+ function escapeHtmlAttribute(value) {
457
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
458
+ }
459
+ function decodeHtmlAttribute(value) {
460
+ return value.replace(/&(?:#(\d+)|#x([0-9a-f]+)|(amp|quot|apos|lt|gt));/gi, (entity, decimal, hexadecimal, named) => {
461
+ if (decimal || hexadecimal) {
462
+ const codePoint = decimal ? Number(decimal) : Number.parseInt(hexadecimal, 16);
463
+ if (!Number.isSafeInteger(codePoint) || codePoint <= 0 || codePoint > 1114111 || codePoint >= 55296 && codePoint <= 57343) {
464
+ return "\uFFFD";
465
+ }
466
+ return String.fromCodePoint(codePoint);
467
+ }
468
+ const namedEntity = {
469
+ amp: "&",
470
+ apos: "'",
471
+ gt: ">",
472
+ lt: "<",
473
+ quot: '"'
474
+ };
475
+ return namedEntity[String(named).toLowerCase()] ?? entity;
476
+ });
477
+ }
478
+
479
+ // src/view-tree.ts
480
+ function richTextHtmlToViewTree(value) {
481
+ if (value.length > 1e6)
482
+ throw new RangeError("Rich text exceeds the rendering limit");
483
+ const html = normalizeRichTextHtml(value).replace(/<!--[\s\S]*?-->/g, "");
484
+ const root = [];
485
+ const stack = [
486
+ { tag: "", children: root }
487
+ ];
488
+ let count = 0;
489
+ const tokens = /<\/?([a-z][a-z\d-]*)\b((?:"[^"]*"|'[^']*'|[^'">])*)>|([^<]+)|</gi;
490
+ for (const match of html.matchAll(tokens)) {
491
+ if (++count > 2e4 || stack.length > 64)
492
+ throw new RangeError("Rich text exceeds the rendering complexity limit");
493
+ const current = stack[stack.length - 1];
494
+ if (!match[1]) {
495
+ current.children.push({ type: "text", value: decodeRichTextEntities(match[3] ?? "<") });
496
+ continue;
497
+ }
498
+ const tag = match[1].toLowerCase();
499
+ if (match[0].startsWith("</")) {
500
+ if (stack.length === 1 || current.tag !== tag)
501
+ throw new Error(`Unbalanced rich-text closing tag ${tag}`);
502
+ stack.pop();
503
+ continue;
504
+ }
505
+ const attributes = {};
506
+ for (const attribute of match[2].matchAll(/([\w-]+)="([^"]*)"/g))
507
+ attributes[attribute[1]] = decodeRichTextEntities(attribute[2]);
508
+ const node = {
509
+ type: "element",
510
+ tag,
511
+ attributes,
512
+ children: []
513
+ };
514
+ current.children.push(node);
515
+ if (!richTextVoidTags.some((voidTag) => voidTag === tag)) stack.push(node);
516
+ }
517
+ if (stack.length !== 1) throw new Error("Unclosed rich-text element");
518
+ return root;
519
+ }
520
+
521
+ // src/collaboration.ts
522
+ var blockId = "data-qb-block-id";
523
+ var inline = /* @__PURE__ */ new Set(["strong", "em", "u", "s", "code", "mark", "sub", "sup", "a", "span"]);
524
+ var escape = (value) => value.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
525
+ function createBlockIdentity() {
526
+ const document = new Y__namespace.Doc();
527
+ const identity = document.guid;
528
+ document.destroy();
529
+ return identity;
530
+ }
531
+ function parse(nodes, marks = {}) {
532
+ const result = [];
533
+ const append = (entry) => {
534
+ const previous = result[result.length - 1];
535
+ if (entry.kind === "text" && previous?.kind === "text") previous.runs.push(...entry.runs);
536
+ else result.push(entry);
537
+ };
538
+ for (const node of nodes) {
539
+ if (node.type === "text") append({ kind: "text", runs: [{ text: node.value, marks }] });
540
+ else if (inline.has(node.tag)) {
541
+ const attributes = JSON.stringify(node.attributes);
542
+ for (const child of parse(node.children, { ...marks, [node.tag]: attributes })) append(child);
543
+ } else append({ kind: "element", tag: node.tag, attributes: { ...node.attributes }, children: parse(node.children, marks) });
544
+ }
545
+ return result;
546
+ }
547
+ function compatible(node, entry) {
548
+ return entry.kind === "text" ? node instanceof Y__namespace.XmlText : node instanceof Y__namespace.XmlElement && node.nodeName === entry.tag && (!entry.attributes[blockId] || node.getAttribute(blockId) === entry.attributes[blockId]);
549
+ }
550
+ function patchText(node, runs) {
551
+ const before = node.toDelta().map((run) => run.insert).join(""), after = runs.map((r) => r.text).join("");
552
+ let prefix = 0, suffix = 0;
553
+ while (prefix < before.length && prefix < after.length && before[prefix] === after[prefix]) prefix++;
554
+ while (suffix < before.length - prefix && suffix < after.length - prefix && before[before.length - 1 - suffix] === after[after.length - 1 - suffix]) suffix++;
555
+ const splitPair = (value, index) => index > 0 && /[\uD800-\uDBFF]/.test(value[index - 1]) && /[\uDC00-\uDFFF]/.test(value[index] ?? "");
556
+ while (prefix > 0 && (splitPair(before, prefix) || splitPair(after, prefix))) prefix--;
557
+ while (suffix > 0 && (splitPair(before, before.length - suffix) || splitPair(after, after.length - suffix))) suffix--;
558
+ if (before.length - prefix - suffix) node.delete(prefix, before.length - prefix - suffix);
559
+ if (after.length - prefix - suffix) node.insert(prefix, after.slice(prefix, after.length - suffix));
560
+ const existing = node.toDelta();
561
+ let offset = 0, oldIndex = 0, oldOffset = 0;
562
+ for (const run of runs) {
563
+ let remaining = run.text.length;
564
+ while (remaining) {
565
+ const old = existing[oldIndex];
566
+ const length = Math.min(remaining, old ? old.insert.length - oldOffset : remaining);
567
+ if (length <= 0) {
568
+ oldIndex++;
569
+ oldOffset = 0;
570
+ continue;
571
+ }
572
+ const changes = {};
573
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(old?.attributes ?? {}), ...Object.keys(run.marks)]))
574
+ if (old?.attributes?.[key] !== run.marks[key]) changes[key] = run.marks[key] ?? null;
575
+ if (Object.keys(changes).length) node.format(offset, length, changes);
576
+ offset += length;
577
+ remaining -= length;
578
+ oldOffset += length;
579
+ if (old && oldOffset === old.insert.length) {
580
+ oldIndex++;
581
+ oldOffset = 0;
582
+ }
583
+ }
584
+ }
585
+ }
586
+ function reconcile(parent, entries) {
587
+ if (entries.length > 5e3) throw new RangeError("Rich-text collaboration sibling limit exceeded");
588
+ const identified = new Set(entries.flatMap((entry) => entry.kind === "element" && entry.attributes[blockId] ? [entry.attributes[blockId]] : []));
589
+ let index = 0;
590
+ for (const entry of entries) {
591
+ let node = parent.get(index);
592
+ const reserved = node instanceof Y__namespace.XmlElement && entry.kind === "element" && !entry.attributes[blockId] && identified.has(node.getAttribute(blockId) ?? "");
593
+ if (!node || reserved || !compatible(node, entry)) {
594
+ let found = -1;
595
+ for (let look = index + 1; look < Math.min(parent.length, index + 33); look++)
596
+ if (!reserved && compatible(parent.get(look), entry)) {
597
+ found = look;
598
+ break;
599
+ }
600
+ if (found >= 0) {
601
+ parent.delete(index, found - index);
602
+ node = parent.get(index);
603
+ } else {
604
+ node = entry.kind === "text" ? new Y__namespace.XmlText() : new Y__namespace.XmlElement(entry.tag);
605
+ parent.insert(index, [node]);
606
+ }
607
+ }
608
+ if (entry.kind === "text" && node instanceof Y__namespace.XmlText) patchText(node, entry.runs);
609
+ else if (entry.kind === "element" && node instanceof Y__namespace.XmlElement) {
610
+ if (!node.getAttribute(blockId)) node.setAttribute(blockId, entry.attributes[blockId] ?? createBlockIdentity());
611
+ for (const name of Object.keys(node.getAttributes())) if (name !== blockId && !(name in entry.attributes)) node.removeAttribute(name);
612
+ for (const [name, value] of Object.entries(entry.attributes)) if (node.getAttribute(name) !== value) node.setAttribute(name, value);
613
+ reconcile(node, entry.children);
614
+ }
615
+ index++;
616
+ }
617
+ if (parent.length > index) parent.delete(index, parent.length - index);
618
+ }
619
+ function render(parent, depth = 0, identity = false) {
620
+ if (depth > 64) throw new RangeError("Rich-text collaboration depth exceeded");
621
+ return parent.toArray().map((node) => {
622
+ if (node instanceof Y__namespace.XmlText) return node.toDelta().map((run) => {
623
+ if (typeof run.insert !== "string") throw new Error("Rich-text collaboration embeds are unsupported");
624
+ let html = escape(run.insert);
625
+ for (const [tag, raw] of Object.entries(run.attributes ?? {}).sort(([a], [b]) => a.localeCompare(b))) {
626
+ if (!inline.has(tag) || typeof raw !== "string") throw new Error("Invalid collaboration inline mark");
627
+ const attributes = JSON.parse(raw);
628
+ if (!attributes || Array.isArray(attributes) || typeof attributes !== "object") throw new Error("Invalid inline attributes");
629
+ const attrs2 = Object.entries(attributes).map(([key, value]) => {
630
+ if (!/^[a-z][a-z0-9-]*$/.test(key) || typeof value !== "string") throw new Error("Invalid inline attribute");
631
+ return ` ${key}="${escape(value)}"`;
632
+ }).join("");
633
+ html = `<${tag}${attrs2}>${html}</${tag}>`;
634
+ }
635
+ return html;
636
+ }).join("");
637
+ if (!(node instanceof Y__namespace.XmlElement) || !/^(?:[a-z][a-z0-9]*|qb-video)$/.test(node.nodeName)) throw new Error("Invalid collaboration element");
638
+ const attrs = Object.entries(node.getAttributes()).filter(([key]) => identity || key !== blockId).map(([key, value]) => {
639
+ if (!/^[a-z][a-z0-9-]*$/.test(key) || typeof value !== "string") throw new Error("Invalid collaboration attribute");
640
+ return ` ${key}="${escape(value)}"`;
641
+ }).join("");
642
+ return `<${node.nodeName}${attrs}>${richTextVoidTags.some((tag) => tag === node.nodeName) ? "" : `${render(node, depth + 1, identity)}</${node.nodeName}>`}`;
643
+ }).join("");
644
+ }
645
+ function readRichTextCollaboration(document) {
646
+ const html = render(document.getXmlFragment("quickbuilder.rich-text"));
647
+ if (html.length > 1e6) throw new RangeError("Rich-text collaboration size exceeded");
648
+ const normalized = normalizeRichTextHtml(html);
649
+ richTextHtmlToViewTree(normalized);
650
+ return normalized;
651
+ }
652
+ function writeRichTextCollaboration(document, html, origin = null, options = {}) {
653
+ const content = parse(richTextHtmlToViewTree(html));
654
+ const tree = options.topLevelParagraphs ? content.map((entry) => entry.kind === "text" ? { kind: "element", tag: "p", attributes: {}, children: [entry] } : entry) : content;
655
+ const seen = /* @__PURE__ */ new Set();
656
+ const unique = (entries) => {
657
+ for (const entry of entries) if (entry.kind === "element") {
658
+ const id = entry.attributes[blockId];
659
+ if (id) {
660
+ if (seen.has(id)) delete entry.attributes[blockId];
661
+ else seen.add(id);
662
+ }
663
+ unique(entry.children);
664
+ }
665
+ };
666
+ unique(tree);
667
+ document.transact(() => reconcile(document.getXmlFragment("quickbuilder.rich-text"), tree), origin);
668
+ }
669
+ function createRichTextCollaborationBinding(document, options = {}) {
670
+ const origin = /* @__PURE__ */ Symbol("quickbuilder.rich-text.editor");
671
+ const fragment = document.getXmlFragment("quickbuilder.rich-text");
672
+ const undo = new Y__namespace.UndoManager(fragment, { trackedOrigins: /* @__PURE__ */ new Set([origin]), captureTimeout: 500 });
673
+ let disposed = false;
674
+ const listeners = /* @__PURE__ */ new Set();
675
+ const changed = () => {
676
+ for (const notify of listeners) notify();
677
+ };
678
+ fragment.observeDeep(changed);
679
+ for (const event of ["stack-item-added", "stack-item-popped", "stack-cleared", "stack-item-updated"]) undo.on(event, changed);
680
+ const active = () => {
681
+ if (disposed) throw new Error("Rich-text collaboration binding is disposed");
682
+ };
683
+ return {
684
+ getHtml: () => {
685
+ active();
686
+ return readRichTextCollaboration(document);
687
+ },
688
+ snapshot: () => {
689
+ active();
690
+ return { html: normalizeRichTextHtml(render(fragment, 0, true)), state: Y__namespace.encodeStateAsUpdate(document) };
691
+ },
692
+ setHtml: (html, baseState) => {
693
+ active();
694
+ if (!baseState) {
695
+ writeRichTextCollaboration(document, html, origin, options);
696
+ return;
697
+ }
698
+ const fork = new Y__namespace.Doc();
699
+ try {
700
+ Y__namespace.applyUpdate(fork, baseState);
701
+ const vector = Y__namespace.encodeStateVector(fork);
702
+ writeRichTextCollaboration(fork, html, origin, options);
703
+ Y__namespace.applyUpdate(document, Y__namespace.encodeStateAsUpdate(fork, vector), origin);
704
+ } finally {
705
+ fork.destroy();
706
+ }
707
+ },
708
+ subscribe: (notify) => {
709
+ active();
710
+ listeners.add(notify);
711
+ return () => {
712
+ listeners.delete(notify);
713
+ };
714
+ },
715
+ undo: () => {
716
+ active();
717
+ undo.undo();
718
+ },
719
+ redo: () => {
720
+ active();
721
+ undo.redo();
722
+ },
723
+ canUndo: () => undo.canUndo(),
724
+ canRedo: () => undo.canRedo(),
725
+ stopCapturing: () => {
726
+ active();
727
+ undo.stopCapturing();
728
+ },
729
+ dispose: () => {
730
+ if (!disposed) {
731
+ disposed = true;
732
+ fragment.unobserveDeep(changed);
733
+ listeners.clear();
734
+ for (const event of ["stack-item-added", "stack-item-popped", "stack-cleared", "stack-item-updated"]) undo.off(event, changed);
735
+ undo.destroy();
736
+ }
737
+ }
738
+ };
739
+ }
740
+ function readRichTextBlockSignatures(document) {
741
+ const blocks = /* @__PURE__ */ new Map();
742
+ for (const node of document.getXmlFragment("quickbuilder.rich-text").toArray()) {
743
+ if (!(node instanceof Y__namespace.XmlElement)) continue;
744
+ const id = node.getAttribute(blockId);
745
+ if (!id || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id)) continue;
746
+ if (blocks.has(id)) throw new Error("Duplicate rich-text collaboration block identity.");
747
+ blocks.set(id, node.toString());
748
+ }
749
+ if (blocks.size > 5e3) throw new RangeError("Rich-text block attribution limit exceeded.");
750
+ return blocks;
751
+ }
752
+
753
+ exports.createRichTextCollaborationBinding = createRichTextCollaborationBinding;
754
+ exports.readRichTextBlockSignatures = readRichTextBlockSignatures;
755
+ exports.readRichTextCollaboration = readRichTextCollaboration;
756
+ exports.writeRichTextCollaboration = writeRichTextCollaboration;
757
+ //# sourceMappingURL=collaboration.js.map
758
+ //# sourceMappingURL=collaboration.js.map