@kayjs/kay 1.106.0 → 1.107.0

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 (222) hide show
  1. package/README.md +2 -2
  2. package/dist/eslint.js +428 -176
  3. package/editors/zed/extension.toml +2 -2
  4. package/llms/action-protection.md +1 -1
  5. package/llms/actions-refused-fields.md +22 -0
  6. package/llms/actions.md +2 -22
  7. package/llms/browser-only.md +1 -1
  8. package/llms/compiler-api.md +1 -1
  9. package/llms/components.md +1 -1
  10. package/llms/deprecated-lints.md +2 -3
  11. package/llms/island-and-form-lints.md +1 -0
  12. package/llms/islands.md +10 -1
  13. package/llms/project-new-and-add.md +1 -1
  14. package/llms/project.md +2 -2
  15. package/llms/schemas.md +6 -4
  16. package/llms/upgrading.md +19 -1
  17. package/llms/whats-new.md +14 -1
  18. package/package.json +15 -6
  19. package/src/build/client.ts +20 -24
  20. package/src/build/entry-files.ts +19 -0
  21. package/src/build/lazy-components.ts +130 -0
  22. package/src/build/lazy-manifest.ts +56 -0
  23. package/src/build/lazy-stubs.ts +31 -0
  24. package/src/build/plugin.ts +3 -1
  25. package/src/build/runtime-chunk.ts +1 -1
  26. package/src/build/transform.ts +17 -7
  27. package/src/build/variants.ts +7 -4
  28. package/src/check/action-options.ts +56 -0
  29. package/src/check/schema-json.ts +226 -0
  30. package/src/check/shadow-types.ts +11 -9
  31. package/src/compiler/codegen.ts +7 -17
  32. package/src/compiler/deprecated-lints-1-105.ts +41 -0
  33. package/src/compiler/deprecated-lints-1-106.ts +1 -1
  34. package/src/compiler/deprecated-lints-1-107.ts +14 -0
  35. package/src/compiler/deprecated-lints.ts +7 -55
  36. package/src/compiler/import-edits.ts +15 -0
  37. package/src/compiler/index.ts +8 -3
  38. package/src/compiler/island-declaration.ts +15 -0
  39. package/src/compiler/kay-exports.ts +1 -0
  40. package/src/compiler/lazy-imports.ts +357 -0
  41. package/src/compiler/parser.ts +2 -2
  42. package/src/compiler/route-lints.ts +2 -0
  43. package/src/compiler/schema-lints.ts +13 -0
  44. package/src/compiler/script-server.ts +6 -3
  45. package/src/content/validate.ts +1 -1
  46. package/src/new.ts +6 -2
  47. package/src/runtime/action.ts +47 -4
  48. package/src/runtime/client.ts +10 -0
  49. package/src/runtime/dom-lazy.ts +276 -0
  50. package/src/runtime/field-errors.ts +58 -0
  51. package/src/runtime/field-refusal.ts +179 -0
  52. package/src/runtime/form.ts +3 -2
  53. package/src/runtime/html.ts +6 -1
  54. package/src/runtime/index.ts +2 -0
  55. package/src/runtime/island.server.ts +36 -2
  56. package/src/runtime/schema-record.ts +2 -1
  57. package/src/runtime/schema.client.ts +104 -14
  58. package/src/runtime/schema.ts +9 -2
  59. package/src/runtime/standard-schema.ts +32 -0
  60. package/src/runtime/validate-run.client.ts +179 -0
  61. package/src/runtime/validate.client.ts +11 -0
  62. package/src/runtime/validate.ts +4 -137
  63. package/src/server/actions.ts +48 -43
  64. package/src/server/answer.ts +102 -0
  65. package/src/server/api-input.ts +166 -0
  66. package/src/server/api.ts +12 -44
  67. package/src/server/app-stages.ts +15 -8
  68. package/src/server/app.ts +5 -2
  69. package/src/server/client.ts +2 -0
  70. package/src/server/dev.ts +7 -9
  71. package/src/server/file-limit.ts +7 -1
  72. package/src/server/forms.ts +1 -1
  73. package/src/server/host-allowlist.ts +7 -7
  74. package/src/server/index.ts +2 -0
  75. package/src/server/kay-routes.ts +221 -0
  76. package/src/server/kay-server.ts +228 -0
  77. package/src/server/kept-exports.ts +1 -0
  78. package/src/server/library.ts +0 -2
  79. package/src/server/mcp.ts +1 -1
  80. package/src/server/openapi.ts +12 -3
  81. package/src/server/phases.ts +249 -0
  82. package/src/server/protection.ts +6 -6
  83. package/src/server/proxy-key.ts +8 -8
  84. package/src/server/query.ts +4 -25
  85. package/src/server/receive.ts +43 -0
  86. package/src/server/render-document.ts +13 -3
  87. package/src/server/request-context.ts +137 -0
  88. package/src/server/schema-check.ts +1 -1
  89. package/src/server/socket.ts +19 -47
  90. package/src/server/stream.ts +1 -1
  91. package/src/server/validate.ts +346 -0
  92. package/src/test/mount.ts +6 -2
  93. package/types/build/client.d.ts +3 -2
  94. package/types/build/client.d.ts.map +1 -1
  95. package/types/build/entry-files.d.ts +4 -0
  96. package/types/build/entry-files.d.ts.map +1 -0
  97. package/types/build/lazy-components.d.ts +6 -0
  98. package/types/build/lazy-components.d.ts.map +1 -0
  99. package/types/build/lazy-manifest.d.ts +19 -0
  100. package/types/build/lazy-manifest.d.ts.map +1 -0
  101. package/types/build/lazy-stubs.d.ts +5 -0
  102. package/types/build/lazy-stubs.d.ts.map +1 -0
  103. package/types/build/plugin.d.ts +1 -0
  104. package/types/build/plugin.d.ts.map +1 -1
  105. package/types/build/transform.d.ts +3 -1
  106. package/types/build/transform.d.ts.map +1 -1
  107. package/types/build/variants.d.ts.map +1 -1
  108. package/types/check/action-options.d.ts +3 -0
  109. package/types/check/action-options.d.ts.map +1 -0
  110. package/types/check/schema-json.d.ts +3 -0
  111. package/types/check/schema-json.d.ts.map +1 -0
  112. package/types/check/shadow-types.d.ts.map +1 -1
  113. package/types/compiler/codegen.d.ts +2 -0
  114. package/types/compiler/codegen.d.ts.map +1 -1
  115. package/types/compiler/deprecated-lints-1-105.d.ts +39 -0
  116. package/types/compiler/deprecated-lints-1-105.d.ts.map +1 -0
  117. package/types/compiler/deprecated-lints-1-106.d.ts +1 -1
  118. package/types/compiler/deprecated-lints-1-106.d.ts.map +1 -1
  119. package/types/compiler/deprecated-lints-1-107.d.ts +12 -0
  120. package/types/compiler/deprecated-lints-1-107.d.ts.map +1 -0
  121. package/types/compiler/deprecated-lints.d.ts +36 -44
  122. package/types/compiler/deprecated-lints.d.ts.map +1 -1
  123. package/types/compiler/import-edits.d.ts +1 -0
  124. package/types/compiler/import-edits.d.ts.map +1 -1
  125. package/types/compiler/index.d.ts +2 -0
  126. package/types/compiler/index.d.ts.map +1 -1
  127. package/types/compiler/island-declaration.d.ts +5 -0
  128. package/types/compiler/island-declaration.d.ts.map +1 -1
  129. package/types/compiler/kay-exports.d.ts.map +1 -1
  130. package/types/compiler/lazy-imports.d.ts +33 -0
  131. package/types/compiler/lazy-imports.d.ts.map +1 -0
  132. package/types/compiler/lints.d.ts +44 -44
  133. package/types/compiler/route-lints.d.ts +8 -0
  134. package/types/compiler/route-lints.d.ts.map +1 -1
  135. package/types/compiler/schema-lints.d.ts +11 -0
  136. package/types/compiler/schema-lints.d.ts.map +1 -0
  137. package/types/compiler/script-server.d.ts.map +1 -1
  138. package/types/new.d.ts +1 -0
  139. package/types/new.d.ts.map +1 -1
  140. package/types/runtime/action.d.ts +26 -1
  141. package/types/runtime/action.d.ts.map +1 -1
  142. package/types/runtime/client.d.ts.map +1 -1
  143. package/types/runtime/dom-lazy.d.ts +6 -0
  144. package/types/runtime/dom-lazy.d.ts.map +1 -0
  145. package/types/runtime/field-errors.d.ts +4 -0
  146. package/types/runtime/field-errors.d.ts.map +1 -0
  147. package/types/runtime/field-refusal.d.ts +37 -0
  148. package/types/runtime/field-refusal.d.ts.map +1 -0
  149. package/types/runtime/form.d.ts +1 -1
  150. package/types/runtime/form.d.ts.map +1 -1
  151. package/types/runtime/html.d.ts.map +1 -1
  152. package/types/runtime/index.d.ts +2 -0
  153. package/types/runtime/index.d.ts.map +1 -1
  154. package/types/runtime/island.server.d.ts +2 -0
  155. package/types/runtime/island.server.d.ts.map +1 -1
  156. package/types/runtime/schema-record.d.ts.map +1 -1
  157. package/types/runtime/schema.client.d.ts.map +1 -1
  158. package/types/runtime/schema.d.ts +6 -1
  159. package/types/runtime/schema.d.ts.map +1 -1
  160. package/types/runtime/standard-schema.d.ts +37 -0
  161. package/types/runtime/standard-schema.d.ts.map +1 -0
  162. package/types/runtime/validate-run.client.d.ts +4 -0
  163. package/types/runtime/validate-run.client.d.ts.map +1 -0
  164. package/types/runtime/validate.client.d.ts +4 -0
  165. package/types/runtime/validate.client.d.ts.map +1 -0
  166. package/types/runtime/validate.d.ts +1 -21
  167. package/types/runtime/validate.d.ts.map +1 -1
  168. package/types/server/actions.d.ts.map +1 -1
  169. package/types/server/answer.d.ts +6 -0
  170. package/types/server/answer.d.ts.map +1 -0
  171. package/types/server/api-input.d.ts +19 -0
  172. package/types/server/api-input.d.ts.map +1 -0
  173. package/types/server/api.d.ts.map +1 -1
  174. package/types/server/app-stages.d.ts +4 -1
  175. package/types/server/app-stages.d.ts.map +1 -1
  176. package/types/server/app.d.ts +2 -0
  177. package/types/server/app.d.ts.map +1 -1
  178. package/types/server/client.d.ts +1 -0
  179. package/types/server/client.d.ts.map +1 -1
  180. package/types/server/dev.d.ts +1 -1
  181. package/types/server/dev.d.ts.map +1 -1
  182. package/types/server/file-limit.d.ts.map +1 -1
  183. package/types/server/host-allowlist.d.ts +3 -3
  184. package/types/server/host-allowlist.d.ts.map +1 -1
  185. package/types/server/index.d.ts +2 -0
  186. package/types/server/index.d.ts.map +1 -1
  187. package/types/server/kay-routes.d.ts +47 -0
  188. package/types/server/kay-routes.d.ts.map +1 -0
  189. package/types/server/kay-server.d.ts +25 -0
  190. package/types/server/kay-server.d.ts.map +1 -0
  191. package/types/server/kept-exports.d.ts.map +1 -1
  192. package/types/server/library.d.ts +0 -1
  193. package/types/server/library.d.ts.map +1 -1
  194. package/types/server/openapi.d.ts.map +1 -1
  195. package/types/server/phases.d.ts +36 -0
  196. package/types/server/phases.d.ts.map +1 -0
  197. package/types/server/protection.d.ts +3 -2
  198. package/types/server/protection.d.ts.map +1 -1
  199. package/types/server/proxy-key.d.ts +3 -3
  200. package/types/server/proxy-key.d.ts.map +1 -1
  201. package/types/server/query.d.ts.map +1 -1
  202. package/types/server/receive.d.ts +9 -0
  203. package/types/server/receive.d.ts.map +1 -0
  204. package/types/server/render-document.d.ts.map +1 -1
  205. package/types/server/request-context.d.ts +29 -0
  206. package/types/server/request-context.d.ts.map +1 -0
  207. package/types/server/schema-check.d.ts +1 -0
  208. package/types/server/schema-check.d.ts.map +1 -1
  209. package/types/server/socket.d.ts +3 -5
  210. package/types/server/socket.d.ts.map +1 -1
  211. package/types/server/validate.d.ts +26 -0
  212. package/types/server/validate.d.ts.map +1 -0
  213. package/types/test/mount.d.ts.map +1 -1
  214. package/src/check/schema-type.ts +0 -9
  215. package/src/compiler/deprecated-script-fence.ts +0 -26
  216. package/src/server/field-errors.ts +0 -136
  217. package/types/check/schema-type.d.ts +0 -3
  218. package/types/check/schema-type.d.ts.map +0 -1
  219. package/types/compiler/deprecated-script-fence.d.ts +0 -3
  220. package/types/compiler/deprecated-script-fence.d.ts.map +0 -1
  221. package/types/server/field-errors.d.ts +0 -6
  222. package/types/server/field-errors.d.ts.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import type { CookieMap } from 'bun'
2
- import type { Elysia, TSchema, ValidationError } from 'elysia'
2
+ import type { Elysia, TSchema } from 'elysia'
3
3
  import type { Server } from 'elysia/universal'
4
4
  import type { ActionsConfig } from '../config'
5
5
  import type { GuardContext, Locals, RouteParams } from '../runtime'
@@ -18,16 +18,17 @@ import type { I18n } from './i18n'
18
18
  import type { DocumentedAction } from './openapi'
19
19
  import type { Unmatched } from './page-routes'
20
20
  import type { ToolOutputs } from './tool-outputs'
21
+ import type { Source } from './validate'
21
22
  import { relative } from 'node:path'
22
23
  import { KayError } from '../compiler/errors'
23
- import { decodeCall, failure, FORM_CALL, FORM_FIELD, isAction, isFailure, protectionFields } from '../runtime/action'
24
+ import { decodeCall, failure, FORM_CALL, FORM_FIELD, honeypotField, isAction, isFailure, protectionFields, STAMP_FIELD } from '../runtime/action'
24
25
  import { joinBase } from '../runtime/base'
25
26
  import { escapeAttribute } from '../runtime/escape'
26
- import { formInput } from '../runtime/form'
27
27
  import { localeState, runInLocale } from '../runtime/locale-state'
28
28
  import { thrownRefusal } from '../runtime/refuse'
29
29
  import { withDefaultBounds } from '../runtime/schema-bounds'
30
30
  import { sizeText } from '../runtime/size-text'
31
+ import { isStandardSchema } from '../runtime/standard-schema'
31
32
  import { FAILURE_HEADER, NAVIGATE_HEADER, PAGE_HEADER, REDIRECT_HEADER } from '../runtime/swap'
32
33
  import { ACTION_PREFIX, encodeValue, FIELDS_PREFIX, unsendable } from '../runtime/wire'
33
34
  import { pageLocale } from '../runtime/words.server'
@@ -40,7 +41,6 @@ import { routerPath } from './base'
40
41
  import { timeoutMs } from './config-limits'
41
42
  import { cookieJar } from './cookies'
42
43
  import { BACK_PARAMETER, crossSiteResponse, isCrossSite, postedFrom, TEXT } from './cross-site'
43
- import { fieldMessage, refusedFields, validated } from './field-errors'
44
44
  import { fileBodyLimit } from './file-limit'
45
45
  import { handOver, submittedValues, writeSuccess } from './flash'
46
46
  import { requiredGuards, runGuards, unguarded } from './guards'
@@ -61,6 +61,7 @@ import { carryContext } from './security'
61
61
  import { actionStoppers, Denied, NotFound, Redirect, stoppers } from './signals'
62
62
  import { toolSettings } from './tool-settings'
63
63
  import { answered, replyTrace, SERVER_SPAN, traced } from './trace'
64
+ import { isRefusal, messagesOf, validate } from './validate'
64
65
  import { visitAs } from './visit'
65
66
  import { kayWord } from './words'
66
67
  import { onceWritten } from './writes'
@@ -94,9 +95,6 @@ const HEAD_START = /<head\b[^>]*>/i
94
95
  // The `action` of a form posting to an action, the site's `base` before it if any.
95
96
  const FORM_ACTION = /(<form\b[^>]*?\saction=")([^"]*\/_kay\/action\/[^"#]*)/gi
96
97
 
97
- // Elysia names a file it refuses `body.<field>`.
98
- const BODY_PREFIX = /^body\./
99
-
100
98
  export interface ActionOptions {
101
99
  // Shows a failed action's message instead of a generic one.
102
100
  dev?: boolean | undefined
@@ -152,7 +150,8 @@ export async function registerActionRoutes(app: Elysia, routes: ServedRoute[], m
152
150
  continue
153
151
 
154
152
  // Every string field with no bound of its own takes the default, for the route's validation, the form's `maxlength` and the tool's schema alike.
155
- Object.assign(exported, { schema: withDefaultBounds(exported.schema) })
153
+ if (!isStandardSchema(exported.schema))
154
+ Object.assign(exported, { schema: withDefaultBounds(exported.schema) })
156
155
 
157
156
  const taken = served.get(exported.url)
158
157
 
@@ -200,7 +199,6 @@ export async function registerActionRoutes(app: Elysia, routes: ServedRoute[], m
200
199
 
201
200
  return carryContext(context.set, response)
202
201
  }, context.request), {
203
- body: validated(value.schema),
204
202
  transform: async (context) => {
205
203
  refuseCrossSite(context.request)
206
204
 
@@ -226,36 +224,37 @@ export async function registerActionRoutes(app: Elysia, routes: ServedRoute[], m
226
224
  if (typeof form === 'string')
227
225
  requestRecord(context.request).postedForm = form
228
226
 
229
- context.body = asForm ? formInput(value.schema, withFixedFields(withoutEmptyFiles(context.body), context.request)) : callInput(context.body)
227
+ context.body = asForm ? withFixedFields(withoutEmptyFiles(context.body), context.request) : callInput(context.body)
230
228
  },
231
- // After validation, the one stage where the app's `resolve` values are there for `ctx.locals`.
232
- ...(guards.length > 0 && {
233
- beforeHandle: async (context: { request: Request }) => {
234
- const { pageParams = {}, pageUrl } = requestRecord(context.request)
235
-
236
- return inLocale(context.request, options, async () => admit(guards, sharedContext(context.request, () => ({ ...context })), pageParams, pageUrl, options))
237
- },
238
- }),
239
- error: async (context) => {
240
- const { code, error, request, body, server, set } = context
229
+ // The guards first, so a caller they refuse learns nothing of the input, then the input against the schema: the handler reads the value it reads.
230
+ beforeHandle: async (context: { request: Request, body: unknown, server: Server | null }) => {
231
+ const { pageParams = {}, pageUrl } = requestRecord(context.request)
232
+ const { request } = context
241
233
 
242
- if ((code === 'VALIDATION' || code === 'INVALID_FILE_TYPE') && guards.length > 0) {
243
- const { pageParams = {}, pageUrl } = requestRecord(request)
244
- const refusal = await inLocale(request, options, async () => guardsFirst(guards, sharedContext(request, () => ({ ...context })), pageParams, pageUrl, options))
234
+ return inLocale(request, options, async () => {
235
+ if (guards.length > 0) {
236
+ const refusal = await admit(guards, sharedContext(request, () => ({ ...context })), pageParams, pageUrl, options)
245
237
 
246
- if (refusal)
247
- return refusal
248
- }
238
+ if (refusal)
239
+ return refusal
240
+ }
249
241
 
250
- if (code === 'VALIDATION')
251
- return inLocale(request, options, async () => refused(value, error, request, server, back))
242
+ // A call with no input posts no body, which an object schema reads as no fields.
243
+ const posted = context.body === undefined && (value.schema as { type?: string }).type === 'object' ? {} : context.body
244
+ const result = await validate(value.schema, isCall(request) && !isFormCall(request) ? posted : withoutKayFields(posted, value), { source: sourceOfCall(request) })
252
245
 
253
- // Elysia checks a top-level `s.File({ type })` against the file's bytes once the schema passed.
254
- if (code === 'INVALID_FILE_TYPE') {
255
- const field = error.property.replace(BODY_PREFIX, '')
246
+ if (isRefusal(result))
247
+ return failed(request, new Headers(), cookieJar(request).cookies, { action: value.url, status: 422, values: isCall(request) ? {} : submittedValues(posted), errors: messagesOf(result.errors) }, context.server, back)
256
248
 
257
- return inLocale(request, options, async () => failed(request, new Headers(), cookieJar(request).cookies, { action: value.url, status: 422, values: submittedValues(body), errors: { [field]: fieldError(value, field) ?? kayWord('kay.action.invalidFile') } }, server, back))
258
- }
249
+ // The copy the guards were handed is the one the handler is run with.
250
+ context.body = result.value
251
+ sharedContext(request, () => ({ ...context })).body = result.value
252
+
253
+ return undefined
254
+ })
255
+ },
256
+ error: async (context) => {
257
+ const { error, set } = context
259
258
 
260
259
  // Read as unknown: some apps' Elysia types narrow the error to an intersection holding `number`.
261
260
  const refusal: unknown = error
@@ -436,9 +435,14 @@ function callInput(body: unknown): unknown {
436
435
  }
437
436
  }
438
437
 
439
- // The `error` option the schema gives a top-level field, read in the request's locale.
440
- function fieldError(action: ServerAction<TSchema, unknown>, field: string): string | undefined {
441
- return fieldMessage(action.schema, `/${field}`)
438
+ // The post without the fields kay adds to a form itself, which the schema never names: the form it came from, the stamp `minTime` reads and the honeypot.
439
+ function withoutKayFields(body: unknown, action: ServerAction<TSchema, unknown>): unknown {
440
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
441
+ return body
442
+
443
+ const honeypot = honeypotField(action.protection)
444
+
445
+ return Object.fromEntries(Object.entries(body).filter(([name]) => name !== FORM_FIELD && name !== STAMP_FIELD && name !== honeypot))
442
446
  }
443
447
 
444
448
  // Browsers send `Origin` on every POST, so a form another site submits on the user's behalf is refused before anything else runs.
@@ -772,13 +776,6 @@ function encodeOrExplain(value: unknown, what: string): string {
772
776
  }
773
777
  }
774
778
 
775
- // Input the schema refused: a message per field, the schema's own `error` when it has one, a function `error` called in the request's locale.
776
- async function refused(action: ServerAction<TSchema, unknown>, error: Readonly<ValidationError>, request: Request, server: Server | null, back: Back): Promise<Response> {
777
- const errors = refusedFields(action.schema, error)
778
-
779
- return failed(request, new Headers(), cookieJar(request).cookies, { action: action.url, status: 422, values: submittedValues(error.value), errors }, server, back)
780
- }
781
-
782
779
  // A call gets the failure as JSON; a plain form post gets the page it came from, rendered with the failure.
783
780
  async function failed(request: Request, headers: Headers, cookies: CookieMap, flash: Flash, server: Server | null, back: Back): Promise<Response> {
784
781
  for (const cookie of cookies.toSetCookieHeaders())
@@ -877,3 +874,11 @@ function visitHeaders(request: Request): Headers {
877
874
  function redirectHeader(request: Request): string {
878
875
  return isCall(request) || request.headers.get(NAVIGATE_HEADER) === '1' ? REDIRECT_HEADER : 'location'
879
876
  }
877
+
878
+ // A call's JSON keeps its types, except one from an MCP client, whose arguments may be the text of a number or a boolean as a form's are.
879
+ function sourceOfCall(request: Request): Source {
880
+ if (!isCall(request) || isFormCall(request))
881
+ return 'form'
882
+
883
+ return request.headers.get('x-kay-tool') === '1' ? 'query' : 'json'
884
+ }
@@ -0,0 +1,102 @@
1
+ import type { RequestContext } from './request-context'
2
+ import { eventStream } from './event-stream'
3
+ import { fileAnswer } from './file-answer'
4
+
5
+ // What a handler returned that has no answer: named by its route, so the fix is where it is written.
6
+ export class UnsupportedAnswerError extends Error {
7
+ override readonly name = 'UnsupportedAnswerError'
8
+ }
9
+
10
+ // A bigint is written as its digits, which JSON has no value for: the replacer swaps it for a marker string only this process knows, and the marker and its quotes are dropped from the text, so a string an app holds can never read as one.
11
+ const MARK = `__kay_bigint_${crypto.randomUUID()}_`
12
+ const MARKED = new RegExp(`"${MARK}(-?\\d+)"`, 'g')
13
+
14
+ function jsonText(value: unknown): string | undefined {
15
+ let marked = false
16
+
17
+ const text = JSON.stringify(value, (_key, held: unknown) => {
18
+ if (typeof held !== 'bigint')
19
+ return held
20
+
21
+ marked = true
22
+
23
+ return `${MARK}${held}`
24
+ })
25
+
26
+ return marked && text !== undefined ? text.replace(MARKED, '$1') : text
27
+ }
28
+
29
+ function isPlain(value: object): boolean {
30
+ const prototype: unknown = Object.getPrototypeOf(value)
31
+
32
+ return prototype === Object.prototype || prototype === null
33
+ }
34
+
35
+ function isEventSource(value: object): boolean {
36
+ return Symbol.asyncIterator in value || Object.prototype.toString.call(value) === '[object Generator]'
37
+ }
38
+
39
+ // A response init whose status is only there when a handler set one.
40
+ function init(status: number | undefined, type: string): ResponseInit {
41
+ return status === undefined ? { headers: { 'content-type': type } } : { status, headers: { 'content-type': type } }
42
+ }
43
+
44
+ function json(text: string, status: number | undefined): Response {
45
+ return new Response(text, init(status, 'application/json'))
46
+ }
47
+
48
+ function named(context: RequestContext): string {
49
+ const { route } = context
50
+
51
+ return route === undefined ? `${context.method} ${context.url.pathname}` : `${route.method} ${route.path}`
52
+ }
53
+
54
+ // The Response a handler's value stands for, made once whatever the route kind:
55
+ // a Response as it is, text, JSON for an object, an array, a number, a boolean, null and a bigint, a Blob or a file with `Range` and `HEAD` answered, a stream, an event stream for an async generator, bytes, and 204 for nothing.
56
+ // A class instance, a Map or a function has no answer and fails the route, which says so by name.
57
+ // The status a handler set goes on a value that is not a Response.
58
+ export function answer(value: unknown, context: RequestContext): Response {
59
+ if (value instanceof Response)
60
+ return value
61
+
62
+ const status = context.written?.status
63
+
64
+ if (value === undefined)
65
+ return new Response(null, { status: status ?? 204 })
66
+
67
+ if (typeof value === 'string')
68
+ return new Response(value, init(status, 'text/plain; charset=utf-8'))
69
+
70
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint' || value === null)
71
+ return json(jsonText(value)!, status)
72
+
73
+ if (typeof value === 'object') {
74
+ if (value instanceof Blob)
75
+ return withStatus(fileAnswer(value, context.request), status)
76
+
77
+ if (value instanceof ReadableStream)
78
+ return new Response(value, init(status, 'application/octet-stream'))
79
+
80
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer)
81
+ return new Response(value as BodyInit, init(status, 'application/octet-stream'))
82
+
83
+ if (isEventSource(value))
84
+ return withStatus(eventStream(value as AsyncIterable<unknown>), status)
85
+
86
+ if (Array.isArray(value) || isPlain(value)) {
87
+ const text = jsonText(value)
88
+
89
+ if (text !== undefined)
90
+ return json(text, status)
91
+ }
92
+ }
93
+
94
+ const kind = typeof value === 'object' ? (value.constructor as { name?: string } | undefined)?.name ?? 'an object with no class' : typeof value
95
+
96
+ throw new UnsupportedAnswerError(`kay: ${named(context)} returned ${kind}, which has no response; return a Response, text, a plain object or array, a file, a stream or an async generator`)
97
+ }
98
+
99
+ // A response with the status a handler set, when that is not the one it has.
100
+ function withStatus(response: Response, status: number | undefined): Response {
101
+ return status === undefined || status === response.status ? response : new Response(response.body, { status, headers: response.headers })
102
+ }
@@ -0,0 +1,166 @@
1
+ import type { Issue, Source } from './validate'
2
+ import { isStandardSchema } from '../runtime/standard-schema'
3
+ import { isRefusal, validate } from './validate'
4
+
5
+ // What a route's `body`, `query`, `params`, `headers` and `cookie` schemas were declared as, kept where OpenAPI reads them since Elysia is left none to validate with.
6
+ const DECLARED = Symbol.for('kay.apiInputs')
7
+
8
+ const INPUTS = ['body', 'query', 'params', 'headers', 'cookie'] as const
9
+
10
+ type Input = typeof INPUTS[number]
11
+
12
+ type Hooks = Partial<Record<Input, unknown>> & { transform?: unknown, standaloneValidator?: Partial<Record<Input, unknown>>[], [DECLARED]?: Partial<Record<Input, object>> }
13
+
14
+ // Input a route's schema refused. It carries Elysia's `VALIDATION` code and the shape of its error, so an `onError` hook that answers refused input still reads it as it did.
15
+ export class InputRefusedError extends Error {
16
+ readonly code = 'VALIDATION'
17
+ readonly status = 422
18
+
19
+ constructor(readonly type: Input, readonly errors: Issue[]) {
20
+ super(`Invalid ${type}: ${errors.map(issue => issue.message).join('; ')}`)
21
+ this.name = 'InputRefusedError'
22
+ }
23
+
24
+ get all(): { path: string, message: string, summary: string }[] {
25
+ return this.errors.map(issue => ({ path: `/${issue.path.replaceAll('.', '/')}`, message: issue.message, summary: issue.message }))
26
+ }
27
+ }
28
+
29
+ // The input schemas of a route as it was declared.
30
+ export function declaredInputs(hooks: unknown): Partial<Record<Input, object>> {
31
+ return (hooks as Hooks | undefined)?.[DECLARED] ?? {}
32
+ }
33
+
34
+ // A query, the headers and the cookies of a request carry what the schema does not name, which is dropped, not refused; so does a body or params with several schemas, a guard's beside the route's, each naming fields the others lack.
35
+ function lenient(schema: object): object {
36
+ if (isStandardSchema(schema))
37
+ return schema
38
+
39
+ const copy: Record<PropertyKey, unknown> = { ...schema, 'x-kay-extra': 'strip' }
40
+
41
+ delete copy.additionalProperties
42
+
43
+ return copy
44
+ }
45
+
46
+ const FORM_BODY = /^(?:multipart\/form-data|application\/x-www-form-urlencoded)\b/i
47
+
48
+ function sourceOf(input: Input, request: Request): Source {
49
+ if (input === 'body')
50
+ return FORM_BODY.test(request.headers.get('content-type') ?? '') ? 'form' : 'json'
51
+
52
+ return input === 'query' ? 'query' : 'params'
53
+ }
54
+
55
+ interface InputContext {
56
+ request: Request
57
+ body?: unknown
58
+ query?: unknown
59
+ params?: unknown
60
+ headers?: unknown
61
+ cookie?: unknown
62
+ }
63
+
64
+ // The value of each cookie, as Elysia hands the jar over as objects holding it.
65
+ function cookieValues(jar: unknown): unknown {
66
+ if (typeof jar !== 'object' || jar === null)
67
+ return jar
68
+
69
+ return Object.fromEntries(Object.entries(jar).map(([name, cookie]) => [name, (cookie as { value?: unknown } | undefined)?.value]))
70
+ }
71
+
72
+ // Takes the route's input schemas out of Elysia's validation, which would call their `error` functions outside the request's locale, and checks them in a hook of its own, the value read being the one the handler gets. Reading each by its property tells Elysia the route needs it parsed.
73
+ // A key the query repeats is a list of its values: Elysia reads it so only for a schema it holds itself, which it is left none of.
74
+ function withRepeats(request: Request, parsed: unknown): unknown {
75
+ if (typeof parsed !== 'object' || parsed === null)
76
+ return parsed
77
+
78
+ const { searchParams } = new URL(request.url)
79
+ const repeated = Object.fromEntries([...new Set(searchParams.keys())].map(key => [key, searchParams.getAll(key)] as const).filter(([, values]) => values.length > 1))
80
+
81
+ return Object.keys(repeated).length === 0 ? parsed : { ...parsed, ...repeated }
82
+ }
83
+
84
+ export function validatingInputs(hooks: unknown, inLocale: <T>(request: Request, run: () => T) => T): void {
85
+ const route = hooks as Hooks | undefined
86
+ const declared: Partial<Record<Input, object>> = {}
87
+ // Every schema an input has: the route's own, and one for each guard around it, which Elysia keeps apart and checks one by one.
88
+ const all: Partial<Record<Input, object[]>> = {}
89
+
90
+ if (route === undefined)
91
+ return
92
+
93
+ for (const input of INPUTS) {
94
+ for (const holder of [route, ...route.standaloneValidator ?? []]) {
95
+ const schema = holder[input]
96
+
97
+ if (typeof schema === 'object' && schema !== null) {
98
+ (all[input] ??= []).push(schema)
99
+ declared[input] ??= schema
100
+ holder[input] = undefined
101
+ }
102
+ }
103
+ }
104
+
105
+ if (Object.keys(declared).length === 0)
106
+ return
107
+
108
+ const checked: Partial<Record<Input, object[]>> = Object.fromEntries(Object.entries(all).map(([input, schemas]) => [input, (input === 'body' || input === 'params') && schemas.length === 1 ? schemas : schemas.map(lenient)]))
109
+
110
+ route[DECLARED] = declared
111
+
112
+ // What an input reads as, or the refusal thrown: the schemas it has, the route's own and its guards', checked one after the other.
113
+ const settle = async (input: Input, request: Request, given: unknown): Promise<unknown> => {
114
+ const schemas = checked[input]
115
+
116
+ if (schemas === undefined)
117
+ return given
118
+
119
+ // Each schema reads what was sent, not what another dropped from it: a form post loses the fields a schema does not name, and a guard's schema names others than the route's.
120
+ const outputs: unknown[] = []
121
+ const refused = new Map<string, Issue>()
122
+
123
+ for (const schema of schemas) {
124
+ const result = await inLocale(request, async () => validate(schema, given, { source: sourceOf(input, request), trim: false }))
125
+
126
+ if (!isRefusal(result)) {
127
+ outputs.push(result.value)
128
+
129
+ continue
130
+ }
131
+
132
+ for (const issue of result.errors) {
133
+ if (!refused.has(issue.path))
134
+ refused.set(issue.path, issue)
135
+ }
136
+ }
137
+
138
+ if (refused.size > 0)
139
+ throw new InputRefusedError(input, [...refused.values()])
140
+
141
+ const plain = outputs.every(output => typeof output === 'object' && output !== null && !Array.isArray(output))
142
+
143
+ return plain ? Object.assign({}, ...outputs) as unknown : outputs.at(-1)
144
+ }
145
+
146
+ // One hook per input, each naming its own property and never passing the context on: Elysia reads a hook's source to know what to parse, so a route declaring only a `query` leaves its body to the handler.
147
+ const readers: Record<Input, (context: InputContext) => Promise<void>> = {
148
+ body: async (context) => {
149
+ context.body = await settle('body', context.request, context.body)
150
+ },
151
+ query: async (context) => {
152
+ context.query = await settle('query', context.request, withRepeats(context.request, context.query))
153
+ },
154
+ params: async (context) => {
155
+ context.params = await settle('params', context.request, context.params)
156
+ },
157
+ headers: async (context) => {
158
+ context.headers = await settle('headers', context.request, context.headers)
159
+ },
160
+ cookie: async (context) => {
161
+ await settle('cookie', context.request, cookieValues(context.cookie))
162
+ },
163
+ }
164
+
165
+ route.transform = [...[route.transform ?? []].flat() as unknown[], ...INPUTS.filter(input => declared[input] !== undefined).map(input => readers[input])]
166
+ }
package/src/server/api.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Server } from 'bun'
2
- import type { Context, TSchema, ValidationError } from 'elysia'
2
+ import type { Context, TSchema } from 'elysia'
3
3
  import type { ExtensionApp } from '../config'
4
4
  import type { Guard, Locals } from '../runtime'
5
5
  import type { ActionTool, RateLimit } from '../runtime/action'
@@ -22,6 +22,7 @@ import { API_MOUNT } from '../runtime/live'
22
22
  import { runInLocale } from '../runtime/locale-state'
23
23
  import { withDefaultBounds } from '../runtime/schema-bounds'
24
24
  import { contextLocale, guardsFirst, passGuards, requestState } from './actions'
25
+ import { InputRefusedError, validatingInputs } from './api-input'
25
26
  import { withDecodedParams } from './api-params'
26
27
  import { importModule } from './bundle'
27
28
  import { timeoutMs } from './config-limits'
@@ -29,7 +30,6 @@ import { cookieJar } from './cookies'
29
30
  import { corsAdmits, corsResponse, corsRule, dropOwnGrant, grantedByKay, preflight, varyByOrigin, withCors, withoutOwnGrant } from './cors'
30
31
  import { admitCrossSite, crossSiteRefused, crossSiteResponse } from './cross-site'
31
32
  import { streamReporters } from './event-stream'
32
- import { refusedFields, validated } from './field-errors'
33
33
  import { keepOwnGuards, loadApiGuards, requiredGuards } from './guards'
34
34
  import { handlerTiming } from './handler-timing'
35
35
  import { inRouteReads, LIVE_HEADER, routeProof } from './live'
@@ -49,7 +49,7 @@ import { markPrivate, wasReadPersonally } from './scope'
49
49
  import { carriedNames, carryContext } from './security'
50
50
  import { holdToLimits, socketOptions } from './socket'
51
51
  import { answered, failed, replyTrace, SERVER_SPAN, startSpan, tracedUnder, tracing } from './trace'
52
- import { kayWord } from './words'
52
+ import { messagesOf } from './validate'
53
53
  import { socketLimits } from './ws-limits'
54
54
 
55
55
  // What a body Elysia streams, awaits or asks for its response has: a generator, a thenable, an object with `toResponse()`.
@@ -63,22 +63,6 @@ const CORS = Symbol.for('kay.cors')
63
63
  const RATE_LIMIT = Symbol.for('kay.rateLimit')
64
64
  // Where `api({ timeout })` keeps the module's timeout.
65
65
  const TIMEOUT = Symbol.for('kay.timeout')
66
- // The inputs of a route Elysia validates, whose schemas are read for their `error` in the request's locale.
67
- const INPUTS = ['body', 'query', 'params', 'headers', 'cookie']
68
- const BODY_PREFIX = /^body\./
69
-
70
- // Elysia reads the whole jar of a request against the `cookie` schema, where the query and the headers it strips, so a strict one would refuse every cookie a third party sets.
71
- function inputSchema(input: string, schema: TSchema): TSchema {
72
- if (input !== 'cookie' || !('additionalProperties' in schema) || schema.additionalProperties !== false)
73
- return schema
74
-
75
- const copy = { ...schema } as Record<PropertyKey, unknown>
76
-
77
- delete copy.additionalProperties
78
-
79
- return copy as unknown as TSchema
80
- }
81
-
82
66
  // The requests the guards of their module let through, whose later errors are no refused input.
83
67
  const admitted = new WeakSet<Request>()
84
68
 
@@ -159,13 +143,9 @@ export async function serveApi(app: Elysia, modules: ApiModule[], options: Actio
159
143
  if (hooks && route.method !== 'WS' && typeof hooks.body === 'object' && hooks.body !== null && !('~standard' in hooks.body))
160
144
  hooks.body = withDefaultBounds(hooks.body as TSchema)
161
145
 
162
- // The `error` functions of an input schema are called by kay in the request's locale, never by Elysia outside it.
163
- for (const input of INPUTS) {
164
- const schema = (hooks as Record<string, unknown> | undefined)?.[input]
165
-
166
- if (route.method !== 'WS' && typeof schema === 'object' && schema !== null && !('~standard' in schema))
167
- (hooks as Record<string, unknown>)[input] = validated(inputSchema(input, schema as TSchema))
168
- }
146
+ // The route's input schemas are checked by kay, in the request's locale, not by Elysia.
147
+ if (route.method !== 'WS')
148
+ validatingInputs(hooks, (request, run) => inApiLocale(request, options, run))
169
149
 
170
150
  // Whichever way the module chains its `.ws()` (in a group, a guard or a used plugin), every websocket route is held to its limits.
171
151
  if (hooks && route.method === 'WS')
@@ -271,7 +251,7 @@ export async function serveApi(app: Elysia, modules: ApiModule[], options: Actio
271
251
  // Before the module's own `onError`, so no custom answer to refused input reaches a caller the guards refuse.
272
252
  .onError(async (context) => {
273
253
  // Past the guards, a failing response schema or a handler's own throw is no input to keep from a refused caller.
274
- if ((context.code !== 'VALIDATION' && context.code !== 'INVALID_FILE_TYPE') || guards.length === 0 || admitted.has(context.request))
254
+ if (!(context.error instanceof InputRefusedError) || guards.length === 0 || admitted.has(context.request))
275
255
  return undefined
276
256
 
277
257
  const refusal = await answeringRequest(context.request, async () => inApiLocale(context.request, options, async () => guardsFirst(guards, sharedContext(context.request, () => ({ ...context })), (context as { params?: Record<string, unknown> }).params ?? {}, undefined, options)))
@@ -311,7 +291,7 @@ export async function serveApi(app: Elysia, modules: ApiModule[], options: Actio
311
291
  .onError(({ request, error, code, set }) => {
312
292
  const refused = { request, error, code, set }
313
293
 
314
- return refusedInput(refused, options) ?? reportThrown(refused, options)
294
+ return refusedInput(refused) ?? reportThrown(refused, options)
315
295
  })
316
296
 
317
297
  letGoOfParent(instance, app)
@@ -570,27 +550,15 @@ function carriedOver(set: { status?: number | string, headers: Record<string, un
570
550
  return Object.keys(set.headers).length > 0 && response === given ? undefined : response
571
551
  }
572
552
 
573
- // Input the route's `body`, `query`, `params` or `headers` refused, answered as an action answers it: `{ errors, status }`, a message per field in the request's locale.
553
+ // Input the route's `body`, `query`, `params`, `headers` or `cookie` refused, answered as an action answers it: `{ errors, status }`, a message per field in the request's locale.
574
554
  // A mismatch of the route's own response is the route's bug and is left to the caller.
575
- function refusedInput({ request, error, code, set }: { request: Request, error: unknown, code: unknown, set: { status?: number | string } }, options: ActionOptions): { errors: Record<string, string>, status: 422 } | undefined {
576
- if (code === 'INVALID_FILE_TYPE') {
577
- const field = (error as { property: string }).property.replace(BODY_PREFIX, '')
578
-
579
- set.status = 422
580
-
581
- return { errors: inApiLocale(request, options, () => ({ [field]: kayWord('kay.action.invalidFile') })), status: 422 }
582
- }
583
-
584
- if (code !== 'VALIDATION' || isResponseMismatch(error, code))
555
+ function refusedInput({ error, set }: { request: Request, error: unknown, code: unknown, set: { status?: number | string } }): { errors: Record<string, string>, status: 422 } | undefined {
556
+ if (!(error instanceof InputRefusedError))
585
557
  return undefined
586
558
 
587
- const { validator } = error as ValidationError
588
- const schema = (validator as { schema?: unknown }).schema ?? validator
589
- const errors = inApiLocale(request, options, () => refusedFields(schema, error as ValidationError))
590
-
591
559
  set.status = 422
592
560
 
593
- return { errors, status: 422 }
561
+ return { errors: messagesOf(error.errors), status: 422 }
594
562
  }
595
563
 
596
564
  // Elysia answers a response that fails its schema as validation (422), a client error for what is the route's own bug.
@@ -9,6 +9,7 @@ import type { OwnRoutes } from './dev'
9
9
  import type { GuardRequirement } from './guard-requirement'
10
10
  import type { ServedRoute } from './guards'
11
11
  import type { ImageRouteOptions } from './image'
12
+ import type { KayServer } from './kay-server'
12
13
  import type { Writes } from './kept-pages'
13
14
  import type { MountedApi } from './openapi'
14
15
  import type { Unmatched } from './page-routes'
@@ -79,6 +80,7 @@ import { checkProxy, requestId, requestIdHeader, setRequestIdHeader, trustProxy
79
80
  import { requireProxyKey } from './proxy-key'
80
81
  import { publicCacheRules, servePublic } from './public'
81
82
  import { NOT_PUBLISHING, watchPublishing } from './publishing'
83
+ import { bridgeReceive } from './receive'
82
84
  import { redirectSpelling } from './redirect-spelling'
83
85
  import { redirectStatus, redirectTarget, serveRedirects } from './redirects'
84
86
  import { remoteImages, remotePatterns } from './remote'
@@ -165,6 +167,8 @@ export type LateApp = ReturnType<typeof lateApp>
165
167
 
166
168
  interface BootInput {
167
169
  app: App
170
+ // The route table and the phases, with `app` as the fallback that serves what the table does not.
171
+ kay: KayServer
168
172
  env: ServerEnv
169
173
  project: Project<ServedOptions>
170
174
  setup: PageSetup
@@ -304,22 +308,25 @@ function hostsToAnswer(setting: SecurityConfig | boolean | undefined, site: stri
304
308
  return hosts === false ? undefined : hosts ?? (env.production && site !== undefined ? true : undefined)
305
309
  }
306
310
 
307
- // Who the request is from and whether it may come: the proxy it came through, the server's own mark, the proxy key, the hosts, then the security headers on every answer.
308
- export function trustRequests({ app, env, options, project, served, security, filePaths, setup, mcpAt, mcpKey, metrics, formerMetrics, formerMcp, log, health }: Boot): void {
311
+ // Who the request is from and whether it may come, as the steps of `receive`: the proxy it came through, the server's own mark, the proxy key, the dev hosts, the hosts; then the security headers on every answer.
312
+ // The steps run in kay's pipeline, which Elysia's first `onRequest` hook hands every request to while the routes are not on kay's table.
313
+ export function trustRequests({ app, kay, env, options, project, served, security, filePaths, setup, mcpAt, mcpKey, metrics, formerMetrics, formerMcp, log, health }: Boot): void {
314
+ const { receive } = kay.pipeline.phases
315
+
309
316
  setRequestIdHeader(options.ops?.observe?.requestIdHeader)
310
- trustProxy(app, options.proxy)
317
+ receive.push(trustProxy(options.proxy))
311
318
  defaultCookies(app, cookieDefaults(options.security, env.base))
312
319
  // Before the key check reads the mark, and dropped from the request there, so no handler reads it.
313
- app.onRequest(({ request }) => {
320
+ receive.push((request) => {
314
321
  receiveInternal(request)
315
322
  })
316
- requireProxyKey(app, checkProxy(options.proxy), { root: setup.source.runtimeRoot(project.root), dev: env.dev, exported: env.exported, base: env.base, health: health?.path, endpoint: mcpKey === undefined ? undefined : () => mcpEndpoints(mcpAt, formerMcp, served), metrics: () => [metrics, formerMetrics].flatMap(claim => claim !== undefined && served.holds(claim) ? [claim.path] : []), logRefused: requestRefusalLogger(log), security })
317
- refuseForeignHosts(app, setup.site, security)
318
323
 
324
+ const key = requireProxyKey(checkProxy(options.proxy), { root: setup.source.runtimeRoot(project.root), dev: env.dev, exported: env.exported, base: env.base, health: health?.path, endpoint: mcpKey === undefined ? undefined : () => mcpEndpoints(mcpAt, formerMcp, served), metrics: () => [metrics, formerMetrics].flatMap(claim => claim !== undefined && served.holds(claim) ? [claim.path] : []), logRefused: requestRefusalLogger(log), security })
325
+ const foreign = refuseForeignHosts(setup.site, security)
319
326
  const hosts = hostsToAnswer(options.security, setup.site, env)
320
327
 
321
- if (hosts !== undefined)
322
- refuseUnknownHosts(app, { site: setup.site, hosts, localeHosts: Object.values(setup.i18n?.settings.hosts ?? {}), security, health: health && [health.path, `${env.base}${health.path}`] })
328
+ receive.push(...[key, foreign, hosts === undefined ? undefined : refuseUnknownHosts({ site: setup.site, hosts, localeHosts: Object.values(setup.i18n?.settings.hosts ?? {}), security, health: health && [health.path, `${env.base}${health.path}`] })].filter(step => step !== undefined))
329
+ bridgeReceive(app, (request, server) => kay.pipeline.receive(request, server))
323
330
 
324
331
  if (security)
325
332
  sendSecurityHeaders(app, security, filePaths)