@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.3
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 +617 -0
- package/src/build/compile.ts +27 -51
- package/src/build/files.ts +174 -0
- package/src/build/graph.ts +223 -0
- package/src/build/index.ts +272 -1466
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +229 -0
- package/src/build/plugin-host.ts +186 -0
- package/src/build/prerender.ts +102 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +51 -0
- package/src/build/routes.ts +163 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +300 -129
- package/src/cli/index.ts +297 -94
- package/src/cli/new.ts +58 -38
- package/src/compiler/analyze.ts +723 -93
- package/src/compiler/dom.ts +848 -762
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +172 -23
- package/src/compiler/shared.ts +485 -0
- package/src/compiler/ssr.ts +331 -342
- package/src/context.ts +120 -0
- package/src/dev/index.ts +339 -76
- package/src/dom/action.ts +114 -14
- package/src/dom/extras.ts +121 -83
- package/src/dom/index.ts +122 -80
- package/src/dom/island.ts +71 -36
- package/src/dom/loop.ts +28 -20
- package/src/index.ts +5 -1
- package/src/jsx-runtime.ts +432 -93
- package/src/plugins/config.ts +49 -0
- package/src/plugins/context.ts +61 -0
- package/src/plugins/index.ts +10 -123
- package/src/plugins/load.ts +38 -0
- package/src/plugins/order.ts +107 -0
- package/src/plugins/services.ts +23 -0
- package/src/plugins/types.ts +197 -0
- package/src/reactivity/index.ts +237 -213
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +36 -11
- package/src/server/action-registry.ts +72 -0
- package/src/server/action.ts +157 -79
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +182 -0
- package/src/server/compress.ts +197 -104
- package/src/server/cookies.ts +46 -16
- package/src/server/document.ts +192 -0
- package/src/server/env.ts +18 -13
- package/src/server/errors.ts +123 -0
- package/src/server/http.ts +203 -77
- package/src/server/index.ts +420 -973
- package/src/server/loader.ts +113 -0
- package/src/server/page.ts +107 -0
- package/src/server/plugin-host.ts +167 -0
- package/src/server/router.ts +69 -26
- package/src/server/security.ts +90 -59
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +163 -0
- package/src/server/stream.ts +94 -0
- package/src/ssr/context.ts +95 -10
- package/src/ssr/index.ts +167 -66
- package/src/style.ts +33 -0
- package/src/test/index.ts +24 -18
- package/src/unrenderable.ts +35 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// The `--analyze` report: eager JS and CSS weight per route, from the manifest and the client metafile.
|
|
2
|
+
|
|
3
|
+
import type { BuildManifest } from './manifest'
|
|
4
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
|
|
7
|
+
export interface RouteBundleMetrics {
|
|
8
|
+
path: string
|
|
9
|
+
jsRaw: number
|
|
10
|
+
jsGzip: number
|
|
11
|
+
cssRaw: number
|
|
12
|
+
cssGzip: number
|
|
13
|
+
jsFiles: number
|
|
14
|
+
cssFiles: number
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function analyzeBundleWeights(
|
|
18
|
+
manifest: BuildManifest,
|
|
19
|
+
clientDir: string,
|
|
20
|
+
assetPrefix = '/_kay',
|
|
21
|
+
metafile?: Bun.BuildOutput['metafile'],
|
|
22
|
+
): { routes: RouteBundleMetrics[], totalJsGzip: number, totalCssGzip: number, topModules: { path: string, bytes: number }[] } {
|
|
23
|
+
const prefix = `${assetPrefix.replace(/\/$/, '')}/`
|
|
24
|
+
const sizeCache = new Map<string, { raw: number, gzip: number }>()
|
|
25
|
+
|
|
26
|
+
const getSize = (url: string): { raw: number, gzip: number } => {
|
|
27
|
+
const cached = sizeCache.get(url)
|
|
28
|
+
if (cached !== undefined)
|
|
29
|
+
return cached
|
|
30
|
+
if (!url.startsWith(prefix))
|
|
31
|
+
return { raw: 0, gzip: 0 }
|
|
32
|
+
const abs = join(clientDir, url.slice(prefix.length))
|
|
33
|
+
if (!existsSync(abs))
|
|
34
|
+
return { raw: 0, gzip: 0 }
|
|
35
|
+
const buf = readFileSync(abs)
|
|
36
|
+
const entry = { raw: buf.byteLength, gzip: Bun.gzipSync(buf, { level: 9 }).byteLength }
|
|
37
|
+
sizeCache.set(url, entry)
|
|
38
|
+
return entry
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Collect transitive JS chunk imports from metafile so eager JS includes shared runtime chunks!
|
|
42
|
+
const jsDeps = new Map<string, string[]>()
|
|
43
|
+
const moduleBytes = new Map<string, number>()
|
|
44
|
+
if (metafile !== undefined) {
|
|
45
|
+
for (const [outKey, info] of Object.entries(metafile.outputs)) {
|
|
46
|
+
const rel = outKey.replace(/^\.\//, '')
|
|
47
|
+
const url = `${prefix}${rel}`
|
|
48
|
+
if (rel.endsWith('.js')) {
|
|
49
|
+
const deps: string[] = []
|
|
50
|
+
for (const imp of info.imports ?? []) {
|
|
51
|
+
if (imp.kind === 'import-statement')
|
|
52
|
+
deps.push(`${prefix}${imp.path.replace(/^\.\//, '')}`)
|
|
53
|
+
}
|
|
54
|
+
jsDeps.set(url, deps)
|
|
55
|
+
}
|
|
56
|
+
for (const [inPath, inInfo] of Object.entries(info.inputs ?? {}))
|
|
57
|
+
moduleBytes.set(inPath, (moduleBytes.get(inPath) ?? 0) + inInfo.bytesInOutput)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const collectTransitiveJs = (urls: readonly string[]): Set<string> => {
|
|
62
|
+
const seen = new Set<string>()
|
|
63
|
+
const stack = [...urls]
|
|
64
|
+
while (stack.length > 0) {
|
|
65
|
+
const cur = stack.pop()!
|
|
66
|
+
if (seen.has(cur))
|
|
67
|
+
continue
|
|
68
|
+
seen.add(cur)
|
|
69
|
+
for (const dep of jsDeps.get(cur) ?? [])
|
|
70
|
+
stack.push(dep)
|
|
71
|
+
}
|
|
72
|
+
return seen
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const routes: RouteBundleMetrics[] = manifest.routes.map((r) => {
|
|
76
|
+
const eagerJsRoots: string[] = []
|
|
77
|
+
if (r.islandChunks.length > 0 && manifest.runtimeScript !== undefined)
|
|
78
|
+
eagerJsRoots.push(manifest.runtimeScript)
|
|
79
|
+
for (const c of r.eagerIslandChunks ?? r.islandChunks)
|
|
80
|
+
eagerJsRoots.push(c)
|
|
81
|
+
|
|
82
|
+
const jsSet = collectTransitiveJs(eagerJsRoots)
|
|
83
|
+
let jsRaw = 0
|
|
84
|
+
let jsGzip = 0
|
|
85
|
+
for (const u of jsSet) {
|
|
86
|
+
const s = getSize(u)
|
|
87
|
+
jsRaw += s.raw
|
|
88
|
+
jsGzip += s.gzip
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const cssList = r.styles ?? manifest.styles
|
|
92
|
+
let cssRaw = 0
|
|
93
|
+
let cssGzip = 0
|
|
94
|
+
for (const u of cssList) {
|
|
95
|
+
const s = getSize(u)
|
|
96
|
+
cssRaw += s.raw
|
|
97
|
+
cssGzip += s.gzip
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return {
|
|
101
|
+
path: r.path,
|
|
102
|
+
jsRaw,
|
|
103
|
+
jsGzip,
|
|
104
|
+
cssRaw,
|
|
105
|
+
cssGzip,
|
|
106
|
+
jsFiles: jsSet.size,
|
|
107
|
+
cssFiles: cssList.length,
|
|
108
|
+
}
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
let totalJsGzip = 0
|
|
112
|
+
let totalCssGzip = 0
|
|
113
|
+
for (const rel of manifest.assets) {
|
|
114
|
+
const s = getSize(`${prefix}${rel}`)
|
|
115
|
+
if (rel.endsWith('.js'))
|
|
116
|
+
totalJsGzip += s.gzip
|
|
117
|
+
else if (rel.endsWith('.css'))
|
|
118
|
+
totalCssGzip += s.gzip
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const topModules = [...moduleBytes.entries()]
|
|
122
|
+
.map(([path, bytes]) => ({ path, bytes }))
|
|
123
|
+
.sort((a, b) => b.bytes - a.bytes)
|
|
124
|
+
.slice(0, 10)
|
|
125
|
+
|
|
126
|
+
return { routes, totalJsGzip, totalCssGzip, topModules }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function formatBundleReport(
|
|
130
|
+
manifest: BuildManifest,
|
|
131
|
+
clientDir: string,
|
|
132
|
+
assetPrefix = '/_kay',
|
|
133
|
+
metafile?: Bun.BuildOutput['metafile'],
|
|
134
|
+
): string {
|
|
135
|
+
const report = analyzeBundleWeights(manifest, clientDir, assetPrefix, metafile)
|
|
136
|
+
const kb = (b: number) => `${(b / 1024).toFixed(2)} KB`
|
|
137
|
+
const lines = [
|
|
138
|
+
'\n=== KAY BUNDLE WEIGHT REPORT ===',
|
|
139
|
+
`Total emitted: JS ${kb(report.totalJsGzip)} gz | CSS ${kb(report.totalCssGzip)} gz`,
|
|
140
|
+
'',
|
|
141
|
+
'Route'.padEnd(28) + 'Eager JS (gz)'.padStart(16) + 'CSS (gz)'.padStart(14) + 'Files'.padStart(10),
|
|
142
|
+
]
|
|
143
|
+
for (const r of report.routes) {
|
|
144
|
+
lines.push(
|
|
145
|
+
r.path.padEnd(28)
|
|
146
|
+
+ kb(r.jsGzip).padStart(16)
|
|
147
|
+
+ kb(r.cssGzip).padStart(14)
|
|
148
|
+
+ `${r.jsFiles}j/${r.cssFiles}c`.padStart(10),
|
|
149
|
+
)
|
|
150
|
+
}
|
|
151
|
+
if (report.topModules.length > 0) {
|
|
152
|
+
lines.push('', 'Top modules (minified output bytes):')
|
|
153
|
+
for (const m of report.topModules.slice(0, 8))
|
|
154
|
+
lines.push(` ${kb(m.bytes).padStart(9)} ${m.path}`)
|
|
155
|
+
}
|
|
156
|
+
return lines.join('\n')
|
|
157
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Resolves an import the way kay build follows it: relative files, then packages through Bun's resolver; kay, node:, bun and ~ aliases stay unresolved.
|
|
2
|
+
|
|
3
|
+
import { statSync } from 'node:fs'
|
|
4
|
+
import { dirname, join, resolve } from 'node:path'
|
|
5
|
+
import pkg from '../../package.json' with { type: 'json' }
|
|
6
|
+
|
|
7
|
+
export const KAY_SRC_ROOT = resolve(import.meta.dir, '..')
|
|
8
|
+
|
|
9
|
+
export function resolveImportPath(fromFile: string, specifier: string): string | undefined {
|
|
10
|
+
if (specifier.startsWith('.')) {
|
|
11
|
+
const base = resolve(dirname(fromFile), specifier)
|
|
12
|
+
const candidates = [base, `${base}.tsx`, `${base}.ts`, join(base, 'index.tsx'), join(base, 'index.ts')]
|
|
13
|
+
for (const c of candidates) {
|
|
14
|
+
if (statSync(c, { throwIfNoEntry: false })?.isFile())
|
|
15
|
+
return c
|
|
16
|
+
}
|
|
17
|
+
return undefined
|
|
18
|
+
}
|
|
19
|
+
if (
|
|
20
|
+
specifier === 'kay'
|
|
21
|
+
|| specifier.startsWith('kay/')
|
|
22
|
+
|| specifier === '@kayjs/kay'
|
|
23
|
+
|| specifier.startsWith('@kayjs/kay/')
|
|
24
|
+
|| specifier.startsWith('node:')
|
|
25
|
+
|| specifier === 'bun'
|
|
26
|
+
|| specifier.startsWith('bun:')
|
|
27
|
+
|| specifier.startsWith('~')
|
|
28
|
+
) {
|
|
29
|
+
return undefined
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
const resolved = Bun.resolveSync(specifier, dirname(fromFile))
|
|
33
|
+
return resolved.endsWith('.tsx') || resolved.endsWith('.ts') ? resolved : undefined
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return undefined
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const KAY_SPECIFIER_FILES = new Map<string, string>(
|
|
41
|
+
Object.entries(pkg.exports as Record<string, string>).map(([subpath, target]) => [
|
|
42
|
+
subpath === '.' ? 'kay' : `kay/${subpath.slice(2)}`,
|
|
43
|
+
target.replace(/^\.\/src\//, ''),
|
|
44
|
+
]),
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
/** Maps `kay`, `kay/<subpath>` and the `@kayjs/kay` spelling of both to their source file. */
|
|
48
|
+
export function resolveKaySpecifier(specifier: string): string | undefined {
|
|
49
|
+
const file = KAY_SPECIFIER_FILES.get(specifier.startsWith('@kayjs/') ? specifier.slice('@kayjs/'.length) : specifier)
|
|
50
|
+
return file === undefined ? undefined : join(KAY_SRC_ROOT, file)
|
|
51
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// Route files: their URL patterns, conflicts, and the `_layout`/`_middleware` chain that wraps them.
|
|
2
|
+
|
|
3
|
+
import type { ModuleAnalysis } from '../compiler/index'
|
|
4
|
+
import { existsSync } from 'node:fs'
|
|
5
|
+
import { dirname, join, relative } from 'node:path'
|
|
6
|
+
import { relPosix } from './files'
|
|
7
|
+
|
|
8
|
+
export const SPECIAL_ROUTE_FILES = new Set(['_layout.tsx', '_middleware.ts', '_middleware.tsx', '_error.tsx', '_404.tsx'])
|
|
9
|
+
export const MIDDLEWARE_NAMES = ['_middleware.ts', '_middleware.tsx']
|
|
10
|
+
const ROUTE_EXPORTS = new Set(['default', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])
|
|
11
|
+
const TS_EXT_RE = /\.(?:tsx|ts)$/
|
|
12
|
+
const CATCH_ALL_RE = /\[\.\.\.([^\]]+)\]/g
|
|
13
|
+
const PARAM_RE = /\[([^\]]+)\]/g
|
|
14
|
+
const PATH_SEPARATOR_RE = /[/\\]/
|
|
15
|
+
|
|
16
|
+
interface ExportSpecifierNode {
|
|
17
|
+
type: string
|
|
18
|
+
exportKind?: string
|
|
19
|
+
specifiers?: { exportKind?: string, exported?: { name?: string, value?: string } }[]
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A file in routes/ is a route when it exports a default component or an HTTP method handler, directly or through `export { ... }`. */
|
|
23
|
+
export function hasRouteHandlerExport(analysis: ModuleAnalysis): boolean {
|
|
24
|
+
for (const name of analysis.exportedNames) {
|
|
25
|
+
if (ROUTE_EXPORTS.has(name))
|
|
26
|
+
return true
|
|
27
|
+
}
|
|
28
|
+
for (const stmt of analysis.program.body as ExportSpecifierNode[]) {
|
|
29
|
+
if (stmt.type !== 'ExportNamedDeclaration' || stmt.exportKind === 'type' || stmt.specifiers === undefined)
|
|
30
|
+
continue
|
|
31
|
+
for (const spec of stmt.specifiers) {
|
|
32
|
+
const exported = spec.exportKind === 'type' ? undefined : spec.exported?.name ?? spec.exported?.value
|
|
33
|
+
if (exported !== undefined && ROUTE_EXPORTS.has(exported))
|
|
34
|
+
return true
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return false
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const LOAD_FIX = 'kay never calls it; export async function load() and read its data with the page\'s load prop'
|
|
41
|
+
const PATHS_FIX = 'kay never calls it; export function paths() returning URL strings such as "/posts/a"'
|
|
42
|
+
const HEAD_FIX = 'kay never reads it; render <Head> in the page'
|
|
43
|
+
// Exports other frameworks read from a route file, and what kay wants instead.
|
|
44
|
+
const FOREIGN_ROUTE_EXPORTS = new Map([
|
|
45
|
+
['getStaticProps', LOAD_FIX],
|
|
46
|
+
['getServerSideProps', LOAD_FIX],
|
|
47
|
+
['getInitialProps', LOAD_FIX],
|
|
48
|
+
['loader', LOAD_FIX],
|
|
49
|
+
['clientLoader', LOAD_FIX],
|
|
50
|
+
['getStaticPaths', PATHS_FIX],
|
|
51
|
+
['generateStaticParams', PATHS_FIX],
|
|
52
|
+
['metadata', HEAD_FIX],
|
|
53
|
+
['generateMetadata', HEAD_FIX],
|
|
54
|
+
['meta', HEAD_FIX],
|
|
55
|
+
...['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'all'].map(m => [m, `kay never calls it; export function ${m === 'all' ? 'GET(), POST() or another method' : `${m.toUpperCase()}()`}`] as const),
|
|
56
|
+
])
|
|
57
|
+
|
|
58
|
+
function findExportOffset(analysis: ModuleAnalysis, exportName: string): number {
|
|
59
|
+
for (const stmt of analysis.program.body) {
|
|
60
|
+
if (stmt.type !== 'ExportNamedDeclaration')
|
|
61
|
+
continue
|
|
62
|
+
if (stmt.declaration?.type === 'FunctionDeclaration' && stmt.declaration.id?.name === exportName)
|
|
63
|
+
return stmt.start
|
|
64
|
+
if (stmt.declaration?.type === 'ClassDeclaration' && stmt.declaration.id?.name === exportName)
|
|
65
|
+
return stmt.start
|
|
66
|
+
if (stmt.declaration?.type === 'VariableDeclaration') {
|
|
67
|
+
for (const d of stmt.declaration.declarations) {
|
|
68
|
+
if (d.id.type === 'Identifier' && d.id.name === exportName)
|
|
69
|
+
return d.start
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const spec of stmt.specifiers) {
|
|
73
|
+
const exp = spec.exported.type === 'Identifier' ? spec.exported.name : spec.exported.value
|
|
74
|
+
if (exp === exportName)
|
|
75
|
+
return spec.start
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return 0
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Returns the first route export problem together with its byte offset in the module source. */
|
|
82
|
+
export function routeExportProblemLocation(analysis: ModuleAnalysis, file: string): { message: string, offset: number } | undefined {
|
|
83
|
+
for (const name of analysis.exportedNames) {
|
|
84
|
+
const fix = FOREIGN_ROUTE_EXPORTS.get(name)
|
|
85
|
+
if (fix !== undefined)
|
|
86
|
+
return { message: `export ${name} in ${file}: ${fix}.`, offset: findExportOffset(analysis, name) }
|
|
87
|
+
}
|
|
88
|
+
for (const stmt of analysis.program.body) {
|
|
89
|
+
if (stmt.type !== 'ExportNamedDeclaration' || stmt.declaration?.type !== 'VariableDeclaration')
|
|
90
|
+
continue
|
|
91
|
+
for (const d of stmt.declaration.declarations) {
|
|
92
|
+
const name = d.id.type === 'Identifier' ? d.id.name : undefined
|
|
93
|
+
const init = d.init
|
|
94
|
+
if (name === 'paths' && init !== null && init.type !== 'ArrowFunctionExpression' && init.type !== 'FunctionExpression')
|
|
95
|
+
return { message: `export const paths in ${file}: export function paths() returning the URLs, such as () => ['/posts/a'].`, offset: d.start }
|
|
96
|
+
if (name === 'prerender' && !(init?.type === 'Literal' && typeof init.value === 'boolean'))
|
|
97
|
+
return { message: `${init?.type === 'Literal' ? `prerender = ${init.raw ?? String(init.value)}` : 'prerender set at runtime'} in ${file}: write prerender = true or prerender = false.`, offset: d.start }
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return undefined
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The first route export kay never reads (Next, Remix and Astro names), `paths` that is not a function, or `prerender` that is not literally `true` or `false`, worded for `kay build` and `kay check` to prefix. */
|
|
104
|
+
export function routeExportProblem(analysis: ModuleAnalysis, file: string): string | undefined {
|
|
105
|
+
return routeExportProblemLocation(analysis, file)?.message
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Throws unless a route's `paths()` gave an array of URL paths starting with `/`. */
|
|
109
|
+
export function assertPathUrls(urls: unknown, file: string): asserts urls is string[] {
|
|
110
|
+
if (!Array.isArray(urls))
|
|
111
|
+
throw new Error(`kay build: paths() in ${file} returned ${JSON.stringify(urls)}: return an array of URL paths such as ["/posts/a"].`)
|
|
112
|
+
for (const url of urls) {
|
|
113
|
+
if (typeof url !== 'string' || !url.startsWith('/'))
|
|
114
|
+
throw new Error(`kay build: paths() in ${file} returned ${JSON.stringify(url)}: return URL paths such as "/posts/a".`)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function fileToRoutePath(routesDir: string, file: string): string {
|
|
119
|
+
const rel = relPosix(routesDir, file).replace(TS_EXT_RE, '')
|
|
120
|
+
if (rel === 'index')
|
|
121
|
+
return '/'
|
|
122
|
+
const clean = rel.endsWith('/index') ? rel.slice(0, -'/index'.length) : rel
|
|
123
|
+
return `/${clean.replace(CATCH_ALL_RE, '*$1').replace(PARAM_RE, ':$1')}`
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The shape two route paths conflict on: parameter names do not matter. */
|
|
127
|
+
export function normalizeRoutePattern(routePath: string): string {
|
|
128
|
+
return routePath
|
|
129
|
+
.split('/')
|
|
130
|
+
.map(seg => (seg.startsWith(':') ? ':' : seg.startsWith('*') ? '*' : seg))
|
|
131
|
+
.join('/')
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Throws on two route files that serve one pattern (about.tsx vs about/index.tsx, [id].tsx vs [slug].tsx). */
|
|
135
|
+
export function assertNoRouteConflicts(root: string, routesDir: string, pageFiles: string[]): void {
|
|
136
|
+
const seen = new Map<string, { file: string, path: string }>()
|
|
137
|
+
for (const file of pageFiles) {
|
|
138
|
+
const routePath = fileToRoutePath(routesDir, file)
|
|
139
|
+
const normalized = normalizeRoutePattern(routePath)
|
|
140
|
+
const existing = seen.get(normalized)
|
|
141
|
+
if (existing !== undefined)
|
|
142
|
+
throw new Error(`kay build: conflicting routes for pattern "${routePath}": "${relPosix(root, existing.file)}" (${existing.path}) and "${relPosix(root, file)}" (${routePath})`)
|
|
143
|
+
seen.set(normalized, { file, path: routePath })
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Finds all ancestor files named one of `names` from routesDir down to dirname(routeFile), outermost first. */
|
|
148
|
+
export function ancestorFiles(routesDir: string, routeFile: string, names: string[]): string[] {
|
|
149
|
+
const result: string[] = []
|
|
150
|
+
const relDir = relative(routesDir, dirname(routeFile))
|
|
151
|
+
const parts = relDir === '' ? [] : relDir.split(PATH_SEPARATOR_RE)
|
|
152
|
+
let cur = routesDir
|
|
153
|
+
for (let i = 0; i <= parts.length; i++) {
|
|
154
|
+
if (i > 0)
|
|
155
|
+
cur = join(cur, parts[i - 1]!)
|
|
156
|
+
for (const name of names) {
|
|
157
|
+
const candidate = join(cur, name)
|
|
158
|
+
if (existsSync(candidate))
|
|
159
|
+
result.push(candidate)
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return result
|
|
163
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// The generated server entry (`dist/server/_entry.js`): the one module that assembles an app from its bundled config, routes and actions.
|
|
2
|
+
|
|
3
|
+
/** The entry's path under the server bundle root, and so under `dist/server/`. An underscore file is never a route. */
|
|
4
|
+
export const SERVER_ENTRY_FILE = '_entry.js'
|
|
5
|
+
|
|
6
|
+
export interface ServerEntryModule {
|
|
7
|
+
/** Absolute source path, bundled in the same pass as the entry. */
|
|
8
|
+
file: string
|
|
9
|
+
/** The module's manifest key (`server/index.js`). */
|
|
10
|
+
key: string
|
|
11
|
+
/** Root-relative source path, read by `testApp().import()`. */
|
|
12
|
+
source: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ServerEntryOptions {
|
|
16
|
+
modules: readonly ServerEntryModule[]
|
|
17
|
+
/** `kay.config.ts`, when the app has one. */
|
|
18
|
+
config?: { file: string, source: string } | undefined
|
|
19
|
+
/** Absolute path of kay's `server/app-entry.ts`, bundled from source like the app's own `kay/server` imports. */
|
|
20
|
+
assembler: string
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function serverEntrySource(options: ServerEntryOptions): string {
|
|
24
|
+
const lines: string[] = []
|
|
25
|
+
const { config } = options
|
|
26
|
+
if (config !== undefined)
|
|
27
|
+
lines.push(`import * as configModule from ${JSON.stringify(config.file)}`)
|
|
28
|
+
options.modules.forEach((m, i) => lines.push(`import * as m${i} from ${JSON.stringify(m.file)}`))
|
|
29
|
+
lines.push(`import { createAppFromEntry } from ${JSON.stringify(options.assembler)}`)
|
|
30
|
+
lines.push(`export const kayConfig = ${config !== undefined ? 'configModule.default ?? {}' : '{}'}`)
|
|
31
|
+
lines.push(`export const modules = {${options.modules.map((m, i) => ` ${JSON.stringify(m.key)}: m${i},`).join('')} }`)
|
|
32
|
+
const sources = options.modules.map((m, i) => ` ${JSON.stringify(m.source)}: m${i},`)
|
|
33
|
+
if (config !== undefined)
|
|
34
|
+
sources.push(` ${JSON.stringify(config.source)}: configModule,`)
|
|
35
|
+
lines.push(`export const sources = {${sources.join('')} }`)
|
|
36
|
+
lines.push('export function createApp(options) { return createAppFromEntry(kayConfig, modules, options) }')
|
|
37
|
+
return `${lines.join('\n')}\n`
|
|
38
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// `kay build --static`: gathers the prerendered pages, client assets and public files into one folder and swaps it in as the output directory.
|
|
2
|
+
|
|
3
|
+
import type { KayApp } from '../server/index'
|
|
4
|
+
import { copyFileSync, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { basename, dirname, join, relative } from 'node:path'
|
|
6
|
+
import { precompressFile, walkAllFiles } from './files'
|
|
7
|
+
|
|
8
|
+
const LEADING_SLASH_RE = /^\//
|
|
9
|
+
|
|
10
|
+
export interface StaticExportOptions {
|
|
11
|
+
/** The folder the site is assembled in; it becomes `finalOutDir`. */
|
|
12
|
+
stageDir: string
|
|
13
|
+
finalOutDir: string
|
|
14
|
+
/** The regular build output the assets and public files are copied from. */
|
|
15
|
+
outDir: string
|
|
16
|
+
clientDir: string
|
|
17
|
+
assetPrefix: string
|
|
18
|
+
assets: string[]
|
|
19
|
+
publicFiles: { files: string[], register: (relPath: string) => string }
|
|
20
|
+
/** The server the pages were prerendered with, used to render `_404` when the app has one. */
|
|
21
|
+
app: KayApp | undefined
|
|
22
|
+
hasNotFoundFile: boolean
|
|
23
|
+
stageSuffix: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function copyInto(dstRoot: string, rel: string, src: string): void {
|
|
27
|
+
const dst = join(dstRoot, rel)
|
|
28
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
29
|
+
copyFileSync(src, dst)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function exportStatic(options: StaticExportOptions): Promise<void> {
|
|
33
|
+
const { stageDir, finalOutDir, outDir, clientDir, publicFiles } = options
|
|
34
|
+
if (options.hasNotFoundFile && options.app !== undefined) {
|
|
35
|
+
const res = await options.app.handle(new Request('http://localhost/__kay_404__'))
|
|
36
|
+
if (res.status >= 500)
|
|
37
|
+
throw new Error(`kay build --static: _404 page returned HTTP ${res.status}.`)
|
|
38
|
+
writeFileSync(join(stageDir, '404.html'), await res.text())
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Client assets go to <stage>/_kay/..., public files to <stage>/...
|
|
42
|
+
const assetDir = join(stageDir, options.assetPrefix.replace(LEADING_SLASH_RE, ''))
|
|
43
|
+
for (const rel of options.assets)
|
|
44
|
+
copyInto(assetDir, rel, join(clientDir, rel))
|
|
45
|
+
// Also pick up files written directly into the public folder without registering them.
|
|
46
|
+
const outPublicDir = join(outDir, 'public')
|
|
47
|
+
for (const abs of walkAllFiles(outPublicDir))
|
|
48
|
+
publicFiles.register(relative(outPublicDir, abs))
|
|
49
|
+
for (const rel of publicFiles.files)
|
|
50
|
+
copyInto(stageDir, rel, join(outPublicDir, rel))
|
|
51
|
+
for (const abs of walkAllFiles(stageDir))
|
|
52
|
+
precompressFile(abs, 128)
|
|
53
|
+
|
|
54
|
+
// Swap the stage in only after every page and asset succeeded.
|
|
55
|
+
if (!existsSync(finalOutDir)) {
|
|
56
|
+
mkdirSync(dirname(finalOutDir), { recursive: true })
|
|
57
|
+
renameSync(stageDir, finalOutDir)
|
|
58
|
+
return
|
|
59
|
+
}
|
|
60
|
+
const backupDir = join(dirname(finalOutDir), `.${basename(finalOutDir)}.prev-${options.stageSuffix}`)
|
|
61
|
+
renameSync(finalOutDir, backupDir)
|
|
62
|
+
try {
|
|
63
|
+
renameSync(stageDir, finalOutDir)
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
try {
|
|
67
|
+
renameSync(backupDir, finalOutDir)
|
|
68
|
+
}
|
|
69
|
+
catch {}
|
|
70
|
+
throw err
|
|
71
|
+
}
|
|
72
|
+
rmSync(backupDir, { recursive: true, force: true })
|
|
73
|
+
}
|