@kayjs/kay 2.0.0-alpha.6 → 2.0.0-alpha.7
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/compile.ts +9 -6
- package/src/build/index.ts +54 -18
- package/src/cli/index.ts +5 -3
- package/src/cli/new.ts +1 -1
- package/src/compiler/dom.ts +151 -37
- package/src/compiler/ssr.ts +16 -1
- package/src/plugins/index.ts +10 -0
- package/src/server/http.ts +4 -2
- package/src/server/index.ts +117 -77
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kayjs/kay",
|
|
3
|
-
"version": "2.0.0-alpha.
|
|
3
|
+
"version": "2.0.0-alpha.7",
|
|
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/compile.ts
CHANGED
|
@@ -15,10 +15,11 @@ export interface CompileExecutableOptions {
|
|
|
15
15
|
outfile: string
|
|
16
16
|
kaySrcRoot: string
|
|
17
17
|
resolveKaySpecifier: (specifier: string) => string | undefined
|
|
18
|
+
bunPlugins?: BunPlugin[] | undefined
|
|
18
19
|
}
|
|
19
20
|
|
|
20
21
|
export async function compileExecutable(opts: CompileExecutableOptions): Promise<void> {
|
|
21
|
-
const { root, outDir, clientDir, manifest, assetPrefix, outfile, kaySrcRoot, resolveKaySpecifier } = opts
|
|
22
|
+
const { root, outDir, clientDir, manifest, assetPrefix, outfile, kaySrcRoot, resolveKaySpecifier, bunPlugins = [] } = opts
|
|
22
23
|
const entryPath = join(outDir, '__compile_entry.ts')
|
|
23
24
|
const imports: string[] = []
|
|
24
25
|
const modEntries: string[] = []
|
|
@@ -81,7 +82,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
81
82
|
}
|
|
82
83
|
|
|
83
84
|
const cfgSpread = hasConfig
|
|
84
|
-
? `, plugins: _kayConfig?.plugins, lang: _kayConfig?.lang, security: _kayConfig?.security, trustedOrigins: _kayConfig?.trustedOrigins, compress: _kayConfig?.compress`
|
|
85
|
+
? `, plugins: _kayConfig?.plugins, lang: _kayConfig?.lang, security: _kayConfig?.security, trustedOrigins: _kayConfig?.trustedOrigins, compress: _kayConfig?.compress, onError: _kayConfig?.onError`
|
|
85
86
|
: ''
|
|
86
87
|
|
|
87
88
|
// Default NODE_ENV to 'production' in compiled binaries (dynamic key avoids Bun.build constant-folding).
|
|
@@ -96,10 +97,12 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
96
97
|
`const publicEtags = { ${embeddedPublicEtags.join(', ')} };`,
|
|
97
98
|
`const prerendered = {};`,
|
|
98
99
|
`const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
|
|
100
|
+
`const port = Number(process.env.PORT ?? ${hasConfig ? '_kayConfig?.port ?? ' : ''}3000);`,
|
|
101
|
+
`const hostname = process.env.HOST || undefined;`,
|
|
102
|
+
`if (Bun.argv.includes('--health')) { const r = await fetch(\`http://\${hostname ?? '127.0.0.1'}:\${port}/\`).catch(() => null); process.exit(r && r.status < 500 ? 0 : 1); }`,
|
|
99
103
|
`const app = await createServerFromEmbedded({ manifest, modules, assets, publicAssets, publicEtags, prerendered, prerenderedFiles, assetPrefix: ${JSON.stringify(assetPrefix)}${cfgSpread} });`,
|
|
100
|
-
`const
|
|
101
|
-
`
|
|
102
|
-
`console.log(\`kay server listening on http://localhost:\${server.port}\`);`,
|
|
104
|
+
`const server = app.serve(port, hostname);`,
|
|
105
|
+
`console.log(\`kay server listening on http://\${hostname ?? 'localhost'}:\${server.port}\`);`,
|
|
103
106
|
].join('\n')
|
|
104
107
|
|
|
105
108
|
writeFileSync(entryPath, code)
|
|
@@ -117,7 +120,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
117
120
|
entrypoints: [entryPath],
|
|
118
121
|
compile: { outfile },
|
|
119
122
|
minify: true,
|
|
120
|
-
plugins: [kayResolvePlugin],
|
|
123
|
+
plugins: [kayResolvePlugin, ...bunPlugins],
|
|
121
124
|
})
|
|
122
125
|
if (!res.success) {
|
|
123
126
|
const msgs = res.logs.map(l => l.message).join('\n')
|
package/src/build/index.ts
CHANGED
|
@@ -655,6 +655,41 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
655
655
|
'@kayjs/kay/test',
|
|
656
656
|
])
|
|
657
657
|
|
|
658
|
+
const reachesTsxCache = new Map<string, boolean>()
|
|
659
|
+
function reachesTsx(file: string, stack = new Set<string>()): boolean {
|
|
660
|
+
const cached = reachesTsxCache.get(file)
|
|
661
|
+
if (cached !== undefined)
|
|
662
|
+
return cached
|
|
663
|
+
if (file.endsWith('.tsx')) {
|
|
664
|
+
reachesTsxCache.set(file, true)
|
|
665
|
+
return true
|
|
666
|
+
}
|
|
667
|
+
if (stack.has(file))
|
|
668
|
+
return false
|
|
669
|
+
stack.add(file)
|
|
670
|
+
const analysis = analyses.get(file)
|
|
671
|
+
if (analysis === undefined) {
|
|
672
|
+
reachesTsxCache.set(file, false)
|
|
673
|
+
return false
|
|
674
|
+
}
|
|
675
|
+
for (const imp of analysis.imports) {
|
|
676
|
+
const target = resolveImportPath(file, imp.source)
|
|
677
|
+
if (target !== undefined && reachesTsx(target, stack)) {
|
|
678
|
+
reachesTsxCache.set(file, true)
|
|
679
|
+
return true
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
for (const re of analysis.reexports) {
|
|
683
|
+
const target = resolveImportPath(file, re.source)
|
|
684
|
+
if (target !== undefined && reachesTsx(target, stack)) {
|
|
685
|
+
reachesTsxCache.set(file, true)
|
|
686
|
+
return true
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
reachesTsxCache.set(file, false)
|
|
690
|
+
return false
|
|
691
|
+
}
|
|
692
|
+
|
|
658
693
|
const runServerBuild = async (): Promise<void> => {
|
|
659
694
|
const serverPlugin: BunPlugin = {
|
|
660
695
|
name: 'kay-v2-server',
|
|
@@ -673,28 +708,28 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
673
708
|
return undefined
|
|
674
709
|
}
|
|
675
710
|
})
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
711
|
+
b.onResolve({ filter: /^[^./]/ }, (args) => {
|
|
712
|
+
if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~') || isAbsolute(args.path))
|
|
713
|
+
return undefined
|
|
714
|
+
let resolved: string | undefined
|
|
715
|
+
try {
|
|
716
|
+
resolved = Bun.resolveSync(args.path, args.resolveDir || root)
|
|
717
|
+
}
|
|
718
|
+
catch {
|
|
681
719
|
try {
|
|
682
|
-
resolved = Bun.resolveSync(args.path,
|
|
720
|
+
resolved = Bun.resolveSync(args.path, root)
|
|
683
721
|
}
|
|
684
722
|
catch {
|
|
685
|
-
|
|
686
|
-
resolved = Bun.resolveSync(args.path, root)
|
|
687
|
-
}
|
|
688
|
-
catch {
|
|
689
|
-
return undefined
|
|
690
|
-
}
|
|
723
|
+
return undefined
|
|
691
724
|
}
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
return
|
|
696
|
-
|
|
697
|
-
|
|
725
|
+
}
|
|
726
|
+
// Bundle any package that exports/re-exports .tsx components so Kay's SSR compiler transforms them.
|
|
727
|
+
if (resolved.endsWith('.tsx') || reachesTsx(resolved))
|
|
728
|
+
return { path: resolved }
|
|
729
|
+
if (outDirOutsideRoot)
|
|
730
|
+
return { path: resolved, external: true }
|
|
731
|
+
return undefined
|
|
732
|
+
})
|
|
698
733
|
b.onLoad({ filter: /\.tsx$/ }, (args) => {
|
|
699
734
|
const analysis = analyses.get(args.path)
|
|
700
735
|
const rawBindings = pageIslandBindings.get(args.path)
|
|
@@ -1151,6 +1186,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
1151
1186
|
outfile,
|
|
1152
1187
|
kaySrcRoot: KAY_SRC_ROOT,
|
|
1153
1188
|
resolveKaySpecifier,
|
|
1189
|
+
bunPlugins: pluginBunPlugins,
|
|
1154
1190
|
})
|
|
1155
1191
|
}
|
|
1156
1192
|
|
package/src/cli/index.ts
CHANGED
|
@@ -70,10 +70,12 @@ else if (cmd === 'build') {
|
|
|
70
70
|
}
|
|
71
71
|
else if (cmd === 'start') {
|
|
72
72
|
process.env.NODE_ENV ??= 'production'
|
|
73
|
-
const
|
|
73
|
+
const config = await loadConfig(root)
|
|
74
|
+
const port = Number(flagValue('--port') || process.env.PORT || config.port || 3000)
|
|
75
|
+
const hostname = process.env.HOST || undefined
|
|
74
76
|
const app = await createServer({ root })
|
|
75
|
-
const server = app.serve(port)
|
|
76
|
-
console.log(`kay server listening on http
|
|
77
|
+
const server = app.serve(port, hostname)
|
|
78
|
+
console.log(`kay server listening on http://${hostname ?? 'localhost'}:${server.port}`)
|
|
77
79
|
}
|
|
78
80
|
else if (cmd === 'dev') {
|
|
79
81
|
const port = Number(flagValue('--port') || process.env.PORT || 3000)
|
package/src/cli/new.ts
CHANGED
|
@@ -15,7 +15,7 @@ export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}
|
|
|
15
15
|
const root = resolve(targetDir)
|
|
16
16
|
const name = basename(root).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'kay-app'
|
|
17
17
|
const template: ScaffoldTemplate = options.template ?? 'minimal'
|
|
18
|
-
const kayVersion = options.kayVersion ?? '^2.0.0-alpha.
|
|
18
|
+
const kayVersion = options.kayVersion ?? '^2.0.0-alpha.7'
|
|
19
19
|
|
|
20
20
|
if (existsSync(root) && readdirSync(root).length > 0 && !options.force)
|
|
21
21
|
throw new Error(`kay new: directory "${root}" is not empty (pass --force to overwrite)`)
|
package/src/compiler/dom.ts
CHANGED
|
@@ -195,8 +195,16 @@ function rewriteFreeIdentifiers(
|
|
|
195
195
|
visit(attr, shadowed)
|
|
196
196
|
return
|
|
197
197
|
}
|
|
198
|
+
case 'TSAsExpression':
|
|
199
|
+
case 'TSNonNullExpression':
|
|
200
|
+
case 'TSSatisfiesExpression':
|
|
201
|
+
case 'TSTypeAssertion':
|
|
202
|
+
case 'TSInstantiationExpression': {
|
|
203
|
+
visit(node.expression, shadowed)
|
|
204
|
+
return
|
|
205
|
+
}
|
|
198
206
|
default: {
|
|
199
|
-
// Skip TypeScript type nodes
|
|
207
|
+
// Skip pure TypeScript type annotation nodes
|
|
200
208
|
if (typeof node.type === 'string' && node.type.startsWith('TS'))
|
|
201
209
|
return
|
|
202
210
|
for (const key of Object.keys(node)) {
|
|
@@ -247,48 +255,152 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
247
255
|
}
|
|
248
256
|
}
|
|
249
257
|
|
|
250
|
-
function
|
|
251
|
-
|
|
258
|
+
function hasJsxDescendant(node: AstNode | null | undefined): boolean {
|
|
259
|
+
if (!node)
|
|
260
|
+
return false
|
|
261
|
+
let found = false
|
|
252
262
|
walk(node, (child) => {
|
|
253
263
|
if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
|
|
254
|
-
|
|
264
|
+
found = true
|
|
255
265
|
return false
|
|
256
266
|
}
|
|
257
267
|
return undefined
|
|
258
268
|
})
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
// Replace nested JSX roots inside this expression
|
|
263
|
-
const subCode = code.slice(node.start, node.end)
|
|
264
|
-
const offset = node.start as number
|
|
265
|
-
const sub = new SourceEditor(subCode)
|
|
269
|
+
return found
|
|
270
|
+
}
|
|
266
271
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
272
|
+
function extractBlockKeyExpr(block: AstNode): AstNode | undefined {
|
|
273
|
+
let found: AstNode | undefined
|
|
274
|
+
walk(block, (child) => {
|
|
275
|
+
if (found !== undefined)
|
|
276
|
+
return false
|
|
277
|
+
if (child.type === 'ArrowFunctionExpression' || child.type === 'FunctionExpression' || child.type === 'FunctionDeclaration')
|
|
270
278
|
return false
|
|
279
|
+
if (child.type === 'ReturnStatement' && child.argument) {
|
|
280
|
+
const arg = unwrapParens(child.argument as AstNode)
|
|
281
|
+
const k = extractKeyExpr(arg)
|
|
282
|
+
if (k !== undefined) {
|
|
283
|
+
found = k
|
|
284
|
+
return false
|
|
285
|
+
}
|
|
271
286
|
}
|
|
272
287
|
return undefined
|
|
273
288
|
})
|
|
289
|
+
return found
|
|
290
|
+
}
|
|
274
291
|
|
|
275
|
-
|
|
276
|
-
if (
|
|
277
|
-
return
|
|
278
|
-
|
|
279
|
-
//
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
292
|
+
function compileExpression(node: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
|
|
293
|
+
if (!hasJsxDescendant(node))
|
|
294
|
+
return rewriteFreeIdentifiers(code, node, scopeRewrites)
|
|
295
|
+
|
|
296
|
+
// Replace nested JSX roots AND rewrite free identifiers in all surrounding non-JSX spans (respecting shadowing)
|
|
297
|
+
const offset = node.start as number
|
|
298
|
+
const sub = new SourceEditor(code.slice(node.start, node.end))
|
|
299
|
+
|
|
300
|
+
function visitExpr(cur: AstNode | null | undefined, shadowed: Set<string>): void {
|
|
301
|
+
if (!cur || typeof cur !== 'object')
|
|
302
|
+
return
|
|
303
|
+
|
|
304
|
+
if (cur.type === 'JSXElement' || cur.type === 'JSXFragment') {
|
|
305
|
+
const activeRewrites = shadowed.size === 0
|
|
306
|
+
? scopeRewrites
|
|
307
|
+
: new Map([...scopeRewrites].filter(([k]) => !shadowed.has(k)))
|
|
308
|
+
sub.replace(cur.start - offset, cur.end - offset, compileRootJsx(cur, activeRewrites))
|
|
309
|
+
return
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
switch (cur.type) {
|
|
313
|
+
case 'Identifier': {
|
|
314
|
+
const name = cur.name as string
|
|
315
|
+
if (!shadowed.has(name)) {
|
|
316
|
+
const rep = scopeRewrites.get(name)
|
|
317
|
+
if (rep !== undefined)
|
|
318
|
+
sub.replace(cur.start - offset, cur.end - offset, rep)
|
|
319
|
+
}
|
|
320
|
+
return
|
|
321
|
+
}
|
|
322
|
+
case 'MemberExpression': {
|
|
323
|
+
visitExpr(cur.object, shadowed)
|
|
324
|
+
if (cur.computed)
|
|
325
|
+
visitExpr(cur.property, shadowed)
|
|
326
|
+
return
|
|
327
|
+
}
|
|
328
|
+
case 'Property': {
|
|
329
|
+
if (cur.computed)
|
|
330
|
+
visitExpr(cur.key, shadowed)
|
|
331
|
+
if (cur.shorthand && cur.value?.type === 'Identifier') {
|
|
332
|
+
const name = cur.value.name as string
|
|
333
|
+
if (!shadowed.has(name) && scopeRewrites.has(name)) {
|
|
334
|
+
sub.replace(cur.start - offset, cur.end - offset, `${name}: ${scopeRewrites.get(name)}`)
|
|
335
|
+
return
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
visitExpr(cur.value, shadowed)
|
|
339
|
+
return
|
|
340
|
+
}
|
|
341
|
+
case 'ArrowFunctionExpression':
|
|
342
|
+
case 'FunctionExpression':
|
|
343
|
+
case 'FunctionDeclaration': {
|
|
344
|
+
const nextShadow = new Set(shadowed)
|
|
345
|
+
if (cur.id?.name)
|
|
346
|
+
nextShadow.add(cur.id.name as string)
|
|
347
|
+
for (const p of cur.params as AstNode[])
|
|
348
|
+
collectPatternNames(p, nextShadow)
|
|
349
|
+
visitExpr(cur.body, nextShadow)
|
|
350
|
+
return
|
|
351
|
+
}
|
|
352
|
+
case 'BlockStatement': {
|
|
353
|
+
const nextShadow = new Set(shadowed)
|
|
354
|
+
for (const stmt of cur.body as AstNode[]) {
|
|
355
|
+
if (stmt.type === 'VariableDeclaration') {
|
|
356
|
+
for (const d of stmt.declarations as AstNode[]) {
|
|
357
|
+
visitExpr(d.init, nextShadow)
|
|
358
|
+
collectPatternNames(d.id, nextShadow)
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
else if (stmt.type === 'FunctionDeclaration') {
|
|
362
|
+
if (stmt.id?.name)
|
|
363
|
+
nextShadow.add(stmt.id.name as string)
|
|
364
|
+
visitExpr(stmt, nextShadow)
|
|
365
|
+
}
|
|
366
|
+
else {
|
|
367
|
+
visitExpr(stmt, nextShadow)
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return
|
|
371
|
+
}
|
|
372
|
+
case 'VariableDeclarator': {
|
|
373
|
+
visitExpr(cur.init, shadowed)
|
|
374
|
+
return
|
|
375
|
+
}
|
|
376
|
+
case 'TSAsExpression':
|
|
377
|
+
case 'TSNonNullExpression':
|
|
378
|
+
case 'TSSatisfiesExpression':
|
|
379
|
+
case 'TSTypeAssertion':
|
|
380
|
+
case 'TSInstantiationExpression': {
|
|
381
|
+
visitExpr(cur.expression, shadowed)
|
|
382
|
+
return
|
|
383
|
+
}
|
|
384
|
+
default: {
|
|
385
|
+
if (typeof cur.type === 'string' && cur.type.startsWith('TS'))
|
|
386
|
+
return
|
|
387
|
+
for (const key of Object.keys(cur)) {
|
|
388
|
+
if (key === 'start' || key === 'end' || key === 'type')
|
|
389
|
+
continue
|
|
390
|
+
const val = cur[key]
|
|
391
|
+
if (Array.isArray(val)) {
|
|
392
|
+
for (let i = 0; i < val.length; i++)
|
|
393
|
+
visitExpr(val[i] as AstNode, shadowed)
|
|
394
|
+
}
|
|
395
|
+
else if (val !== null && typeof val === 'object') {
|
|
396
|
+
visitExpr(val as AstNode, shadowed)
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
291
401
|
}
|
|
402
|
+
|
|
403
|
+
visitExpr(node, new Set())
|
|
292
404
|
return sub.toString()
|
|
293
405
|
}
|
|
294
406
|
|
|
@@ -563,7 +675,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
563
675
|
if (child.type === 'JSXExpressionContainer') {
|
|
564
676
|
const expr = child.expression as AstNode
|
|
565
677
|
|
|
566
|
-
// Case 1: Keyed `.map((item, idx?) => <jsx>)` → `__loop(...)`
|
|
678
|
+
// Case 1: Keyed `.map((item, idx?) => <jsx> | { ... return <jsx> })` → `__loop(...)`
|
|
567
679
|
if (
|
|
568
680
|
expr.type === 'CallExpression'
|
|
569
681
|
&& expr.callee?.type === 'MemberExpression'
|
|
@@ -573,9 +685,11 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
573
685
|
) {
|
|
574
686
|
const cb = expr.arguments[0] as AstNode
|
|
575
687
|
const cbBody = cb.body?.type === 'ParenthesizedExpression' ? cb.body.expression : cb.body
|
|
688
|
+
const isJsxBody = cbBody?.type === 'JSXElement' || cbBody?.type === 'JSXFragment'
|
|
689
|
+
const isBlockJsxBody = cbBody?.type === 'BlockStatement' && hasJsxDescendant(cbBody)
|
|
576
690
|
if (
|
|
577
691
|
(cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression')
|
|
578
|
-
&& (
|
|
692
|
+
&& (isJsxBody || isBlockJsxBody)
|
|
579
693
|
) {
|
|
580
694
|
const loopSkip = domIndex
|
|
581
695
|
const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
|
|
@@ -601,12 +715,12 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
601
715
|
for (const n of names)
|
|
602
716
|
shadowed.delete(n)
|
|
603
717
|
}
|
|
604
|
-
const rowBody = compileRootJsx(cbBody, shadowed)
|
|
718
|
+
const rowBody = isJsxBody ? compileRootJsx(cbBody, shadowed) : compileExpression(cbBody, shadowed)
|
|
605
719
|
ops.push(`${use('eachStatic')}(${elVar}, ${anchorVar}, ${eachCode}, (${rawParams}) => ${rowBody}${skipArg});`)
|
|
606
720
|
continue
|
|
607
721
|
}
|
|
608
722
|
|
|
609
|
-
const keyAst = extractKeyExpr(cbBody)
|
|
723
|
+
const keyAst = isJsxBody ? extractKeyExpr(cbBody) : extractBlockKeyExpr(cbBody)
|
|
610
724
|
|
|
611
725
|
const rowSig = freshVar('_r')
|
|
612
726
|
const idxSig = idxParam !== undefined ? freshVar('_i') : undefined
|
|
@@ -649,7 +763,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
649
763
|
if (idxParam !== undefined && idxSig !== undefined)
|
|
650
764
|
rowRewrites.set(idxParam, `${idxSig}.value`)
|
|
651
765
|
|
|
652
|
-
const rowBody = compileRootJsx(cbBody, rowRewrites)
|
|
766
|
+
const rowBody = isJsxBody ? compileRootJsx(cbBody, rowRewrites) : compileExpression(cbBody, rowRewrites)
|
|
653
767
|
const rowParams = idxSig !== undefined ? `${rowSig}, ${idxSig}` : rowSig
|
|
654
768
|
ops.push(`${use('loop')}(${elVar}, ${anchorVar}, () => ${eachCode}, ${keyFn}, (${rowParams}) => ${rowBody}${skipArg});`)
|
|
655
769
|
continue
|
|
@@ -694,11 +808,11 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
694
808
|
}
|
|
695
809
|
}
|
|
696
810
|
|
|
697
|
-
// Case 4: Dynamic children slot / Node insertion (`{children}
|
|
811
|
+
// Case 4: Dynamic children slot / Node insertion (`{children}`, `{props.children}`, or any expression containing JSX)
|
|
698
812
|
const isChildrenExpr = (expr.type === 'Identifier' && expr.name === 'children')
|
|
699
813
|
|| (expr.type === 'MemberExpression' && !expr.computed && expr.property?.name === 'children')
|
|
700
814
|
const exprCode = compileExpression(expr, scopeRewrites)
|
|
701
|
-
if (isChildrenExpr) {
|
|
815
|
+
if (isChildrenExpr || hasJsxDescendant(expr)) {
|
|
702
816
|
const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
|
|
703
817
|
if (!isLast) {
|
|
704
818
|
html += '<!---->'
|
package/src/compiler/ssr.ts
CHANGED
|
@@ -388,7 +388,22 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
388
388
|
if (body.type === 'JSXElement' || body.type === 'JSXFragment') {
|
|
389
389
|
const target = compileSubExpression(expr.callee.object)
|
|
390
390
|
const params = (cb.params as AstNode[]).map(p => code.slice(p.start, p.end)).join(', ')
|
|
391
|
-
|
|
391
|
+
const rendered = `${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(body)})`
|
|
392
|
+
return isIsland && !isLast ? `(${rendered}) + "<!---->"` : rendered
|
|
393
|
+
}
|
|
394
|
+
if (body.type === 'BlockStatement') {
|
|
395
|
+
let blockHasJsx = false
|
|
396
|
+
walk(body, (c) => {
|
|
397
|
+
if (c.type === 'JSXElement' || c.type === 'JSXFragment') {
|
|
398
|
+
blockHasJsx = true
|
|
399
|
+
return false
|
|
400
|
+
}
|
|
401
|
+
return undefined
|
|
402
|
+
})
|
|
403
|
+
if (blockHasJsx) {
|
|
404
|
+
const rendered = `${use('esc')}(${compileSubExpression(expr)})`
|
|
405
|
+
return isIsland && !isLast ? `(${rendered}) + "<!---->"` : rendered
|
|
406
|
+
}
|
|
392
407
|
}
|
|
393
408
|
}
|
|
394
409
|
}
|
package/src/plugins/index.ts
CHANGED
|
@@ -45,10 +45,18 @@ export interface ServerPluginAPI {
|
|
|
45
45
|
rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
export interface ServerErrorInfo {
|
|
49
|
+
error: unknown
|
|
50
|
+
request: Request
|
|
51
|
+
source: 'route' | 'action' | 'plugin'
|
|
52
|
+
}
|
|
53
|
+
|
|
48
54
|
export interface KayPlugin {
|
|
49
55
|
name: string
|
|
50
56
|
/** Register server routes, global middleware, or URL rewrites. */
|
|
51
57
|
server?: (api: ServerPluginAPI) => void | Promise<void>
|
|
58
|
+
/** Error hook called whenever a route, action, or plugin handler throws an unhandled error. */
|
|
59
|
+
onError?: (info: ServerErrorInfo) => void
|
|
52
60
|
/** Build hook run after route compilation, before prerender / --static / --compile. */
|
|
53
61
|
build?: (ctx: BuildPluginContext) => void | Promise<void>
|
|
54
62
|
/** Code transform run during client & server compilation. */
|
|
@@ -73,6 +81,7 @@ export interface KayPlugin {
|
|
|
73
81
|
|
|
74
82
|
export interface KayConfig {
|
|
75
83
|
lang?: string | undefined
|
|
84
|
+
port?: number | undefined
|
|
76
85
|
routesDir?: string | undefined
|
|
77
86
|
outDir?: string | undefined
|
|
78
87
|
publicDir?: string | undefined
|
|
@@ -80,6 +89,7 @@ export interface KayConfig {
|
|
|
80
89
|
security?: SecurityHeadersOptions | false | undefined
|
|
81
90
|
trustedOrigins?: string[] | undefined
|
|
82
91
|
compress?: boolean | undefined
|
|
92
|
+
onError?: ((info: ServerErrorInfo) => void) | undefined
|
|
83
93
|
plugins?: KayPlugin[] | undefined
|
|
84
94
|
}
|
|
85
95
|
|
package/src/server/http.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// HTTP helpers, MIME table, RequestContext factory, and island tag scanner for Kay v2 server.
|
|
2
2
|
|
|
3
3
|
import type { BuildManifest } from '../build/index'
|
|
4
|
-
import type { KayPlugin } from '../plugins/index'
|
|
4
|
+
import type { KayPlugin, ServerErrorInfo } from '../plugins/index'
|
|
5
5
|
import type { Cookies } from './cookies'
|
|
6
6
|
import type { SecurityHeadersOptions } from './security'
|
|
7
7
|
import { CookieStore } from './cookies'
|
|
@@ -16,6 +16,7 @@ export interface ServerOptions {
|
|
|
16
16
|
security?: SecurityHeadersOptions | false | undefined
|
|
17
17
|
trustedOrigins?: string[] | undefined
|
|
18
18
|
compress?: boolean | undefined
|
|
19
|
+
onError?: ((info: ServerErrorInfo) => void) | undefined
|
|
19
20
|
plugins?: KayPlugin[] | undefined
|
|
20
21
|
}
|
|
21
22
|
|
|
@@ -35,7 +36,7 @@ export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) =>
|
|
|
35
36
|
|
|
36
37
|
export interface KayApp {
|
|
37
38
|
handle: (request: Request) => Promise<Response>
|
|
38
|
-
serve: (port?: number) => ReturnType<typeof Bun.serve>
|
|
39
|
+
serve: (port?: number, hostname?: string) => ReturnType<typeof Bun.serve>
|
|
39
40
|
}
|
|
40
41
|
|
|
41
42
|
export type EmbeddedBody = Uint8Array<ArrayBuffer> | string
|
|
@@ -53,6 +54,7 @@ export interface EmbeddedServerConfig {
|
|
|
53
54
|
security?: SecurityHeadersOptions | false | undefined
|
|
54
55
|
trustedOrigins?: string[] | undefined
|
|
55
56
|
compress?: boolean | undefined
|
|
57
|
+
onError?: ((info: ServerErrorInfo) => void) | undefined
|
|
56
58
|
plugins?: KayPlugin[] | undefined
|
|
57
59
|
}
|
|
58
60
|
|
package/src/server/index.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
import type { BuildManifest, RouteManifestEntry } from '../build/index'
|
|
9
9
|
import type { Html, HydrateStrategy } from '../jsx-runtime'
|
|
10
|
-
import type { KayPlugin, ServerPluginAPI } from '../plugins/index'
|
|
10
|
+
import type { KayPlugin, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
|
|
11
11
|
import type { ActionContext, ServerAction } from './action'
|
|
12
12
|
import type { CookieStore } from './cookies'
|
|
13
13
|
import type { EmbeddedBody, EmbeddedServerConfig, KayApp, Middleware, RequestContext, ServerOptions } from './http'
|
|
@@ -24,7 +24,7 @@ import { Router } from './router'
|
|
|
24
24
|
import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, withCspHashes } from './security'
|
|
25
25
|
|
|
26
26
|
export { defineConfig, definePlugin, loadConfig } from '../plugins/index'
|
|
27
|
-
export type { BuildPluginContext, CheckPluginContext, KayConfig, KayPlugin, ServerPluginAPI } from '../plugins/index'
|
|
27
|
+
export type { BuildPluginContext, CheckPluginContext, KayConfig, KayPlugin, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
|
|
28
28
|
export { action, getActionError } from './action'
|
|
29
29
|
export type { ActionContext, ActionErrorFlash, ActionResult, ServerAction } from './action'
|
|
30
30
|
export { CompressionCache, isCompressibleType, pickEncoding } from './compress'
|
|
@@ -174,6 +174,21 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
174
174
|
}
|
|
175
175
|
|
|
176
176
|
const toResponseBody = (body: EmbeddedBody) => typeof body === 'string' ? Bun.file(body) : body
|
|
177
|
+
const errorHooks: ((info: ServerErrorInfo) => void)[] = []
|
|
178
|
+
if (config.onError !== undefined)
|
|
179
|
+
errorHooks.push(config.onError)
|
|
180
|
+
for (const p of plugins) {
|
|
181
|
+
if (p.onError !== undefined)
|
|
182
|
+
errorHooks.push(p.onError)
|
|
183
|
+
}
|
|
184
|
+
const notifyError = (error: unknown, request: Request, source: ServerErrorInfo['source']) => {
|
|
185
|
+
for (let i = 0; i < errorHooks.length; i++) {
|
|
186
|
+
try {
|
|
187
|
+
errorHooks[i]!({ error, request, source })
|
|
188
|
+
}
|
|
189
|
+
catch {}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
177
192
|
|
|
178
193
|
async function serveAsset(request: Request, pathname: string, asset: AssetEntry): Promise<Response> {
|
|
179
194
|
if (request.method === 'HEAD')
|
|
@@ -367,70 +382,80 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
367
382
|
const fastHeaders = selectHtmlHeaders(hasIslands, false)
|
|
368
383
|
|
|
369
384
|
fastHandler = (request: Request): Response | Promise<Response> => {
|
|
370
|
-
const
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
const wrapLayouts = (inner: string): Response | Promise<Response> => {
|
|
375
|
-
if (layouts.length === 0)
|
|
376
|
-
return respondHtml(inner)
|
|
377
|
-
if (singleLayout !== undefined) {
|
|
378
|
-
const w = singleLayout.default({ children: raw(inner), url: reqUrl, params: {}, locals: {} })
|
|
379
|
-
if (w instanceof Promise)
|
|
380
|
-
return w.then(x => respondHtml(ssrChild(x as Html)))
|
|
381
|
-
return respondHtml(ssrChild(w as Html))
|
|
382
|
-
}
|
|
383
|
-
return (async () => {
|
|
384
|
-
let cur = inner
|
|
385
|
-
for (let i = layouts.length - 1; i >= 0; i--)
|
|
386
|
-
cur = ssrChild(await layouts[i]!.default({ children: raw(cur), url: reqUrl, params: {}, locals: {} }) as Html)
|
|
387
|
-
return respondHtml(cur)
|
|
388
|
-
})()
|
|
385
|
+
const handleErr = (error: unknown): Promise<Response> => {
|
|
386
|
+
notifyError(error, request, 'route')
|
|
387
|
+
return renderError(error, makeRequestContext(request, {}).cookieStore, new URL(request.url))
|
|
389
388
|
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
const
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
(
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
389
|
+
try {
|
|
390
|
+
const reqUrl = new URL(request.url)
|
|
391
|
+
const respondHtml = (body: string): Response =>
|
|
392
|
+
compressedHtmlResponse(docPrefix + body + docSuffix, 200, fastHeaders, request, compressCache)
|
|
393
|
+
|
|
394
|
+
const wrapLayouts = (inner: string): Response | Promise<Response> => {
|
|
395
|
+
if (layouts.length === 0)
|
|
396
|
+
return respondHtml(inner)
|
|
397
|
+
if (singleLayout !== undefined) {
|
|
398
|
+
const w = singleLayout.default({ children: raw(inner), url: reqUrl, params: {}, locals: {} })
|
|
399
|
+
if (w instanceof Promise)
|
|
400
|
+
return w.then(x => respondHtml(ssrChild(x as Html)), handleErr)
|
|
401
|
+
return respondHtml(ssrChild(w as Html))
|
|
402
|
+
}
|
|
403
|
+
return (async () => {
|
|
404
|
+
let cur = inner
|
|
405
|
+
for (let i = layouts.length - 1; i >= 0; i--)
|
|
406
|
+
cur = ssrChild(await layouts[i]!.default({ children: raw(cur), url: reqUrl, params: {}, locals: {} }) as Html)
|
|
407
|
+
return respondHtml(cur)
|
|
408
|
+
})().catch(handleErr)
|
|
407
409
|
}
|
|
408
|
-
const rendered = mod.default!(pageProps)
|
|
409
|
-
if (rendered instanceof Promise)
|
|
410
|
-
return rendered.then(r => wrapLayouts(ssrChild(r as Html)))
|
|
411
|
-
return wrapLayouts(ssrChild(rendered as Html))
|
|
412
|
-
}
|
|
413
410
|
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
411
|
+
const renderPage = (data: unknown): Response | Promise<Response> => {
|
|
412
|
+
const pageProps: Record<string, unknown> = {
|
|
413
|
+
params: {},
|
|
414
|
+
locals: {},
|
|
415
|
+
url: reqUrl,
|
|
416
|
+
...(data !== undefined ? { data } : {}),
|
|
417
|
+
}
|
|
418
|
+
if (entry.isIsland && entry.islandChunk !== undefined) {
|
|
419
|
+
const inner = ssrIsland(
|
|
420
|
+
entry.path,
|
|
421
|
+
entry.islandChunk,
|
|
422
|
+
() => ssrChild(mod.default!(pageProps) as Html),
|
|
423
|
+
data !== undefined ? { data } : {},
|
|
424
|
+
entry.islandHydrate as HydrateStrategy | undefined,
|
|
425
|
+
)
|
|
426
|
+
return wrapLayouts(inner)
|
|
427
|
+
}
|
|
428
|
+
const rendered = mod.default!(pageProps)
|
|
429
|
+
if (rendered instanceof Promise)
|
|
430
|
+
return rendered.then(r => wrapLayouts(ssrChild(r as Html)), handleErr)
|
|
431
|
+
return wrapLayouts(ssrChild(rendered as Html))
|
|
422
432
|
}
|
|
423
|
-
|
|
424
|
-
if (
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
433
|
+
|
|
434
|
+
if (entry.hasLoad && typeof mod.load === 'function') {
|
|
435
|
+
const { ctx, cookieStore } = makeRequestContext(request, {})
|
|
436
|
+
const finish = (res: Response | Promise<Response>): Response | Promise<Response> => {
|
|
437
|
+
if (!cookieStore.hasChanges)
|
|
438
|
+
return res
|
|
439
|
+
if (res instanceof Promise)
|
|
440
|
+
return res.then(r => finalizeResponse(r, cookieStore, securityEntries), handleErr)
|
|
441
|
+
return finalizeResponse(res, cookieStore, securityEntries)
|
|
442
|
+
}
|
|
443
|
+
const loaded = mod.load(ctx)
|
|
444
|
+
if (loaded instanceof Promise) {
|
|
445
|
+
return loaded.then(
|
|
446
|
+
data => finish(data instanceof Response ? data : renderPage(data)),
|
|
447
|
+
handleErr,
|
|
448
|
+
)
|
|
449
|
+
}
|
|
450
|
+
if (loaded instanceof Response)
|
|
451
|
+
return finish(loaded)
|
|
452
|
+
return finish(renderPage(loaded))
|
|
428
453
|
}
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
454
|
+
return renderPage(undefined)
|
|
455
|
+
}
|
|
456
|
+
catch (error) {
|
|
457
|
+
return handleErr(error)
|
|
432
458
|
}
|
|
433
|
-
return renderPage(undefined)
|
|
434
459
|
}
|
|
435
460
|
fastStaticPages.set(entry.path, fastHandler)
|
|
436
461
|
}
|
|
@@ -634,8 +659,14 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
634
659
|
return globalMiddlewares[i]!(ctx, () => dispatch(i + 1))
|
|
635
660
|
return runAction()
|
|
636
661
|
}
|
|
637
|
-
|
|
638
|
-
|
|
662
|
+
try {
|
|
663
|
+
const res = await dispatch(0)
|
|
664
|
+
return finalizeResponse(res, cookieStore, securityEntries)
|
|
665
|
+
}
|
|
666
|
+
catch (error) {
|
|
667
|
+
notifyError(error, request, 'action')
|
|
668
|
+
return renderError(error, cookieStore, ctx.url)
|
|
669
|
+
}
|
|
639
670
|
}
|
|
640
671
|
}
|
|
641
672
|
|
|
@@ -686,22 +717,28 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
686
717
|
if (methodHandler !== undefined) {
|
|
687
718
|
ctx.params = pluginMatch.params
|
|
688
719
|
let res: Response
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
else {
|
|
693
|
-
let index = -1
|
|
694
|
-
const dispatch = async (i: number): Promise<Response> => {
|
|
695
|
-
if (i <= index)
|
|
696
|
-
throw new Error('kay: middleware called next() multiple times')
|
|
697
|
-
index = i
|
|
698
|
-
if (i < globalMiddlewares.length)
|
|
699
|
-
return globalMiddlewares[i]!(ctx, () => dispatch(i + 1))
|
|
700
|
-
return methodHandler(ctx)
|
|
720
|
+
try {
|
|
721
|
+
if (globalMiddlewares.length === 0) {
|
|
722
|
+
res = await methodHandler(ctx)
|
|
701
723
|
}
|
|
702
|
-
|
|
724
|
+
else {
|
|
725
|
+
let index = -1
|
|
726
|
+
const dispatch = async (i: number): Promise<Response> => {
|
|
727
|
+
if (i <= index)
|
|
728
|
+
throw new Error('kay: middleware called next() multiple times')
|
|
729
|
+
index = i
|
|
730
|
+
if (i < globalMiddlewares.length)
|
|
731
|
+
return globalMiddlewares[i]!(ctx, () => dispatch(i + 1))
|
|
732
|
+
return methodHandler(ctx)
|
|
733
|
+
}
|
|
734
|
+
res = await dispatch(0)
|
|
735
|
+
}
|
|
736
|
+
return finalizeResponse(await maybeCompressResponse(res, request, compressCache), cookieStore, securityEntries)
|
|
737
|
+
}
|
|
738
|
+
catch (error) {
|
|
739
|
+
notifyError(error, request, 'plugin')
|
|
740
|
+
return renderError(error, cookieStore, ctx.url)
|
|
703
741
|
}
|
|
704
|
-
return finalizeResponse(await maybeCompressResponse(res, request, compressCache), cookieStore, securityEntries)
|
|
705
742
|
}
|
|
706
743
|
}
|
|
707
744
|
|
|
@@ -729,11 +766,12 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
729
766
|
return finalizeResponse(res, cookieStore, securityEntries)
|
|
730
767
|
}
|
|
731
768
|
catch (error) {
|
|
769
|
+
notifyError(error, request, 'route')
|
|
732
770
|
return renderError(error, cookieStore, ctx.url)
|
|
733
771
|
}
|
|
734
772
|
}
|
|
735
773
|
|
|
736
|
-
function serve(port = 3000) {
|
|
774
|
+
function serve(port = 3000, hostname?: string) {
|
|
737
775
|
const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
|
|
738
776
|
|
|
739
777
|
for (const [path, asset] of assetMap)
|
|
@@ -762,6 +800,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
762
800
|
|
|
763
801
|
return Bun.serve({
|
|
764
802
|
port,
|
|
803
|
+
...(hostname ? { hostname } : {}),
|
|
765
804
|
idleTimeout: 0,
|
|
766
805
|
routes,
|
|
767
806
|
fetch: handle,
|
|
@@ -934,6 +973,7 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
|
934
973
|
security: options.security ?? fileConfig.security,
|
|
935
974
|
trustedOrigins: options.trustedOrigins ?? fileConfig.trustedOrigins,
|
|
936
975
|
compress: options.compress ?? fileConfig.compress,
|
|
976
|
+
onError: options.onError ?? fileConfig.onError,
|
|
937
977
|
plugins,
|
|
938
978
|
})
|
|
939
979
|
}
|