prunelle 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,397 @@
1
+ // Shared compiler helpers & JSX child/hydration IR classification used by both `ssr.ts` and `dom.ts`.
2
+
3
+ import type {
4
+ BlockStatement,
5
+ JSXChild,
6
+ JSXElement,
7
+ JSXElementName,
8
+ JSXFragment,
9
+ JSXNamespacedName,
10
+ Node,
11
+ Program,
12
+ } from 'oxc-parser'
13
+ import { walk } from './ast'
14
+
15
+ export { DOM_PROPS, isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
16
+
17
+ export const VOID_ELEMENTS = new Set([
18
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
19
+ 'link', 'meta', 'param', 'source', 'track', 'wbr',
20
+ ])
21
+
22
+ export const RAW_TEXT_ELEMENTS = new Set(['style', 'script'])
23
+ export const EVENT_ATTR = /^on([A-Z]\w*)$/
24
+
25
+ const CLOSE_STYLE_RE = /<\/(style)/gi
26
+ const SCRIPT_UNSAFE_RE = /<(\/script|script|!--)/gi
27
+ const LINE_BREAK_RE = /\r\n|\n|\r/
28
+
29
+ export function escapeRawText(str: string, tag: 'style' | 'script'): string {
30
+ if (tag === 'script') {
31
+ return str.replace(SCRIPT_UNSAFE_RE, (_, body: string) =>
32
+ body.charCodeAt(0) === 47 ? `<\\${body}` : `\\u003c${body}`)
33
+ }
34
+ return str.replace(CLOSE_STYLE_RE, '<\\/$1')
35
+ }
36
+
37
+ export function escapeStaticText(str: string): string {
38
+ return str.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
39
+ }
40
+
41
+ export function escapeStaticAttr(str: string): string {
42
+ return escapeStaticText(str).replaceAll('"', '&quot;')
43
+ }
44
+
45
+ const HTML_ENTITIES: Record<string, string> = {
46
+ // Core XML/HTML & whitespace
47
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: '\'', nbsp: '\u00A0',
48
+ ensp: '\u2002', emsp: '\u2003', thinsp: '\u2009', zwnj: '\u200C', zwj: '\u200D', lrm: '\u200E', rlm: '\u200F', shy: '\u00AD',
49
+ // Punctuation & symbols
50
+ ndash: '\u2013', mdash: '\u2014', lsquo: '\u2018', rsquo: '\u2019', sbquo: '\u201A',
51
+ ldquo: '\u201C', rdquo: '\u201D', bdquo: '\u201E', hellip: '\u2026', bull: '\u2022',
52
+ middot: '\u00B7', laquo: '\u00AB', raquo: '\u00BB', lsaquo: '\u2039', rsaquo: '\u203A',
53
+ prime: '\u2032', Prime: '\u2033', sect: '\u00A7', para: '\u00B6', dagger: '\u2020', Dagger: '\u2021', permil: '\u2030',
54
+ iexcl: '\u00A1', iquest: '\u00BF', brvbar: '\u00A6', macr: '\u00AF', acute: '\u00B4', cedil: '\u00B8', uml: '\u00A8',
55
+ ordf: '\u00AA', ordm: '\u00BA', not: '\u00AC', loz: '\u25CA',
56
+ // Suits, stars & checkmarks
57
+ spades: '\u2660', clubs: '\u2663', hearts: '\u2665', diams: '\u2666',
58
+ star: '\u2606', check: '\u2713', checkmark: '\u2713', cross: '\u2717',
59
+ // Currency & legal
60
+ copy: '\u00A9', reg: '\u00AE', trade: '\u2122', euro: '\u20AC', pound: '\u00A3', yen: '\u00A5', cent: '\u00A2', curren: '\u00A4',
61
+ // Math & arrows
62
+ deg: '\u00B0', plusmn: '\u00B1', times: '\u00D7', divide: '\u00F7',
63
+ frac12: '\u00BD', frac14: '\u00BC', frac34: '\u00BE', sup1: '\u00B9', sup2: '\u00B2', sup3: '\u00B3',
64
+ micro: '\u00B5', minus: '\u2212', ne: '\u2260', le: '\u2264', ge: '\u2265', approx: '\u2248', infin: '\u221E',
65
+ sum: '\u2211', prod: '\u220F', radic: '\u221A', int: '\u222B', part: '\u2202', empty: '\u2205', nabla: '\u2207',
66
+ isin: '\u2208', notin: '\u2209', ni: '\u220B', cap: '\u2229', cup: '\u222A', sub: '\u2282', sup: '\u2283',
67
+ nsub: '\u2284', sube: '\u2286', supe: '\u2287', oplus: '\u2295', otimes: '\u2297', perp: '\u22A5', sdot: '\u22C5',
68
+ equiv: '\u2261', cong: '\u2245', asymp: '\u2248', prop: '\u221D', and: '\u2227', or: '\u2228', forall: '\u2200', exist: '\u2203',
69
+ larr: '\u2190', uarr: '\u2191', rarr: '\u2192', darr: '\u2193', harr: '\u2194', crarr: '\u21B5',
70
+ lArr: '\u21D0', uArr: '\u21D1', rArr: '\u21D2', dArr: '\u21D3', hArr: '\u21D4',
71
+ // Greek
72
+ Alpha: '\u0391', Beta: '\u0392', Gamma: '\u0393', Delta: '\u0394', Epsilon: '\u0395', Zeta: '\u0396', Eta: '\u0397', Theta: '\u0398',
73
+ Iota: '\u0399', Kappa: '\u039A', Lambda: '\u039B', Mu: '\u039C', Nu: '\u039D', Xi: '\u039E', Omicron: '\u039F', Pi: '\u03A0',
74
+ Rho: '\u03A1', Sigma: '\u03A3', Tau: '\u03A4', Upsilon: '\u03A5', Phi: '\u03A6', Chi: '\u03A7', Psi: '\u03A8', Omega: '\u03A9',
75
+ alpha: '\u03B1', beta: '\u03B2', gamma: '\u03B3', delta: '\u03B4', epsilon: '\u03B5', zeta: '\u03B6', eta: '\u03B7', theta: '\u03B8',
76
+ iota: '\u03B9', kappa: '\u03BA', lambda: '\u03BB', mu: '\u03BC', nu: '\u03BD', xi: '\u03BE', omicron: '\u03BF', pi: '\u03C0',
77
+ rho: '\u03C1', sigmaf: '\u03C2', sigma: '\u03C3', tau: '\u03C4', upsilon: '\u03C5', phi: '\u03C6', chi: '\u03C7', psi: '\u03C8', omega: '\u03C9',
78
+ // Latin-1 & European accents
79
+ Agrave: '\u00C0', Aacute: '\u00C1', Acirc: '\u00C2', Atilde: '\u00C3', Auml: '\u00C4', Aring: '\u00C5', AElig: '\u00C6', Ccedil: '\u00C7',
80
+ Egrave: '\u00C8', Eacute: '\u00C9', Ecirc: '\u00CA', Euml: '\u00CB', Igrave: '\u00CC', Iacute: '\u00CD', Icirc: '\u00CE', Iuml: '\u00CF',
81
+ ETH: '\u00D0', Ntilde: '\u00D1', Ograve: '\u00D2', Oacute: '\u00D3', Ocirc: '\u00D4', Otilde: '\u00D5', Ouml: '\u00D6', Oslash: '\u00D8',
82
+ Ugrave: '\u00D9', Uacute: '\u00DA', Ucirc: '\u00DB', Uuml: '\u00DC', Yacute: '\u00DD', THORN: '\u00DE', szlig: '\u00DF',
83
+ agrave: '\u00E0', aacute: '\u00E1', acirc: '\u00E2', atilde: '\u00E3', auml: '\u00E4', aring: '\u00E5', aelig: '\u00E6', ccedil: '\u00E7',
84
+ egrave: '\u00E8', eacute: '\u00E9', ecirc: '\u00EA', euml: '\u00EB', igrave: '\u00EC', iacute: '\u00ED', icirc: '\u00EE', iuml: '\u00EF',
85
+ eth: '\u00F0', ntilde: '\u00F1', ograve: '\u00F2', oacute: '\u00F3', ocirc: '\u00F4', otilde: '\u00F5', ouml: '\u00F6', oslash: '\u00F8',
86
+ ugrave: '\u00F9', uacute: '\u00FA', ucirc: '\u00FB', uuml: '\u00FC', yacute: '\u00FD', thorn: '\u00FE', yuml: '\u00FF',
87
+ OElig: '\u0152', oelig: '\u0153', Scaron: '\u0160', scaron: '\u0161', Yuml: '\u0178',
88
+ }
89
+
90
+ const ENTITY_RE = /&(?:#(\d+)|#x([0-9a-fA-F]+)|([A-Za-z][A-Za-z0-9]*));/g
91
+
92
+ export function decodeHtmlEntities(str: string): string {
93
+ if (!str.includes('&'))
94
+ return str
95
+ return str.replace(ENTITY_RE, (match, dec: string | undefined, hex: string | undefined, named: string | undefined) => {
96
+ if (dec !== undefined) {
97
+ const cp = Number.parseInt(dec, 10)
98
+ return cp === 0 || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF) ? '\uFFFD' : String.fromCodePoint(cp)
99
+ }
100
+ if (hex !== undefined) {
101
+ const cp = Number.parseInt(hex, 16)
102
+ return cp === 0 || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF) ? '\uFFFD' : String.fromCodePoint(cp)
103
+ }
104
+ if (named !== undefined && Object.hasOwn(HTML_ENTITIES, named))
105
+ return HTML_ENTITIES[named]!
106
+ return match
107
+ })
108
+ }
109
+
110
+ const LINE_STARTS_CACHE_LIMIT = 64
111
+ const lineStartsCache = new Map<string, number[]>()
112
+
113
+ /** Returns sorted 0-based byte offsets where each line begins in `code`, cached in a bounded LRU map. */
114
+ export function getLineStarts(code: string): readonly number[] {
115
+ const cached = lineStartsCache.get(code)
116
+ if (cached !== undefined)
117
+ return cached
118
+ const starts = [0]
119
+ let idx = code.indexOf('\n')
120
+ while (idx !== -1) {
121
+ starts.push(idx + 1)
122
+ idx = code.indexOf('\n', idx + 1)
123
+ }
124
+ if (lineStartsCache.size >= LINE_STARTS_CACHE_LIMIT) {
125
+ const oldest = lineStartsCache.keys().next().value
126
+ if (oldest !== undefined)
127
+ lineStartsCache.delete(oldest)
128
+ }
129
+ lineStartsCache.set(code, starts)
130
+ return starts
131
+ }
132
+
133
+ /** 0-based line index of `offset` in a precomputed `lineStarts` table, in O(log N). */
134
+ export function lineIndexAtOffset(starts: readonly number[], offset: number): number {
135
+ let lo = 0
136
+ let hi = starts.length - 1
137
+ while (lo < hi) {
138
+ const mid = (lo + hi + 1) >> 1
139
+ if (starts[mid]! <= offset)
140
+ lo = mid
141
+ else
142
+ hi = mid - 1
143
+ }
144
+ return lo
145
+ }
146
+
147
+ export function offsetToLineCol(code: string, offset: number): { line: number, col: number } {
148
+ const end = Math.min(Math.max(0, offset), code.length)
149
+ const starts = getLineStarts(code)
150
+ const idx = lineIndexAtOffset(starts, end)
151
+ return { line: idx + 1, col: end - starts[idx]! + 1 }
152
+ }
153
+
154
+ export function formatLoc(filename: string, code: string, offset?: number): string {
155
+ if (offset === undefined || offset < 0)
156
+ return filename
157
+ const { line, col } = offsetToLineCol(code, offset)
158
+ return `${filename}:${line}:${col}`
159
+ }
160
+
161
+ /** Renders a short source code frame around `offset` with 1 context line before/after and a caret underline. */
162
+ export function formatCodeFrame(code: string, offset: number, endOffset?: number): string {
163
+ if (code.length === 0)
164
+ return ''
165
+ const clamped = Math.min(Math.max(0, offset), code.length)
166
+ const { line, col } = offsetToLineCol(code, clamped)
167
+ const lines = code.split(/\r?\n/)
168
+ const lineIdx = Math.min(line - 1, lines.length - 1)
169
+ const startIdx = Math.max(0, lineIdx - 1)
170
+ const endIdx = Math.min(lines.length - 1, lineIdx + 1)
171
+ const gutterWidth = String(endIdx + 1).length
172
+ const pad = (n: number | '') => String(n).padStart(gutterWidth, ' ')
173
+ const targetLine = lines[lineIdx] ?? ''
174
+ const maxSpan = Math.max(1, targetLine.length - (col - 1))
175
+ const rawSpan = endOffset !== undefined && endOffset > clamped ? endOffset - clamped : 1
176
+ const caretLen = Math.max(1, Math.min(rawSpan, maxSpan))
177
+ const out: string[] = []
178
+ for (let i = startIdx; i <= endIdx; i++) {
179
+ const text = lines[i] ?? ''
180
+ out.push(` ${pad(i + 1)} | ${text}`)
181
+ if (i === lineIdx)
182
+ out.push(` ${pad('')} | ${' '.repeat(Math.max(0, col - 1))}${'^'.repeat(caretLen)}`)
183
+ }
184
+ return out.join('\n')
185
+ }
186
+
187
+ export const DIAGNOSTIC_PREFIX_RE = /^.+:\d+:\d+:\s+(?:error|warning):/
188
+
189
+ export function formatDiagnostic(loc: string, message: string, severity: 'error' | 'warning' = 'error'): string {
190
+ return `${loc}: ${severity}: ${message}`
191
+ }
192
+
193
+ export function cleanJsxText(raw: string): string {
194
+ if (!LINE_BREAK_RE.test(raw))
195
+ return raw
196
+ const lines = raw.split(LINE_BREAK_RE)
197
+ let out = ''
198
+ for (let i = 0; i < lines.length; i++) {
199
+ let line = lines[i]!.replace(/\t/g, ' ')
200
+ if (i > 0)
201
+ line = line.replace(/^ +/, '')
202
+ if (i < lines.length - 1)
203
+ line = line.replace(/ +$/, '')
204
+ if (line !== '') {
205
+ if (out !== '')
206
+ out += ' '
207
+ out += line
208
+ }
209
+ }
210
+ return out
211
+ }
212
+
213
+ export function jsxTagName(node: JSXElementName | JSXNamespacedName | { type: 'JSXIdentifier', name: string }): string {
214
+ if (node.type === 'JSXIdentifier')
215
+ return node.name
216
+ if (node.type === 'JSXMemberExpression')
217
+ return `${jsxTagName(node.object)}.${node.property.name}`
218
+ if (node.type === 'JSXNamespacedName')
219
+ return `${node.namespace.name}:${node.name.name}`
220
+ return ''
221
+ }
222
+
223
+ export function isComponentTag(tag: string): boolean {
224
+ const first = tag.charCodeAt(0)
225
+ return (first >= 65 && first <= 90) || tag.includes('.')
226
+ }
227
+
228
+ export function unwrapParens(node: Node): Node {
229
+ let cur = node
230
+ while (cur.type === 'ParenthesizedExpression')
231
+ cur = cur.expression
232
+ return cur
233
+ }
234
+
235
+ /** `fn` or `ns.fn` for a call's callee, '' for any other shape. */
236
+ export function calleeName(callee: Node): string {
237
+ if (callee.type === 'Identifier')
238
+ return callee.name
239
+ if (callee.type === 'MemberExpression' && !callee.computed && callee.object.type === 'Identifier' && callee.property.type === 'Identifier')
240
+ return `${callee.object.name}.${callee.property.name}`
241
+ return ''
242
+ }
243
+
244
+ export function unwrapTsExpr(node: Node): Node {
245
+ let cur = node
246
+ while (
247
+ cur.type === 'ParenthesizedExpression'
248
+ || cur.type === 'TSAsExpression'
249
+ || cur.type === 'TSSatisfiesExpression'
250
+ || cur.type === 'TSNonNullExpression'
251
+ || cur.type === 'TSTypeAssertion'
252
+ ) {
253
+ cur = cur.expression
254
+ }
255
+ return cur
256
+ }
257
+
258
+ export function staticLiteral(node: Node): { ok: true, value: string | number | boolean | null } | { ok: false } {
259
+ const n = unwrapParens(node)
260
+ if (n.type === 'Literal') {
261
+ const v = n.value
262
+ if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null)
263
+ return { ok: true, value: v }
264
+ }
265
+ if (n.type === 'UnaryExpression' && n.operator === '-' && n.argument.type === 'Literal' && typeof n.argument.value === 'number')
266
+ return { ok: true, value: -n.argument.value }
267
+ return { ok: false }
268
+ }
269
+
270
+ export function isJsxNode(node: Node | null | undefined): node is JSXElement | JSXFragment {
271
+ return node?.type === 'JSXElement' || node?.type === 'JSXFragment'
272
+ }
273
+
274
+ /** Whether JSX appears anywhere inside `node`, itself included. Uses O(1) lookup when precomputed `jsxNodes` is passed. */
275
+ export function containsJsx(node: Node | null | undefined, jsxNodes?: WeakSet<Node>): boolean {
276
+ if (node === null || node === undefined)
277
+ return false
278
+ if (jsxNodes !== undefined)
279
+ return jsxNodes.has(node)
280
+ let found = false
281
+ walk(node, (child) => {
282
+ if (found)
283
+ return false
284
+ if (isJsxNode(child))
285
+ found = true
286
+ return undefined
287
+ })
288
+ return found
289
+ }
290
+
291
+ /** Whether a BlockStatement directly returns JSX (ignoring nested functions). */
292
+ export function blockReturnsJsx(block: BlockStatement, jsxNodes?: WeakSet<Node>): boolean {
293
+ if (jsxNodes !== undefined && !jsxNodes.has(block))
294
+ return false
295
+ let found = false
296
+ walk(block, (child) => {
297
+ if (found)
298
+ return false
299
+ if (child !== block && (
300
+ child.type === 'ArrowFunctionExpression'
301
+ || child.type === 'FunctionExpression'
302
+ || child.type === 'FunctionDeclaration'
303
+ )) {
304
+ return false
305
+ }
306
+ if (child.type === 'ReturnStatement' && child.argument !== null && containsJsx(child.argument, jsxNodes)) {
307
+ found = true
308
+ return false
309
+ }
310
+ return undefined
311
+ })
312
+ return found
313
+ }
314
+
315
+ export function filterMeaningfulChildren(children: readonly JSXChild[]): JSXChild[] {
316
+ return children.filter((c) => {
317
+ if (c.type === 'JSXText')
318
+ return cleanJsxText(c.value) !== ''
319
+ if (c.type === 'JSXExpressionContainer' && c.expression.type === 'JSXEmptyExpression')
320
+ return false
321
+ // Empty string literal `{""}` produces zero DOM nodes on SSR and DOM alike.
322
+ if (c.type === 'JSXExpressionContainer' && c.expression.type === 'Literal' && c.expression.value === '')
323
+ return false
324
+ return true
325
+ })
326
+ }
327
+
328
+ /** Collects every identifier name bound by a destructuring/parameter pattern. */
329
+ export function collectPatternNames(pattern: Node | null | undefined, out: Set<string>): void {
330
+ if (pattern === null || pattern === undefined)
331
+ return
332
+ switch (pattern.type) {
333
+ case 'Identifier':
334
+ out.add(pattern.name)
335
+ return
336
+ case 'AssignmentPattern':
337
+ collectPatternNames(pattern.left, out)
338
+ return
339
+ case 'RestElement':
340
+ collectPatternNames(pattern.argument, out)
341
+ return
342
+ case 'TSParameterProperty':
343
+ collectPatternNames(pattern.parameter, out)
344
+ return
345
+ case 'ArrayPattern':
346
+ for (const el of pattern.elements) {
347
+ if (el !== null)
348
+ collectPatternNames(el, out)
349
+ }
350
+ return
351
+ case 'ObjectPattern':
352
+ for (const prop of pattern.properties) {
353
+ if (prop.type === 'RestElement')
354
+ collectPatternNames(prop.argument, out)
355
+ else
356
+ collectPatternNames(prop.value, out)
357
+ }
358
+ }
359
+ }
360
+
361
+ export interface PrunelleTagBinding {
362
+ source: string
363
+ specifiers: readonly { local: string, imported: string }[]
364
+ }
365
+
366
+ type PrunelleTag = 'Head' | 'Region' | 'Suspense' | 'ConsentGate' | 'ConsentBanner' | 'ConsentPreferences' | 'Catch'
367
+
368
+ const PRUNELLE_TAGS = new Set<string>(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences', 'Catch'])
369
+
370
+ /** Resolves a JSX tag (direct, aliased, or namespaced via `prunelle`) to its canonical Prunelle tag. */
371
+ export function resolvePrunelleTag(tag: string, imports: readonly PrunelleTagBinding[]): PrunelleTag | undefined {
372
+ let boundElsewhere = false
373
+ for (const imp of imports) {
374
+ const isPrunelle = imp.source === 'prunelle'
375
+ for (const spec of imp.specifiers) {
376
+ if (isPrunelle) {
377
+ if (spec.local === tag && PRUNELLE_TAGS.has(spec.imported))
378
+ return spec.imported as PrunelleTag
379
+ if (spec.imported === '*' && tag.startsWith(`${spec.local}.`)) {
380
+ const member = tag.slice(spec.local.length + 1)
381
+ if (PRUNELLE_TAGS.has(member))
382
+ return member as PrunelleTag
383
+ }
384
+ }
385
+ else if (spec.local === tag) {
386
+ boundElsewhere = true
387
+ }
388
+ }
389
+ }
390
+ if (!boundElsewhere && PRUNELLE_TAGS.has(tag))
391
+ return tag as PrunelleTag
392
+ return undefined
393
+ }
394
+
395
+ export type { ChildSlotKind, ExprContext, HydrationMarker, MapCallMatch, PlanChildSlotsOptions, PlannedChildSlot } from './slots'
396
+ export { classifyJsxChild, createExprContext, isDefinitelyPrimitive, isNodeCapableExpr, isStaticBranch, matchJsxMapCall, mayReturnNode, planChildSlots } from './slots'
397
+ export type { Program }
@@ -0,0 +1,246 @@
1
+ // Refuses a local signal() or computed() read without `.value`, in JSX or in plain code, following each name through its scopes.
2
+
3
+ import type { Node, Program } from 'oxc-parser'
4
+ import { visitorKeys } from 'oxc-parser'
5
+ import { walk } from './ast'
6
+ import { guarded, mistake } from './mistakes'
7
+ import { calleeName, EVENT_ATTR, isComponentTag, jsxTagName, unwrapTsExpr } from './shared'
8
+
9
+ // Each name a scope binds, true when it holds a signal() or computed().
10
+ type Scope = Map<string, boolean>
11
+
12
+ function bindPattern(scope: Scope, pattern: Node | null | undefined, isSignal = false): void {
13
+ if (pattern === null || pattern === undefined)
14
+ return
15
+ if (pattern.type === 'Identifier') {
16
+ scope.set(pattern.name, isSignal)
17
+ return
18
+ }
19
+ walk(pattern, (node) => {
20
+ if (node.type === 'Identifier')
21
+ scope.set(node.name, false)
22
+ // A default value or a computed key reads names, it binds none.
23
+ if (node.type === 'AssignmentPattern')
24
+ bindPattern(scope, node.left)
25
+ else if (node.type === 'Property')
26
+ bindPattern(scope, node.value)
27
+ return node.type !== 'AssignmentPattern' && node.type !== 'Property'
28
+ })
29
+ }
30
+
31
+ function bindStatements(scope: Scope, statements: readonly Node[], signalCallees: ReadonlySet<string>, importedSignals?: ReadonlySet<string>): void {
32
+ for (const stmt of statements) {
33
+ const decl = (stmt.type === 'ExportNamedDeclaration' || stmt.type === 'ExportDefaultDeclaration') ? stmt.declaration : stmt
34
+ if (decl?.type === 'VariableDeclaration') {
35
+ for (const d of decl.declarations) {
36
+ const init = d.init === null ? undefined : unwrapTsExpr(d.init)
37
+ bindPattern(scope, d.id, init?.type === 'CallExpression' && signalCallees.has(calleeName(init.callee)))
38
+ }
39
+ }
40
+ else if ((decl?.type === 'FunctionDeclaration' || decl?.type === 'ClassDeclaration') && decl.id !== null) {
41
+ scope.set(decl.id.name, false)
42
+ }
43
+ else if (decl?.type === 'ImportDeclaration') {
44
+ for (const spec of decl.specifiers)
45
+ scope.set(spec.local.name, importedSignals?.has(spec.local.name) === true)
46
+ }
47
+ }
48
+ }
49
+
50
+ // The names a node opens a scope for, or undefined when it opens none.
51
+ function scopeOf(node: Node, signalCallees: ReadonlySet<string>, importedSignals?: ReadonlySet<string>): Scope | undefined {
52
+ const scope: Scope = new Map()
53
+ switch (node.type) {
54
+ case 'Program':
55
+ bindStatements(scope, node.body, signalCallees, importedSignals)
56
+ return scope
57
+ case 'BlockStatement':
58
+ case 'StaticBlock':
59
+ bindStatements(scope, node.body, signalCallees)
60
+ return scope
61
+ case 'FunctionDeclaration':
62
+ case 'FunctionExpression':
63
+ case 'ArrowFunctionExpression':
64
+ if (node.type === 'FunctionExpression' && node.id !== null)
65
+ scope.set(node.id.name, false)
66
+ for (const param of node.params)
67
+ bindPattern(scope, param)
68
+ return scope
69
+ case 'ForStatement':
70
+ case 'ForInStatement':
71
+ case 'ForOfStatement': {
72
+ const head = node.type === 'ForStatement' ? node.init : node.left
73
+ if (head?.type === 'VariableDeclaration')
74
+ bindStatements(scope, [head], signalCallees)
75
+ return scope
76
+ }
77
+ case 'CatchClause':
78
+ bindPattern(scope, node.param)
79
+ return scope
80
+ case 'SwitchStatement':
81
+ for (const c of node.cases)
82
+ bindStatements(scope, c.consequent, signalCallees)
83
+ return scope
84
+ default:
85
+ return undefined
86
+ }
87
+ }
88
+
89
+ interface SignalLookup {
90
+ isSignal: (name: string) => boolean
91
+ isSignalMember: (obj: string, prop: string) => boolean
92
+ }
93
+
94
+ // Visits every node of the program with the signals in scope there.
95
+ function walkWithSignals(
96
+ program: Program,
97
+ signalCallees: ReadonlySet<string>,
98
+ importedSignals: ReadonlySet<string>,
99
+ importedSignalMembers: ReadonlyMap<string, ReadonlySet<string>>,
100
+ visit: (node: Node, lookup: SignalLookup) => void,
101
+ ): void {
102
+ const scopes: Scope[] = []
103
+ const lookup: SignalLookup = {
104
+ isSignal(name: string): boolean {
105
+ for (let i = scopes.length - 1; i >= 0; i--) {
106
+ const found = scopes[i]!.get(name)
107
+ if (found !== undefined)
108
+ return found
109
+ }
110
+ return false
111
+ },
112
+ isSignalMember(obj: string, prop: string): boolean {
113
+ const members = importedSignalMembers.get(obj)
114
+ if (members === undefined || !members.has(prop))
115
+ return false
116
+ // Any inner scope binding `obj` shadows the namespace import.
117
+ for (let i = scopes.length - 1; i >= 1; i--) {
118
+ if (scopes[i]!.has(obj))
119
+ return false
120
+ }
121
+ return true
122
+ },
123
+ }
124
+ const visitor = (node: Node): boolean | void => {
125
+ visit(node, lookup)
126
+ const scope = scopeOf(node, signalCallees, importedSignals)
127
+ if (scope === undefined)
128
+ return
129
+ scopes.push(scope)
130
+ for (const key of visitorKeys[node.type] ?? [])
131
+ walk((node as unknown as Record<string, unknown>)[key], visitor)
132
+ scopes.pop()
133
+ return false
134
+ }
135
+ walk(program, visitor)
136
+ }
137
+
138
+ // The signal an expression reads without `.value` where it would print or test it.
139
+ function bareSignal(expr: Node, lookup: SignalLookup): { name: string, start: number } | undefined {
140
+ const node = unwrapTsExpr(expr)
141
+ if (node.type === 'Identifier')
142
+ return lookup.isSignal(node.name) ? { name: node.name, start: node.start } : undefined
143
+ if (node.type === 'MemberExpression' && !node.computed && node.object.type === 'Identifier' && node.property.type === 'Identifier') {
144
+ if (lookup.isSignalMember(node.object.name, node.property.name))
145
+ return { name: `${node.object.name}.${node.property.name}`, start: node.start }
146
+ return undefined
147
+ }
148
+ if (node.type === 'LogicalExpression' || node.type === 'BinaryExpression')
149
+ return bareSignal(node.left, lookup) ?? bareSignal(node.right, lookup)
150
+ if (node.type === 'ConditionalExpression')
151
+ return bareSignal(node.test, lookup) ?? bareSignal(node.consequent, lookup) ?? bareSignal(node.alternate, lookup)
152
+ if (node.type === 'UnaryExpression')
153
+ return node.operator === 'typeof' || node.operator === 'void' ? undefined : bareSignal(node.argument, lookup)
154
+ if (node.type === 'TemplateLiteral') {
155
+ for (const part of node.expressions) {
156
+ const found = bareSignal(part, lookup)
157
+ if (found !== undefined)
158
+ return found
159
+ }
160
+ }
161
+ return undefined
162
+ }
163
+
164
+ // The expressions JSX prints or tests: children on elements, fragments and components, and attributes on elements other than handlers and refs.
165
+ function jsxReads(node: Node): Node[] {
166
+ if (node.type !== 'JSXElement' && node.type !== 'JSXFragment')
167
+ return []
168
+ const reads: Node[] = []
169
+ for (const child of node.children) {
170
+ if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression')
171
+ reads.push(child.expression)
172
+ }
173
+ if (node.type !== 'JSXElement' || isComponentTag(jsxTagName(node.openingElement.name)))
174
+ return reads
175
+ for (const attr of node.openingElement.attributes) {
176
+ if (attr.type !== 'JSXAttribute' || attr.name.type !== 'JSXIdentifier')
177
+ continue
178
+ const name = attr.name.name
179
+ if (name !== '' && name !== 'ref' && name !== 'key' && !EVENT_ATTR.test(name) && attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression')
180
+ reads.push(attr.value.expression)
181
+ }
182
+ return reads
183
+ }
184
+
185
+ // The expressions plain code tests or interpolates: an if/loop/ternary condition, a switch discriminant, template literal slots, and the operand of `!`.
186
+ function codeTests(node: Node): Node[] {
187
+ switch (node.type) {
188
+ case 'IfStatement':
189
+ case 'WhileStatement':
190
+ case 'DoWhileStatement':
191
+ case 'ConditionalExpression':
192
+ return [node.test]
193
+ case 'ForStatement':
194
+ return node.test === null ? [] : [node.test]
195
+ case 'SwitchStatement':
196
+ return [node.discriminant]
197
+ case 'TemplateLiteral':
198
+ return node.expressions
199
+ case 'UnaryExpression':
200
+ return node.operator === '!' ? [node.argument] : []
201
+ default:
202
+ return []
203
+ }
204
+ }
205
+
206
+ // `const { value } = count` copies a signal's value once, so the copy never updates.
207
+ function destructuredSignal(node: Node, lookup: SignalLookup): string | undefined {
208
+ if (node.type !== 'VariableDeclarator' || node.id.type !== 'ObjectPattern' || node.init === null)
209
+ return undefined
210
+ const init = unwrapTsExpr(node.init)
211
+ const name = init.type === 'Identifier' && lookup.isSignal(init.name)
212
+ ? init.name
213
+ : init.type === 'MemberExpression' && !init.computed && init.object.type === 'Identifier' && init.property.type === 'Identifier' && lookup.isSignalMember(init.object.name, init.property.name)
214
+ ? `${init.object.name}.${init.property.name}`
215
+ : undefined
216
+ if (name === undefined)
217
+ return undefined
218
+ const takesValue = node.id.properties.some(p => p.type === 'Property' && !p.computed && p.key.type === 'Identifier' && p.key.name === 'value')
219
+ return takesValue ? name : undefined
220
+ }
221
+
222
+ /** Throws when JSX or plain code prints or tests a local or imported signal/computed without `.value`, or copies its value out by destructuring. */
223
+ export function checkBareSignals(
224
+ program: Program,
225
+ signalCallees: ReadonlySet<string>,
226
+ filename: string,
227
+ importedSignals: ReadonlySet<string> = new Set(),
228
+ importedSignalMembers: ReadonlyMap<string, ReadonlySet<string>> = new Map(),
229
+ ): void {
230
+ if (signalCallees.size === 0 && importedSignals.size === 0 && importedSignalMembers.size === 0)
231
+ return
232
+ // One read sits under several checks, `{!open}` under both the JSX child and the `!`, and is reported once.
233
+ const reported = new Set<number>()
234
+ walkWithSignals(program, signalCallees, importedSignals, importedSignalMembers, (node, lookup) => {
235
+ for (const expr of [...jsxReads(node), ...codeTests(node)]) {
236
+ const found = bareSignal(expr, lookup)
237
+ if (found === undefined || reported.has(found.start))
238
+ continue
239
+ reported.add(found.start)
240
+ guarded(found.start, () => { throw mistake(`${found.name} without .value`, filename, `write ${found.name}.value`) })
241
+ }
242
+ const copied = destructuredSignal(node, lookup)
243
+ if (copied !== undefined)
244
+ guarded(node.start, () => { throw mistake(`{ value } = ${copied}`, filename, `read ${copied}.value where it is used, a copied value never updates`) })
245
+ })
246
+ }