@kayjs/kay 2.0.0-beta.2 → 2.0.0-beta.4

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.
Files changed (101) hide show
  1. package/llms.txt +42 -0
  2. package/package.json +24 -13
  3. package/src/build/bundle.ts +15 -53
  4. package/src/build/client-plugin.ts +108 -0
  5. package/src/build/compile.ts +9 -44
  6. package/src/build/graph.ts +16 -3
  7. package/src/build/index.ts +45 -25
  8. package/src/build/islands.ts +28 -30
  9. package/src/build/manifest.ts +9 -4
  10. package/src/build/prerender.ts +15 -7
  11. package/src/build/report.ts +82 -13
  12. package/src/build/resolve.ts +6 -7
  13. package/src/build/routes.ts +12 -21
  14. package/src/build/server-entry.ts +38 -0
  15. package/src/cli/check.ts +49 -43
  16. package/src/cli/commands.ts +224 -0
  17. package/src/cli/index.ts +46 -302
  18. package/src/cli/new.ts +15 -509
  19. package/src/cli/upgrade-plugins.ts +168 -0
  20. package/src/cli/upgrade.ts +220 -0
  21. package/src/compiler/analyze.ts +319 -565
  22. package/src/compiler/ast.ts +39 -0
  23. package/src/compiler/data-keys.ts +233 -0
  24. package/src/compiler/dom.ts +18 -15
  25. package/src/compiler/interactivity.ts +174 -0
  26. package/src/compiler/mistakes.ts +19 -1
  27. package/src/compiler/server-only.ts +4 -1
  28. package/src/compiler/shared.ts +1 -1
  29. package/src/compiler/ssr.ts +28 -28
  30. package/src/context.ts +1 -1
  31. package/src/dev/index.ts +19 -46
  32. package/src/dom/extras.ts +43 -12
  33. package/src/dom/index.ts +25 -1
  34. package/src/index.ts +0 -13
  35. package/src/jsx-runtime.ts +1 -1
  36. package/src/plugins/config.ts +49 -0
  37. package/src/plugins/context.ts +8 -28
  38. package/src/plugins/index.ts +10 -385
  39. package/src/plugins/load.ts +61 -0
  40. package/src/plugins/order.ts +107 -0
  41. package/src/plugins/public.ts +6 -0
  42. package/src/plugins/services.ts +35 -0
  43. package/src/plugins/types.ts +193 -0
  44. package/src/server/action-registry.ts +78 -0
  45. package/src/server/action.ts +8 -2
  46. package/src/server/app-entry.ts +23 -0
  47. package/src/server/assets.ts +182 -0
  48. package/src/server/document.ts +204 -0
  49. package/src/server/errors.ts +125 -0
  50. package/src/server/http.ts +14 -0
  51. package/src/server/index.ts +66 -766
  52. package/src/server/lifecycle.ts +22 -0
  53. package/src/server/loader.ts +60 -85
  54. package/src/server/page.ts +107 -0
  55. package/src/server/plugin-host.ts +165 -0
  56. package/src/server/public.ts +15 -0
  57. package/src/server/request-scope.ts +22 -0
  58. package/src/server/security.ts +40 -1
  59. package/src/server/static-dir.ts +22 -3
  60. package/src/server/stream.ts +95 -0
  61. package/src/ssr/context.ts +25 -0
  62. package/src/ssr/index.ts +10 -7
  63. package/src/test/browser.ts +180 -0
  64. package/src/test/index.ts +25 -6
  65. package/templates/_shared/AGENTS.md +5 -0
  66. package/templates/_shared/CLAUDE.md +1 -0
  67. package/templates/_shared/public/robots.txt +2 -0
  68. package/templates/_shared/tsconfig.json +19 -0
  69. package/templates/app/.env.example +4 -0
  70. package/templates/app/kay.config.ts +11 -0
  71. package/templates/app/package.json +20 -0
  72. package/templates/app/src/auth.ts +14 -0
  73. package/templates/app/src/routes/_layout.tsx +32 -0
  74. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  75. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  76. package/templates/app/src/routes/index.tsx +15 -0
  77. package/templates/app/src/routes/login.tsx +34 -0
  78. package/templates/app/src/styles/app.css +7 -0
  79. package/templates/blog/content/posts/welcome.md +9 -0
  80. package/templates/blog/kay.config.ts +23 -0
  81. package/templates/blog/package.json +21 -0
  82. package/templates/blog/src/posts.ts +26 -0
  83. package/templates/blog/src/routes/_layout.tsx +20 -0
  84. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  85. package/templates/blog/src/routes/index.tsx +29 -0
  86. package/templates/blog/src/styles/app.css +10 -0
  87. package/templates/fullstack/kay.config.ts +6 -0
  88. package/templates/fullstack/package.json +18 -0
  89. package/templates/fullstack/src/actions/greet.ts +19 -0
  90. package/templates/fullstack/src/components/Counter.tsx +10 -0
  91. package/templates/fullstack/src/components/GreetForm.tsx +26 -0
  92. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  93. package/templates/fullstack/src/routes/api/health.ts +5 -0
  94. package/templates/fullstack/src/routes/index.tsx +13 -0
  95. package/templates/fullstack/src/styles/app.css +29 -0
  96. package/templates/minimal/kay.config.ts +6 -0
  97. package/templates/minimal/package.json +18 -0
  98. package/templates/minimal/src/components/Counter.tsx +10 -0
  99. package/templates/minimal/src/routes/_layout.tsx +14 -0
  100. package/templates/minimal/src/routes/index.tsx +11 -0
  101. package/templates/minimal/src/styles/app.css +22 -0
@@ -0,0 +1,22 @@
1
+ // Graceful stop for `kay start` and compiled binaries; `kay dev` keeps its own.
2
+
3
+ import type { KayApp } from './http'
4
+
5
+ const SIGNALS = ['SIGTERM', 'SIGINT', 'SIGHUP'] as const
6
+
7
+ // On the first signal the server stops taking connections and the app's onShutdown hooks run; the process exits 0 once the open requests finish, or 1 after `timeoutMs`, which closes what is left.
8
+ export function handleSignals(app: KayApp, server: ReturnType<KayApp['serve']>, { timeoutMs = 10_000 } = {}): void {
9
+ const stop = async (): Promise<void> => {
10
+ const forced = setTimeout(() => {
11
+ console.error(`kay: requests still open after ${timeoutMs} ms; closing them`)
12
+ process.exit(1)
13
+ }, timeoutMs)
14
+ const drained = server.stop()
15
+ await app.dispose?.()
16
+ await drained
17
+ clearTimeout(forced)
18
+ process.exit(0)
19
+ }
20
+ for (const signal of SIGNALS)
21
+ process.once(signal, () => void stop())
22
+ }
@@ -1,81 +1,34 @@
1
- // Filesystem server loader: reads `dist/manifest.json` (or falls back to `--static` dir server) and loads built modules.
1
+ // Filesystem server loader: reads `dist/manifest.json`, maps the built assets on disk, and starts the app from `dist/server/_entry.js` (or serves a `--static` dir).
2
2
 
3
3
  import type { BuildManifest } from '../build/index'
4
- import type { KayConfig } from '../plugins/index'
4
+ import type { ServerEntry } from './app-entry'
5
5
  import type { EmbeddedBody, KayApp, ServerOptions } from './http'
6
6
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
7
7
  import { join, resolve } from 'node:path'
8
+ import { SERVER_ENTRY_FILE } from '../build/server-entry'
8
9
  import { loadConfig, resolveServerConfig } from '../plugins/index'
9
- import { createServerFromEmbedded } from './index'
10
10
  import { createStaticDirServer } from './static-dir'
11
11
 
12
12
  let serverLoadSeq = 0
13
13
 
14
14
  export async function createServer(options: ServerOptions): Promise<KayApp> {
15
- const root = resolve(options.root)
16
- const loadStamp = `${Date.now()}-${++serverLoadSeq}`
17
- const importModule = options.importModule ?? ((path: string) => import(`${path}?v=${loadStamp}`))
18
- const isDev = options.dev ?? (process.env.KAY_DEV === '1')
19
-
20
- // When a bundled `manifest.configFile` exists and plugins were not explicitly overridden,
21
- // load the bundled config module so it shares the exact same chunk instances as routes & actions.
22
- const initialOutDir = resolve(root, options.outDir ?? 'dist')
23
- const initialManifestPath = join(initialOutDir, 'manifest.json')
24
- let fileConfig: KayConfig
25
- let outDir: string
26
- let manifest: BuildManifest
27
-
28
- if (options.plugins === undefined && existsSync(initialManifestPath)) {
29
- outDir = initialOutDir
30
- manifest = JSON.parse(readFileSync(initialManifestPath, 'utf8')) as BuildManifest
31
- if (manifest.configFile !== undefined) {
32
- const cfgMod = await importModule(join(outDir, manifest.configFile))
33
- const loaded = (cfgMod.default ?? cfgMod) as KayConfig | undefined
34
- fileConfig = loaded !== undefined && typeof loaded === 'object' ? loaded : {}
35
- }
36
- else {
37
- fileConfig = await loadConfig(root)
38
- }
39
- }
40
- else {
41
- fileConfig = await loadConfig(root)
42
- outDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
43
- const manifestPath = join(outDir, 'manifest.json')
44
- if (!existsSync(manifestPath)) {
45
- const securityOpt = options.security ?? fileConfig.security
46
- const trustProxy = options.trustProxy ?? fileConfig.trustProxy ?? false
47
- if (existsSync(outDir) && readdirSync(outDir).length > 0) {
48
- return createStaticDirServer(
49
- outDir,
50
- options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay',
51
- securityOpt,
52
- (options.compress ?? fileConfig.compress) !== false,
53
- trustProxy,
54
- isDev,
55
- )
56
- }
57
- throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
58
- }
59
- manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
60
- if (options.plugins === undefined && manifest.configFile !== undefined) {
61
- const cfgMod = await importModule(join(outDir, manifest.configFile))
62
- const loaded = (cfgMod.default ?? cfgMod) as KayConfig | undefined
63
- if (loaded !== undefined && typeof loaded === 'object')
64
- fileConfig = loaded
65
- }
66
- }
15
+ return (await startBuiltApp(options)).app
16
+ }
67
17
 
68
- const runtimeConfig = resolveServerConfig(fileConfig, options)
18
+ /** The app and the entry it was assembled from, whose bundled modules `testApp().import()` and the prerender step read. */
19
+ export async function startBuiltApp(options: ServerOptions): Promise<{ app: KayApp, entry?: ServerEntry | undefined }> {
20
+ const built = await loadServerEntry(options)
21
+ if (built.entry === undefined)
22
+ return { app: await serveStaticDir(options, built.root, built.outDir) }
23
+ const { root, outDir, manifest, entry } = built
69
24
  const clientDir = join(outDir, 'client')
70
-
71
- const modules: Record<string, unknown> = {}
72
25
  const assets: Record<string, EmbeddedBody> = {}
73
26
  const publicAssets: Record<string, EmbeddedBody> = {}
74
27
  const publicEtags: Record<string, string> = {}
75
28
  const prerenderedFiles: Record<string, string> = {}
76
- const srcPublicDir = resolve(root, fileConfig.publicDir ?? 'public')
29
+ const srcPublicDir = resolve(root, entry.kayConfig.publicDir ?? 'public')
77
30
 
78
- // Store file paths only (zero-copy Bun.file() serving, zero startup RAM bloat!)
31
+ // File paths only: Bun.file() serves them zero-copy, and nothing is read at startup.
79
32
  for (const rel of manifest.assets) {
80
33
  const abs = join(clientDir, rel)
81
34
  if (existsSync(abs)) {
@@ -97,35 +50,17 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
97
50
  }
98
51
  }
99
52
 
100
- const loadMod = async (rel: string) => {
101
- if (!(rel in modules))
102
- modules[rel] = await importModule(join(outDir, rel))
103
- }
104
-
105
53
  for (const r of manifest.routes) {
106
- await loadMod(r.file)
107
- for (const l of r.layouts) await loadMod(l)
108
- for (const m of r.middlewares) await loadMod(m)
109
- if (r.prerendered) {
110
- for (const relHtml of Object.values(r.prerendered)) {
111
- const abs = join(outDir, relHtml)
112
- if (existsSync(abs))
113
- prerenderedFiles[relHtml] = abs
114
- }
54
+ for (const relHtml of Object.values(r.prerendered ?? {})) {
55
+ const abs = join(outDir, relHtml)
56
+ if (existsSync(abs))
57
+ prerenderedFiles[relHtml] = abs
115
58
  }
116
59
  }
117
- if (manifest.rootLayoutFile) await loadMod(manifest.rootLayoutFile)
118
- if (manifest.errorFile) await loadMod(manifest.errorFile)
119
- if (manifest.notFoundFile) await loadMod(manifest.notFoundFile)
120
- for (const a of manifest.actions) {
121
- await loadMod(a.file)
122
- for (const m of a.middlewares) await loadMod(m)
123
- }
124
60
 
125
- return createServerFromEmbedded({
126
- ...runtimeConfig,
61
+ const app = await entry.createApp({
62
+ ...resolveServerConfig(undefined, options),
127
63
  manifest,
128
- modules,
129
64
  assets,
130
65
  publicAssets,
131
66
  publicEtags,
@@ -133,6 +68,46 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
133
68
  root,
134
69
  outDir,
135
70
  publicDir: join(outDir, 'public'),
136
- dev: isDev,
71
+ dev: options.dev ?? (process.env.KAY_DEV === '1'),
137
72
  })
73
+ return { app, entry }
74
+ }
75
+
76
+ type BuiltOutput =
77
+ | { root: string, outDir: string, manifest: BuildManifest, entry: ServerEntry }
78
+ | { root: string, outDir: string, entry?: undefined }
79
+
80
+ /** Finds the build output and imports its server entry; a `--static` export has none. */
81
+ async function loadServerEntry(options: ServerOptions): Promise<BuiltOutput> {
82
+ const root = resolve(options.root)
83
+ let outDir = resolve(root, options.outDir ?? 'dist')
84
+ // kay.config.ts is read natively only to find an `outDir` it moved; the app itself runs from its bundled copy.
85
+ if (options.outDir === undefined && !existsSync(join(outDir, 'manifest.json')))
86
+ outDir = resolve(root, (await loadConfig(root)).outDir ?? 'dist')
87
+ const manifestPath = join(outDir, 'manifest.json')
88
+ if (!existsSync(manifestPath)) {
89
+ if (existsSync(outDir) && readdirSync(outDir).length > 0)
90
+ return { root, outDir }
91
+ throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
92
+ }
93
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
94
+ const entryPath = join(outDir, 'server', SERVER_ENTRY_FILE)
95
+ if (!existsSync(entryPath))
96
+ throw new Error(`kay server: missing ${entryPath}, the server entry kay build writes. Run kay build again.`)
97
+ const stamp = `${Date.now()}-${++serverLoadSeq}`
98
+ const importModule = options.importModule ?? ((path: string) => import(`${path}?v=${stamp}`))
99
+ const entry = await importModule(entryPath) as unknown as ServerEntry
100
+ return { root, outDir, manifest, entry }
101
+ }
102
+
103
+ async function serveStaticDir(options: ServerOptions, root: string, outDir: string): Promise<KayApp> {
104
+ const config = await loadConfig(root)
105
+ return createStaticDirServer(
106
+ outDir,
107
+ options.assetPrefix ?? config.assetPrefix ?? '/_kay',
108
+ options.security ?? config.security,
109
+ (options.compress ?? config.compress) !== false,
110
+ options.trustProxy ?? config.trustProxy ?? false,
111
+ options.dev ?? (process.env.KAY_DEV === '1'),
112
+ )
138
113
  }
@@ -0,0 +1,107 @@
1
+ // What a route file is to the server: the page, layout and middleware modules it loads, and the answers derived from their exports.
2
+
3
+ import type { BuildManifest, RouteManifestEntry } from '../build/index'
4
+ import type { Html } from '../jsx-runtime'
5
+ import type { Middleware, RequestContext } from './http'
6
+ import type { KayLocals } from './index'
7
+
8
+ export interface LoadedPageModule {
9
+ default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
10
+ load?: (ctx: RequestContext) => unknown | Promise<unknown>
11
+ clientData?: readonly string[] | ((data: unknown) => unknown) | undefined
12
+ csrf?: boolean | undefined
13
+ GET?: (ctx: RequestContext) => Response | Promise<Response>
14
+ POST?: (ctx: RequestContext) => Response | Promise<Response>
15
+ PUT?: (ctx: RequestContext) => Response | Promise<Response>
16
+ PATCH?: (ctx: RequestContext) => Response | Promise<Response>
17
+ DELETE?: (ctx: RequestContext) => Response | Promise<Response>
18
+ HEAD?: (ctx: RequestContext) => Response | Promise<Response>
19
+ OPTIONS?: (ctx: RequestContext) => Response | Promise<Response>
20
+ [key: string]: unknown
21
+ }
22
+
23
+ export interface LoadedLayoutModule {
24
+ default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: KayLocals }) => Html | string | Promise<Html | string>
25
+ }
26
+
27
+ export interface LoadedMiddlewareModule {
28
+ default: Middleware
29
+ }
30
+
31
+ const HTTP_METHOD_EXPORTS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const
32
+
33
+ export function mergedHeadTags(manifest: BuildManifest, entry: RouteManifestEntry): string[] | undefined {
34
+ return entry.headTags !== undefined && entry.headTags.length > 0
35
+ ? [...(manifest.headTags ?? []), ...entry.headTags]
36
+ : manifest.headTags
37
+ }
38
+
39
+ export function allowedMethodsHeader(mod: LoadedPageModule): string {
40
+ const allowed = new Set<string>()
41
+ if (typeof mod.default === 'function') {
42
+ allowed.add('GET')
43
+ allowed.add('HEAD')
44
+ }
45
+ for (const m of HTTP_METHOD_EXPORTS) {
46
+ if (typeof mod[m] === 'function')
47
+ allowed.add(m)
48
+ }
49
+ if (allowed.has('GET'))
50
+ allowed.add('HEAD')
51
+ return [...allowed].join(', ')
52
+ }
53
+
54
+ async function cancelBodyQuietly(body: ReadableStream<Uint8Array>): Promise<void> {
55
+ try {
56
+ await body.cancel()
57
+ }
58
+ catch {}
59
+ }
60
+
61
+ export function stripHeadBody(res: Response): Response {
62
+ if (res.body !== null)
63
+ void cancelBodyQuietly(res.body)
64
+ return new Response(null, { status: res.status, statusText: res.statusText, headers: res.headers })
65
+ }
66
+
67
+ export function isPlainObject(v: unknown): v is Record<string, unknown> {
68
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
69
+ }
70
+
71
+ function pickObjectKeys(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> | undefined {
72
+ if (keys.length === 0)
73
+ return undefined
74
+ const picked: Record<string, unknown> = {}
75
+ let count = 0
76
+ for (const k of keys) {
77
+ if (Object.hasOwn(obj, k)) {
78
+ Object.defineProperty(picked, k, { value: obj[k], enumerable: true, writable: true, configurable: true })
79
+ count++
80
+ }
81
+ }
82
+ return count > 0 ? picked : undefined
83
+ }
84
+
85
+ export function pickPageIslandProps(data: unknown, entry: RouteManifestEntry, mod: LoadedPageModule): Record<string, unknown> {
86
+ if (data === undefined)
87
+ return {}
88
+ if (typeof mod.clientData === 'function') {
89
+ const subset = mod.clientData(data)
90
+ return subset === undefined ? {} : { data: subset }
91
+ }
92
+ if (Array.isArray(mod.clientData)) {
93
+ if (!isPlainObject(data))
94
+ return {}
95
+ const subset = pickObjectKeys(data, mod.clientData)
96
+ return subset === undefined ? {} : { data: subset }
97
+ }
98
+ if (entry.islandDataKeys !== undefined) {
99
+ if (entry.islandDataKeys.length === 0)
100
+ return {}
101
+ if (isPlainObject(data)) {
102
+ const subset = pickObjectKeys(data, entry.islandDataKeys)
103
+ return subset === undefined ? {} : { data: subset }
104
+ }
105
+ }
106
+ return { data }
107
+ }
@@ -0,0 +1,165 @@
1
+ // What plugins see of a running server: each `server(api)` hook, and the middleware, routes, rewrites and shutdown hooks those hooks register.
2
+
3
+ import type { BuildManifest } from '../build/index'
4
+ import type { AppRuntimeContext } from '../plugins/context'
5
+ import type { KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerPluginAPI } from '../plugins/index'
6
+ import type { EmbeddedServerConfig, Middleware, RequestContext } from './http'
7
+ import type { TrustProxy } from './security'
8
+ import { runWithAppContext } from '../plugins/context'
9
+ import { Router } from './router'
10
+
11
+ export interface PluginRouteDef {
12
+ handler: (ctx: RequestContext) => Response | Promise<Response>
13
+ csrf: boolean
14
+ trustedOrigins: Set<string> | undefined
15
+ trustProxy: TrustProxy
16
+ }
17
+
18
+ interface ScopedMiddleware {
19
+ mw: Middleware
20
+ scope: 'all' | 'dynamic' | string
21
+ }
22
+
23
+ export interface ServerPluginHostOptions {
24
+ plugins: readonly KayPlugin[]
25
+ config: EmbeddedServerConfig
26
+ manifest: BuildManifest
27
+ appCtx: AppRuntimeContext
28
+ root: string
29
+ outDir: string
30
+ assetPrefix: string
31
+ site: string | undefined
32
+ dev: boolean
33
+ trustProxy: TrustProxy
34
+ trustedOriginsList: readonly string[]
35
+ trustedOrigins: Set<string> | undefined
36
+ }
37
+
38
+ function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string, isStaticFast: boolean): boolean {
39
+ if (scope === 'all')
40
+ return true
41
+ if (scope === 'dynamic')
42
+ return !isStaticFast
43
+ return path === scope || path.startsWith(scope.endsWith('/') ? scope : `${scope}/`)
44
+ }
45
+
46
+ export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRouteDef>): string {
47
+ const allowed = new Set<string>()
48
+ for (const m of methods.keys()) {
49
+ if (m === 'ALL')
50
+ continue
51
+ allowed.add(m)
52
+ }
53
+ if (allowed.has('GET'))
54
+ allowed.add('HEAD')
55
+ return [...allowed].join(', ')
56
+ }
57
+
58
+ export async function createServerPluginHost(options: ServerPluginHostOptions) {
59
+ const { plugins, config, manifest, appCtx, trustedOrigins, trustProxy } = options
60
+ const scopedMiddlewares: ScopedMiddleware[] = []
61
+ const shutdownHooks: { plugin: string, hook: () => void | Promise<void> }[] = []
62
+ const rewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
63
+ const router = new Router<Map<string, PluginRouteDef>>()
64
+ const routeEntries = new Map<string, Map<string, PluginRouteDef>>()
65
+
66
+ const registerRoute = (
67
+ method: string,
68
+ path: string,
69
+ handler: (ctx: RequestContext) => Response | Promise<Response>,
70
+ routeOptions?: PluginRouteOptions,
71
+ ): void => {
72
+ const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
73
+ let byMethod = routeEntries.get(normPath)
74
+ if (byMethod === undefined) {
75
+ byMethod = new Map()
76
+ routeEntries.set(normPath, byMethod)
77
+ router.add(normPath, byMethod)
78
+ }
79
+ let routeTrustedOrigins = trustedOrigins
80
+ if (routeOptions?.trustedOrigins !== undefined && routeOptions.trustedOrigins.length > 0) {
81
+ routeTrustedOrigins = new Set([...(trustedOrigins ?? []), ...routeOptions.trustedOrigins])
82
+ }
83
+ byMethod.set(method.toUpperCase(), {
84
+ handler,
85
+ csrf: routeOptions?.csrf ?? true,
86
+ trustedOrigins: routeTrustedOrigins,
87
+ trustProxy: routeOptions?.trustProxy ?? trustProxy,
88
+ })
89
+ }
90
+
91
+ const {
92
+ manifest: _m,
93
+ modules: _mods,
94
+ assets: _a,
95
+ publicAssets: _pa,
96
+ publicEtags: _pe,
97
+ prerendered: _pr,
98
+ prerenderedFiles: _pf,
99
+ ...forwardedConfig
100
+ } = config as EmbeddedServerConfig & Record<string, unknown>
101
+ const readonlyRuntimeConfig: Readonly<Record<string, unknown>> = Object.freeze({ ...forwardedConfig })
102
+
103
+ for (const plugin of plugins) {
104
+ if (plugin.server !== undefined) {
105
+ const pluginApi: ServerPluginAPI = {
106
+ root: options.root,
107
+ outDir: options.outDir,
108
+ assetPrefix: options.assetPrefix,
109
+ site: options.site,
110
+ dev: options.dev,
111
+ trustProxy,
112
+ trustedOrigins: options.trustedOriginsList,
113
+ config: readonlyRuntimeConfig,
114
+ use(mw: Middleware, middlewareOptions?: MiddlewareOptions) {
115
+ scopedMiddlewares.push({ mw, scope: middlewareOptions?.scope ?? 'all' })
116
+ },
117
+ route: registerRoute,
118
+ rewrite(fn) {
119
+ rewrites.push(fn)
120
+ },
121
+ provide: appCtx.provide,
122
+ inject: appCtx.inject,
123
+ getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined {
124
+ return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
125
+ },
126
+ onShutdown(fn) {
127
+ shutdownHooks.push({ plugin: plugin.name, hook: fn })
128
+ },
129
+ }
130
+ await runWithAppContext(appCtx, () => plugin.server!(pluginApi))
131
+ }
132
+ }
133
+
134
+ const allMiddlewares: readonly Middleware[] = scopedMiddlewares.map(m => m.mw)
135
+ const staticFastMiddlewares: readonly Middleware[] = scopedMiddlewares
136
+ .filter(m => m.scope === 'all')
137
+ .map(m => m.mw)
138
+ const hasPathScopedMiddlewares = scopedMiddlewares.some(m => m.scope !== 'all' && m.scope !== 'dynamic')
139
+ const middlewaresFor = (path: string, isStaticFast = false): readonly Middleware[] => {
140
+ if (scopedMiddlewares.length === 0)
141
+ return allMiddlewares
142
+ if (!hasPathScopedMiddlewares)
143
+ return isStaticFast ? staticFastMiddlewares : allMiddlewares
144
+ return scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, isStaticFast)).map(m => m.mw)
145
+ }
146
+
147
+ let disposed = false
148
+ async function dispose(): Promise<void> {
149
+ if (disposed)
150
+ return
151
+ disposed = true
152
+ for (const { plugin, hook } of shutdownHooks) {
153
+ try {
154
+ await hook()
155
+ }
156
+ catch (error) {
157
+ console.error(`kay: the onShutdown hook of ${plugin} threw; the other hooks still run.`, error)
158
+ }
159
+ }
160
+ }
161
+
162
+ return { router, rewrites, allMiddlewares, middlewaresFor, dispose }
163
+ }
164
+
165
+ export type ServerPluginHost = Awaited<ReturnType<typeof createServerPluginHost>>
@@ -0,0 +1,15 @@
1
+ // `@kayjs/kay/server`: what an app's routes, actions and middleware use, and `createServer` to run a built app inside another program. Anything not listed here stays internal.
2
+
3
+ export { action, getActionError } from './action'
4
+ export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
5
+ export type { CookieOptions, Cookies } from './cookies'
6
+ export { defineEnv, nodeEnv } from './env'
7
+ export { notFound } from './http'
8
+ export type { ExtractRouteParams, KayApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, ServerOptions } from './http'
9
+ export type { KayLocals } from './index'
10
+ export { createServer } from './loader'
11
+ export { getClientIp, isHttpsRequest, isTrustedOrigin, verifyOrigin } from './security'
12
+ export type { SecurityHeadersOptions, TrustProxy } from './security'
13
+ export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
14
+ export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
15
+ export { esc, escAttr, raw } from '../ssr/index'
@@ -0,0 +1,22 @@
1
+ // The request a server action called from server code runs in, entered by the action registry on the dynamic path only.
2
+
3
+ import type { ActionRegistry } from './action-registry'
4
+ import type { RequestContext } from './http'
5
+ import { AsyncLocalStorage } from 'node:async_hooks'
6
+
7
+ export interface RequestScope {
8
+ ctx: RequestContext
9
+ actions: ActionRegistry
10
+ }
11
+
12
+ const STORAGE_KEY = Symbol.for('kay.requestScope')
13
+ // One storage per process: a test's own copy of kay and the app's bundled one must see the same request.
14
+ const storage: AsyncLocalStorage<RequestScope> = ((globalThis as Record<symbol, AsyncLocalStorage<RequestScope> | undefined>)[STORAGE_KEY] ??= new AsyncLocalStorage<RequestScope>())
15
+
16
+ export function runInRequest<T>(scope: RequestScope, fn: () => T): T {
17
+ return storage.run(scope, fn)
18
+ }
19
+
20
+ export function currentRequest(): RequestScope | undefined {
21
+ return storage.getStore()
22
+ }
@@ -12,6 +12,45 @@ export const KAY_ISLAND_STYLE_HASH = cspSha256(KAY_ISLAND_STYLE)
12
12
  export const KAY_SUSPENSE_STYLE_HASH = cspSha256(KAY_SUSPENSE_STYLE)
13
13
  export const KAY_STREAM_SCRIPT_HASH = cspSha256(KAY_STREAM_SCRIPT)
14
14
 
15
+ const STYLE_HASH_CACHE_SIZE = 256
16
+ const styleHashCache = new Map<string, string>()
17
+
18
+ // Hashes stay cached by content, so a layout's fixed block costs one SHA-256 per process; past the cap a new block is hashed each time.
19
+ function styleHash(content: string): string {
20
+ let hash = styleHashCache.get(content)
21
+ if (hash === undefined) {
22
+ hash = cspSha256(content)
23
+ if (styleHashCache.size < STYLE_HASH_CACHE_SIZE)
24
+ styleHashCache.set(content, hash)
25
+ }
26
+ return hash
27
+ }
28
+
29
+ // A regex finds the next tag ~10x faster than `indexOf('<style')`, which stalls on every `<span` and `<strong` of a large page.
30
+ const STYLE_OPEN_RE = /<style[\s>/]/g
31
+
32
+ /** CSP hashes of the app's own `<style>` blocks in `html`, leaving out kay's island and Suspense styles (hashed apart). */
33
+ export function inlineStyleHashes(html: string): string[] {
34
+ const hashes: string[] = []
35
+ STYLE_OPEN_RE.lastIndex = 0
36
+ let open = STYLE_OPEN_RE.exec(html)
37
+ while (open !== null) {
38
+ const tagEnd = html.indexOf('>', open.index)
39
+ const close = tagEnd === -1 ? -1 : html.indexOf('</style', tagEnd)
40
+ if (close === -1)
41
+ break
42
+ const content = html.slice(tagEnd + 1, close)
43
+ if (content !== KAY_ISLAND_STYLE && content !== KAY_SUSPENSE_STYLE) {
44
+ const hash = styleHash(content)
45
+ if (!hashes.includes(hash))
46
+ hashes.push(hash)
47
+ }
48
+ STYLE_OPEN_RE.lastIndex = close
49
+ open = STYLE_OPEN_RE.exec(html)
50
+ }
51
+ return hashes
52
+ }
53
+
15
54
  /** Augments a Content-Security-Policy header with exact SHA-256 hashes (no `'unsafe-inline'` required). */
16
55
  export function withCspHashes(
17
56
  csp: string,
@@ -68,7 +107,7 @@ export function withCspHashes(
68
107
  }).join('; ')
69
108
  }
70
109
 
71
- export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'"
110
+ export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'"
72
111
  export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
73
112
  export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=()'
74
113
 
@@ -7,7 +7,7 @@ import { existsSync, statSync } from 'node:fs'
7
7
  import { extname, join, resolve } from 'node:path'
8
8
  import { CompressionCache, isCompressibleType, maybeCompressResponse, pickPrecompressedEncoding, toWeakEtag } from './compress'
9
9
  import { applyHstsHeader, etagMatches, MIME } from './http'
10
- import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes } from './security'
10
+ import { buildSecurityHeaderEntries, inlineStyleHashes, KAY_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes } from './security'
11
11
 
12
12
  const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
13
13
 
@@ -68,6 +68,21 @@ export function createStaticDirServer(
68
68
 
69
69
  const initHeaders = (isHtml = false): Headers => new Headers((isHtml ? htmlSecurityEntries : securityEntries) as [string, string][])
70
70
 
71
+ // An exported page's CSP gains the hashes of its own `<style>` blocks, read once per file version.
72
+ const pageCsp = new Map<string, { etag: string, csp: string }>()
73
+ async function setPageCsp(headers: Headers, filePath: string, etag: string): Promise<void> {
74
+ if (htmlCsp === undefined)
75
+ return
76
+ let cached = pageCsp.get(filePath)
77
+ if (cached?.etag !== etag) {
78
+ const styleHashes = inlineStyleHashes(await Bun.file(filePath).text())
79
+ cached = { etag, csp: withCspHashes(htmlCsp, { styleHashes }) }
80
+ pageCsp.set(filePath, cached)
81
+ }
82
+ headers.set('content-security-policy', cached.csp)
83
+ }
84
+ const fileEtag = (st: Stats): string => `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
85
+
71
86
  const handle = async (req: Request): Promise<Response> => {
72
87
  if (!isRead(req)) {
73
88
  const headers = initHeaders()
@@ -79,9 +94,11 @@ export function createStaticDirServer(
79
94
  const found = resolveStaticFile(url.pathname)
80
95
  if (found === undefined) {
81
96
  const notFoundPath = join(absRoot, '404.html')
82
- if (statFile(notFoundPath) !== undefined) {
97
+ const notFoundStat = statFile(notFoundPath)
98
+ if (notFoundStat !== undefined) {
83
99
  const headers = initHeaders(true)
84
100
  headers.set('content-type', 'text/html; charset=utf-8')
101
+ await setPageCsp(headers, notFoundPath, fileEtag(notFoundStat))
85
102
  return withHsts(new Response(req.method === 'HEAD' ? null : Bun.file(notFoundPath), { status: 404, headers }), req)
86
103
  }
87
104
  return withHsts(new Response('Not Found', { status: 404, headers: initHeaders() }), req)
@@ -91,12 +108,14 @@ export function createStaticDirServer(
91
108
  const ext = extname(filePath).toLowerCase()
92
109
  const mime = MIME[ext] ?? 'application/octet-stream'
93
110
  const isHtml = ext === '.html' || ext === '.htm'
94
- const etag = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
111
+ const etag = fileEtag(st)
95
112
  const isImmutable = url.pathname.startsWith(cleanPrefix)
96
113
  const headers = initHeaders(isHtml)
97
114
  headers.set('content-type', mime)
98
115
  headers.set('cache-control', isImmutable ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate')
99
116
  headers.set('etag', etag)
117
+ if (isHtml)
118
+ await setPageCsp(headers, filePath, etag)
100
119
 
101
120
  const hasBr = compressEnabled && existsSync(`${filePath}.br`)
102
121
  const hasGz = compressEnabled && existsSync(`${filePath}.gz`)