@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.1

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 (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +442 -0
  4. package/src/build/compile.ts +20 -11
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +231 -1296
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +224 -0
  10. package/src/build/plugin-host.ts +184 -0
  11. package/src/build/prerender.ts +93 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +58 -0
  14. package/src/build/routes.ts +135 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +228 -114
  17. package/src/cli/index.ts +298 -79
  18. package/src/cli/new.ts +67 -35
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +822 -629
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +164 -21
  24. package/src/compiler/shared.ts +442 -0
  25. package/src/compiler/ssr.ts +390 -324
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +291 -76
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +157 -84
  30. package/src/dom/index.ts +154 -33
  31. package/src/dom/island.ts +117 -39
  32. package/src/dom/loop.ts +34 -21
  33. package/src/index.ts +2 -1
  34. package/src/jsx-runtime.ts +11 -0
  35. package/src/plugins/context.ts +57 -0
  36. package/src/plugins/index.ts +120 -17
  37. package/src/reactivity/index.ts +250 -157
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +37 -12
  40. package/src/server/action.ts +217 -74
  41. package/src/server/compress.ts +155 -56
  42. package/src/server/cookies.ts +59 -22
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +201 -33
  45. package/src/server/index.ts +964 -737
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +27 -8
  48. package/src/server/security.ts +87 -39
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +96 -10
  52. package/src/ssr/index.ts +225 -56
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -0
  55. package/src/unrenderable.ts +35 -0
package/src/dom/index.ts CHANGED
@@ -1,21 +1,32 @@
1
1
  // Kay v2 minimal DOM & hydration core (loop -> kay/dom-loop, extras -> kay/dom-extras for fine-grained chunk splitting).
2
2
 
3
+ import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
3
4
  import { batch, createOwner, disposeOwner, runWithOwner } from '../reactivity/index'
5
+ import { styleText } from '../style'
6
+ import { assertRenderable } from '../unrenderable'
4
7
 
8
+ export { isBlockedAttr } from '../attrs'
5
9
  export { effect } from '../reactivity/index'
6
10
 
7
11
  let hydrating = false
8
12
  let hydrateNode: Node | null = null
13
+ let hydrateRoot: Element | null = null
9
14
 
10
- export function claimLoop(parent: Node, fn: () => void, skip = 0): boolean {
15
+ export function claimLoop(parent: Node, fn: () => void, skip = 0, startMarker?: Node | null): boolean {
11
16
  if (!hydrating)
12
17
  return false
13
18
  const prevCursor = hydrateNode
14
- let cur = parent.firstChild
15
- for (let i = 0; i < skip && cur !== null; i++) {
16
- cur = cur.nextSibling
17
- while (cur !== null && (cur as unknown as { __kayAnchor?: boolean }).__kayAnchor === true)
19
+ let cur: Node | null
20
+ if (startMarker !== undefined && startMarker !== null) {
21
+ cur = startMarker.nextSibling
22
+ }
23
+ else {
24
+ cur = parent.firstChild
25
+ for (let i = 0; i < skip && cur !== null; i++) {
18
26
  cur = cur.nextSibling
27
+ while (cur !== null && (cur as unknown as { __kayAnchor?: boolean }).__kayAnchor === true)
28
+ cur = cur.nextSibling
29
+ }
19
30
  }
20
31
  hydrateNode = cur
21
32
  try {
@@ -27,12 +38,32 @@ export function claimLoop(parent: Node, fn: () => void, skip = 0): boolean {
27
38
  return true
28
39
  }
29
40
 
41
+ // The siblings from `from` up to, not including, `to`; undefined when there are none.
42
+ function between(from: Node | null, to: Node | null): Node[] | undefined {
43
+ const nodes: Node[] = []
44
+ for (let n = from; n !== null && n !== to; n = n.nextSibling)
45
+ nodes.push(n)
46
+ return nodes.length > 0 ? nodes : undefined
47
+ }
48
+
30
49
  // `nodes` is the SSR range the render claimed through template() (a fragment hydrates to null, so the caller learns its nodes here).
31
- export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T): { result: T, marker: Node | null, claimed: Node | null, nodes: Node[] | undefined } {
50
+ export function claimInsert<T>(
51
+ parent: Node,
52
+ marker: Node | null,
53
+ fn: () => T,
54
+ startMarker?: Node | null,
55
+ ): { result: T, marker: Node | null, claimed: Node | null, nodes: Node[] | undefined } {
32
56
  if (!hydrating)
33
57
  return { result: fn(), marker, claimed: null, nodes: undefined }
34
58
 
35
- const claimed: Node | null = marker === null ? parent.lastChild : marker.nodeType === 8 ? null : marker
59
+ let claimed: Node | null
60
+ if (startMarker !== undefined) {
61
+ const first = startMarker === null ? parent.firstChild : startMarker.nextSibling
62
+ claimed = first === marker ? null : first
63
+ }
64
+ else {
65
+ claimed = marker === null ? parent.lastChild : marker.nodeType === 8 ? null : marker
66
+ }
36
67
  const prevNode = hydrateNode
37
68
  hydrateNode = claimed
38
69
  let result: T
@@ -44,7 +75,11 @@ export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T):
44
75
  finally {
45
76
  hydrateNode = prevNode
46
77
  }
47
- if (marker === null || claimed === null)
78
+ if (startMarker !== undefined)
79
+ return { result, marker, claimed, nodes: between(claimed, marker) }
80
+ if (marker === null)
81
+ return { result, marker: null, claimed, nodes: between(claimed, end) }
82
+ if (claimed === null)
48
83
  return { result, marker, claimed, nodes: undefined }
49
84
 
50
85
  // The anchor goes after the claimed range; a text value or a nested insert moves no cursor and claims the one node.
@@ -52,37 +87,44 @@ export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T):
52
87
  const anchor = document.createComment('')
53
88
  ;(anchor as unknown as { __kayAnchor?: boolean }).__kayAnchor = true
54
89
  parent.insertBefore(anchor, consumed ? end : claimed.nextSibling)
55
- let nodes: Node[] | undefined
56
- if (consumed) {
57
- nodes = []
58
- for (let n: Node | null = claimed; n !== null && n !== anchor; n = n.nextSibling)
59
- nodes.push(n)
60
- }
61
- return { result, marker: anchor, claimed, nodes }
90
+ return { result, marker: anchor, claimed, nodes: consumed ? between(claimed, anchor) : undefined }
62
91
  }
63
92
 
64
- export function hydrate(container: Element, render: () => Node | DocumentFragment | null): () => void {
93
+ export function hydrate(container: Element, render: () => Node | DocumentFragment | null, idPrefix?: string): () => void {
65
94
  const owner = createOwner(undefined)
95
+ if (idPrefix !== undefined)
96
+ owner.id = { p: idPrefix, n: 0 }
66
97
  const prevHydrating = hydrating
67
98
  const prevNode = hydrateNode
99
+ const prevRoot = process.env.NODE_ENV !== 'production' ? hydrateRoot : null
68
100
  hydrating = true
69
101
  hydrateNode = container.firstChild
102
+ if (process.env.NODE_ENV !== 'production')
103
+ hydrateRoot = container
70
104
 
71
105
  try {
72
106
  runWithOwner(owner, () => {
73
107
  render()
74
108
  })
75
109
  }
110
+ catch (err) {
111
+ disposeOwner(owner)
112
+ throw err
113
+ }
76
114
  finally {
77
115
  hydrating = prevHydrating
78
116
  hydrateNode = prevNode
117
+ if (process.env.NODE_ENV !== 'production')
118
+ hydrateRoot = prevRoot
79
119
  }
80
120
 
81
121
  return () => disposeOwner(owner)
82
122
  }
83
123
 
84
- export function mount(container: Element, render: () => Node | DocumentFragment | null): () => void {
124
+ export function mount(container: Element, render: () => Node | DocumentFragment | null, idPrefix?: string): () => void {
85
125
  const owner = createOwner(undefined)
126
+ if (idPrefix !== undefined)
127
+ owner.id = { p: idPrefix, n: 0 }
86
128
  const prevHydrating = hydrating
87
129
  hydrating = false
88
130
  try {
@@ -91,6 +133,10 @@ export function mount(container: Element, render: () => Node | DocumentFragment
91
133
  if (node !== null)
92
134
  container.appendChild(node)
93
135
  }
136
+ catch (err) {
137
+ disposeOwner(owner)
138
+ throw err
139
+ }
94
140
  finally {
95
141
  hydrating = prevHydrating
96
142
  }
@@ -99,20 +145,46 @@ export function mount(container: Element, render: () => Node | DocumentFragment
99
145
 
100
146
  export function template(html: string, isSvg?: boolean): () => Node {
101
147
  let cached: Node | undefined
148
+ const expectedTag = process.env.NODE_ENV !== 'production'
149
+ ? /^<([A-Za-z][^\s/>]*)/.exec(html)?.[1]?.toLowerCase()
150
+ : undefined
151
+
152
+ const clone = (): Node => {
153
+ if (cached === undefined) {
154
+ const t = document.createElement('template')
155
+ t.innerHTML = isSvg ? `<svg>${html}</svg>` : html
156
+ cached = isSvg ? t.content.firstChild!.firstChild! : t.content.firstChild!
157
+ }
158
+ return cached.cloneNode(true)
159
+ }
102
160
 
103
161
  return (): Node => {
104
162
  if (hydrating && hydrateNode !== null) {
105
163
  const node = hydrateNode
164
+ if (process.env.NODE_ENV !== 'production' && expectedTag !== undefined) {
165
+ const foundTag = node.nodeType === 1 ? (node as Element).tagName.toLowerCase() : undefined
166
+ if (foundTag !== expectedTag) {
167
+ const island = hydrateRoot?.getAttribute('c') ?? hydrateRoot?.tagName.toLowerCase() ?? 'unknown'
168
+ const foundDesc = foundTag !== undefined
169
+ ? `<${foundTag}>`
170
+ : node.nodeType === 3
171
+ ? `#text(${JSON.stringify((node as Text).data.slice(0, 30))})`
172
+ : node.nodeType === 8
173
+ ? `<!--${(node as Comment).data}-->`
174
+ : `nodeType(${node.nodeType})`
175
+ console.warn(`kay: hydration mismatch in island "${island}": expected <${expectedTag}>, found ${foundDesc}; falling back to fresh clone.`)
176
+ hydrating = false
177
+ hydrateNode = null
178
+ const fresh = clone()
179
+ node.parentNode?.replaceChild(fresh, node)
180
+ return fresh
181
+ }
182
+ }
106
183
  hydrateNode = node.nextSibling
107
184
  return node
108
185
  }
109
186
 
110
- if (cached === undefined) {
111
- const t = document.createElement('template')
112
- t.innerHTML = isSvg ? `<svg>${html}</svg>` : html
113
- cached = isSvg ? t.content.firstChild!.firstChild! : t.content.firstChild!
114
- }
115
- return cached.cloneNode(true)
187
+ return clone()
116
188
  }
117
189
  }
118
190
 
@@ -134,16 +206,25 @@ export function eachStatic<T>(
134
206
  ): void {
135
207
  if (!items || items.length === 0)
136
208
  return
209
+ let startMarker: Node | null | undefined
210
+ let insertBefore = marker
211
+ if (marker !== null && marker.nodeType === 8 && (marker as Comment).data === 'k[') {
212
+ const close = skipRange(marker)
213
+ if (close !== null) {
214
+ startMarker = marker
215
+ insertBefore = close
216
+ }
217
+ }
137
218
  if (claimLoop(parent, () => {
138
219
  for (let i = 0; i < items.length; i++)
139
220
  render(items[i]!, i)
140
- }, skip)) {
221
+ }, skip, startMarker)) {
141
222
  return
142
223
  }
143
224
  const f = document.createDocumentFragment()
144
225
  for (let i = 0; i < items.length; i++)
145
226
  f.appendChild(render(items[i]!, i))
146
- parent.insertBefore(f, marker)
227
+ parent.insertBefore(f, insertBefore)
147
228
  }
148
229
 
149
230
  export function firstText(el: Node): Text {
@@ -170,13 +251,37 @@ export function skipText(marker: Node): Node | null {
170
251
  return next !== null && next.nodeType === 3 ? next.nextSibling : next
171
252
  }
172
253
 
254
+ /** Advance past an SSR-bracketed dynamic range (`<!--k[-->...<!--k]-->` or `<!---->...<!---->`) to its closing comment marker. */
255
+ export function skipRange(marker: Node): Node | null {
256
+ const balanced = marker.nodeType === 8 && (marker as Comment).data === 'k['
257
+ let depth = balanced ? 1 : 0
258
+ let cur = marker.nextSibling
259
+ while (cur !== null) {
260
+ if (cur.nodeType === 8) {
261
+ if (!balanced)
262
+ return cur
263
+ const data = (cur as Comment).data
264
+ if (data === 'k[')
265
+ depth++
266
+ else if (data === 'k]' && --depth === 0)
267
+ return cur
268
+ }
269
+ cur = cur.nextSibling
270
+ }
271
+ return null
272
+ }
273
+
173
274
  export function setText(node: Text, value: unknown): void {
275
+ if (process.env.NODE_ENV !== 'production')
276
+ assertRenderable(value, 'text')
174
277
  const str = value == null || typeof value === 'boolean' ? '' : String(value)
175
278
  if (node.data !== str)
176
279
  node.data = str
177
280
  }
178
281
 
179
282
  export function setClass(el: Element, value: unknown): void {
283
+ if (process.env.NODE_ENV !== 'production')
284
+ assertRenderable(value, 'class')
180
285
  const str = value == null || value === false ? '' : String(value)
181
286
  if (typeof el.className === 'string') {
182
287
  if (el.className !== str) {
@@ -195,12 +300,27 @@ export function setClass(el: Element, value: unknown): void {
195
300
  }
196
301
 
197
302
  export function setAttr(el: Element, name: string, value: unknown): void {
198
- if (value == null || value === false)
303
+ if (isBlockedAttr(name))
304
+ return
305
+ if (process.env.NODE_ENV !== 'production')
306
+ assertRenderable(value, name)
307
+ if (value == null) {
308
+ el.removeAttribute(name)
309
+ }
310
+ else if (typeof value === 'boolean') {
311
+ if (isStringBoolAttr(name))
312
+ el.setAttribute(name, value ? 'true' : 'false')
313
+ else if (value)
314
+ el.setAttribute(name, '')
315
+ else
316
+ el.removeAttribute(name)
317
+ }
318
+ else if (isUnsafeUrlAttr(name, value)) {
199
319
  el.removeAttribute(name)
200
- else if (value === true)
201
- el.setAttribute(name, '')
202
- else
320
+ }
321
+ else {
203
322
  el.setAttribute(name, String(value))
323
+ }
204
324
  }
205
325
 
206
326
  export function setProp(el: Element, name: string, value: unknown): void {
@@ -215,8 +335,7 @@ export function setStyle(el: HTMLElement, value: unknown): void {
215
335
  el.style.cssText = value
216
336
  }
217
337
  else if (typeof value === 'object') {
218
- for (const [k, v] of Object.entries(value as Record<string, unknown>))
219
- el.style.setProperty(k, v == null ? '' : String(v))
338
+ el.style.cssText = styleText(value as Record<string, unknown>)
220
339
  }
221
340
  }
222
341
 
@@ -232,7 +351,7 @@ function dispatchEvent(event: Event): void {
232
351
 
233
352
  while (node !== null) {
234
353
  const handler = node[key]
235
- if (handler !== undefined) {
354
+ if (typeof handler === 'function') {
236
355
  current = node
237
356
  batch(() => handler(event))
238
357
  if (event.cancelBubble)
@@ -254,7 +373,9 @@ export function delegate(events: string[]): void {
254
373
  }
255
374
  }
256
375
 
257
- export function on(el: Node, event: string, handler: (e: Event) => void): void {
376
+ export function on(el: Node, event: string, handler: ((e: Event) => void) | false | null | undefined): void {
377
+ if (typeof handler !== 'function')
378
+ return
258
379
  el.addEventListener(event, (e) => {
259
380
  batch(() => handler(e))
260
381
  })
package/src/dom/island.ts CHANGED
@@ -5,21 +5,24 @@ import { hydrate, mount } from './index'
5
5
  declare const KAY_DEFERRED: boolean | undefined
6
6
  declare const KAY_CLIENT_ONLY: boolean | undefined
7
7
 
8
+ const REVIVERS: Record<string, (v: never) => unknown> = {
9
+ __proto__: null as never,
10
+ D: (v: string) => new Date(v),
11
+ S: (v: unknown[]) => new Set(v),
12
+ M: (v: [unknown, unknown][]) => new Map(v),
13
+ U: (v: string) => new URL(v),
14
+ R: ([src, flags]: [string, string]) => new RegExp(src, flags),
15
+ B: (v: string) => BigInt(v),
16
+ }
17
+
8
18
  export function parseIslandProps(raw: string): Record<string, unknown> {
9
19
  if (!raw.includes('"__k":'))
10
20
  return JSON.parse(raw) as Record<string, unknown>
11
21
  return JSON.parse(raw, (_k, v: unknown) => {
12
22
  if (v !== null && typeof v === 'object' && '__k' in v && 'v' in v) {
13
- const tagged = v as { __k: string, v: unknown }
14
- if (tagged.__k === 'D') return new Date(tagged.v as string)
15
- if (tagged.__k === 'S') return new Set(tagged.v as unknown[])
16
- if (tagged.__k === 'M') return new Map(tagged.v as [unknown, unknown][])
17
- if (tagged.__k === 'U') return new URL(tagged.v as string)
18
- if (tagged.__k === 'R') {
19
- const [src, flags] = tagged.v as [string, string]
20
- return new RegExp(src, flags)
21
- }
22
- if (tagged.__k === 'B') return BigInt(tagged.v as string)
23
+ const revive = REVIVERS[(v as { __k: string }).__k]
24
+ if (revive !== undefined)
25
+ return revive((v as { v: never }).v)
23
26
  }
24
27
  return v
25
28
  }) as Record<string, unknown>
@@ -27,71 +30,123 @@ export function parseIslandProps(raw: string): Record<string, unknown> {
27
30
 
28
31
  type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null }
29
32
 
33
+ /** Finds this island's own `<kay-slot>` without descending into nested `<kay-island>` boundaries. */
34
+ function findOwnSlot(root: Element): Element | null {
35
+ for (let child = root.firstElementChild; child !== null; child = child.nextElementSibling) {
36
+ const tag = child.tagName
37
+ if (tag === 'KAY-SLOT')
38
+ return child
39
+ if (tag === 'KAY-ISLAND')
40
+ continue
41
+ const nested = findOwnSlot(child)
42
+ if (nested !== null)
43
+ return nested
44
+ }
45
+ return null
46
+ }
47
+
48
+ function isAllowedChunkUrl(chunk: string): boolean {
49
+ if (chunk.startsWith('//'))
50
+ return false
51
+ if (chunk.startsWith('/'))
52
+ return true
53
+ if (typeof location !== 'undefined' && location.origin && location.origin !== 'null') {
54
+ try {
55
+ const parsed = new URL(chunk, location.href)
56
+ return parsed.origin === location.origin
57
+ }
58
+ catch {
59
+ return false
60
+ }
61
+ }
62
+ return !/^(?:javascript|data|vbscript):/i.test(chunk)
63
+ }
64
+
65
+ let clientIslandIdSeq = 0
66
+
30
67
  export function defineIslandElement(): void {
31
68
  if (typeof customElements === 'undefined' || customElements.get('kay-island'))
32
69
  return
33
70
 
34
71
  class KayIsland extends HTMLElement {
35
72
  _d: (() => void) | undefined
73
+ _c: (() => void) | undefined
36
74
  _s = false
75
+ _t = 0
76
+
77
+ _clearStrategy(): void {
78
+ this._c?.()
79
+ this._c = undefined
80
+ }
37
81
 
38
82
  connectedCallback(): void {
39
83
  if (this._s)
40
84
  return
41
85
  this._s = true
86
+ const token = ++this._t
42
87
 
43
88
  const h = this.getAttribute('h')
44
89
  if (typeof KAY_DEFERRED === 'undefined' || KAY_DEFERRED) {
45
90
  if (h === 'visible') {
46
- const target = this.firstElementChild ?? this
91
+ const first = this.firstElementChild
92
+ const target = first !== null && first.tagName !== 'SCRIPT' ? first : this
47
93
  const io = new IntersectionObserver((entries) => {
48
- if (entries.some(e => e.isIntersecting)) {
49
- io.disconnect()
50
- void this._l(false)
51
- }
94
+ if (entries.some(e => e.isIntersecting))
95
+ void this._l(false, token)
52
96
  }, { rootMargin: '200px' })
97
+ this._c = () => io.disconnect()
53
98
  io.observe(target)
54
99
  return
55
100
  }
56
101
  if (h === 'idle') {
57
- const ric = (globalThis as { requestIdleCallback?: (cb: () => void) => void }).requestIdleCallback
58
- ric ? ric(() => void this._l(false)) : setTimeout(() => void this._l(false), 1)
102
+ const g = globalThis as { requestIdleCallback?: (cb: () => void) => number, cancelIdleCallback?: (id: number) => void }
103
+ const run = () => void this._l(false, token)
104
+ if (g.requestIdleCallback) {
105
+ const id = g.requestIdleCallback(run)
106
+ this._c = () => g.cancelIdleCallback?.(id)
107
+ }
108
+ else {
109
+ const id = setTimeout(run, 1)
110
+ this._c = () => clearTimeout(id)
111
+ }
59
112
  return
60
113
  }
61
114
  if (h === 'interaction') {
62
115
  const evs = ['pointerdown', 'focusin', 'keydown']
63
- const go = () => {
116
+ const stop = () => {
64
117
  for (const e of evs) this.removeEventListener(e, go, true)
65
- void this._l(false)
66
118
  }
119
+ const go = () => void this._l(false, token)
67
120
  for (const e of evs) this.addEventListener(e, go, { capture: true, once: true })
121
+ this._c = stop
68
122
  return
69
123
  }
70
124
  if (h !== null && h.startsWith('media(')) {
71
125
  const mq = matchMedia(h.slice(6, -1))
72
126
  if (mq.matches) {
73
- void this._l(false)
127
+ void this._l(false, token)
74
128
  }
75
129
  else {
76
130
  const go = () => {
77
- if (mq.matches) {
78
- mq.removeEventListener('change', go)
79
- void this._l(false)
80
- }
131
+ if (mq.matches)
132
+ void this._l(false, token)
81
133
  }
82
134
  mq.addEventListener('change', go)
135
+ this._c = () => mq.removeEventListener('change', go)
83
136
  }
84
137
  return
85
138
  }
86
139
  }
87
140
 
88
- void this._l(h === 'client')
141
+ void this._l(h === 'client', token)
89
142
  }
90
143
 
91
144
  disconnectedCallback(): void {
92
145
  // Defer disposal by a microtask so synchronous DOM moves (e.g. SPA persistent islands) stay alive!
93
146
  queueMicrotask(() => {
94
147
  if (!this.isConnected) {
148
+ this._t++
149
+ this._clearStrategy()
95
150
  this._d?.()
96
151
  this._d = undefined
97
152
  this._s = false
@@ -99,24 +154,47 @@ export function defineIslandElement(): void {
99
154
  })
100
155
  }
101
156
 
102
- async _l(clientOnly: boolean): Promise<void> {
157
+ async _l(clientOnly: boolean, token: number): Promise<void> {
158
+ this._clearStrategy()
103
159
  const chunk = this.getAttribute('c')
104
- if (!chunk)
160
+ if (!chunk || !isAllowedChunkUrl(chunk) || token !== this._t || !this.isConnected || this._d !== undefined)
105
161
  return
106
162
 
107
- const mod = await import(chunk) as IslandModule
108
- if (!this.isConnected)
109
- return
163
+ let dispose: (() => void) | undefined
164
+ try {
165
+ const mod = await import(chunk) as IslandModule
166
+ if (!this.isConnected || token !== this._t || this._d !== undefined)
167
+ return
110
168
 
111
- const p = this.getAttribute('p')
112
- const props: Record<string, unknown> = p ? parseIslandProps(p) : {}
113
- const slot = this.querySelector('kay-slot')
114
- if (slot !== null)
115
- props.children = slot
116
- const render = () => mod.default(props)
117
- this._d = (typeof KAY_CLIENT_ONLY === 'undefined' || KAY_CLIENT_ONLY) && clientOnly
118
- ? mount(this, render)
119
- : hydrate(this, render)
169
+ let props: Record<string, unknown> = {}
170
+ const ps = this.lastElementChild
171
+ if (ps !== null && ps.tagName === 'SCRIPT' && ps.getAttribute('type') === 'application/json') {
172
+ props = parseIslandProps(ps.textContent || '{}')
173
+ ps.remove()
174
+ }
175
+ else {
176
+ const p = this.getAttribute('p')
177
+ if (p)
178
+ props = parseIslandProps(p)
179
+ }
180
+ const slot = findOwnSlot(this)
181
+ if (slot !== null)
182
+ props.children = slot
183
+ const idPrefix = this.getAttribute('i') ?? `c${clientIslandIdSeq++}-`
184
+ const render = () => mod.default(props)
185
+ dispose = (typeof KAY_CLIENT_ONLY === 'undefined' || KAY_CLIENT_ONLY) && clientOnly
186
+ ? mount(this, render, idPrefix)
187
+ : hydrate(this, render, idPrefix)
188
+ if (!this.isConnected || token !== this._t) {
189
+ dispose()
190
+ return
191
+ }
192
+ this._d = dispose
193
+ }
194
+ catch (err) {
195
+ dispose?.()
196
+ console.error(`[kay-island] failed to hydrate ${chunk}:`, err)
197
+ }
120
198
  }
121
199
  }
122
200
 
package/src/dom/loop.ts CHANGED
@@ -2,8 +2,8 @@
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, runWithOwner, signal, untrack } from '../reactivity/index'
6
- import { claimLoop } from './index'
5
+ import { createOwner, disposeOwner, effect, getOwner, onCleanup, runWithOwner, signal, untrack } from '../reactivity/index'
6
+ import { claimLoop, skipRange } from './index'
7
7
 
8
8
  interface Row<T> {
9
9
  key: unknown
@@ -16,6 +16,16 @@ interface Row<T> {
16
16
  const EMPTY: readonly never[] = []
17
17
  const EMPTY_NUMS: number[] = []
18
18
 
19
+ // A new rows array holding the kept prefix and suffix of the old one, with room for the middle.
20
+ function keepEnds<T>(rows: Row<T>[], start: number, oldEnd: number, newEnd: number, nextLen: number): Row<T>[] {
21
+ const result = new Array<Row<T>>(nextLen)
22
+ for (let i = 0; i < start; i++)
23
+ result[i] = rows[i]!
24
+ for (let i = newEnd; i < nextLen; i++)
25
+ result[i] = rows[oldEnd + (i - newEnd)]!
26
+ return result
27
+ }
28
+
19
29
  export function loop<T>(
20
30
  parent: Node,
21
31
  marker: Node | null,
@@ -27,6 +37,12 @@ export function loop<T>(
27
37
  const parentOwner = getOwner()
28
38
  const needsIndex = renderRow.length >= 2
29
39
  let rows: Row<T>[] = []
40
+ let firstRun = true
41
+ if (parentOwner !== undefined) {
42
+ onCleanup(() => {
43
+ rows = []
44
+ })
45
+ }
30
46
 
31
47
  const makeRow = (itemVal: T, idx: number, key: unknown): Row<T> => {
32
48
  const owner = createOwner(parentOwner)
@@ -37,6 +53,18 @@ export function loop<T>(
37
53
  }
38
54
 
39
55
  effect(() => {
56
+ let startMarker: Node | null | undefined
57
+ if (firstRun) {
58
+ firstRun = false
59
+ if (marker !== null && marker.nodeType === 8 && (marker as Comment).data === 'k[') {
60
+ const close = skipRange(marker)
61
+ if (close !== null) {
62
+ startMarker = marker
63
+ marker = close
64
+ }
65
+ }
66
+ }
67
+
40
68
  const list = each()
41
69
  const next = list === false || list == null ? EMPTY : list
42
70
  const nextLen = next.length
@@ -68,7 +96,7 @@ export function loop<T>(
68
96
  const item = next[i]!
69
97
  created[i] = makeRow(item, i, keyFn(item, i))
70
98
  }
71
- }, skip)) {
99
+ }, skip, startMarker)) {
72
100
  rows = created
73
101
  return
74
102
  }
@@ -124,10 +152,7 @@ export function loop<T>(
124
152
  // Fast path 4: Pure insertion (e.g. append 1,000 rows)
125
153
  if (start === oldEnd) {
126
154
  const addCount = newEnd - start
127
- const result = new Array<Row<T>>(nextLen)
128
- for (let i = 0; i < start; i++)
129
- result[i] = rows[i]!
130
-
155
+ const result = keepEnds(rows, start, oldEnd, newEnd, nextLen)
131
156
  const frag = document.createDocumentFragment()
132
157
  for (let i = 0; i < addCount; i++) {
133
158
  const idx = start + i
@@ -137,9 +162,6 @@ export function loop<T>(
137
162
  frag.appendChild(row.node)
138
163
  }
139
164
  parent.insertBefore(frag, after)
140
-
141
- for (let i = newEnd; i < nextLen; i++)
142
- result[i] = rows[oldEnd + (i - newEnd)]!
143
165
  rows = result
144
166
  return
145
167
  }
@@ -151,12 +173,7 @@ export function loop<T>(
151
173
  disposeOwner(row.owner)
152
174
  parent.removeChild(row.node)
153
175
  }
154
- const result = new Array<Row<T>>(nextLen)
155
- for (let i = 0; i < start; i++)
156
- result[i] = rows[i]!
157
- for (let i = newEnd; i < nextLen; i++)
158
- result[i] = rows[oldEnd + (i - newEnd)]!
159
- rows = result
176
+ rows = keepEnds(rows, start, oldEnd, newEnd, nextLen)
160
177
  return
161
178
  }
162
179
 
@@ -166,11 +183,7 @@ export function loop<T>(
166
183
  oldMap.set(rows[i]!.key, i)
167
184
 
168
185
  const midLen = newEnd - start
169
- const result = new Array<Row<T>>(nextLen)
170
- for (let i = 0; i < start; i++)
171
- result[i] = rows[i]!
172
- for (let i = newEnd; i < nextLen; i++)
173
- result[i] = rows[oldEnd + (i - newEnd)]!
186
+ const result = keepEnds(rows, start, oldEnd, newEnd, nextLen)
174
187
 
175
188
  const used = new Uint8Array(oldEnd - start)
176
189
  let reused = 0