@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.1

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 (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +442 -0
  4. package/src/build/compile.ts +10 -10
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +204 -1460
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +224 -0
  10. package/src/build/plugin-host.ts +184 -0
  11. package/src/build/prerender.ts +93 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +58 -0
  14. package/src/build/routes.ts +135 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +228 -114
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +53 -32
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +808 -743
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +164 -21
  24. package/src/compiler/shared.ts +442 -0
  25. package/src/compiler/ssr.ts +329 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +271 -75
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +114 -77
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +2 -1
  34. package/src/jsx-runtime.ts +11 -0
  35. package/src/plugins/context.ts +57 -0
  36. package/src/plugins/index.ts +114 -18
  37. package/src/reactivity/index.ts +237 -213
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +36 -11
  40. package/src/server/action.ts +147 -76
  41. package/src/server/compress.ts +116 -96
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +107 -54
  45. package/src/server/index.ts +887 -870
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +22 -8
  48. package/src/server/security.ts +48 -58
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +95 -10
  52. package/src/ssr/index.ts +167 -66
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +2 -1
  55. package/src/unrenderable.ts +35 -0
@@ -0,0 +1,157 @@
1
+ // The `--analyze` report: eager JS and CSS weight per route, from the manifest and the client metafile.
2
+
3
+ import type { BuildManifest } from './manifest'
4
+ import { existsSync, readFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+
7
+ export interface RouteBundleMetrics {
8
+ path: string
9
+ jsRaw: number
10
+ jsGzip: number
11
+ cssRaw: number
12
+ cssGzip: number
13
+ jsFiles: number
14
+ cssFiles: number
15
+ }
16
+
17
+ export function analyzeBundleWeights(
18
+ manifest: BuildManifest,
19
+ clientDir: string,
20
+ assetPrefix = '/_kay',
21
+ metafile?: Bun.BuildOutput['metafile'],
22
+ ): { routes: RouteBundleMetrics[], totalJsGzip: number, totalCssGzip: number, topModules: { path: string, bytes: number }[] } {
23
+ const prefix = `${assetPrefix.replace(/\/$/, '')}/`
24
+ const sizeCache = new Map<string, { raw: number, gzip: number }>()
25
+
26
+ const getSize = (url: string): { raw: number, gzip: number } => {
27
+ const cached = sizeCache.get(url)
28
+ if (cached !== undefined)
29
+ return cached
30
+ if (!url.startsWith(prefix))
31
+ return { raw: 0, gzip: 0 }
32
+ const abs = join(clientDir, url.slice(prefix.length))
33
+ if (!existsSync(abs))
34
+ return { raw: 0, gzip: 0 }
35
+ const buf = readFileSync(abs)
36
+ const entry = { raw: buf.byteLength, gzip: Bun.gzipSync(buf, { level: 9 }).byteLength }
37
+ sizeCache.set(url, entry)
38
+ return entry
39
+ }
40
+
41
+ // Collect transitive JS chunk imports from metafile so eager JS includes shared runtime chunks!
42
+ const jsDeps = new Map<string, string[]>()
43
+ const moduleBytes = new Map<string, number>()
44
+ if (metafile !== undefined) {
45
+ for (const [outKey, info] of Object.entries(metafile.outputs)) {
46
+ const rel = outKey.replace(/^\.\//, '')
47
+ const url = `${prefix}${rel}`
48
+ if (rel.endsWith('.js')) {
49
+ const deps: string[] = []
50
+ for (const imp of info.imports ?? []) {
51
+ if (imp.kind === 'import-statement')
52
+ deps.push(`${prefix}${imp.path.replace(/^\.\//, '')}`)
53
+ }
54
+ jsDeps.set(url, deps)
55
+ }
56
+ for (const [inPath, inInfo] of Object.entries(info.inputs ?? {}))
57
+ moduleBytes.set(inPath, (moduleBytes.get(inPath) ?? 0) + inInfo.bytesInOutput)
58
+ }
59
+ }
60
+
61
+ const collectTransitiveJs = (urls: readonly string[]): Set<string> => {
62
+ const seen = new Set<string>()
63
+ const stack = [...urls]
64
+ while (stack.length > 0) {
65
+ const cur = stack.pop()!
66
+ if (seen.has(cur))
67
+ continue
68
+ seen.add(cur)
69
+ for (const dep of jsDeps.get(cur) ?? [])
70
+ stack.push(dep)
71
+ }
72
+ return seen
73
+ }
74
+
75
+ const routes: RouteBundleMetrics[] = manifest.routes.map((r) => {
76
+ const eagerJsRoots: string[] = []
77
+ if (r.islandChunks.length > 0 && manifest.runtimeScript !== undefined)
78
+ eagerJsRoots.push(manifest.runtimeScript)
79
+ for (const c of r.eagerIslandChunks ?? r.islandChunks)
80
+ eagerJsRoots.push(c)
81
+
82
+ const jsSet = collectTransitiveJs(eagerJsRoots)
83
+ let jsRaw = 0
84
+ let jsGzip = 0
85
+ for (const u of jsSet) {
86
+ const s = getSize(u)
87
+ jsRaw += s.raw
88
+ jsGzip += s.gzip
89
+ }
90
+
91
+ const cssList = r.styles ?? manifest.styles
92
+ let cssRaw = 0
93
+ let cssGzip = 0
94
+ for (const u of cssList) {
95
+ const s = getSize(u)
96
+ cssRaw += s.raw
97
+ cssGzip += s.gzip
98
+ }
99
+
100
+ return {
101
+ path: r.path,
102
+ jsRaw,
103
+ jsGzip,
104
+ cssRaw,
105
+ cssGzip,
106
+ jsFiles: jsSet.size,
107
+ cssFiles: cssList.length,
108
+ }
109
+ })
110
+
111
+ let totalJsGzip = 0
112
+ let totalCssGzip = 0
113
+ for (const rel of manifest.assets) {
114
+ const s = getSize(`${prefix}${rel}`)
115
+ if (rel.endsWith('.js'))
116
+ totalJsGzip += s.gzip
117
+ else if (rel.endsWith('.css'))
118
+ totalCssGzip += s.gzip
119
+ }
120
+
121
+ const topModules = [...moduleBytes.entries()]
122
+ .map(([path, bytes]) => ({ path, bytes }))
123
+ .sort((a, b) => b.bytes - a.bytes)
124
+ .slice(0, 10)
125
+
126
+ return { routes, totalJsGzip, totalCssGzip, topModules }
127
+ }
128
+
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`
137
+ const lines = [
138
+ '\n=== KAY BUNDLE WEIGHT REPORT ===',
139
+ `Total emitted: JS ${kb(report.totalJsGzip)} gz | CSS ${kb(report.totalCssGzip)} gz`,
140
+ '',
141
+ 'Route'.padEnd(28) + 'Eager JS (gz)'.padStart(16) + 'CSS (gz)'.padStart(14) + 'Files'.padStart(10),
142
+ ]
143
+ for (const r of report.routes) {
144
+ lines.push(
145
+ r.path.padEnd(28)
146
+ + kb(r.jsGzip).padStart(16)
147
+ + kb(r.cssGzip).padStart(14)
148
+ + `${r.jsFiles}j/${r.cssFiles}c`.padStart(10),
149
+ )
150
+ }
151
+ if (report.topModules.length > 0) {
152
+ lines.push('', 'Top modules (minified output bytes):')
153
+ for (const m of report.topModules.slice(0, 8))
154
+ lines.push(` ${kb(m.bytes).padStart(9)} ${m.path}`)
155
+ }
156
+ return lines.join('\n')
157
+ }
@@ -0,0 +1,58 @@
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.
2
+
3
+ import { statSync } from 'node:fs'
4
+ import { dirname, join, resolve } from 'node:path'
5
+
6
+ export const KAY_SRC_ROOT = resolve(import.meta.dir, '..')
7
+
8
+ export function resolveImportPath(fromFile: string, specifier: string): string | undefined {
9
+ if (specifier.startsWith('.')) {
10
+ const base = resolve(dirname(fromFile), specifier)
11
+ const candidates = [base, `${base}.tsx`, `${base}.ts`, join(base, 'index.tsx'), join(base, 'index.ts')]
12
+ for (const c of candidates) {
13
+ if (statSync(c, { throwIfNoEntry: false })?.isFile())
14
+ return c
15
+ }
16
+ return undefined
17
+ }
18
+ if (
19
+ specifier === 'kay'
20
+ || specifier.startsWith('kay/')
21
+ || specifier.startsWith('@kayjs/kay')
22
+ || specifier.startsWith('node:')
23
+ || specifier.startsWith('bun')
24
+ || specifier.startsWith('~')
25
+ ) {
26
+ return undefined
27
+ }
28
+ try {
29
+ const resolved = Bun.resolveSync(specifier, dirname(fromFile))
30
+ return resolved.endsWith('.tsx') || resolved.endsWith('.ts') ? resolved : undefined
31
+ }
32
+ catch {
33
+ return undefined
34
+ }
35
+ }
36
+
37
+ const KAY_SPECIFIER_FILES = new Map([
38
+ ['kay', 'index.ts'],
39
+ ['kay/dom', 'dom/index.ts'],
40
+ ['kay/dom-extras', 'dom/extras.ts'],
41
+ ['kay/dom-loop', 'dom/loop.ts'],
42
+ ['kay/action', 'dom/action.ts'],
43
+ ['kay/island', 'dom/island.ts'],
44
+ ['kay/ssr', 'ssr/index.ts'],
45
+ ['kay/server', 'server/index.ts'],
46
+ ['kay/compiler', 'compiler/index.ts'],
47
+ ['kay/build', 'build/index.ts'],
48
+ ['kay/dev', 'dev/index.ts'],
49
+ ['kay/test', 'test/index.ts'],
50
+ ['kay/jsx-runtime', 'jsx-runtime.ts'],
51
+ ['kay/jsx-dev-runtime', 'jsx-runtime.ts'],
52
+ ])
53
+
54
+ /** Maps `kay`, `kay/<subpath>` and the `@kayjs/kay` spelling of both to their source file. */
55
+ export function resolveKaySpecifier(specifier: string): string | undefined {
56
+ const file = KAY_SPECIFIER_FILES.get(specifier.startsWith('@kayjs/') ? specifier.slice('@kayjs/'.length) : specifier)
57
+ return file === undefined ? undefined : join(KAY_SRC_ROOT, file)
58
+ }
@@ -0,0 +1,135 @@
1
+ // Route files: their URL patterns, conflicts, and the `_layout`/`_middleware` chain that wraps them.
2
+
3
+ import type { ModuleAnalysis } from '../compiler/index'
4
+ import { existsSync } from 'node:fs'
5
+ import { dirname, join, relative } from 'node:path'
6
+ import { relPosix } from './files'
7
+
8
+ export const SPECIAL_ROUTE_FILES = new Set(['_layout.tsx', '_middleware.ts', '_middleware.tsx', '_error.tsx', '_404.tsx'])
9
+ export const MIDDLEWARE_NAMES = ['_middleware.ts', '_middleware.tsx']
10
+ const ROUTE_EXPORTS = new Set(['default', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])
11
+ const TS_EXT_RE = /\.(?:tsx|ts)$/
12
+ const CATCH_ALL_RE = /\[\.\.\.([^\]]+)\]/g
13
+ const PARAM_RE = /\[([^\]]+)\]/g
14
+ const PATH_SEPARATOR_RE = /[/\\]/
15
+
16
+ interface ExportSpecifierNode {
17
+ type: string
18
+ exportKind?: string
19
+ specifiers?: { exportKind?: string, exported?: { name?: string, value?: string } }[]
20
+ }
21
+
22
+ /** A file in routes/ is a route when it exports a default component or an HTTP method handler, directly or through `export { ... }`. */
23
+ 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
38
+ }
39
+
40
+ const LOAD_FIX = 'kay never calls it; export async function load() and read its data with the page\'s load prop'
41
+ const PATHS_FIX = 'kay never calls it; export function paths() returning URL strings such as "/posts/a"'
42
+ const HEAD_FIX = 'kay never reads it; render <Head> in the page'
43
+ // Exports other frameworks read from a route file, and what kay wants instead.
44
+ const FOREIGN_ROUTE_EXPORTS = new Map([
45
+ ['getStaticProps', LOAD_FIX],
46
+ ['getServerSideProps', LOAD_FIX],
47
+ ['getInitialProps', LOAD_FIX],
48
+ ['loader', LOAD_FIX],
49
+ ['clientLoader', LOAD_FIX],
50
+ ['getStaticPaths', PATHS_FIX],
51
+ ['generateStaticParams', PATHS_FIX],
52
+ ['metadata', HEAD_FIX],
53
+ ['generateMetadata', HEAD_FIX],
54
+ ['meta', HEAD_FIX],
55
+ ...['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'all'].map(m => [m, `kay never calls it; export function ${m === 'all' ? 'GET(), POST() or another method' : `${m.toUpperCase()}()`}`] as const),
56
+ ])
57
+
58
+ /** The first route export kay never reads (Next, Remix and Astro names), `paths` that is not a function, or `prerender` that is not literally `true` or `false`, worded for `kay build` and `kay check` to prefix. */
59
+ export function routeExportProblem(analysis: ModuleAnalysis, file: string): string | undefined {
60
+ for (const name of analysis.exportedNames) {
61
+ const fix = FOREIGN_ROUTE_EXPORTS.get(name)
62
+ if (fix !== undefined)
63
+ return `export ${name} in ${file}: ${fix}.`
64
+ }
65
+ for (const stmt of analysis.program.body) {
66
+ if (stmt.type !== 'ExportNamedDeclaration' || stmt.declaration?.type !== 'VariableDeclaration')
67
+ continue
68
+ for (const d of stmt.declaration.declarations) {
69
+ const name = d.id.type === 'Identifier' ? d.id.name : undefined
70
+ const init = d.init
71
+ if (name === 'paths' && init !== null && init.type !== 'ArrowFunctionExpression' && init.type !== 'FunctionExpression')
72
+ return `export const paths in ${file}: export function paths() returning the URLs, such as () => ['/posts/a'].`
73
+ if (name === 'prerender' && !(init?.type === 'Literal' && typeof init.value === 'boolean'))
74
+ return `${init?.type === 'Literal' ? `prerender = ${init.raw ?? String(init.value)}` : 'prerender set at runtime'} in ${file}: write prerender = true or prerender = false.`
75
+ }
76
+ }
77
+ return undefined
78
+ }
79
+
80
+ /** Throws unless a route's `paths()` gave an array of URL paths starting with `/`. */
81
+ export function assertPathUrls(urls: unknown, file: string): asserts urls is string[] {
82
+ if (!Array.isArray(urls))
83
+ throw new Error(`kay build: paths() in ${file} returned ${JSON.stringify(urls)}: return an array of URL paths such as ["/posts/a"].`)
84
+ for (const url of urls) {
85
+ if (typeof url !== 'string' || !url.startsWith('/'))
86
+ throw new Error(`kay build: paths() in ${file} returned ${JSON.stringify(url)}: return URL paths such as "/posts/a".`)
87
+ }
88
+ }
89
+
90
+ export function fileToRoutePath(routesDir: string, file: string): string {
91
+ const rel = relPosix(routesDir, file).replace(TS_EXT_RE, '')
92
+ if (rel === 'index')
93
+ return '/'
94
+ const clean = rel.endsWith('/index') ? rel.slice(0, -'/index'.length) : rel
95
+ return `/${clean.replace(CATCH_ALL_RE, '*$1').replace(PARAM_RE, ':$1')}`
96
+ }
97
+
98
+ /** The shape two route paths conflict on: parameter names do not matter. */
99
+ export function normalizeRoutePattern(routePath: string): string {
100
+ return routePath
101
+ .split('/')
102
+ .map(seg => (seg.startsWith(':') ? ':' : seg.startsWith('*') ? '*' : seg))
103
+ .join('/')
104
+ }
105
+
106
+ /** Throws on two route files that serve one pattern (about.tsx vs about/index.tsx, [id].tsx vs [slug].tsx). */
107
+ export function assertNoRouteConflicts(root: string, routesDir: string, pageFiles: string[]): void {
108
+ const seen = new Map<string, { file: string, path: string }>()
109
+ for (const file of pageFiles) {
110
+ const routePath = fileToRoutePath(routesDir, file)
111
+ const normalized = normalizeRoutePattern(routePath)
112
+ const existing = seen.get(normalized)
113
+ if (existing !== undefined)
114
+ throw new Error(`kay build: conflicting routes for pattern "${routePath}": "${relPosix(root, existing.file)}" (${existing.path}) and "${relPosix(root, file)}" (${routePath})`)
115
+ seen.set(normalized, { file, path: routePath })
116
+ }
117
+ }
118
+
119
+ /** Finds all ancestor files named one of `names` from routesDir down to dirname(routeFile), outermost first. */
120
+ export function ancestorFiles(routesDir: string, routeFile: string, names: string[]): string[] {
121
+ const result: string[] = []
122
+ const relDir = relative(routesDir, dirname(routeFile))
123
+ const parts = relDir === '' ? [] : relDir.split(PATH_SEPARATOR_RE)
124
+ let cur = routesDir
125
+ for (let i = 0; i <= parts.length; i++) {
126
+ if (i > 0)
127
+ cur = join(cur, parts[i - 1]!)
128
+ for (const name of names) {
129
+ const candidate = join(cur, name)
130
+ if (existsSync(candidate))
131
+ result.push(candidate)
132
+ }
133
+ }
134
+ return result
135
+ }
@@ -0,0 +1,73 @@
1
+ // `kay build --static`: gathers the prerendered pages, client assets and public files into one folder and swaps it in as the output directory.
2
+
3
+ import type { KayApp } from '../server/index'
4
+ import { copyFileSync, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'
5
+ import { basename, dirname, join, relative } from 'node:path'
6
+ import { precompressFile, walkAllFiles } from './files'
7
+
8
+ const LEADING_SLASH_RE = /^\//
9
+
10
+ export interface StaticExportOptions {
11
+ /** The folder the site is assembled in; it becomes `finalOutDir`. */
12
+ stageDir: string
13
+ finalOutDir: string
14
+ /** The regular build output the assets and public files are copied from. */
15
+ outDir: string
16
+ clientDir: string
17
+ assetPrefix: string
18
+ assets: string[]
19
+ publicFiles: { files: string[], register: (relPath: string) => string }
20
+ /** The server the pages were prerendered with, used to render `_404` when the app has one. */
21
+ app: KayApp | undefined
22
+ hasNotFoundFile: boolean
23
+ stageSuffix: string
24
+ }
25
+
26
+ function copyInto(dstRoot: string, rel: string, src: string): void {
27
+ const dst = join(dstRoot, rel)
28
+ mkdirSync(dirname(dst), { recursive: true })
29
+ copyFileSync(src, dst)
30
+ }
31
+
32
+ export async function exportStatic(options: StaticExportOptions): Promise<void> {
33
+ const { stageDir, finalOutDir, outDir, clientDir, publicFiles } = options
34
+ if (options.hasNotFoundFile && options.app !== undefined) {
35
+ const res = await options.app.handle(new Request('http://localhost/__kay_404__'))
36
+ if (res.status >= 500)
37
+ throw new Error(`kay build --static: _404 page returned HTTP ${res.status}.`)
38
+ writeFileSync(join(stageDir, '404.html'), await res.text())
39
+ }
40
+
41
+ // Client assets go to <stage>/_kay/..., public files to <stage>/...
42
+ const assetDir = join(stageDir, options.assetPrefix.replace(LEADING_SLASH_RE, ''))
43
+ for (const rel of options.assets)
44
+ copyInto(assetDir, rel, join(clientDir, rel))
45
+ // Also pick up files written directly into the public folder without registering them.
46
+ const outPublicDir = join(outDir, 'public')
47
+ for (const abs of walkAllFiles(outPublicDir))
48
+ publicFiles.register(relative(outPublicDir, abs))
49
+ for (const rel of publicFiles.files)
50
+ copyInto(stageDir, rel, join(outPublicDir, rel))
51
+ for (const abs of walkAllFiles(stageDir))
52
+ precompressFile(abs, 128)
53
+
54
+ // Swap the stage in only after every page and asset succeeded.
55
+ if (!existsSync(finalOutDir)) {
56
+ mkdirSync(dirname(finalOutDir), { recursive: true })
57
+ renameSync(stageDir, finalOutDir)
58
+ return
59
+ }
60
+ const backupDir = join(dirname(finalOutDir), `.${basename(finalOutDir)}.prev-${options.stageSuffix}`)
61
+ renameSync(finalOutDir, backupDir)
62
+ try {
63
+ renameSync(stageDir, finalOutDir)
64
+ }
65
+ catch (err) {
66
+ try {
67
+ renameSync(backupDir, finalOutDir)
68
+ }
69
+ catch {}
70
+ throw err
71
+ }
72
+ rmSync(backupDir, { recursive: true, force: true })
73
+ }