prunelle 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  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/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,69 @@
1
+ // The SSR compiler's emission of `<Suspense>` and `<Catch>`, whose children must reach the component unrendered.
2
+
3
+ import type { JSXChild, JSXElement, JSXFragment, Node } from 'oxc-parser'
4
+ import type { StringParts } from './ssr-helpers'
5
+ import { cleanJsxText, decodeHtmlEntities, filterMeaningfulChildren, isComponentTag, isJsxNode, jsxTagName, matchJsxMapCall } from './shared'
6
+
7
+ /** What the two emitters borrow from the running `compileSsr()`. */
8
+ export interface PrunelleTagEmitter {
9
+ use: (name: string) => string
10
+ compileSubExpression: (node: Node) => string
11
+ compileChildren: (children: readonly JSXChild[], slotMarkers?: boolean, inFragment?: boolean) => string
12
+ compileJsx: (node: JSXElement | JSXFragment) => string
13
+ compileComponentRaw: (node: JSXElement, tag: string) => string
14
+ markersAt: (offset: number) => boolean
15
+ directAwaitNodes: WeakSet<Node>
16
+ jsxNodes: WeakSet<Node>
17
+ }
18
+
19
+ // `<Suspense fallback={...}><AsyncComp .../></Suspense>` passes the raw component call or Promise.
20
+ export function emitSuspense(em: PrunelleTagEmitter, node: JSXElement, tag: string, propEntries: string[], parts: StringParts, onRaw?: (expr: string) => void): void {
21
+ const meaningful = filterMeaningfulChildren(node.children)
22
+ const only = meaningful.length === 1 ? meaningful[0]! : undefined
23
+ if (only?.type === 'JSXElement' && isComponentTag(jsxTagName(only.openingElement.name))) {
24
+ propEntries.push(`children: ${em.compileComponentRaw(only, jsxTagName(only.openingElement.name))}`)
25
+ }
26
+ else if (only?.type === 'JSXExpressionContainer' && only.expression.type !== 'JSXEmptyExpression') {
27
+ propEntries.push(`children: ${em.compileSubExpression(only.expression)}`)
28
+ }
29
+ else if (only?.type === 'JSXText') {
30
+ propEntries.push(`children: ${JSON.stringify(decodeHtmlEntities(cleanJsxText(only.value)))}`)
31
+ }
32
+ else if (only !== undefined && isJsxNode(only)) {
33
+ propEntries.push(`children: ${em.use('raw')}(${em.compileJsx(only)})`)
34
+ }
35
+ const propsObj = propEntries.length > 0 ? `{ ${propEntries.join(', ')} }` : '{}'
36
+ const callExpr = `${tag}(${propsObj})`
37
+ if (onRaw !== undefined)
38
+ onRaw(callExpr)
39
+ else
40
+ parts.pushExpr(`${em.use('ssrChild')}(${callExpr})`)
41
+ }
42
+
43
+ // `<Catch>` reads its children inside a try, so they reach it as a getter even when static; in an island it renders in a range of its own, which the browser swaps.
44
+ export function emitCatch(em: PrunelleTagEmitter, node: JSXElement, tag: string, propEntries: string[], parts: StringParts, onRaw?: (expr: string) => void): void {
45
+ const meaningful = filterMeaningfulChildren(node.children)
46
+ const awaits = node.children.some(c => em.directAwaitNodes.has(c))
47
+ const markers = onRaw === undefined && em.markersAt(node.start)
48
+ if (meaningful.length > 0) {
49
+ const only = meaningful.length === 1 ? meaningful[0]! : undefined
50
+ let childExpr: string
51
+ if (onRaw !== undefined && only?.type === 'JSXElement' && isComponentTag(jsxTagName(only.openingElement.name))) {
52
+ childExpr = em.compileComponentRaw(only, jsxTagName(only.openingElement.name))
53
+ }
54
+ else {
55
+ const singleLoop = only?.type === 'JSXExpressionContainer' && only.expression.type !== 'JSXEmptyExpression' && matchJsxMapCall(only.expression, em.jsxNodes) !== undefined
56
+ childExpr = `${em.use('raw')}(${em.compileChildren(node.children, markers, markers && (meaningful.length > 1 || singleLoop))})`
57
+ }
58
+ propEntries.push(`get children() { return (${awaits ? `(async () => ${childExpr})()` : childExpr}) }`)
59
+ }
60
+ if (markers)
61
+ parts.pushStatic('<!--k[-->')
62
+ const callExpr = `${awaits ? 'await ' : ''}${tag}({ ${propEntries.join(', ')} })`
63
+ if (onRaw !== undefined)
64
+ onRaw(callExpr)
65
+ else
66
+ parts.pushExpr(`${em.use('ssrChild')}(${callExpr})`)
67
+ if (markers)
68
+ parts.pushStatic('<!--k]-->')
69
+ }
@@ -0,0 +1,525 @@
1
+ // Prunelle SSR compiler: compiles TSX directly to flat string concatenation, inline for-loops,
2
+ // static attribute literal folding, compile-time static island props, and shared balanced hydration markers.
3
+
4
+ import type {
5
+ JSXChild,
6
+ JSXElement,
7
+ JSXFragment,
8
+ Node,
9
+ } from 'oxc-parser'
10
+ import type { ModuleAnalysis } from './analyze'
11
+ import type { SelectValueBinding } from './ssr-helpers'
12
+ import type { PrunelleTagEmitter } from './ssr-prunelle-tags'
13
+ import { analyzeModule, getExprContext, parseTsx } from './analyze'
14
+ import { walk } from './ast'
15
+ import { createDevSourceAttr } from './dev-source'
16
+ import { hydrateMistake } from './mistakes'
17
+ import { alignLines, lineMarker, SourceEditor } from './patch'
18
+ import {
19
+ containsJsx,
20
+ decodeHtmlEntities,
21
+ escapeRawText,
22
+ escapeStaticText,
23
+ filterMeaningfulChildren,
24
+ isComponentTag,
25
+ isJsxNode,
26
+ jsxTagName,
27
+ matchJsxMapCall,
28
+ planChildSlots,
29
+ RAW_TEXT_ELEMENTS,
30
+ resolvePrunelleTag,
31
+ unwrapParens,
32
+ VOID_ELEMENTS,
33
+ } from './shared'
34
+ import {
35
+ emitSsrElementAttrs,
36
+ precomputeSsrSubtreeFlags,
37
+ serializeComponentProps,
38
+ staticLiteralOrTemplate,
39
+ StringParts,
40
+ } from './ssr-helpers'
41
+ import { emitIsland } from './ssr-island'
42
+ import { emitCatch, emitSuspense } from './ssr-prunelle-tags'
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
+
118
+ export interface IslandBinding {
119
+ id: string
120
+ chunk: string
121
+ defaultHydrate?: string | undefined
122
+ }
123
+
124
+ export interface CompileSsrOptions {
125
+ islands?: ReadonlyMap<string, IslandBinding> | undefined
126
+ isIsland?: boolean | undefined
127
+ /** Hydration markers everywhere, nowhere, or only inside these source spans. */
128
+ emitMarkers?: boolean | readonly (readonly [number, number])[] | undefined
129
+ analysis?: ModuleAnalysis | undefined
130
+ /** Project root for dev-only `data-pru-src="file:line:col"` attributes; omit in production. */
131
+ devSourceRoot?: string | undefined
132
+ }
133
+
134
+ export interface CompileResult {
135
+ code: string
136
+ analysis: ModuleAnalysis
137
+ }
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
+
166
+ function markerTest(markers: NonNullable<CompileSsrOptions['emitMarkers']>): (offset: number) => boolean {
167
+ return typeof markers === 'boolean' ? () => markers : offset => markers.some(([start, end]) => offset >= start && offset < end)
168
+ }
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
+
227
+ export function compileSsr(filename: string, code: string, options: CompileSsrOptions = {}): CompileResult {
228
+ const program = options.analysis?.program ?? parseTsx(filename, code)
229
+ const analysis = options.analysis ?? analyzeModule(filename, code, program)
230
+
231
+ if (!analysis.hasJsx)
232
+ return { code, analysis }
233
+
234
+ const editor = new SourceEditor(code)
235
+ // 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
+ const mark = lineMarker(code)
237
+ const used = new Set<string>()
238
+ let loopCounter = 0
239
+ let activeSelectValue: SelectValueBinding | undefined
240
+
241
+ const use = (name: string): string => {
242
+ used.add(name)
243
+ return `__${name}`
244
+ }
245
+
246
+ const islands = options.islands
247
+ const devSrc = createDevSourceAttr(filename, code, options.devSourceRoot)
248
+ const markersAt = markerTest(options.emitMarkers ?? options.isIsland ?? analysis.isInteractive)
249
+ const jsxNodes = analysis.jsxNodes
250
+ const exprContext = getExprContext(analysis)
251
+ const { directAwaitNodes, dynamicChildNodes } = precomputeSsrSubtreeFlags(program)
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
257
+ }
258
+ const prunelleTags: PrunelleTagEmitter = { use, compileSubExpression, compileChildren: compileChildrenListToStringExpr, compileJsx: compileJsxToStringExpr, compileComponentRaw, markersAt, directAwaitNodes, jsxNodes }
259
+
260
+ function compileChildrenListToStringExpr(children: readonly JSXChild[], slotMarkers = markersAt(children[0]?.start ?? 0), inFragment = false, rawTextTag?: 'style' | 'script'): string {
261
+ const bufVar = `_o${loopCounter++}`
262
+ const stmts: string[] = []
263
+ const parts = new StringParts()
264
+ const flush = () => flushStringParts(bufVar, parts, stmts)
265
+ emitChildrenIntoBuffer(children, bufVar, parts, flush, s => stmts.push(s), rawTextTag, slotMarkers, inFragment)
266
+ if (stmts.length === 0)
267
+ return parts.toExpr()
268
+ flush()
269
+ const hasAwait = children.some(c => directAwaitNodes.has(c))
270
+ if (hasAwait)
271
+ return `(await (async () => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })())`
272
+ return `(() => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })()`
273
+ }
274
+
275
+ // Emits JSX directly into a string accumulator variable `_out` (zero closures on nested `.map()` loops!)
276
+ function emitIntoBuffer(node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void, actionOverride?: { node: Node, ident: string }): void {
277
+ if (node.type === 'JSXFragment') {
278
+ emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, undefined, markersAt(node.start), true)
279
+ return
280
+ }
281
+
282
+ const tag = jsxTagName(node.openingElement.name)
283
+ if (isComponentTag(tag)) {
284
+ emitComponent(node, tag, parts)
285
+ return
286
+ }
287
+
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)}`)
297
+ const isTextarea = tag === 'textarea'
298
+ const isSelect = tag === 'select'
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)
303
+ parts.pushStatic('>')
304
+ if (VOID_ELEMENTS.has(tag))
305
+ return
306
+
307
+ const prevSelectValue = activeSelectValue
308
+ if (isSelect)
309
+ activeSelectValue = nextSelectValue
310
+
311
+ try {
312
+ if (innerHtmlExpr !== undefined)
313
+ parts.pushExpr(innerHtmlExpr)
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})`)
316
+ else if (tag === 'style') {
317
+ const styleExpr = compileChildrenListToStringExpr(node.children, false, false, 'style')
318
+ if (styleExpr !== '""')
319
+ parts.pushExpr(`${use('ssrStyleBlock')}(${styleExpr})`)
320
+ }
321
+ else
322
+ emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
323
+ }
324
+ finally {
325
+ activeSelectValue = prevSelectValue
326
+ }
327
+ if (actionOverride === undefined)
328
+ parts.pushStatic(`</${tag}>`)
329
+ }
330
+
331
+ function emitChildrenIntoBuffer(
332
+ children: readonly JSXChild[],
333
+ bufVar: string,
334
+ parts: StringParts,
335
+ flushParts: () => void,
336
+ pushStmt: (stmt: string) => void,
337
+ rawTextTag?: 'style' | 'script',
338
+ slotMarkers = markersAt(children[0]?.start ?? 0),
339
+ inFragment = false,
340
+ ): void {
341
+ const planned = planChildSlots(children, { jsxNodes, exprContext, emitMarkers: slotMarkers, inFragment })
342
+
343
+ for (const { child, slot, open, close } of planned) {
344
+ if (slot.kind === 'static-text') {
345
+ if (rawTextTag !== undefined)
346
+ parts.pushStatic(escapeRawText(slot.text, rawTextTag))
347
+ else
348
+ parts.pushStatic(escapeStaticText(slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text)))
349
+ continue
350
+ }
351
+
352
+ if (rawTextTag !== undefined) {
353
+ if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression') {
354
+ const expr = child.expression
355
+ if (expr.type === 'TemplateLiteral' && expr.expressions.length === 0 && expr.quasis.length === 1) {
356
+ const cooked = expr.quasis[0]?.value.cooked
357
+ if (typeof cooked === 'string') {
358
+ parts.pushStatic(escapeRawText(cooked, rawTextTag))
359
+ continue
360
+ }
361
+ }
362
+ parts.pushExpr(`${use('ssrRawText')}(${JSON.stringify(rawTextTag)}, ${compileSubExpression(expr)})`)
363
+ continue
364
+ }
365
+ }
366
+
367
+ if (slot.kind === 'element') {
368
+ emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
369
+ continue
370
+ }
371
+
372
+ if (open !== '')
373
+ parts.pushStatic(open)
374
+
375
+ if (slot.kind === 'component' || slot.kind === 'fragment') {
376
+ emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
377
+ }
378
+ else if (slot.kind === 'loop') {
379
+ const { match } = slot
380
+ const itemParam = match.params[0]?.type === 'Identifier' ? match.params[0].name : undefined
381
+ const idxParam = match.params[1]?.type === 'Identifier' ? match.params[1].name : undefined
382
+
383
+ if (match.isJsxBody && itemParam !== undefined && match.params.length <= 2 && (match.params.length < 2 || idxParam !== undefined)) {
384
+ flushParts()
385
+ const n = loopCounter++
386
+ const arrVar = `_a${n}`
387
+ const idxVar = idxParam ?? `_i${n}`
388
+ const innerStmts: string[] = []
389
+ const innerParts = new StringParts()
390
+ const flushInner = () => flushStringParts(bufVar, innerParts, innerStmts)
391
+ emitIntoBuffer(match.body as JSXElement | JSXFragment, bufVar, innerParts, flushInner, s => innerStmts.push(s))
392
+ flushInner()
393
+
394
+ const target = compileSubExpression(match.target)
395
+ pushStmt(
396
+ `const ${arrVar} = ${target}; if (${arrVar}) for (let ${idxVar} = 0; ${idxVar} < ${arrVar}.length; ${idxVar}++) { const ${itemParam} = ${arrVar}[${idxVar}]; ${innerStmts.join(' ')} }`,
397
+ )
398
+ }
399
+ else if (match.isJsxBody) {
400
+ const target = compileSubExpression(match.target)
401
+ const params = match.params.map(p => compileSubExpression(p)).join(', ')
402
+ parts.pushExpr(`${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(match.body as JSXElement | JSXFragment)})`)
403
+ }
404
+ else {
405
+ parts.pushExpr(`${use('esc')}(${compileSubExpression(match.call)})`)
406
+ }
407
+ }
408
+ else if (slot.kind === 'and-show') {
409
+ const left = compileSubExpression(slot.expr.left)
410
+ const right = compileJsxToStringExpr(slot.right)
411
+ parts.pushExpr(`((${left}) ? (${right}) : "")`)
412
+ }
413
+ else if (slot.kind === 'ternary-show') {
414
+ const test = compileSubExpression(slot.expr.test)
415
+ const cons = compileExpressionAsString(slot.cons)
416
+ const alt = compileExpressionAsString(slot.alt)
417
+ parts.pushExpr(`((${test}) ? (${cons}) : (${alt}))`)
418
+ }
419
+ else {
420
+ parts.pushExpr(`${use('esc')}(${compileSubExpression(slot.expr)})`)
421
+ }
422
+
423
+ if (close !== '')
424
+ parts.pushStatic(close)
425
+ }
426
+ }
427
+
428
+ const compileExpressionAsString = (expr: Node): string => compileSsrExprAsString(expr, use, compileSubExpression, compileJsxToStringExpr)
429
+
430
+ function emitComponent(node: JSXElement, tag: string, parts: StringParts, onRaw?: (expr: string) => void): void {
431
+ const { propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate } = serializeComponentProps(node.openingElement.attributes, compileSubExpression)
432
+ const childNodes = node.children
433
+ const meaningfulChildren = filterMeaningfulChildren(childNodes)
434
+ const hasChildren = meaningfulChildren.length > 0
435
+ // The call sits on the line of its tag, so a component that throws names that line in the caller's frame.
436
+ const call = `${mark(node.start)}${tag}`
437
+
438
+ const prunelleTag = resolvePrunelleTag(tag, analysis.imports)
439
+ if (prunelleTag === 'Suspense' || prunelleTag === 'Catch') {
440
+ ;(prunelleTag === 'Suspense' ? emitSuspense : emitCatch)(prunelleTags, node, tag, propEntries, parts, onRaw)
441
+ return
442
+ }
443
+
444
+ const islandInfo = islands?.get(tag)
445
+ if (islandInfo === undefined && islands !== undefined && hydrateExpr !== undefined)
446
+ throw hydrateMistake(tag, filename, true)
447
+
448
+ const childrenHaveAwait = hasChildren && childNodes.some(c => directAwaitNodes.has(c))
449
+ const childMarkers = islandInfo === undefined && markersAt(node.start)
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))) : '""'
454
+
455
+ if (islandInfo !== undefined) {
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()})`)
460
+ return
461
+ }
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})`
470
+ const childrenHaveDynamic = hasChildren && childNodes.some(c => dynamicChildNodes.has(c))
471
+
472
+ // Lazy memoized getter for non-async dynamic/component children so Providers & context components run before their children!
473
+ if (childrenHaveDynamic && !childrenHaveAwait) {
474
+ const cVar = `_c${loopCounter++}`
475
+ const propsWithGetter = [...propEntries, `get children() { return ${cVar} === undefined ? (${cVar} = ${wrappedChild}) : ${cVar} }`].join(', ')
476
+ emitOut(`${call}((() => { let ${cVar}; return { ${propsWithGetter} }; })())`)
477
+ return
478
+ }
479
+
480
+ if (hasChildren)
481
+ propEntries.push(`children: ${wrappedChild}`)
482
+
483
+ const propsObj = propEntries.length > 0 ? `{ ${propEntries.join(', ')} }` : '{}'
484
+ emitOut(`${call}(${propsObj})`)
485
+ }
486
+
487
+ function compileJsxToStringExpr(node: JSXElement | JSXFragment): string {
488
+ const bufVar = `_o${loopCounter++}`
489
+ const stmts: string[] = []
490
+ const parts = new StringParts()
491
+
492
+ const flush = () => flushStringParts(bufVar, parts, stmts)
493
+
494
+ emitIntoBuffer(node, bufVar, parts, flush, s => stmts.push(s))
495
+
496
+ // If no inline `for` statements were emitted, stay a pure flat concatenation expression!
497
+ if (stmts.length === 0)
498
+ return parts.toExpr()
499
+
500
+ flush()
501
+ if (directAwaitNodes.has(node))
502
+ return `(await (async () => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })())`
503
+ return `(() => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })()`
504
+ }
505
+
506
+ function compileRootJsx(node: JSXElement | JSXFragment): string {
507
+ return `${use('raw')}(${compileJsxToStringExpr(node)})`
508
+ }
509
+
510
+ walk(program, (node) => {
511
+ if (isJsxNode(node)) {
512
+ editor.replace(node.start, node.end, compileRootJsx(node) + mark(node.end))
513
+ return false
514
+ }
515
+ return undefined
516
+ })
517
+
518
+ if (used.size > 0) {
519
+ const specifiers = [...used].sort().map(name => `${name} as __${name}`).join(', ')
520
+ // Last, where it moves no line: an import is hoisted wherever it is written.
521
+ editor.append(`\nimport { ${specifiers} } from 'prunelle/internal/ssr';\n`)
522
+ }
523
+
524
+ return { code: alignLines(editor.toString()), analysis }
525
+ }