prunelle 0.1.1 → 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.
Files changed (177) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +636 -0
  36. package/src/cli/check-imports.ts +31 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +101 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -10,13 +10,13 @@ import type {
10
10
  import type { ModuleAnalysis } from './analyze'
11
11
  import type { SelectValueBinding } from './ssr-helpers'
12
12
  import type { PrunelleTagEmitter } from './ssr-prunelle-tags'
13
- import { analyzeModule, parseTsx } from './analyze'
13
+ import { analyzeModule, getExprContext, parseTsx } from './analyze'
14
14
  import { walk } from './ast'
15
- import { mistake } from './mistakes'
15
+ import { createDevSourceAttr } from './dev-source'
16
+ import { hydrateMistake } from './mistakes'
16
17
  import { alignLines, lineMarker, SourceEditor } from './patch'
17
18
  import {
18
19
  containsJsx,
19
- createExprContext,
20
20
  decodeHtmlEntities,
21
21
  escapeRawText,
22
22
  escapeStaticText,
@@ -24,6 +24,7 @@ import {
24
24
  isComponentTag,
25
25
  isJsxNode,
26
26
  jsxTagName,
27
+ matchJsxMapCall,
27
28
  planChildSlots,
28
29
  RAW_TEXT_ELEMENTS,
29
30
  resolvePrunelleTag,
@@ -34,11 +35,86 @@ import {
34
35
  emitSsrElementAttrs,
35
36
  precomputeSsrSubtreeFlags,
36
37
  serializeComponentProps,
38
+ staticLiteralOrTemplate,
37
39
  StringParts,
38
40
  } from './ssr-helpers'
39
41
  import { emitIsland } from './ssr-island'
40
42
  import { emitCatch, emitSuspense } from './ssr-prunelle-tags'
41
43
 
44
+ const FORM_CONTROL_TAGS = new Set(['input', 'select', 'textarea'])
45
+ const FORM_ATTR_BITS: Record<string, number> = {
46
+ type: 1,
47
+ required: 2,
48
+ minlength: 4,
49
+ maxlength: 8,
50
+ min: 16,
51
+ max: 32,
52
+ step: 64,
53
+ pattern: 128,
54
+ }
55
+
56
+ function findDynamicFormAction(node: JSXElement): Node | undefined {
57
+ for (const attr of node.openingElement.attributes) {
58
+ if (attr.type !== 'JSXAttribute' || jsxTagName(attr.name) !== 'action')
59
+ continue
60
+ if (attr.value?.type !== 'JSXExpressionContainer' || attr.value.expression.type === 'JSXEmptyExpression')
61
+ return undefined
62
+ const expr = attr.value.expression
63
+ if (staticLiteralOrTemplate(expr).ok)
64
+ return undefined
65
+ if (expr.type === 'ConditionalExpression' && staticLiteralOrTemplate(expr.consequent).ok && staticLiteralOrTemplate(expr.alternate).ok)
66
+ return undefined
67
+ return expr
68
+ }
69
+ return undefined
70
+ }
71
+
72
+ function emitFormControlAttrs(
73
+ node: JSXElement,
74
+ tag: 'input' | 'select' | 'textarea',
75
+ parts: StringParts,
76
+ use: (name: string) => string,
77
+ compileSubExpression: (node: Node) => string,
78
+ ): void {
79
+ const attrs = node.openingElement.attributes
80
+ if (attrs.some(a => a.type === 'JSXSpreadAttribute'))
81
+ return
82
+ let nameExpr: string | undefined
83
+ let typeExpr: string | undefined
84
+ let present = 0
85
+ for (const attr of attrs) {
86
+ if (attr.type !== 'JSXAttribute')
87
+ continue
88
+ const attrName = jsxTagName(attr.name).toLowerCase()
89
+ const bit = FORM_ATTR_BITS[attrName]
90
+ if (bit !== undefined)
91
+ present |= bit
92
+ if (attrName === 'name') {
93
+ if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
94
+ nameExpr = JSON.stringify(attr.value.value)
95
+ }
96
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
97
+ const lit = staticLiteralOrTemplate(attr.value.expression)
98
+ nameExpr = lit.ok && typeof lit.value === 'string' ? JSON.stringify(lit.value) : compileSubExpression(attr.value.expression)
99
+ }
100
+ }
101
+ else if (tag === 'input' && attrName === 'type') {
102
+ if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
103
+ typeExpr = JSON.stringify(attr.value.value.toLowerCase())
104
+ }
105
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
106
+ const lit = staticLiteralOrTemplate(attr.value.expression)
107
+ if (lit.ok && typeof lit.value === 'string')
108
+ typeExpr = JSON.stringify(lit.value.toLowerCase())
109
+ }
110
+ }
111
+ }
112
+ if (nameExpr === undefined)
113
+ return
114
+ const typeArg = typeExpr !== undefined ? `, ${typeExpr}` : ''
115
+ parts.pushExpr(`${use('ssrFormAttrs')}(${JSON.stringify(tag)}, ${nameExpr}, ${present}${typeArg})`)
116
+ }
117
+
42
118
  export interface IslandBinding {
43
119
  id: string
44
120
  chunk: string
@@ -51,6 +127,8 @@ export interface CompileSsrOptions {
51
127
  /** Hydration markers everywhere, nowhere, or only inside these source spans. */
52
128
  emitMarkers?: boolean | readonly (readonly [number, number])[] | undefined
53
129
  analysis?: ModuleAnalysis | undefined
130
+ /** Project root for dev-only `data-pru-src="file:line:col"` attributes; omit in production. */
131
+ devSourceRoot?: string | undefined
54
132
  }
55
133
 
56
134
  export interface CompileResult {
@@ -58,10 +136,94 @@ export interface CompileResult {
58
136
  analysis: ModuleAnalysis
59
137
  }
60
138
 
139
+ function emitActionFormExpr(
140
+ formAction: Node,
141
+ isAsyncForm: boolean,
142
+ nextId: () => number,
143
+ use: (name: string) => string,
144
+ compileSubExpression: (node: Node) => string,
145
+ emitBody: (bufVar: string, parts: StringParts, flush: () => void, pushStmt: (stmt: string) => void, override: { node: Node, ident: string }) => void,
146
+ ): string {
147
+ const faVar = `_fa${nextId()}`
148
+ const innerBuf = `_o${nextId()}`
149
+ const innerStmts: string[] = []
150
+ const innerParts = new StringParts()
151
+ const flushInner = () => {
152
+ if (!innerParts.isEmpty()) {
153
+ innerStmts.push(`${innerBuf} += ${innerParts.toExpr()};`)
154
+ innerParts.clear()
155
+ }
156
+ }
157
+ emitBody(innerBuf, innerParts, flushInner, s => innerStmts.push(s), { node: formAction, ident: faVar })
158
+ if (innerStmts.length > 0)
159
+ flushInner()
160
+ const body = innerStmts.length === 0 ? innerParts.toExpr() : `{ let ${innerBuf} = ""; ${innerStmts.join(' ')} return ${innerBuf}; }`
161
+ return isAsyncForm
162
+ ? `await ${use('ssrFormAsync')}(${compileSubExpression(formAction)}, async (${faVar}) => ${body})`
163
+ : `${use('ssrForm')}(${compileSubExpression(formAction)}, (${faVar}) => ${body})`
164
+ }
165
+
61
166
  function markerTest(markers: NonNullable<CompileSsrOptions['emitMarkers']>): (offset: number) => boolean {
62
167
  return typeof markers === 'boolean' ? () => markers : offset => markers.some(([start, end]) => offset >= start && offset < end)
63
168
  }
64
169
 
170
+ function flushStringParts(bufVar: string, parts: StringParts, stmts: string[]): void {
171
+ if (!parts.isEmpty()) {
172
+ stmts.push(`${bufVar} += ${parts.toExpr()};`)
173
+ parts.clear()
174
+ }
175
+ }
176
+
177
+ function isSingleLoopChild(meaningful: readonly JSXChild[], jsxNodes: WeakSet<Node>): boolean {
178
+ return meaningful.length === 1
179
+ && meaningful[0]!.type === 'JSXExpressionContainer'
180
+ && meaningful[0]!.expression.type !== 'JSXEmptyExpression'
181
+ && matchJsxMapCall(meaningful[0]!.expression, jsxNodes) !== undefined
182
+ }
183
+
184
+ function compileSsrSubExpression(
185
+ code: string,
186
+ node: Node,
187
+ jsxNodes: WeakSet<Node>,
188
+ mark: (offset: number) => string,
189
+ compileRootJsx: (n: JSXElement | JSXFragment) => string,
190
+ ): string {
191
+ if (!containsJsx(node, jsxNodes))
192
+ return mark(node.start) + code.slice(node.start, node.end)
193
+ const sub = new SourceEditor(code.slice(node.start, node.end))
194
+ const offset = node.start
195
+ walk(node, (child) => {
196
+ if (isJsxNode(child)) {
197
+ sub.replace(child.start - offset, child.end - offset, compileRootJsx(child) + mark(child.end))
198
+ return false
199
+ }
200
+ return undefined
201
+ })
202
+ return mark(node.start) + sub.toString()
203
+ }
204
+
205
+ function compileSsrExprAsString(
206
+ expr: Node,
207
+ use: (name: string) => string,
208
+ compileSubExpression: (node: Node) => string,
209
+ compileJsxToStringExpr: (node: JSXElement | JSXFragment) => string,
210
+ ): string {
211
+ if (isJsxNode(expr))
212
+ return compileJsxToStringExpr(expr)
213
+ if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
214
+ const right = unwrapParens(expr.right)
215
+ if (isJsxNode(right))
216
+ return `((${compileSubExpression(expr.left)}) ? (${compileJsxToStringExpr(right)}) : "")`
217
+ }
218
+ if (expr.type === 'ConditionalExpression') {
219
+ const consNode = unwrapParens(expr.consequent)
220
+ const altNode = unwrapParens(expr.alternate)
221
+ if (isJsxNode(consNode) || isJsxNode(altNode))
222
+ return `((${compileSubExpression(expr.test)}) ? (${compileSsrExprAsString(consNode, use, compileSubExpression, compileJsxToStringExpr)}) : (${compileSsrExprAsString(altNode, use, compileSubExpression, compileJsxToStringExpr)}))`
223
+ }
224
+ return `${use('esc')}(${compileSubExpression(expr)})`
225
+ }
226
+
65
227
  export function compileSsr(filename: string, code: string, options: CompileSsrOptions = {}): CompileResult {
66
228
  const program = options.analysis?.program ?? parseTsx(filename, code)
67
229
  const analysis = options.analysis ?? analyzeModule(filename, code, program)
@@ -82,38 +244,24 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
82
244
  }
83
245
 
84
246
  const islands = options.islands
247
+ const devSrc = createDevSourceAttr(filename, code, options.devSourceRoot)
85
248
  const markersAt = markerTest(options.emitMarkers ?? options.isIsland ?? analysis.isInteractive)
86
249
  const jsxNodes = analysis.jsxNodes
87
- const exprContext = createExprContext(program, jsxNodes)
250
+ const exprContext = getExprContext(analysis)
88
251
  const { directAwaitNodes, dynamicChildNodes } = precomputeSsrSubtreeFlags(program)
89
- const prunelleTags: PrunelleTagEmitter = { use, compileSubExpression, compileChildren: compileChildrenListToStringExpr, compileJsx: compileJsxToStringExpr, markersAt, directAwaitNodes }
90
-
91
- function compileSubExpression(node: Node): string {
92
- if (!containsJsx(node, jsxNodes))
93
- return mark(node.start) + code.slice(node.start, node.end)
94
-
95
- const sub = new SourceEditor(code.slice(node.start, node.end))
96
- const offset = node.start
97
- walk(node, (child) => {
98
- if (isJsxNode(child)) {
99
- sub.replace(child.start - offset, child.end - offset, compileRootJsx(child) + mark(child.end))
100
- return false
101
- }
102
- return undefined
103
- })
104
- return mark(node.start) + sub.toString()
252
+ const compileSubExpression = (node: Node): string => compileSsrSubExpression(code, node, jsxNodes, mark, compileRootJsx)
253
+ const compileComponentRaw = (node: JSXElement, tag: string): string => {
254
+ let out = ''
255
+ emitComponent(node, tag, new StringParts(), (e) => { out = e })
256
+ return out
105
257
  }
258
+ const prunelleTags: PrunelleTagEmitter = { use, compileSubExpression, compileChildren: compileChildrenListToStringExpr, compileJsx: compileJsxToStringExpr, compileComponentRaw, markersAt, directAwaitNodes, jsxNodes }
106
259
 
107
260
  function compileChildrenListToStringExpr(children: readonly JSXChild[], slotMarkers = markersAt(children[0]?.start ?? 0), inFragment = false, rawTextTag?: 'style' | 'script'): string {
108
261
  const bufVar = `_o${loopCounter++}`
109
262
  const stmts: string[] = []
110
263
  const parts = new StringParts()
111
- const flush = () => {
112
- if (!parts.isEmpty()) {
113
- stmts.push(`${bufVar} += ${parts.toExpr()};`)
114
- parts.clear()
115
- }
116
- }
264
+ const flush = () => flushStringParts(bufVar, parts, stmts)
117
265
  emitChildrenIntoBuffer(children, bufVar, parts, flush, s => stmts.push(s), rawTextTag, slotMarkers, inFragment)
118
266
  if (stmts.length === 0)
119
267
  return parts.toExpr()
@@ -125,7 +273,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
125
273
  }
126
274
 
127
275
  // Emits JSX directly into a string accumulator variable `_out` (zero closures on nested `.map()` loops!)
128
- function emitIntoBuffer(node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void): void {
276
+ function emitIntoBuffer(node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void, actionOverride?: { node: Node, ident: string }): void {
129
277
  if (node.type === 'JSXFragment') {
130
278
  emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, undefined, markersAt(node.start), true)
131
279
  return
@@ -137,21 +285,21 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
137
285
  return
138
286
  }
139
287
 
140
- parts.pushStatic(`<${tag}`)
288
+ if (tag === 'form' && actionOverride === undefined) {
289
+ const formAction = findDynamicFormAction(node)
290
+ 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)))
292
+ return
293
+ }
294
+ }
295
+
296
+ parts.pushStatic(`<${tag}${devSrc(node, tag)}`)
141
297
  const isTextarea = tag === 'textarea'
142
298
  const isSelect = tag === 'select'
143
- const { innerHtmlExpr, textareaValue, nextSelectValue } = emitSsrElementAttrs({
144
- node,
145
- tag,
146
- parts,
147
- activeSelectValue,
148
- flushParts,
149
- pushStmt,
150
- nextId: () => loopCounter++,
151
- use,
152
- compileSubExpression,
153
- })
154
-
299
+ 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 })
301
+ if (FORM_CONTROL_TAGS.has(tag))
302
+ emitFormControlAttrs(node, tag as 'input' | 'select' | 'textarea', parts, use, compileSubExpression)
155
303
  parts.pushStatic('>')
156
304
  if (VOID_ELEMENTS.has(tag))
157
305
  return
@@ -161,28 +309,23 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
161
309
  activeSelectValue = nextSelectValue
162
310
 
163
311
  try {
164
- if (innerHtmlExpr !== undefined) {
312
+ if (innerHtmlExpr !== undefined)
165
313
  parts.pushExpr(innerHtmlExpr)
166
- }
167
- else if (isTextarea && textareaValue !== undefined && filterMeaningfulChildren(node.children).length === 0) {
168
- if (textareaValue.staticText !== undefined)
169
- parts.pushStatic(escapeStaticText(textareaValue.staticText))
170
- else if (textareaValue.expr !== undefined)
171
- parts.pushExpr(`${use('esc')}(${textareaValue.expr})`)
172
- }
314
+ 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})`)
173
316
  else if (tag === 'style') {
174
317
  const styleExpr = compileChildrenListToStringExpr(node.children, false, false, 'style')
175
318
  if (styleExpr !== '""')
176
319
  parts.pushExpr(`${use('ssrStyleBlock')}(${styleExpr})`)
177
320
  }
178
- else {
321
+ else
179
322
  emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
180
- }
181
323
  }
182
324
  finally {
183
325
  activeSelectValue = prevSelectValue
184
326
  }
185
- parts.pushStatic(`</${tag}>`)
327
+ if (actionOverride === undefined)
328
+ parts.pushStatic(`</${tag}>`)
186
329
  }
187
330
 
188
331
  function emitChildrenIntoBuffer(
@@ -244,12 +387,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
244
387
  const idxVar = idxParam ?? `_i${n}`
245
388
  const innerStmts: string[] = []
246
389
  const innerParts = new StringParts()
247
- const flushInner = () => {
248
- if (!innerParts.isEmpty()) {
249
- innerStmts.push(`${bufVar} += ${innerParts.toExpr()};`)
250
- innerParts.clear()
251
- }
252
- }
390
+ const flushInner = () => flushStringParts(bufVar, innerParts, innerStmts)
253
391
  emitIntoBuffer(match.body as JSXElement | JSXFragment, bufVar, innerParts, flushInner, s => innerStmts.push(s))
254
392
  flushInner()
255
393
 
@@ -260,7 +398,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
260
398
  }
261
399
  else if (match.isJsxBody) {
262
400
  const target = compileSubExpression(match.target)
263
- const params = match.params.map(p => code.slice(p.start, p.end)).join(', ')
401
+ const params = match.params.map(p => compileSubExpression(p)).join(', ')
264
402
  parts.pushExpr(`${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(match.body as JSXElement | JSXFragment)})`)
265
403
  }
266
404
  else {
@@ -287,24 +425,9 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
287
425
  }
288
426
  }
289
427
 
290
- function compileExpressionAsString(expr: Node): string {
291
- if (isJsxNode(expr))
292
- return compileJsxToStringExpr(expr)
293
- if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
294
- const right = unwrapParens(expr.right)
295
- if (isJsxNode(right))
296
- return `((${compileSubExpression(expr.left)}) ? (${compileJsxToStringExpr(right)}) : "")`
297
- }
298
- if (expr.type === 'ConditionalExpression') {
299
- const consNode = unwrapParens(expr.consequent)
300
- const altNode = unwrapParens(expr.alternate)
301
- if (isJsxNode(consNode) || isJsxNode(altNode))
302
- return `((${compileSubExpression(expr.test)}) ? (${compileExpressionAsString(consNode)}) : (${compileExpressionAsString(altNode)}))`
303
- }
304
- return `${use('esc')}(${compileSubExpression(expr)})`
305
- }
428
+ const compileExpressionAsString = (expr: Node): string => compileSsrExprAsString(expr, use, compileSubExpression, compileJsxToStringExpr)
306
429
 
307
- function emitComponent(node: JSXElement, tag: string, parts: StringParts): void {
430
+ function emitComponent(node: JSXElement, tag: string, parts: StringParts, onRaw?: (expr: string) => void): void {
308
431
  const { propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate } = serializeComponentProps(node.openingElement.attributes, compileSubExpression)
309
432
  const childNodes = node.children
310
433
  const meaningfulChildren = filterMeaningfulChildren(childNodes)
@@ -314,38 +437,51 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
314
437
 
315
438
  const prunelleTag = resolvePrunelleTag(tag, analysis.imports)
316
439
  if (prunelleTag === 'Suspense' || prunelleTag === 'Catch') {
317
- ;(prunelleTag === 'Suspense' ? emitSuspense : emitCatch)(prunelleTags, node, tag, propEntries, parts)
440
+ ;(prunelleTag === 'Suspense' ? emitSuspense : emitCatch)(prunelleTags, node, tag, propEntries, parts, onRaw)
318
441
  return
319
442
  }
320
443
 
321
444
  const islandInfo = islands?.get(tag)
322
445
  if (islandInfo === undefined && islands !== undefined && hydrateExpr !== undefined)
323
- throw mistake(`$hydrate on <${tag}>`, filename, `${tag} is not an island, so it never hydrates; drop $hydrate, or give ${tag} state or handlers`)
446
+ throw hydrateMistake(tag, filename, true)
324
447
 
325
448
  const childrenHaveAwait = hasChildren && childNodes.some(c => directAwaitNodes.has(c))
326
449
  const childMarkers = islandInfo === undefined && markersAt(node.start)
327
- const childExpr = hasChildren ? compileChildrenListToStringExpr(childNodes, childMarkers, childMarkers && meaningfulChildren.length > 1) : '""'
450
+ const onlyComp = onRaw !== undefined && islandInfo === undefined && meaningfulChildren.length === 1 && meaningfulChildren[0]!.type === 'JSXElement' && isComponentTag(jsxTagName(meaningfulChildren[0]!.openingElement.name)) ? meaningfulChildren[0]! : undefined
451
+ const childExpr = onlyComp !== undefined
452
+ ? compileComponentRaw(onlyComp, jsxTagName(onlyComp.openingElement.name))
453
+ : hasChildren ? compileChildrenListToStringExpr(childNodes, childMarkers, childMarkers && (meaningfulChildren.length > 1 || isSingleLoopChild(meaningfulChildren, jsxNodes))) : '""'
328
454
 
329
455
  if (islandInfo !== undefined) {
330
- emitIsland({ use, nextId: () => loopCounter++, markersAt }, { island: islandInfo, tag, call, start: node.start, propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate, hasChildren, childExpr, childrenHaveAwait }, parts)
456
+ 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)
458
+ if (onRaw !== undefined)
459
+ onRaw(`${use('raw')}(${target.toExpr()})`)
331
460
  return
332
461
  }
333
462
 
463
+ const emitOut = (expr: string): void => {
464
+ if (onRaw !== undefined)
465
+ onRaw(expr)
466
+ else
467
+ parts.pushExpr(`${use('ssrChild')}(${expr})`)
468
+ }
469
+ const wrappedChild = onlyComp !== undefined ? childExpr : `${use('raw')}(${childExpr})`
334
470
  const childrenHaveDynamic = hasChildren && childNodes.some(c => dynamicChildNodes.has(c))
335
471
 
336
472
  // Lazy memoized getter for non-async dynamic/component children so Providers & context components run before their children!
337
473
  if (childrenHaveDynamic && !childrenHaveAwait) {
338
474
  const cVar = `_c${loopCounter++}`
339
- const propsWithGetter = [...propEntries, `get children() { return ${cVar} === undefined ? (${cVar} = ${use('raw')}(${childExpr})) : ${cVar} }`].join(', ')
340
- parts.pushExpr(`${use('ssrChild')}(${call}((() => { let ${cVar}; return { ${propsWithGetter} }; })()))`)
475
+ const propsWithGetter = [...propEntries, `get children() { return ${cVar} === undefined ? (${cVar} = ${wrappedChild}) : ${cVar} }`].join(', ')
476
+ emitOut(`${call}((() => { let ${cVar}; return { ${propsWithGetter} }; })())`)
341
477
  return
342
478
  }
343
479
 
344
480
  if (hasChildren)
345
- propEntries.push(`children: ${use('raw')}(${childExpr})`)
481
+ propEntries.push(`children: ${wrappedChild}`)
346
482
 
347
483
  const propsObj = propEntries.length > 0 ? `{ ${propEntries.join(', ')} }` : '{}'
348
- parts.pushExpr(`${use('ssrChild')}(${call}(${propsObj}))`)
484
+ emitOut(`${call}(${propsObj})`)
349
485
  }
350
486
 
351
487
  function compileJsxToStringExpr(node: JSXElement | JSXFragment): string {
@@ -353,12 +489,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
353
489
  const stmts: string[] = []
354
490
  const parts = new StringParts()
355
491
 
356
- const flush = () => {
357
- if (!parts.isEmpty()) {
358
- stmts.push(`${bufVar} += ${parts.toExpr()};`)
359
- parts.clear()
360
- }
361
- }
492
+ const flush = () => flushStringParts(bufVar, parts, stmts)
362
493
 
363
494
  emitIntoBuffer(node, bufVar, parts, flush, s => stmts.push(s))
364
495
 
package/src/context.ts CHANGED
@@ -21,6 +21,26 @@ export interface ConsentGateProps {
21
21
  children?: PrunelleChild
22
22
  }
23
23
 
24
+ /** The button and legend texts of `<ConsentBanner>` and `<ConsentPreferences>`, English by default. */
25
+ export interface ConsentTexts {
26
+ accept?: string | undefined
27
+ refuse?: string | undefined
28
+ save?: string | undefined
29
+ /** Legend of the checkbox list (default: `'Cookies by purpose'`). */
30
+ legend?: string | undefined
31
+ }
32
+
33
+ export interface ConsentBannerProps extends ConsentTexts {
34
+ /** Heading of the banner (default: `'Cookies'`). */
35
+ title?: string | undefined
36
+ /** What the cookies are for; by default a sentence listing each category's label. */
37
+ children?: PrunelleChild
38
+ /** The cookie or privacy policy page, linked under the text. */
39
+ policyHref?: string | undefined
40
+ /** Text of the disclosure holding the checkboxes (default: `'Choose'`). */
41
+ choose?: string | undefined
42
+ }
43
+
24
44
  export interface CatchProps {
25
45
  /** Rendered in place of `children` when they throw; a function gets the error and a `retry` that renders the children again (a no-op on the server). */
26
46
  fallback?: PrunelleChild | ((error: unknown, retry: () => void) => PrunelleChild)
@@ -30,6 +50,8 @@ export interface CatchProps {
30
50
  export interface ServerContextBridge {
31
51
  region(props: RegionProps): PrunelleChild
32
52
  consentGate(props: ConsentGateProps): PrunelleChild
53
+ consentBanner(props: ConsentBannerProps): PrunelleChild
54
+ consentPreferences(props: ConsentTexts): PrunelleChild
33
55
  getContext(key: symbol): { found: true, value: unknown } | undefined
34
56
  runWithContext<T>(key: symbol, value: unknown, fn: () => T): T
35
57
  nextId(): string | undefined
@@ -83,6 +105,18 @@ export function ConsentGate(props: ConsentGateProps): PrunelleChild {
83
105
  return bridge !== undefined ? bridge.consentGate(props) : (props.fallback ?? null)
84
106
  }
85
107
 
108
+ /** Asks for consent until the visitor accepts, refuses or picks categories: a zero-JS form posting to the consent endpoint, with Accept and Refuse given the same weight. Server-only. */
109
+ export function ConsentBanner(props: ConsentBannerProps): PrunelleChild {
110
+ const bridge = getServerBridge()
111
+ return bridge !== undefined ? bridge.consentBanner(props) : null
112
+ }
113
+
114
+ /** The visitor's current choice per category, to change or withdraw it as easily as it was given: put it on the cookie policy page or behind a footer link. Server-only. */
115
+ export function ConsentPreferences(props: ConsentTexts): PrunelleChild {
116
+ const bridge = getServerBridge()
117
+ return bridge !== undefined ? bridge.consentPreferences(props) : null
118
+ }
119
+
86
120
  export interface Context<T> {
87
121
  readonly id: symbol
88
122
  readonly defaultValue: T