prunelle 0.9.0 → 0.10.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 (96) hide show
  1. package/llms.txt +18 -18
  2. package/package.json +2 -2
  3. package/src/a11y/declaration.ts +4 -7
  4. package/src/build/bundle.ts +6 -2
  5. package/src/build/index.ts +3 -1
  6. package/src/build/island-promote.ts +42 -2
  7. package/src/build/islands.ts +59 -8
  8. package/src/build/manifest.ts +98 -0
  9. package/src/build/plugin-host.ts +11 -1
  10. package/src/build/prerender.ts +6 -1
  11. package/src/build/reach.ts +4 -3
  12. package/src/build/resolve.ts +5 -1
  13. package/src/build/routes.ts +18 -0
  14. package/src/cli/check-forms.ts +8 -0
  15. package/src/cli/check-links.ts +14 -5
  16. package/src/cli/check.ts +12 -6
  17. package/src/cli/commands.ts +5 -3
  18. package/src/cli/form-opaque-children.ts +40 -0
  19. package/src/compiler/analyze.ts +20 -14
  20. package/src/compiler/cacheability-private.ts +13 -3
  21. package/src/compiler/compliance-contrast.ts +48 -10
  22. package/src/compiler/compliance-rules.ts +72 -0
  23. package/src/compiler/compliance.ts +6 -66
  24. package/src/compiler/dom-attrs.ts +178 -22
  25. package/src/compiler/dom.ts +31 -44
  26. package/src/compiler/emit.ts +17 -6
  27. package/src/compiler/expr-context.ts +260 -207
  28. package/src/compiler/props-body.ts +263 -21
  29. package/src/compiler/props.ts +155 -5
  30. package/src/compiler/signal-reads.ts +142 -29
  31. package/src/compiler/spread-handlers.ts +25 -13
  32. package/src/compiler/ssr-emit.ts +3 -3
  33. package/src/compiler/ssr-helpers.ts +0 -5
  34. package/src/compiler/ssr.ts +4 -2
  35. package/src/dev/host-check.ts +2 -1
  36. package/src/dev/reload.ts +4 -1
  37. package/src/dom/attrs.ts +93 -25
  38. package/src/dom/extras.ts +89 -49
  39. package/src/dom/field-marks.ts +9 -1
  40. package/src/dom/index.ts +19 -13
  41. package/src/dom/loop.ts +259 -188
  42. package/src/dom/prefetch.ts +4 -1
  43. package/src/dom/regions.ts +25 -8
  44. package/src/dom/swap.ts +11 -10
  45. package/src/dom/trusted.ts +4 -4
  46. package/src/eco/declaration.ts +5 -1
  47. package/src/eco/index.ts +3 -0
  48. package/src/index.ts +3 -2
  49. package/src/plugins/config.ts +1 -1
  50. package/src/plugins/public.ts +4 -0
  51. package/src/plugins/types.ts +8 -1
  52. package/src/reactivity/graph.ts +244 -41
  53. package/src/reactivity/hmr.ts +14 -3
  54. package/src/reactivity/index.ts +219 -235
  55. package/src/reactivity/resource.ts +17 -3
  56. package/src/reactivity/seed.ts +118 -16
  57. package/src/reactivity/selector.ts +85 -47
  58. package/src/reactivity/server-seed.ts +31 -23
  59. package/src/reactivity/store.ts +316 -136
  60. package/src/server/action-protect.ts +3 -0
  61. package/src/server/action-registry.ts +5 -1
  62. package/src/server/cache-invalidation.ts +4 -3
  63. package/src/server/compress.ts +52 -17
  64. package/src/server/consent.ts +5 -3
  65. package/src/server/cookies.ts +27 -8
  66. package/src/server/cors.ts +98 -0
  67. package/src/server/csp-report.ts +8 -4
  68. package/src/server/health.ts +9 -0
  69. package/src/server/http.ts +3 -1
  70. package/src/server/index.ts +25 -13
  71. package/src/server/loader.ts +1 -0
  72. package/src/server/plugin-host.ts +41 -9
  73. package/src/server/plugin-route-shadow.ts +24 -0
  74. package/src/server/rate-limit.ts +13 -3
  75. package/src/server/region.ts +19 -2
  76. package/src/server/request-handler.ts +58 -22
  77. package/src/server/request-log.ts +1 -1
  78. package/src/server/route-cache.ts +14 -2
  79. package/src/server/route-table.ts +21 -11
  80. package/src/server/router.ts +2 -1
  81. package/src/server/routing.ts +100 -42
  82. package/src/server/sanitize-html.ts +3 -1
  83. package/src/server/serve-handlers.ts +10 -4
  84. package/src/server/served-file.ts +19 -14
  85. package/src/server/shared-store.ts +10 -1
  86. package/src/server/static-dir.ts +21 -3
  87. package/src/server/webhook.ts +6 -4
  88. package/src/ssr/context.ts +149 -51
  89. package/src/ssr/index.ts +41 -46
  90. package/src/ssr/region.ts +9 -3
  91. package/src/style.ts +12 -5
  92. package/src/test/browser.ts +3 -1
  93. package/src/test/build-reuse.ts +22 -7
  94. package/src/test/index.ts +7 -3
  95. package/src/ts-plugin/diagnostics.ts +56 -18
  96. package/ts-plugin.cjs +465 -131
@@ -1,8 +1,12 @@
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.
1
+ // Warns on reactivity-breaking patterns in browser-reachable components: body props destructuring, mutated destructured props, store destructuring, and top-level `.value` snapshots rendered in JSX.
2
2
 
3
- import type { Function as FunctionNode, Node, Program } from 'oxc-parser'
3
+ import type { Function as FunctionNode, JSXElement, JSXFragment, Node, Program } from 'oxc-parser'
4
4
  import type { CompilerWarning } from './mistakes'
5
- import { containsJsx, unwrapTsExpr } from './shared'
5
+ import type { ReactiveImportCallees } from './signal-reads'
6
+ import { walk } from './ast'
7
+ import { collectMutatedNames, walkScoped } from './scope'
8
+ import { calleeName, collectPatternNames, containsJsx, EVENT_ATTR, jsxTagName, unwrapTsExpr } from './shared'
9
+ import { collectReactiveImportCallees } from './signal-reads'
6
10
 
7
11
  function isFunction(node: Node | null | undefined): node is FunctionNode {
8
12
  return node !== null && node !== undefined && (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression')
@@ -26,7 +30,255 @@ function declaredFunctions(stmt: Node): FunctionNode[] {
26
30
  return found
27
31
  }
28
32
 
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. */
33
+ interface ReactiveScope {
34
+ signals: Set<string>
35
+ fieldObjs: Map<string, ReadonlySet<string>>
36
+ stores: Set<string>
37
+ }
38
+
39
+ function shadowNames(scope: ReactiveScope, names: Iterable<string>, snapshots?: Map<string, unknown>): void {
40
+ for (const name of names) {
41
+ scope.signals.delete(name)
42
+ scope.fieldObjs.delete(name)
43
+ scope.stores.delete(name)
44
+ snapshots?.delete(name)
45
+ }
46
+ }
47
+
48
+ function recordDeclaratorBinding(
49
+ d: Extract<Node, { type: 'VariableDeclarator' }>,
50
+ callees: ReactiveImportCallees,
51
+ scope: ReactiveScope,
52
+ snapshots?: Map<string, { source: string, start: number }>,
53
+ isConst = false,
54
+ ): void {
55
+ const init = d.init === null ? undefined : unwrapTsExpr(d.init)
56
+ if (d.id.type === 'Identifier') {
57
+ const name = d.id.name
58
+ shadowNames(scope, [name], snapshots)
59
+ if (init === undefined)
60
+ return
61
+ if (init.type === 'CallExpression') {
62
+ const callee = calleeName(init.callee)
63
+ if (callees.storeCallees.has(callee)) {
64
+ scope.stores.add(name)
65
+ return
66
+ }
67
+ if (callees.signalCallees.has(callee))
68
+ scope.signals.add(name)
69
+ const fields = callees.signalFieldCallees.get(callee)
70
+ if (fields !== undefined)
71
+ scope.fieldObjs.set(name, fields)
72
+ return
73
+ }
74
+ if (isConst && snapshots !== undefined && init.type === 'MemberExpression' && !init.computed && init.property.type === 'Identifier' && init.property.name === 'value') {
75
+ const obj = unwrapTsExpr(init.object)
76
+ if (obj.type === 'Identifier' && scope.signals.has(obj.name))
77
+ snapshots.set(name, { source: `${obj.name}.value`, start: d.start })
78
+ else if (obj.type === 'MemberExpression' && !obj.computed && obj.object.type === 'Identifier' && obj.property.type === 'Identifier' && scope.fieldObjs.get(obj.object.name)?.has(obj.property.name))
79
+ snapshots.set(name, { source: `${obj.object.name}.${obj.property.name}.value`, start: d.start })
80
+ }
81
+ return
82
+ }
83
+ const bound = new Set<string>()
84
+ collectPatternNames(d.id, bound)
85
+ shadowNames(scope, bound, snapshots)
86
+ if (d.id.type === 'ObjectPattern' && init?.type === 'CallExpression') {
87
+ const fields = callees.signalFieldCallees.get(calleeName(init.callee))
88
+ if (fields === undefined)
89
+ return
90
+ for (const prop of d.id.properties) {
91
+ if (prop.type !== 'Property' || prop.computed)
92
+ continue
93
+ const key = prop.key.type === 'Identifier' ? prop.key.name : prop.key.type === 'Literal' ? String(prop.key.value) : undefined
94
+ const target = prop.value.type === 'AssignmentPattern' ? prop.value.left : prop.value
95
+ if (key !== undefined && fields.has(key) && target.type === 'Identifier')
96
+ scope.signals.add(target.name)
97
+ }
98
+ }
99
+ }
100
+
101
+ function collectModuleReactiveScope(program: Program, callees: ReactiveImportCallees): ReactiveScope {
102
+ const scope: ReactiveScope = { signals: new Set(), fieldObjs: new Map(), stores: new Set() }
103
+ for (const stmt of program.body) {
104
+ const decl = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt
105
+ if (decl?.type === 'VariableDeclaration') {
106
+ for (const d of decl.declarations)
107
+ recordDeclaratorBinding(d, callees, scope)
108
+ }
109
+ }
110
+ return scope
111
+ }
112
+
113
+ function collectPatternIdentifierStarts(pattern: Node, out: Map<string, number>): void {
114
+ walk(pattern, (node) => {
115
+ if (node.type === 'Identifier') {
116
+ if (!out.has(node.name))
117
+ out.set(node.name, node.start)
118
+ return false
119
+ }
120
+ if (node.type === 'AssignmentPattern') {
121
+ collectPatternIdentifierStarts(node.left, out)
122
+ return false
123
+ }
124
+ if (node.type === 'Property') {
125
+ collectPatternIdentifierStarts(node.value, out)
126
+ return false
127
+ }
128
+ return undefined
129
+ })
130
+ }
131
+
132
+ function scanJsxNodeReads(
133
+ jsxNode: JSXElement | JSXFragment,
134
+ outerShadowed: ReadonlySet<string>,
135
+ snapshots: ReadonlyMap<string, { source: string, start: number }>,
136
+ jsxNodes: WeakSet<Node>,
137
+ found: Set<string>,
138
+ ): void {
139
+ const scanExpr = (expr: Node): void => {
140
+ walkScoped(expr, {
141
+ onIdentifier(id, innerShadowed) {
142
+ const snap = snapshots.get(id.name)
143
+ if (snap !== undefined && id.start > snap.start && !outerShadowed.has(id.name) && !innerShadowed.has(id.name))
144
+ found.add(id.name)
145
+ },
146
+ onFunction(fn) {
147
+ // Skip event/callback functions without JSX so `onClick={() => log(snap)}` never warns.
148
+ return !containsJsx(fn.body, jsxNodes)
149
+ },
150
+ onJsx(nested, innerShadowed) {
151
+ const combined = innerShadowed.size === 0 ? outerShadowed : new Set([...outerShadowed, ...innerShadowed])
152
+ scanJsxNodeReads(nested, combined, snapshots, jsxNodes, found)
153
+ },
154
+ })
155
+ }
156
+ if (jsxNode.type === 'JSXElement') {
157
+ for (const attr of jsxNode.openingElement.attributes) {
158
+ if (attr.type === 'JSXSpreadAttribute') {
159
+ scanExpr(attr.argument)
160
+ continue
161
+ }
162
+ const attrName = jsxTagName(attr.name)
163
+ if (EVENT_ATTR.test(attrName) || attrName === 'ref')
164
+ continue
165
+ if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression')
166
+ scanExpr(attr.value.expression)
167
+ }
168
+ }
169
+ for (const child of jsxNode.children) {
170
+ if (child.type === 'JSXElement' || child.type === 'JSXFragment')
171
+ scanJsxNodeReads(child, outerShadowed, snapshots, jsxNodes, found)
172
+ else if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression')
173
+ scanExpr(child.expression)
174
+ }
175
+ }
176
+
177
+ function findDirectJsxSnapshotReads(
178
+ body: Extract<Node, { type: 'BlockStatement' }>,
179
+ snapshots: ReadonlyMap<string, { source: string, start: number }>,
180
+ jsxNodes: WeakSet<Node>,
181
+ ): Set<string> {
182
+ const found = new Set<string>()
183
+ for (const stmt of body.body) {
184
+ walkScoped(stmt, {
185
+ onFunction(fn) {
186
+ return !containsJsx(fn.body, jsxNodes)
187
+ },
188
+ onJsx(node, shadowed) {
189
+ scanJsxNodeReads(node, shadowed, snapshots, jsxNodes, found)
190
+ },
191
+ })
192
+ }
193
+ return found
194
+ }
195
+
196
+ function checkComponentBody(
197
+ fn: FunctionNode,
198
+ code: string,
199
+ callees: ReactiveImportCallees,
200
+ moduleScope: ReactiveScope,
201
+ jsxNodes: WeakSet<Node>,
202
+ filename: string,
203
+ warnings: CompilerWarning[],
204
+ isBrowser: boolean,
205
+ ): void {
206
+ if (fn.body === null || !containsJsx(fn.body, jsxNodes))
207
+ return
208
+ const rawParam = fn.params[0]
209
+ const param = rawParam?.type === 'AssignmentPattern' ? rawParam.left : rawParam
210
+
211
+ if (isBrowser && param?.type === 'ObjectPattern') {
212
+ const propNames = new Set<string>()
213
+ collectPatternNames(param, propNames)
214
+ const mutated = collectMutatedNames(fn.body, propNames)
215
+ if (mutated.size > 0) {
216
+ const starts = new Map<string, number>()
217
+ collectPatternIdentifierStarts(param, starts)
218
+ for (const name of mutated) {
219
+ warnings.push({
220
+ start: starts.get(name) ?? param.start,
221
+ message: `prunelle compiler: reassigning destructured prop \`${name}\` in ${filename} copies it once at mount and breaks reactivity: keep props read-only, or copy into a local \`signal(${name})\` or \`let\` variable.`,
222
+ })
223
+ }
224
+ }
225
+ }
226
+
227
+ if (fn.body.type !== 'BlockStatement')
228
+ return
229
+
230
+ const propsParamName = isBrowser && param?.type === 'Identifier' ? param.name : undefined
231
+ const scope: ReactiveScope = {
232
+ signals: new Set(moduleScope.signals),
233
+ fieldObjs: new Map(moduleScope.fieldObjs),
234
+ stores: new Set(moduleScope.stores),
235
+ }
236
+ const paramNames = new Set<string>()
237
+ for (const p of fn.params)
238
+ collectPatternNames(p, paramNames)
239
+ shadowNames(scope, paramNames)
240
+
241
+ const snapshots = new Map<string, { source: string, start: number }>()
242
+
243
+ for (const inner of fn.body.body) {
244
+ if ((inner.type === 'FunctionDeclaration' || inner.type === 'ClassDeclaration') && inner.id !== null) {
245
+ shadowNames(scope, [inner.id.name], snapshots)
246
+ continue
247
+ }
248
+ if (inner.type !== 'VariableDeclaration')
249
+ continue
250
+ for (const d of inner.declarations) {
251
+ const init = d.init === null ? undefined : unwrapTsExpr(d.init)
252
+ if (propsParamName !== undefined && d.id.type === 'ObjectPattern' && init?.type === 'Identifier' && init.name === propsParamName) {
253
+ warnings.push({
254
+ start: d.start,
255
+ 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.`,
256
+ })
257
+ }
258
+ else if ((d.id.type === 'ObjectPattern' || d.id.type === 'ArrayPattern') && init?.type === 'Identifier' && scope.stores.has(init.name)) {
259
+ warnings.push({
260
+ start: d.start,
261
+ message: `prunelle compiler: \`${inner.kind} ${code.slice(d.start, d.end)}\` in ${filename} reads store properties once at mount, so updates never reach it: read \`${init.name}.<prop>\` where it is used, or use \`snapshot(${init.name})\` if a one-time copy is intended.`,
262
+ })
263
+ }
264
+ recordDeclaratorBinding(d, callees, scope, snapshots, inner.kind === 'const')
265
+ }
266
+ }
267
+
268
+ if (snapshots.size > 0) {
269
+ const jsxUsed = findDirectJsxSnapshotReads(fn.body, snapshots, jsxNodes)
270
+ for (const [name, snap] of snapshots) {
271
+ if (jsxUsed.has(name)) {
272
+ warnings.push({
273
+ start: snap.start,
274
+ message: `prunelle compiler: \`const ${name} = ${snap.source}\` in ${filename} snapshots \`${snap.source}\` once at mount and never updates in JSX: read \`${snap.source}\` directly in JSX, or wrap it in \`computed(() => ...)\`.`,
275
+ })
276
+ }
277
+ }
278
+ }
279
+ }
280
+
281
+ /** Warns on reactivity-breaking patterns in browser-reachable components: body props destructuring, mutated destructured props, store destructuring, and top-level `.value` snapshots in JSX. */
30
282
  export function checkBodyPropsDestructure(
31
283
  program: Program,
32
284
  code: string,
@@ -35,26 +287,16 @@ export function checkBodyPropsDestructure(
35
287
  filename: string,
36
288
  warnings: CompilerWarning[],
37
289
  ): void {
38
- if (browserSpans.length === 0)
290
+ const callees = collectReactiveImportCallees(program)
291
+ const hasReactiveHooks = callees.signalCallees.size > 0 || callees.signalFieldCallees.size > 0 || callees.storeCallees.size > 0
292
+ if (browserSpans.length === 0 && !hasReactiveHooks)
39
293
  return
294
+ const moduleScope = collectModuleReactiveScope(program, callees)
40
295
  for (const stmt of program.body) {
41
296
  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
- }
297
+ const isBrowser = browserSpans.some(([s, e]) => fn.start >= s && fn.end <= e)
298
+ if (isBrowser || hasReactiveHooks)
299
+ checkComponentBody(fn, code, callees, moduleScope, jsxNodes, filename, warnings, isBrowser)
58
300
  }
59
301
  }
60
302
  }
@@ -2,6 +2,7 @@
2
2
 
3
3
  import type { ArrowFunctionExpression, Function as OxcFunction, Node, ObjectPattern, ParamPattern } from 'oxc-parser'
4
4
  import type { PatternContext } from './props-pattern'
5
+ import { walk } from './ast'
5
6
  import { SourceEditor } from './patch'
6
7
  import { patternReads } from './props-pattern'
7
8
  import { collectMutatedNames, isSafeLazyJsxRef } from './scope'
@@ -268,7 +269,7 @@ function processFunction(ctx: PropCompilerContext, fn: ArrowFunctionExpression |
268
269
  let prelude = ''
269
270
 
270
271
  if (destructured !== undefined) {
271
- const pVar = '__p'
272
+ const pVar = code.includes('__p') ? ctx.freshVar('__p') : '__p'
272
273
  const defSuffix = destructured.defaultExpr !== undefined
273
274
  ? ` = ${compileExpression(destructured.defaultExpr, new Map())}`
274
275
  : ''
@@ -300,7 +301,134 @@ function processFunction(ctx: PropCompilerContext, fn: ArrowFunctionExpression |
300
301
 
301
302
  type LoopRowOptions = Parameters<PropCompiler['compileLoopRow']>[0]
302
303
 
303
- function compileLoopRow(ctx: PropCompilerContext, opts: LoopRowOptions): { keyFn: string, rowRewrites: Map<string, string>, prelude: string } {
304
+ interface PendingKeyBind {
305
+ paramName: string | undefined
306
+ keyIdent: string | undefined
307
+ propName: string
308
+ expr: string
309
+ keyVar: string
310
+ basePrelude: string
311
+ }
312
+
313
+ const PLAIN_IDENT_RE = /^[A-Za-z_$][\w$]*$/
314
+ const IDENT_CHAR_RE = /[\w$]/
315
+ const ASSIGN_AFTER_RE = /^\s*(?:[+\-*/%&|^]|<<|>>|>>>|\*\*|&&|\|\||\?\?)?=(?![=>])/
316
+ const UPDATE_AFTER_RE = /^\s*(?:\+\+|--)/
317
+ const CALL_AFTER_RE = /^\s*(?:\?\.\s*)?[(`]/
318
+ const UPDATE_BEFORE_RE = /(?:\+\+|--)\s*$/
319
+ const DELETE_BEFORE_RE = /\bdelete\s+$/
320
+
321
+ function extractInvariantKeyBind(
322
+ firstParam: ParamPattern | undefined,
323
+ keyAst: Node | undefined,
324
+ rowSig: string,
325
+ rowRewrites: ReadonlyMap<string, string>,
326
+ ): Omit<PendingKeyBind, 'keyVar' | 'basePrelude'> | undefined {
327
+ if (keyAst === undefined)
328
+ return undefined
329
+ const keyNode = unwrapTsExpr(keyAst)
330
+ if (firstParam?.type === 'Identifier') {
331
+ if (keyNode.type !== 'MemberExpression' || keyNode.computed || keyNode.optional || keyNode.property.type !== 'Identifier')
332
+ return undefined
333
+ const obj = unwrapTsExpr(keyNode.object)
334
+ if (obj.type !== 'Identifier' || obj.name !== firstParam.name)
335
+ return undefined
336
+ const propName = keyNode.property.name
337
+ return { paramName: firstParam.name, keyIdent: undefined, propName, expr: `${rowSig}.value.${propName}` }
338
+ }
339
+ if (firstParam?.type === 'ObjectPattern' && keyNode.type === 'Identifier') {
340
+ const prefix = `${rowSig}.value.`
341
+ const read = rowRewrites.get(keyNode.name)
342
+ if (read === undefined || !read.startsWith(prefix))
343
+ return undefined
344
+ const propName = read.slice(prefix.length)
345
+ if (!PLAIN_IDENT_RE.test(propName))
346
+ return undefined
347
+ return { paramName: undefined, keyIdent: keyNode.name, propName, expr: read }
348
+ }
349
+ return undefined
350
+ }
351
+
352
+ function targetTouchesProp(target: Node | null | undefined, propName: string): boolean {
353
+ if (target === null || target === undefined)
354
+ return false
355
+ let found = false
356
+ walk(target, (node) => {
357
+ if (found)
358
+ return false
359
+ if (node.type === 'MemberExpression' && !node.computed && node.property.type === 'Identifier' && node.property.name === propName) {
360
+ found = true
361
+ return false
362
+ }
363
+ return undefined
364
+ })
365
+ return found
366
+ }
367
+
368
+ function hasKeyMutation(body: Node, bind: PendingKeyBind): boolean {
369
+ const watched = new Set<string>()
370
+ if (bind.paramName !== undefined)
371
+ watched.add(bind.paramName)
372
+ if (bind.keyIdent !== undefined)
373
+ watched.add(bind.keyIdent)
374
+ if (collectMutatedNames(body, watched).size > 0)
375
+ return true
376
+ let mutated = false
377
+ walk(body, (node) => {
378
+ if (mutated)
379
+ return false
380
+ if (node.type === 'AssignmentExpression' && targetTouchesProp(node.left, bind.propName))
381
+ mutated = true
382
+ else if (node.type === 'UpdateExpression' && targetTouchesProp(node.argument, bind.propName))
383
+ mutated = true
384
+ else if (node.type === 'UnaryExpression' && node.operator === 'delete' && targetTouchesProp(node.argument, bind.propName))
385
+ mutated = true
386
+ else if ((node.type === 'ForInStatement' || node.type === 'ForOfStatement') && targetTouchesProp(node.left, bind.propName))
387
+ mutated = true
388
+ return mutated ? false : undefined
389
+ })
390
+ return mutated
391
+ }
392
+
393
+ function rewriteInvariantKeyReads(compiledBody: string, expr: string, keyVar: string): { code: string, replaced: number } {
394
+ const len = expr.length
395
+ let out = ''
396
+ let last = 0
397
+ let pos = 0
398
+ let replaced = 0
399
+ while ((pos = compiledBody.indexOf(expr, pos)) !== -1) {
400
+ const before = pos > 0 ? compiledBody[pos - 1]! : ''
401
+ const after = pos + len < compiledBody.length ? compiledBody[pos + len]! : ''
402
+ const tail = compiledBody.slice(pos + len)
403
+ const head = compiledBody.slice(Math.max(0, pos - 16), pos)
404
+ const blocked = (before !== '' && (IDENT_CHAR_RE.test(before) || before === '.'))
405
+ || (after !== '' && IDENT_CHAR_RE.test(after))
406
+ || ASSIGN_AFTER_RE.test(tail)
407
+ || UPDATE_AFTER_RE.test(tail)
408
+ || CALL_AFTER_RE.test(tail)
409
+ || UPDATE_BEFORE_RE.test(head)
410
+ || DELETE_BEFORE_RE.test(head)
411
+ if (!blocked) {
412
+ out += compiledBody.slice(last, pos) + keyVar
413
+ last = pos + len
414
+ replaced++
415
+ }
416
+ pos += len
417
+ }
418
+ return replaced > 0 ? { code: out + compiledBody.slice(last), replaced } : { code: compiledBody, replaced: 0 }
419
+ }
420
+
421
+ function formatLoopBody(compiledBody: string, body: Node, prelude: string): string {
422
+ if (body.type === 'JSXElement' && compiledBody.startsWith('(() => { ') && compiledBody.endsWith(' })()'))
423
+ return prelude === '' ? compiledBody.slice(7, -3) : `{ ${prelude} ${compiledBody.slice(9, -3)}`
424
+ return withPrelude(compiledBody, body, prelude)
425
+ }
426
+
427
+ function compileLoopRow(
428
+ ctx: PropCompilerContext,
429
+ opts: LoopRowOptions,
430
+ pendingKeyBinds: Map<string, PendingKeyBind>,
431
+ ): { keyFn: string, rowRewrites: Map<string, string>, prelude: string } {
304
432
  const { freshVar, compileExpression } = ctx
305
433
  const { firstParam, idxParam, keyAst, rowSig, scopeRewrites, keyRewrites } = opts
306
434
  const rowRewrites = new Map(scopeRewrites)
@@ -327,14 +455,36 @@ function compileLoopRow(ctx: PropCompilerContext, opts: LoopRowOptions): { keyFn
327
455
  : `(${itemParam}) => ${itemParam}`
328
456
  rowRewrites.set(itemParam, `${rowSig}.value`)
329
457
  }
330
- return { keyFn, rowRewrites, prelude: hoisted.join(' ') }
458
+ const basePrelude = hoisted.join(' ')
459
+ const keyBind = extractInvariantKeyBind(firstParam, keyAst, rowSig, rowRewrites)
460
+ if (keyBind !== undefined) {
461
+ const keyVar = freshVar('_k')
462
+ hoisted.push(`const ${keyVar} = ${rowSig}.peek().${keyBind.propName};`)
463
+ const prelude = hoisted.join(' ')
464
+ pendingKeyBinds.set(prelude, { ...keyBind, keyVar, basePrelude })
465
+ return { keyFn, rowRewrites, prelude }
466
+ }
467
+ return { keyFn, rowRewrites, prelude: basePrelude }
331
468
  }
332
469
 
333
470
  export function createPropCompiler(ctx: PropCompilerContext): PropCompiler {
471
+ const pendingKeyBinds = new Map<string, PendingKeyBind>()
334
472
  return {
335
473
  patternReads: (pattern, source, outerRewrites, hoisted) => patternReads(ctx, pattern, source, outerRewrites, hoisted),
336
- compileLoopRow: opts => compileLoopRow(ctx, opts),
337
- withPrelude,
474
+ compileLoopRow: opts => compileLoopRow(ctx, opts, pendingKeyBinds),
475
+ withPrelude: (compiledBody, body, prelude) => {
476
+ const bind = pendingKeyBinds.get(prelude)
477
+ if (bind !== undefined) {
478
+ pendingKeyBinds.delete(prelude)
479
+ if (!hasKeyMutation(body, bind)) {
480
+ const rewritten = rewriteInvariantKeyReads(compiledBody, bind.expr, bind.keyVar)
481
+ if (rewritten.replaced > 0)
482
+ return formatLoopBody(rewritten.code, body, prelude)
483
+ }
484
+ return formatLoopBody(compiledBody, body, bind.basePrelude)
485
+ }
486
+ return formatLoopBody(compiledBody, body, prelude)
487
+ },
338
488
  extractDestructuredParam: firstParam => extractDestructuredParam(ctx.code, firstParam),
339
489
  buildCompiledFunction: (fn, outerRewrites) => buildCompiledFunction(ctx, fn, outerRewrites),
340
490
  processFunction: fn => processFunction(ctx, fn),