prunelle 0.7.2 → 0.7.4

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.
@@ -451,7 +451,7 @@ function compileElementTree(ctx: DomCompilerCtx, rootEl: JSXElement, scopeRewrit
451
451
  resolveElementAliases(tree)
452
452
 
453
453
  const rootTag = jsxTagName(rootEl.openingElement.name)
454
- const tmplName = `_t${ctx.templates.length}`
454
+ const tmplName = ctx.freshVar('_t')
455
455
  const isSvg = ctx.svgDepth > 0 ? rootTag !== 'svg' : SVG_CHILD_TAGS.has(rootTag)
456
456
  ctx.templates.push({ name: tmplName, html, isSvg })
457
457
 
@@ -478,9 +478,17 @@ function compileFragmentChildren(ctx: DomCompilerCtx, children: readonly JSXChil
478
478
  }
479
479
  }
480
480
 
481
- const emitFragRangeOp = (hydrateCall: string, mountCall: string, needsRemoveChild: boolean): string => {
481
+ const emitFragRangeOp = (
482
+ hydrate: (sVar: string) => string,
483
+ mount: (pVar: string, mVar: string) => string,
484
+ needsRemoveChild: boolean,
485
+ ): string => {
486
+ const sVar = ctx.freshVar('_s')
487
+ const fVar = ctx.freshVar('_f')
488
+ const mVar = ctx.freshVar('_m')
489
+ const pVar = ctx.freshVar('_p')
482
490
  const removeProp = needsRemoveChild ? ', removeChild: (n) => n.parentNode && n.parentNode.removeChild(n)' : ''
483
- return `(() => { const _s = ${ctx.use('claimRange')}(); if (_s !== null) { ${hydrateCall}; return null; } const _f = document.createDocumentFragment(); _f.appendChild(document.createComment("")); const _m = _f.appendChild(document.createComment("")); const _p = { insertBefore: (n, r) => (_m.parentNode || _f).insertBefore(n, r)${removeProp} }; ${mountCall}; return _f; })()`
491
+ return `(() => { const ${sVar} = ${ctx.use('claimRange')}(); if (${sVar} !== null) { ${hydrate(sVar)}; return null; } const ${fVar} = document.createDocumentFragment(); ${fVar}.appendChild(document.createComment("")); const ${mVar} = ${fVar}.appendChild(document.createComment("")); const ${pVar} = { insertBefore: (n, r) => (${mVar}.parentNode || ${fVar}).insertBefore(n, r)${removeProp} }; ${mount(pVar, mVar)}; return ${fVar}; })()`
484
492
  }
485
493
 
486
494
  for (const { slot, marker } of planned) {
@@ -500,17 +508,21 @@ function compileFragmentChildren(ctx: DomCompilerCtx, children: readonly JSXChil
500
508
  }
501
509
  else if (slot.kind === 'loop') {
502
510
  const compiled = compileLoopCall(ctx, slot.match, scopeRewrites)
503
- if (compiled.isStatic)
504
- items.push(`(() => { const _s = ${ctx.use('claimRange')}(); if (_s !== null) { ${compiled.call('_s.parentNode', '_s')}; return null; } const _f = document.createDocumentFragment(); ${compiled.call('_f', 'null')}; return _f; })()`)
505
- else
506
- items.push(emitFragRangeOp(compiled.call('_s.parentNode', '_s'), compiled.call('_p', '_m'), true))
511
+ if (compiled.isStatic) {
512
+ const sVar = ctx.freshVar('_s')
513
+ const fVar = ctx.freshVar('_f')
514
+ items.push(`(() => { const ${sVar} = ${ctx.use('claimRange')}(); if (${sVar} !== null) { ${compiled.call(`${sVar}.parentNode`, sVar)}; return null; } const ${fVar} = document.createDocumentFragment(); ${compiled.call(fVar, 'null')}; return ${fVar}; })()`)
515
+ }
516
+ else {
517
+ items.push(emitFragRangeOp(s => compiled.call(`${s}.parentNode`, s), (p, m) => compiled.call(p, m), true))
518
+ }
507
519
  }
508
520
  else if (slot.kind === 'and-show') {
509
521
  const whenCode = ctx.compileExpression(slot.expr.left, scopeRewrites)
510
522
  const trueCode = compileRootJsx(ctx, slot.right, scopeRewrites)
511
523
  items.push(emitFragRangeOp(
512
- `${ctx.use('show')}(_s.parentNode, _s, () => ${whenCode}, () => ${trueCode})`,
513
- `${ctx.use('show')}(_p, _m, () => ${whenCode}, () => ${trueCode})`,
524
+ s => `${ctx.use('show')}(${s}.parentNode, ${s}, () => ${whenCode}, () => ${trueCode})`,
525
+ (p, m) => `${ctx.use('show')}(${p}, ${m}, () => ${whenCode}, () => ${trueCode})`,
514
526
  false,
515
527
  ))
516
528
  }
@@ -519,17 +531,20 @@ function compileFragmentChildren(ctx: DomCompilerCtx, children: readonly JSXChil
519
531
  const trueCode = isJsxNode(slot.cons) ? compileRootJsx(ctx, slot.cons, scopeRewrites) : ctx.compileExpression(slot.cons, scopeRewrites)
520
532
  const falseCode = isJsxNode(slot.alt) ? compileRootJsx(ctx, slot.alt, scopeRewrites) : ctx.compileExpression(slot.alt, scopeRewrites)
521
533
  items.push(emitFragRangeOp(
522
- `${ctx.use('show')}(_s.parentNode, _s, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
523
- `${ctx.use('show')}(_p, _m, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
534
+ s => `${ctx.use('show')}(${s}.parentNode, ${s}, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
535
+ (p, m) => `${ctx.use('show')}(${p}, ${m}, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
524
536
  false,
525
537
  ))
526
538
  }
527
539
  else {
528
540
  const exprCode = ctx.compileExpression(slot.expr, scopeRewrites)
529
- if (marker === 'range')
541
+ if (marker === 'range') {
530
542
  items.push(`${ctx.use('fragInsert')}(() => (${exprCode}))`)
531
- else
532
- items.push(`(() => { const _t = ${ctx.use('fragText')}("", true); ${formatSetTextOp('_t', `(${exprCode})`, slot.expr, scopeRewrites, ctx.use)} return _t; })()`)
543
+ }
544
+ else {
545
+ const tVar = ctx.freshVar('_t')
546
+ items.push(`(() => { const ${tVar} = ${ctx.use('fragText')}("", true); ${formatSetTextOp(tVar, `(${exprCode})`, slot.expr, scopeRewrites, ctx.use)} return ${tVar}; })()`)
547
+ }
533
548
  }
534
549
  }
535
550
  flushStatic()
@@ -563,13 +578,24 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
563
578
  const used = new Set<string>()
564
579
  const templates: { name: string, html: string, isSvg?: boolean }[] = []
565
580
  const delegatedEvents = new Set<string>()
581
+ const taken = new Set(code.match(/\b_[\w$]*/g))
582
+ const counters = new Map<string, number>()
566
583
  let varCounter = 0
567
584
 
568
585
  const use = (name: string): string => {
569
586
  used.add(name)
570
587
  return `__${name}`
571
588
  }
572
- const freshVar = (prefix = '_e'): string => `${prefix}${varCounter++}`
589
+ const freshVar = (prefix = '_e'): string => {
590
+ let n = counters.get(prefix) ?? 0
591
+ let name: string
592
+ do {
593
+ name = `${prefix}${n++}`
594
+ } while (taken.has(name))
595
+ counters.set(prefix, n)
596
+ taken.add(name)
597
+ return name
598
+ }
573
599
 
574
600
  // Client builds keep the `load` binding, so every export form stays valid, and drop its server-only code.
575
601
  for (const node of loadNodes) {
@@ -135,7 +135,11 @@ export function staticLiteralOrTemplate(node: Node): { ok: true, value: string |
135
135
  }
136
136
 
137
137
  export function formatStaticAttrValue(name: string, value: string | number | boolean | null, tag?: string): string {
138
- if (value === null || isBlockedAttr(name))
138
+ if (value === null || isBlockedAttr(name) || name === 'indeterminate')
139
+ return ''
140
+ if (name === 'checked' || name === 'selected' || name === 'muted')
141
+ return value ? ` ${name}` : ''
142
+ if (name === 'value' && typeof value === 'boolean')
139
143
  return ''
140
144
  if (typeof value === 'boolean') {
141
145
  if (isStringBoolAttr(name))
@@ -264,7 +268,7 @@ export function serializeComponentProps(
264
268
  export interface SelectValueBinding {
265
269
  staticValue?: string | undefined
266
270
  expr?: string | undefined
267
- multiple: boolean
271
+ multiple: boolean | string
268
272
  }
269
273
 
270
274
  export function isSimpleValueExpr(node: Node): boolean {
@@ -300,16 +304,17 @@ export function formatOptionSelectedExpr(
300
304
  return { staticSelected: selectVal.staticValue === optVal.staticValue }
301
305
  const sv = selectVal.staticValue !== undefined ? JSON.stringify(selectVal.staticValue) : selectVal.expr!
302
306
  const ov = optVal.staticValue !== undefined ? JSON.stringify(optVal.staticValue) : optVal.expr!
303
- if (selectVal.multiple) {
307
+ const scalarEq = optVal.staticValue !== undefined
308
+ ? `${sv} != null && typeof ${sv} !== "boolean" && String(${sv}) === ${ov}`
309
+ : `${sv} != null && typeof ${sv} !== "boolean" && ${ov} != null && String(${sv}) === String(${ov})`
310
+ if (selectVal.multiple !== false) {
311
+ const isMulti = selectVal.multiple === true ? `Array.isArray(${sv})` : `(${selectVal.multiple} && Array.isArray(${sv}))`
304
312
  const cond = optVal.staticValue !== undefined
305
- ? `Array.isArray(${sv}) ? ${sv}.some((_x) => String(_x) === ${ov}) : (${sv} != null && String(${sv}) === ${ov})`
306
- : `${ov} != null && (Array.isArray(${sv}) ? ${sv}.some((_x) => String(_x) === String(${ov})) : (${sv} != null && String(${sv}) === String(${ov})))`
313
+ ? `${isMulti} ? ${sv}.some((_x) => String(_x) === ${ov}) : (${scalarEq})`
314
+ : `${ov} != null && (${isMulti} ? ${sv}.some((_x) => String(_x) === String(${ov})) : (${scalarEq}))`
307
315
  return { expr: `((${cond}) ? " selected" : "")` }
308
316
  }
309
- const cond = optVal.staticValue !== undefined
310
- ? `${sv} != null && String(${sv}) === ${ov}`
311
- : `${sv} != null && ${ov} != null && String(${sv}) === String(${ov})`
312
- return { expr: `((${cond}) ? " selected" : "")` }
317
+ return { expr: `((${scalarEq}) ? " selected" : "")` }
313
318
  }
314
319
 
315
320
  export interface SsrElementAttrsContext {
@@ -388,6 +393,32 @@ function emitSsrExprAttr(
388
393
  return undefined
389
394
  }
390
395
 
396
+ function emitSsrSpreadAttrs(
397
+ ctx: SsrElementAttrsContext,
398
+ attrs: readonly JSXAttributeItem[],
399
+ spreadEntries: readonly string[],
400
+ selectIsMultiple: boolean,
401
+ ): Pick<SsrElementAttrsResult, 'textareaValue' | 'nextSelectValue'> {
402
+ const { tag, parts, flushParts, pushStmt, nextId, use, compileSubExpression } = ctx
403
+ if (spreadEntries.length === 0)
404
+ return { textareaValue: undefined, nextSelectValue: undefined }
405
+ const soleSpread = spreadEntries.length === 1 && attrs.length === 1
406
+ ? compileSubExpression((attrs[0] as Extract<JSXAttributeItem, { type: 'JSXSpreadAttribute' }>).argument)
407
+ : undefined
408
+ const propsExpr = soleSpread ?? `{ ${spreadEntries.join(', ')} }`
409
+ if (tag === 'textarea' || tag === 'select') {
410
+ const spVar = `_sp${nextId()}`
411
+ flushParts()
412
+ pushStmt(`const ${spVar} = ${propsExpr};`)
413
+ parts.pushExpr(`${use('ssrSpread')}(${spVar}, ${JSON.stringify(tag)})`)
414
+ if (tag === 'textarea')
415
+ return { textareaValue: { expr: `${spVar}?.value` }, nextSelectValue: undefined }
416
+ return { textareaValue: undefined, nextSelectValue: { expr: `${spVar}?.value`, multiple: selectIsMultiple || `${spVar}?.multiple` } }
417
+ }
418
+ parts.pushExpr(`${use('ssrSpread')}(${propsExpr}, ${JSON.stringify(tag)})`)
419
+ return { textareaValue: undefined, nextSelectValue: undefined }
420
+ }
421
+
391
422
  /** Emits an HTML/SVG element's SSR opening attributes, handling spreads, `<textarea value>`, and `<select value>`/`<option>`. */
392
423
  export function emitSsrElementAttrs(ctx: SsrElementAttrsContext): SsrElementAttrsResult {
393
424
  const { node, tag, parts, activeSelectValue, flushParts, pushStmt, nextId, use, compileSubExpression } = ctx
@@ -430,7 +461,7 @@ export function emitSsrElementAttrs(ctx: SsrElementAttrsContext): SsrElementAttr
430
461
  if (isBlockedAttr(name))
431
462
  continue
432
463
 
433
- if (isTextarea && name === 'value') {
464
+ if (!hasSpread && isTextarea && name === 'value') {
434
465
  if (attr.value?.type === 'Literal') {
435
466
  textareaValue = { staticText: String(attr.value.value) }
436
467
  }
@@ -444,14 +475,14 @@ export function emitSsrElementAttrs(ctx: SsrElementAttrsContext): SsrElementAttr
444
475
  continue
445
476
  }
446
477
 
447
- if (isSelect && name === 'value') {
478
+ if (!hasSpread && isSelect && name === 'value') {
448
479
  if (attr.value?.type === 'Literal') {
449
480
  nextSelectValue = { staticValue: String(attr.value.value), multiple: selectIsMultiple }
450
481
  }
451
482
  else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
452
483
  const lit = staticLiteralOrTemplate(attr.value.expression)
453
484
  if (lit.ok) {
454
- if (lit.value !== null)
485
+ if (lit.value !== null && typeof lit.value !== 'boolean')
455
486
  nextSelectValue = { staticValue: String(lit.value), multiple: selectIsMultiple }
456
487
  }
457
488
  else {
@@ -514,15 +545,8 @@ export function emitSsrElementAttrs(ctx: SsrElementAttrsContext): SsrElementAttr
514
545
  }
515
546
  }
516
547
 
517
- if (hasSpread) {
518
- if (spreadEntries.length === 1 && attrs.length === 1) {
519
- const spreadAttr = attrs[0] as Extract<typeof attrs[number], { type: 'JSXSpreadAttribute' }>
520
- parts.pushExpr(`${use('ssrSpread')}(${compileSubExpression(spreadAttr.argument)}, ${JSON.stringify(tag)})`)
521
- }
522
- else if (spreadEntries.length > 0) {
523
- parts.pushExpr(`${use('ssrSpread')}({ ${spreadEntries.join(', ')} }, ${JSON.stringify(tag)})`)
524
- }
525
- }
548
+ if (hasSpread)
549
+ ({ textareaValue, nextSelectValue } = emitSsrSpreadAttrs(ctx, attrs, spreadEntries, selectIsMultiple))
526
550
 
527
551
  if (isOption && activeSelectValue !== undefined && !optionHasExplicitSelected) {
528
552
  if (optionValue === undefined) {
@@ -224,6 +224,22 @@ function compileSsrExprAsString(
224
224
  return `${use('esc')}(${compileSubExpression(expr)})`
225
225
  }
226
226
 
227
+ function pushLeadNlStatic(parts: StringParts, text: string): void {
228
+ parts.pushStatic(text.startsWith('\n') || text.startsWith('\r') ? `\n${text}` : text)
229
+ }
230
+
231
+ function createIdCounter(code: string): () => number {
232
+ const used = new Set<number>()
233
+ for (const m of code.matchAll(/\b_[A-Za-z_]+(\d+)\b/g))
234
+ used.add(Number(m[1]))
235
+ let n = 0
236
+ return () => {
237
+ while (used.has(n))
238
+ n++
239
+ return n++
240
+ }
241
+ }
242
+
227
243
  export function compileSsr(filename: string, code: string, options: CompileSsrOptions = {}): CompileResult {
228
244
  const program = options.analysis?.program ?? parseTsx(filename, code)
229
245
  const analysis = options.analysis ?? analyzeModule(filename, code, program)
@@ -235,7 +251,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
235
251
  // Generated code keeps each expression on its source line: Bun maps a stack trace by the code this compiler hands it, not by a source map of its own.
236
252
  const mark = lineMarker(code)
237
253
  const used = new Set<string>()
238
- let loopCounter = 0
254
+ const nextId = createIdCounter(code)
239
255
  let activeSelectValue: SelectValueBinding | undefined
240
256
 
241
257
  const use = (name: string): string => {
@@ -258,7 +274,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
258
274
  const prunelleTags: PrunelleTagEmitter = { use, compileSubExpression, compileChildren: compileChildrenListToStringExpr, compileJsx: compileJsxToStringExpr, compileComponentRaw, markersAt, directAwaitNodes, jsxNodes }
259
275
 
260
276
  function compileChildrenListToStringExpr(children: readonly JSXChild[], slotMarkers = markersAt(children[0]?.start ?? 0), inFragment = false, rawTextTag?: 'style' | 'script'): string {
261
- const bufVar = `_o${loopCounter++}`
277
+ const bufVar = `_o${nextId()}`
262
278
  const stmts: string[] = []
263
279
  const parts = new StringParts()
264
280
  const flush = () => flushStringParts(bufVar, parts, stmts)
@@ -288,16 +304,16 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
288
304
  if (tag === 'form' && actionOverride === undefined) {
289
305
  const formAction = findDynamicFormAction(node)
290
306
  if (formAction !== undefined) {
291
- parts.pushExpr(emitActionFormExpr(formAction, directAwaitNodes.has(node), () => loopCounter++, use, compileSubExpression, (b, p, f, ps, ov) => emitIntoBuffer(node, b, p, f, ps, ov)))
307
+ parts.pushExpr(emitActionFormExpr(formAction, directAwaitNodes.has(node), nextId, use, compileSubExpression, (b, p, f, ps, ov) => emitIntoBuffer(node, b, p, f, ps, ov)))
292
308
  return
293
309
  }
294
310
  }
295
311
 
296
312
  parts.pushStatic(`<${tag}${devSrc(node, tag)}`)
297
313
  const isTextarea = tag === 'textarea'
298
- const isSelect = tag === 'select'
314
+ const needsLeadNl = isTextarea || tag === 'pre'
299
315
  const compileAttrExpr = actionOverride !== undefined ? (n: Node) => (n === actionOverride.node ? actionOverride.ident : compileSubExpression(n)) : compileSubExpression
300
- const { innerHtmlExpr, textareaValue, nextSelectValue } = emitSsrElementAttrs({ node, tag, parts, activeSelectValue, flushParts, pushStmt, nextId: () => loopCounter++, use, compileSubExpression: compileAttrExpr })
316
+ const { innerHtmlExpr, textareaValue, nextSelectValue } = emitSsrElementAttrs({ node, tag, parts, activeSelectValue, flushParts, pushStmt, nextId, use, compileSubExpression: compileAttrExpr })
301
317
  if (FORM_CONTROL_TAGS.has(tag))
302
318
  emitFormControlAttrs(node, tag as 'input' | 'select' | 'textarea', parts, use, compileSubExpression)
303
319
  parts.pushStatic('>')
@@ -305,18 +321,18 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
305
321
  return
306
322
 
307
323
  const prevSelectValue = activeSelectValue
308
- if (isSelect)
324
+ if (tag === 'select')
309
325
  activeSelectValue = nextSelectValue
310
326
 
311
327
  try {
312
328
  if (innerHtmlExpr !== undefined)
313
- parts.pushExpr(innerHtmlExpr)
329
+ parts.pushExpr(needsLeadNl ? `${use('ssrLeadNl')}(${innerHtmlExpr})` : innerHtmlExpr)
314
330
  else if (isTextarea && textareaValue !== undefined && filterMeaningfulChildren(node.children).length === 0)
315
- textareaValue.staticText !== undefined ? parts.pushStatic(escapeStaticText(textareaValue.staticText)) : textareaValue.expr !== undefined && parts.pushExpr(`${use('esc')}(${textareaValue.expr})`)
316
- else if (tag === 'style') {
317
- const styleExpr = compileChildrenListToStringExpr(node.children, false, false, 'style')
318
- if (styleExpr !== '""')
319
- parts.pushExpr(`${use('ssrStyleBlock')}(${styleExpr})`)
331
+ textareaValue.staticText !== undefined ? pushLeadNlStatic(parts, escapeStaticText(textareaValue.staticText)) : textareaValue.expr !== undefined && parts.pushExpr(`${use('ssrLeadNl')}(${use('esc')}(${textareaValue.expr}))`)
332
+ else if (tag === 'style' || needsLeadNl) {
333
+ const bodyExpr = tag === 'style' ? compileChildrenListToStringExpr(node.children, false, false, 'style') : compileChildrenListToStringExpr(node.children)
334
+ if (bodyExpr !== '""')
335
+ parts.pushExpr(`${use(tag === 'style' ? 'ssrStyleBlock' : 'ssrLeadNl')}(${bodyExpr})`)
320
336
  }
321
337
  else
322
338
  emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
@@ -382,7 +398,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
382
398
 
383
399
  if (match.isJsxBody && itemParam !== undefined && match.params.length <= 2 && (match.params.length < 2 || idxParam !== undefined)) {
384
400
  flushParts()
385
- const n = loopCounter++
401
+ const n = nextId()
386
402
  const arrVar = `_a${n}`
387
403
  const idxVar = idxParam ?? `_i${n}`
388
404
  const innerStmts: string[] = []
@@ -454,7 +470,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
454
470
 
455
471
  if (islandInfo !== undefined) {
456
472
  const target = onRaw !== undefined ? new StringParts() : parts
457
- emitIsland({ use, nextId: () => loopCounter++, markersAt }, { island: islandInfo, tag, call, start: node.start, propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate, hasChildren, childExpr, childrenHaveAwait }, target)
473
+ emitIsland({ use, nextId, markersAt }, { island: islandInfo, tag, call, start: node.start, propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate, hasChildren, childExpr, childrenHaveAwait }, target)
458
474
  if (onRaw !== undefined)
459
475
  onRaw(`${use('raw')}(${target.toExpr()})`)
460
476
  return
@@ -471,7 +487,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
471
487
 
472
488
  // Lazy memoized getter for non-async dynamic/component children so Providers & context components run before their children!
473
489
  if (childrenHaveDynamic && !childrenHaveAwait) {
474
- const cVar = `_c${loopCounter++}`
490
+ const cVar = `_c${nextId()}`
475
491
  const propsWithGetter = [...propEntries, `get children() { return ${cVar} === undefined ? (${cVar} = ${wrappedChild}) : ${cVar} }`].join(', ')
476
492
  emitOut(`${call}((() => { let ${cVar}; return { ${propsWithGetter} }; })())`)
477
493
  return
@@ -485,7 +501,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
485
501
  }
486
502
 
487
503
  function compileJsxToStringExpr(node: JSXElement | JSXFragment): string {
488
- const bufVar = `_o${loopCounter++}`
504
+ const bufVar = `_o${nextId()}`
489
505
  const stmts: string[] = []
490
506
  const parts = new StringParts()
491
507
 
package/src/context.ts CHANGED
@@ -37,6 +37,8 @@ export interface ConsentBannerProps extends ConsentTexts {
37
37
  children?: PrunelleChild
38
38
  /** The cookie or privacy policy page, linked under the text. */
39
39
  policyHref?: string | undefined
40
+ /** Label of the `policyHref` link (default: `'Cookie policy'`). */
41
+ policyLabel?: string | undefined
40
42
  /** Text of the disclosure holding the checkboxes (default: `'Choose'`). */
41
43
  choose?: string | undefined
42
44
  }
@@ -163,7 +163,7 @@ function safePathname(rawUrl: string): string {
163
163
  }
164
164
  }
165
165
 
166
- /** Builds an `errorSink` callback for `devServer` that records unhandled runtime errors into `.prunelle-dev/last-errors.json`. */
166
+ /** Builds an `errorSink` callback for `devServer` that records unhandled runtime errors into `.prunelle-dev/last-errors.jsonl`. */
167
167
  export function createDevRuntimeErrorSink(root: string): (info: ServerErrorInfo) => void {
168
168
  return (info) => {
169
169
  const message = info.error instanceof Error ? info.error.stack ?? info.error.message : String(info.error)
package/src/dom/attrs.ts CHANGED
@@ -64,7 +64,7 @@ export function setAttr(el: Element, name: string, value: unknown): void {
64
64
 
65
65
  export function setProp(el: Element, name: string, value: unknown): void {
66
66
  const next = name === 'value'
67
- ? (value == null ? '' : String(value))
67
+ ? (value == null || typeof value === 'boolean' ? '' : String(value))
68
68
  : Boolean(value)
69
69
  const rec = el as unknown as Record<string, unknown>
70
70
  if (rec[name] !== next)
@@ -425,7 +425,7 @@ type VoidElementTagName =
425
425
  | 'link' | 'meta' | 'param' | 'source' | 'track' | 'wbr'
426
426
 
427
427
  type HtmlIntrinsicElements = {
428
- [K in keyof HTMLElementTagNameMap]:
428
+ [K in Exclude<keyof HTMLElementTagNameMap, 'slot'>]:
429
429
  (K extends keyof HtmlElementOverrides
430
430
  ? Omit<HTMLAttributes<HTMLElementTagNameMap[K]>, keyof HtmlElementOverrides[K] | (K extends VoidElementTagName ? 'children' : never)> & HtmlElementOverrides[K]
431
431
  : Omit<HTMLAttributes<HTMLElementTagNameMap[K]>, K extends VoidElementTagName ? 'children' : never>)
@@ -301,9 +301,17 @@ class EffectNode implements SubNode, Owner {
301
301
  if (this.f & F.DISPOSED)
302
302
  return
303
303
  this.f &= ~(F.DIRTY | F.CHECK)
304
- releaseOwned(this)
305
- if (this.f & F.DISPOSED)
304
+ let errors: unknown[] | undefined
305
+ try {
306
+ releaseOwned(this)
307
+ }
308
+ catch (err) {
309
+ errors = [err]
310
+ }
311
+ if (this.f & F.DISPOSED) {
312
+ throwErrors(errors)
306
313
  return
314
+ }
307
315
  const prevSub = currentSub
308
316
  const prevOwner = currentOwner
309
317
  this.f |= F.RUNNING
@@ -320,12 +328,16 @@ class EffectNode implements SubNode, Owner {
320
328
  ;(this.cl ??= []).unshift(ret)
321
329
  }
322
330
  }
331
+ catch (err) {
332
+ ;(errors ??= []).push(err)
333
+ }
323
334
  finally {
324
335
  unlinkRemaining(this)
325
336
  this.f &= ~F.RUNNING
326
337
  currentSub = prevSub
327
338
  currentOwner = prevOwner
328
339
  }
340
+ throwErrors(errors)
329
341
  }
330
342
  }
331
343
 
@@ -34,16 +34,34 @@ export interface PrerenderedSources {
34
34
  isFast: (urlPath: string, route: RouteManifestEntry) => boolean
35
35
  }
36
36
 
37
- const EXTRA_PRERENDER_MIME: Record<string, string> = {
37
+ /** Shared MIME table for `public/`, hashed assets, prerendered files and `prunelle start --static`. */
38
+ export const STATIC_MIME: Readonly<Record<string, string>> = {
39
+ ...MIME,
38
40
  '.htm': 'text/html; charset=utf-8',
39
41
  '.rss': 'application/rss+xml; charset=utf-8',
40
42
  '.atom': 'application/atom+xml; charset=utf-8',
41
43
  '.ics': 'text/calendar; charset=utf-8',
42
44
  '.csv': 'text/csv; charset=utf-8',
45
+ '.vtt': 'text/vtt; charset=utf-8',
46
+ '.geojson': 'application/geo+json; charset=utf-8',
47
+ '.mp3': 'audio/mpeg',
48
+ '.ogg': 'audio/ogg',
49
+ '.oga': 'audio/ogg',
50
+ '.ogv': 'video/ogg',
51
+ '.m4a': 'audio/mp4',
52
+ '.wav': 'audio/wav',
53
+ '.flac': 'audio/flac',
54
+ '.opus': 'audio/opus',
55
+ '.zip': 'application/zip',
56
+ }
57
+
58
+ /** MIME type for a file extension, falling back to `application/octet-stream`. */
59
+ export function staticMime(ext: string): string {
60
+ return STATIC_MIME[ext.toLowerCase()] ?? 'application/octet-stream'
43
61
  }
44
62
 
45
63
  function prerenderedMime(ext: string, filePath: string | undefined): string {
46
- const mapped = MIME[ext] ?? EXTRA_PRERENDER_MIME[ext]
64
+ const mapped = STATIC_MIME[ext.toLowerCase()]
47
65
  if (mapped !== undefined)
48
66
  return mapped
49
67
  if (filePath !== undefined) {
@@ -74,7 +92,7 @@ export function createAssets(options: AssetsOptions) {
74
92
 
75
93
  const registerPublic = (rel: string, body: EmbeddedBody, etag?: string, sidecars: ReturnType<typeof sidecarsOf> = { br: undefined, gz: undefined }): void => {
76
94
  const cleanRel = rel.replace(/^\/+/, '')
77
- const type = MIME[extname(cleanRel).toLowerCase()] ?? 'application/octet-stream'
95
+ const type = staticMime(extname(cleanRel))
78
96
  publicMap.set(`/${cleanRel}`, servedFile({
79
97
  key: `p:/${cleanRel}`,
80
98
  source: embedded(body),
@@ -105,7 +123,7 @@ export function createAssets(options: AssetsOptions) {
105
123
  for (const [rel, body] of Object.entries(assets)) {
106
124
  if ((rel.endsWith('.br') || rel.endsWith('.gz')) && rel.slice(0, -3) in assets)
107
125
  continue
108
- const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
126
+ const type = staticMime(extname(rel))
109
127
  const sidecar = (ext: 'br' | 'gz'): FileSource | undefined => {
110
128
  const source = assets[`${rel}.${ext}`] ?? (typeof body === 'string' && existsSync(`${body}.${ext}`) ? `${body}.${ext}` : undefined)
111
129
  return source === undefined ? undefined : embedded(source)
@@ -75,6 +75,8 @@ export function normalizeConsentConfig(config: ConsentConfig | undefined): Norma
75
75
  continue
76
76
  if (name.includes(',') || name.includes(':'))
77
77
  throw new Error(`prunelle: consent category "${name}" cannot contain "," or ":"`)
78
+ if (name === 'action' || name === 'redirect' || name === 'categories')
79
+ throw new Error(`prunelle: consent category "${name}" is reserved by the consent form; choose another category name.`)
78
80
  categorySet.add(name)
79
81
  categories.push(name)
80
82
  labels[name] = given[item]?.trim() || name
@@ -116,7 +118,10 @@ export function parseConsentCookie(raw: string | undefined, declared: ReadonlySe
116
118
  return version === '' ? { decided: true, decidedAt: undefined, granted: grantedOf(raw.slice(LEGACY_COOKIE_PREFIX.length), declared) } : none
117
119
  if (!raw.startsWith(COOKIE_PREFIX))
118
120
  return none
119
- const [seconds, storedVersion, list] = raw.slice(COOKIE_PREFIX.length).split(':')
121
+ const parts = raw.slice(COOKIE_PREFIX.length).split(':')
122
+ if (parts.length !== 3)
123
+ return none
124
+ const [seconds, storedVersion, list] = parts
120
125
  const at = Number(seconds)
121
126
  if (list === undefined || storedVersion !== version || !Number.isSafeInteger(at) || at <= 0)
122
127
  return none
@@ -243,7 +248,7 @@ async function parseConsentSubmission(
243
248
 
244
249
  const listed = new Set(form.getAll('categories').filter((v): v is string => typeof v === 'string'))
245
250
  for (const cat of config.categories) {
246
- if (listed.has(cat) || isTruthyFormValue(form.get(cat)))
251
+ if (listed.has(cat) || (cat !== 'action' && cat !== 'redirect' && cat !== 'categories' && isTruthyFormValue(form.get(cat))))
247
252
  granted.add(cat)
248
253
  }
249
254
  return { ok: true, granted, redirect }
@@ -73,7 +73,14 @@ function serializeCookie(name: string, value: string, options: CookieOptions = {
73
73
  if (sameSite === 'none' && !secure)
74
74
  throw new Error(`prunelle: Cookie "${name}" with sameSite: "none" requires secure: true`)
75
75
 
76
- let out = `${name}=${encodeURIComponent(value)}`
76
+ let encoded: string
77
+ try {
78
+ encoded = encodeURIComponent(value)
79
+ }
80
+ catch {
81
+ throw new TypeError(`prunelle: invalid cookie value for "${name}": contains an unpaired UTF-16 surrogate; sanitize with value.toWellFormed() before setting the cookie.`)
82
+ }
83
+ let out = `${name}=${encoded}`
77
84
  out += `; Path=${path}`
78
85
  if (options.domain !== undefined)
79
86
  out += `; Domain=${options.domain}`