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
package/src/dom/loop.ts CHANGED
@@ -2,9 +2,9 @@
2
2
  // LIS minimal DOM moves (swap = 2 moves), and O(1) parent.textContent = '' clear.
3
3
 
4
4
  import type { Owner, Signal } from '../reactivity/index'
5
- import { createOwner, disposeOwner, effect, getOwner, onCleanup, runWithOwner, signal, untrack } from '../reactivity/index'
5
+ import { createOwner, disposeOwner, domEffect, getOwner, onCleanup, runInOwner, signal, untrack } from '../reactivity/index'
6
6
  import { claimLoop } from './claim'
7
- import { hydrateCursor, isRangeEnd, setMismatchHook, skipRange } from './index'
7
+ import { hydrateCursor, isHydrating, isRangeEnd, setMismatchHook, skipRange } from './index'
8
8
 
9
9
  interface Row<T> {
10
10
  key: unknown
@@ -83,9 +83,60 @@ function keepEnds<T>(rows: Row<T>[], start: number, oldEnd: number, newEnd: numb
83
83
  type RenderRow<T> = (item: Signal<T>, index?: Signal<number>) => Node | DocumentFragment | null | undefined | boolean | string | number
84
84
 
85
85
 
86
- function pushRange(out: Node[], from: Node | null, stop: Node | null): void {
86
+ function warnDuplicateKey(key: unknown): void {
87
+ const label = typeof key === 'string' ? JSON.stringify(key) : String(key)
88
+ console.warn(`prunelle: duplicate key ${label} in list: each item's key must be unique.`)
89
+ }
90
+
91
+ function buildOldMap<T>(rows: Row<T>[], start: number, oldEnd: number): Map<unknown, number> {
92
+ const map = new Map<unknown, number>()
93
+ for (let i = start; i < oldEnd; i++) {
94
+ const k = rows[i]!.key
95
+ if (process.env.NODE_ENV !== 'production' && map.has(k))
96
+ warnDuplicateKey(k)
97
+ map.set(k, i)
98
+ }
99
+ return map
100
+ }
101
+
102
+ function matchMiddle<T>(
103
+ next: readonly T[],
104
+ start: number,
105
+ midLen: number,
106
+ keyFn: (item: T, index: number) => unknown,
107
+ oldMap: Map<unknown, number>,
108
+ used: Uint8Array,
109
+ newKeys: unknown[],
110
+ matchedOldIdx: Int32Array,
111
+ ): number {
112
+ const seen = process.env.NODE_ENV !== 'production' ? new Set<unknown>() : undefined
113
+ let reused = 0
114
+ for (let i = 0; i < midLen; i++) {
115
+ const idx = start + i
116
+ const k = keyFn(next[idx]!, idx)
117
+ newKeys[i] = k
118
+ if (seen !== undefined) {
119
+ if (seen.has(k))
120
+ warnDuplicateKey(k)
121
+ else
122
+ seen.add(k)
123
+ }
124
+ const oldIdx = oldMap.get(k)
125
+ if (oldIdx !== undefined && used[oldIdx - start] === 0) {
126
+ used[oldIdx - start] = 1
127
+ matchedOldIdx[i] = oldIdx
128
+ reused++
129
+ }
130
+ else {
131
+ matchedOldIdx[i] = -1
132
+ }
133
+ }
134
+ return reused
135
+ }
136
+
137
+ function pushRange(out: Set<Node>, from: Node | null, stop: Node | null): void {
87
138
  for (let n = from; n !== null && n !== stop && !isRangeEnd(n); n = n.nextSibling)
88
- out.push(n)
139
+ out.add(n)
89
140
  }
90
141
 
91
142
  // While hydrating, a row that rendered no node of its own takes the server nodes the cursor moved over since `before`.
@@ -95,7 +146,7 @@ function adoptRowNodes<T>(
95
146
  row: Row<T>,
96
147
  before: Node | null,
97
148
  prevSib: Node | null,
98
- leftover: Node[],
149
+ leftover: Set<Node>,
99
150
  fallbackEnd: Node | null,
100
151
  ): boolean {
101
152
  const afterCursor = hydrateCursor()
@@ -103,7 +154,7 @@ function adoptRowNodes<T>(
103
154
  const start = before.parentNode === parent ? before : prevSib !== null ? prevSib.nextSibling : parent.firstChild
104
155
  const claimed: Node[] = []
105
156
  for (let n: Node | null = start; n !== null && n !== afterCursor && n !== marker && n !== fallbackEnd && !isRangeEnd(n); n = n.nextSibling) {
106
- if (!leftover.includes(n))
157
+ if (!leftover.has(n))
107
158
  claimed.push(n)
108
159
  }
109
160
  if (claimed.length === 1) {
@@ -122,71 +173,183 @@ function adoptRowNodes<T>(
122
173
  }
123
174
 
124
175
  // Server nodes no client row claimed (stepped over mid-list, or past the last row): the data changed between the render and hydration, so they would stay in the DOM outside `rows`. They are removed, and the island hears `pru:hydration-mismatch`.
125
- function dropServerRows(parent: Node, leftover: Node[], from: Node | null, marker: Node | null, added: number): void {
176
+ function dropServerRows(parent: Node, leftover: Set<Node>, from: Node | null, marker: Node | null, added: number): void {
126
177
  pushRange(leftover, from, marker)
127
- if (leftover.length === 0 && added === 0)
178
+ if (leftover.size === 0 && added === 0)
128
179
  return
129
180
  if (process.env.NODE_ENV !== 'production')
130
- console.warn(`prunelle: hydration mismatch in a list: removed ${leftover.length} server node(s) and added ${added} client row(s): the island's data changed after the server rendered it.`)
181
+ console.warn(`prunelle: hydration mismatch in a list: removed ${leftover.size} server node(s) and added ${added} client row(s): the island's data changed after the server rendered it.`)
131
182
  for (const n of leftover)
132
183
  (n as ChildNode).remove()
133
184
  const { CustomEvent: Mismatch } = parent.ownerDocument!.defaultView!
134
- parent.dispatchEvent(new Mismatch('pru:hydration-mismatch', { bubbles: true, detail: { removed: leftover.length, added } }))
185
+ parent.dispatchEvent(new Mismatch('pru:hydration-mismatch', { bubbles: true, detail: { removed: leftover.size, added } }))
135
186
  }
136
187
 
137
188
  // The first rows: claimed from the server's while hydrating, else rendered into a fragment inserted at once.
138
189
  function createRows<T>(parent: Node, marker: Node | null, items: readonly T[], newRow: (item: T, index: number) => Row<T>, skip: number, startMarker: Node | null | undefined): Row<T>[] {
139
190
  const created = new Array<Row<T>>(items.length)
140
- let end: Node | null = null
141
- const leftover: Node[] = []
142
- let added = 0
143
- let fallbackEnd: Node | null = null
144
- if (claimLoop(parent, () => {
145
- const prevHook = setMismatchHook((p, stale, target) => {
146
- if (p !== parent)
147
- return
148
- if (stale.parentNode === null) {
149
- leftover.push(stale)
150
- added++
151
- pushRange(leftover, fallbackEnd = target.nextSibling, marker)
152
- }
153
- else {
154
- pushRange(leftover, stale, target)
155
- }
156
- })
157
- try {
158
- for (let i = 0; i < items.length; i++) {
159
- const before = hydrateCursor()
160
- const prevSib = before?.previousSibling ?? null
161
- const row = newRow(items[i]!, i)
162
- if (adoptRowNodes(parent, marker, row, before, prevSib, leftover, fallbackEnd))
191
+ if (isHydrating()) {
192
+ let end: Node | null = null
193
+ const leftover = new Set<Node>()
194
+ let added = 0
195
+ let fallbackEnd: Node | null = null
196
+ claimLoop(parent, () => {
197
+ const prevHook = setMismatchHook((p, stale, target) => {
198
+ if (p !== parent)
199
+ return
200
+ if (stale.parentNode === null) {
201
+ leftover.add(stale)
163
202
  added++
164
- created[i] = row
203
+ pushRange(leftover, fallbackEnd = target.nextSibling, marker)
204
+ }
205
+ else {
206
+ pushRange(leftover, stale, target)
207
+ }
208
+ })
209
+ try {
210
+ for (let i = 0; i < items.length; i++) {
211
+ const before = hydrateCursor()
212
+ const prevSib = before?.previousSibling ?? null
213
+ const row = newRow(items[i]!, i)
214
+ if (adoptRowNodes(parent, marker, row, before, prevSib, leftover, fallbackEnd))
215
+ added++
216
+ created[i] = row
217
+ }
218
+ end = hydrateCursor()
165
219
  }
166
- end = hydrateCursor()
167
- }
168
- finally {
169
- setMismatchHook(prevHook)
170
- }
171
- }, skip, startMarker)) {
220
+ finally {
221
+ setMismatchHook(prevHook)
222
+ }
223
+ }, skip, startMarker)
172
224
  dropServerRows(parent, leftover, end, marker, added)
173
225
  return created
174
226
  }
175
227
  if (items.length > 0) {
176
228
  const frag = document.createDocumentFragment()
177
229
  for (let i = 0; i < items.length; i++) {
178
- created[i] = newRow(items[i]!, i)
179
- insertRow(frag, created[i]!, null)
230
+ const row = newRow(items[i]!, i)
231
+ created[i] = row
232
+ insertRow(frag, row, null)
180
233
  }
181
234
  parent.insertBefore(frag, marker)
182
235
  }
183
236
  return created
184
237
  }
185
238
 
239
+ function updateRow<T>(row: Row<T>, item: T, idx: number): void {
240
+ row.item.value = item
241
+ if (row.index !== undefined)
242
+ row.index.value = idx
243
+ }
244
+
245
+ function materializeRow<T>(raw: ReturnType<RenderRow<T>>, key: unknown, item: Signal<T>, index: Signal<number> | undefined, owner: Owner): Row<T> {
246
+ let node: Node | null = null
247
+ let nodes: Node[] | undefined
248
+ if (raw instanceof Node) {
249
+ if (raw.nodeType === 11) {
250
+ const len = raw.childNodes.length
251
+ if (len === 1) {
252
+ node = raw.firstChild
253
+ }
254
+ else if (len > 1) {
255
+ nodes = Array.from(raw.childNodes)
256
+ node = nodes[0]!
257
+ }
258
+ }
259
+ else {
260
+ node = raw
261
+ }
262
+ }
263
+ else if (typeof raw === 'string' || typeof raw === 'number') {
264
+ const str = String(raw)
265
+ if (str !== '')
266
+ node = document.createTextNode(str)
267
+ }
268
+ return nodes !== undefined ? { key, node, nodes, item, index, owner } : { key, node, item, index, owner }
269
+ }
270
+
271
+ function reconcileMiddle<T>(
272
+ parent: Node,
273
+ marker: Node | null,
274
+ after: Node | null,
275
+ rows: Row<T>[],
276
+ next: readonly T[],
277
+ start: number,
278
+ oldEnd: number,
279
+ newEnd: number,
280
+ keyFn: (item: T, index: number) => unknown,
281
+ makeRow: (itemVal: T, idx: number, key: unknown) => Row<T>,
282
+ skip: number,
283
+ ): Row<T>[] {
284
+ const prevLen = rows.length
285
+ const nextLen = next.length
286
+ const oldMap = buildOldMap(rows, start, oldEnd)
287
+
288
+ const midLen = newEnd - start
289
+ const result = keepEnds(rows, start, oldEnd, newEnd, nextLen)
290
+
291
+ const used = new Uint8Array(oldEnd - start)
292
+ const newKeys = new Array<unknown>(midLen)
293
+ const matchedOldIdx = new Int32Array(midLen)
294
+ const reused = matchMiddle(next, start, midLen, keyFn, oldMap, used, newKeys, matchedOldIdx)
295
+
296
+ // Full replacement fast path (replace 1,000 rows)
297
+ if (reused === 0 && start === 0 && oldEnd === prevLen && marker === null && skip === 0) {
298
+ for (let i = 0; i < prevLen; i++)
299
+ disposeOwner(rows[i]!.owner)
300
+ ;(parent as Element).textContent = ''
301
+ const frag = document.createDocumentFragment()
302
+ for (let i = 0; i < nextLen; i++) {
303
+ const row = makeRow(next[i]!, i, newKeys[i])
304
+ result[i] = row
305
+ insertRow(frag, row, null)
306
+ }
307
+ parent.appendChild(frag)
308
+ return result
309
+ }
310
+
311
+ // Remove unused old rows
312
+ for (let i = start; i < oldEnd; i++) {
313
+ if (used[i - start] === 0) {
314
+ const row = rows[i]!
315
+ disposeOwner(row.owner)
316
+ removeRow(row)
317
+ }
318
+ }
319
+
320
+ // Longest Increasing Subsequence for minimal DOM moves (swap = 2 moves)
321
+ const lis = reused > 0 ? longestIncreasingSubsequence(matchedOldIdx) : EMPTY_NUMS
322
+ let lisPos = lis.length - 1
323
+
324
+ let anchor: Node | null = after
325
+ for (let i = midLen - 1; i >= 0; i--) {
326
+ const idx = start + i
327
+ const oldIdx = matchedOldIdx[i]!
328
+ let row: Row<T>
329
+ if (oldIdx !== -1) {
330
+ row = rows[oldIdx]!
331
+ updateRow(row, next[idx]!, idx)
332
+ if (lisPos >= 0 && lis[lisPos] === i)
333
+ lisPos--
334
+ else
335
+ insertRow(parent, row, anchor)
336
+ }
337
+ else {
338
+ row = makeRow(next[idx]!, idx, newKeys[i])
339
+ insertRow(parent, row, anchor)
340
+ }
341
+ result[idx] = row
342
+ if (row.node !== null)
343
+ anchor = row.node
344
+ }
345
+
346
+ return result
347
+ }
348
+
186
349
  export function loop<T>(
187
350
  parent: Node,
188
351
  marker: Node | null,
189
- each: () => readonly T[] | null | undefined | false,
352
+ each: () => Iterable<T> | null | undefined | false,
190
353
  keyFn: (item: T, index: number) => unknown,
191
354
  renderRow: RenderRow<T>,
192
355
  skip = 0,
@@ -210,7 +373,7 @@ export function loop<T>(
210
373
  const index = needsIndex ? signal(idx) : undefined
211
374
  let raw: ReturnType<RenderRow<T>>
212
375
  try {
213
- raw = runWithOwner(owner, () => renderRow(item, index))
376
+ raw = runInOwner(owner, renderRow, item, index)
214
377
  }
215
378
  catch (err) {
216
379
  disposeOwner(owner)
@@ -220,32 +383,10 @@ export function loop<T>(
220
383
  }
221
384
  return { key: Symbol(), node: null, item, index, owner }
222
385
  }
223
- let node: Node | null = null
224
- let nodes: Node[] | undefined
225
- if (raw instanceof Node) {
226
- if (raw.nodeType === 11) {
227
- const len = raw.childNodes.length
228
- if (len === 1) {
229
- node = raw.firstChild
230
- }
231
- else if (len > 1) {
232
- nodes = Array.from(raw.childNodes)
233
- node = nodes[0]!
234
- }
235
- }
236
- else {
237
- node = raw
238
- }
239
- }
240
- else if (typeof raw === 'string' || typeof raw === 'number') {
241
- const str = String(raw)
242
- if (str !== '')
243
- node = document.createTextNode(str)
244
- }
245
- return nodes !== undefined ? { key, node, nodes, item, index, owner } : { key, node, item, index, owner }
386
+ return materializeRow(raw, key, item, index, owner)
246
387
  }
247
388
 
248
- effect(() => {
389
+ domEffect(() => {
249
390
  let startMarker: Node | null | undefined
250
391
  if (firstRun) {
251
392
  firstRun = false
@@ -259,7 +400,8 @@ export function loop<T>(
259
400
  }
260
401
 
261
402
  const list = each()
262
- const next = list === false || list == null ? EMPTY : list
403
+ // An iterator or a Set has no `.length`: read it into an array so `set.values().map(...)` renders its rows.
404
+ const next: readonly T[] = list === false || list == null ? EMPTY : Array.isArray(list) ? list : Array.from(list)
263
405
  const nextLen = next.length
264
406
  const prevLen = rows.length
265
407
 
@@ -268,13 +410,10 @@ export function loop<T>(
268
410
  if (nextLen === 0 && prevLen > 0) {
269
411
  for (let i = 0; i < prevLen; i++)
270
412
  disposeOwner(rows[i]!.owner)
271
- if (marker === null && skip === 0) {
272
- ;(parent as Element).textContent = ''
273
- }
274
- else {
275
- for (let i = 0; i < prevLen; i++)
276
- removeRow(rows[i]!)
277
- }
413
+ if (marker === null && skip === 0)
414
+ (parent as Element).textContent = ''
415
+ else
416
+ for (let i = 0; i < prevLen; i++) removeRow(rows[i]!)
278
417
  rows = []
279
418
  return
280
419
  }
@@ -285,37 +424,50 @@ export function loop<T>(
285
424
  return
286
425
  }
287
426
 
288
- // Common prefix scan
427
+ // Common prefix, common suffix, and cross-end swap fast paths
289
428
  let start = 0
290
- while (start < prevLen && start < nextLen) {
291
- const item = next[start]!
292
- const k = keyFn(item, start)
293
- const prevRow = rows[start]!
294
- if (prevRow.key !== k)
295
- break
296
- prevRow.item.value = item
297
- if (prevRow.index !== undefined)
298
- prevRow.index.value = start
299
- start++
300
- }
301
-
302
- // Common suffix scan
303
429
  let oldEnd = prevLen
304
430
  let newEnd = nextLen
305
- while (oldEnd > start && newEnd > start) {
306
- const item = next[newEnd - 1]!
307
- const k = keyFn(item, newEnd - 1)
308
- const prevRow = rows[oldEnd - 1]!
309
- if (prevRow.key !== k)
310
- break
311
- prevRow.item.value = item
312
- if (prevRow.index !== undefined)
313
- prevRow.index.value = newEnd - 1
314
- oldEnd--
315
- newEnd--
431
+ let hasStartKey = false
432
+ let startKey: unknown
433
+ while (start < oldEnd && start < newEnd) {
434
+ const startItem = next[start]!
435
+ if (!hasStartKey) {
436
+ startKey = keyFn(startItem, start)
437
+ hasStartKey = true
438
+ }
439
+ if (rows[start]!.key === startKey) {
440
+ updateRow(rows[start]!, startItem, start++)
441
+ hasStartKey = false
442
+ continue
443
+ }
444
+ const endItem = next[newEnd - 1]!
445
+ const endKey = keyFn(endItem, newEnd - 1)
446
+ if (rows[oldEnd - 1]!.key === endKey) {
447
+ updateRow(rows[--oldEnd]!, endItem, --newEnd)
448
+ continue
449
+ }
450
+ if (oldEnd === newEnd && start < oldEnd - 1 && rows[start]!.key === endKey && rows[oldEnd - 1]!.key === startKey) {
451
+ const a = rows[start]!
452
+ const b = rows[oldEnd - 1]!
453
+ if (a.node !== null && b.node !== null && a.nodes === undefined && b.nodes === undefined) {
454
+ const bNext = b.node.nextSibling
455
+ const adj = a.node.nextSibling === b.node
456
+ parent.insertBefore(b.node, a.node)
457
+ if (!adj)
458
+ parent.insertBefore(a.node, bNext)
459
+ rows[start] = b
460
+ rows[--oldEnd] = a
461
+ updateRow(b, startItem, start++)
462
+ updateRow(a, endItem, --newEnd)
463
+ hasStartKey = false
464
+ continue
465
+ }
466
+ }
467
+ break
316
468
  }
317
469
 
318
- // Fast path 3: In-place update only (e.g. update every 10th row)
470
+ // Fast path 3: In-place update / cross-end swaps only
319
471
  if (start === oldEnd && start === newEnd)
320
472
  return
321
473
 
@@ -323,11 +475,9 @@ export function loop<T>(
323
475
 
324
476
  // Fast path 4: Pure insertion (e.g. append 1,000 rows)
325
477
  if (start === oldEnd) {
326
- const addCount = newEnd - start
327
478
  const result = keepEnds(rows, start, oldEnd, newEnd, nextLen)
328
479
  const frag = document.createDocumentFragment()
329
- for (let i = 0; i < addCount; i++) {
330
- const idx = start + i
480
+ for (let idx = start; idx < newEnd; idx++) {
331
481
  const item = next[idx]!
332
482
  const row = makeRow(item, idx, keyFn(item, idx))
333
483
  result[idx] = row
@@ -349,92 +499,13 @@ export function loop<T>(
349
499
  return
350
500
  }
351
501
 
352
- // General middle reconcile
353
- const oldMap = new Map<unknown, number>()
354
- for (let i = start; i < oldEnd; i++)
355
- oldMap.set(rows[i]!.key, i)
356
-
357
- const midLen = newEnd - start
358
- const result = keepEnds(rows, start, oldEnd, newEnd, nextLen)
359
-
360
- const used = new Uint8Array(oldEnd - start)
361
- let reused = 0
362
-
363
- const newKeys = new Array<unknown>(midLen)
364
- const matchedOldIdx = new Int32Array(midLen)
365
- for (let i = 0; i < midLen; i++) {
366
- const idx = start + i
367
- const k = keyFn(next[idx]!, idx)
368
- newKeys[i] = k
369
- const oldIdx = oldMap.get(k)
370
- if (oldIdx !== undefined && used[oldIdx - start] === 0) {
371
- used[oldIdx - start] = 1
372
- matchedOldIdx[i] = oldIdx
373
- reused++
374
- }
375
- else {
376
- matchedOldIdx[i] = -1
377
- }
378
- }
379
-
380
- // Full replacement fast path (replace 1,000 rows)
381
- if (reused === 0 && start === 0 && oldEnd === prevLen && marker === null && skip === 0) {
382
- for (let i = 0; i < prevLen; i++)
383
- disposeOwner(rows[i]!.owner)
384
- ;(parent as Element).textContent = ''
385
- const frag = document.createDocumentFragment()
386
- for (let i = 0; i < nextLen; i++) {
387
- const row = makeRow(next[i]!, i, newKeys[i])
388
- result[i] = row
389
- insertRow(frag, row, null)
390
- }
391
- parent.appendChild(frag)
392
- rows = result
393
- return
394
- }
395
-
396
- // Remove unused old rows
397
- for (let i = start; i < oldEnd; i++) {
398
- if (used[i - start] === 0) {
399
- const row = rows[i]!
400
- disposeOwner(row.owner)
401
- removeRow(row)
402
- }
403
- }
404
-
405
- // Longest Increasing Subsequence for minimal DOM moves (swap = 2 moves)
406
- const lis = reused > 0 ? longestIncreasingSubsequence(matchedOldIdx) : EMPTY_NUMS
407
- let lisPos = lis.length - 1
408
-
409
- let anchor: Node | null = after
410
- for (let i = midLen - 1; i >= 0; i--) {
411
- const idx = start + i
412
- const oldIdx = matchedOldIdx[i]!
413
- let row: Row<T>
414
- if (oldIdx !== -1) {
415
- row = rows[oldIdx]!
416
- row.item.value = next[idx]!
417
- if (row.index !== undefined)
418
- row.index.value = idx
419
- if (lisPos >= 0 && lis[lisPos] === i)
420
- lisPos--
421
- else
422
- insertRow(parent, row, anchor)
423
- }
424
- else {
425
- row = makeRow(next[idx]!, idx, newKeys[i])
426
- insertRow(parent, row, anchor)
427
- }
428
- result[idx] = row
429
- if (row.node !== null)
430
- anchor = row.node
431
- }
432
-
433
- rows = result
502
+ rows = reconcileMiddle(parent, marker, after, rows, next, start, oldEnd, newEnd, keyFn, makeRow, skip)
434
503
  })
435
504
  if (failed) {
505
+ const err = error
506
+ error = undefined
436
507
  failed = false
437
- throw error
508
+ throw err
438
509
  }
439
510
  })
440
511
  }
@@ -8,6 +8,9 @@ export interface PrefetchEntry {
8
8
  region: string | null
9
9
  /** The percent-encoded `x-pru-title` of a region answer: the title the page has at this URL. */
10
10
  title: string | null
11
+ /** The `x-pru-icon` (a URL) and the percent-encoded `x-pru-attrs` of a region answer: the page's tab icon, and the region element's own attributes. */
12
+ icon?: string | null | undefined
13
+ attrs?: string | null | undefined
11
14
  /** The `x-pru-build` of a region answer: the build whose scripts and stylesheets its markup expects. */
12
15
  build?: string | null | undefined
13
16
  /** Response Content-Security-Policy header, used by `spa()` to detect blocked destination `<style>` tags. */
@@ -105,7 +108,7 @@ export async function prefetch(url: string, region?: string): Promise<void> {
105
108
  void res.body?.cancel()
106
109
  return undefined
107
110
  }
108
- const entry: PrefetchEntry = { html: await res.text(), url: res.url || clean.href, ts: Date.now(), region: res.headers.get('x-pru-region'), title: res.headers.get('x-pru-title'), build: res.headers.get('x-pru-build'), csp: res.headers.get('content-security-policy'), view: res.headers.get('x-pru-view') }
111
+ const entry: PrefetchEntry = { html: await res.text(), url: res.url || clean.href, ts: Date.now(), region: res.headers.get('x-pru-region'), title: res.headers.get('x-pru-title'), icon: res.headers.get('x-pru-icon'), attrs: res.headers.get('x-pru-attrs'), build: res.headers.get('x-pru-build'), csp: res.headers.get('content-security-policy'), view: res.headers.get('x-pru-view') }
109
112
  putCachedHtml(key, entry)
110
113
  return entry
111
114
  }
@@ -10,13 +10,18 @@
10
10
  import type { PrefetchEntry } from './prefetch'
11
11
  import type { EntryScroll } from './swap'
12
12
  import { countView, fetchKeyOf, getCachedHtml, getDocId, HTML_ACCEPT, inflightPrefetch, isSameDocRegionState, listenIntent, prefetch, prefetchCache } from './prefetch'
13
- import { announce, entryScroll, persistedIn, readScrolls, replaceKeeping, restoreScroll, saveScroll, swapInTransition, trackScroll, trustedHtml, writeScrolls } from './swap'
13
+ import { announce, entryScroll, persistedIn, readScrolls, replaceKeeping, restoreScroll, saveScroll, swapInTransition, syncElementAttrs, trackScroll, trustedHtml, writeScrolls } from './swap'
14
14
 
15
15
  const BUSY_DELAY = 150
16
16
  const LIVE_DEBOUNCE = 200
17
17
  const BURST_PAUSE = 1000
18
18
  const BUILD = 'script[data-pru-build]'
19
19
  const RUNTIME = 'script[data-pru-runtime]'
20
+ const RESEED = Symbol.for('pru.reseed')
21
+
22
+ function reseedRegion(target: ParentNode): void {
23
+ ;(globalThis as unknown as Record<symbol, ((root?: ParentNode) => void) | undefined>)[RESEED]?.(target)
24
+ }
20
25
 
21
26
  interface RegionState { __pruIdx: number, __pruDoc?: number | undefined, __pruRegion?: string | undefined }
22
27
 
@@ -111,7 +116,7 @@ async function load(swap: Swap, region: string, signal: AbortSignal): Promise<Pr
111
116
  }
112
117
  if (isValidationHtml && !res.redirected)
113
118
  swap.history = 'none'
114
- return { html: await res.text(), url: res.url || fetchKeyOf(url), ts: Date.now(), region: res.headers.get('x-pru-region'), title: res.headers.get('x-pru-title'), build: res.headers.get('x-pru-build') }
119
+ return { html: await res.text(), url: res.url || fetchKeyOf(url), ts: Date.now(), region: res.headers.get('x-pru-region'), title: res.headers.get('x-pru-title'), icon: res.headers.get('x-pru-icon'), attrs: res.headers.get('x-pru-attrs'), build: res.headers.get('x-pru-build') }
115
120
  }
116
121
 
117
122
  // A page and an answer that both name their build and name different ones: the tab was opened before a deploy.
@@ -120,8 +125,10 @@ function fromOtherBuild(answer: string | null | undefined): boolean {
120
125
  return typeof answer === 'string' && typeof page === 'string' && answer !== page
121
126
  }
122
127
 
123
- // The region's inner HTML and the page title: the answer itself when the server sent the region alone, else the region cut out of a full page (a prerendered page, a proxy that dropped the header).
124
- function contentOf(entry: PrefetchEntry, path: string): { content: DocumentFragment, title: string | undefined, build: string | null | undefined } | undefined {
128
+ // The region's inner HTML, the page title and icon, and the region's own attributes: the answer itself when the server sent the region alone, else the region cut out of a full page (a prerendered page, a proxy that dropped the header).
129
+ interface Found { content: DocumentFragment, title: string | undefined, icon: string | undefined, attrs: Element | undefined, build: string | null | undefined }
130
+
131
+ function contentOf(entry: PrefetchEntry, path: string): Found | undefined {
125
132
  const template = document.createElement('template')
126
133
  const leaf = path.split('/').at(-1)!
127
134
  if (entry.region === path || entry.region === leaf) {
@@ -129,14 +136,18 @@ function contentOf(entry: PrefetchEntry, path: string): { content: DocumentFragm
129
136
  // The title is HTML text, percent-encoded in the header: a textarea unescapes it.
130
137
  const unescape = document.createElement('textarea')
131
138
  unescape.innerHTML = trustedHtml(entry.title === null ? '' : decodeURIComponent(entry.title))
132
- return { content: template.content, title: entry.title === null ? undefined : unescape.value, build: entry.build }
139
+ // The region's own attributes, as its tag renders them: parsed as a tag of their own. An answer without the header (a proxy, an older server) leaves them as they are.
140
+ const tag = document.createElement('template')
141
+ if (entry.attrs != null)
142
+ tag.innerHTML = trustedHtml(`<i${decodeURIComponent(entry.attrs)}>`)
143
+ return { content: template.content, title: entry.title === null ? undefined : unescape.value, icon: entry.icon ?? undefined, attrs: tag.content.firstElementChild ?? undefined, build: entry.build }
133
144
  }
134
145
  const page = new DOMParser().parseFromString(trustedHtml(entry.html), 'text/html')
135
146
  const found = page.querySelector(`[data-pru-region="${leaf.replace(/["\\]/g, '\\$&')}"]`)
136
147
  if (found === null)
137
148
  return undefined
138
149
  template.innerHTML = trustedHtml(found.innerHTML)
139
- return { content: template.content, title: page.title === '' ? undefined : page.title, build: page.querySelector(BUILD)?.getAttribute('data-pru-build') }
150
+ return { content: template.content, title: page.title === '' ? undefined : page.title, icon: page.querySelector('link[rel=icon]')?.getAttribute('href') ?? undefined, attrs: found, build: page.querySelector(BUILD)?.getAttribute('data-pru-build') }
140
151
  }
141
152
 
142
153
  function record(url: URL, name: string, mode: 'push' | 'replace' | 'burst'): void {
@@ -221,8 +232,8 @@ function elementOfHash(hash: string): HTMLElement | null {
221
232
  return id === '' ? null : document.getElementById(id)
222
233
  }
223
234
 
224
- async function apply(region: HTMLElement, found: { content: DocumentFragment, title: string | undefined }, swap: Swap, finalUrl: URL): Promise<void> {
225
- const { content, title } = found
235
+ async function apply(region: HTMLElement, found: Found, swap: Swap, finalUrl: URL): Promise<void> {
236
+ const { content, title, icon, attrs } = found
226
237
  // A typing burst and an append stay put: a transition freezes the page, and the field being typed in with it.
227
238
  const animate = !swap.append && swap.history !== 'burst' && swap.fresh !== true
228
239
  await swapInTransition(() => {
@@ -246,13 +257,19 @@ async function apply(region: HTMLElement, found: { content: DocumentFragment, ti
246
257
  for (const inner of region.querySelectorAll('[data-pru-region]'))
247
258
  controllers.get(inner.getAttribute('data-pru-region')!)?.abort()
248
259
  replaceKeeping(region, content)
260
+ // The region's own attributes follow the new page, its name apart.
261
+ if (attrs !== undefined)
262
+ syncElementAttrs(region, attrs, 'data-pru-region')
249
263
  writeScrolls(kept)
250
264
  if (swap.history !== 'none' && !region.hasAttribute('data-pru-keep-scroll'))
251
265
  region.scrollTop = 0
252
266
  }
267
+ reseedRegion(region)
253
268
  ensureIslandRuntime(region)
254
269
  if (title !== undefined)
255
270
  document.title = title
271
+ if (icon !== undefined)
272
+ document.querySelector('link[rel=icon]')?.setAttribute('href', icon)
256
273
  syncParams()
257
274
  syncCurrent()
258
275
  if (swap.restore !== undefined)