@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
@@ -21,16 +21,17 @@ import { planIslands } from './islands'
21
21
  import { buildActionEntries, buildRouteEntries } from './manifest'
22
22
  import { createPluginHost, createPublicFiles } from './plugin-host'
23
23
  import { prerender } from './prerender'
24
- import { formatBundleReport } from './report'
24
+ import { analyzeBundleWeights, checkJsBudget, formatBundleReport, islandOrigins } from './report'
25
+ import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
25
26
  import { KAY_SRC_ROOT, resolveKaySpecifier } from './resolve'
26
- import { assertNoRouteConflicts, hasRouteHandlerExport, routeExportProblem, SPECIAL_ROUTE_FILES } from './routes'
27
+ import { assertNoRouteConflicts, hasRouteHandlerExport, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
27
28
  import { exportStatic } from './static'
28
29
 
29
30
  export type { BuildCache } from './graph'
30
31
  export { createBuildCache } from './graph'
31
32
  export type { ActionManifestEntry, BuildManifest, RouteManifestEntry } from './manifest'
32
- export { analyzeBundleWeights, formatBundleReport } from './report'
33
- export type { RouteBundleMetrics } from './report'
33
+ export { analyzeBundleWeights, checkJsBudget, formatBundleReport } from './report'
34
+ export type { BundleReport, RouteBundleMetrics, RouteIsland } from './report'
34
35
  export { resolveKaySpecifier } from './resolve'
35
36
 
36
37
  export interface BuildOptions {
@@ -46,6 +47,8 @@ export interface BuildOptions {
46
47
  cache?: BuildCache | undefined
47
48
  /** Print a per-route JS/CSS bundle weight report using Bun.build's metafile. */
48
49
  analyze?: boolean | undefined
50
+ /** Fail the build when a route's eager JS, gzipped, is over this many bytes, naming the route and its islands. */
51
+ maxJs?: number | undefined
49
52
  /** Export a static site directly into outDir (dist/) with no server/ folder left behind. */
50
53
  static?: boolean | undefined
51
54
  /** Run build-time prerendering for routes exporting `prerender = true` (default: true; disabled in `kay dev`). */
@@ -158,7 +161,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
158
161
 
159
162
  const allRouteFiles = walkRoutes(routesDir).sort()
160
163
  const specialFiles = allRouteFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
161
- const candidatePageFiles = allRouteFiles.filter(f => !basename(f).startsWith('_'))
164
+ const candidateFiles = allRouteFiles.filter(f => !basename(f).startsWith('_'))
162
165
  const rootLayoutSrc = join(routesDir, '_layout.tsx')
163
166
  const errorSrc = join(routesDir, '_error.tsx')
164
167
  const notFoundSrc = join(routesDir, '_404.tsx')
@@ -167,21 +170,26 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
167
170
  const hasNotFoundFile = existsSync(notFoundSrc)
168
171
 
169
172
  // Every reachable .ts/.tsx file is analyzed & validated BEFORE wiping outDir, so build errors keep the last working dist/.
170
- const graph = new ModuleGraph(options.cache)
171
- for (const f of [...specialFiles, ...candidatePageFiles])
173
+ // kay.config.ts enters the graph too, so an action or component reached only from it is analyzed and gets its URL.
174
+ const configSrc = join(root, 'kay.config.ts')
175
+ const hasConfigFile = existsSync(configSrc)
176
+ const graph = new ModuleGraph(root, options.cache)
177
+ for (const f of [...specialFiles, ...candidateFiles, ...(hasConfigFile ? [configSrc] : [])])
172
178
  graph.load(f)
173
179
  for (const analysis of graph.analyses.values()) {
174
180
  for (const warning of analysis.warnings)
175
181
  console.warn(warning)
176
182
  }
177
183
 
178
- // Skip helper files inside routes/ that export neither a default component nor an HTTP method handler
179
- for (const f of candidatePageFiles) {
180
- const problem = routeExportProblem(graph.analyses.get(f)!, relPosix(root, f))
184
+ const routesRel = relPosix(root, routesDir)
185
+ for (const f of [...specialFiles, ...candidateFiles]) {
186
+ const analysis = graph.analyses.get(f)!
187
+ const problem = routeFileProblem(analysis, relPosix(root, f), routesRel) ?? routeExportProblem(analysis, relPosix(root, f))
181
188
  if (problem !== undefined)
182
189
  throw new Error(`kay build: ${problem}`)
183
190
  }
184
- const pageFiles = candidatePageFiles.filter(f => hasRouteHandlerExport(graph.analyses.get(f)!))
191
+ // A file exporting only actions stays in routes/ for its folder's middleware.
192
+ const pageFiles = candidateFiles.filter(f => hasRouteHandlerExport(graph.analyses.get(f)!))
185
193
  assertNoRouteConflicts(root, routesDir, pageFiles)
186
194
 
187
195
  // Server actions, keyed by source file
@@ -205,25 +213,36 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
205
213
  .flatMap(p => p.css ?? [])
206
214
  .map(c => resolve(root, c))
207
215
  .filter(c => existsSync(c))
208
- const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, analyze: options.analyze === true, graph, cache: options.cache, plugins, actionsByFile, islands }
216
+ const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, analyze: options.analyze === true || options.maxJs !== undefined, graph, cache: options.cache, plugins, actionsByFile, islands }
209
217
 
210
- const configSrc = join(root, 'kay.config.ts')
211
- const hasConfigFile = existsSync(configSrc)
212
218
  const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
213
219
  const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
220
+ // `_entry.js` imports all of these; each stays an entrypoint so its code lands in a content-named chunk that `kay dev` keeps loaded while it is unchanged.
214
221
  const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles, ...(hasConfigFile ? [configSrc] : [])]
215
222
  const serverRoot = standaloneActionFiles.length > 0 || hasConfigFile ? root : routesDir
223
+ const toOutRel = (srcFile: string): string =>
224
+ relPosix(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js')))
225
+ const serverEntry = {
226
+ file: join(serverRoot, SERVER_ENTRY_FILE),
227
+ source: serverEntrySource({
228
+ modules: [...specialFiles, ...pageFiles, ...standaloneActionFiles].map(file => ({ file, key: toOutRel(file), source: relPosix(root, file) })),
229
+ config: hasConfigFile ? { file: configSrc, source: relPosix(root, configSrc) } : undefined,
230
+ assembler: join(KAY_SRC_ROOT, 'server/app-entry.ts'),
231
+ }),
232
+ }
233
+ if (existsSync(serverEntry.file))
234
+ throw new Error(`kay build: ${relPosix(root, serverEntry.file)} is the path of kay's server entry; rename that file.`)
216
235
 
217
236
  // The server compiles against the island chunk URLs, so islands build first; without islands both passes run in parallel.
218
237
  const clientPass = () => buildClient(env, standaloneCssFiles(graph, pluginCssFiles, islands.cssFiles))
219
238
  let client: Awaited<ReturnType<typeof clientPass>>
220
239
  if (islands.targets.size === 0) {
221
- const [built] = await Promise.all([clientPass(), buildServer(env, serverEntries, serverRoot, new Map())])
240
+ const [built] = await Promise.all([clientPass(), buildServer(env, serverEntries, serverRoot, new Map(), serverEntry)])
222
241
  client = built
223
242
  }
224
243
  else {
225
244
  client = await clientPass()
226
- await buildServer(env, serverEntries, serverRoot, client.islandChunks)
245
+ await buildServer(env, serverEntries, serverRoot, client.islandChunks, serverEntry)
227
246
  }
228
247
 
229
248
  if (options.cache !== undefined) {
@@ -264,9 +283,6 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
264
283
  }
265
284
  }
266
285
 
267
- const toOutRel = (srcFile: string): string =>
268
- relPosix(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js')))
269
-
270
286
  const assets: string[] = []
271
287
  for (const rel of client.assetFiles) {
272
288
  const abs = join(clientDir, rel)
@@ -327,7 +343,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
327
343
  globalStyles,
328
344
  ...(host.headTags.length > 0 ? { headTags: host.headTags } : {}),
329
345
  routes,
330
- ...(hasConfigFile ? { configFile: toOutRel(configSrc) } : {}),
346
+
331
347
  ...(hasRootLayout ? { rootLayoutFile: toOutRel(rootLayoutSrc) } : {}),
332
348
  errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
333
349
  notFoundFile: hasNotFoundFile ? toOutRel(notFoundSrc) : undefined,
@@ -339,12 +355,19 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
339
355
  }
340
356
  const writeManifest = (): void => writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
341
357
  writeManifest()
358
+ if (options.analyze === true || options.maxJs !== undefined) {
359
+ const report = analyzeBundleWeights(manifest, clientDir, assetPrefix, client.metafile, islandOrigins(islands, client.islandChunks, graph, root))
360
+ if (options.analyze === true)
361
+ console.log(formatBundleReport(report))
362
+ if (options.maxJs !== undefined)
363
+ checkJsBudget(report, options.maxJs)
364
+ }
342
365
 
343
366
  // Hybrid prerendering / static export (skipped in `kay dev`, where routes render on-demand)
344
367
  const prerenderRoutes = options.prerender !== false || isStatic ? routes.filter(r => r.prerender) : []
345
368
  const prerenderDir = isStatic ? run.staticStageDir! : join(outDir, 'prerendered')
346
369
  const app = prerenderRoutes.length > 0 || isStatic
347
- ? await prerender({ root, outDir, assetPrefix, site: run.site, plugins, isDev, isStatic, prerenderDir, routes: prerenderRoutes })
370
+ ? await prerender({ root, outDir, assetPrefix, site: run.site, plugins, pluginOverride: options.plugins, isDev, isStatic, prerenderDir, routes: prerenderRoutes })
348
371
  : undefined
349
372
 
350
373
  try {
@@ -383,14 +406,11 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
383
406
  manifest,
384
407
  assetPrefix,
385
408
  outfile: typeof options.compile === 'string' ? resolve(root, options.compile) : join(outDir, 'server-bin'),
386
- kaySrcRoot: KAY_SRC_ROOT,
409
+
387
410
  resolveKaySpecifier,
388
411
  bunPlugins: pluginBunPlugins(env, 'compile'),
389
412
  })
390
413
  }
391
414
 
392
- if (options.analyze)
393
- console.log(formatBundleReport(manifest, clientDir, assetPrefix, client.metafile))
394
-
395
415
  return manifest
396
416
  }
@@ -3,6 +3,8 @@
3
3
  import type { ModuleGraph } from './graph'
4
4
  import { basename, extname } from 'node:path'
5
5
  import { asyncInteractiveError } from '../compiler/analyze'
6
+ import { withStateReads } from '../compiler/interactivity'
7
+ import { serverOnlyTagError } from '../compiler/mistakes'
6
8
  import { isTsFile, relPosix } from './files'
7
9
 
8
10
  export interface IslandTarget {
@@ -55,40 +57,36 @@ export function planIslands(graph: ModuleGraph, root: string, pageFiles: string[
55
57
 
56
58
  // A component reading reactive state another module exports runs in the browser too. The promoted analysis lives in this build's map only, so the cached one still reflects the file alone.
57
59
  for (const [file, analysis] of analyses) {
58
- if (!file.endsWith('.tsx') || analysis.isInteractive)
60
+ if (!file.endsWith('.tsx'))
59
61
  continue
60
- for (const imp of analysis.imports) {
62
+ const promoted = withStateReads(analysis, (imp, imported) => {
61
63
  const resolved = graph.resolve(file, imp.source)
62
- const state = resolved === undefined || !isTsFile(resolved)
63
- ? undefined
64
- : imp.specifiers.find((spec) => {
65
- if (analysis.jsxTags.has(spec.local))
66
- return false
67
- if (spec.imported === '*')
68
- return graph.load(resolved).stateExports.length > 0
69
- const target = graph.exportTarget(resolved, spec.imported)
70
- return graph.load(target.file).stateExports.includes(target.exportName)
71
- })
72
- if (state !== undefined) {
73
- const reason = `reads ${state.local} from '${imp.source}'`
74
- if (analysis.hasAsyncDefault)
75
- throw asyncInteractiveError(file, reason)
76
- analyses.set(file, { ...analysis, isInteractive: true, interactiveReason: reason })
77
- break
78
- }
79
- }
64
+ if (resolved === undefined || !isTsFile(resolved))
65
+ return false
66
+ if (imported === '*')
67
+ return graph.load(resolved).stateExports.length > 0
68
+ const target = graph.exportTarget(resolved, imported)
69
+ return graph.load(target.file).stateExports.includes(target.exportName)
70
+ })
71
+ if (promoted === undefined)
72
+ continue
73
+ const page = promoted.exports.get('default')
74
+ if (analysis.hasAsyncDefault && page?.interactive === true)
75
+ throw asyncInteractiveError(file, page.reason)
76
+ if (promoted.serverOnly !== undefined)
77
+ throw serverOnlyTagError(relPosix(root, file), promoted.serverOnly)
78
+ analyses.set(file, { ...analysis, ...promoted })
80
79
  }
81
80
 
82
81
  for (const [file, analysis] of analyses) {
83
82
  if (!file.endsWith('.tsx'))
84
83
  continue
85
- if (analysis.isInteractive) {
86
- if (pageSet.has(file))
87
- registerIsland(file, 'default')
84
+ if (analysis.exports.get('default')?.interactive === true && pageSet.has(file)) {
85
+ registerIsland(file, 'default')
88
86
  continue
89
87
  }
90
88
 
91
- // Only names rendered as tags become islands: `<Counter />`, or `<UI.Counter />` through a namespace import.
89
+ // Only names rendered as tags from server-side code become islands: `<Counter />`, or `<UI.Counter />` through a namespace import.
92
90
  const bindings = new Map<string, IslandTarget>()
93
91
  for (const imp of analysis.imports) {
94
92
  const resolved = graph.resolve(file, imp.source)
@@ -96,11 +94,11 @@ export function planIslands(graph: ModuleGraph, root: string, pageFiles: string[
96
94
  continue
97
95
  for (const spec of imp.specifiers) {
98
96
  const tags = spec.imported === '*'
99
- ? [...analysis.jsxTags].filter(tag => tag.startsWith(`${spec.local}.`) && !tag.slice(spec.local.length + 1).includes('.')).map(tag => [tag, tag.slice(spec.local.length + 1)] as const)
100
- : analysis.jsxTags.has(spec.local) ? [[spec.local, spec.imported] as const] : []
97
+ ? [...analysis.staticJsxTags].filter(tag => tag.startsWith(`${spec.local}.`) && !tag.slice(spec.local.length + 1).includes('.')).map(tag => [tag, tag.slice(spec.local.length + 1)] as const)
98
+ : analysis.staticJsxTags.has(spec.local) ? [[spec.local, spec.imported] as const] : []
101
99
  for (const [tag, exportName] of tags) {
102
100
  const target = graph.exportTarget(resolved, exportName)
103
- if (target.file.endsWith('.tsx') && graph.load(target.file).isInteractive)
101
+ if (target.file.endsWith('.tsx') && graph.load(target.file).exports.get(target.exportName)?.interactive === true)
104
102
  bindings.set(tag, registerIsland(target.file, target.exportName))
105
103
  }
106
104
  }
@@ -134,10 +132,10 @@ export function planIslands(graph: ModuleGraph, root: string, pageFiles: string[
134
132
 
135
133
  // A layout, error or 404 page renders on the server only, so interactivity written in it would never run.
136
134
  for (const file of specialFiles) {
137
- const analysis = analyses.get(file)
138
- if (analysis?.isInteractive === true) {
135
+ const page = analyses.get(file)?.exports.get('default')
136
+ if (page?.interactive === true) {
139
137
  const rel = relPosix(root, file)
140
- throw new Error(`kay build: ${rel} uses browser interactivity (${analysis.interactiveReason}), but it renders on the server only. Move the interactive part into a component and render that component from ${rel}.`)
138
+ throw new Error(`kay build: ${rel} uses browser interactivity (${page.reason}), but it renders on the server only. Move the interactive part into a component and render that component from ${rel}.`)
141
139
  }
142
140
  }
143
141
 
@@ -34,6 +34,8 @@ export interface RouteManifestEntry {
34
34
  usesRenderContext?: boolean | undefined
35
35
  prerender?: boolean | undefined
36
36
  prerendered?: Record<string, string> | undefined
37
+ /** CSP hashes of the app's `<style>` blocks per prerendered URL, for the pages that have any. */
38
+ prerenderedStyleHashes?: Record<string, string[]> | undefined
37
39
  }
38
40
 
39
41
  export interface BuildManifest {
@@ -43,7 +45,7 @@ export interface BuildManifest {
43
45
  globalStyles?: string[] | undefined
44
46
  headTags?: string[] | undefined
45
47
  routes: RouteManifestEntry[]
46
- configFile?: string | undefined
48
+
47
49
  /** Explicit root `_layout.tsx` compiled module path (never inferred from subdirectory layouts). */
48
50
  rootLayoutFile?: string | undefined
49
51
  errorFile?: string | undefined
@@ -82,7 +84,9 @@ function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks
82
84
  if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
83
85
  reach.eager.add(chunk)
84
86
  }
85
- return
87
+ // Imports rendered only inside the module's islands ship within them; a static component beside an island renders its own.
88
+ if (analysis.staticJsxTags.size === 0)
89
+ return
86
90
  }
87
91
  for (const [localName, target] of islands.pageBindings.get(file) ?? []) {
88
92
  const chunk = islandChunks.get(islandKey(target))
@@ -180,6 +184,7 @@ export function buildRouteEntries(options: {
180
184
 
181
185
  const routes = options.pageFiles.map((file): RouteManifestEntry => {
182
186
  const analysis = graph.analyses.get(file)
187
+ const page = analysis?.exports.get('default')
183
188
  const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
184
189
  const chunks = new Set<string>()
185
190
  const eagerChunks = new Set<string>()
@@ -201,10 +206,10 @@ export function buildRouteEntries(options: {
201
206
  layouts: layoutSrcs.map(toOutRel),
202
207
  middlewares: ancestorFiles(routesDir, file, MIDDLEWARE_NAMES).map(toOutRel),
203
208
  hasLoad: analysis?.hasLoadExport,
204
- isIsland: analysis?.isInteractive,
209
+ isIsland: page?.interactive,
205
210
  islandChunk: islandChunks.get(`${file}#default`),
206
211
  islandHydrate: analysis?.defaultHydrate,
207
- islandDataKeys: analysis?.isInteractive && analysis.hasLoadExport ? analysis.defaultDataKeys : undefined,
212
+ islandDataKeys: page?.interactive === true && analysis?.hasLoadExport === true ? analysis.defaultDataKeys : undefined,
208
213
  islandChunks: [...chunks],
209
214
  eagerIslandChunks: [...eagerChunks],
210
215
  styles: [...styles],
@@ -3,14 +3,14 @@
3
3
  import type { KayPlugin } from '../plugins/index'
4
4
  import type { RouteManifestEntry } from './manifest'
5
5
  import { mkdirSync, writeFileSync } from 'node:fs'
6
- import { dirname, join, resolve } from 'node:path'
6
+ import { dirname, resolve } from 'node:path'
7
+ import { inlineStyleHashes } from '../server/security'
7
8
  import { relPosix } from './files'
8
9
  import { assertPathUrls } from './routes'
9
10
 
10
11
  const CONCURRENCY = 8
11
12
  const SLASH_EDGES_RE = /^\/|\/$/g
12
13
 
13
- let prerenderImportSeq = 0
14
14
 
15
15
  function resolvePrerenderHtmlPath(prerenderDir: string, urlStr: string, isStatic: boolean): string {
16
16
  const pathname = new URL(urlStr, 'http://localhost').pathname
@@ -32,6 +32,8 @@ export interface PrerenderOptions {
32
32
  assetPrefix: string
33
33
  site?: string | undefined
34
34
  plugins: KayPlugin[]
35
+ /** Plugins passed to `build()` itself, which the app runs with in place of its bundled config's. */
36
+ pluginOverride?: KayPlugin[] | undefined
35
37
  isDev: boolean
36
38
  isStatic: boolean
37
39
  /** Where the HTML lands: the static stage dir, or `<outDir>/prerendered`. */
@@ -42,18 +44,18 @@ export interface PrerenderOptions {
42
44
  /** Renders every route to HTML, records `route.prerendered`, and returns the server the pages were rendered with. */
43
45
  export async function prerender(options: PrerenderOptions) {
44
46
  const { root, outDir, prerenderDir, isStatic } = options
45
- const { createServer } = await import('../server/index')
46
- const app = await createServer({ root, outDir: relPosix(root, outDir), assetPrefix: options.assetPrefix, site: options.site, plugins: options.plugins, dev: options.isDev })
47
+ // Pages render with the runtime's own plugin instances, from the bundled config; `options.plugins` are the build's native ones.
48
+ const { startBuiltApp } = await import('../server/loader')
49
+ const { app, entry } = await startBuiltApp({ root, outDir: relPosix(root, outDir), assetPrefix: options.assetPrefix, site: options.site, plugins: options.pluginOverride, dev: options.isDev })
47
50
  mkdirSync(prerenderDir, { recursive: true })
48
51
 
49
- const stamp = `${Date.now()}-${++prerenderImportSeq}`
50
52
  for (const route of options.routes) {
51
53
  let urls: string[] = []
52
54
  if (!route.path.includes(':') && !route.path.includes('*')) {
53
55
  urls = [route.path]
54
56
  }
55
57
  else {
56
- const mod = await import(`${join(outDir, route.file)}?v=${stamp}`) as { paths?: () => Promise<string[]> | string[] }
58
+ const mod = entry?.modules[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
57
59
  if (typeof mod.paths === 'function') {
58
60
  const returned: unknown = await mod.paths()
59
61
  assertPathUrls(returned, route.file)
@@ -73,6 +75,7 @@ export async function prerender(options: PrerenderOptions) {
73
75
  }
74
76
 
75
77
  const map: Record<string, string> = {}
78
+ const styleHashes: Record<string, string[]> = {}
76
79
  for (let i = 0; i < urls.length; i += CONCURRENCY) {
77
80
  await Promise.all(urls.slice(i, i + CONCURRENCY).map(async (u) => {
78
81
  const res = await app.handle(new Request(`http://localhost${u}`))
@@ -84,11 +87,16 @@ export async function prerender(options: PrerenderOptions) {
84
87
  }
85
88
  const absHtml = resolvePrerenderHtmlPath(prerenderDir, u, isStatic)
86
89
  mkdirSync(dirname(absHtml), { recursive: true })
87
- writeFileSync(absHtml, await res.text())
90
+ const html = await res.text()
91
+ writeFileSync(absHtml, html)
88
92
  map[u] = relPosix(isStatic ? prerenderDir : outDir, absHtml)
93
+ const hashes = inlineStyleHashes(html)
94
+ if (hashes.length > 0)
95
+ styleHashes[u] = hashes
89
96
  }))
90
97
  }
91
98
  route.prerendered = map
99
+ route.prerenderedStyleHashes = Object.keys(styleHashes).length > 0 ? styleHashes : undefined
92
100
  }
93
101
  return app
94
102
  }
@@ -1,8 +1,28 @@
1
- // The `--analyze` report: eager JS and CSS weight per route, from the manifest and the client metafile.
1
+ // The `--analyze` report and the `--max-js` budget: eager JS and CSS weight per route, from the manifest and the client metafile (or the chunks' own imports), and the islands behind it.
2
2
 
3
+ import type { ModuleGraph } from './graph'
4
+ import type { IslandPlan } from './islands'
3
5
  import type { BuildManifest } from './manifest'
4
6
  import { existsSync, readFileSync } from 'node:fs'
5
- import { join } from 'node:path'
7
+ import { join, posix } from 'node:path'
8
+ import { relPosix } from './files'
9
+
10
+ // A static `import ... from "./x.js"` or `import "./x.js"` of an emitted chunk; `import("./x.js")` stays lazy and is left out.
11
+ const STATIC_CHUNK_IMPORT_RE = /\b(?:import|export)\s*(?:[^"'();]*?\bfrom\s*)?["'](\.\.?\/[^"']+\.js)["']/g
12
+
13
+ export interface IslandOrigin {
14
+ /** The component's export name, `default` for a page or a default export. */
15
+ name: string
16
+ /** Root-relative source file. */
17
+ file: string
18
+ /** Why kay runs it in the browser, e.g. `uses onClick`. */
19
+ reason: string
20
+ }
21
+
22
+ export interface RouteIsland extends IslandOrigin {
23
+ /** Loaded with the page, so counted in the route's eager JS. */
24
+ eager: boolean
25
+ }
6
26
 
7
27
  export interface RouteBundleMetrics {
8
28
  path: string
@@ -12,6 +32,25 @@ export interface RouteBundleMetrics {
12
32
  cssGzip: number
13
33
  jsFiles: number
14
34
  cssFiles: number
35
+ islands: RouteIsland[]
36
+ }
37
+
38
+ export interface BundleReport {
39
+ routes: RouteBundleMetrics[]
40
+ totalJsGzip: number
41
+ totalCssGzip: number
42
+ topModules: { path: string, bytes: number }[]
43
+ }
44
+
45
+ /** Each island chunk URL, mapped to the component it hydrates and why that component became an island. */
46
+ export function islandOrigins(islands: IslandPlan, islandChunks: Map<string, string>, graph: ModuleGraph, root: string): Map<string, IslandOrigin> {
47
+ const origins = new Map<string, IslandOrigin>()
48
+ for (const [key, target] of islands.targets) {
49
+ const url = islandChunks.get(key)
50
+ if (url !== undefined)
51
+ origins.set(url, { name: target.exportName, file: relPosix(root, target.file), reason: graph.load(target.file).exports.get(target.exportName)?.reason ?? 'is interactive' })
52
+ }
53
+ return origins
15
54
  }
16
55
 
17
56
  export function analyzeBundleWeights(
@@ -19,7 +58,8 @@ export function analyzeBundleWeights(
19
58
  clientDir: string,
20
59
  assetPrefix = '/_kay',
21
60
  metafile?: Bun.BuildOutput['metafile'],
22
- ): { routes: RouteBundleMetrics[], totalJsGzip: number, totalCssGzip: number, topModules: { path: string, bytes: number }[] } {
61
+ origins = new Map<string, IslandOrigin>(),
62
+ ): BundleReport {
23
63
  const prefix = `${assetPrefix.replace(/\/$/, '')}/`
24
64
  const sizeCache = new Map<string, { raw: number, gzip: number }>()
25
65
 
@@ -58,6 +98,17 @@ export function analyzeBundleWeights(
58
98
  }
59
99
  }
60
100
 
101
+ // Without the metafile, a chunk's static imports are read from the emitted file itself.
102
+ const depsOf = (url: string): readonly string[] => {
103
+ const known = jsDeps.get(url)
104
+ if (known !== undefined || metafile !== undefined || !url.startsWith(prefix))
105
+ return known ?? []
106
+ const abs = join(clientDir, url.slice(prefix.length))
107
+ const deps = existsSync(abs) ? [...readFileSync(abs, 'utf8').matchAll(STATIC_CHUNK_IMPORT_RE)].map(m => posix.join(posix.dirname(url), m[1]!)) : []
108
+ jsDeps.set(url, deps)
109
+ return deps
110
+ }
111
+
61
112
  const collectTransitiveJs = (urls: readonly string[]): Set<string> => {
62
113
  const seen = new Set<string>()
63
114
  const stack = [...urls]
@@ -66,7 +117,7 @@ export function analyzeBundleWeights(
66
117
  if (seen.has(cur))
67
118
  continue
68
119
  seen.add(cur)
69
- for (const dep of jsDeps.get(cur) ?? [])
120
+ for (const dep of depsOf(cur))
70
121
  stack.push(dep)
71
122
  }
72
123
  return seen
@@ -76,8 +127,15 @@ export function analyzeBundleWeights(
76
127
  const eagerJsRoots: string[] = []
77
128
  if (r.islandChunks.length > 0 && manifest.runtimeScript !== undefined)
78
129
  eagerJsRoots.push(manifest.runtimeScript)
79
- for (const c of r.eagerIslandChunks ?? r.islandChunks)
130
+ const eager = r.eagerIslandChunks ?? r.islandChunks
131
+ for (const c of eager)
80
132
  eagerJsRoots.push(c)
133
+ const islands: RouteIsland[] = []
134
+ for (const chunk of r.islandChunks) {
135
+ const origin = origins.get(chunk)
136
+ if (origin !== undefined)
137
+ islands.push({ ...origin, eager: eager.includes(chunk) })
138
+ }
81
139
 
82
140
  const jsSet = collectTransitiveJs(eagerJsRoots)
83
141
  let jsRaw = 0
@@ -105,6 +163,7 @@ export function analyzeBundleWeights(
105
163
  cssGzip,
106
164
  jsFiles: jsSet.size,
107
165
  cssFiles: cssList.length,
166
+ islands,
108
167
  }
109
168
  })
110
169
 
@@ -126,14 +185,10 @@ export function analyzeBundleWeights(
126
185
  return { routes, totalJsGzip, totalCssGzip, topModules }
127
186
  }
128
187
 
129
- export function formatBundleReport(
130
- manifest: BuildManifest,
131
- clientDir: string,
132
- assetPrefix = '/_kay',
133
- metafile?: Bun.BuildOutput['metafile'],
134
- ): string {
135
- const report = analyzeBundleWeights(manifest, clientDir, assetPrefix, metafile)
136
- const kb = (b: number) => `${(b / 1024).toFixed(2)} KB`
188
+ const kb = (b: number): string => `${(b / 1024).toFixed(2)} KB`
189
+ const islandLine = (island: RouteIsland): string => `${island.name} (${island.file}) ${island.reason}`
190
+
191
+ export function formatBundleReport(report: BundleReport): string {
137
192
  const lines = [
138
193
  '\n=== KAY BUNDLE WEIGHT REPORT ===',
139
194
  `Total emitted: JS ${kb(report.totalJsGzip)} gz | CSS ${kb(report.totalCssGzip)} gz`,
@@ -147,6 +202,8 @@ export function formatBundleReport(
147
202
  + kb(r.cssGzip).padStart(14)
148
203
  + `${r.jsFiles}j/${r.cssFiles}c`.padStart(10),
149
204
  )
205
+ for (const island of r.islands)
206
+ lines.push(` ${island.eager ? 'island' : 'island, deferred'}: ${islandLine(island)}`)
150
207
  }
151
208
  if (report.topModules.length > 0) {
152
209
  lines.push('', 'Top modules (minified output bytes):')
@@ -155,3 +212,15 @@ export function formatBundleReport(
155
212
  }
156
213
  return lines.join('\n')
157
214
  }
215
+
216
+ /** Throws naming each route whose eager JS, gzipped, is over `maxBytes`, with the islands it loads with the page. */
217
+ export function checkJsBudget(report: BundleReport, maxBytes: number): void {
218
+ const over = report.routes.filter(r => r.jsGzip > maxBytes)
219
+ if (over.length === 0)
220
+ return
221
+ const lines = over.map((r) => {
222
+ const eager = r.islands.filter(island => island.eager).map(islandLine)
223
+ return ` ${r.path} ships ${kb(r.jsGzip)} of eager JS: ${eager.length > 0 ? eager.join('; ') : 'the kay runtime alone'}`
224
+ })
225
+ throw new Error(`kay build: eager JS over --max-js ${kb(maxBytes)} (gzip) on ${over.length === 1 ? 'one route' : `${over.length} routes`}:\n${lines.join('\n')}\nDefer an island with export const hydrate = 'visible', move its state into fewer components, or raise --max-js.`)
226
+ }
@@ -1,4 +1,4 @@
1
- // Resolves an import the way kay build follows it: relative files, then packages through Bun's resolver; kay, node:, bun and ~ aliases stay unresolved.
1
+ // Resolves an import the way kay build follows it: relative files, then packages through Bun's resolver; @kayjs/kay, node:, bun and ~ aliases stay unresolved.
2
2
 
3
3
  import { statSync } from 'node:fs'
4
4
  import { dirname, join, resolve } from 'node:path'
@@ -6,6 +6,7 @@ import pkg from '../../package.json' with { type: 'json' }
6
6
 
7
7
  export const KAY_SRC_ROOT = resolve(import.meta.dir, '..')
8
8
 
9
+
9
10
  export function resolveImportPath(fromFile: string, specifier: string): string | undefined {
10
11
  if (specifier.startsWith('.')) {
11
12
  const base = resolve(dirname(fromFile), specifier)
@@ -17,9 +18,7 @@ export function resolveImportPath(fromFile: string, specifier: string): string |
17
18
  return undefined
18
19
  }
19
20
  if (
20
- specifier === 'kay'
21
- || specifier.startsWith('kay/')
22
- || specifier === '@kayjs/kay'
21
+ specifier === '@kayjs/kay'
23
22
  || specifier.startsWith('@kayjs/kay/')
24
23
  || specifier.startsWith('node:')
25
24
  || specifier === 'bun'
@@ -39,13 +38,13 @@ export function resolveImportPath(fromFile: string, specifier: string): string |
39
38
 
40
39
  const KAY_SPECIFIER_FILES = new Map<string, string>(
41
40
  Object.entries(pkg.exports as Record<string, string>).map(([subpath, target]) => [
42
- subpath === '.' ? 'kay' : `kay/${subpath.slice(2)}`,
41
+ subpath === '.' ? '@kayjs/kay' : `@kayjs/kay/${subpath.slice(2)}`,
43
42
  target.replace(/^\.\/src\//, ''),
44
43
  ]),
45
44
  )
46
45
 
47
- /** Maps `kay`, `kay/<subpath>` and the `@kayjs/kay` spelling of both to their source file. */
46
+ /** Maps `@kayjs/kay` and its subpaths to their source file. */
48
47
  export function resolveKaySpecifier(specifier: string): string | undefined {
49
- const file = KAY_SPECIFIER_FILES.get(specifier.startsWith('@kayjs/') ? specifier.slice('@kayjs/'.length) : specifier)
48
+ const file = KAY_SPECIFIER_FILES.get(specifier)
50
49
  return file === undefined ? undefined : join(KAY_SRC_ROOT, file)
51
50
  }
@@ -2,7 +2,7 @@
2
2
 
3
3
  import type { ModuleAnalysis } from '../compiler/index'
4
4
  import { existsSync } from 'node:fs'
5
- import { dirname, join, relative } from 'node:path'
5
+ import { basename, dirname, join, relative } from 'node:path'
6
6
  import { relPosix } from './files'
7
7
 
8
8
  export const SPECIAL_ROUTE_FILES = new Set(['_layout.tsx', '_middleware.ts', '_middleware.tsx', '_error.tsx', '_404.tsx'])
@@ -13,28 +13,19 @@ const CATCH_ALL_RE = /\[\.\.\.([^\]]+)\]/g
13
13
  const PARAM_RE = /\[([^\]]+)\]/g
14
14
  const PATH_SEPARATOR_RE = /[/\\]/
15
15
 
16
- interface ExportSpecifierNode {
17
- type: string
18
- exportKind?: string
19
- specifiers?: { exportKind?: string, exported?: { name?: string, value?: string } }[]
20
- }
21
-
22
16
  /** A file in routes/ is a route when it exports a default component or an HTTP method handler, directly or through `export { ... }`. */
23
17
  export function hasRouteHandlerExport(analysis: ModuleAnalysis): boolean {
24
- for (const name of analysis.exportedNames) {
25
- if (ROUTE_EXPORTS.has(name))
26
- return true
27
- }
28
- for (const stmt of analysis.program.body as ExportSpecifierNode[]) {
29
- if (stmt.type !== 'ExportNamedDeclaration' || stmt.exportKind === 'type' || stmt.specifiers === undefined)
30
- continue
31
- for (const spec of stmt.specifiers) {
32
- const exported = spec.exportKind === 'type' ? undefined : spec.exported?.name ?? spec.exported?.value
33
- if (exported !== undefined && ROUTE_EXPORTS.has(exported))
34
- return true
35
- }
36
- }
37
- return false
18
+ return analysis.exportedNames.some(name => ROUTE_EXPORTS.has(name))
19
+ }
20
+
21
+ const SPECIAL_FILE_DEFAULTS = new Map([['_layout', 'layout component'], ['_middleware', 'middleware function'], ['_error', 'error page component'], ['_404', 'not-found page component']])
22
+
23
+ /** For a route file or a `_layout`, `_middleware`, `_error` or `_404`, what kay would otherwise drop or fail on per request: neither a route nor an action, which its folder's middleware guards, or no default export. `routesRel` is the routes folder as the app writes it. */
24
+ export function routeFileProblem(analysis: ModuleAnalysis, file: string, routesRel: string): string | undefined {
25
+ const name = basename(file)
26
+ if (SPECIAL_ROUTE_FILES.has(name))
27
+ return analysis.exportedNames.includes('default') ? undefined : `${file} has no default export: export default its ${SPECIAL_FILE_DEFAULTS.get(name.replace(TS_EXT_RE, ''))}.`
28
+ return hasRouteHandlerExport(analysis) || analysis.exportedActions.length > 0 ? undefined : `${file} exports no route; move it out of ${routesRel} or prefix it with _.`
38
29
  }
39
30
 
40
31
  const LOAD_FIX = 'kay never calls it; export async function load() and read its data with the page\'s load prop'