@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +615 -0
- package/src/build/compile.ts +32 -19
- package/src/build/files.ts +174 -0
- package/src/build/graph.ts +223 -0
- package/src/build/index.ts +255 -1461
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +227 -0
- package/src/build/plugin-host.ts +186 -0
- package/src/build/prerender.ts +94 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +51 -0
- package/src/build/routes.ts +163 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +300 -129
- package/src/cli/index.ts +297 -94
- package/src/cli/new.ts +58 -38
- package/src/compiler/analyze.ts +723 -93
- package/src/compiler/dom.ts +848 -762
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +172 -23
- package/src/compiler/shared.ts +485 -0
- package/src/compiler/ssr.ts +331 -342
- package/src/context.ts +120 -0
- package/src/dev/index.ts +358 -76
- package/src/dom/action.ts +114 -14
- package/src/dom/extras.ts +121 -83
- package/src/dom/index.ts +122 -80
- package/src/dom/island.ts +71 -36
- package/src/dom/loop.ts +28 -20
- package/src/index.ts +5 -1
- package/src/jsx-runtime.ts +432 -93
- package/src/plugins/context.ts +83 -0
- package/src/plugins/index.ts +285 -23
- package/src/reactivity/index.ts +237 -213
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +36 -11
- package/src/server/action.ts +157 -79
- package/src/server/compress.ts +197 -104
- package/src/server/cookies.ts +46 -16
- package/src/server/env.ts +18 -13
- package/src/server/http.ts +189 -77
- package/src/server/index.ts +1024 -878
- package/src/server/loader.ts +138 -0
- package/src/server/router.ts +69 -26
- package/src/server/security.ts +50 -58
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +144 -0
- package/src/ssr/context.ts +95 -10
- package/src/ssr/index.ts +167 -66
- package/src/style.ts +33 -0
- package/src/test/index.ts +5 -15
- package/src/unrenderable.ts +35 -0
package/src/plugins/index.ts
CHANGED
|
@@ -4,16 +4,27 @@
|
|
|
4
4
|
|
|
5
5
|
import type { BunPlugin } from 'bun'
|
|
6
6
|
import type { RouteManifestEntry } from '../build/index'
|
|
7
|
+
import type { ActionResult, ServerAction } from '../server/action'
|
|
7
8
|
import type { Middleware, RequestContext } from '../server/index'
|
|
8
|
-
import type { SecurityHeadersOptions } from '../server/security'
|
|
9
|
-
import {
|
|
9
|
+
import type { SecurityHeadersOptions, TrustProxy } from '../server/security'
|
|
10
|
+
import type { AppRuntimeContext } from './context'
|
|
11
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
10
12
|
import { join, resolve } from 'node:path'
|
|
13
|
+
import { createAppContext, getAppContext, runWithAppContext } from './context'
|
|
14
|
+
|
|
15
|
+
export { CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, getAppContext, I18N_CONFIG_SERVICE, runWithAppContext } from './context'
|
|
16
|
+
export type { ActiveI18nConfig, AppRuntimeContext, ContentImageResolver, ContentImageResult, CreateAppContextOptions } from './context'
|
|
17
|
+
|
|
18
|
+
export type BuildPluginTarget = 'client' | 'server' | 'compile'
|
|
11
19
|
|
|
12
20
|
export interface BuildPluginContext {
|
|
13
21
|
readonly root: string
|
|
14
22
|
readonly outDir: string
|
|
15
23
|
readonly assetPrefix: string
|
|
24
|
+
readonly site?: string | undefined
|
|
16
25
|
readonly minify: boolean
|
|
26
|
+
readonly isStatic: boolean
|
|
27
|
+
readonly dev: boolean
|
|
17
28
|
readonly routes: readonly RouteManifestEntry[]
|
|
18
29
|
/** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_kay/<relPath>`). */
|
|
19
30
|
emitAsset(relPath: string, content: string | Uint8Array): string
|
|
@@ -27,6 +38,36 @@ export interface BuildPluginContext {
|
|
|
27
38
|
addHead(html: string): void
|
|
28
39
|
/** Add raw HTML to <head> on a specific route path only. */
|
|
29
40
|
addRouteHead(routePath: string, html: string): void
|
|
41
|
+
/** Register an explicit build-scoped service for other plugins or render-time helpers. */
|
|
42
|
+
provide<T>(key: string, value: T): void
|
|
43
|
+
/** Look up a build-scoped service registered by another plugin. */
|
|
44
|
+
inject<T>(key: string): T | undefined
|
|
45
|
+
/** Persist JSON-serializable build data into `manifest.pluginData[plugin.name]` for cold-start servers and `--compile`. */
|
|
46
|
+
setData(data: Record<string, unknown>): void
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface FinalizeBuildContext {
|
|
50
|
+
readonly root: string
|
|
51
|
+
readonly outDir: string
|
|
52
|
+
readonly assetPrefix: string
|
|
53
|
+
readonly site?: string | undefined
|
|
54
|
+
readonly minify: boolean
|
|
55
|
+
readonly isStatic: boolean
|
|
56
|
+
readonly dev: boolean
|
|
57
|
+
/** Route manifest entries with `prerendered` maps populated after Step 3 prerendering. */
|
|
58
|
+
readonly routes: readonly RouteManifestEntry[]
|
|
59
|
+
/** Relative paths of all public files known so far (including files registered during prerender). */
|
|
60
|
+
readonly publicFiles: readonly string[]
|
|
61
|
+
/** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_kay/<relPath>`). */
|
|
62
|
+
emitAsset(relPath: string, content: string | Uint8Array): string
|
|
63
|
+
/** Emit a static file into dist/public/<relPath> served at `/<relPath>` (included in `--static` and `--compile`). */
|
|
64
|
+
emitPublic(relPath: string, content: string | Uint8Array): string
|
|
65
|
+
/** Register a build-scoped service. */
|
|
66
|
+
provide<T>(key: string, value: T): void
|
|
67
|
+
/** Look up a build-scoped service. */
|
|
68
|
+
inject<T>(key: string): T | undefined
|
|
69
|
+
/** Merge/persist JSON-serializable build data into `manifest.pluginData[plugin.name]`. */
|
|
70
|
+
setData(data: Record<string, unknown>): void
|
|
30
71
|
}
|
|
31
72
|
|
|
32
73
|
export interface CheckPluginContext {
|
|
@@ -37,17 +78,46 @@ export interface CheckPluginContext {
|
|
|
37
78
|
}
|
|
38
79
|
|
|
39
80
|
export interface PluginRouteOptions {
|
|
40
|
-
/** Enable CSRF Origin/Sec-Fetch-Site verification on unsafe methods (default: true). Set `false` to opt out (e.g. webhooks). */
|
|
81
|
+
/** Enable CSRF Origin/Sec-Fetch-Site verification on unsafe methods (default: true). Set `false` to opt out (e.g. webhooks, bearer-token APIs). */
|
|
41
82
|
csrf?: boolean | undefined
|
|
83
|
+
/** Additional trusted origins merged with `KayConfig.trustedOrigins` for this route's CSRF check. */
|
|
84
|
+
trustedOrigins?: readonly string[] | undefined
|
|
85
|
+
/** Override `KayConfig.trustProxy` for this route's CSRF check. */
|
|
86
|
+
trustProxy?: TrustProxy | undefined
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface MiddlewareOptions {
|
|
90
|
+
/** `'all'` (default) runs on every route; `'dynamic'` skips static/prerendered fast paths; a string prefix scopes to matching pathnames. */
|
|
91
|
+
scope?: 'all' | 'dynamic' | string | undefined
|
|
42
92
|
}
|
|
43
93
|
|
|
44
94
|
export interface ServerPluginAPI {
|
|
45
|
-
|
|
46
|
-
|
|
95
|
+
readonly root: string
|
|
96
|
+
readonly outDir: string
|
|
97
|
+
readonly assetPrefix: string
|
|
98
|
+
readonly site?: string | undefined
|
|
99
|
+
readonly dev: boolean
|
|
100
|
+
/** Readonly server security configuration so plugins inherit `trustProxy` / `trustedOrigins` without overriding them. */
|
|
101
|
+
readonly trustProxy: TrustProxy
|
|
102
|
+
readonly trustedOrigins: readonly string[]
|
|
103
|
+
/** Readonly runtime config forwarded from `kay.config.ts` (minus build-only keys). */
|
|
104
|
+
readonly config?: Readonly<Record<string, unknown>> | undefined
|
|
105
|
+
/** Register global (or scoped) middleware that runs before route handlers. */
|
|
106
|
+
use(middleware: Middleware, options?: MiddlewareOptions): void
|
|
47
107
|
/** Register a custom HTTP route (e.g. GET /sitemap.xml, POST /auth/callback). */
|
|
48
108
|
route(method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions): void
|
|
49
109
|
/** Rewrite an incoming pathname before route matching (e.g. strip /fr locale prefix). */
|
|
50
110
|
rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
|
|
111
|
+
/** Register a server-scoped service for other plugins or render-time helpers (isolated per server instance). */
|
|
112
|
+
provide<T>(key: string, value: T): void
|
|
113
|
+
/** Look up a server-scoped service registered by another plugin. */
|
|
114
|
+
inject<T>(key: string): T | undefined
|
|
115
|
+
/** Read persisted build data from `manifest.pluginData` (defaults to the current plugin's name). */
|
|
116
|
+
getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined
|
|
117
|
+
/** Register a shutdown cleanup callback run when `app.dispose()` is called (dev reloads, tests, graceful exit). */
|
|
118
|
+
onShutdown(fn: () => void | Promise<void>): void
|
|
119
|
+
/** Invoke a ServerAction with Standard Schema validation and directory-scoped `_middleware.ts` checks. */
|
|
120
|
+
invokeAction<I, O>(action: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>>
|
|
51
121
|
}
|
|
52
122
|
|
|
53
123
|
export interface ServerErrorInfo {
|
|
@@ -56,21 +126,48 @@ export interface ServerErrorInfo {
|
|
|
56
126
|
source: 'route' | 'action' | 'plugin'
|
|
57
127
|
}
|
|
58
128
|
|
|
129
|
+
export interface DocumentHeadContext {
|
|
130
|
+
/** Current document `lang` attribute (mutating sets `<html lang="...">`). */
|
|
131
|
+
lang: string
|
|
132
|
+
/** Extra attributes emitted on `<html>`. */
|
|
133
|
+
readonly htmlAttrs: Record<string, string>
|
|
134
|
+
/** Inner HTML of the page's `<title>` tag (if rendered via `<Head><title>...</title></Head>`), or `undefined`. */
|
|
135
|
+
title: string | undefined
|
|
136
|
+
/** Read-only view of head HTML already collected from `<Head>`, build `addHead`, and earlier plugins. */
|
|
137
|
+
readonly headHtml: string
|
|
138
|
+
/** Append raw HTML to `<head>` (emitted once by core when assembling the document). */
|
|
139
|
+
add(html: string): void
|
|
140
|
+
}
|
|
141
|
+
|
|
59
142
|
export interface KayPlugin {
|
|
60
143
|
name: string
|
|
61
|
-
/**
|
|
144
|
+
/** Execution phase: `'pre'` runs before normal plugins, `'post'` runs after them. */
|
|
145
|
+
enforce?: 'pre' | 'post' | undefined
|
|
146
|
+
/** Names of plugins that must run before this plugin when present. */
|
|
147
|
+
after?: readonly string[] | undefined
|
|
148
|
+
/** `ctx.locals` keys this plugin populates (used for startup order validation). */
|
|
149
|
+
providesLocals?: readonly string[] | undefined
|
|
150
|
+
/** `ctx.locals` keys this plugin reads (startup fails if a provider is ordered after it). */
|
|
151
|
+
readsLocals?: readonly string[] | undefined
|
|
152
|
+
/** Register server routes, global middleware, URL rewrites, or runtime services. */
|
|
62
153
|
server?: (api: ServerPluginAPI) => void | Promise<void>
|
|
154
|
+
/** Optional cleanup hook called when a server instance is disposed (dev reloads, tests, graceful shutdown). */
|
|
155
|
+
dispose?: () => void | Promise<void>
|
|
63
156
|
/** Error hook called whenever a route, action, or plugin handler throws an unhandled error. */
|
|
64
157
|
onError?: (info: ServerErrorInfo) => void
|
|
65
158
|
/** Build hook run after route compilation, before prerender / --static / --compile. */
|
|
66
159
|
build?: (ctx: BuildPluginContext) => void | Promise<void>
|
|
67
|
-
/**
|
|
160
|
+
/** Post-prerender build hook run after `route.prerendered` is populated, before `--static` / `--compile` / final manifest write. */
|
|
161
|
+
afterPrerender?: (ctx: FinalizeBuildContext) => void | Promise<void>
|
|
162
|
+
/** Code transform run during client & server compilation (`.ts` and `.tsx`). */
|
|
68
163
|
transform?: (code: string, id: string, target: 'server' | 'client') => string | undefined | void
|
|
69
|
-
/** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). */
|
|
70
|
-
bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean }) => BunPlugin[]) | undefined
|
|
164
|
+
/** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). Factory is invoked per build target. */
|
|
165
|
+
bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget }) => BunPlugin[]) | undefined
|
|
71
166
|
/** Global CSS files to bundle and inject as <link rel="stylesheet"> in <head>. */
|
|
72
167
|
css?: string[] | undefined
|
|
73
|
-
/**
|
|
168
|
+
/** Mutate `<html lang>`, `htmlAttrs`, `<title>`, or append tags to `<head>` before core renders the document once. */
|
|
169
|
+
head?: (head: DocumentHeadContext, ctx: RequestContext) => void | Promise<void>
|
|
170
|
+
/** Post-process rendered HTML before sending (applies to pages, `<Suspense>` shells, `_error.tsx`, and `_404.tsx`). */
|
|
74
171
|
transformHtml?: (html: string, ctx: RequestContext) => string | Promise<string>
|
|
75
172
|
/** Expand or filter prerender URLs for a route (e.g. @kayjs/i18n expanding `/posts/a` -> `['/posts/a', '/fr/posts/a']`). */
|
|
76
173
|
prerenderPaths?: (paths: string[], route: RouteManifestEntry) => string[] | Promise<string[]>
|
|
@@ -84,42 +181,207 @@ export interface KayPlugin {
|
|
|
84
181
|
commands?: Record<string, (args: string[], root: string) => void | Promise<void>> | undefined
|
|
85
182
|
}
|
|
86
183
|
|
|
87
|
-
|
|
184
|
+
/** Shared runtime server options inherited from `kay.config.ts` and overridable by `createServer`, `testApp`, `devServer`, and `--compile`. */
|
|
185
|
+
export interface ServerRuntimeConfig {
|
|
186
|
+
/** Public origin of the site (e.g. 'https://example.com'), inherited by @kayjs/seo, @kayjs/i18n, @kayjs/content, @kayjs/images, and @kayjs/auth. */
|
|
187
|
+
site?: string | undefined
|
|
88
188
|
lang?: string | undefined
|
|
89
|
-
port?: number | undefined
|
|
90
|
-
routesDir?: string | undefined
|
|
91
|
-
outDir?: string | undefined
|
|
92
|
-
publicDir?: string | undefined
|
|
93
189
|
assetPrefix?: string | undefined
|
|
94
190
|
security?: SecurityHeadersOptions | false | undefined
|
|
95
191
|
trustedOrigins?: string[] | undefined
|
|
96
|
-
trustProxy?:
|
|
192
|
+
trustProxy?: TrustProxy | undefined
|
|
97
193
|
maxRequestBodySize?: number | undefined
|
|
194
|
+
/** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
|
|
195
|
+
streamTimeout?: number | undefined
|
|
98
196
|
compress?: boolean | undefined
|
|
99
197
|
onError?: ((info: ServerErrorInfo) => void) | undefined
|
|
100
198
|
plugins?: KayPlugin[] | undefined
|
|
101
199
|
}
|
|
102
200
|
|
|
201
|
+
export interface KayConfig extends ServerRuntimeConfig {
|
|
202
|
+
port?: number | undefined
|
|
203
|
+
routesDir?: string | undefined
|
|
204
|
+
outDir?: string | undefined
|
|
205
|
+
publicDir?: string | undefined
|
|
206
|
+
}
|
|
207
|
+
|
|
103
208
|
export function defineConfig(config: KayConfig): KayConfig {
|
|
104
209
|
return config
|
|
105
210
|
}
|
|
106
211
|
|
|
212
|
+
/** Forwards every runtime key from `kay.config.ts`, stripping build/CLI-only keys (`routesDir`, `outDir`, `publicDir`, `port`). */
|
|
213
|
+
export function pickRuntimeConfig(config: KayConfig | undefined): ServerRuntimeConfig {
|
|
214
|
+
if (config === undefined)
|
|
215
|
+
return {}
|
|
216
|
+
const { routesDir: _r, outDir: _o, publicDir: _p, port: _pt, ...runtime } = config
|
|
217
|
+
return runtime
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const RUNTIME_CONFIG_KEYS: readonly (keyof ServerRuntimeConfig)[] = [
|
|
221
|
+
'site',
|
|
222
|
+
'lang',
|
|
223
|
+
'assetPrefix',
|
|
224
|
+
'security',
|
|
225
|
+
'trustedOrigins',
|
|
226
|
+
'trustProxy',
|
|
227
|
+
'maxRequestBodySize',
|
|
228
|
+
'streamTimeout',
|
|
229
|
+
'compress',
|
|
230
|
+
'onError',
|
|
231
|
+
'plugins',
|
|
232
|
+
]
|
|
233
|
+
|
|
234
|
+
/** Merges runtime options from `kay.config.ts` with explicit caller overrides (ignoring `undefined` override fields). */
|
|
235
|
+
export function resolveServerConfig(
|
|
236
|
+
fileConfig: KayConfig | undefined,
|
|
237
|
+
overrides?: Partial<ServerRuntimeConfig> | undefined,
|
|
238
|
+
): ServerRuntimeConfig {
|
|
239
|
+
const merged: Record<string, unknown> = { ...pickRuntimeConfig(fileConfig) }
|
|
240
|
+
if (overrides !== undefined) {
|
|
241
|
+
for (const key of RUNTIME_CONFIG_KEYS) {
|
|
242
|
+
const value = overrides[key]
|
|
243
|
+
if (value !== undefined)
|
|
244
|
+
merged[key] = value
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return merged as ServerRuntimeConfig
|
|
248
|
+
}
|
|
249
|
+
|
|
107
250
|
export function definePlugin(plugin: KayPlugin): KayPlugin {
|
|
108
251
|
return plugin
|
|
109
252
|
}
|
|
110
253
|
|
|
111
|
-
|
|
254
|
+
function enforceRank(plugin: KayPlugin): number {
|
|
255
|
+
return plugin.enforce === 'pre' ? 0 : plugin.enforce === 'post' ? 2 : 1
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Sorts plugins stably by `enforce` (`'pre'` -> normal -> `'post'`) and `after` dependencies,
|
|
260
|
+
* then fails fast if any plugin declares `readsLocals` for a key whose provider runs after it.
|
|
261
|
+
*/
|
|
262
|
+
export function resolvePlugins(plugins: readonly KayPlugin[] | undefined): KayPlugin[] {
|
|
263
|
+
if (plugins === undefined || plugins.length === 0)
|
|
264
|
+
return []
|
|
265
|
+
|
|
266
|
+
// Base stable order by `enforce` bucket, preserving config declaration order within each bucket.
|
|
267
|
+
const base = plugins
|
|
268
|
+
.map((plugin, index) => ({ plugin, index, rank: enforceRank(plugin) }))
|
|
269
|
+
.sort((a, b) => a.rank - b.rank || a.index - b.index)
|
|
270
|
+
.map(entry => entry.plugin)
|
|
271
|
+
|
|
272
|
+
const n = base.length
|
|
273
|
+
const indicesByName = new Map<string, number[]>()
|
|
274
|
+
for (let i = 0; i < n; i++) {
|
|
275
|
+
const name = base[i]!.name
|
|
276
|
+
const list = indicesByName.get(name)
|
|
277
|
+
if (list === undefined)
|
|
278
|
+
indicesByName.set(name, [i])
|
|
279
|
+
else
|
|
280
|
+
list.push(i)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Kahn's topological sort using min-index priority so `enforce` + declaration order stays deterministic.
|
|
284
|
+
const inDegree = new Int32Array(n)
|
|
285
|
+
const edges: number[][] = Array.from({ length: n }, () => [])
|
|
286
|
+
for (let i = 0; i < n; i++) {
|
|
287
|
+
const deps = base[i]!.after
|
|
288
|
+
if (deps === undefined)
|
|
289
|
+
continue
|
|
290
|
+
const seen = new Set<number>()
|
|
291
|
+
for (const depName of deps) {
|
|
292
|
+
const targets = indicesByName.get(depName)
|
|
293
|
+
if (targets === undefined)
|
|
294
|
+
continue
|
|
295
|
+
for (const depIdx of targets) {
|
|
296
|
+
if (depIdx === i || seen.has(depIdx))
|
|
297
|
+
continue
|
|
298
|
+
seen.add(depIdx)
|
|
299
|
+
edges[depIdx]!.push(i)
|
|
300
|
+
inDegree[i] = (inDegree[i] ?? 0) + 1
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const ready: number[] = []
|
|
306
|
+
for (let i = 0; i < n; i++) {
|
|
307
|
+
if (inDegree[i] === 0)
|
|
308
|
+
ready.push(i)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const sorted: KayPlugin[] = []
|
|
312
|
+
while (ready.length > 0) {
|
|
313
|
+
// Pick lowest base index so `enforce` and user declaration order are preserved whenever unconstrained.
|
|
314
|
+
let bestPos = 0
|
|
315
|
+
for (let k = 1; k < ready.length; k++) {
|
|
316
|
+
if (ready[k]! < ready[bestPos]!)
|
|
317
|
+
bestPos = k
|
|
318
|
+
}
|
|
319
|
+
const u = ready.splice(bestPos, 1)[0]!
|
|
320
|
+
sorted.push(base[u]!)
|
|
321
|
+
for (const v of edges[u]!) {
|
|
322
|
+
inDegree[v] = (inDegree[v] ?? 0) - 1
|
|
323
|
+
if (inDegree[v] === 0)
|
|
324
|
+
ready.push(v)
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
if (sorted.length !== n) {
|
|
329
|
+
const stuck = base.filter((_, idx) => (inDegree[idx] ?? 0) > 0).map(p => p.name)
|
|
330
|
+
throw new Error(`kay: circular plugin \`after\` dependency involving: ${stuck.join(', ')}`)
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// Validate that no plugin reads a ctx.locals key before another active plugin provides it.
|
|
334
|
+
const providerByLocal = new Map<string, { name: string, index: number }>()
|
|
335
|
+
for (let i = 0; i < sorted.length; i++) {
|
|
336
|
+
const plugin = sorted[i]!
|
|
337
|
+
for (const key of plugin.providesLocals ?? []) {
|
|
338
|
+
if (!providerByLocal.has(key))
|
|
339
|
+
providerByLocal.set(key, { name: plugin.name, index: i })
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
for (let i = 0; i < sorted.length; i++) {
|
|
344
|
+
const plugin = sorted[i]!
|
|
345
|
+
for (const key of plugin.readsLocals ?? []) {
|
|
346
|
+
const provider = providerByLocal.get(key)
|
|
347
|
+
if (provider !== undefined && provider.index > i) {
|
|
348
|
+
throw new Error(
|
|
349
|
+
`kay: plugin "${plugin.name}" reads ctx.locals.${key} before "${provider.name}" provides it. Add \`after: [${JSON.stringify(provider.name)}]\` or adjust plugin order.`,
|
|
350
|
+
)
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
return sorted
|
|
356
|
+
}
|
|
357
|
+
|
|
112
358
|
let configReloadSeq = 0
|
|
113
359
|
|
|
114
|
-
|
|
360
|
+
// 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.
|
|
361
|
+
function configSpecifier(configPath: string, fresh: boolean): string {
|
|
362
|
+
if (fresh)
|
|
363
|
+
return `${configPath}?v=fresh-${++configReloadSeq}`
|
|
364
|
+
if (process.env.KAY_DEV === '1')
|
|
365
|
+
return `${configPath}?v=${Bun.hash(readFileSync(configPath)).toString(36)}`
|
|
366
|
+
return configPath
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export async function loadConfig(root: string, options?: { fresh?: boolean, appContext?: AppRuntimeContext }): Promise<KayConfig> {
|
|
115
370
|
const absRoot = resolve(root)
|
|
116
|
-
;(globalThis as Record<symbol, unknown>)[KAY_ROOT_KEY] = absRoot
|
|
117
371
|
const configPath = join(absRoot, 'kay.config.ts')
|
|
118
372
|
if (!existsSync(configPath))
|
|
119
373
|
return {}
|
|
120
|
-
const spec = options?.fresh
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
374
|
+
const spec = configSpecifier(configPath, options?.fresh === true)
|
|
375
|
+
const active = options?.appContext ?? getAppContext()
|
|
376
|
+
const ctx = active !== undefined && active.root === absRoot
|
|
377
|
+
? active
|
|
378
|
+
: createAppContext({
|
|
379
|
+
root: absRoot,
|
|
380
|
+
outDir: join(absRoot, 'dist'),
|
|
381
|
+
publicDir: join(absRoot, 'dist', 'public'),
|
|
382
|
+
assetPrefix: '/_kay',
|
|
383
|
+
dev: process.env.KAY_DEV === '1',
|
|
384
|
+
})
|
|
385
|
+
const mod = await runWithAppContext(ctx, () => import(spec)) as { default?: KayConfig }
|
|
124
386
|
return mod.default ?? {}
|
|
125
387
|
}
|