mdld-parse 1.0.7 → 1.0.9

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.
@@ -719,7 +719,9 @@ function detectBracketLink(text, startPos) {
719
719
  if (pos < text.length && text[pos] === "(") {
720
720
  const parenEnd = text.indexOf(")", pos + 1);
721
721
  if (parenEnd !== -1) {
722
- url = text.slice(pos + 1, parenEnd);
722
+ const potentialUrl = text.slice(pos + 1, parenEnd);
723
+ const lowerUrl = potentialUrl.toLowerCase();
724
+ if (lowerUrl.startsWith("http://") || lowerUrl.startsWith("https://")) url = potentialUrl;
723
725
  pos = parenEnd + 1;
724
726
  }
725
727
  } else if (pos < text.length && text[pos] === "<") {
@@ -910,6 +912,10 @@ function resolveObject(sem, state) {
910
912
  if (sem.object.startsWith("#")) return resolveFragment(sem.object.substring(1), state.currentSubject, state.df);
911
913
  return state.df.namedNode(expandIRI(sem.object, state.ctx));
912
914
  }
915
+ function escapeHtml$1(text) {
916
+ if (!text) return "";
917
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
918
+ }
913
919
  function isLiteral(term) {
914
920
  return term?.termType === "Literal";
915
921
  }
@@ -2028,6 +2034,370 @@ function buildLabelLookup(subjectGroups, lang = null) {
2028
2034
  return labelLookup;
2029
2035
  }
2030
2036
  //#endregion
2037
+ //#region src/render.js
2038
+ /**
2039
+ * MD-LD UI Renderer
2040
+ *
2041
+ * Generates clean, semantic HTML for presentation.
2042
+ * Preserves the raw MD-LD annotation in `data-annotation` for client-side
2043
+ * JS/CSS targeting, and resolves the primary IRI into `data-iri`.
2044
+ */
2045
+ function render(src, options = {}) {
2046
+ const lines = src.split("\n");
2047
+ const context = buildRenderContext(lines, options.context);
2048
+ function safeExpand(term) {
2049
+ if (!term || term === "RESET") return null;
2050
+ if (term.startsWith("=#") || term.startsWith("#")) return term;
2051
+ return expandIRI(term, context);
2052
+ }
2053
+ function getAttrs(rawAnnotation, parsedSem, isLink = false, fallbackHref = null) {
2054
+ const attrs = [];
2055
+ const classes = [];
2056
+ if (rawAnnotation) attrs.push(`data-annotation="${escapeHtml$1("{" + rawAnnotation + "}")}"`);
2057
+ let iri = null;
2058
+ if (parsedSem?.subject && parsedSem.subject !== "RESET") iri = safeExpand(parsedSem.subject);
2059
+ else if (parsedSem?.object) iri = safeExpand(parsedSem.object);
2060
+ if (iri) attrs.push(`data-iri="${escapeHtml$1(iri)}"`);
2061
+ if (isLink && fallbackHref) attrs.push(`href="${escapeHtml$1(fallbackHref)}"`);
2062
+ if (parsedSem?.types?.some((t) => !t.remove)) classes.push("typed");
2063
+ if (parsedSem?.predicates?.some((p) => p.remove) || parsedSem?.types?.some((t) => t.remove)) classes.push("retracted");
2064
+ if (classes.length > 0) attrs.unshift(`class="${classes.join(" ")}"`);
2065
+ return attrs.join(" ");
2066
+ }
2067
+ function mergeClasses(baseClass, customAttrs) {
2068
+ const classMatch = customAttrs.match(/class="([^"]*)"/);
2069
+ let finalClass = baseClass;
2070
+ let remainingAttrs = customAttrs;
2071
+ if (classMatch) {
2072
+ finalClass += " " + classMatch[1];
2073
+ remainingAttrs = customAttrs.replace(/class="[^"]*"/, "").trim();
2074
+ }
2075
+ return `class="${finalClass}"${remainingAttrs ? " " + remainingAttrs : ""}`;
2076
+ }
2077
+ function renderInline(text) {
2078
+ const carriers = scanInlineCarriers(text, 0);
2079
+ if (carriers.length === 0) return escapeHtml$1(text);
2080
+ let out = "";
2081
+ let lastPos = 0;
2082
+ for (const c of carriers) {
2083
+ if (c.range[0] > lastPos) out += escapeHtml$1(text.slice(lastPos, c.range[0]));
2084
+ const sem = c.attrs ? parseSemanticBlock(c.attrs) : null;
2085
+ const raw = c.attrs || "";
2086
+ const isLink = c.type === "link";
2087
+ const fallbackHref = c.url || null;
2088
+ let tag = "span";
2089
+ let baseClass = "mdld-bracket";
2090
+ if (c.type === "link") {
2091
+ tag = "a";
2092
+ baseClass = "mdld-link";
2093
+ } else if (c.type === "code") {
2094
+ tag = "code";
2095
+ baseClass = "mdld-code";
2096
+ } else if (c.type === "strong") {
2097
+ tag = "strong";
2098
+ baseClass = "mdld-bold";
2099
+ } else if (c.type === "emphasis") {
2100
+ tag = "em";
2101
+ baseClass = "mdld-italic";
2102
+ }
2103
+ const customAttrs = getAttrs(raw, sem, isLink, fallbackHref);
2104
+ const attrString = mergeClasses(baseClass, customAttrs);
2105
+ out += `<${tag} ${attrString}>${renderInline(c.text)}</${tag}>`;
2106
+ lastPos = c.range[1];
2107
+ }
2108
+ if (lastPos < text.length) out += escapeHtml$1(text.slice(lastPos));
2109
+ return out;
2110
+ }
2111
+ const out = [];
2112
+ let i = 0;
2113
+ let codeBlock = null;
2114
+ while (i < lines.length) {
2115
+ const line = lines[i];
2116
+ if (codeBlock) {
2117
+ if (new RegExp(`^${codeBlock.fenceChar}{${codeBlock.fenceLength},}\\s*$`).test(line.trim())) {
2118
+ const sem = codeBlock.attrs ? parseSemanticBlock(codeBlock.attrs) : null;
2119
+ const carrierText = codeBlock.content.join("\n");
2120
+ const customAttrs = getAttrs(codeBlock.attrs, sem);
2121
+ const attrString = mergeClasses(`mdld-codeblock language-${codeBlock.lang || "text"}`, customAttrs);
2122
+ out.push(`<pre><code ${attrString}>${escapeHtml$1(carrierText)}</code></pre>`);
2123
+ codeBlock = null;
2124
+ } else codeBlock.content.push(line);
2125
+ i++;
2126
+ continue;
2127
+ }
2128
+ if (line.trim() === "") {
2129
+ i++;
2130
+ continue;
2131
+ }
2132
+ const fence = detectFence(line.trim());
2133
+ if (fence) {
2134
+ codeBlock = {
2135
+ fenceChar: fence.fenceChar,
2136
+ fenceLength: fence.fenceLength,
2137
+ lang: fence.lang,
2138
+ attrs: fence.attrs,
2139
+ content: []
2140
+ };
2141
+ i++;
2142
+ continue;
2143
+ }
2144
+ const prefix = detectPrefix(line);
2145
+ if (prefix) {
2146
+ const resolvedIri = context[prefix.prefix];
2147
+ 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>`);
2148
+ i++;
2149
+ continue;
2150
+ }
2151
+ const heading = detectHeading(line);
2152
+ if (heading) {
2153
+ const sem = heading.attrs ? parseSemanticBlock(heading.attrs) : null;
2154
+ const attrString = mergeClasses("mdld-heading", getAttrs(heading.attrs, sem));
2155
+ out.push(`<h${heading.depth} ${attrString}>${renderInline(heading.content)}</h${heading.depth}>`);
2156
+ i++;
2157
+ continue;
2158
+ }
2159
+ if (detectList(line)) {
2160
+ out.push("<ul class=\"mdld-list\">");
2161
+ while (i < lines.length) {
2162
+ const l = detectList(lines[i]);
2163
+ if (!l) break;
2164
+ const sem = l.attrs ? parseSemanticBlock(l.attrs) : null;
2165
+ const attrString = mergeClasses("mdld-item", getAttrs(l.attrs, sem));
2166
+ out.push(`<li ${attrString}>${renderInline(l.content)}</li>`);
2167
+ i++;
2168
+ }
2169
+ out.push("</ul>");
2170
+ continue;
2171
+ }
2172
+ const blockquote = detectBlockquote(line);
2173
+ if (blockquote) {
2174
+ let quoteLines = [blockquote.content];
2175
+ i++;
2176
+ while (i < lines.length) {
2177
+ const bq = detectBlockquote(lines[i]);
2178
+ if (!bq) break;
2179
+ quoteLines.push(bq.content);
2180
+ i++;
2181
+ }
2182
+ const sem = blockquote.attrs ? parseSemanticBlock(blockquote.attrs) : null;
2183
+ const attrString = mergeClasses("mdld-quote", getAttrs(blockquote.attrs, sem));
2184
+ const carrierText = quoteLines.join("\n");
2185
+ out.push(`<blockquote ${attrString}>${renderInline(carrierText)}</blockquote>`);
2186
+ continue;
2187
+ }
2188
+ const standalone = detectStandaloneSubject(line);
2189
+ if (standalone) {
2190
+ const fakeSem = parseSemanticBlock(`=${standalone.content}`);
2191
+ const attrString = mergeClasses("mdld-standalone", getAttrs(`=${standalone.content}`, fakeSem));
2192
+ out.push(`<div ${attrString} style="display:none"></div>`);
2193
+ i++;
2194
+ continue;
2195
+ }
2196
+ let paraLines = [line];
2197
+ i++;
2198
+ 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])) {
2199
+ paraLines.push(lines[i]);
2200
+ i++;
2201
+ }
2202
+ const paraText = paraLines.join("\n");
2203
+ out.push(`<p class="mdld-paragraph">${renderInline(paraText)}</p>`);
2204
+ }
2205
+ return out.join("\n");
2206
+ }
2207
+ function buildRenderContext(lines, userContext = {}) {
2208
+ const context = {
2209
+ ...DEFAULT_CONTEXT,
2210
+ ...userContext
2211
+ };
2212
+ for (const line of lines) {
2213
+ const prefix = detectPrefix(line);
2214
+ if (prefix) {
2215
+ let iri = prefix.iri;
2216
+ if (iri.includes(":")) {
2217
+ const colonIndex = iri.indexOf(":");
2218
+ const p = iri.substring(0, colonIndex);
2219
+ const ref = iri.substring(colonIndex + 1);
2220
+ if (context[p] && p !== "@vocab") iri = context[p] + ref;
2221
+ }
2222
+ context[prefix.prefix] = iri;
2223
+ }
2224
+ }
2225
+ return context;
2226
+ }
2227
+ /**
2228
+ * Reconstruct MD-LD from rendered HTML.
2229
+ * Pure string scanning over our constrained output format.
2230
+ * Platform-agnostic: no DOMParser, no browser APIs required.
2231
+ */
2232
+ function deconstruct(html) {
2233
+ const blocks = [];
2234
+ let pos = 0;
2235
+ while (pos < html.length) {
2236
+ while (pos < html.length && /\s/.test(html[pos])) pos++;
2237
+ if (pos >= html.length) break;
2238
+ const nextTagStart = html.indexOf("<", pos);
2239
+ if (nextTagStart === -1) break;
2240
+ const tagEnd = html.indexOf(">", nextTagStart);
2241
+ if (tagEnd === -1) break;
2242
+ const openTag = html.slice(nextTagStart, tagEnd + 1);
2243
+ if (openTag.startsWith("<p") && extractAttr(openTag, "class")?.includes("mdld-paragraph")) {
2244
+ const close = html.indexOf("</p>", pos);
2245
+ if (close === -1) break;
2246
+ const openEnd = html.indexOf(">", pos) + 1;
2247
+ const content = html.slice(openEnd, close);
2248
+ blocks.push(deconstructInline(content));
2249
+ pos = close + 4;
2250
+ } else if (openTag.startsWith("<div") && extractAttr(openTag, "class")?.includes("mdld-prefix")) {
2251
+ const end = html.indexOf("></div>", pos);
2252
+ if (end === -1) break;
2253
+ const tag = html.slice(pos, end + 7);
2254
+ const prefix = extractAttr(tag, "data-prefix");
2255
+ const raw = extractAttr(tag, "data-raw") || extractAttr(tag, "data-iri");
2256
+ blocks.push(`[${prefix}] <${raw}>`);
2257
+ pos = end + 7;
2258
+ } else if (openTag.startsWith("<div") && extractAttr(openTag, "class")?.includes("mdld-standalone")) {
2259
+ const end = html.indexOf("</div>", pos);
2260
+ if (end === -1) break;
2261
+ const ann = extractAttr(html.slice(pos, end + 6), "data-annotation");
2262
+ if (ann) blocks.push(ann);
2263
+ pos = end + 6;
2264
+ } else if (html.startsWith("<pre><code", pos)) {
2265
+ const closePre = html.indexOf("</code></pre>", pos);
2266
+ if (closePre === -1) break;
2267
+ const full = html.slice(pos, closePre + 13);
2268
+ const preClose = full.indexOf(">") + 1;
2269
+ const codeOpenEnd = full.indexOf(">", preClose) + 1;
2270
+ const codeTag = full.slice(preClose, codeOpenEnd);
2271
+ const content = full.slice(codeOpenEnd, full.length - 13);
2272
+ const langMatch = (extractAttr(codeTag, "class") || "").match(/language-(\w+)/);
2273
+ const lang = langMatch ? langMatch[1] : "";
2274
+ const ann = extractAttr(codeTag, "data-annotation");
2275
+ blocks.push(`\`\`\`${lang}${ann ? " " + ann : ""}\n${unescapeHtml(content)}\n\`\`\``);
2276
+ pos = closePre + 13;
2277
+ } else if (html[pos] === "<" && /^<h[1-6]/.test(html.slice(pos, pos + 4))) {
2278
+ const level = html[pos + 2];
2279
+ const closeTag = `</h${level}>`;
2280
+ const close = html.indexOf(closeTag, pos);
2281
+ if (close === -1) break;
2282
+ const full = html.slice(pos, close + closeTag.length);
2283
+ const openEnd = full.indexOf(">") + 1;
2284
+ const openTag = full.slice(0, openEnd);
2285
+ const content = full.slice(openEnd, full.length - closeTag.length);
2286
+ const hashes = "#".repeat(parseInt(level));
2287
+ const ann = extractAttr(openTag, "data-annotation");
2288
+ blocks.push(`${hashes} ${deconstructInline(content)}${ann ? " " + ann : ""}`);
2289
+ pos = close + closeTag.length;
2290
+ } else if (html.startsWith("<blockquote", pos)) {
2291
+ const close = html.indexOf("</blockquote>", pos);
2292
+ if (close === -1) break;
2293
+ const full = html.slice(pos, close + 13);
2294
+ const openEnd = full.indexOf(">") + 1;
2295
+ const openTag = full.slice(0, openEnd);
2296
+ const content = full.slice(openEnd, full.length - 13);
2297
+ const ann = extractAttr(openTag, "data-annotation");
2298
+ const quoted = deconstructInline(content).split("\n").map((l) => l.trim() ? `> ${l}` : ">").join("\n");
2299
+ blocks.push(ann ? `${quoted} ${ann}` : quoted);
2300
+ pos = close + 13;
2301
+ } else if (html.startsWith("<ul class=\"mdld-list\">", pos)) {
2302
+ const close = html.indexOf("</ul>", pos);
2303
+ if (close === -1) break;
2304
+ const inner = html.slice(pos + 21, close);
2305
+ const items = [];
2306
+ let itemPos = 0;
2307
+ while (itemPos < inner.length) {
2308
+ const liStart = inner.indexOf("<li", itemPos);
2309
+ if (liStart === -1) break;
2310
+ const liClose = inner.indexOf("</li>", liStart);
2311
+ if (liClose === -1) break;
2312
+ const liFull = inner.slice(liStart, liClose + 5);
2313
+ const openEnd = liFull.indexOf(">") + 1;
2314
+ const openTag = liFull.slice(0, openEnd);
2315
+ const liContent = liFull.slice(openEnd, liFull.length - 5);
2316
+ const ann = extractAttr(openTag, "data-annotation");
2317
+ items.push(`- ${deconstructInline(liContent)}${ann ? " " + ann : ""}`);
2318
+ itemPos = liClose + 5;
2319
+ }
2320
+ blocks.push(items.join("\n"));
2321
+ pos = close + 5;
2322
+ } else pos++;
2323
+ }
2324
+ return blocks.join("\n\n");
2325
+ }
2326
+ function deconstructInline(html) {
2327
+ let out = "";
2328
+ let i = 0;
2329
+ while (i < html.length) if (html[i] === "<") {
2330
+ const closeGt = html.indexOf(">", i);
2331
+ if (closeGt === -1) {
2332
+ out += html.slice(i);
2333
+ break;
2334
+ }
2335
+ const tagContent = html.slice(i + 1, closeGt);
2336
+ if (tagContent.startsWith("/")) {
2337
+ i = closeGt + 1;
2338
+ continue;
2339
+ }
2340
+ const spaceOrEnd = tagContent.search(/[\s/]/);
2341
+ const tagName = (spaceOrEnd === -1 ? tagContent : tagContent.slice(0, spaceOrEnd)).toLowerCase();
2342
+ const attrs = spaceOrEnd === -1 ? "" : tagContent.slice(spaceOrEnd);
2343
+ const closeTag = `</${tagName}>`;
2344
+ let depth = 1;
2345
+ let j = closeGt + 1;
2346
+ let found = false;
2347
+ while (j < html.length && depth > 0) {
2348
+ const nextOpen = html.indexOf(`<${tagName}`, j);
2349
+ const nextClose = html.indexOf(closeTag, j);
2350
+ if (nextClose === -1) break;
2351
+ if (nextOpen !== -1 && nextOpen < nextClose) {
2352
+ depth++;
2353
+ j = nextOpen + 1;
2354
+ } else {
2355
+ depth--;
2356
+ if (depth === 0) {
2357
+ const inner = html.slice(closeGt + 1, nextClose);
2358
+ out += deconstructInlineElement(tagName, attrs, inner);
2359
+ i = nextClose + closeTag.length;
2360
+ found = true;
2361
+ break;
2362
+ }
2363
+ j = nextClose + 1;
2364
+ }
2365
+ }
2366
+ if (!found) {
2367
+ out += html[i];
2368
+ i++;
2369
+ }
2370
+ } else {
2371
+ const nextTag = html.indexOf("<", i);
2372
+ const textEnd = nextTag === -1 ? html.length : nextTag;
2373
+ out += unescapeHtml(html.slice(i, textEnd));
2374
+ i = textEnd;
2375
+ }
2376
+ return out;
2377
+ }
2378
+ function deconstructInlineElement(tagName, attrs, inner) {
2379
+ const ann = extractAttr(attrs, "data-annotation");
2380
+ const content = deconstructInline(inner);
2381
+ const suffix = ann ? " " + ann : "";
2382
+ switch (tagName) {
2383
+ case "a": return `[${content}](${extractAttr(attrs, "href") || ""})${suffix}`;
2384
+ case "span": return `[${content}]${suffix}`;
2385
+ case "code": return `\`${content}\`${suffix}`;
2386
+ case "strong": return `**${content}**${suffix}`;
2387
+ case "em": return `*${content}*${suffix}`;
2388
+ default: return content + suffix;
2389
+ }
2390
+ }
2391
+ function extractAttr(tag, name) {
2392
+ const re = new RegExp(`(?:\\s|^)${name}=(["'])(.*?)\\1`, "is");
2393
+ const m = tag.match(re);
2394
+ if (!m) return null;
2395
+ return unescapeHtml(m[2]);
2396
+ }
2397
+ function unescapeHtml(s) {
2398
+ return String(s).replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#39;/g, "'");
2399
+ }
2400
+ //#endregion
2031
2401
  //#region src/highlight.js
2032
2402
  /**
2033
2403
  * MD-LD Syntax Highlighter
@@ -2365,4 +2735,4 @@ function updateValue({ text, quad, value, origin }) {
2365
2735
  return text.substring(0, location.valueRange.start) + value + text.substring(location.valueRange.end);
2366
2736
  }
2367
2737
  //#endregion
2368
- export { DEFAULT_CONTEXT, DataFactory, expandIRI, generate, generateNode, getIRIColor, hash, hashIRI, highlightMDLD, locate, merge, parse, parseSemanticBlock, shortenIRI, updateValue };
2738
+ export { DEFAULT_CONTEXT, DataFactory, deconstruct, expandIRI, generate, generateNode, getIRIColor, hash, hashIRI, highlightMDLD, locate, merge, parse, parseSemanticBlock, render, shortenIRI, updateValue };