@kayjs/kay 2.0.0-beta.0 → 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.
Files changed (69) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +617 -0
  4. package/src/build/compile.ts +27 -51
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +272 -1466
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +229 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +102 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/server-entry.ts +38 -0
  16. package/src/build/static.ts +73 -0
  17. package/src/cli/check.ts +300 -129
  18. package/src/cli/index.ts +297 -94
  19. package/src/cli/new.ts +58 -38
  20. package/src/compiler/analyze.ts +723 -93
  21. package/src/compiler/dom.ts +848 -762
  22. package/src/compiler/mistakes.ts +354 -0
  23. package/src/compiler/patch.ts +1 -1
  24. package/src/compiler/server-only.ts +172 -23
  25. package/src/compiler/shared.ts +485 -0
  26. package/src/compiler/ssr.ts +331 -342
  27. package/src/context.ts +120 -0
  28. package/src/dev/index.ts +339 -76
  29. package/src/dom/action.ts +114 -14
  30. package/src/dom/extras.ts +121 -83
  31. package/src/dom/index.ts +122 -80
  32. package/src/dom/island.ts +71 -36
  33. package/src/dom/loop.ts +28 -20
  34. package/src/index.ts +5 -1
  35. package/src/jsx-runtime.ts +432 -93
  36. package/src/plugins/config.ts +49 -0
  37. package/src/plugins/context.ts +61 -0
  38. package/src/plugins/index.ts +10 -123
  39. package/src/plugins/load.ts +38 -0
  40. package/src/plugins/order.ts +107 -0
  41. package/src/plugins/services.ts +23 -0
  42. package/src/plugins/types.ts +197 -0
  43. package/src/reactivity/index.ts +237 -213
  44. package/src/reactivity/selector.ts +11 -9
  45. package/src/reactivity/store.ts +36 -11
  46. package/src/server/action-registry.ts +72 -0
  47. package/src/server/action.ts +157 -79
  48. package/src/server/app-entry.ts +23 -0
  49. package/src/server/assets.ts +182 -0
  50. package/src/server/compress.ts +197 -104
  51. package/src/server/cookies.ts +46 -16
  52. package/src/server/document.ts +192 -0
  53. package/src/server/env.ts +18 -13
  54. package/src/server/errors.ts +123 -0
  55. package/src/server/http.ts +203 -77
  56. package/src/server/index.ts +420 -973
  57. package/src/server/loader.ts +113 -0
  58. package/src/server/page.ts +107 -0
  59. package/src/server/plugin-host.ts +167 -0
  60. package/src/server/router.ts +69 -26
  61. package/src/server/security.ts +90 -59
  62. package/src/server/standard-schema.ts +42 -11
  63. package/src/server/static-dir.ts +163 -0
  64. package/src/server/stream.ts +94 -0
  65. package/src/ssr/context.ts +95 -10
  66. package/src/ssr/index.ts +167 -66
  67. package/src/style.ts +33 -0
  68. package/src/test/index.ts +24 -18
  69. package/src/unrenderable.ts +35 -0
@@ -1,7 +1,7 @@
1
1
  // O(1) row selection primitive: zero WeakSet overhead per row.
2
2
 
3
3
  import type { Owner, Signal } from './index'
4
- import { effect, getOwner, onCleanup, signal } from './index'
4
+ import { effect, getOwner, isTracking, onCleanup, signal } from './index'
5
5
 
6
6
  export interface Selector<K> {
7
7
  is(key: K): boolean
@@ -9,8 +9,7 @@ export interface Selector<K> {
9
9
 
10
10
  interface Entry {
11
11
  s: Signal<boolean>
12
- o: Owner | undefined
13
- r: number
12
+ owners: Set<Owner>
14
13
  }
15
14
 
16
15
  export function selector<K>(source: () => K): Selector<K> {
@@ -34,19 +33,22 @@ export function selector<K>(source: () => K): Selector<K> {
34
33
 
35
34
  return {
36
35
  is(key: K): boolean {
36
+ const owner = getOwner()
37
+ if (owner === undefined && !isTracking())
38
+ return Object.is(current, key)
39
+
37
40
  let entry = subs.get(key)
38
41
  if (entry === undefined) {
39
- entry = { s: signal(Object.is(current, key)), o: undefined, r: 0 }
42
+ entry = { s: signal(Object.is(current, key)), owners: new Set() }
40
43
  subs.set(key, entry)
41
44
  }
42
45
 
43
- const owner = getOwner()
44
- if (owner !== undefined && entry.o !== owner) {
45
- entry.o = owner
46
- entry.r++
46
+ if (owner !== undefined && !entry.owners.has(owner)) {
47
+ entry.owners.add(owner)
47
48
  const target = entry
48
49
  onCleanup(() => {
49
- if (--target.r === 0)
50
+ target.owners.delete(owner)
51
+ if (target.owners.size === 0)
50
52
  subs.delete(key)
51
53
  })
52
54
  }
@@ -1,11 +1,21 @@
1
1
  // Deep reactive proxy store (tree-shakable: 0 B if unused).
2
2
 
3
3
  import type { Signal } from './index'
4
- import { signal, untrack } from './index'
4
+ import { batch, isTracking, signal, untrack } from './index'
5
5
 
6
6
  const RAW = Symbol('kay.store.raw')
7
7
  const OWN_KEYS = Symbol('kay.store.keys')
8
8
 
9
+ // An array method that moves several entries writes each one in turn; batched, its readers see only the finished array.
10
+ const batchedMutators = new Map<PropertyKey, (this: unknown[], ...args: unknown[]) => unknown>(
11
+ (['copyWithin', 'fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'] as const).map((name) => {
12
+ const method = Array.prototype[name] as (...args: unknown[]) => unknown
13
+ return [name, function (this: unknown[], ...args: unknown[]) {
14
+ return batch(() => method.apply(this, args))
15
+ }]
16
+ }),
17
+ )
18
+
9
19
  const proxyCache = new WeakMap<object, object>()
10
20
  const depsCache = new WeakMap<object, Map<PropertyKey, Signal<number>>>()
11
21
 
@@ -18,6 +28,11 @@ function isPlain(value: unknown): value is Record<PropertyKey, unknown> {
18
28
  return proto === Object.prototype || proto === null
19
29
  }
20
30
 
31
+ // The target behind a store proxy, or the value itself.
32
+ function unwrap<T>(value: T): T {
33
+ return typeof value === 'object' && value !== null && RAW in value ? (value as Record<symbol, T>)[RAW]! : value
34
+ }
35
+
21
36
  function getDep(target: object, key: PropertyKey): Signal<number> {
22
37
  let map = depsCache.get(target)
23
38
  if (map === undefined) {
@@ -47,16 +62,22 @@ function wrap<T extends object>(target: T): T {
47
62
  get(obj, key, receiver) {
48
63
  if (key === RAW)
49
64
  return obj
50
- getDep(obj, key).value
65
+ const mutator = Array.isArray(obj) ? batchedMutators.get(key) : undefined
66
+ if (mutator !== undefined)
67
+ return mutator
68
+ if (isTracking()) {
69
+ getDep(obj, key).value
70
+ // A reader of an array's length is walking it (a list loop reads entries untracked), so any entry write reaches it.
71
+ if (key === 'length' && Array.isArray(obj))
72
+ getDep(obj, OWN_KEYS).value
73
+ }
51
74
  const value = Reflect.get(obj, key, receiver)
52
75
  return isPlain(value) ? wrap(value) : value
53
76
  },
54
77
  set(obj, key, value, receiver) {
55
- const rawValue = typeof value === 'object' && value !== null && RAW in value
56
- ? (value as Record<symbol, unknown>)[RAW]
57
- : value
78
+ const rawValue = unwrap(value)
58
79
  const had = Object.prototype.hasOwnProperty.call(obj, key)
59
- const prev = Reflect.get(obj, key, receiver)
80
+ const prev = Reflect.get(obj, key, obj)
60
81
  const prevLength = Array.isArray(obj) ? obj.length : 0
61
82
  const ok = Reflect.set(obj, key, rawValue, receiver)
62
83
  if (!had || !Object.is(prev, rawValue)) {
@@ -79,11 +100,15 @@ function wrap<T extends object>(target: T): T {
79
100
  return ok
80
101
  },
81
102
  has(obj, key) {
82
- getDep(obj, key).value
103
+ if (key === RAW)
104
+ return true
105
+ if (isTracking())
106
+ getDep(obj, key).value
83
107
  return Reflect.has(obj, key)
84
108
  },
85
109
  ownKeys(obj) {
86
- getDep(obj, OWN_KEYS).value
110
+ if (isTracking())
111
+ getDep(obj, OWN_KEYS).value
87
112
  return Reflect.ownKeys(obj)
88
113
  },
89
114
  })
@@ -103,9 +128,9 @@ export function snapshot<T>(value: T): T {
103
128
  }
104
129
 
105
130
  function cloneRaw<T>(value: T): T {
106
- if (typeof value !== 'object' || value === null)
107
- return value
108
- const raw = RAW in value ? (value as Record<symbol, unknown>)[RAW] : value
131
+ const raw = unwrap(value)
132
+ if (typeof raw !== 'object' || raw === null)
133
+ return raw
109
134
  if (Array.isArray(raw))
110
135
  return raw.map(item => cloneRaw(item)) as unknown as T
111
136
  if (isPlain(raw)) {
@@ -0,0 +1,72 @@
1
+ // The app's server actions: their live URLs, the middleware each one runs behind, and invocation with its folder's `_middleware.ts` chain.
2
+
3
+ import type { ActionResult, ServerAction } from './action'
4
+ import type { Middleware, RequestContext } from './http'
5
+ import { invokeActionCore } from './action'
6
+ import { runChain } from './http'
7
+
8
+ export interface RegisteredAction {
9
+ act: ServerAction<unknown, unknown>
10
+ /** Plugin middlewares, then the `_middleware.ts` chain of the action's folder. */
11
+ middlewares: Middleware[]
12
+ }
13
+
14
+ export interface ActionRegistry {
15
+ /** Gives `act` its live URL and records the middlewares a request to it runs behind. */
16
+ register: (act: ServerAction<unknown, unknown>, url: string, dirMiddlewares: Middleware[], pluginMiddlewares: readonly Middleware[]) => void
17
+ byUrl: (url: string) => RegisteredAction | undefined
18
+ /** Runs an action with schema validation behind its folder's `_middleware.ts` chain, as an island call would. */
19
+ invoke: <I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext) => Promise<ActionResult<O>>
20
+ }
21
+
22
+ export function createActionRegistry(): ActionRegistry {
23
+ const handlers = new Map<string, RegisteredAction>()
24
+ const dirMiddlewaresByRef = new WeakMap<ServerAction<unknown, unknown>, Middleware[]>()
25
+
26
+ async function invoke<I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>> {
27
+ const dirMiddlewares = dirMiddlewaresByRef.get(act as unknown as ServerAction<unknown, unknown>) ?? []
28
+ if (dirMiddlewares.length === 0)
29
+ return invokeActionCore(act, input, ctx)
30
+
31
+ let actionResult: ActionResult<O> | undefined
32
+ const res = await runChain(ctx, dirMiddlewares, async () => {
33
+ actionResult = await invokeActionCore(act, input, ctx)
34
+ return new Response(null, { status: actionResult.ok ? 200 : actionResult.status })
35
+ })
36
+ if (actionResult !== undefined)
37
+ return actionResult
38
+ // A directory `_middleware.ts` short-circuited the request (e.g. 401/403 auth guard).
39
+ const ct = res.headers.get('content-type') ?? ''
40
+ if (ct.includes('application/json')) {
41
+ try {
42
+ const body = await res.clone().json() as Record<string, unknown>
43
+ return {
44
+ ok: false,
45
+ status: res.status,
46
+ error: typeof body.error === 'string' ? body.error : res.statusText || 'Forbidden',
47
+ }
48
+ }
49
+ catch {}
50
+ }
51
+ let text = ''
52
+ try {
53
+ text = await res.clone().text()
54
+ }
55
+ catch {}
56
+ return {
57
+ ok: false,
58
+ status: res.status,
59
+ error: text || res.statusText || 'Forbidden',
60
+ }
61
+ }
62
+
63
+ return {
64
+ register(act, url, dirMiddlewares, pluginMiddlewares) {
65
+ ;(act as { url: string }).url = url
66
+ dirMiddlewaresByRef.set(act, dirMiddlewares)
67
+ handlers.set(url, { act, middlewares: [...pluginMiddlewares, ...dirMiddlewares] })
68
+ },
69
+ byUrl: url => handlers.get(url),
70
+ invoke,
71
+ }
72
+ }
@@ -1,11 +1,19 @@
1
1
  // Unified server actions: works as both progressive <form action={fn} method="post"> and typed island RPC.
2
2
 
3
3
  import type { Cookies } from './cookies'
4
- import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } from './standard-schema'
5
- import { DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit } from './http'
6
- import { isTrustedOrigin, verifyOrigin } from './security'
4
+ import type { KayLocals } from './index'
5
+ import type { TrustProxy } from './security'
6
+ import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
7
+ import { wantsJson } from './http'
8
+ import { isTrustedOrigin } from './security'
7
9
  import { validateSchema } from './standard-schema'
8
10
 
11
+ declare module './index' {
12
+ interface KayLocals {
13
+ actionError?: ActionErrorFlash | undefined
14
+ }
15
+ }
16
+
9
17
  export const ACTION_ERROR_COOKIE = '__kay_action_err'
10
18
 
11
19
  const MAX_FLASH_COOKIE_BYTES = 3500
@@ -24,16 +32,15 @@ export interface ActionErrorFlash {
24
32
  values?: Record<string, string> | undefined
25
33
  }
26
34
 
27
- export function getActionError(locals?: Record<string, unknown>): ActionErrorFlash | undefined {
28
- return locals?.actionError as ActionErrorFlash | undefined
35
+ export function getActionError(locals?: KayLocals): ActionErrorFlash | undefined {
36
+ return locals?.actionError
29
37
  }
30
38
 
31
39
  export interface ActionContext {
32
40
  request: Request
33
41
  url: URL
34
- params: Record<string, string>
35
42
  cookies: Cookies
36
- locals: Record<string, unknown>
43
+ locals: KayLocals
37
44
  ip?: string | undefined
38
45
  redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response
39
46
  deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
@@ -104,40 +111,92 @@ export function isServerAction(value: unknown): value is ServerAction<unknown, u
104
111
  return typeof value === 'function' && (value as { __kayAction?: boolean }).__kayAction === true
105
112
  }
106
113
 
107
- class PayloadTooLargeError extends Error {
108
- constructor() {
109
- super('Payload Too Large')
110
- }
111
- }
112
-
113
- async function parseActionBody(request: Request, maxRequestBodySize: number): Promise<unknown> {
114
- const checked = await enforceRequestBodyLimit(request, maxRequestBodySize)
115
- if (!checked.ok)
116
- throw new PayloadTooLargeError()
117
- const boundedReq = checked.request
118
-
114
+ async function parseActionBody(boundedReq: Request): Promise<unknown> {
119
115
  const contentType = boundedReq.headers.get('content-type') ?? ''
120
116
  if (contentType.includes('application/json'))
121
117
  return boundedReq.json()
122
118
 
123
119
  if (contentType.includes('multipart/form-data') || contentType.includes('application/x-www-form-urlencoded')) {
124
- const fd = await boundedReq.formData()
125
- const out: Record<string, unknown> = {}
126
- for (const [key, val] of fd.entries()) {
127
- if (key in out) {
128
- const prev = out[key]
129
- out[key] = Array.isArray(prev) ? [...prev, val] : [prev, val]
120
+ // A Map then fromEntries makes every name an own property, `constructor` and `__proto__` included.
121
+ const fields = new Map<string, FormDataEntryValue | FormDataEntryValue[]>()
122
+ for (const [key, val] of (await boundedReq.formData()).entries()) {
123
+ const prev = fields.get(key)
124
+ if (prev === undefined) {
125
+ fields.set(key, val)
126
+ }
127
+ else if (Array.isArray(prev)) {
128
+ prev.push(val)
130
129
  }
131
130
  else {
132
- out[key] = val
131
+ fields.set(key, [prev, val])
133
132
  }
134
133
  }
135
- return out
134
+ return Object.fromEntries(fields)
136
135
  }
137
136
 
138
137
  return undefined
139
138
  }
140
139
 
140
+ function isJsonBody(request: Request): boolean {
141
+ return (request.headers.get('content-type') ?? '').includes('application/json')
142
+ }
143
+
144
+ // The page a form came from, when its origin is one this server trusts: where a no-JS submit goes back to.
145
+ function trustedReferer(request: Request, trustedOrigins: ReadonlySet<string> | undefined, trustProxy: TrustProxy, requestUrl?: URL): URL | undefined {
146
+ const referer = request.headers.get('referer')
147
+ if (!referer)
148
+ return undefined
149
+ let refUrl: URL
150
+ try {
151
+ refUrl = new URL(referer)
152
+ }
153
+ catch {
154
+ return undefined
155
+ }
156
+ return isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy, requestUrl) ? refUrl : undefined
157
+ }
158
+
159
+ function topLevelKey(issue: StandardSchemaIssue): string | undefined {
160
+ const seg = issue.path?.length === 1 ? issue.path[0] : undefined
161
+ const key = typeof seg === 'object' && seg !== null ? seg.key : seg
162
+ return typeof key === 'string' ? key : undefined
163
+ }
164
+
165
+ function setField(target: Record<string, unknown>, key: string, value: unknown): void {
166
+ Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })
167
+ }
168
+
169
+ // A form sends one checked box as a single value and none as nothing, so a field the schema wants as an array fails. Each failing top-level field is retried as an array, and the array is kept only where it clears that field's issue.
170
+ async function retryWithFormArrays(schema: StandardSchemaV1, body: Record<string, unknown>, failed: ValidationFailure): Promise<ValidationResult<unknown>> {
171
+ const retried = { ...body }
172
+ const wrapped: string[] = []
173
+ for (const issue of failed.issues) {
174
+ const key = topLevelKey(issue)
175
+ if (key === undefined || Array.isArray(retried[key]) || wrapped.includes(key))
176
+ continue
177
+ setField(retried, key, Object.hasOwn(body, key) ? [body[key]] : [])
178
+ wrapped.push(key)
179
+ }
180
+ if (wrapped.length === 0)
181
+ return failed
182
+ const second = await validateSchema(schema, retried)
183
+ if (second.ok)
184
+ return second
185
+ const stillFailing = new Set(second.issues.map(topLevelKey))
186
+ const kept = wrapped.filter(key => !stillFailing.has(key))
187
+ if (kept.length === 0)
188
+ return failed
189
+ for (const key of wrapped) {
190
+ if (kept.includes(key))
191
+ continue
192
+ if (Object.hasOwn(body, key))
193
+ setField(retried, key, body[key])
194
+ else
195
+ delete retried[key]
196
+ }
197
+ return kept.length === wrapped.length ? second : validateSchema(schema, retried)
198
+ }
199
+
141
200
  function encodedFlashSize(flash: ActionErrorFlash): number {
142
201
  return Buffer.byteLength(encodeURIComponent(JSON.stringify(flash)), 'utf8')
143
202
  }
@@ -178,8 +237,10 @@ function buildActionErrorFlash(
178
237
  }
179
238
  values[k] = v
180
239
  const candidate: ActionErrorFlash = { ...base, values }
181
- if (encodedFlashSize(candidate) > MAX_FLASH_COOKIE_BYTES)
240
+ if (encodedFlashSize(candidate) > MAX_FLASH_COOKIE_BYTES) {
182
241
  delete values[k]
242
+ break
243
+ }
183
244
  }
184
245
  }
185
246
 
@@ -190,60 +251,88 @@ function buildActionErrorFlash(
190
251
  return JSON.stringify(finalFlash)
191
252
  }
192
253
 
254
+ /** Programmatic action invocation with Standard Schema validation (used by `ServerPluginAPI.invokeAction` inside middleware chains). */
255
+ export async function invokeActionCore<I, O>(
256
+ act: ServerAction<I, O>,
257
+ input: I,
258
+ ctx: ActionContext,
259
+ ): Promise<ActionResult<O>> {
260
+ let validated: unknown = input
261
+ if (act.schema !== undefined) {
262
+ const checked = await validateSchema(act.schema, input)
263
+ if (!checked.ok) {
264
+ return {
265
+ ok: false,
266
+ status: 400,
267
+ error: 'Validation failed',
268
+ fieldErrors: checked.fieldErrors,
269
+ issues: checked.issues,
270
+ }
271
+ }
272
+ validated = checked.value
273
+ }
274
+
275
+ const result = await act.handler(validated as never, ctx)
276
+ if (result instanceof Response) {
277
+ if (result.status >= 300 && result.status < 400)
278
+ return { ok: true, data: result as unknown as O }
279
+ const ok = result.status >= 200 && result.status < 300
280
+ const ct = result.headers.get('content-type') ?? ''
281
+ if (ct.includes('application/json')) {
282
+ try {
283
+ const body = await result.clone().json() as Record<string, unknown>
284
+ if (typeof body === 'object' && body !== null && 'ok' in body)
285
+ return body as unknown as ActionResult<O>
286
+ return ok
287
+ ? { ok: true, data: body as O }
288
+ : {
289
+ ok: false,
290
+ status: result.status,
291
+ error: typeof body.error === 'string' ? body.error : result.statusText,
292
+ ...(body.fieldErrors !== undefined ? { fieldErrors: body.fieldErrors as Record<string, string> } : {}),
293
+ }
294
+ }
295
+ catch {}
296
+ }
297
+ return ok
298
+ ? { ok: true, data: undefined as O }
299
+ : { ok: false, status: result.status, error: (await result.clone().text().catch(() => '')) || result.statusText }
300
+ }
301
+ return { ok: true, data: result as O }
302
+ }
303
+
193
304
  export async function executeAction(
194
305
  act: ServerAction<unknown, unknown>,
195
306
  request: Request,
196
307
  ctx: ActionContext,
197
308
  trustedOrigins?: ReadonlySet<string>,
198
- trustProxy = false,
199
- maxRequestBodySize = DEFAULT_MAX_REQUEST_BODY_SIZE,
309
+ trustProxy: TrustProxy = false,
200
310
  ): Promise<Response> {
201
- const originCheck = verifyOrigin(request, trustedOrigins, trustProxy)
202
- if (!originCheck.ok) {
203
- return Response.json(
204
- { ok: false, status: 403, error: originCheck.reason },
205
- { status: 403 },
206
- )
207
- }
208
-
209
- const wantsJson = (request.headers.get('accept') ?? '').includes('application/json')
210
- || (request.headers.get('content-type') ?? '').includes('application/json')
311
+ const json = wantsJson(request)
211
312
 
212
313
  let input: unknown
213
314
  if (act.schema !== undefined) {
214
315
  let rawBody: unknown
215
316
  try {
216
- rawBody = await parseActionBody(request, maxRequestBodySize)
317
+ rawBody = await parseActionBody(request)
217
318
  }
218
- catch (err) {
219
- if (err instanceof PayloadTooLargeError)
220
- return Response.json({ ok: false, status: 413, error: 'Payload Too Large' }, { status: 413 })
319
+ catch {
221
320
  return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
222
321
  }
223
322
 
224
- const checked = await validateSchema(act.schema, rawBody)
323
+ let checked = await validateSchema(act.schema, rawBody)
324
+ if (!checked.ok && !isJsonBody(request) && rawBody !== null && typeof rawBody === 'object' && !Array.isArray(rawBody))
325
+ checked = await retryWithFormArrays(act.schema, rawBody as Record<string, unknown>, checked)
225
326
  if (!checked.ok) {
226
327
  // Zero-JS progressive HTML <form> submit: flash fieldErrors + safe submitted values (<4KB) and redirect 303 back to trusted Referer
227
- if (!wantsJson) {
228
- const referer = request.headers.get('referer')
229
- if (referer) {
230
- let refUrl: URL | undefined
231
- try {
232
- refUrl = new URL(referer)
233
- }
234
- catch {
235
- refUrl = undefined
236
- }
237
- if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy)) {
238
- const serializedFlash = buildActionErrorFlash(act.url, checked.fieldErrors, rawBody, act.flashFields)
239
- ctx.cookies.set(ACTION_ERROR_COOKIE, serializedFlash, {
240
- httpOnly: true,
241
- sameSite: 'lax',
242
- maxAge: 60,
243
- })
244
- return Response.redirect(refUrl.href, 303)
245
- }
246
- }
328
+ const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy, ctx.url)
329
+ if (back !== undefined) {
330
+ ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, checked.fieldErrors, rawBody, act.flashFields), {
331
+ httpOnly: true,
332
+ sameSite: 'lax',
333
+ maxAge: 60,
334
+ })
335
+ return new Response(null, { status: 303, headers: { location: back.href } })
247
336
  }
248
337
  return Response.json(
249
338
  { ok: false, status: 400, error: 'Validation failed', fieldErrors: checked.fieldErrors, issues: checked.issues },
@@ -257,20 +346,9 @@ export async function executeAction(
257
346
  if (result instanceof Response)
258
347
  return result
259
348
 
260
- if (!wantsJson) {
261
- const referer = request.headers.get('referer')
262
- if (referer) {
263
- let refUrl: URL | undefined
264
- try {
265
- refUrl = new URL(referer)
266
- }
267
- catch {
268
- refUrl = undefined
269
- }
270
- if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy))
271
- return Response.redirect(refUrl.href, 303)
272
- }
273
- }
349
+ const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy, ctx.url)
350
+ if (back !== undefined)
351
+ return new Response(null, { status: 303, headers: { location: back.href } })
274
352
 
275
353
  return Response.json({ ok: true, data: result }, { status: 200 })
276
354
  }
@@ -0,0 +1,23 @@
1
+ // What the generated `dist/server/_entry.js` calls: an app from its bundled config and modules, plus what the caller serves it with.
2
+
3
+ import type { KayConfig } from '../plugins/index'
4
+ import type { EmbeddedServerConfig, KayApp } from './http'
5
+ import { resolveServerConfig } from '../plugins/index'
6
+ import { createServerFromEmbedded } from './index'
7
+
8
+ /** The manifest, assets and paths the caller read or embedded; runtime keys set here win over `kay.config.ts`. */
9
+ export type AppEntryOptions = Omit<EmbeddedServerConfig, 'modules'>
10
+
11
+ /** The exports of `dist/server/_entry.js`. */
12
+ export interface ServerEntry {
13
+ kayConfig: KayConfig
14
+ /** Bundled modules by manifest key. */
15
+ modules: Record<string, Record<string, unknown>>
16
+ /** The same modules by root-relative source path. */
17
+ sources: Record<string, Record<string, unknown>>
18
+ createApp: (options: AppEntryOptions) => Promise<KayApp>
19
+ }
20
+
21
+ export function createAppFromEntry(config: KayConfig, modules: Record<string, unknown>, options: AppEntryOptions): Promise<KayApp> {
22
+ return createServerFromEmbedded({ ...options, ...resolveServerConfig(config, options), modules })
23
+ }