@publisle/adapter-core 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,981 @@
1
+ import { isInteractiveEnvelope, locateDiagnostic, richText, createIslandInput, } from "@publisle/schema";
2
+ let mathRenderer;
3
+ /** Install the shared renderer after a host explicitly loads math support. */
4
+ export function installMathRenderer(renderer) {
5
+ mathRenderer = renderer;
6
+ }
7
+ const text = (value) => ({ kind: "text", value });
8
+ const element = (tag, attributes, children) => ({ kind: "element", tag, attributes, children });
9
+ /** Stable identity for a citation cluster, independent of object property order. */
10
+ export function citationKey(cluster) {
11
+ return JSON.stringify([
12
+ cluster.items.map((item) => [
13
+ item.id,
14
+ item.locator ?? "",
15
+ item.label ?? "",
16
+ item.suppressAuthor ?? false,
17
+ ]),
18
+ cluster.prefix ?? "",
19
+ cluster.suffix ?? "",
20
+ ]);
21
+ }
22
+ function referenceText(target) {
23
+ if (target.kind === "heading")
24
+ return target.title ?? target.label;
25
+ const name = target.kind.charAt(0).toUpperCase() + target.kind.slice(1);
26
+ return `${name} ${target.ordinal ?? ""}`.trim();
27
+ }
28
+ function renderMath(value, display, diagnostics, block) {
29
+ try {
30
+ return [
31
+ {
32
+ kind: "raw",
33
+ value: mathRenderer.renderToString(value, {
34
+ displayMode: display,
35
+ throwOnError: true,
36
+ trust: false,
37
+ strict: "warn",
38
+ maxExpand: 1000,
39
+ maxSize: 100,
40
+ output: "htmlAndMathml",
41
+ }),
42
+ },
43
+ ];
44
+ }
45
+ catch (error) {
46
+ diagnostics.push({
47
+ level: "warning",
48
+ code: "invalid-math",
49
+ message: error instanceof Error ? error.message : "Math rendering failed.",
50
+ blockId: block.id,
51
+ });
52
+ return [
53
+ element(display ? "pre" : "code", { class: "publisle-math-error" }, [
54
+ text(value),
55
+ ]),
56
+ ];
57
+ }
58
+ }
59
+ function safeUrl(url) {
60
+ // Conservative superset of browser URL preprocessing, shared with Python.
61
+ // Browsers remove embedded TAB/LF/CR before identifying a scheme.
62
+ // eslint-disable-next-line no-control-regex -- deliberately remove URL control characters
63
+ const normalized = url.replace(/[\u0000-\u0020]/gu, "").toLowerCase();
64
+ return /^(?:javascript|vbscript|data):/u.test(normalized) ? undefined : url;
65
+ }
66
+ function safeEmbedUrl(url) {
67
+ return /^https:\/\//iu.test(url.trim()) ? url : undefined;
68
+ }
69
+ const builtinEmbedProviders = {
70
+ youtube: (resourceId) => {
71
+ return /^[\w-]{6,20}$/u.test(resourceId)
72
+ ? {
73
+ src: `https://www.youtube-nocookie.com/embed/${resourceId}`,
74
+ allow: "accelerometer; autoplay; encrypted-media; picture-in-picture",
75
+ allowFullscreen: true,
76
+ }
77
+ : undefined;
78
+ },
79
+ vimeo: (resourceId) => {
80
+ return /^\d+$/u.test(resourceId)
81
+ ? {
82
+ src: `https://player.vimeo.com/video/${resourceId}`,
83
+ allow: "autoplay; fullscreen; picture-in-picture",
84
+ allowFullscreen: true,
85
+ }
86
+ : undefined;
87
+ },
88
+ };
89
+ function inline(nodes, diagnostics, block, references = []) {
90
+ return nodes.flatMap((node, index) => {
91
+ switch (node.type) {
92
+ case "text": {
93
+ const value = String(node["value"] ?? "");
94
+ const direction = node["direction"];
95
+ if (direction === "ltr" || direction === "rtl" || direction === "auto")
96
+ return [element("span", { dir: direction }, [text(value)])];
97
+ return [text(value)];
98
+ }
99
+ case "emphasis":
100
+ return [
101
+ element("em", {}, inline(node["children"], diagnostics, block, references)),
102
+ ];
103
+ case "strong":
104
+ return [
105
+ element("strong", {}, inline(node["children"], diagnostics, block, references)),
106
+ ];
107
+ case "strikethrough":
108
+ return [
109
+ element("del", {}, inline(node["children"], diagnostics, block, references)),
110
+ ];
111
+ case "inlineCode":
112
+ return [element("code", {}, [text(String(node["value"] ?? ""))])];
113
+ case "inlineMath":
114
+ return renderMath(String(node["value"] ?? ""), false, diagnostics, block);
115
+ case "hardBreak":
116
+ return [element("br", {}, [])];
117
+ case "softBreak":
118
+ return [text("\n")];
119
+ case "footnoteReference": {
120
+ const localId = `footnote-${String(node["identifier"] ?? "")}`;
121
+ return [
122
+ element("sup", {}, [
123
+ element("a", { href: `#${localId}`, "data-publisle-ref": localId }, [text(String(node["identifier"] ?? ""))]),
124
+ ]),
125
+ ];
126
+ }
127
+ case "citationReference": {
128
+ const items = Array.isArray(node["items"])
129
+ ? node["items"]
130
+ : [];
131
+ const value = `${String(node["prefix"] ?? "")}${items
132
+ .map((item) => {
133
+ const id = String(item["id"] ?? "");
134
+ const locator = typeof item["locator"] === "string" ? `, ${item["locator"]}` : "";
135
+ return `${id}${locator}`;
136
+ })
137
+ .join("; ")}${String(node["suffix"] ?? "")}`;
138
+ return [
139
+ element("span", {
140
+ class: "publisle-citation",
141
+ "data-publisle-citation": JSON.stringify(items),
142
+ ...(node["prefix"]
143
+ ? { "data-publisle-citation-prefix": String(node["prefix"]) }
144
+ : {}),
145
+ ...(node["suffix"]
146
+ ? { "data-publisle-citation-suffix": String(node["suffix"]) }
147
+ : {}),
148
+ }, [text(`[${value}]`)]),
149
+ ];
150
+ }
151
+ case "crossReference": {
152
+ const target = String(node["target"] ?? "");
153
+ const resolved = references.find((entry) => entry.label === target);
154
+ const preceding = nodes
155
+ .slice(0, index)
156
+ .map(function plain(item) {
157
+ return item.type === "text"
158
+ ? String(item["value"] ?? "")
159
+ : Array.isArray(item["children"])
160
+ ? item["children"].map(plain).join("")
161
+ : "";
162
+ })
163
+ .join("");
164
+ const kind = resolved?.kind;
165
+ const authoredKind = kind &&
166
+ kind !== "heading" &&
167
+ new RegExp(`\\b${kind}\\s+$`, "iu").test(preceding);
168
+ const label = resolved
169
+ ? authoredKind
170
+ ? String(resolved.ordinal ?? resolved.label)
171
+ : referenceText(resolved)
172
+ : target;
173
+ const children = Array.isArray(node["children"])
174
+ ? inline(node["children"], diagnostics, block, references)
175
+ : [text(label)];
176
+ return [
177
+ element("a", {
178
+ href: `#reference-${target}`,
179
+ "data-publisle-ref": `reference-${target}`,
180
+ ...(resolved ? {} : { "data-publisle-unresolved": true }),
181
+ }, children),
182
+ ];
183
+ }
184
+ case "rawHtml":
185
+ return [
186
+ element("pre", { "data-publisle-raw-html": true }, [
187
+ text(String(node["value"] ?? "")),
188
+ ]),
189
+ ];
190
+ case "link": {
191
+ const url = safeUrl(String(node["url"] ?? ""));
192
+ if (!url)
193
+ diagnostics.push({
194
+ level: "warning",
195
+ code: "unsafe-url",
196
+ message: "An unsafe link URL was removed.",
197
+ blockId: block.id,
198
+ });
199
+ return [
200
+ element("a", url ? { href: url } : {}, inline(node["children"], diagnostics, block, references)),
201
+ ];
202
+ }
203
+ case "inlineImage": {
204
+ const url = safeUrl(String(node["url"] ?? ""));
205
+ if (!url)
206
+ diagnostics.push({
207
+ level: "warning",
208
+ code: "unsafe-url",
209
+ message: "An unsafe image URL was removed.",
210
+ blockId: block.id,
211
+ });
212
+ return [
213
+ element("img", { ...(url ? { src: url } : {}), alt: String(node["alt"] ?? "") }, []),
214
+ ];
215
+ }
216
+ default:
217
+ return [];
218
+ }
219
+ });
220
+ }
221
+ function flow(nodes, diagnostics, block, references = []) {
222
+ return nodes.flatMap((node) => {
223
+ switch (node.type) {
224
+ case "paragraph":
225
+ return [
226
+ element("p", {}, inline(node["content"], diagnostics, block, references)),
227
+ ];
228
+ case "heading":
229
+ return [
230
+ element(`h${Number(node["level"])}`, {}, inline(node["content"], diagnostics, block, references)),
231
+ ];
232
+ case "quote":
233
+ return [
234
+ element("blockquote", {}, flow(node["children"], diagnostics, block, references)),
235
+ ];
236
+ case "code":
237
+ return [
238
+ element("pre", {}, [
239
+ element("code", typeof node["language"] === "string"
240
+ ? { class: `language-${node["language"]}` }
241
+ : {}, [text(String(node["value"] ?? ""))]),
242
+ ]),
243
+ ];
244
+ case "divider":
245
+ return [element("hr", {}, [])];
246
+ case "rawHtml":
247
+ return [
248
+ element("pre", { "data-publisle-raw-html": true }, [
249
+ text(String(node["value"] ?? "")),
250
+ ]),
251
+ ];
252
+ case "list": {
253
+ const ordered = node["ordered"] === true;
254
+ const items = node["items"];
255
+ return [
256
+ element(ordered ? "ol" : "ul", ordered && typeof node["start"] === "number"
257
+ ? { start: node["start"] }
258
+ : {}, items.map((item) => element("li", typeof item.checked === "boolean"
259
+ ? { class: "publisle-task-list-item" }
260
+ : {}, [
261
+ ...(typeof item.checked === "boolean"
262
+ ? [
263
+ element("input", {
264
+ type: "checkbox",
265
+ disabled: true,
266
+ ...(item.checked ? { checked: true } : {}),
267
+ }, []),
268
+ ]
269
+ : []),
270
+ ...flow(item.children, diagnostics, block, references),
271
+ ]))),
272
+ ];
273
+ }
274
+ default:
275
+ return [];
276
+ }
277
+ });
278
+ }
279
+ function inlinePlain(nodes) {
280
+ return nodes
281
+ .map((node) => {
282
+ if (typeof node !== "object" || node === null || Array.isArray(node))
283
+ return "";
284
+ const record = node;
285
+ if (record["type"] === "text" && typeof record["value"] === "string")
286
+ return record["value"];
287
+ return Array.isArray(record["children"])
288
+ ? inlinePlain(record["children"])
289
+ : "";
290
+ })
291
+ .join("");
292
+ }
293
+ function envelopeProps(envelope) {
294
+ const props = {
295
+ activation: envelope.activation,
296
+ payload: envelope.payload,
297
+ };
298
+ if (envelope.content !== undefined)
299
+ props["content"] = envelope.content;
300
+ if (envelope.fallback !== undefined)
301
+ props["fallback"] = envelope.fallback;
302
+ if (envelope.initialState !== undefined)
303
+ props["initialState"] = envelope.initialState;
304
+ if (envelope.accessibility !== undefined)
305
+ props["accessibility"] = envelope.accessibility;
306
+ return props;
307
+ }
308
+ function nonempty(value, fallback) {
309
+ return value !== undefined && value.length > 0 ? value : fallback;
310
+ }
311
+ function accessibleName(envelope, displayName) {
312
+ const title = envelope.content?.title
313
+ ? inlinePlain(envelope.content.title).trim()
314
+ : "";
315
+ return nonempty(envelope.accessibility?.label, nonempty(title, displayName ?? "Interactive"));
316
+ }
317
+ function exploreLabel(envelope, displayName) {
318
+ const title = envelope.content?.title
319
+ ? inlinePlain(envelope.content.title).trim()
320
+ : "";
321
+ const name = nonempty(title, envelope.accessibility?.label ?? displayName ?? "");
322
+ return name.length > 0 ? `Explore ${name}` : "Explore";
323
+ }
324
+ function contractProvenance(type, pins) {
325
+ const pin = pins.find((entry) => entry.type === type);
326
+ return pin ? `${pin.id} ${pin.digest}` : undefined;
327
+ }
328
+ function interactiveReference(renderer) {
329
+ if (renderer.interactive)
330
+ return {
331
+ module: renderer.interactive.module,
332
+ exportName: renderer.interactive.exportName ?? "default",
333
+ };
334
+ if (renderer.module)
335
+ return {
336
+ module: renderer.module,
337
+ exportName: renderer.exportName ?? "default",
338
+ };
339
+ return undefined;
340
+ }
341
+ function interactiveNodes(block, envelope, options, diagnostics, references, displayName, pins = []) {
342
+ const renderer = options.renderers?.[block.type];
343
+ const interactive = renderer ? interactiveReference(renderer) : undefined;
344
+ const staticRenderer = renderer?.static;
345
+ const description = envelope.content?.description;
346
+ const hasDescription = Array.isArray(description) && description.length > 0;
347
+ const fallbackContent = envelope.fallback ?? envelope.content?.fallback;
348
+ const hasFallback = Array.isArray(fallbackContent) && fallbackContent.length > 0;
349
+ if (!staticRenderer && !hasFallback && !hasDescription) {
350
+ diagnostics.push({
351
+ level: "warning",
352
+ code: "missing-static-representation",
353
+ message: `Interactive block ${block.type} has no static representation.`,
354
+ blockId: block.id,
355
+ });
356
+ }
357
+ const explanation = [];
358
+ if (envelope.content?.title?.length) {
359
+ explanation.push(element("p", { class: "publisle-interactive-title" }, inline(envelope.content.title, diagnostics, block, references)));
360
+ }
361
+ if (hasDescription)
362
+ explanation.push(...flow(description, diagnostics, block, references));
363
+ if (envelope.content?.instructions?.length)
364
+ explanation.push(...flow(envelope.content.instructions, diagnostics, block, references));
365
+ for (const key of ["purpose", "observations", "assumptions"]) {
366
+ const content = envelope.content?.[key];
367
+ if (content?.length)
368
+ explanation.push(...flow(content, diagnostics, block, references));
369
+ }
370
+ for (const preset of envelope.content?.presets ?? []) {
371
+ if (preset.description?.length)
372
+ explanation.push(...flow(preset.description, diagnostics, block, references));
373
+ }
374
+ const visualization = staticRenderer
375
+ ? [
376
+ {
377
+ kind: "component",
378
+ module: staticRenderer.module,
379
+ exportName: staticRenderer.exportName ?? "default",
380
+ blockId: block.id,
381
+ props: envelopeProps(envelope),
382
+ artifact: staticRenderer.lower
383
+ ? staticRenderer.lower(createIslandInput(block, envelope, pins))
384
+ : hasFallback
385
+ ? flow(fallbackContent, diagnostics, block, references)
386
+ : [],
387
+ },
388
+ ]
389
+ : hasFallback
390
+ ? flow(fallbackContent, diagnostics, block, references)
391
+ : [];
392
+ const provenance = contractProvenance(block.type, pins);
393
+ const region = (children) => [
394
+ element("section", {
395
+ class: "publisle-interactive",
396
+ ...(provenance ? { "data-publisle-contract": provenance } : {}),
397
+ }, children),
398
+ ];
399
+ if (!interactive) {
400
+ diagnostics.push({
401
+ level: "warning",
402
+ code: "missing-island-renderer",
403
+ message: `No island renderer is configured for ${block.type}.`,
404
+ blockId: block.id,
405
+ });
406
+ return region([...explanation, ...visualization]);
407
+ }
408
+ const fallback = [...visualization];
409
+ if (envelope.activation === "interaction") {
410
+ fallback.push(element("button", { type: "button", "data-publisle-activate": "true" }, [
411
+ text(exploreLabel(envelope, displayName)),
412
+ ]));
413
+ }
414
+ return region([
415
+ ...explanation,
416
+ {
417
+ kind: "island",
418
+ blockId: block.id,
419
+ activation: envelope.activation,
420
+ label: accessibleName(envelope, displayName),
421
+ module: interactive.module,
422
+ exportName: interactive.exportName,
423
+ props: envelopeProps(envelope),
424
+ fallback,
425
+ ...(provenance ? { provenance } : {}),
426
+ },
427
+ ]);
428
+ }
429
+ function blockNodes(block, options, diagnostics, references, displayName, pins = []) {
430
+ if (isInteractiveEnvelope(block.data))
431
+ return interactiveNodes(block, block.data, options, diagnostics, references, displayName, pins);
432
+ const data = block.data;
433
+ const reference = references.find((entry) => entry.blockId === block.id);
434
+ switch (block.type) {
435
+ case "publisle:paragraph":
436
+ return [
437
+ element("p", {}, inline(data["content"], diagnostics, block, references)),
438
+ ];
439
+ case "publisle:heading":
440
+ return [
441
+ element(`h${Number(data["level"])}`, {
442
+ "data-publisle-id": block.id,
443
+ ...(typeof data["label"] === "string"
444
+ ? { id: `reference-${data["label"]}` }
445
+ : {}),
446
+ }, inline(data["content"], diagnostics, block, references)),
447
+ ];
448
+ case "publisle:list":
449
+ return flow([{ type: "list", ...data }], diagnostics, block, references);
450
+ case "publisle:quote":
451
+ return [
452
+ element("blockquote", {}, flow(data["children"], diagnostics, block, references)),
453
+ ];
454
+ case "publisle:code":
455
+ return flow([{ type: "code", ...data }], diagnostics, block, references);
456
+ case "publisle:math":
457
+ return [
458
+ element(data["display"] === true ? "div" : "span", {
459
+ class: data["display"] === true && reference?.ordinal
460
+ ? "publisle-math publisle-math-numbered"
461
+ : "publisle-math",
462
+ ...(typeof data["label"] === "string"
463
+ ? { id: `reference-${data["label"]}` }
464
+ : {}),
465
+ }, [
466
+ ...renderMath(String(data["value"] ?? ""), data["display"] === true, diagnostics, block),
467
+ ...(reference?.ordinal
468
+ ? [
469
+ element("span", { class: "publisle-equation-number" }, [
470
+ text(`(${reference.ordinal})`),
471
+ ]),
472
+ ]
473
+ : []),
474
+ ]),
475
+ ];
476
+ case "publisle:divider":
477
+ return [element("hr", {}, [])];
478
+ case "publisle:figure": {
479
+ const src = safeUrl(String(data["src"] ?? ""));
480
+ const original = data["original"];
481
+ const originalSrc = typeof original?.["src"] === "string"
482
+ ? safeUrl(original["src"])
483
+ : undefined;
484
+ if (!src)
485
+ diagnostics.push({
486
+ level: "warning",
487
+ code: "unsafe-url",
488
+ message: "An unsafe figure URL was removed.",
489
+ blockId: block.id,
490
+ });
491
+ // Alternative renditions keyed by variant name ("dark", …). The host's
492
+ // CSS decides which variant its active theme consumes; hosts without a
493
+ // mapping keep the base rendition.
494
+ const variants = Object.entries((data["variants"] ?? {})).flatMap(([name, value]) => {
495
+ if (typeof value !== "string")
496
+ return [];
497
+ const variantSrc = safeUrl(value);
498
+ if (!variantSrc) {
499
+ diagnostics.push({
500
+ level: "warning",
501
+ code: "unsafe-url",
502
+ message: `An unsafe figure ${name} variant URL was removed.`,
503
+ blockId: block.id,
504
+ });
505
+ return [];
506
+ }
507
+ return [[name, variantSrc]];
508
+ });
509
+ const themed = src !== undefined && variants.length > 0;
510
+ return [
511
+ element("figure", {
512
+ ...(typeof data["label"] === "string"
513
+ ? { id: `reference-${data["label"]}` }
514
+ : {}),
515
+ ...(themed ? { class: "publisle-figure-themed" } : {}),
516
+ }, [
517
+ element("img", {
518
+ ...(src ? { src } : {}),
519
+ alt: String(data["alt"] ?? "Figure description missing."),
520
+ }, []),
521
+ ...variants.map(([name, variantSrc]) =>
522
+ // The base image carries the description; renditions are decorative.
523
+ element("img", {
524
+ src: variantSrc,
525
+ alt: "",
526
+ "data-publisle-variant": name,
527
+ "aria-hidden": "true",
528
+ }, [])),
529
+ ...(data["alt"] === undefined
530
+ ? [
531
+ element("p", { class: "publisle-figure-missing-alt" }, [
532
+ text("Figure description missing."),
533
+ ]),
534
+ ]
535
+ : []),
536
+ ...(reference || Array.isArray(data["caption"])
537
+ ? [
538
+ element("figcaption", {}, [
539
+ ...(reference
540
+ ? [
541
+ element("span", { class: "publisle-figure-number" }, [
542
+ text(`${referenceText(reference)}. `),
543
+ ]),
544
+ ]
545
+ : []),
546
+ ...(Array.isArray(data["caption"])
547
+ ? flow(data["caption"], diagnostics, block, references)
548
+ : []),
549
+ ]),
550
+ ]
551
+ : []),
552
+ ...(Array.isArray(data["credit"])
553
+ ? [
554
+ element("small", { class: "publisle-figure-credit" }, inline(data["credit"], diagnostics, block, references)),
555
+ ]
556
+ : []),
557
+ ...(originalSrc
558
+ ? [
559
+ element("a", {
560
+ class: "publisle-figure-original",
561
+ href: originalSrc,
562
+ download: String(original?.["filename"] ?? true),
563
+ }, [text("Download original")]),
564
+ ]
565
+ : []),
566
+ ]),
567
+ ];
568
+ }
569
+ case "publisle:table": {
570
+ const rows = data["rows"];
571
+ const align = data["align"];
572
+ return [
573
+ element("figure", typeof data["label"] === "string"
574
+ ? { id: `reference-${data["label"]}` }
575
+ : {}, [
576
+ ...(reference || Array.isArray(data["caption"])
577
+ ? [
578
+ element("figcaption", {}, [
579
+ ...(reference
580
+ ? [
581
+ element("span", { class: "publisle-table-number" }, [
582
+ text(`${referenceText(reference)}. `),
583
+ ]),
584
+ ]
585
+ : []),
586
+ ...(Array.isArray(data["caption"])
587
+ ? flow(data["caption"], diagnostics, block, references)
588
+ : []),
589
+ ]),
590
+ ]
591
+ : []),
592
+ element("table", {}, [
593
+ element("tbody", {}, rows.map((row, rowIndex) => element("tr", {}, row.map((cell, cellIndex) => element((typeof data["headerRows"] === "number"
594
+ ? data["headerRows"]
595
+ : 1) > rowIndex
596
+ ? "th"
597
+ : "td", {
598
+ ...((typeof data["headerRows"] === "number"
599
+ ? data["headerRows"]
600
+ : 1) > rowIndex
601
+ ? { scope: "col" }
602
+ : {}),
603
+ ...(align[cellIndex]
604
+ ? { class: `publisle-align-${align[cellIndex]}` }
605
+ : {}),
606
+ }, inline(cell, diagnostics, block, references)))))),
607
+ ]),
608
+ ]),
609
+ ];
610
+ }
611
+ case "publisle:callout":
612
+ return [
613
+ element("aside", {
614
+ class: `publisle-callout publisle-callout-${String(data["variant"] ?? "note")}`,
615
+ }, [
616
+ ...(typeof data["title"] === "string"
617
+ ? [element("strong", {}, [text(data["title"])])]
618
+ : []),
619
+ ...flow(data["children"], diagnostics, block, references),
620
+ ]),
621
+ ];
622
+ case "publisle:footnote":
623
+ return [
624
+ element("aside", { id: `footnote-${String(data["identifier"] ?? "")}` }, flow(data["children"], diagnostics, block, references)),
625
+ ];
626
+ case "publisle:embed": {
627
+ const providerName = String(data["provider"] ?? "");
628
+ const configuredProvider = options.embedProviders?.[providerName];
629
+ const builtinProvider = builtinEmbedProviders[providerName];
630
+ const provider = configuredProvider ??
631
+ (builtinProvider
632
+ ? (resourceId) => builtinProvider(resourceId)
633
+ : undefined);
634
+ const result = provider?.(String(data["resourceId"] ?? ""));
635
+ const embedSrc = result ? safeEmbedUrl(result.src) : undefined;
636
+ if (!result || !embedSrc) {
637
+ diagnostics.push({
638
+ level: "warning",
639
+ code: "missing-embed-provider",
640
+ message: `Embed provider ${providerName} is unavailable or rejected the resource ID.`,
641
+ blockId: block.id,
642
+ });
643
+ return Array.isArray(data["fallback"])
644
+ ? flow(data["fallback"], diagnostics, block, references)
645
+ : [
646
+ element("p", { "data-publisle-embed-unavailable": providerName }, [text(String(data["title"] ?? "Embedded content"))]),
647
+ ];
648
+ }
649
+ const ratio = data["aspectRatio"];
650
+ return [
651
+ element("figure", { class: "publisle-embed" }, [
652
+ element("iframe", {
653
+ src: embedSrc,
654
+ title: String(data["title"] ?? ""),
655
+ loading: "lazy",
656
+ referrerpolicy: "strict-origin-when-cross-origin",
657
+ allow: result.allow ?? "fullscreen",
658
+ sandbox: ("sandbox" in result ? result.sandbox : undefined) ??
659
+ "allow-scripts allow-same-origin allow-presentation",
660
+ ...(result.allowFullscreen ? { allowfullscreen: true } : {}),
661
+ style: `aspect-ratio:${Number(ratio["width"] ?? 16)}/${Number(ratio["height"] ?? 9)}`,
662
+ }, []),
663
+ ...(Array.isArray(data["caption"])
664
+ ? [
665
+ element("figcaption", {}, flow(data["caption"], diagnostics, block, references)),
666
+ ]
667
+ : []),
668
+ ]),
669
+ ];
670
+ }
671
+ case "publisle:diagram": {
672
+ const engine = String(data["engine"] ?? "");
673
+ const renderer = options.diagramRenderers?.[engine];
674
+ if (!renderer) {
675
+ diagnostics.push({
676
+ level: "warning",
677
+ code: "missing-diagram-renderer",
678
+ message: `No renderer is registered for diagram engine ${engine}.`,
679
+ blockId: block.id,
680
+ });
681
+ const print = data["printFallback"];
682
+ const printSrc = typeof print?.["src"] === "string"
683
+ ? safeUrl(print["src"])
684
+ : undefined;
685
+ const fallback = printSrc
686
+ ? [
687
+ element("img", { src: printSrc, alt: String(data["alt"] ?? "") }, []),
688
+ ]
689
+ : Array.isArray(data["fallback"])
690
+ ? flow(data["fallback"], diagnostics, block, references)
691
+ : [element("pre", {}, [text(String(data["source"] ?? ""))])];
692
+ return [
693
+ element("figure", typeof data["label"] === "string"
694
+ ? { id: `reference-${data["label"]}` }
695
+ : {}, [
696
+ ...fallback,
697
+ ...(reference || Array.isArray(data["caption"])
698
+ ? [
699
+ element("figcaption", {}, [
700
+ ...(reference
701
+ ? [
702
+ element("span", { class: "publisle-diagram-number" }, [text(`${referenceText(reference)}. `)]),
703
+ ]
704
+ : []),
705
+ ...(Array.isArray(data["caption"])
706
+ ? flow(data["caption"], diagnostics, block, references)
707
+ : []),
708
+ ]),
709
+ ]
710
+ : []),
711
+ ]),
712
+ ];
713
+ }
714
+ let result;
715
+ try {
716
+ result = renderer({
717
+ engine,
718
+ source: String(data["source"] ?? ""),
719
+ alt: String(data["alt"] ?? ""),
720
+ });
721
+ }
722
+ catch (error) {
723
+ diagnostics.push({
724
+ level: "warning",
725
+ code: "diagram-render-failed",
726
+ message: error instanceof Error
727
+ ? error.message
728
+ : `Rendering ${engine} failed.`,
729
+ blockId: block.id,
730
+ });
731
+ return Array.isArray(data["fallback"])
732
+ ? flow(data["fallback"], diagnostics, block, references)
733
+ : [element("pre", {}, [text(String(data["source"] ?? ""))])];
734
+ }
735
+ const rendered = [...result.static];
736
+ if (result.interactive)
737
+ rendered.push({
738
+ kind: "island",
739
+ blockId: block.id,
740
+ implementation: result.interactive.implementation,
741
+ activation: result.interactive.activation ?? "visible",
742
+ label: result.accessibleText ?? String(data["alt"] ?? "Diagram"),
743
+ module: result.interactive.module,
744
+ exportName: result.interactive.exportName ?? "default",
745
+ props: result.interactive.props ?? {},
746
+ fallback: result.static,
747
+ });
748
+ return [
749
+ element("figure", typeof data["label"] === "string"
750
+ ? { id: `reference-${data["label"]}` }
751
+ : {}, [
752
+ element("div", { class: "publisle-diagram-screen" }, rendered),
753
+ ...(result.print
754
+ ? [
755
+ element("div", { class: "publisle-diagram-print" }, result.print),
756
+ ]
757
+ : []),
758
+ ...(reference || Array.isArray(data["caption"])
759
+ ? [
760
+ element("figcaption", {}, [
761
+ ...(reference
762
+ ? [
763
+ element("span", { class: "publisle-diagram-number" }, [text(`${referenceText(reference)}. `)]),
764
+ ]
765
+ : []),
766
+ ...(Array.isArray(data["caption"])
767
+ ? flow(data["caption"], diagnostics, block, references)
768
+ : []),
769
+ ]),
770
+ ]
771
+ : []),
772
+ ]),
773
+ ];
774
+ }
775
+ case "publisle:bibliography": {
776
+ const entries = Array.isArray(data["entries"]) ? data["entries"] : [];
777
+ if (options.bibliography)
778
+ return [
779
+ element("section", { class: "publisle-bibliography" }, options.bibliography.map((entry) => element("p", { "data-publisle-bibliography-id": entry.id }, [
780
+ text(entry.text),
781
+ ]))),
782
+ ];
783
+ return [
784
+ element("section", { class: "publisle-bibliography" }, entries.flatMap((entry) => {
785
+ if (typeof entry !== "object" ||
786
+ entry === null ||
787
+ Array.isArray(entry))
788
+ return [];
789
+ const record = entry;
790
+ const authors = Array.isArray(record["authors"])
791
+ ? record["authors"].filter((author) => typeof author === "string")
792
+ : [];
793
+ const parts = [
794
+ record["id"],
795
+ ...authors,
796
+ record["title"],
797
+ record["raw"],
798
+ ].filter((part) => typeof part === "string");
799
+ return [element("p", {}, [text(parts.join(" "))])];
800
+ })),
801
+ ];
802
+ }
803
+ case "publisle:raw-html":
804
+ return options.rawHtml === "omit"
805
+ ? []
806
+ : options.rawHtml === "trusted" || typeof options.rawHtml === "function"
807
+ ? [
808
+ {
809
+ kind: "raw",
810
+ value: typeof options.rawHtml === "function"
811
+ ? options.rawHtml(String(data["value"] ?? ""))
812
+ : String(data["value"] ?? ""),
813
+ },
814
+ ]
815
+ : [
816
+ element("pre", { "data-publisle-raw-html": true }, [
817
+ text(String(data["value"] ?? "")),
818
+ ]),
819
+ ];
820
+ default:
821
+ diagnostics.push({
822
+ level: "warning",
823
+ code: "missing-renderer",
824
+ message: `No renderer is available for ${block.type}.`,
825
+ blockId: block.id,
826
+ });
827
+ if ("readableContent" in block && block.readableContent) {
828
+ const content = block.readableContent;
829
+ const prose = content.fallback?.length
830
+ ? [content.fallback]
831
+ : [
832
+ content.title,
833
+ content.description,
834
+ content.purpose,
835
+ content.instructions,
836
+ content.observations,
837
+ content.assumptions,
838
+ ...(content.presets?.map((preset) => preset.description) ?? []),
839
+ ];
840
+ return [
841
+ element("section", { "data-publisle-unknown-block": block.type }, [
842
+ ...(block.readable?.provenance.kind === "generated"
843
+ ? [
844
+ element("p", { "data-publisle-generated": true }, [
845
+ text(`Generated by ${block.readable.provenance.generator} (${block.readable.provenance.version}); source: ${block.readable.provenance.source}.`),
846
+ ]),
847
+ ]
848
+ : []),
849
+ ...prose
850
+ .filter((nodes) => nodes?.length)
851
+ .map((nodes) => element("p", {}, [text(richText(nodes))])),
852
+ ]),
853
+ ];
854
+ }
855
+ return [
856
+ element("div", { "data-publisle-unknown-block": block.type }, [
857
+ text(`Unsupported block: ${block.type}`),
858
+ ]),
859
+ ];
860
+ }
861
+ }
862
+ export function createRenderPlan(document, options = {}) {
863
+ const diagnostics = [];
864
+ const nodes = applyFootnoteNumbers(document.blocks.flatMap((block) => blockNodes(block, options, diagnostics, document.references.targets, document.islands.find((island) => island.blockId === block.id)
865
+ ?.displayName, document.dependencies ?? [])), collectFootnoteNumbers(document.blocks));
866
+ const base = {
867
+ document,
868
+ nodes: wrapInputs(resolveCitations(nodes, options.citations), document),
869
+ diagnostics: diagnostics.map((diagnostic) => locateDiagnostic(diagnostic, document.sourceMap)),
870
+ };
871
+ return document.metadata === undefined
872
+ ? base
873
+ : { ...base, metadata: document.metadata };
874
+ }
875
+ /** Footnote numbers by first-reference order, over the raw block payloads. */
876
+ function collectFootnoteNumbers(blocks) {
877
+ const numbers = new Map();
878
+ const visit = (value) => {
879
+ if (Array.isArray(value)) {
880
+ value.forEach(visit);
881
+ return;
882
+ }
883
+ if (!value || typeof value !== "object")
884
+ return;
885
+ const node = value;
886
+ if (node["type"] === "footnoteReference" &&
887
+ typeof node["identifier"] === "string" &&
888
+ !numbers.has(node["identifier"]))
889
+ numbers.set(node["identifier"], numbers.size + 1);
890
+ for (const child of Object.values(node))
891
+ visit(child);
892
+ };
893
+ for (const block of blocks)
894
+ visit(block.data);
895
+ return numbers;
896
+ }
897
+ /** Replace raw footnote labels with numbers on markers and definitions. */
898
+ function applyFootnoteNumbers(nodes, numbers) {
899
+ return nodes.map((node) => {
900
+ if (node.kind !== "element")
901
+ return node;
902
+ const reference = node.tag === "sup" ? node : undefined;
903
+ const anchor = reference?.children.find((child) => child.kind === "element" &&
904
+ child.tag === "a" &&
905
+ typeof child.attributes["data-publisle-ref"] === "string" &&
906
+ child.attributes["data-publisle-ref"].startsWith("footnote-"));
907
+ if (anchor) {
908
+ const identifier = String(anchor.attributes["data-publisle-ref"]).slice("footnote-".length);
909
+ const number = numbers.get(identifier);
910
+ return number === undefined
911
+ ? node
912
+ : {
913
+ ...node,
914
+ children: node.children.map((child) => child === anchor
915
+ ? { ...anchor, children: [text(String(number))] }
916
+ : child),
917
+ };
918
+ }
919
+ if (node.tag === "aside" && typeof node.attributes["id"] === "string") {
920
+ const number = numbers.get(node.attributes["id"].slice("footnote-".length));
921
+ if (number !== undefined)
922
+ return {
923
+ ...node,
924
+ children: [
925
+ element("span", { class: "publisle-footnote-number" }, [
926
+ text(`${String(number)}. `),
927
+ ]),
928
+ ...node.children,
929
+ ],
930
+ };
931
+ }
932
+ return { ...node, children: applyFootnoteNumbers(node.children, numbers) };
933
+ });
934
+ }
935
+ function resolveCitations(nodes, citations) {
936
+ if (!citations)
937
+ return [...nodes];
938
+ return nodes.map((node) => {
939
+ if (node.kind === "island")
940
+ return { ...node, fallback: resolveCitations(node.fallback, citations) };
941
+ if (node.kind === "component" && node.artifact)
942
+ return { ...node, artifact: resolveCitations(node.artifact, citations) };
943
+ if (node.kind !== "element")
944
+ return node;
945
+ const raw = node.attributes["data-publisle-citation"];
946
+ if (typeof raw === "string") {
947
+ const key = citationKey({
948
+ items: JSON.parse(raw),
949
+ prefix: String(node.attributes["data-publisle-citation-prefix"] ?? ""),
950
+ suffix: String(node.attributes["data-publisle-citation-suffix"] ?? ""),
951
+ });
952
+ const value = citations[key];
953
+ if (value !== undefined)
954
+ return { ...node, children: [text(value)] };
955
+ }
956
+ return { ...node, children: resolveCitations(node.children, citations) };
957
+ });
958
+ }
959
+ function wrapInputs(nodes, document) {
960
+ return nodes.map((node) => {
961
+ if (node.kind === "element")
962
+ return { ...node, children: wrapInputs(node.children, document) };
963
+ if (node.kind !== "island" && !(node.kind === "component" && node.blockId))
964
+ return node;
965
+ const block = document.blocks.find((entry) => entry.id === node.blockId);
966
+ if (!block)
967
+ throw new Error("Island input requires a corresponding prepared block.");
968
+ const activation = node.kind === "island" ? node.activation : "visible";
969
+ const envelope = isInteractiveEnvelope(node.props)
970
+ ? node.props
971
+ : { activation, payload: node.props };
972
+ return {
973
+ ...node,
974
+ ...(node.kind === "island"
975
+ ? { fallback: wrapInputs(node.fallback, document) }
976
+ : {}),
977
+ props: createIslandInput(block, envelope, document.dependencies),
978
+ };
979
+ });
980
+ }
981
+ //# sourceMappingURL=render-plan-core.js.map