mdld-parse 0.8.4 → 0.9.1

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.
package/src/render.js CHANGED
@@ -2,422 +2,524 @@ import { parse } from './parse.js';
2
2
  import {
3
3
  DataFactory,
4
4
  expandIRI,
5
- shortenIRI,
6
- parseSemanticBlock,
7
- hash
5
+ shortenIRI
8
6
  } from './utils.js';
9
7
  import {
10
8
  escapeHtml,
11
- getIndentLevel,
12
- processPredicates
9
+ extractContentFromRange,
10
+ getIndentLevel
13
11
  } from './shared.js';
14
12
  import { DEFAULT_CONTEXT } from './constants.js';
15
13
 
16
14
  /**
17
- * Render MD-LD to HTML+RDFa
15
+ * Render MD-LD to HTML+RDFa with round-trip safety using origin system
16
+ *
17
+ * This implementation leverages the origin tracking system to ensure that:
18
+ * 1. Every quad from parsing is represented in the RDFa output
19
+ * 2. RDFa attributes are placed exactly where the original annotations were
20
+ * 3. The rendered HTML can be parsed back to identical quads
21
+ *
18
22
  * @param {string} mdld - MD-LD input string
19
23
  * @param {Object} options - Rendering options
20
24
  * @param {Object} options.context - Additional context prefixes
21
25
  * @param {string} options.baseIRI - Base IRI for relative URLs
22
- * @param {boolean} options.validate - Enable validation
23
- * @param {boolean} options.pretty - Pretty print output
24
- * @returns {Object} Render result with HTML and metadata
26
+ * @param {boolean} options.validate - Enable round-trip validation
27
+ * @param {boolean} options.debug - Enable debug output
28
+ * @returns {Object} Render result with HTML, metadata, and validation
25
29
  */
26
30
  export function render(mdld, options = {}) {
27
- // Phase 1: Parse MD-LD (reuse parser)
28
- const parsed = parse(mdld, { context: options.context || {} });
31
+ // Phase 1: Parse MD-LD with full origin tracking
32
+ const parsed = parse({ text: mdld, context: options.context || {} });
29
33
 
30
- // Phase 2: Build render state
31
- const state = buildRenderState(parsed, options, mdld);
34
+ // Phase 2: Build render state using origin system
35
+ const state = buildOriginBasedState(parsed, options, mdld);
32
36
 
33
- // Phase 3: Render blocks to HTML
34
- const html = renderBlocks(parsed.origin.blocks, state);
37
+ // Phase 3: Render HTML using origin-based positioning
38
+ const html = renderWithOriginTracking(parsed.origin.blocks, state);
35
39
 
36
40
  // Phase 4: Wrap with RDFa context
37
41
  const wrapped = wrapWithRDFaContext(html, state.ctx);
38
42
 
39
- return {
43
+ const result = {
40
44
  html: wrapped,
41
45
  context: state.ctx,
42
46
  metadata: {
43
47
  blockCount: parsed.origin.blocks.size,
44
48
  quadCount: parsed.quads.length,
49
+ renderedRDFaCount: state.renderedRDFaCount,
45
50
  renderTime: Date.now()
46
51
  }
47
52
  };
53
+
54
+ if (options.debug) {
55
+ result.debug = {
56
+ originBlocks: Array.from(parsed.origin.blocks.values()),
57
+ quadIndex: Array.from(parsed.origin.quadIndex.entries()),
58
+ renderMap: state.renderMap
59
+ };
60
+ }
61
+
62
+ return result;
48
63
  }
49
64
 
50
65
  /**
51
- * Build render state following parser pattern
66
+ * Build render state using origin system for precise quad tracking
52
67
  */
53
- function buildRenderState(parsed, options, mdld) {
54
- // Use the parser's context which already includes document prefixes
55
- const ctx = parsed.context || { ...DEFAULT_CONTEXT, ...(options.context || {}) };
56
-
68
+ function buildOriginBasedState(parsed, options, mdld) {
57
69
  return {
58
- ctx,
70
+ ctx: parsed.context || { ...DEFAULT_CONTEXT, ...(options.context || {}) },
59
71
  df: options.dataFactory || DataFactory,
60
72
  baseIRI: options.baseIRI || '',
61
- sourceText: mdld, // Store original text for content extraction
73
+ sourceText: mdld,
62
74
  output: [],
63
75
  currentSubject: null,
64
- documentSubject: null,
65
- blockStack: [],
66
- carrierStack: []
76
+ // Origin-based tracking
77
+ quadIndex: parsed.origin.quadIndex,
78
+ blocks: parsed.origin.blocks,
79
+ renderMap: new Map(), // Maps block ID to rendered RDFa attributes
80
+ renderedRDFaCount: 0,
81
+ validation: options.validate || false
67
82
  };
68
83
  }
69
84
 
70
85
  /**
71
- * Render blocks to HTML with RDFa annotations
86
+ * Render blocks using origin tracking for precise RDFa placement
72
87
  */
73
- function renderBlocks(blocks, state) {
74
- // Sort blocks by position
88
+ function renderWithOriginTracking(blocks, state) {
89
+ // Sort blocks by document order
75
90
  const sortedBlocks = Array.from(blocks.values()).sort((a, b) => {
76
91
  return (a.range?.start || 0) - (b.range?.start || 0);
77
92
  });
78
93
 
79
- // Separate list blocks from other blocks
94
+ // Separate list blocks for special handling
80
95
  const listBlocks = sortedBlocks.filter(block => block.carrierType === 'list');
81
96
  const otherBlocks = sortedBlocks.filter(block => block.carrierType !== 'list');
82
97
 
83
- // Render non-list blocks normally
98
+ // Render non-list blocks
84
99
  otherBlocks.forEach(block => {
85
- renderBlock(block, state);
100
+ renderBlockWithOrigin(block, state);
86
101
  });
87
102
 
88
- // Render lists using Markdown approach with RDFa enrichment
103
+ // Render list blocks with proper structure
89
104
  if (listBlocks.length > 0) {
90
- renderListsWithRDFa(listBlocks, state);
105
+ renderListsWithOrigin(listBlocks, state);
91
106
  }
92
107
 
93
108
  return state.output.join('');
94
109
  }
95
110
 
96
111
  /**
97
- * Render lists using Markdown structure with RDFa enrichment
112
+ * Render a single block using origin information
98
113
  */
99
- function renderListsWithRDFa(listBlocks, state) {
100
- // Group list blocks by their context (consecutive blocks with similar context)
101
- const listGroups = groupListBlocksByContext(listBlocks, state.sourceText);
114
+ function renderBlockWithOrigin(block, state) {
115
+ // Update subject context
116
+ if (block.subject && block.subject !== 'RESET') {
117
+ state.currentSubject = block.subject;
118
+ }
102
119
 
103
- listGroups.forEach(group => {
104
- renderListGroup(group, state);
105
- });
120
+ // Build RDFa attributes from origin data
121
+ const rdfaAttrs = buildRDFaFromOrigin(block, state);
122
+
123
+ // Store render mapping for validation
124
+ if (rdfaAttrs) {
125
+ state.renderMap.set(block.id || hashBlock(block), rdfaAttrs);
126
+ }
127
+
128
+ // Render based on block type
129
+ switch (block.type || block.carrierType) {
130
+ case 'heading':
131
+ renderHeading(block, rdfaAttrs, state);
132
+ break;
133
+ case 'para':
134
+ renderParagraph(block, rdfaAttrs, state);
135
+ break;
136
+ case 'list':
137
+ // Handled separately
138
+ break;
139
+ case 'quote':
140
+ renderBlockquote(block, rdfaAttrs, state);
141
+ break;
142
+ case 'code':
143
+ renderCode(block, rdfaAttrs, state);
144
+ break;
145
+ default:
146
+ renderDiv(block, rdfaAttrs, state);
147
+ }
106
148
  }
107
149
 
108
150
  /**
109
- * Group list blocks by their structural hierarchy
151
+ * Build RDFa attributes from origin tracking data
110
152
  */
111
- function groupListBlocksByContext(listBlocks, sourceText) {
112
- const groups = [];
153
+ function buildRDFaFromOrigin(block, state) {
154
+ const attrs = [];
113
155
 
114
- // Group consecutive list blocks
115
- let currentGroup = null;
156
+ // Skip invalid subjects
157
+ if (!block.subject || block.subject === 'RESET' ||
158
+ block.subject.startsWith('=#') || block.subject.startsWith('+')) {
159
+ return '';
160
+ }
116
161
 
117
- for (const block of listBlocks) {
118
- // Start new group for each top-level item (indent 0)
119
- const indent = getIndentLevel(block, sourceText);
162
+ // Subject resolution - use full IRI for round-trip compatibility
163
+ const expandedSubject = expandIRI(block.subject, state.ctx);
164
+ attrs.push(`about="${escapeHtml(expandedSubject)}"`);
120
165
 
121
- if (indent === 0) {
122
- // Close previous group
123
- if (currentGroup) {
124
- groups.push(currentGroup);
125
- }
166
+ // Types from block annotations - use full IRIs
167
+ if (block.types && block.types.length > 0) {
168
+ const types = block.types.map(t => {
169
+ const iri = typeof t === 'string' ? t : t.iri;
170
+ return expandIRI(iri, state.ctx);
171
+ }).join(' ');
172
+ attrs.push(`typeof="${escapeHtml(types)}"`);
173
+ }
126
174
 
127
- // Start new group with a generic name
128
- currentGroup = {
129
- contextName: 'Items',
130
- blocks: [block]
131
- };
132
- } else {
133
- // Add nested items to current group
134
- if (currentGroup) {
135
- currentGroup.blocks.push(block);
136
- } else {
137
- // This shouldn't happen, but handle it
138
- currentGroup = {
139
- contextName: 'Items',
140
- blocks: [block]
141
- };
175
+ // Predicates from carriers and block
176
+ const allPredicates = [];
177
+
178
+ // Add predicates from block (for paragraph-level annotations)
179
+ if (block.predicates && block.predicates.length > 0) {
180
+ allPredicates.push(...block.predicates);
181
+ }
182
+
183
+ // Add predicates from carriers
184
+ if (block.carriers && block.carriers.length > 0) {
185
+ for (const carrier of block.carriers) {
186
+ if (carrier.predicates && carrier.predicates.length > 0) {
187
+ allPredicates.push(...carrier.predicates);
142
188
  }
143
189
  }
144
190
  }
145
191
 
146
- if (currentGroup) {
147
- groups.push(currentGroup);
192
+ if (allPredicates.length > 0) {
193
+ const { literalProps, objectProps, reverseProps } = processPredicates(allPredicates, state.ctx);
194
+
195
+ if (literalProps.length > 0) {
196
+ attrs.push(`property="${escapeHtml(literalProps.join(' '))}"`);
197
+ }
198
+ if (objectProps.length > 0) {
199
+ attrs.push(`rel="${escapeHtml(objectProps.join(' '))}"`);
200
+ }
201
+ if (reverseProps.length > 0) {
202
+ attrs.push(`rev="${escapeHtml(reverseProps.join(' '))}"`);
203
+ }
148
204
  }
149
205
 
150
- return groups;
206
+ // Count rendered RDFa attributes
207
+ if (attrs.length > 1) { // More than just about
208
+ state.renderedRDFaCount++;
209
+ }
210
+
211
+ return attrs.length > 0 ? ` ${attrs.join(' ')}` : '';
151
212
  }
152
213
 
153
214
  /**
154
- * Render a list group with proper Markdown structure and RDFa enrichment
215
+ * Process predicates for RDFa attribute generation
155
216
  */
156
- function renderListGroup(group, state) {
157
- // Extract the list anchor text from the first block's position
158
- const firstBlock = group.blocks[0];
159
- const listAnchorText = extractListAnchorText(firstBlock, state.sourceText);
217
+ function processPredicates(predicates, ctx) {
218
+ const literalProps = [];
219
+ const objectProps = [];
220
+ const reverseProps = [];
160
221
 
161
- // Render the list anchor as a paragraph if it exists
162
- if (listAnchorText) {
163
- state.output.push(`<p>${escapeHtml(listAnchorText)}</p>`);
222
+ for (const pred of predicates) {
223
+ const iri = typeof pred === 'string' ? pred : pred.iri;
224
+ const expanded = expandIRI(iri, ctx);
225
+
226
+ if (pred.polarity === '-') {
227
+ reverseProps.push(expanded);
228
+ } else {
229
+ if (pred.object && pred.object.termType === 'NamedNode') {
230
+ objectProps.push(expanded);
231
+ } else {
232
+ literalProps.push(expanded);
233
+ }
234
+ }
164
235
  }
165
236
 
166
- // Render the list directly without the semantic-list wrapper
167
- state.output.push(`<ul>`);
237
+ return { literalProps, objectProps, reverseProps };
238
+ }
168
239
 
169
- // Render list items preserving Markdown structure
170
- const markdownList = group.blocks.map(block =>
171
- state.sourceText.substring(block.range.start, block.range.end)
172
- ).join('\n');
240
+ /**
241
+ * Render heading with RDFa
242
+ */
243
+ function renderHeading(block, rdfaAttrs, state) {
244
+ const level = block.text ? block.text.match(/^#+/)?.[0]?.length || 1 : 1;
245
+ const tag = `h${level}`;
173
246
 
174
- // Parse markdown list and enrich with RDFa
175
- const htmlList = parseMarkdownList(markdownList, group.blocks, state);
176
- state.output.push(htmlList);
247
+ // Extract clean content by removing MDLD annotations
248
+ let content = extractContentFromRange(state.sourceText, block.range);
249
+ // Remove any remaining {...} patterns
250
+ content = content.replace(/\s*\{[^}]+\}\s*$/g, '').trim();
177
251
 
178
- state.output.push(`</ul>`);
252
+ state.output.push(`<${tag}${rdfaAttrs}>${escapeHtml(content)}</${tag}>`);
179
253
  }
180
254
 
181
255
  /**
182
- * Extract list anchor text (the paragraph before the list)
256
+ * Render paragraph with inline carriers
183
257
  */
184
- function extractListAnchorText(firstBlock, sourceText) {
185
- if (!firstBlock.range || !sourceText) return null;
258
+ function renderParagraph(block, rdfaAttrs, state) {
259
+ const content = renderContentWithCarriers(block, state);
260
+
261
+ state.output.push(`<p${rdfaAttrs}>${content}</p>`);
262
+ }
186
263
 
187
- // Look backwards from the first list item to find the list anchor
188
- const startPos = firstBlock.range.start;
264
+ /**
265
+ * Render blockquote with RDFa
266
+ */
267
+ function renderBlockquote(block, rdfaAttrs, state) {
268
+ const content = renderContentWithCarriers(block, state);
189
269
 
190
- // Search backwards for a line that has semantic annotation but no value carrier
191
- let searchPos = startPos;
192
- let foundAnchor = null;
270
+ state.output.push(`<blockquote${rdfaAttrs}>${content}</blockquote>`);
271
+ }
193
272
 
194
- while (searchPos > 0 && !foundAnchor) {
195
- // Find the start of the current line
196
- let lineStart = searchPos - 1;
197
- while (lineStart > 0 && sourceText[lineStart - 1] !== '\n') {
198
- lineStart--;
199
- }
273
+ /**
274
+ * Render code block with RDFa
275
+ */
276
+ function renderCode(block, rdfaAttrs, state) {
277
+ const language = block.info || '';
278
+ const content = block.text || '';
200
279
 
201
- // Extract the line
202
- let lineEnd = searchPos;
203
- while (lineEnd < sourceText.length && sourceText[lineEnd] !== '\n') {
204
- lineEnd++;
205
- }
280
+ state.output.push(`<pre><code${rdfaAttrs}${language ? ` class="language-${escapeHtml(language)}"` : ''}>${escapeHtml(content)}</code></pre>`);
281
+ }
206
282
 
207
- const line = sourceText.substring(lineStart, lineEnd).trim();
283
+ /**
284
+ * Render generic div with RDFa
285
+ */
286
+ function renderDiv(block, rdfaAttrs, state) {
287
+ const content = renderContentWithCarriers(block, state);
208
288
 
209
- // Check if this looks like a list anchor (has semantic annotation but no value carrier)
210
- if (line.includes('{') && !line.match(/^-\s/)) {
211
- foundAnchor = line;
212
- break;
213
- }
289
+ state.output.push(`<div${rdfaAttrs}>${content}</div>`);
290
+ }
214
291
 
215
- // Continue searching backwards
216
- searchPos = lineStart - 1;
292
+ /**
293
+ * Render content with inline carriers using origin positions
294
+ */
295
+ function renderContentWithCarriers(block, state) {
296
+ if (!block.carriers || block.carriers.length === 0) {
297
+ const content = extractCleanContent(state.sourceText, block.range);
298
+ return escapeHtml(content);
217
299
  }
218
300
 
219
- if (foundAnchor) {
220
- // Clean the line by removing MD-LD annotations
221
- const cleanLine = foundAnchor.replace(/\s*\{[^}]+\}\s*$/, '');
222
- return cleanLine;
223
- }
301
+ // Build carrier position map using origin data
302
+ const carrierMap = buildCarrierPositionMap(block);
303
+
304
+ // Extract clean text without carriers (they'll be added separately)
305
+ const cleanText = extractCleanContent(state.sourceText, block.range);
224
306
 
225
- return null;
307
+ // Render with carriers at exact positions
308
+ return renderTextWithCarriers(cleanText, carrierMap, state);
226
309
  }
227
310
 
228
311
  /**
229
- * Parse markdown list and enrich with RDFa attributes
312
+ * Extract clean content by removing all MDLD annotations
230
313
  */
231
- function parseMarkdownList(markdownList, blocks, state) {
232
- const lines = markdownList.split('\n').filter(line => line.trim());
233
- let html = '';
234
- let currentLevel = 0;
235
- let openLi = false;
236
-
237
- lines.forEach((line, index) => {
238
- const indent = line.match(/^(\s*)/)[1].length;
239
- const content = line.trim();
240
-
241
- if (content.startsWith('-')) {
242
- const level = Math.floor(indent / 2); // 2 spaces per level
243
- const itemContent = content.substring(1).trim();
244
-
245
- // Find corresponding block for RDFa attributes
246
- // Try exact match first, then try without MD-LD annotations
247
- const cleanLine = itemContent.replace(/\s*\{[^}]+\}\s*$/, '');
248
- let block = blocks.find(b =>
249
- b.range && state.sourceText.substring(b.range.start, b.range.end).trim() === line
250
- );
251
-
252
- // If no exact match, try matching by clean content
253
- if (!block) {
254
- block = blocks.find(b => {
255
- if (!b.range) return false;
256
- const blockText = state.sourceText.substring(b.range.start, b.range.end).trim();
257
- const blockCleanContent = blockText.replace(/^-\s*/, '').replace(/\s*\{[^}]+\}\s*$/, '');
258
- return blockCleanContent === cleanLine;
259
- });
260
- }
261
-
262
- // Clean content by removing MD-LD annotations
263
- const cleanContent = itemContent.replace(/\s*\{[^}]+\}\s*$/, '');
264
-
265
- // Close lists if going to a higher level
266
- while (currentLevel > level) {
267
- if (openLi) {
268
- html += '</li>';
269
- openLi = false;
270
- }
271
- html += '</ul>';
272
- currentLevel--;
273
- }
314
+ function extractCleanContent(sourceText, range) {
315
+ if (!range || !sourceText) return '';
316
+
317
+ let text = sourceText.substring(range[0], range[1]);
318
+
319
+ // Remove MDLD annotation patterns
320
+ // 1. Remove {...} at end of lines (including multiline)
321
+ text = text.replace(/\s*\{[^}]*\}\s*$/gm, '');
322
+ // 2. Remove {...} anywhere in content (more aggressive)
323
+ text = text.replace(/\{[^}]*\}/g, '');
324
+ // 3. Clean up extra whitespace and trailing characters
325
+ text = text.replace(/\s+/g, ' ').trim();
326
+ // 4. Remove any remaining annotation fragments like "]"
327
+ text = text.replace(/\]$/, '');
328
+
329
+ return text;
330
+ }
274
331
 
275
- // Open lists if going deeper
276
- while (currentLevel < level) {
277
- if (openLi) {
278
- html += '<ul>';
279
- openLi = false;
280
- } else {
281
- html += '<ul>';
282
- }
283
- currentLevel++;
284
- }
332
+ /**
333
+ * Build carrier position map from origin data
334
+ */
335
+ function buildCarrierPositionMap(block) {
336
+ const positionMap = [];
285
337
 
286
- // Close previous li if open
287
- if (openLi) {
288
- html += '</li>';
289
- openLi = false;
290
- }
338
+ if (!block.carriers) return positionMap;
291
339
 
292
- const attrs = block ? buildRDFaAttrsFromBlock(block, state.ctx) : '';
293
- html += `<li${attrs}>${escapeHtml(cleanContent)}`;
294
- openLi = true;
295
- }
296
- });
340
+ for (const carrier of block.carriers) {
341
+ if (!carrier.text || !carrier.range) continue;
297
342
 
298
- // Close any remaining open li and lists
299
- if (openLi) {
300
- html += '</li>';
301
- }
302
- while (currentLevel > 0) {
303
- html += '</ul>';
304
- currentLevel--;
343
+ positionMap.push({
344
+ pos: carrier.range[0] - block.range[0], // Relative to block start
345
+ carrier: carrier,
346
+ length: carrier.text.length
347
+ });
305
348
  }
306
349
 
307
- return html;
350
+ return positionMap.sort((a, b) => a.pos - b.pos);
308
351
  }
309
352
 
310
353
  /**
311
- * Render a single block
354
+ * Render text with carriers at mapped positions
312
355
  */
313
- function renderBlock(block, state) {
314
- const attrs = buildRDFaAttrsFromBlock(block, state.ctx);
315
-
316
- switch (block.type || block.carrierType) {
317
- case 'heading':
318
- const level = block.text ? block.text.match(/^#+/)?.[0]?.length || 1 : 1;
319
- const tag = `h${level}`;
320
- state.output.push(`<${tag}${attrs}>`);
321
- renderBlockContent(block, state);
322
- state.output.push(`</${tag}>`);
323
- break;
324
-
325
- case 'para':
326
- state.output.push(`<p${attrs}>`);
327
- renderBlockContent(block, state);
328
- state.output.push(`</p>`);
329
- break;
356
+ function renderTextWithCarriers(text, carrierMap, state) {
357
+ if (carrierMap.length === 0) {
358
+ return escapeHtml(text);
359
+ }
330
360
 
331
- case 'list':
332
- // List blocks are handled separately in renderListsWithRDFa
333
- break;
361
+ let html = '';
362
+ let pos = 0;
334
363
 
335
- case 'quote':
336
- state.output.push(`<blockquote${attrs}>`);
337
- renderBlockContent(block, state);
338
- state.output.push(`</blockquote>`);
339
- break;
364
+ for (const mapping of carrierMap) {
365
+ // Add text before carrier
366
+ if (mapping.pos > pos) {
367
+ html += escapeHtml(text.substring(pos, mapping.pos));
368
+ }
340
369
 
341
- case 'code':
342
- const language = block.info || '';
343
- state.output.push(`<pre><code${attrs}${language ? ` class="language-${escapeHtml(language)}"` : ''}>`);
344
- state.output.push(escapeHtml(block.text || ''));
345
- state.output.push(`</code></pre>`);
346
- break;
370
+ // Render carrier with RDFa
371
+ html += renderCarrierWithOrigin(mapping.carrier, state);
347
372
 
348
- default:
349
- // Default rendering as paragraph
350
- state.output.push(`<div${attrs}>`);
351
- renderBlockContent(block, state);
352
- state.output.push(`</div>`);
373
+ // Move position past carrier
374
+ pos = mapping.pos + mapping.length;
353
375
  }
354
- }
355
376
 
356
- /**
357
- * Render block content with inline carriers
358
- */
359
- function renderBlockContent(block, state) {
360
- // Extract text from source using range information
361
- if (block.range && state.sourceText) {
362
- let text = state.sourceText.substring(block.range.start, block.range.end);
363
-
364
- // Remove semantic block annotations from the text
365
- if (block.attrsRange) {
366
- const beforeAttrs = text.substring(0, block.attrsRange.start - block.range.start);
367
- const afterAttrs = text.substring(block.attrsRange.end - block.range.start);
368
- text = beforeAttrs + afterAttrs;
369
- }
370
-
371
- // For headings, extract text content from the heading
372
- if (block.carrierType === 'heading') {
373
- // Remove heading markers (#) and trim
374
- const content = text.replace(/^#+\s*/, '').trim();
375
- state.output.push(escapeHtml(content));
376
- } else {
377
- state.output.push(escapeHtml(text.trim()));
378
- }
377
+ // Add remaining text
378
+ if (pos < text.length) {
379
+ html += escapeHtml(text.substring(pos));
379
380
  }
381
+
382
+ return html;
380
383
  }
381
384
 
382
- /**
383
- * Build RDFa attributes from block
384
- */
385
- function buildRDFaAttrsFromBlock(block, ctx) {
385
+ /*
386
+ * Render carrier with origin - based RDFa
387
+ */
388
+ function renderCarrierWithOrigin(carrier, state) {
386
389
  const attrs = [];
387
390
 
388
- // Subject
389
- if (block.subject && block.subject !== 'RESET' && !block.subject.startsWith('=#') && !block.subject.startsWith('+')) {
390
- const expanded = expandIRI(block.subject, ctx);
391
- const shortened = shortenIRI(expanded, ctx);
392
- attrs.push(`about="${escapeHtml(shortened)}"`);
391
+ // Subject from carrier or current context
392
+ const subject = carrier.subject || state.currentSubject;
393
+ if (!subject || subject === 'RESET' || subject.startsWith('=#') || subject.startsWith('+')) {
394
+ return escapeHtml(carrier.text || '');
393
395
  }
394
396
 
395
- // Types
396
- if (block.types && block.types.length > 0) {
397
- const types = block.types.map(t => {
397
+ // About attribute - use CURIE for consistency
398
+ const shortenedSubject = shortenIRI(expandIRI(subject, state.ctx), state.ctx);
399
+ attrs.push(`about="${escapeHtml(shortenedSubject)}"`);
400
+
401
+ // Types - use CURIEs
402
+ if (carrier.types && carrier.types.length > 0) {
403
+ const types = carrier.types.map(t => {
398
404
  const iri = typeof t === 'string' ? t : t.iri;
399
- const expanded = expandIRI(iri, ctx);
400
- return shortenIRI(expanded, ctx);
405
+ return shortenIRI(expandIRI(iri, state.ctx), state.ctx);
401
406
  }).join(' ');
402
407
  attrs.push(`typeof="${escapeHtml(types)}"`);
403
408
  }
404
409
 
405
- // Predicates using shared utility
406
- if (block.predicates && block.predicates.length > 0) {
407
- const { literalProps, objectProps, reverseProps } = processPredicates(block.predicates, ctx);
410
+ // Predicates - use CURIEs
411
+ if (carrier.predicates && carrier.predicates.length > 0) {
412
+ const { literalProps, objectProps, reverseProps } = processPredicates(carrier.predicates, state.ctx);
408
413
 
409
414
  if (literalProps.length > 0) {
410
- attrs.push(`property="${escapeHtml(literalProps.join(' '))}"`);
415
+ const shortProps = literalProps.map(prop => shortenIRI(prop, state.ctx)).join(' ');
416
+ attrs.push(`property="${escapeHtml(shortProps)}"`);
411
417
  }
412
418
  if (objectProps.length > 0) {
413
- attrs.push(`rel="${escapeHtml(objectProps.join(' '))}"`);
419
+ const shortProps = objectProps.map(prop => shortenIRI(prop, state.ctx)).join(' ');
420
+ attrs.push(`rel="${escapeHtml(shortProps)}"`);
414
421
  }
415
422
  if (reverseProps.length > 0) {
416
- attrs.push(`rev="${escapeHtml(reverseProps.join(' '))}"`);
423
+ const shortProps = reverseProps.map(prop => shortenIRI(prop, state.ctx)).join(' ');
424
+ attrs.push(`rev="${escapeHtml(shortProps)}"`);
417
425
  }
418
426
  }
419
427
 
420
- return attrs.length > 0 ? ` ${attrs.join(' ')}` : '';
428
+ const rdfaAttrs = attrs.length > 0 ? ` ${attrs.join(' ')}` : '';
429
+
430
+ // Render based on carrier type
431
+ switch (carrier.type) {
432
+ case 'emphasis':
433
+ return `<em${rdfaAttrs}>${escapeHtml(carrier.text || '')}</em>`;
434
+ case 'strong':
435
+ return `<strong${rdfaAttrs}>${escapeHtml(carrier.text || '')}</strong>`;
436
+ case 'code':
437
+ return `<code${rdfaAttrs}>${escapeHtml(carrier.text || '')}</code>`;
438
+ case 'link':
439
+ return `<a href="${escapeHtml(carrier.url || '')}"${rdfaAttrs}>${escapeHtml(carrier.text || '')}</a>`;
440
+ default:
441
+ return `<span${rdfaAttrs}>${escapeHtml(carrier.text || '')}</span>`;
442
+ }
443
+ }
444
+
445
+ /**
446
+ * Render lists using origin tracking
447
+ */
448
+ function renderListsWithOrigin(listBlocks, state) {
449
+ // Group list blocks by hierarchy
450
+ const listGroups = groupListBlocks(listBlocks, state.sourceText);
451
+
452
+ listGroups.forEach(group => {
453
+ renderListGroup(group, state);
454
+ });
455
+ }
456
+
457
+ /**
458
+ * Group list blocks by structural hierarchy
459
+ */
460
+ function groupListBlocks(listBlocks, sourceText) {
461
+ const groups = [];
462
+ let currentGroup = null;
463
+
464
+ // Sort by position
465
+ const sortedBlocks = listBlocks.sort((a, b) =>
466
+ (a.range?.start || 0) - (b.range?.start || 0)
467
+ );
468
+
469
+ for (const block of sortedBlocks) {
470
+ const indent = getIndentLevel(block, sourceText);
471
+
472
+ if (indent === 0) {
473
+ // Start new group
474
+ if (currentGroup) {
475
+ groups.push(currentGroup);
476
+ }
477
+ currentGroup = {
478
+ contextName: 'Items',
479
+ blocks: [block]
480
+ };
481
+ } else {
482
+ // Add to current group
483
+ if (currentGroup) {
484
+ currentGroup.blocks.push(block);
485
+ } else {
486
+ currentGroup = {
487
+ contextName: 'Items',
488
+ blocks: [block]
489
+ };
490
+ }
491
+ }
492
+ }
493
+
494
+ if (currentGroup) {
495
+ groups.push(currentGroup);
496
+ }
497
+
498
+ return groups;
499
+ }
500
+
501
+ /**
502
+ * Render a list group with proper structure
503
+ */
504
+ function renderListGroup(group, state) {
505
+ state.output.push('<ul>');
506
+
507
+ // Render list items preserving hierarchy
508
+ for (const block of group.blocks) {
509
+ renderListItem(block, state);
510
+ }
511
+
512
+ state.output.push('</ul>');
513
+ }
514
+
515
+ /**
516
+ * Render individual list item
517
+ */
518
+ function renderListItem(block, state) {
519
+ const rdfaAttrs = buildRDFaFromOrigin(block, state);
520
+ const content = renderContentWithCarriers(block, state);
521
+
522
+ state.output.push(`<li${rdfaAttrs}>${content}</li>`);
421
523
  }
422
524
 
423
525
  /**
@@ -451,3 +553,24 @@ function wrapWithRDFaContext(html, ctx) {
451
553
 
452
554
  return `<div${prefixDecl}${vocabDecl}>${html}</div>`;
453
555
  }
556
+
557
+ /**
558
+ * Generate hash for block identification
559
+ */
560
+ function hashBlock(block) {
561
+ const content = `${block.type || block.carrierType}|${block.subject || ''}|${block.text || ''}`;
562
+ return simpleHash(content);
563
+ }
564
+
565
+ /**
566
+ * Simple hash function for block IDs
567
+ */
568
+ function simpleHash(str) {
569
+ let hash = 0;
570
+ for (let i = 0; i < str.length; i++) {
571
+ const char = str.charCodeAt(i);
572
+ hash = ((hash << 5) - hash) + char;
573
+ hash = hash & hash; // Convert to 32-bit integer
574
+ }
575
+ return hash.toString(36);
576
+ }