@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.
Files changed (48) hide show
  1. package/package.json +1 -1
  2. package/src/build/bundle.ts +209 -34
  3. package/src/build/compile.ts +22 -46
  4. package/src/build/files.ts +38 -0
  5. package/src/build/graph.ts +67 -2
  6. package/src/build/index.ts +75 -13
  7. package/src/build/manifest.ts +5 -0
  8. package/src/build/plugin-host.ts +2 -0
  9. package/src/build/prerender.ts +16 -7
  10. package/src/build/resolve.ts +11 -18
  11. package/src/build/routes.ts +33 -5
  12. package/src/build/server-entry.ts +38 -0
  13. package/src/cli/check.ts +102 -45
  14. package/src/cli/new.ts +6 -7
  15. package/src/compiler/analyze.ts +65 -10
  16. package/src/compiler/dom.ts +143 -122
  17. package/src/compiler/server-only.ts +14 -8
  18. package/src/compiler/shared.ts +57 -14
  19. package/src/compiler/ssr.ts +14 -12
  20. package/src/dev/index.ts +96 -29
  21. package/src/dom/action.ts +91 -1
  22. package/src/dom/index.ts +8 -3
  23. package/src/index.ts +3 -0
  24. package/src/jsx-runtime.ts +421 -93
  25. package/src/plugins/config.ts +49 -0
  26. package/src/plugins/context.ts +4 -0
  27. package/src/plugins/index.ts +7 -216
  28. package/src/plugins/load.ts +38 -0
  29. package/src/plugins/order.ts +107 -0
  30. package/src/plugins/services.ts +23 -0
  31. package/src/plugins/types.ts +197 -0
  32. package/src/server/action-registry.ts +72 -0
  33. package/src/server/action.ts +15 -8
  34. package/src/server/app-entry.ts +23 -0
  35. package/src/server/assets.ts +182 -0
  36. package/src/server/compress.ts +87 -14
  37. package/src/server/document.ts +192 -0
  38. package/src/server/errors.ts +123 -0
  39. package/src/server/http.ts +103 -30
  40. package/src/server/index.ts +131 -701
  41. package/src/server/loader.ts +62 -69
  42. package/src/server/page.ts +107 -0
  43. package/src/server/plugin-host.ts +167 -0
  44. package/src/server/router.ts +49 -20
  45. package/src/server/security.ts +44 -3
  46. package/src/server/static-dir.ts +22 -3
  47. package/src/server/stream.ts +94 -0
  48. package/src/test/index.ts +24 -19
@@ -1,221 +1,12 @@
1
1
  // Kay v2 public Plugin API & config helpers.
2
2
  // Strict architectural rule: every non-core capability (@kayjs/tailwind, @kayjs/spa, @kayjs/i18n, etc.)
3
- // is built strictly through these public hooks — never hardcoded in @kay/core.
4
-
5
- import type { BunPlugin } from 'bun'
6
- import type { RouteManifestEntry } from '../build/index'
7
- import type { ActionResult, ServerAction } from '../server/action'
8
- import type { Middleware, RequestContext } from '../server/index'
9
- import type { SecurityHeadersOptions, TrustProxy } from '../server/security'
10
- import type { AppRuntimeContext } from './context'
11
- import { existsSync, readFileSync } from 'node:fs'
12
- import { join, resolve } from 'node:path'
13
- import { createAppContext, getAppContext, runWithAppContext } from './context'
3
+ // is built strictly through these public hooks - never hardcoded in @kay/core.
14
4
 
5
+ export { defineConfig, definePlugin, pickRuntimeConfig, resolveServerConfig } from './config'
15
6
  export { createAppContext, getAppContext, runWithAppContext } from './context'
16
7
  export type { AppRuntimeContext, CreateAppContextOptions } from './context'
17
-
18
- export type BuildPluginTarget = 'client' | 'server' | 'compile'
19
-
20
- export interface BuildPluginContext {
21
- readonly root: string
22
- readonly outDir: string
23
- readonly assetPrefix: string
24
- readonly minify: boolean
25
- readonly isStatic: boolean
26
- readonly dev: boolean
27
- readonly routes: readonly RouteManifestEntry[]
28
- /** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_kay/<relPath>`). */
29
- emitAsset(relPath: string, content: string | Uint8Array): string
30
- /** Emit a static file into dist/public/<relPath> served at `/<relPath>`. */
31
- emitPublic(relPath: string, content: string | Uint8Array): string
32
- /** Add a stylesheet URL to <head> on every page. */
33
- addStyle(href: string): void
34
- /** Add a stylesheet URL to <head> on a specific route path only. */
35
- addRouteStyle(routePath: string, href: string): void
36
- /** Add raw HTML to <head> on every page (e.g. font preloads, default meta/OG, JSON-LD). */
37
- addHead(html: string): void
38
- /** Add raw HTML to <head> on a specific route path only. */
39
- addRouteHead(routePath: string, html: string): void
40
- /** Register an explicit build-scoped service for other plugins or render-time helpers. */
41
- provide<T>(key: string, value: T): void
42
- /** Look up a build-scoped service registered by another plugin. */
43
- inject<T>(key: string): T | undefined
44
- /** Persist JSON-serializable build data into `manifest.pluginData[plugin.name]` for cold-start servers and `--compile`. */
45
- setData(data: Record<string, unknown>): void
46
- }
47
-
48
- export interface FinalizeBuildContext {
49
- readonly root: string
50
- readonly outDir: string
51
- readonly assetPrefix: string
52
- readonly minify: boolean
53
- readonly isStatic: boolean
54
- readonly dev: boolean
55
- /** Route manifest entries with `prerendered` maps populated after Step 3 prerendering. */
56
- readonly routes: readonly RouteManifestEntry[]
57
- /** Relative paths of all public files known so far (including files registered during prerender). */
58
- readonly publicFiles: readonly string[]
59
- /** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_kay/<relPath>`). */
60
- emitAsset(relPath: string, content: string | Uint8Array): string
61
- /** Emit a static file into dist/public/<relPath> served at `/<relPath>` (included in `--static` and `--compile`). */
62
- emitPublic(relPath: string, content: string | Uint8Array): string
63
- /** Register a build-scoped service. */
64
- provide<T>(key: string, value: T): void
65
- /** Look up a build-scoped service. */
66
- inject<T>(key: string): T | undefined
67
- /** Merge/persist JSON-serializable build data into `manifest.pluginData[plugin.name]`. */
68
- setData(data: Record<string, unknown>): void
69
- }
70
-
71
- export interface CheckPluginContext {
72
- readonly root: string
73
- readonly routesDir: string
74
- /** Report a validation error from `kay check`. */
75
- error(message: string): void
76
- }
77
-
78
- export interface PluginRouteOptions {
79
- /** Enable CSRF Origin/Sec-Fetch-Site verification on unsafe methods (default: true). Set `false` to opt out (e.g. webhooks, bearer-token APIs). */
80
- csrf?: boolean | undefined
81
- /** Additional trusted origins merged with `KayConfig.trustedOrigins` for this route's CSRF check. */
82
- trustedOrigins?: readonly string[] | undefined
83
- /** Override `KayConfig.trustProxy` for this route's CSRF check. */
84
- trustProxy?: TrustProxy | undefined
85
- }
86
-
87
- export interface MiddlewareOptions {
88
- /** `'all'` (default) runs on every route; `'dynamic'` skips static/prerendered fast paths; a string prefix scopes to matching pathnames. */
89
- scope?: 'all' | 'dynamic' | string | undefined
90
- }
91
-
92
- export interface ServerPluginAPI {
93
- readonly root: string
94
- readonly outDir: string
95
- readonly assetPrefix: string
96
- readonly dev: boolean
97
- /** Readonly server security configuration so plugins inherit `trustProxy` / `trustedOrigins` without overriding them. */
98
- readonly trustProxy: TrustProxy
99
- readonly trustedOrigins: readonly string[]
100
- /** Readonly runtime config forwarded from `kay.config.ts` (minus build-only keys). */
101
- readonly config?: Readonly<Record<string, unknown>> | undefined
102
- /** Register global (or scoped) middleware that runs before route handlers. */
103
- use(middleware: Middleware, options?: MiddlewareOptions): void
104
- /** Register a custom HTTP route (e.g. GET /sitemap.xml, POST /auth/callback). */
105
- route(method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions): void
106
- /** Rewrite an incoming pathname before route matching (e.g. strip /fr locale prefix). */
107
- rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
108
- /** Register a server-scoped service for other plugins or render-time helpers (isolated per server instance). */
109
- provide<T>(key: string, value: T): void
110
- /** Look up a server-scoped service registered by another plugin. */
111
- inject<T>(key: string): T | undefined
112
- /** Read persisted build data from `manifest.pluginData` (defaults to the current plugin's name). */
113
- getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined
114
- /** Register a shutdown cleanup callback run when `app.dispose()` is called (dev reloads, tests, graceful exit). */
115
- onShutdown(fn: () => void | Promise<void>): void
116
- /** Invoke a ServerAction with Standard Schema validation and directory-scoped `_middleware.ts` checks. */
117
- invokeAction<I, O>(action: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>>
118
- }
119
-
120
- export interface ServerErrorInfo {
121
- error: unknown
122
- request: Request
123
- source: 'route' | 'action' | 'plugin'
124
- }
125
-
126
- export interface KayPlugin {
127
- name: string
128
- /** Register server routes, global middleware, URL rewrites, or runtime services. */
129
- server?: (api: ServerPluginAPI) => void | Promise<void>
130
- /** Optional cleanup hook called when a server instance is disposed (dev reloads, tests, graceful shutdown). */
131
- dispose?: () => void | Promise<void>
132
- /** Error hook called whenever a route, action, or plugin handler throws an unhandled error. */
133
- onError?: (info: ServerErrorInfo) => void
134
- /** Build hook run after route compilation, before prerender / --static / --compile. */
135
- build?: (ctx: BuildPluginContext) => void | Promise<void>
136
- /** Post-prerender build hook run after `route.prerendered` is populated, before `--static` / `--compile` / final manifest write. */
137
- afterPrerender?: (ctx: FinalizeBuildContext) => void | Promise<void>
138
- /** Code transform run during client & server compilation (`.ts` and `.tsx`). */
139
- transform?: (code: string, id: string, target: 'server' | 'client') => string | undefined | void
140
- /** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). Factory is invoked per build target. */
141
- bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget }) => BunPlugin[]) | undefined
142
- /** Global CSS files to bundle and inject as <link rel="stylesheet"> in <head>. */
143
- css?: string[] | undefined
144
- /** Post-process rendered HTML before sending (applies to pages, `<Suspense>` shells, `_error.tsx`, and `_404.tsx`). */
145
- transformHtml?: (html: string, ctx: RequestContext) => string | Promise<string>
146
- /** Expand or filter prerender URLs for a route (e.g. @kayjs/i18n expanding `/posts/a` -> `['/posts/a', '/fr/posts/a']`). */
147
- prerenderPaths?: (paths: string[], route: RouteManifestEntry) => string[] | Promise<string[]>
148
- /** Client bootstrap module path — bundled ONLY when this plugin is active. */
149
- clientEntry?: string | undefined
150
- /** Validate plugin-specific invariants during `kay check` (e.g. missing i18n keys, content frontmatter). */
151
- check?: (ctx: CheckPluginContext) => void | Promise<void>
152
- /** Extra directories or files (relative to app root or absolute) for `kay dev` to watch. */
153
- watchPaths?: string[] | ((root: string) => string[]) | undefined
154
- /** Register custom CLI subcommands (e.g. `kay i18n check`). */
155
- commands?: Record<string, (args: string[], root: string) => void | Promise<void>> | undefined
156
- }
157
-
158
- export interface KayConfig {
159
- lang?: string | undefined
160
- port?: number | undefined
161
- routesDir?: string | undefined
162
- outDir?: string | undefined
163
- publicDir?: string | undefined
164
- assetPrefix?: string | undefined
165
- security?: SecurityHeadersOptions | false | undefined
166
- trustedOrigins?: string[] | undefined
167
- trustProxy?: TrustProxy | undefined
168
- maxRequestBodySize?: number | undefined
169
- /** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
170
- streamTimeout?: number | undefined
171
- compress?: boolean | undefined
172
- onError?: ((info: ServerErrorInfo) => void) | undefined
173
- plugins?: KayPlugin[] | undefined
174
- }
175
-
176
- export function defineConfig(config: KayConfig): KayConfig {
177
- return config
178
- }
179
-
180
- /** Forwards every runtime key from `kay.config.ts`, stripping build/CLI-only keys (`routesDir`, `outDir`, `publicDir`, `port`). */
181
- export function pickRuntimeConfig(config: KayConfig | undefined): Omit<KayConfig, 'routesDir' | 'outDir' | 'publicDir' | 'port'> {
182
- if (config === undefined)
183
- return {}
184
- const { routesDir: _r, outDir: _o, publicDir: _p, port: _pt, ...runtime } = config
185
- return runtime
186
- }
187
-
188
- export function definePlugin(plugin: KayPlugin): KayPlugin {
189
- return plugin
190
- }
191
-
192
- let configReloadSeq = 0
193
-
194
- // In dev the query follows the file content: a save elsewhere reuses the loaded config and its plugin instances instead of re-running every factory.
195
- function configSpecifier(configPath: string, fresh: boolean): string {
196
- if (fresh)
197
- return `${configPath}?v=fresh-${++configReloadSeq}`
198
- if (process.env.KAY_DEV === '1')
199
- return `${configPath}?v=${Bun.hash(readFileSync(configPath)).toString(36)}`
200
- return configPath
201
- }
202
-
203
- export async function loadConfig(root: string, options?: { fresh?: boolean, appContext?: AppRuntimeContext }): Promise<KayConfig> {
204
- const absRoot = resolve(root)
205
- const configPath = join(absRoot, 'kay.config.ts')
206
- if (!existsSync(configPath))
207
- return {}
208
- const spec = configSpecifier(configPath, options?.fresh === true)
209
- const active = options?.appContext ?? getAppContext()
210
- const ctx = active !== undefined && active.root === absRoot
211
- ? active
212
- : createAppContext({
213
- root: absRoot,
214
- outDir: join(absRoot, 'dist'),
215
- publicDir: join(absRoot, 'dist', 'public'),
216
- assetPrefix: '/_kay',
217
- dev: process.env.KAY_DEV === '1',
218
- })
219
- const mod = await runWithAppContext(ctx, () => import(spec)) as { default?: KayConfig }
220
- return mod.default ?? {}
221
- }
8
+ export { loadConfig } from './load'
9
+ export { resolvePlugins } from './order'
10
+ export { CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE } from './services'
11
+ export type { ActiveI18nConfig, ContentImageResolver, ContentImageResult } from './services'
12
+ export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, KayConfig, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
@@ -0,0 +1,38 @@
1
+ // Native `kay.config.ts` load, for the build, check and dev steps that run beside the bundled app.
2
+
3
+ import type { AppRuntimeContext } from './context'
4
+ import type { KayConfig } from './types'
5
+ import { existsSync, readFileSync } from 'node:fs'
6
+ import { join, resolve } from 'node:path'
7
+ import { createAppContext, getAppContext, runWithAppContext } from './context'
8
+
9
+ let configReloadSeq = 0
10
+
11
+ // In dev the query follows the file content: a save elsewhere reuses the loaded config and its plugin instances instead of re-running every factory.
12
+ function configSpecifier(configPath: string, fresh: boolean): string {
13
+ if (fresh)
14
+ return `${configPath}?v=fresh-${++configReloadSeq}`
15
+ if (process.env.KAY_DEV === '1')
16
+ return `${configPath}?v=${Bun.hash(readFileSync(configPath)).toString(36)}`
17
+ return configPath
18
+ }
19
+
20
+ export async function loadConfig(root: string, options?: { fresh?: boolean, appContext?: AppRuntimeContext }): Promise<KayConfig> {
21
+ const absRoot = resolve(root)
22
+ const configPath = join(absRoot, 'kay.config.ts')
23
+ if (!existsSync(configPath))
24
+ return {}
25
+ const spec = configSpecifier(configPath, options?.fresh === true)
26
+ const active = options?.appContext ?? getAppContext()
27
+ const ctx = active !== undefined && active.root === absRoot
28
+ ? active
29
+ : createAppContext({
30
+ root: absRoot,
31
+ outDir: join(absRoot, 'dist'),
32
+ publicDir: join(absRoot, 'dist', 'public'),
33
+ assetPrefix: '/_kay',
34
+ dev: process.env.KAY_DEV === '1',
35
+ })
36
+ const mod = await runWithAppContext(ctx, () => import(spec)) as { default?: KayConfig }
37
+ return mod.default ?? {}
38
+ }
@@ -0,0 +1,107 @@
1
+ // Plugin ordering: `enforce` buckets, `after` dependencies, and the `readsLocals`/`providesLocals` startup check.
2
+
3
+ import type { KayPlugin } from './types'
4
+
5
+ function enforceRank(plugin: KayPlugin): number {
6
+ return plugin.enforce === 'pre' ? 0 : plugin.enforce === 'post' ? 2 : 1
7
+ }
8
+
9
+ /**
10
+ * Sorts plugins stably by `enforce` (`'pre'` -> normal -> `'post'`) and `after` dependencies,
11
+ * then fails fast if any plugin declares `readsLocals` for a key whose provider runs after it.
12
+ */
13
+ export function resolvePlugins(plugins: readonly KayPlugin[] | undefined): KayPlugin[] {
14
+ if (plugins === undefined || plugins.length === 0)
15
+ return []
16
+
17
+ // Base stable order by `enforce` bucket, preserving config declaration order within each bucket.
18
+ const base = plugins
19
+ .map((plugin, index) => ({ plugin, index, rank: enforceRank(plugin) }))
20
+ .sort((a, b) => a.rank - b.rank || a.index - b.index)
21
+ .map(entry => entry.plugin)
22
+
23
+ const n = base.length
24
+ const indicesByName = new Map<string, number[]>()
25
+ for (let i = 0; i < n; i++) {
26
+ const name = base[i]!.name
27
+ const list = indicesByName.get(name)
28
+ if (list === undefined)
29
+ indicesByName.set(name, [i])
30
+ else
31
+ list.push(i)
32
+ }
33
+
34
+ // Kahn's topological sort using min-index priority so `enforce` + declaration order stays deterministic.
35
+ const inDegree = new Int32Array(n)
36
+ const edges: number[][] = Array.from({ length: n }, () => [])
37
+ for (let i = 0; i < n; i++) {
38
+ const deps = base[i]!.after
39
+ if (deps === undefined)
40
+ continue
41
+ const seen = new Set<number>()
42
+ for (const depName of deps) {
43
+ const targets = indicesByName.get(depName)
44
+ if (targets === undefined)
45
+ continue
46
+ for (const depIdx of targets) {
47
+ if (depIdx === i || seen.has(depIdx))
48
+ continue
49
+ seen.add(depIdx)
50
+ edges[depIdx]!.push(i)
51
+ inDegree[i] = (inDegree[i] ?? 0) + 1
52
+ }
53
+ }
54
+ }
55
+
56
+ const ready: number[] = []
57
+ for (let i = 0; i < n; i++) {
58
+ if (inDegree[i] === 0)
59
+ ready.push(i)
60
+ }
61
+
62
+ const sorted: KayPlugin[] = []
63
+ while (ready.length > 0) {
64
+ // Pick lowest base index so `enforce` and user declaration order are preserved whenever unconstrained.
65
+ let bestPos = 0
66
+ for (let k = 1; k < ready.length; k++) {
67
+ if (ready[k]! < ready[bestPos]!)
68
+ bestPos = k
69
+ }
70
+ const u = ready.splice(bestPos, 1)[0]!
71
+ sorted.push(base[u]!)
72
+ for (const v of edges[u]!) {
73
+ inDegree[v] = (inDegree[v] ?? 0) - 1
74
+ if (inDegree[v] === 0)
75
+ ready.push(v)
76
+ }
77
+ }
78
+
79
+ if (sorted.length !== n) {
80
+ const stuck = base.filter((_, idx) => (inDegree[idx] ?? 0) > 0).map(p => p.name)
81
+ throw new Error(`kay: circular plugin \`after\` dependency involving: ${stuck.join(', ')}`)
82
+ }
83
+
84
+ // Validate that no plugin reads a ctx.locals key before another active plugin provides it.
85
+ const providerByLocal = new Map<string, { name: string, index: number }>()
86
+ for (let i = 0; i < sorted.length; i++) {
87
+ const plugin = sorted[i]!
88
+ for (const key of plugin.providesLocals ?? []) {
89
+ if (!providerByLocal.has(key))
90
+ providerByLocal.set(key, { name: plugin.name, index: i })
91
+ }
92
+ }
93
+
94
+ for (let i = 0; i < sorted.length; i++) {
95
+ const plugin = sorted[i]!
96
+ for (const key of plugin.readsLocals ?? []) {
97
+ const provider = providerByLocal.get(key)
98
+ if (provider !== undefined && provider.index > i) {
99
+ throw new Error(
100
+ `kay: plugin "${plugin.name}" reads ctx.locals.${key} before "${provider.name}" provides it. Add \`after: [${JSON.stringify(provider.name)}]\` or adjust plugin order.`,
101
+ )
102
+ }
103
+ }
104
+ }
105
+
106
+ return sorted
107
+ }
@@ -0,0 +1,23 @@
1
+ // Service keys shared between two plugins, kept in core as contracts so neither plugin depends on the other.
2
+
3
+ export interface ActiveI18nConfig {
4
+ readonly locales: readonly string[]
5
+ readonly defaultLocale: string
6
+ readonly prefixDefault: boolean
7
+ }
8
+
9
+ export const I18N_CONFIG_SERVICE = 'kay.i18n.config'
10
+
11
+ export interface ContentImageResult {
12
+ src: string
13
+ srcset?: string | undefined
14
+ avifSrcset?: string | undefined
15
+ sizes?: string | undefined
16
+ width?: number | undefined
17
+ height?: number | undefined
18
+ loading?: 'lazy' | 'eager' | undefined
19
+ }
20
+
21
+ export type ContentImageResolver = (src: string, file: string | undefined) => ContentImageResult | string | undefined
22
+
23
+ export const CONTENT_IMAGE_RESOLVER_SERVICE = 'kay.content.imageResolver'
@@ -0,0 +1,197 @@
1
+ // The plugin contract: what a `KayPlugin` declares and what the build, check and server hosts hand its hooks.
2
+
3
+ import type { BunPlugin } from 'bun'
4
+ import type { RouteManifestEntry } from '../build/index'
5
+ import type { ActionResult, ServerAction } from '../server/action'
6
+ import type { Middleware, RequestContext } from '../server/index'
7
+ import type { SecurityHeadersOptions, TrustProxy } from '../server/security'
8
+
9
+ export type BuildPluginTarget = 'client' | 'server' | 'compile'
10
+
11
+ export interface BuildPluginContext {
12
+ readonly root: string
13
+ readonly outDir: string
14
+ readonly assetPrefix: string
15
+ readonly site?: string | undefined
16
+ readonly minify: boolean
17
+ readonly isStatic: boolean
18
+ readonly dev: boolean
19
+ readonly routes: readonly RouteManifestEntry[]
20
+ /** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_kay/<relPath>`). */
21
+ emitAsset(relPath: string, content: string | Uint8Array): string
22
+ /** Emit a static file into dist/public/<relPath> served at `/<relPath>`. */
23
+ emitPublic(relPath: string, content: string | Uint8Array): string
24
+ /** Add a stylesheet URL to <head> on every page. */
25
+ addStyle(href: string): void
26
+ /** Add a stylesheet URL to <head> on a specific route path only. */
27
+ addRouteStyle(routePath: string, href: string): void
28
+ /** Add raw HTML to <head> on every page (e.g. font preloads, default meta/OG, JSON-LD). */
29
+ addHead(html: string): void
30
+ /** Add raw HTML to <head> on a specific route path only. */
31
+ addRouteHead(routePath: string, html: string): void
32
+ /** Register an explicit build-scoped service for other plugins or render-time helpers. */
33
+ provide<T>(key: string, value: T): void
34
+ /** Look up a build-scoped service registered by another plugin. */
35
+ inject<T>(key: string): T | undefined
36
+ /** Persist JSON-serializable build data into `manifest.pluginData[plugin.name]` for cold-start servers and `--compile`. */
37
+ setData(data: Record<string, unknown>): void
38
+ }
39
+
40
+ export interface FinalizeBuildContext {
41
+ readonly root: string
42
+ readonly outDir: string
43
+ readonly assetPrefix: string
44
+ readonly site?: string | undefined
45
+ readonly minify: boolean
46
+ readonly isStatic: boolean
47
+ readonly dev: boolean
48
+ /** Route manifest entries with `prerendered` maps populated after Step 3 prerendering. */
49
+ readonly routes: readonly RouteManifestEntry[]
50
+ /** Relative paths of all public files known so far (including files registered during prerender). */
51
+ readonly publicFiles: readonly string[]
52
+ /** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_kay/<relPath>`). */
53
+ emitAsset(relPath: string, content: string | Uint8Array): string
54
+ /** Emit a static file into dist/public/<relPath> served at `/<relPath>` (included in `--static` and `--compile`). */
55
+ emitPublic(relPath: string, content: string | Uint8Array): string
56
+ /** Register a build-scoped service. */
57
+ provide<T>(key: string, value: T): void
58
+ /** Look up a build-scoped service. */
59
+ inject<T>(key: string): T | undefined
60
+ /** Merge/persist JSON-serializable build data into `manifest.pluginData[plugin.name]`. */
61
+ setData(data: Record<string, unknown>): void
62
+ }
63
+
64
+ export interface CheckPluginContext {
65
+ readonly root: string
66
+ readonly routesDir: string
67
+ /** Report a validation error from `kay check`. */
68
+ error(message: string): void
69
+ }
70
+
71
+ export interface PluginRouteOptions {
72
+ /** Enable CSRF Origin/Sec-Fetch-Site verification on unsafe methods (default: true). Set `false` to opt out (e.g. webhooks, bearer-token APIs). */
73
+ csrf?: boolean | undefined
74
+ /** Additional trusted origins merged with `KayConfig.trustedOrigins` for this route's CSRF check. */
75
+ trustedOrigins?: readonly string[] | undefined
76
+ /** Override `KayConfig.trustProxy` for this route's CSRF check. */
77
+ trustProxy?: TrustProxy | undefined
78
+ }
79
+
80
+ export interface MiddlewareOptions {
81
+ /** `'all'` (default) runs on every route; `'dynamic'` skips static/prerendered fast paths; a string prefix scopes to matching pathnames. */
82
+ scope?: 'all' | 'dynamic' | string | undefined
83
+ }
84
+
85
+ export interface ServerPluginAPI {
86
+ readonly root: string
87
+ readonly outDir: string
88
+ readonly assetPrefix: string
89
+ readonly site?: string | undefined
90
+ readonly dev: boolean
91
+ /** Readonly server security configuration so plugins inherit `trustProxy` / `trustedOrigins` without overriding them. */
92
+ readonly trustProxy: TrustProxy
93
+ readonly trustedOrigins: readonly string[]
94
+ /** Readonly runtime config forwarded from `kay.config.ts` (minus build-only keys). */
95
+ readonly config?: Readonly<Record<string, unknown>> | undefined
96
+ /** Register global (or scoped) middleware that runs before route handlers. */
97
+ use(middleware: Middleware, options?: MiddlewareOptions): void
98
+ /** Register a custom HTTP route (e.g. GET /sitemap.xml, POST /auth/callback). */
99
+ route(method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions): void
100
+ /** Rewrite an incoming pathname before route matching (e.g. strip /fr locale prefix). */
101
+ rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
102
+ /** Register a server-scoped service for other plugins or render-time helpers (isolated per server instance). */
103
+ provide<T>(key: string, value: T): void
104
+ /** Look up a server-scoped service registered by another plugin. */
105
+ inject<T>(key: string): T | undefined
106
+ /** Read persisted build data from `manifest.pluginData` (defaults to the current plugin's name). */
107
+ getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined
108
+ /** Register a shutdown cleanup callback run when `app.dispose()` is called (dev reloads, tests, graceful exit). */
109
+ onShutdown(fn: () => void | Promise<void>): void
110
+ /** Invoke a ServerAction with Standard Schema validation and directory-scoped `_middleware.ts` checks. */
111
+ invokeAction<I, O>(action: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>>
112
+ }
113
+
114
+ export interface ServerErrorInfo {
115
+ error: unknown
116
+ request: Request
117
+ source: 'route' | 'action' | 'plugin'
118
+ }
119
+
120
+ export interface DocumentHeadContext {
121
+ /** Current document `lang` attribute (mutating sets `<html lang="...">`). */
122
+ lang: string
123
+ /** Extra attributes emitted on `<html>`. */
124
+ readonly htmlAttrs: Record<string, string>
125
+ /** Inner HTML of the page's `<title>` tag (if rendered via `<Head><title>...</title></Head>`), or `undefined`. */
126
+ title: string | undefined
127
+ /** Read-only view of head HTML already collected from `<Head>`, build `addHead`, and earlier plugins. */
128
+ readonly headHtml: string
129
+ /** Append raw HTML to `<head>` (emitted once by core when assembling the document). */
130
+ add(html: string): void
131
+ }
132
+
133
+ export interface KayPlugin {
134
+ name: string
135
+ /** Execution phase: `'pre'` runs before normal plugins, `'post'` runs after them. */
136
+ enforce?: 'pre' | 'post' | undefined
137
+ /** Names of plugins that must run before this plugin when present. */
138
+ after?: readonly string[] | undefined
139
+ /** `ctx.locals` keys this plugin populates (used for startup order validation). */
140
+ providesLocals?: readonly string[] | undefined
141
+ /** `ctx.locals` keys this plugin reads (startup fails if a provider is ordered after it). */
142
+ readsLocals?: readonly string[] | undefined
143
+ /** Register server routes, global middleware, URL rewrites, or runtime services. */
144
+ server?: (api: ServerPluginAPI) => void | Promise<void>
145
+ /** Optional cleanup hook called when a server instance is disposed (dev reloads, tests, graceful shutdown). */
146
+ dispose?: () => void | Promise<void>
147
+ /** Error hook called whenever a route, action, or plugin handler throws an unhandled error. */
148
+ onError?: (info: ServerErrorInfo) => void
149
+ /** Build hook run after route compilation, before prerender / --static / --compile. */
150
+ build?: (ctx: BuildPluginContext) => void | Promise<void>
151
+ /** Post-prerender build hook run after `route.prerendered` is populated, before `--static` / `--compile` / final manifest write. */
152
+ afterPrerender?: (ctx: FinalizeBuildContext) => void | Promise<void>
153
+ /** Code transform run during client & server compilation (`.ts` and `.tsx`). */
154
+ transform?: (code: string, id: string, target: 'server' | 'client') => string | undefined | void
155
+ /** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). Factory is invoked per build target. */
156
+ bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget }) => BunPlugin[]) | undefined
157
+ /** Global CSS files to bundle and inject as <link rel="stylesheet"> in <head>. */
158
+ css?: string[] | undefined
159
+ /** Mutate `<html lang>`, `htmlAttrs`, `<title>`, or append tags to `<head>` before core renders the document once. */
160
+ head?: (head: DocumentHeadContext, ctx: RequestContext) => void | Promise<void>
161
+ /** Post-process rendered HTML before sending (applies to pages, `<Suspense>` shells, `_error.tsx`, and `_404.tsx`). */
162
+ transformHtml?: (html: string, ctx: RequestContext) => string | Promise<string>
163
+ /** Expand or filter prerender URLs for a route (e.g. @kayjs/i18n expanding `/posts/a` -> `['/posts/a', '/fr/posts/a']`). */
164
+ prerenderPaths?: (paths: string[], route: RouteManifestEntry) => string[] | Promise<string[]>
165
+ /** Client bootstrap module path — bundled ONLY when this plugin is active. */
166
+ clientEntry?: string | undefined
167
+ /** Validate plugin-specific invariants during `kay check` (e.g. missing i18n keys, content frontmatter). */
168
+ check?: (ctx: CheckPluginContext) => void | Promise<void>
169
+ /** Extra directories or files (relative to app root or absolute) for `kay dev` to watch. */
170
+ watchPaths?: string[] | ((root: string) => string[]) | undefined
171
+ /** Register custom CLI subcommands (e.g. `kay i18n check`). */
172
+ commands?: Record<string, (args: string[], root: string) => void | Promise<void>> | undefined
173
+ }
174
+
175
+ /** Shared runtime server options inherited from `kay.config.ts` and overridable by `createServer`, `testApp`, `devServer`, and `--compile`. */
176
+ export interface ServerRuntimeConfig {
177
+ /** Public origin of the site (e.g. 'https://example.com'), inherited by @kayjs/seo, @kayjs/i18n, @kayjs/content, @kayjs/images, and @kayjs/auth. */
178
+ site?: string | undefined
179
+ lang?: string | undefined
180
+ assetPrefix?: string | undefined
181
+ security?: SecurityHeadersOptions | false | undefined
182
+ trustedOrigins?: string[] | undefined
183
+ trustProxy?: TrustProxy | undefined
184
+ maxRequestBodySize?: number | undefined
185
+ /** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
186
+ streamTimeout?: number | undefined
187
+ compress?: boolean | undefined
188
+ onError?: ((info: ServerErrorInfo) => void) | undefined
189
+ plugins?: KayPlugin[] | undefined
190
+ }
191
+
192
+ export interface KayConfig extends ServerRuntimeConfig {
193
+ port?: number | undefined
194
+ routesDir?: string | undefined
195
+ outDir?: string | undefined
196
+ publicDir?: string | undefined
197
+ }
@@ -0,0 +1,72 @@
1
+ // The app's server actions: their live URLs, the middleware each one runs behind, and invocation with its folder's `_middleware.ts` chain.
2
+
3
+ import type { ActionResult, ServerAction } from './action'
4
+ import type { Middleware, RequestContext } from './http'
5
+ import { invokeActionCore } from './action'
6
+ import { runChain } from './http'
7
+
8
+ export interface RegisteredAction {
9
+ act: ServerAction<unknown, unknown>
10
+ /** Plugin middlewares, then the `_middleware.ts` chain of the action's folder. */
11
+ middlewares: Middleware[]
12
+ }
13
+
14
+ export interface ActionRegistry {
15
+ /** Gives `act` its live URL and records the middlewares a request to it runs behind. */
16
+ register: (act: ServerAction<unknown, unknown>, url: string, dirMiddlewares: Middleware[], pluginMiddlewares: readonly Middleware[]) => void
17
+ byUrl: (url: string) => RegisteredAction | undefined
18
+ /** Runs an action with schema validation behind its folder's `_middleware.ts` chain, as an island call would. */
19
+ invoke: <I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext) => Promise<ActionResult<O>>
20
+ }
21
+
22
+ export function createActionRegistry(): ActionRegistry {
23
+ const handlers = new Map<string, RegisteredAction>()
24
+ const dirMiddlewaresByRef = new WeakMap<ServerAction<unknown, unknown>, Middleware[]>()
25
+
26
+ async function invoke<I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>> {
27
+ const dirMiddlewares = dirMiddlewaresByRef.get(act as unknown as ServerAction<unknown, unknown>) ?? []
28
+ if (dirMiddlewares.length === 0)
29
+ return invokeActionCore(act, input, ctx)
30
+
31
+ let actionResult: ActionResult<O> | undefined
32
+ const res = await runChain(ctx, dirMiddlewares, async () => {
33
+ actionResult = await invokeActionCore(act, input, ctx)
34
+ return new Response(null, { status: actionResult.ok ? 200 : actionResult.status })
35
+ })
36
+ if (actionResult !== undefined)
37
+ return actionResult
38
+ // A directory `_middleware.ts` short-circuited the request (e.g. 401/403 auth guard).
39
+ const ct = res.headers.get('content-type') ?? ''
40
+ if (ct.includes('application/json')) {
41
+ try {
42
+ const body = await res.clone().json() as Record<string, unknown>
43
+ return {
44
+ ok: false,
45
+ status: res.status,
46
+ error: typeof body.error === 'string' ? body.error : res.statusText || 'Forbidden',
47
+ }
48
+ }
49
+ catch {}
50
+ }
51
+ let text = ''
52
+ try {
53
+ text = await res.clone().text()
54
+ }
55
+ catch {}
56
+ return {
57
+ ok: false,
58
+ status: res.status,
59
+ error: text || res.statusText || 'Forbidden',
60
+ }
61
+ }
62
+
63
+ return {
64
+ register(act, url, dirMiddlewares, pluginMiddlewares) {
65
+ ;(act as { url: string }).url = url
66
+ dirMiddlewaresByRef.set(act, dirMiddlewares)
67
+ handlers.set(url, { act, middlewares: [...pluginMiddlewares, ...dirMiddlewares] })
68
+ },
69
+ byUrl: url => handlers.get(url),
70
+ invoke,
71
+ }
72
+ }