@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.1
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/package.json +1 -1
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +442 -0
- package/src/build/compile.ts +20 -11
- package/src/build/files.ts +136 -0
- package/src/build/graph.ts +158 -0
- package/src/build/index.ts +231 -1296
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +224 -0
- package/src/build/plugin-host.ts +184 -0
- package/src/build/prerender.ts +93 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +58 -0
- package/src/build/routes.ts +135 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +228 -114
- package/src/cli/index.ts +298 -79
- package/src/cli/new.ts +67 -35
- package/src/compiler/analyze.ts +666 -91
- package/src/compiler/dom.ts +822 -629
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +164 -21
- package/src/compiler/shared.ts +442 -0
- package/src/compiler/ssr.ts +390 -324
- package/src/context.ts +120 -0
- package/src/dev/index.ts +291 -76
- package/src/dom/action.ts +23 -13
- package/src/dom/extras.ts +157 -84
- package/src/dom/index.ts +154 -33
- package/src/dom/island.ts +117 -39
- package/src/dom/loop.ts +34 -21
- package/src/index.ts +2 -1
- package/src/jsx-runtime.ts +11 -0
- package/src/plugins/context.ts +57 -0
- package/src/plugins/index.ts +120 -17
- package/src/reactivity/index.ts +250 -157
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +37 -12
- package/src/server/action.ts +217 -74
- package/src/server/compress.ts +155 -56
- package/src/server/cookies.ts +59 -22
- package/src/server/env.ts +18 -13
- package/src/server/http.ts +201 -33
- package/src/server/index.ts +964 -737
- package/src/server/loader.ts +120 -0
- package/src/server/router.ts +27 -8
- package/src/server/security.ts +87 -39
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +144 -0
- package/src/ssr/context.ts +96 -10
- package/src/ssr/index.ts +225 -56
- package/src/style.ts +33 -0
- package/src/test/index.ts +5 -0
- package/src/unrenderable.ts +35 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// Island discovery: which exports run in the browser, which modules render them, and the checks that keep server code out of them.
|
|
2
|
+
|
|
3
|
+
import type { ModuleGraph } from './graph'
|
|
4
|
+
import { basename, extname } from 'node:path'
|
|
5
|
+
import { asyncInteractiveError } from '../compiler/analyze'
|
|
6
|
+
import { isTsFile, relPosix } from './files'
|
|
7
|
+
|
|
8
|
+
export interface IslandTarget {
|
|
9
|
+
id: string
|
|
10
|
+
file: string
|
|
11
|
+
exportName: string
|
|
12
|
+
defaultHydrate: string | undefined
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type ActionsByFile = Map<string, { exportName: string, url: string }[]>
|
|
16
|
+
|
|
17
|
+
export interface IslandPlan {
|
|
18
|
+
/** Island roots keyed `file#exportName`. */
|
|
19
|
+
targets: Map<string, IslandTarget>
|
|
20
|
+
/** Per static module, the island each rendered tag stands for. */
|
|
21
|
+
pageBindings: Map<string, Map<string, IslandTarget>>
|
|
22
|
+
/** CSS files imported (transitively) by an island: bundled with it, not as standalone styles. */
|
|
23
|
+
cssFiles: Set<string>
|
|
24
|
+
/** Modules the client compiles for an island, whose SSR must emit hydration markers too. */
|
|
25
|
+
reach: Set<string>
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function islandKey(target: { file: string, exportName: string }): string {
|
|
29
|
+
return `${target.file}#${target.exportName}`
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function planIslands(graph: ModuleGraph, root: string, pageFiles: string[], specialFiles: string[], actionsByFile: ActionsByFile): IslandPlan {
|
|
33
|
+
const { analyses } = graph
|
|
34
|
+
const targets = new Map<string, IslandTarget>()
|
|
35
|
+
const usedIds = new Set<string>()
|
|
36
|
+
const pageBindings = new Map<string, Map<string, IslandTarget>>()
|
|
37
|
+
const pageSet = new Set(pageFiles)
|
|
38
|
+
|
|
39
|
+
function registerIsland(file: string, exportName: string): IslandTarget {
|
|
40
|
+
const key = islandKey({ file, exportName })
|
|
41
|
+
const existing = targets.get(key)
|
|
42
|
+
if (existing !== undefined)
|
|
43
|
+
return existing
|
|
44
|
+
const baseName = basename(file, extname(file)).toLowerCase()
|
|
45
|
+
const expLower = exportName.toLowerCase()
|
|
46
|
+
let id = exportName === 'default' || expLower === baseName ? baseName : `${baseName}-${expLower}`
|
|
47
|
+
// The id names the entry file and the chunk: two islands sharing a basename keep it readable and add a hash of their path.
|
|
48
|
+
if (usedIds.has(id))
|
|
49
|
+
id = `${id}-${Bun.hash(relPosix(root, key)).toString(36).slice(0, 6)}`
|
|
50
|
+
usedIds.add(id)
|
|
51
|
+
const target: IslandTarget = { id, file, exportName, defaultHydrate: graph.load(file).defaultHydrate }
|
|
52
|
+
targets.set(key, target)
|
|
53
|
+
return target
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// A component reading reactive state another module exports runs in the browser too. The promoted analysis lives in this build's map only, so the cached one still reflects the file alone.
|
|
57
|
+
for (const [file, analysis] of analyses) {
|
|
58
|
+
if (!file.endsWith('.tsx') || analysis.isInteractive)
|
|
59
|
+
continue
|
|
60
|
+
for (const imp of analysis.imports) {
|
|
61
|
+
const resolved = graph.resolve(file, imp.source)
|
|
62
|
+
const state = resolved === undefined || !isTsFile(resolved)
|
|
63
|
+
? undefined
|
|
64
|
+
: imp.specifiers.find((spec) => {
|
|
65
|
+
if (analysis.jsxTags.has(spec.local))
|
|
66
|
+
return false
|
|
67
|
+
if (spec.imported === '*')
|
|
68
|
+
return graph.load(resolved).stateExports.length > 0
|
|
69
|
+
const target = graph.exportTarget(resolved, spec.imported)
|
|
70
|
+
return graph.load(target.file).stateExports.includes(target.exportName)
|
|
71
|
+
})
|
|
72
|
+
if (state !== undefined) {
|
|
73
|
+
const reason = `reads ${state.local} from '${imp.source}'`
|
|
74
|
+
if (analysis.hasAsyncDefault)
|
|
75
|
+
throw asyncInteractiveError(file, reason)
|
|
76
|
+
analyses.set(file, { ...analysis, isInteractive: true, interactiveReason: reason })
|
|
77
|
+
break
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
for (const [file, analysis] of analyses) {
|
|
83
|
+
if (!file.endsWith('.tsx'))
|
|
84
|
+
continue
|
|
85
|
+
if (analysis.isInteractive) {
|
|
86
|
+
if (pageSet.has(file))
|
|
87
|
+
registerIsland(file, 'default')
|
|
88
|
+
continue
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Only names rendered as tags become islands: `<Counter />`, or `<UI.Counter />` through a namespace import.
|
|
92
|
+
const bindings = new Map<string, IslandTarget>()
|
|
93
|
+
for (const imp of analysis.imports) {
|
|
94
|
+
const resolved = graph.resolve(file, imp.source)
|
|
95
|
+
if (resolved === undefined || !isTsFile(resolved))
|
|
96
|
+
continue
|
|
97
|
+
for (const spec of imp.specifiers) {
|
|
98
|
+
const tags = spec.imported === '*'
|
|
99
|
+
? [...analysis.jsxTags].filter(tag => tag.startsWith(`${spec.local}.`) && !tag.slice(spec.local.length + 1).includes('.')).map(tag => [tag, tag.slice(spec.local.length + 1)] as const)
|
|
100
|
+
: analysis.jsxTags.has(spec.local) ? [[spec.local, spec.imported] as const] : []
|
|
101
|
+
for (const [tag, exportName] of tags) {
|
|
102
|
+
const target = graph.exportTarget(resolved, exportName)
|
|
103
|
+
if (target.file.endsWith('.tsx') && graph.load(target.file).isInteractive)
|
|
104
|
+
bindings.set(tag, registerIsland(target.file, target.exportName))
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (bindings.size > 0)
|
|
109
|
+
pageBindings.set(file, bindings)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const isStubbedActionFile = (file: string): boolean =>
|
|
113
|
+
!analyses.get(file)?.isInteractive && actionsByFile.has(file)
|
|
114
|
+
|
|
115
|
+
// Component/page CSS & CSS Module imports reached from islands are bundled via island entrypoints.
|
|
116
|
+
const cssFiles = new Set<string>()
|
|
117
|
+
const cssSeen = new Set<string>()
|
|
118
|
+
const cssStack = [...targets.values()].map(t => t.file)
|
|
119
|
+
while (cssStack.length > 0) {
|
|
120
|
+
const file = cssStack.pop()!
|
|
121
|
+
if (cssSeen.has(file))
|
|
122
|
+
continue
|
|
123
|
+
cssSeen.add(file)
|
|
124
|
+
for (const imp of analyses.get(file)?.imports ?? []) {
|
|
125
|
+
const target = graph.resolve(file, imp.source)
|
|
126
|
+
if (target === undefined)
|
|
127
|
+
continue
|
|
128
|
+
if (target.endsWith('.css'))
|
|
129
|
+
cssFiles.add(target)
|
|
130
|
+
else if (isTsFile(target) && !isStubbedActionFile(target))
|
|
131
|
+
cssStack.push(target)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// A layout, error or 404 page renders on the server only, so interactivity written in it would never run.
|
|
136
|
+
for (const file of specialFiles) {
|
|
137
|
+
const analysis = analyses.get(file)
|
|
138
|
+
if (analysis?.isInteractive === true) {
|
|
139
|
+
const rel = relPosix(root, file)
|
|
140
|
+
throw new Error(`kay build: ${rel} uses browser interactivity (${analysis.interactiveReason}), but it renders on the server only. Move the interactive part into a component and render that component from ${rel}.`)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// The client compiles every module an island imports to hydrate against SSR markers, so their SSR must emit them too.
|
|
145
|
+
const reach = new Set<string>()
|
|
146
|
+
const reachSeen = new Set<string>()
|
|
147
|
+
const reachStack = [...targets.values()].map(t => t.file)
|
|
148
|
+
while (reachStack.length > 0) {
|
|
149
|
+
const file = reachStack.pop()!
|
|
150
|
+
if (reachSeen.has(file))
|
|
151
|
+
continue
|
|
152
|
+
reachSeen.add(file)
|
|
153
|
+
if (file.endsWith('.tsx'))
|
|
154
|
+
reach.add(file)
|
|
155
|
+
for (const dep of graph.localDeps(file)) {
|
|
156
|
+
if (!isStubbedActionFile(dep))
|
|
157
|
+
reachStack.push(dep)
|
|
158
|
+
}
|
|
159
|
+
const analysis = analyses.get(file)
|
|
160
|
+
for (const imp of analysis?.imports ?? []) {
|
|
161
|
+
// The client build swaps an action file for stubs of its actions, so any other export it has is missing there.
|
|
162
|
+
const target = graph.resolve(file, imp.source)
|
|
163
|
+
const actions = target !== undefined && isStubbedActionFile(target) ? actionsByFile.get(target) : undefined
|
|
164
|
+
const missing = actions !== undefined ? imp.specifiers.find(s => s.imported !== '*' && !actions.some(a => a.exportName === s.imported)) : undefined
|
|
165
|
+
if (missing !== undefined)
|
|
166
|
+
throw new Error(`kay build: ${relPosix(root, file)} runs in the browser and imports ${missing.imported} from ${relPosix(root, target!)}, a file of server actions: the browser only gets its actions. Move ${missing.imported} into a module without actions.`)
|
|
167
|
+
}
|
|
168
|
+
for (const re of analysis?.reexports ?? []) {
|
|
169
|
+
const target = graph.resolve(file, re.source)
|
|
170
|
+
const actions = target !== undefined && isStubbedActionFile(target) ? actionsByFile.get(target) : undefined
|
|
171
|
+
if (actions !== undefined && re.local !== '*' && !actions.some(a => a.exportName === re.local))
|
|
172
|
+
throw new Error(`kay build: ${relPosix(root, file)} runs in the browser and re-exports ${re.local} from ${relPosix(root, target!)}, a file of server actions: the browser only gets its actions. Move ${re.local} into a module without actions.`)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return { targets, pageBindings, cssFiles, reach }
|
|
177
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// The build manifest: its shape, and the per-route entries (islands, styles, layouts, middlewares) computed from the module graph.
|
|
2
|
+
|
|
3
|
+
import type { ModuleGraph } from './graph'
|
|
4
|
+
import type { IslandPlan } from './islands'
|
|
5
|
+
import { join, relative } from 'node:path'
|
|
6
|
+
import { islandKey } from './islands'
|
|
7
|
+
import { ancestorFiles, fileToRoutePath, MIDDLEWARE_NAMES } from './routes'
|
|
8
|
+
|
|
9
|
+
export interface ActionManifestEntry {
|
|
10
|
+
url: string
|
|
11
|
+
file: string
|
|
12
|
+
exportName: string
|
|
13
|
+
/** `_middleware.ts` chain of the folder declaring the action, outermost first. */
|
|
14
|
+
middlewares: string[]
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface RouteManifestEntry {
|
|
18
|
+
path: string
|
|
19
|
+
file: string
|
|
20
|
+
layouts: string[]
|
|
21
|
+
middlewares: string[]
|
|
22
|
+
hasLoad?: boolean | undefined
|
|
23
|
+
isIsland?: boolean | undefined
|
|
24
|
+
islandChunk?: string | undefined
|
|
25
|
+
islandHydrate?: string | undefined
|
|
26
|
+
/** Top-level keys of `load()` data statically read by a page island (`undefined` when `data` escapes). */
|
|
27
|
+
islandDataKeys?: string[] | undefined
|
|
28
|
+
islandChunks: string[]
|
|
29
|
+
eagerIslandChunks?: string[] | undefined
|
|
30
|
+
/** Per-route stylesheets (global plugin styles + CSS imported by this route, its layouts, and its islands). */
|
|
31
|
+
styles?: string[] | undefined
|
|
32
|
+
/** Per-route raw <head> HTML tags injected by plugins via `ctx.addRouteHead()`. */
|
|
33
|
+
headTags?: string[] | undefined
|
|
34
|
+
usesRenderContext?: boolean | undefined
|
|
35
|
+
prerender?: boolean | undefined
|
|
36
|
+
prerendered?: Record<string, string> | undefined
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface BuildManifest {
|
|
40
|
+
runtimeScript: string | undefined
|
|
41
|
+
styles: string[]
|
|
42
|
+
/** Stylesheets applied globally (plugin CSS, ctx.addStyle, and root layout CSS) — used by _error/_404. */
|
|
43
|
+
globalStyles?: string[] | undefined
|
|
44
|
+
headTags?: string[] | undefined
|
|
45
|
+
routes: RouteManifestEntry[]
|
|
46
|
+
errorFile?: string | undefined
|
|
47
|
+
notFoundFile?: string | undefined
|
|
48
|
+
actions: ActionManifestEntry[]
|
|
49
|
+
islands: Record<string, string>
|
|
50
|
+
assets: string[]
|
|
51
|
+
publicFiles: string[]
|
|
52
|
+
/** Serializable build-time metadata persisted by plugins via `ctx.setData()`, read via `api.getBuildData()`. */
|
|
53
|
+
pluginData?: Record<string, Record<string, unknown>> | undefined
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface FileReach {
|
|
57
|
+
/** Island chunks reachable from the file, and the subset loaded eagerly. */
|
|
58
|
+
chunks: Set<string>
|
|
59
|
+
eager: Set<string>
|
|
60
|
+
styles: Set<string>
|
|
61
|
+
usesRenderContext: boolean
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Walks what a module renders and imports to find the island chunks, stylesheets and render-context use behind it. */
|
|
65
|
+
function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks: Map<string, string>, srcCssToUrl: Map<string, string>, islandCssUrl: Map<string, string>) {
|
|
66
|
+
const { analyses } = graph
|
|
67
|
+
|
|
68
|
+
function walkIslands(file: string, seen: Set<string>, reach: FileReach): void {
|
|
69
|
+
if (seen.has(file))
|
|
70
|
+
return
|
|
71
|
+
seen.add(file)
|
|
72
|
+
const analysis = analyses.get(file)
|
|
73
|
+
if (analysis === undefined)
|
|
74
|
+
return
|
|
75
|
+
if (analysis.isInteractive) {
|
|
76
|
+
const chunk = islandChunks.get(`${file}#default`)
|
|
77
|
+
if (chunk !== undefined) {
|
|
78
|
+
reach.chunks.add(chunk)
|
|
79
|
+
if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
|
|
80
|
+
reach.eager.add(chunk)
|
|
81
|
+
}
|
|
82
|
+
return
|
|
83
|
+
}
|
|
84
|
+
for (const [localName, target] of islands.pageBindings.get(file) ?? []) {
|
|
85
|
+
const chunk = islandChunks.get(islandKey(target))
|
|
86
|
+
if (chunk === undefined)
|
|
87
|
+
continue
|
|
88
|
+
reach.chunks.add(chunk)
|
|
89
|
+
const isDeferred = analysis.deferredIslandTags.has(localName)
|
|
90
|
+
|| (target.defaultHydrate !== undefined && target.defaultHydrate !== 'load')
|
|
91
|
+
if (!isDeferred)
|
|
92
|
+
reach.eager.add(chunk)
|
|
93
|
+
}
|
|
94
|
+
for (const dep of graph.localDeps(file))
|
|
95
|
+
walkIslands(dep, seen, reach)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function walkStyles(file: string, seen: Set<string>, out: Set<string>): void {
|
|
99
|
+
if (seen.has(file))
|
|
100
|
+
return
|
|
101
|
+
seen.add(file)
|
|
102
|
+
const analysis = analyses.get(file)
|
|
103
|
+
if (analysis === undefined)
|
|
104
|
+
return
|
|
105
|
+
if (analysis.isInteractive) {
|
|
106
|
+
const islCss = islandCssUrl.get(`${file}#default`)
|
|
107
|
+
if (islCss !== undefined)
|
|
108
|
+
out.add(islCss)
|
|
109
|
+
}
|
|
110
|
+
for (const target of islands.pageBindings.get(file)?.values() ?? []) {
|
|
111
|
+
const islCss = islandCssUrl.get(islandKey(target))
|
|
112
|
+
if (islCss !== undefined)
|
|
113
|
+
out.add(islCss)
|
|
114
|
+
walkStyles(target.file, seen, out)
|
|
115
|
+
}
|
|
116
|
+
for (const imp of analysis.imports) {
|
|
117
|
+
const cssUrl = srcCssToUrl.get(graph.resolve(file, imp.source) ?? '')
|
|
118
|
+
if (cssUrl !== undefined)
|
|
119
|
+
out.add(cssUrl)
|
|
120
|
+
}
|
|
121
|
+
for (const dep of graph.localDeps(file))
|
|
122
|
+
walkStyles(dep, seen, out)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function walkRenderContext(file: string, seen: Set<string>): boolean {
|
|
126
|
+
if (seen.has(file))
|
|
127
|
+
return false
|
|
128
|
+
seen.add(file)
|
|
129
|
+
const analysis = analyses.get(file)
|
|
130
|
+
if (analysis === undefined)
|
|
131
|
+
return false
|
|
132
|
+
return analysis.usesRenderContext || graph.localDeps(file).some(dep => walkRenderContext(dep, seen))
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Layouts are shared by many routes, so each file is walked once.
|
|
136
|
+
const memo = new Map<string, FileReach>()
|
|
137
|
+
return (file: string): FileReach => {
|
|
138
|
+
let reach = memo.get(file)
|
|
139
|
+
if (reach === undefined) {
|
|
140
|
+
reach = { chunks: new Set(), eager: new Set(), styles: new Set(), usesRenderContext: false }
|
|
141
|
+
walkIslands(file, new Set(), reach)
|
|
142
|
+
walkStyles(file, new Set(), reach.styles)
|
|
143
|
+
reach.usesRenderContext = walkRenderContext(file, new Set())
|
|
144
|
+
memo.set(file, reach)
|
|
145
|
+
}
|
|
146
|
+
return reach
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface RouteEntries {
|
|
151
|
+
routes: RouteManifestEntry[]
|
|
152
|
+
/** Stylesheets of every page: the plugins' CSS, then the root layout's. */
|
|
153
|
+
globalStyles: string[]
|
|
154
|
+
/** The plugins' CSS alone. */
|
|
155
|
+
globalPluginStyles: string[]
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function buildRouteEntries(options: {
|
|
159
|
+
graph: ModuleGraph
|
|
160
|
+
islands: IslandPlan
|
|
161
|
+
islandChunks: Map<string, string>
|
|
162
|
+
srcCssToUrl: Map<string, string>
|
|
163
|
+
islandCssUrl: Map<string, string>
|
|
164
|
+
routesDir: string
|
|
165
|
+
pageFiles: string[]
|
|
166
|
+
pluginCssFiles: string[]
|
|
167
|
+
isStatic: boolean
|
|
168
|
+
/** Maps a source file to its compiled module, relative to the out dir. */
|
|
169
|
+
toOutRel: (srcFile: string) => string
|
|
170
|
+
}): RouteEntries {
|
|
171
|
+
const { graph, islands, islandChunks, routesDir, toOutRel } = options
|
|
172
|
+
const reachOf = createReachWalker(graph, islands, islandChunks, options.srcCssToUrl, options.islandCssUrl)
|
|
173
|
+
|
|
174
|
+
const globalPluginStyles = [...new Set(options.pluginCssFiles.map(css => options.srcCssToUrl.get(css)).filter((url): url is string => url !== undefined))]
|
|
175
|
+
const rootLayout = join(routesDir, '_layout.tsx')
|
|
176
|
+
const globalStyles = [...new Set([...globalPluginStyles, ...(graph.analyses.has(rootLayout) ? reachOf(rootLayout).styles : [])])]
|
|
177
|
+
|
|
178
|
+
const routes = options.pageFiles.map((file): RouteManifestEntry => {
|
|
179
|
+
const analysis = graph.analyses.get(file)
|
|
180
|
+
const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
|
|
181
|
+
const chunks = new Set<string>()
|
|
182
|
+
const eagerChunks = new Set<string>()
|
|
183
|
+
const styles = new Set<string>(globalPluginStyles)
|
|
184
|
+
let usesRenderContext = false
|
|
185
|
+
for (const src of [...layoutSrcs, file]) {
|
|
186
|
+
const reach = reachOf(src)
|
|
187
|
+
for (const chunk of reach.chunks)
|
|
188
|
+
chunks.add(chunk)
|
|
189
|
+
for (const chunk of reach.eager)
|
|
190
|
+
eagerChunks.add(chunk)
|
|
191
|
+
for (const style of reach.styles)
|
|
192
|
+
styles.add(style)
|
|
193
|
+
usesRenderContext ||= reach.usesRenderContext
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
path: fileToRoutePath(routesDir, file),
|
|
197
|
+
file: toOutRel(file),
|
|
198
|
+
layouts: layoutSrcs.map(toOutRel),
|
|
199
|
+
middlewares: ancestorFiles(routesDir, file, MIDDLEWARE_NAMES).map(toOutRel),
|
|
200
|
+
hasLoad: analysis?.hasLoadExport,
|
|
201
|
+
isIsland: analysis?.isInteractive,
|
|
202
|
+
islandChunk: islandChunks.get(`${file}#default`),
|
|
203
|
+
islandHydrate: analysis?.defaultHydrate,
|
|
204
|
+
islandDataKeys: analysis?.isInteractive && analysis.hasLoadExport ? analysis.defaultDataKeys : undefined,
|
|
205
|
+
islandChunks: [...chunks],
|
|
206
|
+
eagerIslandChunks: [...eagerChunks],
|
|
207
|
+
styles: [...styles],
|
|
208
|
+
usesRenderContext,
|
|
209
|
+
prerender: analysis?.hasPrerender || options.isStatic,
|
|
210
|
+
}
|
|
211
|
+
})
|
|
212
|
+
return { routes, globalStyles, globalPluginStyles }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export function buildActionEntries(actionsByFile: Map<string, { exportName: string, url: string }[]>, routesDir: string, toOutRel: (srcFile: string) => string): ActionManifestEntry[] {
|
|
216
|
+
const entries: ActionManifestEntry[] = []
|
|
217
|
+
for (const [srcFile, list] of actionsByFile) {
|
|
218
|
+
const inRoutes = !relative(routesDir, srcFile).startsWith('..')
|
|
219
|
+
const middlewares = inRoutes ? ancestorFiles(routesDir, srcFile, MIDDLEWARE_NAMES).map(toOutRel) : []
|
|
220
|
+
for (const a of list)
|
|
221
|
+
entries.push({ url: a.url, file: toOutRel(srcFile), exportName: a.exportName, middlewares })
|
|
222
|
+
}
|
|
223
|
+
return entries
|
|
224
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// What plugins see of a build: the `build(ctx)` and `afterPrerender(ctx)` hooks, and the shared lists (assets, styles, head tags, public files) those hooks add to.
|
|
2
|
+
|
|
3
|
+
import type { AppRuntimeContext } from '../plugins/context'
|
|
4
|
+
import type { BuildPluginContext, FinalizeBuildContext, KayPlugin } from '../plugins/index'
|
|
5
|
+
import type { RouteManifestEntry } from './manifest'
|
|
6
|
+
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { dirname, join } from 'node:path'
|
|
8
|
+
import { precompressFile } from './files'
|
|
9
|
+
|
|
10
|
+
const LEADING_SLASHES_RE = /^\/+/
|
|
11
|
+
const BACKSLASH_RE = /\\/g
|
|
12
|
+
|
|
13
|
+
function cleanRel(relPath: string): string {
|
|
14
|
+
return relPath.replace(LEADING_SLASHES_RE, '').replace(BACKSLASH_RE, '/')
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface PublicFiles {
|
|
18
|
+
/** Public files known so far, as relative paths in registration order. */
|
|
19
|
+
files: string[]
|
|
20
|
+
/** Records a public file and returns its normalized relative path. */
|
|
21
|
+
register: (relPath: string) => string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function createPublicFiles(): PublicFiles {
|
|
25
|
+
const files: string[] = []
|
|
26
|
+
const seen = new Set<string>()
|
|
27
|
+
return {
|
|
28
|
+
files,
|
|
29
|
+
register(relPath) {
|
|
30
|
+
const clean = cleanRel(relPath)
|
|
31
|
+
if (clean !== '' && !seen.has(clean)) {
|
|
32
|
+
seen.add(clean)
|
|
33
|
+
files.push(clean)
|
|
34
|
+
}
|
|
35
|
+
return clean
|
|
36
|
+
},
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface PluginHostOptions {
|
|
41
|
+
plugins: KayPlugin[]
|
|
42
|
+
appCtx: AppRuntimeContext
|
|
43
|
+
root: string
|
|
44
|
+
outDir: string
|
|
45
|
+
clientDir: string
|
|
46
|
+
outPublicDir: string
|
|
47
|
+
assetPrefix: string
|
|
48
|
+
minify: boolean
|
|
49
|
+
isStatic: boolean
|
|
50
|
+
isDev: boolean
|
|
51
|
+
routes: RouteManifestEntry[]
|
|
52
|
+
publicFiles: PublicFiles
|
|
53
|
+
/** Client files already emitted, relative to the client dir. */
|
|
54
|
+
assets: string[]
|
|
55
|
+
styleUrls: string[]
|
|
56
|
+
globalStyles: string[]
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function createPluginHost(options: PluginHostOptions) {
|
|
60
|
+
const { plugins, appCtx, outDir, clientDir, outPublicDir, assetPrefix, routes, assets, styleUrls, globalStyles } = options
|
|
61
|
+
const assetSet = new Set(assets)
|
|
62
|
+
const styleSet = new Set(styleUrls)
|
|
63
|
+
const globalStyleSet = new Set(globalStyles)
|
|
64
|
+
const headTags: string[] = []
|
|
65
|
+
const pluginData: Record<string, Record<string, unknown>> = {}
|
|
66
|
+
const precompressed = new Set<string>()
|
|
67
|
+
|
|
68
|
+
function emitAsset(relPath: string, content: string | Uint8Array): string {
|
|
69
|
+
const clean = cleanRel(relPath)
|
|
70
|
+
const dst = join(clientDir, clean)
|
|
71
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
72
|
+
writeFileSync(dst, content)
|
|
73
|
+
if (!assetSet.has(clean)) {
|
|
74
|
+
assetSet.add(clean)
|
|
75
|
+
assets.push(clean)
|
|
76
|
+
}
|
|
77
|
+
return `${assetPrefix}/${clean}`
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function emitPublic(relPath: string, content: string | Uint8Array): string {
|
|
81
|
+
const clean = options.publicFiles.register(relPath)
|
|
82
|
+
const dst = join(outPublicDir, clean)
|
|
83
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
84
|
+
writeFileSync(dst, content)
|
|
85
|
+
return `/${clean}`
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function addStyleUrl(href: string): void {
|
|
89
|
+
if (!styleSet.has(href)) {
|
|
90
|
+
styleSet.add(href)
|
|
91
|
+
styleUrls.push(href)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const setDataFor = (pluginName: string) => (data: Record<string, unknown>): void => {
|
|
96
|
+
pluginData[pluginName] = { ...pluginData[pluginName], ...data }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const shared = {
|
|
100
|
+
root: options.root,
|
|
101
|
+
outDir,
|
|
102
|
+
assetPrefix,
|
|
103
|
+
minify: options.minify,
|
|
104
|
+
isStatic: options.isStatic,
|
|
105
|
+
dev: options.isDev,
|
|
106
|
+
routes,
|
|
107
|
+
emitAsset,
|
|
108
|
+
emitPublic,
|
|
109
|
+
provide: appCtx.provide,
|
|
110
|
+
inject: appCtx.inject,
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const buildCtx = {
|
|
114
|
+
...shared,
|
|
115
|
+
addStyle(href: string) {
|
|
116
|
+
addStyleUrl(href)
|
|
117
|
+
if (!globalStyleSet.has(href)) {
|
|
118
|
+
globalStyleSet.add(href)
|
|
119
|
+
globalStyles.push(href)
|
|
120
|
+
}
|
|
121
|
+
for (const r of routes) {
|
|
122
|
+
if (r.styles !== undefined && !r.styles.includes(href))
|
|
123
|
+
r.styles.push(href)
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
addRouteStyle(routePath: string, href: string) {
|
|
127
|
+
addStyleUrl(href)
|
|
128
|
+
const route = routes.find(r => r.path === routePath)
|
|
129
|
+
if (route !== undefined) {
|
|
130
|
+
route.styles ??= [...globalStyles]
|
|
131
|
+
if (!route.styles.includes(href))
|
|
132
|
+
route.styles.push(href)
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
addHead(html: string) {
|
|
136
|
+
if (html !== '')
|
|
137
|
+
headTags.push(html)
|
|
138
|
+
},
|
|
139
|
+
addRouteHead(routePath: string, html: string) {
|
|
140
|
+
const route = html === '' ? undefined : routes.find(r => r.path === routePath)
|
|
141
|
+
if (route !== undefined)
|
|
142
|
+
(route.headTags ??= []).push(html)
|
|
143
|
+
},
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
headTags,
|
|
148
|
+
pluginData,
|
|
149
|
+
/** Runs every plugin's `build(ctx)`, so plugins can emit hashed assets, public files, styles, <head> tags, or services. */
|
|
150
|
+
async runBuild(): Promise<void> {
|
|
151
|
+
for (const plugin of plugins) {
|
|
152
|
+
if (plugin.build !== undefined) {
|
|
153
|
+
const ctx: BuildPluginContext = { ...buildCtx, setData: setDataFor(plugin.name) }
|
|
154
|
+
await plugin.build(ctx)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
|
|
159
|
+
/** Runs every plugin's `afterPrerender(ctx)`, once `route.prerendered` and prerender-emitted public files are known. */
|
|
160
|
+
async runAfterPrerender(): Promise<boolean> {
|
|
161
|
+
let ran = false
|
|
162
|
+
for (const plugin of plugins) {
|
|
163
|
+
if (plugin.afterPrerender !== undefined) {
|
|
164
|
+
ran = true
|
|
165
|
+
const ctx: FinalizeBuildContext = { ...shared, publicFiles: options.publicFiles.files, setData: setDataFor(plugin.name) }
|
|
166
|
+
await plugin.afterPrerender(ctx)
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return ran
|
|
170
|
+
},
|
|
171
|
+
|
|
172
|
+
/** Writes `.br`/`.gz` sidecars for client assets not compressed yet (production server builds only: `--static` compresses its own output). */
|
|
173
|
+
precompressAssets(): void {
|
|
174
|
+
if (options.isDev || options.isStatic)
|
|
175
|
+
return
|
|
176
|
+
for (const rel of assets) {
|
|
177
|
+
if (!precompressed.has(rel)) {
|
|
178
|
+
precompressed.add(rel)
|
|
179
|
+
precompressFile(join(clientDir, rel), 256)
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
}
|
|
184
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Build-time rendering: routes exporting `prerender = true` (and every route in a static export) are rendered through the real server and written as HTML.
|
|
2
|
+
|
|
3
|
+
import type { KayPlugin } from '../plugins/index'
|
|
4
|
+
import type { RouteManifestEntry } from './manifest'
|
|
5
|
+
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
6
|
+
import { dirname, join, resolve } from 'node:path'
|
|
7
|
+
import { relPosix } from './files'
|
|
8
|
+
import { assertPathUrls } from './routes'
|
|
9
|
+
|
|
10
|
+
const CONCURRENCY = 8
|
|
11
|
+
const SLASH_EDGES_RE = /^\/|\/$/g
|
|
12
|
+
|
|
13
|
+
let prerenderImportSeq = 0
|
|
14
|
+
|
|
15
|
+
function resolvePrerenderHtmlPath(prerenderDir: string, urlStr: string, isStatic: boolean): string {
|
|
16
|
+
const pathname = new URL(urlStr, 'http://localhost').pathname
|
|
17
|
+
const rel = pathname === '/'
|
|
18
|
+
? 'index.html'
|
|
19
|
+
: (isStatic && pathname === '/404')
|
|
20
|
+
? '404.html'
|
|
21
|
+
: `${pathname.replace(SLASH_EDGES_RE, '')}/index.html`
|
|
22
|
+
const absRoot = resolve(prerenderDir)
|
|
23
|
+
const abs = resolve(absRoot, rel)
|
|
24
|
+
if (!abs.startsWith(`${absRoot}/`) && !abs.startsWith(`${absRoot}\\`))
|
|
25
|
+
throw new Error(`kay build: prerender path "${urlStr}" escapes output directory.`)
|
|
26
|
+
return abs
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface PrerenderOptions {
|
|
30
|
+
root: string
|
|
31
|
+
outDir: string
|
|
32
|
+
assetPrefix: string
|
|
33
|
+
plugins: KayPlugin[]
|
|
34
|
+
isDev: boolean
|
|
35
|
+
isStatic: boolean
|
|
36
|
+
/** Where the HTML lands: the static stage dir, or `<outDir>/prerendered`. */
|
|
37
|
+
prerenderDir: string
|
|
38
|
+
routes: RouteManifestEntry[]
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Renders every route to HTML, records `route.prerendered`, and returns the server the pages were rendered with. */
|
|
42
|
+
export async function prerender(options: PrerenderOptions) {
|
|
43
|
+
const { root, outDir, prerenderDir, isStatic } = options
|
|
44
|
+
const { createServer } = await import('../server/index')
|
|
45
|
+
const app = await createServer({ root, outDir: relPosix(root, outDir), assetPrefix: options.assetPrefix, plugins: options.plugins, dev: options.isDev })
|
|
46
|
+
mkdirSync(prerenderDir, { recursive: true })
|
|
47
|
+
|
|
48
|
+
const stamp = `${Date.now()}-${++prerenderImportSeq}`
|
|
49
|
+
for (const route of options.routes) {
|
|
50
|
+
let urls: string[] = []
|
|
51
|
+
if (!route.path.includes(':') && !route.path.includes('*')) {
|
|
52
|
+
urls = [route.path]
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
const mod = await import(`${join(outDir, route.file)}?v=${stamp}`) as { paths?: () => Promise<string[]> | string[] }
|
|
56
|
+
if (typeof mod.paths === 'function') {
|
|
57
|
+
const returned: unknown = await mod.paths()
|
|
58
|
+
assertPathUrls(returned, route.file)
|
|
59
|
+
urls = returned
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
console.warn(`kay build${isStatic ? ' --static' : ''}: skipping dynamic route "${route.path}" (${route.file}) because it does not export a paths() function.`)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (urls.length === 0)
|
|
67
|
+
continue
|
|
68
|
+
|
|
69
|
+
for (const plugin of options.plugins) {
|
|
70
|
+
if (plugin.prerenderPaths !== undefined)
|
|
71
|
+
urls = await plugin.prerenderPaths(urls, route)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const map: Record<string, string> = {}
|
|
75
|
+
for (let i = 0; i < urls.length; i += CONCURRENCY) {
|
|
76
|
+
await Promise.all(urls.slice(i, i + CONCURRENCY).map(async (u) => {
|
|
77
|
+
const res = await app.handle(new Request(`http://localhost${u}`))
|
|
78
|
+
const isExplicit404 = u === '/404' && res.status === 404
|
|
79
|
+
if (res.status !== 200 && !isExplicit404) {
|
|
80
|
+
if (isStatic || res.status >= 500)
|
|
81
|
+
throw new Error(`kay build${isStatic ? ' --static' : ''}: prerender route "${u}" returned HTTP ${res.status} (expected 200).`)
|
|
82
|
+
return
|
|
83
|
+
}
|
|
84
|
+
const absHtml = resolvePrerenderHtmlPath(prerenderDir, u, isStatic)
|
|
85
|
+
mkdirSync(dirname(absHtml), { recursive: true })
|
|
86
|
+
writeFileSync(absHtml, await res.text())
|
|
87
|
+
map[u] = relPosix(isStatic ? prerenderDir : outDir, absHtml)
|
|
88
|
+
}))
|
|
89
|
+
}
|
|
90
|
+
route.prerendered = map
|
|
91
|
+
}
|
|
92
|
+
return app
|
|
93
|
+
}
|