prunelle 0.7.7 → 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.
Files changed (189) hide show
  1. package/llms.txt +63 -46
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +6 -10
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +88 -134
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +15 -7
  14. package/src/build/index.ts +20 -10
  15. package/src/build/island-promote.ts +1 -1
  16. package/src/build/islands.ts +4 -1
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +19 -1
  19. package/src/build/plugin-host.ts +2 -0
  20. package/src/build/prerender.ts +2 -2
  21. package/src/build/reach.ts +14 -1
  22. package/src/build/report.ts +1 -1
  23. package/src/build/route-types.ts +16 -0
  24. package/src/build/routes.ts +24 -15
  25. package/src/build/seed-ids.ts +65 -0
  26. package/src/build/seed-writes.ts +111 -0
  27. package/src/build/static-headers.ts +2 -2
  28. package/src/build/static.ts +1 -1
  29. package/src/cli/check-cache.ts +51 -0
  30. package/src/cli/check-consent.ts +95 -0
  31. package/src/cli/check-forms.ts +2 -2
  32. package/src/cli/check-links-patterns.ts +101 -0
  33. package/src/cli/check-links.ts +16 -100
  34. package/src/cli/check-regions.ts +185 -0
  35. package/src/cli/check-security.ts +57 -6
  36. package/src/cli/check.ts +40 -17
  37. package/src/cli/commands.ts +134 -14
  38. package/src/cli/docs.ts +21 -2
  39. package/src/cli/index.ts +1 -1
  40. package/src/cli/inspect.ts +2 -0
  41. package/src/cli/mcp-tools.ts +2 -2
  42. package/src/cli/new.ts +9 -5
  43. package/src/cli/upgrade-names.ts +14 -2
  44. package/src/cli/upgrade.ts +3 -0
  45. package/src/compiler/analyze.ts +18 -4
  46. package/src/compiler/cacheability.ts +24 -2
  47. package/src/compiler/compliance-contrast.ts +284 -0
  48. package/src/compiler/compliance-empty.ts +24 -0
  49. package/src/compiler/compliance-rgaa-content.ts +95 -0
  50. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  51. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  52. package/src/compiler/compliance-rgaa.ts +19 -0
  53. package/src/compiler/compliance-third-party.ts +59 -0
  54. package/src/compiler/compliance-urls.ts +52 -0
  55. package/src/compiler/compliance.ts +72 -42
  56. package/src/compiler/cookie-inventory.ts +119 -0
  57. package/src/compiler/dom-attrs.ts +4 -1
  58. package/src/compiler/emit.ts +1 -1
  59. package/src/compiler/foreign-imports.ts +5 -3
  60. package/src/compiler/mistakes.ts +18 -9
  61. package/src/compiler/props-pattern.ts +211 -0
  62. package/src/compiler/props.ts +177 -346
  63. package/src/compiler/shared.ts +9 -16
  64. package/src/compiler/ssr-emit.ts +510 -0
  65. package/src/compiler/ssr-helpers.ts +170 -121
  66. package/src/compiler/ssr.ts +25 -440
  67. package/src/context.ts +14 -1
  68. package/src/dev/child.ts +1 -1
  69. package/src/dev/hot-islands.ts +71 -0
  70. package/src/dev/index.ts +31 -18
  71. package/src/dev/protocol.ts +1 -1
  72. package/src/dev/queue.ts +3 -2
  73. package/src/dev/reload.ts +1 -1
  74. package/src/dev/supervisor.ts +3 -1
  75. package/src/dev/watchers.ts +6 -2
  76. package/src/dom/action.ts +97 -14
  77. package/src/dom/attrs.ts +8 -0
  78. package/src/dom/extras.ts +2 -1
  79. package/src/dom/field-marks.ts +24 -0
  80. package/src/dom/hot.ts +9 -0
  81. package/src/dom/index.ts +25 -5
  82. package/src/dom/island-hot.ts +29 -0
  83. package/src/dom/island.ts +13 -2
  84. package/src/dom/prefetch.ts +132 -0
  85. package/src/dom/regions.ts +498 -0
  86. package/src/dom/swap.ts +245 -0
  87. package/src/dom/trusted.ts +22 -0
  88. package/src/dom/upload.ts +44 -0
  89. package/src/eco/declaration.ts +39 -40
  90. package/src/eco/index.ts +5 -5
  91. package/src/href.ts +31 -0
  92. package/src/index.ts +9 -3
  93. package/src/plugins/config.ts +1 -1
  94. package/src/plugins/context.ts +7 -1
  95. package/src/plugins/daily.ts +27 -0
  96. package/src/plugins/index.ts +3 -3
  97. package/src/plugins/order.ts +1 -1
  98. package/src/plugins/public.ts +8 -5
  99. package/src/plugins/services.ts +88 -14
  100. package/src/plugins/types.ts +121 -10
  101. package/src/reactivity/hmr.ts +90 -0
  102. package/src/reactivity/index.ts +38 -18
  103. package/src/reactivity/resource.ts +115 -0
  104. package/src/reactivity/seed.ts +39 -0
  105. package/src/reactivity/server-seed.ts +194 -0
  106. package/src/reactivity/store.ts +55 -1
  107. package/src/rgpd/draft.ts +171 -0
  108. package/src/rgpd/forms.ts +85 -0
  109. package/src/rgpd/index.ts +57 -0
  110. package/src/server/action-flash.ts +1 -0
  111. package/src/server/action-registry.ts +6 -8
  112. package/src/server/action.ts +51 -19
  113. package/src/server/app-secret.ts +22 -17
  114. package/src/server/cache-invalidation.ts +96 -0
  115. package/src/server/compress.ts +3 -1
  116. package/src/server/consent.ts +16 -2
  117. package/src/server/cookie-inventory.ts +78 -0
  118. package/src/server/cookies.ts +50 -0
  119. package/src/server/csp-report.ts +86 -0
  120. package/src/server/discard.ts +13 -0
  121. package/src/server/document.ts +7 -4
  122. package/src/server/env.ts +1 -1
  123. package/src/server/errors.ts +9 -2
  124. package/src/server/field-errors.ts +91 -0
  125. package/src/server/form-schema.ts +16 -11
  126. package/src/server/health.ts +35 -14
  127. package/src/server/http.ts +25 -10
  128. package/src/server/index.ts +102 -299
  129. package/src/server/loader.ts +1 -0
  130. package/src/server/page.ts +11 -24
  131. package/src/server/plugin-host.ts +26 -8
  132. package/src/server/public.ts +14 -3
  133. package/src/server/rate-limit.ts +39 -10
  134. package/src/server/region.ts +3 -0
  135. package/src/server/request-handler.ts +370 -0
  136. package/src/server/request-log.ts +94 -0
  137. package/src/server/route-cache.ts +41 -6
  138. package/src/server/route-input.ts +54 -0
  139. package/src/server/route-table.ts +35 -19
  140. package/src/server/routing.ts +12 -11
  141. package/src/server/sanitize-html.ts +1 -1
  142. package/src/server/security.ts +81 -20
  143. package/src/server/serve-handlers.ts +9 -5
  144. package/src/server/shared-store.ts +314 -0
  145. package/src/server/start.ts +12 -5
  146. package/src/server/static-dir.ts +14 -10
  147. package/src/server/stream.ts +2 -1
  148. package/src/server/surface.ts +39 -0
  149. package/src/server/webhook.ts +48 -0
  150. package/src/server/workers.ts +168 -0
  151. package/src/ssr/consent-banner.ts +20 -16
  152. package/src/ssr/consent-texts.ts +40 -0
  153. package/src/ssr/context.ts +26 -3
  154. package/src/ssr/cookie-table.ts +75 -0
  155. package/src/ssr/index.ts +23 -13
  156. package/src/ssr/navigation.ts +161 -14
  157. package/src/test/browser.ts +50 -22
  158. package/src/test/build-reuse.ts +70 -0
  159. package/src/test/index.ts +45 -6
  160. package/src/test/mount.ts +53 -0
  161. package/src/test/outside.ts +94 -0
  162. package/templates/_shared/AGENTS.md +1 -1
  163. package/templates/_shared/Dockerfile +22 -0
  164. package/templates/_shared/dockerignore +9 -0
  165. package/templates/_shared/gitignore +2 -0
  166. package/templates/app/.env.example +3 -1
  167. package/templates/app/compose.yaml +32 -0
  168. package/templates/app/db/migrations/001_notes.sql +7 -0
  169. package/templates/app/db/schema.ts +11 -0
  170. package/templates/app/package.json +1 -0
  171. package/templates/app/prunelle.config.ts +6 -0
  172. package/templates/app/src/actions/notes.ts +26 -0
  173. package/templates/app/src/auth.ts +4 -2
  174. package/templates/app/src/db.ts +5 -0
  175. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  176. package/templates/app/src/routes/privacy.tsx +6 -2
  177. package/templates/app/tests/app.test.ts +14 -3
  178. package/templates/plugin/AGENTS.md +11 -0
  179. package/templates/plugin/CLAUDE.md +1 -0
  180. package/templates/plugin/README.md +27 -0
  181. package/templates/plugin/gitignore +2 -0
  182. package/templates/plugin/llms.txt +19 -0
  183. package/templates/plugin/package.json +33 -0
  184. package/templates/plugin/src/index.ts +40 -0
  185. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  186. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  187. package/templates/plugin/tests/plugin.test.ts +42 -0
  188. package/templates/plugin/tsconfig.json +19 -0
  189. package/ts-plugin.cjs +3674 -2196
package/src/ssr/index.ts CHANGED
@@ -10,7 +10,7 @@ import { extractFormSchema, lookupFieldConstraint } from '../server/form-schema'
10
10
  import { styleText } from '../style'
11
11
  import { assertRenderable } from '../unrenderable'
12
12
  import { currentFormFields, currentRenderContext, lookupFormAction, PRUNELLE_STREAM_SCRIPT, renderIsland, runWithFormFields } from './context'
13
- import { KEEP_SCROLL_TAG, keepScrollTag } from './navigation'
13
+ import { withKeepScroll } from './navigation'
14
14
  export { ssrStyleBlock } from './context'
15
15
 
16
16
  export const PRUNELLE_ISLAND_STYLE = 'pru-island,pru-slot{display:contents}'
@@ -300,10 +300,11 @@ export function ssrLoop<T>(items: Iterable<T> | null | undefined | false, render
300
300
  if (!items)
301
301
  return ''
302
302
  const list: readonly T[] = Array.isArray(items) ? items : [...items]
303
- let out = ''
303
+ // Joined once, like the loops the compiler writes inline: `+=` would leave a rope node per row for the garbage collector.
304
+ const out: string[] = []
304
305
  for (let i = 0; i < list.length; i++)
305
- out += render(list[i] as T, i, list)
306
- return out
306
+ out.push(render(list[i] as T, i, list))
307
+ return out.join('')
307
308
  }
308
309
 
309
310
  export function ssrChild(value: PrunelleChild): string {
@@ -395,7 +396,7 @@ export function ssrInIsland(render: () => string, chunk?: string, hydrate?: Hydr
395
396
  recordRenderedIsland(chunk, hydrate)
396
397
  ctx.islandDepth++
397
398
  try {
398
- return renderOnServer(ctx.islandDepth === 1 ? () => renderIsland(ctx, name, render) : render)
399
+ return renderOnServer(ctx.islandDepth === 1 ? () => renderIsland(ctx, name, render) : render, ctx.seeds ??= { ops: [], out: undefined })
399
400
  }
400
401
  finally {
401
402
  ctx.islandDepth--
@@ -475,6 +476,9 @@ function renderIslandBody(
475
476
  inner = ssrInIsland(render, undefined, undefined, name)
476
477
  if (ctx.idSeq > 0)
477
478
  idAttr = ` i="${islandPrefix}"`
479
+ // The module state this island wrote, for the browser to start from as the server rendered it.
480
+ if (ctx.seeds?.out !== undefined)
481
+ idAttr += ` s="${escAttr(JSON.stringify(ctx.seeds.out))}"`
478
482
  }
479
483
  finally {
480
484
  ctx.idPrefix = prevPrefix
@@ -556,8 +560,10 @@ export interface DocumentOptions {
556
560
  htmlAttrs?: Record<string, string> | undefined
557
561
  runtimeScript?: string | undefined
558
562
  alwaysLoadRuntime?: boolean | undefined
559
- /** Set on a route that renders a `<Region>`: the plugins' `regionClientEntry` bundle. */
563
+ /** Set on a route that renders a `<Region>`: the core region client bundle. */
560
564
  regionScript?: string | undefined
565
+ /** The manifest's `buildId`, stamped on the region script so a swap can tell an answer from another build. */
566
+ buildId?: string | undefined
561
567
  preloadChunks?: Iterable<string> | undefined
562
568
  /** Script URL to the chunks it imports statically, preloaded with it: the browser then fetches them all at once. */
563
569
  chunkImports?: Readonly<Record<string, readonly string[]>> | undefined
@@ -576,7 +582,7 @@ const TAB_ICON_RE = /<link\b[^>]*\brel=["']?(?:[^"'>]*\s)?icon(?=[\s"'>])/i
576
582
  const EMPTY_ICON = '<link rel="icon" href="data:,">'
577
583
 
578
584
  export function renderDocument(options: DocumentOptions): string {
579
- const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, regionScript, preloadChunks, chunkImports, styles, hasIslands, hasSuspense, hasFavicon, navigation } = options
585
+ const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, regionScript, buildId, preloadChunks, chunkImports, styles, hasIslands, hasSuspense, hasFavicon, navigation } = options
580
586
  let headExtra = head
581
587
 
582
588
  if (headTags !== undefined) {
@@ -603,8 +609,10 @@ export function renderDocument(options: DocumentOptions): string {
603
609
  for (const dep of chunkImports?.[script] ?? [])
604
610
  preloads.add(dep)
605
611
  }
606
- if (hasIslands) {
612
+ const hasCombinedIslandStyle = headExtra.includes('pru-island,pru-slot,pru-s{display:contents}')
613
+ if (!hasCombinedIslandStyle && (hasIslands || (regionScript !== undefined && runtimeScript !== undefined)))
607
614
  headExtra += `<style>${PRUNELLE_ISLAND_STYLE}</style>`
615
+ if (hasIslands) {
608
616
  for (const chunk of preloadChunks ?? [])
609
617
  preload(chunk, true)
610
618
  }
@@ -614,12 +622,15 @@ export function renderDocument(options: DocumentOptions): string {
614
622
  headExtra += `<link rel="modulepreload" href="${escAttr(href)}">`
615
623
 
616
624
  if (hasSuspense)
617
- headExtra += `<style>${PRUNELLE_SUSPENSE_STYLE}</style><script>${PRUNELLE_STREAM_SCRIPT}</script>`
625
+ headExtra += `${hasCombinedIslandStyle ? '' : `<style>${PRUNELLE_SUSPENSE_STYLE}</style>`}<script>${PRUNELLE_STREAM_SCRIPT}</script>`
618
626
 
619
627
  if (loadsRuntime)
620
628
  headExtra += `<script type="module" src="${escAttr(runtimeScript)}"></script>`
621
- if (regionScript !== undefined)
622
- headExtra += `<script type="module" src="${escAttr(regionScript)}"></script>`
629
+ if (regionScript !== undefined) {
630
+ const buildAttr = buildId === undefined ? '' : ` data-pru-build="${escAttr(buildId)}"`
631
+ const runtimeAttr = !loadsRuntime && runtimeScript !== undefined ? ` data-pru-runtime="${escAttr(runtimeScript)}"` : ''
632
+ headExtra += `<script type="module" src="${escAttr(regionScript)}"${buildAttr}${runtimeAttr}></script>`
633
+ }
623
634
 
624
635
  let attrStr = ''
625
636
  const effectiveLang = htmlAttrs?.lang ?? lang
@@ -631,6 +642,5 @@ export function renderDocument(options: DocumentOptions): string {
631
642
  }
632
643
  }
633
644
 
634
- const scrollTag = keepScrollTag(body) || (hasSuspense ? KEEP_SCROLL_TAG : '')
635
- return `<!DOCTYPE html><html${attrStr}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${headExtra}</head><body>${body}${scrollTag}</body></html>`
645
+ return withKeepScroll(`<!DOCTYPE html><html${attrStr}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${headExtra}</head><body>`, body, '</body></html>', hasSuspense)
636
646
  }
@@ -50,12 +50,14 @@ export function checkNavigationConfig(config: NavigationConfig | undefined): voi
50
50
  }
51
51
 
52
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]` } }] }
53
+ function rulesWhere(assetPrefix = '/_pru'): object {
54
+ const trimmed = assetPrefix.replace(/\/+$/, '')
55
+ const internalPattern = trimmed.startsWith('/') && trimmed.length > 1 ? `${trimmed}/*` : '/_pru/*'
56
+ return { and: [{ href_matches: '/*' }, { not: { href_matches: internalPattern } }, { not: { selector_matches: `[${NO_PREFETCH_ATTR}], [${NO_PREFETCH_ATTR}] a, [download], [rel~=nofollow]` } }] }
55
57
  }
56
58
 
57
59
  /** 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 {
60
+ export function createNavigation(config: NavigationConfig | undefined, assetPrefix?: string): Navigation {
59
61
  checkNavigationConfig(config)
60
62
  const styleHashes: string[] = []
61
63
  const scriptHashes = [cspSha256(KEEP_SCROLL_SCRIPT)]
@@ -67,7 +69,7 @@ export function createNavigation(config: NavigationConfig | undefined): Navigati
67
69
  const prefetch = config?.prefetch === undefined ? 'conservative' : config.prefetch
68
70
  const prerender = config?.prerender === true ? 'moderate' : config?.prerender || undefined
69
71
  if (prefetch !== false || prerender !== undefined) {
70
- const where = rulesWhere()
72
+ const where = rulesWhere(assetPrefix)
71
73
  const rules: Record<string, unknown[]> = {}
72
74
  if (prefetch !== false)
73
75
  rules.prefetch = [{ source: 'document', where, eagerness: prefetch }]
@@ -80,17 +82,162 @@ export function createNavigation(config: NavigationConfig | undefined): Navigati
80
82
  return { html, styleHashes, scriptHashes }
81
83
  }
82
84
 
83
- const DUPLICATE_RE = new RegExp(` ${KEEP_SCROLL_ATTR}="([^"]*)"`, 'g')
85
+ const KEEP_SCROLL_MARK = ` ${KEEP_SCROLL_ATTR}`
86
+ const TAG_NAME_RE = /^([a-z][a-z0-9:-]*)/i
87
+ const ATTR_NAME_RE = /^[a-z0-9_:-]+/i
88
+ const RAW_TEXT_TAGS = new Set(['script', 'style', 'textarea', 'title'])
84
89
 
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 ''
90
+ function findTagEnd(html: string, start: number): number {
91
+ for (let i = start; i < html.length; i++) {
92
+ const ch = html.charCodeAt(i)
93
+ if (ch === 34 || ch === 39) {
94
+ const close = html.indexOf(ch === 34 ? '"' : '\'', i + 1)
95
+ if (close === -1)
96
+ return -1
97
+ i = close
98
+ }
99
+ else if (ch === 62) {
100
+ return i
101
+ }
102
+ }
103
+ return -1
104
+ }
105
+
106
+ function scanTagKeepScroll(html: string, start: number, end: number, seen: Set<string>): boolean {
107
+ let found = false
108
+ let i = start
109
+ while (i < end) {
110
+ while (i < end && (html.charCodeAt(i) <= 32 || html.charCodeAt(i) === 47))
111
+ i++
112
+ if (i >= end)
113
+ break
114
+ const nameMatch = ATTR_NAME_RE.exec(html.slice(i, end))
115
+ if (nameMatch === null) {
116
+ i++
117
+ continue
118
+ }
119
+ const name = nameMatch[0].toLowerCase()
120
+ i += name.length
121
+ while (i < end && html.charCodeAt(i) <= 32)
122
+ i++
123
+ let value = ''
124
+ if (i < end && html.charCodeAt(i) === 61) {
125
+ i++
126
+ while (i < end && html.charCodeAt(i) <= 32)
127
+ i++
128
+ if (i < end) {
129
+ const q = html.charCodeAt(i)
130
+ if (q === 34 || q === 39) {
131
+ const close = html.indexOf(q === 34 ? '"' : '\'', i + 1)
132
+ const valEnd = close === -1 || close > end ? end : close
133
+ value = html.slice(i + 1, valEnd)
134
+ i = valEnd + 1
135
+ }
136
+ else {
137
+ let valEnd = i
138
+ while (valEnd < end && html.charCodeAt(valEnd) > 32)
139
+ valEnd++
140
+ value = html.slice(i, valEnd)
141
+ i = valEnd
142
+ }
143
+ }
144
+ }
145
+ if (name === KEEP_SCROLL_ATTR) {
146
+ found = true
147
+ if (seen.has(value))
148
+ throw new Error(`prunelle: ${KEEP_SCROLL_ATTR}="${value}" is on two elements of one page: give each panel its own key.`)
149
+ seen.add(value)
150
+ }
151
+ }
152
+ return found
153
+ }
154
+
155
+ // Scans only real element open tags outside comments, raw-text elements, and `<code>`/`<pre>` bodies so literal docs/code text never triggers false-positive duplicate errors.
156
+ function scanKeepScrollBody(body: string): boolean {
89
157
  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!)
158
+ let found = false
159
+ let codeDepth = 0
160
+ let preDepth = 0
161
+ let i = 0
162
+ while (i < body.length) {
163
+ const lt = body.indexOf('<', i)
164
+ if (lt === -1)
165
+ break
166
+ if (body.startsWith('<!--', lt)) {
167
+ const end = body.indexOf('-->', lt + 4)
168
+ if (end === -1)
169
+ break
170
+ i = end + 3
171
+ continue
172
+ }
173
+ const next = body.charCodeAt(lt + 1)
174
+ if (next === 47) {
175
+ const tagMatch = TAG_NAME_RE.exec(body.slice(lt + 2, lt + 32))
176
+ const gt = body.indexOf('>', lt + 2)
177
+ if (tagMatch !== null) {
178
+ const tag = tagMatch[1]!.toLowerCase()
179
+ if (tag === 'code' && codeDepth > 0)
180
+ codeDepth--
181
+ else if (tag === 'pre' && preDepth > 0)
182
+ preDepth--
183
+ }
184
+ if (gt === -1)
185
+ break
186
+ i = gt + 1
187
+ continue
188
+ }
189
+ if (next === 33 || next === 63) {
190
+ const gt = body.indexOf('>', lt + 2)
191
+ if (gt === -1)
192
+ break
193
+ i = gt + 1
194
+ continue
195
+ }
196
+ const tagMatch = TAG_NAME_RE.exec(body.slice(lt + 1, lt + 32))
197
+ if (tagMatch === null) {
198
+ i = lt + 1
199
+ continue
200
+ }
201
+ const tag = tagMatch[1]!.toLowerCase()
202
+ const attrsStart = lt + 1 + tag.length
203
+ const gt = findTagEnd(body, attrsStart)
204
+ if (gt === -1)
205
+ break
206
+ const selfClosing = body.charCodeAt(gt - 1) === 47
207
+ if (codeDepth === 0 && preDepth === 0) {
208
+ const markAt = body.indexOf(KEEP_SCROLL_ATTR, attrsStart)
209
+ if (markAt !== -1 && markAt < gt && scanTagKeepScroll(body, attrsStart, selfClosing ? gt - 1 : gt, seen))
210
+ found = true
211
+ }
212
+ if (!selfClosing && RAW_TEXT_TAGS.has(tag)) {
213
+ const closeRe = new RegExp(`</${tag}\\s*>`, 'gi')
214
+ closeRe.lastIndex = gt + 1
215
+ const closeMatch = closeRe.exec(body)
216
+ if (closeMatch === null)
217
+ break
218
+ i = closeMatch.index + closeMatch[0].length
219
+ continue
220
+ }
221
+ if (!selfClosing) {
222
+ if (tag === 'code')
223
+ codeDepth++
224
+ else if (tag === 'pre')
225
+ preDepth++
226
+ }
227
+ i = gt + 1
94
228
  }
95
- return KEEP_SCROLL_TAG
229
+ return found
230
+ }
231
+
232
+ /** `before + body + after`, with the script keeping the scroll offset of the panels `body` marks ahead of `after`, or always when `always`: a page marking none costs one `indexOf`. Two panels of one key throw, as the browser could keep only one offset for them. */
233
+ export function withKeepScroll(before: string, body: string, after: string, always = false): string {
234
+ // The joined page is searched, not `body`: searching a string built with `+` copies it into one buffer, the joined page would then be copied again, and the Response needs it in one buffer anyway.
235
+ const html = before + body + (always ? KEEP_SCROLL_TAG : '') + after
236
+ const end = before.length + body.length
237
+ const first = html.indexOf(KEEP_SCROLL_MARK, before.length)
238
+ if (first === -1 || first >= end)
239
+ return html
240
+ if (!scanKeepScrollBody(body))
241
+ return html
242
+ return always ? html : before + body + KEEP_SCROLL_TAG + after
96
243
  }
@@ -1,8 +1,10 @@
1
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
2
 
3
3
  import type { TestApp, TestAppOptions } from './index'
4
+ import type { MountedApp } from './mount'
4
5
  import { existsSync } from 'node:fs'
5
6
  import { testApp } from './index'
7
+ import { serveMount } from './mount'
6
8
 
7
9
  export interface BrowserTestOptions extends TestAppOptions {
8
10
  /** Chrome or Chromium executable; defaults to `BUN_CHROME_PATH`, Playwright's own, then the system's. */
@@ -36,11 +38,15 @@ export interface BrowserTest {
36
38
  /** `http://127.0.0.1:<port>`, a port the test owns. */
37
39
  readonly origin: string
38
40
  /** 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>
41
+ open(path: string, options?: OpenOptions): Promise<BrowserPage>
42
+ /** Opens the component `file` exports (its default export, or `export`) alone on an empty page with `props` (JSON values), built and hydrated as the app's pages are; the app is built once per component. */
43
+ mount(file: string, props?: Record<string, unknown>, options?: OpenOptions & { export?: string | undefined }): Promise<BrowserPage>
40
44
  /** Closes the browser and the server. */
41
45
  close(): Promise<void>
42
46
  }
43
47
 
48
+ interface OpenOptions { reducedMotion?: boolean | undefined }
49
+
44
50
  const DEFAULT_TIMEOUT_MS = 10_000
45
51
 
46
52
  // The few playwright-core types used here, so an app's typecheck never needs playwright-core installed.
@@ -69,7 +75,13 @@ interface Browser {
69
75
  }
70
76
 
71
77
  // 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 })`
78
+ // Passed as a function (not a string) so Playwright evaluates it via CDP rather than `eval()`, which strict CSP + Trusted Types blocks.
79
+ function islandsHydrated(): boolean {
80
+ return [...document.querySelectorAll('pru-island')].every((el) => {
81
+ const h = el.getAttribute('h')
82
+ return h === 'visible' || h === 'idle' || h === 'interaction' || (h !== null && h.startsWith('media(')) || (el as Element & { _d?: unknown })._d !== undefined
83
+ })
84
+ }
73
85
 
74
86
  interface PlaywrightCore {
75
87
  chromium: { launch: (options: { headless: boolean, executablePath: string }) => Promise<Browser>, executablePath: () => string }
@@ -164,36 +176,52 @@ export async function testBrowser(options: BrowserTestOptions): Promise<BrowserT
164
176
  await stop()
165
177
  throw error
166
178
  }
167
- return {
168
- app,
169
- origin,
170
- async open(path, openOptions) {
171
- const context = await browser.newContext(openOptions?.reducedMotion === true ? { reducedMotion: 'reduce' } : undefined)
179
+ const mounts = new Map<string, Promise<MountedApp>>()
180
+ const openAt = async (at: string, path: string, openOptions: OpenOptions | undefined): Promise<BrowserPage> => {
181
+ const context = await browser.newContext(openOptions?.reducedMotion === true ? { reducedMotion: 'reduce' } : undefined)
182
+ try {
183
+ const page = await context.newPage()
184
+ const url = new URL(path, at).href
185
+ const wrapped = wrapPage(page, context, timeout)
186
+ // Not `networkidle`: a page that polls or streams never goes idle.
187
+ await page.goto(url, { waitUntil: 'load', timeout })
172
188
  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
189
+ await page.waitForFunction(islandsHydrated, undefined, { timeout })
186
190
  }
187
191
  catch (error) {
188
- await context.close().catch(() => undefined)
189
- throw error
192
+ const seen = wrapped.errors.length > 0 ? `; the page reported: ${wrapped.errors.join('; ')}` : ''
193
+ throw new Error(`prunelle: the islands of ${url} did not hydrate within ${timeout} ms${seen}.`, { cause: error })
194
+ }
195
+ return wrapped
196
+ }
197
+ catch (error) {
198
+ await context.close().catch(() => undefined)
199
+ throw error
200
+ }
201
+ }
202
+ return {
203
+ app,
204
+ origin,
205
+ open: async (path, openOptions) => openAt(origin, path, openOptions),
206
+ async mount(file, props = {}, mountOptions) {
207
+ const exportName = mountOptions?.export ?? 'default'
208
+ const key = `${file}#${exportName}`
209
+ let mounted = mounts.get(key)
210
+ if (mounted === undefined) {
211
+ mounted = serveMount(options, file, exportName)
212
+ mounts.set(key, mounted)
213
+ // A mount that failed to build is tried again by the next call rather than failing it too.
214
+ mounted.catch(() => mounts.delete(key))
190
215
  }
216
+ return openAt((await mounted).origin, `/?props=${encodeURIComponent(JSON.stringify(props))}`, mountOptions)
191
217
  },
192
218
  async close() {
193
219
  try {
194
220
  await browser.close()
195
221
  }
196
222
  finally {
223
+ const built = await Promise.allSettled(mounts.values())
224
+ await Promise.all(built.map(async result => result.status === 'fulfilled' ? result.value.close() : undefined))
197
225
  await stop()
198
226
  }
199
227
  },
@@ -0,0 +1,70 @@
1
+ // testApp() builds an app once per test run: `bun test` runs every file in one process, so a later call with the same build options, environment and files reuses the build the first one made.
2
+
3
+ import type { BuildManifest } from '../build/index'
4
+ import { readdirSync, readFileSync, statSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+
7
+ /** The build options that change what a build writes; a call passing `plugins` or an analysis callback always builds. */
8
+ export interface ReusableBuildOptions {
9
+ routesDir?: string | undefined
10
+ publicDir?: string | undefined
11
+ minify?: boolean | undefined
12
+ assetPrefix?: string | undefined
13
+ site?: string | undefined
14
+ cache?: unknown
15
+ maxJs?: unknown
16
+ prerender?: unknown
17
+ autoPrerender?: unknown
18
+ copyPublic?: boolean | undefined
19
+ dev?: boolean | undefined
20
+ nodeEnv?: string | undefined
21
+ }
22
+
23
+ const SKIPPED_DIRS = new Set(['node_modules', '.git', '.prunelle-cache', '.prunelle-dev', 'dist', 'data', 'data-prod'])
24
+ // Files up to this size are fingerprinted by content, larger ones by size and modification time.
25
+ const HASHED_MAX_BYTES = 64 * 1024
26
+
27
+ /** A build testApp() made: the folder it wrote and its manifest. */
28
+ export interface TestBuild {
29
+ outDir: string
30
+ manifest: BuildManifest
31
+ }
32
+
33
+ const lastBuilds = new Map<string, { key: string, build: TestBuild }>()
34
+
35
+ /** This process's last build of `root` when nothing it depends on has changed since. */
36
+ export function reusableBuild(root: string, options: ReusableBuildOptions): TestBuild | undefined {
37
+ const last = lastBuilds.get(root)
38
+ return last !== undefined && last.key === buildKey(root, options) ? last.build : undefined
39
+ }
40
+
41
+ /** Remembers a build of `root`, keyed on the files as the build left them: it writes route types into `src/`. */
42
+ export function rememberBuild(root: string, options: ReusableBuildOptions, build: TestBuild): void {
43
+ lastBuilds.set(root, { key: buildKey(root, options), build })
44
+ }
45
+
46
+ function buildKey(root: string, options: ReusableBuildOptions): string {
47
+ const env = Object.entries(process.env).sort(([a], [b]) => a < b ? -1 : 1)
48
+ return `${JSON.stringify(options)}\n${JSON.stringify(env)}\n${fingerprint(root)}`
49
+ }
50
+
51
+ function fingerprint(root: string): string {
52
+ const parts: string[] = []
53
+ const walk = (dir: string, rel: string): void => {
54
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : 1)) {
55
+ const path = join(dir, entry.name)
56
+ const relPath = rel === '' ? entry.name : `${rel}/${entry.name}`
57
+ if (entry.isDirectory()) {
58
+ if (!SKIPPED_DIRS.has(entry.name))
59
+ walk(path, relPath)
60
+ continue
61
+ }
62
+ if (!entry.isFile())
63
+ continue
64
+ const { size, mtimeMs } = statSync(path)
65
+ parts.push(`${relPath}:${size}:${size <= HASHED_MAX_BYTES ? Bun.hash(readFileSync(path)).toString(36) : mtimeMs}`)
66
+ }
67
+ }
68
+ walk(root, '')
69
+ return Bun.hash(parts.join('\n')).toString(36)
70
+ }
package/src/test/index.ts CHANGED
@@ -11,6 +11,9 @@ import { ensureCacheGitignore } from '../build/precompress'
11
11
  import { resolveServerConfig } from '../server/index'
12
12
  import { FORM_TIMESTAMP_FIELD, honeypotFieldName, signFormTimestamp } from '../server/action-protect'
13
13
  import { startBuiltApp } from '../server/loader'
14
+ import { rememberBuild, reusableBuild, type TestBuild } from './build-reuse'
15
+ import type { StubAnswer, TestClock } from './outside'
16
+ import { guardOutgoing, testClock } from './outside'
14
17
 
15
18
  const TEST_DIR_PREFIX = 'test-'
16
19
  const ABSOLUTE_URL_RE = /^https?:\/\//i
@@ -80,7 +83,11 @@ export interface TestApp {
80
83
  /** Posts `fields` as a form to an action, given as one from `import()` or as its URL. */
81
84
  submit(action: ServerAction<never, unknown> | string, fields: Record<string, string>, headers?: HeadersInit): Promise<Response>
82
85
  clearCookies(): void
83
- /** Runs plugin shutdown hooks and cleans up app resources (idempotent). */
86
+ /** The time the app reads, set and advanced by the test. */
87
+ readonly clock: TestClock
88
+ /** Answers the app's requests to `url` (its origin and path, any query) or to the URLs a RegExp matches. A request leaving the machine that no stub answers is refused, and fails `dispose()`; one to a loopback server of the test goes through. */
89
+ stub(url: string | RegExp, answer: StubAnswer): void
90
+ /** Runs plugin shutdown hooks and cleans up app resources (idempotent), restores the clock and `fetch`, and throws if the app sent a request no stub answered. */
84
91
  dispose(): Promise<void>
85
92
  [Symbol.asyncDispose](): Promise<void>
86
93
  }
@@ -113,10 +120,17 @@ function ownOutDir(root: string): string {
113
120
  return dir
114
121
  }
115
122
 
116
- export async function testApp(options: TestAppOptions): Promise<TestApp> {
117
- const root = resolve(options.root)
118
- const outDir = options.outDir ?? (options.prebuilt ? latestOutDirs.get(root) : ownOutDir(root))
119
- const manifest = options.prebuilt ? undefined : await build({
123
+ /** Builds the app, or reuses the folder of this process's last build when its inputs match: the server modules load under a fresh `?v=`, so two apps never share module state. */
124
+ async function buildForTest(root: string, options: TestAppOptions): Promise<TestBuild> {
125
+ const reusable = options.outDir === undefined && options.plugins === undefined && options.analyze === undefined && options.analyzeJson === undefined && options.onAnalyze === undefined
126
+ const inputs = { routesDir: options.routesDir, publicDir: options.publicDir, minify: options.minify, assetPrefix: options.assetPrefix, site: options.site, cache: options.cache, maxJs: options.maxJs, prerender: options.prerender, autoPrerender: options.autoPrerender, copyPublic: options.copyPublic, dev: options.dev, nodeEnv: options.nodeEnv }
127
+ const reused = reusable ? reusableBuild(root, inputs) : undefined
128
+ if (reused !== undefined && existsSync(reused.outDir)) {
129
+ latestOutDirs.set(root, reused.outDir)
130
+ return reused
131
+ }
132
+ const outDir = options.outDir ?? ownOutDir(root)
133
+ const manifest = await build({
120
134
  root: options.root,
121
135
  routesDir: options.routesDir,
122
136
  outDir,
@@ -136,8 +150,18 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
136
150
  dev: options.dev,
137
151
  nodeEnv: options.nodeEnv,
138
152
  })
153
+ if (reusable)
154
+ rememberBuild(root, inputs, { outDir, manifest })
155
+ return { outDir, manifest }
156
+ }
157
+
158
+ export async function testApp(options: TestAppOptions): Promise<TestApp> {
159
+ const root = resolve(options.root)
160
+ const { outDir, manifest } = options.prebuilt ? { outDir: options.outDir ?? latestOutDirs.get(root), manifest: undefined } : await buildForTest(root, options)
139
161
 
140
162
  const errors: string[] = []
163
+ const outside = guardOutgoing(errors)
164
+ const time = testClock()
141
165
  const { app, entry } = await startBuiltApp({
142
166
  root: options.root,
143
167
  outDir,
@@ -147,6 +171,9 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
147
171
  errorSink: ({ error, request, source }) => {
148
172
  errors.push(`${source} ${request.method} ${new URL(request.url).pathname}: ${error instanceof Error ? error.message : String(error)}`)
149
173
  },
174
+ }).catch((error: unknown) => {
175
+ outside.release()
176
+ throw error
150
177
  })
151
178
 
152
179
  const cookies = new Map<string, string>()
@@ -192,12 +219,21 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
192
219
  }
193
220
 
194
221
  let disposed = false
222
+ const disposeApp = app.dispose
195
223
  async function dispose(): Promise<void> {
196
224
  if (disposed)
197
225
  return
198
226
  disposed = true
199
- await app.dispose?.()
227
+ try {
228
+ await disposeApp?.()
229
+ }
230
+ finally {
231
+ time.restore()
232
+ outside.release()
233
+ }
200
234
  }
235
+ // A test that disposes `testApp().app` itself restores the clock and fetch too.
236
+ app.dispose = dispose
201
237
 
202
238
  return {
203
239
  app,
@@ -253,6 +289,8 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
253
289
  clearCookies() {
254
290
  cookies.clear()
255
291
  },
292
+ clock: time.clock,
293
+ stub: outside.stub,
256
294
  dispose,
257
295
  [Symbol.asyncDispose]: dispose,
258
296
  }
@@ -260,3 +298,4 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
260
298
 
261
299
  export { testBrowser } from './browser'
262
300
  export type { BrowserPage, BrowserTest, BrowserTestOptions } from './browser'
301
+ export type { StubAnswer, TestClock } from './outside'
@@ -0,0 +1,53 @@
1
+ // `browser.mount()`: one component alone on an empty page, built by `prunelle build` and hydrated as the app's own pages are.
2
+
3
+ import type { TestApp, TestAppOptions } from './index'
4
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
5
+ import { join, resolve } from 'node:path'
6
+ import { testApp } from './index'
7
+
8
+ export interface MountedApp {
9
+ readonly app: TestApp
10
+ readonly origin: string
11
+ close: () => Promise<void>
12
+ }
13
+
14
+ const EXPORT_NAME_RE = /^[A-Z_$][\w$]*$/i
15
+
16
+ /** Builds the app with a routes folder holding one page, which renders the component with the props the `props` query parameter carries as JSON. */
17
+ export async function serveMount(options: TestAppOptions, file: string, exportName: string): Promise<MountedApp> {
18
+ const root = resolve(options.root)
19
+ const component = resolve(root, file)
20
+ if (!existsSync(component))
21
+ throw new Error(`prunelle: browser.mount("${file}"): no such file: give the component's path from the app's root.`)
22
+ if (exportName !== 'default' && !EXPORT_NAME_RE.test(exportName))
23
+ throw new Error(`prunelle: browser.mount("${file}"): \`export\` must be the name of an export, got "${exportName}".`)
24
+ const cacheDir = join(root, '.prunelle-cache')
25
+ mkdirSync(cacheDir, { recursive: true })
26
+ const dir = mkdtempSync(join(cacheDir, 'mount-'))
27
+ const routesDir = join(dir, 'routes')
28
+ mkdirSync(routesDir)
29
+ const binding = exportName === 'default' ? 'Mounted' : `{ ${exportName} as Mounted }`
30
+ writeFileSync(join(routesDir, 'index.tsx'), `import ${binding} from ${JSON.stringify(component)}\n\nexport default function Mount({ url }: { url: URL }) {\n return <Mounted {...JSON.parse(url.searchParams.get('props') ?? '{}')} />\n}\n`)
31
+ let app: TestApp
32
+ try {
33
+ app = await testApp({ ...options, routesDir, minify: options.minify ?? true })
34
+ }
35
+ catch (error) {
36
+ rmSync(dir, { recursive: true, force: true })
37
+ throw error
38
+ }
39
+ const server = app.app.serve(0, '127.0.0.1')
40
+ return {
41
+ app,
42
+ origin: `http://127.0.0.1:${server.port}`,
43
+ async close() {
44
+ server.stop(true)
45
+ try {
46
+ await app.dispose()
47
+ }
48
+ finally {
49
+ rmSync(dir, { recursive: true, force: true })
50
+ }
51
+ },
52
+ }
53
+ }