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
package/src/dom/island.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  // Native <pru-island> Custom Element: the build defines which strategies an app uses, so the loader drops the code of the others.
2
2
 
3
- import { hydrate, mount } from './index'
4
-
3
+ import type { hydrate, mount } from './index'
5
4
 
6
5
  declare const PRUNELLE_VISIBLE: boolean | undefined
7
6
  declare const PRUNELLE_IDLE: boolean | undefined
@@ -14,7 +13,8 @@ declare const PRUNELLE_REVIVE: string | undefined
14
13
  // Only props holding a Date, Map, Set or another tagged value load the revivers: plain JSON parses with no extra file.
15
14
  const reviver = (): Promise<typeof import('./revive')> => typeof PRUNELLE_REVIVE === 'undefined' ? import('./revive') : import(PRUNELLE_REVIVE)
16
15
 
17
- type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null }
16
+ // An island chunk also re-exports the DOM runtime it imports (`writeClientEntries`), `mount` only in an app with a client-only island.
17
+ type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null, hydrate: typeof hydrate, mount?: typeof mount }
18
18
 
19
19
  /** Finds this island's own `<script type="application/json" data-pru-props>` direct child. */
20
20
  function findOwnPropsScript(root: Element): Element | null {
@@ -90,19 +90,49 @@ function replayEvent(root: Element, ev: Event, target: EventTarget | null): void
90
90
  target.dispatchEvent(clone)
91
91
  }
92
92
 
93
+ // A failed load keeps the listeners and drops the queued events: the next interaction loads the chunk again and is replayed once it is in.
94
+ function watchInteraction(root: Element, onTrigger: (after: () => void) => Promise<boolean>): () => void {
95
+ const evs = ['pointerdown', 'click', 'focusin', 'keydown']
96
+ const queued: { ev: Event, target: EventTarget | null }[] = []
97
+ let loading = false
98
+ const go = (ev: Event) => {
99
+ // Prevent native toggle/submit/navigation before hydration so replaying the click triggers it once with handlers attached.
100
+ if (ev.type === 'click')
101
+ ev.preventDefault()
102
+ queued.push({ ev, target: ev.target })
103
+ if (!loading) {
104
+ loading = true
105
+ void onTrigger(() => {
106
+ for (let i = 0; i < queued.length; i++)
107
+ replayEvent(root, queued[i]!.ev, queued[i]!.target)
108
+ }).then((ok) => {
109
+ if (!ok) {
110
+ loading = false
111
+ queued.length = 0
112
+ }
113
+ })
114
+ }
115
+ }
116
+ for (const e of evs) root.addEventListener(e, go, true)
117
+ return () => {
118
+ for (const e of evs) root.removeEventListener(e, go, true)
119
+ }
120
+ }
121
+
93
122
  function isAllowedChunkUrl(chunk: string): boolean {
94
- // A browser reads `//host` and `/\host` as another site.
95
- if (chunk[0] === '/')
96
- return chunk[1] !== '/' && chunk[1] !== '\\'
123
+ if (/[\u0000-\u0020\u007F]/.test(chunk))
124
+ return false
97
125
  if (typeof location !== 'undefined' && location.origin && location.origin !== 'null') {
98
126
  try {
99
- const parsed = new URL(chunk, location.href)
100
- return parsed.origin === location.origin
127
+ return new URL(chunk, location.href).origin === location.origin
101
128
  }
102
129
  catch {
103
130
  return false
104
131
  }
105
132
  }
133
+ // A browser reads `//host` and `/\host` as another site.
134
+ if (chunk[0] === '/')
135
+ return chunk[1] !== '/' && chunk[1] !== '\\'
106
136
  return !/^(?:javascript|data|vbscript):/i.test(chunk)
107
137
  }
108
138
 
@@ -162,10 +192,10 @@ export function defineIslandElement(): void {
162
192
  return
163
193
  }
164
194
  if ((typeof PRUNELLE_IDLE === 'undefined' || PRUNELLE_IDLE) && h === 'idle') {
165
- const g = globalThis as { requestIdleCallback?: (cb: () => void) => number, cancelIdleCallback?: (id: number) => void }
195
+ const g = globalThis as { requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number, cancelIdleCallback?: (id: number) => void }
166
196
  const run = () => void this._l(false, token)
167
197
  if (g.requestIdleCallback) {
168
- const id = g.requestIdleCallback(run)
198
+ const id = g.requestIdleCallback(run, { timeout: 2000 })
169
199
  this._c = () => g.cancelIdleCallback?.(id)
170
200
  }
171
201
  else {
@@ -175,24 +205,7 @@ export function defineIslandElement(): void {
175
205
  return
176
206
  }
177
207
  if ((typeof PRUNELLE_INTERACTION === 'undefined' || PRUNELLE_INTERACTION) && h === 'interaction') {
178
- const evs = ['pointerdown', 'click', 'focusin', 'keydown']
179
- const queued: { ev: Event, target: EventTarget | null }[] = []
180
- let loading = false
181
- const stop = () => {
182
- for (const e of evs) this.removeEventListener(e, go, true)
183
- }
184
- const go = (ev: Event) => {
185
- queued.push({ ev, target: ev.target })
186
- if (!loading) {
187
- loading = true
188
- void this._l(false, token, true, () => {
189
- for (let i = 0; i < queued.length; i++)
190
- replayEvent(this, queued[i]!.ev, queued[i]!.target)
191
- })
192
- }
193
- }
194
- for (const e of evs) this.addEventListener(e, go, true)
195
- this._c = stop
208
+ this._c = watchInteraction(this, after => this._l(false, token, true, after))
196
209
  return
197
210
  }
198
211
  if ((typeof PRUNELLE_MEDIA === 'undefined' || PRUNELLE_MEDIA) && h !== null && h.startsWith('media(')) {
@@ -227,13 +240,16 @@ export function defineIslandElement(): void {
227
240
  })
228
241
  }
229
242
 
230
- async _l(clientOnly: boolean, token: number, keepStrategy = false, after?: () => void): Promise<void> {
243
+ // Resolves false when the chunk failed to load or hydrate.
244
+ async _l(clientOnly: boolean, token: number, keepStrategy = false, after?: () => void): Promise<boolean> {
231
245
  if (!keepStrategy)
232
246
  this._clearStrategy()
233
247
  const chunk = this.getAttribute('c')
234
248
  if (!chunk || !isAllowedChunkUrl(chunk) || token !== this._t || !this.isConnected || this._d !== undefined) {
249
+ if (chunk && !isAllowedChunkUrl(chunk))
250
+ console.error(`[pru-island] refused chunk URL ${chunk}: it must be on this origin.`)
235
251
  this._clearStrategy()
236
- return
252
+ return true
237
253
  }
238
254
 
239
255
  let dispose: (() => void) | undefined
@@ -249,7 +265,7 @@ export function defineIslandElement(): void {
249
265
  mod = loaded
250
266
  if (!this.isConnected || token !== this._t || this._d !== undefined) {
251
267
  this._clearStrategy()
252
- return
268
+ return true
253
269
  }
254
270
  this._clearStrategy()
255
271
 
@@ -262,20 +278,23 @@ export function defineIslandElement(): void {
262
278
  const idPrefix = this.getAttribute('i') ?? `c${clientIslandIdSeq++}-`
263
279
  const render = () => loaded.default(props)
264
280
  dispose = (typeof PRUNELLE_CLIENT_ONLY === 'undefined' || PRUNELLE_CLIENT_ONLY) && clientOnly
265
- ? mount(this, render, idPrefix)
266
- : hydrate(this, render, idPrefix)
281
+ ? loaded.mount!(this, render, idPrefix)
282
+ : loaded.hydrate(this, render, idPrefix)
267
283
  if (!this.isConnected || token !== this._t) {
268
284
  dispose()
269
- return
285
+ return true
270
286
  }
271
287
  this._d = dispose
272
288
  after?.()
289
+ return true
273
290
  }
274
291
  catch (err) {
275
- this._clearStrategy()
292
+ if (!keepStrategy)
293
+ this._clearStrategy()
276
294
  dispose?.()
277
295
  // The chunk URL is a hash; in dev the component's own name says which island failed.
278
296
  console.error(`[pru-island] failed to hydrate ${process.env.NODE_ENV !== 'production' && mod?.default?.name ? `<${mod.default.name}> (${chunk})` : chunk}:`, err)
297
+ return false
279
298
  }
280
299
  }
281
300
  }
package/src/dom/loop.ts CHANGED
@@ -49,11 +49,10 @@ function insertRow<T>(parent: Node, row: Row<T>, anchor: Node | null): void {
49
49
  parent.insertBefore(list[i]!, anchor)
50
50
  }
51
51
 
52
- function removeRow<T>(parent: Node, row: Row<T>): void {
52
+ function removeRow<T>(row: Row<T>): void {
53
53
  const list = row.nodes
54
54
  if (list === undefined) {
55
- if (row.node !== null)
56
- parent.removeChild(row.node)
55
+ row.node?.parentNode?.removeChild(row.node)
57
56
  return
58
57
  }
59
58
  const first = list[0]!
@@ -85,11 +84,12 @@ type RenderRow<T> = (item: Signal<T>, index?: Signal<number>) => Node | Document
85
84
 
86
85
 
87
86
  // While hydrating, a row that rendered no node of its own takes the server nodes the cursor moved over since `before`.
88
- function adoptRowNodes<T>(parent: Node, marker: Node | null, row: Row<T>, before: Node | null): void {
87
+ function adoptRowNodes<T>(parent: Node, marker: Node | null, row: Row<T>, before: Node | null, prevSib: Node | null): boolean {
89
88
  const afterCursor = hydrateCursor()
90
89
  if (row.node === null && before !== null && before !== afterCursor) {
90
+ const start = before.parentNode === parent ? before : prevSib !== null ? prevSib.nextSibling : parent.firstChild
91
91
  const claimed: Node[] = []
92
- for (let n: Node | null = before; n !== null && n !== afterCursor; n = n.nextSibling) {
92
+ for (let n: Node | null = start; n !== null && n !== afterCursor && n !== marker; n = n.nextSibling) {
93
93
  if (n.nodeType === 8 && (n as Comment).data === 'k]')
94
94
  break
95
95
  claimed.push(n)
@@ -104,38 +104,48 @@ function adoptRowNodes<T>(parent: Node, marker: Node | null, row: Row<T>, before
104
104
  }
105
105
  else if (row.node !== null && row.node.parentNode !== parent) {
106
106
  insertRow(parent, row, marker)
107
+ return true
107
108
  }
109
+ return false
108
110
  }
109
111
 
110
- // Server rows past the browser's last one: the data changed between the render and hydration, so they would stay in the DOM outside `rows`.
111
- function dropServerRows(from: Node | null, marker: Node | null): void {
112
- if (process.env.NODE_ENV !== 'production' && from !== null && from !== marker) {
113
- let removed = 0
114
- for (let n: Node | null = from; n !== null && n !== marker; n = n.nextSibling)
115
- removed++
116
- console.warn(`prunelle: hydration removed ${removed} server node(s) past the list's last row: the island's data changed after the server rendered it.`)
117
- }
118
- while (from !== null && from !== marker) {
119
- const next: Node | null = from.nextSibling
120
- ;(from as ChildNode).remove()
121
- from = next
122
- }
112
+ // Server nodes no client row claimed (stepped over mid-list, or past the last row): the data changed between the render and hydration, so they would stay in the DOM outside `rows`. They are removed, and the island hears `pru:hydration-mismatch`.
113
+ function dropServerRows(parent: Node, leftover: Node[], from: Node | null, marker: Node | null, added: number): void {
114
+ for (let n = from; n !== null && n !== marker; n = n.nextSibling)
115
+ leftover.push(n)
116
+ if (leftover.length === 0 && added === 0)
117
+ return
118
+ if (process.env.NODE_ENV !== 'production')
119
+ console.warn(`prunelle: hydration mismatch in a list: removed ${leftover.length} server node(s) and added ${added} client row(s): the island's data changed after the server rendered it.`)
120
+ for (const n of leftover)
121
+ (n as ChildNode).remove()
122
+ const { CustomEvent: Mismatch } = parent.ownerDocument!.defaultView!
123
+ parent.dispatchEvent(new Mismatch('pru:hydration-mismatch', { bubbles: true, detail: { removed: leftover.length, added } }))
123
124
  }
124
125
 
125
126
  // The first rows: claimed from the server's while hydrating, else rendered into a fragment inserted at once.
126
127
  function createRows<T>(parent: Node, marker: Node | null, items: readonly T[], newRow: (item: T, index: number) => Row<T>, skip: number, startMarker: Node | null | undefined): Row<T>[] {
127
128
  const created = new Array<Row<T>>(items.length)
128
129
  let end: Node | null = null
130
+ const leftover: Node[] = []
131
+ let added = 0
129
132
  if (claimLoop(parent, () => {
130
133
  for (let i = 0; i < items.length; i++) {
131
134
  const before = hydrateCursor()
135
+ const prevSib = before?.previousSibling ?? null
132
136
  const row = newRow(items[i]!, i)
133
- adoptRowNodes(parent, marker, row, before)
137
+ // A row that claimed a node past the cursor stepped over the server nodes between.
138
+ if (before !== null && row.node !== null && row.node.parentNode === parent) {
139
+ for (let n: Node | null = before; n !== null && n !== row.node; n = n.nextSibling)
140
+ leftover.push(n)
141
+ }
142
+ if (adoptRowNodes(parent, marker, row, before, prevSib))
143
+ added++
134
144
  created[i] = row
135
145
  }
136
146
  end = hydrateCursor()
137
147
  }, skip, startMarker)) {
138
- dropServerRows(end, marker)
148
+ dropServerRows(parent, leftover, end, marker, added)
139
149
  return created
140
150
  }
141
151
  if (items.length > 0) {
@@ -239,7 +249,7 @@ export function loop<T>(
239
249
  }
240
250
  else {
241
251
  for (let i = 0; i < prevLen; i++)
242
- removeRow(parent, rows[i]!)
252
+ removeRow(rows[i]!)
243
253
  }
244
254
  rows = []
245
255
  return
@@ -309,7 +319,7 @@ export function loop<T>(
309
319
  for (let i = start; i < oldEnd; i++) {
310
320
  const row = rows[i]!
311
321
  disposeOwner(row.owner)
312
- removeRow(parent, row)
322
+ removeRow(row)
313
323
  }
314
324
  rows = keepEnds(rows, start, oldEnd, newEnd, nextLen)
315
325
  return
@@ -364,7 +374,7 @@ export function loop<T>(
364
374
  if (used[i - start] === 0) {
365
375
  const row = rows[i]!
366
376
  disposeOwner(row.owner)
367
- removeRow(parent, row)
377
+ removeRow(row)
368
378
  }
369
379
  }
370
380
 
@@ -0,0 +1,257 @@
1
+ // Drafts an editable French RGESN 2024 eco-design declaration page, shaped like the State's declaration tool, from what a build and `prunelle check` measure.
2
+
3
+ import type { BundleReport } from '../build/report'
4
+ import { mkdirSync, writeFileSync } from 'node:fs'
5
+ import { dirname, join, resolve } from 'node:path'
6
+ import { escapeAttr, escapeJsxText, formatFrenchDate, layoutRendersMain, STATEMENT_PLACEHOLDER } from '../a11y/declaration'
7
+ import { relPosix } from '../build/files'
8
+ import { fileToRoutePath } from '../build/routes'
9
+
10
+ export const DEFAULT_ECO_DECLARATION_PATH = 'src/routes/ecoconception.tsx'
11
+ const RGESN_URL = 'https://ecoresponsable.numerique.gouv.fr/publications/referentiel-general-ecoconception/'
12
+
13
+ /** What prunelle knows about an app when it drafts the declaration. */
14
+ export interface EcoFacts {
15
+ report: BundleReport
16
+ /** `prunelle check` warnings, as it prints them. */
17
+ warnings: readonly string[]
18
+ assetPrefix: string
19
+ compress: boolean
20
+ /** `budget.firstLoad` in bytes, when the config sets one. */
21
+ firstLoadBudget: number | undefined
22
+ }
23
+
24
+ export type EcoVerdict = 'Validé' | 'Non validé'
25
+
26
+ export interface EcoCriterion {
27
+ id: string
28
+ /** The criterion's wording in the RGESN 2024. */
29
+ label: string
30
+ priority: 'Prioritaire' | 'Recommandé' | 'Modéré'
31
+ /** Absent when prunelle measures part of the criterion and a person has to judge the rest. */
32
+ verdict?: EcoVerdict | undefined
33
+ evidence: string
34
+ }
35
+
36
+ export interface EcoDeclarationOptions {
37
+ root: string
38
+ /** Destination relative to `root` (or absolute). Default: `'src/routes/ecoconception.tsx'`. */
39
+ outPath?: string | undefined
40
+ facts: EcoFacts
41
+ service?: string | undefined
42
+ organization?: string | undefined
43
+ contactEmail?: string | undefined
44
+ date?: Date | undefined
45
+ /** Write the page to disk (default: `true`). */
46
+ write?: boolean | undefined
47
+ }
48
+
49
+ export interface EcoDeclarationResult {
50
+ path: string
51
+ relativePath: string
52
+ criteria: EcoCriterion[]
53
+ content: string
54
+ }
55
+
56
+ const WARNING_RE = /^(.+?):\d+:\d+: warning: \[([a-z]+\/[a-z-]+)\]/
57
+ const ABSOLUTE_URL_RE = /^(?:[a-z][a-z\d+.-]*:)?\/\//i
58
+ const frNumber = new Intl.NumberFormat('fr-FR', { maximumFractionDigits: 1 })
59
+
60
+ function ko(bytes: number): string {
61
+ return `${frNumber.format(bytes / 1000)} ko`
62
+ }
63
+
64
+ function filesWarnedFor(warnings: readonly string[], rule: string): string[] {
65
+ const files = new Set<string>()
66
+ for (const warning of warnings) {
67
+ const match = WARNING_RE.exec(warning)
68
+ if (match !== null && match[2] === rule)
69
+ files.add(match[1]!)
70
+ }
71
+ return [...files].sort()
72
+ }
73
+
74
+ function fill(what: string): string {
75
+ return `${STATEMENT_PLACEHOLDER} : ${what}]`
76
+ }
77
+
78
+ /** The RGESN 2024 criteria prunelle can judge, or measure in part, from the build, `prunelle check` and the config. */
79
+ export function evaluateEcoCriteria(facts: EcoFacts): EcoCriterion[] {
80
+ const autoplay = filesWarnedFor(facts.warnings, 'rgesn/autoplay')
81
+ const thirdParty = filesWarnedFor(facts.warnings, 'rgpd/third-party-url')
82
+ const measured = facts.report.routes.flatMap(r => r.ecoIndex === undefined ? [] : [r.ecoIndex])
83
+ const requests = Math.max(0, ...measured.map(e => e.requests))
84
+ const mostRequests = measured.length === 0 ? '' : ` La page la plus sollicitée fait ${requests} requête${requests > 1 ? 's' : ''} ;`
85
+ const total = facts.report.routes.length
86
+ const noJs = facts.report.routes.filter(r => r.jsGzip === 0).length
87
+ const assetOrigin = ABSOLUTE_URL_RE.test(facts.assetPrefix) ? facts.assetPrefix : undefined
88
+ return [
89
+ {
90
+ id: '4.1',
91
+ label: 'Le service numérique comporte-t-il uniquement des animations, vidéos et sons dont la lecture automatique est désactivée ?',
92
+ priority: 'Prioritaire',
93
+ verdict: autoplay.length === 0 ? 'Validé' : 'Non validé',
94
+ evidence: autoplay.length === 0
95
+ ? 'Aucune vidéo ni aucun son du code source ne se lance seul (prunelle check, règle rgesn/autoplay).'
96
+ : `Une lecture automatique reste dans : ${autoplay.join(', ')}.`,
97
+ },
98
+ {
99
+ id: '4.4',
100
+ label: 'Le service numérique permet-il à l\'utilisateur de décider de l\'activation d\'un service tiers ?',
101
+ priority: 'Recommandé',
102
+ verdict: thirdParty.length === 0 ? 'Validé' : 'Non validé',
103
+ evidence: thirdParty.length === 0
104
+ ? 'Aucune ressource tierce n\'est chargée avant le consentement du visiteur : chacune attend son accord (prunelle check, règle rgpd/third-party-url).'
105
+ : `Des ressources tierces se chargent sans consentement dans : ${thirdParty.join(', ')}.`,
106
+ },
107
+ {
108
+ id: '6.1',
109
+ label: 'Le service numérique s\'astreint-il à un poids maximum et une limite de requête par écran ?',
110
+ priority: 'Recommandé',
111
+ verdict: facts.firstLoadBudget === undefined ? 'Non validé' : undefined,
112
+ evidence: facts.firstLoadBudget === undefined
113
+ ? 'Aucun poids maximum par écran n\'est fixé.'
114
+ : `Le premier chargement de chaque page est plafonné à ${frNumber.format(facts.firstLoadBudget / 1024)} Kio, vérifié à chaque build.${mostRequests} ${fill('limite de requêtes par écran')}.`,
115
+ },
116
+ {
117
+ id: '6.3',
118
+ label: 'Le service numérique a-t-il mis en place des techniques de compression pour les ressources transférées dont il a le contrôle ?',
119
+ priority: 'Modéré',
120
+ verdict: facts.compress ? 'Validé' : 'Non validé',
121
+ evidence: facts.compress
122
+ ? 'Le JavaScript et les feuilles de style sont minifiés ; les fichiers sont précompressés en brotli et gzip au build, et les réponses dynamiques compressées à l\'envoi.'
123
+ : `La compression du serveur est désactivée (compress: false) ; ${fill('compression assurée en amont, le cas échéant')}.`,
124
+ },
125
+ {
126
+ id: '6.5',
127
+ label: 'Le service numérique évite-t-il de déclencher le chargement de ressources et de contenus inutilisés pour chaque fonctionnalité ?',
128
+ priority: 'Recommandé',
129
+ evidence: `${noJs === total ? 'Aucune page n\'envoie de JavaScript.' : `${noJs} page${noJs <= 1 ? '' : 's'} sur ${total} n'${noJs <= 1 ? 'envoie' : 'envoient'} aucun JavaScript ; les autres ne chargent que le code de leurs composants interactifs.`} ${fill('images, polices et données chargées sans être affichées')}.`,
130
+ },
131
+ {
132
+ id: '6.7',
133
+ label: 'Le service numérique héberge-t-il toutes les ressources statiques transférées dont il est l\'émetteur sur un même domaine ?',
134
+ priority: 'Modéré',
135
+ verdict: assetOrigin === undefined ? 'Validé' : 'Non validé',
136
+ evidence: assetOrigin === undefined
137
+ ? 'Les scripts, feuilles de style, polices et images sont servis par le domaine des pages.'
138
+ : `Les scripts et feuilles de style sont servis depuis ${assetOrigin}, un autre domaine que celui des pages.`,
139
+ },
140
+ ]
141
+ }
142
+
143
+ function measuresSection(report: BundleReport): string {
144
+ const rows = report.routes.flatMap((r) => {
145
+ const e = r.ecoIndex
146
+ if (e === undefined)
147
+ return []
148
+ const url = e.url ?? r.path
149
+ return [` <tr><th scope="row"><code>${escapeJsxText(url)}</code></th><td>${e.grade} (${e.score})</td><td>${ko(e.weightBytes)}</td><td>${e.requests}</td><td>${frNumber.format(e.ghgGrams)}</td><td>${frNumber.format(e.waterCl)}</td></tr>`]
150
+ })
151
+ if (rows.length === 0)
152
+ return ` <p>${fill('mesures des pages représentatives : aucune page n\'est prérendue, prunelle n\'a rien mesuré')}</p>`
153
+ return [
154
+ ' <table>',
155
+ ' <caption>EcoIndex de chaque page prérendue, mesuré par prunelle build, avec les gaz à effet de serre (gCO2e) et l\'eau (cl) d\'une visite</caption>',
156
+ ' <thead>',
157
+ ' <tr><th scope="col">Page</th><th scope="col">EcoIndex</th><th scope="col">Poids</th><th scope="col">Requêtes</th><th scope="col">GES</th><th scope="col">Eau</th></tr>',
158
+ ' </thead>',
159
+ ' <tbody>',
160
+ ...rows,
161
+ ' </tbody>',
162
+ ' </table>',
163
+ ].join('\n')
164
+ }
165
+
166
+ function criteriaSections(criteria: readonly EcoCriterion[]): string {
167
+ return criteria.map(c => [
168
+ ` <h3>${c.id}. ${escapeJsxText(c.label)}</h3>`,
169
+ ' <dl>',
170
+ ` <dt>Priorité</dt><dd>${c.priority}</dd>`,
171
+ ` <dt>Évaluation</dt><dd>${escapeJsxText(c.verdict ?? fill('Validé, Non validé ou Non applicable'))}</dd>`,
172
+ ` <dt>Justification</dt><dd>${escapeJsxText(c.evidence)}</dd>`,
173
+ ' </dl>',
174
+ ].join('\n')).join('\n')
175
+ }
176
+
177
+ /** Generates (and by default writes) a draft RGESN 2024 eco-design declaration page in TSX. */
178
+ export function draftEcoDeclaration(options: EcoDeclarationOptions): EcoDeclarationResult {
179
+ const root = resolve(options.root)
180
+ const dest = resolve(root, options.outPath ?? DEFAULT_ECO_DECLARATION_PATH)
181
+ const relativePath = relPosix(root, dest)
182
+ // A second run finds the declaration among the built pages: it is not part of the service it describes.
183
+ const ownPath = fileToRoutePath(join(root, 'src/routes'), dest)
184
+ const report = { ...options.facts.report, routes: options.facts.report.routes.filter(r => r.path !== ownPath) }
185
+ const criteria = evaluateEcoCriteria({ ...options.facts, report })
186
+ const { iso, human } = formatFrenchDate(options.date ?? new Date())
187
+ const service = options.service?.trim() || fill('nom du service')
188
+ const org = options.organization?.trim() || fill('entité qui procède à l\'évaluation')
189
+ const contact = options.contactEmail?.trim()
190
+ const pages = report.routes.map(r => r.ecoIndex?.url ?? r.path)
191
+ const wrapper = layoutRendersMain(root, dest) ? 'article' : 'main'
192
+
193
+ const content = `// Brouillon de déclaration d'écoconception RGESN 2024 généré par \`prunelle eco --declaration\`.
194
+ // prunelle évalue les critères qu'il mesure ; les autres, et chaque mention entre crochets, sont à compléter avant publication : \`prunelle check\` signale celles qui restent.
195
+
196
+ import { Head } from 'prunelle'
197
+
198
+ export const prerender = true
199
+
200
+ export default function Ecoconception() {
201
+ return (
202
+ <>
203
+ <Head>
204
+ <title>Déclaration d'écoconception</title>
205
+ </Head>
206
+ <${wrapper} lang="fr">
207
+ <h1>Déclaration d'écoconception</h1>
208
+ <p>
209
+ <strong>${escapeJsxText(service)}</strong> s'inscrit dans une démarche d'écoconception visant à réduire ses impacts environnementaux.
210
+ Cette déclaration suit le <a href="${RGESN_URL}">référentiel général de l'écoconception des services numériques</a> (RGESN, version 2024).
211
+ </p>
212
+ <dl>
213
+ <dt>Service évalué</dt>
214
+ <dd>${escapeJsxText(service)}</dd>
215
+ <dt>Échantillon de pages</dt>
216
+ <dd>${escapeJsxText(pages.length > 0 ? pages.join(', ') : fill('pages représentatives des fonctionnalités principales'))}</dd>
217
+ <dt>Entité qui procède à l'évaluation</dt>
218
+ <dd>${escapeJsxText(org)}</dd>
219
+ <dt>Responsable de l'évaluation</dt>
220
+ <dd>${escapeJsxText(fill('nom du ou de la référente en écoconception'))}</dd>
221
+ <dt>Contact</dt>
222
+ <dd>${contact ? `<a href="mailto:${escapeAttr(contact)}">${escapeJsxText(contact)}</a>` : escapeJsxText(fill('adresse de contact'))}</dd>
223
+ <dt>Date de l'évaluation</dt>
224
+ <dd><time dateTime="${iso}">${human}</time></dd>
225
+ <dt>Score global</dt>
226
+ <dd>${escapeJsxText(fill('part des critères applicables validés, en %'))}</dd>
227
+ <dt>Profil matériel minimum</dt>
228
+ <dd>${escapeJsxText(fill('plus ancien terminal et navigateur sur lesquels le service fonctionne'))}</dd>
229
+ </dl>
230
+
231
+ <section>
232
+ <h2>Mesures</h2>
233
+ ${measuresSection(report)}
234
+ </section>
235
+
236
+ <section>
237
+ <h2>Objectifs et plan d'action</h2>
238
+ <p>${escapeJsxText(fill('objectifs de réduction des impacts, actions envisagées et fréquence des revues'))}</p>
239
+ </section>
240
+
241
+ <section>
242
+ <h2>Critères évalués</h2>
243
+ ${criteriaSections(criteria)}
244
+ <p>${escapeJsxText(fill('évaluation des autres critères applicables du RGESN 2024, avec leur justification'))}</p>
245
+ </section>
246
+ </${wrapper}>
247
+ </>
248
+ )
249
+ }
250
+ `
251
+
252
+ if (options.write !== false) {
253
+ mkdirSync(dirname(dest), { recursive: true })
254
+ writeFileSync(dest, content)
255
+ }
256
+ return { path: dest, relativePath, criteria, content }
257
+ }
@@ -0,0 +1,65 @@
1
+ // `prunelle eco`: builds the app, then judges the RGESN 2024 criteria prunelle can measure and, with --declaration, drafts the declaration page.
2
+
3
+ import type { BundleReport } from '../build/report'
4
+ import type { EcoCriterion, EcoDeclarationResult, EcoFacts } from './declaration'
5
+ import { parseByteSize } from '../build/byte-size'
6
+ import { loadConfig } from '../plugins/load'
7
+ import { DEFAULT_ECO_DECLARATION_PATH, draftEcoDeclaration, evaluateEcoCriteria } from './declaration'
8
+
9
+ export { DEFAULT_ECO_DECLARATION_PATH, draftEcoDeclaration, evaluateEcoCriteria } from './declaration'
10
+ export type { EcoCriterion, EcoDeclarationOptions, EcoDeclarationResult, EcoFacts, EcoVerdict } from './declaration'
11
+
12
+ export interface EcoRunOptions {
13
+ root: string
14
+ /** Write the declaration page, at this path (`''` for `src/routes/ecoconception.tsx`). */
15
+ declaration?: string | undefined
16
+ service?: string | undefined
17
+ organization?: string | undefined
18
+ contactEmail?: string | undefined
19
+ }
20
+
21
+ export interface EcoRunResult {
22
+ criteria: EcoCriterion[]
23
+ declaration?: EcoDeclarationResult | undefined
24
+ }
25
+
26
+ export async function collectEcoFacts(root: string): Promise<EcoFacts> {
27
+ const { build } = await import('../build/index')
28
+ const { checkProject } = await import('../cli/check')
29
+ let report: BundleReport = { routes: [], totalJsGzip: 0, totalCssGzip: 0, topModules: [] }
30
+ await build({ root, onAnalyze: (built) => { report = built } })
31
+ const { warnings } = await checkProject(root, { skipTypecheck: true })
32
+ const config = await loadConfig(root)
33
+ return {
34
+ report,
35
+ warnings,
36
+ assetPrefix: config.assetPrefix ?? '/_pru',
37
+ compress: config.compress !== false,
38
+ firstLoadBudget: config.budget?.firstLoad === undefined ? undefined : parseByteSize(config.budget.firstLoad),
39
+ }
40
+ }
41
+
42
+ export async function runEco(options: EcoRunOptions): Promise<EcoRunResult> {
43
+ const facts = await collectEcoFacts(options.root)
44
+ if (options.declaration === undefined)
45
+ return { criteria: evaluateEcoCriteria(facts) }
46
+ const declaration = draftEcoDeclaration({
47
+ root: options.root,
48
+ outPath: options.declaration === '' ? DEFAULT_ECO_DECLARATION_PATH : options.declaration,
49
+ facts,
50
+ service: options.service,
51
+ organization: options.organization,
52
+ contactEmail: options.contactEmail,
53
+ })
54
+ return { criteria: declaration.criteria, declaration }
55
+ }
56
+
57
+ export function formatEcoResult(result: EcoRunResult): string {
58
+ const lines = ['prunelle eco: the RGESN 2024 criteria prunelle can judge from the build, prunelle check and the config']
59
+ for (const c of result.criteria)
60
+ lines.push(` ${c.id.padEnd(4)} ${(c.verdict ?? 'to judge').padEnd(10)} ${c.evidence}`)
61
+ lines.push(result.declaration === undefined
62
+ ? 'The other criteria are for a person to judge: prunelle eco --declaration drafts the page that holds them all.'
63
+ : `prunelle eco: drafted the RGESN 2024 eco-design declaration at ${result.declaration.relativePath}: fill in each [à compléter ...] before publishing it.`)
64
+ return lines.join('\n')
65
+ }
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { Catch, ConsentGate, createContext, Head, provideContext, Region, Suspense, useContext, useId } from './context'
2
- export type { CatchProps, ConsentGateProps, Context, RegionProps } from './context'
1
+ export { Catch, ConsentBanner, ConsentGate, ConsentPreferences, createContext, Head, provideContext, Region, Suspense, useContext, useId } from './context'
2
+ export type { CatchProps, ConsentBannerProps, ConsentGateProps, ConsentTexts, Context, RegionProps } from './context'
3
3
  export {
4
4
  batch,
5
5
  computed,
@@ -35,11 +35,11 @@ export function Fragment(props: { children?: PrunelleChild }): PrunelleChild {
35
35
  return props.children
36
36
  }
37
37
 
38
- // Runtime fallbacks (only used if JSX isn't compiled, e.g. quick tests)
38
+ // Only a component call reaches this: prunelle's compiler turns every element into HTML or DOM calls, so an element here means the file skipped it.
39
39
  export function jsx(tag: unknown, props: Record<string, unknown>): PrunelleChild | Promise<PrunelleChild> {
40
40
  if (typeof tag === 'function')
41
41
  return (tag as Component)(props)
42
- return null
42
+ throw new Error(`prunelle: <${String(tag)}> reached the JSX runtime, so this file was not compiled by prunelle: run it with prunelle dev, build or prunelle/test, and check that nothing else (a bundler, a test runner, a tsconfig \`jsxImportSource\`) compiles the TSX first.`)
43
43
  }
44
44
 
45
45
  export const jsxs = jsx