prunelle 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,96 @@
1
+ // What the platform does for plain page changes with no prunelle JS: cross-document view transitions, Speculation Rules and a marked panel's scroll offset kept across page loads.
2
+
3
+ import { escJson } from './index'
4
+
5
+ export const KEEP_SCROLL_ATTR = 'data-pru-keep-scroll'
6
+ export const NO_PREFETCH_ATTR = 'data-pru-no-prefetch'
7
+
8
+ export type Eagerness = 'conservative' | 'moderate' | 'eager'
9
+
10
+ export interface NavigationConfig {
11
+ /** Fades one page into the next with a cross-document view transition (`@view-transition { navigation: auto }`), off under `prefers-reduced-motion`. On by default, `false` leaves the browser's plain repaint. */
12
+ viewTransitions?: boolean | undefined
13
+ /** When the browser fetches the page a same-origin link points at, through Speculation Rules: `'conservative'` (the default) on press, `'moderate'` on hover (and, on phones, as a link scrolls into view), `'eager'` as soon as it can, `false` never. A link, or an ancestor of it, with `data-pru-no-prefetch` is never fetched; neither is a `download` or `rel="nofollow"` link, a prunelle route (actions among them) or another origin's page. */
14
+ prefetch?: Eagerness | false | undefined
15
+ /** Renders the page a link points at before it is followed, which runs its `load()`: off by default, `true` is `'moderate'`. */
16
+ prerender?: Eagerness | boolean | undefined
17
+ }
18
+
19
+ /** The head markup shared by every page and the CSP sources that allow it. */
20
+ export interface Navigation {
21
+ html: string
22
+ styleHashes: readonly string[]
23
+ scriptHashes: readonly string[]
24
+ }
25
+
26
+ export const VIEW_TRANSITION_STYLE = '@media (prefers-reduced-motion:no-preference){@view-transition{navigation:auto}}'
27
+
28
+ // Runs at the end of the body, with the marked panels parsed and before the first paint of a page sent whole. An offset is kept per history entry (an id in `history.state`, which back, forward and reload keep) when the page is left, and a new entry starts from the offsets of the page its link came from, a same-origin referrer showing that. Storage that throws leaves the page as it loaded.
29
+ export const KEEP_SCROLL_SCRIPT = `{try{const A="${KEEP_SCROLL_ATTR}",S=sessionStorage,s=history.state,o=s&&typeof s=="object"?s:{},own=o.pruScroll,id=own||Math.random().toString(36).slice(2),read=k=>JSON.parse(S.getItem(k)||"{}"),saved=own?read("pru-scroll:"+id):document.referrer.startsWith(location.origin+"/")?read("pru-scroll"):{};own||history.replaceState({...o,pruScroll:id},"");for(const e of document.querySelectorAll("["+A+"]"))saved[e.getAttribute(A)]>0&&(e.scrollTop=saved[e.getAttribute(A)]);addEventListener("pagehide",()=>{try{const m={};for(const e of document.querySelectorAll("["+A+"]"))m[e.getAttribute(A)]=e.scrollTop;const j=JSON.stringify(m);S.setItem("pru-scroll:"+id,j);S.setItem("pru-scroll",j)}catch{}})}catch{}}`
30
+ export const KEEP_SCROLL_TAG = `<script>${KEEP_SCROLL_SCRIPT}</script>`
31
+
32
+ /** The CSP source allowing exactly this inline script or style. */
33
+ export function cspSha256(text: string): string {
34
+ return `'sha256-${new Bun.CryptoHasher('sha256').update(text).digest('base64')}'`
35
+ }
36
+
37
+
38
+ const EAGERNESS = new Set<unknown>(['conservative', 'moderate', 'eager'])
39
+
40
+ /** Throws on a `navigation` setting the browser would ignore without a word. */
41
+ export function checkNavigationConfig(config: NavigationConfig | undefined): void {
42
+ if (config === undefined)
43
+ return
44
+ for (const key of ['prefetch', 'prerender'] as const) {
45
+ const value: unknown = config[key]
46
+ const allowed = value === undefined || value === false || EAGERNESS.has(value) || (key === 'prerender' && value === true)
47
+ if (!allowed)
48
+ throw new Error(`prunelle: navigation.${key} is ${JSON.stringify(value)} in prunelle.config.ts: use 'conservative', 'moderate', 'eager'${key === 'prefetch' ? ' or false' : ', true or false'}.`)
49
+ }
50
+ }
51
+
52
+ // Never a link that opts out (or sits in a container that does), a download, a nofollow link (a sign-out link often is), prunelle's own routes (an action's URL among them); `href_matches: '/*'` only reaches this origin.
53
+ function rulesWhere(): object {
54
+ return { and: [{ href_matches: '/*' }, { not: { href_matches: '/_pru/*' } }, { not: { selector_matches: `[${NO_PREFETCH_ATTR}], [${NO_PREFETCH_ATTR}] a, [download], [rel~=nofollow]` } }] }
55
+ }
56
+
57
+ /** What a page's head holds for the `navigation` settings, made once at start: the rules for each setting left on, as one style and one script the policy hashes. */
58
+ export function createNavigation(config: NavigationConfig | undefined): Navigation {
59
+ checkNavigationConfig(config)
60
+ const styleHashes: string[] = []
61
+ const scriptHashes = [cspSha256(KEEP_SCROLL_SCRIPT)]
62
+ let html = ''
63
+ if (config?.viewTransitions !== false) {
64
+ html += `<style>${VIEW_TRANSITION_STYLE}</style>`
65
+ styleHashes.push(cspSha256(VIEW_TRANSITION_STYLE))
66
+ }
67
+ const prefetch = config?.prefetch === undefined ? 'conservative' : config.prefetch
68
+ const prerender = config?.prerender === true ? 'moderate' : config?.prerender || undefined
69
+ if (prefetch !== false || prerender !== undefined) {
70
+ const where = rulesWhere()
71
+ const rules: Record<string, unknown[]> = {}
72
+ if (prefetch !== false)
73
+ rules.prefetch = [{ source: 'document', where, eagerness: prefetch }]
74
+ if (prerender !== undefined)
75
+ rules.prerender = [{ source: 'document', where, eagerness: prerender }]
76
+ const json = escJson(JSON.stringify(rules))
77
+ html += `<script type="speculationrules">${json}</script>`
78
+ scriptHashes.push(cspSha256(json))
79
+ }
80
+ return { html, styleHashes, scriptHashes }
81
+ }
82
+
83
+ const DUPLICATE_RE = new RegExp(` ${KEEP_SCROLL_ATTR}="([^"]*)"`, 'g')
84
+
85
+ /** The script a document needs for the panels it marks, or nothing: a page leaving `data-pru-keep-scroll` out costs one `includes`. Two panels of one key throw, as the browser could keep only one offset for them. */
86
+ export function keepScrollTag(body: string): string {
87
+ if (!body.includes(` ${KEEP_SCROLL_ATTR}`))
88
+ return ''
89
+ const seen = new Set<string>()
90
+ for (const [, key] of body.matchAll(DUPLICATE_RE)) {
91
+ if (seen.has(key!))
92
+ throw new Error(`prunelle: ${KEEP_SCROLL_ATTR}="${key}" is on two elements of one page: give each panel its own key.`)
93
+ seen.add(key!)
94
+ }
95
+ return KEEP_SCROLL_TAG
96
+ }
@@ -0,0 +1,192 @@
1
+ // <Region>: a part of a page that a link or form can swap alone. A request naming a region renders only that one, and the others never read their children.
2
+
3
+ import type { RegionProps } from '../context'
4
+ import type { Html, PrunelleChild } from '../jsx-runtime'
5
+ import type { PendingChunk, RenderContext, SettledChunk } from './context'
6
+ import { currentRenderContext, isInTarget, runInTarget } from './context'
7
+ import { escAttr, raw, ssrChild, ssrSpread } from './index'
8
+
9
+ const TAG_RE = /^[a-z][a-z0-9-]*$/
10
+ const DEFAULT_REGION_STREAM_TIMEOUT = 30_000
11
+ const PRUNELLE_S_TAG_RE = /<(\/?)pru-s(?=\s|>)/g
12
+
13
+ // The requested region's children render with `inTarget` set, so the regions inside it come out in full.
14
+ function renderTarget(ctx: RenderContext, children: () => PrunelleChild): string {
15
+ return runInTarget(ctx, () => ssrChild(children()))
16
+ }
17
+
18
+ export function Region(props: RegionProps): Html {
19
+ const { name, as = 'div' } = props
20
+ if (typeof name !== 'string' || name === '')
21
+ throw new Error('prunelle: <Region> needs a name: write <Region name="pane">.')
22
+ if (!TAG_RE.test(as))
23
+ throw new Error(`prunelle: <Region name="${name}" as="${as}"> is not an element name: write as="section", for example.`)
24
+ const ctx = currentRenderContext()
25
+ if (ctx !== undefined) {
26
+ if (ctx.regionNames.has(name))
27
+ throw new Error(`prunelle: two <Region name="${name}"> on one page: give each region its own name.`)
28
+ ctx.regionNames.add(name)
29
+ if (ctx.region !== undefined && !isInTarget(ctx)) {
30
+ if (ctx.region === name)
31
+ ctx.regionHtml = renderTarget(ctx, () => props.children)
32
+ else if (ctx.regionAncestors.has(name))
33
+ ssrChild(props.children)
34
+ return raw('')
35
+ }
36
+ }
37
+ const inner = ssrChild(props.children)
38
+ // Copied key by key: spreading `props` would read `children`, a lazy getter the other regions must never trigger.
39
+ const attributes: Record<string, unknown> = {}
40
+ for (const key of Object.keys(props)) {
41
+ if (key !== 'name' && key !== 'as' && key !== 'children')
42
+ attributes[key] = props[key]
43
+ }
44
+ return raw(`<${as} data-pru-region="${escAttr(name)}"${ssrSpread(attributes)}>${inner}</${as}>`)
45
+ }
46
+
47
+ function findPlaceholderRange(html: string, id: number): [number, number] | undefined {
48
+ const openTag = `<pru-s id="k-s-${id}">`
49
+ const start = html.indexOf(openTag)
50
+ if (start === -1)
51
+ return undefined
52
+ let depth = 1
53
+ PRUNELLE_S_TAG_RE.lastIndex = start + openTag.length
54
+ let match: RegExpExecArray | null
55
+ while ((match = PRUNELLE_S_TAG_RE.exec(html)) !== null) {
56
+ if (match[1] === '/') {
57
+ depth--
58
+ if (depth === 0) {
59
+ const closeEnd = html.indexOf('>', match.index)
60
+ return closeEnd === -1 ? undefined : [start, closeEnd + 1]
61
+ }
62
+ }
63
+ else {
64
+ depth++
65
+ }
66
+ }
67
+ return undefined
68
+ }
69
+
70
+ export interface FinishRegionOptions {
71
+ streamTimeout?: number | undefined
72
+ onError?: ((error: unknown) => void) | undefined
73
+ runInScope?: (<T>(fn: () => T) => T) | undefined
74
+ }
75
+
76
+ async function settleChunkWithin(
77
+ chunk: PendingChunk,
78
+ deadline: number,
79
+ streamTimeout: number,
80
+ runInScope: <T>(fn: () => T) => T,
81
+ ): Promise<SettledChunk> {
82
+ const remaining = Math.max(0, deadline - Date.now())
83
+ let timer: ReturnType<typeof setTimeout> | undefined
84
+ const timedOut = new Promise<SettledChunk>((resolve) => {
85
+ timer = setTimeout(() => {
86
+ chunk.discard?.()
87
+ const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${streamTimeout} ms`)
88
+ resolve({ html: runInScope(() => chunk.renderError(error)), error })
89
+ }, remaining)
90
+ })
91
+ try {
92
+ return await Promise.race([chunk.settled, timedOut])
93
+ }
94
+ finally {
95
+ clearTimeout(timer)
96
+ }
97
+ }
98
+
99
+ async function awaitRegionDiscovery(
100
+ ctx: RenderContext,
101
+ deadline: number,
102
+ reportError: (id: number, error: unknown) => void,
103
+ ): Promise<void> {
104
+ const watched = new Set<number>()
105
+ let pendingCount = 0
106
+ let timer: ReturnType<typeof setTimeout> | undefined
107
+ let done = false
108
+
109
+ await new Promise<void>((resolve) => {
110
+ const finish = () => {
111
+ if (done)
112
+ return
113
+ done = true
114
+ clearTimeout(timer)
115
+ resolve()
116
+ }
117
+ const watchNew = () => {
118
+ for (let i = 0; i < ctx.pending.length; i++) {
119
+ const chunk = ctx.pending[i]!
120
+ if (watched.has(chunk.id))
121
+ continue
122
+ watched.add(chunk.id)
123
+ pendingCount++
124
+ void chunk.settled.then((settled) => {
125
+ pendingCount--
126
+ if (done)
127
+ return
128
+ if ('error' in settled)
129
+ reportError(chunk.id, settled.error)
130
+ if (ctx.regionHtml !== undefined) {
131
+ finish()
132
+ return
133
+ }
134
+ watchNew()
135
+ if (pendingCount === 0)
136
+ finish()
137
+ })
138
+ }
139
+ }
140
+ timer = setTimeout(finish, Math.max(0, deadline - Date.now()))
141
+ watchNew()
142
+ if (ctx.regionHtml !== undefined || pendingCount === 0)
143
+ finish()
144
+ })
145
+ }
146
+
147
+ /** The requested region's HTML with its `<Suspense>` boundaries resolved in place, or `undefined` when the page rendered no such region. */
148
+ export async function finishRegion(ctx: RenderContext, options?: FinishRegionOptions): Promise<string | undefined> {
149
+ const streamTimeout = options?.streamTimeout ?? DEFAULT_REGION_STREAM_TIMEOUT
150
+ const onError = options?.onError
151
+ const runInScope = options?.runInScope ?? (<T>(fn: () => T) => fn())
152
+ const deadline = Date.now() + streamTimeout
153
+ const reported = new Set<number>()
154
+ const reportError = (id: number, error: unknown): void => {
155
+ if (onError === undefined || reported.has(id))
156
+ return
157
+ reported.add(id)
158
+ runInScope(() => onError(error))
159
+ }
160
+
161
+ try {
162
+ if (ctx.regionHtml === undefined && ctx.pending.length > 0)
163
+ await awaitRegionDiscovery(ctx, deadline, reportError)
164
+
165
+ let html = ctx.regionHtml
166
+ if (html === undefined)
167
+ return undefined
168
+ const resolved = new Set<number>()
169
+ let progressed = true
170
+ while (progressed) {
171
+ progressed = false
172
+ for (let i = 0; i < ctx.pending.length; i++) {
173
+ const chunk = ctx.pending[i]!
174
+ if (resolved.has(chunk.id))
175
+ continue
176
+ const range = findPlaceholderRange(html, chunk.id)
177
+ if (range === undefined)
178
+ continue
179
+ resolved.add(chunk.id)
180
+ const settled = await settleChunkWithin(chunk, deadline, streamTimeout, runInScope)
181
+ if ('error' in settled)
182
+ reportError(chunk.id, settled.error)
183
+ html = html.slice(0, range[0]) + settled.html + html.slice(range[1])
184
+ progressed = true
185
+ }
186
+ }
187
+ return html
188
+ }
189
+ finally {
190
+ ctx.aborted = true
191
+ }
192
+ }
package/src/style.ts ADDED
@@ -0,0 +1,96 @@
1
+ // The CSS text of a style object, shared by the server and the browser so both render the same declarations.
2
+
3
+ // Properties that take a bare number; any other number gets `px`.
4
+ const UNITLESS = new Set([
5
+ 'animation-iteration-count', 'aspect-ratio', 'border-image-outset', 'border-image-slice', 'border-image-width',
6
+ 'column-count', 'columns', 'fill-opacity', 'flex', 'flex-grow', 'flex-shrink', 'flood-opacity', 'font-weight',
7
+ 'grid-area', 'grid-column', 'grid-column-end', 'grid-column-start', 'grid-row', 'grid-row-end', 'grid-row-start',
8
+ 'line-clamp', '-webkit-line-clamp', 'line-height', 'opacity', 'order', 'orphans', 'scale', 'stop-opacity',
9
+ 'stroke-dasharray', 'stroke-dashoffset', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'tab-size',
10
+ 'widows', 'z-index', 'zoom',
11
+ ])
12
+ const UPPER = /[A-Z]/g
13
+ const MS_PREFIX = /^ms[A-Z]/
14
+
15
+ // `backgroundColor` becomes `background-color` and `msTransform` `-ms-transform`; a custom property keeps its case.
16
+ function cssName(key: string): string {
17
+ if (key.startsWith('--'))
18
+ return key
19
+ const name = key.replace(UPPER, c => `-${c.toLowerCase()}`)
20
+ return MS_PREFIX.test(key) ? `-${name}` : name
21
+ }
22
+
23
+ const PROPERTY_NAME = /^-{0,2}[a-z][\w-]*$/i
24
+
25
+ const NL = /[\n\r\f]/
26
+ const URL_FN = /(?:^|[^\w-])url$/i
27
+ // After `url(`, either a quoted string opener (group 1) or a valid unquoted `<url-token>` through `)` (disjoint branches: linear time).
28
+ const UNQUOTED_URL = /[ \t]*(?:(["'])|(?:\\[^\n\r\f]|[^"'(){}\u0000-\u0020\u007F\\])*[ \t]*\))/y
29
+
30
+ // Whether `value` stays one declaration value: a `;`, `{` or `}` outside quotes and parentheses, a comment, a raw newline, a trailing/newline escape, an unquoted bad-url, or a quote or parenthesis left open would end it and let the rest add declarations.
31
+ function isOneValue(value: string): boolean {
32
+ let depth = 0
33
+ let quote = ''
34
+ let esc = false
35
+ for (let i = 0; i < value.length; i++) {
36
+ const c = value[i]!
37
+ if (c === '\\') {
38
+ if (++i >= value.length || NL.test(value[i]!))
39
+ return false
40
+ esc = true
41
+ }
42
+ else if (NL.test(c)) {
43
+ return false
44
+ }
45
+ else if (quote !== '') {
46
+ quote = c === quote ? '' : quote
47
+ }
48
+ else if (c === '"' || c === '\'') {
49
+ quote = c
50
+ esc = false
51
+ }
52
+ else if (c === '/' && value[i + 1] === '*') {
53
+ return false
54
+ }
55
+ else if (c === '(') {
56
+ const checkUrl = esc || URL_FN.test(value.slice(0, i))
57
+ esc = false
58
+ if (checkUrl) {
59
+ UNQUOTED_URL.lastIndex = i + 1
60
+ const m = UNQUOTED_URL.exec(value)
61
+ if (m === null || (m[1] === undefined && m[0].includes('/*')))
62
+ return false
63
+ if (m[1] === undefined) {
64
+ i = UNQUOTED_URL.lastIndex - 1
65
+ continue
66
+ }
67
+ }
68
+ depth++
69
+ }
70
+ else if (c === ')' && --depth < 0) {
71
+ return false
72
+ }
73
+ else if (depth === 0 && (c === ';' || c === '{' || c === '}')) {
74
+ return false
75
+ }
76
+ else if (',);{}'.includes(c)) {
77
+ esc = false
78
+ }
79
+ }
80
+ return quote === '' && depth === 0
81
+ }
82
+
83
+ /** The CSS text of a style object. A declaration that could not stay one is dropped, as a browser drops an invalid one: a key that is not a property name, a non-finite number, a string value `isOneValue` refuses. */
84
+ export function styleText(style: Record<string, unknown>): string {
85
+ let out = ''
86
+ for (const [key, value] of Object.entries(style)) {
87
+ if (value == null || value === '' || value === false || !PROPERTY_NAME.test(key))
88
+ continue
89
+ if (typeof value === 'number' ? !Number.isFinite(value) : !isOneValue(String(value)))
90
+ continue
91
+ const name = cssName(key)
92
+ const px = typeof value === 'number' && !name.startsWith('--') && !UNITLESS.has(name)
93
+ out += `${name}:${value}${px ? 'px' : ''};`
94
+ }
95
+ return out
96
+ }
@@ -0,0 +1,201 @@
1
+ // prunelle/test browser tests: the built app served on a loopback port of its own, its pages opened in Chromium with islands hydrated.
2
+
3
+ import type { TestApp, TestAppOptions } from './index'
4
+ import { existsSync } from 'node:fs'
5
+ import { testApp } from './index'
6
+
7
+ export interface BrowserTestOptions extends TestAppOptions {
8
+ /** Chrome or Chromium executable; defaults to `BUN_CHROME_PATH`, Playwright's own, then the system's. */
9
+ browserPath?: string | undefined
10
+ /** Milliseconds `open`, `waitFor` and `click` wait before they throw. Default 10000. */
11
+ timeout?: number | undefined
12
+ }
13
+
14
+ export interface BrowserPage {
15
+ readonly url: string
16
+ /** Page errors, `console.error` messages and failed requests (status 400 and up, but the favicon) seen since the page opened. */
17
+ readonly errors: string[]
18
+ /** Runs `fn` (or the expression string) in the page and returns its JSON-serializable result. */
19
+ evaluate<T>(fn: string | (() => T | Promise<T>)): Promise<T>
20
+ /** Waits for a CSS selector to match, or for `fn` to return a truthy value in the page. */
21
+ waitFor(selectorOrFn: string | (() => unknown)): Promise<void>
22
+ click(selector: string): Promise<void>
23
+ /** Moves the pointer over the first element matching `selector`, as a visitor hovering a link does. */
24
+ hover(selector: string): Promise<void>
25
+ fill(selector: string, value: string): Promise<void>
26
+ /** Presses a key (`'Escape'`, `'ArrowRight'`, `'Tab'`) through the browser's keyboard input pipeline. */
27
+ press(key: string): Promise<void>
28
+ /** The text content of the first element matching `selector`. */
29
+ text(selector: string): Promise<string>
30
+ close(): Promise<void>
31
+ }
32
+
33
+ export interface BrowserTest {
34
+ /** The built app, for requests that need no browser. */
35
+ readonly app: TestApp
36
+ /** `http://127.0.0.1:<port>`, a port the test owns. */
37
+ readonly origin: string
38
+ /** Opens `path` and resolves once the page has loaded and the islands that hydrate on load have hydrated; `reducedMotion` opens it for a visitor asking for less motion. */
39
+ open(path: string, options?: { reducedMotion?: boolean | undefined }): Promise<BrowserPage>
40
+ /** Closes the browser and the server. */
41
+ close(): Promise<void>
42
+ }
43
+
44
+ const DEFAULT_TIMEOUT_MS = 10_000
45
+
46
+ // The few playwright-core types used here, so an app's typecheck never needs playwright-core installed.
47
+ interface Page {
48
+ url(): string
49
+ on(event: 'pageerror', listener: (error: Error) => void): void
50
+ on(event: 'response', listener: (response: { status: () => number, url: () => string }) => void): void
51
+ on(event: 'console', listener: (message: { type: () => string, text: () => string }) => void): void
52
+ goto(url: string, options: { waitUntil: 'load', timeout: number }): Promise<unknown>
53
+ evaluate<T>(fn: string | (() => T | Promise<T>)): Promise<T>
54
+ waitForSelector(selector: string, options: { timeout: number }): Promise<unknown>
55
+ waitForFunction(fn: string | (() => unknown), arg: undefined, options: { timeout: number }): Promise<unknown>
56
+ click(selector: string, options: { timeout: number }): Promise<void>
57
+ hover(selector: string, options: { timeout: number }): Promise<void>
58
+ fill(selector: string, value: string, options: { timeout: number }): Promise<void>
59
+ keyboard: { press(key: string): Promise<void> }
60
+ locator(selector: string): { first: () => { innerText: (options: { timeout: number }) => Promise<string> } }
61
+ }
62
+ interface BrowserContext {
63
+ newPage(): Promise<Page>
64
+ close(): Promise<void>
65
+ }
66
+ interface Browser {
67
+ newContext(options?: { reducedMotion: 'reduce' }): Promise<BrowserContext>
68
+ close(): Promise<void>
69
+ }
70
+
71
+ // True once every island that hydrates on load has hydrated; the ones waiting to be seen, idle, touched or matching a media query are left to the test.
72
+ const ISLANDS_HYDRATED = `[...document.querySelectorAll('pru-island')].every(e => { const h = e.getAttribute('h'); return h === 'visible' || h === 'idle' || h === 'interaction' || (h !== null && h.startsWith('media(')) || e._d !== undefined })`
73
+
74
+ interface PlaywrightCore {
75
+ chromium: { launch: (options: { headless: boolean, executablePath: string }) => Promise<Browser>, executablePath: () => string }
76
+ }
77
+
78
+ async function loadPlaywright(): Promise<PlaywrightCore> {
79
+ try {
80
+ return await import('playwright-core') as unknown as PlaywrightCore
81
+ }
82
+ catch {
83
+ throw new Error('prunelle: browser tests need playwright-core, and it is not installed: run `bun add -d playwright-core`.')
84
+ }
85
+ }
86
+
87
+ function findBrowser(playwright: PlaywrightCore, given: string | undefined): string {
88
+ if (given !== undefined) {
89
+ if (!existsSync(given))
90
+ throw new Error(`prunelle: no browser at ${given}: give the path of Chrome or Chromium as \`browserPath\`, or set BUN_CHROME_PATH.`)
91
+ return given
92
+ }
93
+ const found = [process.env.BUN_CHROME_PATH, playwright.chromium.executablePath(), '/usr/bin/chromium', '/usr/bin/google-chrome']
94
+ .find((path): path is string => typeof path === 'string' && path.length > 0 && existsSync(path))
95
+ if (found === undefined)
96
+ throw new Error('prunelle: browser tests found no Chrome or Chromium: install one, run `bunx playwright install chromium`, or give its path as `browserPath` or BUN_CHROME_PATH.')
97
+ return found
98
+ }
99
+
100
+ function wrapPage(page: Page, context: BrowserContext, timeout: number): BrowserPage {
101
+ const errors: string[] = []
102
+ page.on('pageerror', error => errors.push(error.message))
103
+ // A failed load logs a console error without its URL, so the response names it instead; the favicon browsers ask for unprompted is no mistake of the app.
104
+ page.on('response', (response) => {
105
+ if (response.status() >= 400 && !response.url().endsWith('/favicon.ico'))
106
+ errors.push(`${response.status()} ${response.url()}`)
107
+ })
108
+ page.on('console', (message) => {
109
+ if (message.type() === 'error' && !message.text().startsWith('Failed to load resource'))
110
+ errors.push(message.text())
111
+ })
112
+ return {
113
+ get url() {
114
+ return page.url()
115
+ },
116
+ errors,
117
+ async evaluate(fn) {
118
+ return await page.evaluate(fn as () => never)
119
+ },
120
+ async waitFor(selectorOrFn) {
121
+ if (typeof selectorOrFn === 'string')
122
+ await page.waitForSelector(selectorOrFn, { timeout })
123
+ else
124
+ await page.waitForFunction(selectorOrFn, undefined, { timeout })
125
+ },
126
+ async click(selector) {
127
+ await page.click(selector, { timeout })
128
+ },
129
+ async hover(selector) {
130
+ await page.hover(selector, { timeout })
131
+ },
132
+ async fill(selector, value) {
133
+ await page.fill(selector, value, { timeout })
134
+ },
135
+ async press(key) {
136
+ await page.keyboard.press(key)
137
+ },
138
+ async text(selector) {
139
+ return await page.locator(selector).first().innerText({ timeout })
140
+ },
141
+ async close() {
142
+ await context.close()
143
+ },
144
+ }
145
+ }
146
+
147
+ /** Builds the app for production, serves it on 127.0.0.1 on a free port and opens its pages in Chromium. */
148
+ export async function testBrowser(options: BrowserTestOptions): Promise<BrowserTest> {
149
+ const playwright = await loadPlaywright()
150
+ const executablePath = findBrowser(playwright, options.browserPath)
151
+ const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS
152
+ const app = await testApp({ ...options, minify: options.minify ?? true })
153
+ const server = app.app.serve(0, '127.0.0.1')
154
+ const origin = `http://127.0.0.1:${server.port}`
155
+ const stop = async () => {
156
+ server.stop(true)
157
+ await app.app.dispose?.()
158
+ }
159
+ let browser: Browser
160
+ try {
161
+ browser = await playwright.chromium.launch({ headless: true, executablePath })
162
+ }
163
+ catch (error) {
164
+ await stop()
165
+ throw error
166
+ }
167
+ return {
168
+ app,
169
+ origin,
170
+ async open(path, openOptions) {
171
+ const context = await browser.newContext(openOptions?.reducedMotion === true ? { reducedMotion: 'reduce' } : undefined)
172
+ try {
173
+ const page = await context.newPage()
174
+ const url = new URL(path, origin).href
175
+ const wrapped = wrapPage(page, context, timeout)
176
+ // Not `networkidle`: a page that polls or streams never goes idle.
177
+ await page.goto(url, { waitUntil: 'load', timeout })
178
+ try {
179
+ await page.waitForFunction(ISLANDS_HYDRATED, undefined, { timeout })
180
+ }
181
+ catch (error) {
182
+ const seen = wrapped.errors.length > 0 ? `; the page reported: ${wrapped.errors.join('; ')}` : ''
183
+ throw new Error(`prunelle: the islands of ${url} did not hydrate within ${timeout} ms${seen}.`, { cause: error })
184
+ }
185
+ return wrapped
186
+ }
187
+ catch (error) {
188
+ await context.close().catch(() => undefined)
189
+ throw error
190
+ }
191
+ },
192
+ async close() {
193
+ try {
194
+ await browser.close()
195
+ }
196
+ finally {
197
+ await stop()
198
+ }
199
+ },
200
+ }
201
+ }