@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,193 @@
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 { Middleware, RequestContext } from '../server/index'
6
+ import type { SecurityHeadersOptions, TrustProxy } from '../server/security'
7
+ import type { ServiceKey } from './services'
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: ServiceKey<T>, value: T): void
34
+ /** Look up a build-scoped service registered by another plugin. */
35
+ inject<T>(key: ServiceKey<T>): 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: ServiceKey<T>, value: T): void
58
+ /** Look up a build-scoped service. */
59
+ inject<T>(key: ServiceKey<T>): 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: ServiceKey<T>, value: T): void
104
+ /** Look up a server-scoped service registered by another plugin. */
105
+ inject<T>(key: ServiceKey<T>): 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
+ }
111
+
112
+ export interface ServerErrorInfo {
113
+ error: unknown
114
+ request: Request
115
+ source: 'route' | 'action' | 'plugin'
116
+ }
117
+
118
+ export interface DocumentHeadContext {
119
+ /** Current document `lang` attribute (mutating sets `<html lang="...">`). */
120
+ lang: string
121
+ /** Extra attributes emitted on `<html>`. */
122
+ readonly htmlAttrs: Record<string, string>
123
+ /** Inner HTML of the page's `<title>` tag (if rendered via `<Head><title>...</title></Head>`), or `undefined`. */
124
+ title: string | undefined
125
+ /** Read-only view of head HTML already collected from `<Head>`, build `addHead`, and earlier plugins. */
126
+ readonly headHtml: string
127
+ /** Append raw HTML to `<head>` (emitted once by core when assembling the document). */
128
+ add(html: string): void
129
+ }
130
+
131
+ export interface KayPlugin {
132
+ name: string
133
+ /** Execution phase: `'pre'` runs before normal plugins, `'post'` runs after them. */
134
+ enforce?: 'pre' | 'post' | undefined
135
+ /** Names of plugins that must run before this plugin when present. */
136
+ after?: readonly string[] | undefined
137
+ /** `ctx.locals` keys this plugin populates (used for startup order validation). */
138
+ providesLocals?: readonly string[] | undefined
139
+ /** `ctx.locals` keys this plugin reads (startup fails if a provider is ordered after it). */
140
+ readsLocals?: readonly string[] | undefined
141
+ /** Register server routes, global middleware, URL rewrites, or runtime services. */
142
+ server?: (api: ServerPluginAPI) => void | Promise<void>
143
+ /** Error hook called whenever a route, action, or plugin handler throws an unhandled error. */
144
+ onError?: (info: ServerErrorInfo) => void
145
+ /** Build hook run after route compilation, before prerender / --static / --compile. */
146
+ build?: (ctx: BuildPluginContext) => void | Promise<void>
147
+ /** Post-prerender build hook run after `route.prerendered` is populated, before `--static` / `--compile` / final manifest write. */
148
+ afterPrerender?: (ctx: FinalizeBuildContext) => void | Promise<void>
149
+ /** Code transform run during client & server compilation (`.ts` and `.tsx`). */
150
+ transform?: (code: string, id: string, target: 'server' | 'client') => string | undefined | void
151
+ /** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). Factory is invoked per build target. */
152
+ bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget }) => BunPlugin[]) | undefined
153
+ /** Global CSS files to bundle and inject as <link rel="stylesheet"> in <head>. */
154
+ css?: string[] | undefined
155
+ /** Mutate `<html lang>`, `htmlAttrs`, `<title>`, or append tags to `<head>` before core renders the document once. */
156
+ head?: (head: DocumentHeadContext, ctx: RequestContext) => void | Promise<void>
157
+ /** Post-process rendered HTML before sending (applies to pages, `<Suspense>` shells, `_error.tsx`, and `_404.tsx`). */
158
+ transformHtml?: (html: string, ctx: RequestContext) => string | Promise<string>
159
+ /** Expand or filter prerender URLs for a route (e.g. @kayjs/i18n expanding `/posts/a` -> `['/posts/a', '/fr/posts/a']`). */
160
+ prerenderPaths?: (paths: string[], route: RouteManifestEntry) => string[] | Promise<string[]>
161
+ /** Client bootstrap module path — bundled ONLY when this plugin is active. */
162
+ clientEntry?: string | undefined
163
+ /** Validate plugin-specific invariants during `kay check` (e.g. missing i18n keys, content frontmatter). */
164
+ check?: (ctx: CheckPluginContext) => void | Promise<void>
165
+ /** Extra directories or files (relative to app root or absolute) for `kay dev` to watch. */
166
+ watchPaths?: string[] | ((root: string) => string[]) | undefined
167
+ /** Register custom CLI subcommands (e.g. `kay i18n check`). */
168
+ commands?: Record<string, (args: string[], root: string) => void | Promise<void>> | undefined
169
+ }
170
+
171
+ /** Shared runtime server options inherited from `kay.config.ts` and overridable by `createServer`, `testApp`, `devServer`, and `--compile`. */
172
+ export interface ServerRuntimeConfig {
173
+ /** Public origin of the site (e.g. 'https://example.com'), inherited by @kayjs/seo, @kayjs/i18n, @kayjs/content, @kayjs/images, and @kayjs/auth. */
174
+ site?: string | undefined
175
+ lang?: string | undefined
176
+ assetPrefix?: string | undefined
177
+ security?: SecurityHeadersOptions | false | undefined
178
+ trustedOrigins?: string[] | undefined
179
+ trustProxy?: TrustProxy | undefined
180
+ maxRequestBodySize?: number | undefined
181
+ /** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
182
+ streamTimeout?: number | undefined
183
+ compress?: boolean | undefined
184
+ onError?: ((info: ServerErrorInfo) => void) | undefined
185
+ plugins?: KayPlugin[] | undefined
186
+ }
187
+
188
+ export interface KayConfig extends ServerRuntimeConfig {
189
+ port?: number | undefined
190
+ routesDir?: string | undefined
191
+ outDir?: string | undefined
192
+ publicDir?: string | undefined
193
+ }
@@ -0,0 +1,78 @@
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
+ import { runInRequest } from './request-scope'
8
+
9
+ export interface RegisteredAction {
10
+ act: ServerAction<unknown, unknown>
11
+ /** Plugin middlewares, then the `_middleware.ts` chain of the action's folder. */
12
+ middlewares: Middleware[]
13
+ }
14
+
15
+ export interface ActionRegistry {
16
+ /** Gives `act` its name and live URL and records the middlewares a request to it runs behind. */
17
+ register: (act: ServerAction<unknown, unknown>, name: string, url: string, dirMiddlewares: Middleware[], pluginMiddlewares: readonly Middleware[]) => void
18
+ byUrl: (url: string) => RegisteredAction | undefined
19
+ /** Runs an action with schema validation behind its folder's `_middleware.ts` chain, as an island call would. */
20
+ invoke: <I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext) => Promise<ActionResult<O>>
21
+ /** Runs `fn` as part of the request `ctx`, so the actions it calls run in that request. */
22
+ run: <T>(ctx: RequestContext, fn: () => T) => T
23
+ }
24
+
25
+ export function createActionRegistry(): ActionRegistry {
26
+ const handlers = new Map<string, RegisteredAction>()
27
+ const dirMiddlewaresByRef = new WeakMap<ServerAction<unknown, unknown>, Middleware[]>()
28
+
29
+ async function invoke<I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>> {
30
+ const dirMiddlewares = dirMiddlewaresByRef.get(act as unknown as ServerAction<unknown, unknown>) ?? []
31
+ if (dirMiddlewares.length === 0)
32
+ return invokeActionCore(act, input, ctx)
33
+
34
+ let actionResult: ActionResult<O> | undefined
35
+ const res = await runChain(ctx, dirMiddlewares, async () => {
36
+ actionResult = await invokeActionCore(act, input, ctx)
37
+ return new Response(null, { status: actionResult.ok ? 200 : actionResult.status })
38
+ })
39
+ if (actionResult !== undefined)
40
+ return actionResult
41
+ // A directory `_middleware.ts` short-circuited the request (e.g. 401/403 auth guard).
42
+ const ct = res.headers.get('content-type') ?? ''
43
+ if (ct.includes('application/json')) {
44
+ try {
45
+ const body = await res.clone().json() as Record<string, unknown>
46
+ return {
47
+ ok: false,
48
+ status: res.status,
49
+ error: typeof body.error === 'string' ? body.error : res.statusText || 'Forbidden',
50
+ }
51
+ }
52
+ catch {}
53
+ }
54
+ let text = ''
55
+ try {
56
+ text = await res.clone().text()
57
+ }
58
+ catch {}
59
+ return {
60
+ ok: false,
61
+ status: res.status,
62
+ error: text || res.statusText || 'Forbidden',
63
+ }
64
+ }
65
+
66
+ const registry: ActionRegistry = {
67
+ register(act, name, url, dirMiddlewares, pluginMiddlewares) {
68
+ ;(act as { url: string }).url = url
69
+ Object.defineProperty(act, 'name', { value: name, configurable: true })
70
+ dirMiddlewaresByRef.set(act, dirMiddlewares)
71
+ handlers.set(url, { act, middlewares: [...pluginMiddlewares, ...dirMiddlewares] })
72
+ },
73
+ byUrl: url => handlers.get(url),
74
+ invoke,
75
+ run: (ctx, fn) => runInRequest({ ctx, actions: registry }, fn),
76
+ }
77
+ return registry
78
+ }
@@ -5,6 +5,7 @@ import type { KayLocals } from './index'
5
5
  import type { TrustProxy } from './security'
6
6
  import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
7
7
  import { wantsJson } from './http'
8
+ import { currentRequest } from './request-scope'
8
9
  import { isTrustedOrigin } from './security'
9
10
  import { validateSchema } from './standard-schema'
10
11
 
@@ -86,11 +87,16 @@ export function action(
86
87
  : ((_input: never, ctx: ActionContext) => (schemaOrHandler as (c: ActionContext) => unknown)(ctx))
87
88
  const options = hasSchema ? maybeOpts : (maybeHandlerOrOpts as ActionOptions | undefined)
88
89
 
89
- const fn = (async () => {
90
- throw new Error('kay: server action cannot be called directly without a request context; invoke it from an island or via HTTP POST')
90
+ const fn = (async (input: unknown) => {
91
+ const scope = currentRequest()
92
+ if (scope === undefined)
93
+ throw new Error(`kay: ${fn.name || 'a server action'} was called outside a request; call it from a route, load(), middleware or another action, or with app.submit in a test.`)
94
+ return scope.actions.invoke(fn, input, scope.ctx)
91
95
  }) as unknown as ServerAction<unknown, unknown> & { url: string }
92
96
 
93
97
  Object.defineProperties(fn, {
98
+ // The registry names it after its export.
99
+ name: { value: '', configurable: true },
94
100
  __kayAction: { value: true, enumerable: false },
95
101
  schema: { value: schema, enumerable: false },
96
102
  flashFields: { value: options?.flashFields, enumerable: false },
@@ -0,0 +1,23 @@
1
+ // What the generated `dist/server/_entry.js` calls: an app from its bundled config and modules, plus what the caller serves it with.
2
+
3
+ import type { KayConfig } from '../plugins/index'
4
+ import type { EmbeddedServerConfig, KayApp } from './http'
5
+ import { resolveServerConfig } from '../plugins/index'
6
+ import { createServerFromEmbedded } from './index'
7
+
8
+ /** The manifest, assets and paths the caller read or embedded; runtime keys set here win over `kay.config.ts`. */
9
+ export type AppEntryOptions = Omit<EmbeddedServerConfig, 'modules'>
10
+
11
+ /** The exports of `dist/server/_entry.js`. */
12
+ export interface ServerEntry {
13
+ kayConfig: KayConfig
14
+ /** Bundled modules by manifest key. */
15
+ modules: Record<string, Record<string, unknown>>
16
+ /** The same modules by root-relative source path. */
17
+ sources: Record<string, Record<string, unknown>>
18
+ createApp: (options: AppEntryOptions) => Promise<KayApp>
19
+ }
20
+
21
+ export function createAppFromEntry(config: KayConfig, modules: Record<string, unknown>, options: AppEntryOptions): Promise<KayApp> {
22
+ return createServerFromEmbedded({ ...options, ...resolveServerConfig(config, options), modules })
23
+ }
@@ -0,0 +1,182 @@
1
+ // Files served as they are: hashed build assets, public files and prerendered pages, with their headers fixed at startup.
2
+
3
+ import type { RouteManifestEntry } from '../build/index'
4
+ import type { CompressionCache } from './compress'
5
+ import type { EmbeddedBody } from './http'
6
+ import { existsSync, statSync } from 'node:fs'
7
+ import { extname, join } from 'node:path'
8
+ import { isCompressibleType, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
9
+ import { etagMatches, MIME } from './http'
10
+
11
+ const textEncoder = new TextEncoder()
12
+
13
+ // A build file ready to serve: headers and compression key are fixed at startup, so a request only picks a variant.
14
+ export interface ServedFile {
15
+ key: string
16
+ headers: Record<string, string>
17
+ /** Headers of the on-the-fly compressed variant; undefined when the file is never compressed here. */
18
+ compressedHeaders: Record<string, string> | undefined
19
+ body: BodyInit
20
+ read: () => Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>
21
+ }
22
+
23
+ interface Sidecar {
24
+ body: BodyInit
25
+ headers: Record<string, string>
26
+ }
27
+
28
+ export interface AssetEntry {
29
+ file: ServedFile
30
+ br: Sidecar | undefined
31
+ gz: Sidecar | undefined
32
+ }
33
+
34
+ export interface PublicEntry {
35
+ file: ServedFile
36
+ etag: string
37
+ notModifiedHeaders: Record<string, string>
38
+ }
39
+
40
+ export interface AssetsOptions {
41
+ assets: Record<string, EmbeddedBody>
42
+ assetPrefix: string
43
+ isDev: boolean
44
+ compressEnabled: boolean
45
+ compressCache: CompressionCache | undefined
46
+ nosniffHeader: Record<string, string>
47
+ withHsts: (res: Response, request: Request) => Response
48
+ }
49
+
50
+ export interface PrerenderedSources {
51
+ prerendered: Record<string, string>
52
+ prerenderedFiles: Record<string, string>
53
+ /** HTML headers of a prerendered page, before the `Vary` header compression adds. */
54
+ htmlHeaders: (route: RouteManifestEntry, urlPath: string) => Record<string, string>
55
+ /** Whether a prerendered URL may be answered before any middleware, rewrite or plugin route. */
56
+ isFast: (urlPath: string, route: RouteManifestEntry) => boolean
57
+ }
58
+
59
+ export function createAssets(options: AssetsOptions) {
60
+ const { assets, assetPrefix, isDev, compressEnabled, compressCache, nosniffHeader, withHsts } = options
61
+ const varyEncoding: Record<string, string> = compressCache !== undefined ? { vary: 'Accept-Encoding' } : {}
62
+
63
+ const toBody = (body: EmbeddedBody): BodyInit => typeof body === 'string' ? Bun.file(body) : body
64
+ const readBody = async (body: EmbeddedBody): Promise<Uint8Array<ArrayBuffer>> => typeof body === 'string' ? new Uint8Array(await Bun.file(body).arrayBuffer()) : body
65
+ const builtFile = (key: string, source: EmbeddedBody, headers: Record<string, string>, compressedHeaders: Record<string, string> | undefined): ServedFile =>
66
+ ({ key, headers, compressedHeaders, body: toBody(source), read: () => readBody(source) })
67
+
68
+ const publicMap = new Map<string, PublicEntry>()
69
+ const publicCacheControl = isDev ? 'no-cache' : 'public, max-age=3600'
70
+
71
+ const registerPublic = (rel: string, body: EmbeddedBody, explicitEtag?: string): void => {
72
+ const cleanRel = rel.replace(/^\/+/, '')
73
+ const etag = explicitEtag ?? `W/"${Bun.hash(typeof body === 'string' ? cleanRel : body).toString(36)}"`
74
+ const type = MIME[extname(cleanRel).toLowerCase()] ?? 'application/octet-stream'
75
+ const hasVary = compressCache !== undefined && isCompressibleType(type)
76
+ const validators = { etag, 'cache-control': publicCacheControl, ...(hasVary ? { vary: 'Accept-Encoding' } : {}), ...nosniffHeader }
77
+ const headers = { 'content-type': type, ...validators }
78
+ publicMap.set(`/${cleanRel}`, {
79
+ etag,
80
+ notModifiedHeaders: validators,
81
+ file: builtFile(`p:/${cleanRel}:${etag}`, body, headers, hasVary ? { ...headers, etag: toWeakEtag(etag) } : undefined),
82
+ })
83
+ }
84
+
85
+ // A file a plugin writes into the public dir at runtime, served once it exists on disk.
86
+ const registerPublicFromDisk = (publicDir: string, rel: string): void => {
87
+ const cleanRel = rel.replace(/^\/+/, '')
88
+ const abs = join(publicDir, cleanRel)
89
+ if (existsSync(abs)) {
90
+ const st = statSync(abs)
91
+ registerPublic(cleanRel, abs, `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`)
92
+ }
93
+ }
94
+
95
+ // Hashed build assets: immutable cache, precompressed .br/.gz sidecars, optional lazy compression.
96
+ // Skip `.br`/`.gz` sidecars as standalone HTTP routes when their base asset exists.
97
+ const assetMap = new Map<string, AssetEntry>()
98
+ for (const [rel, body] of Object.entries(assets)) {
99
+ if ((rel.endsWith('.br') || rel.endsWith('.gz')) && rel.slice(0, -3) in assets)
100
+ continue
101
+ const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
102
+ const compressible = compressCache !== undefined && isCompressibleType(type)
103
+ const headers: Record<string, string> = {
104
+ 'content-type': type,
105
+ 'cache-control': 'public, max-age=31536000, immutable',
106
+ ...nosniffHeader,
107
+ }
108
+ const sidecar = (ext: 'br' | 'gz', encoding: string): Sidecar | undefined => {
109
+ const source = assets[`${rel}.${ext}`] ?? (typeof body === 'string' && existsSync(`${body}.${ext}`) ? `${body}.${ext}` : undefined)
110
+ return source === undefined ? undefined : { body: toBody(source), headers: { ...headers, 'content-encoding': encoding, 'vary': 'Accept-Encoding' } }
111
+ }
112
+ const br = sidecar('br', 'br')
113
+ const gz = sidecar('gz', 'gzip')
114
+ const varyHeaders = compressible || br !== undefined || gz !== undefined ? { ...headers, vary: 'Accept-Encoding' } : headers
115
+ assetMap.set(`${assetPrefix}/${rel}`, {
116
+ file: builtFile(`a:${assetPrefix}/${rel}`, body, varyHeaders, compressible ? varyHeaders : undefined),
117
+ br,
118
+ gz,
119
+ })
120
+ }
121
+
122
+ // Prerendered pages (zero-copy file paths preferred; raw HTML strings supported). `fast` holds those nothing may intercept.
123
+ function collectPrerendered(routes: readonly RouteManifestEntry[], sources: PrerenderedSources): { all: Map<string, ServedFile>, fast: Map<string, ServedFile> } {
124
+ const all = new Map<string, ServedFile>()
125
+ const fast = new Map<string, ServedFile>()
126
+ for (const route of routes) {
127
+ if (route.prerendered === undefined)
128
+ continue
129
+ for (const [urlPath, relHtml] of Object.entries(route.prerendered)) {
130
+ const headers: Record<string, string> = { ...sources.htmlHeaders(route, urlPath), ...varyEncoding }
131
+ const compressedHeaders = compressCache !== undefined ? headers : undefined
132
+ const filePath = sources.prerenderedFiles[relHtml]
133
+ const html = sources.prerendered[relHtml]
134
+ const key = `pre:${urlPath}`
135
+ const entry: ServedFile | undefined = filePath !== undefined
136
+ ? builtFile(key, filePath, headers, compressedHeaders)
137
+ : html !== undefined
138
+ ? { key, headers, compressedHeaders, body: html, read: () => textEncoder.encode(html) }
139
+ : undefined
140
+ if (entry === undefined)
141
+ continue
142
+ all.set(urlPath, entry)
143
+ if (sources.isFast(urlPath, route))
144
+ fast.set(urlPath, entry)
145
+ }
146
+ }
147
+ return { all, fast }
148
+ }
149
+
150
+ async function serveFile(request: Request, file: ServedFile): Promise<Response> {
151
+ if (request.method === 'HEAD')
152
+ return withHsts(new Response(null, { status: 200, headers: file.headers }), request)
153
+ if (file.compressedHeaders !== undefined && compressCache !== undefined) {
154
+ const enc = pickEncoding(request.headers.get('accept-encoding'))
155
+ if (enc !== undefined) {
156
+ const compressed = await compressCache.file(file.key, enc, file.read)
157
+ if (compressed !== undefined)
158
+ return withHsts(new Response(compressed, { status: 200, headers: { ...file.compressedHeaders, 'content-encoding': enc } }), request)
159
+ }
160
+ }
161
+ return withHsts(new Response(file.body, { status: 200, headers: file.headers }), request)
162
+ }
163
+
164
+ async function serveAsset(request: Request, asset: AssetEntry): Promise<Response> {
165
+ if (compressEnabled && request.method !== 'HEAD' && (asset.br !== undefined || asset.gz !== undefined)) {
166
+ const preEnc = pickPrecompressedEncoding(request.headers.get('accept-encoding'), { br: asset.br !== undefined, gz: asset.gz !== undefined })
167
+ if (preEnc !== undefined) {
168
+ const sidecar = preEnc === 'br' ? asset.br! : asset.gz!
169
+ return withHsts(new Response(sidecar.body, { status: 200, headers: sidecar.headers }), request)
170
+ }
171
+ }
172
+ return serveFile(request, asset.file)
173
+ }
174
+
175
+ async function servePublic(request: Request, pub: PublicEntry): Promise<Response> {
176
+ if (etagMatches(request.headers.get('if-none-match'), pub.etag))
177
+ return withHsts(new Response(null, { status: 304, headers: pub.notModifiedHeaders }), request)
178
+ return serveFile(request, pub.file)
179
+ }
180
+
181
+ return { assetMap, publicMap, registerPublic, registerPublicFromDisk, collectPrerendered, serveFile, serveAsset, servePublic }
182
+ }