prunelle 0.1.1 → 0.7.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 (173) 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 +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  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 +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -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 +610 -0
  36. package/src/cli/check-imports.ts +25 -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 +107 -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 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -0,0 +1,230 @@
1
+ // Mapping between axe-core rule identifiers and French RGAA 4.1 criteria.
2
+
3
+ export interface RgaaCriterion {
4
+ /** RGAA 4.1 criterion identifier (e.g. `'1.1'`, `'3.2'`, `'11.1'`). */
5
+ id: string
6
+ /** RGAA 4.1 theme number (1–13). */
7
+ theme: number
8
+ /** Short French RGAA 4.1 criterion title. */
9
+ label: string
10
+ }
11
+
12
+ /** Subset of official French RGAA 4.1 criteria detectable by automated axe-core checks. */
13
+ export const RGAA_CRITERIA: Readonly<Record<string, RgaaCriterion>> = {
14
+ '1.1': { id: '1.1', theme: 1, label: 'Alternative textuelle pour chaque image porteuse d\'information' },
15
+ '1.2': { id: '1.2', theme: 1, label: 'Image de décoration ignorée par les technologies d\'assistance' },
16
+ '1.3': { id: '1.3', theme: 1, label: 'Pertinence de l\'alternative textuelle des images' },
17
+ '2.1': { id: '2.1', theme: 2, label: 'Titre de chaque cadre (iframe)' },
18
+ '2.2': { id: '2.2', theme: 2, label: 'Pertinence du titre de chaque cadre' },
19
+ '3.1': { id: '3.1', theme: 3, label: 'Information non donnée uniquement par la couleur' },
20
+ '3.2': { id: '3.2', theme: 3, label: 'Contraste suffisant entre texte et arrière-plan' },
21
+ '4.1': { id: '4.1', theme: 4, label: 'Transcription textuelle ou audiodescription des médias temporels' },
22
+ '4.3': { id: '4.3', theme: 4, label: 'Sous-titres synchronisés des médias temporels synchronisés' },
23
+ '4.10': { id: '4.10', theme: 4, label: 'Contrôle des sons déclenchés automatiquement' },
24
+ '5.1': { id: '5.1', theme: 5, label: 'Résumé des tableaux de données complexes' },
25
+ '5.2': { id: '5.2', theme: 5, label: 'Pertinence du résumé des tableaux de données complexes' },
26
+ '5.3': { id: '5.3', theme: 5, label: 'Compréhension du contenu linéarisé des tableaux de mise en forme' },
27
+ '5.4': { id: '5.4', theme: 5, label: 'Association du titre au tableau de données' },
28
+ '5.6': { id: '5.6', theme: 5, label: 'Déclaration des en-têtes de colonnes et de lignes des tableaux' },
29
+ '5.7': { id: '5.7', theme: 5, label: 'Association des cellules de données avec leurs en-têtes' },
30
+ '6.1': { id: '6.1', theme: 6, label: 'Intitulé explicite de chaque lien' },
31
+ '6.2': { id: '6.2', theme: 6, label: 'Présence d\'un intitulé pour chaque lien' },
32
+ '7.1': { id: '7.1', theme: 7, label: 'Compatibilité des scripts et composants ARIA avec les technologies d\'assistance' },
33
+ '7.3': { id: '7.3', theme: 7, label: 'Contrôle au clavier et par tout dispositif de pointage' },
34
+ '8.2': { id: '8.2', theme: 8, label: 'Validité du code source généré (identifiants uniques)' },
35
+ '8.3': { id: '8.3', theme: 8, label: 'Présence de la langue par défaut de la page' },
36
+ '8.4': { id: '8.4', theme: 8, label: 'Pertinence du code de langue par défaut' },
37
+ '8.5': { id: '8.5', theme: 8, label: 'Présence d\'un titre de page (<title>)' },
38
+ '8.7': { id: '8.7', theme: 8, label: 'Indication des changements de langue dans le code source' },
39
+ '8.8': { id: '8.8', theme: 8, label: 'Validité et pertinence du code de langue des changements de langue' },
40
+ '9.1': { id: '9.1', theme: 9, label: 'Structuration de l\'information par les titres (h1–h6)' },
41
+ '9.2': { id: '9.2', theme: 9, label: 'Cohérence de la structure et des zones principales (landmarks)' },
42
+ '9.3': { id: '9.3', theme: 9, label: 'Structuration correcte des listes' },
43
+ '10.1': { id: '10.1', theme: 10, label: 'Utilisation des feuilles de styles pour contrôler la présentation' },
44
+ '10.4': { id: '10.4', theme: 10, label: 'Lisibilité du texte lors d\'un agrandissement jusqu\'à 200 %' },
45
+ '10.6': { id: '10.6', theme: 10, label: 'Visibilité des liens dont la nature n\'est pas évidente par rapport au texte environnant' },
46
+ '10.8': { id: '10.8', theme: 10, label: 'Contenus cachés destinés à être ignorés par les technologies d\'assistance' },
47
+ '10.11': { id: '10.11', theme: 10, label: 'Présentation sans perte d\'information ni défilement horizontal (reflow)' },
48
+ '10.13': { id: '10.13', theme: 10, label: 'Contrôle des contenus additionnels au focus ou au survol' },
49
+ '11.1': { id: '11.1', theme: 11, label: 'Étiquette associée à chaque champ de formulaire' },
50
+ '11.2': { id: '11.2', theme: 11, label: 'Pertinence de l\'étiquette associée à chaque champ de formulaire' },
51
+ '11.5': { id: '11.5', theme: 11, label: 'Regroupement des champs de même nature dans les formulaires' },
52
+ '11.9': { id: '11.9', theme: 11, label: 'Pertinence de l\'intitulé de chaque bouton' },
53
+ '11.13': { id: '11.13', theme: 11, label: 'Déduction de la finalité des champs de saisie (autocomplete)' },
54
+ '12.6': { id: '12.6', theme: 12, label: 'Accès et évitement des zones de regroupement de contenus' },
55
+ '12.7': { id: '12.7', theme: 12, label: 'Lien d\'évitement ou d\'accès rapide au contenu principal' },
56
+ '12.8': { id: '12.8', theme: 12, label: 'Cohérence de l\'ordre de tabulation' },
57
+ '13.1': { id: '13.1', theme: 13, label: 'Contrôle par l\'utilisateur de chaque limite de temps' },
58
+ '13.8': { id: '13.8', theme: 13, label: 'Contrôle des contenus en mouvement ou clignotants' },
59
+ '13.9': { id: '13.9', theme: 13, label: 'Consultation du contenu quelle que soit l\'orientation de l\'écran' },
60
+ }
61
+
62
+ /**
63
+ * Direct lookup from axe-core rule ID to one or more RGAA 4.1 criterion IDs.
64
+ * A rule axe-core tags `RGAA-x.y.z` maps to what axe names, and `a11y-audit.test.ts` fails when an axe-core upgrade moves one; the rest are axe best-practice rules mapped here.
65
+ */
66
+ export const AXE_TO_RGAA: Readonly<Record<string, readonly string[]>> = {
67
+ // Theme 1 - Images
68
+ 'area-alt': ['1.1'],
69
+ 'image-alt': ['1.1'],
70
+ 'input-image-alt': ['1.1'],
71
+ 'object-alt': ['1.1'],
72
+ 'role-img-alt': ['1.1'],
73
+ 'server-side-image-map': ['1.1'],
74
+ 'svg-img-alt': ['1.1'],
75
+ 'presentation-role-conflict': ['1.2', '7.1'],
76
+ 'image-redundant-alt': ['1.3'],
77
+
78
+ // Theme 2 - Cadres
79
+ 'frame-title': ['2.1'],
80
+ 'frame-title-unique': ['2.2'],
81
+
82
+ // Theme 3 - Couleurs
83
+ 'color-contrast': ['3.2'],
84
+ 'color-contrast-enhanced': ['3.2'],
85
+
86
+ // Theme 4 - Multimédia
87
+ 'audio-caption': ['4.1'],
88
+ 'video-caption': ['4.3'],
89
+ 'no-autoplay-audio': ['4.10'],
90
+
91
+ // Theme 5 - Tableaux
92
+ 'table-duplicate-name': ['5.2'],
93
+ 'table-fake-caption': ['5.4'],
94
+ 'empty-table-header': ['5.6'],
95
+ 'scope-attr-valid': ['5.7'],
96
+ 'td-has-header': ['5.7'],
97
+ 'td-headers-attr': ['5.7'],
98
+ 'th-has-data-cells': ['5.7'],
99
+
100
+ // Theme 6 - Liens
101
+ 'identical-links-same-purpose': ['6.1'],
102
+ 'label-content-name-mismatch': ['6.1'],
103
+ 'link-name': ['6.2'],
104
+
105
+ // Theme 7 - Scripts & ARIA
106
+ 'aria-allowed-attr': ['7.1'],
107
+ 'aria-conditional-attr': ['7.1'],
108
+ 'aria-deprecated-role': ['7.1'],
109
+ 'aria-prohibited-attr': ['7.1'],
110
+ 'aria-required-attr': ['7.1'],
111
+ 'aria-roles': ['7.1'],
112
+ 'aria-tab-name': ['7.1'],
113
+ 'aria-toggle-field-name': ['7.1'],
114
+ 'aria-valid-attr': ['7.1'],
115
+ 'aria-valid-attr-value': ['7.1'],
116
+ 'nested-interactive': ['7.1'],
117
+ 'summary-name': ['7.1'],
118
+ 'frame-focusable-content': ['7.3'],
119
+ 'scrollable-region-focusable': ['7.3'],
120
+
121
+ // Theme 8 - Éléments obligatoires
122
+ 'duplicate-id': ['8.2'],
123
+ 'duplicate-id-active': ['8.2'],
124
+ 'duplicate-id-aria': ['8.2'],
125
+ 'html-has-lang': ['8.3'],
126
+ 'html-xml-lang-mismatch': ['8.3'],
127
+ 'html-lang-valid': ['8.4'],
128
+ 'document-title': ['8.5'],
129
+ 'valid-lang': ['8.8'],
130
+
131
+ // Theme 9 - Structuration de l'information
132
+ 'empty-heading': ['9.1'],
133
+ 'heading-order': ['9.1'],
134
+ 'p-as-heading': ['9.1'],
135
+ 'page-has-heading-one': ['9.1'],
136
+ 'landmark-banner-is-top-level': ['9.2'],
137
+ 'landmark-complementary-is-top-level': ['9.2'],
138
+ 'landmark-contentinfo-is-top-level': ['9.2'],
139
+ 'landmark-main-is-top-level': ['9.2'],
140
+ 'landmark-no-duplicate-banner': ['9.2'],
141
+ 'landmark-no-duplicate-contentinfo': ['9.2'],
142
+ 'landmark-no-duplicate-main': ['9.2'],
143
+ 'landmark-one-main': ['9.2'],
144
+ 'landmark-unique': ['9.2'],
145
+ 'region': ['9.2'],
146
+ 'aria-required-children': ['9.3'],
147
+ 'aria-required-parent': ['9.3'],
148
+ 'definition-list': ['9.3'],
149
+ 'dlitem': ['9.3'],
150
+ 'list': ['9.3'],
151
+ 'listitem': ['9.3'],
152
+
153
+ // Theme 10 - Présentation de l'information
154
+ 'meta-viewport': ['10.4'],
155
+ 'meta-viewport-large': ['10.4'],
156
+ 'link-in-text-block': ['10.6'],
157
+ 'aria-hidden-body': ['10.8'],
158
+ 'aria-hidden-focus': ['10.8'],
159
+ 'avoid-inline-spacing': ['10.11'],
160
+ 'target-size': ['10.13'],
161
+
162
+ // Theme 11 - Formulaires
163
+ 'aria-input-field-name': ['11.1'],
164
+ 'aria-meter-name': ['11.1'],
165
+ 'aria-progressbar-name': ['11.1'],
166
+ 'label': ['11.1'],
167
+ 'label-title-only': ['11.1'],
168
+ 'select-name': ['11.1'],
169
+ 'form-field-multiple-labels': ['11.2'],
170
+ 'aria-command-name': ['11.9'],
171
+ 'button-name': ['11.9'],
172
+ 'input-button-name': ['11.9'],
173
+ 'autocomplete-valid': ['11.13'],
174
+
175
+ // Theme 12 - Navigation
176
+ 'bypass': ['12.7'],
177
+ 'skip-link': ['12.7'],
178
+ 'accesskeys': ['12.8'],
179
+ 'focus-order-semantics': ['12.8'],
180
+ 'tabindex': ['12.8'],
181
+
182
+ // Theme 13 - Consultation
183
+ 'meta-refresh': ['13.1'],
184
+ 'meta-refresh-no-exceptions': ['13.1'],
185
+ 'blink': ['13.8'],
186
+ 'marquee': ['13.8'],
187
+ 'css-orientation-lock': ['13.9'],
188
+ }
189
+
190
+ function lookupCriteria(ids: readonly string[]): RgaaCriterion[] {
191
+ const out: RgaaCriterion[] = []
192
+ for (const id of ids) {
193
+ const found = RGAA_CRITERIA[id]
194
+ if (found !== undefined)
195
+ out.push(found)
196
+ }
197
+ return out
198
+ }
199
+
200
+ // `RGAA-11.9.1` names test 1 of criterion 11.9.
201
+ function criteriaFromTags(tags: readonly string[]): string[] {
202
+ const ids: string[] = []
203
+ for (const tag of tags) {
204
+ if (!tag.startsWith('RGAA-'))
205
+ continue
206
+ const id = tag.slice(5).split('.').slice(0, 2).join('.')
207
+ if (!ids.includes(id))
208
+ ids.push(id)
209
+ }
210
+ return ids
211
+ }
212
+
213
+ /** Resolves an axe-core rule ID (e.g. `'image-alt'`, `'aria-roles'`) to its RGAA 4.1 criteria, from the result's own `RGAA-x.y.z` tags when it has them. */
214
+ export function rgaaCriteriaForAxeRule(ruleId: string, tags: readonly string[] = []): RgaaCriterion[] {
215
+ const tagged = criteriaFromTags(tags)
216
+ if (tagged.length > 0)
217
+ return lookupCriteria(tagged)
218
+ const exact = AXE_TO_RGAA[ruleId]
219
+ if (exact !== undefined)
220
+ return lookupCriteria(exact)
221
+ if (ruleId.startsWith('aria-'))
222
+ return lookupCriteria(['7.1'])
223
+ if (ruleId.startsWith('table-') || ruleId.startsWith('td-') || ruleId.startsWith('th-'))
224
+ return lookupCriteria(['5.7'])
225
+ if (ruleId.startsWith('landmark-'))
226
+ return lookupCriteria(['9.2'])
227
+ if (ruleId.startsWith('frame-'))
228
+ return lookupCriteria(['2.1'])
229
+ return []
230
+ }
package/src/attrs.ts CHANGED
@@ -3,7 +3,9 @@
3
3
  export const VALID_ATTR_NAME = /^[A-Za-z_:][-\w:.]*$/
4
4
  export const URL_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'xlink:href', 'data'])
5
5
  const UNSAFE_URL_RE = /^(?:javascript|vbscript):/i
6
- const SAFE_IMAGE_DATA_URL_RE = /^data:image\/(?:png|jpe?g|gif|webp|avif|bmp|ico|x-icon|vnd\.microsoft\.icon|svg\+xml)[;,]/i
6
+ const SAFE_RASTER_DATA_URL_RE = /^data:image\/(?:png|jpe?g|gif|webp|avif|bmp|ico|x-icon|vnd\.microsoft\.icon)[;,]/i
7
+ const SAFE_SVG_DATA_URL_RE = /^data:image\/svg\+xml[;,]/i
8
+ const SVG_DATA_SRC_TAGS = new Set(['img', 'source'])
7
9
  const STRING_BOOL_ATTRS = new Set(['draggable', 'spellcheck', 'contenteditable'])
8
10
 
9
11
  export const DOM_PROPS = new Set(['value', 'checked', 'selected', 'muted', 'indeterminate'])
@@ -29,7 +31,13 @@ export function isUnsafeUrlAttr(name: string, value: unknown, tag?: string): boo
29
31
  return true
30
32
  if (!/^data:/i.test(cleaned))
31
33
  return false
32
- if (lower === 'src' || (lower === 'href' && tag?.toLowerCase() === 'link'))
33
- return !SAFE_IMAGE_DATA_URL_RE.test(cleaned)
34
+ const lowerTag = tag?.toLowerCase()
35
+ if (lower === 'src') {
36
+ if (SAFE_RASTER_DATA_URL_RE.test(cleaned))
37
+ return false
38
+ return !(lowerTag !== undefined && SVG_DATA_SRC_TAGS.has(lowerTag) && SAFE_SVG_DATA_URL_RE.test(cleaned))
39
+ }
40
+ if (lower === 'href' && lowerTag === 'link')
41
+ return !(SAFE_RASTER_DATA_URL_RE.test(cleaned) || SAFE_SVG_DATA_URL_RE.test(cleaned))
34
42
  return true
35
43
  }
@@ -6,7 +6,7 @@ import type { BuildPluginTarget, PrunellePlugin } from '../plugins/index'
6
6
  import type { ClientTransforms } from './client-plugin'
7
7
  import type { BuildCache, ModuleGraph } from './graph'
8
8
  import type { ActionsByFile, IslandPlan } from './islands'
9
- import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, realpathSync } from 'node:fs'
9
+ import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, realpathSync, writeFileSync } from 'node:fs'
10
10
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
11
11
  import { compileSsr } from '../compiler/index'
12
12
  import { readsPrivateEnv } from '../compiler/server-only'
@@ -17,6 +17,7 @@ import { stampFiles, stampsMatch } from './graph'
17
17
  import { entryStaticImports, hydrateStrategies, writeClientEntries } from './client-entries'
18
18
  import { clientLeakError, islandKey } from './islands'
19
19
  import { pluginHookError } from './plugin-host'
20
+ import { ensureCacheGitignore } from './precompress'
20
21
  import { PRUNELLE_SRC_ROOT, resolvePrunelleSpecifier } from './resolve'
21
22
 
22
23
  export interface BundleEnv {
@@ -25,6 +26,8 @@ export interface BundleEnv {
25
26
  clientDir: string
26
27
  serverDir: string
27
28
  assetPrefix: string
29
+ /** `lang` from the config, handed to plugin `bunPlugins` factories. */
30
+ lang?: string | undefined
28
31
  minify: boolean
29
32
  isDev: boolean
30
33
  nodeEnv?: string | undefined
@@ -46,15 +49,34 @@ export function linkOrCopyFile(src: string, dst: string): void {
46
49
  }
47
50
  }
48
51
 
49
- function reuseDirFiles(srcDir: string, dstDir: string, relFiles?: readonly string[]): boolean {
52
+ const prunedClientCss = new WeakMap<BuildCache, Map<string, Uint8Array>>()
53
+
54
+ /** Keeps intermediate CSS bytes pruned by stylesheet consolidation so the next `buildClient` cache hit can restore them before consolidating again. */
55
+ export function setPrunedClientCss(cache: BuildCache | undefined, files: Map<string, Uint8Array>): void {
56
+ if (cache === undefined)
57
+ return
58
+ if (files.size > 0)
59
+ prunedClientCss.set(cache, files)
60
+ else
61
+ prunedClientCss.delete(cache)
62
+ }
63
+
64
+ function reuseDirFiles(srcDir: string, dstDir: string, relFiles?: readonly string[], fallbackFiles?: ReadonlyMap<string, Uint8Array>): boolean {
50
65
  if (!existsSync(srcDir))
51
66
  return false
52
67
  if (relFiles !== undefined) {
53
68
  for (const rel of relFiles) {
54
69
  const from = join(srcDir, rel)
55
- if (!existsSync(from))
70
+ const to = join(dstDir, rel)
71
+ if (existsSync(from)) {
72
+ linkOrCopyFile(from, to)
73
+ continue
74
+ }
75
+ const bytes = fallbackFiles?.get(rel)
76
+ if (bytes === undefined)
56
77
  return false
57
- linkOrCopyFile(from, join(dstDir, rel))
78
+ mkdirSync(dirname(to), { recursive: true })
79
+ writeFileSync(to, bytes)
58
80
  }
59
81
  return true
60
82
  }
@@ -74,11 +96,11 @@ const PRUNELLE_SCOPE_RE = /^@prunellejs\//
74
96
  const LEADING_DOT_SLASH_RE = /^\.\//
75
97
  const EXTERNAL_PRUNELLE_SPECIFIERS = new Set(['prunelle/build', 'prunelle/test'])
76
98
 
77
- export function pluginBunPlugins(env: Pick<BundleEnv, 'plugins' | 'root' | 'assetPrefix' | 'minify'>, target: BuildPluginTarget): BunPlugin[] {
78
- const { root, assetPrefix, minify } = env
99
+ export function pluginBunPlugins(env: Pick<BundleEnv, 'plugins' | 'root' | 'assetPrefix' | 'minify' | 'lang'>, target: BuildPluginTarget): BunPlugin[] {
100
+ const { root, assetPrefix, minify, lang } = env
79
101
  return env.plugins.flatMap((p) => {
80
102
  const bp = p.bunPlugins
81
- return typeof bp === 'function' ? bp({ root, assetPrefix, minify, target }) : bp ?? []
103
+ return typeof bp === 'function' ? bp({ root, assetPrefix, minify, target, lang }) : bp ?? []
82
104
  })
83
105
  }
84
106
 
@@ -182,6 +204,40 @@ function publicEnvDefines(): Record<string, string> {
182
204
  }
183
205
 
184
206
 
207
+ function buildClientSignature(
208
+ env: BundleEnv,
209
+ standaloneCss: readonly string[],
210
+ pluginClientEntries: readonly string[],
211
+ regionClientEntries: readonly string[],
212
+ transformsKey: string,
213
+ strategies: ReturnType<typeof hydrateStrategies>['strategies'],
214
+ hasClientOnlyHydrate: boolean,
215
+ envDefines: Readonly<Record<string, string>>,
216
+ ): string {
217
+ if (env.cache === undefined)
218
+ return ''
219
+ return JSON.stringify({
220
+ minify: env.minify,
221
+ assetPrefix: env.assetPrefix,
222
+ isDev: env.isDev,
223
+ nodeEnv: env.nodeEnv ?? (env.isDev ? 'development' : 'production'),
224
+ transforms: transformsKey,
225
+ strategies,
226
+ hasClientOnlyHydrate,
227
+ pluginClientEntries,
228
+ regionClientEntries,
229
+ standaloneCss: [...standaloneCss].sort(),
230
+ islands: [...env.islands.targets.entries()]
231
+ .sort(([a], [b]) => a.localeCompare(b))
232
+ .map(([k, t]) => [k, t.id, t.file, t.exportName, t.defaultHydrate ?? '']),
233
+ actions: [...env.actionsByFile.entries()]
234
+ .sort(([a], [b]) => a.localeCompare(b))
235
+ .map(([f, list]) => [f, list.map(a => `${a.exportName}=${a.url}`)]),
236
+ envDefines: Object.entries(envDefines).sort(([a], [b]) => a.localeCompare(b)),
237
+ bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
238
+ })
239
+ }
240
+
185
241
  export async function buildClient(env: BundleEnv, standaloneCss: string[]): Promise<ClientBuild> {
186
242
  const { root, clientDir, assetPrefix, graph, cache, actionsByFile, islands } = env
187
243
  const result: ClientBuild = {
@@ -199,8 +255,10 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
199
255
  const pluginClientEntries = env.plugins.map(p => p.clientEntry).filter((e): e is string => Boolean(e))
200
256
  const regionClientEntries = env.plugins.map(p => p.regionClientEntry).filter((e): e is string => Boolean(e))
201
257
  if (islands.targets.size === 0 && pluginClientEntries.length === 0 && regionClientEntries.length === 0 && standaloneCss.length === 0) {
202
- if (cache !== undefined)
258
+ if (cache !== undefined) {
203
259
  cache.lastClient = undefined
260
+ prunedClientCss.delete(cache)
261
+ }
204
262
  return result
205
263
  }
206
264
 
@@ -208,27 +266,7 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
208
266
  const { strategies, hasClientOnlyHydrate } = hydrateStrategies(graph.analyses.values())
209
267
 
210
268
  const envDefines = publicEnvDefines()
211
- const clientSignature = cache !== undefined
212
- ? JSON.stringify({
213
- minify: env.minify,
214
- assetPrefix,
215
- isDev: env.isDev,
216
- transforms: transforms.key,
217
- strategies,
218
- hasClientOnlyHydrate,
219
- pluginClientEntries,
220
- regionClientEntries,
221
- standaloneCss: [...standaloneCss].sort(),
222
- islands: [...islands.targets.entries()]
223
- .sort(([a], [b]) => a.localeCompare(b))
224
- .map(([k, t]) => [k, t.id, t.file, t.exportName, t.defaultHydrate ?? '']),
225
- actions: [...actionsByFile.entries()]
226
- .sort(([a], [b]) => a.localeCompare(b))
227
- .map(([f, list]) => [f, list.map(a => `${a.exportName}=${a.url}`)]),
228
- envDefines: Object.entries(envDefines).sort(([a], [b]) => a.localeCompare(b)),
229
- bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
230
- })
231
- : ''
269
+ const clientSignature = buildClientSignature(env, standaloneCss, pluginClientEntries, regionClientEntries, transforms.key, strategies, hasClientOnlyHydrate, envDefines)
232
270
 
233
271
  if (
234
272
  cache !== undefined
@@ -236,7 +274,7 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
236
274
  && cache.lastClient !== undefined
237
275
  && cache.lastClient.signature === clientSignature
238
276
  && stampsMatch(cache.lastClient.inputStamps)
239
- && reuseDirFiles(cache.lastClient.clientDir, clientDir, cache.lastClient.assetFiles)
277
+ && reuseDirFiles(cache.lastClient.clientDir, clientDir, cache.lastClient.assetFiles, prunedClientCss.get(cache))
240
278
  ) {
241
279
  cache.stats.clientSkips++
242
280
  cache.lastClient.clientDir = clientDir
@@ -255,13 +293,14 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
255
293
  }
256
294
 
257
295
  // Bun hashes an entry's path into its chunk name, so the entries sit at one path per app: a dev rebuild or a static stage then keeps every unchanged chunk name.
258
- const entriesDir = join(root, 'node_modules/.cache/prunelle/entries')
296
+ const entriesDir = join(root, '.prunelle-cache/entries')
259
297
  mkdirSync(entriesDir, { recursive: true })
298
+ ensureCacheGitignore(dirname(entriesDir))
260
299
  const { entryPoints, islandEntryToKey, runtimeEntryPath, regionEntryPath } = writeClientEntries(env, entriesDir, { pluginClientEntries, regionClientEntries, hasClientOnlyHydrate, standaloneCss })
261
300
 
262
301
  const clientLeaks = new Set<string>()
263
302
  const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in envDefines
264
- const plugin = clientPlugin({ root, graph, cache, actionsByFile, transforms, leaks: clientLeaks, localExports: localIslandExports(islands.targets.values()), clientKeep: islands.clientKeep })
303
+ const plugin = clientPlugin({ root, isDev: env.isDev, graph, cache, actionsByFile, transforms, leaks: clientLeaks, localExports: localIslandExports(islands.targets.values()), clientKeep: islands.clientKeep })
265
304
  const reviver = islands.targets.size > 0 ? await buildReviver(env) : undefined
266
305
 
267
306
  const clientResult = await runBunBuild('client', env.root, () => {
@@ -383,6 +422,7 @@ function rememberClientBuild(
383
422
  ): void {
384
423
  const { signature, clientDir, entriesDir, actionsByFile, graph, resolveMetaPath } = options
385
424
  cache.stats.clientBuilds++
425
+ prunedClientCss.delete(cache)
386
426
  const inputFiles = new Set<string>(options.inputFiles)
387
427
  for (const inKey of Object.keys(result.metafile?.inputs ?? {})) {
388
428
  const abs = resolveMetaPath(inKey)
@@ -428,8 +468,9 @@ function resolveServerImports(b: PluginBuilder, isDev: boolean, root: string, re
428
468
  return undefined
429
469
  }
430
470
  })
471
+ b.onLoad({ filter: /.*/, namespace: 'prunelle-server-css' }, () => ({ contents: '', loader: 'js' }))
431
472
  b.onResolve({ filter: /^[^./]/ }, (args) => {
432
- if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~') || isAbsolute(args.path))
473
+ if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~icons/') || args.path.startsWith('virtual:') || isAbsolute(args.path))
433
474
  return undefined
434
475
  let resolved: string | undefined
435
476
  try {
@@ -443,15 +484,21 @@ function resolveServerImports(b: PluginBuilder, isDev: boolean, root: string, re
443
484
  return undefined
444
485
  }
445
486
  }
487
+ if (resolved.endsWith('.css'))
488
+ return resolved.endsWith('.module.css') ? { path: resolved } : { path: resolved, namespace: 'prunelle-server-css' }
446
489
  if (resolved.endsWith('.tsx') || reachesTsx(resolved))
447
490
  return { path: resolved }
448
- if (isDev && isTsFile(resolved)) {
449
- try {
450
- const real = realpathSync(resolved)
451
- if (!isInNodeModules(real))
452
- return { path: resolved }
491
+ if (isTsFile(resolved)) {
492
+ if (!isInNodeModules(resolved))
493
+ return { path: resolved }
494
+ if (isDev) {
495
+ try {
496
+ const real = realpathSync(resolved)
497
+ if (!isInNodeModules(real))
498
+ return { path: resolved }
499
+ }
500
+ catch {}
453
501
  }
454
- catch {}
455
502
  }
456
503
  if (externalOutDir)
457
504
  return { path: resolved, external: true }
@@ -540,7 +587,7 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
540
587
  // Island code of another module may render any component of a module it imports; in its own module, only the code an island reaches.
541
588
  const emitMarkers = islands.reach.has(args.path) || (isInteractive && analysis.browserSpans)
542
589
  let islandMap: Map<string, IslandBinding> | undefined
543
- let key = `${isInteractive ? '1' : '0'}:${emitMarkers === true ? '1' : emitMarkers === false ? '0' : 's'}|t=${transforms.key}`
590
+ let key = `${env.isDev ? 'd:' : ''}${isInteractive ? '1' : '0'}:${emitMarkers === true ? '1' : emitMarkers === false ? '0' : 's'}|t=${transforms.key}`
544
591
  if (rawBindings !== undefined) {
545
592
  islandMap = new Map()
546
593
  for (const [localName, target] of rawBindings) {
@@ -560,6 +607,7 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
560
607
  islands: islandMap,
561
608
  isIsland: isInteractive,
562
609
  emitMarkers,
610
+ devSourceRoot: env.isDev ? root : undefined,
563
611
  } as Parameters<typeof compileSsr>[2])
564
612
  const code = transforms.apply(compiled.code, args.path, 'server')
565
613
  if (cache !== undefined && stamp !== undefined)
@@ -0,0 +1,11 @@
1
+ // Sizes as `prunelle.config.ts` and `--max-js` take them, kept free of imports so the CLI reads them before it loads the build.
2
+
3
+ const SIZE_RE = /^(\d+(?:\.\d+)?)\s*(kb)?$/i
4
+
5
+ /** `40kb`, `40KB` or `40960` as bytes (a KB is 1024 bytes), or `undefined` when it is not a size. */
6
+ export function parseByteSize(raw: number | string): number | undefined {
7
+ if (typeof raw === 'number')
8
+ return Number.isFinite(raw) && raw >= 0 ? raw : undefined
9
+ const match = SIZE_RE.exec(raw.trim())
10
+ return match === null ? undefined : Math.round(Number(match[1]) * (match[2] === undefined ? 1 : 1024))
11
+ }
@@ -47,7 +47,6 @@ export function writeClientEntries(env: BundleEnv, entriesDir: string, options:
47
47
  const runtimeLines: string[] = []
48
48
  if (env.islands.targets.size > 0) {
49
49
  runtimeLines.push(`import { defineIslandElement } from 'prunelle/internal/island';`)
50
- runtimeLines.push(`export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'prunelle/internal/dom';`)
51
50
  runtimeLines.push(`defineIslandElement();`)
52
51
  }
53
52
  for (const pe of pluginClientEntries)
@@ -64,12 +63,14 @@ export function writeClientEntries(env: BundleEnv, entriesDir: string, options:
64
63
 
65
64
  out.entryPoints.push(...options.standaloneCss)
66
65
 
66
+ // Each island hands the loader the DOM runtime its chunk imports anyway, so a page whose islands all wait downloads the loader alone.
67
+ const domExports = `export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'prunelle/internal/dom';\n`
67
68
  for (const [key, target] of env.islands.targets) {
68
69
  const entryPath = join(entriesDir, `${target.id}.ts`)
69
70
  const exportStmt = target.exportName === 'default'
70
71
  ? `export { default } from ${JSON.stringify(target.file)};\n`
71
72
  : `export { ${target.exportName} as default } from ${JSON.stringify(target.file)};\n`
72
- writeEntry(entryPath, exportStmt)
73
+ writeEntry(entryPath, exportStmt + domExports)
73
74
  out.entryPoints.push(entryPath)
74
75
  out.islandEntryToKey.set(entryPath, key)
75
76
  }
@@ -13,6 +13,7 @@ import { resolvePrunelleSpecifier } from './resolve'
13
13
  export const PRUNELLE_SPECIFIER_FILTER = /^prunelle(?:\/.*)?$/
14
14
  export const TS_FILTER = /\.(?:ts|tsx)$/
15
15
  const TS_LANG_RE = /\.[cm]?ts$/i
16
+ const BARREL_IMPORT_RE = /['"]prunelle['"]/
16
17
 
17
18
  export interface ClientTransforms {
18
19
  active: boolean
@@ -24,6 +25,7 @@ export interface ClientTransforms {
24
25
 
25
26
  export interface ClientPluginEnv {
26
27
  root: string
28
+ isDev: boolean
27
29
  graph: ModuleGraph
28
30
  cache: BuildCache | undefined
29
31
  actionsByFile: ActionsByFile
@@ -54,7 +56,8 @@ export function localIslandExports(targets: Iterable<{ file: string, exportName:
54
56
  * Through the barrel every island reaches every module it re-exports, and Bun then places a module only some islands use (the action runtime) in the shared chunk in one build and in the island's own chunk in the next (#3598).
55
57
  */
56
58
  export function directPrunelleImports(code: string, graph: ModuleGraph, filename = 'module.tsx'): string {
57
- if (!code.includes('prunelle'))
59
+ // Compiled DOM output imports `prunelle/internal/…` only, so it is parsed again only when the module itself imports the barrel.
60
+ if (!BARREL_IMPORT_RE.test(code))
58
61
  return code
59
62
  const barrel = resolvePrunelleSpecifier('prunelle')!
60
63
  const lang = TS_LANG_RE.test(filename) ? 'ts' : 'tsx'
@@ -114,7 +117,7 @@ export function directPrunelleImports(code: string, graph: ModuleGraph, filename
114
117
  }
115
118
 
116
119
  export function clientPlugin(env: ClientPluginEnv): BunPlugin {
117
- const { root, graph, cache, actionsByFile, transforms, leaks, localExports, clientKeep } = env
120
+ const { root, isDev, graph, cache, actionsByFile, transforms, leaks, localExports, clientKeep } = env
118
121
  return {
119
122
  name: 'prunelle-client',
120
123
  setup(b) {
@@ -151,14 +154,17 @@ export function clientPlugin(env: ClientPluginEnv): BunPlugin {
151
154
  const stamp = graph.stamp(args.path)
152
155
  const extraExports = localExports.get(args.path) ?? ''
153
156
  const keep = clientKeep.get(args.path)
154
- const key = `${transforms.key}${extraExports}${keep === undefined ? '' : `|keep=${[...keep].sort().join(',')}`}`
157
+ const key = `${isDev ? 'd:' : ''}${transforms.key}${extraExports}${keep === undefined ? '' : `|keep=${[...keep].sort().join(',')}`}`
155
158
  const cachedDom = stamp !== undefined ? cache?.domCompiled.get(args.path) : undefined
156
159
  if (cachedDom !== undefined && cachedDom.mtimeMs === stamp!.mtimeMs && cachedDom.size === stamp!.size && (cachedDom.key ?? '') === key)
157
160
  return { contents: cachedDom.code, loader: 'tsx' }
158
161
  const analysis = graph.analyses.get(args.path)
159
162
  const source = graph.source(args.path)
160
- const clientSource = keep === undefined || analysis === undefined ? source : pruneForClient(source, analysis.program, keep)
161
- const dom = compileDom(args.path, clientSource, clientSource === source ? { analysis } : {})
163
+ const clientSource = keep === undefined || analysis === undefined ? source : pruneForClient(source, analysis.program, keep, { preserveLines: isDev })
164
+ const dom = compileDom(args.path, clientSource, {
165
+ ...(clientSource === source ? { analysis } : {}),
166
+ devSourceRoot: isDev ? root : undefined,
167
+ })
162
168
  const compiled = directPrunelleImports(transforms.apply(dom.code, args.path, 'client'), graph, args.path) + extraExports
163
169
  if (cache !== undefined && stamp !== undefined)
164
170
  cache.domCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key, code: compiled })