@kayjs/kay 2.0.0-beta.1 → 2.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/build/bundle.ts +206 -33
- package/src/build/compile.ts +25 -12
- package/src/build/files.ts +38 -0
- package/src/build/graph.ts +67 -2
- package/src/build/index.ts +57 -7
- package/src/build/manifest.ts +3 -0
- package/src/build/plugin-host.ts +2 -0
- package/src/build/prerender.ts +2 -1
- package/src/build/resolve.ts +11 -18
- package/src/build/routes.ts +33 -5
- package/src/cli/check.ts +102 -45
- package/src/cli/new.ts +6 -7
- package/src/compiler/analyze.ts +65 -10
- package/src/compiler/dom.ts +143 -122
- package/src/compiler/server-only.ts +14 -8
- package/src/compiler/shared.ts +57 -14
- package/src/compiler/ssr.ts +14 -12
- package/src/dev/index.ts +94 -8
- package/src/dom/action.ts +91 -1
- package/src/dom/index.ts +8 -3
- package/src/index.ts +3 -0
- package/src/jsx-runtime.ts +421 -93
- package/src/plugins/context.ts +26 -0
- package/src/plugins/index.ts +174 -8
- package/src/server/action.ts +15 -8
- package/src/server/compress.ts +87 -14
- package/src/server/http.ts +89 -30
- package/src/server/index.ts +191 -62
- package/src/server/loader.ts +53 -35
- package/src/server/router.ts +49 -20
- package/src/server/security.ts +4 -2
- package/src/test/index.ts +5 -16
package/src/build/index.ts
CHANGED
|
@@ -9,9 +9,9 @@ import type { BuildCache } from './graph'
|
|
|
9
9
|
import type { ActionsByFile } from './islands'
|
|
10
10
|
import type { BuildManifest } from './manifest'
|
|
11
11
|
import type { PublicFiles } from './plugin-host'
|
|
12
|
-
import { copyFileSync, existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
|
|
13
13
|
import { basename, dirname, join, relative, resolve } from 'node:path'
|
|
14
|
-
import { createAppContext, loadConfig, runWithAppContext } from '../plugins/index'
|
|
14
|
+
import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
15
15
|
import { actionHash } from '../server/action'
|
|
16
16
|
import { buildClient, buildServer, pluginBunPlugins, standaloneCssFiles } from './bundle'
|
|
17
17
|
import { compileExecutable } from './compile'
|
|
@@ -40,6 +40,7 @@ export interface BuildOptions {
|
|
|
40
40
|
publicDir?: string | undefined
|
|
41
41
|
minify?: boolean | undefined
|
|
42
42
|
assetPrefix?: string | undefined
|
|
43
|
+
site?: string | undefined
|
|
43
44
|
plugins?: KayPlugin[] | undefined
|
|
44
45
|
/** Reusable incremental cache for `kay dev` (skips re-parsing/re-compiling unchanged files). */
|
|
45
46
|
cache?: BuildCache | undefined
|
|
@@ -70,6 +71,7 @@ interface BuildRun {
|
|
|
70
71
|
staticStageDir: string | undefined
|
|
71
72
|
stageSuffix: string
|
|
72
73
|
assetPrefix: string
|
|
74
|
+
site: string | undefined
|
|
73
75
|
minify: boolean
|
|
74
76
|
isDev: boolean
|
|
75
77
|
appCtx: AppRuntimeContext
|
|
@@ -96,12 +98,14 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
96
98
|
const outDir = options.static ? join(cacheBaseDir, `.static-stage-${stageSuffix}`) : finalOutDir
|
|
97
99
|
const staticStageDir = options.static ? join(dirname(finalOutDir), `.${basename(finalOutDir)}.stage-${stageSuffix}`) : undefined
|
|
98
100
|
const assetPrefix = (options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay').replace(/\/$/, '')
|
|
101
|
+
const site = (options.site ?? fileConfig.site)?.replace(/\/$/, '') || undefined
|
|
99
102
|
const publicFiles = createPublicFiles()
|
|
100
103
|
const appCtx = createAppContext({
|
|
101
104
|
root,
|
|
102
105
|
outDir,
|
|
103
106
|
publicDir: join(outDir, 'public'),
|
|
104
107
|
assetPrefix,
|
|
108
|
+
site,
|
|
105
109
|
dev: isDev,
|
|
106
110
|
onRegisterPublicFile: publicFiles.register,
|
|
107
111
|
})
|
|
@@ -114,7 +118,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
114
118
|
return await runWithAppContext(appCtx, () => runBuild({
|
|
115
119
|
options,
|
|
116
120
|
root,
|
|
117
|
-
plugins: options.plugins ?? fileConfig.plugins
|
|
121
|
+
plugins: resolvePlugins(options.plugins ?? fileConfig.plugins),
|
|
118
122
|
routesDir,
|
|
119
123
|
publicDir,
|
|
120
124
|
finalOutDir,
|
|
@@ -122,6 +126,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
122
126
|
staticStageDir,
|
|
123
127
|
stageSuffix,
|
|
124
128
|
assetPrefix,
|
|
129
|
+
site,
|
|
125
130
|
minify: options.minify ?? true,
|
|
126
131
|
isDev,
|
|
127
132
|
appCtx,
|
|
@@ -154,8 +159,10 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
154
159
|
const allRouteFiles = walkRoutes(routesDir).sort()
|
|
155
160
|
const specialFiles = allRouteFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
|
|
156
161
|
const candidatePageFiles = allRouteFiles.filter(f => !basename(f).startsWith('_'))
|
|
162
|
+
const rootLayoutSrc = join(routesDir, '_layout.tsx')
|
|
157
163
|
const errorSrc = join(routesDir, '_error.tsx')
|
|
158
164
|
const notFoundSrc = join(routesDir, '_404.tsx')
|
|
165
|
+
const hasRootLayout = existsSync(rootLayoutSrc)
|
|
159
166
|
const hasErrorFile = existsSync(errorSrc)
|
|
160
167
|
const hasNotFoundFile = existsSync(notFoundSrc)
|
|
161
168
|
|
|
@@ -198,12 +205,14 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
198
205
|
.flatMap(p => p.css ?? [])
|
|
199
206
|
.map(c => resolve(root, c))
|
|
200
207
|
.filter(c => existsSync(c))
|
|
201
|
-
const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, graph, cache: options.cache, plugins, actionsByFile, islands }
|
|
208
|
+
const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, analyze: options.analyze === true, graph, cache: options.cache, plugins, actionsByFile, islands }
|
|
202
209
|
|
|
210
|
+
const configSrc = join(root, 'kay.config.ts')
|
|
211
|
+
const hasConfigFile = existsSync(configSrc)
|
|
203
212
|
const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
|
|
204
213
|
const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
|
|
205
|
-
const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles]
|
|
206
|
-
const serverRoot = standaloneActionFiles.length > 0 ? root : routesDir
|
|
214
|
+
const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles, ...(hasConfigFile ? [configSrc] : [])]
|
|
215
|
+
const serverRoot = standaloneActionFiles.length > 0 || hasConfigFile ? root : routesDir
|
|
207
216
|
|
|
208
217
|
// The server compiles against the island chunk URLs, so islands build first; without islands both passes run in parallel.
|
|
209
218
|
const clientPass = () => buildClient(env, standaloneCssFiles(graph, pluginCssFiles, islands.cssFiles))
|
|
@@ -217,6 +226,44 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
217
226
|
await buildServer(env, serverEntries, serverRoot, client.islandChunks)
|
|
218
227
|
}
|
|
219
228
|
|
|
229
|
+
if (options.cache !== undefined) {
|
|
230
|
+
const watched = options.cache.watchedFiles
|
|
231
|
+
watched.clear()
|
|
232
|
+
const recordWatched = (file: string) => {
|
|
233
|
+
if (!existsSync(file))
|
|
234
|
+
return
|
|
235
|
+
let real = file
|
|
236
|
+
try {
|
|
237
|
+
real = realpathSync(file)
|
|
238
|
+
}
|
|
239
|
+
catch {}
|
|
240
|
+
watched.add(real)
|
|
241
|
+
}
|
|
242
|
+
for (const f of graph.analyses.keys())
|
|
243
|
+
recordWatched(f)
|
|
244
|
+
for (const f of options.cache.lastClient?.inputStamps.keys() ?? [])
|
|
245
|
+
recordWatched(f)
|
|
246
|
+
for (const f of options.cache.lastServer?.inputStamps.keys() ?? [])
|
|
247
|
+
recordWatched(f)
|
|
248
|
+
for (const f of pluginCssFiles)
|
|
249
|
+
recordWatched(f)
|
|
250
|
+
if (hasConfigFile)
|
|
251
|
+
recordWatched(configSrc)
|
|
252
|
+
// Prune deleted files from caches so long-lived dev sessions stay flat in memory.
|
|
253
|
+
for (const f of [...options.cache.analyses.keys()]) {
|
|
254
|
+
if (!existsSync(f))
|
|
255
|
+
options.cache.analyses.delete(f)
|
|
256
|
+
}
|
|
257
|
+
for (const f of [...options.cache.domCompiled.keys()]) {
|
|
258
|
+
if (!existsSync(f))
|
|
259
|
+
options.cache.domCompiled.delete(f)
|
|
260
|
+
}
|
|
261
|
+
for (const f of [...options.cache.ssrCompiled.keys()]) {
|
|
262
|
+
if (!existsSync(f))
|
|
263
|
+
options.cache.ssrCompiled.delete(f)
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
220
267
|
const toOutRel = (srcFile: string): string =>
|
|
221
268
|
relPosix(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js')))
|
|
222
269
|
|
|
@@ -261,6 +308,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
261
308
|
clientDir,
|
|
262
309
|
outPublicDir,
|
|
263
310
|
assetPrefix,
|
|
311
|
+
site: run.site,
|
|
264
312
|
minify: run.minify,
|
|
265
313
|
isStatic,
|
|
266
314
|
isDev,
|
|
@@ -279,6 +327,8 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
279
327
|
globalStyles,
|
|
280
328
|
...(host.headTags.length > 0 ? { headTags: host.headTags } : {}),
|
|
281
329
|
routes,
|
|
330
|
+
...(hasConfigFile ? { configFile: toOutRel(configSrc) } : {}),
|
|
331
|
+
...(hasRootLayout ? { rootLayoutFile: toOutRel(rootLayoutSrc) } : {}),
|
|
282
332
|
errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
|
|
283
333
|
notFoundFile: hasNotFoundFile ? toOutRel(notFoundSrc) : undefined,
|
|
284
334
|
actions: buildActionEntries(actionsByFile, routesDir, toOutRel),
|
|
@@ -294,7 +344,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
294
344
|
const prerenderRoutes = options.prerender !== false || isStatic ? routes.filter(r => r.prerender) : []
|
|
295
345
|
const prerenderDir = isStatic ? run.staticStageDir! : join(outDir, 'prerendered')
|
|
296
346
|
const app = prerenderRoutes.length > 0 || isStatic
|
|
297
|
-
? await prerender({ root, outDir, assetPrefix, plugins, isDev, isStatic, prerenderDir, routes: prerenderRoutes })
|
|
347
|
+
? await prerender({ root, outDir, assetPrefix, site: run.site, plugins, isDev, isStatic, prerenderDir, routes: prerenderRoutes })
|
|
298
348
|
: undefined
|
|
299
349
|
|
|
300
350
|
try {
|
package/src/build/manifest.ts
CHANGED
|
@@ -43,6 +43,9 @@ export interface BuildManifest {
|
|
|
43
43
|
globalStyles?: string[] | undefined
|
|
44
44
|
headTags?: string[] | undefined
|
|
45
45
|
routes: RouteManifestEntry[]
|
|
46
|
+
configFile?: string | undefined
|
|
47
|
+
/** Explicit root `_layout.tsx` compiled module path (never inferred from subdirectory layouts). */
|
|
48
|
+
rootLayoutFile?: string | undefined
|
|
46
49
|
errorFile?: string | undefined
|
|
47
50
|
notFoundFile?: string | undefined
|
|
48
51
|
actions: ActionManifestEntry[]
|
package/src/build/plugin-host.ts
CHANGED
|
@@ -45,6 +45,7 @@ export interface PluginHostOptions {
|
|
|
45
45
|
clientDir: string
|
|
46
46
|
outPublicDir: string
|
|
47
47
|
assetPrefix: string
|
|
48
|
+
site?: string | undefined
|
|
48
49
|
minify: boolean
|
|
49
50
|
isStatic: boolean
|
|
50
51
|
isDev: boolean
|
|
@@ -100,6 +101,7 @@ export function createPluginHost(options: PluginHostOptions) {
|
|
|
100
101
|
root: options.root,
|
|
101
102
|
outDir,
|
|
102
103
|
assetPrefix,
|
|
104
|
+
...(options.site !== undefined ? { site: options.site } : {}),
|
|
103
105
|
minify: options.minify,
|
|
104
106
|
isStatic: options.isStatic,
|
|
105
107
|
dev: options.isDev,
|
package/src/build/prerender.ts
CHANGED
|
@@ -30,6 +30,7 @@ export interface PrerenderOptions {
|
|
|
30
30
|
root: string
|
|
31
31
|
outDir: string
|
|
32
32
|
assetPrefix: string
|
|
33
|
+
site?: string | undefined
|
|
33
34
|
plugins: KayPlugin[]
|
|
34
35
|
isDev: boolean
|
|
35
36
|
isStatic: boolean
|
|
@@ -42,7 +43,7 @@ export interface PrerenderOptions {
|
|
|
42
43
|
export async function prerender(options: PrerenderOptions) {
|
|
43
44
|
const { root, outDir, prerenderDir, isStatic } = options
|
|
44
45
|
const { createServer } = await import('../server/index')
|
|
45
|
-
const app = await createServer({ root, outDir: relPosix(root, outDir), assetPrefix: options.assetPrefix, plugins: options.plugins, dev: options.isDev })
|
|
46
|
+
const app = await createServer({ root, outDir: relPosix(root, outDir), assetPrefix: options.assetPrefix, site: options.site, plugins: options.plugins, dev: options.isDev })
|
|
46
47
|
mkdirSync(prerenderDir, { recursive: true })
|
|
47
48
|
|
|
48
49
|
const stamp = `${Date.now()}-${++prerenderImportSeq}`
|
package/src/build/resolve.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { statSync } from 'node:fs'
|
|
4
4
|
import { dirname, join, resolve } from 'node:path'
|
|
5
|
+
import pkg from '../../package.json' with { type: 'json' }
|
|
5
6
|
|
|
6
7
|
export const KAY_SRC_ROOT = resolve(import.meta.dir, '..')
|
|
7
8
|
|
|
@@ -18,9 +19,11 @@ export function resolveImportPath(fromFile: string, specifier: string): string |
|
|
|
18
19
|
if (
|
|
19
20
|
specifier === 'kay'
|
|
20
21
|
|| specifier.startsWith('kay/')
|
|
21
|
-
|| specifier
|
|
22
|
+
|| specifier === '@kayjs/kay'
|
|
23
|
+
|| specifier.startsWith('@kayjs/kay/')
|
|
22
24
|
|| specifier.startsWith('node:')
|
|
23
|
-
|| specifier
|
|
25
|
+
|| specifier === 'bun'
|
|
26
|
+
|| specifier.startsWith('bun:')
|
|
24
27
|
|| specifier.startsWith('~')
|
|
25
28
|
) {
|
|
26
29
|
return undefined
|
|
@@ -34,22 +37,12 @@ export function resolveImportPath(fromFile: string, specifier: string): string |
|
|
|
34
37
|
}
|
|
35
38
|
}
|
|
36
39
|
|
|
37
|
-
const KAY_SPECIFIER_FILES = new Map(
|
|
38
|
-
[
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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
|
-
])
|
|
40
|
+
const KAY_SPECIFIER_FILES = new Map<string, string>(
|
|
41
|
+
Object.entries(pkg.exports as Record<string, string>).map(([subpath, target]) => [
|
|
42
|
+
subpath === '.' ? 'kay' : `kay/${subpath.slice(2)}`,
|
|
43
|
+
target.replace(/^\.\/src\//, ''),
|
|
44
|
+
]),
|
|
45
|
+
)
|
|
53
46
|
|
|
54
47
|
/** Maps `kay`, `kay/<subpath>` and the `@kayjs/kay` spelling of both to their source file. */
|
|
55
48
|
export function resolveKaySpecifier(specifier: string): string | undefined {
|
package/src/build/routes.ts
CHANGED
|
@@ -55,12 +55,35 @@ const FOREIGN_ROUTE_EXPORTS = new Map([
|
|
|
55
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
56
|
])
|
|
57
57
|
|
|
58
|
-
|
|
59
|
-
|
|
58
|
+
function findExportOffset(analysis: ModuleAnalysis, exportName: string): number {
|
|
59
|
+
for (const stmt of analysis.program.body) {
|
|
60
|
+
if (stmt.type !== 'ExportNamedDeclaration')
|
|
61
|
+
continue
|
|
62
|
+
if (stmt.declaration?.type === 'FunctionDeclaration' && stmt.declaration.id?.name === exportName)
|
|
63
|
+
return stmt.start
|
|
64
|
+
if (stmt.declaration?.type === 'ClassDeclaration' && stmt.declaration.id?.name === exportName)
|
|
65
|
+
return stmt.start
|
|
66
|
+
if (stmt.declaration?.type === 'VariableDeclaration') {
|
|
67
|
+
for (const d of stmt.declaration.declarations) {
|
|
68
|
+
if (d.id.type === 'Identifier' && d.id.name === exportName)
|
|
69
|
+
return d.start
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const spec of stmt.specifiers) {
|
|
73
|
+
const exp = spec.exported.type === 'Identifier' ? spec.exported.name : spec.exported.value
|
|
74
|
+
if (exp === exportName)
|
|
75
|
+
return spec.start
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return 0
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Returns the first route export problem together with its byte offset in the module source. */
|
|
82
|
+
export function routeExportProblemLocation(analysis: ModuleAnalysis, file: string): { message: string, offset: number } | undefined {
|
|
60
83
|
for (const name of analysis.exportedNames) {
|
|
61
84
|
const fix = FOREIGN_ROUTE_EXPORTS.get(name)
|
|
62
85
|
if (fix !== undefined)
|
|
63
|
-
return `export ${name} in ${file}: ${fix}
|
|
86
|
+
return { message: `export ${name} in ${file}: ${fix}.`, offset: findExportOffset(analysis, name) }
|
|
64
87
|
}
|
|
65
88
|
for (const stmt of analysis.program.body) {
|
|
66
89
|
if (stmt.type !== 'ExportNamedDeclaration' || stmt.declaration?.type !== 'VariableDeclaration')
|
|
@@ -69,14 +92,19 @@ export function routeExportProblem(analysis: ModuleAnalysis, file: string): stri
|
|
|
69
92
|
const name = d.id.type === 'Identifier' ? d.id.name : undefined
|
|
70
93
|
const init = d.init
|
|
71
94
|
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']
|
|
95
|
+
return { message: `export const paths in ${file}: export function paths() returning the URLs, such as () => ['/posts/a'].`, offset: d.start }
|
|
73
96
|
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
|
|
97
|
+
return { message: `${init?.type === 'Literal' ? `prerender = ${init.raw ?? String(init.value)}` : 'prerender set at runtime'} in ${file}: write prerender = true or prerender = false.`, offset: d.start }
|
|
75
98
|
}
|
|
76
99
|
}
|
|
77
100
|
return undefined
|
|
78
101
|
}
|
|
79
102
|
|
|
103
|
+
/** 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. */
|
|
104
|
+
export function routeExportProblem(analysis: ModuleAnalysis, file: string): string | undefined {
|
|
105
|
+
return routeExportProblemLocation(analysis, file)?.message
|
|
106
|
+
}
|
|
107
|
+
|
|
80
108
|
/** Throws unless a route's `paths()` gave an array of URL paths starting with `/`. */
|
|
81
109
|
export function assertPathUrls(urls: unknown, file: string): asserts urls is string[] {
|
|
82
110
|
if (!Array.isArray(urls))
|
package/src/cli/check.ts
CHANGED
|
@@ -5,11 +5,11 @@ import { existsSync, readFileSync } from 'node:fs'
|
|
|
5
5
|
import { basename, join, relative, resolve } from 'node:path'
|
|
6
6
|
import { isTsFile, relPosix, walkFiles, walkRoutes } from '../build/files'
|
|
7
7
|
import { ModuleGraph } from '../build/graph'
|
|
8
|
-
import { fileToRoutePath, hasRouteHandlerExport, normalizeRoutePattern,
|
|
8
|
+
import { fileToRoutePath, hasRouteHandlerExport, normalizeRoutePattern, routeExportProblemLocation, SPECIAL_ROUTE_FILES } from '../build/routes'
|
|
9
9
|
import { analyzeModule, walk } from '../compiler/analyze'
|
|
10
|
-
import {
|
|
11
|
-
import { jsxTagName } from '../compiler/shared'
|
|
12
|
-
import { createAppContext, loadConfig, runWithAppContext } from '../plugins/index'
|
|
10
|
+
import { findPrivateEnvOffset, SERVER_ONLY_MODULES } from '../compiler/server-only'
|
|
11
|
+
import { DIAGNOSTIC_PREFIX_RE, formatDiagnostic, formatLoc, jsxTagName } from '../compiler/shared'
|
|
12
|
+
import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
13
13
|
|
|
14
14
|
export interface CheckResult {
|
|
15
15
|
ok: boolean
|
|
@@ -28,10 +28,19 @@ function walkTsFiles(dir: string): string[] {
|
|
|
28
28
|
})
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
function
|
|
31
|
+
function sourceOf(file: string, sources: Map<string, string>): string {
|
|
32
|
+
let code = sources.get(file)
|
|
33
|
+
if (code === undefined) {
|
|
34
|
+
code = readFileSync(file, 'utf8')
|
|
35
|
+
sources.set(file, code)
|
|
36
|
+
}
|
|
37
|
+
return code
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function analysisOf(file: string, analyses: Map<string, ModuleAnalysis>, sources: Map<string, string>, unparsable: Set<string>): ModuleAnalysis | undefined {
|
|
32
41
|
if (!analyses.has(file) && !unparsable.has(file) && isTsFile(file)) {
|
|
33
42
|
try {
|
|
34
|
-
analyses.set(file, analyzeModule(file,
|
|
43
|
+
analyses.set(file, analyzeModule(file, sourceOf(file, sources)))
|
|
35
44
|
}
|
|
36
45
|
catch {
|
|
37
46
|
unparsable.add(file)
|
|
@@ -40,8 +49,44 @@ function analysisOf(file: string, analyses: Map<string, ModuleAnalysis>, unparsa
|
|
|
40
49
|
return analyses.get(file)
|
|
41
50
|
}
|
|
42
51
|
|
|
52
|
+
function locOf(root: string, file: string, sources: Map<string, string>, offset = 0): string {
|
|
53
|
+
const rel = relPosix(root, file)
|
|
54
|
+
const code = sources.get(file)
|
|
55
|
+
return code !== undefined ? formatLoc(rel, code, offset) : `${rel}:1:1`
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function findExportedConstOffset(analysis: ModuleAnalysis, name: string): number {
|
|
59
|
+
for (const stmt of analysis.program.body) {
|
|
60
|
+
if (stmt.type === 'ExportNamedDeclaration' && stmt.declaration?.type === 'VariableDeclaration') {
|
|
61
|
+
for (const d of stmt.declaration.declarations) {
|
|
62
|
+
if (d.id.type === 'Identifier' && d.id.name === name)
|
|
63
|
+
return d.start
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return 0
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function normalizeDiagnosticPath(root: string, file: string, message: string): string {
|
|
71
|
+
const rel = relPosix(root, file)
|
|
72
|
+
if (DIAGNOSTIC_PREFIX_RE.test(message)) {
|
|
73
|
+
if (message.startsWith(`${file}:`))
|
|
74
|
+
return `${rel}${message.slice(file.length)}`
|
|
75
|
+
return message
|
|
76
|
+
}
|
|
77
|
+
return formatDiagnostic(`${rel}:1:1`, message)
|
|
78
|
+
}
|
|
79
|
+
|
|
43
80
|
// Walks the local imports of an island the way the client build follows them: a module that only declares actions is stubbed there, so its imports stop the walk.
|
|
44
|
-
function checkIslandReach(
|
|
81
|
+
function checkIslandReach(
|
|
82
|
+
island: string,
|
|
83
|
+
root: string,
|
|
84
|
+
graph: ModuleGraph,
|
|
85
|
+
sources: Map<string, string>,
|
|
86
|
+
unparsable: Set<string>,
|
|
87
|
+
reported: Set<string>,
|
|
88
|
+
errors: string[],
|
|
89
|
+
): void {
|
|
45
90
|
const islandRel = relPosix(root, island)
|
|
46
91
|
const seen = new Set<string>()
|
|
47
92
|
const stack = [island]
|
|
@@ -52,30 +97,29 @@ function checkIslandReach(island: string, root: string, graph: ModuleGraph, unpa
|
|
|
52
97
|
seen.add(file)
|
|
53
98
|
if (NODE_MODULES_RE.test(file))
|
|
54
99
|
continue
|
|
55
|
-
const analysis = analysisOf(file, graph.analyses, unparsable)
|
|
100
|
+
const analysis = analysisOf(file, graph.analyses, sources, unparsable)
|
|
56
101
|
if (analysis === undefined || (file !== island && !analysis.isInteractive && analysis.exportedActions.length > 0))
|
|
57
102
|
continue
|
|
58
|
-
const
|
|
59
|
-
const report = (key: string, message: string): void => {
|
|
103
|
+
const report = (key: string, offset: number, message: string): void => {
|
|
60
104
|
if (reported.has(`${file}\0${key}`))
|
|
61
105
|
return
|
|
62
106
|
reported.add(`${file}\0${key}`)
|
|
63
|
-
errors.push(message)
|
|
107
|
+
errors.push(formatDiagnostic(locOf(root, file, sources, offset), message))
|
|
64
108
|
}
|
|
65
109
|
for (const imp of analysis.imports) {
|
|
66
110
|
if (SERVER_ONLY_MODULES.has(imp.source)) {
|
|
67
|
-
report(imp.source, file === island
|
|
68
|
-
? `kay check:
|
|
69
|
-
: `kay check:
|
|
111
|
+
report(imp.source, imp.start, file === island
|
|
112
|
+
? `kay check: interactive island imports server-only module "${imp.source}". Move server logic to a server action or async server component.`
|
|
113
|
+
: `kay check: imports server-only module "${imp.source}" and is reachable from the island in ${islandRel}. Move server logic to a server action or async server component.`)
|
|
70
114
|
continue
|
|
71
115
|
}
|
|
72
116
|
const target = graph.resolve(file, imp.source)
|
|
73
117
|
if (target !== undefined) {
|
|
74
|
-
const targetAnalysis = analysisOf(target, graph.analyses, unparsable)
|
|
118
|
+
const targetAnalysis = analysisOf(target, graph.analyses, sources, unparsable)
|
|
75
119
|
if (targetAnalysis !== undefined && !targetAnalysis.isInteractive && targetAnalysis.exportedActions.length > 0) {
|
|
76
120
|
const missing = imp.specifiers.find(s => s.imported !== '*' && !targetAnalysis.exportedActions.includes(s.imported))
|
|
77
121
|
if (missing !== undefined)
|
|
78
|
-
report(`action-export:${target}:${missing.imported}`, `kay check:
|
|
122
|
+
report(`action-export:${target}:${missing.imported}`, imp.start, `kay check: imports non-action "${missing.imported}" from server action file ${relPosix(root, target)}. Move ${missing.imported} into a module without actions.`)
|
|
79
123
|
continue
|
|
80
124
|
}
|
|
81
125
|
stack.push(target)
|
|
@@ -83,15 +127,16 @@ function checkIslandReach(island: string, root: string, graph: ModuleGraph, unpa
|
|
|
83
127
|
}
|
|
84
128
|
for (const re of analysis.reexports) {
|
|
85
129
|
if (SERVER_ONLY_MODULES.has(re.source)) {
|
|
86
|
-
report(re.source, `kay check:
|
|
130
|
+
report(re.source, re.start, `kay check: re-exports from server-only module "${re.source}" and is reachable from the island in ${islandRel}.`)
|
|
87
131
|
continue
|
|
88
132
|
}
|
|
89
133
|
const target = graph.resolve(file, re.source)
|
|
90
134
|
if (target !== undefined)
|
|
91
135
|
stack.push(target)
|
|
92
136
|
}
|
|
93
|
-
|
|
94
|
-
|
|
137
|
+
const envOffset = findPrivateEnvOffset(analysis.program)
|
|
138
|
+
if (envOffset !== undefined)
|
|
139
|
+
report('process.env', envOffset, `kay check: reads process.env and is reachable from the island in ${islandRel}. Only process.env.PUBLIC_* reaches the browser.`)
|
|
95
140
|
}
|
|
96
141
|
}
|
|
97
142
|
|
|
@@ -106,7 +151,7 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
106
151
|
let plugins: Awaited<ReturnType<typeof loadConfig>>['plugins'] = []
|
|
107
152
|
try {
|
|
108
153
|
const cfg = await loadConfig(root)
|
|
109
|
-
plugins = cfg.plugins
|
|
154
|
+
plugins = resolvePlugins(cfg.plugins)
|
|
110
155
|
if (cfg.routesDir !== undefined)
|
|
111
156
|
routesDir = resolve(root, cfg.routesDir)
|
|
112
157
|
if (cfg.outDir !== undefined)
|
|
@@ -115,12 +160,14 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
115
160
|
assetPrefix = cfg.assetPrefix.replace(/\/$/, '')
|
|
116
161
|
}
|
|
117
162
|
catch (err) {
|
|
118
|
-
errors.push(
|
|
163
|
+
errors.push(formatDiagnostic('kay.config.ts:1:1', err instanceof Error ? err.message : String(err)))
|
|
119
164
|
}
|
|
120
165
|
|
|
121
166
|
// 2. Validate routesDir exists
|
|
122
|
-
if (!existsSync(routesDir))
|
|
123
|
-
|
|
167
|
+
if (!existsSync(routesDir)) {
|
|
168
|
+
const relRoutes = relative(root, routesDir) || routesDir
|
|
169
|
+
errors.push(formatDiagnostic(`${relRoutes.replace(/\\/g, '/')}:1:1`, `kay check: missing routes directory: ${relRoutes}`))
|
|
170
|
+
}
|
|
124
171
|
|
|
125
172
|
// 3. Parse & run Kay static compiler analysis across src/ AND custom routesDir
|
|
126
173
|
const srcDir = resolve(root, 'src')
|
|
@@ -136,18 +183,21 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
136
183
|
const files = [...fileSet].sort()
|
|
137
184
|
const graph = new ModuleGraph()
|
|
138
185
|
const { analyses } = graph
|
|
186
|
+
const sources = new Map<string, string>()
|
|
139
187
|
const unparsable = new Set<string>()
|
|
140
188
|
|
|
141
189
|
const warnings: string[] = []
|
|
142
190
|
for (const file of files) {
|
|
143
191
|
try {
|
|
144
|
-
const
|
|
192
|
+
const code = sourceOf(file, sources)
|
|
193
|
+
const analysis = analyzeModule(file, code)
|
|
145
194
|
analyses.set(file, analysis)
|
|
146
195
|
warnings.push(...analysis.warnings)
|
|
147
196
|
}
|
|
148
197
|
catch (err) {
|
|
149
198
|
unparsable.add(file)
|
|
150
|
-
|
|
199
|
+
const msg = err instanceof Error ? err.message : String(err)
|
|
200
|
+
errors.push(normalizeDiagnosticPath(root, file, msg))
|
|
151
201
|
}
|
|
152
202
|
}
|
|
153
203
|
|
|
@@ -164,9 +214,9 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
164
214
|
return false
|
|
165
215
|
try {
|
|
166
216
|
if (spec.imported === '*')
|
|
167
|
-
return (analysisOf(resolved, analyses, unparsable)?.stateExports.length ?? 0) > 0
|
|
217
|
+
return (analysisOf(resolved, analyses, sources, unparsable)?.stateExports.length ?? 0) > 0
|
|
168
218
|
const target = graph.exportTarget(resolved, spec.imported)
|
|
169
|
-
return analysisOf(target.file, analyses, unparsable)?.stateExports.includes(target.exportName) === true
|
|
219
|
+
return analysisOf(target.file, analyses, sources, unparsable)?.stateExports.includes(target.exportName) === true
|
|
170
220
|
}
|
|
171
221
|
catch {
|
|
172
222
|
return false
|
|
@@ -175,9 +225,9 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
175
225
|
if (state !== undefined) {
|
|
176
226
|
const reason = `reads ${state.local} from '${imp.source}'`
|
|
177
227
|
if (analysis.hasAsyncDefault)
|
|
178
|
-
errors.push(`kay check: async route component
|
|
228
|
+
errors.push(formatDiagnostic(locOf(root, file, sources, imp.start), `kay check: async route component cannot use browser interactivity (${reason}).`))
|
|
179
229
|
else
|
|
180
|
-
analyses.set(file, { ...analysis, isInteractive: true, interactiveReason: reason })
|
|
230
|
+
analyses.set(file, { ...analysis, isInteractive: true, interactiveReason: reason, interactiveOffset: imp.start })
|
|
181
231
|
break
|
|
182
232
|
}
|
|
183
233
|
}
|
|
@@ -196,12 +246,15 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
196
246
|
|
|
197
247
|
// Special route files (`_layout.tsx`, `_error.tsx`, `_404.tsx`) cannot be interactive
|
|
198
248
|
if (routeFileSet.has(file) && SPECIAL_ROUTE_FILES.has(basename(file)) && analysis.isInteractive) {
|
|
199
|
-
errors.push(
|
|
249
|
+
errors.push(formatDiagnostic(
|
|
250
|
+
locOf(root, file, sources, analysis.interactiveOffset ?? 0),
|
|
251
|
+
`kay check: ${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}.`,
|
|
252
|
+
))
|
|
200
253
|
}
|
|
201
254
|
|
|
202
255
|
// Guardrail 1: server-only imports and private env reads in an island or any module it imports
|
|
203
256
|
if (analysis.isInteractive)
|
|
204
|
-
checkIslandReach(file, root, graph, unparsable, reported, errors)
|
|
257
|
+
checkIslandReach(file, root, graph, sources, unparsable, reported, errors)
|
|
205
258
|
|
|
206
259
|
// Guardrail 2: non-serializable props passed from static server code into an island (including barrels & namespaces)
|
|
207
260
|
if (!analysis.isInteractive && file.endsWith('.tsx')) {
|
|
@@ -218,7 +271,7 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
218
271
|
}
|
|
219
272
|
try {
|
|
220
273
|
const target = graph.exportTarget(resolved, spec.imported)
|
|
221
|
-
if (analysisOf(target.file, analyses, unparsable)?.isInteractive)
|
|
274
|
+
if (analysisOf(target.file, analyses, sources, unparsable)?.isInteractive)
|
|
222
275
|
islandTags.add(spec.local)
|
|
223
276
|
}
|
|
224
277
|
catch {}
|
|
@@ -234,7 +287,7 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
234
287
|
if (nsFile !== undefined && member !== undefined) {
|
|
235
288
|
try {
|
|
236
289
|
const target = graph.exportTarget(nsFile, member)
|
|
237
|
-
return analysisOf(target.file, analyses, unparsable)?.isInteractive === true
|
|
290
|
+
return analysisOf(target.file, analyses, sources, unparsable)?.isInteractive === true
|
|
238
291
|
}
|
|
239
292
|
catch {}
|
|
240
293
|
}
|
|
@@ -259,14 +312,16 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
259
312
|
continue
|
|
260
313
|
const expr = attr.value.expression
|
|
261
314
|
if (expr.type === 'ArrowFunctionExpression' || expr.type === 'FunctionExpression') {
|
|
262
|
-
errors.push(
|
|
263
|
-
|
|
264
|
-
|
|
315
|
+
errors.push(formatDiagnostic(
|
|
316
|
+
locOf(root, file, sources, attr.start),
|
|
317
|
+
`kay check: cannot pass function prop "${attrName}" from a server component into island <${tag}>. Define the handler inside the island or pass serializable data.`,
|
|
318
|
+
))
|
|
265
319
|
}
|
|
266
320
|
else if (expr.type === 'NewExpression' && expr.callee.type === 'Identifier' && !SERIALIZABLE_NEW_CTORS.has(expr.callee.name)) {
|
|
267
|
-
errors.push(
|
|
268
|
-
|
|
269
|
-
|
|
321
|
+
errors.push(formatDiagnostic(
|
|
322
|
+
locOf(root, file, sources, expr.start),
|
|
323
|
+
`kay check: cannot pass non-serializable \`new ${expr.callee.name}()\` prop "${attrName}" into island <${tag}>.`,
|
|
324
|
+
))
|
|
270
325
|
}
|
|
271
326
|
}
|
|
272
327
|
})
|
|
@@ -275,15 +330,15 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
275
330
|
|
|
276
331
|
// Route-specific guardrails (only real route files matching `kay build`)
|
|
277
332
|
if (routeFileSet.has(file) && !basename(file).startsWith('_')) {
|
|
278
|
-
const problem =
|
|
333
|
+
const problem = routeExportProblemLocation(analysis, rel)
|
|
279
334
|
if (problem !== undefined)
|
|
280
|
-
errors.push(`kay check: ${problem}`)
|
|
335
|
+
errors.push(formatDiagnostic(locOf(root, file, sources, problem.offset), `kay check: ${problem.message}`))
|
|
281
336
|
|
|
282
337
|
if (hasRouteHandlerExport(analysis)) {
|
|
283
338
|
const conflictKey = normalizeRoutePattern(fileToRoutePath(routesDir, file))
|
|
284
339
|
const prev = seenRoutes.get(conflictKey)
|
|
285
340
|
if (prev !== undefined) {
|
|
286
|
-
errors.push(`kay check: conflicting routes "${prev}" and "${rel}" both match "${conflictKey}".`)
|
|
341
|
+
errors.push(formatDiagnostic(`${rel}:1:1`, `kay check: conflicting routes "${prev}" and "${rel}" both match "${conflictKey}".`))
|
|
287
342
|
}
|
|
288
343
|
else {
|
|
289
344
|
seenRoutes.set(conflictKey, rel)
|
|
@@ -291,7 +346,8 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
291
346
|
|
|
292
347
|
// Guardrail 4: dynamic prerender = true route missing paths()
|
|
293
348
|
if (analysis.hasPrerender && (conflictKey.includes(':') || conflictKey.includes('*')) && !analysis.hasPaths) {
|
|
294
|
-
|
|
349
|
+
const offset = findExportedConstOffset(analysis, 'prerender')
|
|
350
|
+
errors.push(formatDiagnostic(locOf(root, file, sources, offset), `kay check: dynamic route exports \`prerender = true\` without exporting \`paths()\`.`))
|
|
295
351
|
}
|
|
296
352
|
}
|
|
297
353
|
}
|
|
@@ -310,7 +366,7 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
310
366
|
root,
|
|
311
367
|
routesDir,
|
|
312
368
|
error(message: string) {
|
|
313
|
-
errors.push(message)
|
|
369
|
+
errors.push(DIAGNOSTIC_PREFIX_RE.test(message) ? message : formatDiagnostic('kay.config.ts:1:1', message))
|
|
314
370
|
},
|
|
315
371
|
}
|
|
316
372
|
for (const plugin of plugins) {
|
|
@@ -319,7 +375,8 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
319
375
|
await runWithAppContext(appCtx, () => plugin.check!(pluginCtx))
|
|
320
376
|
}
|
|
321
377
|
catch (err) {
|
|
322
|
-
|
|
378
|
+
const msg = `${plugin.name}: ${err instanceof Error ? err.message : String(err)}`
|
|
379
|
+
errors.push(DIAGNOSTIC_PREFIX_RE.test(msg) ? msg : formatDiagnostic('kay.config.ts:1:1', msg))
|
|
323
380
|
}
|
|
324
381
|
}
|
|
325
382
|
}
|