@kayjs/kay 2.0.0-beta.1 → 2.0.0-beta.3
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 +209 -34
- package/src/build/compile.ts +22 -46
- package/src/build/files.ts +38 -0
- package/src/build/graph.ts +67 -2
- package/src/build/index.ts +75 -13
- package/src/build/manifest.ts +5 -0
- package/src/build/plugin-host.ts +2 -0
- package/src/build/prerender.ts +16 -7
- package/src/build/resolve.ts +11 -18
- package/src/build/routes.ts +33 -5
- package/src/build/server-entry.ts +38 -0
- 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 +96 -29
- 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/config.ts +49 -0
- package/src/plugins/context.ts +4 -0
- package/src/plugins/index.ts +7 -216
- package/src/plugins/load.ts +38 -0
- package/src/plugins/order.ts +107 -0
- package/src/plugins/services.ts +23 -0
- package/src/plugins/types.ts +197 -0
- package/src/server/action-registry.ts +72 -0
- package/src/server/action.ts +15 -8
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +182 -0
- package/src/server/compress.ts +87 -14
- package/src/server/document.ts +192 -0
- package/src/server/errors.ts +123 -0
- package/src/server/http.ts +103 -30
- package/src/server/index.ts +131 -701
- package/src/server/loader.ts +62 -69
- package/src/server/page.ts +107 -0
- package/src/server/plugin-host.ts +167 -0
- package/src/server/router.ts +49 -20
- package/src/server/security.ts +44 -3
- package/src/server/static-dir.ts +22 -3
- package/src/server/stream.ts +94 -0
- package/src/test/index.ts +24 -19
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'
|
|
@@ -22,6 +22,7 @@ import { buildActionEntries, buildRouteEntries } from './manifest'
|
|
|
22
22
|
import { createPluginHost, createPublicFiles } from './plugin-host'
|
|
23
23
|
import { prerender } from './prerender'
|
|
24
24
|
import { formatBundleReport } from './report'
|
|
25
|
+
import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
|
|
25
26
|
import { KAY_SRC_ROOT, resolveKaySpecifier } from './resolve'
|
|
26
27
|
import { assertNoRouteConflicts, hasRouteHandlerExport, routeExportProblem, SPECIAL_ROUTE_FILES } from './routes'
|
|
27
28
|
import { exportStatic } from './static'
|
|
@@ -40,6 +41,7 @@ export interface BuildOptions {
|
|
|
40
41
|
publicDir?: string | undefined
|
|
41
42
|
minify?: boolean | undefined
|
|
42
43
|
assetPrefix?: string | undefined
|
|
44
|
+
site?: string | undefined
|
|
43
45
|
plugins?: KayPlugin[] | undefined
|
|
44
46
|
/** Reusable incremental cache for `kay dev` (skips re-parsing/re-compiling unchanged files). */
|
|
45
47
|
cache?: BuildCache | undefined
|
|
@@ -70,6 +72,7 @@ interface BuildRun {
|
|
|
70
72
|
staticStageDir: string | undefined
|
|
71
73
|
stageSuffix: string
|
|
72
74
|
assetPrefix: string
|
|
75
|
+
site: string | undefined
|
|
73
76
|
minify: boolean
|
|
74
77
|
isDev: boolean
|
|
75
78
|
appCtx: AppRuntimeContext
|
|
@@ -96,12 +99,14 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
96
99
|
const outDir = options.static ? join(cacheBaseDir, `.static-stage-${stageSuffix}`) : finalOutDir
|
|
97
100
|
const staticStageDir = options.static ? join(dirname(finalOutDir), `.${basename(finalOutDir)}.stage-${stageSuffix}`) : undefined
|
|
98
101
|
const assetPrefix = (options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay').replace(/\/$/, '')
|
|
102
|
+
const site = (options.site ?? fileConfig.site)?.replace(/\/$/, '') || undefined
|
|
99
103
|
const publicFiles = createPublicFiles()
|
|
100
104
|
const appCtx = createAppContext({
|
|
101
105
|
root,
|
|
102
106
|
outDir,
|
|
103
107
|
publicDir: join(outDir, 'public'),
|
|
104
108
|
assetPrefix,
|
|
109
|
+
site,
|
|
105
110
|
dev: isDev,
|
|
106
111
|
onRegisterPublicFile: publicFiles.register,
|
|
107
112
|
})
|
|
@@ -114,7 +119,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
114
119
|
return await runWithAppContext(appCtx, () => runBuild({
|
|
115
120
|
options,
|
|
116
121
|
root,
|
|
117
|
-
plugins: options.plugins ?? fileConfig.plugins
|
|
122
|
+
plugins: resolvePlugins(options.plugins ?? fileConfig.plugins),
|
|
118
123
|
routesDir,
|
|
119
124
|
publicDir,
|
|
120
125
|
finalOutDir,
|
|
@@ -122,6 +127,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
122
127
|
staticStageDir,
|
|
123
128
|
stageSuffix,
|
|
124
129
|
assetPrefix,
|
|
130
|
+
site,
|
|
125
131
|
minify: options.minify ?? true,
|
|
126
132
|
isDev,
|
|
127
133
|
appCtx,
|
|
@@ -154,14 +160,19 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
154
160
|
const allRouteFiles = walkRoutes(routesDir).sort()
|
|
155
161
|
const specialFiles = allRouteFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
|
|
156
162
|
const candidatePageFiles = allRouteFiles.filter(f => !basename(f).startsWith('_'))
|
|
163
|
+
const rootLayoutSrc = join(routesDir, '_layout.tsx')
|
|
157
164
|
const errorSrc = join(routesDir, '_error.tsx')
|
|
158
165
|
const notFoundSrc = join(routesDir, '_404.tsx')
|
|
166
|
+
const hasRootLayout = existsSync(rootLayoutSrc)
|
|
159
167
|
const hasErrorFile = existsSync(errorSrc)
|
|
160
168
|
const hasNotFoundFile = existsSync(notFoundSrc)
|
|
161
169
|
|
|
162
170
|
// Every reachable .ts/.tsx file is analyzed & validated BEFORE wiping outDir, so build errors keep the last working dist/.
|
|
171
|
+
// kay.config.ts enters the graph too, so an action or component reached only from it is analyzed and gets its URL.
|
|
172
|
+
const configSrc = join(root, 'kay.config.ts')
|
|
173
|
+
const hasConfigFile = existsSync(configSrc)
|
|
163
174
|
const graph = new ModuleGraph(options.cache)
|
|
164
|
-
for (const f of [...specialFiles, ...candidatePageFiles])
|
|
175
|
+
for (const f of [...specialFiles, ...candidatePageFiles, ...(hasConfigFile ? [configSrc] : [])])
|
|
165
176
|
graph.load(f)
|
|
166
177
|
for (const analysis of graph.analyses.values()) {
|
|
167
178
|
for (const warning of analysis.warnings)
|
|
@@ -198,27 +209,75 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
198
209
|
.flatMap(p => p.css ?? [])
|
|
199
210
|
.map(c => resolve(root, c))
|
|
200
211
|
.filter(c => existsSync(c))
|
|
201
|
-
const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, graph, cache: options.cache, plugins, actionsByFile, islands }
|
|
212
|
+
const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, analyze: options.analyze === true, graph, cache: options.cache, plugins, actionsByFile, islands }
|
|
202
213
|
|
|
203
214
|
const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
|
|
204
215
|
const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
|
|
205
|
-
|
|
206
|
-
const
|
|
216
|
+
// `_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.
|
|
217
|
+
const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles, ...(hasConfigFile ? [configSrc] : [])]
|
|
218
|
+
const serverRoot = standaloneActionFiles.length > 0 || hasConfigFile ? root : routesDir
|
|
219
|
+
const toOutRel = (srcFile: string): string =>
|
|
220
|
+
relPosix(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js')))
|
|
221
|
+
const serverEntry = {
|
|
222
|
+
file: join(serverRoot, SERVER_ENTRY_FILE),
|
|
223
|
+
source: serverEntrySource({
|
|
224
|
+
modules: [...specialFiles, ...pageFiles, ...standaloneActionFiles].map(file => ({ file, key: toOutRel(file), source: relPosix(root, file) })),
|
|
225
|
+
config: hasConfigFile ? { file: configSrc, source: relPosix(root, configSrc) } : undefined,
|
|
226
|
+
assembler: join(KAY_SRC_ROOT, 'server/app-entry.ts'),
|
|
227
|
+
}),
|
|
228
|
+
}
|
|
229
|
+
if (existsSync(serverEntry.file))
|
|
230
|
+
throw new Error(`kay build: ${relPosix(root, serverEntry.file)} is the path of kay's server entry; rename that file.`)
|
|
207
231
|
|
|
208
232
|
// The server compiles against the island chunk URLs, so islands build first; without islands both passes run in parallel.
|
|
209
233
|
const clientPass = () => buildClient(env, standaloneCssFiles(graph, pluginCssFiles, islands.cssFiles))
|
|
210
234
|
let client: Awaited<ReturnType<typeof clientPass>>
|
|
211
235
|
if (islands.targets.size === 0) {
|
|
212
|
-
const [built] = await Promise.all([clientPass(), buildServer(env, serverEntries, serverRoot, new Map())])
|
|
236
|
+
const [built] = await Promise.all([clientPass(), buildServer(env, serverEntries, serverRoot, new Map(), serverEntry)])
|
|
213
237
|
client = built
|
|
214
238
|
}
|
|
215
239
|
else {
|
|
216
240
|
client = await clientPass()
|
|
217
|
-
await buildServer(env, serverEntries, serverRoot, client.islandChunks)
|
|
241
|
+
await buildServer(env, serverEntries, serverRoot, client.islandChunks, serverEntry)
|
|
218
242
|
}
|
|
219
243
|
|
|
220
|
-
|
|
221
|
-
|
|
244
|
+
if (options.cache !== undefined) {
|
|
245
|
+
const watched = options.cache.watchedFiles
|
|
246
|
+
watched.clear()
|
|
247
|
+
const recordWatched = (file: string) => {
|
|
248
|
+
if (!existsSync(file))
|
|
249
|
+
return
|
|
250
|
+
let real = file
|
|
251
|
+
try {
|
|
252
|
+
real = realpathSync(file)
|
|
253
|
+
}
|
|
254
|
+
catch {}
|
|
255
|
+
watched.add(real)
|
|
256
|
+
}
|
|
257
|
+
for (const f of graph.analyses.keys())
|
|
258
|
+
recordWatched(f)
|
|
259
|
+
for (const f of options.cache.lastClient?.inputStamps.keys() ?? [])
|
|
260
|
+
recordWatched(f)
|
|
261
|
+
for (const f of options.cache.lastServer?.inputStamps.keys() ?? [])
|
|
262
|
+
recordWatched(f)
|
|
263
|
+
for (const f of pluginCssFiles)
|
|
264
|
+
recordWatched(f)
|
|
265
|
+
if (hasConfigFile)
|
|
266
|
+
recordWatched(configSrc)
|
|
267
|
+
// Prune deleted files from caches so long-lived dev sessions stay flat in memory.
|
|
268
|
+
for (const f of [...options.cache.analyses.keys()]) {
|
|
269
|
+
if (!existsSync(f))
|
|
270
|
+
options.cache.analyses.delete(f)
|
|
271
|
+
}
|
|
272
|
+
for (const f of [...options.cache.domCompiled.keys()]) {
|
|
273
|
+
if (!existsSync(f))
|
|
274
|
+
options.cache.domCompiled.delete(f)
|
|
275
|
+
}
|
|
276
|
+
for (const f of [...options.cache.ssrCompiled.keys()]) {
|
|
277
|
+
if (!existsSync(f))
|
|
278
|
+
options.cache.ssrCompiled.delete(f)
|
|
279
|
+
}
|
|
280
|
+
}
|
|
222
281
|
|
|
223
282
|
const assets: string[] = []
|
|
224
283
|
for (const rel of client.assetFiles) {
|
|
@@ -261,6 +320,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
261
320
|
clientDir,
|
|
262
321
|
outPublicDir,
|
|
263
322
|
assetPrefix,
|
|
323
|
+
site: run.site,
|
|
264
324
|
minify: run.minify,
|
|
265
325
|
isStatic,
|
|
266
326
|
isDev,
|
|
@@ -279,6 +339,8 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
279
339
|
globalStyles,
|
|
280
340
|
...(host.headTags.length > 0 ? { headTags: host.headTags } : {}),
|
|
281
341
|
routes,
|
|
342
|
+
|
|
343
|
+
...(hasRootLayout ? { rootLayoutFile: toOutRel(rootLayoutSrc) } : {}),
|
|
282
344
|
errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
|
|
283
345
|
notFoundFile: hasNotFoundFile ? toOutRel(notFoundSrc) : undefined,
|
|
284
346
|
actions: buildActionEntries(actionsByFile, routesDir, toOutRel),
|
|
@@ -294,7 +356,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
294
356
|
const prerenderRoutes = options.prerender !== false || isStatic ? routes.filter(r => r.prerender) : []
|
|
295
357
|
const prerenderDir = isStatic ? run.staticStageDir! : join(outDir, 'prerendered')
|
|
296
358
|
const app = prerenderRoutes.length > 0 || isStatic
|
|
297
|
-
? await prerender({ root, outDir, assetPrefix, plugins, isDev, isStatic, prerenderDir, routes: prerenderRoutes })
|
|
359
|
+
? await prerender({ root, outDir, assetPrefix, site: run.site, plugins, pluginOverride: options.plugins, isDev, isStatic, prerenderDir, routes: prerenderRoutes })
|
|
298
360
|
: undefined
|
|
299
361
|
|
|
300
362
|
try {
|
|
@@ -333,7 +395,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
333
395
|
manifest,
|
|
334
396
|
assetPrefix,
|
|
335
397
|
outfile: typeof options.compile === 'string' ? resolve(root, options.compile) : join(outDir, 'server-bin'),
|
|
336
|
-
|
|
398
|
+
|
|
337
399
|
resolveKaySpecifier,
|
|
338
400
|
bunPlugins: pluginBunPlugins(env, 'compile'),
|
|
339
401
|
})
|
package/src/build/manifest.ts
CHANGED
|
@@ -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,6 +45,9 @@ export interface BuildManifest {
|
|
|
43
45
|
globalStyles?: string[] | undefined
|
|
44
46
|
headTags?: string[] | undefined
|
|
45
47
|
routes: RouteManifestEntry[]
|
|
48
|
+
|
|
49
|
+
/** Explicit root `_layout.tsx` compiled module path (never inferred from subdirectory layouts). */
|
|
50
|
+
rootLayoutFile?: string | undefined
|
|
46
51
|
errorFile?: string | undefined
|
|
47
52
|
notFoundFile?: string | undefined
|
|
48
53
|
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
|
@@ -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,
|
|
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
|
|
@@ -30,7 +30,10 @@ export interface PrerenderOptions {
|
|
|
30
30
|
root: string
|
|
31
31
|
outDir: string
|
|
32
32
|
assetPrefix: string
|
|
33
|
+
site?: string | undefined
|
|
33
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
|
|
34
37
|
isDev: boolean
|
|
35
38
|
isStatic: boolean
|
|
36
39
|
/** Where the HTML lands: the static stage dir, or `<outDir>/prerendered`. */
|
|
@@ -41,18 +44,18 @@ export interface PrerenderOptions {
|
|
|
41
44
|
/** Renders every route to HTML, records `route.prerendered`, and returns the server the pages were rendered with. */
|
|
42
45
|
export async function prerender(options: PrerenderOptions) {
|
|
43
46
|
const { root, outDir, prerenderDir, isStatic } = options
|
|
44
|
-
|
|
45
|
-
const
|
|
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 })
|
|
46
50
|
mkdirSync(prerenderDir, { recursive: true })
|
|
47
51
|
|
|
48
|
-
const stamp = `${Date.now()}-${++prerenderImportSeq}`
|
|
49
52
|
for (const route of options.routes) {
|
|
50
53
|
let urls: string[] = []
|
|
51
54
|
if (!route.path.includes(':') && !route.path.includes('*')) {
|
|
52
55
|
urls = [route.path]
|
|
53
56
|
}
|
|
54
57
|
else {
|
|
55
|
-
const mod =
|
|
58
|
+
const mod = entry?.modules[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
|
|
56
59
|
if (typeof mod.paths === 'function') {
|
|
57
60
|
const returned: unknown = await mod.paths()
|
|
58
61
|
assertPathUrls(returned, route.file)
|
|
@@ -72,6 +75,7 @@ export async function prerender(options: PrerenderOptions) {
|
|
|
72
75
|
}
|
|
73
76
|
|
|
74
77
|
const map: Record<string, string> = {}
|
|
78
|
+
const styleHashes: Record<string, string[]> = {}
|
|
75
79
|
for (let i = 0; i < urls.length; i += CONCURRENCY) {
|
|
76
80
|
await Promise.all(urls.slice(i, i + CONCURRENCY).map(async (u) => {
|
|
77
81
|
const res = await app.handle(new Request(`http://localhost${u}`))
|
|
@@ -83,11 +87,16 @@ export async function prerender(options: PrerenderOptions) {
|
|
|
83
87
|
}
|
|
84
88
|
const absHtml = resolvePrerenderHtmlPath(prerenderDir, u, isStatic)
|
|
85
89
|
mkdirSync(dirname(absHtml), { recursive: true })
|
|
86
|
-
|
|
90
|
+
const html = await res.text()
|
|
91
|
+
writeFileSync(absHtml, html)
|
|
87
92
|
map[u] = relPosix(isStatic ? prerenderDir : outDir, absHtml)
|
|
93
|
+
const hashes = inlineStyleHashes(html)
|
|
94
|
+
if (hashes.length > 0)
|
|
95
|
+
styleHashes[u] = hashes
|
|
88
96
|
}))
|
|
89
97
|
}
|
|
90
98
|
route.prerendered = map
|
|
99
|
+
route.prerenderedStyleHashes = Object.keys(styleHashes).length > 0 ? styleHashes : undefined
|
|
91
100
|
}
|
|
92
101
|
return app
|
|
93
102
|
}
|
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))
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// The generated server entry (`dist/server/_entry.js`): the one module that assembles an app from its bundled config, routes and actions.
|
|
2
|
+
|
|
3
|
+
/** The entry's path under the server bundle root, and so under `dist/server/`. An underscore file is never a route. */
|
|
4
|
+
export const SERVER_ENTRY_FILE = '_entry.js'
|
|
5
|
+
|
|
6
|
+
export interface ServerEntryModule {
|
|
7
|
+
/** Absolute source path, bundled in the same pass as the entry. */
|
|
8
|
+
file: string
|
|
9
|
+
/** The module's manifest key (`server/index.js`). */
|
|
10
|
+
key: string
|
|
11
|
+
/** Root-relative source path, read by `testApp().import()`. */
|
|
12
|
+
source: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ServerEntryOptions {
|
|
16
|
+
modules: readonly ServerEntryModule[]
|
|
17
|
+
/** `kay.config.ts`, when the app has one. */
|
|
18
|
+
config?: { file: string, source: string } | undefined
|
|
19
|
+
/** Absolute path of kay's `server/app-entry.ts`, bundled from source like the app's own `kay/server` imports. */
|
|
20
|
+
assembler: string
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function serverEntrySource(options: ServerEntryOptions): string {
|
|
24
|
+
const lines: string[] = []
|
|
25
|
+
const { config } = options
|
|
26
|
+
if (config !== undefined)
|
|
27
|
+
lines.push(`import * as configModule from ${JSON.stringify(config.file)}`)
|
|
28
|
+
options.modules.forEach((m, i) => lines.push(`import * as m${i} from ${JSON.stringify(m.file)}`))
|
|
29
|
+
lines.push(`import { createAppFromEntry } from ${JSON.stringify(options.assembler)}`)
|
|
30
|
+
lines.push(`export const kayConfig = ${config !== undefined ? 'configModule.default ?? {}' : '{}'}`)
|
|
31
|
+
lines.push(`export const modules = {${options.modules.map((m, i) => ` ${JSON.stringify(m.key)}: m${i},`).join('')} }`)
|
|
32
|
+
const sources = options.modules.map((m, i) => ` ${JSON.stringify(m.source)}: m${i},`)
|
|
33
|
+
if (config !== undefined)
|
|
34
|
+
sources.push(` ${JSON.stringify(config.source)}: configModule,`)
|
|
35
|
+
lines.push(`export const sources = {${sources.join('')} }`)
|
|
36
|
+
lines.push('export function createApp(options) { return createAppFromEntry(kayConfig, modules, options) }')
|
|
37
|
+
return `${lines.join('\n')}\n`
|
|
38
|
+
}
|