@pyreon/runtime-dom 0.14.0 → 0.16.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.
@@ -174,4 +174,97 @@ describe('context inheritance through reactive boundaries', () => {
174
174
  expect(collected.length).toBe(3)
175
175
  expect(collected.every((v) => v === 'parent-provided')).toBe(true)
176
176
  })
177
+
178
+ // ── Lock-in for the context-truncation fix (PR #406) ──────────────────────
179
+ //
180
+ // Pre-fix `mountReactive`'s `restoreContextStack` did
181
+ // `stack.length = savedLength` in its finally block — which destroyed
182
+ // every provider frame that the synchronous mount had pushed via
183
+ // `provide()`. Signal-driven re-runs of `_bind` / `renderEffect` inside
184
+ // the mounted subtree later saw a half-empty stack and `useContext()`
185
+ // silently fell back to the default. The original symptom was
186
+ // `<PyreonUI mode={signal()}>` toggling not propagating to consumers
187
+ // — discovered while writing PR #406's regression e2e and traced back
188
+ // through the binding subscription chain to this stack truncation.
189
+ //
190
+ // The fix has two cooperating layers; each provides defense-in-depth
191
+ // for the other, so this assertion would still pass if you revert
192
+ // EITHER alone — but reverting BOTH layers together fails it. To
193
+ // bisect-verify cleanly, revert both:
194
+ // 1. `packages/core/core/src/context.ts:restoreContextStack` — change
195
+ // the finally block back to `stack.length = savedLength` (truncate
196
+ // everything fn() pushed).
197
+ // 2. `packages/core/reactivity/src/effect.ts:_bind` — remove the
198
+ // `_snapshotCapture` capture/restore wiring so re-runs call fn()
199
+ // against whatever the live stack happens to be at re-run time.
200
+ //
201
+ // With both reverted, this test fails with `seen[1] === 'default'`.
202
+ //
203
+ // What the test exercises: a `_bind` text binding inside a child mounted
204
+ // through a reactive accessor (which goes through `mountReactive`). The
205
+ // binding subscribes to a signal and reads `useContext(Ctx)`. After
206
+ // initial mount, the provider frame is at risk of being truncated by
207
+ // `mountReactive`'s cleanup — toggling the signal forces the binding to
208
+ // re-run, which re-reads context. If either fix is in place, the
209
+ // re-read finds the provider frame and returns the provided value.
210
+ it('binding re-runs preserve context lookup across mountReactive cleanup boundary (PR #406 splice + snapshot capture)', async () => {
211
+ const Ctx = createContext('default')
212
+ const trigger = signal(0)
213
+ let lastSeen: string | undefined
214
+ let runCount = 0
215
+
216
+ function Inner() {
217
+ // JSX text accessor compiles to a `_bind` / renderEffect text binding
218
+ // that subscribes to `trigger` (signal read inside the body) AND
219
+ // captures the external context snapshot at setup time.
220
+ return h('span', null, () => {
221
+ trigger()
222
+ const v = useContext(Ctx)
223
+ lastSeen = v
224
+ runCount++
225
+ return v
226
+ })
227
+ }
228
+
229
+ function Provider() {
230
+ // CRITICAL for exercising the bug: `provide()` runs INSIDE the
231
+ // reactive child fn (the accessor `() => h(Provider)` returned by
232
+ // App below). That puts Ctx on the stack DURING `mountReactive`'s
233
+ // restoreContextStack(snapshot, fn) execution — and pre-fix the
234
+ // truncating finally block (`stack.length = savedLength`) destroyed
235
+ // the frame the moment fn returned. If Outer pushed Ctx in its OWN
236
+ // body BEFORE returning the accessor, the frame would already be on
237
+ // the stack at snapshot-capture time and survive truncation
238
+ // unrelated — so the test wouldn't actually exercise the bug.
239
+ provide(Ctx, 'provider-value')
240
+ return h(Inner, null)
241
+ }
242
+
243
+ function App() {
244
+ // No provide() here — the provider frame must be pushed strictly
245
+ // inside the reactive accessor body (= inside `mountReactive`'s fn)
246
+ // so the truncation-vs-splice path is reached.
247
+ return () => h(Provider, null)
248
+ }
249
+
250
+ const container = document.createElement('div')
251
+ mount(h(App, null), container)
252
+ await new Promise((r) => setTimeout(r, 20))
253
+ expect(lastSeen).toBe('provider-value')
254
+ const initialRunCount = runCount
255
+
256
+ // Force the binding's effect to re-run AFTER the synchronous mount
257
+ // has fully unwound. With the broken pre-fix shape, mountReactive's
258
+ // `stack.length = savedLength` finally block has already destroyed
259
+ // the Ctx frame Provider pushed, so this re-run reads useContext
260
+ // against a stack that no longer contains the provider — and
261
+ // `lastSeen` becomes `'default'`.
262
+ trigger.set(1)
263
+ await new Promise((r) => setTimeout(r, 20))
264
+ expect(lastSeen).toBe('provider-value')
265
+ // Sanity: the re-run actually happened. Otherwise the test could
266
+ // pass for the wrong reason (e.g. if the trigger subscription wasn't
267
+ // established because the accessor didn't read `trigger()` reactively).
268
+ expect(runCount).toBeGreaterThan(initialRunCount)
269
+ })
177
270
  })
@@ -1,5 +1,5 @@
1
1
  import { computed, signal } from '@pyreon/reactivity'
2
- import { _bindDirect, _bindText } from '../template'
2
+ import { _bindDirect, _bindText, _clearTplCache, _tpl, _tplCacheSize } from '../template'
3
3
 
4
4
  // ─── _bindText ──────────────────────────────────────────────────────────────
5
5
 
@@ -311,3 +311,73 @@ describe('_mountSlot', async () => {
311
311
  expect(parent.childNodes.length).toBe(0)
312
312
  })
313
313
  })
314
+
315
+ // ─── Audit bug #5: _tplCache LRU eviction ───────────────────────────────────
316
+ //
317
+ // The cache is an LRU-bounded Map keyed on the HTML string. Typed JSX
318
+ // produces a small bounded set of unique HTML strings — most apps stay in
319
+ // the dozens-to-hundreds. But an app that constructs JSX from user input
320
+ // or compiles many large dynamic templates could grow this unbounded
321
+ // pre-fix. The cap at 1024 entries keeps memory predictable while being
322
+ // generous enough that no realistic codebase hits it.
323
+
324
+ describe('_tpl cache — LRU eviction (audit bug #5)', () => {
325
+ const TPL_CACHE_MAX = 1024
326
+
327
+ test('cache stays bounded when more than MAX unique templates are emitted', () => {
328
+ _clearTplCache()
329
+ const noBind = (): null => null
330
+
331
+ // Emit 1.5x the cap of unique templates — without LRU bound, cache
332
+ // would grow to 1536 entries.
333
+ const overshoot = Math.floor(TPL_CACHE_MAX * 1.5)
334
+ for (let i = 0; i < overshoot; i++) {
335
+ _tpl(`<div data-i="${i}">${i}</div>`, noBind)
336
+ }
337
+
338
+ expect(_tplCacheSize()).toBeLessThanOrEqual(TPL_CACHE_MAX)
339
+ expect(_tplCacheSize()).toBeGreaterThan(0)
340
+ })
341
+
342
+ test('eviction is oldest-first; recently-touched entries survive', () => {
343
+ _clearTplCache()
344
+ const noBind = (): null => null
345
+
346
+ // Fill the cache to the cap.
347
+ const baseHtml = (i: number): string => `<span data-i="${i}">${i}</span>`
348
+ for (let i = 0; i < TPL_CACHE_MAX; i++) _tpl(baseHtml(i), noBind)
349
+ expect(_tplCacheSize()).toBe(TPL_CACHE_MAX)
350
+
351
+ // Touch entry 0 (the oldest). Map insertion-order semantics mean a
352
+ // re-insert after delete moves it to the most-recent position.
353
+ _tpl(baseHtml(0), noBind)
354
+
355
+ // Add ONE new entry — the OLDEST untouched entry should evict, NOT entry 0.
356
+ _tpl('<p>brand-new</p>', noBind)
357
+
358
+ expect(_tplCacheSize()).toBe(TPL_CACHE_MAX)
359
+
360
+ // Touch entry 0 again — if eviction policy were broken and entry 0
361
+ // had been evicted, this re-creates it. We need a way to assert it
362
+ // was retained. Approach: count cache misses by checking size delta.
363
+ // Adding the brand-new entry above evicted ONE; the cache stayed at
364
+ // cap. If we now add 1 more brand-new entry without re-using existing
365
+ // keys, size stays at cap. If we re-touch entry 0, size also stays at
366
+ // cap (already cached). The assertion: re-emitting entry 0 must NOT
367
+ // grow the cache (cache hit, not miss).
368
+ const sizeBeforeReHit = _tplCacheSize()
369
+ _tpl(baseHtml(0), noBind)
370
+ expect(_tplCacheSize()).toBe(sizeBeforeReHit) // re-emit was a hit
371
+ })
372
+
373
+ test('repeated emit of same template produces ONE cached entry', () => {
374
+ _clearTplCache()
375
+ const noBind = (): null => null
376
+
377
+ for (let i = 0; i < 100; i++) {
378
+ _tpl('<div class="static"></div>', noBind)
379
+ }
380
+
381
+ expect(_tplCacheSize()).toBe(1)
382
+ })
383
+ })
@@ -118,7 +118,11 @@ describe('Transition', () => {
118
118
  const target = el.querySelector('.lifecycle') as HTMLElement
119
119
  if (target) {
120
120
  target.dispatchEvent(new Event('transitionend'))
121
- await new Promise<void>((r) => setTimeout(r, 10))
121
+ // 10ms was too tight under CI scheduling pressure — the dispatched
122
+ // event's listener callback runs on next-tick + microtask flush,
123
+ // and shared CI runners can have 10-30ms scheduling latency. 50ms
124
+ // gives enough headroom without slowing the test meaningfully.
125
+ await new Promise<void>((r) => setTimeout(r, 50))
122
126
  expect(onAfterEnter).toHaveBeenCalled()
123
127
  }
124
128
  })
@@ -1,5 +1,5 @@
1
1
  import type { Props, VNode, VNodeChild } from '@pyreon/core'
2
- import { createRef, h, onMount, onUnmount } from '@pyreon/core'
2
+ import { createRef, h, nativeCompat, onMount, onUnmount } from '@pyreon/core'
3
3
  import { effect, runUntracked, signal } from '@pyreon/reactivity'
4
4
  import { mountChild } from './mount'
5
5
 
@@ -199,12 +199,22 @@ export function TransitionGroup<T = unknown>(props: TransitionGroupProps<T>): VN
199
199
  const key = props.keyFn(item, i)
200
200
  if (entries.has(key)) continue
201
201
  const itemRef = createRef<HTMLElement>()
202
- const rawVNode = runUntracked(() => props.render(item, i))
203
- const vnode: VNode =
204
- typeof rawVNode.type === 'string'
205
- ? { ...rawVNode, props: { ...rawVNode.props, ref: itemRef } as Props }
206
- : rawVNode
207
- const cleanup = mountChild(vnode, container, null)
202
+ // Both render AND mountChild must run untracked — child component
203
+ // setup (signal reads inside the render callback's resulting tree,
204
+ // useTheme / useQuery's options() construction etc.) must NOT
205
+ // subscribe this effect. Otherwise an unrelated signal flip re-runs
206
+ // the TransitionGroup effect, runCleanup() disposes the children's
207
+ // inner effects, and the next mount path skips re-rendering kept
208
+ // entries → the inner reactivity is lost. Same shape as the
209
+ // mountFor / mountKeyedList fix in nodes.ts.
210
+ const cleanup = runUntracked(() => {
211
+ const rawVNode = props.render(item, i)
212
+ const vnode: VNode =
213
+ typeof rawVNode.type === 'string'
214
+ ? { ...rawVNode, props: { ...rawVNode.props, ref: itemRef } as Props }
215
+ : rawVNode
216
+ return mountChild(vnode, container, null)
217
+ })
208
218
  const entry: ItemEntry = { key, ref: itemRef, cleanup, leaving: false, cancelTransition: null }
209
219
  entries.set(key, entry)
210
220
  newEntries.push(entry)
@@ -333,3 +343,8 @@ export function TransitionGroup<T = unknown>(props: TransitionGroupProps<T>): VN
333
343
 
334
344
  return h(tag, { ref: containerRef })
335
345
  }
346
+
347
+ // Mark as native so compat-mode jsx() runtimes skip wrapCompatComponent —
348
+ // TransitionGroup uses signal/effect/onMount/onUnmount + mountChild that
349
+ // need Pyreon's setup frame.
350
+ nativeCompat(TransitionGroup)
package/src/transition.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Props, VNode, VNodeChild } from '@pyreon/core'
2
- import { createRef, Fragment, h, onUnmount } from '@pyreon/core'
2
+ import { createRef, Fragment, h, nativeCompat, onUnmount } from '@pyreon/core'
3
3
  import { effect, runUntracked, signal } from '@pyreon/reactivity'
4
4
 
5
5
  // Dev-mode gate: `import.meta.env.DEV` is the Vite/Rolldown standard,
@@ -7,8 +7,7 @@ import { effect, runUntracked, signal } from '@pyreon/reactivity'
7
7
  // pattern was dead code in real Vite browser bundles because Vite does not
8
8
  // polyfill `process` for the client — every wrapped warning silently never
9
9
  // fired in dev. Enforced by the `pyreon/no-process-dev-gate` lint rule.
10
- // @ts-ignore `import.meta.env.DEV` is provided by Vite/Rolldown at build time
11
- const __DEV__ = import.meta.env?.DEV === true
10
+ const __DEV__ = process.env.NODE_ENV !== 'production'
12
11
 
13
12
  export interface TransitionProps {
14
13
  /**
@@ -189,6 +188,11 @@ export function Transition(props: TransitionProps): VNodeChild {
189
188
  applyLeave(el)
190
189
  }
191
190
 
191
+ // queueMicrotask defers the appear-animation to after the DOM has
192
+ // committed the initial mount — that scheduling IS the reactive
193
+ // subscription's job here (it tracks `props.show()` and `props.appear`
194
+ // and schedules the visual transition). Not setup work.
195
+ // pyreon-lint-disable-next-line pyreon/no-imperative-effect-on-create
192
196
  effect(() => {
193
197
  const visible = props.show()
194
198
  if (!initialized) {
@@ -235,3 +239,7 @@ export function Transition(props: TransitionProps): VNodeChild {
235
239
  return { ...vnode, props: { ...vnode.props, ref } as Props }
236
240
  }) as unknown as VNode
237
241
  }
242
+
243
+ // Mark as native so compat-mode jsx() runtimes skip wrapCompatComponent —
244
+ // Transition uses signal/effect/onUnmount that need Pyreon's setup frame.
245
+ nativeCompat(Transition)