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.
- package/llms.txt +63 -46
- package/package.json +7 -2
- package/src/a11y/declaration.ts +6 -10
- package/src/a11y/index.ts +69 -125
- package/src/animate.ts +127 -0
- package/src/build/asides.ts +51 -0
- package/src/build/bundle.ts +88 -134
- package/src/build/client-entries.ts +6 -6
- package/src/build/client-outputs.ts +75 -0
- package/src/build/client-plugin.ts +9 -4
- package/src/build/ecoindex.ts +4 -2
- package/src/build/files.ts +18 -0
- package/src/build/graph.ts +15 -7
- package/src/build/index.ts +20 -10
- package/src/build/island-promote.ts +1 -1
- package/src/build/islands.ts +4 -1
- package/src/build/key-types.ts +31 -0
- package/src/build/manifest.ts +19 -1
- package/src/build/plugin-host.ts +2 -0
- package/src/build/prerender.ts +2 -2
- package/src/build/reach.ts +14 -1
- package/src/build/report.ts +1 -1
- package/src/build/route-types.ts +16 -0
- package/src/build/routes.ts +24 -15
- package/src/build/seed-ids.ts +65 -0
- package/src/build/seed-writes.ts +111 -0
- package/src/build/static-headers.ts +2 -2
- package/src/build/static.ts +1 -1
- package/src/cli/check-cache.ts +51 -0
- package/src/cli/check-consent.ts +95 -0
- package/src/cli/check-forms.ts +2 -2
- package/src/cli/check-links-patterns.ts +101 -0
- package/src/cli/check-links.ts +16 -100
- package/src/cli/check-regions.ts +185 -0
- package/src/cli/check-security.ts +57 -6
- package/src/cli/check.ts +40 -17
- package/src/cli/commands.ts +134 -14
- package/src/cli/docs.ts +21 -2
- package/src/cli/index.ts +1 -1
- package/src/cli/inspect.ts +2 -0
- package/src/cli/mcp-tools.ts +2 -2
- package/src/cli/new.ts +9 -5
- package/src/cli/upgrade-names.ts +14 -2
- package/src/cli/upgrade.ts +3 -0
- package/src/compiler/analyze.ts +18 -4
- package/src/compiler/cacheability.ts +24 -2
- package/src/compiler/compliance-contrast.ts +284 -0
- package/src/compiler/compliance-empty.ts +24 -0
- package/src/compiler/compliance-rgaa-content.ts +95 -0
- package/src/compiler/compliance-rgaa-criteria.ts +45 -0
- package/src/compiler/compliance-rgaa-pages.ts +140 -0
- package/src/compiler/compliance-rgaa.ts +19 -0
- package/src/compiler/compliance-third-party.ts +59 -0
- package/src/compiler/compliance-urls.ts +52 -0
- package/src/compiler/compliance.ts +72 -42
- package/src/compiler/cookie-inventory.ts +119 -0
- package/src/compiler/dom-attrs.ts +4 -1
- package/src/compiler/emit.ts +1 -1
- package/src/compiler/foreign-imports.ts +5 -3
- package/src/compiler/mistakes.ts +18 -9
- package/src/compiler/props-pattern.ts +211 -0
- package/src/compiler/props.ts +177 -346
- package/src/compiler/shared.ts +9 -16
- package/src/compiler/ssr-emit.ts +510 -0
- package/src/compiler/ssr-helpers.ts +170 -121
- package/src/compiler/ssr.ts +25 -440
- package/src/context.ts +14 -1
- package/src/dev/child.ts +1 -1
- package/src/dev/hot-islands.ts +71 -0
- package/src/dev/index.ts +31 -18
- package/src/dev/protocol.ts +1 -1
- package/src/dev/queue.ts +3 -2
- package/src/dev/reload.ts +1 -1
- package/src/dev/supervisor.ts +3 -1
- package/src/dev/watchers.ts +6 -2
- package/src/dom/action.ts +97 -14
- package/src/dom/attrs.ts +8 -0
- package/src/dom/extras.ts +2 -1
- package/src/dom/field-marks.ts +24 -0
- package/src/dom/hot.ts +9 -0
- package/src/dom/index.ts +25 -5
- package/src/dom/island-hot.ts +29 -0
- package/src/dom/island.ts +13 -2
- package/src/dom/prefetch.ts +132 -0
- package/src/dom/regions.ts +498 -0
- package/src/dom/swap.ts +245 -0
- package/src/dom/trusted.ts +22 -0
- package/src/dom/upload.ts +44 -0
- package/src/eco/declaration.ts +39 -40
- package/src/eco/index.ts +5 -5
- package/src/href.ts +31 -0
- package/src/index.ts +9 -3
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +7 -1
- package/src/plugins/daily.ts +27 -0
- package/src/plugins/index.ts +3 -3
- package/src/plugins/order.ts +1 -1
- package/src/plugins/public.ts +8 -5
- package/src/plugins/services.ts +88 -14
- package/src/plugins/types.ts +121 -10
- package/src/reactivity/hmr.ts +90 -0
- package/src/reactivity/index.ts +38 -18
- package/src/reactivity/resource.ts +115 -0
- package/src/reactivity/seed.ts +39 -0
- package/src/reactivity/server-seed.ts +194 -0
- package/src/reactivity/store.ts +55 -1
- package/src/rgpd/draft.ts +171 -0
- package/src/rgpd/forms.ts +85 -0
- package/src/rgpd/index.ts +57 -0
- package/src/server/action-flash.ts +1 -0
- package/src/server/action-registry.ts +6 -8
- package/src/server/action.ts +51 -19
- package/src/server/app-secret.ts +22 -17
- package/src/server/cache-invalidation.ts +96 -0
- package/src/server/compress.ts +3 -1
- package/src/server/consent.ts +16 -2
- package/src/server/cookie-inventory.ts +78 -0
- package/src/server/cookies.ts +50 -0
- package/src/server/csp-report.ts +86 -0
- package/src/server/discard.ts +13 -0
- package/src/server/document.ts +7 -4
- package/src/server/env.ts +1 -1
- package/src/server/errors.ts +9 -2
- package/src/server/field-errors.ts +91 -0
- package/src/server/form-schema.ts +16 -11
- package/src/server/health.ts +35 -14
- package/src/server/http.ts +25 -10
- package/src/server/index.ts +102 -299
- package/src/server/loader.ts +1 -0
- package/src/server/page.ts +11 -24
- package/src/server/plugin-host.ts +26 -8
- package/src/server/public.ts +14 -3
- package/src/server/rate-limit.ts +39 -10
- package/src/server/region.ts +3 -0
- package/src/server/request-handler.ts +370 -0
- package/src/server/request-log.ts +94 -0
- package/src/server/route-cache.ts +41 -6
- package/src/server/route-input.ts +54 -0
- package/src/server/route-table.ts +35 -19
- package/src/server/routing.ts +12 -11
- package/src/server/sanitize-html.ts +1 -1
- package/src/server/security.ts +81 -20
- package/src/server/serve-handlers.ts +9 -5
- package/src/server/shared-store.ts +314 -0
- package/src/server/start.ts +12 -5
- package/src/server/static-dir.ts +14 -10
- package/src/server/stream.ts +2 -1
- package/src/server/surface.ts +39 -0
- package/src/server/webhook.ts +48 -0
- package/src/server/workers.ts +168 -0
- package/src/ssr/consent-banner.ts +20 -16
- package/src/ssr/consent-texts.ts +40 -0
- package/src/ssr/context.ts +26 -3
- package/src/ssr/cookie-table.ts +75 -0
- package/src/ssr/index.ts +23 -13
- package/src/ssr/navigation.ts +161 -14
- package/src/test/browser.ts +50 -22
- package/src/test/build-reuse.ts +70 -0
- package/src/test/index.ts +45 -6
- package/src/test/mount.ts +53 -0
- package/src/test/outside.ts +94 -0
- package/templates/_shared/AGENTS.md +1 -1
- package/templates/_shared/Dockerfile +22 -0
- package/templates/_shared/dockerignore +9 -0
- package/templates/_shared/gitignore +2 -0
- package/templates/app/.env.example +3 -1
- package/templates/app/compose.yaml +32 -0
- package/templates/app/db/migrations/001_notes.sql +7 -0
- package/templates/app/db/schema.ts +11 -0
- package/templates/app/package.json +1 -0
- package/templates/app/prunelle.config.ts +6 -0
- package/templates/app/src/actions/notes.ts +26 -0
- package/templates/app/src/auth.ts +4 -2
- package/templates/app/src/db.ts +5 -0
- package/templates/app/src/routes/dashboard/index.tsx +26 -1
- package/templates/app/src/routes/privacy.tsx +6 -2
- package/templates/app/tests/app.test.ts +14 -3
- package/templates/plugin/AGENTS.md +11 -0
- package/templates/plugin/CLAUDE.md +1 -0
- package/templates/plugin/README.md +27 -0
- package/templates/plugin/gitignore +2 -0
- package/templates/plugin/llms.txt +19 -0
- package/templates/plugin/package.json +33 -0
- package/templates/plugin/src/index.ts +40 -0
- package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
- package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
- package/templates/plugin/tests/plugin.test.ts +42 -0
- package/templates/plugin/tsconfig.json +19 -0
- package/ts-plugin.cjs +3674 -2196
package/src/compiler/ssr.ts
CHANGED
|
@@ -2,118 +2,19 @@
|
|
|
2
2
|
// static attribute literal folding, compile-time static island props, and shared balanced hydration markers.
|
|
3
3
|
|
|
4
4
|
import type {
|
|
5
|
-
JSXChild,
|
|
6
5
|
JSXElement,
|
|
7
6
|
JSXFragment,
|
|
8
7
|
Node,
|
|
9
8
|
} from 'oxc-parser'
|
|
10
9
|
import type { ModuleAnalysis } from './analyze'
|
|
11
|
-
import type {
|
|
12
|
-
import type { PrunelleTagEmitter } from './ssr-prunelle-tags'
|
|
10
|
+
import type { SsrEnv } from './ssr-emit'
|
|
13
11
|
import { analyzeModule, getExprContext, parseTsx } from './analyze'
|
|
14
12
|
import { walk } from './ast'
|
|
15
13
|
import { createDevSourceAttr } from './dev-source'
|
|
16
|
-
import { hydrateMistake } from './mistakes'
|
|
17
14
|
import { alignLines, lineMarker, SourceEditor } from './patch'
|
|
18
|
-
import {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
escapeRawText,
|
|
22
|
-
escapeStaticText,
|
|
23
|
-
filterMeaningfulChildren,
|
|
24
|
-
isComponentTag,
|
|
25
|
-
isJsxNode,
|
|
26
|
-
jsxTagName,
|
|
27
|
-
matchJsxMapCall,
|
|
28
|
-
planChildSlots,
|
|
29
|
-
RAW_TEXT_ELEMENTS,
|
|
30
|
-
resolvePrunelleTag,
|
|
31
|
-
unwrapParens,
|
|
32
|
-
VOID_ELEMENTS,
|
|
33
|
-
} from './shared'
|
|
34
|
-
import {
|
|
35
|
-
emitSsrElementAttrs,
|
|
36
|
-
precomputeSsrSubtreeFlags,
|
|
37
|
-
serializeComponentProps,
|
|
38
|
-
staticLiteralOrTemplate,
|
|
39
|
-
StringParts,
|
|
40
|
-
} from './ssr-helpers'
|
|
41
|
-
import { emitIsland } from './ssr-island'
|
|
42
|
-
import { emitCatch, emitSuspense } from './ssr-prunelle-tags'
|
|
43
|
-
|
|
44
|
-
const FORM_CONTROL_TAGS = new Set(['input', 'select', 'textarea'])
|
|
45
|
-
const FORM_ATTR_BITS: Record<string, number> = {
|
|
46
|
-
type: 1,
|
|
47
|
-
required: 2,
|
|
48
|
-
minlength: 4,
|
|
49
|
-
maxlength: 8,
|
|
50
|
-
min: 16,
|
|
51
|
-
max: 32,
|
|
52
|
-
step: 64,
|
|
53
|
-
pattern: 128,
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function findDynamicFormAction(node: JSXElement): Node | undefined {
|
|
57
|
-
for (const attr of node.openingElement.attributes) {
|
|
58
|
-
if (attr.type !== 'JSXAttribute' || jsxTagName(attr.name) !== 'action')
|
|
59
|
-
continue
|
|
60
|
-
if (attr.value?.type !== 'JSXExpressionContainer' || attr.value.expression.type === 'JSXEmptyExpression')
|
|
61
|
-
return undefined
|
|
62
|
-
const expr = attr.value.expression
|
|
63
|
-
if (staticLiteralOrTemplate(expr).ok)
|
|
64
|
-
return undefined
|
|
65
|
-
if (expr.type === 'ConditionalExpression' && staticLiteralOrTemplate(expr.consequent).ok && staticLiteralOrTemplate(expr.alternate).ok)
|
|
66
|
-
return undefined
|
|
67
|
-
return expr
|
|
68
|
-
}
|
|
69
|
-
return undefined
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
function emitFormControlAttrs(
|
|
73
|
-
node: JSXElement,
|
|
74
|
-
tag: 'input' | 'select' | 'textarea',
|
|
75
|
-
parts: StringParts,
|
|
76
|
-
use: (name: string) => string,
|
|
77
|
-
compileSubExpression: (node: Node) => string,
|
|
78
|
-
): void {
|
|
79
|
-
const attrs = node.openingElement.attributes
|
|
80
|
-
if (attrs.some(a => a.type === 'JSXSpreadAttribute'))
|
|
81
|
-
return
|
|
82
|
-
let nameExpr: string | undefined
|
|
83
|
-
let typeExpr: string | undefined
|
|
84
|
-
let present = 0
|
|
85
|
-
for (const attr of attrs) {
|
|
86
|
-
if (attr.type !== 'JSXAttribute')
|
|
87
|
-
continue
|
|
88
|
-
const attrName = jsxTagName(attr.name).toLowerCase()
|
|
89
|
-
const bit = FORM_ATTR_BITS[attrName]
|
|
90
|
-
if (bit !== undefined)
|
|
91
|
-
present |= bit
|
|
92
|
-
if (attrName === 'name') {
|
|
93
|
-
if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
|
|
94
|
-
nameExpr = JSON.stringify(attr.value.value)
|
|
95
|
-
}
|
|
96
|
-
else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
|
|
97
|
-
const lit = staticLiteralOrTemplate(attr.value.expression)
|
|
98
|
-
nameExpr = lit.ok && typeof lit.value === 'string' ? JSON.stringify(lit.value) : compileSubExpression(attr.value.expression)
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
else if (tag === 'input' && attrName === 'type') {
|
|
102
|
-
if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
|
|
103
|
-
typeExpr = JSON.stringify(attr.value.value.toLowerCase())
|
|
104
|
-
}
|
|
105
|
-
else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
|
|
106
|
-
const lit = staticLiteralOrTemplate(attr.value.expression)
|
|
107
|
-
if (lit.ok && typeof lit.value === 'string')
|
|
108
|
-
typeExpr = JSON.stringify(lit.value.toLowerCase())
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
if (nameExpr === undefined)
|
|
113
|
-
return
|
|
114
|
-
const typeArg = typeExpr !== undefined ? `, ${typeExpr}` : ''
|
|
115
|
-
parts.pushExpr(`${use('ssrFormAttrs')}(${JSON.stringify(tag)}, ${nameExpr}, ${present}${typeArg})`)
|
|
116
|
-
}
|
|
15
|
+
import { containsJsx, isJsxNode } from './shared'
|
|
16
|
+
import { precomputeSsrSubtreeFlags } from './ssr-helpers'
|
|
17
|
+
import { compileRootJsx } from './ssr-emit'
|
|
117
18
|
|
|
118
19
|
export interface IslandBinding {
|
|
119
20
|
id: string
|
|
@@ -136,57 +37,16 @@ export interface CompileResult {
|
|
|
136
37
|
analysis: ModuleAnalysis
|
|
137
38
|
}
|
|
138
39
|
|
|
139
|
-
function emitActionFormExpr(
|
|
140
|
-
formAction: Node,
|
|
141
|
-
isAsyncForm: boolean,
|
|
142
|
-
nextId: () => number,
|
|
143
|
-
use: (name: string) => string,
|
|
144
|
-
compileSubExpression: (node: Node) => string,
|
|
145
|
-
emitBody: (bufVar: string, parts: StringParts, flush: () => void, pushStmt: (stmt: string) => void, override: { node: Node, ident: string }) => void,
|
|
146
|
-
): string {
|
|
147
|
-
const faVar = `_fa${nextId()}`
|
|
148
|
-
const innerBuf = `_o${nextId()}`
|
|
149
|
-
const innerStmts: string[] = []
|
|
150
|
-
const innerParts = new StringParts()
|
|
151
|
-
const flushInner = () => {
|
|
152
|
-
if (!innerParts.isEmpty()) {
|
|
153
|
-
innerStmts.push(`${innerBuf} += ${innerParts.toExpr()};`)
|
|
154
|
-
innerParts.clear()
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
emitBody(innerBuf, innerParts, flushInner, s => innerStmts.push(s), { node: formAction, ident: faVar })
|
|
158
|
-
if (innerStmts.length > 0)
|
|
159
|
-
flushInner()
|
|
160
|
-
const body = innerStmts.length === 0 ? innerParts.toExpr() : `{ let ${innerBuf} = ""; ${innerStmts.join(' ')} return ${innerBuf}; }`
|
|
161
|
-
return isAsyncForm
|
|
162
|
-
? `await ${use('ssrFormAsync')}(${compileSubExpression(formAction)}, async (${faVar}) => ${body})`
|
|
163
|
-
: `${use('ssrForm')}(${compileSubExpression(formAction)}, (${faVar}) => ${body})`
|
|
164
|
-
}
|
|
165
|
-
|
|
166
40
|
function markerTest(markers: NonNullable<CompileSsrOptions['emitMarkers']>): (offset: number) => boolean {
|
|
167
41
|
return typeof markers === 'boolean' ? () => markers : offset => markers.some(([start, end]) => offset >= start && offset < end)
|
|
168
42
|
}
|
|
169
43
|
|
|
170
|
-
function flushStringParts(bufVar: string, parts: StringParts, stmts: string[]): void {
|
|
171
|
-
if (!parts.isEmpty()) {
|
|
172
|
-
stmts.push(`${bufVar} += ${parts.toExpr()};`)
|
|
173
|
-
parts.clear()
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
function isSingleLoopChild(meaningful: readonly JSXChild[], jsxNodes: WeakSet<Node>): boolean {
|
|
178
|
-
return meaningful.length === 1
|
|
179
|
-
&& meaningful[0]!.type === 'JSXExpressionContainer'
|
|
180
|
-
&& meaningful[0]!.expression.type !== 'JSXEmptyExpression'
|
|
181
|
-
&& matchJsxMapCall(meaningful[0]!.expression, jsxNodes) !== undefined
|
|
182
|
-
}
|
|
183
|
-
|
|
184
44
|
function compileSsrSubExpression(
|
|
185
45
|
code: string,
|
|
186
46
|
node: Node,
|
|
187
47
|
jsxNodes: WeakSet<Node>,
|
|
188
48
|
mark: (offset: number) => string,
|
|
189
|
-
|
|
49
|
+
compileRoot: (n: JSXElement | JSXFragment) => string,
|
|
190
50
|
): string {
|
|
191
51
|
if (!containsJsx(node, jsxNodes))
|
|
192
52
|
return mark(node.start) + code.slice(node.start, node.end)
|
|
@@ -194,7 +54,7 @@ function compileSsrSubExpression(
|
|
|
194
54
|
const offset = node.start
|
|
195
55
|
walk(node, (child) => {
|
|
196
56
|
if (isJsxNode(child)) {
|
|
197
|
-
sub.replace(child.start - offset, child.end - offset,
|
|
57
|
+
sub.replace(child.start - offset, child.end - offset, compileRoot(child) + mark(child.end))
|
|
198
58
|
return false
|
|
199
59
|
}
|
|
200
60
|
return undefined
|
|
@@ -202,32 +62,6 @@ function compileSsrSubExpression(
|
|
|
202
62
|
return mark(node.start) + sub.toString()
|
|
203
63
|
}
|
|
204
64
|
|
|
205
|
-
function compileSsrExprAsString(
|
|
206
|
-
expr: Node,
|
|
207
|
-
use: (name: string) => string,
|
|
208
|
-
compileSubExpression: (node: Node) => string,
|
|
209
|
-
compileJsxToStringExpr: (node: JSXElement | JSXFragment) => string,
|
|
210
|
-
): string {
|
|
211
|
-
if (isJsxNode(expr))
|
|
212
|
-
return compileJsxToStringExpr(expr)
|
|
213
|
-
if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
|
|
214
|
-
const right = unwrapParens(expr.right)
|
|
215
|
-
if (isJsxNode(right))
|
|
216
|
-
return `((${compileSubExpression(expr.left)}) ? (${compileJsxToStringExpr(right)}) : "")`
|
|
217
|
-
}
|
|
218
|
-
if (expr.type === 'ConditionalExpression') {
|
|
219
|
-
const consNode = unwrapParens(expr.consequent)
|
|
220
|
-
const altNode = unwrapParens(expr.alternate)
|
|
221
|
-
if (isJsxNode(consNode) || isJsxNode(altNode))
|
|
222
|
-
return `((${compileSubExpression(expr.test)}) ? (${compileSsrExprAsString(consNode, use, compileSubExpression, compileJsxToStringExpr)}) : (${compileSsrExprAsString(altNode, use, compileSubExpression, compileJsxToStringExpr)}))`
|
|
223
|
-
}
|
|
224
|
-
return `${use('esc')}(${compileSubExpression(expr)})`
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
function pushLeadNlStatic(parts: StringParts, text: string): void {
|
|
228
|
-
parts.pushStatic(text.startsWith('\n') || text.startsWith('\r') ? `\n${text}` : text)
|
|
229
|
-
}
|
|
230
|
-
|
|
231
65
|
function createIdCounter(code: string): () => number {
|
|
232
66
|
const used = new Set<number>()
|
|
233
67
|
for (const m of code.matchAll(/\b_[A-Za-z_]+(\d+)\b/g))
|
|
@@ -251,281 +85,32 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
251
85
|
// Generated code keeps each expression on its source line: Bun maps a stack trace by the code this compiler hands it, not by a source map of its own.
|
|
252
86
|
const mark = lineMarker(code)
|
|
253
87
|
const used = new Set<string>()
|
|
254
|
-
const nextId = createIdCounter(code)
|
|
255
|
-
let activeSelectValue: SelectValueBinding | undefined
|
|
256
|
-
|
|
257
|
-
const use = (name: string): string => {
|
|
258
|
-
used.add(name)
|
|
259
|
-
return `__${name}`
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
const islands = options.islands
|
|
263
|
-
const devSrc = createDevSourceAttr(filename, code, options.devSourceRoot)
|
|
264
|
-
const markersAt = markerTest(options.emitMarkers ?? options.isIsland ?? analysis.isInteractive)
|
|
265
88
|
const jsxNodes = analysis.jsxNodes
|
|
266
|
-
const exprContext = getExprContext(analysis)
|
|
267
89
|
const { directAwaitNodes, dynamicChildNodes } = precomputeSsrSubtreeFlags(program)
|
|
268
|
-
const compileSubExpression = (node: Node): string => compileSsrSubExpression(code, node, jsxNodes, mark, compileRootJsx)
|
|
269
|
-
const compileComponentRaw = (node: JSXElement, tag: string): string => {
|
|
270
|
-
let out = ''
|
|
271
|
-
emitComponent(node, tag, new StringParts(), (e) => { out = e })
|
|
272
|
-
return out
|
|
273
|
-
}
|
|
274
|
-
const prunelleTags: PrunelleTagEmitter = { use, compileSubExpression, compileChildren: compileChildrenListToStringExpr, compileJsx: compileJsxToStringExpr, compileComponentRaw, markersAt, directAwaitNodes, jsxNodes }
|
|
275
|
-
|
|
276
|
-
function compileChildrenListToStringExpr(children: readonly JSXChild[], slotMarkers = markersAt(children[0]?.start ?? 0), inFragment = false, rawTextTag?: 'style' | 'script'): string {
|
|
277
|
-
const bufVar = `_o${nextId()}`
|
|
278
|
-
const stmts: string[] = []
|
|
279
|
-
const parts = new StringParts()
|
|
280
|
-
const flush = () => flushStringParts(bufVar, parts, stmts)
|
|
281
|
-
emitChildrenIntoBuffer(children, bufVar, parts, flush, s => stmts.push(s), rawTextTag, slotMarkers, inFragment)
|
|
282
|
-
if (stmts.length === 0)
|
|
283
|
-
return parts.toExpr()
|
|
284
|
-
flush()
|
|
285
|
-
const hasAwait = children.some(c => directAwaitNodes.has(c))
|
|
286
|
-
if (hasAwait)
|
|
287
|
-
return `(await (async () => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })())`
|
|
288
|
-
return `(() => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })()`
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
// Emits JSX directly into a string accumulator variable `_out` (zero closures on nested `.map()` loops!)
|
|
292
|
-
function emitIntoBuffer(node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void, actionOverride?: { node: Node, ident: string }): void {
|
|
293
|
-
if (node.type === 'JSXFragment') {
|
|
294
|
-
emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, undefined, markersAt(node.start), true)
|
|
295
|
-
return
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
const tag = jsxTagName(node.openingElement.name)
|
|
299
|
-
if (isComponentTag(tag)) {
|
|
300
|
-
emitComponent(node, tag, parts)
|
|
301
|
-
return
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
if (tag === 'form' && actionOverride === undefined) {
|
|
305
|
-
const formAction = findDynamicFormAction(node)
|
|
306
|
-
if (formAction !== undefined) {
|
|
307
|
-
parts.pushExpr(emitActionFormExpr(formAction, directAwaitNodes.has(node), nextId, use, compileSubExpression, (b, p, f, ps, ov) => emitIntoBuffer(node, b, p, f, ps, ov)))
|
|
308
|
-
return
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
parts.pushStatic(`<${tag}${devSrc(node, tag)}`)
|
|
313
|
-
const isTextarea = tag === 'textarea'
|
|
314
|
-
const needsLeadNl = isTextarea || tag === 'pre'
|
|
315
|
-
const compileAttrExpr = actionOverride !== undefined ? (n: Node) => (n === actionOverride.node ? actionOverride.ident : compileSubExpression(n)) : compileSubExpression
|
|
316
|
-
const { innerHtmlExpr, textareaValue, nextSelectValue } = emitSsrElementAttrs({ node, tag, parts, activeSelectValue, flushParts, pushStmt, nextId, use, compileSubExpression: compileAttrExpr })
|
|
317
|
-
if (FORM_CONTROL_TAGS.has(tag))
|
|
318
|
-
emitFormControlAttrs(node, tag as 'input' | 'select' | 'textarea', parts, use, compileSubExpression)
|
|
319
|
-
parts.pushStatic('>')
|
|
320
|
-
if (VOID_ELEMENTS.has(tag))
|
|
321
|
-
return
|
|
322
|
-
|
|
323
|
-
const prevSelectValue = activeSelectValue
|
|
324
|
-
if (tag === 'select')
|
|
325
|
-
activeSelectValue = nextSelectValue
|
|
326
|
-
|
|
327
|
-
try {
|
|
328
|
-
if (innerHtmlExpr !== undefined)
|
|
329
|
-
parts.pushExpr(needsLeadNl ? `${use('ssrLeadNl')}(${innerHtmlExpr})` : innerHtmlExpr)
|
|
330
|
-
else if (isTextarea && textareaValue !== undefined && filterMeaningfulChildren(node.children).length === 0)
|
|
331
|
-
textareaValue.staticText !== undefined ? pushLeadNlStatic(parts, escapeStaticText(textareaValue.staticText)) : textareaValue.expr !== undefined && parts.pushExpr(`${use('ssrLeadNl')}(${use('esc')}(${textareaValue.expr}))`)
|
|
332
|
-
else if (tag === 'style' || needsLeadNl) {
|
|
333
|
-
const bodyExpr = tag === 'style' ? compileChildrenListToStringExpr(node.children, false, false, 'style') : compileChildrenListToStringExpr(node.children)
|
|
334
|
-
if (bodyExpr !== '""')
|
|
335
|
-
parts.pushExpr(`${use(tag === 'style' ? 'ssrStyleBlock' : 'ssrLeadNl')}(${bodyExpr})`)
|
|
336
|
-
}
|
|
337
|
-
else
|
|
338
|
-
emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
|
|
339
|
-
}
|
|
340
|
-
finally {
|
|
341
|
-
activeSelectValue = prevSelectValue
|
|
342
|
-
}
|
|
343
|
-
if (actionOverride === undefined)
|
|
344
|
-
parts.pushStatic(`</${tag}>`)
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
function emitChildrenIntoBuffer(
|
|
348
|
-
children: readonly JSXChild[],
|
|
349
|
-
bufVar: string,
|
|
350
|
-
parts: StringParts,
|
|
351
|
-
flushParts: () => void,
|
|
352
|
-
pushStmt: (stmt: string) => void,
|
|
353
|
-
rawTextTag?: 'style' | 'script',
|
|
354
|
-
slotMarkers = markersAt(children[0]?.start ?? 0),
|
|
355
|
-
inFragment = false,
|
|
356
|
-
): void {
|
|
357
|
-
const planned = planChildSlots(children, { jsxNodes, exprContext, emitMarkers: slotMarkers, inFragment })
|
|
358
|
-
|
|
359
|
-
for (const { child, slot, open, close } of planned) {
|
|
360
|
-
if (slot.kind === 'static-text') {
|
|
361
|
-
if (rawTextTag !== undefined)
|
|
362
|
-
parts.pushStatic(escapeRawText(slot.text, rawTextTag))
|
|
363
|
-
else
|
|
364
|
-
parts.pushStatic(escapeStaticText(slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text)))
|
|
365
|
-
continue
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
if (rawTextTag !== undefined) {
|
|
369
|
-
if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression') {
|
|
370
|
-
const expr = child.expression
|
|
371
|
-
if (expr.type === 'TemplateLiteral' && expr.expressions.length === 0 && expr.quasis.length === 1) {
|
|
372
|
-
const cooked = expr.quasis[0]?.value.cooked
|
|
373
|
-
if (typeof cooked === 'string') {
|
|
374
|
-
parts.pushStatic(escapeRawText(cooked, rawTextTag))
|
|
375
|
-
continue
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
parts.pushExpr(`${use('ssrRawText')}(${JSON.stringify(rawTextTag)}, ${compileSubExpression(expr)})`)
|
|
379
|
-
continue
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
if (slot.kind === 'element') {
|
|
384
|
-
emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
|
|
385
|
-
continue
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
if (open !== '')
|
|
389
|
-
parts.pushStatic(open)
|
|
390
|
-
|
|
391
|
-
if (slot.kind === 'component' || slot.kind === 'fragment') {
|
|
392
|
-
emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
|
|
393
|
-
}
|
|
394
|
-
else if (slot.kind === 'loop') {
|
|
395
|
-
const { match } = slot
|
|
396
|
-
const itemParam = match.params[0]?.type === 'Identifier' ? match.params[0].name : undefined
|
|
397
|
-
const idxParam = match.params[1]?.type === 'Identifier' ? match.params[1].name : undefined
|
|
398
|
-
|
|
399
|
-
if (match.isJsxBody && itemParam !== undefined && match.params.length <= 2 && (match.params.length < 2 || idxParam !== undefined)) {
|
|
400
|
-
flushParts()
|
|
401
|
-
const n = nextId()
|
|
402
|
-
const arrVar = `_a${n}`
|
|
403
|
-
const idxVar = idxParam ?? `_i${n}`
|
|
404
|
-
const innerStmts: string[] = []
|
|
405
|
-
const innerParts = new StringParts()
|
|
406
|
-
const flushInner = () => flushStringParts(bufVar, innerParts, innerStmts)
|
|
407
|
-
emitIntoBuffer(match.body as JSXElement | JSXFragment, bufVar, innerParts, flushInner, s => innerStmts.push(s))
|
|
408
|
-
flushInner()
|
|
409
|
-
|
|
410
|
-
const target = compileSubExpression(match.target)
|
|
411
|
-
pushStmt(
|
|
412
|
-
`const ${arrVar} = ${target}; if (${arrVar}) for (let ${idxVar} = 0; ${idxVar} < ${arrVar}.length; ${idxVar}++) { const ${itemParam} = ${arrVar}[${idxVar}]; ${innerStmts.join(' ')} }`,
|
|
413
|
-
)
|
|
414
|
-
}
|
|
415
|
-
else if (match.isJsxBody) {
|
|
416
|
-
const target = compileSubExpression(match.target)
|
|
417
|
-
const params = match.params.map(p => compileSubExpression(p)).join(', ')
|
|
418
|
-
parts.pushExpr(`${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(match.body as JSXElement | JSXFragment)})`)
|
|
419
|
-
}
|
|
420
|
-
else {
|
|
421
|
-
parts.pushExpr(`${use('esc')}(${compileSubExpression(match.call)})`)
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
else if (slot.kind === 'and-show') {
|
|
425
|
-
const left = compileSubExpression(slot.expr.left)
|
|
426
|
-
const right = compileJsxToStringExpr(slot.right)
|
|
427
|
-
parts.pushExpr(`((${left}) ? (${right}) : "")`)
|
|
428
|
-
}
|
|
429
|
-
else if (slot.kind === 'ternary-show') {
|
|
430
|
-
const test = compileSubExpression(slot.expr.test)
|
|
431
|
-
const cons = compileExpressionAsString(slot.cons)
|
|
432
|
-
const alt = compileExpressionAsString(slot.alt)
|
|
433
|
-
parts.pushExpr(`((${test}) ? (${cons}) : (${alt}))`)
|
|
434
|
-
}
|
|
435
|
-
else {
|
|
436
|
-
parts.pushExpr(`${use('esc')}(${compileSubExpression(slot.expr)})`)
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
if (close !== '')
|
|
440
|
-
parts.pushStatic(close)
|
|
441
|
-
}
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
const compileExpressionAsString = (expr: Node): string => compileSsrExprAsString(expr, use, compileSubExpression, compileJsxToStringExpr)
|
|
445
|
-
|
|
446
|
-
function emitComponent(node: JSXElement, tag: string, parts: StringParts, onRaw?: (expr: string) => void): void {
|
|
447
|
-
const { propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate } = serializeComponentProps(node.openingElement.attributes, compileSubExpression)
|
|
448
|
-
const childNodes = node.children
|
|
449
|
-
const meaningfulChildren = filterMeaningfulChildren(childNodes)
|
|
450
|
-
const hasChildren = meaningfulChildren.length > 0
|
|
451
|
-
// The call sits on the line of its tag, so a component that throws names that line in the caller's frame.
|
|
452
|
-
const call = `${mark(node.start)}${tag}`
|
|
453
|
-
|
|
454
|
-
const prunelleTag = resolvePrunelleTag(tag, analysis.imports)
|
|
455
|
-
if (prunelleTag === 'Suspense' || prunelleTag === 'Catch') {
|
|
456
|
-
;(prunelleTag === 'Suspense' ? emitSuspense : emitCatch)(prunelleTags, node, tag, propEntries, parts, onRaw)
|
|
457
|
-
return
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
const islandInfo = islands?.get(tag)
|
|
461
|
-
if (islandInfo === undefined && islands !== undefined && hydrateExpr !== undefined)
|
|
462
|
-
throw hydrateMistake(tag, filename, true)
|
|
463
|
-
|
|
464
|
-
const childrenHaveAwait = hasChildren && childNodes.some(c => directAwaitNodes.has(c))
|
|
465
|
-
const childMarkers = islandInfo === undefined && markersAt(node.start)
|
|
466
|
-
const onlyComp = onRaw !== undefined && islandInfo === undefined && meaningfulChildren.length === 1 && meaningfulChildren[0]!.type === 'JSXElement' && isComponentTag(jsxTagName(meaningfulChildren[0]!.openingElement.name)) ? meaningfulChildren[0]! : undefined
|
|
467
|
-
const childExpr = onlyComp !== undefined
|
|
468
|
-
? compileComponentRaw(onlyComp, jsxTagName(onlyComp.openingElement.name))
|
|
469
|
-
: hasChildren ? compileChildrenListToStringExpr(childNodes, childMarkers, childMarkers && (meaningfulChildren.length > 1 || isSingleLoopChild(meaningfulChildren, jsxNodes))) : '""'
|
|
470
|
-
|
|
471
|
-
if (islandInfo !== undefined) {
|
|
472
|
-
const target = onRaw !== undefined ? new StringParts() : parts
|
|
473
|
-
emitIsland({ use, nextId, markersAt }, { island: islandInfo, tag, call, start: node.start, propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate, hasChildren, childExpr, childrenHaveAwait }, target)
|
|
474
|
-
if (onRaw !== undefined)
|
|
475
|
-
onRaw(`${use('raw')}(${target.toExpr()})`)
|
|
476
|
-
return
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
const emitOut = (expr: string): void => {
|
|
480
|
-
if (onRaw !== undefined)
|
|
481
|
-
onRaw(expr)
|
|
482
|
-
else
|
|
483
|
-
parts.pushExpr(`${use('ssrChild')}(${expr})`)
|
|
484
|
-
}
|
|
485
|
-
const wrappedChild = onlyComp !== undefined ? childExpr : `${use('raw')}(${childExpr})`
|
|
486
|
-
const childrenHaveDynamic = hasChildren && childNodes.some(c => dynamicChildNodes.has(c))
|
|
487
|
-
|
|
488
|
-
// Lazy memoized getter for non-async dynamic/component children so Providers & context components run before their children!
|
|
489
|
-
if (childrenHaveDynamic && !childrenHaveAwait) {
|
|
490
|
-
const cVar = `_c${nextId()}`
|
|
491
|
-
const propsWithGetter = [...propEntries, `get children() { return ${cVar} === undefined ? (${cVar} = ${wrappedChild}) : ${cVar} }`].join(', ')
|
|
492
|
-
emitOut(`${call}((() => { let ${cVar}; return { ${propsWithGetter} }; })())`)
|
|
493
|
-
return
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
if (hasChildren)
|
|
497
|
-
propEntries.push(`children: ${wrappedChild}`)
|
|
498
|
-
|
|
499
|
-
const propsObj = propEntries.length > 0 ? `{ ${propEntries.join(', ')} }` : '{}'
|
|
500
|
-
emitOut(`${call}(${propsObj})`)
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
function compileJsxToStringExpr(node: JSXElement | JSXFragment): string {
|
|
504
|
-
const bufVar = `_o${nextId()}`
|
|
505
|
-
const stmts: string[] = []
|
|
506
|
-
const parts = new StringParts()
|
|
507
|
-
|
|
508
|
-
const flush = () => flushStringParts(bufVar, parts, stmts)
|
|
509
|
-
|
|
510
|
-
emitIntoBuffer(node, bufVar, parts, flush, s => stmts.push(s))
|
|
511
|
-
|
|
512
|
-
// If no inline `for` statements were emitted, stay a pure flat concatenation expression!
|
|
513
|
-
if (stmts.length === 0)
|
|
514
|
-
return parts.toExpr()
|
|
515
|
-
|
|
516
|
-
flush()
|
|
517
|
-
if (directAwaitNodes.has(node))
|
|
518
|
-
return `(await (async () => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })())`
|
|
519
|
-
return `(() => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })()`
|
|
520
|
-
}
|
|
521
90
|
|
|
522
|
-
|
|
523
|
-
|
|
91
|
+
const env: SsrEnv = {
|
|
92
|
+
filename,
|
|
93
|
+
analysis,
|
|
94
|
+
islands: options.islands,
|
|
95
|
+
devSrc: createDevSourceAttr(filename, code, options.devSourceRoot),
|
|
96
|
+
markersAt: markerTest(options.emitMarkers ?? options.isIsland ?? analysis.isInteractive),
|
|
97
|
+
jsxNodes,
|
|
98
|
+
exprContext: getExprContext(analysis),
|
|
99
|
+
directAwaitNodes,
|
|
100
|
+
dynamicChildNodes,
|
|
101
|
+
use: (name) => {
|
|
102
|
+
used.add(name)
|
|
103
|
+
return `__${name}`
|
|
104
|
+
},
|
|
105
|
+
nextId: createIdCounter(code),
|
|
106
|
+
mark,
|
|
107
|
+
compileSubExpression: node => compileSsrSubExpression(code, node, jsxNodes, mark, n => compileRootJsx(env, n)),
|
|
108
|
+
activeSelectValue: undefined,
|
|
524
109
|
}
|
|
525
110
|
|
|
526
111
|
walk(program, (node) => {
|
|
527
112
|
if (isJsxNode(node)) {
|
|
528
|
-
editor.replace(node.start, node.end, compileRootJsx(node) + mark(node.end))
|
|
113
|
+
editor.replace(node.start, node.end, compileRootJsx(env, node) + mark(node.end))
|
|
529
114
|
return false
|
|
530
115
|
}
|
|
531
116
|
return undefined
|
package/src/context.ts
CHANGED
|
@@ -21,7 +21,7 @@ export interface ConsentGateProps {
|
|
|
21
21
|
children?: PrunelleChild
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
/** The button and legend texts of `<ConsentBanner>` and `<ConsentPreferences>`, English
|
|
24
|
+
/** The button and legend texts of `<ConsentBanner>` and `<ConsentPreferences>`, French when `lang` is `fr` and English otherwise. */
|
|
25
25
|
export interface ConsentTexts {
|
|
26
26
|
accept?: string | undefined
|
|
27
27
|
refuse?: string | undefined
|
|
@@ -43,6 +43,11 @@ export interface ConsentBannerProps extends ConsentTexts {
|
|
|
43
43
|
choose?: string | undefined
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
export interface CookieTableProps {
|
|
47
|
+
/** Caption of the table (default: `'Cookies this site sets'`, or its French when `lang` is `fr`). */
|
|
48
|
+
caption?: string | undefined
|
|
49
|
+
}
|
|
50
|
+
|
|
46
51
|
export interface CatchProps {
|
|
47
52
|
/** Rendered in place of `children` when they throw; a function gets the error and a `retry` that renders the children again (a no-op on the server). */
|
|
48
53
|
fallback?: PrunelleChild | ((error: unknown, retry: () => void) => PrunelleChild)
|
|
@@ -54,9 +59,11 @@ export interface ServerContextBridge {
|
|
|
54
59
|
consentGate(props: ConsentGateProps): PrunelleChild
|
|
55
60
|
consentBanner(props: ConsentBannerProps): PrunelleChild
|
|
56
61
|
consentPreferences(props: ConsentTexts): PrunelleChild
|
|
62
|
+
cookieTable(props: CookieTableProps): PrunelleChild
|
|
57
63
|
getContext(key: symbol): { found: true, value: unknown } | undefined
|
|
58
64
|
runWithContext<T>(key: symbol, value: unknown, fn: () => T): T
|
|
59
65
|
nextId(): string | undefined
|
|
66
|
+
requestLocale?(): string | undefined
|
|
60
67
|
head(props: { children?: PrunelleChild }): PrunelleChild
|
|
61
68
|
suspense(props: { fallback?: PrunelleChild, error?: PrunelleChild | ((error: unknown) => PrunelleChild), children?: PrunelleChild | Promise<PrunelleChild> }): PrunelleChild
|
|
62
69
|
catch(props: CatchProps): PrunelleChild | Promise<PrunelleChild>
|
|
@@ -119,6 +126,12 @@ export function ConsentPreferences(props: ConsentTexts): PrunelleChild {
|
|
|
119
126
|
return bridge !== undefined ? bridge.consentPreferences(props) : null
|
|
120
127
|
}
|
|
121
128
|
|
|
129
|
+
/** Every cookie the site sets, with its purpose, its consent category and how long it lives: prunelle's, each plugin's, and the app's, read from its `cookies.set` calls at build time. Server-only, 0 KB browser JS. */
|
|
130
|
+
export function CookieTable(props: CookieTableProps): PrunelleChild {
|
|
131
|
+
const bridge = getServerBridge()
|
|
132
|
+
return bridge !== undefined ? bridge.cookieTable(props) : null
|
|
133
|
+
}
|
|
134
|
+
|
|
122
135
|
export interface Context<T> {
|
|
123
136
|
readonly id: symbol
|
|
124
137
|
readonly defaultValue: T
|
package/src/dev/child.ts
CHANGED
|
@@ -26,5 +26,5 @@ if (import.meta.main) {
|
|
|
26
26
|
process.on('disconnect', stop)
|
|
27
27
|
process.on('SIGINT', stop)
|
|
28
28
|
process.on('SIGTERM', stop)
|
|
29
|
-
send({ t: 'ready', assetPrefix: srv.assetPrefix })
|
|
29
|
+
send({ t: 'ready', assetPrefix: srv.assetPrefix, allowedOrigins: srv.allowedOrigins })
|
|
30
30
|
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// prunelle dev's hot swap: after a rebuild, which islands of the open page get new code in place and which edits still reload it.
|
|
2
|
+
|
|
3
|
+
import type { BuildCache } from '../build/graph'
|
|
4
|
+
import type { BuildManifest } from '../build/manifest'
|
|
5
|
+
|
|
6
|
+
/** What each analysed source file read as, to tell which ones a rebuild changed. */
|
|
7
|
+
function sourceSnapshot(cache: BuildCache): Map<string, string> {
|
|
8
|
+
return new Map([...cache.analyses].map(([file, entry]) => [file, entry.code]))
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function sameList(a: readonly string[] | undefined, b: readonly string[] | undefined): boolean {
|
|
12
|
+
return (a ?? []).join('\n') === (b ?? []).join('\n')
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The island chunk URLs to swap, old to new, or `undefined` when the page must reload.
|
|
17
|
+
* Only the code of islands may have changed: the files this rebuild changed are island files with no `load()`, the scripts and styles every page loads are the same, and the same islands exist.
|
|
18
|
+
*/
|
|
19
|
+
function hotIslandSwaps(prev: BuildManifest, next: BuildManifest, before: ReadonlyMap<string, string>, cache: BuildCache): Record<string, string> | undefined {
|
|
20
|
+
const keys = Object.keys(next.islands)
|
|
21
|
+
if (keys.length !== Object.keys(prev.islands).length || keys.some(key => prev.islands[key] === undefined))
|
|
22
|
+
return undefined
|
|
23
|
+
if (prev.runtimeScript !== next.runtimeScript || prev.regionScript !== next.regionScript || prev.reviveScript !== next.reviveScript)
|
|
24
|
+
return undefined
|
|
25
|
+
if (!sameList(prev.styles, next.styles) || !sameList(prev.globalStyles, next.globalStyles) || !sameList(prev.headTags, next.headTags))
|
|
26
|
+
return undefined
|
|
27
|
+
const swaps: Record<string, string> = {}
|
|
28
|
+
for (const key of keys) {
|
|
29
|
+
if (prev.islands[key] !== next.islands[key])
|
|
30
|
+
swaps[prev.islands[key]!] = next.islands[key]!
|
|
31
|
+
}
|
|
32
|
+
if (Object.keys(swaps).length === 0)
|
|
33
|
+
return undefined
|
|
34
|
+
const islandExports = new Map<string, Set<string>>()
|
|
35
|
+
for (const key of keys) {
|
|
36
|
+
const cut = key.lastIndexOf('#')
|
|
37
|
+
const file = key.slice(0, cut)
|
|
38
|
+
islandExports.set(file, (islandExports.get(file) ?? new Set()).add(key.slice(cut + 1)))
|
|
39
|
+
}
|
|
40
|
+
const files = new Set([...before.keys(), ...cache.analyses.keys()])
|
|
41
|
+
let changed = 0
|
|
42
|
+
for (const file of files) {
|
|
43
|
+
if (before.get(file) === cache.analyses.get(file)?.code)
|
|
44
|
+
continue
|
|
45
|
+
// A file that is no island, one that exports more than its islands (static markup of the page), or whose server side (`load()`) shows in the open page, cannot be told apart from a change to the static page.
|
|
46
|
+
const exported = islandExports.get(file)
|
|
47
|
+
const analysis = cache.analyses.get(file)?.analysis
|
|
48
|
+
if (exported === undefined || analysis?.hasLoadExport !== false || analysis.exportedNames.some(name => !exported.has(name)))
|
|
49
|
+
return undefined
|
|
50
|
+
changed++
|
|
51
|
+
}
|
|
52
|
+
return changed === 0 ? undefined : swaps
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Remembers the last build's manifest and what each analysed file read as, so each rebuild can say which islands to swap. */
|
|
56
|
+
export function createHotSwaps(cache: BuildCache) {
|
|
57
|
+
let last: BuildManifest | undefined
|
|
58
|
+
let before = new Map<string, string>()
|
|
59
|
+
return {
|
|
60
|
+
/** Called before a rebuild reads the sources. */
|
|
61
|
+
start(): void {
|
|
62
|
+
before = sourceSnapshot(cache)
|
|
63
|
+
},
|
|
64
|
+
/** Called once the rebuild landed; `allowed` is false when the page must reload anyway. */
|
|
65
|
+
land(manifest: BuildManifest, allowed: boolean): Record<string, string> | undefined {
|
|
66
|
+
const swaps = allowed && last !== undefined ? hotIslandSwaps(last, manifest, before, cache) : undefined
|
|
67
|
+
last = manifest
|
|
68
|
+
return swaps
|
|
69
|
+
},
|
|
70
|
+
}
|
|
71
|
+
}
|