@prunellejs/content 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,577 @@
1
+ // MDX-lite: literal prop parsing and embedded component expansion for Markdown bodies.
2
+
3
+ import type { MarkdownComponent, RenderMarkdownOptions } from './index'
4
+ import { ssrRaw } from 'prunelle/internal/ssr'
5
+ import { raw } from 'prunelle/server'
6
+
7
+ // Safe recursive-descent JSON5-literal parser for embedded Markdown component props.
8
+ // Supports objects (unquoted/quoted keys, trailing commas), arrays (trailing commas),
9
+ // single/double-quoted strings, numbers (sign, float, exponent, hex), booleans, null, undefined.
10
+ // Rejects all arbitrary JS expressions (calls, operators, identifiers, templates, etc.).
11
+ function parseLiteralValue(src: string): unknown {
12
+ let i = 0
13
+ const len = src.length
14
+
15
+ function skipWsAndComments(): void {
16
+ while (i < len) {
17
+ const ch = src[i]!
18
+ if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
19
+ i++
20
+ continue
21
+ }
22
+ if (ch === '/' && src[i + 1] === '/') {
23
+ i += 2
24
+ while (i < len && src[i] !== '\n') i++
25
+ continue
26
+ }
27
+ if (ch === '/' && src[i + 1] === '*') {
28
+ i += 2
29
+ const end = src.indexOf('*/', i)
30
+ if (end === -1)
31
+ throw new SyntaxError('Unterminated block comment')
32
+ i = end + 2
33
+ continue
34
+ }
35
+ break
36
+ }
37
+ }
38
+
39
+ function parseString(quote: string): string {
40
+ i++ // skip opening quote
41
+ let out = ''
42
+ while (i < len) {
43
+ const ch = src[i]!
44
+ if (ch === quote) {
45
+ i++
46
+ return out
47
+ }
48
+ if (ch === '\\') {
49
+ i++
50
+ if (i >= len)
51
+ throw new SyntaxError('Unterminated string escape')
52
+ const esc = src[i++]!
53
+ switch (esc) {
54
+ case 'n': out += '\n'; break
55
+ case 'r': out += '\r'; break
56
+ case 't': out += '\t'; break
57
+ case 'b': out += '\b'; break
58
+ case 'f': out += '\f'; break
59
+ case 'v': out += '\v'; break
60
+ case '0': out += '\0'; break
61
+ case '\n': break
62
+ case '\r': if (src[i] === '\n') i++; break
63
+ case 'x': {
64
+ const hex = src.slice(i, i + 2)
65
+ if (!/^[0-9a-fA-F]{2}$/.test(hex))
66
+ throw new SyntaxError('Invalid hex escape')
67
+ out += String.fromCharCode(Number.parseInt(hex, 16))
68
+ i += 2
69
+ break
70
+ }
71
+ case 'u': {
72
+ if (src[i] === '{') {
73
+ const close = src.indexOf('}', i + 1)
74
+ if (close === -1)
75
+ throw new SyntaxError('Unterminated unicode escape')
76
+ const hex = src.slice(i + 1, close)
77
+ if (!/^[0-9a-fA-F]+$/.test(hex))
78
+ throw new SyntaxError('Invalid unicode escape')
79
+ out += String.fromCodePoint(Number.parseInt(hex, 16))
80
+ i = close + 1
81
+ }
82
+ else {
83
+ const hex = src.slice(i, i + 4)
84
+ if (!/^[0-9a-fA-F]{4}$/.test(hex))
85
+ throw new SyntaxError('Invalid unicode escape')
86
+ out += String.fromCharCode(Number.parseInt(hex, 16))
87
+ i += 4
88
+ }
89
+ break
90
+ }
91
+ default: out += esc; break
92
+ }
93
+ continue
94
+ }
95
+ if (ch === '\n' || ch === '\r')
96
+ throw new SyntaxError('Unescaped newline in string')
97
+ out += ch
98
+ i++
99
+ }
100
+ throw new SyntaxError('Unterminated string literal')
101
+ }
102
+
103
+ function parseNumber(): number {
104
+ const start = i
105
+ if (src[i] === '+' || src[i] === '-')
106
+ i++
107
+ if (src[i] === '0' && (src[i + 1] === 'x' || src[i + 1] === 'X')) {
108
+ i += 2
109
+ const hexStart = i
110
+ while (i < len && /[0-9a-fA-F]/.test(src[i]!)) i++
111
+ if (i === hexStart)
112
+ throw new SyntaxError('Invalid hex number')
113
+ const sign = src[start] === '-' ? -1 : 1
114
+ return sign * Number.parseInt(src.slice(hexStart, i), 16)
115
+ }
116
+ let hasDigits = false
117
+ while (i < len && /[0-9]/.test(src[i]!)) {
118
+ hasDigits = true
119
+ i++
120
+ }
121
+ if (src[i] === '.') {
122
+ i++
123
+ while (i < len && /[0-9]/.test(src[i]!)) {
124
+ hasDigits = true
125
+ i++
126
+ }
127
+ }
128
+ if (!hasDigits)
129
+ throw new SyntaxError('Invalid number')
130
+ if (src[i] === 'e' || src[i] === 'E') {
131
+ i++
132
+ if (src[i] === '+' || src[i] === '-')
133
+ i++
134
+ const expStart = i
135
+ while (i < len && /[0-9]/.test(src[i]!)) i++
136
+ if (i === expStart)
137
+ throw new SyntaxError('Invalid exponent')
138
+ }
139
+ const num = Number(src.slice(start, i))
140
+ if (Number.isNaN(num))
141
+ throw new SyntaxError('Invalid number')
142
+ return num
143
+ }
144
+
145
+ function parseArray(): unknown[] {
146
+ i++ // skip '['
147
+ const arr: unknown[] = []
148
+ while (true) {
149
+ skipWsAndComments()
150
+ if (i >= len)
151
+ throw new SyntaxError('Unterminated array')
152
+ if (src[i] === ']') {
153
+ i++
154
+ return arr
155
+ }
156
+ arr.push(parseValue())
157
+ skipWsAndComments()
158
+ if (src[i] === ',') {
159
+ i++
160
+ continue
161
+ }
162
+ if (src[i] === ']') {
163
+ i++
164
+ return arr
165
+ }
166
+ throw new SyntaxError('Expected "," or "]" in array')
167
+ }
168
+ }
169
+
170
+ function parseObject(): Record<string, unknown> {
171
+ i++ // skip '{'
172
+ const obj: Record<string, unknown> = {}
173
+ while (true) {
174
+ skipWsAndComments()
175
+ if (i >= len)
176
+ throw new SyntaxError('Unterminated object')
177
+ if (src[i] === '}') {
178
+ i++
179
+ return obj
180
+ }
181
+ let key: string
182
+ const ch = src[i]!
183
+ if (ch === '"' || ch === '\'') {
184
+ key = parseString(ch)
185
+ }
186
+ else if (/[A-Za-z_$]/.test(ch)) {
187
+ const keyStart = i
188
+ while (i < len && /[A-Za-z0-9_$]/.test(src[i]!)) i++
189
+ key = src.slice(keyStart, i)
190
+ }
191
+ else {
192
+ throw new SyntaxError('Expected object key')
193
+ }
194
+ skipWsAndComments()
195
+ if (src[i] !== ':')
196
+ throw new SyntaxError('Expected ":" after object key')
197
+ i++
198
+ const val = parseValue()
199
+ if (key !== '__proto__' && key !== 'constructor' && key !== 'prototype') {
200
+ Object.defineProperty(obj, key, {
201
+ value: val,
202
+ enumerable: true,
203
+ writable: true,
204
+ configurable: true,
205
+ })
206
+ }
207
+ skipWsAndComments()
208
+ if (src[i] === ',') {
209
+ i++
210
+ continue
211
+ }
212
+ if (src[i] === '}') {
213
+ i++
214
+ return obj
215
+ }
216
+ throw new SyntaxError('Expected "," or "}" in object')
217
+ }
218
+ }
219
+
220
+ function parseValue(): unknown {
221
+ skipWsAndComments()
222
+ if (i >= len)
223
+ throw new SyntaxError('Unexpected end of literal')
224
+ const ch = src[i]!
225
+ if (ch === '"' || ch === '\'')
226
+ return parseString(ch)
227
+ if (ch === '[')
228
+ return parseArray()
229
+ if (ch === '{')
230
+ return parseObject()
231
+ if (ch === '-' || ch === '+' || ch === '.' || (ch >= '0' && ch <= '9'))
232
+ return parseNumber()
233
+ if (src.startsWith('true', i) && !/[A-Za-z0-9_$]/.test(src[i + 4] ?? '')) {
234
+ i += 4
235
+ return true
236
+ }
237
+ if (src.startsWith('false', i) && !/[A-Za-z0-9_$]/.test(src[i + 5] ?? '')) {
238
+ i += 5
239
+ return false
240
+ }
241
+ if (src.startsWith('null', i) && !/[A-Za-z0-9_$]/.test(src[i + 4] ?? '')) {
242
+ i += 4
243
+ return null
244
+ }
245
+ if (src.startsWith('undefined', i) && !/[A-Za-z0-9_$]/.test(src[i + 9] ?? '')) {
246
+ i += 9
247
+ return undefined
248
+ }
249
+ throw new SyntaxError(`Unsupported non-literal expression at offset ${i}`)
250
+ }
251
+
252
+ const value = parseValue()
253
+ skipWsAndComments()
254
+ if (i !== len)
255
+ throw new SyntaxError(`Unexpected trailing token at offset ${i}`)
256
+ return value
257
+ }
258
+
259
+ // Prop names that would reach the prototype chain are dropped, however the value is written.
260
+ function setProp(props: Record<string, unknown>, name: string, value: unknown): void {
261
+ if (name !== '__proto__' && name !== 'constructor' && name !== 'prototype')
262
+ props[name] = value
263
+ }
264
+
265
+ // Parse JSX-style attributes inside embedded Markdown components: title="hi" count={42} rows={[...]} flag
266
+ function parseComponentProps(attrSrc: string, tag: string, file: string | undefined): Record<string, unknown> {
267
+ const props: Record<string, unknown> = {}
268
+ let i = 0
269
+ const len = attrSrc.length
270
+
271
+ while (i < len) {
272
+ while (i < len && /\s/.test(attrSrc[i]!)) i++
273
+ if (i >= len) break
274
+
275
+ const nameStart = i
276
+ while (i < len && /[\w:-]/.test(attrSrc[i]!)) i++
277
+ const name = attrSrc.slice(nameStart, i)
278
+ if (!name) {
279
+ i++
280
+ continue
281
+ }
282
+
283
+ while (i < len && /\s/.test(attrSrc[i]!)) i++
284
+ if (attrSrc[i] !== '=') {
285
+ setProp(props, name, true)
286
+ continue
287
+ }
288
+ i++ // skip '='
289
+ while (i < len && /\s/.test(attrSrc[i]!)) i++
290
+
291
+ const ch = attrSrc[i]
292
+ if (ch === '"' || ch === '\'') {
293
+ const quote = ch
294
+ i++
295
+ let val = ''
296
+ while (i < len && attrSrc[i] !== quote) {
297
+ if (attrSrc[i] === '\\' && i + 1 < len) {
298
+ const next = attrSrc[i + 1]!
299
+ if (next === quote || next === '\\') {
300
+ val += next
301
+ i += 2
302
+ continue
303
+ }
304
+ }
305
+ val += attrSrc[i]!
306
+ i++
307
+ }
308
+ setProp(props, name, val)
309
+ if (i < len) i++
310
+ }
311
+ else if (ch === '{') {
312
+ let depth = 0
313
+ const exprStart = i + 1
314
+ let inStr: string | null = null
315
+ while (i < len) {
316
+ const c = attrSrc[i]!
317
+ if (inStr !== null) {
318
+ if (c === '\\') { i += 2; continue }
319
+ if (c === inStr) inStr = null
320
+ }
321
+ else {
322
+ if (c === '"' || c === '\'' || c === '`') inStr = c
323
+ else if (c === '{') depth++
324
+ else if (c === '}') {
325
+ depth--
326
+ if (depth === 0) break
327
+ }
328
+ }
329
+ i++
330
+ }
331
+ const expr = attrSrc.slice(exprStart, i).trim()
332
+ i++ // skip closing '}'
333
+ try {
334
+ setProp(props, name, parseLiteralValue(expr))
335
+ }
336
+ catch {
337
+ throw new Error(`@prunellejs/content: the prop "${name}" of <${tag}> in "${file ?? 'the markdown source'}" is not a literal (${expr}): write a string, number, boolean, array or object literal, or compute the value inside the component.`)
338
+ }
339
+ }
340
+ }
341
+ return props
342
+ }
343
+
344
+ // What one expansion pass has learnt about the source, so no scan is run twice over the same ground.
345
+ export interface ScanMemo {
346
+ // Offsets a failed tag-end scan crossed outside any string or brace: a scan reaching one fails the same way.
347
+ failedAt?: Uint8Array
348
+ // Per tag name, the offset of the matching close tag (-1 for none), keyed by the end of the opening tag.
349
+ closes: Map<string, Map<number, number>>
350
+ }
351
+
352
+ export function createScanMemo(): ScanMemo {
353
+ return { closes: new Map() }
354
+ }
355
+
356
+ const MAX_BRACE_DEPTH = 32
357
+
358
+ // Find the end of an opening JSX tag (`>` or `/>`), respecting strings and balanced `{...}` expressions.
359
+ function findTagEnd(src: string, start: number, memo: ScanMemo): { end: number, selfClosing: boolean } | undefined {
360
+ let i = start
361
+ const len = src.length
362
+ let braceDepth = 0
363
+ let inStr: string | null = null
364
+ const crossed: number[] = []
365
+ const fail = (): undefined => {
366
+ const failedAt = memo.failedAt ??= new Uint8Array(len)
367
+ for (const at of crossed)
368
+ failedAt[at] = 1
369
+ return undefined
370
+ }
371
+
372
+ while (i < len) {
373
+ const c = src[i]!
374
+ if (inStr === null && braceDepth === 0) {
375
+ if (memo.failedAt?.[i] === 1)
376
+ return fail()
377
+ crossed.push(i)
378
+ }
379
+ if (inStr !== null) {
380
+ if (c === '\\') { i += 2; continue }
381
+ if (c === inStr) inStr = null
382
+ i++
383
+ continue
384
+ }
385
+ if (c === '"' || c === '\'' || c === '`') {
386
+ inStr = c
387
+ i++
388
+ continue
389
+ }
390
+ if (c === '{') {
391
+ if (++braceDepth > MAX_BRACE_DEPTH)
392
+ return fail()
393
+ i++
394
+ continue
395
+ }
396
+ if (c === '}') {
397
+ braceDepth = Math.max(0, braceDepth - 1)
398
+ i++
399
+ continue
400
+ }
401
+ if (braceDepth === 0) {
402
+ if (c === '/' && src[i + 1] === '>')
403
+ return { end: i + 2, selfClosing: true }
404
+ if (c === '>')
405
+ return { end: i + 1, selfClosing: false }
406
+ }
407
+ i++
408
+ }
409
+ return fail()
410
+ }
411
+
412
+ // Returns true when the character at `idx` is escaped by an odd number of preceding backslashes.
413
+ function isBackslashEscaped(src: string, idx: number): boolean {
414
+ let slashes = 0
415
+ for (let k = idx - 1; k >= 0 && src[k] === '\\'; k--)
416
+ slashes++
417
+ return (slashes & 1) === 1
418
+ }
419
+
420
+ // Advances past a CommonMark inline code span starting at backtick offset `start`.
421
+ // Returns the offset right after the matching closing backtick run, or -1 if unclosed.
422
+ function matchInlineCodeSpan(src: string, start: number): number {
423
+ let ticks = 0
424
+ while (start + ticks < src.length && src[start + ticks] === '`')
425
+ ticks++
426
+ let pos = start + ticks
427
+ while (pos < src.length) {
428
+ if (src[pos] === '`') {
429
+ let run = 0
430
+ while (pos + run < src.length && src[pos + run] === '`')
431
+ run++
432
+ if (run === ticks)
433
+ return pos + run
434
+ pos += run
435
+ continue
436
+ }
437
+ pos++
438
+ }
439
+ return -1
440
+ }
441
+
442
+ // One pass pairs every opening tag it meets with its close, so the next unclosed tag of the same name is answered from the memo.
443
+ function findMatchingCloseTag(md: string, tagName: string, start: number, memo: ScanMemo): number {
444
+ let closes = memo.closes.get(tagName)
445
+ const known = closes?.get(start)
446
+ if (known !== undefined)
447
+ return known
448
+ closes ??= new Map()
449
+ memo.closes.set(tagName, closes)
450
+ const closeTag = `</${tagName}>`
451
+ const len = md.length
452
+ const open = [start]
453
+ let pos = start
454
+ while (pos < len) {
455
+ const ch = md[pos]!
456
+ if (ch === '`' && !isBackslashEscaped(md, pos)) {
457
+ const spanEnd = matchInlineCodeSpan(md, pos)
458
+ if (spanEnd !== -1) {
459
+ pos = spanEnd
460
+ continue
461
+ }
462
+ while (pos < len && md[pos] === '`') pos++
463
+ continue
464
+ }
465
+ if (ch === '<') {
466
+ if (md.startsWith(closeTag, pos)) {
467
+ closes.set(open.pop()!, pos)
468
+ if (open.length === 0)
469
+ return pos
470
+ pos += closeTag.length
471
+ continue
472
+ }
473
+ if (md.startsWith(`<${tagName}`, pos) && /[\s/>]/.test(md[pos + 1 + tagName.length] ?? '')) {
474
+ const innerEnd = findTagEnd(md, pos + 1 + tagName.length, memo)
475
+ if (innerEnd !== undefined) {
476
+ if (!innerEnd.selfClosing)
477
+ open.push(innerEnd.end)
478
+ pos = innerEnd.end
479
+ continue
480
+ }
481
+ }
482
+ }
483
+ pos++
484
+ }
485
+ for (const unclosed of open)
486
+ closes.set(unclosed, -1)
487
+ return -1
488
+ }
489
+
490
+ export function expandComponents(
491
+ md: string,
492
+ components: Record<string, MarkdownComponent>,
493
+ options: RenderMarkdownOptions,
494
+ slots: string[],
495
+ slotPrefix: string,
496
+ renderMarkdown: (md: string, options: RenderMarkdownOptions) => { html: string },
497
+ ): string {
498
+ const names = Object.keys(components)
499
+ if (names.length === 0)
500
+ return md
501
+ const memo = createScanMemo()
502
+
503
+ let out = ''
504
+ let i = 0
505
+ const len = md.length
506
+
507
+ while (i < len) {
508
+ const lt = md.indexOf('<', i)
509
+ const tick = md.indexOf('`', i)
510
+
511
+ // Skip CommonMark inline code spans so `<Component />` inside backticks is never expanded.
512
+ if (tick !== -1 && (lt === -1 || tick < lt)) {
513
+ if (!isBackslashEscaped(md, tick)) {
514
+ const spanEnd = matchInlineCodeSpan(md, tick)
515
+ if (spanEnd !== -1) {
516
+ out += md.slice(i, spanEnd)
517
+ i = spanEnd
518
+ continue
519
+ }
520
+ }
521
+ let endTick = tick + 1
522
+ while (endTick < len && md[endTick] === '`') endTick++
523
+ out += md.slice(i, endTick)
524
+ i = endTick
525
+ continue
526
+ }
527
+
528
+ if (lt === -1) {
529
+ out += md.slice(i)
530
+ break
531
+ }
532
+
533
+ const match = /^<([A-Z][\w]*)(?=[\s/>])/.exec(md.slice(lt))
534
+ if (match && !Object.hasOwn(components, match[1]!))
535
+ throw new Error(`@prunellejs/content: unknown component <${match[1]}> in "${options.file ?? 'the markdown source'}": registered components are ${names.join(', ')}; register it in the \`components\` option, or wrap the text in backticks if it is not a component.`)
536
+ if (!match) {
537
+ out += md.slice(i, lt + 1)
538
+ i = lt + 1
539
+ continue
540
+ }
541
+
542
+ const tagName = match[1]!
543
+ const tagEnd = findTagEnd(md, lt + match[0].length, memo)
544
+ if (!tagEnd) {
545
+ out += md.slice(i, lt + 1)
546
+ i = lt + 1
547
+ continue
548
+ }
549
+
550
+ out += md.slice(i, lt)
551
+ const attrSrc = md.slice(lt + match[0].length, tagEnd.selfClosing ? tagEnd.end - 2 : tagEnd.end - 1)
552
+ const props = parseComponentProps(attrSrc, tagName, options.file)
553
+ let afterIndex = tagEnd.end
554
+
555
+ if (!tagEnd.selfClosing) {
556
+ const closeTag = `</${tagName}>`
557
+ const closeIdx = findMatchingCloseTag(md, tagName, tagEnd.end, memo)
558
+ if (closeIdx !== -1) {
559
+ const innerMd = md.slice(tagEnd.end, closeIdx).trim()
560
+ const innerRendered = renderMarkdown(innerMd, options)
561
+ props.children = raw(innerRendered.html.trim())
562
+ afterIndex = closeIdx + closeTag.length
563
+ }
564
+ }
565
+
566
+ if (options.locale !== undefined && props.locale === undefined)
567
+ props.locale = options.locale
568
+
569
+ const renderedHtml = ssrRaw(components[tagName]!(props as never))
570
+ const slotIdx = slots.length
571
+ slots.push(renderedHtml)
572
+ out += `\n\n<div data-pru-md-slot="${slotPrefix}${slotIdx}"></div>\n\n`
573
+ i = afterIndex
574
+ }
575
+
576
+ return out
577
+ }