prunelle 0.1.1 → 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 (177) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  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/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +636 -0
  36. package/src/cli/check-imports.ts +31 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +101 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -1,11 +1,13 @@
1
1
  // `prunelle upgrade`: moves an app written for kay v2 (`@kayjs/kay`) onto prunelle: its dependencies, config file, imports, the names it imports and the names the browser receives.
2
2
 
3
+ import type { Dirent } from 'node:fs'
3
4
  import { existsSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
4
- import { dirname, join } from 'node:path'
5
+ import { dirname, join, resolve } from 'node:path'
5
6
  import pkg from '../../package.json' with { type: 'json' }
6
7
  import { isNotSourceDir, relPosix } from '../build/files'
7
8
  import { resolvePrunelleSpecifier } from '../build/resolve'
8
9
  import { parseTsx } from '../compiler/analyze'
10
+ import { walk } from '../compiler/ast'
9
11
  import { renameKayNames } from './upgrade-names'
10
12
 
11
13
  export interface UpgradeResult {
@@ -17,11 +19,13 @@ export interface UpgradeResult {
17
19
 
18
20
  // The specifiers and file names every kind of file may name.
19
21
  const PATH_RULES: [RegExp, string][] = [
22
+ // A kay v2 version written beside a package, as notes do, names no prunelle release: the current one replaces it.
23
+ [/(@kayjs\/[\w-]+)@[\^~]?2\.\d+\.\d+[\w.-]*/g, `$1@^${pkg.version}`],
20
24
  [/@kayjs\/kay(?![\w-])/g, 'prunelle'],
21
25
  [/@kayjs\//g, '@prunellejs/'],
22
26
  [/\.kay-(cache|dev)\b/g, '.prunelle-$1'],
23
27
  [/\bkay\.config\b/g, 'prunelle.config'],
24
- [/\bkay v2\b/g, 'prunelle'],
28
+ [/\bkay v2\b/gi, 'prunelle'],
25
29
  ]
26
30
  // The names kay sent the browser, as app code and styles may spell them.
27
31
  const WIRE_RULES: [RegExp, string][] = [
@@ -32,24 +36,48 @@ const WIRE_RULES: [RegExp, string][] = [
32
36
  [/\bkay:(consent|navigate|region)\b/g, 'pru:$1'],
33
37
  [/\bkay_(session|consent)\b/g, 'pru_$1'],
34
38
  ]
35
- // The kay CLI run as a command; the PATH_RULES run first, so `kay.config` and `.kay-cache` are gone by then.
36
- const CLI_RULE: [RegExp, string] = [/(?<![\w.@/-])kay(?![\w.:/-])/g, 'prunelle']
39
+ // The kay CLI where a script, build, CI or agent file runs it, after a runner or before one of its commands, so a user, label or prose named kay stays (#142, #165).
40
+ const KAY_COMMAND = String.raw`(?:new|check|inspect|docs|render|mcp|dev|build|eco|a11y|start|upgrade|test|[a-z]+-[a-z-]+)(?![\w:-])`
41
+ const RUN_CLI_RULES: [RegExp, string][] = [
42
+ [/(?<=\b(?:bunx|npx|bun(?:\s+(?:x|run))?)\s+|"bunx",\s*")kay(?![\w.:/-])/g, 'prunelle'],
43
+ [new RegExp(String.raw`(?<![\w.@/-])kay(?=(?:\s+|",\s*")${KAY_COMMAND})`, 'g'), 'prunelle'],
44
+ ]
37
45
 
38
46
  const SOURCE_FILE_RE = /\.(?:tsx?|mts)$/
39
47
  const STYLE_OR_SCRIPT_RE = /\.(?:css|js|mjs)$/
48
+ const TSCONFIG_FILE_RE = /^tsconfig(?:\.[\w-]+)?\.json$/
40
49
  const CONFIG_FILE_RE = /^(?:tsconfig(?:\.[\w-]+)?\.json|bunfig\.toml|\.gitignore|\.dockerignore)$/
41
50
  const BUILD_FILE_RE = /^(?:Dockerfile(?:\.[\w-]+)?|[\w-]+\.Dockerfile|[Jj]ustfile|Makefile|(?:docker-)?compose(?:\.[\w-]+)?\.ya?ml)$/
51
+ // The agent instructions `prunelle new` writes, which name the llms.txt to read and the CLI to run (#42).
52
+ const AGENT_FILE_RE = /^(?:AGENTS|CLAUDE)\.md$/
42
53
  const CI_DIRS = ['.forgejo/workflows', '.github/workflows', '.gitea/workflows']
43
54
  const CACHE_DIRS = ['.kay-cache', '.kay-dev']
44
55
  const PRUNELLE_SOURCE_RE = /^prunelle(\/.*)?$/
56
+ const NPM_KAY_ALIAS_RE = /^npm:(@kayjs\/[\w-]+)(?:@.*)?$/
57
+ const ESCAPE_RE = /[.*+?^${}()|[\]\\]/g
58
+ const GITIGNORE_CACHE_RE = /(?:^|\/)\.prunelle-cache(?:\/|$|\s)/m
45
59
 
46
60
  const apply = (text: string, rules: readonly [RegExp, string][]): string => rules.reduce((out, [re, to]) => out.replace(re, to), text)
47
61
 
62
+ /** Why `root` is no app to upgrade: neither on kay nor prunelle, nor a workspace holding one; undefined when it is one. */
63
+ export function notAnApp(root: string): string | undefined {
64
+ if (hasKayOrPrunelle(root) || existsSync(join(root, 'kay.config.ts')) || existsSync(join(root, 'prunelle.config.ts')) || workspaceMembers(root).some(m => hasKayOrPrunelle(join(root, m))))
65
+ return undefined
66
+ const manifest = existsSync(join(root, 'package.json')) ? 'its package.json names neither @kayjs/kay nor prunelle' : 'it has no package.json'
67
+ return `${root} is not a kay v2 app: ${manifest}, and it has no kay.config.ts`
68
+ }
69
+
48
70
  /** Rewrites the app at `root` in place, and each package its bun workspace lists; installing the renamed dependencies is the caller's job. */
49
71
  export function upgradeProject(root: string): UpgradeResult {
72
+ return upgradeDir(root)
73
+ }
74
+
75
+ function upgradeDir(root: string, inheritedAliases?: ReadonlyMap<string, string>): UpgradeResult {
50
76
  const v1 = kayV1Dependency(root)
51
77
  if (v1 !== undefined)
52
78
  return { changed: [], manual: [`package.json:1: ${v1} is kay v1: prunelle upgrade moves kay v2 apps, so this one is left as it is.`] }
79
+ const aliases = kayAliases(root, inheritedAliases)
80
+ const isApp = hasKayOrPrunelle(root)
53
81
  const changed: string[] = []
54
82
  const manual: string[] = []
55
83
  const write = (file: string, before: string, after: string): void => {
@@ -63,23 +91,28 @@ export function upgradeProject(root: string): UpgradeResult {
63
91
  const text = readFileSync(join(root, file), 'utf8')
64
92
  if (file === 'package.json')
65
93
  write(file, text, upgradePackageJson(text))
94
+ else if (TSCONFIG_FILE_RE.test(file))
95
+ write(file, text, upgradeTsconfig(text, aliases))
96
+ else if (file === '.gitignore')
97
+ write(file, text, upgradeGitignore(text, isApp))
66
98
  else if (CONFIG_FILE_RE.test(file))
67
99
  write(file, text, apply(text, PATH_RULES))
68
- else if (BUILD_FILE_RE.test(file))
69
- write(file, text, apply(apply(text, PATH_RULES), [CLI_RULE]))
100
+ else if (BUILD_FILE_RE.test(file) || AGENT_FILE_RE.test(file))
101
+ write(file, text, apply(apply(text, PATH_RULES), RUN_CLI_RULES))
70
102
  }
71
103
  for (const dir of CI_DIRS) {
72
104
  if (!existsSync(join(root, dir)))
73
105
  continue
74
- for (const name of readdirSync(join(root, dir)).sort()) {
106
+ for (const name of readdirSync(join(root, dir), { withFileTypes: true }).filter(e => e.isFile()).map(e => e.name).sort()) {
75
107
  const file = `${dir}/${name}`
76
108
  const text = readFileSync(join(root, file), 'utf8')
77
- write(file, text, apply(apply(text, PATH_RULES), [CLI_RULE]))
109
+ write(file, text, apply(apply(text, PATH_RULES), RUN_CLI_RULES))
78
110
  }
79
111
  }
80
- for (const file of sourceFiles(root)) {
112
+ const publicDir = configuredPublicDir(root)
113
+ for (const file of sourceFiles(root, publicDir)) {
81
114
  const text = readFileSync(join(root, file), 'utf8')
82
- const renamed = SOURCE_FILE_RE.test(file) ? renameKayNames(file, text) : text
115
+ const renamed = SOURCE_FILE_RE.test(file) ? renameKayNames(file, text, aliases) : text
83
116
  const next = apply(apply(renamed, PATH_RULES), WIRE_RULES)
84
117
  write(file, text, next)
85
118
  if (SOURCE_FILE_RE.test(file) && next !== text)
@@ -91,8 +124,9 @@ export function upgradeProject(root: string): UpgradeResult {
91
124
  changed.push(`${dir}/`)
92
125
  }
93
126
  }
94
- for (const member of workspaceMembers(root)) {
95
- const res = upgradeProject(join(root, member))
127
+ // A member on neither kay nor prunelle, a plain Bun app or a tool, has nothing to move; one already on prunelle may keep names an earlier upgrade missed.
128
+ for (const member of workspaceMembers(root).filter(m => hasKayOrPrunelle(join(root, m)))) {
129
+ const res = upgradeDir(join(root, member), aliases)
96
130
  changed.push(...res.changed.map(file => `${member}/${file}`))
97
131
  manual.push(...res.manual.map(line => `${member}/${line}`))
98
132
  }
@@ -102,6 +136,83 @@ export function upgradeProject(root: string): UpgradeResult {
102
136
  const DEP_FIELDS = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']
103
137
  const V1_RANGE_RE = /^[~^>=\s]*1\./
104
138
 
139
+ const KAY_OR_PRUNELLE_RE = /^(?:npm:)?(?:@kayjs\/|prunelle(?:@|$)|@prunellejs\/)/
140
+
141
+ function hasKayOrPrunelle(root: string): boolean {
142
+ if (!existsSync(join(root, 'package.json')))
143
+ return false
144
+ const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as Record<string, Record<string, string> | undefined>
145
+ return DEP_FIELDS.some(field => Object.entries(json[field] ?? {}).some(([name, range]) => KAY_OR_PRUNELLE_RE.test(name) || KAY_OR_PRUNELLE_RE.test(range)))
146
+ }
147
+
148
+ function kayTargetPackage(name: string, version: string): string | undefined {
149
+ if (name.startsWith('@kayjs/'))
150
+ return apply(name, PATH_RULES)
151
+ const match = NPM_KAY_ALIAS_RE.exec(version)
152
+ return match === null ? undefined : apply(match[1]!, PATH_RULES)
153
+ }
154
+
155
+ function kayAliases(root: string, inherited?: ReadonlyMap<string, string>): Map<string, string> {
156
+ const aliases = new Map<string, string>(inherited)
157
+ if (!existsSync(join(root, 'package.json')))
158
+ return aliases
159
+ const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as Record<string, Record<string, string> | undefined>
160
+ for (const field of DEP_FIELDS) {
161
+ for (const [name, version] of Object.entries(json[field] ?? {})) {
162
+ if (name.startsWith('@kayjs/'))
163
+ continue
164
+ const match = NPM_KAY_ALIAS_RE.exec(version)
165
+ if (match !== null)
166
+ aliases.set(name, apply(match[1]!, PATH_RULES))
167
+ }
168
+ }
169
+ return aliases
170
+ }
171
+
172
+ function upgradeTsconfig(text: string, aliases: ReadonlyMap<string, string>): string {
173
+ let out = apply(text, PATH_RULES)
174
+ for (const [alias, target] of aliases) {
175
+ const escaped = alias.replace(ESCAPE_RE, '\\$&')
176
+ if (target === 'prunelle')
177
+ out = out.replace(new RegExp(`("jsxImportSource"\\s*:\\s*")${escaped}(")`, 'g'), `$1${target}$2`)
178
+ out = out.replace(/"types"\s*:\s*\[[^\]]*\]/g, block =>
179
+ block.replace(new RegExp(`"${escaped}((?:/[^"]*)?)"`, 'g'), `"${target}$1"`))
180
+ }
181
+ return out
182
+ }
183
+
184
+ function upgradeGitignore(text: string, addCache: boolean): string {
185
+ const next = apply(text, PATH_RULES)
186
+ if (!addCache || GITIGNORE_CACHE_RE.test(next))
187
+ return next
188
+ const eol = next.includes('\r\n') ? '\r\n' : '\n'
189
+ const sep = next === '' || next.endsWith('\n') ? '' : eol
190
+ return `${next}${sep}.prunelle-cache/${eol}`
191
+ }
192
+
193
+ // Reads `publicDir` statically from prunelle.config.ts (or kay.config.ts) so built scripts in `public/` are left alone (#43).
194
+ function configuredPublicDir(root: string): string {
195
+ const file = existsSync(join(root, 'prunelle.config.ts'))
196
+ ? 'prunelle.config.ts'
197
+ : existsSync(join(root, 'kay.config.ts')) ? 'kay.config.ts' : undefined
198
+ if (file === undefined)
199
+ return resolve(root, 'public')
200
+ const program = parseTsx(file, readFileSync(join(root, file), 'utf8'))
201
+ let value: string | undefined
202
+ walk(program.body, (node) => {
203
+ if (value !== undefined)
204
+ return false
205
+ if (node.type === 'Property' && !node.computed && node.key.type === 'Identifier' && node.key.name === 'publicDir') {
206
+ if (node.value.type === 'Literal' && typeof node.value.value === 'string')
207
+ value = node.value.value
208
+ else if (node.value.type === 'TemplateLiteral' && node.value.expressions.length === 0)
209
+ value = node.value.quasis[0]?.value.cooked ?? node.value.quasis[0]?.value.raw
210
+ }
211
+ return true
212
+ })
213
+ return resolve(root, value ?? 'public')
214
+ }
215
+
105
216
  // kay's core at a 1.x range, as `@kayjs/kay` or an `npm:@kayjs/kay@` alias: an app of `.kay` files prunelle cannot take.
106
217
  function kayV1Dependency(root: string): string | undefined {
107
218
  if (!existsSync(join(root, 'package.json')))
@@ -149,18 +260,34 @@ function rootFiles(root: string): string[] {
149
260
  return readdirSync(root, { withFileTypes: true }).filter(e => e.isFile()).map(e => e.name).sort()
150
261
  }
151
262
 
152
- // A folder holding its own package.json is another package, upgraded on its own.
153
- function sourceFiles(root: string, dir = root, out: string[] = []): string[] {
263
+ // The entries of `dir`, none for a folder the user cannot read: a container's data, never source they edit.
264
+ function readableEntries(dir: string): Dirent[] {
265
+ try {
266
+ return readdirSync(dir, { withFileTypes: true })
267
+ }
268
+ catch (err) {
269
+ if ((err as NodeJS.ErrnoException).code === 'EACCES' || (err as NodeJS.ErrnoException).code === 'EPERM')
270
+ return []
271
+ throw err
272
+ }
273
+ }
274
+
275
+ // A folder holding its own package.json is another package, upgraded on its own; `publicDir` holds built static files left untouched (#43).
276
+ function sourceFiles(root: string, publicDir: string, dir = root, out: string[] = []): string[] {
154
277
  if (dir !== root && existsSync(join(dir, 'package.json')))
155
278
  return out
156
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
279
+ for (const entry of readableEntries(dir)) {
157
280
  if (isNotSourceDir(entry.name))
158
281
  continue
159
282
  const path = join(dir, entry.name)
160
- if (entry.isDirectory())
161
- sourceFiles(root, path, out)
162
- else if ((SOURCE_FILE_RE.test(entry.name) && !entry.name.endsWith('.d.ts')) || STYLE_OR_SCRIPT_RE.test(entry.name))
283
+ if (entry.isDirectory()) {
284
+ if (resolve(path) !== publicDir)
285
+ sourceFiles(root, publicDir, path, out)
286
+ }
287
+ // A link is skipped: its target may lie outside the app, or be a file the app reaches twice.
288
+ else if (entry.isFile() && (SOURCE_FILE_RE.test(entry.name) || STYLE_OR_SCRIPT_RE.test(entry.name))) {
163
289
  out.push(relPosix(root, path))
290
+ }
164
291
  }
165
292
  return out.sort()
166
293
  }
@@ -173,14 +300,21 @@ function upgradePackageJson(text: string): string {
173
300
  const range = `^${pkg.version}`
174
301
  for (const field of DEP_FIELDS) {
175
302
  const deps = json[field] as Record<string, string> | undefined
176
- if (deps === undefined || !Object.keys(deps).some(name => name.startsWith('@kayjs/')))
303
+ if (deps === undefined || !Object.entries(deps).some(([name, version]) => kayTargetPackage(name, version) !== undefined))
177
304
  continue
178
- const entries = Object.entries(deps).map(([name, version]) => name.startsWith('@kayjs/') ? [apply(name, PATH_RULES), range] : [name, version])
179
- json[field] = Object.fromEntries(entries.sort(([a], [b]) => a!.localeCompare(b!)))
305
+ const next = new Map<string, string>()
306
+ for (const [name, version] of Object.entries(deps)) {
307
+ const target = kayTargetPackage(name, version)
308
+ if (target !== undefined)
309
+ next.set(target, range)
310
+ else if (!next.has(name))
311
+ next.set(name, version)
312
+ }
313
+ json[field] = Object.fromEntries([...next.entries()].sort(([a], [b]) => a.localeCompare(b)))
180
314
  }
181
315
  const scripts = json.scripts as Record<string, string> | undefined
182
316
  if (scripts !== undefined)
183
- json.scripts = Object.fromEntries(Object.entries(scripts).map(([name, cmd]) => [name, apply(apply(cmd, PATH_RULES), [CLI_RULE])]))
317
+ json.scripts = Object.fromEntries(Object.entries(scripts).map(([name, cmd]) => [name, apply(apply(cmd, PATH_RULES), RUN_CLI_RULES)]))
184
318
  const after = JSON.stringify(json, null, indent)
185
319
  return after === before ? text : `${after}\n`
186
320
  }
@@ -3,17 +3,24 @@
3
3
  import type { CallExpression, ExportNamedDeclaration, Function as OxcFunction, Node, Program, Statement, VariableDeclaration } from 'oxc-parser'
4
4
  import { parseSync } from 'oxc-parser'
5
5
  import { computeJsxNodes, walk } from './ast'
6
+ import type { RouteCacheSpec } from '../server/route-cache'
6
7
  import type { BindingFacts, Interactivity } from './interactivity'
7
8
  import type { CompilerWarning } from './mistakes'
9
+ import type { ExprContext } from './shared'
8
10
  import { checkBrowserGlobals } from './browser-globals'
11
+ import { parseCacheExport } from './cacheability'
9
12
  import { analyzeDefaultDataKeys } from './data-keys'
10
13
  import { checkCompliance } from './compliance'
14
+ import { assertNoForeignImport } from './foreign-imports'
11
15
  import { resolveInteractivity } from './interactivity'
12
16
  import { findNodeEnvReads } from './node-env'
13
- import { assertNoKayImport, checkExportHydrate, checkHabits, checkHydrateMode, checkMistakes, guarded, islandRemoved, PrunelleMistake, mistake, serverOnlyTagError, staticStringValue } from './mistakes'
17
+ import { assertNoKayImport, checkExportHydrate, checkHabits, checkHydrateMode, checkMistakes, frontmatterMistake, guarded, islandRemoved, PrunelleMistake, mistake, serverOnlyTagError, staticStringValue } from './mistakes'
14
18
  import { walkScoped } from './scope'
15
- import { calleeName, decodeHtmlEntities, EVENT_ATTR, formatCodeFrame, formatDiagnostic, formatLoc, isComponentTag, isJsxNode, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from './shared'
19
+ import { calleeName, createExprContext, decodeHtmlEntities, EVENT_ATTR, formatCodeFrame, formatDiagnostic, formatLoc, isComponentTag, isJsxNode, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from './shared'
20
+ import { checkBodyPropsDestructure } from './props-body'
16
21
  import { checkBareSignals } from './signal-reads'
22
+ import type { BindingUnit } from './spread-handlers'
23
+ import { bindingUnits, checkStaticSpreadHandlers, collectUnitInits, findSpreadInteractiveAttr } from './spread-handlers'
17
24
 
18
25
  const REACTIVE_IMPORTS = new Set(['signal', 'computed', 'effect', 'onMount', 'onCleanup', 'selector', 'store', 'useAction'])
19
26
  // Primitives whose result is reactive state another module can import and read.
@@ -21,8 +28,8 @@ const STATE_PRIMITIVES = new Set(['signal', 'computed', 'selector', 'store'])
21
28
  const PRUNELLE_SOURCES = new Set(['prunelle'])
22
29
  const PRUNELLE_SSR_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
23
30
  const PRUNELLE_SERVER_SOURCES = new Set(['prunelle/server'])
24
- const RENDER_CONTEXT_IMPORTS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate', 'createContext', 'provideContext', 'useContext', 'useId'])
25
- const SERVER_ONLY_TAGS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate'])
31
+ const RENDER_CONTEXT_IMPORTS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences', 'createContext', 'provideContext', 'useContext', 'useId'])
32
+ const SERVER_ONLY_TAGS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences'])
26
33
 
27
34
  export interface ImportInfo {
28
35
  source: string
@@ -46,7 +53,13 @@ export interface ModuleAnalysis extends Interactivity {
46
53
  hasJsx: boolean
47
54
  /** Precomputed set of AST nodes containing JSX (itself included), for O(1) subtree checks during codegen. */
48
55
  jsxNodes: WeakSet<Node>
56
+ /** Lazily cached expression type/primitivity context shared between SSR and DOM compilers. */
57
+ exprContext?: ExprContext | undefined
49
58
  hasPrerender: boolean
59
+ /** True when the module explicitly exports `prerender = false`. */
60
+ prerenderFalse: boolean
61
+ /** Parsed `export const cache = ...` policy when present and valid. */
62
+ cache?: RouteCacheSpec | undefined
50
63
  hasPaths: boolean
51
64
  usesRenderContext: boolean
52
65
  defaultHydrate: string | undefined
@@ -133,10 +146,15 @@ function decodeAttributeEntities(program: Program): void {
133
146
  })
134
147
  }
135
148
 
149
+ const FRONTMATTER_RE = /^\s*---[ \t]*\r?\n/
150
+
136
151
  export function parseTsx(filename: string, code: string): Program {
137
152
  const lang = /\.[cm]?ts$/i.test(filename) ? 'ts' : 'tsx'
138
153
  const result = parseSync(filename, code, { lang, sourceType: 'module' })
139
154
  if (result.errors.length > 0) {
155
+ const frontmatter = FRONTMATTER_RE.exec(code)
156
+ if (frontmatter !== null)
157
+ throw frontmatterMistake(filename, frontmatter[0].indexOf('---'))
140
158
  const first = result.errors[0]!
141
159
  const label = first.labels?.[0]
142
160
  const offset = label?.start ?? 0
@@ -241,6 +259,7 @@ function scanImports(program: Program, filename: string): ImportScan {
241
259
  }
242
260
 
243
261
  function scanPrunelleImport(scan: ImportScan, source: string, imported: string, local: string, filename: string, start: number): void {
262
+ guarded(start, () => assertNoForeignImport(source, imported, filename))
244
263
  if (PRUNELLE_SOURCES.has(source)) {
245
264
  if (REACTIVE_IMPORTS.has(imported))
246
265
  scan.reactiveLocals.set(local, `uses ${imported}`)
@@ -272,6 +291,7 @@ interface DeclarationScan {
272
291
  hasLoadExport: boolean
273
292
  hasPaths: boolean
274
293
  hasPrerender: boolean
294
+ prerenderFalse: boolean
275
295
  defaultHydrate: string | undefined
276
296
  exportedActions: string[]
277
297
  /** The action() calls prunelle gives a URL to: the initialisers of top-level `export const`s. */
@@ -281,7 +301,7 @@ interface DeclarationScan {
281
301
  }
282
302
 
283
303
  function scanDeclarations(program: Program, filename: string, imports: ImportScan): DeclarationScan {
284
- const scan: DeclarationScan = { localInits: new Map(), exportLocals: new Map(), asyncLocals: new Set(), defaultLocal: undefined, hasAsyncDefault: false, hasLoadExport: false, hasPaths: false, hasPrerender: false, defaultHydrate: undefined, exportedActions: [], registeredActions: new Set(), reexports: [], exportedNames: [] }
304
+ const scan: DeclarationScan = { localInits: new Map(), exportLocals: new Map(), asyncLocals: new Set(), defaultLocal: undefined, hasAsyncDefault: false, hasLoadExport: false, hasPaths: false, hasPrerender: false, prerenderFalse: false, defaultHydrate: undefined, exportedActions: [], registeredActions: new Set(), reexports: [], exportedNames: [] }
285
305
  const collectInits = (decl: VariableDeclaration): void => {
286
306
  for (const d of decl.declarations) {
287
307
  if (d.id.type === 'Identifier' && d.init !== null)
@@ -358,8 +378,12 @@ function scanExportedDeclaration(scan: DeclarationScan, decl: NonNullable<Export
358
378
  continue
359
379
  const name = d.id.name
360
380
  addExport(name, name)
361
- if (name === 'prerender' && d.init?.type === 'Literal' && d.init.value === true)
362
- scan.hasPrerender = true
381
+ if (name === 'prerender' && d.init?.type === 'Literal') {
382
+ if (d.init.value === true)
383
+ scan.hasPrerender = true
384
+ else if (d.init.value === false)
385
+ scan.prerenderFalse = true
386
+ }
363
387
  if (name === 'hydrate' && d.init !== null)
364
388
  scan.defaultHydrate = checkExportHydrate(d.init, filename)
365
389
  if (d.init !== null && isActionCall(d.init, imports.actionLocalName, imports.serverNamespaces)) {
@@ -370,42 +394,6 @@ function scanExportedDeclaration(scan: DeclarationScan, decl: NonNullable<Export
370
394
  }
371
395
  }
372
396
 
373
- // A module's body as top-level bindings, each with the node holding its code; module-level statements go under ''.
374
- function bindingUnits(program: Program): { name: string, node: Node }[] {
375
- const units: { name: string, node: Node }[] = []
376
- const add = (node: Node): void => {
377
- if (node.type.startsWith('TS'))
378
- return
379
- if ((node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') && node.id !== null) {
380
- units.push({ name: node.id.name, node })
381
- }
382
- else if (node.type === 'VariableDeclaration') {
383
- for (const d of node.declarations)
384
- units.push({ name: d.id.type === 'Identifier' ? d.id.name : '', node: d })
385
- }
386
- else {
387
- units.push({ name: '', node })
388
- }
389
- }
390
- for (const stmt of program.body) {
391
- if (stmt.type === 'ExportNamedDeclaration') {
392
- if (stmt.declaration !== null)
393
- add(stmt.declaration)
394
- }
395
- else if (stmt.type === 'ExportDefaultDeclaration') {
396
- const decl = unwrapTsExpr(stmt.declaration)
397
- if ((decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') && decl.id !== null)
398
- add(decl)
399
- else if (decl.type !== 'Identifier')
400
- units.push({ name: 'default', node: decl })
401
- }
402
- else if (stmt.type !== 'ImportDeclaration') {
403
- add(stmt)
404
- }
405
- }
406
- return units
407
- }
408
-
409
397
  /** What the walk over a module's body finds. */
410
398
  interface BodyScan {
411
399
  hasJsx: boolean
@@ -415,14 +403,15 @@ interface BodyScan {
415
403
  jsxTags: Set<string>
416
404
  dynamicImports: { source: string, start: number }[]
417
405
  bindings: BindingFacts[]
406
+ units: BindingUnit[]
418
407
  }
419
408
 
420
409
  const TS_EXPR_WRAPPERS = new Set(['TSAsExpression', 'TSNonNullExpression', 'TSSatisfiesExpression', 'TSTypeAssertion', 'TSInstantiationExpression'])
421
410
 
422
411
  // Walks each top-level binding for JSX, mistakes, action() placement and what makes it run in the browser.
423
412
  function scanBody(program: Program, filename: string, code: string, imports: ImportScan, decls: DeclarationScan, warnings: CompilerWarning[], loadCode: ReadonlySet<Node>): BodyScan {
424
- const body: BodyScan = { hasJsx: false, usesRenderContext: imports.usesRenderContext, deferredIslandTags: new Set(), hydrateModes: new Set(), jsxTags: new Set(), dynamicImports: [], bindings: [] }
425
413
  const units = bindingUnits(program)
414
+ const body: BodyScan = { hasJsx: false, usesRenderContext: imports.usesRenderContext, deferredIslandTags: new Set(), hydrateModes: new Set(), jsxTags: new Set(), dynamicImports: [], bindings: [], units }
426
415
  const tracked = new Set(units.map(u => u.name))
427
416
  for (const imp of imports.imports) {
428
417
  for (const spec of imp.specifiers)
@@ -459,6 +448,7 @@ function scanBody(program: Program, filename: string, code: string, imports: Imp
459
448
  },
460
449
  })
461
450
  const isLoadUnit = loadCode.has(unit.node) || (unit.node.type === 'VariableDeclarator' && unit.node.init !== null && loadCode.has(unit.node.init))
451
+ const unitInits = collectUnitInits(unit.node, decls.localInits)
462
452
  walk(unit.node, (node): boolean | void => {
463
453
  if (node.type.startsWith('TS') && !TS_EXPR_WRAPPERS.has(node.type))
464
454
  return false
@@ -475,10 +465,10 @@ function scanBody(program: Program, filename: string, code: string, imports: Imp
475
465
  body.dynamicImports.push({ source: src, start: node.start })
476
466
  }
477
467
  else if (node.type === 'JSXOpeningElement') {
478
- scanOpeningElement(node, binding, body, imports, filename)
479
- const root = jsxTagName(node.name).split('.')[0]!
480
- if (isComponentTag(root))
481
- ref(binding, root, node.start)
468
+ scanOpeningElement(node, binding, body, imports, unitInits, filename)
469
+ const tag = jsxTagName(node.name)
470
+ if (isComponentTag(tag))
471
+ ref(binding, tag.split('.')[0]!, node.start)
482
472
  }
483
473
  else if (node.type === 'MemberExpression' && !node.computed && node.object.type === 'Identifier' && freeIds.has(node.object.start) && node.property.type === 'Identifier') {
484
474
  memberObjStarts.add(node.object.start)
@@ -494,7 +484,7 @@ function scanBody(program: Program, filename: string, code: string, imports: Imp
494
484
  return body
495
485
  }
496
486
 
497
- function scanOpeningElement(node: Extract<Node, { type: 'JSXOpeningElement' }>, binding: BindingFacts, body: BodyScan, imports: ImportScan, filename: string): void {
487
+ function scanOpeningElement(node: Extract<Node, { type: 'JSXOpeningElement' }>, binding: BindingFacts, body: BodyScan, imports: ImportScan, unitInits: ReadonlyMap<string, Node>, filename: string): void {
498
488
  const tag = jsxTagName(node.name)
499
489
  const isComponent = isComponentTag(tag)
500
490
  if (isComponent) {
@@ -509,7 +499,15 @@ function scanOpeningElement(node: Extract<Node, { type: 'JSXOpeningElement' }>,
509
499
  }
510
500
  }
511
501
  for (const attr of node.attributes) {
512
- if (attr.type !== 'JSXAttribute' || attr.name.type !== 'JSXIdentifier')
502
+ if (attr.type === 'JSXSpreadAttribute') {
503
+ if (!isComponent && tag !== '') {
504
+ const found = findSpreadInteractiveAttr(attr.argument, unitInits)
505
+ if (found !== undefined)
506
+ binding.fact ??= { reason: `uses ${found}`, offset: attr.start }
507
+ }
508
+ continue
509
+ }
510
+ if (attr.name.type !== 'JSXIdentifier')
513
511
  continue
514
512
  const attrName = attr.name.name
515
513
  if (isComponent && attrName === '$hydrate') {
@@ -560,6 +558,29 @@ function stateExportsOf(decls: DeclarationScan, callees: ReadonlySet<string>, co
560
558
  return [...decls.exportLocals].filter(([, local]) => containsStateInit(decls.localInits.get(local), callees, containers)).map(([exported]) => exported)
561
559
  }
562
560
 
561
+ const exprContextCache = new WeakMap<Program, ExprContext>()
562
+
563
+ /** Lazily computes and caches `ExprContext` on `analysis` (and by `program` across shallow copies) so SSR and DOM compilation never build it twice. */
564
+ export function getExprContext(analysis: ModuleAnalysis): ExprContext {
565
+ if (analysis.exprContext !== undefined)
566
+ return analysis.exprContext
567
+ let ctx = exprContextCache.get(analysis.program)
568
+ if (ctx === undefined) {
569
+ ctx = createExprContext(analysis.program, analysis.jsxNodes)
570
+ exprContextCache.set(analysis.program, ctx)
571
+ }
572
+ analysis.exprContext = ctx
573
+ return ctx
574
+ }
575
+
576
+ // An island page whose reads of `data` the compiler cannot follow ships the whole `load()` result, personal data it never shows included.
577
+ export function wholeLoadShippedWarning(filename: string, start: number): CompilerWarning {
578
+ return {
579
+ start,
580
+ message: `prunelle compiler: the island page in ${filename} uses \`data\` in a way the compiler cannot follow, so the whole load() result is sent to the browser: export \`clientData\` listing the keys the page reads (\`export const clientData = ['title']\`), or \`(data) => data\` to send all of it on purpose.`,
581
+ }
582
+ }
583
+
563
584
  export function analyzeModule(filename: string, code: string, program: Program = parseTsx(filename, code)): ModuleAnalysis {
564
585
  const imports = scanImports(program, filename)
565
586
  const decls = scanDeclarations(program, filename, imports)
@@ -567,9 +588,10 @@ export function analyzeModule(filename: string, code: string, program: Program =
567
588
  const loadNodes = loadDeclarations(program)
568
589
  const body = scanBody(program, filename, code, imports, decls, warnings, new Set(loadNodes))
569
590
  checkBareSignals(program, imports.signalCallees, filename)
591
+ const jsxNodes = body.hasJsx ? computeJsxNodes(program) : new WeakSet<Node>()
570
592
  if (body.hasJsx) {
571
593
  checkCompliance(program, filename, code, warnings, tag => resolvePrunelleTag(tag, imports.imports))
572
- checkBrowserGlobals(program, code, filename, warnings)
594
+ checkBrowserGlobals(program, code, filename, warnings, jsxNodes)
573
595
  }
574
596
 
575
597
  for (const [name, init] of decls.localInits) {
@@ -578,22 +600,33 @@ export function analyzeModule(filename: string, code: string, program: Program =
578
600
  }
579
601
  const hasAsyncDefault = decls.hasAsyncDefault || (decls.defaultLocal !== undefined && decls.asyncLocals.has(decls.defaultLocal))
580
602
  const interactivity = resolveInteractivity(body.bindings, decls.exportLocals)
603
+ if (body.hasJsx) {
604
+ checkBodyPropsDestructure(program, code, interactivity.browserSpans, jsxNodes, filename, warnings)
605
+ checkStaticSpreadHandlers(body.units, decls.localInits, interactivity, filename, warnings)
606
+ }
581
607
  const page = interactivity.exports.get('default')
582
608
  if (hasAsyncDefault && page?.interactive === true)
583
609
  guarded(page.offset ?? 0, () => { throw asyncInteractiveError(filename, page.reason, page.offset) })
584
610
  if (interactivity.serverOnly !== undefined)
585
611
  guarded(interactivity.serverOnly.offset, () => { throw serverOnlyTagError(filename, interactivity.serverOnly!) })
586
612
 
613
+ const cacheExport = parseCacheExport(program)
614
+ const hasLoadExport = decls.hasLoadExport || loadNodes.length > 0
615
+ const defaultDataKeys = page?.interactive === true || hasLoadExport ? analyzeDefaultDataKeys(program, decls.defaultLocal, decls.localInits) : undefined
616
+ if (page?.interactive === true && hasLoadExport && defaultDataKeys === undefined && !decls.exportedNames.includes('clientData'))
617
+ warnings.push(wholeLoadShippedWarning(filename, decls.localInits.get(decls.defaultLocal ?? '')?.start ?? page.offset ?? 0))
587
618
  return {
588
619
  filename,
589
620
  program,
590
621
  warnings,
591
622
  ...interactivity,
592
623
  hasAsyncDefault,
593
- hasLoadExport: decls.hasLoadExport || loadNodes.length > 0,
624
+ hasLoadExport,
594
625
  hasJsx: body.hasJsx,
595
- jsxNodes: body.hasJsx ? computeJsxNodes(program) : new WeakSet<Node>(),
626
+ jsxNodes,
596
627
  hasPrerender: decls.hasPrerender,
628
+ prerenderFalse: decls.prerenderFalse,
629
+ ...(cacheExport.spec !== undefined ? { cache: cacheExport.spec } : {}),
597
630
  hasPaths: decls.hasPaths,
598
631
  usesRenderContext: body.usesRenderContext,
599
632
  defaultHydrate: decls.defaultHydrate,
@@ -603,7 +636,7 @@ export function analyzeModule(filename: string, code: string, program: Program =
603
636
  asyncLocals: decls.hasAsyncDefault ? new Set([...decls.asyncLocals, decls.exportLocals.get('default') ?? 'default']) : decls.asyncLocals,
604
637
  stateExports: stateExportsOf(decls, imports.stateCallees, true),
605
638
  signalExports: stateExportsOf(decls, imports.signalCallees, false),
606
- defaultDataKeys: page?.interactive === true ? analyzeDefaultDataKeys(program, decls.defaultLocal, decls.localInits) : undefined,
639
+ defaultDataKeys,
607
640
  exportedActions: decls.exportedActions,
608
641
  imports: imports.imports,
609
642
  dynamicImports: body.dynamicImports,