@standard-reader/renderer-core 0.1.0 → 0.3.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.
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Markdown content formats. Two shapes funnel through here:
3
+ *
4
+ * · `site.standard.content.markdown` — the canonical Standard Site markdown
5
+ * block (also what Greengale documents are normalized to on ingest).
6
+ * · markdown-in-record third-party lexicons (Lemma, wtr, unthread, lichen, …)
7
+ * whose body is a markdown string under a format-specific key.
8
+ *
9
+ * Every one is parsed with the unified/remark ecosystem
10
+ * (`mdast-util-from-markdown` + GFM) into an mdast tree, then mapped onto the
11
+ * shared {@link StructuredRenderableBlock} vocabulary — the same blocks every
12
+ * framework renderer already consumes, so markdown renders identically across
13
+ * them with no per-format or per-renderer code. Inline emphasis/links become
14
+ * byte-indexed AT-Proto facets, exactly like the ProseMirror/BlockNote parsers.
15
+ */
16
+ import { fromMarkdown } from "mdast-util-from-markdown";
17
+ import { gfmFromMarkdown } from "mdast-util-gfm";
18
+ import { gfm } from "micromark-extension-gfm";
19
+ import { isRecord } from "../../internal";
20
+ import { utf8ByteLength } from "../../leaflet/utf8";
21
+ import { mergeTextRuns, syntheticFacet } from "./text-runs";
22
+ import { STANDARD_MARKDOWN_CONTENT } from "./types";
23
+ const field = (key) => (content) => content[key];
24
+ /**
25
+ * Known markdown content `$type`s → the key holding the raw markdown body.
26
+ * Mirrors the host app's `ALT_MARKDOWN_EXTRACTORS`, plus the canonical
27
+ * `site.standard.content.markdown` block.
28
+ */
29
+ const MARKDOWN_EXTRACTORS = {
30
+ [STANDARD_MARKDOWN_CONTENT]: field("text"),
31
+ "actor.rpg.news#markdown": field("value"),
32
+ "app.blento.markdown": field("value"),
33
+ "app.wtr.content.markdown": field("markdown"),
34
+ "at.unthread.content": field("content"),
35
+ "com.pricelessmisc.content.markdown": field("markdown"),
36
+ "com.scanash.content.markdown": field("markdown"),
37
+ "dev.disnet.blog.content.markdown": field("markdown"),
38
+ "download.darkworld.content.markdown#markdown": field("body"),
39
+ "me.tompscanlan.content.markdown": field("markdown"),
40
+ "net.commoninternet.lichen.content.markdown": field("text"),
41
+ "pub.lemma.blog.entry": field("content"),
42
+ "rip.nate.content.markdown": field("text"),
43
+ "site.standard.document#markdown": field("value"),
44
+ };
45
+ /** Every markdown content `$type` the parser understands. */
46
+ export const MARKDOWN_FORMATS = Object.keys(MARKDOWN_EXTRACTORS);
47
+ /** Whether `format` is a known markdown content `$type`. */
48
+ export function isMarkdownFormat(format) {
49
+ return Boolean(format && format in MARKDOWN_EXTRACTORS);
50
+ }
51
+ /**
52
+ * Raw markdown body from a markdown `content` payload, or null. The format is
53
+ * resolved from `content.$type`, falling back to the stored `contentFormat`.
54
+ */
55
+ export function markdownText(content, contentFormat) {
56
+ if (!isRecord(content))
57
+ return null;
58
+ const format = typeof content.$type === "string" ? content.$type : contentFormat;
59
+ if (!format)
60
+ return null;
61
+ const extract = MARKDOWN_EXTRACTORS[format];
62
+ if (!extract)
63
+ return null;
64
+ const raw = extract(content);
65
+ return typeof raw === "string" && raw.trim() ? raw : null;
66
+ }
67
+ /** Flatten nested phrasing content into styled runs, accumulating marks. */
68
+ function collectRuns(nodes, kinds, link, out) {
69
+ for (const node of nodes) {
70
+ switch (node.type) {
71
+ case "text": {
72
+ out.push({ text: node.value, kinds, link });
73
+ break;
74
+ }
75
+ case "strong": {
76
+ collectRuns(node.children, [...kinds, "bold"], link, out);
77
+ break;
78
+ }
79
+ case "emphasis": {
80
+ collectRuns(node.children, [...kinds, "italic"], link, out);
81
+ break;
82
+ }
83
+ case "delete": {
84
+ collectRuns(node.children, [...kinds, "strikethrough"], link, out);
85
+ break;
86
+ }
87
+ case "inlineCode": {
88
+ out.push({ text: node.value, kinds: [...kinds, "code"], link });
89
+ break;
90
+ }
91
+ case "link": {
92
+ collectRuns(node.children, kinds, node.url || link, out);
93
+ break;
94
+ }
95
+ case "break": {
96
+ out.push({ text: "\n", kinds, link });
97
+ break;
98
+ }
99
+ default: {
100
+ // image (inline), html, footnoteReference, etc. carry no plain body
101
+ // we can faithfully inline — skip rather than emit noise.
102
+ break;
103
+ }
104
+ }
105
+ }
106
+ }
107
+ /** Rich text for a run of inline phrasing content. */
108
+ function inlineText(nodes) {
109
+ const runs = [];
110
+ collectRuns(nodes, [], undefined, runs);
111
+ let plaintext = "";
112
+ const facets = [];
113
+ for (const run of runs) {
114
+ const byteStart = utf8ByteLength(plaintext);
115
+ plaintext += run.text;
116
+ const facet = syntheticFacet(byteStart, utf8ByteLength(plaintext), run.kinds, run.link);
117
+ if (facet)
118
+ facets.push(facet);
119
+ }
120
+ return facets.length > 0 ? { facets, plaintext } : { plaintext };
121
+ }
122
+ // ---------------------------------------------------------------------------
123
+ // Blocks: mdast content → StructuredRenderableBlock
124
+ // ---------------------------------------------------------------------------
125
+ /** A paragraph that is a single standalone image (ignoring blank text). */
126
+ function paragraphImage(children) {
127
+ const meaningful = children.filter((child) => !(child.type === "text" && !child.value.trim()));
128
+ const only = meaningful[0];
129
+ if (meaningful.length === 1 && only?.type === "image") {
130
+ return { alt: only.alt ?? undefined, externalSrc: only.url, kind: "image" };
131
+ }
132
+ return null;
133
+ }
134
+ /** Flatten one list item to a single rich-text line (nested lists dropped —
135
+ * the structured list vocabulary is flat, matching the other parsers). */
136
+ function listItemText(item) {
137
+ const texts = item.children.flatMap((child) => child.type === "paragraph"
138
+ ? [inlineText(child.children)].filter((t) => t.plaintext.trim())
139
+ : []);
140
+ if (texts.length === 0)
141
+ return null;
142
+ if (texts.length === 1)
143
+ return texts[0];
144
+ const separated = texts.flatMap((text, index) => index === 0 ? [text] : [{ plaintext: "\n" }, text]);
145
+ return mergeTextRuns(separated);
146
+ }
147
+ function mapList(node) {
148
+ const isTaskList = node.children.some((item) => typeof item.checked === "boolean");
149
+ if (isTaskList) {
150
+ const items = node.children.flatMap((item) => {
151
+ const text = listItemText(item);
152
+ return text ? [{ checked: item.checked ?? false, text }] : [];
153
+ });
154
+ return items.length > 0 ? { items, kind: "taskList" } : null;
155
+ }
156
+ const items = node.children.flatMap((item) => {
157
+ const text = listItemText(item);
158
+ return text ? [text] : [];
159
+ });
160
+ if (items.length === 0)
161
+ return null;
162
+ return node.ordered
163
+ ? { items, kind: "orderedList", start: node.start ?? undefined }
164
+ : { items, kind: "bulletList" };
165
+ }
166
+ function mapTable(rows) {
167
+ const mapped = rows.map((row, rowIndex) => row.children.map((cell) => ({
168
+ isHeader: rowIndex === 0,
169
+ text: inlineText(cell.children),
170
+ })));
171
+ return mapped.length > 0 ? { kind: "table", rows: mapped } : null;
172
+ }
173
+ function mapBlock(node) {
174
+ switch (node.type) {
175
+ case "paragraph": {
176
+ const image = paragraphImage(node.children);
177
+ if (image)
178
+ return [image];
179
+ const text = inlineText(node.children);
180
+ return text.plaintext.trim() ? [{ kind: "text", text }] : [];
181
+ }
182
+ case "heading": {
183
+ const text = inlineText(node.children);
184
+ return text.plaintext.trim()
185
+ ? [{ kind: "heading", level: node.depth, text }]
186
+ : [];
187
+ }
188
+ case "blockquote": {
189
+ const blocks = node.children.flatMap(mapBlock);
190
+ return blocks.length > 0 ? [{ blocks, kind: "blockquote" }] : [];
191
+ }
192
+ case "thematicBreak": {
193
+ return [{ kind: "horizontalRule" }];
194
+ }
195
+ case "code": {
196
+ return [
197
+ {
198
+ kind: "code",
199
+ language: node.lang ?? undefined,
200
+ plaintext: node.value,
201
+ },
202
+ ];
203
+ }
204
+ case "list": {
205
+ const list = mapList(node);
206
+ return list ? [list] : [];
207
+ }
208
+ case "table": {
209
+ const table = mapTable(node.children);
210
+ return table ? [table] : [];
211
+ }
212
+ case "image": {
213
+ return [
214
+ { alt: node.alt ?? undefined, externalSrc: node.url, kind: "image" },
215
+ ];
216
+ }
217
+ default: {
218
+ // html, definition, footnoteDefinition, yaml, etc. — nothing to render.
219
+ return [];
220
+ }
221
+ }
222
+ }
223
+ /**
224
+ * Renderable blocks for a raw markdown string, or null when it is blank or
225
+ * parses to nothing. Formats that carry markdown but need normalizing first
226
+ * (Markpub strips front matter and applies facets) go through here rather than
227
+ * {@link markdownBlocks}.
228
+ */
229
+ export function markdownBlocksFromText(text, flavor = "gfm") {
230
+ const body = text.trim();
231
+ if (!body)
232
+ return null;
233
+ const tree = fromMarkdown(body, flavor === "commonmark"
234
+ ? {}
235
+ : { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] });
236
+ const blocks = tree.children.flatMap(mapBlock);
237
+ return blocks.length > 0 ? blocks : null;
238
+ }
239
+ /**
240
+ * Renderable blocks for a markdown `content` payload, or null when the format
241
+ * isn't markdown or the body is empty. Registered for every
242
+ * {@link MARKDOWN_FORMATS} entry so {@link structuredFormatBlocks} — and thus
243
+ * `buildRenderTree` — handles markdown like any other structured format.
244
+ */
245
+ export function markdownBlocks(content, contentFormat) {
246
+ const text = markdownText(content, contentFormat);
247
+ if (!text)
248
+ return null;
249
+ return markdownBlocksFromText(text);
250
+ }
251
+ //# sourceMappingURL=markdown.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdown.js","sourceRoot":"","sources":["../../../src/document/structured-content/markdown.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAQH,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,MAAM,yBAAyB,CAAC;AAE9C,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAM5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAC;AAIpD,MAAM,KAAK,GACT,CAAC,GAAW,EAAqB,EAAE,CACnC,CAAC,OAAO,EAAE,EAAE,CACV,OAAO,CAAC,GAAG,CAAC,CAAC;AAEjB;;;;GAIG;AAC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,EAAE,IAAI,CAAC,GAAG,IAAI,SAAS,EAAE,WAAW,EAAE,IAAI,CAAC,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE;aACrE,CAAC;QACJ,CAAC;QACD,OAAO,CAAC,CAAC,CAAC;YACR,wEAAwE;YACxE,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;AACH,CAAC;AAMD;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,IAAY,EACZ,SAAyB,KAAK;IAE9B,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;IACzB,IAAI,CAAC,IAAI;QAAE,OAAO,IAAI,CAAC;IACvB,MAAM,IAAI,GAAS,YAAY,CAC7B,IAAI,EACJ,MAAM,KAAK,YAAY;QACrB,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,eAAe,EAAE,CAAC,eAAe,EAAE,CAAC,EAAE,CAClE,CAAC;IACF,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC/C,OAAO,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;AAC3C,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAC5B,OAAgB,EAChB,aAA6B;IAE7B,MAAM,IAAI,GAAG,YAAY,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;IAClD,IAAI,CAAC,IAAI;QAAE,OAAO,IAAI,CAAC;IACvB,OAAO,sBAAsB,CAAC,IAAI,CAAC,CAAC;AACtC,CAAC"}
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Markpub (`at.markpub.markdown`) — the markdown content format used by
3
+ * Mochott and anything else built on the Markpub lexicon.
4
+ *
5
+ * Unlike the plain markdown-in-record formats (see `markdown.ts`), a Markpub
6
+ * payload is markdown *plus* out-of-band metadata:
7
+ *
8
+ * · `flavor` — `gfm` (default) or `commonmark`.
9
+ * · `extensions` — declared syntax extensions (`yaml`, `latex`, …).
10
+ * · `frontMatter` — when present (or the `yaml` extension is declared), a
11
+ * leading YAML block is metadata, not body.
12
+ * · `text.facets` — byte-indexed facets over the *markdown source*. Most are
13
+ * redundant with the syntax already in the source, but some formats
14
+ * (headers, strong, horizontal rules, front matter) are expressed *only*
15
+ * as facets, with the source left unmarked.
16
+ * · `text.lenses` — alias groups that map a publisher's own facet `$type`s
17
+ * onto the canonical ones.
18
+ *
19
+ * So rendering is: normalize facet `$type`s through the lenses, rewrite the
20
+ * facet-only constructs back into markdown syntax, strip front matter, then
21
+ * hand the result to the shared markdown parser. Everything lands in the same
22
+ * {@link StructuredRenderableBlock} vocabulary as every other format — no
23
+ * Markpub-specific node types and no per-renderer code.
24
+ *
25
+ * Two knowingly-dropped details: `#idify` heading anchors (the block
26
+ * vocabulary has no heading id) and the `latex` extension (core's markdown
27
+ * parser has no math extension, so `$$…$$` stays literal text).
28
+ */
29
+ import type { LeafletFacet } from "../../leaflet/types";
30
+ import type { MarkdownFlavor } from "./markdown";
31
+ import type { StructuredRenderableBlock } from "./types";
32
+ export declare const MARKPUB_MARKDOWN = "at.markpub.markdown";
33
+ export declare const MARKPUB_TEXT = "at.markpub.text";
34
+ /** Content `$type`s handled by this module. */
35
+ export declare const MARKPUB_FORMATS: string[];
36
+ export declare function isMarkpubFormat(format: string | null | undefined): boolean;
37
+ /** A lens: a group of facet `$type`s that all mean the same thing. */
38
+ export interface MarkpubLens {
39
+ facets: Array<{
40
+ $type?: string;
41
+ }>;
42
+ }
43
+ export interface MarkpubDocument {
44
+ markdown: string;
45
+ flavor: MarkdownFlavor;
46
+ extensions: Array<string>;
47
+ frontMatter: Array<unknown>;
48
+ facets: Array<LeafletFacet>;
49
+ lenses: Array<MarkpubLens>;
50
+ }
51
+ /** Parse an `at.markpub.markdown` (or bare `at.markpub.text`) payload. */
52
+ export declare function parseMarkpubContent(content: unknown): MarkpubDocument | null;
53
+ /** Rewrite facet feature `$type`s onto their canonical form via the lenses. */
54
+ export declare function normalizeMarkpubFacets(facets: Array<LeafletFacet>, lenses: Array<MarkpubLens>): Array<LeafletFacet>;
55
+ /**
56
+ * Apply Markpub facets to the markdown source. Applied back-to-front so each
57
+ * splice leaves earlier byte offsets valid.
58
+ */
59
+ export declare function applyMarkpubFacets(markdown: string, facets: Array<LeafletFacet>): string;
60
+ export interface PreparedMarkpubMarkdown {
61
+ body: string;
62
+ flavor: MarkdownFlavor;
63
+ }
64
+ /**
65
+ * Normalize an `at.markpub.markdown` payload into plain renderable markdown:
66
+ * strip front matter, apply facet transforms, honor the declared flavor.
67
+ */
68
+ export declare function prepareMarkpubMarkdown(content: unknown): PreparedMarkpubMarkdown | null;
69
+ /**
70
+ * Renderable blocks for an `at.markpub.markdown` payload, or null when the
71
+ * format doesn't match or the body is empty. Registered for every
72
+ * {@link MARKPUB_FORMATS} entry so `buildRenderTree` handles Markpub like any
73
+ * other structured format.
74
+ */
75
+ export declare function markpubBlocks(content: unknown, contentFormat?: string | null): Array<StructuredRenderableBlock> | null;
76
+ //# sourceMappingURL=markpub.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markpub.d.ts","sourceRoot":"","sources":["../../../src/document/structured-content/markpub.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AAE7E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAC;AAEzD,eAAO,MAAM,gBAAgB,wBAAwB,CAAC;AACtD,eAAO,MAAM,YAAY,oBAAoB,CAAC;AAE9C,+CAA+C;AAC/C,eAAO,MAAM,eAAe,UAAmC,CAAC;AAEhE,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,G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by
3
+ * Mochott and anything else built on the Markpub lexicon.
4
+ *
5
+ * Unlike the plain markdown-in-record formats (see `markdown.ts`), a Markpub
6
+ * payload is markdown *plus* out-of-band metadata:
7
+ *
8
+ * · `flavor` — `gfm` (default) or `commonmark`.
9
+ * · `extensions` — declared syntax extensions (`yaml`, `latex`, …).
10
+ * · `frontMatter` — when present (or the `yaml` extension is declared), a
11
+ * leading YAML block is metadata, not body.
12
+ * · `text.facets` — byte-indexed facets over the *markdown source*. Most are
13
+ * redundant with the syntax already in the source, but some formats
14
+ * (headers, strong, horizontal rules, front matter) are expressed *only*
15
+ * as facets, with the source left unmarked.
16
+ * · `text.lenses` — alias groups that map a publisher's own facet `$type`s
17
+ * onto the canonical ones.
18
+ *
19
+ * So rendering is: normalize facet `$type`s through the lenses, rewrite the
20
+ * facet-only constructs back into markdown syntax, strip front matter, then
21
+ * hand the result to the shared markdown parser. Everything lands in the same
22
+ * {@link StructuredRenderableBlock} vocabulary as every other format — no
23
+ * Markpub-specific node types and no per-renderer code.
24
+ *
25
+ * Two knowingly-dropped details: `#idify` heading anchors (the block
26
+ * vocabulary has no heading id) and the `latex` extension (core's markdown
27
+ * parser has no math extension, so `$$…$$` stays literal text).
28
+ */
29
+ import { isRecord } from "../../internal";
30
+ import { sliceUtf8, utf8ByteLength } from "../../leaflet/utf8";
31
+ import { markdownBlocksFromText } from "./markdown";
32
+ export const MARKPUB_MARKDOWN = "at.markpub.markdown";
33
+ export const MARKPUB_TEXT = "at.markpub.text";
34
+ /** Content `$type`s handled by this module. */
35
+ export const MARKPUB_FORMATS = [MARKPUB_MARKDOWN, MARKPUB_TEXT];
36
+ export function isMarkpubFormat(format) {
37
+ return format === MARKPUB_MARKDOWN || format === MARKPUB_TEXT;
38
+ }
39
+ // ---------------------------------------------------------------------------
40
+ // Parsing the record payload
41
+ // ---------------------------------------------------------------------------
42
+ function parseFacet(value) {
43
+ if (!isRecord(value) || !isRecord(value.index))
44
+ return null;
45
+ const byteStart = value.index.byteStart;
46
+ const byteEnd = value.index.byteEnd;
47
+ if (typeof byteStart !== "number" || typeof byteEnd !== "number")
48
+ return null;
49
+ if (!Array.isArray(value.features))
50
+ return null;
51
+ const features = value.features.filter((feature) => isRecord(feature) && typeof feature.$type === "string");
52
+ if (features.length === 0)
53
+ return null;
54
+ return { features, index: { byteEnd, byteStart } };
55
+ }
56
+ function parseFacets(value) {
57
+ if (!Array.isArray(value))
58
+ return [];
59
+ return value
60
+ .map((facet) => parseFacet(facet))
61
+ .filter((facet) => facet != null)
62
+ .toSorted((a, b) => a.index.byteStart - b.index.byteStart);
63
+ }
64
+ function parseLenses(value) {
65
+ if (!Array.isArray(value))
66
+ return [];
67
+ return value.flatMap((entry) => {
68
+ if (!isRecord(entry) || !Array.isArray(entry.facets))
69
+ return [];
70
+ const facets = entry.facets.filter((facet) => isRecord(facet) && typeof facet.$type === "string");
71
+ return facets.length > 0 ? [{ facets }] : [];
72
+ });
73
+ }
74
+ function parseFlavor(value) {
75
+ return value === "commonmark" ? "commonmark" : "gfm";
76
+ }
77
+ function parseExtensions(value) {
78
+ if (!Array.isArray(value))
79
+ return [];
80
+ return value.filter((entry) => typeof entry === "string");
81
+ }
82
+ /** `text` is normally an `at.markpub.text` record; tolerate a bare string. */
83
+ function textPayload(content) {
84
+ const text = content.text;
85
+ if (isRecord(text))
86
+ return text;
87
+ if (typeof text === "string")
88
+ return { $type: MARKPUB_TEXT, markdown: text };
89
+ return null;
90
+ }
91
+ function documentFromText(text, meta) {
92
+ const markdown = typeof text.markdown === "string" ? text.markdown.trim() : "";
93
+ if (!markdown)
94
+ return null;
95
+ return {
96
+ extensions: meta.extensions,
97
+ facets: parseFacets(text.facets),
98
+ flavor: meta.flavor,
99
+ frontMatter: meta.frontMatter,
100
+ lenses: parseLenses(text.lenses),
101
+ markdown,
102
+ };
103
+ }
104
+ /** Parse an `at.markpub.markdown` (or bare `at.markpub.text`) payload. */
105
+ export function parseMarkpubContent(content) {
106
+ if (!isRecord(content))
107
+ return null;
108
+ if (content.$type === MARKPUB_MARKDOWN) {
109
+ const text = textPayload(content);
110
+ if (!text)
111
+ return null;
112
+ return documentFromText(text, {
113
+ extensions: parseExtensions(content.extensions),
114
+ flavor: parseFlavor(content.flavor),
115
+ frontMatter: Array.isArray(content.frontMatter)
116
+ ? content.frontMatter
117
+ : [],
118
+ });
119
+ }
120
+ if (content.$type === MARKPUB_TEXT) {
121
+ return documentFromText(content, {
122
+ extensions: [],
123
+ flavor: "gfm",
124
+ frontMatter: [],
125
+ });
126
+ }
127
+ return null;
128
+ }
129
+ // ---------------------------------------------------------------------------
130
+ // Facets → markdown syntax
131
+ // ---------------------------------------------------------------------------
132
+ /** Canonical facet kinds this module understands after lens normalization. */
133
+ const KNOWN_FACET_ALIASES = {
134
+ bold: "strong",
135
+ code: "code",
136
+ didMention: "mention",
137
+ header: "header",
138
+ highlight: "highlight",
139
+ horizontalRule: "horizontalRule",
140
+ idify: "idify",
141
+ italic: "italic",
142
+ link: "link",
143
+ mention: "mention",
144
+ raw: "raw",
145
+ strikethrough: "strikethrough",
146
+ strong: "strong",
147
+ underline: "underline",
148
+ "yaml-front-matter": "yaml-front-matter",
149
+ };
150
+ function facetFeatureSuffix($type) {
151
+ if (!$type)
152
+ return null;
153
+ const hash = $type.indexOf("#");
154
+ return hash === -1 ? null : $type.slice(hash + 1);
155
+ }
156
+ function featureKind(feature) {
157
+ const kind = facetFeatureSuffix(feature.$type);
158
+ return kind ? (KNOWN_FACET_ALIASES[kind] ?? kind) : null;
159
+ }
160
+ /** `$type` → canonical `$type`, from every lens that groups two or more. */
161
+ function buildLensMap(lenses) {
162
+ const map = new Map();
163
+ for (const lens of lenses) {
164
+ const types = lens.facets
165
+ .map((facet) => facet.$type)
166
+ .filter((type) => typeof type === "string");
167
+ if (types.length < 2)
168
+ continue;
169
+ const first = types[0];
170
+ if (first === undefined)
171
+ continue;
172
+ const canonical = featureKind({ $type: first }) ?? first;
173
+ for (const type of types)
174
+ map.set(type, canonical);
175
+ }
176
+ return map;
177
+ }
178
+ function normalizeFeature(feature, lensMap) {
179
+ const type = feature.$type;
180
+ if (!type)
181
+ return feature;
182
+ const canonicalType = lensMap.get(type);
183
+ if (!canonicalType)
184
+ return feature;
185
+ if (canonicalType === featureKind(feature))
186
+ return feature;
187
+ const hash = type.indexOf("#");
188
+ const prefix = hash === -1 ? type : type.slice(0, hash + 1);
189
+ return { ...feature, $type: `${prefix}${canonicalType}` };
190
+ }
191
+ /** Rewrite facet feature `$type`s onto their canonical form via the lenses. */
192
+ export function normalizeMarkpubFacets(facets, lenses) {
193
+ const lensMap = buildLensMap(lenses);
194
+ if (lensMap.size === 0)
195
+ return facets;
196
+ return facets.map((facet) => ({
197
+ ...facet,
198
+ features: facet.features.map((feature) => normalizeFeature(feature, lensMap)),
199
+ }));
200
+ }
201
+ function hasFeatureKind(features, kind) {
202
+ return features.some((feature) => featureKind(feature) === kind);
203
+ }
204
+ function headerLevel(features) {
205
+ for (const feature of features) {
206
+ const level = feature.level;
207
+ if (featureKind(feature) === "header" && typeof level === "number") {
208
+ return Math.min(6, Math.max(1, level));
209
+ }
210
+ }
211
+ return 1;
212
+ }
213
+ function stripHeaderSyntax(text) {
214
+ return text.replace(/^#{1,6}\s+/, "").trimEnd();
215
+ }
216
+ function stripStrongSyntax(text) {
217
+ const trimmed = text.trim();
218
+ const doubleStar = /^\*\*([\S\s]+)\*\*$/.exec(trimmed);
219
+ if (doubleStar?.[1])
220
+ return doubleStar[1];
221
+ const doubleUnderscore = /^__([\S\s]+)__$/.exec(trimmed);
222
+ if (doubleUnderscore?.[1])
223
+ return doubleUnderscore[1];
224
+ return trimmed;
225
+ }
226
+ /**
227
+ * The markdown a faceted range should become, or null to leave it as-is.
228
+ *
229
+ * The app renderer rewrites these to inline HTML and leans on `rehype-raw`;
230
+ * here they become markdown syntax instead, so the constructs survive core's
231
+ * markdown parser (which drops raw HTML nodes) and arrive as real heading /
232
+ * strong / horizontal-rule blocks.
233
+ */
234
+ function facetReplacement(text, features) {
235
+ if (hasFeatureKind(features, "yaml-front-matter"))
236
+ return "";
237
+ if (hasFeatureKind(features, "horizontalRule"))
238
+ return "\n\n---\n\n";
239
+ if (hasFeatureKind(features, "raw"))
240
+ return text;
241
+ if (hasFeatureKind(features, "header")) {
242
+ const hashes = "#".repeat(headerLevel(features));
243
+ return `\n\n${hashes} ${stripHeaderSyntax(text)}\n\n`;
244
+ }
245
+ if (hasFeatureKind(features, "strong")) {
246
+ return `**${stripStrongSyntax(text)}**`;
247
+ }
248
+ return null;
249
+ }
250
+ function spliceUtf8(text, byteStart, byteEnd, replacement) {
251
+ const before = sliceUtf8(text, 0, byteStart);
252
+ const after = sliceUtf8(text, byteEnd, utf8ByteLength(text));
253
+ return `${before}${replacement}${after}`;
254
+ }
255
+ /**
256
+ * Apply Markpub facets to the markdown source. Applied back-to-front so each
257
+ * splice leaves earlier byte offsets valid.
258
+ */
259
+ export function applyMarkpubFacets(markdown, facets) {
260
+ if (facets.length === 0)
261
+ return markdown;
262
+ let result = markdown;
263
+ const ordered = facets.toSorted((a, b) => b.index.byteStart - a.index.byteStart);
264
+ for (const facet of ordered) {
265
+ const { byteStart, byteEnd } = facet.index;
266
+ if (byteEnd <= byteStart)
267
+ continue;
268
+ const slice = sliceUtf8(result, byteStart, byteEnd);
269
+ const replacement = facetReplacement(slice, facet.features);
270
+ if (replacement === null)
271
+ continue;
272
+ result = spliceUtf8(result, byteStart, byteEnd, replacement);
273
+ }
274
+ return result.replace(/^\s+/, "");
275
+ }
276
+ // ---------------------------------------------------------------------------
277
+ // Public entry points
278
+ // ---------------------------------------------------------------------------
279
+ const YAML_FRONT_MATTER = /^---\r?\n[\S\s]*?\r?\n---\r?\n?/;
280
+ function hasExtension(extensions, ...names) {
281
+ return extensions.some((entry) => names.includes(entry.toLowerCase()));
282
+ }
283
+ /**
284
+ * Normalize an `at.markpub.markdown` payload into plain renderable markdown:
285
+ * strip front matter, apply facet transforms, honor the declared flavor.
286
+ */
287
+ export function prepareMarkpubMarkdown(content) {
288
+ const doc = parseMarkpubContent(content);
289
+ if (!doc)
290
+ return null;
291
+ let body = doc.markdown;
292
+ if (doc.frontMatter.length > 0 ||
293
+ hasExtension(doc.extensions, "yaml", "yml")) {
294
+ body = body.replace(YAML_FRONT_MATTER, "").trimStart();
295
+ }
296
+ body = applyMarkpubFacets(body, normalizeMarkpubFacets(doc.facets, doc.lenses)).trim();
297
+ if (!body)
298
+ return null;
299
+ return { body, flavor: doc.flavor };
300
+ }
301
+ /**
302
+ * Renderable blocks for an `at.markpub.markdown` payload, or null when the
303
+ * format doesn't match or the body is empty. Registered for every
304
+ * {@link MARKPUB_FORMATS} entry so `buildRenderTree` handles Markpub like any
305
+ * other structured format.
306
+ */
307
+ export function markpubBlocks(content, contentFormat) {
308
+ const format = isRecord(content) && typeof content.$type === "string"
309
+ ? content.$type
310
+ : contentFormat;
311
+ if (!isMarkpubFormat(format))
312
+ return null;
313
+ // Records that carry the format only in `contentFormat` still need a `$type`
314
+ // for the payload parser to dispatch on.
315
+ const payload = isRecord(content) && typeof content.$type !== "string"
316
+ ? { ...content, $type: format }
317
+ : content;
318
+ const prepared = prepareMarkpubMarkdown(payload);
319
+ if (!prepared)
320
+ return null;
321
+ return markdownBlocksFromText(prepared.body, prepared.flavor);
322
+ }
323
+ //# sourceMappingURL=markpub.js.map