prunelle 0.0.0-stage → 0.5.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 (200) hide show
  1. package/llms.txt +152 -0
  2. package/package.json +59 -4
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/ambient.d.ts +6 -0
  7. package/src/attrs.ts +43 -0
  8. package/src/build/bundle.ts +657 -0
  9. package/src/build/carry.ts +57 -0
  10. package/src/build/client-entries.ts +107 -0
  11. package/src/build/client-plugin.ts +173 -0
  12. package/src/build/client-prune.ts +168 -0
  13. package/src/build/compile.ts +129 -0
  14. package/src/build/ecoindex.ts +229 -0
  15. package/src/build/files.ts +156 -0
  16. package/src/build/first-load.ts +164 -0
  17. package/src/build/graph.ts +247 -0
  18. package/src/build/index.ts +641 -0
  19. package/src/build/is-inside.ts +12 -0
  20. package/src/build/islands.ts +641 -0
  21. package/src/build/manifest.ts +325 -0
  22. package/src/build/output.ts +84 -0
  23. package/src/build/plugin-host.ts +278 -0
  24. package/src/build/precompress.ts +139 -0
  25. package/src/build/prerender.ts +232 -0
  26. package/src/build/render-rules.ts +205 -0
  27. package/src/build/report.ts +268 -0
  28. package/src/build/resolve.ts +52 -0
  29. package/src/build/routes.ts +342 -0
  30. package/src/build/server-entry.ts +38 -0
  31. package/src/build/static.ts +207 -0
  32. package/src/build/status-pages.ts +127 -0
  33. package/src/build/style-bundles.ts +526 -0
  34. package/src/cli/check-forms.ts +654 -0
  35. package/src/cli/check-links.ts +619 -0
  36. package/src/cli/check.ts +381 -0
  37. package/src/cli/commands.ts +345 -0
  38. package/src/cli/docs.ts +402 -0
  39. package/src/cli/index.ts +70 -0
  40. package/src/cli/inspect.ts +345 -0
  41. package/src/cli/mcp-tools.ts +480 -0
  42. package/src/cli/mcp.ts +205 -0
  43. package/src/cli/new.ts +41 -0
  44. package/src/cli/render.ts +261 -0
  45. package/src/cli/upgrade-names.ts +209 -0
  46. package/src/cli/upgrade.ts +354 -0
  47. package/src/compiler/analyze.ts +632 -0
  48. package/src/compiler/ast.ts +82 -0
  49. package/src/compiler/browser-globals.ts +127 -0
  50. package/src/compiler/cacheability.ts +592 -0
  51. package/src/compiler/compliance-rgaa.ts +502 -0
  52. package/src/compiler/compliance.ts +497 -0
  53. package/src/compiler/data-keys.ts +295 -0
  54. package/src/compiler/dev-source.ts +87 -0
  55. package/src/compiler/dom-attrs.ts +452 -0
  56. package/src/compiler/dom.ts +567 -0
  57. package/src/compiler/emit.ts +131 -0
  58. package/src/compiler/expr-context.ts +518 -0
  59. package/src/compiler/index.ts +8 -0
  60. package/src/compiler/interactivity.ts +366 -0
  61. package/src/compiler/mistakes.ts +499 -0
  62. package/src/compiler/node-env.ts +50 -0
  63. package/src/compiler/patch.ts +97 -0
  64. package/src/compiler/props.ts +511 -0
  65. package/src/compiler/scope.ts +607 -0
  66. package/src/compiler/server-only.ts +326 -0
  67. package/src/compiler/shared.ts +369 -0
  68. package/src/compiler/signal-reads.ts +242 -0
  69. package/src/compiler/slots.ts +227 -0
  70. package/src/compiler/ssr-helpers.ts +555 -0
  71. package/src/compiler/ssr-island.ts +90 -0
  72. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  73. package/src/compiler/ssr.ts +526 -0
  74. package/src/context.ts +165 -0
  75. package/src/dev/child.ts +30 -0
  76. package/src/dev/error-log.ts +151 -0
  77. package/src/dev/index.ts +258 -0
  78. package/src/dev/modules.ts +68 -0
  79. package/src/dev/open-editor.ts +204 -0
  80. package/src/dev/protocol.ts +22 -0
  81. package/src/dev/queue.ts +79 -0
  82. package/src/dev/reload.ts +159 -0
  83. package/src/dev/supervisor.ts +204 -0
  84. package/src/dev/watchers.ts +251 -0
  85. package/src/dom/action.ts +164 -0
  86. package/src/dom/attrs.ts +84 -0
  87. package/src/dom/claim.ts +120 -0
  88. package/src/dom/extras.ts +562 -0
  89. package/src/dom/index.ts +289 -0
  90. package/src/dom/island.ts +285 -0
  91. package/src/dom/loop.ts +450 -0
  92. package/src/dom/revive.ts +36 -0
  93. package/src/index.ts +22 -0
  94. package/src/jsx-runtime.ts +566 -0
  95. package/src/plugins/config.ts +86 -0
  96. package/src/plugins/context.ts +66 -0
  97. package/src/plugins/index.ts +14 -0
  98. package/src/plugins/load.ts +70 -0
  99. package/src/plugins/order.ts +111 -0
  100. package/src/plugins/public.ts +15 -0
  101. package/src/plugins/requires.ts +47 -0
  102. package/src/plugins/services.ts +97 -0
  103. package/src/plugins/types.ts +261 -0
  104. package/src/reactivity/graph.ts +249 -0
  105. package/src/reactivity/index.ts +533 -0
  106. package/src/reactivity/selector.ts +51 -0
  107. package/src/reactivity/store.ts +208 -0
  108. package/src/server/action-protect.ts +198 -0
  109. package/src/server/action-registry.ts +78 -0
  110. package/src/server/action.ts +530 -0
  111. package/src/server/app-entry.ts +23 -0
  112. package/src/server/assets.ts +168 -0
  113. package/src/server/compress.ts +642 -0
  114. package/src/server/consent.ts +253 -0
  115. package/src/server/cookies.ts +139 -0
  116. package/src/server/document.ts +271 -0
  117. package/src/server/env.ts +33 -0
  118. package/src/server/errors.ts +391 -0
  119. package/src/server/form-schema.ts +343 -0
  120. package/src/server/health.ts +244 -0
  121. package/src/server/http.ts +538 -0
  122. package/src/server/index.ts +586 -0
  123. package/src/server/lifecycle.ts +75 -0
  124. package/src/server/loader.ts +123 -0
  125. package/src/server/page.ts +107 -0
  126. package/src/server/param-matchers.ts +112 -0
  127. package/src/server/plugin-host.ts +265 -0
  128. package/src/server/prerendered.ts +71 -0
  129. package/src/server/public.ts +19 -0
  130. package/src/server/rate-limit.ts +156 -0
  131. package/src/server/region.ts +96 -0
  132. package/src/server/request-body.ts +27 -0
  133. package/src/server/request-path.ts +73 -0
  134. package/src/server/request-scope.ts +22 -0
  135. package/src/server/route-cache.ts +423 -0
  136. package/src/server/route-table.ts +410 -0
  137. package/src/server/router.ts +261 -0
  138. package/src/server/routing.ts +472 -0
  139. package/src/server/security.ts +499 -0
  140. package/src/server/serve-handlers.ts +83 -0
  141. package/src/server/served-file.ts +128 -0
  142. package/src/server/standard-schema.ts +87 -0
  143. package/src/server/start.ts +143 -0
  144. package/src/server/static-dir.ts +220 -0
  145. package/src/server/stream.ts +211 -0
  146. package/src/ssr/context.ts +383 -0
  147. package/src/ssr/index.ts +596 -0
  148. package/src/ssr/navigation.ts +96 -0
  149. package/src/ssr/region.ts +183 -0
  150. package/src/style.ts +33 -0
  151. package/src/test/browser.ts +192 -0
  152. package/src/test/index.ts +191 -0
  153. package/src/ts-plugin/diagnostics.ts +378 -0
  154. package/src/ts-plugin/fixes.ts +364 -0
  155. package/src/ts-plugin/index.ts +194 -0
  156. package/src/unrenderable.ts +35 -0
  157. package/templates/_shared/AGENTS.md +10 -0
  158. package/templates/_shared/CLAUDE.md +1 -0
  159. package/templates/_shared/gitignore +3 -0
  160. package/templates/_shared/mcp.json +11 -0
  161. package/templates/_shared/public/robots.txt +2 -0
  162. package/templates/_shared/src/routes/legal.tsx +13 -0
  163. package/templates/_shared/tsconfig.json +25 -0
  164. package/templates/app/.env.example +4 -0
  165. package/templates/app/package.json +21 -0
  166. package/templates/app/prunelle.config.ts +11 -0
  167. package/templates/app/src/auth.ts +14 -0
  168. package/templates/app/src/routes/_layout.tsx +32 -0
  169. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  170. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  171. package/templates/app/src/routes/index.tsx +15 -0
  172. package/templates/app/src/routes/login.tsx +34 -0
  173. package/templates/app/src/styles/app.css +7 -0
  174. package/templates/app/tests/app.test.ts +32 -0
  175. package/templates/blog/content/posts/welcome.md +9 -0
  176. package/templates/blog/package.json +22 -0
  177. package/templates/blog/prunelle.config.ts +23 -0
  178. package/templates/blog/src/posts.ts +26 -0
  179. package/templates/blog/src/routes/_layout.tsx +20 -0
  180. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  181. package/templates/blog/src/routes/index.tsx +33 -0
  182. package/templates/blog/src/styles/app.css +10 -0
  183. package/templates/fullstack/package.json +19 -0
  184. package/templates/fullstack/prunelle.config.ts +6 -0
  185. package/templates/fullstack/src/actions/greet.ts +19 -0
  186. package/templates/fullstack/src/components/Counter.tsx +10 -0
  187. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  188. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  189. package/templates/fullstack/src/routes/api/health.ts +5 -0
  190. package/templates/fullstack/src/routes/index.tsx +13 -0
  191. package/templates/fullstack/src/styles/app.css +29 -0
  192. package/templates/fullstack/tests/app.test.ts +37 -0
  193. package/templates/minimal/package.json +19 -0
  194. package/templates/minimal/prunelle.config.ts +6 -0
  195. package/templates/minimal/src/components/Counter.tsx +10 -0
  196. package/templates/minimal/src/routes/_layout.tsx +14 -0
  197. package/templates/minimal/src/routes/index.tsx +11 -0
  198. package/templates/minimal/src/styles/app.css +22 -0
  199. package/ts-plugin.cjs +4277 -0
  200. package/README.md +0 -3
@@ -0,0 +1,289 @@
1
+ // Prunelle minimal DOM & hydration core. Every island imports it, so what only some islands need lives apart: attribute bindings in prunelle/internal/dom-attrs, claiming SSR lists and inserts in dom-claim, lists in dom-loop, inserts and spreads in dom-extras.
2
+
3
+ import { batch, createOwner, disposeOwner, getOwner, onCleanup, runWithOwner } from '../reactivity/index'
4
+ import { assertRenderable } from '../unrenderable'
5
+
6
+ export { effect } from '../reactivity/index'
7
+
8
+ let hydrating = false
9
+ let hydrateNode: Node | null = null
10
+ let hydrateRoot: Element | null = null
11
+
12
+ export function isRangeEnd(node: Node): boolean {
13
+ return node.nodeType === 8 && (node as Comment).data === 'k]'
14
+ }
15
+
16
+ export function hydrateCursor(): Node | null {
17
+ return hydrating ? hydrateNode : null
18
+ }
19
+
20
+ export function isHydrating(): boolean {
21
+ return hydrating
22
+ }
23
+
24
+ /** Points the hydration cursor at `node` (claiming SSR nodes when `on`) and returns the cursor it replaced, for the caller to restore. */
25
+ export function moveCursor(on: boolean, node: Node | null): [boolean, Node | null] {
26
+ const prev: [boolean, Node | null] = [hydrating, hydrateNode]
27
+ hydrating = on
28
+ hydrateNode = node
29
+ return prev
30
+ }
31
+
32
+ export function hydrate(container: Element, render: () => Node | DocumentFragment | null, idPrefix?: string): () => void {
33
+ const owner = createOwner(undefined)
34
+ if (idPrefix !== undefined)
35
+ owner.id = { p: idPrefix, n: 0 }
36
+ const prevHydrating = hydrating
37
+ const prevNode = hydrateNode
38
+ const prevRoot = process.env.NODE_ENV !== 'production' ? hydrateRoot : null
39
+ hydrating = true
40
+ hydrateNode = container.firstChild
41
+ if (process.env.NODE_ENV !== 'production')
42
+ hydrateRoot = container
43
+
44
+ try {
45
+ runWithOwner(owner, () => {
46
+ render()
47
+ })
48
+ }
49
+ catch (err) {
50
+ disposeOwner(owner)
51
+ throw err
52
+ }
53
+ finally {
54
+ hydrating = prevHydrating
55
+ hydrateNode = prevNode
56
+ if (process.env.NODE_ENV !== 'production')
57
+ hydrateRoot = prevRoot
58
+ }
59
+
60
+ return () => disposeOwner(owner)
61
+ }
62
+
63
+ export function mount(container: Element, render: () => Node | DocumentFragment | null, idPrefix?: string): () => void {
64
+ const owner = createOwner(undefined)
65
+ if (idPrefix !== undefined)
66
+ owner.id = { p: idPrefix, n: 0 }
67
+ const prevHydrating = hydrating
68
+ hydrating = false
69
+ try {
70
+ const node = runWithOwner(owner, render)
71
+ container.textContent = ''
72
+ if (node !== null)
73
+ container.appendChild(node)
74
+ }
75
+ catch (err) {
76
+ disposeOwner(owner)
77
+ throw err
78
+ }
79
+ finally {
80
+ hydrating = prevHydrating
81
+ }
82
+ return () => disposeOwner(owner)
83
+ }
84
+
85
+ function warnMismatch(node: Node, expectedTag: string, steppedOver: boolean): void {
86
+ const island = hydrateRoot?.getAttribute('c') ?? hydrateRoot?.tagName.toLowerCase() ?? 'unknown'
87
+ const found = node.nodeType === 1
88
+ ? `<${(node as Element).tagName.toLowerCase()}>`
89
+ : node.nodeType === 3
90
+ ? `#text(${JSON.stringify((node as Text).data.slice(0, 30))})`
91
+ : node.nodeType === 8
92
+ ? `<!--${(node as Comment).data}-->`
93
+ : `nodeType(${node.nodeType})`
94
+ console.warn(`prunelle: hydration mismatch in island "${island}": expected <${expectedTag}>, found ${found}; ${steppedOver ? `hydrating the next <${expectedTag}>` : 'falling back to fresh clone'}.`)
95
+ }
96
+
97
+ export function template(html: string, isSvg?: boolean): () => Node {
98
+ let cached: Node | undefined
99
+ const expectedTag = /^<([A-Za-z][^\s/>]*)/.exec(html)?.[1]?.toLowerCase()
100
+
101
+ const clone = (): Node => {
102
+ if (cached === undefined) {
103
+ const t = document.createElement('template')
104
+ t.innerHTML = isSvg ? `<svg>${html}</svg>` : html
105
+ cached = isSvg ? t.content.firstChild!.firstChild! : t.content.firstChild!
106
+ }
107
+ return cached.cloneNode(true)
108
+ }
109
+
110
+ return (): Node => {
111
+ if (hydrating && hydrateNode !== null) {
112
+ const stale = hydrateNode
113
+ // Stop at a closing range marker so a mismatch inside a branch never steals or replaces nodes outside it.
114
+ if (isRangeEnd(stale)) {
115
+ if (process.env.NODE_ENV !== 'production' && expectedTag !== undefined)
116
+ warnMismatch(stale, expectedTag, false)
117
+ hydrating = false
118
+ hydrateNode = null
119
+ return clone()
120
+ }
121
+ // A node injected before the markup (an extension, a password manager) is stepped over; no matching node at all means the server rendered something else.
122
+ let node: Node | null = stale
123
+ while (node !== null && !isRangeEnd(node) && expectedTag !== undefined && node.nodeName.toLowerCase() !== expectedTag)
124
+ node = node.nextSibling
125
+ if (node !== null && isRangeEnd(node))
126
+ node = null
127
+ if (process.env.NODE_ENV !== 'production' && node !== stale)
128
+ warnMismatch(stale, expectedTag!, node !== null)
129
+ if (node === null) {
130
+ hydrating = false
131
+ hydrateNode = null
132
+ const fresh = clone()
133
+ stale.parentNode?.replaceChild(fresh, stale)
134
+ return fresh
135
+ }
136
+ hydrateNode = node.nextSibling
137
+ return node
138
+ }
139
+
140
+ return clone()
141
+ }
142
+ }
143
+
144
+ // Moves the hydration cursor past the SSR range of a root fragment's dynamic child (`<!--k[-->...<!--k]-->` or `<!---->text<!---->`) and returns its opening marker; null when not hydrating.
145
+ export function claimRange(): Node | null {
146
+ const start = hydrating ? hydrateNode : null
147
+ if (start === null || start.nodeType !== 8)
148
+ return null
149
+ hydrateNode = skipRange(start)?.nextSibling ?? null
150
+ return start
151
+ }
152
+
153
+ // A text child of a root fragment, claimed from the SSR markup while hydrating; a dynamic one sits between `<!---->` markers.
154
+ export function fragText(data: string, dynamic?: boolean): Text {
155
+ if (dynamic) {
156
+ const start = claimRange()
157
+ if (start !== null)
158
+ return textAfter(start)
159
+ }
160
+ else if (hydrating && hydrateNode !== null && hydrateNode.nodeType === 3) {
161
+ const text = hydrateNode as Text
162
+ hydrateNode = text.nextSibling
163
+ return text
164
+ }
165
+ return document.createTextNode(data)
166
+ }
167
+
168
+ export function frag(...nodes: Node[]): Node | null {
169
+ if (hydrating)
170
+ return null
171
+ const f = document.createDocumentFragment()
172
+ for (let i = 0; i < nodes.length; i++)
173
+ f.appendChild(nodes[i]!)
174
+ return f
175
+ }
176
+
177
+ export function firstText(el: Node): Text {
178
+ const first = el.firstChild
179
+ if (first !== null && first.nodeType === 3)
180
+ return first as Text
181
+ const text = document.createTextNode('')
182
+ el.insertBefore(text, first)
183
+ return text
184
+ }
185
+
186
+ export function textAfter(marker: Node): Text {
187
+ const next = marker.nextSibling
188
+ if (next !== null && next.nodeType === 3)
189
+ return next as Text
190
+ const text = document.createTextNode('')
191
+ marker.parentNode!.insertBefore(text, next)
192
+ return text
193
+ }
194
+
195
+ /** Advance past an optional SSR text node (`<!-->text<!-->` or `<!--><!-->`) to the closing comment marker. */
196
+ export function skipText(marker: Node): Node | null {
197
+ const next = marker.nextSibling
198
+ return next !== null && next.nodeType === 3 ? next.nextSibling : next
199
+ }
200
+
201
+ /** Advance past an SSR-bracketed dynamic range (`<!--k[-->...<!--k]-->` or `<!---->...<!---->`) to its closing comment marker. */
202
+ export function skipRange(marker: Node): Node | null {
203
+ const balanced = marker.nodeType === 8 && (marker as Comment).data === 'k['
204
+ let depth = balanced ? 1 : 0
205
+ let cur = marker.nextSibling
206
+ while (cur !== null) {
207
+ if (cur.nodeType === 8) {
208
+ if (!balanced)
209
+ return cur
210
+ const data = (cur as Comment).data
211
+ if (data === 'k[')
212
+ depth++
213
+ else if (data === 'k]' && --depth === 0)
214
+ return cur
215
+ }
216
+ cur = cur.nextSibling
217
+ }
218
+ return null
219
+ }
220
+
221
+ export function setText(node: Text, value: unknown): void {
222
+ if (process.env.NODE_ENV !== 'production')
223
+ assertRenderable(value, 'text')
224
+ const str = value == null || typeof value === 'boolean' ? '' : String(value)
225
+ if (node.data !== str)
226
+ node.data = str
227
+ }
228
+
229
+ // ---- Delegated events
230
+
231
+ const delegated = new WeakMap<Document, Set<string>>()
232
+
233
+ function dispatchEvent(event: Event): void {
234
+ const key = `$$${event.type}`
235
+ let current: EventTarget | null = null
236
+ const prevDesc = Object.getOwnPropertyDescriptor(event, 'currentTarget')
237
+ Object.defineProperty(event, 'currentTarget', { configurable: true, get: () => current })
238
+
239
+ try {
240
+ const path = event.composedPath?.()
241
+ const usePath = path !== undefined && path.length > 0
242
+ let i = 0
243
+ let node = (usePath ? path[0] : event.target) as (EventTarget & Record<string, ((e: Event) => void) | undefined>) | null | undefined
244
+ while (node != null) {
245
+ const handler = node[key]
246
+ if (typeof handler === 'function') {
247
+ current = node
248
+ batch(() => handler(event))
249
+ if (event.cancelBubble)
250
+ return
251
+ }
252
+ node = (usePath ? path[++i] : (node as unknown as Node).parentNode) as (EventTarget & Record<string, ((e: Event) => void) | undefined>) | null | undefined
253
+ }
254
+ }
255
+ finally {
256
+ if (prevDesc !== undefined)
257
+ Object.defineProperty(event, 'currentTarget', prevDesc)
258
+ else
259
+ delete (event as unknown as Record<string, unknown>).currentTarget
260
+ }
261
+ }
262
+
263
+ export function delegate(events: string[]): void {
264
+ if (typeof document === 'undefined')
265
+ return
266
+ let set = delegated.get(document)
267
+ if (set === undefined) {
268
+ set = new Set()
269
+ delegated.set(document, set)
270
+ }
271
+ for (let i = 0; i < events.length; i++) {
272
+ const type = events[i]!
273
+ if (!set.has(type)) {
274
+ set.add(type)
275
+ document.addEventListener(type, dispatchEvent)
276
+ }
277
+ }
278
+ }
279
+
280
+ export function on(el: Node, event: string, handler: ((e: Event) => void) | false | null | undefined): void {
281
+ if (typeof handler !== 'function')
282
+ return
283
+ const fn = (e: Event) => {
284
+ batch(() => handler(e))
285
+ }
286
+ el.addEventListener(event, fn)
287
+ if (getOwner() !== undefined)
288
+ onCleanup(() => el.removeEventListener(event, fn))
289
+ }
@@ -0,0 +1,285 @@
1
+ // Native <pru-island> Custom Element: the build defines which strategies an app uses, so the loader drops the code of the others.
2
+
3
+ import type { hydrate, mount } from './index'
4
+
5
+ declare const PRUNELLE_VISIBLE: boolean | undefined
6
+ declare const PRUNELLE_IDLE: boolean | undefined
7
+ declare const PRUNELLE_INTERACTION: boolean | undefined
8
+ declare const PRUNELLE_MEDIA: boolean | undefined
9
+ declare const PRUNELLE_CLIENT_ONLY: boolean | undefined
10
+ /** The URL `prunelle build` gave the prop revivers; left undefined, they load from source. */
11
+ declare const PRUNELLE_REVIVE: string | undefined
12
+
13
+ // Only props holding a Date, Map, Set or another tagged value load the revivers: plain JSON parses with no extra file.
14
+ const reviver = (): Promise<typeof import('./revive')> => typeof PRUNELLE_REVIVE === 'undefined' ? import('./revive') : import(PRUNELLE_REVIVE)
15
+
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
+
19
+ /** Finds this island's own `<script type="application/json" data-pru-props>` direct child. */
20
+ function findOwnPropsScript(root: Element): Element | null {
21
+ for (let child = root.lastElementChild; child !== null; child = child.previousElementSibling) {
22
+ if (child.tagName === 'SCRIPT' && child.hasAttribute('data-pru-props'))
23
+ return child
24
+ }
25
+ return null
26
+ }
27
+
28
+ /** Finds this island's own `<pru-slot>` without descending into nested `<pru-island>` boundaries. */
29
+ function findOwnSlot(root: Element): Element | null {
30
+ for (let child = root.firstElementChild; child !== null; child = child.nextElementSibling) {
31
+ const tag = child.tagName
32
+ if (tag === 'PRU-SLOT')
33
+ return child
34
+ if (tag === 'PRU-ISLAND')
35
+ continue
36
+ const nested = findOwnSlot(child)
37
+ if (nested !== null)
38
+ return nested
39
+ }
40
+ return null
41
+ }
42
+
43
+ function extractOwnSlot(root: Element): Element | null {
44
+ for (let child = root.lastElementChild; child !== null; child = child.previousElementSibling) {
45
+ if (child.tagName === 'TEMPLATE' && child.hasAttribute('data-pru-slot')) {
46
+ const slot = document.createElement('pru-slot')
47
+ slot.appendChild((child as HTMLTemplateElement).content)
48
+ child.remove()
49
+ return slot
50
+ }
51
+ }
52
+ return findOwnSlot(root)
53
+ }
54
+
55
+ /** Collects box-generating descendant elements for IntersectionObserver, stepping through `display: contents` wrappers. */
56
+ function collectVisibleTargets(root: Element, out: Element[]): void {
57
+ for (let child = root.firstElementChild; child !== null; child = child.nextElementSibling) {
58
+ const tag = child.tagName
59
+ if (tag === 'SCRIPT' || tag === 'TEMPLATE')
60
+ continue
61
+ const isContents = tag === 'PRU-SLOT'
62
+ || tag === 'PRU-ISLAND'
63
+ || (typeof getComputedStyle === 'function' && getComputedStyle(child).display === 'contents')
64
+ if (isContents)
65
+ collectVisibleTargets(child, out)
66
+ else
67
+ out.push(child)
68
+ }
69
+ }
70
+
71
+ function replayEvent(root: Element, ev: Event, target: EventTarget | null): void {
72
+ if (target === null || typeof target.dispatchEvent !== 'function')
73
+ return
74
+ if (typeof (target as Node).nodeType === 'number' && !root.contains(target as Node))
75
+ return
76
+ const init: EventInit = { bubbles: ev.bubbles, cancelable: ev.cancelable, composed: ev.composed }
77
+ let clone: Event
78
+ if (ev.type === 'keydown') {
79
+ const ke = ev as KeyboardEvent
80
+ clone = new KeyboardEvent(ev.type, { ...init, key: ke.key, code: ke.code, altKey: ke.altKey, ctrlKey: ke.ctrlKey, shiftKey: ke.shiftKey, metaKey: ke.metaKey })
81
+ }
82
+ else if (ev.type === 'click' || ev.type === 'pointerdown') {
83
+ const me = ev as MouseEvent
84
+ const Ctor = ev.type === 'pointerdown' && typeof PointerEvent === 'function' ? PointerEvent : MouseEvent
85
+ clone = new Ctor(ev.type, { ...init, button: me.button, buttons: me.buttons, clientX: me.clientX, clientY: me.clientY, altKey: me.altKey, ctrlKey: me.ctrlKey, shiftKey: me.shiftKey, metaKey: me.metaKey })
86
+ }
87
+ else {
88
+ clone = typeof FocusEvent === 'function' ? new FocusEvent(ev.type, init) : new Event(ev.type, init)
89
+ }
90
+ target.dispatchEvent(clone)
91
+ }
92
+
93
+ function isAllowedChunkUrl(chunk: string): boolean {
94
+ if (/[\u0000-\u0020\u007F]/.test(chunk))
95
+ return false
96
+ if (typeof location !== 'undefined' && location.origin && location.origin !== 'null') {
97
+ try {
98
+ return new URL(chunk, location.href).origin === location.origin
99
+ }
100
+ catch {
101
+ return false
102
+ }
103
+ }
104
+ // A browser reads `//host` and `/\host` as another site.
105
+ if (chunk[0] === '/')
106
+ return chunk[1] !== '/' && chunk[1] !== '\\'
107
+ return !/^(?:javascript|data|vbscript):/i.test(chunk)
108
+ }
109
+
110
+ let clientIslandIdSeq = 0
111
+
112
+ export function defineIslandElement(): void {
113
+ if (typeof customElements === 'undefined' || customElements.get('pru-island'))
114
+ return
115
+
116
+ class PrunelleIsland extends HTMLElement {
117
+ _d: (() => void) | undefined
118
+ _c: (() => void) | undefined
119
+ _p: string | undefined
120
+ _slot: Element | undefined
121
+ _s = false
122
+ _t = 0
123
+
124
+ _clearStrategy(): void {
125
+ this._c?.()
126
+ this._c = undefined
127
+ }
128
+
129
+ connectedCallback(): void {
130
+ if (this._s)
131
+ return
132
+ this._s = true
133
+ const token = ++this._t
134
+
135
+ const h = this.getAttribute('h')
136
+ if ((typeof PRUNELLE_VISIBLE === 'undefined' || PRUNELLE_VISIBLE) && h === 'visible') {
137
+ if (typeof IntersectionObserver === 'undefined') {
138
+ void this._l(false, token)
139
+ return
140
+ }
141
+ const targets: Element[] = []
142
+ collectVisibleTargets(this, targets)
143
+ let restoreDisplay: (() => void) | undefined
144
+ if (targets.length === 0) {
145
+ const display = typeof getComputedStyle === 'function' ? getComputedStyle(this).display : 'contents'
146
+ if (display === 'contents' || display === '') {
147
+ const prev = this.style.display
148
+ this.style.display = 'inline'
149
+ restoreDisplay = () => { this.style.display = prev }
150
+ }
151
+ targets.push(this)
152
+ }
153
+ const io = new IntersectionObserver((entries) => {
154
+ if (entries.some(e => e.isIntersecting))
155
+ void this._l(false, token)
156
+ }, { rootMargin: '200px' })
157
+ this._c = () => {
158
+ io.disconnect()
159
+ restoreDisplay?.()
160
+ }
161
+ for (const target of targets)
162
+ io.observe(target)
163
+ return
164
+ }
165
+ if ((typeof PRUNELLE_IDLE === 'undefined' || PRUNELLE_IDLE) && h === 'idle') {
166
+ const g = globalThis as { requestIdleCallback?: (cb: () => void) => number, cancelIdleCallback?: (id: number) => void }
167
+ const run = () => void this._l(false, token)
168
+ if (g.requestIdleCallback) {
169
+ const id = g.requestIdleCallback(run)
170
+ this._c = () => g.cancelIdleCallback?.(id)
171
+ }
172
+ else {
173
+ const id = setTimeout(run, 1)
174
+ this._c = () => clearTimeout(id)
175
+ }
176
+ return
177
+ }
178
+ if ((typeof PRUNELLE_INTERACTION === 'undefined' || PRUNELLE_INTERACTION) && h === 'interaction') {
179
+ const evs = ['pointerdown', 'click', 'focusin', 'keydown']
180
+ const queued: { ev: Event, target: EventTarget | null }[] = []
181
+ let loading = false
182
+ const stop = () => {
183
+ for (const e of evs) this.removeEventListener(e, go, true)
184
+ }
185
+ const go = (ev: Event) => {
186
+ queued.push({ ev, target: ev.target })
187
+ if (!loading) {
188
+ loading = true
189
+ void this._l(false, token, true, () => {
190
+ for (let i = 0; i < queued.length; i++)
191
+ replayEvent(this, queued[i]!.ev, queued[i]!.target)
192
+ })
193
+ }
194
+ }
195
+ for (const e of evs) this.addEventListener(e, go, true)
196
+ this._c = stop
197
+ return
198
+ }
199
+ if ((typeof PRUNELLE_MEDIA === 'undefined' || PRUNELLE_MEDIA) && h !== null && h.startsWith('media(')) {
200
+ const mq = matchMedia(h.slice(6, -1))
201
+ if (mq.matches) {
202
+ void this._l(false, token)
203
+ }
204
+ else {
205
+ const go = () => {
206
+ if (mq.matches)
207
+ void this._l(false, token)
208
+ }
209
+ mq.addEventListener('change', go)
210
+ this._c = () => mq.removeEventListener('change', go)
211
+ }
212
+ return
213
+ }
214
+
215
+ void this._l(h === 'client', token)
216
+ }
217
+
218
+ disconnectedCallback(): void {
219
+ // Defer disposal by a microtask so synchronous DOM moves (e.g. SPA persistent islands) stay alive!
220
+ queueMicrotask(() => {
221
+ if (!this.isConnected) {
222
+ this._t++
223
+ this._clearStrategy()
224
+ this._d?.()
225
+ this._d = undefined
226
+ this._s = false
227
+ }
228
+ })
229
+ }
230
+
231
+ async _l(clientOnly: boolean, token: number, keepStrategy = false, after?: () => void): Promise<void> {
232
+ if (!keepStrategy)
233
+ this._clearStrategy()
234
+ const chunk = this.getAttribute('c')
235
+ if (!chunk || !isAllowedChunkUrl(chunk) || token !== this._t || !this.isConnected || this._d !== undefined) {
236
+ this._clearStrategy()
237
+ return
238
+ }
239
+
240
+ let dispose: (() => void) | undefined
241
+ let mod: IslandModule | undefined
242
+ try {
243
+ const ps = findOwnPropsScript(this)
244
+ if (ps !== null) {
245
+ this._p = ps.textContent || '{}'
246
+ ps.remove()
247
+ }
248
+ const raw = this._p ?? this.getAttribute('p')
249
+ const [loaded, revive] = await Promise.all([import(chunk) as Promise<IslandModule>, raw?.includes('"__k":') ? reviver() : undefined])
250
+ mod = loaded
251
+ if (!this.isConnected || token !== this._t || this._d !== undefined) {
252
+ this._clearStrategy()
253
+ return
254
+ }
255
+ this._clearStrategy()
256
+
257
+ const props = (raw ? revive?.parseIslandProps(raw) ?? JSON.parse(raw) : {}) as Record<string, unknown>
258
+ const slot = extractOwnSlot(this) ?? this._slot ?? null
259
+ if (slot !== null) {
260
+ this._slot = slot
261
+ props.children = slot
262
+ }
263
+ const idPrefix = this.getAttribute('i') ?? `c${clientIslandIdSeq++}-`
264
+ const render = () => loaded.default(props)
265
+ dispose = (typeof PRUNELLE_CLIENT_ONLY === 'undefined' || PRUNELLE_CLIENT_ONLY) && clientOnly
266
+ ? loaded.mount!(this, render, idPrefix)
267
+ : loaded.hydrate(this, render, idPrefix)
268
+ if (!this.isConnected || token !== this._t) {
269
+ dispose()
270
+ return
271
+ }
272
+ this._d = dispose
273
+ after?.()
274
+ }
275
+ catch (err) {
276
+ this._clearStrategy()
277
+ dispose?.()
278
+ // The chunk URL is a hash; in dev the component's own name says which island failed.
279
+ console.error(`[pru-island] failed to hydrate ${process.env.NODE_ENV !== 'production' && mod?.default?.name ? `<${mod.default.name}> (${chunk})` : chunk}:`, err)
280
+ }
281
+ }
282
+ }
283
+
284
+ customElements.define('pru-island', PrunelleIsland)
285
+ }