mdld-parse 1.0.6 → 1.0.8

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 (3) hide show
  1. package/README.md +142 -3
  2. package/dist/index.js +379 -42
  3. package/package.json +10 -9
package/README.md CHANGED
@@ -43,7 +43,7 @@ pnpm install mdld-parse
43
43
  ```
44
44
 
45
45
  ```javascript
46
- import { parse, generate, merge } from 'mdld-parse';
46
+ import { parse, generate, merge, render, deconstruct } from 'mdld-parse';
47
47
 
48
48
  // Parse MDLD to RDF quads
49
49
  const result = parse({ text: mdldString });
@@ -55,6 +55,16 @@ console.log(result.origin); // Provenance tracking
55
55
  // Generate MDLD from quads
56
56
  const { text } = generate({ quads: result.quads });
57
57
 
58
+ // Render to semantic HTML with preserved annotations
59
+ const html = render(mdldString);
60
+
61
+ // Reconstruct MDLD from HTML (lossless roundtrip)
62
+ const reconstructed = deconstruct(html);
63
+ const quads = parse(reconstructed).quads; // Same quads as original!
64
+
65
+ // Lossy rendering for privacy-preserving publishing
66
+ const cleanHtml = render(parse(mdldString).md);
67
+
58
68
  // Merge multiple documents (CRDT-style)
59
69
  const merged = merge([doc1, doc2, doc3]);
60
70
  ```
@@ -128,6 +138,15 @@ Authored by [Alice Johnson] {+alice:alice-johnson ?alice:author} on [2026-08-12]
128
138
  [MD-LD] {blog:emphasized} allows you to embed RDF directly in Markdown.
129
139
  ```
130
140
 
141
+ #### Local-First Personal Knowledge Base
142
+ ```markdown
143
+ [alice] <tag:alice@example.com,2026:>
144
+
145
+ # Meeting with Bob {=alice:meeting-2026-01-21 .Meeting label}
146
+ Attendees: [Alice] {=alice:alice}, [Bob] {+alice:bob ?attendees}
147
+ Location: [Coffee Shop] {alice:location}
148
+ Discussed [Project Alpha] {alice:discussed}
149
+
131
150
  ## ✨ Core Features
132
151
 
133
152
  - **🔗 Prefix folding** — Build hierarchical namespaces with CURIE-based IRI authoring
@@ -143,8 +162,9 @@ Authored by [Alice Johnson] {+alice:alice-johnson ?alice:author} on [2026-08-12]
143
162
  - **🎯 Elevated statements** — Automatic rdf:Statement pattern detection
144
163
  - **🏷️ Primary metadata quartet** — Subject, type, label, comment for document identity
145
164
  - **🔄 Round-trip safety** — Deterministic parse ↔ generate cycles
165
+ - **🌐 HTML Codec** — Lossless `render()` and `deconstruct()` pair for web publishing
146
166
 
147
- **Bundle size:** 86KB unminified, 20KB gzipped
167
+ **Bundle size:** 101KB unminified, 24KB gzipped
148
168
 
149
169
  ## 📦 Installation
150
170
 
@@ -352,6 +372,10 @@ Parse MDLD to RDF quads with lean origin tracking.
352
372
  - `primary` — Primary metadata quartet: `{ subject, type, label, comment }`
353
373
  - `md` — Clean Markdown with annotations stripped
354
374
 
375
+ `primarySubject` is useful to allow each iri have it's page and vice versa - so we can have arbitrary MD content attached to it. This is where we can render the `md` on the entity page if we have it in our custom `const pages = new Map()`.
376
+
377
+ `md` is useful to detect parsing success: `if(originalText!=parsed.md) {console.log('Parse success. Total annotations: ', originalText.length-md.length) letters.`
378
+
355
379
  ### `merge(docs, options)`
356
380
 
357
381
  Merge multiple MDLD documents with diff polarity resolution.
@@ -438,6 +462,74 @@ Locate quad origin entry for UI navigation.
438
462
 
439
463
  **Returns:** `{ blockId, range, valueRange, carrierType, ... }` or `null`
440
464
 
465
+ ### `render(mdld, options?)`
466
+
467
+ Convert MD-LD to semantic HTML with preserved annotations.
468
+
469
+ **Parameters:**
470
+ - `mdld` (string, required) — MD-LD formatted text
471
+ - `options` (object, optional):
472
+ - `context` (object) — Additional prefix mappings
473
+
474
+ **Returns:** `string` — Semantic HTML with `data-annotation` attributes
475
+
476
+ **Features:**
477
+ - Preserves complete MD-LD syntax in `data-annotation` for roundtrip reconstruction
478
+ - Resolves IRIs into `data-iri` attributes for easy querying
479
+ - Adds semantic CSS classes: `.mdld-heading`, `.mdld-link`, `.typed`, `.retracted`
480
+ - Platform-agnostic: works in Node.js, Deno, browsers, edge workers
481
+
482
+ **Example:**
483
+ ```javascript
484
+ const html = render('# Alice {=ex:alice .Person label}');
485
+ ```
486
+ produces
487
+ ```html
488
+ <h1 class="mdld-heading typed"
489
+ data-annotation="{=ex:alice .Person label}"
490
+ data-iri="http://example.org/alice">Alice</h1>
491
+ ```
492
+
493
+ ### `deconstruct(html)`
494
+
495
+ Reconstruct MD-LD from rendered HTML via pure string scanning.
496
+
497
+ **Parameters:**
498
+ - `html` (string, required) — HTML produced by `render()`
499
+
500
+ **Returns:** `string` — Reconstructed MD-LD text
501
+
502
+ **Roundtrip invariant:**
503
+ ```javascript
504
+ parse(deconstruct(render(mdld))).quads === parse(mdld).quads
505
+ ```
506
+
507
+ **Example:**
508
+ ```javascript
509
+ const html = '<h1 data-annotation="{=ex:alice .Person label}">Alice</h1>';
510
+ const mdld = deconstruct(html);
511
+ // # Alice {=ex:alice .Person label}
512
+ ```
513
+
514
+ **Use cases:**
515
+ - Server-side rendering: render MD-LD to HTML, send to client
516
+ - Client-side graph extraction: `parse(deconstruct(document.body.innerHTML))`
517
+ - Offline-first apps: cache HTML, reconstruct quads on demand
518
+
519
+ ## Styling by Type
520
+
521
+ Use CSS attribute selectors to style elements by their RDF types:
522
+
523
+ ```css
524
+ /* Style all Person entities */
525
+ [data-iri$="Person"] { color: green; }
526
+
527
+ /* Style all Recipe entities */
528
+ [data-types*="Recipe"] { background: #fff3cd; }
529
+
530
+ /* Style entities with specific IRI */
531
+ [data-iri="http://example.org/alice"] { font-weight: bold; }
532
+
441
533
  ### Utility Functions
442
534
 
443
535
  ```javascript
@@ -454,13 +546,14 @@ import {
454
546
  ## 🏗️ Architecture
455
547
 
456
548
  ### Design Principles
457
- - **Zero dependencies** — Pure JavaScript, 85KB unminified (20KB gzipped)
549
+ - **Zero dependencies** — Pure JavaScript, 101KB unminified (24KB gzipped)
458
550
  - **Streaming-first** — Single-pass parsing, O(n) complexity
459
551
  - **Character-based tokenization** — 20-28% faster than regex-based approaches
460
552
  - **Standards-compliant** — RDF/JS data model, W3C CURIE 1.0 syntax
461
553
  - **Deterministic** — Same input always produces same output
462
554
  - **Explicit semantics** — No guessing, inference, or heuristics
463
555
  - **Dual-layer origin** — Every parse emits both a semantic quad graph and a walkable textual topology graph simultaneously
556
+ - **HTML as codec** — Lossless roundtrip between MD-LD and HTML via `render()`/`deconstruct()`
464
557
 
465
558
  ### Origin: Blocks and Spans
466
559
 
@@ -475,6 +568,42 @@ The parser output includes a complete document chain at no extra cost:
475
568
 
476
569
  Spans store no text — content is always recovered via `sourceText.slice(span.range[0], span.range[1])`. This unlocks context-aware UI, autocomplete neighborhood retrieval, and cross-document topology without any parser-level interpretation.
477
570
 
571
+ ### HTML Codec: Server/Client Equivalence
572
+
573
+ The `render()` and `deconstruct()` pair enables two equivalent workflows:
574
+
575
+ **Server-Side Rendering (SSR):**
576
+ ```
577
+ MD-LD files → render() → HTML → Browser
578
+ ↓
579
+ deconstruct() → parse() → quads
580
+ ```
581
+
582
+ **Client-Side Rendering (CSR):**
583
+ ```
584
+ MD-LD files → Browser → render() → HTML
585
+ ↓
586
+ deconstruct() → parse() → quads
587
+ ```
588
+
589
+ Both modes produce identical quads. The choice depends on your deployment model:
590
+ - **SSR:** Better for SEO, faster initial page load, works without JavaScript
591
+ - **CSR:** Better for offline-first apps, reduces server load, enables dynamic updates
592
+
593
+ **Bandwidth optimization:**
594
+ - Full fidelity: `render(mdld)` includes `data-annotation` for roundtrip
595
+ - Lossy mode: `render(parse(mdld).md)` strips annotations for privacy-preserving publishing
596
+ - HTML payload is 2-3x smaller than MD-LD + JSON-LD combination
597
+
598
+ **Use cases:**
599
+ - Personal knowledge bases (Obsidian-like, web-native)
600
+ - Community wikis with semantic search
601
+ - Offline-first research notes with citations
602
+ - Collaborative task management with provenance
603
+ - Reading lists that become knowledge graphs
604
+ - Meeting notes with automatic linking
605
+ - Decentralized community event calendars
606
+
478
607
  ### Performance Characteristics
479
608
  - **Real-time (60fps):** Up to 4,527 quads per frame
480
609
  - **Batch processing:** Up to 225,059 quads per second
@@ -508,6 +637,7 @@ Comprehensive test suite covering:
508
637
  - Elevated statements detection
509
638
  - Primary metadata extraction
510
639
  - Round-trip parse/generate cycles
640
+ - HTML codec roundtrip — `mdld = deconstruct(render(mdld))`
511
641
  - Origin tracking and provenance
512
642
 
513
643
 
@@ -517,9 +647,11 @@ Comprehensive test suite covering:
517
647
  - [Formal Specification](./spec/Spec.md)
518
648
  - [Compact Spec](./spec/Spec-compact.md)
519
649
  - [Ultra Compact Spec](./spec/Spec-ultra.md)
650
+
520
651
  - **📚 [Grammar](./grammar/index.md)** — EBNF+TextMate grammar specifications
521
652
  - [The TextMate grammar](./grammar/mdld.tmLanguage.json)
522
653
  - [ISO 14977 EBNF grammar](./grammar/mdld.ebnf)
654
+
523
655
  - **📖 [Documentation](./docs/index.md)** — Complete documentation with guides and references
524
656
  - [MD-LD Authoring Guide](./docs/Guide.md)
525
657
  - [One Page Guide](./docs/one-page.md)
@@ -531,6 +663,7 @@ Comprehensive test suite covering:
531
663
  - [Subject System](./docs/Subject.md)
532
664
  - [API Reference](./docs/API.md)
533
665
  - [Generate: Quads to MDLD](./docs/generate.md)
666
+ - [Render MDLD to HTML and deconstruct it back](./docs/render.md)
534
667
  - [Diff Documents](./docs/diff.md)
535
668
  - [Syntax Reference](./docs/Syntax.md)
536
669
  - [Architecture & Design](./docs/Architecture.md)
@@ -541,6 +674,7 @@ Comprehensive test suite covering:
541
674
  - [Human-Scale Software & Semantic Infrastructure](./docs/Human-Scale.md)
542
675
  - [Quad[] as a Universal Semantic Runtime](./docs/quad-runtime.md)
543
676
  - [Use Cases](./docs/Use-Cases.md)
677
+
544
678
  - **🎯 [Examples](./examples/index.md)** — Real-world MD-LD examples and use cases
545
679
  - [Minimal](./examples/demo/minimal.md)
546
680
  - [One-Page Guide](./examples/one-page.md)
@@ -553,6 +687,7 @@ Comprehensive test suite covering:
553
687
  - [Task Management System](./examples/demo/tasks.md)
554
688
  - [Cassini-Huygens Mission](./examples/demo/space-mission.md)
555
689
  - [RDF Fundamentals](./examples/demo/rdf.md)
690
+ - [Statements Golden Graph](./examples/statements.md)
556
691
  - [PROV-O Patterns](./examples/demo/prov.md)
557
692
  - [SHACL Validation](./examples/demo/shacl.md)
558
693
  - [XSD Datatypes](./examples/demo/xsd.md)
@@ -560,6 +695,10 @@ Comprehensive test suite covering:
560
695
  - [LLM Time Workflow](./examples/llm-time-workflow.md)
561
696
  - [Research Workflow](./examples/workflow.md)
562
697
  - [Dogfood](./examples/dogfood.md)
698
+
699
+ - **💻 [Reference server](./server/index.md) - a Node.js implementation of the server for git-powered semantic workflows and publishing
700
+ - [Source code](./server/mdld-server.js)
701
+
563
702
  - **🧩 [Ontologies](./ontologies/index.md)** — W3C and related standard ontologies used in RDF
564
703
  - [RDF — Resource Description Framework](./ontologies/rdf.md)
565
704
  - [RDFS — RDF Schema](./ontologies/rdfs.md)
package/dist/index.js CHANGED
@@ -910,6 +910,10 @@ function resolveObject(sem, state) {
910
910
  if (sem.object.startsWith("#")) return resolveFragment(sem.object.substring(1), state.currentSubject, state.df);
911
911
  return state.df.namedNode(expandIRI(sem.object, state.ctx));
912
912
  }
913
+ function escapeHtml$1(text) {
914
+ if (!text) return "";
915
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
916
+ }
913
917
  function isLiteral(term) {
914
918
  return term?.termType === "Literal";
915
919
  }
@@ -1841,13 +1845,15 @@ function generateNode({ quads, focusIRI, context = {}, compactInline = true, ren
1841
1845
  compactStats: null
1842
1846
  };
1843
1847
  const fullContext = Object.assign({}, DEFAULT_CONTEXT, context);
1844
- const { nodeGroups, reverseIndex } = groupQuadsByNode(normalizeAndSortQuads(quads));
1845
- if (!nodeGroups.has(focusIRI)) return {
1848
+ const normalizedQuads = normalizeAndSortQuads(quads.filter((q) => q.subject.value === focusIRI || q.predicate.value === focusIRI || q.object.value === focusIRI || q.object.termType === "Literal" && q.object.datatype && (q.object.datatype.value || q.object.datatype) === focusIRI));
1849
+ const { subjectGroups: nodeGroups, reverseIndex } = groupQuadsBySubject(normalizedQuads);
1850
+ const subjectRoots = Array.from(new Set(normalizedQuads.map((q) => q.subject.value)));
1851
+ if (subjectRoots.length === 0) return {
1846
1852
  text: "",
1847
1853
  context: fullContext,
1848
1854
  compactStats: null
1849
1855
  };
1850
- const { text, compactStats } = buildDeterministicMDLD(nodeGroups, fullContext, focusIRI, renderReverse ? reverseIndex : null, compactInline, /* @__PURE__ */ new Map(), lang);
1856
+ const { text, compactStats } = buildDeterministicMDLD(nodeGroups, fullContext, subjectRoots.includes(focusIRI) ? focusIRI : subjectRoots[0], renderReverse ? reverseIndex : null, compactInline, /* @__PURE__ */ new Map(), lang);
1851
1857
  return {
1852
1858
  text,
1853
1859
  context: fullContext,
@@ -1893,36 +1899,7 @@ function groupQuadsBySubject(quads) {
1893
1899
  reverseIndex
1894
1900
  };
1895
1901
  }
1896
- function groupQuadsByNode(quads) {
1897
- const groups = /* @__PURE__ */ new Map();
1898
- const reverseIndex = /* @__PURE__ */ new Map();
1899
- const ensure = (key) => {
1900
- const existing = groups.get(key);
1901
- if (existing) return existing;
1902
- const newArray = [];
1903
- groups.set(key, newArray);
1904
- return newArray;
1905
- };
1906
- for (const quad of quads) {
1907
- const { subject, predicate, object } = quad;
1908
- ensure(subject.value).push(quad);
1909
- if (object.termType === "NamedNode") {
1910
- ensure(object.value).push(quad);
1911
- const objectValue = object.value;
1912
- const reverseList = reverseIndex.get(objectValue);
1913
- if (reverseList) reverseList.push(quad);
1914
- else reverseIndex.set(objectValue, [quad]);
1915
- }
1916
- ensure(predicate.value).push(quad);
1917
- if (predicate.value === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && object.termType === "NamedNode") ensure(object.value).push(quad);
1918
- if (object.termType === "Literal" && object.datatype) ensure(object.datatype.value || object.datatype).push(quad);
1919
- }
1920
- return {
1921
- nodeGroups: groups,
1922
- reverseIndex
1923
- };
1924
- }
1925
- function buildDeterministicMDLD(subjectGroups, context, primarySubject = null, reverseIndex = null, compactInline = true, removeBySubject = /* @__PURE__ */ new Map(), lang = null) {
1902
+ function buildDeterministicMDLD(subjectGroups, context, primarySubjectIRI = null, reverseIndex = null, compactInline = true, removeBySubject = /* @__PURE__ */ new Map(), lang = null) {
1926
1903
  const textParts = [];
1927
1904
  const usedPrefixes = collectUsedPrefixes(subjectGroups, context);
1928
1905
  const labelLookup = buildLabelLookup(subjectGroups, lang);
@@ -1938,7 +1915,6 @@ function buildDeterministicMDLD(subjectGroups, context, primarySubject = null, r
1938
1915
  for (const [prefix, namespace] of sortedPrefixes) if (prefix !== "@vocab" && !prefix.startsWith("@") && !DEFAULT_CONTEXT[prefix] && usedPrefixes.has(prefix)) textParts.push(generatePrefixDeclaration(prefix, namespace));
1939
1916
  if (sortedPrefixes.length > 0) textParts.push("\n");
1940
1917
  const sortedSubjects = Array.from(subjectGroups.keys()).sort();
1941
- const primarySubjectIRI = primarySubject;
1942
1918
  const orderedSubjects = primarySubjectIRI ? [primarySubjectIRI, ...sortedSubjects.filter((s) => s !== primarySubjectIRI)] : sortedSubjects;
1943
1919
  for (const subjectIRI of orderedSubjects) {
1944
1920
  const subjectQuads = subjectGroups.get(subjectIRI);
@@ -1961,7 +1937,7 @@ function buildDeterministicMDLD(subjectGroups, context, primarySubject = null, r
1961
1937
  annotations += (annotations ? " " : "") + "label" + langTag;
1962
1938
  }
1963
1939
  const annotationStr = annotations ? " " + annotations : "";
1964
- textParts.push(`# ${displayName} {=${shortSubject}${annotationStr}}\n`);
1940
+ textParts.push(`## ${displayName} {=${shortSubject}${annotationStr}}\n`);
1965
1941
  types.forEach((t) => renderedQuads.add(t));
1966
1942
  if (labelQuad) renderedQuads.add(labelQuad);
1967
1943
  const headingLabel = hasLabel ? labelEntry.value : null;
@@ -2017,7 +1993,7 @@ function buildDeterministicMDLD(subjectGroups, context, primarySubject = null, r
2017
1993
  for (const [subjectIRI, removeQuads] of removeBySubject) {
2018
1994
  const shortSubject = getCachedShortIRI(subjectIRI, context);
2019
1995
  const displayName = extractLocalName(subjectIRI, context);
2020
- textParts.push(`# ${displayName} {=${shortSubject}}\n`);
1996
+ textParts.push(`### ${displayName} {=${shortSubject}}\n`);
2021
1997
  for (const quad of removeQuads) textParts.push(generateRetractionText(quad, context));
2022
1998
  textParts.push("\n");
2023
1999
  }
@@ -2056,6 +2032,367 @@ function buildLabelLookup(subjectGroups, lang = null) {
2056
2032
  return labelLookup;
2057
2033
  }
2058
2034
  //#endregion
2035
+ //#region src/render.js
2036
+ /**
2037
+ * MD-LD UI Renderer
2038
+ *
2039
+ * Generates clean, semantic HTML for presentation.
2040
+ * Preserves the raw MD-LD annotation in `data-annotation` for client-side
2041
+ * JS/CSS targeting, and resolves the primary IRI into `data-iri`.
2042
+ */
2043
+ function render(src, options = {}) {
2044
+ const lines = src.split("\n");
2045
+ const context = buildRenderContext(lines, options.context);
2046
+ function safeExpand(term) {
2047
+ if (!term || term === "RESET") return null;
2048
+ if (term.startsWith("=#") || term.startsWith("#")) return term;
2049
+ return expandIRI(term, context);
2050
+ }
2051
+ function getAttrs(rawAnnotation, parsedSem, isLink = false, fallbackHref = null) {
2052
+ const attrs = [];
2053
+ const classes = [];
2054
+ if (rawAnnotation) attrs.push(`data-annotation="${escapeHtml$1("{" + rawAnnotation + "}")}"`);
2055
+ let iri = null;
2056
+ if (parsedSem?.subject && parsedSem.subject !== "RESET") iri = safeExpand(parsedSem.subject);
2057
+ else if (parsedSem?.object) iri = safeExpand(parsedSem.object);
2058
+ else if (isLink && fallbackHref) iri = safeExpand(fallbackHref);
2059
+ if (iri) {
2060
+ attrs.push(`data-iri="${escapeHtml$1(iri)}"`);
2061
+ if (isLink) attrs.push(`href="${escapeHtml$1(iri)}"`);
2062
+ } else if (isLink && fallbackHref) attrs.push(`href="${escapeHtml$1(fallbackHref)}"`);
2063
+ if (parsedSem?.types?.some((t) => !t.remove)) classes.push("typed");
2064
+ if (parsedSem?.predicates?.some((p) => p.remove) || parsedSem?.types?.some((t) => t.remove)) classes.push("retracted");
2065
+ if (classes.length > 0) attrs.unshift(`class="${classes.join(" ")}"`);
2066
+ return attrs.join(" ");
2067
+ }
2068
+ function mergeClasses(baseClass, customAttrs) {
2069
+ const classMatch = customAttrs.match(/class="([^"]*)"/);
2070
+ let finalClass = baseClass;
2071
+ let remainingAttrs = customAttrs;
2072
+ if (classMatch) {
2073
+ finalClass += " " + classMatch[1];
2074
+ remainingAttrs = customAttrs.replace(/class="[^"]*"/, "").trim();
2075
+ }
2076
+ return `class="${finalClass}"${remainingAttrs ? " " + remainingAttrs : ""}`;
2077
+ }
2078
+ function renderInline(text) {
2079
+ const carriers = scanInlineCarriers(text, 0);
2080
+ if (carriers.length === 0) return escapeHtml$1(text);
2081
+ let out = "";
2082
+ let lastPos = 0;
2083
+ for (const c of carriers) {
2084
+ if (c.range[0] > lastPos) out += escapeHtml$1(text.slice(lastPos, c.range[0]));
2085
+ const sem = c.attrs ? parseSemanticBlock(c.attrs) : null;
2086
+ const raw = c.attrs || "";
2087
+ const isLink = c.type === "link";
2088
+ const fallbackHref = c.url || null;
2089
+ let tag = "span";
2090
+ let baseClass = "mdld-bracket";
2091
+ if (c.type === "link") {
2092
+ tag = "a";
2093
+ baseClass = "mdld-link";
2094
+ } else if (c.type === "code") {
2095
+ tag = "code";
2096
+ baseClass = "mdld-code";
2097
+ } else if (c.type === "strong") {
2098
+ tag = "strong";
2099
+ baseClass = "mdld-bold";
2100
+ } else if (c.type === "emphasis") {
2101
+ tag = "em";
2102
+ baseClass = "mdld-italic";
2103
+ }
2104
+ const customAttrs = getAttrs(raw, sem, isLink, fallbackHref);
2105
+ const attrString = mergeClasses(baseClass, customAttrs);
2106
+ out += `<${tag} ${attrString}>${renderInline(c.text)}</${tag}>`;
2107
+ lastPos = c.range[1];
2108
+ }
2109
+ if (lastPos < text.length) out += escapeHtml$1(text.slice(lastPos));
2110
+ return out;
2111
+ }
2112
+ const out = [];
2113
+ let i = 0;
2114
+ let codeBlock = null;
2115
+ while (i < lines.length) {
2116
+ const line = lines[i];
2117
+ if (codeBlock) {
2118
+ if (new RegExp(`^${codeBlock.fenceChar}{${codeBlock.fenceLength},}\\s*$`).test(line.trim())) {
2119
+ const sem = codeBlock.attrs ? parseSemanticBlock(codeBlock.attrs) : null;
2120
+ const carrierText = codeBlock.content.join("\n");
2121
+ const customAttrs = getAttrs(codeBlock.attrs, sem);
2122
+ const attrString = mergeClasses(`mdld-codeblock language-${codeBlock.lang || "text"}`, customAttrs);
2123
+ out.push(`<pre><code ${attrString}>${escapeHtml$1(carrierText)}</code></pre>`);
2124
+ codeBlock = null;
2125
+ } else codeBlock.content.push(line);
2126
+ i++;
2127
+ continue;
2128
+ }
2129
+ if (line.trim() === "") {
2130
+ i++;
2131
+ continue;
2132
+ }
2133
+ const fence = detectFence(line.trim());
2134
+ if (fence) {
2135
+ codeBlock = {
2136
+ fenceChar: fence.fenceChar,
2137
+ fenceLength: fence.fenceLength,
2138
+ lang: fence.lang,
2139
+ attrs: fence.attrs,
2140
+ content: []
2141
+ };
2142
+ i++;
2143
+ continue;
2144
+ }
2145
+ const prefix = detectPrefix(line);
2146
+ if (prefix) {
2147
+ const resolvedIri = context[prefix.prefix];
2148
+ out.push(`<div class="mdld-prefix" data-prefix="${prefix.prefix}" data-raw="${escapeHtml$1(prefix.iri)}" data-iri="${escapeHtml$1(resolvedIri)}" style="display:none"></div>`);
2149
+ i++;
2150
+ continue;
2151
+ }
2152
+ const heading = detectHeading(line);
2153
+ if (heading) {
2154
+ const sem = heading.attrs ? parseSemanticBlock(heading.attrs) : null;
2155
+ const attrString = mergeClasses("mdld-heading", getAttrs(heading.attrs, sem));
2156
+ out.push(`<h${heading.depth} ${attrString}>${renderInline(heading.content)}</h${heading.depth}>`);
2157
+ i++;
2158
+ continue;
2159
+ }
2160
+ if (detectList(line)) {
2161
+ out.push("<ul class=\"mdld-list\">");
2162
+ while (i < lines.length) {
2163
+ const l = detectList(lines[i]);
2164
+ if (!l) break;
2165
+ const sem = l.attrs ? parseSemanticBlock(l.attrs) : null;
2166
+ const attrString = mergeClasses("mdld-item", getAttrs(l.attrs, sem));
2167
+ out.push(`<li ${attrString}>${renderInline(l.content)}</li>`);
2168
+ i++;
2169
+ }
2170
+ out.push("</ul>");
2171
+ continue;
2172
+ }
2173
+ const blockquote = detectBlockquote(line);
2174
+ if (blockquote) {
2175
+ let quoteLines = [blockquote.content];
2176
+ i++;
2177
+ while (i < lines.length) {
2178
+ const bq = detectBlockquote(lines[i]);
2179
+ if (!bq) break;
2180
+ quoteLines.push(bq.content);
2181
+ i++;
2182
+ }
2183
+ const sem = blockquote.attrs ? parseSemanticBlock(blockquote.attrs) : null;
2184
+ const attrString = mergeClasses("mdld-quote", getAttrs(blockquote.attrs, sem));
2185
+ const carrierText = quoteLines.join("\n");
2186
+ out.push(`<blockquote ${attrString}>${renderInline(carrierText)}</blockquote>`);
2187
+ continue;
2188
+ }
2189
+ const standalone = detectStandaloneSubject(line);
2190
+ if (standalone) {
2191
+ const fakeSem = parseSemanticBlock(`=${standalone.content}`);
2192
+ const attrString = mergeClasses("mdld-standalone", getAttrs(`=${standalone.content}`, fakeSem));
2193
+ out.push(`<div ${attrString} style="display:none"></div>`);
2194
+ i++;
2195
+ continue;
2196
+ }
2197
+ let paraLines = [line];
2198
+ i++;
2199
+ while (i < lines.length && lines[i].trim() !== "" && !detectFence(lines[i].trim()) && !detectPrefix(lines[i]) && !detectHeading(lines[i]) && !detectList(lines[i]) && !detectBlockquote(lines[i]) && !detectStandaloneSubject(lines[i])) {
2200
+ paraLines.push(lines[i]);
2201
+ i++;
2202
+ }
2203
+ const paraText = paraLines.join("\n");
2204
+ out.push(`<p class="mdld-paragraph">${renderInline(paraText)}</p>`);
2205
+ }
2206
+ return out.join("\n");
2207
+ }
2208
+ function buildRenderContext(lines, userContext = {}) {
2209
+ const context = {
2210
+ ...DEFAULT_CONTEXT,
2211
+ ...userContext
2212
+ };
2213
+ for (const line of lines) {
2214
+ const prefix = detectPrefix(line);
2215
+ if (prefix) {
2216
+ let iri = prefix.iri;
2217
+ if (iri.includes(":")) {
2218
+ const colonIndex = iri.indexOf(":");
2219
+ const p = iri.substring(0, colonIndex);
2220
+ const ref = iri.substring(colonIndex + 1);
2221
+ if (context[p] && p !== "@vocab") iri = context[p] + ref;
2222
+ }
2223
+ context[prefix.prefix] = iri;
2224
+ }
2225
+ }
2226
+ return context;
2227
+ }
2228
+ /**
2229
+ * Reconstruct MD-LD from rendered HTML.
2230
+ * Pure string scanning over our constrained output format.
2231
+ * Platform-agnostic: no DOMParser, no browser APIs required.
2232
+ */
2233
+ function deconstruct(html) {
2234
+ const blocks = [];
2235
+ let pos = 0;
2236
+ while (pos < html.length) {
2237
+ while (pos < html.length && /\s/.test(html[pos])) pos++;
2238
+ if (pos >= html.length) break;
2239
+ if (html.startsWith("<div class=\"mdld-prefix\"", pos)) {
2240
+ const end = html.indexOf("></div>", pos);
2241
+ if (end === -1) break;
2242
+ const tag = html.slice(pos, end + 7);
2243
+ const prefix = extractAttr(tag, "data-prefix");
2244
+ const raw = extractAttr(tag, "data-raw") || extractAttr(tag, "data-iri");
2245
+ blocks.push(`[${prefix}] <${raw}>`);
2246
+ pos = end + 7;
2247
+ } else if (html.startsWith("<div class=\"mdld-standalone\"", pos)) {
2248
+ const end = html.indexOf("</div>", pos);
2249
+ if (end === -1) break;
2250
+ const ann = extractAttr(html.slice(pos, end + 6), "data-annotation");
2251
+ if (ann) blocks.push(ann);
2252
+ pos = end + 6;
2253
+ } else if (html.startsWith("<pre><code", pos)) {
2254
+ const closePre = html.indexOf("</code></pre>", pos);
2255
+ if (closePre === -1) break;
2256
+ const full = html.slice(pos, closePre + 13);
2257
+ const preClose = full.indexOf(">") + 1;
2258
+ const codeOpenEnd = full.indexOf(">", preClose) + 1;
2259
+ const codeTag = full.slice(preClose, codeOpenEnd);
2260
+ const content = full.slice(codeOpenEnd, full.length - 13);
2261
+ const langMatch = (extractAttr(codeTag, "class") || "").match(/language-(\w+)/);
2262
+ const lang = langMatch ? langMatch[1] : "";
2263
+ const ann = extractAttr(codeTag, "data-annotation");
2264
+ blocks.push(`\`\`\`${lang}${ann ? " " + ann : ""}\n${unescapeHtml(content)}\n\`\`\``);
2265
+ pos = closePre + 13;
2266
+ } else if (html[pos] === "<" && /^<h[1-6]/.test(html.slice(pos, pos + 4))) {
2267
+ const level = html[pos + 2];
2268
+ const closeTag = `</h${level}>`;
2269
+ const close = html.indexOf(closeTag, pos);
2270
+ if (close === -1) break;
2271
+ const full = html.slice(pos, close + closeTag.length);
2272
+ const openEnd = full.indexOf(">") + 1;
2273
+ const openTag = full.slice(0, openEnd);
2274
+ const content = full.slice(openEnd, full.length - closeTag.length);
2275
+ const hashes = "#".repeat(parseInt(level));
2276
+ const ann = extractAttr(openTag, "data-annotation");
2277
+ blocks.push(`${hashes} ${deconstructInline(content)}${ann ? " " + ann : ""}`);
2278
+ pos = close + closeTag.length;
2279
+ } else if (html.startsWith("<blockquote", pos)) {
2280
+ const close = html.indexOf("</blockquote>", pos);
2281
+ if (close === -1) break;
2282
+ const full = html.slice(pos, close + 13);
2283
+ const openEnd = full.indexOf(">") + 1;
2284
+ const openTag = full.slice(0, openEnd);
2285
+ const content = full.slice(openEnd, full.length - 13);
2286
+ const ann = extractAttr(openTag, "data-annotation");
2287
+ const quoted = deconstructInline(content).split("\n").map((l) => l.trim() ? `> ${l}` : ">").join("\n");
2288
+ blocks.push(ann ? `${quoted} ${ann}` : quoted);
2289
+ pos = close + 13;
2290
+ } else if (html.startsWith("<ul class=\"mdld-list\">", pos)) {
2291
+ const close = html.indexOf("</ul>", pos);
2292
+ if (close === -1) break;
2293
+ const inner = html.slice(pos + 21, close);
2294
+ const items = [];
2295
+ let itemPos = 0;
2296
+ while (itemPos < inner.length) {
2297
+ const liStart = inner.indexOf("<li", itemPos);
2298
+ if (liStart === -1) break;
2299
+ const liClose = inner.indexOf("</li>", liStart);
2300
+ if (liClose === -1) break;
2301
+ const liFull = inner.slice(liStart, liClose + 5);
2302
+ const openEnd = liFull.indexOf(">") + 1;
2303
+ const openTag = liFull.slice(0, openEnd);
2304
+ const liContent = liFull.slice(openEnd, liFull.length - 5);
2305
+ const ann = extractAttr(openTag, "data-annotation");
2306
+ items.push(`- ${deconstructInline(liContent)}${ann ? " " + ann : ""}`);
2307
+ itemPos = liClose + 5;
2308
+ }
2309
+ blocks.push(items.join("\n"));
2310
+ pos = close + 5;
2311
+ } else if (html.startsWith("<p class=\"mdld-paragraph\">", pos)) {
2312
+ const close = html.indexOf("</p>", pos);
2313
+ if (close === -1) break;
2314
+ const content = html.slice(pos + 25, close);
2315
+ blocks.push(deconstructInline(content));
2316
+ pos = close + 4;
2317
+ } else pos++;
2318
+ }
2319
+ return blocks.join("\n\n");
2320
+ }
2321
+ function deconstructInline(html) {
2322
+ let out = "";
2323
+ let i = 0;
2324
+ while (i < html.length) if (html[i] === "<") {
2325
+ const closeGt = html.indexOf(">", i);
2326
+ if (closeGt === -1) {
2327
+ out += html.slice(i);
2328
+ break;
2329
+ }
2330
+ const tagContent = html.slice(i + 1, closeGt);
2331
+ if (tagContent.startsWith("/")) {
2332
+ i = closeGt + 1;
2333
+ continue;
2334
+ }
2335
+ const spaceOrEnd = tagContent.search(/[\s/]/);
2336
+ const tagName = (spaceOrEnd === -1 ? tagContent : tagContent.slice(0, spaceOrEnd)).toLowerCase();
2337
+ const attrs = spaceOrEnd === -1 ? "" : tagContent.slice(spaceOrEnd);
2338
+ const closeTag = `</${tagName}>`;
2339
+ let depth = 1;
2340
+ let j = closeGt + 1;
2341
+ let found = false;
2342
+ while (j < html.length && depth > 0) {
2343
+ const nextOpen = html.indexOf(`<${tagName}`, j);
2344
+ const nextClose = html.indexOf(closeTag, j);
2345
+ if (nextClose === -1) break;
2346
+ if (nextOpen !== -1 && nextOpen < nextClose) {
2347
+ depth++;
2348
+ j = nextOpen + 1;
2349
+ } else {
2350
+ depth--;
2351
+ if (depth === 0) {
2352
+ const inner = html.slice(closeGt + 1, nextClose);
2353
+ out += deconstructInlineElement(tagName, attrs, inner);
2354
+ i = nextClose + closeTag.length;
2355
+ found = true;
2356
+ break;
2357
+ }
2358
+ j = nextClose + 1;
2359
+ }
2360
+ }
2361
+ if (!found) {
2362
+ out += html[i];
2363
+ i++;
2364
+ }
2365
+ } else {
2366
+ const nextTag = html.indexOf("<", i);
2367
+ const textEnd = nextTag === -1 ? html.length : nextTag;
2368
+ out += unescapeHtml(html.slice(i, textEnd));
2369
+ i = textEnd;
2370
+ }
2371
+ return out;
2372
+ }
2373
+ function deconstructInlineElement(tagName, attrs, inner) {
2374
+ const ann = extractAttr(attrs, "data-annotation");
2375
+ const content = deconstructInline(inner);
2376
+ const suffix = ann ? " " + ann : "";
2377
+ switch (tagName) {
2378
+ case "a": return `[${content}](${extractAttr(attrs, "href") || ""})${suffix}`;
2379
+ case "span": return `[${content}]${suffix}`;
2380
+ case "code": return `\`${content}\`${suffix}`;
2381
+ case "strong": return `**${content}**${suffix}`;
2382
+ case "em": return `*${content}*${suffix}`;
2383
+ default: return content + suffix;
2384
+ }
2385
+ }
2386
+ function extractAttr(tag, name) {
2387
+ const re = new RegExp(`${name}=(?:"([^"]*)"|'([^']*)')`, "i");
2388
+ const m = tag.match(re);
2389
+ if (!m) return null;
2390
+ return unescapeHtml(m[1] !== void 0 ? m[1] : m[2]);
2391
+ }
2392
+ function unescapeHtml(s) {
2393
+ return String(s).replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#39;/g, "'");
2394
+ }
2395
+ //#endregion
2059
2396
  //#region src/highlight.js
2060
2397
  /**
2061
2398
  * MD-LD Syntax Highlighter
@@ -2196,7 +2533,7 @@ function renderTerm(part, isRetracted, prefixes) {
2196
2533
  const prefixColor = getIRIColor(prefixIRI);
2197
2534
  const fullIRI = prefixIRI + local;
2198
2535
  const localColor = getIRIColor(fullIRI);
2199
- return `<span style="color: ${prefixColor}">${escapeHtml(prefix)}</span><span style="color: ${TOKEN_COLORS.marker}">:</span><span data-iri="${fullIRI}" style="color: ${localColor}">${escapeHtml(local)}</span> `;
2536
+ return `<span data-iri="${fullIRI}"><span style="color: ${prefixColor}">${escapeHtml(prefix)}</span><span style="color: ${TOKEN_COLORS.marker}">:</span><span style="color: ${localColor}">${escapeHtml(local)}</span></span> `;
2200
2537
  }
2201
2538
  }
2202
2539
  if (part.startsWith("http:") || part.startsWith("https:") || part.startsWith("tag:") || part.startsWith("urn:")) return `<span style="color: ${getIRIColor(part)}">${escapeHtml(part)}</span> `;
@@ -2272,9 +2609,9 @@ function highlightMDLD(code) {
2272
2609
  continue;
2273
2610
  }
2274
2611
  const parsed = parseAnnotation(code.slice(i + 1, endIdx), prefixes);
2275
- result += `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">{</span>`;
2612
+ result += `<span class="mdld-annotation"><span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">{</span>`;
2276
2613
  result += parsed;
2277
- result += `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">}</span>`;
2614
+ result += `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">}</span></span>`;
2278
2615
  i = endIdx + 1;
2279
2616
  continue;
2280
2617
  }
@@ -2301,7 +2638,7 @@ function highlightMDLD(code) {
2301
2638
  const content = code.slice(i + 1, endBracket);
2302
2639
  const bracketColor = hasFollowingAnnotation(code, endBracket + 1) ? TOKEN_COLORS.marker : TOKEN_COLORS.value;
2303
2640
  const escapedContent = escapeHtml(content);
2304
- result += `<span style="color: ${bracketColor}; opacity: 0.85">[</span><span style=" opacity: 1.0">${escapedContent}</span><span style="color: ${bracketColor}; opacity: 0.85">]</span>`;
2641
+ result += `<span style="color: ${bracketColor}; opacity: 0.85">[</span><span style="background-color: ${bracketColor}15">${escapedContent}</span><span style="color: ${bracketColor}; opacity: 0.85">]</span>`;
2305
2642
  i = endBracket + 1;
2306
2643
  continue;
2307
2644
  }
@@ -2333,7 +2670,7 @@ function highlightMDLD(code) {
2333
2670
  const beforeText = headerText.slice(lastIndex, annotationStart);
2334
2671
  processedHeaderText += escapeHtml(beforeText);
2335
2672
  const parsedAnnotation = parseAnnotation(headerText.slice(annotationStart + 1, annotationEnd), prefixes);
2336
- processedHeaderText += `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">{</span>` + parsedAnnotation + `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">}</span>`;
2673
+ processedHeaderText += `<span class="mdld-annotation"><span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">{</span>` + parsedAnnotation + `<span style="color: ${TOKEN_COLORS.annotation}; opacity: 0.75">}</span></span>`;
2337
2674
  lastIndex = annotationEnd + 1;
2338
2675
  annotationStart = headerText.indexOf("{", lastIndex);
2339
2676
  }
@@ -2393,4 +2730,4 @@ function updateValue({ text, quad, value, origin }) {
2393
2730
  return text.substring(0, location.valueRange.start) + value + text.substring(location.valueRange.end);
2394
2731
  }
2395
2732
  //#endregion
2396
- export { DEFAULT_CONTEXT, DataFactory, expandIRI, generate, generateNode, getIRIColor, hash, hashIRI, highlightMDLD, locate, merge, parse, parseSemanticBlock, shortenIRI, updateValue };
2733
+ export { DEFAULT_CONTEXT, DataFactory, deconstruct, expandIRI, generate, generateNode, getIRIColor, hash, hashIRI, highlightMDLD, locate, merge, parse, parseSemanticBlock, render, shortenIRI, updateValue };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mdld-parse",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
4
4
  "description": "Write RDF knowledge graphs as plain Markdown. Parse to quads, generate back, merge documents. The human-friendly semantic web format.",
5
5
  "keywords": [
6
6
  "rdf",
@@ -24,7 +24,6 @@
24
24
  "triple-store"
25
25
  ],
26
26
  "type": "module",
27
- "packageManager": "pnpm@11.24.0+sha512.bd27e345e976dcb0be0b7a1228217b049a817e21b1f355c90dbe7dc46671895a8bc1e6d06c24554505ea93ea0b45f489a27ec1bfbc8de6a9659fca0f16fa0000",
28
27
  "main": "./dist/index.js",
29
28
  "exports": {
30
29
  ".": "./dist/index.js"
@@ -35,7 +34,7 @@
35
34
  "scripts": {
36
35
  "test": "node tests/index.js",
37
36
  "dev": "vite dev",
38
- "build": "vite build && vite build --config vite.config.lib.js && cp -r docs/ dist/docs/ && cp -r examples/ dist/examples/ && cp -r grammar/ dist/grammar/ && cp -r ontologies/ dist/ontologies/ && cp -r spec/ dist/spec/ && cp -r README.md dist/README.md && cp -r docs.html dist/docs.html && cp -r demo/ dist/demo/"
37
+ "build": "vite build && vite build --config vite.config.lib.js && cp -r docs/ dist/docs/ && cp -r server/ dist/server/ && cp -r examples/ dist/examples/ && cp -r grammar/ dist/grammar/ && cp -r ontologies/ dist/ontologies/ && cp -r spec/ dist/spec/ && cp -r README.md dist/README.md && cp -r docs.html dist/docs.html && cp -r demo/ dist/demo/ && cp -r src/ dist/src/"
39
38
  },
40
39
  "author": "davay42",
41
40
  "repository": {
@@ -47,17 +46,19 @@
47
46
  "url": "https://github.com/davay42/mdld-parse/issues"
48
47
  },
49
48
  "devDependencies": {
50
- "@unocss/extractor-pug": "^66.8.1",
49
+ "@unocss/extractor-pug": "^66.10.2",
51
50
  "@vitejs/plugin-vue": "^6.0.8",
52
51
  "@vueuse/core": "^14.4.0",
53
52
  "codejar": "^4.3.0",
54
- "markdown-it": "^15.0.0",
55
- "n3": "^2.6.0",
53
+ "markdown-it": "^15.0.2",
54
+ "n3": "^2.7.12",
55
+ "rdfa-parse": "^1.0.1",
56
56
  "shiki": "^4.4.3",
57
- "unocss": "^66.8.1",
58
- "vite": "^8.2.2",
57
+ "unocss": "^66.10.2",
58
+ "vite": "^8.3.0",
59
59
  "vite-plugin-singlefile": "^2.3.3",
60
60
  "vscode-textmate": "^9.3.2",
61
61
  "vue": "^3.6.0-beta.17"
62
- }
62
+ },
63
+ "packageManager": "pnpm@11.26.0+sha512.fc0e2bf890b9f983611f1ab68c0637bce914390653699f83c1a78b005ed25f2c81e77920c8fd8eee2ecf0b58b28cdcb00a84d97f69bcf7c56b2f344710238664"
63
64
  }