@abraca/dabra 2.90.0 → 2.92.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 (71) hide show
  1. package/package.json +5 -11
  2. package/src/AbracadabraBaseProvider.ts +0 -963
  3. package/src/AbracadabraClient.ts +0 -1960
  4. package/src/AbracadabraProvider.ts +0 -915
  5. package/src/AbracadabraWS.ts +0 -695
  6. package/src/BackgroundSyncManager.ts +0 -856
  7. package/src/BackgroundSyncPersistence.ts +0 -140
  8. package/src/ChatClient.ts +0 -314
  9. package/src/CloseEvents.ts +0 -49
  10. package/src/ContentManager.ts +0 -246
  11. package/src/CoverReconcile.ts +0 -168
  12. package/src/CryptoIdentityKeystore.ts +0 -754
  13. package/src/DeviceRegistrationService.ts +0 -257
  14. package/src/DocConverters.ts +0 -1859
  15. package/src/DocKeyManager.ts +0 -163
  16. package/src/DocTypes.ts +0 -628
  17. package/src/DocUtils.ts +0 -251
  18. package/src/DocumentCache.ts +0 -210
  19. package/src/DocumentManager.ts +0 -410
  20. package/src/E2EAbracadabraProvider.ts +0 -426
  21. package/src/E2EOfflineStore.ts +0 -55
  22. package/src/EncryptedChatClient.ts +0 -173
  23. package/src/EncryptedY.ts +0 -145
  24. package/src/EventEmitter.ts +0 -59
  25. package/src/FileBlobStore.ts +0 -569
  26. package/src/IdentityDoc.ts +0 -711
  27. package/src/IncomingMessage.ts +0 -63
  28. package/src/MessageReceiver.ts +0 -151
  29. package/src/MessageSender.ts +0 -22
  30. package/src/MetaManager.ts +0 -194
  31. package/src/MnemonicKeyDerivation.ts +0 -171
  32. package/src/NodeConnect.ts +0 -63
  33. package/src/NodeIdentity.ts +0 -378
  34. package/src/NotificationsClient.ts +0 -207
  35. package/src/OfflineStore.ts +0 -294
  36. package/src/OutgoingMessage.ts +0 -25
  37. package/src/OutgoingMessages/AuthenticationMessage.ts +0 -23
  38. package/src/OutgoingMessages/AwarenessMessage.ts +0 -41
  39. package/src/OutgoingMessages/CloseMessage.ts +0 -17
  40. package/src/OutgoingMessages/QueryAwarenessMessage.ts +0 -17
  41. package/src/OutgoingMessages/StatelessMessage.ts +0 -18
  42. package/src/OutgoingMessages/SubdocMessage.ts +0 -35
  43. package/src/OutgoingMessages/SyncStepOneMessage.ts +0 -25
  44. package/src/OutgoingMessages/SyncStepTwoMessage.ts +0 -25
  45. package/src/OutgoingMessages/UpdateMessage.ts +0 -20
  46. package/src/QueryClient.ts +0 -209
  47. package/src/RpcClient.ts +0 -659
  48. package/src/SchemaTypes.ts +0 -179
  49. package/src/SearchIndex.ts +0 -250
  50. package/src/ServerRegistry.ts +0 -220
  51. package/src/ServerReset.ts +0 -222
  52. package/src/TokenManager.ts +0 -337
  53. package/src/TreeManager.ts +0 -894
  54. package/src/TreeTimestamps.ts +0 -101
  55. package/src/auth.ts +0 -62
  56. package/src/awarenessStatesToArray.ts +0 -10
  57. package/src/index.ts +0 -219
  58. package/src/messageRecord.ts +0 -121
  59. package/src/sync/BroadcastChannelSync.ts +0 -235
  60. package/src/types.ts +0 -790
  61. package/src/webrtc/AbracadabraWebRTC.ts +0 -683
  62. package/src/webrtc/DataChannelRouter.ts +0 -179
  63. package/src/webrtc/DevicePairingChannel.ts +0 -496
  64. package/src/webrtc/E2EEChannel.ts +0 -195
  65. package/src/webrtc/FileTransferChannel.ts +0 -367
  66. package/src/webrtc/ManualSignaling.ts +0 -204
  67. package/src/webrtc/PeerConnection.ts +0 -133
  68. package/src/webrtc/SignalingSocket.ts +0 -378
  69. package/src/webrtc/YjsDataChannel.ts +0 -203
  70. package/src/webrtc/index.ts +0 -26
  71. package/src/webrtc/types.ts +0 -177
@@ -1,1859 +0,0 @@
1
- /**
2
- * Document content converters — markdown ↔ Y.js.
3
- *
4
- * Canonical implementations for converting between Markdown text and TipTap-
5
- * compatible Y.XmlFragment structures. Previously lived in
6
- * `mcp/converters/` — now the authoritative home is the provider package so
7
- * any consumer of `@abraca/dabra` can use them without pulling in MCP deps.
8
- */
9
- import * as Y from "yjs";
10
- import type { PageMeta } from "./DocTypes.ts";
11
-
12
- // ══════════════════════════════════════════════════════════════════════════════
13
- // Y.XmlFragment → Markdown (yjsToMarkdown)
14
- // ══════════════════════════════════════════════════════════════════════════════
15
-
16
- // ── Inline text serialization ────────────────────────────────────────────────
17
-
18
- function deltaToMarkdown(
19
- delta: { insert: string; attributes?: Record<string, any> }[],
20
- ): string {
21
- return delta
22
- .map((op) => {
23
- let text = op.insert as string;
24
- if (!op.attributes) return text;
25
-
26
- const a = op.attributes;
27
-
28
- if (a.code) text = `\`${text}\``;
29
- if (a.bold) text = `**${text}**`;
30
- if (a.italic) text = `*${text}*`;
31
- if (a.strike) text = `~~${text}~~`;
32
- if (a.link?.href) text = `[${text}](${a.link.href})`;
33
- if (a.badge) text = `:badge[${a.badge.label || text}]`;
34
- if (a.kbd) text = `:kbd{value="${a.kbd.value || text}"}`;
35
- if (a.proseIcon) text = `:icon{name="${a.proseIcon.name}"}`;
36
-
37
- return text;
38
- })
39
- .join("");
40
- }
41
-
42
- function xmlTextToMarkdown(xmlText: Y.XmlText): string {
43
- const delta = xmlText.toDelta();
44
- return deltaToMarkdown(delta);
45
- }
46
-
47
- function elementTextContent(el: Y.XmlElement | Y.XmlFragment): string {
48
- const parts: string[] = [];
49
- for (const child of el.toArray()) {
50
- if (child instanceof Y.XmlText) {
51
- parts.push(xmlTextToMarkdown(child));
52
- } else if (child instanceof Y.XmlElement) {
53
- if (child.nodeName === "docLink") {
54
- const docId = child.getAttribute("docId");
55
- if (docId) parts.push(`[[${docId}]]`);
56
- continue;
57
- }
58
- parts.push(elementTextContent(child));
59
- }
60
- }
61
- return parts.join("");
62
- }
63
-
64
- // ── Block serialization ──────────────────────────────────────────────────────
65
-
66
- function serializeElement(el: Y.XmlElement, indent = ""): string {
67
- const name = el.nodeName;
68
-
69
- switch (name) {
70
- case "documentHeader":
71
- case "documentMeta":
72
- return "";
73
-
74
- case "heading": {
75
- const level = Number(el.getAttribute("level")) || 1;
76
- const prefix = "#".repeat(level);
77
- return `${prefix} ${elementTextContent(el)}`;
78
- }
79
-
80
- case "paragraph":
81
- return elementTextContent(el);
82
-
83
- case "bulletList":
84
- return serializeList(el, "bullet", indent);
85
-
86
- case "orderedList":
87
- return serializeList(el, "ordered", indent);
88
-
89
- case "taskList":
90
- return serializeTaskList(el, indent);
91
-
92
- case "codeBlock": {
93
- const lang = el.getAttribute("language") || "";
94
- const code = elementTextContent(el);
95
- return `\`\`\`${lang}\n${code}\n\`\`\``;
96
- }
97
-
98
- case "blockquote": {
99
- const lines: string[] = [];
100
- for (let i = 0; i < el.length; i++) {
101
- const child = el.get(i);
102
- if (child instanceof Y.XmlElement) {
103
- lines.push(serializeElement(child, indent));
104
- }
105
- }
106
- return lines.map((l) => `> ${l}`).join("\n");
107
- }
108
-
109
- case "horizontalRule":
110
- return "---";
111
-
112
- case "table":
113
- return serializeTable(el);
114
-
115
- case "docEmbed": {
116
- const docId = el.getAttribute("docId");
117
- if (!docId) return "";
118
- const seamlessAttr = el.getAttribute("seamless");
119
- const seamless =
120
- (seamlessAttr as unknown) === true || seamlessAttr === "true";
121
- return seamless ? `![[${docId}]]{seamless}` : `![[${docId}]]`;
122
- }
123
-
124
- case "svgEmbed": {
125
- const svg = el.getAttribute("svg") || "";
126
- const svgTitle = el.getAttribute("title") || "";
127
- if (!svg) return "";
128
- return `\`\`\`svg${svgTitle ? ` ${svgTitle}` : ""}\n${svg}\n\`\`\``;
129
- }
130
-
131
- case "image": {
132
- const src = el.getAttribute("src") || "";
133
- const alt = el.getAttribute("alt") || "";
134
- const w = el.getAttribute("width");
135
- const h = el.getAttribute("height");
136
- let attrs = "";
137
- if (w || h) {
138
- const imgParts: string[] = [];
139
- if (w) imgParts.push(`width="${w}"`);
140
- if (h) imgParts.push(`height="${h}"`);
141
- attrs = `{${imgParts.join(" ")}}`;
142
- }
143
- return `![${alt}](${src})${attrs}`;
144
- }
145
-
146
- case "callout": {
147
- const type = el.getAttribute("type") || "note";
148
- const inner = serializeChildren(el, indent);
149
- return `::${type}\n${inner}\n::`;
150
- }
151
-
152
- case "collapsible": {
153
- const label = el.getAttribute("label") || "Details";
154
- const open = el.getAttribute("open");
155
- const props: string[] = [`label="${label}"`];
156
- if ((open as unknown) === true || open === "true") props.push('open="true"');
157
- const inner = serializeChildren(el, indent);
158
- return `::collapsible{${props.join(" ")}}\n${inner}\n::`;
159
- }
160
-
161
- case "steps": {
162
- const inner = serializeChildren(el, indent);
163
- return `::steps\n${inner}\n::`;
164
- }
165
-
166
- case "card": {
167
- const title = el.getAttribute("title") || "";
168
- const icon = el.getAttribute("icon") || "";
169
- const to = el.getAttribute("to") || "";
170
- const props: string[] = [];
171
- if (title) props.push(`title="${title}"`);
172
- if (icon) props.push(`icon="${icon}"`);
173
- if (to) props.push(`to="${to}"`);
174
- const inner = serializeChildren(el, indent);
175
- return `::card{${props.join(" ")}}\n${inner}\n::`;
176
- }
177
-
178
- case "cardGroup": {
179
- const inner = serializeChildren(el, indent);
180
- return `::card-group\n${inner}\n::`;
181
- }
182
-
183
- case "codeCollapse": {
184
- const inner = serializeChildren(el, indent);
185
- return `::code-collapse\n${inner}\n::`;
186
- }
187
-
188
- case "codeGroup": {
189
- const inner = serializeChildren(el, indent);
190
- return `::code-group\n${inner}\n::`;
191
- }
192
-
193
- case "codePreview": {
194
- const inner = serializeChildren(el, indent);
195
- return `::code-preview\n${inner}\n::`;
196
- }
197
-
198
- case "codeTree": {
199
- const files = el.getAttribute("files") || "[]";
200
- return `::code-tree{files="${files}"}\n::`;
201
- }
202
-
203
- case "accordion":
204
- return serializeSlottedComponent(
205
- el,
206
- "accordion",
207
- "accordionItem",
208
- "item",
209
- );
210
-
211
- case "tabs":
212
- return serializeSlottedComponent(el, "tabs", "tabsItem", "tab");
213
-
214
- case "field": {
215
- const fieldName = el.getAttribute("name") || "";
216
- const fieldType = el.getAttribute("type") || "string";
217
- const required = el.getAttribute("required");
218
- const props: string[] = [];
219
- if (fieldName) props.push(`name="${fieldName}"`);
220
- props.push(`type="${fieldType}"`);
221
- if ((required as unknown) === true || required === "true")
222
- props.push('required="true"');
223
- const inner = serializeChildren(el, indent);
224
- return `::field{${props.join(" ")}}\n${inner}\n::`;
225
- }
226
-
227
- case "fieldGroup": {
228
- const inner = serializeChildren(el, indent);
229
- return `::field-group\n${inner}\n::`;
230
- }
231
-
232
- default: {
233
- return serializeChildren(el, indent);
234
- }
235
- }
236
- }
237
-
238
- function serializeList(
239
- el: Y.XmlElement,
240
- type: "bullet" | "ordered",
241
- indent: string,
242
- ): string {
243
- const lines: string[] = [];
244
- const items = el.toArray();
245
- for (let i = 0; i < items.length; i++) {
246
- const item = items[i];
247
- if (
248
- item instanceof Y.XmlElement &&
249
- item.nodeName === "listItem"
250
- ) {
251
- const prefix = type === "bullet" ? "- " : `${i + 1}. `;
252
- const content = elementTextContent(item);
253
- lines.push(`${indent}${prefix}${content}`);
254
- }
255
- }
256
- return lines.join("\n");
257
- }
258
-
259
- function serializeTaskList(el: Y.XmlElement, indent: string): string {
260
- const lines: string[] = [];
261
- for (const item of el.toArray()) {
262
- if (
263
- item instanceof Y.XmlElement &&
264
- item.nodeName === "taskItem"
265
- ) {
266
- const checked = item.getAttribute("checked");
267
- const marker =
268
- (checked as unknown) === true || checked === "true" ? "[x]" : "[ ]";
269
- const content = elementTextContent(item);
270
- lines.push(`${indent}- ${marker} ${content}`);
271
- }
272
- }
273
- return lines.join("\n");
274
- }
275
-
276
- function serializeTable(el: Y.XmlElement): string {
277
- const rows: string[][] = [];
278
-
279
- for (const row of el.toArray()) {
280
- if (
281
- !(row instanceof Y.XmlElement) ||
282
- row.nodeName !== "tableRow"
283
- )
284
- continue;
285
-
286
- const cells: string[] = [];
287
- for (const cell of row.toArray()) {
288
- if (cell instanceof Y.XmlElement) {
289
- cells.push(elementTextContent(cell));
290
- }
291
- }
292
- rows.push(cells);
293
- }
294
-
295
- if (!rows.length) return "";
296
-
297
- const headerRow = rows[0]!;
298
- const lines = [`| ${headerRow.join(" | ")} |`];
299
-
300
- // Separator
301
- lines.push(`| ${headerRow.map(() => "---").join(" | ")} |`);
302
-
303
- // Data rows
304
- for (let i = 1; i < rows.length; i++) {
305
- lines.push(`| ${rows[i]!.join(" | ")} |`);
306
- }
307
-
308
- return lines.join("\n");
309
- }
310
-
311
- function serializeSlottedComponent(
312
- el: Y.XmlElement,
313
- componentName: string,
314
- childNodeName: string,
315
- slotName: string,
316
- ): string {
317
- const parts: string[] = [`::${componentName}`];
318
-
319
- for (let i = 0; i < el.length; i++) {
320
- const child = el.get(i);
321
- if (
322
- !(child instanceof Y.XmlElement) ||
323
- child.nodeName !== childNodeName
324
- )
325
- continue;
326
-
327
- const label = child.getAttribute("label") || `Item ${i + 1}`;
328
- const icon = child.getAttribute("icon") || "";
329
- const props: string[] = [`label="${label}"`];
330
- if (icon) props.push(`icon="${icon}"`);
331
- parts.push(`#${slotName}{${props.join(" ")}}`);
332
-
333
- const inner = serializeChildren(child, "");
334
- if (inner) parts.push(inner);
335
- }
336
-
337
- parts.push("::");
338
- return parts.join("\n");
339
- }
340
-
341
- function serializeChildren(
342
- el: Y.XmlElement | Y.XmlFragment,
343
- indent: string,
344
- ): string {
345
- const parts: string[] = [];
346
- for (const child of el.toArray()) {
347
- if (child instanceof Y.XmlElement) {
348
- const serialized = serializeElement(child, indent);
349
- if (serialized) parts.push(serialized);
350
- } else if (child instanceof Y.XmlText) {
351
- const text = xmlTextToMarkdown(child);
352
- if (text) parts.push(text);
353
- }
354
- }
355
- return parts.join("\n\n");
356
- }
357
-
358
- // ── Public: Y.js → Markdown ─────────────────────────────────────────────────
359
-
360
- /**
361
- * Converts a Y.XmlFragment (TipTap document) to markdown.
362
- * Extracts the title from the documentHeader element.
363
- *
364
- * @returns `{ title, markdown }` where title is the H1/header text
365
- */
366
- export function yjsToMarkdown(
367
- fragment: Y.XmlFragment,
368
- ): { title: string; markdown: string } {
369
- let title = "Untitled";
370
- const bodyParts: string[] = [];
371
-
372
- // Iterate via toArray() (O(n)). Indexed fragment.get(i) is an O(i)
373
- // linked-list walk, which made this top-level loop O(n²) on large docs.
374
- for (const child of fragment.toArray()) {
375
- if (!(child instanceof Y.XmlElement)) continue;
376
-
377
- if (child.nodeName === "documentHeader") {
378
- title = elementTextContent(child) || "Untitled";
379
- continue;
380
- }
381
-
382
- if (child.nodeName === "documentMeta") {
383
- continue;
384
- }
385
-
386
- const serialized = serializeElement(child);
387
- if (serialized !== "") {
388
- bodyParts.push(serialized);
389
- }
390
- }
391
-
392
- return { title, markdown: bodyParts.join("\n\n") };
393
- }
394
-
395
- // ══════════════════════════════════════════════════════════════════════════════
396
- // Markdown → Y.XmlFragment (populateYDocFromMarkdown)
397
- // ══════════════════════════════════════════════════════════════════════════════
398
-
399
- // ── Filename → readable label ────────────────────────────────────────────────
400
-
401
- export function filenameToLabel(raw: string): string {
402
- const base = raw.replace(/\.[^.]+$/, "");
403
- const spaced = base.replace(/([a-z])([A-Z])/g, "$1 $2");
404
- const clean = spaced
405
- .replace(/[-_.]+/g, " ")
406
- .replace(/\s+/g, " ")
407
- .trim();
408
- return clean.charAt(0).toUpperCase() + clean.slice(1);
409
- }
410
-
411
- // ── YAML frontmatter parser ──────────────────────────────────────────────────
412
-
413
- export interface FrontmatterResult {
414
- title?: string;
415
- meta: Partial<PageMeta>;
416
- body: string;
417
- }
418
-
419
- function parseInlineArray(raw: string): string[] {
420
- return raw
421
- .slice(1, -1)
422
- .split(",")
423
- .map((s) => s.trim())
424
- .filter(Boolean);
425
- }
426
-
427
- export function parseFrontmatter(markdown: string): FrontmatterResult {
428
- const noResult: FrontmatterResult = { meta: {}, body: markdown };
429
-
430
- const match = markdown.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
431
- if (!match) return noResult;
432
-
433
- const yamlBlock = match[1]!;
434
- const body = markdown.slice(match[0].length);
435
-
436
- const raw: Record<string, string | string[]> = {};
437
- const lines = yamlBlock.split("\n");
438
- let i = 0;
439
- while (i < lines.length) {
440
- const line = lines[i]!;
441
- const blockSeqKey = line.match(/^(\w[\w-]*):\s*$/);
442
- if (
443
- blockSeqKey &&
444
- i + 1 < lines.length &&
445
- /^\s+-\s/.test(lines[i + 1]!)
446
- ) {
447
- const key = blockSeqKey[1]!;
448
- const items: string[] = [];
449
- i++;
450
- while (i < lines.length && /^\s+-\s/.test(lines[i]!)) {
451
- items.push(lines[i]!.replace(/^\s+-\s/, "").trim());
452
- i++;
453
- }
454
- raw[key] = items;
455
- continue;
456
- }
457
- const kvMatch = line.match(/^(\w[\w-]*):\s*(.*)$/);
458
- if (kvMatch) {
459
- const key = kvMatch[1]!;
460
- const val = kvMatch[2]!.trim();
461
- if (val.startsWith("[") && val.endsWith("]")) {
462
- raw[key] = parseInlineArray(val);
463
- } else {
464
- raw[key] = val;
465
- }
466
- }
467
- i++;
468
- }
469
-
470
- const meta: Partial<PageMeta> = {};
471
-
472
- const getStr = (keys: string[]): string | undefined => {
473
- for (const k of keys) {
474
- const v = raw[k];
475
- if (typeof v === "string" && v) return v;
476
- }
477
- };
478
-
479
- if (raw["tags"])
480
- meta.tags = Array.isArray(raw["tags"])
481
- ? raw["tags"]
482
- : [raw["tags"] as string];
483
- const color = getStr(["color"]);
484
- if (color) meta.color = color;
485
- const icon = getStr(["icon"]);
486
- if (icon) meta.icon = icon;
487
- const status = getStr(["status"]);
488
- if (status) meta.status = status;
489
-
490
- const priorityRaw = getStr(["priority"]);
491
- if (priorityRaw !== undefined) {
492
- const map: Record<string, number> = {
493
- low: 1,
494
- medium: 2,
495
- high: 3,
496
- urgent: 4,
497
- };
498
- meta.priority =
499
- map[priorityRaw.toLowerCase()] ?? (Number(priorityRaw) || 0);
500
- }
501
-
502
- const checkedRaw = raw["checked"] ?? raw["done"];
503
- if (checkedRaw !== undefined)
504
- meta.checked = checkedRaw === "true" || (checkedRaw as unknown) === true;
505
-
506
- const dateStart = getStr(["date", "created"]);
507
- if (dateStart) meta.dateStart = dateStart;
508
- const dateEnd = getStr(["due"]);
509
- if (dateEnd) meta.dateEnd = dateEnd;
510
-
511
- const subtitle = getStr(["description", "subtitle"]);
512
- if (subtitle) meta.subtitle = subtitle;
513
- const url = getStr(["url"]);
514
- if (url) meta.url = url;
515
- const email = getStr(["email"]);
516
- if (email) meta.email = email;
517
- const phone = getStr(["phone"]);
518
- if (phone) meta.phone = phone;
519
-
520
- const ratingRaw = getStr(["rating"]);
521
- if (ratingRaw !== undefined) {
522
- const n = Number(ratingRaw);
523
- if (!Number.isNaN(n)) meta.rating = Math.min(5, Math.max(0, n));
524
- }
525
-
526
- // Datetime fields
527
- const datetimeStart = getStr(["datetimeStart"]);
528
- if (datetimeStart) meta.datetimeStart = datetimeStart;
529
- const datetimeEnd = getStr(["datetimeEnd"]);
530
- if (datetimeEnd) meta.datetimeEnd = datetimeEnd;
531
- const allDayRaw = raw["allDay"];
532
- if (allDayRaw !== undefined)
533
- meta.allDay = allDayRaw === "true" || (allDayRaw as unknown) === true;
534
-
535
- // Geo fields
536
- const geoLatRaw = getStr(["geoLat"]);
537
- if (geoLatRaw !== undefined) {
538
- const n = Number(geoLatRaw);
539
- if (!Number.isNaN(n)) meta.geoLat = n;
540
- }
541
- const geoLngRaw = getStr(["geoLng"]);
542
- if (geoLngRaw !== undefined) {
543
- const n = Number(geoLngRaw);
544
- if (!Number.isNaN(n)) meta.geoLng = n;
545
- }
546
- const geoType = getStr(["geoType"]);
547
- if (
548
- geoType &&
549
- (geoType === "marker" || geoType === "line" || geoType === "measure")
550
- ) {
551
- meta.geoType = geoType;
552
- }
553
- const geoDescription = getStr(["geoDescription"]);
554
- if (geoDescription) meta.geoDescription = geoDescription;
555
-
556
- // Numeric fields
557
- const numberRaw = getStr(["number"]);
558
- if (numberRaw !== undefined) {
559
- const n = Number(numberRaw);
560
- if (!Number.isNaN(n)) meta.number = n;
561
- }
562
- const unit = getStr(["unit"]);
563
- if (unit) meta.unit = unit;
564
-
565
- // Note
566
- const note = getStr(["note"]);
567
- if (note) meta.note = note;
568
-
569
- const title = typeof raw["title"] === "string" ? raw["title"] : undefined;
570
-
571
- return { title, meta, body };
572
- }
573
-
574
- // ── Inline token parsing ─────────────────────────────────────────────────────
575
-
576
- interface InlineToken {
577
- text: string;
578
- attrs?: Record<string, unknown>;
579
- /** If set, emit an inline Y.XmlElement with this nodeName instead of text+marks. */
580
- node?: string;
581
- /** Attributes for the inline node (when node is set). */
582
- nodeAttrs?: Record<string, string>;
583
- }
584
-
585
- function parseMdcProps(
586
- propsStr: string | undefined,
587
- ): Record<string, string> {
588
- if (!propsStr) return {};
589
- const result: Record<string, string> = {};
590
- const re = /(\w[\w-]*)="([^"]*)"/g;
591
- let m: RegExpExecArray | null;
592
- while ((m = re.exec(propsStr)) !== null) {
593
- result[m[1]!] = m[2]!;
594
- }
595
- return result;
596
- }
597
-
598
- function parseInline(text: string): InlineToken[] {
599
- const stripped = text
600
- .replace(/\{lang="[^"]*"\}/g, "")
601
- .replace(
602
- /:(?!badge|icon|kbd)(\w[\w-]*)\[([^\]]*)\](\{[^}]*\})?/g,
603
- "$2",
604
- )
605
- .replace(/:(?!badge|icon|kbd)(\w[\w-]*)(\{[^}]*\})/g, "");
606
-
607
- const tokens: InlineToken[] = [];
608
- const re =
609
- /:badge\[([^\]]*)\](\{[^}]*\})?|:icon\{([^}]*)\}|:kbd\{([^}]*)\}|!?\[\[([^\]|]+?)(?:\|([^\]]+?))?\]\]|~~(.+?)~~|\*\*(.+?)\*\*|\*(.+?)\*|_(.+?)_|`(.+?)`|\[(.+?)\]\((.+?)\)/g;
610
- let lastIndex = 0;
611
- let match: RegExpExecArray | null;
612
-
613
- while ((match = re.exec(stripped)) !== null) {
614
- if (match.index > lastIndex) {
615
- tokens.push({ text: stripped.slice(lastIndex, match.index) });
616
- }
617
- if (match[1] !== undefined) {
618
- const badgeProps = parseMdcProps(match[2]);
619
- tokens.push({
620
- text: match[1] || "Badge",
621
- attrs: {
622
- badge: {
623
- label: match[1] || "Badge",
624
- color: badgeProps["color"] || "neutral",
625
- variant: badgeProps["variant"] || "subtle",
626
- },
627
- },
628
- });
629
- } else if (match[3] !== undefined) {
630
- const iconProps = parseMdcProps(`{${match[3]}}`);
631
- tokens.push({
632
- text: "\u200B",
633
- attrs: {
634
- proseIcon: {
635
- name: iconProps["name"] || "i-lucide-star",
636
- },
637
- },
638
- });
639
- } else if (match[4] !== undefined) {
640
- const kbdProps = parseMdcProps(`{${match[4]}}`);
641
- tokens.push({
642
- text: kbdProps["value"] || "",
643
- attrs: { kbd: { value: kbdProps["value"] || "" } },
644
- });
645
- } else if (match[5] !== undefined) {
646
- tokens.push({
647
- text: "",
648
- node: "docLink",
649
- nodeAttrs: { docId: match[5]! },
650
- });
651
- } else if (match[7] !== undefined) {
652
- tokens.push({ text: match[7], attrs: { strike: true } });
653
- } else if (match[8] !== undefined) {
654
- tokens.push({ text: match[8], attrs: { bold: true } });
655
- } else if (match[9] !== undefined) {
656
- tokens.push({ text: match[9], attrs: { italic: true } });
657
- } else if (match[10] !== undefined) {
658
- tokens.push({ text: match[10], attrs: { italic: true } });
659
- } else if (match[11] !== undefined) {
660
- tokens.push({ text: match[11], attrs: { code: true } });
661
- } else if (match[12] !== undefined && match[13] !== undefined) {
662
- tokens.push({
663
- text: match[12],
664
- attrs: { link: { href: match[13] } },
665
- });
666
- }
667
- lastIndex = match.index + match[0].length;
668
- }
669
-
670
- if (lastIndex < stripped.length) {
671
- tokens.push({ text: stripped.slice(lastIndex) });
672
- }
673
- return tokens.filter((t) => t.node || t.text.length > 0);
674
- }
675
-
676
- // ── Block-level parser ───────────────────────────────────────────────────────
677
-
678
- interface TaskItem {
679
- text: string;
680
- checked: boolean;
681
- }
682
-
683
- type Block =
684
- | { type: "heading"; level: number; text: string }
685
- | { type: "paragraph"; text: string }
686
- | { type: "bulletList"; items: string[] }
687
- | { type: "orderedList"; items: string[] }
688
- | { type: "taskList"; items: TaskItem[] }
689
- | { type: "codeBlock"; lang: string; code: string }
690
- | { type: "blockquote"; lines: string[] }
691
- | { type: "table"; headerRow: string[]; dataRows: string[][] }
692
- | { type: "hr" }
693
- | { type: "callout"; calloutType: string; innerBlocks: Block[] }
694
- | {
695
- type: "collapsible";
696
- label: string;
697
- open: boolean;
698
- innerBlocks: Block[];
699
- }
700
- | { type: "steps"; innerBlocks: Block[] }
701
- | {
702
- type: "card";
703
- title: string;
704
- icon: string;
705
- to: string;
706
- innerBlocks: Block[];
707
- }
708
- | { type: "cardGroup"; cards: Block[] }
709
- | { type: "codeCollapse"; codeBlocks: Block[] }
710
- | { type: "codeGroup"; codeBlocks: Block[] }
711
- | { type: "codePreview"; innerBlocks: Block[]; codeBlocks: Block[] }
712
- | { type: "codeTree"; files: string }
713
- | {
714
- type: "accordion";
715
- items: { label: string; icon: string; innerBlocks: Block[] }[];
716
- }
717
- | {
718
- type: "tabs";
719
- items: { label: string; icon: string; innerBlocks: Block[] }[];
720
- }
721
- | {
722
- type: "field";
723
- name: string;
724
- fieldType: string;
725
- required: boolean;
726
- innerBlocks: Block[];
727
- }
728
- | { type: "fieldGroup"; fields: Block[] }
729
- | {
730
- type: "image";
731
- src: string;
732
- alt: string;
733
- width?: string;
734
- height?: string;
735
- }
736
- | { type: "docEmbed"; docId: string; seamless?: boolean }
737
- | { type: "svgEmbed"; svg: string; title: string };
738
-
739
- function parseTableRow(line: string): string[] {
740
- const parts = line.split("|");
741
- return parts.slice(1, parts.length - 1).map((c) => c.trim());
742
- }
743
-
744
- function isTableSeparator(line: string): boolean {
745
- return /^\|[\s|:-]+\|$/.test(line.trim());
746
- }
747
-
748
- function extractFencedCode(lines: string[]): Block[] {
749
- const result: Block[] = [];
750
- let i = 0;
751
- while (i < lines.length) {
752
- const line = lines[i]!;
753
- const fenceMatch = line.match(/^(`{3,})(\w*)/);
754
- if (fenceMatch) {
755
- const fence = fenceMatch[1]!;
756
- const lang = fenceMatch[2] ?? "";
757
- const codeLines: string[] = [];
758
- i++;
759
- while (i < lines.length && !lines[i]!.startsWith(fence)) {
760
- codeLines.push(lines[i]!);
761
- i++;
762
- }
763
- i++;
764
- result.push({
765
- type: "codeBlock",
766
- lang,
767
- code: codeLines.join("\n"),
768
- });
769
- continue;
770
- }
771
- i++;
772
- }
773
- return result;
774
- }
775
-
776
- function parseMdcChildren(
777
- innerLines: string[],
778
- slotPrefix: string,
779
- ): { label: string; icon: string; innerBlocks: Block[] }[] {
780
- const items: { label: string; icon: string; lines: string[] }[] = [];
781
- let current: { label: string; icon: string; lines: string[] } | null =
782
- null;
783
- const slotRe = new RegExp(`^#${slotPrefix}(\\{[^}]*\\})?\\s*$`);
784
-
785
- for (const line of innerLines) {
786
- const slotMatch = line.match(slotRe);
787
- if (slotMatch) {
788
- if (current) items.push(current);
789
- const props = parseMdcProps(slotMatch[1]);
790
- current = {
791
- label:
792
- props["label"] ||
793
- props["title"] ||
794
- `Item ${items.length + 1}`,
795
- icon: props["icon"] || "",
796
- lines: [],
797
- };
798
- continue;
799
- }
800
- if (current) {
801
- current.lines.push(line);
802
- } else {
803
- if (!items.length && !current) {
804
- current = { label: "Item 1", icon: "", lines: [line] };
805
- }
806
- }
807
- }
808
- if (current) items.push(current);
809
-
810
- return items.map((item) => ({
811
- label: item.label,
812
- icon: item.icon,
813
- innerBlocks: parseBlocks(item.lines.join("\n")),
814
- }));
815
- }
816
-
817
- const TASK_RE = /^[-*+]\s+\[([ xX])\]\s+(.*)/;
818
-
819
- function parseBlocks(markdown: string): Block[] {
820
- const rawLines = markdown.split("\n");
821
- let firstContentLine = 0;
822
- while (firstContentLine < rawLines.length) {
823
- const l = rawLines[firstContentLine]!;
824
- if (l.trim() === "" || /^import\s/.test(l) || /^export\s/.test(l)) {
825
- firstContentLine++;
826
- } else {
827
- break;
828
- }
829
- }
830
- const stripped = rawLines.slice(firstContentLine).join("\n");
831
-
832
- const blocks: Block[] = [];
833
- const lines = stripped.split("\n");
834
- let i = 0;
835
-
836
- while (i < lines.length) {
837
- const line = lines[i]!;
838
-
839
- const fenceBlockMatch = line.match(/^(`{3,})(.*)$/);
840
- if (fenceBlockMatch) {
841
- const fence = fenceBlockMatch[1]!;
842
- const lang = fenceBlockMatch[2]!
843
- .trim()
844
- .replace(/\{[^}]*\}$/, "")
845
- .replace(/\s*\[.*\]$/, "")
846
- .trim();
847
- const codeLines: string[] = [];
848
- i++;
849
- while (i < lines.length && !lines[i]!.startsWith(fence)) {
850
- codeLines.push(lines[i]!);
851
- i++;
852
- }
853
- i++;
854
- if (lang === "svg" || lang.startsWith("svg ")) {
855
- const svgTitle =
856
- lang === "svg" ? "" : lang.slice(4).trim();
857
- blocks.push({
858
- type: "svgEmbed",
859
- svg: codeLines.join("\n"),
860
- title: svgTitle,
861
- });
862
- } else {
863
- blocks.push({
864
- type: "codeBlock",
865
- lang,
866
- code: codeLines.join("\n"),
867
- });
868
- }
869
- continue;
870
- }
871
-
872
- const headingMatch = line.match(/^(#{1,6})\s+(.*)/);
873
- if (headingMatch) {
874
- blocks.push({
875
- type: "heading",
876
- level: headingMatch[1]!.length,
877
- text: headingMatch[2]!.trim(),
878
- });
879
- i++;
880
- continue;
881
- }
882
-
883
- if (/^[-*_]{3,}\s*$/.test(line)) {
884
- blocks.push({ type: "hr" });
885
- i++;
886
- continue;
887
- }
888
-
889
- const docEmbedMatch = line.match(
890
- /^!\[\[([^\]|]+?)(?:\|[^\]]*?)?\]\](\{[^}]*\})?\s*$/,
891
- );
892
- if (docEmbedMatch) {
893
- const props = parseMdcProps(docEmbedMatch[2]);
894
- const seamless =
895
- "seamless" in props ||
896
- props["seamless"] === "true" ||
897
- /\{[^}]*\bseamless\b[^}]*\}/.test(docEmbedMatch[2] ?? "");
898
- blocks.push({
899
- type: "docEmbed",
900
- docId: docEmbedMatch[1]!,
901
- seamless: seamless || undefined,
902
- });
903
- i++;
904
- continue;
905
- }
906
-
907
- const imgMatch = line.match(
908
- /^!\[([^\]]*)\]\(([^)]+)\)(\{[^}]*\})?\s*$/,
909
- );
910
- if (imgMatch) {
911
- const alt = imgMatch[1] ?? "";
912
- const src = imgMatch[2] ?? "";
913
- const attrs = parseMdcProps(imgMatch[3]);
914
- blocks.push({
915
- type: "image",
916
- src,
917
- alt,
918
- width: attrs["width"],
919
- height: attrs["height"],
920
- });
921
- i++;
922
- continue;
923
- }
924
-
925
- if (line.startsWith("> ") || line === ">") {
926
- const bqLines: string[] = [];
927
- while (
928
- i < lines.length &&
929
- (lines[i]!.startsWith("> ") || lines[i] === ">")
930
- ) {
931
- bqLines.push(lines[i]!.replace(/^>\s?/, ""));
932
- i++;
933
- }
934
- blocks.push({ type: "blockquote", lines: bqLines });
935
- continue;
936
- }
937
-
938
- if (/^\s*\|/.test(line)) {
939
- const tableLines: string[] = [];
940
- while (i < lines.length && /^\s*\|/.test(lines[i]!)) {
941
- tableLines.push(lines[i]!);
942
- i++;
943
- }
944
- if (
945
- tableLines.length >= 2 &&
946
- isTableSeparator(tableLines[1]!)
947
- ) {
948
- const headerRow = parseTableRow(tableLines[0]!);
949
- const dataRows = tableLines
950
- .slice(2)
951
- .filter((l) => !isTableSeparator(l))
952
- .map(parseTableRow);
953
- blocks.push({ type: "table", headerRow, dataRows });
954
- } else {
955
- for (const l of tableLines)
956
- blocks.push({ type: "paragraph", text: l });
957
- }
958
- continue;
959
- }
960
-
961
- const MDC_OPEN = /^\s*(:{2,})(\w[\w-]*)(\{[^}]*\})?\s*$/;
962
- if (MDC_OPEN.test(line)) {
963
- const colons =
964
- line.match(/^\s*(:+)/)?.[1]?.length ?? 2;
965
- const componentName =
966
- line.match(/^\s*:{2,}(\w[\w-]*)/)?.[1] ?? "";
967
- const innerLines: string[] = [];
968
- i++;
969
- while (i < lines.length) {
970
- const l = lines[i]!;
971
- if (
972
- new RegExp(`^\\s*:{${colons}}\\s*$`).test(l)
973
- ) {
974
- i++;
975
- break;
976
- }
977
- const innerFence = l.match(/^(\s*`{3,})/);
978
- if (innerFence) {
979
- const fenceStr = innerFence[1]!.trimStart();
980
- innerLines.push(l);
981
- i++;
982
- while (
983
- i < lines.length &&
984
- !lines[i]!.trimStart().startsWith(fenceStr)
985
- ) {
986
- innerLines.push(lines[i]!);
987
- i++;
988
- }
989
- if (i < lines.length) {
990
- innerLines.push(lines[i]!);
991
- i++;
992
- }
993
- continue;
994
- }
995
- innerLines.push(l);
996
- i++;
997
- }
998
-
999
- const nonBlank = innerLines.filter(
1000
- (l) => l.trim().length > 0,
1001
- );
1002
- if (nonBlank.length) {
1003
- const minIndent = Math.min(
1004
- ...nonBlank.map(
1005
- (l) => l.match(/^(\s*)/)?.[1]?.length ?? 0,
1006
- ),
1007
- );
1008
- if (minIndent > 0) {
1009
- for (let j = 0; j < innerLines.length; j++) {
1010
- innerLines[j] = innerLines[j]!.slice(
1011
- Math.min(minIndent, innerLines[j]!.length),
1012
- );
1013
- }
1014
- }
1015
- }
1016
-
1017
- let contentStart = 0;
1018
- if (innerLines[0]?.trim() === "---") {
1019
- const fmEnd = innerLines.findIndex(
1020
- (l, idx) => idx > 0 && l.trim() === "---",
1021
- );
1022
- if (fmEnd !== -1) contentStart = fmEnd + 1;
1023
- }
1024
- const contentLines = innerLines.slice(contentStart);
1025
-
1026
- const defaultSlotLines: string[] = [];
1027
- const codeSlotLines: string[] = [];
1028
- let currentSlot: "default" | "code" | "other" = "default";
1029
- for (const l of contentLines) {
1030
- if (/^#code\s*$/.test(l)) {
1031
- currentSlot = "code";
1032
- continue;
1033
- }
1034
- if (/^#\w+/.test(l) && !/^#{2,}\s/.test(l)) {
1035
- currentSlot = "other";
1036
- continue;
1037
- }
1038
- if (currentSlot === "default") defaultSlotLines.push(l);
1039
- else if (currentSlot === "code") codeSlotLines.push(l);
1040
- }
1041
- const innerBlocks = parseBlocks(defaultSlotLines.join("\n"));
1042
-
1043
- const codeBlocks = extractFencedCode(codeSlotLines);
1044
-
1045
- const CALLOUT_NAMES = new Set([
1046
- "tip",
1047
- "note",
1048
- "info",
1049
- "warning",
1050
- "caution",
1051
- "danger",
1052
- "callout",
1053
- "alert",
1054
- ]);
1055
- if (CALLOUT_NAMES.has(componentName.toLowerCase())) {
1056
- blocks.push({
1057
- type: "callout",
1058
- calloutType: componentName.toLowerCase(),
1059
- innerBlocks,
1060
- });
1061
- } else {
1062
- const mdcProps = parseMdcProps(
1063
- line.match(MDC_OPEN)?.[3],
1064
- );
1065
- const lc = componentName.toLowerCase();
1066
-
1067
- if (lc === "collapsible") {
1068
- blocks.push({
1069
- type: "collapsible",
1070
- label: mdcProps["label"] || "Details",
1071
- open: mdcProps["open"] === "true",
1072
- innerBlocks,
1073
- });
1074
- } else if (lc === "steps") {
1075
- blocks.push({ type: "steps", innerBlocks });
1076
- } else if (lc === "card") {
1077
- blocks.push({
1078
- type: "card",
1079
- title: mdcProps["title"] || "",
1080
- icon: mdcProps["icon"] || "",
1081
- to: mdcProps["to"] || "",
1082
- innerBlocks,
1083
- });
1084
- } else if (lc === "card-group") {
1085
- const cards = innerBlocks.filter(
1086
- (b) => b.type === "card",
1087
- );
1088
- if (cards.length) {
1089
- blocks.push({ type: "cardGroup", cards });
1090
- } else {
1091
- blocks.push(...innerBlocks);
1092
- }
1093
- } else if (lc === "code-collapse") {
1094
- blocks.push({
1095
- type: "codeCollapse",
1096
- codeBlocks: codeBlocks.length
1097
- ? codeBlocks
1098
- : innerBlocks.filter(
1099
- (b) => b.type === "codeBlock",
1100
- ),
1101
- });
1102
- } else if (lc === "code-group") {
1103
- const allCode = [
1104
- ...innerBlocks.filter(
1105
- (b) => b.type === "codeBlock",
1106
- ),
1107
- ...codeBlocks,
1108
- ];
1109
- blocks.push({ type: "codeGroup", codeBlocks: allCode });
1110
- } else if (lc === "code-preview") {
1111
- blocks.push({
1112
- type: "codePreview",
1113
- innerBlocks,
1114
- codeBlocks,
1115
- });
1116
- } else if (lc === "code-tree") {
1117
- blocks.push({
1118
- type: "codeTree",
1119
- files: mdcProps["files"] || "[]",
1120
- });
1121
- } else if (lc === "accordion") {
1122
- const items = parseMdcChildren(
1123
- contentLines,
1124
- "item",
1125
- );
1126
- if (items.length) {
1127
- blocks.push({ type: "accordion", items });
1128
- } else {
1129
- blocks.push({
1130
- type: "accordion",
1131
- items: [
1132
- {
1133
- label: "Item 1",
1134
- icon: "",
1135
- innerBlocks,
1136
- },
1137
- ],
1138
- });
1139
- }
1140
- } else if (lc === "tabs") {
1141
- const items = parseMdcChildren(
1142
- contentLines,
1143
- "tab",
1144
- );
1145
- if (items.length) {
1146
- blocks.push({ type: "tabs", items });
1147
- } else {
1148
- blocks.push({
1149
- type: "tabs",
1150
- items: [
1151
- {
1152
- label: "Tab 1",
1153
- icon: "",
1154
- innerBlocks,
1155
- },
1156
- ],
1157
- });
1158
- }
1159
- } else if (lc === "field") {
1160
- blocks.push({
1161
- type: "field",
1162
- name: mdcProps["name"] || "",
1163
- fieldType: mdcProps["type"] || "string",
1164
- required: mdcProps["required"] === "true",
1165
- innerBlocks,
1166
- });
1167
- } else if (lc === "field-group") {
1168
- const fields = innerBlocks.filter(
1169
- (b) => b.type === "field",
1170
- );
1171
- if (fields.length) {
1172
- blocks.push({ type: "fieldGroup", fields });
1173
- } else {
1174
- blocks.push(...innerBlocks);
1175
- }
1176
- } else {
1177
- blocks.push(...innerBlocks);
1178
- blocks.push(...codeBlocks);
1179
- }
1180
- }
1181
- continue;
1182
- }
1183
-
1184
- if (TASK_RE.test(line)) {
1185
- const items: TaskItem[] = [];
1186
- while (i < lines.length && TASK_RE.test(lines[i]!)) {
1187
- const m = lines[i]!.match(TASK_RE)!;
1188
- items.push({
1189
- checked: m[1]!.toLowerCase() === "x",
1190
- text: m[2]!,
1191
- });
1192
- i++;
1193
- }
1194
- blocks.push({ type: "taskList", items });
1195
- continue;
1196
- }
1197
-
1198
- if (/^[-*+]\s+/.test(line)) {
1199
- const items: string[] = [];
1200
- while (
1201
- i < lines.length &&
1202
- /^[-*+]\s+/.test(lines[i]!) &&
1203
- !TASK_RE.test(lines[i]!)
1204
- ) {
1205
- items.push(lines[i]!.replace(/^[-*+]\s+/, ""));
1206
- i++;
1207
- }
1208
- if (items.length) {
1209
- blocks.push({ type: "bulletList", items });
1210
- continue;
1211
- }
1212
- }
1213
-
1214
- if (/^\d+\.\s+/.test(line)) {
1215
- const items: string[] = [];
1216
- while (i < lines.length && /^\d+\.\s+/.test(lines[i]!)) {
1217
- items.push(lines[i]!.replace(/^\d+\.\s+/, ""));
1218
- i++;
1219
- }
1220
- blocks.push({ type: "orderedList", items });
1221
- continue;
1222
- }
1223
-
1224
- if (line.trim() === "") {
1225
- i++;
1226
- continue;
1227
- }
1228
-
1229
- const paraLines: string[] = [];
1230
- while (
1231
- i < lines.length &&
1232
- lines[i]!.trim() !== "" &&
1233
- !/^(#{1,6}\s|[-*+]\s|\d+\.\s|>|`{3,}|\s*\||[-*_]{3,}\s*$|\s*:{2,}\w)/.test(
1234
- lines[i]!,
1235
- )
1236
- ) {
1237
- paraLines.push(lines[i]!);
1238
- i++;
1239
- }
1240
- if (paraLines.length) {
1241
- blocks.push({ type: "paragraph", text: paraLines.join(" ") });
1242
- }
1243
- }
1244
-
1245
- return blocks;
1246
- }
1247
-
1248
- // ── Y.js content population helpers ──────────────────────────────────────────
1249
-
1250
- function fillTextInto(
1251
- el: Y.XmlElement,
1252
- tokens: InlineToken[],
1253
- ): void {
1254
- const filtered = tokens.filter((t) => t.node || t.text.length > 0);
1255
- if (!filtered.length) return;
1256
-
1257
- const children: (Y.XmlText | Y.XmlElement)[] = filtered.map((tok) => {
1258
- if (tok.node) {
1259
- const xe = new Y.XmlElement(tok.node);
1260
- if (tok.nodeAttrs) {
1261
- for (const [k, v] of Object.entries(tok.nodeAttrs))
1262
- xe.setAttribute(k, v);
1263
- }
1264
- return xe;
1265
- }
1266
- return new Y.XmlText();
1267
- });
1268
- el.insert(0, children);
1269
-
1270
- filtered.forEach((tok, i) => {
1271
- if (tok.node) return;
1272
- const xt = children[i] as Y.XmlText;
1273
- if (tok.attrs) {
1274
- xt.insert(
1275
- 0,
1276
- tok.text,
1277
- tok.attrs as Record<string, boolean | object>,
1278
- );
1279
- } else {
1280
- xt.insert(0, tok.text);
1281
- }
1282
- });
1283
- }
1284
-
1285
- function blockElName(b: Block): string {
1286
- switch (b.type) {
1287
- case "heading":
1288
- return "heading";
1289
- case "paragraph":
1290
- return "paragraph";
1291
- case "bulletList":
1292
- return "bulletList";
1293
- case "orderedList":
1294
- return "orderedList";
1295
- case "taskList":
1296
- return "taskList";
1297
- case "codeBlock":
1298
- return "codeBlock";
1299
- case "blockquote":
1300
- return "blockquote";
1301
- case "table":
1302
- return "table";
1303
- case "hr":
1304
- return "horizontalRule";
1305
- case "callout":
1306
- return "callout";
1307
- case "collapsible":
1308
- return "collapsible";
1309
- case "steps":
1310
- return "steps";
1311
- case "card":
1312
- return "card";
1313
- case "cardGroup":
1314
- return "cardGroup";
1315
- case "codeCollapse":
1316
- return "codeCollapse";
1317
- case "codeGroup":
1318
- return "codeGroup";
1319
- case "codePreview":
1320
- return "codePreview";
1321
- case "codeTree":
1322
- return "codeTree";
1323
- case "accordion":
1324
- return "accordion";
1325
- case "tabs":
1326
- return "tabs";
1327
- case "field":
1328
- return "field";
1329
- case "fieldGroup":
1330
- return "fieldGroup";
1331
- case "image":
1332
- return "image";
1333
- case "docEmbed":
1334
- return "docEmbed";
1335
- case "svgEmbed":
1336
- return "svgEmbed";
1337
- }
1338
- }
1339
-
1340
- function fillBlock(el: Y.XmlElement, block: Block): void {
1341
- switch (block.type) {
1342
- case "heading": {
1343
- el.setAttribute("level", block.level as any);
1344
- fillTextInto(el, parseInline(block.text));
1345
- break;
1346
- }
1347
- case "paragraph": {
1348
- fillTextInto(el, parseInline(block.text));
1349
- break;
1350
- }
1351
- case "bulletList":
1352
- case "orderedList": {
1353
- const listItemEls = block.items.map(
1354
- () => new Y.XmlElement("listItem"),
1355
- );
1356
- el.insert(0, listItemEls);
1357
- block.items.forEach((text, i) => {
1358
- const paraEl = new Y.XmlElement("paragraph");
1359
- listItemEls[i]!.insert(0, [paraEl]);
1360
- fillTextInto(paraEl, parseInline(text));
1361
- });
1362
- break;
1363
- }
1364
- case "taskList": {
1365
- const taskItemEls = block.items.map(
1366
- () => new Y.XmlElement("taskItem"),
1367
- );
1368
- el.insert(0, taskItemEls);
1369
- block.items.forEach((item, i) => {
1370
- taskItemEls[i]!.setAttribute(
1371
- "checked",
1372
- item.checked as any,
1373
- );
1374
- const paraEl = new Y.XmlElement("paragraph");
1375
- taskItemEls[i]!.insert(0, [paraEl]);
1376
- fillTextInto(paraEl, parseInline(item.text));
1377
- });
1378
- break;
1379
- }
1380
- case "codeBlock": {
1381
- if (block.lang) el.setAttribute("language", block.lang);
1382
- const xt = new Y.XmlText();
1383
- el.insert(0, [xt]);
1384
- xt.insert(0, block.code);
1385
- break;
1386
- }
1387
- case "blockquote": {
1388
- const paraEls = block.lines.map(
1389
- () => new Y.XmlElement("paragraph"),
1390
- );
1391
- el.insert(0, paraEls);
1392
- block.lines.forEach((line, i) =>
1393
- fillTextInto(paraEls[i]!, parseInline(line)),
1394
- );
1395
- break;
1396
- }
1397
- case "table": {
1398
- const headerRowEl = new Y.XmlElement("tableRow");
1399
- const dataRowEls = block.dataRows.map(
1400
- () => new Y.XmlElement("tableRow"),
1401
- );
1402
- el.insert(0, [headerRowEl, ...dataRowEls]);
1403
-
1404
- const headerCellEls = block.headerRow.map(
1405
- () => new Y.XmlElement("tableHeader"),
1406
- );
1407
- headerRowEl.insert(0, headerCellEls);
1408
- block.headerRow.forEach((cellText, i) => {
1409
- const paraEl = new Y.XmlElement("paragraph");
1410
- headerCellEls[i]!.insert(0, [paraEl]);
1411
- fillTextInto(paraEl, parseInline(cellText));
1412
- });
1413
-
1414
- block.dataRows.forEach((row, ri) => {
1415
- const cellEls = row.map(
1416
- () => new Y.XmlElement("tableCell"),
1417
- );
1418
- dataRowEls[ri]!.insert(0, cellEls);
1419
- row.forEach((cellText, ci) => {
1420
- const paraEl = new Y.XmlElement("paragraph");
1421
- cellEls[ci]!.insert(0, [paraEl]);
1422
- fillTextInto(paraEl, parseInline(cellText));
1423
- });
1424
- });
1425
- break;
1426
- }
1427
- case "hr":
1428
- break;
1429
- case "callout": {
1430
- el.setAttribute("type", block.calloutType);
1431
- if (!block.innerBlocks.length) {
1432
- const paraEl = new Y.XmlElement("paragraph");
1433
- el.insert(0, [paraEl]);
1434
- break;
1435
- }
1436
- const innerEls = block.innerBlocks.map(
1437
- (b) => new Y.XmlElement(blockElName(b)),
1438
- );
1439
- el.insert(0, innerEls);
1440
- block.innerBlocks.forEach((b, i) =>
1441
- fillBlock(innerEls[i]!, b),
1442
- );
1443
- break;
1444
- }
1445
- case "collapsible": {
1446
- el.setAttribute("label", block.label);
1447
- el.setAttribute("open", block.open as any);
1448
- const inner = block.innerBlocks.length
1449
- ? block.innerBlocks
1450
- : [{ type: "paragraph" as const, text: "" }];
1451
- const innerEls = inner.map(
1452
- (b) => new Y.XmlElement(blockElName(b)),
1453
- );
1454
- el.insert(0, innerEls);
1455
- inner.forEach((b, i) => fillBlock(innerEls[i]!, b));
1456
- break;
1457
- }
1458
- case "steps": {
1459
- const inner = block.innerBlocks.length
1460
- ? block.innerBlocks
1461
- : [{ type: "paragraph" as const, text: "" }];
1462
- const innerEls = inner.map(
1463
- (b) => new Y.XmlElement(blockElName(b)),
1464
- );
1465
- el.insert(0, innerEls);
1466
- inner.forEach((b, i) => fillBlock(innerEls[i]!, b));
1467
- break;
1468
- }
1469
- case "card": {
1470
- if (block.title) el.setAttribute("title", block.title);
1471
- if (block.icon) el.setAttribute("icon", block.icon);
1472
- if (block.to) el.setAttribute("to", block.to);
1473
- const inner = block.innerBlocks.length
1474
- ? block.innerBlocks
1475
- : [{ type: "paragraph" as const, text: "" }];
1476
- const innerEls = inner.map(
1477
- (b) => new Y.XmlElement(blockElName(b)),
1478
- );
1479
- el.insert(0, innerEls);
1480
- inner.forEach((b, i) => fillBlock(innerEls[i]!, b));
1481
- break;
1482
- }
1483
- case "cardGroup": {
1484
- const cardEls = block.cards.map(
1485
- (b) => new Y.XmlElement(blockElName(b)),
1486
- );
1487
- el.insert(0, cardEls);
1488
- block.cards.forEach((b, i) => fillBlock(cardEls[i]!, b));
1489
- break;
1490
- }
1491
- case "codeCollapse": {
1492
- const codes = block.codeBlocks.length
1493
- ? block.codeBlocks
1494
- : [{ type: "codeBlock" as const, lang: "", code: "" }];
1495
- const codeEl = new Y.XmlElement("codeBlock");
1496
- el.insert(0, [codeEl]);
1497
- fillBlock(codeEl, codes[0]!);
1498
- break;
1499
- }
1500
- case "codeGroup": {
1501
- const codes = block.codeBlocks.length
1502
- ? block.codeBlocks
1503
- : [{ type: "codeBlock" as const, lang: "", code: "" }];
1504
- const codeEls = codes.map(() => new Y.XmlElement("codeBlock"));
1505
- el.insert(0, codeEls);
1506
- codes.forEach((b, i) => fillBlock(codeEls[i]!, b));
1507
- break;
1508
- }
1509
- case "codePreview": {
1510
- const all = [...block.innerBlocks, ...block.codeBlocks];
1511
- const inner = all.length
1512
- ? all
1513
- : [{ type: "paragraph" as const, text: "" }];
1514
- const innerEls = inner.map(
1515
- (b) => new Y.XmlElement(blockElName(b)),
1516
- );
1517
- el.insert(0, innerEls);
1518
- inner.forEach((b, i) => fillBlock(innerEls[i]!, b));
1519
- break;
1520
- }
1521
- case "codeTree": {
1522
- el.setAttribute("files", block.files);
1523
- break;
1524
- }
1525
- case "accordion": {
1526
- const itemEls = block.items.map(
1527
- () => new Y.XmlElement("accordionItem"),
1528
- );
1529
- el.insert(0, itemEls);
1530
- block.items.forEach((item, i) => {
1531
- itemEls[i]!.setAttribute("label", item.label);
1532
- if (item.icon)
1533
- itemEls[i]!.setAttribute("icon", item.icon);
1534
- const inner = item.innerBlocks.length
1535
- ? item.innerBlocks
1536
- : [{ type: "paragraph" as const, text: "" }];
1537
- const childEls = inner.map(
1538
- (b) => new Y.XmlElement(blockElName(b)),
1539
- );
1540
- itemEls[i]!.insert(0, childEls);
1541
- inner.forEach((b, ci) => fillBlock(childEls[ci]!, b));
1542
- });
1543
- break;
1544
- }
1545
- case "tabs": {
1546
- const itemEls = block.items.map(
1547
- () => new Y.XmlElement("tabsItem"),
1548
- );
1549
- el.insert(0, itemEls);
1550
- block.items.forEach((item, i) => {
1551
- itemEls[i]!.setAttribute("label", item.label);
1552
- if (item.icon)
1553
- itemEls[i]!.setAttribute("icon", item.icon);
1554
- const inner = item.innerBlocks.length
1555
- ? item.innerBlocks
1556
- : [{ type: "paragraph" as const, text: "" }];
1557
- const childEls = inner.map(
1558
- (b) => new Y.XmlElement(blockElName(b)),
1559
- );
1560
- itemEls[i]!.insert(0, childEls);
1561
- inner.forEach((b, ci) => fillBlock(childEls[ci]!, b));
1562
- });
1563
- break;
1564
- }
1565
- case "field": {
1566
- if (block.name) el.setAttribute("name", block.name);
1567
- el.setAttribute("type", block.fieldType);
1568
- el.setAttribute("required", block.required as any);
1569
- const inner = block.innerBlocks.length
1570
- ? block.innerBlocks
1571
- : [{ type: "paragraph" as const, text: "" }];
1572
- const innerEls = inner.map(
1573
- (b) => new Y.XmlElement(blockElName(b)),
1574
- );
1575
- el.insert(0, innerEls);
1576
- inner.forEach((b, i) => fillBlock(innerEls[i]!, b));
1577
- break;
1578
- }
1579
- case "fieldGroup": {
1580
- const fieldEls = block.fields.map(
1581
- (b) => new Y.XmlElement(blockElName(b)),
1582
- );
1583
- el.insert(0, fieldEls);
1584
- block.fields.forEach((b, i) => fillBlock(fieldEls[i]!, b));
1585
- break;
1586
- }
1587
- case "image": {
1588
- el.setAttribute("src", block.src);
1589
- if (block.alt) el.setAttribute("alt", block.alt);
1590
- if (block.width) el.setAttribute("width", block.width);
1591
- if (block.height) el.setAttribute("height", block.height);
1592
- break;
1593
- }
1594
- case "docEmbed": {
1595
- el.setAttribute("docId", block.docId);
1596
- if (block.seamless) el.setAttribute("seamless", "true");
1597
- break;
1598
- }
1599
- case "svgEmbed": {
1600
- el.setAttribute("svg", block.svg);
1601
- if (block.title) el.setAttribute("title", block.title);
1602
- break;
1603
- }
1604
- }
1605
- }
1606
-
1607
- // ── Public: Markdown → Y.js ─────────────────────────────────────────────────
1608
-
1609
- export function populateYDocFromMarkdown(
1610
- fragment: Y.XmlFragment,
1611
- markdown: string,
1612
- fallbackTitle = "Untitled",
1613
- ): void {
1614
- const ydoc = fragment.doc;
1615
- if (!ydoc) {
1616
- console.warn(
1617
- "[markdownToYjs] fragment has no doc — skipping population",
1618
- );
1619
- return;
1620
- }
1621
-
1622
- const blocks = parseBlocks(markdown);
1623
-
1624
- let title = fallbackTitle;
1625
- let contentBlocks = blocks;
1626
- const h1 = blocks.findIndex(
1627
- (b) => b.type === "heading" && b.level === 1,
1628
- );
1629
- if (h1 !== -1) {
1630
- title = (
1631
- blocks[h1] as { type: "heading"; level: number; text: string }
1632
- ).text;
1633
- contentBlocks = blocks.filter((_, i) => i !== h1);
1634
- }
1635
- if (!contentBlocks.length)
1636
- contentBlocks = [{ type: "paragraph", text: "" }];
1637
-
1638
- ydoc.transact(() => {
1639
- const headerEl = new Y.XmlElement("documentHeader");
1640
- const metaEl = new Y.XmlElement("documentMeta");
1641
- const bodyEls: Y.XmlElement[] = contentBlocks.map((b) => {
1642
- switch (b.type) {
1643
- case "heading":
1644
- return new Y.XmlElement("heading");
1645
- case "paragraph":
1646
- return new Y.XmlElement("paragraph");
1647
- case "bulletList":
1648
- return new Y.XmlElement("bulletList");
1649
- case "orderedList":
1650
- return new Y.XmlElement("orderedList");
1651
- case "taskList":
1652
- return new Y.XmlElement("taskList");
1653
- case "codeBlock":
1654
- return new Y.XmlElement("codeBlock");
1655
- case "blockquote":
1656
- return new Y.XmlElement("blockquote");
1657
- case "table":
1658
- return new Y.XmlElement("table");
1659
- case "hr":
1660
- return new Y.XmlElement("horizontalRule");
1661
- case "callout":
1662
- return new Y.XmlElement("callout");
1663
- case "collapsible":
1664
- return new Y.XmlElement("collapsible");
1665
- case "steps":
1666
- return new Y.XmlElement("steps");
1667
- case "card":
1668
- return new Y.XmlElement("card");
1669
- case "cardGroup":
1670
- return new Y.XmlElement("cardGroup");
1671
- case "codeCollapse":
1672
- return new Y.XmlElement("codeCollapse");
1673
- case "codeGroup":
1674
- return new Y.XmlElement("codeGroup");
1675
- case "codePreview":
1676
- return new Y.XmlElement("codePreview");
1677
- case "codeTree":
1678
- return new Y.XmlElement("codeTree");
1679
- case "accordion":
1680
- return new Y.XmlElement("accordion");
1681
- case "tabs":
1682
- return new Y.XmlElement("tabs");
1683
- case "field":
1684
- return new Y.XmlElement("field");
1685
- case "fieldGroup":
1686
- return new Y.XmlElement("fieldGroup");
1687
- case "image":
1688
- return new Y.XmlElement("image");
1689
- case "docEmbed":
1690
- return new Y.XmlElement("docEmbed");
1691
- case "svgEmbed":
1692
- return new Y.XmlElement("svgEmbed");
1693
- }
1694
- });
1695
-
1696
- fragment.insert(0, [headerEl, metaEl, ...bodyEls]);
1697
-
1698
- const headerXt = new Y.XmlText();
1699
- headerEl.insert(0, [headerXt]);
1700
- headerXt.insert(0, title);
1701
-
1702
- contentBlocks.forEach((block, i) => fillBlock(bodyEls[i]!, block));
1703
- });
1704
- }
1705
-
1706
- // ── Block element builders (exported for ContentManager and SDK consumers) ────
1707
-
1708
- export function buildHeadingElement(text: string, level: 1|2|3|4|5|6 = 1): Y.XmlElement {
1709
- const el = new Y.XmlElement("heading");
1710
- el.setAttribute("level", level as any);
1711
- fillTextInto(el, parseInline(text));
1712
- return el;
1713
- }
1714
-
1715
- export function buildParagraphElement(text: string): Y.XmlElement {
1716
- const el = new Y.XmlElement("paragraph");
1717
- fillTextInto(el, parseInline(text));
1718
- return el;
1719
- }
1720
-
1721
- export function buildBulletListElement(items: string[]): Y.XmlElement {
1722
- const el = new Y.XmlElement("bulletList");
1723
- const itemEls = items.map(() => new Y.XmlElement("listItem"));
1724
- el.insert(0, itemEls);
1725
- items.forEach((text, i) => {
1726
- const paraEl = new Y.XmlElement("paragraph");
1727
- itemEls[i]!.insert(0, [paraEl]);
1728
- fillTextInto(paraEl, parseInline(text));
1729
- });
1730
- return el;
1731
- }
1732
-
1733
- export function buildOrderedListElement(items: string[]): Y.XmlElement {
1734
- const el = new Y.XmlElement("orderedList");
1735
- const itemEls = items.map(() => new Y.XmlElement("listItem"));
1736
- el.insert(0, itemEls);
1737
- items.forEach((text, i) => {
1738
- const paraEl = new Y.XmlElement("paragraph");
1739
- itemEls[i]!.insert(0, [paraEl]);
1740
- fillTextInto(paraEl, parseInline(text));
1741
- });
1742
- return el;
1743
- }
1744
-
1745
- export function buildTaskListElement(
1746
- items: Array<{ text: string; checked?: boolean }>,
1747
- ): Y.XmlElement {
1748
- const el = new Y.XmlElement("taskList");
1749
- const itemEls = items.map(() => new Y.XmlElement("taskItem"));
1750
- el.insert(0, itemEls);
1751
- items.forEach((item, i) => {
1752
- itemEls[i]!.setAttribute("checked", (item.checked ?? false) as any);
1753
- const paraEl = new Y.XmlElement("paragraph");
1754
- itemEls[i]!.insert(0, [paraEl]);
1755
- fillTextInto(paraEl, parseInline(item.text));
1756
- });
1757
- return el;
1758
- }
1759
-
1760
- export function buildCodeBlockElement(code: string, language?: string): Y.XmlElement {
1761
- const el = new Y.XmlElement("codeBlock");
1762
- if (language) el.setAttribute("language", language);
1763
- const xt = new Y.XmlText();
1764
- el.insert(0, [xt]);
1765
- xt.insert(0, code);
1766
- return el;
1767
- }
1768
-
1769
- export function buildBlockquoteElement(text: string): Y.XmlElement {
1770
- const el = new Y.XmlElement("blockquote");
1771
- const paraEl = new Y.XmlElement("paragraph");
1772
- el.insert(0, [paraEl]);
1773
- fillTextInto(paraEl, parseInline(text));
1774
- return el;
1775
- }
1776
-
1777
- export function buildHorizontalRuleElement(): Y.XmlElement {
1778
- return new Y.XmlElement("horizontalRule");
1779
- }
1780
-
1781
- /** Parse markdown into block Y.XmlElements (no header/meta). */
1782
- export function buildBlocksFromMarkdown(markdown: string): Y.XmlElement[] {
1783
- const blocks = parseBlocks(markdown);
1784
- return blocks
1785
- .filter((b) => b.type !== "heading" || (b as any).level !== 1)
1786
- .map((b) => {
1787
- const el = new Y.XmlElement(blockElName(b));
1788
- fillBlock(el, b);
1789
- return el;
1790
- });
1791
- }
1792
-
1793
- // ── Block reader ──────────────────────────────────────────────────────────────
1794
-
1795
- export interface DocumentBlock {
1796
- type: string;
1797
- attrs: Record<string, unknown>;
1798
- text: string;
1799
- items?: string[];
1800
- children?: DocumentBlock[];
1801
- }
1802
-
1803
- export function readBlocksFromFragment(fragment: Y.XmlFragment): DocumentBlock[] {
1804
- const result: DocumentBlock[] = [];
1805
- // toArray() is O(n); indexed fragment.get(i) would make this O(n²).
1806
- for (const child of fragment.toArray()) {
1807
- if (!(child instanceof Y.XmlElement)) continue;
1808
- const name = child.nodeName;
1809
- if (name === "documentHeader" || name === "documentMeta") continue;
1810
- result.push(_xmlElToBlock(child));
1811
- }
1812
- return result;
1813
- }
1814
-
1815
- function _xmlElToBlock(el: Y.XmlElement): DocumentBlock {
1816
- const name = el.nodeName;
1817
- switch (name) {
1818
- case "heading":
1819
- return { type: "heading", attrs: { level: el.getAttribute("level") }, text: elementTextContent(el) };
1820
- case "paragraph":
1821
- case "blockquote":
1822
- case "horizontalRule":
1823
- return { type: name, attrs: {}, text: elementTextContent(el) };
1824
- case "codeBlock": {
1825
- const lang = el.getAttribute("language");
1826
- return { type: "codeBlock", attrs: lang ? { language: lang } : {}, text: elementTextContent(el) };
1827
- }
1828
- case "bulletList":
1829
- case "orderedList": {
1830
- const items: string[] = [];
1831
- for (let i = 0; i < el.length; i++) {
1832
- const item = el.get(i);
1833
- if (item instanceof Y.XmlElement && item.nodeName === "listItem")
1834
- items.push(elementTextContent(item));
1835
- }
1836
- return { type: name, attrs: {}, text: "", items };
1837
- }
1838
- case "taskList": {
1839
- const items: string[] = [];
1840
- const children: DocumentBlock[] = [];
1841
- for (let i = 0; i < el.length; i++) {
1842
- const item = el.get(i);
1843
- if (item instanceof Y.XmlElement && item.nodeName === "taskItem") {
1844
- const checked = item.getAttribute("checked");
1845
- const text = elementTextContent(item);
1846
- items.push(text);
1847
- children.push({
1848
- type: "taskItem",
1849
- attrs: { checked: checked === "true" || (checked as unknown) === true },
1850
- text,
1851
- });
1852
- }
1853
- }
1854
- return { type: "taskList", attrs: {}, text: "", items, children };
1855
- }
1856
- default:
1857
- return { type: name, attrs: {}, text: elementTextContent(el) };
1858
- }
1859
- }