prunelle 0.6.0 → 0.7.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 (128) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +48 -43
  3. package/package.json +4 -1
  4. package/src/a11y/declaration.ts +106 -72
  5. package/src/a11y/index.ts +59 -39
  6. package/src/a11y/rgaa-map.ts +95 -49
  7. package/src/build/bundle.ts +8 -4
  8. package/src/build/byte-size.ts +11 -0
  9. package/src/build/client-plugin.ts +3 -1
  10. package/src/build/compile.ts +2 -1
  11. package/src/build/ecoindex.ts +25 -16
  12. package/src/build/files.ts +6 -0
  13. package/src/build/first-load.ts +83 -11
  14. package/src/build/graph.ts +29 -39
  15. package/src/build/index.ts +61 -18
  16. package/src/build/island-promote.ts +250 -0
  17. package/src/build/islands.ts +12 -201
  18. package/src/build/manifest.ts +4 -125
  19. package/src/build/plugin-host.ts +21 -8
  20. package/src/build/precompress.ts +1 -1
  21. package/src/build/prerender.ts +97 -44
  22. package/src/build/reach.ts +136 -0
  23. package/src/build/render-rules.ts +2 -2
  24. package/src/build/report.ts +25 -3
  25. package/src/build/static-headers.ts +93 -0
  26. package/src/build/static.ts +2 -0
  27. package/src/cli/check-forms.ts +97 -48
  28. package/src/cli/check-imports.ts +25 -0
  29. package/src/cli/check-links.ts +2 -2
  30. package/src/cli/check-security.ts +64 -0
  31. package/src/cli/check.ts +37 -7
  32. package/src/cli/commands.ts +35 -7
  33. package/src/cli/docs.ts +4 -3
  34. package/src/cli/inspect.ts +2 -1
  35. package/src/cli/mcp-tools.ts +7 -5
  36. package/src/cli/mcp.ts +1 -1
  37. package/src/cli/new.ts +14 -3
  38. package/src/cli/render.ts +14 -19
  39. package/src/cli/upgrade.ts +22 -5
  40. package/src/compiler/analyze.ts +27 -5
  41. package/src/compiler/cacheability.ts +2 -2
  42. package/src/compiler/compliance-eco.ts +71 -0
  43. package/src/compiler/compliance-rgaa.ts +110 -4
  44. package/src/compiler/compliance-urls.ts +146 -0
  45. package/src/compiler/compliance.ts +168 -116
  46. package/src/compiler/foreign-imports.ts +88 -0
  47. package/src/compiler/mistakes.ts +19 -1
  48. package/src/compiler/props-body.ts +60 -0
  49. package/src/compiler/shared.ts +2 -2
  50. package/src/compiler/ssr.ts +2 -2
  51. package/src/context.ts +34 -0
  52. package/src/dev/error-log.ts +90 -64
  53. package/src/dev/host-check.ts +32 -0
  54. package/src/dev/index.ts +17 -7
  55. package/src/dev/open-editor.ts +36 -12
  56. package/src/dev/protocol.ts +2 -0
  57. package/src/dev/supervisor.ts +8 -0
  58. package/src/dev/watchers.ts +27 -2
  59. package/src/dom/action.ts +4 -1
  60. package/src/dom/extras.ts +1 -2
  61. package/src/dom/index.ts +28 -6
  62. package/src/dom/island.ts +22 -10
  63. package/src/dom/loop.ts +60 -27
  64. package/src/eco/declaration.ts +257 -0
  65. package/src/eco/index.ts +65 -0
  66. package/src/index.ts +2 -2
  67. package/src/jsx-runtime.ts +2 -2
  68. package/src/plugins/config.ts +1 -1
  69. package/src/plugins/context.ts +44 -1
  70. package/src/plugins/load.ts +4 -3
  71. package/src/plugins/public.ts +2 -2
  72. package/src/plugins/services.ts +3 -0
  73. package/src/plugins/types.ts +17 -2
  74. package/src/server/action-flash.ts +158 -0
  75. package/src/server/action-protect.ts +38 -37
  76. package/src/server/action.ts +11 -127
  77. package/src/server/app-secret.ts +63 -0
  78. package/src/server/compress.ts +5 -1
  79. package/src/server/consent.ts +59 -22
  80. package/src/server/cookies.ts +16 -2
  81. package/src/server/env.ts +14 -0
  82. package/src/server/errors.ts +3 -1
  83. package/src/server/form-schema.ts +1 -1
  84. package/src/server/health.ts +46 -15
  85. package/src/server/http.ts +56 -8
  86. package/src/server/index.ts +59 -30
  87. package/src/server/loader.ts +10 -2
  88. package/src/server/plugin-host.ts +3 -1
  89. package/src/server/public.ts +4 -3
  90. package/src/server/rate-limit.ts +52 -9
  91. package/src/server/route-cache.ts +26 -4
  92. package/src/server/route-table.ts +7 -3
  93. package/src/server/routing.ts +3 -87
  94. package/src/server/sanitize-html.ts +309 -0
  95. package/src/server/security.ts +73 -22
  96. package/src/server/serve-handlers.ts +14 -4
  97. package/src/server/start.ts +1 -1
  98. package/src/server/static-dir.ts +31 -5
  99. package/src/server/stream.ts +28 -6
  100. package/src/ssr/consent-banner.ts +58 -0
  101. package/src/ssr/context.ts +20 -4
  102. package/src/ssr/index.ts +18 -0
  103. package/src/ssr/navigation.ts +2 -2
  104. package/src/style.ts +64 -1
  105. package/templates/_shared/gitignore +5 -0
  106. package/templates/_shared/src/routes/legal.tsx +10 -1
  107. package/templates/app/.env.example +4 -0
  108. package/templates/app/package.json +2 -1
  109. package/templates/app/prunelle.config.ts +2 -0
  110. package/templates/app/src/auth.ts +4 -6
  111. package/templates/app/src/mail.ts +4 -0
  112. package/templates/app/src/routes/_layout.tsx +9 -1
  113. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  114. package/templates/app/src/routes/login.tsx +49 -30
  115. package/templates/app/src/routes/privacy.tsx +25 -0
  116. package/templates/app/src/styles/app.css +8 -1
  117. package/templates/app/tests/app.test.ts +44 -3
  118. package/templates/blog/package.json +1 -1
  119. package/templates/blog/src/routes/_layout.tsx +6 -1
  120. package/templates/blog/src/routes/index.tsx +1 -1
  121. package/templates/blog/src/styles/app.css +6 -1
  122. package/templates/fullstack/package.json +1 -1
  123. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  124. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  125. package/templates/fullstack/src/styles/app.css +11 -1
  126. package/templates/minimal/package.json +1 -1
  127. package/templates/minimal/src/routes/_layout.tsx +4 -0
  128. package/templates/minimal/src/styles/app.css +11 -1
@@ -1,8 +1,10 @@
1
1
  // Opens a project source file at `line:col` in `$PRUNELLE_EDITOR` or `$VISUAL` on Alt-click in `prunelle dev`.
2
2
 
3
+ import type { TrustProxy } from '../server/security'
3
4
  import { existsSync, realpathSync } from 'node:fs'
4
5
  import { relative, resolve } from 'node:path'
5
6
  import { isInside } from '../build/is-inside'
7
+ import { verifyOrigin } from '../server/security'
6
8
 
7
9
  export const OPEN_EDITOR_SUBPATH = 'open-editor'
8
10
 
@@ -135,6 +137,17 @@ export function buildEditorCommand(editorSpec: string, loc: { file: string, line
135
137
  export interface OpenEditorOptions {
136
138
  env?: Record<string, string | undefined> | undefined
137
139
  spawn?: ((cmd: string[]) => void) | undefined
140
+ trustedOrigins?: ReadonlySet<string> | readonly string[] | undefined
141
+ trustProxy?: TrustProxy | undefined
142
+ remoteIp?: string | undefined
143
+ }
144
+
145
+ const IPV4_LOOPBACK_RE = /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
146
+
147
+ function isLoopbackIp(ip: string): boolean {
148
+ const bare = ip.trim().toLowerCase().replace(/^\[|\]$/g, '')
149
+ const unmapped = bare.startsWith('::ffff:') ? bare.slice(7) : bare
150
+ return unmapped === '::1' || unmapped === '0:0:0:0:0:0:0:1' || IPV4_LOOPBACK_RE.test(unmapped)
138
151
  }
139
152
 
140
153
  export function openInEditor(
@@ -175,7 +188,7 @@ export function openInEditor(
175
188
  return { ok: true, command }
176
189
  }
177
190
 
178
- /** Handles `POST /_pru/open-editor` from the dev server's Alt-click listener. */
191
+ /** Handles `POST /_pru/open-editor` from the dev server's Alt-click listener: a same-origin JSON body only, so another site cannot open the editor with a form or a no-cors fetch. */
179
192
  export async function handleOpenEditorRequest(
180
193
  request: Request,
181
194
  root: string,
@@ -183,17 +196,28 @@ export async function handleOpenEditorRequest(
183
196
  ): Promise<Response> {
184
197
  if (request.method !== 'POST')
185
198
  return Response.json({ ok: false, error: 'Method Not Allowed' }, { status: 405, headers: { allow: 'POST' } })
186
-
187
- let rawSrc = new URL(request.url).searchParams.get('src') ?? ''
188
- if (rawSrc === '') {
189
- try {
190
- const body = await request.json() as unknown
191
- if (body !== null && typeof body === 'object' && typeof (body as { src?: unknown }).src === 'string')
192
- rawSrc = (body as { src: string }).src
193
- }
194
- catch {
195
- return Response.json({ ok: false, error: 'Invalid JSON body; expected { "src": "file:line:col" }.' }, { status: 400 })
196
- }
199
+ if (options?.remoteIp !== undefined && !isLoopbackIp(options.remoteIp))
200
+ return Response.json({ ok: false, error: 'Open-editor is only available from loopback addresses.' }, { status: 403 })
201
+ const trusted = options?.trustedOrigins === undefined
202
+ ? undefined
203
+ : options.trustedOrigins instanceof Set
204
+ ? options.trustedOrigins
205
+ : new Set(options.trustedOrigins)
206
+ const originCheck = verifyOrigin(request, trusted, options?.trustProxy ?? false)
207
+ if (!originCheck.ok)
208
+ return Response.json({ ok: false, error: originCheck.reason }, { status: 403 })
209
+ const mediaType = (request.headers.get('content-type') ?? '').split(';', 1)[0]!.trim().toLowerCase()
210
+ if (mediaType !== 'application/json')
211
+ return Response.json({ ok: false, error: 'Expected content-type: application/json.' }, { status: 415 })
212
+
213
+ let rawSrc = ''
214
+ try {
215
+ const body = await request.json() as unknown
216
+ if (body !== null && typeof body === 'object' && typeof (body as { src?: unknown }).src === 'string')
217
+ rawSrc = (body as { src: string }).src
218
+ }
219
+ catch {
220
+ return Response.json({ ok: false, error: 'Invalid JSON body; expected { "src": "file:line:col" }.' }, { status: 400 })
197
221
  }
198
222
 
199
223
  if (rawSrc.trim() === '')
@@ -12,6 +12,8 @@ export interface DevChildOptions {
12
12
  root: string
13
13
  routesDir?: string | undefined
14
14
  unix: string
15
+ /** The address the parent binds, which the app's plugins see as `api.devExposed`. */
16
+ hostname?: string | undefined
15
17
  maxRequestBodySize?: number | undefined
16
18
  maxRssMb?: number | undefined
17
19
  }
@@ -7,6 +7,7 @@ import { existsSync, mkdtempSync, rmSync, watch } from 'node:fs'
7
7
  import { tmpdir } from 'node:os'
8
8
  import { join, resolve } from 'node:path'
9
9
  import { recordDevCrashError } from './error-log'
10
+ import { createDevHostCheck } from './host-check'
10
11
  import { DEV_CHILD_ENV, DEV_CLIENT_IP_HEADER } from './protocol'
11
12
  import { buildErrorResponse, createReloadHub, makeDevReloadAssets } from './reload'
12
13
 
@@ -18,6 +19,8 @@ export interface DevSupervisorOptions {
18
19
  maxRequestBodySize?: number | undefined
19
20
  /** The app process is replaced once its RSS passes this after a rebuild. */
20
21
  maxRssMb?: number | undefined
22
+ /** Origins besides loopback and IP addresses the server answers under: the config's `site` and `trustedOrigins`. */
23
+ allowedOrigins?: readonly (string | undefined)[] | undefined
21
24
  }
22
25
 
23
26
  interface Child {
@@ -75,6 +78,7 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
75
78
  root,
76
79
  routesDir: options.routesDir,
77
80
  unix: socket,
81
+ hostname: options.hostname,
78
82
  ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}),
79
83
  maxRssMb: options.maxRssMb ?? DEFAULT_MAX_RSS_MB,
80
84
  }
@@ -140,12 +144,16 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
140
144
  ready = spawnChild()
141
145
  await ready
142
146
 
147
+ const checkHost = createDevHostCheck(options.hostname, options.allowedOrigins ?? [])
143
148
  const server = Bun.serve({
144
149
  port: options.port ?? 3000,
145
150
  hostname: options.hostname ?? '127.0.0.1',
146
151
  idleTimeout: 30,
147
152
  maxRequestBodySize: options.maxRequestBodySize ?? DEFAULT_SUPERVISOR_MAX_BODY,
148
153
  async fetch(request, srv) {
154
+ const refused = checkHost(request)
155
+ if (refused !== undefined)
156
+ return refused
149
157
  const url = new URL(request.url)
150
158
  if (url.pathname === reloadAssets.eventsPath) {
151
159
  srv.timeout(request, 0)
@@ -21,9 +21,34 @@ export function srcChangeKind(name: string): ChangeKind {
21
21
  return CODE_FILE_RE.test(name) ? 'code' : 'full'
22
22
  }
23
23
 
24
+ type ScanLoader = 'js' | 'jsx' | 'ts' | 'tsx'
25
+
26
+ // A `.ts` file is read as TS, not TSX: there `<T>(x: T) => x` is a generic arrow, not a JSX tag (#108).
27
+ function scanLoader(file: string): ScanLoader {
28
+ if (file.endsWith('.tsx'))
29
+ return 'tsx'
30
+ if (file.endsWith('.jsx'))
31
+ return 'jsx'
32
+ return /\.[cm]?js$/.test(file) ? 'js' : 'ts'
33
+ }
34
+
24
35
  // The files outside node_modules that `entry` imports, transitively, `entry` left out.
25
36
  export function localImports(entry: string): string[] {
26
- const transpiler = new Bun.Transpiler({ loader: 'tsx' })
37
+ const transpilers = new Map<ScanLoader, Bun.Transpiler>()
38
+ const importsOf = (file: string, source: string): string[] => {
39
+ const loader = scanLoader(file)
40
+ let transpiler = transpilers.get(loader)
41
+ if (transpiler === undefined) {
42
+ transpiler = new Bun.Transpiler({ loader })
43
+ transpilers.set(loader, transpiler)
44
+ }
45
+ try {
46
+ return transpiler.scanImports(source).map(entry => entry.path)
47
+ }
48
+ catch {
49
+ return [] // a syntax error, which the config load reports itself
50
+ }
51
+ }
27
52
  const seen = new Set<string>([entry])
28
53
  const queue = [entry]
29
54
  for (let file = queue.pop(); file !== undefined; file = queue.pop()) {
@@ -34,7 +59,7 @@ export function localImports(entry: string): string[] {
34
59
  catch {
35
60
  continue // deleted since it was resolved
36
61
  }
37
- for (const { path } of transpiler.scanImports(source)) {
62
+ for (const path of importsOf(file, source)) {
38
63
  let resolved: string
39
64
  try {
40
65
  resolved = Bun.resolveSync(path, dirname(file))
package/src/dom/action.ts CHANGED
@@ -148,6 +148,8 @@ export function actionStub<Input = unknown, Output = unknown>(url: string): Clie
148
148
  if (to) {
149
149
  if (typeof location !== 'undefined') {
150
150
  try {
151
+ if (typeof location.href === 'string' && h.get('x-pru-redirect-external') !== '1' && new URL(to, location.href).origin !== new URL(location.href).origin)
152
+ throw new Error('Redirect to another site refused')
151
153
  location.assign(to)
152
154
  }
153
155
  catch (err) {
@@ -155,7 +157,8 @@ export function actionStub<Input = unknown, Output = unknown>(url: string): Clie
155
157
  }
156
158
  if (isSameDocHash(to))
157
159
  return { ok: true, data: undefined as Output }
158
- return new Promise<never>(() => {})
160
+ // A navigation unloads the page first; when none happens (a refused prompt, a download) the caller gets an error instead of waiting forever.
161
+ return new Promise<ActionResult<Output>>(resolve => setTimeout(() => resolve(fail(0, 'Navigation did not complete')), 10000))
159
162
  }
160
163
  return fail(res.status || 302, to)
161
164
  }
package/src/dom/extras.ts CHANGED
@@ -4,10 +4,9 @@
4
4
  import type { CatchProps } from '../context'
5
5
  import type { Owned } from '../reactivity/graph'
6
6
  import type { Owner } from '../reactivity/index'
7
- import { DOM_PROPS } from '../attrs'
7
+ import { DOM_PROPS, isBlockedAttr } from '../attrs'
8
8
  import { batch, createOwner, disposeOwner, effect, getOwner, onCleanup, onEffectError, runOwned, runWithOwner, signal, untrack } from '../reactivity/index'
9
9
  import { assertRenderable } from '../unrenderable'
10
- import { isBlockedAttr } from '../attrs'
11
10
  import { setAttr, setClass, setProp, setStyle } from './attrs'
12
11
  import { claimInsert } from './claim'
13
12
  import { claimRange, delegate, hydrateCursor, isHydrating, moveCursor, skipRange } from './index'
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]'
@@ -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)
142
+ }
143
+ else {
144
+ hydrateNode = node.nextSibling
135
145
  }
136
- hydrateNode = node.nextSibling
146
+ if (node !== stale && parent !== null)
147
+ mismatchHook?.(parent, stale, node)
137
148
  return node
138
149
  }
139
150
 
@@ -253,6 +264,7 @@ function dispatchEvent(event: Event): void {
253
264
  let current: EventTarget | null = null
254
265
  const prevDesc = Object.getOwnPropertyDescriptor(event, 'currentTarget')
255
266
  Object.defineProperty(event, 'currentTarget', { configurable: true, get: () => current })
267
+ const errors: unknown[] = []
256
268
 
257
269
  try {
258
270
  const path = event.composedPath?.()
@@ -263,9 +275,14 @@ function dispatchEvent(event: Event): void {
263
275
  const handler = node[key]
264
276
  if (typeof handler === 'function') {
265
277
  current = node
266
- batch(() => handler(event))
278
+ try {
279
+ batch(() => handler(event))
280
+ }
281
+ catch (err) {
282
+ errors.push(err)
283
+ }
267
284
  if (event.cancelBubble)
268
- return
285
+ break
269
286
  }
270
287
  node = (usePath ? path[++i] : (node as unknown as Node).parentNode) as (EventTarget & Record<string, ((e: Event) => void) | undefined>) | null | undefined
271
288
  }
@@ -276,6 +293,11 @@ function dispatchEvent(event: Event): void {
276
293
  else
277
294
  delete (event as unknown as Record<string, unknown>).currentTarget
278
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]
279
301
  }
280
302
 
281
303
  export function delegate(events: string[]): void {
package/src/dom/island.ts CHANGED
@@ -90,7 +90,8 @@ function replayEvent(root: Element, ev: Event, target: EventTarget | null): void
90
90
  target.dispatchEvent(clone)
91
91
  }
92
92
 
93
- function watchInteraction(root: Element, onTrigger: (after: () => void) => void): () => void {
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 {
94
95
  const evs = ['pointerdown', 'click', 'focusin', 'keydown']
95
96
  const queued: { ev: Event, target: EventTarget | null }[] = []
96
97
  let loading = false
@@ -101,9 +102,14 @@ function watchInteraction(root: Element, onTrigger: (after: () => void) => void)
101
102
  queued.push({ ev, target: ev.target })
102
103
  if (!loading) {
103
104
  loading = true
104
- onTrigger(() => {
105
+ void onTrigger(() => {
105
106
  for (let i = 0; i < queued.length; i++)
106
107
  replayEvent(root, queued[i]!.ev, queued[i]!.target)
108
+ }).then((ok) => {
109
+ if (!ok) {
110
+ loading = false
111
+ queued.length = 0
112
+ }
107
113
  })
108
114
  }
109
115
  }
@@ -186,10 +192,10 @@ export function defineIslandElement(): void {
186
192
  return
187
193
  }
188
194
  if ((typeof PRUNELLE_IDLE === 'undefined' || PRUNELLE_IDLE) && h === 'idle') {
189
- const g = globalThis as { requestIdleCallback?: (cb: () => void) => number, cancelIdleCallback?: (id: number) => void }
195
+ const g = globalThis as { requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number, cancelIdleCallback?: (id: number) => void }
190
196
  const run = () => void this._l(false, token)
191
197
  if (g.requestIdleCallback) {
192
- const id = g.requestIdleCallback(run)
198
+ const id = g.requestIdleCallback(run, { timeout: 2000 })
193
199
  this._c = () => g.cancelIdleCallback?.(id)
194
200
  }
195
201
  else {
@@ -199,7 +205,7 @@ export function defineIslandElement(): void {
199
205
  return
200
206
  }
201
207
  if ((typeof PRUNELLE_INTERACTION === 'undefined' || PRUNELLE_INTERACTION) && h === 'interaction') {
202
- this._c = watchInteraction(this, after => void this._l(false, token, true, after))
208
+ this._c = watchInteraction(this, after => this._l(false, token, true, after))
203
209
  return
204
210
  }
205
211
  if ((typeof PRUNELLE_MEDIA === 'undefined' || PRUNELLE_MEDIA) && h !== null && h.startsWith('media(')) {
@@ -234,13 +240,16 @@ export function defineIslandElement(): void {
234
240
  })
235
241
  }
236
242
 
237
- async _l(clientOnly: boolean, token: number, keepStrategy = false, after?: () => void): Promise<void> {
243
+ // Resolves false when the chunk failed to load or hydrate.
244
+ async _l(clientOnly: boolean, token: number, keepStrategy = false, after?: () => void): Promise<boolean> {
238
245
  if (!keepStrategy)
239
246
  this._clearStrategy()
240
247
  const chunk = this.getAttribute('c')
241
248
  if (!chunk || !isAllowedChunkUrl(chunk) || token !== this._t || !this.isConnected || this._d !== undefined) {
249
+ if (chunk && !isAllowedChunkUrl(chunk))
250
+ console.error(`[pru-island] refused chunk URL ${chunk}: it must be on this origin.`)
242
251
  this._clearStrategy()
243
- return
252
+ return true
244
253
  }
245
254
 
246
255
  let dispose: (() => void) | undefined
@@ -256,7 +265,7 @@ export function defineIslandElement(): void {
256
265
  mod = loaded
257
266
  if (!this.isConnected || token !== this._t || this._d !== undefined) {
258
267
  this._clearStrategy()
259
- return
268
+ return true
260
269
  }
261
270
  this._clearStrategy()
262
271
 
@@ -273,16 +282,19 @@ export function defineIslandElement(): void {
273
282
  : loaded.hydrate(this, render, idPrefix)
274
283
  if (!this.isConnected || token !== this._t) {
275
284
  dispose()
276
- return
285
+ return true
277
286
  }
278
287
  this._d = dispose
279
288
  after?.()
289
+ return true
280
290
  }
281
291
  catch (err) {
282
- this._clearStrategy()
292
+ if (!keepStrategy)
293
+ this._clearStrategy()
283
294
  dispose?.()
284
295
  // The chunk URL is a hash; in dev the component's own name says which island failed.
285
296
  console.error(`[pru-island] failed to hydrate ${process.env.NODE_ENV !== 'production' && mod?.default?.name ? `<${mod.default.name}> (${chunk})` : chunk}:`, err)
297
+ return false
286
298
  }
287
299
  }
288
300
  }
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
@@ -83,16 +83,28 @@ 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 {
87
+ for (let n = from; n !== null && n !== stop && !isRangeEnd(n); n = n.nextSibling)
88
+ out.push(n)
89
+ }
90
+
86
91
  // While hydrating, a row that rendered no node of its own takes the server nodes the cursor moved over since `before`.
87
- function adoptRowNodes<T>(parent: Node, marker: Node | null, row: Row<T>, before: Node | null, prevSib: 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 {
88
101
  const afterCursor = hydrateCursor()
89
102
  if (row.node === null && before !== null && before !== afterCursor) {
90
103
  const start = before.parentNode === parent ? before : prevSib !== null ? prevSib.nextSibling : parent.firstChild
91
104
  const claimed: Node[] = []
92
- for (let n: Node | null = start; n !== null && n !== afterCursor && n !== marker; 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,39 +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 prevSib = before?.previousSibling ?? null
133
- const row = newRow(items[i]!, i)
134
- adoptRowNodes(parent, marker, row, before, prevSib)
135
- 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)
136
170
  }
137
- end = hydrateCursor()
138
171
  }, skip, startMarker)) {
139
- dropServerRows(end, marker)
172
+ dropServerRows(parent, leftover, end, marker, added)
140
173
  return created
141
174
  }
142
175
  if (items.length > 0) {