prunelle 0.8.0 → 0.9.0

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 (184) hide show
  1. package/llms.txt +61 -44
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +6 -10
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +88 -134
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +14 -6
  14. package/src/build/index.ts +20 -10
  15. package/src/build/islands.ts +4 -1
  16. package/src/build/key-types.ts +31 -0
  17. package/src/build/manifest.ts +19 -1
  18. package/src/build/plugin-host.ts +2 -0
  19. package/src/build/prerender.ts +2 -2
  20. package/src/build/reach.ts +14 -1
  21. package/src/build/report.ts +1 -1
  22. package/src/build/route-types.ts +16 -0
  23. package/src/build/routes.ts +24 -15
  24. package/src/build/seed-ids.ts +65 -0
  25. package/src/build/seed-writes.ts +111 -0
  26. package/src/build/static-headers.ts +2 -2
  27. package/src/build/static.ts +1 -1
  28. package/src/cli/check-cache.ts +51 -0
  29. package/src/cli/check-consent.ts +95 -0
  30. package/src/cli/check-forms.ts +2 -2
  31. package/src/cli/check-links-patterns.ts +101 -0
  32. package/src/cli/check-links.ts +16 -100
  33. package/src/cli/check-regions.ts +185 -0
  34. package/src/cli/check-security.ts +50 -6
  35. package/src/cli/check.ts +40 -18
  36. package/src/cli/commands.ts +134 -14
  37. package/src/cli/docs.ts +21 -2
  38. package/src/cli/index.ts +1 -1
  39. package/src/cli/inspect.ts +2 -0
  40. package/src/cli/mcp-tools.ts +2 -2
  41. package/src/cli/new.ts +9 -5
  42. package/src/cli/upgrade-names.ts +14 -2
  43. package/src/cli/upgrade.ts +3 -0
  44. package/src/compiler/analyze.ts +2 -2
  45. package/src/compiler/cacheability.ts +24 -2
  46. package/src/compiler/compliance-contrast.ts +284 -0
  47. package/src/compiler/compliance-empty.ts +24 -0
  48. package/src/compiler/compliance-rgaa-content.ts +95 -0
  49. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  50. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  51. package/src/compiler/compliance-rgaa.ts +19 -0
  52. package/src/compiler/compliance-third-party.ts +59 -0
  53. package/src/compiler/compliance-urls.ts +52 -0
  54. package/src/compiler/compliance.ts +70 -42
  55. package/src/compiler/cookie-inventory.ts +119 -0
  56. package/src/compiler/foreign-imports.ts +5 -3
  57. package/src/compiler/mistakes.ts +18 -9
  58. package/src/compiler/props-pattern.ts +211 -0
  59. package/src/compiler/props.ts +177 -346
  60. package/src/compiler/ssr-emit.ts +510 -0
  61. package/src/compiler/ssr-helpers.ts +170 -121
  62. package/src/compiler/ssr.ts +25 -440
  63. package/src/context.ts +14 -1
  64. package/src/dev/child.ts +1 -1
  65. package/src/dev/hot-islands.ts +71 -0
  66. package/src/dev/index.ts +31 -18
  67. package/src/dev/protocol.ts +1 -1
  68. package/src/dev/queue.ts +3 -2
  69. package/src/dev/reload.ts +1 -1
  70. package/src/dev/supervisor.ts +3 -1
  71. package/src/dev/watchers.ts +6 -2
  72. package/src/dom/action.ts +97 -14
  73. package/src/dom/extras.ts +2 -1
  74. package/src/dom/field-marks.ts +24 -0
  75. package/src/dom/hot.ts +9 -0
  76. package/src/dom/index.ts +25 -5
  77. package/src/dom/island-hot.ts +29 -0
  78. package/src/dom/island.ts +13 -2
  79. package/src/dom/prefetch.ts +132 -0
  80. package/src/dom/regions.ts +498 -0
  81. package/src/dom/swap.ts +245 -0
  82. package/src/dom/trusted.ts +22 -0
  83. package/src/dom/upload.ts +44 -0
  84. package/src/eco/declaration.ts +39 -40
  85. package/src/eco/index.ts +5 -5
  86. package/src/href.ts +31 -0
  87. package/src/index.ts +9 -3
  88. package/src/plugins/config.ts +1 -1
  89. package/src/plugins/context.ts +7 -1
  90. package/src/plugins/daily.ts +27 -0
  91. package/src/plugins/index.ts +3 -3
  92. package/src/plugins/order.ts +1 -1
  93. package/src/plugins/public.ts +8 -5
  94. package/src/plugins/services.ts +88 -14
  95. package/src/plugins/types.ts +120 -9
  96. package/src/reactivity/hmr.ts +90 -0
  97. package/src/reactivity/index.ts +38 -18
  98. package/src/reactivity/resource.ts +115 -0
  99. package/src/reactivity/seed.ts +39 -0
  100. package/src/reactivity/server-seed.ts +194 -0
  101. package/src/reactivity/store.ts +55 -1
  102. package/src/rgpd/draft.ts +171 -0
  103. package/src/rgpd/forms.ts +85 -0
  104. package/src/rgpd/index.ts +57 -0
  105. package/src/server/action-flash.ts +1 -0
  106. package/src/server/action-registry.ts +6 -8
  107. package/src/server/action.ts +51 -19
  108. package/src/server/app-secret.ts +14 -8
  109. package/src/server/cache-invalidation.ts +96 -0
  110. package/src/server/compress.ts +3 -1
  111. package/src/server/consent.ts +16 -2
  112. package/src/server/cookie-inventory.ts +78 -0
  113. package/src/server/cookies.ts +50 -0
  114. package/src/server/csp-report.ts +86 -0
  115. package/src/server/discard.ts +13 -0
  116. package/src/server/document.ts +2 -2
  117. package/src/server/env.ts +1 -1
  118. package/src/server/errors.ts +9 -2
  119. package/src/server/field-errors.ts +91 -0
  120. package/src/server/form-schema.ts +16 -11
  121. package/src/server/health.ts +33 -12
  122. package/src/server/http.ts +25 -10
  123. package/src/server/index.ts +101 -298
  124. package/src/server/loader.ts +1 -0
  125. package/src/server/page.ts +3 -9
  126. package/src/server/plugin-host.ts +26 -8
  127. package/src/server/public.ts +14 -3
  128. package/src/server/rate-limit.ts +39 -10
  129. package/src/server/region.ts +3 -0
  130. package/src/server/request-handler.ts +370 -0
  131. package/src/server/request-log.ts +94 -0
  132. package/src/server/route-cache.ts +41 -6
  133. package/src/server/route-input.ts +54 -0
  134. package/src/server/route-table.ts +35 -19
  135. package/src/server/routing.ts +12 -11
  136. package/src/server/sanitize-html.ts +1 -1
  137. package/src/server/security.ts +38 -8
  138. package/src/server/serve-handlers.ts +9 -5
  139. package/src/server/shared-store.ts +314 -0
  140. package/src/server/start.ts +12 -5
  141. package/src/server/static-dir.ts +14 -10
  142. package/src/server/stream.ts +2 -1
  143. package/src/server/surface.ts +39 -0
  144. package/src/server/webhook.ts +48 -0
  145. package/src/server/workers.ts +168 -0
  146. package/src/ssr/consent-banner.ts +20 -16
  147. package/src/ssr/consent-texts.ts +40 -0
  148. package/src/ssr/context.ts +26 -3
  149. package/src/ssr/cookie-table.ts +75 -0
  150. package/src/ssr/index.ts +23 -13
  151. package/src/ssr/navigation.ts +161 -14
  152. package/src/test/browser.ts +50 -22
  153. package/src/test/build-reuse.ts +70 -0
  154. package/src/test/index.ts +45 -6
  155. package/src/test/mount.ts +53 -0
  156. package/src/test/outside.ts +94 -0
  157. package/templates/_shared/AGENTS.md +1 -1
  158. package/templates/_shared/Dockerfile +22 -0
  159. package/templates/_shared/dockerignore +9 -0
  160. package/templates/_shared/gitignore +2 -0
  161. package/templates/app/.env.example +3 -1
  162. package/templates/app/compose.yaml +32 -0
  163. package/templates/app/db/migrations/001_notes.sql +7 -0
  164. package/templates/app/db/schema.ts +11 -0
  165. package/templates/app/package.json +1 -0
  166. package/templates/app/prunelle.config.ts +6 -0
  167. package/templates/app/src/actions/notes.ts +26 -0
  168. package/templates/app/src/auth.ts +4 -2
  169. package/templates/app/src/db.ts +5 -0
  170. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  171. package/templates/app/src/routes/privacy.tsx +6 -2
  172. package/templates/app/tests/app.test.ts +14 -3
  173. package/templates/plugin/AGENTS.md +11 -0
  174. package/templates/plugin/CLAUDE.md +1 -0
  175. package/templates/plugin/README.md +27 -0
  176. package/templates/plugin/gitignore +2 -0
  177. package/templates/plugin/llms.txt +19 -0
  178. package/templates/plugin/package.json +33 -0
  179. package/templates/plugin/src/index.ts +40 -0
  180. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  181. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  182. package/templates/plugin/tests/plugin.test.ts +42 -0
  183. package/templates/plugin/tsconfig.json +19 -0
  184. package/ts-plugin.cjs +3674 -2196
@@ -0,0 +1,510 @@
1
+ // SSR emitters: each turns one kind of JSX node into string parts or buffer statements, sharing the state of one `compileSsr` call through `SsrEnv`.
2
+
3
+ import type {
4
+ JSXChild,
5
+ JSXElement,
6
+ JSXFragment,
7
+ Node,
8
+ } from 'oxc-parser'
9
+ import type { ModuleAnalysis } from './analyze'
10
+ import type { createDevSourceAttr } from './dev-source'
11
+ import type { ChildSlotKind, ExprContext } from './shared'
12
+ import type { IslandBinding } from './ssr'
13
+ import type { SelectValueBinding } from './ssr-helpers'
14
+ import type { PrunelleTagEmitter } from './ssr-prunelle-tags'
15
+ import { hydrateMistake } from './mistakes'
16
+ import {
17
+ decodeHtmlEntities,
18
+ escapeRawText,
19
+ escapeStaticText,
20
+ filterMeaningfulChildren,
21
+ isComponentTag,
22
+ isJsxNode,
23
+ jsxTagName,
24
+ matchJsxMapCall,
25
+ planChildSlots,
26
+ RAW_TEXT_ELEMENTS,
27
+ resolvePrunelleTag,
28
+ unwrapParens,
29
+ VOID_ELEMENTS,
30
+ } from './shared'
31
+ import {
32
+ emitSsrElementAttrs,
33
+ serializeComponentProps,
34
+ staticLiteralOrTemplate,
35
+ StringParts,
36
+ } from './ssr-helpers'
37
+ import { emitIsland } from './ssr-island'
38
+ import { emitCatch, emitSuspense } from './ssr-prunelle-tags'
39
+
40
+ /** The state one `compileSsr` call shares across its emitters. */
41
+ export interface SsrEnv {
42
+ filename: string
43
+ analysis: ModuleAnalysis
44
+ islands: ReadonlyMap<string, IslandBinding> | undefined
45
+ devSrc: ReturnType<typeof createDevSourceAttr>
46
+ markersAt: (offset: number) => boolean
47
+ jsxNodes: WeakSet<Node>
48
+ exprContext: ExprContext
49
+ directAwaitNodes: WeakSet<Node>
50
+ dynamicChildNodes: WeakSet<Node>
51
+ use: (name: string) => string
52
+ nextId: () => number
53
+ mark: (offset: number) => string
54
+ compileSubExpression: (node: Node) => string
55
+ activeSelectValue: SelectValueBinding | undefined
56
+ }
57
+
58
+ type Sink = [bufVar: string, parts: StringParts, flush: () => void, pushStmt: (stmt: string) => void]
59
+ type ActionOverride = { node: Node, ident: string }
60
+ type LoopSlot = Extract<ChildSlotKind, { kind: 'loop' }>
61
+
62
+ const FORM_CONTROL_TAGS = new Set(['input', 'select', 'textarea'])
63
+ const FORM_ATTR_BITS: Record<string, number> = {
64
+ type: 1,
65
+ required: 2,
66
+ minlength: 4,
67
+ maxlength: 8,
68
+ min: 16,
69
+ max: 32,
70
+ step: 64,
71
+ pattern: 128,
72
+ }
73
+
74
+ function findDynamicFormAction(node: JSXElement): Node | undefined {
75
+ for (const attr of node.openingElement.attributes) {
76
+ if (attr.type !== 'JSXAttribute' || jsxTagName(attr.name) !== 'action')
77
+ continue
78
+ if (attr.value?.type !== 'JSXExpressionContainer' || attr.value.expression.type === 'JSXEmptyExpression')
79
+ return undefined
80
+ const expr = attr.value.expression
81
+ if (staticLiteralOrTemplate(expr).ok)
82
+ return undefined
83
+ if (expr.type === 'ConditionalExpression' && staticLiteralOrTemplate(expr.consequent).ok && staticLiteralOrTemplate(expr.alternate).ok)
84
+ return undefined
85
+ return expr
86
+ }
87
+ return undefined
88
+ }
89
+
90
+ function emitFormControlAttrs(
91
+ node: JSXElement,
92
+ tag: 'input' | 'select' | 'textarea',
93
+ parts: StringParts,
94
+ use: (name: string) => string,
95
+ compileSubExpression: (node: Node) => string,
96
+ ): void {
97
+ const attrs = node.openingElement.attributes
98
+ if (attrs.some(a => a.type === 'JSXSpreadAttribute'))
99
+ return
100
+ let nameExpr: string | undefined
101
+ let typeExpr: string | undefined
102
+ let present = 0
103
+ for (const attr of attrs) {
104
+ if (attr.type !== 'JSXAttribute')
105
+ continue
106
+ const attrName = jsxTagName(attr.name).toLowerCase()
107
+ const bit = FORM_ATTR_BITS[attrName]
108
+ if (bit !== undefined)
109
+ present |= bit
110
+ if (attrName === 'name') {
111
+ if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
112
+ nameExpr = JSON.stringify(attr.value.value)
113
+ }
114
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
115
+ const lit = staticLiteralOrTemplate(attr.value.expression)
116
+ nameExpr = lit.ok && typeof lit.value === 'string' ? JSON.stringify(lit.value) : compileSubExpression(attr.value.expression)
117
+ }
118
+ }
119
+ else if (tag === 'input' && attrName === 'type') {
120
+ if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
121
+ typeExpr = JSON.stringify(attr.value.value.toLowerCase())
122
+ }
123
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
124
+ const lit = staticLiteralOrTemplate(attr.value.expression)
125
+ if (lit.ok && typeof lit.value === 'string')
126
+ typeExpr = JSON.stringify(lit.value.toLowerCase())
127
+ }
128
+ }
129
+ }
130
+ if (nameExpr === undefined)
131
+ return
132
+ const typeArg = typeExpr !== undefined ? `, ${typeExpr}` : ''
133
+ parts.pushExpr(`${use('ssrFormAttrs')}(${JSON.stringify(tag)}, ${nameExpr}, ${present}${typeArg})`)
134
+ }
135
+
136
+ function emitActionFormExpr(
137
+ formAction: Node,
138
+ isAsyncForm: boolean,
139
+ nextId: () => number,
140
+ use: (name: string) => string,
141
+ compileSubExpression: (node: Node) => string,
142
+ emitBody: (bufVar: string, parts: StringParts, flush: () => void, pushStmt: (stmt: string) => void, override: ActionOverride) => void,
143
+ ): string {
144
+ const faVar = `_fa${nextId()}`
145
+ const innerBuf = `_o${nextId()}`
146
+ const innerStmts: string[] = []
147
+ const innerParts = new StringParts()
148
+ const flushInner = () => flushStringParts(innerBuf, innerParts, innerStmts)
149
+ emitBody(innerBuf, innerParts, flushInner, s => innerStmts.push(s), { node: formAction, ident: faVar })
150
+ if (innerStmts.length > 0)
151
+ flushInner()
152
+ const body = innerStmts.length === 0 ? innerParts.toExpr() : `{ ${bufferBody(innerBuf, innerStmts)} }`
153
+ return isAsyncForm
154
+ ? `await ${use('ssrFormAsync')}(${compileSubExpression(formAction)}, async (${faVar}) => ${body})`
155
+ : `${use('ssrForm')}(${compileSubExpression(formAction)}, (${faVar}) => ${body})`
156
+ }
157
+
158
+ // A buffer is an array joined once: `+=` in a loop allocates a rope node for every two parts, about half again as many bytes for a page of 500 rows, and the garbage collector runs that much more often.
159
+ function flushStringParts(bufVar: string, parts: StringParts, stmts: string[]): void {
160
+ if (!parts.isEmpty()) {
161
+ stmts.push(`${bufVar}.push(${parts.toArgs()});`)
162
+ parts.clear()
163
+ }
164
+ }
165
+
166
+ function bufferBody(bufVar: string, stmts: readonly string[]): string {
167
+ return `const ${bufVar} = []; ${stmts.join(' ')} return ${bufVar}.join("");`
168
+ }
169
+
170
+ function isSingleLoopChild(meaningful: readonly JSXChild[], jsxNodes: WeakSet<Node>): boolean {
171
+ return meaningful.length === 1
172
+ && meaningful[0]!.type === 'JSXExpressionContainer'
173
+ && meaningful[0]!.expression.type !== 'JSXEmptyExpression'
174
+ && matchJsxMapCall(meaningful[0]!.expression, jsxNodes) !== undefined
175
+ }
176
+
177
+ function compileSsrExprAsString(
178
+ expr: Node,
179
+ use: (name: string) => string,
180
+ compileSubExpression: (node: Node) => string,
181
+ compileJsxToStringExpr: (node: JSXElement | JSXFragment) => string,
182
+ ): string {
183
+ if (isJsxNode(expr))
184
+ return compileJsxToStringExpr(expr)
185
+ if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
186
+ const right = unwrapParens(expr.right)
187
+ if (isJsxNode(right))
188
+ return `((${compileSubExpression(expr.left)}) ? (${compileJsxToStringExpr(right)}) : "")`
189
+ }
190
+ if (expr.type === 'ConditionalExpression') {
191
+ const consNode = unwrapParens(expr.consequent)
192
+ const altNode = unwrapParens(expr.alternate)
193
+ if (isJsxNode(consNode) || isJsxNode(altNode))
194
+ return `((${compileSubExpression(expr.test)}) ? (${compileSsrExprAsString(consNode, use, compileSubExpression, compileJsxToStringExpr)}) : (${compileSsrExprAsString(altNode, use, compileSubExpression, compileJsxToStringExpr)}))`
195
+ }
196
+ return `${use('esc')}(${compileSubExpression(expr)})`
197
+ }
198
+
199
+ function pushLeadNlStatic(parts: StringParts, text: string): void {
200
+ parts.pushStatic(text.startsWith('\n') || text.startsWith('\r') ? `\n${text}` : text)
201
+ }
202
+
203
+ // The statements of a buffer wrapped as one expression, awaiting when the subtree has a direct `await`.
204
+ function bufferExpr(bufVar: string, stmts: readonly string[], hasAwait: boolean): string {
205
+ return hasAwait
206
+ ? `(await (async () => { ${bufferBody(bufVar, stmts)} })())`
207
+ : `(() => { ${bufferBody(bufVar, stmts)} })()`
208
+ }
209
+
210
+ export function compileChildrenListToStringExpr(
211
+ env: SsrEnv,
212
+ children: readonly JSXChild[],
213
+ slotMarkers = env.markersAt(children[0]?.start ?? 0),
214
+ inFragment = false,
215
+ rawTextTag?: 'style' | 'script',
216
+ ): string {
217
+ const bufVar = `_o${env.nextId()}`
218
+ const stmts: string[] = []
219
+ const parts = new StringParts()
220
+ const flush = () => flushStringParts(bufVar, parts, stmts)
221
+ emitChildrenIntoBuffer(env, children, bufVar, parts, flush, s => stmts.push(s), rawTextTag, slotMarkers, inFragment)
222
+ if (stmts.length === 0)
223
+ return parts.toExpr()
224
+ flush()
225
+ return bufferExpr(bufVar, stmts, children.some(c => env.directAwaitNodes.has(c)))
226
+ }
227
+
228
+ export function compileJsxToStringExpr(env: SsrEnv, node: JSXElement | JSXFragment): string {
229
+ const bufVar = `_o${env.nextId()}`
230
+ const stmts: string[] = []
231
+ const parts = new StringParts()
232
+
233
+ const flush = () => flushStringParts(bufVar, parts, stmts)
234
+
235
+ emitIntoBuffer(env, node, bufVar, parts, flush, s => stmts.push(s))
236
+
237
+ // If no inline `for` statements were emitted, stay a pure flat concatenation expression!
238
+ if (stmts.length === 0)
239
+ return parts.toExpr()
240
+
241
+ flush()
242
+ return bufferExpr(bufVar, stmts, env.directAwaitNodes.has(node))
243
+ }
244
+
245
+ export function compileRootJsx(env: SsrEnv, node: JSXElement | JSXFragment): string {
246
+ return `${env.use('raw')}(${compileJsxToStringExpr(env, node)})`
247
+ }
248
+
249
+ function compileExpressionAsString(env: SsrEnv, expr: Node): string {
250
+ return compileSsrExprAsString(expr, env.use, env.compileSubExpression, n => compileJsxToStringExpr(env, n))
251
+ }
252
+
253
+ function compileComponentRaw(env: SsrEnv, node: JSXElement, tag: string): string {
254
+ let out = ''
255
+ emitComponent(env, node, tag, new StringParts(), (e) => { out = e })
256
+ return out
257
+ }
258
+
259
+ // The body of an open element: raw inner HTML, a `<textarea>` value, a `<style>`/`<pre>` block, or its children.
260
+ function emitElementBody(
261
+ env: SsrEnv,
262
+ node: JSXElement,
263
+ tag: string,
264
+ attrs: ReturnType<typeof emitSsrElementAttrs>,
265
+ emit: Sink,
266
+ ): void {
267
+ const { use } = env
268
+ const [bufVar, parts, flushParts, pushStmt] = emit
269
+ const { innerHtmlExpr, textareaValue } = attrs
270
+ const isTextarea = tag === 'textarea'
271
+ const needsLeadNl = isTextarea || tag === 'pre'
272
+ if (innerHtmlExpr !== undefined)
273
+ parts.pushExpr(needsLeadNl ? `${use('ssrLeadNl')}(${innerHtmlExpr})` : innerHtmlExpr)
274
+ else if (isTextarea && textareaValue !== undefined && filterMeaningfulChildren(node.children).length === 0)
275
+ textareaValue.staticText !== undefined ? pushLeadNlStatic(parts, escapeStaticText(textareaValue.staticText)) : textareaValue.expr !== undefined && parts.pushExpr(`${use('ssrLeadNl')}(${use('esc')}(${textareaValue.expr}))`)
276
+ else if (tag === 'style' || needsLeadNl) {
277
+ const bodyExpr = tag === 'style' ? compileChildrenListToStringExpr(env, node.children, false, false, 'style') : compileChildrenListToStringExpr(env, node.children)
278
+ if (bodyExpr !== '""')
279
+ parts.pushExpr(`${use(tag === 'style' ? 'ssrStyleBlock' : 'ssrLeadNl')}(${bodyExpr})`)
280
+ }
281
+ else
282
+ emitChildrenIntoBuffer(env, node.children, bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
283
+ }
284
+
285
+ // Emits JSX directly into a string accumulator variable `_out` (zero closures on nested `.map()` loops!)
286
+ export function emitIntoBuffer(env: SsrEnv, node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void, actionOverride?: ActionOverride): void {
287
+ const { use, nextId, markersAt, compileSubExpression } = env
288
+ if (node.type === 'JSXFragment') {
289
+ emitChildrenIntoBuffer(env, node.children, bufVar, parts, flushParts, pushStmt, undefined, markersAt(node.start), true)
290
+ return
291
+ }
292
+
293
+ const tag = jsxTagName(node.openingElement.name)
294
+ if (isComponentTag(tag)) {
295
+ emitComponent(env, node, tag, parts)
296
+ return
297
+ }
298
+
299
+ if (tag === 'form' && actionOverride === undefined) {
300
+ const formAction = findDynamicFormAction(node)
301
+ if (formAction !== undefined) {
302
+ parts.pushExpr(emitActionFormExpr(formAction, env.directAwaitNodes.has(node), nextId, use, compileSubExpression, (b, p, f, ps, ov) => emitIntoBuffer(env, node, b, p, f, ps, ov)))
303
+ return
304
+ }
305
+ }
306
+
307
+ parts.pushStatic(`<${tag}${env.devSrc(node, tag)}`)
308
+ const compileAttrExpr = actionOverride !== undefined ? (n: Node) => (n === actionOverride.node ? actionOverride.ident : compileSubExpression(n)) : compileSubExpression
309
+ const attrs = emitSsrElementAttrs({ node, tag, parts, activeSelectValue: env.activeSelectValue, flushParts, pushStmt, nextId, use, compileSubExpression: compileAttrExpr })
310
+ if (FORM_CONTROL_TAGS.has(tag))
311
+ emitFormControlAttrs(node, tag as 'input' | 'select' | 'textarea', parts, use, compileSubExpression)
312
+ parts.pushStatic('>')
313
+ if (VOID_ELEMENTS.has(tag))
314
+ return
315
+
316
+ const prevSelectValue = env.activeSelectValue
317
+ if (tag === 'select')
318
+ env.activeSelectValue = attrs.nextSelectValue
319
+
320
+ try {
321
+ emitElementBody(env, node, tag, attrs, [bufVar, parts, flushParts, pushStmt])
322
+ }
323
+ finally {
324
+ env.activeSelectValue = prevSelectValue
325
+ }
326
+ if (actionOverride === undefined)
327
+ parts.pushStatic(`</${tag}>`)
328
+ }
329
+
330
+ // A `.map()` with a JSX body: an inline `for` over the array when its params are plain, else a `ssrLoop` call.
331
+ function emitLoopSlot(env: SsrEnv, slot: LoopSlot, emit: Sink): void {
332
+ const { use, nextId, compileSubExpression } = env
333
+ const [bufVar, parts, flushParts, pushStmt] = emit
334
+ const { match } = slot
335
+ const itemParam = match.params[0]?.type === 'Identifier' ? match.params[0].name : undefined
336
+ const idxParam = match.params[1]?.type === 'Identifier' ? match.params[1].name : undefined
337
+
338
+ if (match.isJsxBody && itemParam !== undefined && match.params.length <= 2 && (match.params.length < 2 || idxParam !== undefined)) {
339
+ flushParts()
340
+ const n = nextId()
341
+ const arrVar = `_a${n}`
342
+ const idxVar = idxParam ?? `_i${n}`
343
+ const innerStmts: string[] = []
344
+ const innerParts = new StringParts()
345
+ const flushInner = () => flushStringParts(bufVar, innerParts, innerStmts)
346
+ emitIntoBuffer(env, match.body as JSXElement | JSXFragment, bufVar, innerParts, flushInner, s => innerStmts.push(s))
347
+ flushInner()
348
+
349
+ const target = compileSubExpression(match.target)
350
+ pushStmt(
351
+ `const ${arrVar} = ${target}; if (${arrVar}) for (let ${idxVar} = 0; ${idxVar} < ${arrVar}.length; ${idxVar}++) { const ${itemParam} = ${arrVar}[${idxVar}]; ${innerStmts.join(' ')} }`,
352
+ )
353
+ }
354
+ else if (match.isJsxBody) {
355
+ const target = compileSubExpression(match.target)
356
+ const params = match.params.map(p => compileSubExpression(p)).join(', ')
357
+ parts.pushExpr(`${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(env, match.body as JSXElement | JSXFragment)})`)
358
+ }
359
+ else {
360
+ parts.pushExpr(`${use('esc')}(${compileSubExpression(match.call)})`)
361
+ }
362
+ }
363
+
364
+ // A child of a `<style>`/`<script>` element: a plain template literal stays static, any other expression goes through `ssrRawText`. False when the child is no expression.
365
+ function emitRawTextChild(env: SsrEnv, child: JSXChild, rawTextTag: 'style' | 'script', parts: StringParts): boolean {
366
+ if (child.type !== 'JSXExpressionContainer' || child.expression.type === 'JSXEmptyExpression')
367
+ return false
368
+ const expr = child.expression
369
+ if (expr.type === 'TemplateLiteral' && expr.expressions.length === 0 && expr.quasis.length === 1) {
370
+ const cooked = expr.quasis[0]?.value.cooked
371
+ if (typeof cooked === 'string') {
372
+ parts.pushStatic(escapeRawText(cooked, rawTextTag))
373
+ return true
374
+ }
375
+ }
376
+ parts.pushExpr(`${env.use('ssrRawText')}(${JSON.stringify(rawTextTag)}, ${env.compileSubExpression(expr)})`)
377
+ return true
378
+ }
379
+
380
+ // A dynamic slot that is neither an element nor a static text: components, fragments, loops, `&&` and ternary shows, plain expressions.
381
+ function emitDynamicSlot(env: SsrEnv, slot: Exclude<ChildSlotKind, { kind: 'static-text' | 'element' }>, emit: Sink): void {
382
+ const { use, compileSubExpression } = env
383
+ const [bufVar, parts, flushParts, pushStmt] = emit
384
+ if (slot.kind === 'component' || slot.kind === 'fragment') {
385
+ emitIntoBuffer(env, slot.node, bufVar, parts, flushParts, pushStmt)
386
+ }
387
+ else if (slot.kind === 'loop') {
388
+ emitLoopSlot(env, slot, emit)
389
+ }
390
+ else if (slot.kind === 'and-show') {
391
+ const left = compileSubExpression(slot.expr.left)
392
+ const right = compileJsxToStringExpr(env, slot.right)
393
+ parts.pushExpr(`((${left}) ? (${right}) : "")`)
394
+ }
395
+ else if (slot.kind === 'ternary-show') {
396
+ const test = compileSubExpression(slot.expr.test)
397
+ const cons = compileExpressionAsString(env, slot.cons)
398
+ const alt = compileExpressionAsString(env, slot.alt)
399
+ parts.pushExpr(`((${test}) ? (${cons}) : (${alt}))`)
400
+ }
401
+ else {
402
+ parts.pushExpr(`${use('esc')}(${compileSubExpression(slot.expr)})`)
403
+ }
404
+ }
405
+
406
+ function emitChildrenIntoBuffer(
407
+ env: SsrEnv,
408
+ children: readonly JSXChild[],
409
+ bufVar: string,
410
+ parts: StringParts,
411
+ flushParts: () => void,
412
+ pushStmt: (stmt: string) => void,
413
+ rawTextTag?: 'style' | 'script',
414
+ slotMarkers = env.markersAt(children[0]?.start ?? 0),
415
+ inFragment = false,
416
+ ): void {
417
+ const planned = planChildSlots(children, { jsxNodes: env.jsxNodes, exprContext: env.exprContext, emitMarkers: slotMarkers, inFragment })
418
+
419
+ for (const { child, slot, open, close } of planned) {
420
+ if (slot.kind === 'static-text') {
421
+ if (rawTextTag !== undefined)
422
+ parts.pushStatic(escapeRawText(slot.text, rawTextTag))
423
+ else
424
+ parts.pushStatic(escapeStaticText(slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text)))
425
+ continue
426
+ }
427
+
428
+ if (rawTextTag !== undefined && emitRawTextChild(env, child, rawTextTag, parts))
429
+ continue
430
+
431
+ if (slot.kind === 'element') {
432
+ emitIntoBuffer(env, slot.node, bufVar, parts, flushParts, pushStmt)
433
+ continue
434
+ }
435
+
436
+ if (open !== '')
437
+ parts.pushStatic(open)
438
+ emitDynamicSlot(env, slot, [bufVar, parts, flushParts, pushStmt])
439
+ if (close !== '')
440
+ parts.pushStatic(close)
441
+ }
442
+ }
443
+
444
+ export function emitComponent(env: SsrEnv, node: JSXElement, tag: string, parts: StringParts, onRaw?: (expr: string) => void): void {
445
+ const { use, nextId, markersAt, jsxNodes, directAwaitNodes, islands } = env
446
+ const { propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate } = serializeComponentProps(node.openingElement.attributes, env.compileSubExpression)
447
+ const childNodes = node.children
448
+ const meaningfulChildren = filterMeaningfulChildren(childNodes)
449
+ const hasChildren = meaningfulChildren.length > 0
450
+ // The call sits on the line of its tag, so a component that throws names that line in the caller's frame.
451
+ const call = `${env.mark(node.start)}${tag}`
452
+
453
+ const prunelleTag = resolvePrunelleTag(tag, env.analysis.imports)
454
+ if (prunelleTag === 'Suspense' || prunelleTag === 'Catch') {
455
+ const prunelleTags: PrunelleTagEmitter = {
456
+ use,
457
+ compileSubExpression: env.compileSubExpression,
458
+ compileChildren: (children, slotMarkers, inFragment) => compileChildrenListToStringExpr(env, children, slotMarkers, inFragment),
459
+ compileJsx: n => compileJsxToStringExpr(env, n),
460
+ compileComponentRaw: (n, t) => compileComponentRaw(env, n, t),
461
+ markersAt,
462
+ directAwaitNodes,
463
+ jsxNodes,
464
+ }
465
+ ;(prunelleTag === 'Suspense' ? emitSuspense : emitCatch)(prunelleTags, node, tag, propEntries, parts, onRaw)
466
+ return
467
+ }
468
+
469
+ const islandInfo = islands?.get(tag)
470
+ if (islandInfo === undefined && islands !== undefined && hydrateExpr !== undefined)
471
+ throw hydrateMistake(tag, env.filename, true)
472
+
473
+ const childrenHaveAwait = hasChildren && childNodes.some(c => directAwaitNodes.has(c))
474
+ const childMarkers = islandInfo === undefined && markersAt(node.start)
475
+ const onlyComp = onRaw !== undefined && islandInfo === undefined && meaningfulChildren.length === 1 && meaningfulChildren[0]!.type === 'JSXElement' && isComponentTag(jsxTagName(meaningfulChildren[0]!.openingElement.name)) ? meaningfulChildren[0]! : undefined
476
+ const childExpr = onlyComp !== undefined
477
+ ? compileComponentRaw(env, onlyComp, jsxTagName(onlyComp.openingElement.name))
478
+ : hasChildren ? compileChildrenListToStringExpr(env, childNodes, childMarkers, childMarkers && (meaningfulChildren.length > 1 || isSingleLoopChild(meaningfulChildren, jsxNodes))) : '""'
479
+
480
+ if (islandInfo !== undefined) {
481
+ const target = onRaw !== undefined ? new StringParts() : parts
482
+ emitIsland({ use, nextId, markersAt }, { island: islandInfo, tag, call, start: node.start, propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate, hasChildren, childExpr, childrenHaveAwait }, target)
483
+ if (onRaw !== undefined)
484
+ onRaw(`${use('raw')}(${target.toExpr()})`)
485
+ return
486
+ }
487
+
488
+ const emitOut = (expr: string): void => {
489
+ if (onRaw !== undefined)
490
+ onRaw(expr)
491
+ else
492
+ parts.pushExpr(`${use('ssrChild')}(${expr})`)
493
+ }
494
+ const wrappedChild = onlyComp !== undefined ? childExpr : `${use('raw')}(${childExpr})`
495
+ const childrenHaveDynamic = hasChildren && childNodes.some(c => env.dynamicChildNodes.has(c))
496
+
497
+ // Lazy memoized getter for non-async dynamic/component children so Providers & context components run before their children!
498
+ if (childrenHaveDynamic && !childrenHaveAwait) {
499
+ const cVar = `_c${nextId()}`
500
+ const propsWithGetter = [...propEntries, `get children() { return ${cVar} === undefined ? (${cVar} = ${wrappedChild}) : ${cVar} }`].join(', ')
501
+ emitOut(`${call}((() => { let ${cVar}; return { ${propsWithGetter} }; })())`)
502
+ return
503
+ }
504
+
505
+ if (hasChildren)
506
+ propEntries.push(`children: ${wrappedChild}`)
507
+
508
+ const propsObj = propEntries.length > 0 ? `{ ${propEntries.join(', ')} }` : '{}'
509
+ emitOut(`${call}(${propsObj})`)
510
+ }