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,97 @@
1
+ // Zero-dependency span patcher (replaces magic-string for fast TSX AST transforms).
2
+
3
+ interface Patch {
4
+ start: number
5
+ end: number
6
+ text: string
7
+ }
8
+
9
+ export class SourceEditor {
10
+ readonly #source: string
11
+ readonly #patches: Patch[] = []
12
+ readonly #prepends: string[] = []
13
+ readonly #appends: string[] = []
14
+
15
+ constructor(source: string) {
16
+ this.#source = source
17
+ }
18
+
19
+ replace(start: number, end: number, text: string): void {
20
+ this.#patches.push({ start, end, text })
21
+ }
22
+
23
+ remove(start: number, end: number): void {
24
+ this.#patches.push({ start, end, text: '' })
25
+ }
26
+
27
+ prepend(text: string): void {
28
+ this.#prepends.push(text)
29
+ }
30
+
31
+ append(text: string): void {
32
+ this.#appends.push(text)
33
+ }
34
+
35
+ toString(): string {
36
+ const patches = this.#patches.slice().sort((a, b) => a.start - b.start || a.end - b.end)
37
+ let out = this.#prepends.join('')
38
+ let cursor = 0
39
+
40
+ for (let i = 0; i < patches.length; i++) {
41
+ const p = patches[i]!
42
+ if (p.start < cursor)
43
+ throw new Error(`prunelle compiler: overlapping source patch [${p.start}, ${p.end}] overlaps previous end ${cursor}`)
44
+ out += this.#source.slice(cursor, p.start)
45
+ out += p.text
46
+ cursor = p.end
47
+ }
48
+
49
+ out += this.#source.slice(cursor)
50
+ if (this.#appends.length > 0)
51
+ out += this.#appends.join('')
52
+ return out
53
+ }
54
+ }
55
+
56
+ // A mark holds a source line inside generated code; `alignLines` turns it into the newlines that put the code after it back on that line.
57
+ const LINE_MARK_RE = /\/\*\x01(\d+)\*\//g
58
+
59
+ /** Marks the source line of an offset, for code spliced where a newline is allowed (an expression's start, never after `return`). */
60
+ export function lineMarker(source: string): (offset: number) => string {
61
+ let starts: number[] | undefined
62
+ return (offset) => {
63
+ if (starts === undefined) {
64
+ starts = [0]
65
+ for (let i = source.indexOf('\n'); i !== -1; i = source.indexOf('\n', i + 1))
66
+ starts.push(i + 1)
67
+ }
68
+ let lo = 0
69
+ let hi = starts.length - 1
70
+ while (lo < hi) {
71
+ const mid = (lo + hi + 1) >> 1
72
+ if (starts[mid]! <= offset)
73
+ lo = mid
74
+ else
75
+ hi = mid - 1
76
+ }
77
+ return `/*\x01${lo + 1}*/`
78
+ }
79
+ }
80
+
81
+ /** Replaces each line mark with the newlines that bring the code after it down to its source line, so a stack trace names the line it was written on. */
82
+ export function alignLines(code: string): string {
83
+ if (!code.includes('\x01'))
84
+ return code
85
+ let line = 1
86
+ let last = 0
87
+ return code.replace(LINE_MARK_RE, (mark: string, target: string, at: number) => {
88
+ for (let i = code.indexOf('\n', last); i !== -1 && i < at; i = code.indexOf('\n', i + 1))
89
+ line++
90
+ last = at + mark.length
91
+ const pad = Number(target) - line
92
+ if (pad <= 0)
93
+ return ''
94
+ line += pad
95
+ return '\n'.repeat(pad)
96
+ })
97
+ }
@@ -0,0 +1,60 @@
1
+ // Warns on `const { a } = props` in a component that runs in the browser: only a destructured parameter is rewritten to stay reactive, and a read of stable objects in the body can be meant.
2
+
3
+ import type { Function as FunctionNode, Node, Program } from 'oxc-parser'
4
+ import type { CompilerWarning } from './mistakes'
5
+ import { containsJsx, unwrapTsExpr } from './shared'
6
+
7
+ function isFunction(node: Node | null | undefined): node is FunctionNode {
8
+ return node !== null && node !== undefined && (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression')
9
+ }
10
+
11
+ // The functions a top-level statement declares: `function C`, `export default function`, `const C = () => ...`.
12
+ function declaredFunctions(stmt: Node): FunctionNode[] {
13
+ const decl = stmt.type === 'ExportNamedDeclaration' || stmt.type === 'ExportDefaultDeclaration' ? stmt.declaration : stmt
14
+ if (decl === null || decl === undefined)
15
+ return []
16
+ if (isFunction(decl))
17
+ return [decl]
18
+ if (decl.type !== 'VariableDeclaration')
19
+ return []
20
+ const found: FunctionNode[] = []
21
+ for (const d of decl.declarations) {
22
+ const init = d.init === null ? undefined : unwrapTsExpr(d.init)
23
+ if (isFunction(init))
24
+ found.push(init)
25
+ }
26
+ return found
27
+ }
28
+
29
+ /** Warns on a top-level statement of a browser component's body that destructures its first parameter, with the parameter form as the fix. */
30
+ export function checkBodyPropsDestructure(
31
+ program: Program,
32
+ code: string,
33
+ browserSpans: readonly [number, number][],
34
+ jsxNodes: WeakSet<Node>,
35
+ filename: string,
36
+ warnings: CompilerWarning[],
37
+ ): void {
38
+ if (browserSpans.length === 0)
39
+ return
40
+ for (const stmt of program.body) {
41
+ for (const fn of declaredFunctions(stmt)) {
42
+ if (!browserSpans.some(([s, e]) => fn.start >= s && fn.end <= e))
43
+ continue
44
+ const rawParam = fn.params[0]
45
+ const param = rawParam?.type === 'AssignmentPattern' ? rawParam.left : rawParam
46
+ if (param?.type !== 'Identifier' || fn.body?.type !== 'BlockStatement' || !containsJsx(fn.body, jsxNodes))
47
+ continue
48
+ for (const inner of fn.body.body) {
49
+ if (inner.type !== 'VariableDeclaration')
50
+ continue
51
+ for (const d of inner.declarations) {
52
+ const init = d.init === null ? undefined : unwrapTsExpr(d.init)
53
+ if (d.id.type !== 'ObjectPattern' || init?.type !== 'Identifier' || init.name !== param.name)
54
+ continue
55
+ warnings.push({ start: d.start, message: `prunelle compiler: \`${inner.kind} ${code.slice(d.start, d.end)}\` in ${filename} reads the props once, so a change to them never reaches this component: destructure in the parameter list, (${code.slice(d.id.start, d.id.end)}), which stays reactive, or read props.<name> where it is used.` })
56
+ }
57
+ }
58
+ }
59
+ }
60
+ }
@@ -0,0 +1,511 @@
1
+ // Compiles a component's destructured props: reads stay reactive through `__p`, and the function is rewritten around it.
2
+
3
+ import type { ArrowFunctionExpression, Function as OxcFunction, Node, ObjectPattern, ParamPattern } from 'oxc-parser'
4
+ import { walk } from './ast'
5
+ import { SourceEditor } from './patch'
6
+ import { collectMutatedNames, isSafeLazyJsxRef, referencesAny } from './scope'
7
+ import { collectPatternNames, containsJsx, isJsxNode, unwrapParens, unwrapTsExpr } from './shared'
8
+
9
+ function isReactiveDefault(node: Node, running: ReadonlyMap<string, string>): boolean {
10
+ if (running.size > 0 && referencesAny(node, new Set(running.keys())))
11
+ return true
12
+ let readsValue = false
13
+ walk(node, (child) => {
14
+ if (readsValue)
15
+ return false
16
+ if (child.type === 'ArrowFunctionExpression' || child.type === 'FunctionExpression' || child.type === 'FunctionDeclaration')
17
+ return false
18
+ if (child.type === 'MemberExpression' && !child.computed && child.property.type === 'Identifier' && child.property.name === 'value') {
19
+ readsValue = true
20
+ return false
21
+ }
22
+ return undefined
23
+ })
24
+ return readsValue
25
+ }
26
+
27
+ function patchParamDefaults(
28
+ param: Node | null | undefined,
29
+ rewrites: ReadonlyMap<string, string>,
30
+ targetEditor: SourceEditor,
31
+ offset: number,
32
+ compileExpression: (node: Node, rewrites: ReadonlyMap<string, string>) => string,
33
+ ): void {
34
+ if (param === null || param === undefined)
35
+ return
36
+ switch (param.type) {
37
+ case 'AssignmentPattern':
38
+ patchParamDefaults(param.left, rewrites, targetEditor, offset, compileExpression)
39
+ targetEditor.replace(param.right.start - offset, param.right.end - offset, compileExpression(param.right, rewrites))
40
+ return
41
+ case 'RestElement':
42
+ patchParamDefaults(param.argument, rewrites, targetEditor, offset, compileExpression)
43
+ return
44
+ case 'TSParameterProperty':
45
+ patchParamDefaults(param.parameter, rewrites, targetEditor, offset, compileExpression)
46
+ return
47
+ case 'ArrayPattern': {
48
+ let cur = rewrites
49
+ for (const el of param.elements) {
50
+ patchParamDefaults(el, cur, targetEditor, offset, compileExpression)
51
+ if (el !== null)
52
+ cur = withoutBindings(cur, [el])
53
+ }
54
+ return
55
+ }
56
+ case 'ObjectPattern': {
57
+ let cur = rewrites
58
+ for (const prop of param.properties) {
59
+ if (prop.type === 'RestElement') {
60
+ patchParamDefaults(prop.argument, cur, targetEditor, offset, compileExpression)
61
+ }
62
+ else {
63
+ if (prop.computed)
64
+ targetEditor.replace(prop.key.start - offset, prop.key.end - offset, compileExpression(prop.key, cur))
65
+ patchParamDefaults(prop.value, cur, targetEditor, offset, compileExpression)
66
+ }
67
+ cur = withoutBindings(cur, [prop])
68
+ }
69
+ }
70
+ }
71
+ }
72
+
73
+ export function compileParamList(
74
+ code: string,
75
+ params: readonly ParamPattern[],
76
+ scopeRewrites: ReadonlyMap<string, string>,
77
+ compileExpression: (node: Node, rewrites: ReadonlyMap<string, string>) => string,
78
+ ): string {
79
+ let cur = scopeRewrites
80
+ const out: string[] = []
81
+ for (const p of params) {
82
+ const sub = new SourceEditor(code.slice(p.start, p.end))
83
+ patchParamDefaults(p, cur, sub, p.start, compileExpression)
84
+ out.push(sub.toString())
85
+ cur = withoutBindings(cur, [p])
86
+ }
87
+ return out.join(', ')
88
+ }
89
+
90
+ export function withoutBindings(rewrites: ReadonlyMap<string, string>, patterns: readonly Node[]): Map<string, string> {
91
+ const names = new Set<string>()
92
+ for (const pattern of patterns)
93
+ collectPatternNames(pattern, names)
94
+ const kept = new Map(rewrites)
95
+ for (const name of names)
96
+ kept.delete(name)
97
+ return kept
98
+ }
99
+
100
+ /** True when a JSX prop expression is statically stable (non-rewritten identifier, literal, function, or constant array/object) and needs no reactive getter. */
101
+ export function isStaticPropExpr(rawNode: Node, scopeRewrites: ReadonlyMap<string, string>): boolean {
102
+ const node = unwrapTsExpr(rawNode)
103
+ switch (node.type) {
104
+ case 'Literal':
105
+ case 'ArrowFunctionExpression':
106
+ case 'FunctionExpression':
107
+ return true
108
+ case 'Identifier':
109
+ return !scopeRewrites.has(node.name)
110
+ case 'UnaryExpression':
111
+ return (node.operator === '-' || node.operator === '+' || node.operator === '!' || node.operator === '~' || node.operator === 'void')
112
+ && isStaticPropExpr(node.argument, scopeRewrites)
113
+ case 'TemplateLiteral':
114
+ return node.expressions.every(e => isStaticPropExpr(e, scopeRewrites))
115
+ case 'ArrayExpression':
116
+ return node.elements.every(el => el === null || (el.type !== 'SpreadElement' && isStaticPropExpr(el, scopeRewrites)))
117
+ case 'ObjectExpression':
118
+ return node.properties.every((prop) => {
119
+ if (prop.type !== 'Property' || prop.kind !== 'init')
120
+ return false
121
+ if (prop.computed && !isStaticPropExpr(prop.key, scopeRewrites))
122
+ return false
123
+ return isStaticPropExpr(prop.value, scopeRewrites)
124
+ })
125
+ default:
126
+ return false
127
+ }
128
+ }
129
+
130
+ export interface DestructuredParam {
131
+ pattern: ObjectPattern
132
+ defaultExpr: Node | undefined
133
+ replaceStart: number
134
+ replaceEnd: number
135
+ typeAnn: string
136
+ }
137
+
138
+ export interface PropCompilerContext {
139
+ code: string
140
+ editor: SourceEditor
141
+ jsxNodes: WeakSet<Node>
142
+ use: (name: string) => string
143
+ freshVar: (prefix?: string) => string
144
+ compileExpression: (node: Node, rewrites: ReadonlyMap<string, string>) => string
145
+ }
146
+
147
+ export interface PropCompiler {
148
+ patternReads: (pattern: Node, source: string, outerRewrites: ReadonlyMap<string, string>, hoisted?: string[]) => Map<string, string>
149
+ compileLoopRow: (opts: {
150
+ firstParam: ParamPattern | undefined
151
+ idxParam: string | undefined
152
+ keyAst: Node | undefined
153
+ rowSig: string
154
+ scopeRewrites: ReadonlyMap<string, string>
155
+ keyRewrites: ReadonlyMap<string, string>
156
+ }) => { keyFn: string, rowRewrites: Map<string, string>, prelude: string }
157
+ withPrelude: (compiledBody: string, body: Node, prelude: string) => string
158
+ extractDestructuredParam: (firstParam: ParamPattern | undefined) => DestructuredParam | undefined
159
+ buildCompiledFunction: (fn: ArrowFunctionExpression | OxcFunction, outerRewrites: ReadonlyMap<string, string>) => string
160
+ processFunction: (fn: ArrowFunctionExpression | OxcFunction) => void
161
+ }
162
+
163
+ export function createPropCompiler(ctx: PropCompilerContext): PropCompiler {
164
+ const { code, editor, jsxNodes, use, freshVar, compileExpression } = ctx
165
+
166
+ // How each name a destructuring pattern binds is read from `source` on every access, so reads stay reactive.
167
+ // With `hoisted`, a default (at any nesting depth) and a nested pattern's getter become statements for the start of the body (evaluated once per call/row) instead of running on every read.
168
+ function patternReads(pattern: Node, source: string, outerRewrites: ReadonlyMap<string, string>, hoisted?: string[]): Map<string, string> {
169
+ const reads = new Map<string, string>()
170
+ const running = new Map(outerRewrites)
171
+ const hoist = (init: string): string => {
172
+ const name = freshVar('__d')
173
+ hoisted!.push(`const ${name} = ${init};`)
174
+ return name
175
+ }
176
+
177
+ function bindPattern(pat: Node, src: string): void {
178
+ if (pat.type === 'Identifier') {
179
+ reads.set(pat.name, src)
180
+ running.set(pat.name, src)
181
+ return
182
+ }
183
+ if (pat.type === 'AssignmentPattern') {
184
+ const defExpr = compileExpression(pat.right, running)
185
+ const simpleDef = pat.right.type === 'Literal' || pat.right.type === 'Identifier'
186
+ const reactiveDef = !simpleDef && !containsJsx(pat.right, jsxNodes) && isReactiveDefault(pat.right, running)
187
+ let fallback = simpleDef ? defExpr : `(${defExpr})`
188
+ if (!simpleDef && !reactiveDef && hoisted !== undefined)
189
+ fallback = `${hoist(`${use('propDefault')}(() => (${defExpr}), ${src} === undefined)`)}()`
190
+ let nextSrc: string
191
+ if (pat.left.type !== 'Identifier' && hoisted !== undefined) {
192
+ const v = freshVar('__v')
193
+ nextSrc = `${hoist(`() => { const ${v} = ${src}; return ${v} === undefined ? ${fallback} : ${v}; }`)}()`
194
+ }
195
+ else {
196
+ nextSrc = `(${src} === undefined ? ${fallback} : ${src})`
197
+ }
198
+ bindPattern(pat.left, nextSrc)
199
+ return
200
+ }
201
+ if (pat.type === 'ObjectPattern') {
202
+ const excludedKeys: string[] = []
203
+ let canOmit = hoisted !== undefined
204
+ for (const prop of pat.properties) {
205
+ if (prop.type === 'RestElement') {
206
+ if (canOmit) {
207
+ const restRead = `${use('omit')}(${src}, [${excludedKeys.join(', ')}])`
208
+ bindPattern(prop.argument, restRead)
209
+ }
210
+ continue
211
+ }
212
+ let propSrc: string | undefined
213
+ if (!prop.computed && prop.key.type === 'Identifier') {
214
+ excludedKeys.push(JSON.stringify(prop.key.name))
215
+ propSrc = `${src}.${prop.key.name}`
216
+ }
217
+ else if (!prop.computed && prop.key.type === 'Literal' && (typeof prop.key.value === 'string' || typeof prop.key.value === 'number')) {
218
+ excludedKeys.push(JSON.stringify(String(prop.key.value)))
219
+ propSrc = `${src}[${JSON.stringify(prop.key.value)}]`
220
+ }
221
+ else if (prop.computed && hoisted !== undefined) {
222
+ const keyVar = hoist(compileExpression(prop.key, running))
223
+ excludedKeys.push(`typeof ${keyVar} === 'symbol' ? ${keyVar} : String(${keyVar})`)
224
+ propSrc = `${src}[${keyVar}]`
225
+ }
226
+ else {
227
+ canOmit = false
228
+ }
229
+ if (propSrc !== undefined)
230
+ bindPattern(prop.value, propSrc)
231
+ }
232
+ return
233
+ }
234
+ if (pat.type === 'ArrayPattern') {
235
+ for (let i = 0; i < pat.elements.length; i++) {
236
+ const el = pat.elements[i]
237
+ if (el == null)
238
+ continue
239
+ if (el.type === 'RestElement')
240
+ bindPattern(el.argument, `Array.from(${src}).slice(${i})`)
241
+ else
242
+ bindPattern(el, `${src}[${i}]`)
243
+ }
244
+ }
245
+ }
246
+
247
+ bindPattern(pattern, source)
248
+
249
+ const compilePatternSource = (patNode: Node): string => {
250
+ const sub = new SourceEditor(code.slice(patNode.start, patNode.end))
251
+ const base = patNode.start
252
+ const patchPattern = (p: Node | null | undefined): void => {
253
+ if (p === null || p === undefined)
254
+ return
255
+ if ('typeAnnotation' in p && p.typeAnnotation != null) {
256
+ const ann = p.typeAnnotation as Node
257
+ sub.remove(ann.start - base, ann.end - base)
258
+ }
259
+ switch (p.type) {
260
+ case 'AssignmentPattern':
261
+ patchPattern(p.left)
262
+ sub.replace(p.right.start - base, p.right.end - base, compileExpression(p.right, outerRewrites))
263
+ return
264
+ case 'RestElement':
265
+ patchPattern(p.argument)
266
+ return
267
+ case 'ArrayPattern':
268
+ for (const el of p.elements)
269
+ patchPattern(el)
270
+ return
271
+ case 'ObjectPattern':
272
+ for (const prop of p.properties) {
273
+ if (prop.type === 'RestElement') {
274
+ patchPattern(prop.argument)
275
+ }
276
+ else {
277
+ if (prop.computed)
278
+ sub.replace(prop.key.start - base, prop.key.end - base, compileExpression(prop.key, outerRewrites))
279
+ patchPattern(prop.value)
280
+ }
281
+ }
282
+ }
283
+ }
284
+ patchPattern(patNode)
285
+ return sub.toString()
286
+ }
287
+
288
+ const names = new Set<string>()
289
+ collectPatternNames(pattern, names)
290
+ // The pattern a read runs: only the property binding `name`, so another property's default does not run on this read.
291
+ const patternFor = (name: string): string => {
292
+ if (pattern.type === 'ObjectPattern') {
293
+ for (const prop of (pattern as ObjectPattern).properties) {
294
+ const bound = new Set<string>()
295
+ collectPatternNames(prop.type === 'RestElement' ? prop.argument : prop.value, bound)
296
+ if (prop.type === 'Property' && bound.has(name)) {
297
+ const sub = new SourceEditor(code.slice(prop.start, prop.end))
298
+ const base = prop.start
299
+ if (prop.computed)
300
+ sub.replace(prop.key.start - base, prop.key.end - base, compileExpression(prop.key, outerRewrites))
301
+ sub.replace(prop.value.start - base, prop.value.end - base, compilePatternSource(prop.value))
302
+ return `{ ${sub.toString()} }`
303
+ }
304
+ }
305
+ }
306
+ return compilePatternSource(pattern)
307
+ }
308
+ for (const name of names) {
309
+ if (reads.has(name))
310
+ continue
311
+ const getter = `(${patternFor(name)}) => ${name}`
312
+ reads.set(name, hoisted === undefined ? `(${getter})(${source})` : `${hoist(getter)}(${source})`)
313
+ }
314
+ return reads
315
+ }
316
+
317
+ function extractDestructuredParam(firstParam: ParamPattern | undefined): {
318
+ pattern: ObjectPattern
319
+ defaultExpr: Node | undefined
320
+ replaceStart: number
321
+ replaceEnd: number
322
+ typeAnn: string
323
+ } | undefined {
324
+ if (firstParam === undefined)
325
+ return undefined
326
+ if (firstParam.type === 'ObjectPattern') {
327
+ const typeAnn = firstParam.typeAnnotation ? code.slice(firstParam.typeAnnotation.start, firstParam.typeAnnotation.end) : ''
328
+ return { pattern: firstParam, defaultExpr: undefined, replaceStart: firstParam.start, replaceEnd: firstParam.end, typeAnn }
329
+ }
330
+ if (firstParam.type === 'AssignmentPattern' && firstParam.left.type === 'ObjectPattern') {
331
+ const pat = firstParam.left
332
+ const typeAnn = pat.typeAnnotation ? code.slice(pat.typeAnnotation.start, pat.typeAnnotation.end) : ''
333
+ return { pattern: pat, defaultExpr: firstParam.right, replaceStart: firstParam.start, replaceEnd: firstParam.end, typeAnn }
334
+ }
335
+ return undefined
336
+ }
337
+
338
+ function computePropRewrites(
339
+ destructured: { pattern: ObjectPattern, defaultExpr: Node | undefined },
340
+ pVar: string,
341
+ outerRewrites: ReadonlyMap<string, string>,
342
+ body: Node | null,
343
+ ): { rewrites: Map<string, string>, prelude: string } {
344
+ const rewrites = new Map(outerRewrites)
345
+ const hoisted: string[] = []
346
+ const propReads = patternReads(destructured.pattern, pVar, outerRewrites, hoisted)
347
+ const mutated = collectMutatedNames(body, new Set(propReads.keys()))
348
+ for (const [name, read] of propReads) {
349
+ if (mutated.has(name)) {
350
+ // A mutated destructured prop becomes a local `let` binding initialized once, avoiding invalid assignment targets like `(a === undefined ? b : a) = c`.
351
+ hoisted.push(`let ${name} = ${read};`)
352
+ rewrites.delete(name)
353
+ }
354
+ else {
355
+ rewrites.set(name, read)
356
+ }
357
+ }
358
+ return { rewrites, prelude: hoisted.join(' ') }
359
+ }
360
+
361
+ // Puts the hoisted default statements at the start of a body, giving an expression body a block to hold them.
362
+ function withPrelude(compiledBody: string, body: Node, prelude: string): string {
363
+ if (prelude === '')
364
+ return compiledBody
365
+ return body.type === 'BlockStatement' ? `{ ${prelude}${compiledBody.slice(1)}` : `{ ${prelude} return (${compiledBody}); }`
366
+ }
367
+
368
+ function buildCompiledFunction(fn: ArrowFunctionExpression | OxcFunction, outerRewrites: ReadonlyMap<string, string>): string {
369
+ const fnEditor = new SourceEditor(code.slice(fn.start, fn.end))
370
+ const offset = fn.start
371
+ const destructured = extractDestructuredParam(fn.params[0])
372
+ const pVar = freshVar('__p')
373
+ const baseRewrites = new Map(outerRewrites)
374
+ if (fn.type !== 'ArrowFunctionExpression' && fn.id !== null)
375
+ baseRewrites.delete(fn.id.name)
376
+ let propRewrites = baseRewrites
377
+ let prelude = ''
378
+
379
+ if (destructured !== undefined) {
380
+ const defSuffix = destructured.defaultExpr !== undefined
381
+ ? ` = ${compileExpression(destructured.defaultExpr, baseRewrites)}`
382
+ : ''
383
+ fnEditor.replace(destructured.replaceStart - offset, destructured.replaceEnd - offset, `${pVar}${destructured.typeAnn}${defSuffix}`)
384
+ ;({ rewrites: propRewrites, prelude } = computePropRewrites(destructured, pVar, baseRewrites, fn.body))
385
+ }
386
+
387
+ for (let i = 1; i < fn.params.length; i++) {
388
+ const extraParam = fn.params[i]!
389
+ patchParamDefaults(extraParam, propRewrites, fnEditor, offset, compileExpression)
390
+ propRewrites = withoutBindings(propRewrites, [extraParam])
391
+ }
392
+
393
+ if (fn.body !== null)
394
+ fnEditor.replace(fn.body.start - offset, fn.body.end - offset, withPrelude(compileExpression(fn.body, propRewrites), fn.body, prelude))
395
+ return fnEditor.toString()
396
+ }
397
+
398
+ // Handle top-level component functions with destructured props + JSX compilation
399
+ function processFunction(fn: ArrowFunctionExpression | OxcFunction): void {
400
+ if (fn.body === null || !containsJsx(fn.body, jsxNodes))
401
+ return
402
+
403
+ const destructured = extractDestructuredParam(fn.params[0])
404
+ let propRewrites = new Map<string, string>()
405
+ let prelude = ''
406
+
407
+ if (destructured !== undefined) {
408
+ const pVar = '__p'
409
+ const defSuffix = destructured.defaultExpr !== undefined
410
+ ? ` = ${compileExpression(destructured.defaultExpr, new Map())}`
411
+ : ''
412
+ editor.replace(destructured.replaceStart, destructured.replaceEnd, `${pVar}${destructured.typeAnn}${defSuffix}`)
413
+ ;({ rewrites: propRewrites, prelude } = computePropRewrites(destructured, pVar, new Map(), fn.body))
414
+ }
415
+
416
+ for (let i = 1; i < fn.params.length; i++) {
417
+ const extraParam = fn.params[i]!
418
+ patchParamDefaults(extraParam, propRewrites, editor, 0, compileExpression)
419
+ propRewrites = withoutBindings(propRewrites, [extraParam])
420
+ }
421
+
422
+ const hasLazyJsxDecl = fn.body.type === 'BlockStatement' && fn.body.body.some(s =>
423
+ s.type === 'VariableDeclaration' && s.kind === 'const' && s.declarations.length === 1
424
+ && s.declarations[0]!.id.type === 'Identifier' && s.declarations[0]!.init !== null
425
+ && isJsxNode(unwrapParens(s.declarations[0]!.init)),
426
+ )
427
+
428
+ if ((propRewrites.size > 0 || hasLazyJsxDecl) && fn.body.type === 'BlockStatement') {
429
+ if (prelude !== '')
430
+ editor.replace(fn.body.start + 1, fn.body.start + 1, ` ${prelude}`)
431
+ const shadowed = new Set<string>()
432
+ for (const stmt of fn.body.body) {
433
+ if (stmt.type === 'FunctionDeclaration' && stmt.id !== null)
434
+ shadowed.add(stmt.id.name)
435
+ else if (stmt.type === 'ClassDeclaration' && stmt.id !== null)
436
+ shadowed.add(stmt.id.name)
437
+ }
438
+ const stmts = fn.body.body
439
+ for (let i = 0; i < stmts.length; i++) {
440
+ const stmt = stmts[i]!
441
+ const active = new Map<string, string>()
442
+ for (const [k, v] of propRewrites) {
443
+ if (!shadowed.has(k))
444
+ active.set(k, v)
445
+ }
446
+ // Defer `const badge = <span />` to `const badge = () => _t0()` when only used in JSX slots so SSR hydration claims the outer element before the slot's nodes.
447
+ if (
448
+ stmt.type === 'VariableDeclaration' && stmt.kind === 'const' && stmt.declarations.length === 1
449
+ && stmt.declarations[0]!.id.type === 'Identifier' && stmt.declarations[0]!.init !== null
450
+ ) {
451
+ const decl = stmt.declarations[0]!
452
+ const jsxInit = unwrapParens(decl.init!)
453
+ const varName = (decl.id as Extract<Node, { type: 'Identifier' }>).name
454
+ if (isJsxNode(jsxInit) && isSafeLazyJsxRef(varName, stmts.slice(i + 1))) {
455
+ editor.replace(stmt.start, stmt.end, `const ${varName} = () => ${compileExpression(jsxInit, active)};`)
456
+ propRewrites.set(varName, `${varName}()`)
457
+ shadowed.delete(varName)
458
+ continue
459
+ }
460
+ }
461
+ if (active.size > 0 || containsJsx(stmt, jsxNodes))
462
+ editor.replace(stmt.start, stmt.end, compileExpression(stmt, active))
463
+ if (stmt.type === 'VariableDeclaration') {
464
+ for (const d of stmt.declarations)
465
+ collectPatternNames(d.id, shadowed)
466
+ }
467
+ }
468
+ }
469
+ else {
470
+ editor.replace(fn.body.start, fn.body.end, withPrelude(compileExpression(fn.body, propRewrites), fn.body, prelude))
471
+ }
472
+ }
473
+
474
+ function compileLoopRow(opts: {
475
+ firstParam: ParamPattern | undefined
476
+ idxParam: string | undefined
477
+ keyAst: Node | undefined
478
+ rowSig: string
479
+ scopeRewrites: ReadonlyMap<string, string>
480
+ keyRewrites: ReadonlyMap<string, string>
481
+ }): { keyFn: string, rowRewrites: Map<string, string>, prelude: string } {
482
+ const { firstParam, idxParam, keyAst, rowSig, scopeRewrites, keyRewrites } = opts
483
+ const rowRewrites = new Map(scopeRewrites)
484
+ const hoisted: string[] = []
485
+ let keyFn: string
486
+ if (firstParam !== undefined && firstParam.type !== 'Identifier') {
487
+ if (keyAst !== undefined) {
488
+ const keyItem = freshVar('_item')
489
+ const keyScope = new Map(keyRewrites)
490
+ for (const [name, read] of patternReads(firstParam, keyItem, scopeRewrites))
491
+ keyScope.set(name, read)
492
+ keyFn = `(${keyItem}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyScope)}`
493
+ }
494
+ else {
495
+ keyFn = `(_item) => _item`
496
+ }
497
+ for (const [name, read] of patternReads(firstParam, `${rowSig}.value`, scopeRewrites, hoisted))
498
+ rowRewrites.set(name, read)
499
+ }
500
+ else {
501
+ const itemParam = firstParam?.type === 'Identifier' ? firstParam.name : '_item'
502
+ keyFn = keyAst !== undefined
503
+ ? `(${itemParam}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyRewrites)}`
504
+ : `(${itemParam}) => ${itemParam}`
505
+ rowRewrites.set(itemParam, `${rowSig}.value`)
506
+ }
507
+ return { keyFn, rowRewrites, prelude: hoisted.join(' ') }
508
+ }
509
+
510
+ return { patternReads, compileLoopRow, withPrelude, extractDestructuredParam, buildCompiledFunction, processFunction }
511
+ }