@kayjs/kay 2.0.0-beta.1 → 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/build/bundle.ts +209 -34
- package/src/build/compile.ts +22 -46
- package/src/build/files.ts +38 -0
- package/src/build/graph.ts +67 -2
- package/src/build/index.ts +75 -13
- package/src/build/manifest.ts +5 -0
- package/src/build/plugin-host.ts +2 -0
- package/src/build/prerender.ts +16 -7
- package/src/build/resolve.ts +11 -18
- package/src/build/routes.ts +33 -5
- package/src/build/server-entry.ts +38 -0
- package/src/cli/check.ts +102 -45
- package/src/cli/new.ts +6 -7
- package/src/compiler/analyze.ts +65 -10
- package/src/compiler/dom.ts +143 -122
- package/src/compiler/server-only.ts +14 -8
- package/src/compiler/shared.ts +57 -14
- package/src/compiler/ssr.ts +14 -12
- package/src/dev/index.ts +96 -29
- package/src/dom/action.ts +91 -1
- package/src/dom/index.ts +8 -3
- package/src/index.ts +3 -0
- package/src/jsx-runtime.ts +421 -93
- package/src/plugins/config.ts +49 -0
- package/src/plugins/context.ts +4 -0
- package/src/plugins/index.ts +7 -216
- 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/server/action-registry.ts +72 -0
- package/src/server/action.ts +15 -8
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +182 -0
- package/src/server/compress.ts +87 -14
- package/src/server/document.ts +192 -0
- package/src/server/errors.ts +123 -0
- package/src/server/http.ts +103 -30
- package/src/server/index.ts +131 -701
- package/src/server/loader.ts +62 -69
- package/src/server/page.ts +107 -0
- package/src/server/plugin-host.ts +167 -0
- package/src/server/router.ts +49 -20
- package/src/server/security.ts +44 -3
- package/src/server/static-dir.ts +22 -3
- package/src/server/stream.ts +94 -0
- package/src/test/index.ts +24 -19
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kayjs/kay",
|
|
3
|
-
"version": "2.0.0-beta.
|
|
3
|
+
"version": "2.0.0-beta.3",
|
|
4
4
|
"description": "Bun-native TSX web framework with zero-directive automatic islands, fine-grained signals, and single-binary deploys",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://kayjs.kaynooo.fr",
|
package/src/build/bundle.ts
CHANGED
|
@@ -5,11 +5,12 @@ import type { IslandBinding } from '../compiler/index'
|
|
|
5
5
|
import type { BuildPluginTarget, KayPlugin } from '../plugins/index'
|
|
6
6
|
import type { BuildCache, ModuleGraph } from './graph'
|
|
7
7
|
import type { ActionsByFile, IslandPlan } from './islands'
|
|
8
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
9
|
-
import { isAbsolute, join, resolve } from 'node:path'
|
|
8
|
+
import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
|
|
9
|
+
import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
10
10
|
import { compileDom, compileSsr } from '../compiler/index'
|
|
11
11
|
import { readsPrivateEnv, SERVER_ONLY_FILTER } from '../compiler/server-only'
|
|
12
|
-
import { isOutsideRoot, isTsFile, relPosix } from './files'
|
|
12
|
+
import { formatBunBuildLogs, isOutsideRoot, isTsFile, relPosix } from './files'
|
|
13
|
+
import { stampFiles, stampsMatch } from './graph'
|
|
13
14
|
import { islandKey } from './islands'
|
|
14
15
|
import { resolveKaySpecifier } from './resolve'
|
|
15
16
|
|
|
@@ -21,6 +22,7 @@ export interface BundleEnv {
|
|
|
21
22
|
assetPrefix: string
|
|
22
23
|
minify: boolean
|
|
23
24
|
isDev: boolean
|
|
25
|
+
analyze?: boolean | undefined
|
|
24
26
|
graph: ModuleGraph
|
|
25
27
|
cache: BuildCache | undefined
|
|
26
28
|
plugins: KayPlugin[]
|
|
@@ -28,6 +30,40 @@ export interface BundleEnv {
|
|
|
28
30
|
islands: IslandPlan
|
|
29
31
|
}
|
|
30
32
|
|
|
33
|
+
function linkOrCopyFile(src: string, dst: string): void {
|
|
34
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
35
|
+
try {
|
|
36
|
+
linkSync(src, dst)
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
copyFileSync(src, dst)
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function reuseDirFiles(srcDir: string, dstDir: string, relFiles?: readonly string[]): boolean {
|
|
44
|
+
if (!existsSync(srcDir))
|
|
45
|
+
return false
|
|
46
|
+
if (relFiles !== undefined) {
|
|
47
|
+
for (const rel of relFiles) {
|
|
48
|
+
const from = join(srcDir, rel)
|
|
49
|
+
if (!existsSync(from))
|
|
50
|
+
return false
|
|
51
|
+
linkOrCopyFile(from, join(dstDir, rel))
|
|
52
|
+
}
|
|
53
|
+
return true
|
|
54
|
+
}
|
|
55
|
+
let count = 0
|
|
56
|
+
for (const ent of readdirSync(srcDir, { recursive: true, withFileTypes: true })) {
|
|
57
|
+
if (!ent.isFile())
|
|
58
|
+
continue
|
|
59
|
+
const from = join(ent.parentPath, ent.name)
|
|
60
|
+
const rel = relative(srcDir, from)
|
|
61
|
+
linkOrCopyFile(from, join(dstDir, rel))
|
|
62
|
+
count++
|
|
63
|
+
}
|
|
64
|
+
return count > 0
|
|
65
|
+
}
|
|
66
|
+
|
|
31
67
|
const KAY_SPECIFIER_FILTER = /^(?:@kayjs\/)?kay(?:\/.*)?$/
|
|
32
68
|
const TS_FILTER = /\.(?:ts|tsx)$/
|
|
33
69
|
const KAY_SCOPE_RE = /^@kayjs\//
|
|
@@ -111,10 +147,68 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
|
|
|
111
147
|
metafile: undefined,
|
|
112
148
|
}
|
|
113
149
|
const pluginClientEntries = env.plugins.map(p => p.clientEntry).filter((e): e is string => Boolean(e))
|
|
114
|
-
if (islands.targets.size === 0 && pluginClientEntries.length === 0 && standaloneCss.length === 0)
|
|
150
|
+
if (islands.targets.size === 0 && pluginClientEntries.length === 0 && standaloneCss.length === 0) {
|
|
151
|
+
if (cache !== undefined)
|
|
152
|
+
cache.lastClient = undefined
|
|
115
153
|
return result
|
|
154
|
+
}
|
|
116
155
|
|
|
117
156
|
const transforms = pluginTransforms(env.plugins)
|
|
157
|
+
// A mode computed at runtime may be any of them, so it keeps both loaders.
|
|
158
|
+
let hasDeferredHydrate = false
|
|
159
|
+
let hasClientOnlyHydrate = false
|
|
160
|
+
for (const analysis of graph.analyses.values()) {
|
|
161
|
+
for (const mode of [analysis.defaultHydrate, ...analysis.hydrateModes]) {
|
|
162
|
+
if (mode === 'client' || mode === '*')
|
|
163
|
+
hasClientOnlyHydrate = true
|
|
164
|
+
if (mode !== undefined && mode !== 'load' && mode !== 'client')
|
|
165
|
+
hasDeferredHydrate = true
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const envDefines = publicEnvDefines()
|
|
170
|
+
const clientSignature = cache !== undefined
|
|
171
|
+
? JSON.stringify({
|
|
172
|
+
minify: env.minify,
|
|
173
|
+
assetPrefix,
|
|
174
|
+
isDev: env.isDev,
|
|
175
|
+
transforms: transforms.key,
|
|
176
|
+
hasDeferredHydrate,
|
|
177
|
+
hasClientOnlyHydrate,
|
|
178
|
+
pluginClientEntries,
|
|
179
|
+
standaloneCss: [...standaloneCss].sort(),
|
|
180
|
+
islands: [...islands.targets.entries()]
|
|
181
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
182
|
+
.map(([k, t]) => [k, t.id, t.file, t.exportName, t.defaultHydrate ?? '']),
|
|
183
|
+
actions: [...actionsByFile.entries()]
|
|
184
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
185
|
+
.map(([f, list]) => [f, list.map(a => `${a.exportName}=${a.url}`)]),
|
|
186
|
+
envDefines: Object.entries(envDefines).sort(([a], [b]) => a.localeCompare(b)),
|
|
187
|
+
bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
|
|
188
|
+
})
|
|
189
|
+
: ''
|
|
190
|
+
|
|
191
|
+
if (
|
|
192
|
+
cache !== undefined
|
|
193
|
+
&& !env.analyze
|
|
194
|
+
&& cache.lastClient !== undefined
|
|
195
|
+
&& cache.lastClient.signature === clientSignature
|
|
196
|
+
&& stampsMatch(cache.lastClient.inputStamps)
|
|
197
|
+
&& reuseDirFiles(cache.lastClient.clientDir, clientDir, cache.lastClient.assetFiles)
|
|
198
|
+
) {
|
|
199
|
+
cache.stats.clientSkips++
|
|
200
|
+
cache.lastClient.clientDir = clientDir
|
|
201
|
+
return {
|
|
202
|
+
islandChunks: new Map(cache.lastClient.islandChunks),
|
|
203
|
+
srcCssToUrl: new Map(cache.lastClient.srcCssToUrl),
|
|
204
|
+
islandCssUrl: new Map(cache.lastClient.islandCssUrl),
|
|
205
|
+
assetFiles: [...cache.lastClient.assetFiles],
|
|
206
|
+
styleUrls: [...cache.lastClient.styleUrls],
|
|
207
|
+
runtimeScript: cache.lastClient.runtimeScript,
|
|
208
|
+
metafile: undefined,
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
118
212
|
// Bun hashes an entry's path into its chunk name, so the entries sit at one path per app: a dev rebuild or a static stage then keeps every unchanged chunk name.
|
|
119
213
|
const entriesDir = join(root, 'node_modules/.cache/kay/entries')
|
|
120
214
|
mkdirSync(entriesDir, { recursive: true })
|
|
@@ -129,18 +223,6 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
|
|
|
129
223
|
const entryPoints: string[] = []
|
|
130
224
|
const islandEntryToKey = new Map<string, string>()
|
|
131
225
|
|
|
132
|
-
// A mode computed at runtime may be any of them, so it keeps both loaders.
|
|
133
|
-
let hasDeferredHydrate = false
|
|
134
|
-
let hasClientOnlyHydrate = false
|
|
135
|
-
for (const analysis of graph.analyses.values()) {
|
|
136
|
-
for (const mode of [analysis.defaultHydrate, ...analysis.hydrateModes]) {
|
|
137
|
-
if (mode === 'client' || mode === '*')
|
|
138
|
-
hasClientOnlyHydrate = true
|
|
139
|
-
if (mode !== undefined && mode !== 'load' && mode !== 'client')
|
|
140
|
-
hasDeferredHydrate = true
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
226
|
if (islands.targets.size > 0 || pluginClientEntries.length > 0) {
|
|
145
227
|
const runtimeLines: string[] = []
|
|
146
228
|
if (islands.targets.size > 0) {
|
|
@@ -168,7 +250,6 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
|
|
|
168
250
|
}
|
|
169
251
|
|
|
170
252
|
const clientLeaks = new Set<string>()
|
|
171
|
-
const envDefines = publicEnvDefines()
|
|
172
253
|
const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in envDefines
|
|
173
254
|
const clientPlugin: BunPlugin = {
|
|
174
255
|
name: 'kay-v2-client',
|
|
@@ -235,13 +316,15 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
|
|
|
235
316
|
catch (err) {
|
|
236
317
|
if (clientLeaks.size > 0)
|
|
237
318
|
throw clientLeakError(clientLeaks)
|
|
319
|
+
if (err instanceof AggregateError && err.errors.length > 0)
|
|
320
|
+
throw new Error(`kay build (client) failed:\n${formatBunBuildLogs(err.errors, env.root)}`)
|
|
238
321
|
throw err
|
|
239
322
|
}
|
|
240
323
|
|
|
241
324
|
if (clientLeaks.size > 0)
|
|
242
325
|
throw clientLeakError(clientLeaks)
|
|
243
326
|
if (!clientResult.success) {
|
|
244
|
-
const msgs = clientResult.logs
|
|
327
|
+
const msgs = formatBunBuildLogs(clientResult.logs, env.root)
|
|
245
328
|
throw new Error(`kay build (client) failed:\n${msgs}`)
|
|
246
329
|
}
|
|
247
330
|
|
|
@@ -314,14 +397,68 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
|
|
|
314
397
|
else if (output.kind === 'entry-point' && relFile.startsWith('runtime-'))
|
|
315
398
|
result.runtimeScript = url
|
|
316
399
|
}
|
|
400
|
+
|
|
401
|
+
if (cache !== undefined) {
|
|
402
|
+
cache.stats.clientBuilds++
|
|
403
|
+
const inputFiles = new Set<string>([...standaloneCss, ...pluginClientEntries])
|
|
404
|
+
for (const inKey of Object.keys(metafile?.inputs ?? {})) {
|
|
405
|
+
const abs = resolveMetaPath(inKey)
|
|
406
|
+
// Skip generated entry shims and stubbed action files (whose signature tracks exported action names/URLs, not server body).
|
|
407
|
+
if (abs.startsWith(entriesDir))
|
|
408
|
+
continue
|
|
409
|
+
if (actionsByFile.has(abs) && !graph.analyses.get(abs)?.isInteractive)
|
|
410
|
+
continue
|
|
411
|
+
inputFiles.add(abs)
|
|
412
|
+
}
|
|
413
|
+
cache.lastClient = {
|
|
414
|
+
signature: clientSignature,
|
|
415
|
+
clientDir,
|
|
416
|
+
inputStamps: stampFiles(inputFiles),
|
|
417
|
+
islandChunks: new Map(result.islandChunks),
|
|
418
|
+
srcCssToUrl: new Map(result.srcCssToUrl),
|
|
419
|
+
islandCssUrl: new Map(result.islandCssUrl),
|
|
420
|
+
assetFiles: [...result.assetFiles],
|
|
421
|
+
styleUrls: [...result.styleUrls],
|
|
422
|
+
runtimeScript: result.runtimeScript,
|
|
423
|
+
}
|
|
424
|
+
}
|
|
317
425
|
return result
|
|
318
426
|
}
|
|
319
427
|
|
|
320
|
-
|
|
428
|
+
/** `entry` is the generated `_entry.js`, an in-memory file bundled beside `entries` so it shares their chunks. */
|
|
429
|
+
export async function buildServer(env: BundleEnv, entries: string[], serverRoot: string, islandChunks: Map<string, string>, entry: { file: string, source: string }): Promise<void> {
|
|
321
430
|
const { root, outDir, serverDir, graph, cache, islands } = env
|
|
322
431
|
const transforms = pluginTransforms(env.plugins)
|
|
323
432
|
const externalOutDir = isOutsideRoot(root, outDir)
|
|
324
433
|
|
|
434
|
+
const serverSignature = cache !== undefined
|
|
435
|
+
? JSON.stringify({
|
|
436
|
+
serverRoot,
|
|
437
|
+
assetPrefix: env.assetPrefix,
|
|
438
|
+
isDev: env.isDev,
|
|
439
|
+
transforms: transforms.key,
|
|
440
|
+
entries: [...entries].sort(),
|
|
441
|
+
islandChunks: [...islandChunks.entries()].sort(([a], [b]) => a.localeCompare(b)),
|
|
442
|
+
reach: [...islands.reach].sort(),
|
|
443
|
+
bindings: [...islands.pageBindings.entries()]
|
|
444
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
445
|
+
.map(([f, map]) => [f, [...map.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([l, t]) => [l, t.id, t.defaultHydrate ?? ''])]),
|
|
446
|
+
bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
|
|
447
|
+
})
|
|
448
|
+
: ''
|
|
449
|
+
|
|
450
|
+
if (
|
|
451
|
+
cache !== undefined
|
|
452
|
+
&& cache.lastServer !== undefined
|
|
453
|
+
&& cache.lastServer.signature === serverSignature
|
|
454
|
+
&& stampsMatch(cache.lastServer.inputStamps)
|
|
455
|
+
&& reuseDirFiles(cache.lastServer.serverDir, serverDir)
|
|
456
|
+
) {
|
|
457
|
+
cache.stats.serverSkips++
|
|
458
|
+
cache.lastServer.serverDir = serverDir
|
|
459
|
+
return
|
|
460
|
+
}
|
|
461
|
+
|
|
325
462
|
// Whether a file renders components, directly or through what it imports: such packages are bundled so Kay's SSR compiler transforms them.
|
|
326
463
|
const tsxReach = new Map<string, boolean>()
|
|
327
464
|
const reachesTsx = (file: string, visiting = new Set<string>()): boolean => {
|
|
@@ -374,6 +511,14 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
|
|
|
374
511
|
}
|
|
375
512
|
if (resolved.endsWith('.tsx') || reachesTsx(resolved))
|
|
376
513
|
return { path: resolved }
|
|
514
|
+
if (env.isDev && isTsFile(resolved)) {
|
|
515
|
+
try {
|
|
516
|
+
const real = realpathSync(resolved)
|
|
517
|
+
if (!real.includes('/node_modules/') && !real.includes('\\node_modules\\'))
|
|
518
|
+
return { path: resolved }
|
|
519
|
+
}
|
|
520
|
+
catch {}
|
|
521
|
+
}
|
|
377
522
|
if (externalOutDir)
|
|
378
523
|
return { path: resolved, external: true }
|
|
379
524
|
return undefined
|
|
@@ -420,23 +565,53 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
|
|
|
420
565
|
},
|
|
421
566
|
}
|
|
422
567
|
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
568
|
+
let serverResult: Awaited<ReturnType<typeof Bun.build>>
|
|
569
|
+
try {
|
|
570
|
+
serverResult = await Bun.build({
|
|
571
|
+
entrypoints: [...entries, entry.file],
|
|
572
|
+
files: { [entry.file]: entry.source },
|
|
573
|
+
outdir: serverDir,
|
|
574
|
+
root: serverRoot,
|
|
575
|
+
target: 'bun',
|
|
576
|
+
format: 'esm',
|
|
577
|
+
splitting: true,
|
|
578
|
+
packages: 'external',
|
|
579
|
+
minify: false,
|
|
580
|
+
metafile: cache !== undefined,
|
|
581
|
+
define: {
|
|
582
|
+
'process.env.NODE_ENV': 'process.env.NODE_ENV',
|
|
583
|
+
},
|
|
584
|
+
plugins: [serverPlugin, ...pluginBunPlugins(env, 'server')],
|
|
585
|
+
})
|
|
586
|
+
}
|
|
587
|
+
catch (err) {
|
|
588
|
+
if (err instanceof AggregateError && err.errors.length > 0)
|
|
589
|
+
throw new Error(`kay build (server) failed:\n${formatBunBuildLogs(err.errors, env.root)}`)
|
|
590
|
+
throw err
|
|
591
|
+
}
|
|
437
592
|
|
|
438
593
|
if (!serverResult.success) {
|
|
439
|
-
const msgs = serverResult.logs
|
|
594
|
+
const msgs = formatBunBuildLogs(serverResult.logs, env.root)
|
|
440
595
|
throw new Error(`kay build (server) failed:\n${msgs}`)
|
|
441
596
|
}
|
|
597
|
+
|
|
598
|
+
if (cache !== undefined) {
|
|
599
|
+
cache.stats.serverBuilds++
|
|
600
|
+
const inputFiles = new Set<string>(entries)
|
|
601
|
+
for (const inKey of Object.keys(serverResult.metafile?.inputs ?? {})) {
|
|
602
|
+
const fromCwd = resolve(process.cwd(), inKey)
|
|
603
|
+
const abs = existsSync(fromCwd) ? fromCwd : resolve(serverDir, inKey)
|
|
604
|
+
if (!existsSync(abs))
|
|
605
|
+
continue
|
|
606
|
+
// Plain `.css` stylesheets are bundled exclusively by `buildClient`; CSS edits must not trigger a server rebuild.
|
|
607
|
+
if (abs.endsWith('.css') && !abs.endsWith('.module.css'))
|
|
608
|
+
continue
|
|
609
|
+
inputFiles.add(abs)
|
|
610
|
+
}
|
|
611
|
+
cache.lastServer = {
|
|
612
|
+
signature: serverSignature,
|
|
613
|
+
serverDir,
|
|
614
|
+
inputStamps: stampFiles(inputFiles),
|
|
615
|
+
}
|
|
616
|
+
}
|
|
442
617
|
}
|
package/src/build/compile.ts
CHANGED
|
@@ -5,6 +5,8 @@ import type { BunPlugin } from 'bun'
|
|
|
5
5
|
import type { BuildManifest } from './index'
|
|
6
6
|
import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
7
7
|
import { join } from 'node:path'
|
|
8
|
+
import { formatBunBuildLogs } from './files'
|
|
9
|
+
import { SERVER_ENTRY_FILE } from './server-entry'
|
|
8
10
|
|
|
9
11
|
export interface CompileExecutableOptions {
|
|
10
12
|
root: string
|
|
@@ -13,47 +15,18 @@ export interface CompileExecutableOptions {
|
|
|
13
15
|
manifest: BuildManifest
|
|
14
16
|
assetPrefix: string
|
|
15
17
|
outfile: string
|
|
16
|
-
kaySrcRoot: string
|
|
17
18
|
resolveKaySpecifier: (specifier: string) => string | undefined
|
|
18
19
|
bunPlugins?: BunPlugin[] | undefined
|
|
19
20
|
}
|
|
20
21
|
|
|
21
22
|
export async function compileExecutable(opts: CompileExecutableOptions): Promise<void> {
|
|
22
|
-
const { root, outDir, clientDir, manifest, assetPrefix, outfile,
|
|
23
|
+
const { root, outDir, clientDir, manifest, assetPrefix, outfile, resolveKaySpecifier, bunPlugins = [] } = opts
|
|
23
24
|
const entryPath = join(outDir, '__compile_entry.ts')
|
|
24
25
|
const prodEnvPath = join(outDir, '__compile_prod_env.ts')
|
|
25
26
|
// Evaluated first via ESM static import order so `kay.config.ts` and route modules see NODE_ENV=production!
|
|
26
27
|
writeFileSync(prodEnvPath, `const _envKey = 'NODE_ENV';\nprocess.env[_envKey] ??= 'production';\n`)
|
|
27
|
-
const
|
|
28
|
-
const
|
|
29
|
-
const seenFiles = new Set<string>()
|
|
30
|
-
let idx = 0
|
|
31
|
-
|
|
32
|
-
const addMod = (rel: string) => {
|
|
33
|
-
if (seenFiles.has(rel))
|
|
34
|
-
return
|
|
35
|
-
seenFiles.add(rel)
|
|
36
|
-
const v = `_m${idx++}`
|
|
37
|
-
imports.push(`import * as ${v} from ${JSON.stringify(join(outDir, rel))};`)
|
|
38
|
-
modEntries.push(`${JSON.stringify(rel)}: ${v}`)
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
for (const r of manifest.routes) {
|
|
42
|
-
addMod(r.file)
|
|
43
|
-
for (const l of r.layouts) addMod(l)
|
|
44
|
-
for (const m of r.middlewares) addMod(m)
|
|
45
|
-
}
|
|
46
|
-
if (manifest.errorFile) addMod(manifest.errorFile)
|
|
47
|
-
if (manifest.notFoundFile) addMod(manifest.notFoundFile)
|
|
48
|
-
for (const a of manifest.actions) {
|
|
49
|
-
addMod(a.file)
|
|
50
|
-
for (const m of a.middlewares) addMod(m)
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
const configPath = join(root, 'kay.config.ts')
|
|
54
|
-
const hasConfig = existsSync(configPath)
|
|
55
|
-
if (hasConfig)
|
|
56
|
-
imports.push(`import _kayConfig from ${JSON.stringify(configPath)};`)
|
|
28
|
+
const entryJs = join(outDir, 'server', SERVER_ENTRY_FILE)
|
|
29
|
+
const imports: string[] = [`import ${JSON.stringify(prodEnvPath)};`, `import { createApp, kayConfig } from ${JSON.stringify(entryJs)};`]
|
|
57
30
|
|
|
58
31
|
// Embed client assets and public files natively via `with { type: "file" }` (0 base64, 0 startup decode!)
|
|
59
32
|
const embeddedAssets: string[] = []
|
|
@@ -96,22 +69,17 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
96
69
|
}
|
|
97
70
|
}
|
|
98
71
|
|
|
99
|
-
const cfgSpread = hasConfig ? `...pickRuntimeConfig(_kayConfig), ` : ''
|
|
100
|
-
|
|
101
72
|
const code = [
|
|
102
73
|
...imports,
|
|
103
|
-
`import { createServerFromEmbedded, pickRuntimeConfig } from ${JSON.stringify(join(kaySrcRoot, 'server/index.ts'))};`,
|
|
104
74
|
`const manifest = ${JSON.stringify(manifest)};`,
|
|
105
|
-
`const modules = { ${modEntries.join(', ')} };`,
|
|
106
75
|
`const assets = { ${embeddedAssets.join(', ')} };`,
|
|
107
76
|
`const publicAssets = { ${embeddedPublic.join(', ')} };`,
|
|
108
77
|
`const publicEtags = { ${embeddedPublicEtags.join(', ')} };`,
|
|
109
|
-
`const prerendered = {};`,
|
|
110
78
|
`const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
|
|
111
|
-
`const port = Number(process.env.PORT ||
|
|
79
|
+
`const port = Number(process.env.PORT || kayConfig.port || 3000);`,
|
|
112
80
|
`const hostname = process.env.HOST || undefined;`,
|
|
113
81
|
`if (Bun.argv.includes('--health')) { const probeHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${probeHost}:\${port}/\`).catch(() => null); process.exit(r && r.status < 500 ? 0 : 1); }`,
|
|
114
|
-
`const app = await
|
|
82
|
+
`const app = await createApp({ assetPrefix: ${JSON.stringify(assetPrefix)}, manifest, assets, publicAssets, publicEtags, prerenderedFiles });`,
|
|
115
83
|
`const server = app.serve(port, hostname);`,
|
|
116
84
|
`console.log(\`kay server listening on http://\${hostname ?? 'localhost'}:\${server.port}\`);`,
|
|
117
85
|
].join('\n')
|
|
@@ -127,14 +95,22 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
127
95
|
})
|
|
128
96
|
},
|
|
129
97
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
98
|
+
let res: Awaited<ReturnType<typeof Bun.build>>
|
|
99
|
+
try {
|
|
100
|
+
res = await Bun.build({
|
|
101
|
+
entrypoints: [entryPath],
|
|
102
|
+
compile: { outfile },
|
|
103
|
+
minify: true,
|
|
104
|
+
plugins: [kayResolvePlugin, ...bunPlugins],
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
catch (err) {
|
|
108
|
+
if (err instanceof AggregateError && err.errors.length > 0)
|
|
109
|
+
throw new Error(`kay build --compile failed:\n${formatBunBuildLogs(err.errors, root)}`)
|
|
110
|
+
throw err
|
|
111
|
+
}
|
|
136
112
|
if (!res.success) {
|
|
137
|
-
const msgs = res.logs
|
|
113
|
+
const msgs = formatBunBuildLogs(res.logs, root)
|
|
138
114
|
throw new Error(`kay build --compile failed:\n${msgs}`)
|
|
139
115
|
}
|
|
140
116
|
}
|
package/src/build/files.ts
CHANGED
|
@@ -134,3 +134,41 @@ export function precompressFile(abs: string, minBytes: number): void {
|
|
|
134
134
|
if (gz.byteLength < raw.byteLength)
|
|
135
135
|
writeFileSync(`${abs}.gz`, gz)
|
|
136
136
|
}
|
|
137
|
+
|
|
138
|
+
export interface BunBuildLogLike {
|
|
139
|
+
message?: string | undefined
|
|
140
|
+
level?: string | undefined
|
|
141
|
+
position?: {
|
|
142
|
+
file?: string | undefined
|
|
143
|
+
line?: number | undefined
|
|
144
|
+
column?: number | undefined
|
|
145
|
+
length?: number | undefined
|
|
146
|
+
lineText?: string | undefined
|
|
147
|
+
} | null | undefined
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Formats Bun `BuildMessage` / `ResolveMessage` logs with `file:line:col: error|warning: <message>` and a source line frame. */
|
|
151
|
+
export function formatBunBuildLogs(logs: readonly unknown[], root?: string): string {
|
|
152
|
+
return logs.map((raw) => {
|
|
153
|
+
if (raw === null || typeof raw !== 'object')
|
|
154
|
+
return String(raw)
|
|
155
|
+
const log = raw as BunBuildLogLike
|
|
156
|
+
const msg = typeof log.message === 'string' && log.message.length > 0 ? log.message : String(raw)
|
|
157
|
+
const pos = log.position
|
|
158
|
+
if (pos && typeof pos.file === 'string' && pos.file.length > 0 && typeof pos.line === 'number') {
|
|
159
|
+
const file = root !== undefined && isAbsolute(pos.file) ? relPosix(root, pos.file) : pos.file
|
|
160
|
+
const col = typeof pos.column === 'number' && pos.column > 0 ? pos.column : 1
|
|
161
|
+
const severity = log.level === 'warning' ? 'warning' : 'error'
|
|
162
|
+
const header = `${file}:${pos.line}:${col}: ${severity}: ${msg}`
|
|
163
|
+
if (typeof pos.lineText === 'string') {
|
|
164
|
+
const lineStr = String(pos.line)
|
|
165
|
+
const pad = ' '.repeat(lineStr.length)
|
|
166
|
+
const maxSpan = Math.max(1, pos.lineText.length - (col - 1))
|
|
167
|
+
const len = typeof pos.length === 'number' && pos.length > 0 ? Math.min(pos.length, maxSpan) : 1
|
|
168
|
+
return `${header}\n ${lineStr} | ${pos.lineText}\n ${pad} | ${' '.repeat(Math.max(0, col - 1))}${'^'.repeat(len)}`
|
|
169
|
+
}
|
|
170
|
+
return header
|
|
171
|
+
}
|
|
172
|
+
return msg
|
|
173
|
+
}).join('\n')
|
|
174
|
+
}
|
package/src/build/graph.ts
CHANGED
|
@@ -1,20 +1,49 @@
|
|
|
1
1
|
// The module graph of one build: every .ts/.tsx file reachable from the routes, analyzed once (and reused across `kay dev` rebuilds while mtime and size match).
|
|
2
2
|
|
|
3
3
|
import type { ModuleAnalysis } from '../compiler/index'
|
|
4
|
-
import { readFileSync, statSync } from 'node:fs'
|
|
4
|
+
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
5
5
|
import { analyzeModule } from '../compiler/index'
|
|
6
6
|
import { isTsFile } from './files'
|
|
7
7
|
import { resolveImportPath } from './resolve'
|
|
8
8
|
|
|
9
|
-
interface FileStamp {
|
|
9
|
+
export interface FileStamp {
|
|
10
10
|
mtimeMs: number
|
|
11
11
|
size: number
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
export interface CachedClientBuild {
|
|
15
|
+
signature: string
|
|
16
|
+
clientDir: string
|
|
17
|
+
inputStamps: Map<string, FileStamp>
|
|
18
|
+
islandChunks: Map<string, string>
|
|
19
|
+
srcCssToUrl: Map<string, string>
|
|
20
|
+
islandCssUrl: Map<string, string>
|
|
21
|
+
assetFiles: string[]
|
|
22
|
+
styleUrls: string[]
|
|
23
|
+
runtimeScript: string | undefined
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface CachedServerBuild {
|
|
27
|
+
signature: string
|
|
28
|
+
serverDir: string
|
|
29
|
+
inputStamps: Map<string, FileStamp>
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface BuildCacheStats {
|
|
33
|
+
clientBuilds: number
|
|
34
|
+
clientSkips: number
|
|
35
|
+
serverBuilds: number
|
|
36
|
+
serverSkips: number
|
|
37
|
+
}
|
|
38
|
+
|
|
14
39
|
export interface BuildCache {
|
|
15
40
|
analyses: Map<string, FileStamp & { code: string, analysis: ModuleAnalysis }>
|
|
16
41
|
domCompiled: Map<string, FileStamp & { key?: string | undefined, code: string }>
|
|
17
42
|
ssrCompiled: Map<string, FileStamp & { key: string, code: string }>
|
|
43
|
+
lastClient?: CachedClientBuild | undefined
|
|
44
|
+
lastServer?: CachedServerBuild | undefined
|
|
45
|
+
watchedFiles: Set<string>
|
|
46
|
+
stats: BuildCacheStats
|
|
18
47
|
}
|
|
19
48
|
|
|
20
49
|
export function createBuildCache(): BuildCache {
|
|
@@ -22,6 +51,8 @@ export function createBuildCache(): BuildCache {
|
|
|
22
51
|
analyses: new Map(),
|
|
23
52
|
domCompiled: new Map(),
|
|
24
53
|
ssrCompiled: new Map(),
|
|
54
|
+
watchedFiles: new Set(),
|
|
55
|
+
stats: { clientBuilds: 0, clientSkips: 0, serverBuilds: 0, serverSkips: 0 },
|
|
25
56
|
}
|
|
26
57
|
}
|
|
27
58
|
|
|
@@ -29,6 +60,40 @@ export function clearBuildCache(cache: BuildCache): void {
|
|
|
29
60
|
cache.analyses.clear()
|
|
30
61
|
cache.domCompiled.clear()
|
|
31
62
|
cache.ssrCompiled.clear()
|
|
63
|
+
cache.lastClient = undefined
|
|
64
|
+
cache.lastServer = undefined
|
|
65
|
+
cache.watchedFiles.clear()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function stampFiles(files: Iterable<string>): Map<string, FileStamp> {
|
|
69
|
+
const out = new Map<string, FileStamp>()
|
|
70
|
+
for (const file of files) {
|
|
71
|
+
if (out.has(file))
|
|
72
|
+
continue
|
|
73
|
+
try {
|
|
74
|
+
const st = statSync(file)
|
|
75
|
+
if (st.isFile())
|
|
76
|
+
out.set(file, { mtimeMs: st.mtimeMs, size: st.size })
|
|
77
|
+
}
|
|
78
|
+
catch {}
|
|
79
|
+
}
|
|
80
|
+
return out
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function stampsMatch(inputStamps: ReadonlyMap<string, FileStamp>): boolean {
|
|
84
|
+
for (const [file, prev] of inputStamps) {
|
|
85
|
+
if (!existsSync(file))
|
|
86
|
+
return false
|
|
87
|
+
try {
|
|
88
|
+
const st = statSync(file)
|
|
89
|
+
if (st.mtimeMs !== prev.mtimeMs || st.size !== prev.size)
|
|
90
|
+
return false
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return false
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return true
|
|
32
97
|
}
|
|
33
98
|
|
|
34
99
|
const MAX_REEXPORT_DEPTH = 8
|