prunelle 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +61 -44
- package/package.json +7 -2
- package/src/a11y/declaration.ts +6 -10
- package/src/a11y/index.ts +69 -125
- package/src/animate.ts +127 -0
- package/src/build/asides.ts +51 -0
- package/src/build/bundle.ts +88 -134
- package/src/build/client-entries.ts +6 -6
- package/src/build/client-outputs.ts +75 -0
- package/src/build/client-plugin.ts +9 -4
- package/src/build/ecoindex.ts +4 -2
- package/src/build/files.ts +18 -0
- package/src/build/graph.ts +14 -6
- package/src/build/index.ts +20 -10
- package/src/build/islands.ts +4 -1
- package/src/build/key-types.ts +31 -0
- package/src/build/manifest.ts +19 -1
- package/src/build/plugin-host.ts +2 -0
- package/src/build/prerender.ts +2 -2
- package/src/build/reach.ts +14 -1
- package/src/build/report.ts +1 -1
- package/src/build/route-types.ts +16 -0
- package/src/build/routes.ts +24 -15
- package/src/build/seed-ids.ts +65 -0
- package/src/build/seed-writes.ts +111 -0
- package/src/build/static-headers.ts +2 -2
- package/src/build/static.ts +1 -1
- package/src/cli/check-cache.ts +51 -0
- package/src/cli/check-consent.ts +95 -0
- package/src/cli/check-forms.ts +2 -2
- package/src/cli/check-links-patterns.ts +101 -0
- package/src/cli/check-links.ts +16 -100
- package/src/cli/check-regions.ts +185 -0
- package/src/cli/check-security.ts +50 -6
- package/src/cli/check.ts +40 -18
- package/src/cli/commands.ts +134 -14
- package/src/cli/docs.ts +21 -2
- package/src/cli/index.ts +1 -1
- package/src/cli/inspect.ts +2 -0
- package/src/cli/mcp-tools.ts +2 -2
- package/src/cli/new.ts +9 -5
- package/src/cli/upgrade-names.ts +14 -2
- package/src/cli/upgrade.ts +3 -0
- package/src/compiler/analyze.ts +2 -2
- package/src/compiler/cacheability.ts +24 -2
- package/src/compiler/compliance-contrast.ts +284 -0
- package/src/compiler/compliance-empty.ts +24 -0
- package/src/compiler/compliance-rgaa-content.ts +95 -0
- package/src/compiler/compliance-rgaa-criteria.ts +45 -0
- package/src/compiler/compliance-rgaa-pages.ts +140 -0
- package/src/compiler/compliance-rgaa.ts +19 -0
- package/src/compiler/compliance-third-party.ts +59 -0
- package/src/compiler/compliance-urls.ts +52 -0
- package/src/compiler/compliance.ts +70 -42
- package/src/compiler/cookie-inventory.ts +119 -0
- package/src/compiler/foreign-imports.ts +5 -3
- package/src/compiler/mistakes.ts +18 -9
- package/src/compiler/props-pattern.ts +211 -0
- package/src/compiler/props.ts +177 -346
- package/src/compiler/ssr-emit.ts +510 -0
- package/src/compiler/ssr-helpers.ts +170 -121
- package/src/compiler/ssr.ts +25 -440
- package/src/context.ts +14 -1
- package/src/dev/child.ts +1 -1
- package/src/dev/hot-islands.ts +71 -0
- package/src/dev/index.ts +31 -18
- package/src/dev/protocol.ts +1 -1
- package/src/dev/queue.ts +3 -2
- package/src/dev/reload.ts +1 -1
- package/src/dev/supervisor.ts +3 -1
- package/src/dev/watchers.ts +6 -2
- package/src/dom/action.ts +97 -14
- package/src/dom/extras.ts +2 -1
- package/src/dom/field-marks.ts +24 -0
- package/src/dom/hot.ts +9 -0
- package/src/dom/index.ts +25 -5
- package/src/dom/island-hot.ts +29 -0
- package/src/dom/island.ts +13 -2
- package/src/dom/prefetch.ts +132 -0
- package/src/dom/regions.ts +498 -0
- package/src/dom/swap.ts +245 -0
- package/src/dom/trusted.ts +22 -0
- package/src/dom/upload.ts +44 -0
- package/src/eco/declaration.ts +39 -40
- package/src/eco/index.ts +5 -5
- package/src/href.ts +31 -0
- package/src/index.ts +9 -3
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +7 -1
- package/src/plugins/daily.ts +27 -0
- package/src/plugins/index.ts +3 -3
- package/src/plugins/order.ts +1 -1
- package/src/plugins/public.ts +8 -5
- package/src/plugins/services.ts +88 -14
- package/src/plugins/types.ts +120 -9
- package/src/reactivity/hmr.ts +90 -0
- package/src/reactivity/index.ts +38 -18
- package/src/reactivity/resource.ts +115 -0
- package/src/reactivity/seed.ts +39 -0
- package/src/reactivity/server-seed.ts +194 -0
- package/src/reactivity/store.ts +55 -1
- package/src/rgpd/draft.ts +171 -0
- package/src/rgpd/forms.ts +85 -0
- package/src/rgpd/index.ts +57 -0
- package/src/server/action-flash.ts +1 -0
- package/src/server/action-registry.ts +6 -8
- package/src/server/action.ts +51 -19
- package/src/server/app-secret.ts +14 -8
- package/src/server/cache-invalidation.ts +96 -0
- package/src/server/compress.ts +3 -1
- package/src/server/consent.ts +16 -2
- package/src/server/cookie-inventory.ts +78 -0
- package/src/server/cookies.ts +50 -0
- package/src/server/csp-report.ts +86 -0
- package/src/server/discard.ts +13 -0
- package/src/server/document.ts +2 -2
- package/src/server/env.ts +1 -1
- package/src/server/errors.ts +9 -2
- package/src/server/field-errors.ts +91 -0
- package/src/server/form-schema.ts +16 -11
- package/src/server/health.ts +33 -12
- package/src/server/http.ts +25 -10
- package/src/server/index.ts +101 -298
- package/src/server/loader.ts +1 -0
- package/src/server/page.ts +3 -9
- package/src/server/plugin-host.ts +26 -8
- package/src/server/public.ts +14 -3
- package/src/server/rate-limit.ts +39 -10
- package/src/server/region.ts +3 -0
- package/src/server/request-handler.ts +370 -0
- package/src/server/request-log.ts +94 -0
- package/src/server/route-cache.ts +41 -6
- package/src/server/route-input.ts +54 -0
- package/src/server/route-table.ts +35 -19
- package/src/server/routing.ts +12 -11
- package/src/server/sanitize-html.ts +1 -1
- package/src/server/security.ts +38 -8
- package/src/server/serve-handlers.ts +9 -5
- package/src/server/shared-store.ts +314 -0
- package/src/server/start.ts +12 -5
- package/src/server/static-dir.ts +14 -10
- package/src/server/stream.ts +2 -1
- package/src/server/surface.ts +39 -0
- package/src/server/webhook.ts +48 -0
- package/src/server/workers.ts +168 -0
- package/src/ssr/consent-banner.ts +20 -16
- package/src/ssr/consent-texts.ts +40 -0
- package/src/ssr/context.ts +26 -3
- package/src/ssr/cookie-table.ts +75 -0
- package/src/ssr/index.ts +23 -13
- package/src/ssr/navigation.ts +161 -14
- package/src/test/browser.ts +50 -22
- package/src/test/build-reuse.ts +70 -0
- package/src/test/index.ts +45 -6
- package/src/test/mount.ts +53 -0
- package/src/test/outside.ts +94 -0
- package/templates/_shared/AGENTS.md +1 -1
- package/templates/_shared/Dockerfile +22 -0
- package/templates/_shared/dockerignore +9 -0
- package/templates/_shared/gitignore +2 -0
- package/templates/app/.env.example +3 -1
- package/templates/app/compose.yaml +32 -0
- package/templates/app/db/migrations/001_notes.sql +7 -0
- package/templates/app/db/schema.ts +11 -0
- package/templates/app/package.json +1 -0
- package/templates/app/prunelle.config.ts +6 -0
- package/templates/app/src/actions/notes.ts +26 -0
- package/templates/app/src/auth.ts +4 -2
- package/templates/app/src/db.ts +5 -0
- package/templates/app/src/routes/dashboard/index.tsx +26 -1
- package/templates/app/src/routes/privacy.tsx +6 -2
- package/templates/app/tests/app.test.ts +14 -3
- package/templates/plugin/AGENTS.md +11 -0
- package/templates/plugin/CLAUDE.md +1 -0
- package/templates/plugin/README.md +27 -0
- package/templates/plugin/gitignore +2 -0
- package/templates/plugin/llms.txt +19 -0
- package/templates/plugin/package.json +33 -0
- package/templates/plugin/src/index.ts +40 -0
- package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
- package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
- package/templates/plugin/tests/plugin.test.ts +42 -0
- package/templates/plugin/tsconfig.json +19 -0
- package/ts-plugin.cjs +3674 -2196
package/src/dom/swap.ts
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// What a region swap and a whole-page `@prunellejs/spa` swap share: view transitions, scroll restoration, live announcements, and `Element.moveBefore`-based `[data-persist]` preservation.
|
|
2
|
+
// An element with `data-pru-keep-scroll="<key>"` keeps its offset by key; a `<Region>` that scrolls itself is remembered per entry as `region:<name>`.
|
|
3
|
+
|
|
4
|
+
import { getDocId } from './prefetch'
|
|
5
|
+
|
|
6
|
+
// Kept apart from `dom/trusted.ts` so island pages without `<Region>` never download a shared Trusted Types chunk.
|
|
7
|
+
interface HtmlPolicy { createHTML: (html: string) => string }
|
|
8
|
+
let htmlPolicy: HtmlPolicy | undefined
|
|
9
|
+
|
|
10
|
+
export function trustedHtml(html: string): string {
|
|
11
|
+
if (htmlPolicy === undefined) {
|
|
12
|
+
const pass: HtmlPolicy = { createHTML: s => s }
|
|
13
|
+
try {
|
|
14
|
+
htmlPolicy = (globalThis as { trustedTypes?: { createPolicy: (name: string, rules: HtmlPolicy) => HtmlPolicy } }).trustedTypes?.createPolicy('prunelle', pass) ?? pass
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
htmlPolicy = pass
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return htmlPolicy.createHTML(html)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface EntryScroll { y: number, k: Record<string, number> }
|
|
24
|
+
|
|
25
|
+
const SCROLLERS = '[data-pru-keep-scroll],[data-pru-region]'
|
|
26
|
+
const PERSIST = '[data-persist]'
|
|
27
|
+
|
|
28
|
+
const keyOf = (el: Element): string => el.getAttribute('data-pru-keep-scroll') ?? `region:${el.getAttribute('data-pru-region')}`
|
|
29
|
+
|
|
30
|
+
/** The offsets of the elements that keep theirs; `regions` adds the scrolled `<Region>`s, which a swap resets and a history entry restores. */
|
|
31
|
+
export function readScrolls(regions: boolean): Record<string, number> {
|
|
32
|
+
const out: Record<string, number> = {}
|
|
33
|
+
for (const el of document.querySelectorAll(SCROLLERS)) {
|
|
34
|
+
if (el.hasAttribute('data-pru-keep-scroll') || (regions && el.scrollTop > 0))
|
|
35
|
+
out[keyOf(el)] = el.scrollTop
|
|
36
|
+
}
|
|
37
|
+
return out
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function writeScrolls(offsets: Record<string, number>): void {
|
|
41
|
+
for (const el of document.querySelectorAll(SCROLLERS)) {
|
|
42
|
+
const top = offsets[keyOf(el)]
|
|
43
|
+
if (top !== undefined)
|
|
44
|
+
el.scrollTop = top
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function entryScroll(state: unknown): EntryScroll | undefined {
|
|
49
|
+
const saved = typeof state === 'object' && state !== null ? (state as { __pruScroll?: EntryScroll }).__pruScroll : undefined
|
|
50
|
+
return typeof saved?.y === 'number' ? saved : undefined
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function restoreScroll(saved: EntryScroll): void {
|
|
54
|
+
writeScrolls(saved.k)
|
|
55
|
+
window.scrollTo(0, saved.y)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Writes the page's scroll into the current history entry, so back and forward can return to it. */
|
|
59
|
+
export function saveScroll(): void {
|
|
60
|
+
try {
|
|
61
|
+
const prev = typeof history.state === 'object' && history.state !== null ? history.state as Record<string, unknown> : {}
|
|
62
|
+
history.replaceState({ ...prev, __pruDoc: getDocId(), __pruScroll: { y: window.scrollY, k: readScrolls(true) } satisfies EntryScroll }, '')
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// Restricted history API environments (e.g. sandboxed iframes) refuse state updates: the entry keeps no scroll.
|
|
66
|
+
return
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const trackedDocs = new WeakSet<Document>()
|
|
71
|
+
|
|
72
|
+
/** Keeps the current entry's scroll up to date once the page stops scrolling, as a swap by back or forward has no earlier moment to read it. */
|
|
73
|
+
export function trackScroll(): void {
|
|
74
|
+
if (typeof document === 'undefined' || trackedDocs.has(document))
|
|
75
|
+
return
|
|
76
|
+
trackedDocs.add(document)
|
|
77
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
78
|
+
document.addEventListener('scroll', () => {
|
|
79
|
+
clearTimeout(timer)
|
|
80
|
+
timer = setTimeout(saveScroll, 150)
|
|
81
|
+
}, { capture: true, passive: true })
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const ANNOUNCER_ID = '__pru-spa-announcer'
|
|
85
|
+
|
|
86
|
+
function applySrOnlyStyle(el: HTMLElement): void {
|
|
87
|
+
const s = el.style
|
|
88
|
+
s.position = 'absolute'
|
|
89
|
+
s.width = '1px'
|
|
90
|
+
s.height = '1px'
|
|
91
|
+
s.padding = '0'
|
|
92
|
+
s.margin = '-1px'
|
|
93
|
+
s.overflow = 'hidden'
|
|
94
|
+
s.clip = 'rect(0,0,0,0)'
|
|
95
|
+
s.whiteSpace = 'nowrap'
|
|
96
|
+
s.border = '0'
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// A screen reader speaks a live region's change only once the region is in the page, and only when its text differs:
|
|
100
|
+
// the region is emptied now and filled on the next frame, so a new region, a moved one and a repeated title are all heard.
|
|
101
|
+
export function announce(text: string): void {
|
|
102
|
+
let region = document.getElementById(ANNOUNCER_ID)
|
|
103
|
+
if (region === null) {
|
|
104
|
+
region = document.createElement('div')
|
|
105
|
+
region.id = ANNOUNCER_ID
|
|
106
|
+
region.setAttribute('role', 'status')
|
|
107
|
+
region.setAttribute('aria-live', 'polite')
|
|
108
|
+
region.setAttribute('aria-atomic', 'true')
|
|
109
|
+
applySrOnlyStyle(region)
|
|
110
|
+
document.body.appendChild(region)
|
|
111
|
+
}
|
|
112
|
+
region.textContent = ''
|
|
113
|
+
requestAnimationFrame(() => {
|
|
114
|
+
region.textContent = text
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The outermost `[data-persist]` elements under `root` by key (a nested one moves with its own), and a key found on two of them. */
|
|
119
|
+
export function persistedIn(root: ParentNode & Node): { byKey: Map<string, Element>, twice: string | undefined } {
|
|
120
|
+
const byKey = new Map<string, Element>()
|
|
121
|
+
let twice: string | undefined
|
|
122
|
+
for (const el of root.querySelectorAll(PERSIST)) {
|
|
123
|
+
const outer = el.parentElement?.closest(PERSIST)
|
|
124
|
+
const key = el.getAttribute('data-persist')
|
|
125
|
+
if (key === null || key === '' || (outer !== null && outer !== undefined && root.contains(outer)))
|
|
126
|
+
continue
|
|
127
|
+
if (byKey.has(key))
|
|
128
|
+
twice ??= key
|
|
129
|
+
byKey.set(key, el)
|
|
130
|
+
}
|
|
131
|
+
return { byKey, twice }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
type Movable = ParentNode & { moveBefore?: (node: Node, child: Node | null) => void }
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Replaces `container`'s children with `content`, preserving each live `[data-persist]` element in the place of
|
|
138
|
+
* the incoming element with the same key. Uses `Element.moveBefore` when available so focused fields keep focus/caret
|
|
139
|
+
* and iframes/media keep state; falls back to `insertBefore` with focus and selection restoration.
|
|
140
|
+
*/
|
|
141
|
+
export function replaceKeeping(container: HTMLElement, content: DocumentFragment, keep?: ReadonlySet<Node>): void {
|
|
142
|
+
const incoming = persistedIn(content).byKey
|
|
143
|
+
const live = persistedIn(container).byKey
|
|
144
|
+
const old = [...container.childNodes]
|
|
145
|
+
container.append(content)
|
|
146
|
+
const focused = document.activeElement
|
|
147
|
+
const field = focused instanceof HTMLInputElement || focused instanceof HTMLTextAreaElement ? focused : undefined
|
|
148
|
+
const selection = field?.selectionStart == null ? undefined : [field.selectionStart, field.selectionEnd ?? field.selectionStart, field.selectionDirection ?? 'none'] as const
|
|
149
|
+
const preserved = new Set<Node>(keep)
|
|
150
|
+
let refocus = false
|
|
151
|
+
for (const [key, el] of live) {
|
|
152
|
+
const slot = incoming.get(key)
|
|
153
|
+
const parent = slot?.parentNode as Movable | null | undefined
|
|
154
|
+
if (slot === undefined || parent === null || parent === undefined)
|
|
155
|
+
continue
|
|
156
|
+
preserved.add(el)
|
|
157
|
+
if (typeof parent.moveBefore === 'function') {
|
|
158
|
+
parent.moveBefore(el, slot)
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
refocus ||= focused !== null && el.contains(focused)
|
|
162
|
+
parent.insertBefore(el, slot)
|
|
163
|
+
}
|
|
164
|
+
slot.remove()
|
|
165
|
+
}
|
|
166
|
+
for (const node of old) {
|
|
167
|
+
if (!preserved.has(node))
|
|
168
|
+
node.remove()
|
|
169
|
+
}
|
|
170
|
+
if (refocus && focused instanceof HTMLElement && document.activeElement !== focused) {
|
|
171
|
+
focused.focus({ preventScroll: true })
|
|
172
|
+
if (field !== undefined && selection !== undefined)
|
|
173
|
+
field.setSelectionRange(...selection)
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Copies attributes from `source` to `target`, removing attributes absent on `source`. */
|
|
178
|
+
export function syncElementAttrs(target: Element, source: Element): void {
|
|
179
|
+
for (const attr of [...target.attributes]) {
|
|
180
|
+
if (!source.hasAttribute(attr.name))
|
|
181
|
+
target.removeAttribute(attr.name)
|
|
182
|
+
}
|
|
183
|
+
for (const attr of source.attributes) {
|
|
184
|
+
if (target.getAttribute(attr.name) !== attr.value)
|
|
185
|
+
target.setAttribute(attr.name, attr.value)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
interface Transition { updateCallbackDone: Promise<void>, ready: Promise<void>, finished: Promise<void>, skipTransition: () => void }
|
|
190
|
+
type Transitions = Document & { startViewTransition?: (update: () => void) => Transition }
|
|
191
|
+
|
|
192
|
+
let running: Transition | undefined
|
|
193
|
+
const transitionDocs = new WeakSet<Document>()
|
|
194
|
+
|
|
195
|
+
// While a view transition runs, Chrome hit-tests every click to <html>: the click skips the transition and goes to what is under the pointer once it ends.
|
|
196
|
+
function retargetClick(event: MouseEvent): void {
|
|
197
|
+
const transition = running
|
|
198
|
+
if (transition === undefined || event.target !== document.documentElement || event.detail === 0 || event.button !== 0)
|
|
199
|
+
return
|
|
200
|
+
event.preventDefault()
|
|
201
|
+
event.stopImmediatePropagation()
|
|
202
|
+
const { clientX, clientY } = event
|
|
203
|
+
// A skipped transition rejects `ready` with AbortError.
|
|
204
|
+
void transition.ready.catch((err) => {
|
|
205
|
+
if (!(err instanceof DOMException && err.name === 'AbortError'))
|
|
206
|
+
console.error('[prunelle] view transition failed:', err)
|
|
207
|
+
})
|
|
208
|
+
transition.skipTransition()
|
|
209
|
+
const resend = (): void => {
|
|
210
|
+
const under = document.elementFromPoint(clientX, clientY)
|
|
211
|
+
if (under instanceof HTMLElement && under !== document.documentElement)
|
|
212
|
+
under.click()
|
|
213
|
+
}
|
|
214
|
+
void transition.finished.then(resend, resend)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// `navigation: { viewTransitions: false }` leaves the `@view-transition` rule out of every page: swaps follow what the page says.
|
|
218
|
+
function pageAnimates(): boolean {
|
|
219
|
+
for (const style of document.head.querySelectorAll('style')) {
|
|
220
|
+
if (style.textContent?.includes('@view-transition'))
|
|
221
|
+
return true
|
|
222
|
+
}
|
|
223
|
+
return false
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Runs the DOM `update` inside a view transition where the browser has them, the app keeps them and the user allows motion; resolves once it ran. */
|
|
227
|
+
export async function swapInTransition(update: () => void, animate = true): Promise<void> {
|
|
228
|
+
const doc = document as Transitions
|
|
229
|
+
if (!animate || typeof doc.startViewTransition !== 'function' || matchMedia('(prefers-reduced-motion: reduce)').matches || !pageAnimates()) {
|
|
230
|
+
update()
|
|
231
|
+
return
|
|
232
|
+
}
|
|
233
|
+
if (!transitionDocs.has(document)) {
|
|
234
|
+
transitionDocs.add(document)
|
|
235
|
+
document.addEventListener('click', retargetClick, true)
|
|
236
|
+
}
|
|
237
|
+
const transition = doc.startViewTransition(update)
|
|
238
|
+
running = transition
|
|
239
|
+
const done = (): void => {
|
|
240
|
+
if (running === transition)
|
|
241
|
+
running = undefined
|
|
242
|
+
}
|
|
243
|
+
void transition.finished.then(done, done)
|
|
244
|
+
await transition.updateCallbackDone
|
|
245
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Every HTML string prunelle and its plugins write into the page goes through one Trusted Types policy, so the default CSP (`require-trusted-types-for 'script'`) can refuse the strings app code writes itself.
|
|
2
|
+
// The policy passes the string through: what it covers is HTML the app asked for in so many words (`innerHTML={html}`, a compiled template, a region swap).
|
|
3
|
+
|
|
4
|
+
interface HtmlPolicy { createHTML: (html: string) => string }
|
|
5
|
+
|
|
6
|
+
let policy: HtmlPolicy | undefined
|
|
7
|
+
|
|
8
|
+
function createPolicy(): HtmlPolicy {
|
|
9
|
+
const pass = { createHTML: (html: string) => html }
|
|
10
|
+
try {
|
|
11
|
+
return (globalThis as { trustedTypes?: { createPolicy: (name: string, rules: HtmlPolicy) => HtmlPolicy } }).trustedTypes?.createPolicy('prunelle', pass) ?? pass
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
// A CSP whose `trusted-types` leaves `prunelle` out refuses the policy; without `require-trusted-types-for` the plain string still works.
|
|
15
|
+
return pass
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The HTML as a sink accepts it under Trusted Types: a `TrustedHTML` where the browser has them, the string itself elsewhere. */
|
|
20
|
+
export function trustedHtml(html: string): string {
|
|
21
|
+
return (policy ??= createPolicy()).createHTML(html)
|
|
22
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Loaded by an action stub only when a `useAction` form's `progress` is read, to send a FormData holding a `File` because `fetch` reports no upload progress: a page that never reads it ships none of it.
|
|
2
|
+
|
|
3
|
+
/** Posts a FormData holding a `File` with XMLHttpRequest, calling `onProgress` with the fraction sent (0 to 1), then 0 once it answers, and answers as `fetch` would; any other body goes through `fetch`. */
|
|
4
|
+
export function upload(url: string, init: RequestInit, onProgress: (fraction: number) => void): Promise<Response> {
|
|
5
|
+
const body = init.body
|
|
6
|
+
if (!(body instanceof FormData) || ![...body.values()].some(v => typeof v != 'string'))
|
|
7
|
+
return fetch(url, init)
|
|
8
|
+
const headers = init.headers as Record<string, string>
|
|
9
|
+
return new Promise<Response>((resolve, reject) => {
|
|
10
|
+
const signal = init.signal
|
|
11
|
+
if (signal?.aborted) {
|
|
12
|
+
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'))
|
|
13
|
+
return
|
|
14
|
+
}
|
|
15
|
+
const onAbort = () => xhr.abort()
|
|
16
|
+
const end = <T>(settle: (value: T) => void, value: T) => {
|
|
17
|
+
signal?.removeEventListener('abort', onAbort)
|
|
18
|
+
onProgress(0)
|
|
19
|
+
settle(value)
|
|
20
|
+
}
|
|
21
|
+
const xhr = new XMLHttpRequest()
|
|
22
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
23
|
+
xhr.open('POST', url)
|
|
24
|
+
xhr.responseType = 'arraybuffer'
|
|
25
|
+
for (const name in headers)
|
|
26
|
+
xhr.setRequestHeader(name, headers[name]!)
|
|
27
|
+
xhr.upload.onprogress = e => e.lengthComputable && onProgress(e.loaded / e.total)
|
|
28
|
+
xhr.onerror = xhr.ontimeout = () => end(reject, new Error('Network error'))
|
|
29
|
+
xhr.onabort = () => end(reject, signal?.aborted ? (signal.reason ?? new DOMException('Aborted', 'AbortError')) : new Error('Network error'))
|
|
30
|
+
xhr.onload = () => {
|
|
31
|
+
// XHR follows redirects without telling: an answer from another URL is one, which `fetch` with `redirect: 'manual'` refuses.
|
|
32
|
+
if (xhr.responseURL && xhr.responseURL !== new URL(url, location.href).href)
|
|
33
|
+
return end(reject, new Error('Unexpected redirect'))
|
|
34
|
+
const res = new Response([204, 205, 304].includes(xhr.status) ? null : xhr.response as ArrayBuffer, { status: xhr.status, statusText: xhr.statusText })
|
|
35
|
+
for (const line of xhr.getAllResponseHeaders().trim().split(/\r?\n/)) {
|
|
36
|
+
const at = line.indexOf(':')
|
|
37
|
+
if (at > 0)
|
|
38
|
+
res.headers.append(line.slice(0, at), line.slice(at + 1).trim())
|
|
39
|
+
}
|
|
40
|
+
end(resolve, res)
|
|
41
|
+
}
|
|
42
|
+
xhr.send(body)
|
|
43
|
+
})
|
|
44
|
+
}
|
package/src/eco/declaration.ts
CHANGED
|
@@ -29,15 +29,12 @@ export interface EcoFacts {
|
|
|
29
29
|
routesDir?: string | undefined
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
-
export type EcoVerdict = 'Validé' | 'Non validé'
|
|
33
|
-
|
|
34
32
|
export interface EcoCriterion {
|
|
35
33
|
id: string
|
|
36
34
|
/** The criterion's wording in the RGESN 2024. */
|
|
37
35
|
label: string
|
|
38
36
|
priority: 'Prioritaire' | 'Recommandé' | 'Modéré'
|
|
39
|
-
/**
|
|
40
|
-
verdict?: EcoVerdict | undefined
|
|
37
|
+
/** What prunelle saw: the verdict is a person's to write, a lint with partial coverage cannot back one. */
|
|
41
38
|
evidence: string
|
|
42
39
|
}
|
|
43
40
|
|
|
@@ -97,44 +94,48 @@ function foreignAssetPrefix(assetPrefix: string, site: string | undefined): stri
|
|
|
97
94
|
return assetPrefix
|
|
98
95
|
}
|
|
99
96
|
|
|
100
|
-
|
|
97
|
+
// What `prunelle check` reads is the JSX of the source files: the rest of an app escapes it.
|
|
98
|
+
const LINT_LIMITS = 'Cette vérification lit le JSX : elle ne voit ni les valeurs dynamiques, ni le contenu des composants, ni les lignes ignorées (prunelle-ignore).'
|
|
99
|
+
|
|
100
|
+
function lintEvidence(
|
|
101
101
|
files: readonly string[],
|
|
102
102
|
ignored: boolean,
|
|
103
103
|
rule: string,
|
|
104
|
-
|
|
105
|
-
|
|
104
|
+
cleanText: string,
|
|
105
|
+
foundPrefix: string,
|
|
106
106
|
manualPrompt: string,
|
|
107
|
-
):
|
|
107
|
+
): string {
|
|
108
108
|
if (files.length > 0)
|
|
109
|
-
return
|
|
109
|
+
return `${foundPrefix}${files.join(', ')}. ${LINT_LIMITS}`
|
|
110
110
|
if (ignored)
|
|
111
|
-
return
|
|
112
|
-
return {
|
|
111
|
+
return `La règle ${rule} est ignorée dans prunelle.config.ts (compliance.ignore) ; ${fill(manualPrompt)}.`
|
|
112
|
+
return `${cleanText} ${LINT_LIMITS}`
|
|
113
113
|
}
|
|
114
114
|
|
|
115
|
-
function
|
|
115
|
+
function sameDomainEvidence(assetOrigin: string | undefined, externalPages: readonly string[], measured: number): string {
|
|
116
|
+
const notMeasured = measured === 0 ? 'Aucune page n\'est prérendue : prunelle n\'a mesuré aucune requête des pages. ' : ''
|
|
116
117
|
if (assetOrigin === undefined && externalPages.length === 0) {
|
|
117
|
-
return
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
if (assetOrigin !== undefined && externalPages.length === 0) {
|
|
123
|
-
return {
|
|
124
|
-
verdict: 'Non validé',
|
|
125
|
-
evidence: `Les scripts et feuilles de style sont servis depuis ${assetOrigin}, un autre domaine que celui des pages.`,
|
|
126
|
-
}
|
|
118
|
+
return measured === 0
|
|
119
|
+
? `${notMeasured}Les scripts et feuilles de style du build ne viennent pas d'un domaine distinct (assetPrefix).`
|
|
120
|
+
: 'Les scripts et feuilles de style du build ne viennent pas d\'un domaine distinct (assetPrefix), et les pages prérendues ne chargent aucune ressource tierce que prunelle ait vue.'
|
|
127
121
|
}
|
|
122
|
+
if (assetOrigin !== undefined && externalPages.length === 0)
|
|
123
|
+
return `${notMeasured}Les scripts et feuilles de style sont servis depuis ${assetOrigin}, un autre domaine que celui des pages.`
|
|
128
124
|
const externalNote = `des ressources statiques sont chargées depuis un autre domaine sur : ${externalPages.join(', ')}`
|
|
129
|
-
return
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
125
|
+
return assetOrigin === undefined
|
|
126
|
+
? `${externalNote[0]!.toUpperCase()}${externalNote.slice(1)}.`
|
|
127
|
+
: `Les scripts et feuilles de style sont servis depuis ${assetOrigin}, un autre domaine que celui des pages ; ${externalNote}.`
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function noJsEvidence(total: number, noJs: number): string {
|
|
131
|
+
if (total === 0)
|
|
132
|
+
return 'Aucune page n\'est prérendue : prunelle n\'a rien mesuré du JavaScript envoyé.'
|
|
133
|
+
if (noJs === total)
|
|
134
|
+
return 'Aucune page n\'envoie de JavaScript.'
|
|
135
|
+
return `${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.`
|
|
135
136
|
}
|
|
136
137
|
|
|
137
|
-
/**
|
|
138
|
+
/** What prunelle saw of the RGESN 2024 criteria it can read from the build, `prunelle check` and the config: a person writes each verdict. */
|
|
138
139
|
export function evaluateEcoCriteria(facts: EcoFacts): EcoCriterion[] {
|
|
139
140
|
const autoplay = filesWarnedFor(facts.warnings, 'rgesn/autoplay')
|
|
140
141
|
const thirdParty = filesWarnedFor(facts.warnings, 'rgpd/third-party-url')
|
|
@@ -155,11 +156,11 @@ export function evaluateEcoCriteria(facts: EcoFacts): EcoCriterion[] {
|
|
|
155
156
|
id: '4.1',
|
|
156
157
|
label: 'Le service numérique comporte-t-il uniquement des animations, vidéos et sons dont la lecture automatique est désactivée ?',
|
|
157
158
|
priority: 'Prioritaire',
|
|
158
|
-
|
|
159
|
+
evidence: lintEvidence(
|
|
159
160
|
autoplay,
|
|
160
161
|
ignored.has('rgesn/autoplay'),
|
|
161
162
|
'rgesn/autoplay',
|
|
162
|
-
'
|
|
163
|
+
'prunelle check ne signale aucune lecture automatique de vidéo ni de son (règle rgesn/autoplay).',
|
|
163
164
|
'Une lecture automatique reste dans : ',
|
|
164
165
|
'vérification manuelle de la lecture automatique',
|
|
165
166
|
),
|
|
@@ -168,11 +169,11 @@ export function evaluateEcoCriteria(facts: EcoFacts): EcoCriterion[] {
|
|
|
168
169
|
id: '4.4',
|
|
169
170
|
label: 'Le service numérique permet-il à l\'utilisateur de décider de l\'activation d\'un service tiers ?',
|
|
170
171
|
priority: 'Recommandé',
|
|
171
|
-
|
|
172
|
+
evidence: lintEvidence(
|
|
172
173
|
thirdParty,
|
|
173
174
|
ignored.has('rgpd/third-party-url'),
|
|
174
175
|
'rgpd/third-party-url',
|
|
175
|
-
'
|
|
176
|
+
'prunelle check ne signale aucune ressource tierce chargée sans le consentement du visiteur (règle rgpd/third-party-url).',
|
|
176
177
|
'Des ressources tierces se chargent sans consentement dans : ',
|
|
177
178
|
'vérification manuelle des services tiers',
|
|
178
179
|
),
|
|
@@ -181,7 +182,6 @@ export function evaluateEcoCriteria(facts: EcoFacts): EcoCriterion[] {
|
|
|
181
182
|
id: '6.1',
|
|
182
183
|
label: 'Le service numérique s\'astreint-il à un poids maximum et une limite de requête par écran ?',
|
|
183
184
|
priority: 'Recommandé',
|
|
184
|
-
verdict: facts.firstLoadBudget === undefined ? 'Non validé' : undefined,
|
|
185
185
|
evidence: facts.firstLoadBudget === undefined
|
|
186
186
|
? 'Aucun poids maximum par écran n\'est fixé.'
|
|
187
187
|
: `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')}.`,
|
|
@@ -190,7 +190,6 @@ export function evaluateEcoCriteria(facts: EcoFacts): EcoCriterion[] {
|
|
|
190
190
|
id: '6.3',
|
|
191
191
|
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 ?',
|
|
192
192
|
priority: 'Modéré',
|
|
193
|
-
verdict: facts.compress ? 'Validé' : 'Non validé',
|
|
194
193
|
evidence: facts.compress
|
|
195
194
|
? '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.'
|
|
196
195
|
: `La compression du serveur est désactivée (compress: false) ; ${fill('compression assurée en amont, le cas échéant')}.`,
|
|
@@ -199,13 +198,13 @@ export function evaluateEcoCriteria(facts: EcoFacts): EcoCriterion[] {
|
|
|
199
198
|
id: '6.5',
|
|
200
199
|
label: 'Le service numérique évite-t-il de déclencher le chargement de ressources et de contenus inutilisés pour chaque fonctionnalité ?',
|
|
201
200
|
priority: 'Recommandé',
|
|
202
|
-
evidence: `${
|
|
201
|
+
evidence: `${noJsEvidence(total, noJs)} ${fill('images, polices et données chargées sans être affichées')}.`,
|
|
203
202
|
},
|
|
204
203
|
{
|
|
205
204
|
id: '6.7',
|
|
206
205
|
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 ?',
|
|
207
206
|
priority: 'Modéré',
|
|
208
|
-
|
|
207
|
+
evidence: sameDomainEvidence(assetOrigin, externalPages, measured.length),
|
|
209
208
|
},
|
|
210
209
|
]
|
|
211
210
|
}
|
|
@@ -222,7 +221,7 @@ function measuresSection(report: BundleReport): string {
|
|
|
222
221
|
return ` <p>${fill('mesures des pages représentatives : aucune page n\'est prérendue, prunelle n\'a rien mesuré')}</p>`
|
|
223
222
|
return [
|
|
224
223
|
' <table>',
|
|
225
|
-
' <caption>EcoIndex de chaque page prérendue,
|
|
224
|
+
' <caption>Estimation statique de l\'EcoIndex de chaque page prérendue, calculée par prunelle build sur le HTML et les fichiers du build (et non sur une visite dans un navigateur), avec les gaz à effet de serre (gCO2e) et l\'eau (cl) d\'une visite</caption>',
|
|
226
225
|
' <thead>',
|
|
227
226
|
' <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>',
|
|
228
227
|
' </thead>',
|
|
@@ -238,7 +237,7 @@ function criteriaSections(criteria: readonly EcoCriterion[]): string {
|
|
|
238
237
|
` <h3>${c.id}. ${escapeJsxText(c.label)}</h3>`,
|
|
239
238
|
' <dl>',
|
|
240
239
|
` <dt>Priorité</dt><dd>${c.priority}</dd>`,
|
|
241
|
-
` <dt>Évaluation</dt><dd>${escapeJsxText(
|
|
240
|
+
` <dt>Évaluation</dt><dd>${escapeJsxText(fill('Validé, Non validé ou Non applicable'))}</dd>`,
|
|
242
241
|
` <dt>Justification</dt><dd>${escapeJsxText(c.evidence)}</dd>`,
|
|
243
242
|
' </dl>',
|
|
244
243
|
].join('\n')).join('\n')
|
|
@@ -262,7 +261,7 @@ export function draftEcoDeclaration(options: EcoDeclarationOptions): EcoDeclarat
|
|
|
262
261
|
const wrapper = layoutRendersMain(root, dest) ? 'article' : 'main'
|
|
263
262
|
|
|
264
263
|
const content = `// Brouillon de déclaration d'écoconception RGESN 2024 généré par \`prunelle eco --declaration\`.
|
|
265
|
-
// prunelle
|
|
264
|
+
// prunelle indique ce qu'il a constaté pour chaque critère ; l'évaluation de chacun, et chaque mention entre crochets, sont à compléter avant publication : \`prunelle check\` signale celles qui restent.
|
|
266
265
|
|
|
267
266
|
import { Head } from 'prunelle'
|
|
268
267
|
|
package/src/eco/index.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { loadConfig } from '../plugins/load'
|
|
|
7
7
|
import { draftEcoDeclaration, evaluateEcoCriteria } from './declaration'
|
|
8
8
|
|
|
9
9
|
export { DEFAULT_ECO_DECLARATION_PATH, draftEcoDeclaration, evaluateEcoCriteria } from './declaration'
|
|
10
|
-
export type { EcoCriterion, EcoDeclarationOptions, EcoDeclarationResult, EcoFacts
|
|
10
|
+
export type { EcoCriterion, EcoDeclarationOptions, EcoDeclarationResult, EcoFacts } from './declaration'
|
|
11
11
|
|
|
12
12
|
export interface EcoRunOptions {
|
|
13
13
|
root: string
|
|
@@ -59,11 +59,11 @@ export async function runEco(options: EcoRunOptions): Promise<EcoRunResult> {
|
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
export function formatEcoResult(result: EcoRunResult): string {
|
|
62
|
-
const lines = ['prunelle eco: the RGESN 2024 criteria
|
|
62
|
+
const lines = ['prunelle eco: what prunelle saw of the RGESN 2024 criteria it can read from the build, prunelle check and the config']
|
|
63
63
|
for (const c of result.criteria)
|
|
64
|
-
lines.push(` ${c.id.padEnd(4)} ${
|
|
64
|
+
lines.push(` ${c.id.padEnd(4)} ${c.evidence}`)
|
|
65
65
|
lines.push(result.declaration === undefined
|
|
66
|
-
? 'The
|
|
67
|
-
: `prunelle eco: drafted the RGESN 2024 eco-design declaration at ${result.declaration.relativePath}: fill in each [à compléter ...] before publishing it.`)
|
|
66
|
+
? 'The verdicts are for a person to write: prunelle eco --declaration drafts the page that holds them all.'
|
|
67
|
+
: `prunelle eco: drafted the RGESN 2024 eco-design declaration at ${result.declaration.relativePath}: write each verdict and fill in each [à compléter ...] before publishing it.`)
|
|
68
68
|
return lines.join('\n')
|
|
69
69
|
}
|
package/src/href.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// `href('/posts/[slug]', { slug })`: the path of a route, built from its pattern; a pattern no route file serves fails to typecheck once prunelle has written `prunelle-routes.d.ts`.
|
|
2
|
+
|
|
3
|
+
import type { ExtractRouteParams, RoutePattern } from './server/http'
|
|
4
|
+
|
|
5
|
+
type HrefParams<P extends string> = { [K in keyof ExtractRouteParams<P>]: ExtractRouteParams<P>[K] | number }
|
|
6
|
+
|
|
7
|
+
const OPTIONAL_SEG_RE = /^\[\[([^\]=]+)(?:=[^\]]+)?\]\]$/
|
|
8
|
+
const REST_SEG_RE = /^\[\.\.\.([^\]=]+)(?:=[^\]]+)?\]$/
|
|
9
|
+
const PARAM_RE = /\[([^\]=]+)(?:=[^\]]+)?\]/g
|
|
10
|
+
|
|
11
|
+
export function href<P extends RoutePattern>(pattern: P, ...[params]: {} extends ExtractRouteParams<P> ? [params?: HrefParams<P>] : [params: HrefParams<P>]): string {
|
|
12
|
+
const values = (params ?? {}) as Record<string, string | number | undefined>
|
|
13
|
+
const value = (name: string): string => {
|
|
14
|
+
const given = values[name]
|
|
15
|
+
if (given === undefined || given === '')
|
|
16
|
+
throw new Error(`prunelle: href("${pattern}") needs \`${name}\` in its params: pass it, or link to a route without it.`)
|
|
17
|
+
return String(given)
|
|
18
|
+
}
|
|
19
|
+
const parts: string[] = []
|
|
20
|
+
for (const segment of pattern.split('/')) {
|
|
21
|
+
const optional = OPTIONAL_SEG_RE.exec(segment)
|
|
22
|
+
const rest = REST_SEG_RE.exec(segment)
|
|
23
|
+
if (optional !== null)
|
|
24
|
+
parts.push(values[optional[1]!] === undefined ? '' : encodeURIComponent(String(values[optional[1]!])))
|
|
25
|
+
else if (rest !== null)
|
|
26
|
+
parts.push(value(rest[1]!).split('/').map(encodeURIComponent).join('/'))
|
|
27
|
+
else
|
|
28
|
+
parts.push(segment.replace(PARAM_RE, (_, name: string) => encodeURIComponent(value(name))))
|
|
29
|
+
}
|
|
30
|
+
return `/${parts.filter(part => part !== '').join('/')}`
|
|
31
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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'
|
|
1
|
+
export { Catch, ConsentBanner, ConsentGate, ConsentPreferences, CookieTable, createContext, Head, provideContext, Region, Suspense, useContext, useId } from './context'
|
|
2
|
+
export type { CatchProps, ConsentBannerProps, ConsentGateProps, ConsentTexts, Context, CookieTableProps, RegionProps } from './context'
|
|
3
3
|
export {
|
|
4
4
|
batch,
|
|
5
5
|
computed,
|
|
@@ -12,11 +12,17 @@ export {
|
|
|
12
12
|
untrack,
|
|
13
13
|
} from './reactivity/index'
|
|
14
14
|
export type { Owner, ReadonlySignal, Signal } from './reactivity/index'
|
|
15
|
+
export { resource } from './reactivity/resource'
|
|
16
|
+
export type { Resource, ResourceOptions, ResourceRun } from './reactivity/resource'
|
|
15
17
|
export { selector } from './reactivity/selector'
|
|
16
18
|
export type { Selector } from './reactivity/selector'
|
|
17
19
|
export { snapshot, store } from './reactivity/store'
|
|
20
|
+
export { animate } from './animate'
|
|
21
|
+
export type { AnimateEffect, AnimateOptions } from './animate'
|
|
18
22
|
export { useAction } from './dom/action'
|
|
19
23
|
export type { ActionForm, ClientAction, UseActionOptions } from './dom/action'
|
|
24
|
+
export { refreshRegion } from './dom/regions'
|
|
20
25
|
export type { Component, Html, HydrateStrategy, PrunelleChild } from './jsx-runtime'
|
|
21
|
-
export
|
|
26
|
+
export { href } from './href'
|
|
27
|
+
export type { ExtractRouteParams, PrunelleLocals, LayoutProps, LoaderData, LoaderFn, NotFoundResult, PageProps, RequestConsent, RouteContext, RoutePattern } from './server/index'
|
|
22
28
|
|
package/src/plugins/config.ts
CHANGED
|
@@ -7,7 +7,7 @@ export function defineConfig(config: PrunelleConfig): PrunelleConfig {
|
|
|
7
7
|
}
|
|
8
8
|
|
|
9
9
|
// Typed as records so that a key added to the config types without being listed here fails the typecheck.
|
|
10
|
-
const RUNTIME_KEYS: Record<keyof ServerRuntimeConfig, true> = { site: true, lang: true, assetPrefix: true, security: true, trustedOrigins: true, trustProxy: true, maxRequestBodySize: true, navigation: true, streamTimeout: true, consent: true, compress: true, routeCache: true, healthCheck: true, onError: true, plugins: true }
|
|
10
|
+
const RUNTIME_KEYS: Record<keyof ServerRuntimeConfig, true> = { site: true, lang: true, assetPrefix: true, security: true, trustedOrigins: true, trustProxy: true, maxRequestBodySize: true, navigation: true, streamTimeout: true, consent: true, compress: true, routeCache: true, store: true, healthCheck: true, onError: true, log: true, plugins: true }
|
|
11
11
|
const BUILD_KEYS: Record<Exclude<keyof PrunelleConfig, keyof ServerRuntimeConfig>, true> = { port: true, routesDir: true, outDir: true, publicDir: true, compliance: true, autoPrerender: true, budget: true }
|
|
12
12
|
const BUILD_KEY_SET = new Set<string>(Object.keys(BUILD_KEYS))
|
|
13
13
|
const RUNTIME_CONFIG_KEYS = Object.keys(RUNTIME_KEYS) as (keyof ServerRuntimeConfig)[]
|
package/src/plugins/context.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Per-build / per-server scoped runtime context (AsyncLocalStorage-backed, zero mutable process globals).
|
|
2
2
|
|
|
3
|
-
import type { ServiceKey } from './services'
|
|
3
|
+
import type { ServiceKey, UserDataService } from './services'
|
|
4
4
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
5
|
+
import { mergeUserDataServices, USER_DATA_SERVICE } from './services'
|
|
5
6
|
|
|
6
7
|
export interface AppRuntimeContext {
|
|
7
8
|
readonly root: string
|
|
@@ -46,6 +47,11 @@ export function createAppContext(options: CreateAppContextOptions): AppRuntimeCo
|
|
|
46
47
|
...(options.nodeEnv !== undefined ? { nodeEnv: options.nodeEnv } : {}),
|
|
47
48
|
// Keyed by name: the natively loaded config and the bundled app each hold their own key object.
|
|
48
49
|
provide<T>(key: ServiceKey<T>, value: T): void {
|
|
50
|
+
if (key.name === USER_DATA_SERVICE.name && value !== undefined) {
|
|
51
|
+
const existing = services.get(key.name) as UserDataService | undefined
|
|
52
|
+
services.set(key.name, mergeUserDataServices(existing, value as unknown as UserDataService))
|
|
53
|
+
return
|
|
54
|
+
}
|
|
49
55
|
services.set(key.name, value)
|
|
50
56
|
},
|
|
51
57
|
inject<T>(key: ServiceKey<T>): T | undefined {
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// A plugin's daily chore (a retention purge): on `@prunellejs/jobs` when the app has it, else in each process.
|
|
2
|
+
|
|
3
|
+
import type { ServerPluginAPI } from './types'
|
|
4
|
+
import { JOBS_SERVICE } from './services'
|
|
5
|
+
|
|
6
|
+
const DAY_MS = 86_400_000
|
|
7
|
+
// `prunelle check` and `prunelle inspect` start each plugin's server to list its routes and stop it at once: a chore waiting a minute never runs there.
|
|
8
|
+
const FIRST_RUN_MS = 60_000
|
|
9
|
+
|
|
10
|
+
/** Runs `chore` daily at `cron` on `@prunellejs/jobs` when the app has it; without it, a minute after start then every day in this process, logging `failure` when it throws. */
|
|
11
|
+
export function scheduleDaily(api: ServerPluginAPI, name: string, cron: string, chore: () => Promise<unknown>, failure: string): void {
|
|
12
|
+
const jobs = api.inject(JOBS_SERVICE)
|
|
13
|
+
if (jobs?.schedule !== undefined) {
|
|
14
|
+
jobs.schedule(name, cron, async () => {
|
|
15
|
+
await chore()
|
|
16
|
+
})
|
|
17
|
+
return
|
|
18
|
+
}
|
|
19
|
+
const run = (): void => void chore().catch((error: unknown) => console.error(failure, error))
|
|
20
|
+
let timer = setTimeout(() => {
|
|
21
|
+
run()
|
|
22
|
+
timer = setInterval(run, DAY_MS)
|
|
23
|
+
timer.unref()
|
|
24
|
+
}, FIRST_RUN_MS)
|
|
25
|
+
timer.unref()
|
|
26
|
+
api.onShutdown(() => clearTimeout(timer))
|
|
27
|
+
}
|