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,4 +1,4 @@
1
- // Refuses a local signal() or computed() read without `.value`, in JSX or in plain code, following each name through its scopes.
1
+ // Refuses a local signal(), computed(), resource(), or signal-valued field read without `.value`, in JSX or in plain code, following each name through its scopes.
2
2
 
3
3
  import type { Node, Program } from 'oxc-parser'
4
4
  import { visitorKeys } from 'oxc-parser'
@@ -6,19 +6,113 @@ import { walk } from './ast'
6
6
  import { guarded, mistake } from './mistakes'
7
7
  import { calleeName, EVENT_ATTR, isComponentTag, jsxTagName, unwrapTsExpr } from './shared'
8
8
 
9
- // Each name a scope binds, true when it holds a signal() or computed().
10
- type Scope = Map<string, boolean>
9
+ export const RESOURCE_SIGNAL_FIELDS: ReadonlySet<string> = new Set(['loading', 'error'])
10
+ export const USE_ACTION_SIGNAL_FIELDS: ReadonlySet<string> = new Set(['pending', 'error', 'fieldErrors', 'data', 'progress'])
11
+ export const USE_LIVE_SIGNAL_FIELDS: ReadonlySet<string> = new Set(['status', 'last', 'error'])
12
+ export const USE_NAVIGATION_SIGNAL_FIELDS: ReadonlySet<string> = new Set(['url', 'pathname', 'navigating'])
11
13
 
12
- function bindPattern(scope: Scope, pattern: Node | null | undefined, isSignal = false): void {
14
+ const CLIENT_FIELD_HOOKS: ReadonlyMap<string, ReadonlyMap<string, ReadonlySet<string>>> = new Map([
15
+ ['@prunellejs/live/client', new Map([['useLive', USE_LIVE_SIGNAL_FIELDS]])],
16
+ ['@prunellejs/spa/client', new Map([['useNavigation', USE_NAVIGATION_SIGNAL_FIELDS]])],
17
+ ])
18
+
19
+ export interface ReactiveImportCallees {
20
+ signalCallees: Set<string>
21
+ signalFieldCallees: Map<string, ReadonlySet<string>>
22
+ storeCallees: Set<string>
23
+ }
24
+
25
+ const EMPTY_FIELD_MAP: ReadonlyMap<string, ReadonlySet<string>> = new Map()
26
+
27
+ /** Collects local callee names (direct, aliased, and namespace) for prunelle signals, stores, and hooks returning signal-valued fields. */
28
+ export function collectReactiveImportCallees(program: Program): ReactiveImportCallees {
29
+ const signalCallees = new Set<string>()
30
+ const signalFieldCallees = new Map<string, ReadonlySet<string>>()
31
+ const storeCallees = new Set<string>()
32
+ for (const stmt of program.body) {
33
+ if (stmt.type !== 'ImportDeclaration' || stmt.importKind === 'type')
34
+ continue
35
+ const src = stmt.source.value
36
+ const clientHooks = CLIENT_FIELD_HOOKS.get(src)
37
+ if (src !== 'prunelle' && clientHooks === undefined)
38
+ continue
39
+ for (const spec of stmt.specifiers) {
40
+ if (spec.type === 'ImportSpecifier') {
41
+ if (spec.importKind === 'type')
42
+ continue
43
+ const imported = spec.imported.type === 'Identifier' ? spec.imported.name : spec.imported.value
44
+ const local = spec.local.name
45
+ if (src === 'prunelle') {
46
+ if (imported === 'signal' || imported === 'computed' || imported === 'resource')
47
+ signalCallees.add(local)
48
+ if (imported === 'resource')
49
+ signalFieldCallees.set(local, RESOURCE_SIGNAL_FIELDS)
50
+ else if (imported === 'useAction')
51
+ signalFieldCallees.set(local, USE_ACTION_SIGNAL_FIELDS)
52
+ else if (imported === 'store')
53
+ storeCallees.add(local)
54
+ }
55
+ else {
56
+ const fields = clientHooks?.get(imported)
57
+ if (fields !== undefined)
58
+ signalFieldCallees.set(local, fields)
59
+ }
60
+ }
61
+ else if (spec.type === 'ImportNamespaceSpecifier') {
62
+ const ns = spec.local.name
63
+ if (src === 'prunelle') {
64
+ signalCallees.add(`${ns}.signal`)
65
+ signalCallees.add(`${ns}.computed`)
66
+ signalCallees.add(`${ns}.resource`)
67
+ signalFieldCallees.set(`${ns}.resource`, RESOURCE_SIGNAL_FIELDS)
68
+ signalFieldCallees.set(`${ns}.useAction`, USE_ACTION_SIGNAL_FIELDS)
69
+ storeCallees.add(`${ns}.store`)
70
+ }
71
+ else if (clientHooks !== undefined) {
72
+ for (const [hook, fields] of clientHooks)
73
+ signalFieldCallees.set(`${ns}.${hook}`, fields)
74
+ }
75
+ }
76
+ }
77
+ }
78
+ return { signalCallees, signalFieldCallees, storeCallees }
79
+ }
80
+
81
+ interface ScopeEntry {
82
+ isSignal: boolean
83
+ fields?: ReadonlySet<string> | undefined
84
+ }
85
+
86
+ const PLAIN_ENTRY: ScopeEntry = { isSignal: false }
87
+ const SIGNAL_ENTRY: ScopeEntry = { isSignal: true }
88
+
89
+ // Each name a scope binds, with whether it holds a signal/computed/resource and any signal-valued fields on it.
90
+ type Scope = Map<string, ScopeEntry>
91
+
92
+ function bindPattern(scope: Scope, pattern: Node | null | undefined, entry: ScopeEntry = PLAIN_ENTRY): void {
13
93
  if (pattern === null || pattern === undefined)
14
94
  return
15
95
  if (pattern.type === 'Identifier') {
16
- scope.set(pattern.name, isSignal)
96
+ scope.set(pattern.name, entry)
97
+ return
98
+ }
99
+ if (pattern.type === 'ObjectPattern' && entry.fields !== undefined) {
100
+ for (const prop of pattern.properties) {
101
+ if (prop.type === 'RestElement') {
102
+ bindPattern(scope, prop.argument)
103
+ continue
104
+ }
105
+ const key = !prop.computed
106
+ ? (prop.key.type === 'Identifier' ? prop.key.name : prop.key.type === 'Literal' ? String(prop.key.value) : undefined)
107
+ : undefined
108
+ const target = prop.value.type === 'AssignmentPattern' ? prop.value.left : prop.value
109
+ bindPattern(scope, target, key !== undefined && entry.fields.has(key) ? SIGNAL_ENTRY : PLAIN_ENTRY)
110
+ }
17
111
  return
18
112
  }
19
113
  walk(pattern, (node) => {
20
114
  if (node.type === 'Identifier')
21
- scope.set(node.name, false)
115
+ scope.set(node.name, PLAIN_ENTRY)
22
116
  // A default value or a computed key reads names, it binds none.
23
117
  if (node.type === 'AssignmentPattern')
24
118
  bindPattern(scope, node.left)
@@ -28,41 +122,55 @@ function bindPattern(scope: Scope, pattern: Node | null | undefined, isSignal =
28
122
  })
29
123
  }
30
124
 
31
- function bindStatements(scope: Scope, statements: readonly Node[], signalCallees: ReadonlySet<string>, importedSignals?: ReadonlySet<string>): void {
125
+ function bindStatements(
126
+ scope: Scope,
127
+ statements: readonly Node[],
128
+ signalCallees: ReadonlySet<string>,
129
+ signalFieldCallees: ReadonlyMap<string, ReadonlySet<string>>,
130
+ importedSignals?: ReadonlySet<string>,
131
+ ): void {
32
132
  for (const stmt of statements) {
33
133
  const decl = (stmt.type === 'ExportNamedDeclaration' || stmt.type === 'ExportDefaultDeclaration') ? stmt.declaration : stmt
34
134
  if (decl?.type === 'VariableDeclaration') {
35
135
  for (const d of decl.declarations) {
36
136
  const init = d.init === null ? undefined : unwrapTsExpr(d.init)
37
- bindPattern(scope, d.id, init?.type === 'CallExpression' && signalCallees.has(calleeName(init.callee)))
137
+ const callee = init?.type === 'CallExpression' ? calleeName(init.callee) : ''
138
+ const isSignal = callee !== '' && signalCallees.has(callee)
139
+ const fields = callee !== '' ? signalFieldCallees.get(callee) : undefined
140
+ bindPattern(scope, d.id, isSignal || fields !== undefined ? { isSignal, fields } : PLAIN_ENTRY)
38
141
  }
39
142
  }
40
143
  else if ((decl?.type === 'FunctionDeclaration' || decl?.type === 'ClassDeclaration') && decl.id !== null) {
41
- scope.set(decl.id.name, false)
144
+ scope.set(decl.id.name, PLAIN_ENTRY)
42
145
  }
43
146
  else if (decl?.type === 'ImportDeclaration') {
44
147
  for (const spec of decl.specifiers)
45
- scope.set(spec.local.name, importedSignals?.has(spec.local.name) === true)
148
+ scope.set(spec.local.name, importedSignals?.has(spec.local.name) === true ? SIGNAL_ENTRY : PLAIN_ENTRY)
46
149
  }
47
150
  }
48
151
  }
49
152
 
50
153
  // The names a node opens a scope for, or undefined when it opens none.
51
- function scopeOf(node: Node, signalCallees: ReadonlySet<string>, importedSignals?: ReadonlySet<string>): Scope | undefined {
154
+ function scopeOf(
155
+ node: Node,
156
+ signalCallees: ReadonlySet<string>,
157
+ signalFieldCallees: ReadonlyMap<string, ReadonlySet<string>>,
158
+ importedSignals?: ReadonlySet<string>,
159
+ ): Scope | undefined {
52
160
  const scope: Scope = new Map()
53
161
  switch (node.type) {
54
162
  case 'Program':
55
- bindStatements(scope, node.body, signalCallees, importedSignals)
163
+ bindStatements(scope, node.body, signalCallees, signalFieldCallees, importedSignals)
56
164
  return scope
57
165
  case 'BlockStatement':
58
166
  case 'StaticBlock':
59
- bindStatements(scope, node.body, signalCallees)
167
+ bindStatements(scope, node.body, signalCallees, signalFieldCallees)
60
168
  return scope
61
169
  case 'FunctionDeclaration':
62
170
  case 'FunctionExpression':
63
171
  case 'ArrowFunctionExpression':
64
172
  if (node.type === 'FunctionExpression' && node.id !== null)
65
- scope.set(node.id.name, false)
173
+ scope.set(node.id.name, PLAIN_ENTRY)
66
174
  for (const param of node.params)
67
175
  bindPattern(scope, param)
68
176
  return scope
@@ -71,7 +179,7 @@ function scopeOf(node: Node, signalCallees: ReadonlySet<string>, importedSignals
71
179
  case 'ForOfStatement': {
72
180
  const head = node.type === 'ForStatement' ? node.init : node.left
73
181
  if (head?.type === 'VariableDeclaration')
74
- bindStatements(scope, [head], signalCallees)
182
+ bindStatements(scope, [head], signalCallees, signalFieldCallees)
75
183
  return scope
76
184
  }
77
185
  case 'CatchClause':
@@ -79,7 +187,7 @@ function scopeOf(node: Node, signalCallees: ReadonlySet<string>, importedSignals
79
187
  return scope
80
188
  case 'SwitchStatement':
81
189
  for (const c of node.cases)
82
- bindStatements(scope, c.consequent, signalCallees)
190
+ bindStatements(scope, c.consequent, signalCallees, signalFieldCallees)
83
191
  return scope
84
192
  default:
85
193
  return undefined
@@ -95,6 +203,7 @@ interface SignalLookup {
95
203
  function walkWithSignals(
96
204
  program: Program,
97
205
  signalCallees: ReadonlySet<string>,
206
+ signalFieldCallees: ReadonlyMap<string, ReadonlySet<string>>,
98
207
  importedSignals: ReadonlySet<string>,
99
208
  importedSignalMembers: ReadonlyMap<string, ReadonlySet<string>>,
100
209
  visit: (node: Node, lookup: SignalLookup) => void,
@@ -105,25 +214,27 @@ function walkWithSignals(
105
214
  for (let i = scopes.length - 1; i >= 0; i--) {
106
215
  const found = scopes[i]!.get(name)
107
216
  if (found !== undefined)
108
- return found
217
+ return found.isSignal
109
218
  }
110
219
  return false
111
220
  },
112
221
  isSignalMember(obj: string, prop: string): boolean {
113
- const members = importedSignalMembers.get(obj)
114
- if (members === undefined || !members.has(prop))
115
- return false
116
- // Any inner scope binding `obj` shadows the namespace import.
117
- for (let i = scopes.length - 1; i >= 1; i--) {
118
- if (scopes[i]!.has(obj))
119
- return false
222
+ for (let i = scopes.length - 1; i >= 0; i--) {
223
+ const found = scopes[i]!.get(obj)
224
+ if (found !== undefined) {
225
+ if (found.fields !== undefined)
226
+ return found.fields.has(prop)
227
+ if (i > 0)
228
+ return false
229
+ break
230
+ }
120
231
  }
121
- return true
232
+ return importedSignalMembers.get(obj)?.has(prop) === true
122
233
  },
123
234
  }
124
235
  const visitor = (node: Node): boolean | void => {
125
236
  visit(node, lookup)
126
- const scope = scopeOf(node, signalCallees, importedSignals)
237
+ const scope = scopeOf(node, signalCallees, signalFieldCallees, importedSignals)
127
238
  if (scope === undefined)
128
239
  return
129
240
  scopes.push(scope)
@@ -219,7 +330,7 @@ function destructuredSignal(node: Node, lookup: SignalLookup): string | undefine
219
330
  return takesValue ? name : undefined
220
331
  }
221
332
 
222
- /** Throws when JSX or plain code prints or tests a local or imported signal/computed without `.value`, or copies its value out by destructuring. */
333
+ /** Throws when JSX or plain code prints or tests a local or imported signal/computed/resource (or signal-valued hook field) without `.value`, or copies its value out by destructuring. */
223
334
  export function checkBareSignals(
224
335
  program: Program,
225
336
  signalCallees: ReadonlySet<string>,
@@ -227,11 +338,13 @@ export function checkBareSignals(
227
338
  importedSignals: ReadonlySet<string> = new Set(),
228
339
  importedSignalMembers: ReadonlyMap<string, ReadonlySet<string>> = new Map(),
229
340
  ): void {
230
- if (signalCallees.size === 0 && importedSignals.size === 0 && importedSignalMembers.size === 0)
341
+ const checkLocal = importedSignals.size === 0 && importedSignalMembers.size === 0
342
+ const signalFieldCallees = checkLocal ? collectReactiveImportCallees(program).signalFieldCallees : EMPTY_FIELD_MAP
343
+ if (signalCallees.size === 0 && signalFieldCallees.size === 0 && importedSignals.size === 0 && importedSignalMembers.size === 0)
231
344
  return
232
345
  // One read sits under several checks, `{!open}` under both the JSX child and the `!`, and is reported once.
233
346
  const reported = new Set<number>()
234
- walkWithSignals(program, signalCallees, importedSignals, importedSignalMembers, (node, lookup) => {
347
+ walkWithSignals(program, signalCallees, signalFieldCallees, importedSignals, importedSignalMembers, (node, lookup) => {
235
348
  for (const expr of [...jsxReads(node), ...codeTests(node)]) {
236
349
  const found = bareSignal(expr, lookup)
237
350
  if (found === undefined || reported.has(found.start))
@@ -142,11 +142,13 @@ function unwrapComponentFn(node: Node): OxcFunction | Extract<Node, { type: 'Arr
142
142
  return undefined
143
143
  }
144
144
 
145
- function collectPropVars(fn: OxcFunction | Extract<Node, { type: 'ArrowFunctionExpression' }>): Set<string> {
145
+ // The props variables of a component, and the names its parameter pattern takes out of its rest (`{ onDismiss, ...rest }` leaves `onDismiss` out of `rest`).
146
+ function collectPropVars(fn: OxcFunction | Extract<Node, { type: 'ArrowFunctionExpression' }>): { vars: Set<string>, excluded: Set<string> } {
146
147
  const vars = new Set<string>()
148
+ const excluded = new Set<string>()
147
149
  const p0 = fn.params[0]
148
150
  if (p0 === undefined)
149
- return vars
151
+ return { vars, excluded }
150
152
  const pat = p0.type === 'AssignmentPattern' ? p0.left : p0
151
153
  if (pat.type === 'Identifier') {
152
154
  vars.add(pat.name)
@@ -155,10 +157,15 @@ function collectPropVars(fn: OxcFunction | Extract<Node, { type: 'ArrowFunctionE
155
157
  for (const prop of pat.properties) {
156
158
  if (prop.type === 'RestElement' && prop.argument.type === 'Identifier')
157
159
  vars.add(prop.argument.name)
160
+ else if (prop.type === 'Property' && !prop.computed) {
161
+ const key = propKeyName(prop.key)
162
+ if (key !== undefined)
163
+ excluded.add(key)
164
+ }
158
165
  }
159
166
  }
160
167
  if (vars.size === 0 || fn.body === null)
161
- return vars
168
+ return { vars, excluded }
162
169
  walk(fn.body, (node) => {
163
170
  if (node.type !== 'VariableDeclarator' || node.init === null)
164
171
  return
@@ -177,7 +184,7 @@ function collectPropVars(fn: OxcFunction | Extract<Node, { type: 'ArrowFunctionE
177
184
  }
178
185
  }
179
186
  })
180
- return vars
187
+ return { vars, excluded }
181
188
  }
182
189
 
183
190
  function exprCarriesPropVar(expr: Node, propVars: ReadonlySet<string>): boolean {
@@ -195,8 +202,10 @@ function exprCarriesPropVar(expr: Node, propVars: ReadonlySet<string>): boolean
195
202
  return false
196
203
  }
197
204
 
198
- function findStaticPropSpreaders(units: readonly BindingUnit[], inIsland: (offset: number) => boolean): Set<string> {
199
- const direct = new Set<string>()
205
+ // The static components that put their props on a DOM element, each with the props its parameter pattern keeps out of the spread.
206
+ function findStaticPropSpreaders(units: readonly BindingUnit[], inIsland: (offset: number) => boolean): Map<string, ReadonlySet<string>> {
207
+ const direct = new Map<string, ReadonlySet<string>>()
208
+ const own = new Map<string, ReadonlySet<string>>()
200
209
  const forwardsTo = new Map<string, Set<string>>()
201
210
  const staticNames = new Set<string>()
202
211
 
@@ -207,9 +216,10 @@ function findStaticPropSpreaders(units: readonly BindingUnit[], inIsland: (offse
207
216
  if (fn === undefined || fn.body === null)
208
217
  continue
209
218
  staticNames.add(unit.name)
210
- const propVars = collectPropVars(fn)
219
+ const { vars: propVars, excluded } = collectPropVars(fn)
211
220
  if (propVars.size === 0)
212
221
  continue
222
+ own.set(unit.name, excluded)
213
223
  walk(fn.body, (node) => {
214
224
  if (node.type !== 'JSXOpeningElement')
215
225
  return
@@ -220,7 +230,7 @@ function findStaticPropSpreaders(units: readonly BindingUnit[], inIsland: (offse
220
230
  if (!spreadsProps)
221
231
  return
222
232
  if (!isComponentTag(tag)) {
223
- direct.add(unit.name)
233
+ direct.set(unit.name, excluded)
224
234
  }
225
235
  else if (!tag.includes('.')) {
226
236
  const set = forwardsTo.get(unit.name) ?? new Set<string>()
@@ -236,8 +246,9 @@ function findStaticPropSpreaders(units: readonly BindingUnit[], inIsland: (offse
236
246
  if (direct.has(name) || !staticNames.has(name))
237
247
  continue
238
248
  for (const target of targets) {
239
- if (direct.has(target)) {
240
- direct.add(name)
249
+ const through = direct.get(target)
250
+ if (through !== undefined) {
251
+ direct.set(name, new Set([...own.get(name) ?? [], ...through]))
241
252
  changed = true
242
253
  break
243
254
  }
@@ -268,12 +279,13 @@ export function checkStaticSpreadHandlers(
268
279
  if (node.type !== 'JSXOpeningElement')
269
280
  return
270
281
  const tag = jsxTagName(node.name)
271
- if (!spreaders.has(tag))
282
+ const excluded = spreaders.get(tag)
283
+ if (excluded === undefined)
272
284
  return
273
285
  for (const attr of node.attributes) {
274
286
  if (attr.type === 'JSXAttribute' && attr.name.type === 'JSXIdentifier') {
275
287
  const name = attr.name.name
276
- if (isInteractiveKey(name) && !isOmittedHandlerValue(attr.value)) {
288
+ if (isInteractiveKey(name) && !excluded.has(name) && !isOmittedHandlerValue(attr.value)) {
277
289
  warnings.push({
278
290
  start: attr.start,
279
291
  message: `prunelle compiler: "${name}" passed to <${tag}> in ${filename} will not bind because <${tag}> is static and its caller is not an island: move the handler inside <${tag}>, or render <${tag}> from an island.`,
@@ -282,7 +294,7 @@ export function checkStaticSpreadHandlers(
282
294
  }
283
295
  else if (attr.type === 'JSXSpreadAttribute') {
284
296
  const found = findSpreadInteractiveAttr(attr.argument, inits)
285
- if (found !== undefined) {
297
+ if (found !== undefined && !excluded.has(found)) {
286
298
  warnings.push({
287
299
  start: attr.start,
288
300
  message: `prunelle compiler: "${found}" spread into <${tag}> in ${filename} will not bind because <${tag}> is static and its caller is not an island: move the handler inside <${tag}>, or render <${tag}> from an island.`,
@@ -155,10 +155,10 @@ function emitActionFormExpr(
155
155
  : `${use('ssrForm')}(${compileSubExpression(formAction)}, (${faVar}) => ${body})`
156
156
  }
157
157
 
158
- // A buffer is an array joined once: `+=` in a loop allocates a rope node for every two parts, about half again as many bytes for a page of 500 rows, and the garbage collector runs that much more often.
158
+ // A buffer is an array joined once with one concatenated expression per flush: single-arg push avoids variadic Array.push overhead and cuts array elements ~3.5x while letting Array.join flatten shallow ropes in one pass.
159
159
  function flushStringParts(bufVar: string, parts: StringParts, stmts: string[]): void {
160
160
  if (!parts.isEmpty()) {
161
- stmts.push(`${bufVar}.push(${parts.toArgs()});`)
161
+ stmts.push(`${bufVar}.push(${parts.toExpr()});`)
162
162
  parts.clear()
163
163
  }
164
164
  }
@@ -348,7 +348,7 @@ function emitLoopSlot(env: SsrEnv, slot: LoopSlot, emit: Sink): void {
348
348
 
349
349
  const target = compileSubExpression(match.target)
350
350
  pushStmt(
351
- `const ${arrVar} = ${target}; if (${arrVar}) for (let ${idxVar} = 0; ${idxVar} < ${arrVar}.length; ${idxVar}++) { const ${itemParam} = ${arrVar}[${idxVar}]; ${innerStmts.join(' ')} }`,
351
+ `let ${arrVar} = ${target}; if (${arrVar} && !Array.isArray(${arrVar})) ${arrVar} = Array.from(${arrVar}); if (${arrVar}) for (let ${idxVar} = 0; ${idxVar} < ${arrVar}.length; ${idxVar}++) { const ${itemParam} = ${arrVar}[${idxVar}]; ${innerStmts.join(' ')} }`,
352
352
  )
353
353
  }
354
354
  else if (match.isJsxBody) {
@@ -116,11 +116,6 @@ export class StringParts {
116
116
  return this.#code().join(' + ')
117
117
  }
118
118
 
119
- /** The parts as the arguments of a buffer's `push`. */
120
- toArgs(): string {
121
- return this.#code().join(', ')
122
- }
123
-
124
119
  #code(): string[] {
125
120
  return this.#parts.map(p => (p.static ? JSON.stringify(p.value) : `(${p.value})`))
126
121
  }
@@ -11,6 +11,7 @@ import type { SsrEnv } from './ssr-emit'
11
11
  import { analyzeModule, getExprContext, parseTsx } from './analyze'
12
12
  import { walk } from './ast'
13
13
  import { createDevSourceAttr } from './dev-source'
14
+ import { runtimeAlias } from './emit'
14
15
  import { alignLines, lineMarker, SourceEditor } from './patch'
15
16
  import { containsJsx, isJsxNode } from './shared'
16
17
  import { precomputeSsrSubtreeFlags } from './ssr-helpers'
@@ -85,6 +86,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
85
86
  // 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.
86
87
  const mark = lineMarker(code)
87
88
  const used = new Set<string>()
89
+ const alias = runtimeAlias(code)
88
90
  const jsxNodes = analysis.jsxNodes
89
91
  const { directAwaitNodes, dynamicChildNodes } = precomputeSsrSubtreeFlags(program)
90
92
 
@@ -100,7 +102,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
100
102
  dynamicChildNodes,
101
103
  use: (name) => {
102
104
  used.add(name)
103
- return `__${name}`
105
+ return alias(name)
104
106
  },
105
107
  nextId: createIdCounter(code),
106
108
  mark,
@@ -117,7 +119,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
117
119
  })
118
120
 
119
121
  if (used.size > 0) {
120
- const specifiers = [...used].sort().map(name => `${name} as __${name}`).join(', ')
122
+ const specifiers = [...used].sort().map(name => `${name} as ${alias(name)}`).join(', ')
121
123
  // Last, where it moves no line: an import is hoisted wherever it is written.
122
124
  editor.append(`\nimport { ${specifiers} } from 'prunelle/internal/ssr';\n`)
123
125
  }
@@ -24,7 +24,8 @@ export function createDevHostCheck(hostname: string | undefined, origins: readon
24
24
  }
25
25
  return (request) => {
26
26
  const host = request.headers.get('host') ?? ''
27
- const name = hostnameOf(host)
27
+ // `localhost.` names the same host as `localhost`.
28
+ const name = hostnameOf(host)?.replace(/\.$/, '')
28
29
  if (name !== undefined && (LOOPBACK_NAMES.has(name) || name.endsWith('.localhost') || name.startsWith('[') || IPV4_RE.test(name) || names.has(name)))
29
30
  return undefined
30
31
  return new Response(`prunelle dev: refused Host "${name ?? host}": a dev server answers only localhost, an IP address, its --host and the hosts of site and trustedOrigins in prunelle.config.ts, so that a page on another domain cannot reach it by DNS rebinding. Add the origin you open it under to trustedOrigins.\n`, { status: 421, headers: { 'content-type': 'text/plain; charset=utf-8' } })
package/src/dev/reload.ts CHANGED
@@ -55,7 +55,10 @@ export function injectReloadStream(body: ReadableStream<Uint8Array>, reloadScrip
55
55
  return
56
56
  }
57
57
  if (text.length > KEEP) {
58
- const split = text.length - KEEP
58
+ let split = text.length - KEEP
59
+ // A cut between the halves of an emoji would encode each half as U+FFFD.
60
+ if (text.charCodeAt(split) >= 0xDC00 && text.charCodeAt(split) <= 0xDFFF)
61
+ split--
59
62
  controller.enqueue(encoder.encode(text.slice(0, split)))
60
63
  tail = text.slice(split)
61
64
  }
package/src/dom/attrs.ts CHANGED
@@ -1,15 +1,17 @@
1
1
  // Attribute, class, property and style bindings, in a module of their own (`dom-attrs`): only the islands that bind one load it.
2
2
 
3
- import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
4
- import { styleText } from '../style'
3
+ import { isStringBoolAttr, isUnsafeUrlAttr, URL_ATTRS, VALID_ATTR_NAME } from '../attrs'
4
+ import { eachStyleProp } from '../style'
5
5
  import { assertRenderable } from '../unrenderable'
6
+ import { isHydrating } from './index'
6
7
 
7
8
  export function setClass(el: Element, value: unknown): void {
8
9
  if (process.env.NODE_ENV !== 'production')
9
10
  assertRenderable(value, 'class')
10
11
  const str = value == null || value === false ? '' : String(value)
11
- if (typeof el.className === 'string') {
12
- if (el.className !== str) {
12
+ const cur = el.className
13
+ if (typeof cur === 'string') {
14
+ if (cur !== str) {
13
15
  if (str === '')
14
16
  el.removeAttribute('class')
15
17
  else
@@ -26,39 +28,53 @@ export function setClass(el: Element, value: unknown): void {
26
28
 
27
29
  const XLINK_NS = 'http://www.w3.org/1999/xlink'
28
30
 
31
+ function removeAttr(el: Element, name: string, isXlink: boolean): void {
32
+ if (isXlink) {
33
+ if (el.hasAttributeNS(XLINK_NS, 'href'))
34
+ el.removeAttributeNS(XLINK_NS, 'href')
35
+ }
36
+ else if (el.hasAttribute(name)) {
37
+ el.removeAttribute(name)
38
+ }
39
+ }
40
+
41
+ function writeAttr(el: Element, name: string, isXlink: boolean, next: string): void {
42
+ if (isXlink) {
43
+ if (el.getAttributeNS(XLINK_NS, 'href') !== next)
44
+ el.setAttributeNS(XLINK_NS, name, next)
45
+ }
46
+ else if (el.getAttribute(name) !== next) {
47
+ el.setAttribute(name, next)
48
+ }
49
+ }
50
+
29
51
  export function setAttr(el: Element, name: string, value: unknown): void {
30
- if (isBlockedAttr(name))
52
+ if (!VALID_ATTR_NAME.test(name))
53
+ return
54
+ const lower = name.toLowerCase()
55
+ if (lower.startsWith('on') || lower === 'innerhtml' || lower === 'srcdoc')
31
56
  return
32
57
  if (process.env.NODE_ENV !== 'production')
33
58
  assertRenderable(value, name)
34
59
  const isXlink = name === 'xlink:href'
35
- const remove = (): void => {
36
- if (isXlink)
37
- el.removeAttributeNS(XLINK_NS, 'href')
38
- else
39
- el.removeAttribute(name)
40
- }
41
60
  if (value == null) {
42
- remove()
61
+ removeAttr(el, name, isXlink)
43
62
  }
44
63
  else if (typeof value === 'boolean') {
45
- if (isStringBoolAttr(name))
46
- el.setAttribute(name, value ? 'true' : 'false')
64
+ if (isStringBoolAttr(lower))
65
+ writeAttr(el, name, isXlink, value ? 'true' : 'false')
47
66
  else if (value)
48
- el.setAttribute(name, '')
67
+ writeAttr(el, name, isXlink, '')
49
68
  else
50
- remove()
69
+ removeAttr(el, name, isXlink)
51
70
  }
52
- else if (isUnsafeUrlAttr(name, value, el.tagName)) {
71
+ else if (URL_ATTRS.has(lower) && isUnsafeUrlAttr(lower, value, el.tagName)) {
53
72
  if (process.env.NODE_ENV !== 'production')
54
73
  console.warn(`prunelle: dropped unsafe URL on <${el.tagName.toLowerCase()} ${name}>.`)
55
- remove()
56
- }
57
- else if (isXlink) {
58
- el.setAttributeNS(XLINK_NS, name, String(value))
74
+ removeAttr(el, name, isXlink)
59
75
  }
60
76
  else {
61
- el.setAttribute(name, String(value))
77
+ writeAttr(el, name, isXlink, String(value))
62
78
  }
63
79
  }
64
80
 
@@ -79,14 +95,66 @@ export function setSelectValues(el: HTMLSelectElement, value: unknown): void {
79
95
  option.selected = value.some(v => String(v) === option.value)
80
96
  }
81
97
 
98
+ const IMPORTANT = /\s*!\s*important\s*$/i
99
+ let prevStyles: WeakMap<Element, Record<string, string> | string> | undefined
100
+
101
+ function applyProp(style: CSSStyleDeclaration, prop: string, raw: string): void {
102
+ const important = IMPORTANT.test(raw)
103
+ const val = important ? raw.replace(IMPORTANT, '') : raw
104
+ const priority = important ? 'important' : ''
105
+ if (style.getPropertyValue(prop) !== val || style.getPropertyPriority(prop) !== priority)
106
+ style.setProperty(prop, val, priority)
107
+ }
108
+
82
109
  export function setStyle(el: HTMLElement, value: unknown): void {
110
+ const prev = prevStyles?.get(el)
83
111
  if (value == null || value === false) {
84
- el.removeAttribute('style')
112
+ prevStyles?.delete(el)
113
+ if (prev !== undefined && typeof prev === 'object') {
114
+ for (const prop in prev)
115
+ el.style.removeProperty(prop)
116
+ if (el.style.cssText === '' && el.hasAttribute('style'))
117
+ el.removeAttribute('style')
118
+ }
119
+ else if (el.hasAttribute('style')) {
120
+ el.removeAttribute('style')
121
+ }
85
122
  }
86
123
  else if (typeof value === 'string') {
87
- el.style.cssText = value
124
+ if (prev === value)
125
+ return
126
+ ;(prevStyles ??= new WeakMap()).set(el, value)
127
+ if (el.style.cssText !== value)
128
+ el.style.cssText = value
88
129
  }
89
130
  else if (typeof value === 'object') {
90
- el.style.cssText = styleText(value as Record<string, unknown>)
131
+ const next = Object.create(null) as Record<string, string>
132
+ eachStyleProp(value as Record<string, unknown>, (prop, raw) => {
133
+ next[prop] = raw
134
+ })
135
+ let prevObj = typeof prev === 'object' ? prev : undefined
136
+ if (prev === undefined && isHydrating() && el.style.length > 0) {
137
+ prevObj = Object.create(null) as Record<string, string>
138
+ for (let i = 0; i < el.style.length; i++) {
139
+ const prop = el.style.item(i)
140
+ const val = el.style.getPropertyValue(prop)
141
+ const prio = el.style.getPropertyPriority(prop)
142
+ prevObj[prop] = prio ? `${val} !${prio}` : val
143
+ }
144
+ }
145
+ if (typeof prev === 'string' && prev !== '')
146
+ el.style.cssText = ''
147
+ if (prevObj !== undefined) {
148
+ for (const prop in prevObj) {
149
+ if (!(prop in next))
150
+ el.style.removeProperty(prop)
151
+ }
152
+ }
153
+ for (const prop in next) {
154
+ const raw = next[prop]!
155
+ if (prevObj === undefined || prevObj[prop] !== raw)
156
+ applyProp(el.style, prop, raw)
157
+ }
158
+ ;(prevStyles ??= new WeakMap()).set(el, next)
91
159
  }
92
160
  }