prunelle 0.0.0-stage → 0.1.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 (173) hide show
  1. package/llms.txt +148 -0
  2. package/package.json +53 -4
  3. package/src/ambient.d.ts +6 -0
  4. package/src/attrs.ts +35 -0
  5. package/src/build/bundle.ts +613 -0
  6. package/src/build/carry.ts +57 -0
  7. package/src/build/client-entries.ts +106 -0
  8. package/src/build/client-plugin.ts +169 -0
  9. package/src/build/client-prune.ts +118 -0
  10. package/src/build/compile.ts +127 -0
  11. package/src/build/files.ts +156 -0
  12. package/src/build/first-load.ts +164 -0
  13. package/src/build/graph.ts +247 -0
  14. package/src/build/index.ts +575 -0
  15. package/src/build/is-inside.ts +12 -0
  16. package/src/build/islands.ts +641 -0
  17. package/src/build/manifest.ts +264 -0
  18. package/src/build/output.ts +84 -0
  19. package/src/build/plugin-host.ts +220 -0
  20. package/src/build/precompress.ts +126 -0
  21. package/src/build/prerender.ts +150 -0
  22. package/src/build/render-rules.ts +205 -0
  23. package/src/build/report.ts +247 -0
  24. package/src/build/resolve.ts +50 -0
  25. package/src/build/routes.ts +177 -0
  26. package/src/build/server-entry.ts +38 -0
  27. package/src/build/static.ts +109 -0
  28. package/src/cli/check.ts +334 -0
  29. package/src/cli/commands.ts +265 -0
  30. package/src/cli/index.ts +70 -0
  31. package/src/cli/inspect.ts +316 -0
  32. package/src/cli/new.ts +41 -0
  33. package/src/cli/upgrade-names.ts +149 -0
  34. package/src/cli/upgrade.ts +258 -0
  35. package/src/compiler/analyze.ts +618 -0
  36. package/src/compiler/ast.ts +82 -0
  37. package/src/compiler/browser-globals.ts +127 -0
  38. package/src/compiler/compliance.ts +598 -0
  39. package/src/compiler/data-keys.ts +295 -0
  40. package/src/compiler/dom-attrs.ts +379 -0
  41. package/src/compiler/dom.ts +566 -0
  42. package/src/compiler/emit.ts +131 -0
  43. package/src/compiler/expr-context.ts +408 -0
  44. package/src/compiler/index.ts +8 -0
  45. package/src/compiler/interactivity.ts +366 -0
  46. package/src/compiler/mistakes.ts +499 -0
  47. package/src/compiler/node-env.ts +50 -0
  48. package/src/compiler/patch.ts +97 -0
  49. package/src/compiler/props.ts +460 -0
  50. package/src/compiler/scope.ts +568 -0
  51. package/src/compiler/server-only.ts +326 -0
  52. package/src/compiler/shared.ts +369 -0
  53. package/src/compiler/signal-reads.ts +242 -0
  54. package/src/compiler/slots.ts +227 -0
  55. package/src/compiler/ssr-helpers.ts +555 -0
  56. package/src/compiler/ssr-island.ts +90 -0
  57. package/src/compiler/ssr-prunelle-tags.ts +56 -0
  58. package/src/compiler/ssr.ts +394 -0
  59. package/src/context.ts +165 -0
  60. package/src/dev/child.ts +30 -0
  61. package/src/dev/index.ts +208 -0
  62. package/src/dev/modules.ts +68 -0
  63. package/src/dev/protocol.ts +21 -0
  64. package/src/dev/queue.ts +79 -0
  65. package/src/dev/reload.ts +157 -0
  66. package/src/dev/supervisor.ts +187 -0
  67. package/src/dev/watchers.ts +215 -0
  68. package/src/dom/action.ts +161 -0
  69. package/src/dom/attrs.ts +72 -0
  70. package/src/dom/claim.ts +120 -0
  71. package/src/dom/extras.ts +562 -0
  72. package/src/dom/index.ts +289 -0
  73. package/src/dom/island.ts +284 -0
  74. package/src/dom/loop.ts +450 -0
  75. package/src/dom/revive.ts +36 -0
  76. package/src/index.ts +22 -0
  77. package/src/jsx-runtime.ts +566 -0
  78. package/src/plugins/config.ts +86 -0
  79. package/src/plugins/context.ts +66 -0
  80. package/src/plugins/index.ts +14 -0
  81. package/src/plugins/load.ts +70 -0
  82. package/src/plugins/order.ts +111 -0
  83. package/src/plugins/public.ts +12 -0
  84. package/src/plugins/requires.ts +47 -0
  85. package/src/plugins/services.ts +35 -0
  86. package/src/plugins/types.ts +234 -0
  87. package/src/reactivity/graph.ts +249 -0
  88. package/src/reactivity/index.ts +533 -0
  89. package/src/reactivity/selector.ts +51 -0
  90. package/src/reactivity/store.ts +208 -0
  91. package/src/server/action-registry.ts +78 -0
  92. package/src/server/action.ts +475 -0
  93. package/src/server/app-entry.ts +23 -0
  94. package/src/server/assets.ts +136 -0
  95. package/src/server/compress.ts +560 -0
  96. package/src/server/consent.ts +253 -0
  97. package/src/server/cookies.ts +139 -0
  98. package/src/server/document.ts +271 -0
  99. package/src/server/env.ts +33 -0
  100. package/src/server/errors.ts +153 -0
  101. package/src/server/http.ts +441 -0
  102. package/src/server/index.ts +616 -0
  103. package/src/server/lifecycle.ts +75 -0
  104. package/src/server/loader.ts +118 -0
  105. package/src/server/page.ts +107 -0
  106. package/src/server/plugin-host.ts +251 -0
  107. package/src/server/prerendered.ts +71 -0
  108. package/src/server/public.ts +19 -0
  109. package/src/server/rate-limit.ts +133 -0
  110. package/src/server/region.ts +96 -0
  111. package/src/server/request-body.ts +27 -0
  112. package/src/server/request-path.ts +73 -0
  113. package/src/server/request-scope.ts +22 -0
  114. package/src/server/route-table.ts +79 -0
  115. package/src/server/router.ts +184 -0
  116. package/src/server/routing.ts +339 -0
  117. package/src/server/security.ts +323 -0
  118. package/src/server/serve-handlers.ts +69 -0
  119. package/src/server/served-file.ts +128 -0
  120. package/src/server/standard-schema.ts +87 -0
  121. package/src/server/start.ts +99 -0
  122. package/src/server/static-dir.ts +167 -0
  123. package/src/server/stream.ts +192 -0
  124. package/src/ssr/context.ts +301 -0
  125. package/src/ssr/index.ts +477 -0
  126. package/src/ssr/navigation.ts +96 -0
  127. package/src/ssr/region.ts +171 -0
  128. package/src/style.ts +33 -0
  129. package/src/test/browser.ts +186 -0
  130. package/src/test/index.ts +177 -0
  131. package/src/unrenderable.ts +35 -0
  132. package/templates/_shared/AGENTS.md +10 -0
  133. package/templates/_shared/CLAUDE.md +1 -0
  134. package/templates/_shared/gitignore +3 -0
  135. package/templates/_shared/public/robots.txt +2 -0
  136. package/templates/_shared/src/routes/legal.tsx +8 -0
  137. package/templates/_shared/tsconfig.json +20 -0
  138. package/templates/app/.env.example +4 -0
  139. package/templates/app/package.json +21 -0
  140. package/templates/app/prunelle.config.ts +11 -0
  141. package/templates/app/src/auth.ts +14 -0
  142. package/templates/app/src/routes/_layout.tsx +32 -0
  143. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  144. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  145. package/templates/app/src/routes/index.tsx +15 -0
  146. package/templates/app/src/routes/login.tsx +34 -0
  147. package/templates/app/src/styles/app.css +7 -0
  148. package/templates/app/tests/app.test.ts +32 -0
  149. package/templates/blog/content/posts/welcome.md +9 -0
  150. package/templates/blog/package.json +22 -0
  151. package/templates/blog/prunelle.config.ts +23 -0
  152. package/templates/blog/src/posts.ts +26 -0
  153. package/templates/blog/src/routes/_layout.tsx +20 -0
  154. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  155. package/templates/blog/src/routes/index.tsx +29 -0
  156. package/templates/blog/src/styles/app.css +10 -0
  157. package/templates/fullstack/package.json +19 -0
  158. package/templates/fullstack/prunelle.config.ts +6 -0
  159. package/templates/fullstack/src/actions/greet.ts +19 -0
  160. package/templates/fullstack/src/components/Counter.tsx +10 -0
  161. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  162. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  163. package/templates/fullstack/src/routes/api/health.ts +5 -0
  164. package/templates/fullstack/src/routes/index.tsx +13 -0
  165. package/templates/fullstack/src/styles/app.css +29 -0
  166. package/templates/fullstack/tests/app.test.ts +37 -0
  167. package/templates/minimal/package.json +19 -0
  168. package/templates/minimal/prunelle.config.ts +6 -0
  169. package/templates/minimal/src/components/Counter.tsx +10 -0
  170. package/templates/minimal/src/routes/_layout.tsx +14 -0
  171. package/templates/minimal/src/routes/index.tsx +11 -0
  172. package/templates/minimal/src/styles/app.css +22 -0
  173. package/README.md +0 -3
@@ -0,0 +1,477 @@
1
+ // Prunelle SSR runtime: flat string concatenation with fast-path escaping and zero-overhead islands.
2
+
3
+ import type { Html, HydrateStrategy, PrunelleChild } from '../jsx-runtime'
4
+ import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
5
+ import { renderOnServer } from '../reactivity/index'
6
+ import { styleText } from '../style'
7
+ import { assertRenderable } from '../unrenderable'
8
+ import { currentRenderContext, PRUNELLE_STREAM_SCRIPT, renderIsland } from './context'
9
+ import { keepScrollTag } from './navigation'
10
+ export { ssrStyleBlock } from './context'
11
+
12
+ export const PRUNELLE_ISLAND_STYLE = 'pru-island,pru-slot{display:contents}'
13
+ export const PRUNELLE_SUSPENSE_STYLE = 'pru-s{display:contents}'
14
+
15
+ export const RAW_HTML = Symbol.for('pru.html')
16
+
17
+ function isRawHtml(value: unknown): value is Html {
18
+ return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[RAW_HTML] === true && '__html' in value
19
+ }
20
+
21
+ const ESC_TEXT = /[&<>]/
22
+ const ESC_ATTR = /[&"<>]/
23
+ const bunEscape = typeof Bun !== 'undefined' && typeof Bun.escapeHTML === 'function' ? Bun.escapeHTML : undefined
24
+
25
+ function escText(str: string): string {
26
+ if (bunEscape !== undefined)
27
+ return bunEscape(str)
28
+ if (!ESC_TEXT.test(str))
29
+ return str
30
+ return str.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
31
+ }
32
+
33
+ export function esc(value: unknown): string {
34
+ if (typeof value === 'string')
35
+ return escText(value)
36
+ if (typeof value === 'number')
37
+ return String(value)
38
+ if (value == null || typeof value === 'boolean')
39
+ return ''
40
+ if (isRawHtml(value))
41
+ return value.__html
42
+ if (Array.isArray(value)) {
43
+ let out = ''
44
+ for (let i = 0; i < value.length; i++)
45
+ out += esc(value[i])
46
+ return out
47
+ }
48
+ assertRenderable(value, 'text')
49
+ return escText(String(value))
50
+ }
51
+
52
+ export function ssrRaw(value: unknown): string {
53
+ if (value == null || value === false)
54
+ return ''
55
+ if (isRawHtml(value))
56
+ return String(value.__html)
57
+ if (typeof value === 'object' && '__html' in value)
58
+ throw new TypeError(UNBRANDED_INNER_HTML)
59
+ return String(value)
60
+ }
61
+
62
+ /** React's `{ __html }` shape reaching innerHTML unbranded: prunelle would print `[object Object]`. */
63
+ const UNBRANDED_INNER_HTML = 'prunelle: innerHTML takes the HTML string, got a { __html } object; pass the string, or raw(html) for a value typed Html.'
64
+
65
+ const CLOSE_STYLE_RE = /<\/(style)/gi
66
+ const SCRIPT_UNSAFE_RE = /<(\/script|script|!--)/gi
67
+
68
+ /** Emits raw text inside `<style>` or `<script>` without HTML entity escaping, neutralizing dangerous script/style sequences. */
69
+ export function ssrRawText(tag: 'style' | 'script', value: unknown): string {
70
+ if (value == null || typeof value === 'boolean')
71
+ return ''
72
+ if (Array.isArray(value)) {
73
+ let out = ''
74
+ for (let i = 0; i < value.length; i++)
75
+ out += ssrRawText(tag, value[i])
76
+ return out
77
+ }
78
+ const str = isRawHtml(value) ? String(value.__html) : String(value)
79
+ if (tag === 'script') {
80
+ return str.replace(SCRIPT_UNSAFE_RE, (_, body: string) =>
81
+ body.charCodeAt(0) === 47 ? `<\\${body}` : `\\u003c${body}`)
82
+ }
83
+ return str.replace(CLOSE_STYLE_RE, '<\\/$1')
84
+ }
85
+
86
+ export function escAttr(value: unknown): string {
87
+ const str = String(value)
88
+ if (bunEscape !== undefined)
89
+ return bunEscape(str)
90
+ if (!ESC_ATTR.test(str))
91
+ return str
92
+ return str
93
+ .replaceAll('&', '&amp;')
94
+ .replaceAll('"', '&quot;')
95
+ .replaceAll('<', '&lt;')
96
+ .replaceAll('>', '&gt;')
97
+ }
98
+
99
+ // `<`, then the two line separators, built from their code points so the source shows no invisible character.
100
+ const SCRIPT_JSON_RE = new RegExp(`[<${String.fromCharCode(0x2028, 0x2029)}]`, 'g')
101
+
102
+ /** JSON text made safe inside a `<script>` element: `<` can no longer close it or open a comment, and U+2028 and U+2029 cannot end a line of script. */
103
+ export function escJson(json: string): string {
104
+ return json.replace(SCRIPT_JSON_RE, c => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`)
105
+ }
106
+
107
+ export function raw(html: string): Html {
108
+ return { __html: html, [RAW_HTML]: true } as unknown as Html
109
+ }
110
+
111
+ export function ssrAttr(name: string, value: unknown, tag?: string): string {
112
+ if (value == null || isBlockedAttr(name))
113
+ return ''
114
+ if (typeof value === 'boolean') {
115
+ if (isStringBoolAttr(name))
116
+ return ` ${name}="${value ? 'true' : 'false'}"`
117
+ return value ? ` ${name}` : ''
118
+ }
119
+ if (isUnsafeUrlAttr(name, value, tag)) {
120
+ if (process.env.NODE_ENV !== 'production')
121
+ console.warn(`prunelle: dropped unsafe URL on <${tag ?? 'element'} ${name}>.`)
122
+ return ''
123
+ }
124
+ assertRenderable(value, name)
125
+ return ` ${name}="${escAttr(value)}"`
126
+ }
127
+
128
+ export function ssrStyle(value: unknown): string {
129
+ if (value == null || value === false)
130
+ return ''
131
+ if (typeof value === 'string')
132
+ return ` style="${escAttr(value)}"`
133
+ if (typeof value === 'object') {
134
+ const out = styleText(value as Record<string, unknown>)
135
+ return out === '' ? '' : ` style="${escAttr(out)}"`
136
+ }
137
+ return ''
138
+ }
139
+
140
+ const SPREAD_DANGEROUS_HTML = 'prunelle: dangerouslySetInnerHTML in a spread: write innerHTML={html} on the element.'
141
+
142
+ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag?: string): string {
143
+ if (props == null || typeof props !== 'object')
144
+ return ''
145
+ let out = ''
146
+ for (const [rawKey, value] of Object.entries(props)) {
147
+ if (rawKey === 'key' || rawKey === 'ref' || rawKey === '$hydrate' || rawKey === 'children')
148
+ continue
149
+ if (rawKey === 'dangerouslySetInnerHTML')
150
+ throw new TypeError(SPREAD_DANGEROUS_HTML)
151
+ const name = rawKey === 'className' ? 'class' : rawKey === 'htmlFor' ? 'for' : rawKey
152
+ if (isBlockedAttr(name))
153
+ continue
154
+ out += name === 'style' ? ssrStyle(value) : ssrAttr(name, value, tag)
155
+ }
156
+ return out
157
+ }
158
+
159
+ export function ssrLoop<T>(items: Iterable<T> | null | undefined | false, render: (item: T, index: number, array: readonly T[]) => string): string {
160
+ if (!items)
161
+ return ''
162
+ const list: readonly T[] = Array.isArray(items) ? items : [...items]
163
+ let out = ''
164
+ for (let i = 0; i < list.length; i++)
165
+ out += render(list[i] as T, i, list)
166
+ return out
167
+ }
168
+
169
+ export function ssrChild(value: PrunelleChild): string {
170
+ if (typeof value === 'string')
171
+ return esc(value)
172
+ if (typeof value === 'number')
173
+ return String(value)
174
+ if (value == null || typeof value === 'boolean')
175
+ return ''
176
+ if (isRawHtml(value))
177
+ return value.__html
178
+ if (Array.isArray(value)) {
179
+ let out = ''
180
+ for (let i = 0; i < value.length; i++)
181
+ out += ssrChild(value[i])
182
+ return out
183
+ }
184
+ assertRenderable(value, 'text')
185
+ return esc(String(value))
186
+ }
187
+
188
+ function serializeIslandProps(props: Record<string, unknown>): string {
189
+ return JSON.stringify(props, function (this: Record<string, unknown>, key: string, value: unknown) {
190
+ const orig = key !== '' && this != null && typeof this === 'object' ? this[key] : value
191
+ if (orig === undefined)
192
+ return Array.isArray(this) ? { __k: 'u', v: 0 } : value
193
+ if (typeof orig === 'number') {
194
+ if (!Number.isFinite(orig))
195
+ return { __k: 'N', v: String(orig) }
196
+ if (Object.is(orig, -0))
197
+ return { __k: 'N', v: '-0' }
198
+ return value
199
+ }
200
+ if (orig instanceof Date)
201
+ return { __k: 'D', v: Number.isNaN(orig.getTime()) ? 'NaN' : orig.toISOString() }
202
+ if (orig instanceof Set)
203
+ return { __k: 'S', v: [...orig] }
204
+ if (orig instanceof Map)
205
+ return { __k: 'M', v: [...orig.entries()] }
206
+ if (orig instanceof URL)
207
+ return { __k: 'U', v: orig.href }
208
+ if (orig instanceof RegExp)
209
+ return { __k: 'R', v: [orig.source, orig.flags] }
210
+ if (typeof orig === 'bigint')
211
+ return { __k: 'B', v: orig.toString() }
212
+ if (isRawHtml(orig))
213
+ throw new TypeError(`prunelle: island prop "${key}" is server-rendered JSX, which cannot reach the browser; pass it as children, or build it inside the island.`)
214
+ if (typeof orig === 'function')
215
+ throw new TypeError(`prunelle: island prop "${key}" is a function, which cannot reach the browser; define it inside the island, or import it there.`)
216
+ if (typeof orig === 'object' && orig !== null && 'peek' in orig && 'value' in orig)
217
+ throw new TypeError(`prunelle: island prop "${key}" is a signal; pass ${key}.value, or import the signal in the island from a shared module.`)
218
+ if (typeof orig === 'object' && orig !== null && !Array.isArray(orig) && Object.hasOwn(orig, '__k'))
219
+ return { __k: 'O', v: Object.entries(orig).filter(([, x]) => x !== undefined) }
220
+ return value
221
+ })
222
+ }
223
+
224
+ let fallbackIslandDepth = 0
225
+
226
+ function getIslandDepth(): number {
227
+ const ctx = currentRenderContext()
228
+ return ctx !== undefined ? ctx.islandDepth : fallbackIslandDepth
229
+ }
230
+
231
+ export function recordRenderedIsland(chunk: string, hydrate?: HydrateStrategy): void {
232
+ const ctx = currentRenderContext()
233
+ if (ctx === undefined)
234
+ return
235
+ ctx.hasIslands = true
236
+ const eager = hydrate === undefined || hydrate === 'load'
237
+ if (eager)
238
+ ctx.renderedIslands.set(chunk, true)
239
+ else if (!ctx.renderedIslands.has(chunk))
240
+ ctx.renderedIslands.set(chunk, false)
241
+ }
242
+
243
+ export function ssrInIsland(render: () => string, chunk?: string, hydrate?: HydrateStrategy, name = 'island'): string {
244
+ const ctx = currentRenderContext()
245
+ if (ctx !== undefined) {
246
+ if (chunk !== undefined && ctx.islandDepth === 0)
247
+ recordRenderedIsland(chunk, hydrate)
248
+ ctx.islandDepth++
249
+ try {
250
+ return renderOnServer(ctx.islandDepth === 1 ? () => renderIsland(ctx, name, render) : render)
251
+ }
252
+ finally {
253
+ ctx.islandDepth--
254
+ }
255
+ }
256
+ fallbackIslandDepth++
257
+ try {
258
+ return renderOnServer(render)
259
+ }
260
+ finally {
261
+ fallbackIslandDepth--
262
+ }
263
+ }
264
+
265
+
266
+ /** Lazily evaluates non-async component children on first read inside the component's dynamic context, memoizing the result. */
267
+ export function ssrChildProp<P extends Record<string, unknown>>(props: P, fn: () => Html): P {
268
+ let cached: Html | undefined
269
+ let evaluated = false
270
+ return Object.defineProperty(props, 'children', {
271
+ enumerable: true,
272
+ configurable: true,
273
+ get() {
274
+ if (!evaluated) {
275
+ evaluated = true
276
+ cached = fn()
277
+ }
278
+ return cached
279
+ },
280
+ })
281
+ }
282
+
283
+ export interface TrackedSlot {
284
+ prop: Html
285
+ html: string
286
+ used: boolean
287
+ }
288
+
289
+ /** Wraps server-rendered island children in `<pru-slot>` and tracks whether the island emitted them during SSR. */
290
+ export function ssrSlot(html: string): TrackedSlot {
291
+ const slot: TrackedSlot = {
292
+ html,
293
+ used: false,
294
+ prop: null as unknown as Html,
295
+ }
296
+ slot.prop = Object.defineProperty(
297
+ { [RAW_HTML]: true },
298
+ '__html',
299
+ {
300
+ enumerable: true,
301
+ get() {
302
+ slot.used = true
303
+ return `<pru-slot>${html}</pru-slot>`
304
+ },
305
+ },
306
+ ) as unknown as Html
307
+ return slot
308
+ }
309
+
310
+ function renderIslandBody(
311
+ ctx: ReturnType<typeof currentRenderContext>,
312
+ render: (() => string) | undefined,
313
+ hydrate: HydrateStrategy | undefined,
314
+ name: string | undefined,
315
+ slot: TrackedSlot | undefined,
316
+ ): { idAttr: string, inner: string, hiddenSlot: string } {
317
+ let idAttr = ''
318
+ let inner = ''
319
+ if (render !== undefined && hydrate !== 'client') {
320
+ if (ctx !== undefined) {
321
+ const prevPrefix = ctx.idPrefix
322
+ const prevSeq = ctx.idSeq
323
+ const islandPrefix = `i${ctx.islandSeq++}-`
324
+ ctx.idPrefix = islandPrefix
325
+ ctx.idSeq = 0
326
+ try {
327
+ inner = ssrInIsland(render, undefined, undefined, name)
328
+ if (ctx.idSeq > 0)
329
+ idAttr = ` i="${islandPrefix}"`
330
+ }
331
+ finally {
332
+ ctx.idPrefix = prevPrefix
333
+ ctx.idSeq = prevSeq
334
+ }
335
+ }
336
+ else {
337
+ inner = ssrInIsland(render, undefined, undefined, name)
338
+ }
339
+ }
340
+
341
+ const hiddenSlot = slot !== undefined && !slot.used && slot.html !== ''
342
+ ? `<template data-pru-slot>${slot.html}</template>`
343
+ : ''
344
+ return { idAttr, inner, hiddenSlot }
345
+ }
346
+
347
+ export function ssrIslandStatic(
348
+ chunk: string,
349
+ openTag: string,
350
+ render: (() => string) | undefined,
351
+ hydrate?: HydrateStrategy,
352
+ name?: string,
353
+ slot?: TrackedSlot,
354
+ ): string {
355
+ if (getIslandDepth() > 0)
356
+ return render !== undefined ? render() : ''
357
+
358
+ const ctx = currentRenderContext()
359
+ if (ctx !== undefined)
360
+ recordRenderedIsland(chunk, hydrate)
361
+
362
+ const { idAttr, inner, hiddenSlot } = renderIslandBody(ctx, render, hydrate, name, slot)
363
+ const tag = idAttr === '' ? openTag : `${openTag.slice(0, -1)}${idAttr}>`
364
+ return `${tag}${inner}${hiddenSlot}</pru-island>`
365
+ }
366
+
367
+
368
+ export function ssrIsland(
369
+ chunk: string,
370
+ render: () => string,
371
+ props: Record<string, unknown>,
372
+ hydrate?: HydrateStrategy,
373
+ scriptProps = false,
374
+ name?: string,
375
+ slot?: TrackedSlot,
376
+ ): string {
377
+ if (getIslandDepth() > 0)
378
+ return render()
379
+
380
+ const ctx = currentRenderContext()
381
+ if (ctx !== undefined)
382
+ recordRenderedIsland(chunk, hydrate)
383
+
384
+ let propsAttr = ''
385
+ let propsScript = ''
386
+ if (Object.keys(props).length > 0) {
387
+ const json = serializeIslandProps(props)
388
+ if (ctx !== undefined && json.includes('"__k":'))
389
+ ctx.revives = true
390
+ if (scriptProps)
391
+ propsScript = `<script type="application/json" data-pru-props>${escJson(json)}</script>`
392
+ else
393
+ propsAttr = ` p="${escAttr(json)}"`
394
+ }
395
+ const hydrateAttr = hydrate !== undefined && hydrate !== 'load'
396
+ ? ` h="${escAttr(hydrate)}"`
397
+ : ''
398
+
399
+ const { idAttr, inner, hiddenSlot } = renderIslandBody(ctx, render, hydrate, name, slot)
400
+ return `<pru-island c="${escAttr(chunk)}"${propsAttr}${hydrateAttr}${idAttr}>${inner}${hiddenSlot}${propsScript}</pru-island>`
401
+ }
402
+
403
+ export interface DocumentOptions {
404
+ body: string
405
+ head?: string | undefined
406
+ headTags?: Iterable<string> | undefined
407
+ lang?: string | undefined
408
+ htmlAttrs?: Record<string, string> | undefined
409
+ runtimeScript?: string | undefined
410
+ alwaysLoadRuntime?: boolean | undefined
411
+ /** Set on a route that renders a `<Region>`: the plugins' `regionClientEntry` bundle. */
412
+ regionScript?: string | undefined
413
+ preloadChunks?: Iterable<string> | undefined
414
+ /** Script URL to the chunks it imports statically, preloaded with it: the browser then fetches them all at once. */
415
+ chunkImports?: Readonly<Record<string, readonly string[]>> | undefined
416
+ styles?: Iterable<string> | undefined
417
+ hasIslands?: boolean | undefined
418
+ hasSuspense?: boolean | undefined
419
+ // The head markup every page shares for the `navigation` settings: see `createNavigation`.
420
+ navigation?: string | undefined
421
+ }
422
+
423
+ export function renderDocument(options: DocumentOptions): string {
424
+ const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, regionScript, preloadChunks, chunkImports, styles, hasIslands, hasSuspense, navigation } = options
425
+ let headExtra = head
426
+
427
+ if (headTags !== undefined) {
428
+ for (const tag of headTags)
429
+ headExtra += tag
430
+ }
431
+
432
+ if (styles !== undefined) {
433
+ for (const href of styles)
434
+ headExtra += `<link rel="stylesheet" href="${escAttr(href)}">`
435
+ }
436
+
437
+ if (navigation !== undefined)
438
+ headExtra += navigation
439
+
440
+ const loadsRuntime = runtimeScript !== undefined && (hasIslands || alwaysLoadRuntime)
441
+ const preloads = new Set<string>()
442
+ const preload = (script: string, self: boolean): void => {
443
+ if (self)
444
+ preloads.add(script)
445
+ for (const dep of chunkImports?.[script] ?? [])
446
+ preloads.add(dep)
447
+ }
448
+ if (hasIslands) {
449
+ headExtra += `<style>${PRUNELLE_ISLAND_STYLE}</style>`
450
+ for (const chunk of preloadChunks ?? [])
451
+ preload(chunk, true)
452
+ }
453
+ if (loadsRuntime)
454
+ preload(runtimeScript, false)
455
+ for (const href of preloads)
456
+ headExtra += `<link rel="modulepreload" href="${escAttr(href)}">`
457
+
458
+ if (hasSuspense)
459
+ headExtra += `<style>${PRUNELLE_SUSPENSE_STYLE}</style><script>${PRUNELLE_STREAM_SCRIPT}</script>`
460
+
461
+ if (loadsRuntime)
462
+ headExtra += `<script type="module" src="${escAttr(runtimeScript)}"></script>`
463
+ if (regionScript !== undefined)
464
+ headExtra += `<script type="module" src="${escAttr(regionScript)}"></script>`
465
+
466
+ let attrStr = ''
467
+ const effectiveLang = htmlAttrs?.lang ?? lang
468
+ attrStr += ` lang="${escAttr(effectiveLang)}"`
469
+ if (htmlAttrs !== undefined) {
470
+ for (const [k, v] of Object.entries(htmlAttrs)) {
471
+ if (k !== 'lang' && !isBlockedAttr(k))
472
+ attrStr += ` ${k}="${escAttr(v)}"`
473
+ }
474
+ }
475
+
476
+ return `<!DOCTYPE html><html${attrStr}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${headExtra}</head><body>${body}${keepScrollTag(body)}</body></html>`
477
+ }
@@ -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: `'moderate'` (the default) on hover, `'conservative'` on press, `'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 ? 'moderate' : 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
+ }