prunelle 0.7.7 → 0.9.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 (189) hide show
  1. package/llms.txt +63 -46
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +6 -10
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +88 -134
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +15 -7
  14. package/src/build/index.ts +20 -10
  15. package/src/build/island-promote.ts +1 -1
  16. package/src/build/islands.ts +4 -1
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +19 -1
  19. package/src/build/plugin-host.ts +2 -0
  20. package/src/build/prerender.ts +2 -2
  21. package/src/build/reach.ts +14 -1
  22. package/src/build/report.ts +1 -1
  23. package/src/build/route-types.ts +16 -0
  24. package/src/build/routes.ts +24 -15
  25. package/src/build/seed-ids.ts +65 -0
  26. package/src/build/seed-writes.ts +111 -0
  27. package/src/build/static-headers.ts +2 -2
  28. package/src/build/static.ts +1 -1
  29. package/src/cli/check-cache.ts +51 -0
  30. package/src/cli/check-consent.ts +95 -0
  31. package/src/cli/check-forms.ts +2 -2
  32. package/src/cli/check-links-patterns.ts +101 -0
  33. package/src/cli/check-links.ts +16 -100
  34. package/src/cli/check-regions.ts +185 -0
  35. package/src/cli/check-security.ts +57 -6
  36. package/src/cli/check.ts +40 -17
  37. package/src/cli/commands.ts +134 -14
  38. package/src/cli/docs.ts +21 -2
  39. package/src/cli/index.ts +1 -1
  40. package/src/cli/inspect.ts +2 -0
  41. package/src/cli/mcp-tools.ts +2 -2
  42. package/src/cli/new.ts +9 -5
  43. package/src/cli/upgrade-names.ts +14 -2
  44. package/src/cli/upgrade.ts +3 -0
  45. package/src/compiler/analyze.ts +18 -4
  46. package/src/compiler/cacheability.ts +24 -2
  47. package/src/compiler/compliance-contrast.ts +284 -0
  48. package/src/compiler/compliance-empty.ts +24 -0
  49. package/src/compiler/compliance-rgaa-content.ts +95 -0
  50. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  51. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  52. package/src/compiler/compliance-rgaa.ts +19 -0
  53. package/src/compiler/compliance-third-party.ts +59 -0
  54. package/src/compiler/compliance-urls.ts +52 -0
  55. package/src/compiler/compliance.ts +72 -42
  56. package/src/compiler/cookie-inventory.ts +119 -0
  57. package/src/compiler/dom-attrs.ts +4 -1
  58. package/src/compiler/emit.ts +1 -1
  59. package/src/compiler/foreign-imports.ts +5 -3
  60. package/src/compiler/mistakes.ts +18 -9
  61. package/src/compiler/props-pattern.ts +211 -0
  62. package/src/compiler/props.ts +177 -346
  63. package/src/compiler/shared.ts +9 -16
  64. package/src/compiler/ssr-emit.ts +510 -0
  65. package/src/compiler/ssr-helpers.ts +170 -121
  66. package/src/compiler/ssr.ts +25 -440
  67. package/src/context.ts +14 -1
  68. package/src/dev/child.ts +1 -1
  69. package/src/dev/hot-islands.ts +71 -0
  70. package/src/dev/index.ts +31 -18
  71. package/src/dev/protocol.ts +1 -1
  72. package/src/dev/queue.ts +3 -2
  73. package/src/dev/reload.ts +1 -1
  74. package/src/dev/supervisor.ts +3 -1
  75. package/src/dev/watchers.ts +6 -2
  76. package/src/dom/action.ts +97 -14
  77. package/src/dom/attrs.ts +8 -0
  78. package/src/dom/extras.ts +2 -1
  79. package/src/dom/field-marks.ts +24 -0
  80. package/src/dom/hot.ts +9 -0
  81. package/src/dom/index.ts +25 -5
  82. package/src/dom/island-hot.ts +29 -0
  83. package/src/dom/island.ts +13 -2
  84. package/src/dom/prefetch.ts +132 -0
  85. package/src/dom/regions.ts +498 -0
  86. package/src/dom/swap.ts +245 -0
  87. package/src/dom/trusted.ts +22 -0
  88. package/src/dom/upload.ts +44 -0
  89. package/src/eco/declaration.ts +39 -40
  90. package/src/eco/index.ts +5 -5
  91. package/src/href.ts +31 -0
  92. package/src/index.ts +9 -3
  93. package/src/plugins/config.ts +1 -1
  94. package/src/plugins/context.ts +7 -1
  95. package/src/plugins/daily.ts +27 -0
  96. package/src/plugins/index.ts +3 -3
  97. package/src/plugins/order.ts +1 -1
  98. package/src/plugins/public.ts +8 -5
  99. package/src/plugins/services.ts +88 -14
  100. package/src/plugins/types.ts +121 -10
  101. package/src/reactivity/hmr.ts +90 -0
  102. package/src/reactivity/index.ts +38 -18
  103. package/src/reactivity/resource.ts +115 -0
  104. package/src/reactivity/seed.ts +39 -0
  105. package/src/reactivity/server-seed.ts +194 -0
  106. package/src/reactivity/store.ts +55 -1
  107. package/src/rgpd/draft.ts +171 -0
  108. package/src/rgpd/forms.ts +85 -0
  109. package/src/rgpd/index.ts +57 -0
  110. package/src/server/action-flash.ts +1 -0
  111. package/src/server/action-registry.ts +6 -8
  112. package/src/server/action.ts +51 -19
  113. package/src/server/app-secret.ts +22 -17
  114. package/src/server/cache-invalidation.ts +96 -0
  115. package/src/server/compress.ts +3 -1
  116. package/src/server/consent.ts +16 -2
  117. package/src/server/cookie-inventory.ts +78 -0
  118. package/src/server/cookies.ts +50 -0
  119. package/src/server/csp-report.ts +86 -0
  120. package/src/server/discard.ts +13 -0
  121. package/src/server/document.ts +7 -4
  122. package/src/server/env.ts +1 -1
  123. package/src/server/errors.ts +9 -2
  124. package/src/server/field-errors.ts +91 -0
  125. package/src/server/form-schema.ts +16 -11
  126. package/src/server/health.ts +35 -14
  127. package/src/server/http.ts +25 -10
  128. package/src/server/index.ts +102 -299
  129. package/src/server/loader.ts +1 -0
  130. package/src/server/page.ts +11 -24
  131. package/src/server/plugin-host.ts +26 -8
  132. package/src/server/public.ts +14 -3
  133. package/src/server/rate-limit.ts +39 -10
  134. package/src/server/region.ts +3 -0
  135. package/src/server/request-handler.ts +370 -0
  136. package/src/server/request-log.ts +94 -0
  137. package/src/server/route-cache.ts +41 -6
  138. package/src/server/route-input.ts +54 -0
  139. package/src/server/route-table.ts +35 -19
  140. package/src/server/routing.ts +12 -11
  141. package/src/server/sanitize-html.ts +1 -1
  142. package/src/server/security.ts +81 -20
  143. package/src/server/serve-handlers.ts +9 -5
  144. package/src/server/shared-store.ts +314 -0
  145. package/src/server/start.ts +12 -5
  146. package/src/server/static-dir.ts +14 -10
  147. package/src/server/stream.ts +2 -1
  148. package/src/server/surface.ts +39 -0
  149. package/src/server/webhook.ts +48 -0
  150. package/src/server/workers.ts +168 -0
  151. package/src/ssr/consent-banner.ts +20 -16
  152. package/src/ssr/consent-texts.ts +40 -0
  153. package/src/ssr/context.ts +26 -3
  154. package/src/ssr/cookie-table.ts +75 -0
  155. package/src/ssr/index.ts +23 -13
  156. package/src/ssr/navigation.ts +161 -14
  157. package/src/test/browser.ts +50 -22
  158. package/src/test/build-reuse.ts +70 -0
  159. package/src/test/index.ts +45 -6
  160. package/src/test/mount.ts +53 -0
  161. package/src/test/outside.ts +94 -0
  162. package/templates/_shared/AGENTS.md +1 -1
  163. package/templates/_shared/Dockerfile +22 -0
  164. package/templates/_shared/dockerignore +9 -0
  165. package/templates/_shared/gitignore +2 -0
  166. package/templates/app/.env.example +3 -1
  167. package/templates/app/compose.yaml +32 -0
  168. package/templates/app/db/migrations/001_notes.sql +7 -0
  169. package/templates/app/db/schema.ts +11 -0
  170. package/templates/app/package.json +1 -0
  171. package/templates/app/prunelle.config.ts +6 -0
  172. package/templates/app/src/actions/notes.ts +26 -0
  173. package/templates/app/src/auth.ts +4 -2
  174. package/templates/app/src/db.ts +5 -0
  175. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  176. package/templates/app/src/routes/privacy.tsx +6 -2
  177. package/templates/app/tests/app.test.ts +14 -3
  178. package/templates/plugin/AGENTS.md +11 -0
  179. package/templates/plugin/CLAUDE.md +1 -0
  180. package/templates/plugin/README.md +27 -0
  181. package/templates/plugin/gitignore +2 -0
  182. package/templates/plugin/llms.txt +19 -0
  183. package/templates/plugin/package.json +33 -0
  184. package/templates/plugin/src/index.ts +40 -0
  185. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  186. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  187. package/templates/plugin/tests/plugin.test.ts +42 -0
  188. package/templates/plugin/tsconfig.json +19 -0
  189. package/ts-plugin.cjs +3674 -2196
@@ -156,7 +156,10 @@ function emitDomExprAttr(
156
156
  }
157
157
  else if (DOM_PROPS.has(name)) {
158
158
  const targetOps = isSelect && name === 'value' ? postChildOps : ops
159
- targetOps.push(wrapDomOp(`${use('setProp')}(${elVar}, ${JSON.stringify(name)}, ${exprCode})`, isStatic, use))
159
+ // Only a <select multiple> pulls in setSelectValues, so other pages ship none of it.
160
+ const multiple = isSelect && name === 'value' && ctx.el.openingElement.attributes.some(a => a.type === 'JSXAttribute' && jsxTagName(a.name) === 'multiple')
161
+ const call = multiple ? `${use('setSelectValues')}(${elVar}, ${exprCode})` : `${use('setProp')}(${elVar}, ${JSON.stringify(name)}, ${exprCode})`
162
+ targetOps.push(wrapDomOp(call, isStatic, use))
160
163
  }
161
164
  else {
162
165
  ops.push(wrapDomOp(`${use('setAttr')}(${elVar}, ${JSON.stringify(name)}, ${exprCode})`, isStatic, use))
@@ -20,7 +20,7 @@ export const DELEGATED_EVENTS = new Set([
20
20
  ])
21
21
 
22
22
  // Helpers kept out of the dom core, which every island loads: a page pays for them only when one of its islands binds them.
23
- const ATTR_HELPERS = ['setAttr', 'setClass', 'setProp', 'setStyle']
23
+ const ATTR_HELPERS = ['setAttr', 'setClass', 'setProp', 'setSelectValues', 'setStyle']
24
24
  const CLAIM_HELPERS = ['eachStatic']
25
25
  const EXTRA_HELPERS = ['catchBoundary', 'fragInsert', 'insert', 'mergeProps', 'omit', 'propDefault', 'setInnerHtml', 'show', 'spread']
26
26
 
@@ -1,6 +1,6 @@
1
1
  // Refuses a reactive primitive imported from another framework, with the prunelle name to write instead.
2
2
 
3
- import { mistake } from './mistakes'
3
+ import { mistake, NEXT_GUIDE, withGuide } from './mistakes'
4
4
 
5
5
  const REACT: Record<string, string> = {
6
6
  useState: 'signal() from \'prunelle\' (count.value reads and writes it)',
@@ -83,6 +83,8 @@ const FOREIGN = new Map<string, Record<string, string>>([
83
83
  /** Throws on a name a React, Solid, Vue or Svelte app imports for what prunelle spells differently, naming the prunelle form. */
84
84
  export function assertNoForeignImport(source: string, imported: string, filename: string): void {
85
85
  const table = FOREIGN.get(source)
86
- if (table !== undefined && Object.hasOwn(table, imported))
87
- throw mistake(`import { ${imported} } from '${source}'`, filename, `prunelle has no ${source}; write ${table[imported]}`)
86
+ if (table !== undefined && Object.hasOwn(table, imported)) {
87
+ const fix = `prunelle has no ${source}; write ${table[imported]}`
88
+ throw mistake(`import { ${imported} } from '${source}'`, filename, source.startsWith('react') ? withGuide(fix, NEXT_GUIDE) : fix)
89
+ }
88
90
  }
@@ -66,6 +66,15 @@ export function mistake(what: string, filename: string, fix: string): PrunelleMi
66
66
  return new PrunelleMistake(`prunelle compiler: ${what} in ${filename}: ${fix}.`)
67
67
  }
68
68
 
69
+ const GUIDES = 'https://prunelle.kaynooo.fr/docs/getting-started'
70
+ // The pages mapping another framework's concepts to prunelle's, linked from each error refusing a habit that framework taught.
71
+ export const ASTRO_GUIDE = `${GUIDES}/coming-from-astro`
72
+ export const NEXT_GUIDE = `${GUIDES}/coming-from-next`
73
+
74
+ export function withGuide(fix: string, guide: string): string {
75
+ return `${fix}; see ${guide}`
76
+ }
77
+
69
78
  /** `$hydrate` where nothing can hydrate: on an element (`component` false) or on a component that is not an island. The one wording the compiler, the build and `prunelle check` share. */
70
79
  export function hydrateMistake(tag: string, filename: string, component: boolean): PrunelleMistake {
71
80
  return mistake(`$hydrate on <${tag}>`, filename, component
@@ -121,7 +130,7 @@ export function serverOnlyTagError(filename: string, { tag, island, reason, offs
121
130
 
122
131
  /** The error for an Astro `---` block opening a file, at the first dash. */
123
132
  export function frontmatterMistake(filename: string, start: number): PrunelleMistake {
124
- const err = mistake('a --- frontmatter block', filename, 'prunelle files are plain TypeScript with no --- fence; write that code above the component, or inside it, and delete both --- lines')
133
+ const err = mistake('a --- frontmatter block', filename, withGuide('prunelle files are plain TypeScript with no --- fence; write that code above the component, or inside it, and delete both --- lines', ASTRO_GUIDE))
125
134
  err.start = start
126
135
  return err
127
136
  }
@@ -242,13 +251,13 @@ function checkNamespacedAttribute(namespace: string, name: string, filename: str
242
251
  if (namespace === 'on')
243
252
  throw mistake(what, filename, `write ${eventProp(name.toLowerCase())}={...}`)
244
253
  if (namespace === 'client')
245
- throw mistake(what, filename, `write $hydrate="${CLIENT_DIRECTIVES.get(name) ?? 'load'}"`)
254
+ throw mistake(what, filename, withGuide(`write $hydrate="${CLIENT_DIRECTIVES.get(name) ?? 'load'}"`, ASTRO_GUIDE))
246
255
  if (what === 'class:list')
247
- throw mistake(what, filename, 'pass one string to class, joining the names yourself')
256
+ throw mistake(what, filename, withGuide('pass one string to class, joining the names yourself', ASTRO_GUIDE))
248
257
  if (what === 'set:html')
249
- throw mistake(what, filename, 'write innerHTML={...}')
258
+ throw mistake(what, filename, withGuide('write innerHTML={...}', ASTRO_GUIDE))
250
259
  if (what === 'set:text')
251
- throw mistake(what, filename, 'write the text as children')
260
+ throw mistake(what, filename, withGuide('write the text as children', ASTRO_GUIDE))
252
261
  if (namespace === 'use')
253
262
  throw mistake(what, filename, `call ${name} in a ref`)
254
263
  if (namespace === 'prop' || namespace === 'attr' || namespace === 'bool')
@@ -389,7 +398,7 @@ export function checkMistakes(
389
398
  const isCustomElement = tag.includes('-')
390
399
  if (tag === 'slot') {
391
400
  const named = staticAttr(element.openingElement.attributes, 'name') !== undefined
392
- guarded(element.start, () => { throw mistake('<slot>', filename, named ? 'prunelle has no slots, pass the named part as its own prop, <Card footer={<p />} />, and write {footer} where it goes' : 'prunelle has no slots, take children as a prop, function Card({ children }) { return <div>{children}</div> }, and write {children} where the content goes') })
401
+ guarded(element.start, () => { throw mistake('<slot>', filename, withGuide(named ? 'prunelle has no slots, pass the named part as its own prop, <Card footer={<p />} />, and write {footer} where it goes' : 'prunelle has no slots, take children as a prop, function Card({ children }) { return <div>{children}</div> }, and write {children} where the content goes', ASTRO_GUIDE)) })
393
402
  }
394
403
  if (canonical === 'Suspense') {
395
404
  const children = filterMeaningfulChildren(element.children).length
@@ -452,7 +461,7 @@ function checkRegionNesting(
452
461
  })
453
462
  }
454
463
 
455
- // The markup `regions()` from `@prunellejs/spa` reads: <Region name>, and data-pru-target, data-pru-append and data-pru-live on the elements that can use them.
464
+ // The markup core `<Region>` reads: <Region name>, and data-pru-target, data-pru-append and data-pru-live on the elements that can use them.
456
465
  function checkRegionMarkup(
457
466
  tag: string,
458
467
  canonical: string | undefined,
@@ -500,8 +509,8 @@ function checkKeepScroll(element: JSXElement, attributes: readonly JSXAttributeI
500
509
  }
501
510
 
502
511
  const DIRECTIVE_FIXES: Record<string, string> = {
503
- 'use client': 'delete it, prunelle makes a component an island by itself when it uses state or handlers',
504
- 'use server': 'delete it, a server function is an action() exported from its own file',
512
+ 'use client': withGuide('delete it, prunelle makes a component an island by itself when it uses state or handlers', NEXT_GUIDE),
513
+ 'use server': withGuide('delete it, a server function is an action() exported from its own file', NEXT_GUIDE),
505
514
  }
506
515
 
507
516
  /** Throws on a React or Next habit plain code carries: a 'use client' or 'use server' directive, or an effect(async ...). */
@@ -0,0 +1,211 @@
1
+ // How each name a destructuring pattern binds is read from a source expression, so a destructured prop or loop row stays reactive.
2
+
3
+ import type { Node, ObjectPattern } from 'oxc-parser'
4
+ import { walk } from './ast'
5
+ import { SourceEditor } from './patch'
6
+ import { referencesAny } from './scope'
7
+ import { collectPatternNames, containsJsx } from './shared'
8
+
9
+ export interface PatternContext {
10
+ code: string
11
+ jsxNodes: WeakSet<Node>
12
+ use: (name: string) => string
13
+ freshVar: (prefix?: string) => string
14
+ compileExpression: (node: Node, rewrites: ReadonlyMap<string, string>) => string
15
+ }
16
+
17
+ function hoistInto(ctx: PatternContext, hoisted: string[], init: string): string {
18
+ const name = ctx.freshVar('__d')
19
+ hoisted.push(`const ${name} = ${init};`)
20
+ return name
21
+ }
22
+
23
+ function isReactiveDefault(node: Node, running: ReadonlyMap<string, string>): boolean {
24
+ if (running.size > 0 && referencesAny(node, new Set(running.keys())))
25
+ return true
26
+ let readsValue = false
27
+ walk(node, (child) => {
28
+ if (readsValue)
29
+ return false
30
+ if (child.type === 'ArrowFunctionExpression' || child.type === 'FunctionExpression' || child.type === 'FunctionDeclaration')
31
+ return false
32
+ if (child.type === 'MemberExpression' && !child.computed && child.property.type === 'Identifier' && child.property.name === 'value') {
33
+ readsValue = true
34
+ return false
35
+ }
36
+ return undefined
37
+ })
38
+ return readsValue
39
+ }
40
+
41
+ // Walks a pattern, recording in `reads` how each identifier is read from `src`. With `hoisted`, defaults and computed keys become statements for the start of the body.
42
+ function createBinder(
43
+ ctx: PatternContext,
44
+ reads: Map<string, string>,
45
+ running: Map<string, string>,
46
+ hoisted: string[] | undefined,
47
+ ): (pat: Node, src: string) => void {
48
+ const { jsxNodes, use, freshVar, compileExpression } = ctx
49
+
50
+ const hoist = (init: string): string => hoistInto(ctx, hoisted!, init)
51
+
52
+ function bindDefault(pat: Extract<Node, { type: 'AssignmentPattern' }>, src: string): void {
53
+ const defExpr = compileExpression(pat.right, running)
54
+ const simpleDef = pat.right.type === 'Literal' || pat.right.type === 'Identifier'
55
+ const reactiveDef = !simpleDef && !containsJsx(pat.right, jsxNodes) && isReactiveDefault(pat.right, running)
56
+ let fallback = simpleDef ? defExpr : `(${defExpr})`
57
+ if (!simpleDef && !reactiveDef && hoisted !== undefined)
58
+ fallback = `${hoist(`${use('propDefault')}(() => (${defExpr}), ${src} === undefined)`)}()`
59
+ let nextSrc: string
60
+ if (pat.left.type !== 'Identifier' && hoisted !== undefined) {
61
+ const v = freshVar('__v')
62
+ nextSrc = `${hoist(`() => { const ${v} = ${src}; return ${v} === undefined ? ${fallback} : ${v}; }`)}()`
63
+ }
64
+ else {
65
+ nextSrc = `(${src} === undefined ? ${fallback} : ${src})`
66
+ }
67
+ bind(pat.left, nextSrc)
68
+ }
69
+
70
+ function bindObject(pat: Extract<Node, { type: 'ObjectPattern' }>, src: string): void {
71
+ const excludedKeys: string[] = []
72
+ let canOmit = hoisted !== undefined
73
+ for (const prop of pat.properties) {
74
+ if (prop.type === 'RestElement') {
75
+ if (canOmit) {
76
+ const restRead = `${use('omit')}(${src}, [${excludedKeys.join(', ')}])`
77
+ bind(prop.argument, restRead)
78
+ }
79
+ continue
80
+ }
81
+ let propSrc: string | undefined
82
+ if (!prop.computed && prop.key.type === 'Identifier') {
83
+ excludedKeys.push(JSON.stringify(prop.key.name))
84
+ propSrc = `${src}.${prop.key.name}`
85
+ }
86
+ else if (!prop.computed && prop.key.type === 'Literal' && (typeof prop.key.value === 'string' || typeof prop.key.value === 'number')) {
87
+ excludedKeys.push(JSON.stringify(String(prop.key.value)))
88
+ propSrc = `${src}[${JSON.stringify(prop.key.value)}]`
89
+ }
90
+ else if (prop.computed && hoisted !== undefined) {
91
+ const keyVar = hoist(compileExpression(prop.key, running))
92
+ excludedKeys.push(`typeof ${keyVar} === 'symbol' ? ${keyVar} : String(${keyVar})`)
93
+ propSrc = `${src}[${keyVar}]`
94
+ }
95
+ else {
96
+ canOmit = false
97
+ }
98
+ if (propSrc !== undefined)
99
+ bind(prop.value, propSrc)
100
+ }
101
+ }
102
+
103
+ function bind(pat: Node, src: string): void {
104
+ if (pat.type === 'Identifier') {
105
+ reads.set(pat.name, src)
106
+ running.set(pat.name, src)
107
+ }
108
+ else if (pat.type === 'AssignmentPattern') {
109
+ bindDefault(pat, src)
110
+ }
111
+ else if (pat.type === 'ObjectPattern') {
112
+ bindObject(pat, src)
113
+ }
114
+ else if (pat.type === 'ArrayPattern') {
115
+ for (let i = 0; i < pat.elements.length; i++) {
116
+ const el = pat.elements[i]
117
+ if (el == null)
118
+ continue
119
+ if (el.type === 'RestElement')
120
+ bind(el.argument, `Array.from(${src}).slice(${i})`)
121
+ else
122
+ bind(el, `${src}[${i}]`)
123
+ }
124
+ }
125
+ }
126
+
127
+ return bind
128
+ }
129
+
130
+ // The source of a pattern node as a getter parameter: type annotations dropped, defaults and computed keys compiled.
131
+ function compilePatternSource(ctx: PatternContext, patNode: Node, outerRewrites: ReadonlyMap<string, string>): string {
132
+ const sub = new SourceEditor(ctx.code.slice(patNode.start, patNode.end))
133
+ const base = patNode.start
134
+ const patchPattern = (p: Node | null | undefined): void => {
135
+ if (p === null || p === undefined)
136
+ return
137
+ if ('typeAnnotation' in p && p.typeAnnotation != null) {
138
+ const ann = p.typeAnnotation as Node
139
+ sub.remove(ann.start - base, ann.end - base)
140
+ }
141
+ switch (p.type) {
142
+ case 'AssignmentPattern':
143
+ patchPattern(p.left)
144
+ sub.replace(p.right.start - base, p.right.end - base, ctx.compileExpression(p.right, outerRewrites))
145
+ return
146
+ case 'RestElement':
147
+ patchPattern(p.argument)
148
+ return
149
+ case 'ArrayPattern':
150
+ for (const el of p.elements)
151
+ patchPattern(el)
152
+ return
153
+ case 'ObjectPattern':
154
+ for (const prop of p.properties) {
155
+ if (prop.type === 'RestElement') {
156
+ patchPattern(prop.argument)
157
+ }
158
+ else {
159
+ if (prop.computed)
160
+ sub.replace(prop.key.start - base, prop.key.end - base, ctx.compileExpression(prop.key, outerRewrites))
161
+ patchPattern(prop.value)
162
+ }
163
+ }
164
+ }
165
+ }
166
+ patchPattern(patNode)
167
+ return sub.toString()
168
+ }
169
+
170
+ // The pattern a read runs: only the property binding `name`, so another property's default does not run on this read.
171
+ function patternFor(ctx: PatternContext, pattern: Node, name: string, outerRewrites: ReadonlyMap<string, string>): string {
172
+ if (pattern.type === 'ObjectPattern') {
173
+ for (const prop of (pattern as ObjectPattern).properties) {
174
+ const bound = new Set<string>()
175
+ collectPatternNames(prop.type === 'RestElement' ? prop.argument : prop.value, bound)
176
+ if (prop.type === 'Property' && bound.has(name)) {
177
+ const sub = new SourceEditor(ctx.code.slice(prop.start, prop.end))
178
+ const base = prop.start
179
+ if (prop.computed)
180
+ sub.replace(prop.key.start - base, prop.key.end - base, ctx.compileExpression(prop.key, outerRewrites))
181
+ sub.replace(prop.value.start - base, prop.value.end - base, compilePatternSource(ctx, prop.value, outerRewrites))
182
+ return `{ ${sub.toString()} }`
183
+ }
184
+ }
185
+ }
186
+ return compilePatternSource(ctx, pattern, outerRewrites)
187
+ }
188
+
189
+ // How each name a destructuring pattern binds is read from `source` on every access, so reads stay reactive.
190
+ // With `hoisted`, a default (at any nesting depth) and a nested pattern's getter become statements for the start of the body (evaluated once per call/row) instead of running on every read.
191
+ export function patternReads(
192
+ ctx: PatternContext,
193
+ pattern: Node,
194
+ source: string,
195
+ outerRewrites: ReadonlyMap<string, string>,
196
+ hoisted?: string[],
197
+ ): Map<string, string> {
198
+ const reads = new Map<string, string>()
199
+ const running = new Map(outerRewrites)
200
+ createBinder(ctx, reads, running, hoisted)(pattern, source)
201
+
202
+ const names = new Set<string>()
203
+ collectPatternNames(pattern, names)
204
+ for (const name of names) {
205
+ if (reads.has(name))
206
+ continue
207
+ const getter = `(${patternFor(ctx, pattern, name, outerRewrites)}) => ${name}`
208
+ reads.set(name, hoisted === undefined ? `(${getter})(${source})` : `${hoistInto(ctx, hoisted, getter)}(${source})`)
209
+ }
210
+ return reads
211
+ }