prunelle 0.7.3 → 0.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/llms.txt +19 -17
  2. package/package.json +1 -1
  3. package/src/a11y/index.ts +9 -2
  4. package/src/build/index.ts +30 -31
  5. package/src/build/output.ts +1 -1
  6. package/src/build/prerender.ts +29 -13
  7. package/src/build/routes.ts +19 -1
  8. package/src/build/static.ts +24 -2
  9. package/src/cli/check-forms.ts +16 -6
  10. package/src/cli/check-links.ts +12 -9
  11. package/src/cli/check-security.ts +87 -12
  12. package/src/cli/check.ts +1 -1
  13. package/src/cli/commands.ts +3 -3
  14. package/src/cli/upgrade.ts +36 -3
  15. package/src/compiler/compliance.ts +2 -0
  16. package/src/compiler/dom.ts +41 -15
  17. package/src/compiler/ssr-helpers.ts +45 -21
  18. package/src/compiler/ssr.ts +32 -16
  19. package/src/context.ts +2 -0
  20. package/src/dev/error-log.ts +1 -1
  21. package/src/dev/index.ts +1 -1
  22. package/src/dev/supervisor.ts +2 -2
  23. package/src/dom/attrs.ts +1 -1
  24. package/src/dom/island.ts +30 -4
  25. package/src/jsx-runtime.ts +1 -1
  26. package/src/plugins/context.ts +18 -1
  27. package/src/plugins/services.ts +1 -0
  28. package/src/reactivity/index.ts +14 -2
  29. package/src/server/action.ts +26 -18
  30. package/src/server/assets.ts +22 -4
  31. package/src/server/consent.ts +7 -2
  32. package/src/server/cookies.ts +8 -1
  33. package/src/server/errors.ts +57 -26
  34. package/src/server/http.ts +1 -1
  35. package/src/server/index.ts +18 -16
  36. package/src/server/page.ts +4 -0
  37. package/src/server/rate-limit.ts +36 -12
  38. package/src/server/route-cache.ts +9 -10
  39. package/src/server/route-table.ts +38 -13
  40. package/src/server/router.ts +4 -4
  41. package/src/server/sanitize-html.ts +21 -7
  42. package/src/server/security.ts +13 -3
  43. package/src/server/serve-handlers.ts +3 -3
  44. package/src/server/start.ts +2 -2
  45. package/src/server/static-dir.ts +3 -10
  46. package/src/server/stream.ts +4 -4
  47. package/src/ssr/consent-banner.ts +3 -1
  48. package/src/ssr/context.ts +85 -2
  49. package/src/ssr/index.ts +16 -4
  50. package/src/ssr/navigation.ts +1 -1
  51. package/src/style.ts +9 -7
  52. package/src/unrenderable.ts +15 -5
@@ -1,9 +1,14 @@
1
1
  // `prunelle check` warnings about what weakens an app's defences: dotfiles under public/, and the security opt-outs in its config.
2
2
 
3
+ import type { Node } from 'oxc-parser'
4
+ import type { ComplianceConfig } from '../compiler/compliance'
3
5
  import type { SecurityHeadersOptions } from '../server/security'
4
6
  import { relative } from 'node:path'
7
+ import { parseSync } from 'oxc-parser'
5
8
  import { isHiddenPublicPath, walkAllFiles } from '../build/files'
6
- import { formatDiagnostic } from '../compiler/shared'
9
+ import { walk } from '../compiler/ast'
10
+ import { isIgnoredAt, isRuleIgnored, parsePrunelleIgnores } from '../compiler/compliance'
11
+ import { formatDiagnostic, unwrapTsExpr } from '../compiler/shared'
7
12
  import { resolveCspPolicy } from '../server/security'
8
13
 
9
14
  /** One warning per dotfile in `public/` (other than `.well-known`): the build leaves it out, so it is either dead weight or a secret about to be committed. */
@@ -15,18 +20,82 @@ export function publicDotfileWarnings(publicDir: string, root: string): string[]
15
20
  .map(file => formatDiagnostic(`${relative(root, file.abs)}:1:1`, `[security/public-dotfile] "${file.rel}" is in public/ but the build does not copy dotfiles, so it is never served: delete it, or move it out of public/ (only .well-known/ is kept).`, 'warning'))
16
21
  }
17
22
 
18
- // `.redirect("https://…"` or `.redirect("//…"`: a literal address on another site, up to the closing parenthesis of the call.
19
- const EXTERNAL_REDIRECT_RE = /\.redirect\(\s*(['"`])(?:https?:)?\/\/[^)]*\)/g
23
+ const EXTERNAL_URL_PREFIX_RE = /^(?:https?:)?\/\//i
24
+
25
+ function isResponseObject(node: Node): boolean {
26
+ const expr = unwrapTsExpr(node)
27
+ if (expr.type === 'Identifier')
28
+ return expr.name === 'Response'
29
+ return expr.type === 'MemberExpression'
30
+ && !expr.computed
31
+ && expr.object.type === 'Identifier'
32
+ && expr.object.name === 'globalThis'
33
+ && expr.property.type === 'Identifier'
34
+ && expr.property.name === 'Response'
35
+ }
36
+
37
+ function leadingStringLiteral(node: Node): string | undefined {
38
+ const expr = unwrapTsExpr(node)
39
+ if (expr.type === 'Literal' && typeof expr.value === 'string')
40
+ return expr.value
41
+ if (expr.type === 'TemplateLiteral')
42
+ return expr.quasis[0]?.value.cooked ?? expr.quasis[0]?.value.raw ?? ''
43
+ return undefined
44
+ }
45
+
46
+ function allowsExternalRedirect(arg: Node | undefined): boolean {
47
+ if (arg === undefined || arg.type === 'SpreadElement')
48
+ return false
49
+ const expr = unwrapTsExpr(arg)
50
+ if (expr.type !== 'ObjectExpression')
51
+ return true
52
+ let external: boolean | undefined
53
+ for (const prop of expr.properties) {
54
+ if (prop.type === 'SpreadElement') {
55
+ external = true
56
+ continue
57
+ }
58
+ const key = !prop.computed && prop.key.type === 'Identifier'
59
+ ? prop.key.name
60
+ : prop.key.type === 'Literal' && typeof prop.key.value === 'string'
61
+ ? prop.key.value
62
+ : undefined
63
+ if (key !== 'external')
64
+ continue
65
+ const val = unwrapTsExpr(prop.value)
66
+ const definitelyNotTrue = (val.type === 'Literal' && val.value !== true)
67
+ || (val.type === 'Identifier' && val.name === 'undefined')
68
+ external = !definitelyNotTrue
69
+ }
70
+ return external === true
71
+ }
20
72
 
21
73
  /** One warning per `ctx.redirect("https://other.site/…")` that lacks `{ external: true }`: since 0.x it throws at runtime. */
22
74
  export function externalRedirectWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string): string[] {
23
75
  const warnings: string[] = []
24
76
  for (const file of files) {
25
77
  const code = read(file)
26
- for (const match of code.matchAll(EXTERNAL_REDIRECT_RE)) {
27
- if (!match[0].includes('external'))
28
- warnings.push(formatDiagnostic(locate(file, match.index), '[security/external-redirect] ctx.redirect() to another site throws unless the app passes { external: true } as its third argument: add `{ external: true }` if the address is the app\'s own, and never pass one read from the request.', 'warning'))
29
- }
78
+ if (!code.includes('.redirect('))
79
+ continue
80
+ const lang = file.endsWith('.tsx') || file.endsWith('.jsx') ? 'tsx' : 'ts'
81
+ const parsed = parseSync(file, code, { lang, sourceType: 'module' })
82
+ walk(parsed.program, (node) => {
83
+ if (node.type !== 'CallExpression')
84
+ return
85
+ const callee = unwrapTsExpr(node.callee)
86
+ if (callee.type !== 'MemberExpression' || callee.computed || callee.property.type !== 'Identifier' || callee.property.name !== 'redirect')
87
+ return
88
+ if (isResponseObject(callee.object))
89
+ return
90
+ const first = node.arguments[0]
91
+ if (first === undefined || first.type === 'SpreadElement')
92
+ return
93
+ const prefix = leadingStringLiteral(first)
94
+ if (prefix === undefined || !EXTERNAL_URL_PREFIX_RE.test(prefix))
95
+ return
96
+ if (!allowsExternalRedirect(node.arguments[2]))
97
+ warnings.push(formatDiagnostic(locate(file, callee.object.end), '[security/external-redirect] ctx.redirect() to another site throws unless the app passes { external: true } as its third argument: add `{ external: true }` if the address is the app\'s own, and never pass one read from the request.', 'warning'))
98
+ })
30
99
  }
31
100
  return warnings
32
101
  }
@@ -44,7 +113,7 @@ export function securityConfigWarnings(security: SecurityHeadersOptions | false
44
113
  const csp = resolveCspPolicy(security)
45
114
  const loose = (csp ?? '').split(';')
46
115
  .map(part => part.trim().split(/\s+/))
47
- .filter(([name, ...tokens]) => INLINE_CODE_DIRECTIVES.has(name!.toLowerCase()) && tokens.includes('\'unsafe-inline\''))
116
+ .filter(([name, ...tokens]) => INLINE_CODE_DIRECTIVES.has(name!.toLowerCase()) && tokens.some(token => token.toLowerCase() === '\'unsafe-inline\''))
48
117
  .map(([name]) => name!.toLowerCase())
49
118
  return loose.length === 0
50
119
  ? []
@@ -53,12 +122,18 @@ export function securityConfigWarnings(security: SecurityHeadersOptions | false
53
122
 
54
123
  const CSRF_OFF_RE = /export\s+const\s+csrf\s*=\s*false\b/g
55
124
 
56
- /** One warning per route file that exports `csrf = false`: it accepts a cross-site POST, so it must check a signature or a token itself. */
57
- export function csrfOffWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string): string[] {
125
+ /** One warning per route file that exports `csrf = false`: it accepts a cross-site POST, so it must check a signature or a token itself. A route that does says so with `// prunelle-ignore security/csrf-off` above the export. */
126
+ export function csrfOffWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string, compliance?: ComplianceConfig | undefined): string[] {
127
+ if (isRuleIgnored('security/csrf-off', compliance))
128
+ return []
58
129
  const warnings: string[] = []
59
130
  for (const file of files) {
60
- for (const match of read(file).matchAll(CSRF_OFF_RE))
61
- warnings.push(formatDiagnostic(locate(file, match.index), '[security/csrf-off] this route skips the cross-site request check, so any site can post to it: keep it only for a webhook or bearer-token API that verifies a signature or token itself, and drop `export const csrf = false` for anything a browser form posts to.', 'warning'))
131
+ const code = read(file)
132
+ const ignores = parsePrunelleIgnores(code)
133
+ for (const match of code.matchAll(CSRF_OFF_RE)) {
134
+ if (!isIgnoredAt(ignores, 'security/csrf-off', match.index))
135
+ warnings.push(formatDiagnostic(locate(file, match.index), '[security/csrf-off] this route skips the cross-site request check, so any site can post to it: keep it only for a webhook or bearer-token API that verifies a signature or token itself, and say so with `// prunelle-ignore security/csrf-off` above the export; drop `export const csrf = false` for anything a browser form posts to.', 'warning'))
136
+ }
62
137
  }
63
138
  return warnings
64
139
  }
package/src/cli/check.ts CHANGED
@@ -394,7 +394,7 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
394
394
 
395
395
  warnings.push(...publicDotfileWarnings(publicDir, root))
396
396
  warnings.push(...securityConfigWarnings(loadedConfig.security))
397
- warnings.push(...csrfOffWarnings(routeFiles, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset)))
397
+ warnings.push(...csrfOffWarnings(routeFiles, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset), compliance))
398
398
  warnings.push(...externalRedirectWarnings(files, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset)))
399
399
 
400
400
  // 3e. Broken internal link checks (#3)
@@ -130,16 +130,16 @@ function upgradeCommand(cwd: string): Commands[string] {
130
130
  console.log(`prunelle upgrade rewrote ${res.changed.length} file${res.changed.length === 1 ? '' : 's'}`)
131
131
  // The dependencies moved: the first run for this app, which renames its cookies; a later run only fixes what an older prunelle left.
132
132
  const moved = res.changed.some(file => file === 'package.json' || file.endsWith('/package.json'))
133
+ let installFailed = false
133
134
  if (moved && values['no-install'] !== true) {
134
135
  const install = Bun.spawnSync(['bun', 'install'], { cwd: root, stdout: 'inherit', stderr: 'inherit' })
135
- if (install.exitCode !== 0)
136
- return 1
136
+ installFailed = install.exitCode !== 0
137
137
  }
138
138
  if (moved)
139
139
  console.log('Signed-in users sign in again and visitors answer the cookie banner again: prunelle names its cookies pru_session and pru_consent.')
140
140
  for (const line of res.manual)
141
141
  console.error(line)
142
- if (res.manual.length > 0)
142
+ if (installFailed || res.manual.length > 0)
143
143
  return 1
144
144
  console.log('Next: prunelle check')
145
145
  return 0
@@ -56,9 +56,18 @@ const PRUNELLE_SOURCE_RE = /^prunelle(\/.*)?$/
56
56
  const NPM_KAY_ALIAS_RE = /^npm:(@kayjs\/[\w-]+)(?:@.*)?$/
57
57
  const ESCAPE_RE = /[.*+?^${}()|[\]\\]/g
58
58
  const GITIGNORE_CACHE_RE = /(?:^|\/)\.prunelle-cache(?:\/|$|\s)/m
59
+ const PARSE_LOC_RE = /:(\d+):\d+:\s*error:\s*(?:prunelle compiler:\s*)?([^\n]+)/
59
60
 
60
61
  const apply = (text: string, rules: readonly [RegExp, string][]): string => rules.reduce((out, [re, to]) => out.replace(re, to), text)
61
62
 
63
+ function formatParseManual(file: string, err: unknown, action: string): string {
64
+ const msg = err instanceof Error ? err.message : String(err)
65
+ const match = PARSE_LOC_RE.exec(msg)
66
+ const line = match?.[1] ?? '1'
67
+ const reason = match?.[2]?.trim() ?? msg.split('\n', 1)[0]!.trim()
68
+ return `${file}:${line}: ${reason} — ${action}.`
69
+ }
70
+
62
71
  /** Why `root` is no app to upgrade: neither on kay nor prunelle, nor a workspace holding one; undefined when it is one. */
63
72
  export function notAnApp(root: string): string | undefined {
64
73
  if (hasKayOrPrunelle(root) || existsSync(join(root, 'kay.config.ts')) || existsSync(join(root, 'prunelle.config.ts')) || workspaceMembers(root).some(m => hasKayOrPrunelle(join(root, m))))
@@ -112,7 +121,16 @@ function upgradeDir(root: string, inheritedAliases?: ReadonlyMap<string, string>
112
121
  const publicDir = configuredPublicDir(root)
113
122
  for (const file of sourceFiles(root, publicDir)) {
114
123
  const text = readFileSync(join(root, file), 'utf8')
115
- const renamed = SOURCE_FILE_RE.test(file) ? renameKayNames(file, text, aliases) : text
124
+ let renamed = text
125
+ if (SOURCE_FILE_RE.test(file)) {
126
+ try {
127
+ renamed = renameKayNames(file, text, aliases)
128
+ }
129
+ catch (err) {
130
+ manual.push(formatParseManual(file, err, 'fix the syntax error and re-run prunelle upgrade'))
131
+ continue
132
+ }
133
+ }
116
134
  const next = apply(apply(renamed, PATH_RULES), WIRE_RULES)
117
135
  write(file, text, next)
118
136
  if (SOURCE_FILE_RE.test(file) && next !== text)
@@ -197,7 +215,14 @@ function configuredPublicDir(root: string): string {
197
215
  : existsSync(join(root, 'kay.config.ts')) ? 'kay.config.ts' : undefined
198
216
  if (file === undefined)
199
217
  return resolve(root, 'public')
200
- const program = parseTsx(file, readFileSync(join(root, file), 'utf8'))
218
+ let program: ReturnType<typeof parseTsx>
219
+ try {
220
+ program = parseTsx(file, readFileSync(join(root, file), 'utf8'))
221
+ }
222
+ catch (err) {
223
+ void err
224
+ return resolve(root, 'public')
225
+ }
201
226
  let value: string | undefined
202
227
  walk(program.body, (node) => {
203
228
  if (value !== undefined)
@@ -349,7 +374,15 @@ function exportsOf(file: string): Set<string> {
349
374
 
350
375
  // A name kay exported that prunelle no longer does is reported on the line importing it.
351
376
  function checkImports(file: string, code: string, manual: string[]): void {
352
- for (const stmt of parseTsx(file, code).body) {
377
+ let body: ReturnType<typeof parseTsx>['body']
378
+ try {
379
+ body = parseTsx(file, code).body
380
+ }
381
+ catch (err) {
382
+ manual.push(formatParseManual(file, err, 'fix the syntax error and check its prunelle imports'))
383
+ return
384
+ }
385
+ for (const stmt of body) {
353
386
  if (stmt.type !== 'ImportDeclaration' || !PRUNELLE_SOURCE_RE.test(stmt.source.value))
354
387
  continue
355
388
  const line = code.slice(0, stmt.start).split('\n').length
@@ -41,6 +41,7 @@ export type ComplianceRule =
41
41
  | 'lcen/legal-notice'
42
42
  | 'rgaa/document-lang'
43
43
  | 'rgaa/accessibility-statement'
44
+ | 'security/csrf-off'
44
45
  | FormWarningRule
45
46
 
46
47
  /** The warnings of the form-vs-action check (`cli/check-forms.ts`), silenced like the compliance rules. */
@@ -69,6 +70,7 @@ const COMPLIANCE_RULES = new Set<ComplianceRule>([
69
70
  'lcen/legal-notice',
70
71
  'rgaa/document-lang',
71
72
  'rgaa/accessibility-statement',
73
+ 'security/csrf-off',
72
74
  'action/unguarded-public-form',
73
75
  'form/invalid-option',
74
76
  'form/schema-unsupported',
@@ -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/dev/index.ts CHANGED
@@ -98,7 +98,7 @@ async function handleAppFetch(
98
98
  if (state.lastError !== undefined)
99
99
  return buildErrorResponse(request, state.lastError, state.reloadAssets.script)
100
100
 
101
- const res = await state.app!.handle(request, remoteIp)
101
+ const res = await state.app!.handle(request, remoteIp, seconds => srv.timeout(request, seconds))
102
102
  const ct = res.headers.get('content-type') ?? ''
103
103
  const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
104
104
  if (ct.includes('text/event-stream') || isStreamedHtml)