@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/compiler/ssr.ts
CHANGED
|
@@ -150,9 +150,10 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
150
150
|
|
|
151
151
|
const islands = options.islands
|
|
152
152
|
const emitMarkers = options.emitMarkers ?? options.isIsland ?? analysis.isInteractive
|
|
153
|
+
const jsxNodes = analysis.jsxNodes
|
|
153
154
|
|
|
154
155
|
function compileSubExpression(node: Node): string {
|
|
155
|
-
if (!containsJsx(node))
|
|
156
|
+
if (!containsJsx(node, jsxNodes))
|
|
156
157
|
return code.slice(node.start, node.end)
|
|
157
158
|
|
|
158
159
|
const sub = new SourceEditor(code.slice(node.start, node.end))
|
|
@@ -223,7 +224,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
223
224
|
return { propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate }
|
|
224
225
|
}
|
|
225
226
|
|
|
226
|
-
function compileChildrenListToStringExpr(children: readonly JSXChild[]): string {
|
|
227
|
+
function compileChildrenListToStringExpr(children: readonly JSXChild[], slotMarkers = emitMarkers): string {
|
|
227
228
|
const bufVar = `_o${loopCounter++}`
|
|
228
229
|
const stmts: string[] = []
|
|
229
230
|
const parts = new StringParts()
|
|
@@ -233,7 +234,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
233
234
|
parts.clear()
|
|
234
235
|
}
|
|
235
236
|
}
|
|
236
|
-
emitChildrenIntoBuffer(children, bufVar, parts, flush, s => stmts.push(s))
|
|
237
|
+
emitChildrenIntoBuffer(children, bufVar, parts, flush, s => stmts.push(s), undefined, slotMarkers)
|
|
237
238
|
if (stmts.length === 0)
|
|
238
239
|
return parts.toExpr()
|
|
239
240
|
flush()
|
|
@@ -325,9 +326,10 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
325
326
|
flushParts: () => void,
|
|
326
327
|
pushStmt: (stmt: string) => void,
|
|
327
328
|
rawTextTag?: 'style' | 'script',
|
|
329
|
+
slotMarkers = emitMarkers,
|
|
328
330
|
): void {
|
|
329
331
|
const meaningful = filterMeaningfulChildren(children)
|
|
330
|
-
const slots = meaningful.map(c => ({ child: c, slot: classifyJsxChild(c) })).filter(s => s.slot !== undefined)
|
|
332
|
+
const slots = meaningful.map(c => ({ child: c, slot: classifyJsxChild(c, jsxNodes) })).filter(s => s.slot !== undefined)
|
|
331
333
|
const hasSiblings = slots.length > 1
|
|
332
334
|
let hadVariableRange = false
|
|
333
335
|
|
|
@@ -365,7 +367,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
365
367
|
}
|
|
366
368
|
|
|
367
369
|
if (slot.kind === 'component' || slot.kind === 'fragment') {
|
|
368
|
-
if (
|
|
370
|
+
if (slotMarkers && hasSiblings) {
|
|
369
371
|
parts.pushStatic('<!--k[-->')
|
|
370
372
|
emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
|
|
371
373
|
if (!isLast)
|
|
@@ -380,7 +382,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
380
382
|
|
|
381
383
|
if (slot.kind === 'loop') {
|
|
382
384
|
const { match } = slot
|
|
383
|
-
const needsBracket =
|
|
385
|
+
const needsBracket = slotMarkers && (!isLast || hadVariableRange)
|
|
384
386
|
if (needsBracket)
|
|
385
387
|
parts.pushStatic('<!--k[-->')
|
|
386
388
|
|
|
@@ -426,7 +428,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
426
428
|
if (slot.kind === 'and-show') {
|
|
427
429
|
const left = compileSubExpression(slot.expr.left)
|
|
428
430
|
const right = compileJsxToStringExpr(slot.right)
|
|
429
|
-
if (
|
|
431
|
+
if (slotMarkers && hasSiblings) {
|
|
430
432
|
parts.pushStatic('<!--k[-->')
|
|
431
433
|
parts.pushExpr(`((${left}) ? (${right}) : "")`)
|
|
432
434
|
parts.pushStatic('<!--k]-->')
|
|
@@ -442,7 +444,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
442
444
|
const test = compileSubExpression(slot.expr.test)
|
|
443
445
|
const cons = compileExpressionAsString(slot.cons)
|
|
444
446
|
const alt = compileExpressionAsString(slot.alt)
|
|
445
|
-
if (
|
|
447
|
+
if (slotMarkers && hasSiblings) {
|
|
446
448
|
parts.pushStatic('<!--k[-->')
|
|
447
449
|
parts.pushExpr(`((${test}) ? (${cons}) : (${alt}))`)
|
|
448
450
|
parts.pushStatic('<!--k]-->')
|
|
@@ -457,8 +459,8 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
457
459
|
// Generic expression slot
|
|
458
460
|
const exprCode = compileSubExpression(slot.expr)
|
|
459
461
|
const rendered = `${use('esc')}(${exprCode})`
|
|
460
|
-
if (isNodeCapableExpr(slot.expr)) {
|
|
461
|
-
if (
|
|
462
|
+
if (isNodeCapableExpr(slot.expr, jsxNodes)) {
|
|
463
|
+
if (slotMarkers && hasSiblings) {
|
|
462
464
|
parts.pushStatic('<!--k[-->')
|
|
463
465
|
parts.pushExpr(rendered)
|
|
464
466
|
if (!isLast)
|
|
@@ -469,7 +471,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
469
471
|
}
|
|
470
472
|
hadVariableRange = true
|
|
471
473
|
}
|
|
472
|
-
else if (
|
|
474
|
+
else if (slotMarkers && hasSiblings) {
|
|
473
475
|
parts.pushStatic('<!---->')
|
|
474
476
|
parts.pushExpr(rendered)
|
|
475
477
|
if (!isLast)
|
|
@@ -532,7 +534,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
532
534
|
}
|
|
533
535
|
|
|
534
536
|
const childrenHaveAwait = hasChildren && childNodes.some(c => containsDirectAwait(c))
|
|
535
|
-
const childExpr = hasChildren ? compileChildrenListToStringExpr(childNodes) : '""'
|
|
537
|
+
const childExpr = hasChildren ? compileChildrenListToStringExpr(childNodes, false) : '""'
|
|
536
538
|
|
|
537
539
|
const islandInfo = islands?.get(tag)
|
|
538
540
|
if (islandInfo === undefined && islands !== undefined && hydrateExpr !== undefined)
|
package/src/dev/index.ts
CHANGED
|
@@ -2,12 +2,13 @@
|
|
|
2
2
|
// SSE error push, and live config reload.
|
|
3
3
|
|
|
4
4
|
import type { FSWatcher } from 'node:fs'
|
|
5
|
+
import type { BuildCacheStats } from '../build/graph'
|
|
5
6
|
import type { KayApp } from '../server/index'
|
|
6
|
-
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, watch, writeFileSync } from 'node:fs'
|
|
7
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, watch, writeFileSync } from 'node:fs'
|
|
7
8
|
import { dirname, join, relative, resolve } from 'node:path'
|
|
8
9
|
import { clearBuildCache } from '../build/graph'
|
|
9
10
|
import { build, createBuildCache } from '../build/index'
|
|
10
|
-
import { createAppContext, loadConfig, runWithAppContext } from '../plugins/index'
|
|
11
|
+
import { createAppContext, loadConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
|
|
11
12
|
import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
|
|
12
13
|
import { createServer, withCspHashes } from '../server/index'
|
|
13
14
|
|
|
@@ -94,7 +95,8 @@ function injectReloadStream(body: ReadableStream<Uint8Array>, reloadScript: stri
|
|
|
94
95
|
}
|
|
95
96
|
|
|
96
97
|
// Bun never unloads a module, so each build's server files are copied into a generation store.
|
|
97
|
-
//
|
|
98
|
+
// Only `_entry.js` is imported, with its hash: the code lives in content-named chunks, so an unchanged chunk keeps its loaded instance across saves.
|
|
99
|
+
// A failed import starts a new generation, since Bun keeps a module that failed to evaluate.
|
|
98
100
|
function createModuleStore(storeRoot: string) {
|
|
99
101
|
const hashes = new Map<string, string>()
|
|
100
102
|
let generation = 0
|
|
@@ -104,7 +106,7 @@ function createModuleStore(storeRoot: string) {
|
|
|
104
106
|
reloadAll(): void {
|
|
105
107
|
stale = true
|
|
106
108
|
},
|
|
107
|
-
sync(serverDir: string
|
|
109
|
+
sync(serverDir: string): void {
|
|
108
110
|
const nextFiles = new Map<string, { bytes: Buffer, hash: string }>()
|
|
109
111
|
for (const entry of readdirSync(serverDir, { recursive: true, withFileTypes: true })) {
|
|
110
112
|
if (!entry.isFile())
|
|
@@ -116,17 +118,6 @@ function createModuleStore(storeRoot: string) {
|
|
|
116
118
|
nextFiles.set(rel, { bytes, hash })
|
|
117
119
|
}
|
|
118
120
|
|
|
119
|
-
// If an already-loaded standalone action file (statically imported by routes) changed, bump generation so static importers re-resolve cleanly.
|
|
120
|
-
if (!stale && hashes.size > 0) {
|
|
121
|
-
for (const [rel, { hash }] of nextFiles) {
|
|
122
|
-
const prev = hashes.get(rel)
|
|
123
|
-
if (prev !== undefined && prev !== hash && sharedRelFiles.has(rel)) {
|
|
124
|
-
stale = true
|
|
125
|
-
break
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
121
|
if (stale) {
|
|
131
122
|
stale = false
|
|
132
123
|
hashes.clear()
|
|
@@ -167,12 +158,19 @@ function createModuleStore(storeRoot: string) {
|
|
|
167
158
|
}
|
|
168
159
|
}
|
|
169
160
|
|
|
170
|
-
export async function devServer(options: DevServerOptions): Promise<{
|
|
161
|
+
export async function devServer(options: DevServerOptions): Promise<{
|
|
162
|
+
url: string
|
|
163
|
+
stop: () => void
|
|
164
|
+
rebuild: () => Promise<void>
|
|
165
|
+
stats: () => BuildCacheStats
|
|
166
|
+
}> {
|
|
171
167
|
const prevKayDev = process.env.KAY_DEV
|
|
172
168
|
process.env.KAY_DEV = '1'
|
|
173
169
|
const root = resolve(options.root)
|
|
174
170
|
const devRoot = join(root, '.kay-dev')
|
|
171
|
+
let initialConfigFailed = false
|
|
175
172
|
const initialCfg = await loadConfig(root).catch((err) => {
|
|
173
|
+
initialConfigFailed = true
|
|
176
174
|
console.warn(`[kay dev] failed to load kay.config.ts: ${err instanceof Error ? err.message : String(err)}`)
|
|
177
175
|
return {} as Awaited<ReturnType<typeof loadConfig>>
|
|
178
176
|
})
|
|
@@ -188,15 +186,71 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
|
|
|
188
186
|
const watchers: FSWatcher[] = []
|
|
189
187
|
const watchedDirs = new Set<string>()
|
|
190
188
|
const pluginWatchers: FSWatcher[] = []
|
|
189
|
+
const graphWatchers = new Map<string, FSWatcher>()
|
|
191
190
|
let activeAssetPrefix = assetPrefix
|
|
191
|
+
let pluginWatchersAttached = false
|
|
192
|
+
|
|
193
|
+
const isInsideDir = (parent: string, target: string): boolean =>
|
|
194
|
+
target === parent || target.startsWith(`${parent}/`) || target.startsWith(`${parent}\\`)
|
|
195
|
+
|
|
196
|
+
function isCoveredByStaticWatchers(dir: string): boolean {
|
|
197
|
+
if (dir === root)
|
|
198
|
+
return false
|
|
199
|
+
for (const base of watchedDirs) {
|
|
200
|
+
if (isInsideDir(base, dir))
|
|
201
|
+
return true
|
|
202
|
+
}
|
|
203
|
+
return false
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function syncBuildWatchers(watchedFiles: ReadonlySet<string>): void {
|
|
207
|
+
const nextDirs = new Set<string>()
|
|
208
|
+
let realRoot = root
|
|
209
|
+
try {
|
|
210
|
+
realRoot = realpathSync(root)
|
|
211
|
+
}
|
|
212
|
+
catch {}
|
|
213
|
+
for (const file of watchedFiles) {
|
|
214
|
+
if (file.includes('/node_modules/') || file.includes('\\node_modules\\'))
|
|
215
|
+
continue
|
|
216
|
+
if (isInsideDir(devRoot, file) || isInsideDir(join(root, '.kay-cache'), file))
|
|
217
|
+
continue
|
|
218
|
+
const dir = dirname(file)
|
|
219
|
+
// Root is already watched non-recursively for `kay.config.ts`; skip if it's only kay.config.ts itself.
|
|
220
|
+
if (dir === root || dir === realRoot) {
|
|
221
|
+
if (file === join(root, 'kay.config.ts') || file === join(realRoot, 'kay.config.ts'))
|
|
222
|
+
continue
|
|
223
|
+
}
|
|
224
|
+
if (isCoveredByStaticWatchers(dir))
|
|
225
|
+
continue
|
|
226
|
+
nextDirs.add(dir)
|
|
227
|
+
}
|
|
228
|
+
for (const [dir, watcher] of graphWatchers) {
|
|
229
|
+
if (!nextDirs.has(dir)) {
|
|
230
|
+
watcher.close()
|
|
231
|
+
graphWatchers.delete(dir)
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
for (const dir of nextDirs) {
|
|
235
|
+
if (graphWatchers.has(dir) || !existsSync(dir))
|
|
236
|
+
continue
|
|
237
|
+
try {
|
|
238
|
+
graphWatchers.set(dir, watch(dir, (_ev, filename) => {
|
|
239
|
+
const name = typeof filename === 'string' ? filename : ''
|
|
240
|
+
scheduleRebuild(srcChangeKind(name))
|
|
241
|
+
}))
|
|
242
|
+
}
|
|
243
|
+
catch {}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
192
246
|
|
|
193
247
|
function refreshPluginWatchers(cfg: Awaited<ReturnType<typeof loadConfig>>): void {
|
|
194
248
|
for (const w of pluginWatchers)
|
|
195
249
|
w.close()
|
|
196
250
|
pluginWatchers.length = 0
|
|
197
251
|
const seen = new Set<string>(watchedDirs)
|
|
198
|
-
const watchCtx = createAppContext({ root, outDir: devRoot, publicDir, assetPrefix: activeAssetPrefix, dev: true })
|
|
199
|
-
for (const plugin of cfg.plugins
|
|
252
|
+
const watchCtx = createAppContext({ root, outDir: devRoot, publicDir, assetPrefix: activeAssetPrefix, site: cfg.site, dev: true })
|
|
253
|
+
for (const plugin of resolvePlugins(cfg.plugins)) {
|
|
200
254
|
const paths = runWithAppContext(watchCtx, () =>
|
|
201
255
|
typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : (plugin.watchPaths ?? []))
|
|
202
256
|
for (const p of paths) {
|
|
@@ -272,14 +326,7 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
|
|
|
272
326
|
return
|
|
273
327
|
}
|
|
274
328
|
const serverDir = join(root, outDir, 'server')
|
|
275
|
-
|
|
276
|
-
const sharedRelFiles = new Set<string>()
|
|
277
|
-
for (const a of manifest.actions) {
|
|
278
|
-
const rel = a.file.replace(/^server\//, '')
|
|
279
|
-
if (!routeFiles.has(rel))
|
|
280
|
-
sharedRelFiles.add(rel)
|
|
281
|
-
}
|
|
282
|
-
modules.sync(serverDir, sharedRelFiles)
|
|
329
|
+
modules.sync(serverDir)
|
|
283
330
|
const nextApp = await createServer({
|
|
284
331
|
root,
|
|
285
332
|
outDir,
|
|
@@ -294,8 +341,21 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
|
|
|
294
341
|
}
|
|
295
342
|
const prevApp = currentApp
|
|
296
343
|
currentApp = nextApp
|
|
297
|
-
|
|
344
|
+
await prevApp?.dispose?.()
|
|
298
345
|
lastError = undefined
|
|
346
|
+
syncBuildWatchers(buildCache.watchedFiles)
|
|
347
|
+
if (!pluginWatchersAttached && !initialConfigFailed) {
|
|
348
|
+
pluginWatchersAttached = true
|
|
349
|
+
}
|
|
350
|
+
else if (initialConfigFailed) {
|
|
351
|
+
initialConfigFailed = false
|
|
352
|
+
try {
|
|
353
|
+
const recoveredCfg = await loadConfig(root)
|
|
354
|
+
refreshPluginWatchers(recoveredCfg)
|
|
355
|
+
pluginWatchersAttached = true
|
|
356
|
+
}
|
|
357
|
+
catch {}
|
|
358
|
+
}
|
|
299
359
|
if (n > 2)
|
|
300
360
|
rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
|
|
301
361
|
console.log(`[kay dev] rebuilt in ${(performance.now() - t0).toFixed(1)} ms`)
|
|
@@ -397,7 +457,8 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
|
|
|
397
457
|
const pingChunk = encoder.encode(': ping\n\n')
|
|
398
458
|
const pingInterval = setInterval(() => pushToClients(pingChunk), 15_000)
|
|
399
459
|
|
|
400
|
-
const
|
|
460
|
+
const runtimeCfg = resolveServerConfig(initialCfg, { maxRequestBodySize: options.maxRequestBodySize })
|
|
461
|
+
const maxRequestBodySize = runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
|
|
401
462
|
|
|
402
463
|
const server = Bun.serve({
|
|
403
464
|
port,
|
|
@@ -449,7 +510,7 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
|
|
|
449
510
|
const ct = res.headers.get('content-type') ?? ''
|
|
450
511
|
if (ct.includes('text/event-stream'))
|
|
451
512
|
srv.timeout(request, 0)
|
|
452
|
-
if (ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null) {
|
|
513
|
+
if (ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-encoding')) {
|
|
453
514
|
const headers = new Headers(res.headers)
|
|
454
515
|
headers.delete('content-length')
|
|
455
516
|
const existingCsp = headers.get('content-security-policy')
|
|
@@ -471,6 +532,9 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
|
|
|
471
532
|
pendingCssOnly = false
|
|
472
533
|
return drainRebuilds()
|
|
473
534
|
},
|
|
535
|
+
stats() {
|
|
536
|
+
return { ...buildCache.stats }
|
|
537
|
+
},
|
|
474
538
|
stop() {
|
|
475
539
|
stopped = true
|
|
476
540
|
clearTimeout(timer)
|
|
@@ -479,6 +543,9 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
|
|
|
479
543
|
w.close()
|
|
480
544
|
for (const w of pluginWatchers)
|
|
481
545
|
w.close()
|
|
546
|
+
for (const w of graphWatchers.values())
|
|
547
|
+
w.close()
|
|
548
|
+
graphWatchers.clear()
|
|
482
549
|
server.stop(true)
|
|
483
550
|
void currentApp?.dispose?.()
|
|
484
551
|
rmSync(devRoot, { recursive: true, force: true })
|
package/src/dom/action.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// Tiny client-side action stub (~300 B gzip, 0 B when no island imports an action).
|
|
2
2
|
|
|
3
|
-
import type {
|
|
3
|
+
import type { ReadonlySignal } from '../reactivity/index'
|
|
4
|
+
import type { ActionResult, ServerAction } from '../server/action'
|
|
5
|
+
import { signal } from '../reactivity/index'
|
|
4
6
|
|
|
5
7
|
export interface ClientAction<Input, Output> {
|
|
6
8
|
/** A FormData input is sent as multipart, so it can carry files. */
|
|
@@ -9,6 +11,94 @@ export interface ClientAction<Input, Output> {
|
|
|
9
11
|
toString(): string
|
|
10
12
|
}
|
|
11
13
|
|
|
14
|
+
export interface UseActionOptions<Output> {
|
|
15
|
+
/** Reset the submitted `<form>` element after a successful submission (default: false). */
|
|
16
|
+
reset?: boolean | undefined
|
|
17
|
+
/** Called with the typed action `data` when the action succeeds (`res.ok === true`). */
|
|
18
|
+
onSuccess?: ((data: Output, form?: HTMLFormElement) => void | Promise<void>) | undefined
|
|
19
|
+
/** Called when the action fails (`res.ok === false`). */
|
|
20
|
+
onError?: ((result: Extract<ActionResult<Output>, { ok: false }>) => void) | undefined
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ActionForm<Input, Output> {
|
|
24
|
+
readonly pending: ReadonlySignal<boolean>
|
|
25
|
+
readonly error: ReadonlySignal<string>
|
|
26
|
+
readonly fieldErrors: ReadonlySignal<Record<string, string>>
|
|
27
|
+
readonly data: ReadonlySignal<Output | undefined>
|
|
28
|
+
/** Action URL for progressive `<form action={form.action} method="post">` (or pass the action directly). */
|
|
29
|
+
readonly action: string
|
|
30
|
+
/** Progressive `<form onSubmit={form.onSubmit}>` handler that submits `FormData` via fetch when JS is loaded. */
|
|
31
|
+
readonly onSubmit: (event: SubmitEvent & { currentTarget: HTMLFormElement }) => Promise<ActionResult<Output> | undefined>
|
|
32
|
+
/** Imperatively submit typed input or `FormData` while tracking `pending`, `error`, `fieldErrors`, and `data`. */
|
|
33
|
+
submit(input: Input | FormData, form?: HTMLFormElement): Promise<ActionResult<Output> | undefined>
|
|
34
|
+
/** Clears `error`, `fieldErrors`, and `data`. */
|
|
35
|
+
reset(): void
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Reactive progressive-enhancement form controller for a Kay server `action()`. */
|
|
39
|
+
export function useAction<Input, Output>(
|
|
40
|
+
action: ClientAction<Input, Output> | ServerAction<Input, Output>,
|
|
41
|
+
options: UseActionOptions<Output> = {},
|
|
42
|
+
): ActionForm<Input, Output> {
|
|
43
|
+
const pending = signal(false)
|
|
44
|
+
const error = signal('')
|
|
45
|
+
const fieldErrors = signal<Record<string, string>>({})
|
|
46
|
+
const data = signal<Output | undefined>(undefined)
|
|
47
|
+
|
|
48
|
+
const submit = async (input: Input | FormData, formEl?: HTMLFormElement): Promise<ActionResult<Output> | undefined> => {
|
|
49
|
+
if (pending.peek())
|
|
50
|
+
return undefined
|
|
51
|
+
pending.value = true
|
|
52
|
+
error.value = ''
|
|
53
|
+
fieldErrors.value = {}
|
|
54
|
+
try {
|
|
55
|
+
const res = await (action as ClientAction<Input, Output>)(input)
|
|
56
|
+
if (!res.ok) {
|
|
57
|
+
fieldErrors.value = res.fieldErrors ?? {}
|
|
58
|
+
error.value = res.error
|
|
59
|
+
options.onError?.(res)
|
|
60
|
+
return res
|
|
61
|
+
}
|
|
62
|
+
data.value = res.data
|
|
63
|
+
if (options.reset && formEl)
|
|
64
|
+
formEl.reset()
|
|
65
|
+
await options.onSuccess?.(res.data, formEl)
|
|
66
|
+
return res
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
const msg = err instanceof Error ? err.message : String(err)
|
|
70
|
+
error.value = msg
|
|
71
|
+
const failed: Extract<ActionResult<Output>, { ok: false }> = { ok: false, status: 0, error: msg }
|
|
72
|
+
options.onError?.(failed)
|
|
73
|
+
return failed
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
pending.value = false
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return {
|
|
81
|
+
pending,
|
|
82
|
+
error,
|
|
83
|
+
fieldErrors,
|
|
84
|
+
data,
|
|
85
|
+
get action() {
|
|
86
|
+
return action.url || String(action)
|
|
87
|
+
},
|
|
88
|
+
onSubmit(event) {
|
|
89
|
+
event.preventDefault()
|
|
90
|
+
const formEl = event.currentTarget
|
|
91
|
+
return submit(new FormData(formEl), formEl)
|
|
92
|
+
},
|
|
93
|
+
submit,
|
|
94
|
+
reset() {
|
|
95
|
+
error.value = ''
|
|
96
|
+
fieldErrors.value = {}
|
|
97
|
+
data.value = undefined
|
|
98
|
+
},
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
12
102
|
export function actionStub<Input = unknown, Output = unknown>(url: string): ClientAction<Input, Output> {
|
|
13
103
|
const call = (async (input: Input | FormData): Promise<ActionResult<Output>> => {
|
|
14
104
|
const isForm = typeof FormData !== 'undefined' && input instanceof FormData
|
package/src/dom/index.ts
CHANGED
|
@@ -341,7 +341,7 @@ export function setStyle(el: HTMLElement, value: unknown): void {
|
|
|
341
341
|
|
|
342
342
|
// ---- Delegated events
|
|
343
343
|
|
|
344
|
-
const delegated = new Set<string
|
|
344
|
+
const delegated = new WeakMap<Document, Set<string>>()
|
|
345
345
|
|
|
346
346
|
function dispatchEvent(event: Event): void {
|
|
347
347
|
const key = `$$${event.type}`
|
|
@@ -364,10 +364,15 @@ function dispatchEvent(event: Event): void {
|
|
|
364
364
|
export function delegate(events: string[]): void {
|
|
365
365
|
if (typeof document === 'undefined')
|
|
366
366
|
return
|
|
367
|
+
let set = delegated.get(document)
|
|
368
|
+
if (set === undefined) {
|
|
369
|
+
set = new Set()
|
|
370
|
+
delegated.set(document, set)
|
|
371
|
+
}
|
|
367
372
|
for (let i = 0; i < events.length; i++) {
|
|
368
373
|
const type = events[i]!
|
|
369
|
-
if (!
|
|
370
|
-
|
|
374
|
+
if (!set.has(type)) {
|
|
375
|
+
set.add(type)
|
|
371
376
|
document.addEventListener(type, dispatchEvent)
|
|
372
377
|
}
|
|
373
378
|
}
|
package/src/index.ts
CHANGED
|
@@ -15,7 +15,10 @@ export type { Owner, ReadonlySignal, Signal } from './reactivity/index'
|
|
|
15
15
|
export { selector } from './reactivity/selector'
|
|
16
16
|
export type { Selector } from './reactivity/selector'
|
|
17
17
|
export { snapshot, store } from './reactivity/store'
|
|
18
|
+
export { useAction } from './dom/action'
|
|
19
|
+
export type { ActionForm, ClientAction, UseActionOptions } from './dom/action'
|
|
18
20
|
export type { Component, Html, HydrateStrategy, KayChild } from './jsx-runtime'
|
|
21
|
+
export type { ExtractRouteParams, KayLocals, LayoutProps, LoaderData, LoaderFn, NotFoundResult, PageProps, RouteContext } from './server/index'
|
|
19
22
|
|
|
20
23
|
import type { Component, HydrateStrategy } from './jsx-runtime'
|
|
21
24
|
|