prunelle 0.1.1 → 0.7.2

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 (177) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +636 -0
  36. package/src/cli/check-imports.ts +31 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +101 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
package/src/dom/index.ts CHANGED
@@ -8,6 +8,13 @@ export { effect } from '../reactivity/index'
8
8
  let hydrating = false
9
9
  let hydrateNode: Node | null = null
10
10
  let hydrateRoot: Element | null = null
11
+ let mismatchHook: ((parent: Node, stale: Node, node: Node) => void) | null = null
12
+
13
+ export function setMismatchHook(fn: typeof mismatchHook): typeof mismatchHook {
14
+ const prev = mismatchHook
15
+ mismatchHook = fn
16
+ return prev
17
+ }
11
18
 
12
19
  export function isRangeEnd(node: Node): boolean {
13
20
  return node.nodeType === 8 && (node as Comment).data === 'k]'
@@ -42,9 +49,9 @@ export function hydrate(container: Element, render: () => Node | DocumentFragmen
42
49
  hydrateRoot = container
43
50
 
44
51
  try {
45
- runWithOwner(owner, () => {
46
- render()
47
- })
52
+ const node = runWithOwner(owner, render)
53
+ if (node !== null && node.parentNode === null)
54
+ container.appendChild(node)
48
55
  }
49
56
  catch (err) {
50
57
  disposeOwner(owner)
@@ -126,14 +133,18 @@ export function template(html: string, isSvg?: boolean): () => Node {
126
133
  node = null
127
134
  if (process.env.NODE_ENV !== 'production' && node !== stale)
128
135
  warnMismatch(stale, expectedTag!, node !== null)
136
+ const parent = stale.parentNode
129
137
  if (node === null) {
130
138
  hydrating = false
131
139
  hydrateNode = null
132
- const fresh = clone()
133
- stale.parentNode?.replaceChild(fresh, stale)
134
- return fresh
140
+ node = clone()
141
+ parent?.replaceChild(node, stale)
135
142
  }
136
- hydrateNode = node.nextSibling
143
+ else {
144
+ hydrateNode = node.nextSibling
145
+ }
146
+ if (node !== stale && parent !== null)
147
+ mismatchHook?.(parent, stale, node)
137
148
  return node
138
149
  }
139
150
 
@@ -165,12 +176,30 @@ export function fragText(data: string, dynamic?: boolean): Text {
165
176
  return document.createTextNode(data)
166
177
  }
167
178
 
168
- export function frag(...nodes: Node[]): Node | null {
169
- if (hydrating)
179
+ export function frag(...nodes: (Node | null)[]): Node | null {
180
+ const first = nodes.find(n => n?.parentNode && n.parentNode.nodeType !== 11)
181
+ if (first) {
182
+ const parent = first.parentNode!
183
+ let prev: Node | null = null
184
+ for (const n of nodes) {
185
+ if (!n)
186
+ continue
187
+ if (n.parentNode === parent) {
188
+ prev = n
189
+ continue
190
+ }
191
+ const tail = n.nodeType === 11 ? n.lastChild : n
192
+ parent.insertBefore(n, prev ? prev.nextSibling : first)
193
+ if (prev && tail)
194
+ prev = tail
195
+ }
170
196
  return null
171
- const f = document.createDocumentFragment()
172
- for (let i = 0; i < nodes.length; i++)
173
- f.appendChild(nodes[i]!)
197
+ }
198
+ let f: DocumentFragment | null = null
199
+ for (const n of nodes) {
200
+ if (n)
201
+ (f ??= document.createDocumentFragment()).appendChild(n)
202
+ }
174
203
  return f
175
204
  }
176
205
 
@@ -235,6 +264,7 @@ function dispatchEvent(event: Event): void {
235
264
  let current: EventTarget | null = null
236
265
  const prevDesc = Object.getOwnPropertyDescriptor(event, 'currentTarget')
237
266
  Object.defineProperty(event, 'currentTarget', { configurable: true, get: () => current })
267
+ const errors: unknown[] = []
238
268
 
239
269
  try {
240
270
  const path = event.composedPath?.()
@@ -245,9 +275,14 @@ function dispatchEvent(event: Event): void {
245
275
  const handler = node[key]
246
276
  if (typeof handler === 'function') {
247
277
  current = node
248
- batch(() => handler(event))
278
+ try {
279
+ batch(() => handler(event))
280
+ }
281
+ catch (err) {
282
+ errors.push(err)
283
+ }
249
284
  if (event.cancelBubble)
250
- return
285
+ break
251
286
  }
252
287
  node = (usePath ? path[++i] : (node as unknown as Node).parentNode) as (EventTarget & Record<string, ((e: Event) => void) | undefined>) | null | undefined
253
288
  }
@@ -258,6 +293,11 @@ function dispatchEvent(event: Event): void {
258
293
  else
259
294
  delete (event as unknown as Record<string, unknown>).currentTarget
260
295
  }
296
+ // Every handler ran: the first error is thrown as before, the others are reported.
297
+ for (let i = 1; i < errors.length; i++)
298
+ reportError(errors[i])
299
+ if (errors.length > 0)
300
+ throw errors[0]
261
301
  }
262
302
 
263
303
  export function delegate(events: string[]): void {
package/src/dom/island.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  // Native <pru-island> Custom Element: the build defines which strategies an app uses, so the loader drops the code of the others.
2
2
 
3
- import { hydrate, mount } from './index'
4
-
3
+ import type { hydrate, mount } from './index'
5
4
 
6
5
  declare const PRUNELLE_VISIBLE: boolean | undefined
7
6
  declare const PRUNELLE_IDLE: boolean | undefined
@@ -14,7 +13,8 @@ declare const PRUNELLE_REVIVE: string | undefined
14
13
  // Only props holding a Date, Map, Set or another tagged value load the revivers: plain JSON parses with no extra file.
15
14
  const reviver = (): Promise<typeof import('./revive')> => typeof PRUNELLE_REVIVE === 'undefined' ? import('./revive') : import(PRUNELLE_REVIVE)
16
15
 
17
- type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null }
16
+ // An island chunk also re-exports the DOM runtime it imports (`writeClientEntries`), `mount` only in an app with a client-only island.
17
+ type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null, hydrate: typeof hydrate, mount?: typeof mount }
18
18
 
19
19
  /** Finds this island's own `<script type="application/json" data-pru-props>` direct child. */
20
20
  function findOwnPropsScript(root: Element): Element | null {
@@ -90,22 +90,81 @@ function replayEvent(root: Element, ev: Event, target: EventTarget | null): void
90
90
  target.dispatchEvent(clone)
91
91
  }
92
92
 
93
+ // A failed load keeps the listeners and drops the queued events: the next interaction loads the chunk again and is replayed once it is in.
94
+ function watchInteraction(root: Element, onTrigger: (after: () => void) => Promise<boolean>): () => void {
95
+ const evs = ['pointerdown', 'click', 'focusin', 'keydown']
96
+ const queued: { ev: Event, target: EventTarget | null }[] = []
97
+ let loading = false
98
+ const go = (ev: Event) => {
99
+ // Prevent native toggle/submit/navigation before hydration so replaying the click triggers it once with handlers attached.
100
+ if (ev.type === 'click')
101
+ ev.preventDefault()
102
+ queued.push({ ev, target: ev.target })
103
+ if (!loading) {
104
+ loading = true
105
+ void onTrigger(() => {
106
+ for (let i = 0; i < queued.length; i++)
107
+ replayEvent(root, queued[i]!.ev, queued[i]!.target)
108
+ }).then((ok) => {
109
+ if (!ok) {
110
+ loading = false
111
+ queued.length = 0
112
+ }
113
+ })
114
+ }
115
+ }
116
+ for (const e of evs) root.addEventListener(e, go, true)
117
+ return () => {
118
+ for (const e of evs) root.removeEventListener(e, go, true)
119
+ }
120
+ }
121
+
93
122
  function isAllowedChunkUrl(chunk: string): boolean {
94
- // A browser reads `//host` and `/\host` as another site.
95
- if (chunk[0] === '/')
96
- return chunk[1] !== '/' && chunk[1] !== '\\'
123
+ if (/[\u0000-\u0020\u007F]/.test(chunk))
124
+ return false
97
125
  if (typeof location !== 'undefined' && location.origin && location.origin !== 'null') {
98
126
  try {
99
- const parsed = new URL(chunk, location.href)
100
- return parsed.origin === location.origin
127
+ return new URL(chunk, location.href).origin === location.origin
101
128
  }
102
129
  catch {
103
130
  return false
104
131
  }
105
132
  }
133
+ // A browser reads `//host` and `/\host` as another site.
134
+ if (chunk[0] === '/')
135
+ return chunk[1] !== '/' && chunk[1] !== '\\'
106
136
  return !/^(?:javascript|data|vbscript):/i.test(chunk)
107
137
  }
108
138
 
139
+ function watchVisible(root: HTMLElement, onVisible: () => void): (() => void) | undefined {
140
+ if (typeof IntersectionObserver === 'undefined') {
141
+ onVisible()
142
+ return undefined
143
+ }
144
+ const targets: Element[] = []
145
+ collectVisibleTargets(root, targets)
146
+ let restoreDisplay: (() => void) | undefined
147
+ if (targets.length === 0) {
148
+ const display = typeof getComputedStyle === 'function' ? getComputedStyle(root).display : 'contents'
149
+ if (display === 'contents' || display === '') {
150
+ const prev = root.style.display
151
+ root.style.display = 'inline'
152
+ restoreDisplay = () => { root.style.display = prev }
153
+ }
154
+ targets.push(root)
155
+ }
156
+ const io = new IntersectionObserver((entries) => {
157
+ if (entries.some(e => e.isIntersecting))
158
+ onVisible()
159
+ }, { rootMargin: '200px' })
160
+ for (const target of targets)
161
+ io.observe(target)
162
+ return () => {
163
+ io.disconnect()
164
+ restoreDisplay?.()
165
+ }
166
+ }
167
+
109
168
  let clientIslandIdSeq = 0
110
169
 
111
170
  export function defineIslandElement(): void {
@@ -120,7 +179,9 @@ export function defineIslandElement(): void {
120
179
  _s = false
121
180
  _t = 0
122
181
 
123
- _clearStrategy(): void {
182
+ _clearStrategy(token?: number): void {
183
+ if (token !== undefined && token !== this._t)
184
+ return
124
185
  this._c?.()
125
186
  this._c = undefined
126
187
  }
@@ -133,39 +194,14 @@ export function defineIslandElement(): void {
133
194
 
134
195
  const h = this.getAttribute('h')
135
196
  if ((typeof PRUNELLE_VISIBLE === 'undefined' || PRUNELLE_VISIBLE) && h === 'visible') {
136
- if (typeof IntersectionObserver === 'undefined') {
137
- void this._l(false, token)
138
- return
139
- }
140
- const targets: Element[] = []
141
- collectVisibleTargets(this, targets)
142
- let restoreDisplay: (() => void) | undefined
143
- if (targets.length === 0) {
144
- const display = typeof getComputedStyle === 'function' ? getComputedStyle(this).display : 'contents'
145
- if (display === 'contents' || display === '') {
146
- const prev = this.style.display
147
- this.style.display = 'inline'
148
- restoreDisplay = () => { this.style.display = prev }
149
- }
150
- targets.push(this)
151
- }
152
- const io = new IntersectionObserver((entries) => {
153
- if (entries.some(e => e.isIntersecting))
154
- void this._l(false, token)
155
- }, { rootMargin: '200px' })
156
- this._c = () => {
157
- io.disconnect()
158
- restoreDisplay?.()
159
- }
160
- for (const target of targets)
161
- io.observe(target)
197
+ this._c = watchVisible(this, () => void this._l(false, token))
162
198
  return
163
199
  }
164
200
  if ((typeof PRUNELLE_IDLE === 'undefined' || PRUNELLE_IDLE) && h === 'idle') {
165
- const g = globalThis as { requestIdleCallback?: (cb: () => void) => number, cancelIdleCallback?: (id: number) => void }
201
+ const g = globalThis as { requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number, cancelIdleCallback?: (id: number) => void }
166
202
  const run = () => void this._l(false, token)
167
203
  if (g.requestIdleCallback) {
168
- const id = g.requestIdleCallback(run)
204
+ const id = g.requestIdleCallback(run, { timeout: 2000 })
169
205
  this._c = () => g.cancelIdleCallback?.(id)
170
206
  }
171
207
  else {
@@ -175,24 +211,7 @@ export function defineIslandElement(): void {
175
211
  return
176
212
  }
177
213
  if ((typeof PRUNELLE_INTERACTION === 'undefined' || PRUNELLE_INTERACTION) && h === 'interaction') {
178
- const evs = ['pointerdown', 'click', 'focusin', 'keydown']
179
- const queued: { ev: Event, target: EventTarget | null }[] = []
180
- let loading = false
181
- const stop = () => {
182
- for (const e of evs) this.removeEventListener(e, go, true)
183
- }
184
- const go = (ev: Event) => {
185
- queued.push({ ev, target: ev.target })
186
- if (!loading) {
187
- loading = true
188
- void this._l(false, token, true, () => {
189
- for (let i = 0; i < queued.length; i++)
190
- replayEvent(this, queued[i]!.ev, queued[i]!.target)
191
- })
192
- }
193
- }
194
- for (const e of evs) this.addEventListener(e, go, true)
195
- this._c = stop
214
+ this._c = watchInteraction(this, after => this._l(false, token, true, after))
196
215
  return
197
216
  }
198
217
  if ((typeof PRUNELLE_MEDIA === 'undefined' || PRUNELLE_MEDIA) && h !== null && h.startsWith('media(')) {
@@ -227,13 +246,20 @@ export function defineIslandElement(): void {
227
246
  })
228
247
  }
229
248
 
230
- async _l(clientOnly: boolean, token: number, keepStrategy = false, after?: () => void): Promise<void> {
249
+ // Resolves false when the chunk failed to load or hydrate.
250
+ async _l(clientOnly: boolean, token: number, keepStrategy = false, after?: () => void): Promise<boolean> {
251
+ if (token !== this._t)
252
+ return true
231
253
  if (!keepStrategy)
232
- this._clearStrategy()
254
+ this._clearStrategy(token)
233
255
  const chunk = this.getAttribute('c')
234
- if (!chunk || !isAllowedChunkUrl(chunk) || token !== this._t || !this.isConnected || this._d !== undefined) {
235
- this._clearStrategy()
236
- return
256
+ if (!chunk || !isAllowedChunkUrl(chunk) || !this.isConnected || this._d !== undefined) {
257
+ if (chunk && !isAllowedChunkUrl(chunk))
258
+ console.error(`[pru-island] refused chunk URL ${chunk}: it must be on this origin.`)
259
+ this._clearStrategy(token)
260
+ if (!this.isConnected)
261
+ this._s = false
262
+ return true
237
263
  }
238
264
 
239
265
  let dispose: (() => void) | undefined
@@ -247,11 +273,14 @@ export function defineIslandElement(): void {
247
273
  const raw = this._p ?? this.getAttribute('p')
248
274
  const [loaded, revive] = await Promise.all([import(chunk) as Promise<IslandModule>, raw?.includes('"__k":') ? reviver() : undefined])
249
275
  mod = loaded
250
- if (!this.isConnected || token !== this._t || this._d !== undefined) {
251
- this._clearStrategy()
252
- return
276
+ if (token !== this._t)
277
+ return true
278
+ this._clearStrategy(token)
279
+ if (!this.isConnected || this._d !== undefined) {
280
+ if (!this.isConnected)
281
+ this._s = false
282
+ return true
253
283
  }
254
- this._clearStrategy()
255
284
 
256
285
  const props = (raw ? revive?.parseIslandProps(raw) ?? JSON.parse(raw) : {}) as Record<string, unknown>
257
286
  const slot = extractOwnSlot(this) ?? this._slot ?? null
@@ -262,20 +291,25 @@ export function defineIslandElement(): void {
262
291
  const idPrefix = this.getAttribute('i') ?? `c${clientIslandIdSeq++}-`
263
292
  const render = () => loaded.default(props)
264
293
  dispose = (typeof PRUNELLE_CLIENT_ONLY === 'undefined' || PRUNELLE_CLIENT_ONLY) && clientOnly
265
- ? mount(this, render, idPrefix)
266
- : hydrate(this, render, idPrefix)
294
+ ? loaded.mount!(this, render, idPrefix)
295
+ : loaded.hydrate(this, render, idPrefix)
267
296
  if (!this.isConnected || token !== this._t) {
268
297
  dispose()
269
- return
298
+ if (token === this._t)
299
+ this._s = false
300
+ return true
270
301
  }
271
302
  this._d = dispose
272
303
  after?.()
304
+ return true
273
305
  }
274
306
  catch (err) {
275
- this._clearStrategy()
307
+ if (!keepStrategy)
308
+ this._clearStrategy(token)
276
309
  dispose?.()
277
310
  // The chunk URL is a hash; in dev the component's own name says which island failed.
278
311
  console.error(`[pru-island] failed to hydrate ${process.env.NODE_ENV !== 'production' && mod?.default?.name ? `<${mod.default.name}> (${chunk})` : chunk}:`, err)
312
+ return false
279
313
  }
280
314
  }
281
315
  }
package/src/dom/loop.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  import type { Owner, Signal } from '../reactivity/index'
5
5
  import { createOwner, disposeOwner, effect, getOwner, onCleanup, runWithOwner, signal, untrack } from '../reactivity/index'
6
6
  import { claimLoop } from './claim'
7
- import { hydrateCursor, skipRange } from './index'
7
+ import { hydrateCursor, isRangeEnd, setMismatchHook, skipRange } from './index'
8
8
 
9
9
  interface Row<T> {
10
10
  key: unknown
@@ -49,11 +49,10 @@ function insertRow<T>(parent: Node, row: Row<T>, anchor: Node | null): void {
49
49
  parent.insertBefore(list[i]!, anchor)
50
50
  }
51
51
 
52
- function removeRow<T>(parent: Node, row: Row<T>): void {
52
+ function removeRow<T>(row: Row<T>): void {
53
53
  const list = row.nodes
54
54
  if (list === undefined) {
55
- if (row.node !== null)
56
- parent.removeChild(row.node)
55
+ row.node?.parentNode?.removeChild(row.node)
57
56
  return
58
57
  }
59
58
  const first = list[0]!
@@ -84,15 +83,28 @@ function keepEnds<T>(rows: Row<T>[], start: number, oldEnd: number, newEnd: numb
84
83
  type RenderRow<T> = (item: Signal<T>, index?: Signal<number>) => Node | DocumentFragment | null | undefined | boolean | string | number
85
84
 
86
85
 
86
+ function pushRange(out: Node[], from: Node | null, stop: Node | null): void {
87
+ for (let n = from; n !== null && n !== stop && !isRangeEnd(n); n = n.nextSibling)
88
+ out.push(n)
89
+ }
90
+
87
91
  // While hydrating, a row that rendered no node of its own takes the server nodes the cursor moved over since `before`.
88
- function adoptRowNodes<T>(parent: Node, marker: Node | null, row: Row<T>, before: Node | null): void {
92
+ function adoptRowNodes<T>(
93
+ parent: Node,
94
+ marker: Node | null,
95
+ row: Row<T>,
96
+ before: Node | null,
97
+ prevSib: Node | null,
98
+ leftover: Node[],
99
+ fallbackEnd: Node | null,
100
+ ): boolean {
89
101
  const afterCursor = hydrateCursor()
90
102
  if (row.node === null && before !== null && before !== afterCursor) {
103
+ const start = before.parentNode === parent ? before : prevSib !== null ? prevSib.nextSibling : parent.firstChild
91
104
  const claimed: Node[] = []
92
- for (let n: Node | null = before; n !== null && n !== afterCursor; n = n.nextSibling) {
93
- if (n.nodeType === 8 && (n as Comment).data === 'k]')
94
- break
95
- claimed.push(n)
105
+ for (let n: Node | null = start; n !== null && n !== afterCursor && n !== marker && n !== fallbackEnd && !isRangeEnd(n); n = n.nextSibling) {
106
+ if (!leftover.includes(n))
107
+ claimed.push(n)
96
108
  }
97
109
  if (claimed.length === 1) {
98
110
  row.node = claimed[0]!
@@ -104,38 +116,60 @@ function adoptRowNodes<T>(parent: Node, marker: Node | null, row: Row<T>, before
104
116
  }
105
117
  else if (row.node !== null && row.node.parentNode !== parent) {
106
118
  insertRow(parent, row, marker)
119
+ return true
107
120
  }
121
+ return false
108
122
  }
109
123
 
110
- // Server rows past the browser's last one: the data changed between the render and hydration, so they would stay in the DOM outside `rows`.
111
- function dropServerRows(from: Node | null, marker: Node | null): void {
112
- if (process.env.NODE_ENV !== 'production' && from !== null && from !== marker) {
113
- let removed = 0
114
- for (let n: Node | null = from; n !== null && n !== marker; n = n.nextSibling)
115
- removed++
116
- console.warn(`prunelle: hydration removed ${removed} server node(s) past the list's last row: the island's data changed after the server rendered it.`)
117
- }
118
- while (from !== null && from !== marker) {
119
- const next: Node | null = from.nextSibling
120
- ;(from as ChildNode).remove()
121
- from = next
122
- }
124
+ // 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 {
126
+ pushRange(leftover, from, marker)
127
+ if (leftover.length === 0 && added === 0)
128
+ return
129
+ 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.`)
131
+ for (const n of leftover)
132
+ (n as ChildNode).remove()
133
+ const { CustomEvent: Mismatch } = parent.ownerDocument!.defaultView!
134
+ parent.dispatchEvent(new Mismatch('pru:hydration-mismatch', { bubbles: true, detail: { removed: leftover.length, added } }))
123
135
  }
124
136
 
125
137
  // The first rows: claimed from the server's while hydrating, else rendered into a fragment inserted at once.
126
138
  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>[] {
127
139
  const created = new Array<Row<T>>(items.length)
128
140
  let end: Node | null = null
141
+ const leftover: Node[] = []
142
+ let added = 0
143
+ let fallbackEnd: Node | null = null
129
144
  if (claimLoop(parent, () => {
130
- for (let i = 0; i < items.length; i++) {
131
- const before = hydrateCursor()
132
- const row = newRow(items[i]!, i)
133
- adoptRowNodes(parent, marker, row, before)
134
- created[i] = row
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))
163
+ added++
164
+ created[i] = row
165
+ }
166
+ end = hydrateCursor()
167
+ }
168
+ finally {
169
+ setMismatchHook(prevHook)
135
170
  }
136
- end = hydrateCursor()
137
171
  }, skip, startMarker)) {
138
- dropServerRows(end, marker)
172
+ dropServerRows(parent, leftover, end, marker, added)
139
173
  return created
140
174
  }
141
175
  if (items.length > 0) {
@@ -239,7 +273,7 @@ export function loop<T>(
239
273
  }
240
274
  else {
241
275
  for (let i = 0; i < prevLen; i++)
242
- removeRow(parent, rows[i]!)
276
+ removeRow(rows[i]!)
243
277
  }
244
278
  rows = []
245
279
  return
@@ -309,7 +343,7 @@ export function loop<T>(
309
343
  for (let i = start; i < oldEnd; i++) {
310
344
  const row = rows[i]!
311
345
  disposeOwner(row.owner)
312
- removeRow(parent, row)
346
+ removeRow(row)
313
347
  }
314
348
  rows = keepEnds(rows, start, oldEnd, newEnd, nextLen)
315
349
  return
@@ -364,7 +398,7 @@ export function loop<T>(
364
398
  if (used[i - start] === 0) {
365
399
  const row = rows[i]!
366
400
  disposeOwner(row.owner)
367
- removeRow(parent, row)
401
+ removeRow(row)
368
402
  }
369
403
  }
370
404