prunelle 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/llms.txt +18 -18
  2. package/package.json +2 -2
  3. package/src/a11y/declaration.ts +4 -7
  4. package/src/build/bundle.ts +6 -2
  5. package/src/build/index.ts +3 -1
  6. package/src/build/island-promote.ts +42 -2
  7. package/src/build/islands.ts +59 -8
  8. package/src/build/manifest.ts +98 -0
  9. package/src/build/plugin-host.ts +11 -1
  10. package/src/build/prerender.ts +6 -1
  11. package/src/build/reach.ts +4 -3
  12. package/src/build/resolve.ts +5 -1
  13. package/src/build/routes.ts +18 -0
  14. package/src/cli/check-forms.ts +8 -0
  15. package/src/cli/check-links.ts +14 -5
  16. package/src/cli/check.ts +12 -6
  17. package/src/cli/commands.ts +5 -3
  18. package/src/cli/form-opaque-children.ts +40 -0
  19. package/src/compiler/analyze.ts +20 -14
  20. package/src/compiler/cacheability-private.ts +13 -3
  21. package/src/compiler/compliance-contrast.ts +48 -10
  22. package/src/compiler/compliance-rules.ts +72 -0
  23. package/src/compiler/compliance.ts +6 -66
  24. package/src/compiler/dom-attrs.ts +178 -22
  25. package/src/compiler/dom.ts +31 -44
  26. package/src/compiler/emit.ts +17 -6
  27. package/src/compiler/expr-context.ts +260 -207
  28. package/src/compiler/props-body.ts +263 -21
  29. package/src/compiler/props.ts +155 -5
  30. package/src/compiler/signal-reads.ts +142 -29
  31. package/src/compiler/spread-handlers.ts +25 -13
  32. package/src/compiler/ssr-emit.ts +3 -3
  33. package/src/compiler/ssr-helpers.ts +0 -5
  34. package/src/compiler/ssr.ts +4 -2
  35. package/src/dev/host-check.ts +2 -1
  36. package/src/dev/reload.ts +4 -1
  37. package/src/dom/attrs.ts +93 -25
  38. package/src/dom/extras.ts +89 -49
  39. package/src/dom/field-marks.ts +9 -1
  40. package/src/dom/index.ts +19 -13
  41. package/src/dom/loop.ts +259 -188
  42. package/src/dom/prefetch.ts +4 -1
  43. package/src/dom/regions.ts +25 -8
  44. package/src/dom/swap.ts +11 -10
  45. package/src/dom/trusted.ts +4 -4
  46. package/src/eco/declaration.ts +5 -1
  47. package/src/eco/index.ts +3 -0
  48. package/src/index.ts +3 -2
  49. package/src/plugins/config.ts +1 -1
  50. package/src/plugins/public.ts +4 -0
  51. package/src/plugins/types.ts +8 -1
  52. package/src/reactivity/graph.ts +244 -41
  53. package/src/reactivity/hmr.ts +14 -3
  54. package/src/reactivity/index.ts +219 -235
  55. package/src/reactivity/resource.ts +17 -3
  56. package/src/reactivity/seed.ts +118 -16
  57. package/src/reactivity/selector.ts +85 -47
  58. package/src/reactivity/server-seed.ts +31 -23
  59. package/src/reactivity/store.ts +316 -136
  60. package/src/server/action-protect.ts +3 -0
  61. package/src/server/action-registry.ts +5 -1
  62. package/src/server/cache-invalidation.ts +4 -3
  63. package/src/server/compress.ts +52 -17
  64. package/src/server/consent.ts +5 -3
  65. package/src/server/cookies.ts +27 -8
  66. package/src/server/cors.ts +98 -0
  67. package/src/server/csp-report.ts +8 -4
  68. package/src/server/health.ts +9 -0
  69. package/src/server/http.ts +3 -1
  70. package/src/server/index.ts +25 -13
  71. package/src/server/loader.ts +1 -0
  72. package/src/server/plugin-host.ts +41 -9
  73. package/src/server/plugin-route-shadow.ts +24 -0
  74. package/src/server/rate-limit.ts +13 -3
  75. package/src/server/region.ts +19 -2
  76. package/src/server/request-handler.ts +58 -22
  77. package/src/server/request-log.ts +1 -1
  78. package/src/server/route-cache.ts +14 -2
  79. package/src/server/route-table.ts +21 -11
  80. package/src/server/router.ts +2 -1
  81. package/src/server/routing.ts +100 -42
  82. package/src/server/sanitize-html.ts +3 -1
  83. package/src/server/serve-handlers.ts +10 -4
  84. package/src/server/served-file.ts +19 -14
  85. package/src/server/shared-store.ts +10 -1
  86. package/src/server/static-dir.ts +21 -3
  87. package/src/server/webhook.ts +6 -4
  88. package/src/ssr/context.ts +149 -51
  89. package/src/ssr/index.ts +41 -46
  90. package/src/ssr/region.ts +9 -3
  91. package/src/style.ts +12 -5
  92. package/src/test/browser.ts +3 -1
  93. package/src/test/build-reuse.ts +22 -7
  94. package/src/test/index.ts +7 -3
  95. package/src/ts-plugin/diagnostics.ts +56 -18
  96. package/ts-plugin.cjs +465 -131
package/src/dom/swap.ts CHANGED
@@ -3,21 +3,22 @@
3
3
 
4
4
  import { getDocId } from './prefetch'
5
5
 
6
- // Kept apart from `dom/trusted.ts` so island pages without `<Region>` never download a shared Trusted Types chunk.
6
+ // Kept apart from `dom/trusted.ts` so island pages without `<Region>` never download a shared Trusted Types chunk, while sharing the created policy on `globalThis`.
7
7
  interface HtmlPolicy { createHTML: (html: string) => string }
8
- let htmlPolicy: HtmlPolicy | undefined
8
+ interface TrustedGlobal { __pruTT?: HtmlPolicy, trustedTypes?: { createPolicy: (name: string, rules: HtmlPolicy) => HtmlPolicy } }
9
9
 
10
10
  export function trustedHtml(html: string): string {
11
- if (htmlPolicy === undefined) {
11
+ const g = globalThis as TrustedGlobal
12
+ if (g.__pruTT === undefined) {
12
13
  const pass: HtmlPolicy = { createHTML: s => s }
13
14
  try {
14
- htmlPolicy = (globalThis as { trustedTypes?: { createPolicy: (name: string, rules: HtmlPolicy) => HtmlPolicy } }).trustedTypes?.createPolicy('prunelle', pass) ?? pass
15
+ g.__pruTT = g.trustedTypes?.createPolicy('prunelle', pass) ?? pass
15
16
  }
16
17
  catch {
17
- htmlPolicy = pass
18
+ g.__pruTT = pass
18
19
  }
19
20
  }
20
- return htmlPolicy.createHTML(html)
21
+ return g.__pruTT.createHTML(html)
21
22
  }
22
23
 
23
24
  export interface EntryScroll { y: number, k: Record<string, number> }
@@ -174,14 +175,14 @@ export function replaceKeeping(container: HTMLElement, content: DocumentFragment
174
175
  }
175
176
  }
176
177
 
177
- /** Copies attributes from `source` to `target`, removing attributes absent on `source`. */
178
- export function syncElementAttrs(target: Element, source: Element): void {
178
+ /** Copies attributes from `source` to `target`, removing attributes absent on `source`; the `keep` attribute is left as it is. */
179
+ export function syncElementAttrs(target: Element, source: Element, keep = ''): void {
179
180
  for (const attr of [...target.attributes]) {
180
- if (!source.hasAttribute(attr.name))
181
+ if (!source.hasAttribute(attr.name) && attr.name !== keep)
181
182
  target.removeAttribute(attr.name)
182
183
  }
183
184
  for (const attr of source.attributes) {
184
- if (target.getAttribute(attr.name) !== attr.value)
185
+ if (attr.name !== keep && target.getAttribute(attr.name) !== attr.value)
185
186
  target.setAttribute(attr.name, attr.value)
186
187
  }
187
188
  }
@@ -2,13 +2,12 @@
2
2
  // The policy passes the string through: what it covers is HTML the app asked for in so many words (`innerHTML={html}`, a compiled template, a region swap).
3
3
 
4
4
  interface HtmlPolicy { createHTML: (html: string) => string }
5
-
6
- let policy: HtmlPolicy | undefined
5
+ interface TrustedGlobal { __pruTT?: HtmlPolicy, trustedTypes?: { createPolicy: (name: string, rules: HtmlPolicy) => HtmlPolicy } }
7
6
 
8
7
  function createPolicy(): HtmlPolicy {
9
8
  const pass = { createHTML: (html: string) => html }
10
9
  try {
11
- return (globalThis as { trustedTypes?: { createPolicy: (name: string, rules: HtmlPolicy) => HtmlPolicy } }).trustedTypes?.createPolicy('prunelle', pass) ?? pass
10
+ return (globalThis as TrustedGlobal).trustedTypes?.createPolicy('prunelle', pass) ?? pass
12
11
  }
13
12
  catch {
14
13
  // A CSP whose `trusted-types` leaves `prunelle` out refuses the policy; without `require-trusted-types-for` the plain string still works.
@@ -18,5 +17,6 @@ function createPolicy(): HtmlPolicy {
18
17
 
19
18
  /** The HTML as a sink accepts it under Trusted Types: a `TrustedHTML` where the browser has them, the string itself elsewhere. */
20
19
  export function trustedHtml(html: string): string {
21
- return (policy ??= createPolicy()).createHTML(html)
20
+ const g = globalThis as TrustedGlobal
21
+ return (g.__pruTT ??= createPolicy()).createHTML(html)
22
22
  }
@@ -1,7 +1,7 @@
1
1
  // Drafts an editable French RGESN 2024 eco-design declaration page, shaped like the State's declaration tool, from what a build and `prunelle check` measure.
2
2
 
3
3
  import type { BundleReport } from '../build/report'
4
- import { mkdirSync, writeFileSync } from 'node:fs'
4
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
5
5
  import { dirname, join, resolve } from 'node:path'
6
6
  import { escapeAttr, escapeJsxText, formatFrenchDate, layoutRendersMain, STATEMENT_PLACEHOLDER } from '../a11y/declaration'
7
7
  import { relPosix } from '../build/files'
@@ -51,6 +51,8 @@ export interface EcoDeclarationOptions {
51
51
  date?: Date | undefined
52
52
  /** Write the page to disk (default: `true`). */
53
53
  write?: boolean | undefined
54
+ /** Overwrite a declaration already at the destination (default: refuse). */
55
+ force?: boolean | undefined
54
56
  }
55
57
 
56
58
  export interface EcoDeclarationResult {
@@ -320,6 +322,8 @@ ${criteriaSections(criteria)}
320
322
  `
321
323
 
322
324
  if (options.write !== false) {
325
+ if (existsSync(dest) && options.force !== true)
326
+ throw new Error(`prunelle: ${relativePath} already exists: pass --force to overwrite it.`)
323
327
  mkdirSync(dirname(dest), { recursive: true })
324
328
  writeFileSync(dest, content)
325
329
  }
package/src/eco/index.ts CHANGED
@@ -13,6 +13,8 @@ export interface EcoRunOptions {
13
13
  root: string
14
14
  /** Write the declaration page, at this path (`''` for `<routesDir>/ecoconception.tsx`). */
15
15
  declaration?: string | undefined
16
+ /** Overwrite a declaration already there. */
17
+ force?: boolean | undefined
16
18
  service?: string | undefined
17
19
  organization?: string | undefined
18
20
  contactEmail?: string | undefined
@@ -51,6 +53,7 @@ export async function runEco(options: EcoRunOptions): Promise<EcoRunResult> {
51
53
  outPath: options.declaration === '' ? undefined : options.declaration,
52
54
  routesDir: facts.routesDir,
53
55
  facts,
56
+ force: options.force,
54
57
  service: options.service,
55
58
  organization: options.organization,
56
59
  contactEmail: options.contactEmail,
package/src/index.ts CHANGED
@@ -8,15 +8,16 @@ export {
8
8
  onCleanup,
9
9
  onMount,
10
10
  root,
11
+ runWithOwner,
11
12
  signal,
12
13
  untrack,
13
14
  } from './reactivity/index'
14
- export type { Owner, ReadonlySignal, Signal } from './reactivity/index'
15
+ export type { Owner, ReadonlySignal, Signal, SignalOptions } from './reactivity/index'
15
16
  export { resource } from './reactivity/resource'
16
17
  export type { Resource, ResourceOptions, ResourceRun } from './reactivity/resource'
17
18
  export { selector } from './reactivity/selector'
18
19
  export type { Selector } from './reactivity/selector'
19
- export { snapshot, store } from './reactivity/store'
20
+ export { reconcile, snapshot, store } from './reactivity/store'
20
21
  export { animate } from './animate'
21
22
  export type { AnimateEffect, AnimateOptions } from './animate'
22
23
  export { useAction } from './dom/action'
@@ -7,7 +7,7 @@ export function defineConfig(config: PrunelleConfig): PrunelleConfig {
7
7
  }
8
8
 
9
9
  // Typed as records so that a key added to the config types without being listed here fails the typecheck.
10
- const RUNTIME_KEYS: Record<keyof ServerRuntimeConfig, true> = { site: true, lang: true, assetPrefix: true, security: true, trustedOrigins: true, trustProxy: true, maxRequestBodySize: true, navigation: true, streamTimeout: true, consent: true, compress: true, routeCache: true, store: true, healthCheck: true, onError: true, log: true, plugins: true }
10
+ const RUNTIME_KEYS: Record<keyof ServerRuntimeConfig, true> = { site: true, lang: true, assetPrefix: true, security: true, trustedOrigins: true, cors: true, trustProxy: true, maxRequestBodySize: true, navigation: true, streamTimeout: true, consent: true, compress: true, routeCache: true, store: true, healthCheck: true, onError: true, log: true, plugins: true }
11
11
  const BUILD_KEYS: Record<Exclude<keyof PrunelleConfig, keyof ServerRuntimeConfig>, true> = { port: true, routesDir: true, outDir: true, publicDir: true, compliance: true, autoPrerender: true, budget: true }
12
12
  const BUILD_KEY_SET = new Set<string>(Object.keys(BUILD_KEYS))
13
13
  const RUNTIME_CONFIG_KEYS = Object.keys(RUNTIME_KEYS) as (keyof ServerRuntimeConfig)[]
@@ -1,5 +1,9 @@
1
1
  // `prunelle/config`: what `prunelle.config.ts` and plugin packages use.
2
2
 
3
+ // Declared here, the file `prunelle/config` resolves to: an augmentation reaches an interface only where it is declared, not through a re-export.
4
+ /** The warning rules plugins report from `check(ctx)`, each a key `compliance.ignore` accepts; a plugin adds its own with `declare module 'prunelle/config' { interface PrunellePluginRules { 'pwa/manifest-missing': true } }`. */
5
+ export interface PrunellePluginRules {}
6
+
3
7
  export { auditAccessibility, draftAccessibilityStatement, formatA11yReport, rgaaCriteriaForAxeRule } from '../a11y/index'
4
8
  export type { A11yAuditOptions, A11yAuditReport, A11yImpact, A11yRouteReport, A11yViolation, A11yViolationNode, AccessibilityDeclarationOptions, AccessibilityDeclarationResult, ComplianceStatus, RgaaCriterion } from '../a11y/index'
5
9
  export { isInside } from '../build/is-inside'
@@ -4,6 +4,7 @@ import type { BunPlugin } from 'bun'
4
4
  import type { RouteManifestEntry } from '../build/index'
5
5
  import type { ComplianceConfig } from '../compiler/compliance'
6
6
  import type { ConsentConfig } from '../server/consent'
7
+ import type { CorsConfig } from '../server/cors'
7
8
  import type { HealthCheckConfig, HealthCheckFn, HealthCheckResult, RequestPhaseName } from '../server/health'
8
9
  import type { Middleware, RequestContext } from '../server/index'
9
10
  import type { RateLimit, RateLimiter } from '../server/rate-limit'
@@ -134,6 +135,8 @@ export interface MiddlewareOptions {
134
135
  * A path prefix runs on the pathnames under it.
135
136
  */
136
137
  scope?: 'all' | 'rendered' | 'dynamic' | string | undefined
138
+ /** When `scope` is a path, match only that exact path rather than its subpaths (e.g. `{ scope: '/', exact: true }`). */
139
+ exact?: boolean | undefined
137
140
  }
138
141
 
139
142
  /** What an action or an API route takes: no schema, a schema with its JSON Schema, or a schema whose library gives none (`vendor` names it). */
@@ -173,7 +176,7 @@ export interface ServerPluginAPI {
173
176
  readonly dev: boolean
174
177
  /** True when `prunelle dev --host` binds an address other machines reach (`0.0.0.0`, a LAN address): a dev-only route that writes or reveals data then needs a guard. */
175
178
  readonly devExposed: boolean
176
- /** Readonly server security configuration so plugins inherit `trustProxy` / `trustedOrigins` without overriding them. */
179
+ /** Readonly server security configuration so plugins inherit `trustProxy` / `trustedOrigins` without overriding them; `trustedOrigins` also holds the origins `cors` lists. */
177
180
  readonly trustProxy: TrustProxy
178
181
  readonly trustedOrigins: readonly string[]
179
182
  /** Readonly runtime config forwarded from `prunelle.config.ts` (minus build-only keys). */
@@ -221,6 +224,8 @@ export interface RequestRecord {
221
224
  duration: number
222
225
  /** The phases the request went through, in the order they began: none for a file or a prerendered page. */
223
226
  phases: readonly RequestPhase[]
227
+ /** The route template that answered (`/reset/:token`), a page's or a plugin's: none for a file, a prerendered page or no match. */
228
+ route?: string | undefined
224
229
  }
225
230
 
226
231
  export interface LogConfig {
@@ -347,6 +352,8 @@ export interface ServerRuntimeConfig {
347
352
  assetPrefix?: string | undefined
348
353
  security?: SecurityHeadersOptions | false | undefined
349
354
  trustedOrigins?: string[] | undefined
355
+ /** The origins whose scripts may call this app, answered with CORS headers and their preflight; unset, no other origin may. */
356
+ cors?: CorsConfig | undefined
350
357
  trustProxy?: boolean | number | undefined
351
358
  maxRequestBodySize?: number | undefined
352
359
  /** How plain page changes feel without client JS: view transitions between pages, Speculation Rules prefetch on hover, opt-in prerender. */
@@ -1,9 +1,16 @@
1
1
  // Internal dependency-graph links, flags, and ownership list primitives for the reactive kernel.
2
2
 
3
3
  const enum F {
4
+ CLEAN = 0,
5
+ CHECK = 1,
6
+ DIRTY = 2,
7
+ RUNNING = 4,
4
8
  DISPOSED = 8,
5
9
  COMPUTED = 16,
10
+ EFFECT = 32,
11
+ QUEUED = 64,
6
12
  UNOBSERVED = 128,
13
+ PENDING = 256,
7
14
  }
8
15
 
9
16
  export interface Link {
@@ -42,6 +49,133 @@ export interface SubNode extends Owned {
42
49
  r(): void // run
43
50
  }
44
51
 
52
+ interface ComputedLike extends DepNode, SubNode {
53
+ w: number
54
+ pw: number
55
+ }
56
+
57
+ // Signal writes so far: an unobserved computed that checked at the same count can skip its version walk.
58
+ let writes = 0
59
+ export const writeCount = (): number => writes
60
+ export const bumpWrites = (): void => { writes++ }
61
+
62
+ const propStack: DepNode[] = []
63
+ const srStack: (SubNode | Link)[] = []
64
+
65
+ export function propagate(dep: DepNode, flag: number, q: SubNode[], propWave: number): void {
66
+ let cur: DepNode | undefined = dep
67
+ let fFlag = flag
68
+ while (cur) {
69
+ for (let l = cur.s; l; l = l.ns) {
70
+ const sub = l.s
71
+ const f = sub.f
72
+ if (f & F.DISPOSED)
73
+ continue
74
+ const prev = f & (F.DIRTY | F.CHECK)
75
+ if (prev < fFlag)
76
+ sub.f = (f & ~(F.DIRTY | F.CHECK)) | fFlag
77
+ if (f & F.EFFECT) {
78
+ if (!(f & F.QUEUED)) {
79
+ sub.f |= F.QUEUED
80
+ q.push(sub)
81
+ }
82
+ }
83
+ else if (f & F.COMPUTED) {
84
+ const comp = sub as unknown as ComputedLike
85
+ if (prev === F.CLEAN || comp.pw !== propWave) {
86
+ comp.pw = propWave
87
+ if (comp.s)
88
+ propStack.push(comp)
89
+ }
90
+ }
91
+ }
92
+ cur = propStack.pop()
93
+ fFlag = F.CHECK
94
+ }
95
+ }
96
+
97
+ export function shouldRun(sub: SubNode): boolean {
98
+ const f0 = sub.f
99
+ if (f0 & F.DISPOSED)
100
+ return false
101
+ if (f0 & F.DIRTY)
102
+ return true
103
+ if (!(f0 & F.CHECK) && (!(f0 & F.UNOBSERVED) || (sub as unknown as ComputedLike).w === writes))
104
+ return false
105
+
106
+ const base = srStack.length
107
+ const w = writes
108
+ let cur: SubNode = sub
109
+ let l: Link | undefined = sub.d
110
+
111
+ try {
112
+ while (true) {
113
+ let dirty = false
114
+ while (l) {
115
+ const dep = l.d
116
+ if (dep.f & F.COMPUTED) {
117
+ const comp = dep as unknown as ComputedLike
118
+ const cf = comp.f
119
+ if (!(cf & F.DISPOSED)) {
120
+ if (cf & F.DIRTY) {
121
+ comp.r()
122
+ if (cur.f & F.DISPOSED)
123
+ break
124
+ }
125
+ else if ((cf & F.CHECK) || ((cf & F.UNOBSERVED) && comp.w !== writes)) {
126
+ srStack.push(cur, l)
127
+ cur = comp
128
+ l = comp.d
129
+ continue
130
+ }
131
+ }
132
+ }
133
+ if (dep.v !== l.v) {
134
+ dirty = true
135
+ break
136
+ }
137
+ l = l.nd
138
+ }
139
+
140
+ while (true) {
141
+ if (cur.f & F.DISPOSED) {
142
+ dirty = false
143
+ }
144
+ else if (dirty) {
145
+ cur.f |= F.DIRTY
146
+ }
147
+ else {
148
+ cur.f &= ~F.CHECK
149
+ if (cur.f & F.UNOBSERVED)
150
+ (cur as unknown as ComputedLike).w = w
151
+ }
152
+ if (srStack.length === base)
153
+ return dirty
154
+
155
+ const child = cur as unknown as ComputedLike
156
+ if (dirty)
157
+ child.r()
158
+
159
+ l = srStack.pop() as Link
160
+ cur = srStack.pop() as SubNode
161
+ if (cur.f & F.DISPOSED) {
162
+ dirty = false
163
+ continue
164
+ }
165
+ if (child.v !== l.v) {
166
+ dirty = true
167
+ continue
168
+ }
169
+ l = l.nd
170
+ break
171
+ }
172
+ }
173
+ }
174
+ finally {
175
+ srStack.length = base
176
+ }
177
+ }
178
+
45
179
  export interface IdScope {
46
180
  p: string
47
181
  n: number
@@ -93,17 +227,7 @@ export function linkSub(dep: DepNode, sub: SubNode): void {
93
227
  return
94
228
  }
95
229
 
96
- const link: Link = {
97
- d: dep,
98
- s: sub,
99
- v: dep.v,
100
- e,
101
- pd: undefined,
102
- nd: undefined,
103
- ps: undefined,
104
- ns: undefined,
105
- }
106
-
230
+ const link: Link = { d: dep, s: sub, v: dep.v, e, pd: undefined, nd: undefined, ps: undefined, ns: undefined }
107
231
  if (!(sub.f & F.UNOBSERVED))
108
232
  addSub(link)
109
233
 
@@ -130,21 +254,27 @@ export function linkSub(dep: DepNode, sub: SubNode): void {
130
254
 
131
255
  // Puts a link at the end of its source's subscriber list; a computed gaining its first subscriber follows its own sources again.
132
256
  export function addSub(link: Link): void {
133
- const dep = link.d
134
- const tail = dep.st
135
- link.ps = tail
136
- link.ns = undefined
137
- if (tail) {
138
- tail.ns = link
139
- dep.st = link
140
- return
141
- }
142
- dep.s = dep.st = link
143
- if (dep.f & F.UNOBSERVED) {
144
- const comp = dep as unknown as SubNode
145
- comp.f &= ~F.UNOBSERVED
146
- for (let l = comp.d; l; l = l.nd)
147
- addSub(l)
257
+ let cur: Link | undefined = link
258
+ let stack: Link[] | undefined
259
+ while (cur) {
260
+ const dep = cur.d
261
+ const tail = dep.st
262
+ cur.ps = tail
263
+ cur.ns = undefined
264
+ if (tail) {
265
+ tail.ns = cur
266
+ dep.st = cur
267
+ }
268
+ else {
269
+ dep.s = dep.st = cur
270
+ if (dep.f & F.UNOBSERVED) {
271
+ const comp = dep as unknown as SubNode
272
+ comp.f &= ~F.UNOBSERVED
273
+ for (let l = comp.d; l; l = l.nd)
274
+ (stack ??= []).push(l)
275
+ }
276
+ }
277
+ cur = stack?.pop()
148
278
  }
149
279
  }
150
280
 
@@ -156,21 +286,31 @@ export function unobserve(comp: SubNode): void {
156
286
 
157
287
  // Takes a link out of its source's subscriber list; a computed losing its last subscriber lets go of its own sources.
158
288
  export function removeSub(link: Link): void {
159
- const { d, ps, ns } = link
160
- if (ps)
161
- ps.ns = ns
162
- else
163
- d.s = ns
164
- if (ns)
165
- ns.ps = ps
166
- else
167
- d.st = ps
168
- link.ps = link.ns = undefined
169
- if (!d.s) {
170
- if ((d.f & (F.COMPUTED | F.UNOBSERVED)) === F.COMPUTED)
171
- unobserve(d as unknown as SubNode)
172
- else if (d.u)
173
- d.u()
289
+ let cur: Link | undefined = link
290
+ let stack: Link[] | undefined
291
+ while (cur) {
292
+ const { d, ps, ns } = cur
293
+ if (ps)
294
+ ps.ns = ns
295
+ else
296
+ d.s = ns
297
+ if (ns)
298
+ ns.ps = ps
299
+ else
300
+ d.st = ps
301
+ cur.ps = cur.ns = undefined
302
+ if (!d.s) {
303
+ if ((d.f & (F.COMPUTED | F.UNOBSERVED)) === F.COMPUTED) {
304
+ const comp = d as unknown as SubNode
305
+ comp.f |= F.UNOBSERVED
306
+ for (let l = comp.d; l; l = l.nd)
307
+ (stack ??= []).push(l)
308
+ }
309
+ else if (d.u) {
310
+ d.u()
311
+ }
312
+ }
313
+ cur = stack?.pop()
174
314
  }
175
315
  }
176
316
 
@@ -257,3 +397,66 @@ export function throwErrors(errors: unknown[] | undefined): void {
257
397
  throw errors[0]
258
398
  throw new AggregateError(errors, `prunelle: ${errors.length} errors`)
259
399
  }
400
+
401
+ function detach(node: Owned, f: number): void {
402
+ node.f = f | F.DISPOSED
403
+ if (f & (F.COMPUTED | F.EFFECT))
404
+ unlinkAll(node as unknown as SubNode)
405
+ if (f & F.COMPUTED)
406
+ unlinkSubs(node as unknown as DepNode)
407
+ }
408
+
409
+ // Disposes an owner, an effect or a computed: leaves its owner, drops its sources, releases what it owns, runs its cleanup.
410
+ export function disposeOwner(node: Owner): void {
411
+ const f = node.f
412
+ if (f & F.DISPOSED)
413
+ return
414
+ unadopt(node)
415
+ detach(node, f)
416
+ if (!(f & F.COMPUTED))
417
+ releaseOwned(node)
418
+ }
419
+
420
+ // Pops the head each time, so a cleanup that disposes a sibling cannot cut the walk short; every child and cleanup runs even if one throws.
421
+ export function releaseOwned(owner: Owner): void {
422
+ if (!owner.fs && !owner.cl)
423
+ return
424
+ let errors: unknown[] | undefined
425
+ let stack: Owner[] | undefined
426
+ let cur: Owner = owner
427
+ while (true) {
428
+ const child = cur.fs
429
+ if (child) {
430
+ unadopt(child)
431
+ const f = child.f
432
+ if (f & F.DISPOSED)
433
+ continue
434
+ detach(child, f)
435
+ if (!(f & F.COMPUTED)) {
436
+ const co = child as Owner
437
+ if (co.fs || co.cl) {
438
+ ;(stack ??= []).push(cur)
439
+ cur = co
440
+ }
441
+ }
442
+ continue
443
+ }
444
+ const fns = cur.cl
445
+ if (fns) {
446
+ cur.cl = undefined
447
+ for (let i = fns.length - 1; i >= 0; i--) {
448
+ try {
449
+ fns[i]!()
450
+ }
451
+ catch (err) {
452
+ ;(errors ??= []).push(err)
453
+ }
454
+ }
455
+ }
456
+ if (!stack || stack.length === 0)
457
+ break
458
+ cur = stack.pop()!
459
+ }
460
+
461
+ throwErrors(errors)
462
+ }
@@ -2,13 +2,15 @@
2
2
 
3
3
  import type { Signal } from './graph'
4
4
 
5
- /** A signal an island made while it rendered, and what its declaration was. */
6
- export interface HmrSignal { k: string, s: Signal<unknown> }
5
+ /** A signal or store an island made while it rendered, and what its declaration was. */
6
+ export interface HmrSignal { k: string, s?: Signal<unknown>, st?: () => unknown }
7
7
 
8
8
  /** What the reactivity and DOM runtimes call, once an island chunk has put it on the page. */
9
9
  export interface HmrHooks {
10
10
  /** Lists a signal made now, and gives it the value the previous render's signal in the same place ended with, when both were declared alike. */
11
11
  note: (s: Signal<unknown>) => void
12
+ /** Lists a store made now, and reconciles it with the previous render's store snapshot when both were declared alike. */
13
+ noteStore?: <T extends object>(s: T, snap: (v: T) => T, apply: (target: T, next: T) => T) => void
12
14
  /** `render`, listing the signals made while it runs (the ones made later, from an effect or a handler, are not listed). */
13
15
  wrap: <T>(render: () => T) => () => T
14
16
  /** Ties the signals the render that just ran made to the function that disposes it, so the next render can start from them. */
@@ -48,10 +50,19 @@ export const hooks: HmrHooks = {
48
50
  return
49
51
  const k = declarationOf(s.peek())
50
52
  const before = recording.prev?.[recording.made.length]
51
- if (before !== undefined && before.k === k)
53
+ if (before !== undefined && before.k === k && before.s !== undefined)
52
54
  (s as unknown as { _v: unknown })._v = before.s.peek()
53
55
  recording.made.push({ k, s })
54
56
  },
57
+ noteStore(s, snap, apply) {
58
+ if (recording === undefined)
59
+ return
60
+ const k = `store:${declarationOf(snap(s))}`
61
+ const before = recording.prev?.[recording.made.length]
62
+ if (before !== undefined && before.k === k && before.st !== undefined)
63
+ apply(s, before.st() as typeof s)
64
+ recording.made.push({ k, st: () => snap(s) })
65
+ },
55
66
  wrap(render) {
56
67
  return () => {
57
68
  const outer = recording