@jini-ai/core 0.7.1 → 0.7.3-next.1

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 (339) hide show
  1. package/README.md +40 -12
  2. package/dist/admin-runtime/admin-api-error.d.ts +68 -0
  3. package/dist/admin-runtime/admin-api-error.js +72 -0
  4. package/dist/admin-runtime/admin-config-error.d.ts +8 -0
  5. package/dist/admin-runtime/admin-config-error.js +11 -0
  6. package/dist/admin-runtime/controller-store.d.ts +20 -0
  7. package/dist/admin-runtime/controller-store.js +32 -0
  8. package/dist/admin-runtime/index.d.ts +13 -0
  9. package/dist/admin-runtime/index.js +12 -0
  10. package/dist/admin-runtime/panel-access.d.ts +88 -0
  11. package/dist/admin-runtime/panel-access.js +76 -0
  12. package/dist/admin-runtime/query-suffix.d.ts +5 -0
  13. package/dist/admin-runtime/query-suffix.js +5 -0
  14. package/dist/agent-handles/element-handles.d.ts +134 -0
  15. package/dist/agent-handles/element-handles.js +45 -0
  16. package/dist/agent-handles/field-descriptor.d.ts +28 -0
  17. package/dist/agent-handles/field-descriptor.js +3 -0
  18. package/dist/agent-handles/handle.d.ts +109 -0
  19. package/dist/agent-handles/handle.js +109 -0
  20. package/dist/agent-handles/index.d.ts +9 -0
  21. package/dist/agent-handles/index.js +6 -0
  22. package/dist/agent-handles/list-handles.d.ts +46 -0
  23. package/dist/agent-handles/list-handles.js +67 -0
  24. package/dist/agent-handles/secret-attrs.d.ts +14 -0
  25. package/dist/agent-handles/secret-attrs.js +13 -0
  26. package/dist/approval-batch-chain.d.ts +45 -0
  27. package/dist/approval-batch-chain.js +75 -0
  28. package/dist/approval.d.ts +33 -14
  29. package/dist/approval.js +57 -43
  30. package/dist/batch-tool-inputs.js +24 -20
  31. package/dist/contracts/admin-module.d.ts +166 -0
  32. package/dist/contracts/admin-module.js +14 -0
  33. package/dist/contracts/agents/definition.d.ts +459 -0
  34. package/dist/contracts/agents/definition.js +2 -0
  35. package/dist/contracts/agents/index.d.ts +7 -0
  36. package/dist/contracts/agents/index.js +2 -0
  37. package/dist/contracts/agents/launch.d.ts +64 -0
  38. package/dist/contracts/agents/launch.js +2 -0
  39. package/dist/contracts/agents/model-catalog.d.ts +213 -0
  40. package/dist/contracts/agents/model-catalog.js +4 -0
  41. package/dist/contracts/agents/native-tool-policy.d.ts +42 -0
  42. package/dist/contracts/agents/native-tool-policy.js +2 -0
  43. package/dist/contracts/ai-trace/capture.d.ts +17 -0
  44. package/dist/contracts/ai-trace/capture.js +43 -0
  45. package/dist/contracts/ai-trace/classify.d.ts +12 -0
  46. package/dist/contracts/ai-trace/classify.js +16 -0
  47. package/dist/contracts/ai-trace/index.d.ts +13 -0
  48. package/dist/contracts/ai-trace/index.js +6 -0
  49. package/dist/contracts/ai-trace/recorder.d.ts +64 -0
  50. package/dist/contracts/ai-trace/recorder.js +283 -0
  51. package/dist/contracts/ai-trace/sinks.d.ts +51 -0
  52. package/dist/contracts/ai-trace/sinks.js +153 -0
  53. package/dist/contracts/ai-trace/types.d.ts +123 -0
  54. package/dist/contracts/ai-trace/types.js +17 -0
  55. package/dist/contracts/ai-trace/usage.d.ts +16 -0
  56. package/dist/contracts/ai-trace/usage.js +45 -0
  57. package/dist/contracts/blob.d.ts +31 -0
  58. package/dist/contracts/blob.js +10 -0
  59. package/dist/contracts/capabilities.d.ts +95 -0
  60. package/dist/contracts/capabilities.js +111 -0
  61. package/dist/contracts/charts.d.ts +75 -0
  62. package/dist/contracts/charts.js +4 -0
  63. package/dist/contracts/env.d.ts +96 -0
  64. package/dist/contracts/env.js +6 -0
  65. package/dist/contracts/events/change-set.d.ts +106 -0
  66. package/dist/contracts/events/change-set.js +2 -0
  67. package/dist/contracts/events/command.d.ts +118 -0
  68. package/dist/contracts/events/command.js +2 -0
  69. package/dist/contracts/events/ports.d.ts +172 -0
  70. package/dist/contracts/events/ports.js +2 -0
  71. package/dist/contracts/events.d.ts +5 -0
  72. package/dist/contracts/events.js +2 -0
  73. package/dist/contracts/forms.d.ts +110 -0
  74. package/dist/contracts/forms.js +4 -0
  75. package/dist/contracts/hosted-mcp/config.d.ts +19 -0
  76. package/dist/contracts/hosted-mcp/record.d.ts +61 -4
  77. package/dist/contracts/mail/email-sender.d.ts +118 -0
  78. package/dist/contracts/mail/email-sender.js +20 -0
  79. package/dist/contracts/mail/smtp-payload.d.ts +32 -0
  80. package/dist/contracts/mail/smtp-payload.js +2 -0
  81. package/dist/contracts/mail.d.ts +2 -0
  82. package/dist/contracts/mail.js +1 -1
  83. package/dist/contracts/observability.d.ts +232 -0
  84. package/dist/contracts/observability.js +27 -0
  85. package/dist/contracts/plugin-sdk.d.ts +186 -0
  86. package/dist/contracts/plugin-sdk.js +39 -0
  87. package/dist/contracts/runtime/command.d.ts +41 -0
  88. package/dist/contracts/runtime/command.js +60 -0
  89. package/dist/contracts/runtime/environment.d.ts +18 -0
  90. package/dist/contracts/runtime/environment.js +26 -0
  91. package/dist/contracts/runtime/file-lock.d.ts +94 -0
  92. package/dist/contracts/runtime/file-lock.js +25 -0
  93. package/dist/contracts/runtime/fs.d.ts +33 -0
  94. package/dist/contracts/runtime/fs.js +2 -0
  95. package/dist/contracts/runtime/http.d.ts +89 -0
  96. package/dist/contracts/runtime/http.js +2 -0
  97. package/dist/contracts/runtime/platform.d.ts +3 -0
  98. package/dist/contracts/runtime/platform.js +2 -0
  99. package/dist/contracts/runtime/process.d.ts +40 -0
  100. package/dist/contracts/runtime/process.js +31 -0
  101. package/dist/contracts/runtime/reader.d.ts +11 -0
  102. package/dist/contracts/runtime/reader.js +2 -0
  103. package/dist/contracts/runtime/terminal.d.ts +99 -0
  104. package/dist/contracts/runtime/terminal.js +2 -0
  105. package/dist/contracts/runtime/testing.d.ts +84 -0
  106. package/dist/contracts/runtime/testing.js +116 -0
  107. package/dist/contracts/runtime.d.ts +10 -0
  108. package/dist/contracts/runtime.js +10 -0
  109. package/dist/contracts/server/api-error.d.ts +43 -0
  110. package/dist/contracts/server/api-error.js +49 -0
  111. package/dist/contracts/server/auth.d.ts +20 -0
  112. package/dist/contracts/server/auth.js +21 -0
  113. package/dist/contracts/server/conformance.d.ts +25 -0
  114. package/dist/contracts/server/conformance.js +50 -0
  115. package/dist/contracts/server/json-route.d.ts +176 -0
  116. package/dist/contracts/server/json-route.js +155 -0
  117. package/dist/contracts/server/middleware.d.ts +35 -0
  118. package/dist/contracts/server/middleware.js +56 -0
  119. package/dist/contracts/server/origin.d.ts +44 -0
  120. package/dist/contracts/server/origin.js +32 -0
  121. package/dist/contracts/server/query.d.ts +16 -0
  122. package/dist/contracts/server/query.js +69 -0
  123. package/dist/contracts/server/rate-limit.d.ts +20 -0
  124. package/dist/contracts/server/rate-limit.js +8 -0
  125. package/dist/contracts/server/request-body.d.ts +26 -0
  126. package/dist/contracts/server/request-body.js +82 -0
  127. package/dist/contracts/server/result.d.ts +17 -0
  128. package/dist/contracts/server/result.js +5 -0
  129. package/dist/contracts/server/route-table.d.ts +54 -0
  130. package/dist/contracts/server/route-table.js +119 -0
  131. package/dist/contracts/server/same-origin-write.d.ts +18 -0
  132. package/dist/contracts/server/same-origin-write.js +31 -0
  133. package/dist/contracts/server/security-headers.d.ts +30 -0
  134. package/dist/contracts/server/security-headers.js +35 -0
  135. package/dist/contracts/server/sse.d.ts +82 -0
  136. package/dist/contracts/server/sse.js +103 -0
  137. package/dist/contracts/server/testing.d.ts +59 -0
  138. package/dist/contracts/server/testing.js +68 -0
  139. package/dist/contracts/server/verified-origin/configured-origin.d.ts +37 -0
  140. package/dist/contracts/server/verified-origin/configured-origin.js +103 -0
  141. package/dist/contracts/server/verified-origin/index.d.ts +7 -0
  142. package/dist/contracts/server/verified-origin/index.js +6 -0
  143. package/dist/contracts/server/verified-origin/loopback-host.d.ts +9 -0
  144. package/dist/contracts/server/verified-origin/loopback-host.js +17 -0
  145. package/dist/contracts/server/verified-origin/origin.d.ts +64 -0
  146. package/dist/contracts/server/verified-origin/origin.js +162 -0
  147. package/dist/contracts/server/verified-origin/ports.d.ts +38 -0
  148. package/dist/contracts/server/verified-origin/ports.js +2 -0
  149. package/dist/contracts/server/verified-origin/repo.memory.d.ts +32 -0
  150. package/dist/contracts/server/verified-origin/repo.memory.js +34 -0
  151. package/dist/contracts/server/verified-origin/site-path.d.ts +113 -0
  152. package/dist/contracts/server/verified-origin/site-path.js +188 -0
  153. package/dist/contracts/server/verified-origin/types.d.ts +33 -0
  154. package/dist/contracts/server/verified-origin/types.js +30 -0
  155. package/dist/contracts/server.d.ts +46 -2
  156. package/dist/contracts/server.js +17 -3
  157. package/dist/contracts/storage/kernel.d.ts +86 -0
  158. package/dist/contracts/storage/kernel.js +38 -0
  159. package/dist/contracts/storage/migration.d.ts +32 -0
  160. package/dist/contracts/storage/migration.js +2 -0
  161. package/dist/contracts/storage/rows.d.ts +33 -0
  162. package/dist/contracts/storage/rows.js +42 -0
  163. package/dist/contracts/storage/sqlite.d.ts +113 -0
  164. package/dist/contracts/storage/sqlite.js +8 -0
  165. package/dist/contracts/storage/values.d.ts +25 -0
  166. package/dist/contracts/storage/values.js +25 -0
  167. package/dist/contracts/storage.d.ts +8 -0
  168. package/dist/contracts/storage.js +6 -0
  169. package/dist/contracts/vault/invariants.d.ts +26 -0
  170. package/dist/contracts/vault/invariants.js +49 -0
  171. package/dist/contracts/vault.d.ts +1 -0
  172. package/dist/contracts/vault.js +1 -1
  173. package/dist/env/coercers.d.ts +21 -0
  174. package/dist/env/coercers.js +68 -0
  175. package/dist/env/describe-env-for-diagnostics.d.ts +16 -0
  176. package/dist/env/describe-env-for-diagnostics.js +23 -0
  177. package/dist/env/format-env-issue.d.ts +13 -0
  178. package/dist/env/format-env-issue.js +22 -0
  179. package/dist/env/parse-env.d.ts +24 -0
  180. package/dist/env/parse-env.js +102 -0
  181. package/dist/env/value-echo.d.ts +17 -0
  182. package/dist/env/value-echo.js +42 -0
  183. package/dist/errors/approved-cause.d.ts +36 -0
  184. package/dist/errors/approved-cause.js +17 -0
  185. package/dist/errors/bindings.d.ts +61 -0
  186. package/dist/errors/bindings.js +57 -0
  187. package/dist/errors/catalog.d.ts +84 -0
  188. package/dist/errors/catalog.js +151 -0
  189. package/dist/errors/disclosure.d.ts +48 -0
  190. package/dist/errors/disclosure.js +27 -0
  191. package/dist/errors/error-id.d.ts +26 -0
  192. package/dist/errors/error-id.js +23 -0
  193. package/dist/errors/idioms.d.ts +73 -0
  194. package/dist/errors/idioms.js +85 -0
  195. package/dist/errors/incident-text.d.ts +16 -0
  196. package/dist/errors/incident-text.js +77 -0
  197. package/dist/errors/reporter.d.ts +94 -0
  198. package/dist/errors/reporter.js +152 -0
  199. package/dist/errors/sentences.d.ts +68 -0
  200. package/dist/errors/sentences.js +93 -0
  201. package/dist/errors/testing.d.ts +50 -0
  202. package/dist/errors/testing.js +44 -0
  203. package/dist/fetch/cache.d.ts +12 -5
  204. package/dist/fetch/cache.js +46 -47
  205. package/dist/fetch/index.d.ts +1 -1
  206. package/dist/fetch/loader-read.d.ts +6 -2
  207. package/dist/fetch/loader-read.js +4 -4
  208. package/dist/format-error-for-log.d.ts +15 -0
  209. package/dist/format-error-for-log.js +55 -0
  210. package/dist/host-read-vocabulary.d.ts +47 -0
  211. package/dist/host-read-vocabulary.js +44 -0
  212. package/dist/index.d.ts +5 -1
  213. package/dist/index.js +4 -0
  214. package/dist/list-page.d.ts +93 -0
  215. package/dist/list-page.js +154 -0
  216. package/dist/model-facing-tool-errors.d.ts +67 -5
  217. package/dist/model-facing-tool-errors.js +155 -19
  218. package/dist/net/endpoint-policy.d.ts +39 -0
  219. package/dist/net/endpoint-policy.js +218 -0
  220. package/dist/net/fetch-timeouts.d.ts +38 -0
  221. package/dist/net/fetch-timeouts.js +31 -0
  222. package/dist/net/index.d.ts +4 -0
  223. package/dist/net/index.js +4 -0
  224. package/dist/net/loopback.d.ts +13 -0
  225. package/dist/net/loopback.js +39 -0
  226. package/dist/optimistic-concurrency.d.ts +183 -0
  227. package/dist/optimistic-concurrency.js +222 -0
  228. package/dist/primitives/errors.d.ts +9 -0
  229. package/dist/primitives/errors.js +12 -0
  230. package/dist/primitives/ids.d.ts +0 -2
  231. package/dist/primitives/ids.js +1 -4
  232. package/dist/primitives/index.d.ts +3 -0
  233. package/dist/primitives/index.js +2 -0
  234. package/dist/primitives/logger.d.ts +36 -1
  235. package/dist/primitives/logger.js +125 -9
  236. package/dist/primitives/node-shape.d.ts +24 -0
  237. package/dist/primitives/node-shape.js +21 -0
  238. package/dist/primitives/time.d.ts +9 -2
  239. package/dist/primitives/time.js +4 -3
  240. package/dist/provider-registry.js +26 -20
  241. package/dist/records.d.ts +40 -7
  242. package/dist/records.js +37 -3
  243. package/dist/redact.d.ts +1 -84
  244. package/dist/redact.js +2 -826
  245. package/dist/redaction-collectors.d.ts +7 -0
  246. package/dist/redaction-collectors.js +152 -0
  247. package/dist/redaction-exact-secrets.d.ts +14 -0
  248. package/dist/redaction-exact-secrets.js +115 -0
  249. package/dist/redaction-labels.d.ts +14 -0
  250. package/dist/redaction-labels.js +156 -0
  251. package/dist/redaction-patterns.d.ts +54 -0
  252. package/dist/redaction-patterns.js +178 -0
  253. package/dist/redaction-spans.d.ts +31 -0
  254. package/dist/redaction-spans.js +83 -0
  255. package/dist/registration-kit.d.ts +1 -1
  256. package/dist/revision-conflict-error.d.ts +18 -0
  257. package/dist/revision-conflict-error.js +20 -0
  258. package/dist/secret-shapes.d.ts +50 -0
  259. package/dist/secret-shapes.js +105 -0
  260. package/dist/settings/agent-tools.js +22 -8
  261. package/dist/settings/agent-value-write-tools.d.ts +4 -1
  262. package/dist/settings/agent-value-write-tools.js +7 -6
  263. package/dist/settings/agent-writable-preferences.d.ts +3 -1
  264. package/dist/settings/agent-writable-preferences.js +1 -1
  265. package/dist/settings/agent-write-denylist.d.ts +7 -4
  266. package/dist/settings/agent-write-denylist.js +1 -1
  267. package/dist/settings/{express/cms-adapter.d.ts → cms-adapter.d.ts} +3 -2
  268. package/dist/settings/{express/cms-adapter.js → cms-adapter.js} +21 -11
  269. package/dist/settings/definitions-dispatch.js +3 -1
  270. package/dist/settings/ensure-definitions.js +3 -1
  271. package/dist/settings/errors.d.ts +1 -13
  272. package/dist/settings/errors.js +2 -15
  273. package/dist/settings/index.d.ts +11 -2
  274. package/dist/settings/index.js +10 -2
  275. package/dist/settings/purge-service.js +63 -86
  276. package/dist/settings/{express/contracts.d.ts → route-policy.d.ts} +53 -47
  277. package/dist/settings/{express/shared.js → route-policy.js} +1 -16
  278. package/dist/settings/settings.d.ts +19 -11
  279. package/dist/settings/settings.js +9 -11
  280. package/dist/settings/tool-registrations.d.ts +3 -3
  281. package/dist/settings/tool-registrations.js +130 -125
  282. package/dist/settings/types.d.ts +1 -1
  283. package/dist/settings/write-definition-rename.d.ts +37 -0
  284. package/dist/settings/write-definition-rename.js +119 -0
  285. package/dist/settings/write-definition-retype.d.ts +61 -0
  286. package/dist/settings/write-definition-retype.js +109 -0
  287. package/dist/settings/write-definition-status.d.ts +81 -0
  288. package/dist/settings/write-definition-status.js +121 -0
  289. package/dist/settings/write-reset.d.ts +34 -0
  290. package/dist/settings/write-reset.js +73 -0
  291. package/dist/settings/write-service.d.ts +16 -287
  292. package/dist/settings/write-service.js +49 -681
  293. package/dist/settings/write-value-revisions.d.ts +68 -0
  294. package/dist/settings/write-value-revisions.js +124 -0
  295. package/dist/settings/write-values.d.ts +96 -0
  296. package/dist/settings/write-values.js +83 -0
  297. package/dist/surface-exchanges.d.ts +2 -2
  298. package/dist/text/dictionary-translator.d.ts +19 -0
  299. package/dist/text/dictionary-translator.js +14 -0
  300. package/dist/text/format-byte-size.d.ts +25 -0
  301. package/dist/text/format-byte-size.js +25 -0
  302. package/dist/text/format-timestamp.d.ts +22 -0
  303. package/dist/text/format-timestamp.js +57 -0
  304. package/dist/text/index.d.ts +12 -0
  305. package/dist/text/index.js +9 -0
  306. package/dist/text/is-abort-error.d.ts +5 -0
  307. package/dist/text/is-abort-error.js +5 -0
  308. package/dist/text/mime.d.ts +5 -0
  309. package/dist/text/mime.js +21 -0
  310. package/dist/text/redact-urls.d.ts +7 -0
  311. package/dist/text/redact-urls.js +5 -0
  312. package/dist/text/resolve-active-tab-id.d.ts +13 -0
  313. package/dist/text/resolve-active-tab-id.js +15 -0
  314. package/dist/text/sanitize-untrusted-text.d.ts +1 -1
  315. package/dist/text/sanitize-untrusted-text.js +2 -1
  316. package/dist/text/tagged-text-suppression.d.ts +103 -0
  317. package/dist/text/tagged-text-suppression.js +143 -0
  318. package/dist/text/template-i18n.d.ts +37 -0
  319. package/dist/text/template-i18n.js +48 -0
  320. package/dist/tool-call-text.d.ts +59 -0
  321. package/dist/tool-call-text.js +62 -0
  322. package/dist/tool-input-envelope.js +8 -4
  323. package/dist/tool-input-normalization.js +8 -1
  324. package/dist/tool-input-repairs.d.ts +58 -0
  325. package/dist/tool-input-repairs.js +154 -0
  326. package/dist/tool-tokens.js +1 -1
  327. package/dist/user-facing-error.d.ts +1 -1
  328. package/dist/user-facing-error.js +3 -1
  329. package/package.json +234 -13
  330. package/dist/settings/express/contracts.js +0 -2
  331. package/dist/settings/express/http-request.d.ts +0 -33
  332. package/dist/settings/express/http-request.js +0 -50
  333. package/dist/settings/express/http.d.ts +0 -10
  334. package/dist/settings/express/http.js +0 -196
  335. package/dist/settings/express/index.d.ts +0 -5
  336. package/dist/settings/express/index.js +0 -4
  337. package/dist/settings/express/shared.d.ts +0 -68
  338. package/dist/settings/express/stream.d.ts +0 -24
  339. package/dist/settings/express/stream.js +0 -171
@@ -0,0 +1,155 @@
1
+ import { statusForError } from './api-error.js';
2
+ import { guardSameOrigin } from './origin.js';
3
+ import { readQuery } from './query.js';
4
+ import { readJsonBody } from './request-body.js';
5
+ /**
6
+ * Thrown by a route's `handle` — or by anything it calls, at any depth — to bypass the SEC-005
7
+ * redaction below with an error the throwing code has already decided is safe for the caller
8
+ * to see. Prefer returning `err(...)` from `handle` when the failure is anticipated at that point;
9
+ * this class is for the same kind of failure discovered a level deeper, inside an awaited call
10
+ * `handle` did not wrap in its own `try`.
11
+ *
12
+ * Not a way to defeat SEC-005: the only way to reach the branch that reads this class is for code to
13
+ * construct one itself, naming the exact error — code and message — it is choosing to disclose.
14
+ * Any thrown value that is not this class (including a plain `Error` with an actionable-looking
15
+ * message) still redacts; nothing here widens what a route can leak by accident.
16
+ */
17
+ export class ClientFacingError extends Error {
18
+ apiError;
19
+ constructor({ apiError }, _optional = {}) {
20
+ super(apiError.message);
21
+ this.name = 'ClientFacingError';
22
+ this.apiError = apiError;
23
+ }
24
+ }
25
+ /**
26
+ * Combines required route fields and optional settings into a fresh spec while pinning its generic
27
+ * parameters at the definition site so callers do not have to repeat them. Optional settings take
28
+ * precedence. Never mutates either argument.
29
+ * @complexity O(1) time/space for the fixed spec fields.
30
+ */
31
+ export function defineJsonRoute(requiredArgs, optionalArgs = {}) {
32
+ return { ...requiredArgs, ...optionalArgs };
33
+ }
34
+ /** Statuses whose response must not carry a body; the web `Response` constructor throws on one with a body. */
35
+ const NULL_BODY_STATUSES = new Set([204, 205, 304]);
36
+ /**
37
+ * A JSON response with Express's `res.json` content type, so clients see the same header. A null-body
38
+ * status (204, 205, 304) gets no body and no content type.
39
+ */
40
+ export function jsonResponse({ status, body }, { headers = {} } = {}) {
41
+ if (NULL_BODY_STATUSES.has(status))
42
+ return new Response(null, { status, headers });
43
+ const text = JSON.stringify(body);
44
+ // The length is stated here because only the producer knows the body is a finished string: a host that
45
+ // writes a `Response` cannot tell it from a stream without buffering, and Express sent this header too.
46
+ return new Response(text, { status, headers: { 'content-type': 'application/json; charset=utf-8', 'content-length': String(new TextEncoder().encode(text).byteLength), ...headers } });
47
+ }
48
+ const errorAnswer = ({ error }) => jsonResponse({ status: statusForError({ error }), body: { error } });
49
+ /**
50
+ * Builds the one `ServerRoute` for `spec`. The route's parse and handle functions operate on
51
+ * `RouteInputContext` and `Deps`, so they are unit testable without a server. A host context is
52
+ * required only for routes that opt into the same-origin guard or that can throw unanticipated errors.
53
+ */
54
+ export function jsonRoute({ spec, deps, reportInternalError }, { host } = {}) {
55
+ return {
56
+ method: spec.method.toUpperCase(),
57
+ path: spec.path,
58
+ handler: ({ request, params, locals = {} }) => answerJsonRoute({ spec, deps, reportInternalError, request, params: { ...params }, locals }, { host }),
59
+ };
60
+ }
61
+ async function answerJsonRoute(call, { host }) {
62
+ try {
63
+ return await routeAnswer(call, { host });
64
+ }
65
+ catch (error) {
66
+ return exceptionAnswer({ call, error }, { host });
67
+ }
68
+ }
69
+ async function readRawInput({ spec, request, params }) {
70
+ const query = readQuery({ request });
71
+ if (request.method === 'GET' || request.method === 'HEAD')
72
+ return { ok: true, value: { body: {}, query, params } };
73
+ const body = await readJsonBody({ request }, spec.maxBodyBytes === undefined ? {} : { maxBytes: spec.maxBodyBytes });
74
+ return body.ok ? { ok: true, value: { body: body.value, query, params } } : body;
75
+ }
76
+ /**
77
+ * The same-origin check for a hand-built route (an SSE stream, an upload) that is not a `jsonRoute` and so does not
78
+ * get `requireSameOrigin`: the host's origin policy is asked with the request's `host`, `origin` and `sec-fetch-site`
79
+ * headers, and a refusal is the standard 403 `Response`. Returns `undefined` when the request may proceed, so the
80
+ * route's first line is `const refused = sameOriginRefusal(...); if (refused) return refused;`.
81
+ */
82
+ export function sameOriginRefusal({ request, origin }, _optional = {}) {
83
+ const header = (name) => request.headers.get(name) ?? undefined;
84
+ const verdict = guardSameOrigin({ req: { headers: { host: header('host'), origin: header('origin'), 'sec-fetch-site': header('sec-fetch-site') } }, origin });
85
+ return verdict.ok ? undefined : errorAnswer({ error: verdict.error });
86
+ }
87
+ function originRefusal({ spec, request }, { host }) {
88
+ if (!spec.requireSameOrigin)
89
+ return undefined;
90
+ if (!host)
91
+ throw new Error('same-origin adapter context is required');
92
+ return sameOriginRefusal({ request, origin: host });
93
+ }
94
+ // The route chooses where authorization occurs: reads may authorize before validation,
95
+ // while writes must reject an inconsistent tenant target before asking for a permission.
96
+ function makeAuthorize({ spec, deps, context }) {
97
+ return async ({ permission, entityType }) => {
98
+ if (!spec.ports?.authorize)
99
+ throw new Error('JSON route authorizer is required');
100
+ await spec.ports.authorize({ context, deps, permission, entityType });
101
+ };
102
+ }
103
+ function authenticate({ call, raw }) {
104
+ const { spec, deps, request, locals } = call;
105
+ return spec.ports?.authenticate ? spec.ports.authenticate({ raw, request, locals, deps }) : undefined;
106
+ }
107
+ async function routeAnswer(call, { host }) {
108
+ const { spec, deps, request } = call;
109
+ const raw = await readRawInput(call);
110
+ if (!raw.ok)
111
+ return errorAnswer({ error: raw.error });
112
+ if (spec.ports?.workspace)
113
+ await spec.ports.workspace({ raw: raw.value, deps });
114
+ const refused = originRefusal(call, { host });
115
+ if (refused)
116
+ return refused;
117
+ const context = await authenticate({ call, raw: raw.value });
118
+ const parsed = spec.parse(raw.value);
119
+ if (!parsed.ok)
120
+ return errorAnswer({ error: parsed.error });
121
+ const authorize = makeAuthorize({ spec, deps, context });
122
+ const result = await spec.handle({ input: parsed.value, deps, context, authorize }, { signal: request.signal });
123
+ return finalAnswer({ spec, result, request });
124
+ }
125
+ function finalAnswer({ spec, result, request }) {
126
+ // Disconnect comes from `request.signal`, which the adapter aborts on the response's close,
127
+ // never on the request body finishing. Aborted means the client was already gone before any
128
+ // answer: serializing one now is wasted work and would turn a benign disconnect into a false
129
+ // internal error if the socket rejects the write.
130
+ if (request.signal.aborted)
131
+ return new Response(null, { status: 499 });
132
+ return result.ok ? jsonResponse({ status: spec.successStatus ?? 200, body: result.value }) : errorAnswer({ error: result.error });
133
+ }
134
+ async function exceptionAnswer({ call, error }, { host }) {
135
+ const { spec, request } = call;
136
+ // An explicit host error port owns exception classification and the answer, including its
137
+ // guard rejections. Hosts without it keep the SEC-005 policy below.
138
+ if (spec.ports?.onError)
139
+ return spec.ports.onError({ error, request });
140
+ // A route (or something it called) already classified this failure as safe to disclose, so it is
141
+ // sent verbatim at its own status and never routed to the SEC-005 sink below.
142
+ if (error instanceof ClientFacingError)
143
+ return errorAnswer({ error: error.apiError });
144
+ // SEC-005. This catch exists for exceptions no route anticipated, which makes it precisely the
145
+ // path most likely to be holding something private: a driver error naming a database file, a
146
+ // connection string, a credential a provider echoed back. The real error reaches the operator
147
+ // through the sink, correlated to what the caller was told by the request ID.
148
+ const apiError = call.reportInternalError({
149
+ report: { method: spec.method, path: spec.path, error },
150
+ logSource: `${spec.method.toUpperCase()} ${spec.path}`,
151
+ message: 'The server could not finish this request. Check whether your change was saved, then copy the request ID and report this problem.',
152
+ }, { onInternalError: host?.onInternalError });
153
+ return errorAnswer({ error: apiError });
154
+ }
155
+ //# sourceMappingURL=json-route.js.map
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @file Middleware decorator for the `Server` contract.
3
+ *
4
+ * Why a decorator instead of `Server.use`: middleware wraps the routes registered THROUGH it, so
5
+ * which routes a gate covers is decided by where they are registered, never by registration order
6
+ * against a framework's layer stack. That keeps the `Server` contract one method wide and makes
7
+ * an exemption explicit (`exemptPaths`) instead of an accident of mount order.
8
+ */
9
+ import type { Server, ServerMiddleware, ServerRoute } from '../server.js';
10
+ /**
11
+ * Returns a `Server` that runs `middleware` (in array order) in front of every route registered
12
+ * through it whose path is under `pathPrefix`, except routes whose registered path is listed in
13
+ * `exemptPaths` (compared against the route PATTERN, so a mount prefix can never silently turn an
14
+ * exemption off). Routes registered directly on the inner `server` are untouched.
15
+ * @throws From a route's handler when a middleware calls `next()` twice for one request.
16
+ */
17
+ export declare function withServerMiddleware({ server, middleware }: {
18
+ readonly server: Server;
19
+ readonly middleware: readonly ServerMiddleware[];
20
+ }, { pathPrefix, exemptPaths }?: {
21
+ readonly pathPrefix?: string;
22
+ readonly exemptPaths?: readonly string[];
23
+ }): Server;
24
+ /**
25
+ * Returns `route` with `middleware` (in array order) in front of its handler: the per-route form of
26
+ * {@link withServerMiddleware}, for a route group that must carry its own gates so a host cannot mount the
27
+ * route without them (it never sees the `Server` the group is mounted on). Method, path and `locals` sharing
28
+ * behave as in `withServerMiddleware`; the input route is not modified.
29
+ * @throws From the route's handler when a middleware calls `next()` twice for one request.
30
+ */
31
+ export declare function withRouteMiddleware({ route, middleware }: {
32
+ readonly route: ServerRoute;
33
+ readonly middleware: readonly ServerMiddleware[];
34
+ }, _optional?: Record<string, never>): ServerRoute;
35
+ //# sourceMappingURL=middleware.d.ts.map
@@ -0,0 +1,56 @@
1
+ function coversPath({ path, pathPrefix }) {
2
+ if (pathPrefix === '/' || pathPrefix === '')
3
+ return true;
4
+ const prefix = pathPrefix.endsWith('/') ? pathPrefix.slice(0, -1) : pathPrefix;
5
+ return path === prefix || path.startsWith(`${prefix}/`);
6
+ }
7
+ /**
8
+ * Returns a `Server` that runs `middleware` (in array order) in front of every route registered
9
+ * through it whose path is under `pathPrefix`, except routes whose registered path is listed in
10
+ * `exemptPaths` (compared against the route PATTERN, so a mount prefix can never silently turn an
11
+ * exemption off). Routes registered directly on the inner `server` are untouched.
12
+ * @throws From a route's handler when a middleware calls `next()` twice for one request.
13
+ */
14
+ export function withServerMiddleware({ server, middleware }, { pathPrefix = '/', exemptPaths = [] } = {}) {
15
+ return {
16
+ route(route) {
17
+ if (!coversPath({ path: route.path, pathPrefix }) || exemptPaths.includes(route.path)) {
18
+ server.route(route);
19
+ return;
20
+ }
21
+ server.route(withRouteMiddleware({ route, middleware }));
22
+ },
23
+ };
24
+ }
25
+ /**
26
+ * Returns `route` with `middleware` (in array order) in front of its handler: the per-route form of
27
+ * {@link withServerMiddleware}, for a route group that must carry its own gates so a host cannot mount the
28
+ * route without them (it never sees the `Server` the group is mounted on). Method, path and `locals` sharing
29
+ * behave as in `withServerMiddleware`; the input route is not modified.
30
+ * @throws From the route's handler when a middleware calls `next()` twice for one request.
31
+ */
32
+ export function withRouteMiddleware({ route, middleware }, _optional = {}) {
33
+ return { ...route, handler: (args) => runChain({ route, middleware, args }) };
34
+ }
35
+ /** Runs `middleware[index..]` and then the route's handler, sharing one `locals` object per request. */
36
+ function runChain({ route, middleware, args }) {
37
+ const { request, params, client } = args;
38
+ const locals = args.locals ?? {};
39
+ const peer = client ? { client } : {};
40
+ const routeInfo = { method: route.method, path: route.path };
41
+ const run = async (index) => {
42
+ const current = middleware[index];
43
+ if (!current)
44
+ return route.handler({ request, params, locals, ...peer });
45
+ let called = false;
46
+ const next = () => {
47
+ if (called)
48
+ throw new Error(`A middleware in front of ${route.method} ${route.path} called next() twice.`);
49
+ called = true;
50
+ return run(index + 1);
51
+ };
52
+ return current({ request, params, locals, route: routeInfo, ...peer, next });
53
+ };
54
+ return run(0);
55
+ }
56
+ //# sourceMappingURL=middleware.js.map
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @file Same-origin security guard: wraps the host's origin policy in the `Result` pipeline so a route
3
+ * host can treat an origin failure the same as a parse/handle failure.
4
+ */
5
+ import { type OriginValidationEnvConfig, type OriginValidationLoggerPort, type RequestWithOriginHeaders } from '../../origin-validation.js';
6
+ import { type Result } from './result.js';
7
+ /** Decides whether a request comes from one of the host's own pages. The host injects it, and tests pass a fake. */
8
+ export interface SameOriginPolicyPort {
9
+ isSameOrigin(required: {
10
+ readonly req: RequestWithOriginHeaders;
11
+ }, optional?: Record<string, never>): boolean;
12
+ }
13
+ /** What a route host hands every same-origin-guarded route. */
14
+ export interface OriginContext {
15
+ readonly originPolicy: SameOriginPolicyPort;
16
+ }
17
+ /**
18
+ * The standard local-daemon policy: loopback/bind host, the resolved port, and the host's allow-list env var.
19
+ * `port` is read on every call, because the listener binds after the routes are built.
20
+ *
21
+ * `env` is the host-supplied environment; the host also names the bind-host, allowed-origin and web-port vars.
22
+ *
23
+ * Present because a host can inject its own environment, and that injection already reaches
24
+ * the origin-guard *middleware* — which is handed an explicit `env`. Without the same seam here,
25
+ * the two halves of one decision read two different environments: the middleware admits an origin
26
+ * the host configured and the per-route guard then rejects it, or a bind host the host never set
27
+ * decides what counts as same-origin.
28
+ */
29
+ export declare function createLocalSameOriginPolicy(required: {
30
+ readonly port: () => number;
31
+ readonly env: Readonly<Record<string, string | undefined>>;
32
+ readonly config: OriginValidationEnvConfig;
33
+ }, optional?: {
34
+ readonly logger?: OriginValidationLoggerPort;
35
+ }): SameOriginPolicyPort;
36
+ /**
37
+ * Asks the host's origin policy and folds a refusal into the same error-handling pipeline as
38
+ * parse/handle failures.
39
+ */
40
+ export declare function guardSameOrigin({ req, origin }: {
41
+ readonly req: RequestWithOriginHeaders;
42
+ readonly origin: OriginContext;
43
+ }, _optional?: Record<string, never>): Result<void>;
44
+ //# sourceMappingURL=origin.d.ts.map
@@ -0,0 +1,32 @@
1
+ /**
2
+ * @file Same-origin security guard: wraps the host's origin policy in the `Result` pipeline so a route
3
+ * host can treat an origin failure the same as a parse/handle failure.
4
+ */
5
+ import { isLocalSameOrigin } from '../../origin-validation.js';
6
+ import { err, ok } from './result.js';
7
+ /**
8
+ * The standard local-daemon policy: loopback/bind host, the resolved port, and the host's allow-list env var.
9
+ * `port` is read on every call, because the listener binds after the routes are built.
10
+ *
11
+ * `env` is the host-supplied environment; the host also names the bind-host, allowed-origin and web-port vars.
12
+ *
13
+ * Present because a host can inject its own environment, and that injection already reaches
14
+ * the origin-guard *middleware* — which is handed an explicit `env`. Without the same seam here,
15
+ * the two halves of one decision read two different environments: the middleware admits an origin
16
+ * the host configured and the per-route guard then rejects it, or a bind host the host never set
17
+ * decides what counts as same-origin.
18
+ */
19
+ export function createLocalSameOriginPolicy(required, optional = {}) {
20
+ return { isSameOrigin: ({ req }) => isLocalSameOrigin({ req, port: required.port(), env: required.env, config: required.config }, optional) };
21
+ }
22
+ /**
23
+ * Asks the host's origin policy and folds a refusal into the same error-handling pipeline as
24
+ * parse/handle failures.
25
+ */
26
+ export function guardSameOrigin({ req, origin }, _optional = {}) {
27
+ if (origin.originPolicy.isSameOrigin({ req }))
28
+ return ok({ value: undefined });
29
+ const error = { code: 'FORBIDDEN', message: 'cross-origin request rejected' };
30
+ return err({ error });
31
+ }
32
+ //# sourceMappingURL=origin.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @file Query-string parsing shaped like the Express 4 `req.query`, on a web `Request`.
3
+ */
4
+ /**
5
+ * The query string in the shapes the Express 4 host's `req.query` gave routes, so a converted
6
+ * route's existing validation sees the same values: one value → string; a repeated key, `name[]`
7
+ * or `name[i]` (i ≤ 20), in any mix → `string[]` in qs's order; any other bracketed key
8
+ * (`a[b]=1`, `a[21]=1`) → a non-string, non-list value, so a route that requires a string or a
9
+ * list of strings still refuses it instead of reading it as absent. Nested values are not parsed:
10
+ * no Jini route reads them. Built from entries, so `__proto__` is a plain key.
11
+ * @complexity O(n) in query parameters.
12
+ */
13
+ export declare function readQuery({ request }: {
14
+ readonly request: Request;
15
+ }, _optional?: Record<string, never>): Record<string, unknown>;
16
+ //# sourceMappingURL=query.d.ts.map
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @file Query-string parsing shaped like the Express 4 `req.query`, on a web `Request`.
3
+ */
4
+ /** Stands in for what `qs` turned a bracketed key into (`a[b]=1` → an object): not a string, so a route's "must be a string" check still refuses it. */
5
+ const BRACKETED_QUERY_VALUE = Object.freeze({});
6
+ /** qs's default `arrayLimit`: `a[20]=x` is still a list index, `a[21]=x` makes `a` an object. */
7
+ const MAX_QUERY_LIST_INDEX = 20;
8
+ /** The list index a bracket suffix names (`[]` is index 0, as in qs), or undefined for any other suffix. */
9
+ function listIndex(suffix) {
10
+ if (suffix === '[]')
11
+ return 0;
12
+ // qs takes only a canonical number as an index: `a[01]` is an object key, like `a[b]`.
13
+ const digits = /^\[(0|[1-9]\d*)\]$/.exec(suffix)?.[1];
14
+ const index = digits === undefined ? Number.NaN : Number(digits);
15
+ return index <= MAX_QUERY_LIST_INDEX ? index : undefined;
16
+ }
17
+ /** qs's merge of a plain `name=value` into what the key already holds. */
18
+ function withPlainValue(previous, value) {
19
+ if (previous === undefined)
20
+ return value;
21
+ if (typeof previous === 'string')
22
+ return [previous, value];
23
+ if (Array.isArray(previous))
24
+ previous.push(value);
25
+ return previous;
26
+ }
27
+ /**
28
+ * qs's merge of `name[index]=value`: a free slot takes the value, a taken one appends it, and a
29
+ * plain value already there comes first. Holes are compacted at the end, so only order matters.
30
+ */
31
+ function withListValue(previous, { index, value }) {
32
+ if (previous !== undefined && typeof previous !== 'string' && !Array.isArray(previous))
33
+ return previous;
34
+ const list = typeof previous === 'string' ? [previous] : (previous ?? []);
35
+ const slot = typeof previous === 'string' ? index + 1 : index;
36
+ if (slot in list)
37
+ list.push(value);
38
+ else
39
+ list[slot] = value;
40
+ return list;
41
+ }
42
+ function addQueryValue({ query, key, value }) {
43
+ const bracket = key.indexOf('[');
44
+ if (bracket <= 0) {
45
+ query.set(key, withPlainValue(query.get(key), value));
46
+ return;
47
+ }
48
+ const name = key.slice(0, bracket);
49
+ const index = listIndex(key.slice(bracket));
50
+ // Any other bracketed key (`a[b]`, `a[0][b]`, `a[21]`) made `a` an object in qs, whatever came before.
51
+ query.set(name, index === undefined ? BRACKETED_QUERY_VALUE : withListValue(query.get(name), { index, value }));
52
+ }
53
+ /**
54
+ * The query string in the shapes the Express 4 host's `req.query` gave routes, so a converted
55
+ * route's existing validation sees the same values: one value → string; a repeated key, `name[]`
56
+ * or `name[i]` (i ≤ 20), in any mix → `string[]` in qs's order; any other bracketed key
57
+ * (`a[b]=1`, `a[21]=1`) → a non-string, non-list value, so a route that requires a string or a
58
+ * list of strings still refuses it instead of reading it as absent. Nested values are not parsed:
59
+ * no Jini route reads them. Built from entries, so `__proto__` is a plain key.
60
+ * @complexity O(n) in query parameters.
61
+ */
62
+ export function readQuery({ request }, _optional = {}) {
63
+ const query = new Map();
64
+ for (const [key, value] of new URL(request.url).searchParams)
65
+ addQueryValue({ query, key, value });
66
+ // `filter` skips the holes an index left, as qs's compaction did.
67
+ return Object.fromEntries([...query].map(([key, value]) => [key, Array.isArray(value) ? value.filter(() => true) : value]));
68
+ }
69
+ //# sourceMappingURL=query.js.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @file The request rate-limiting port a route consumer calls. The fixed-window implementation
3
+ * (clock, counter store, eviction) stays in `@jini-ai/http-kit/rate-limit`; only the interface a
4
+ * caller depends on lives here, so packages that merely *check* a budget (comments, forms) need no
5
+ * dependency on the HTTP toolkit.
6
+ */
7
+ export type RateLimitResult = {
8
+ allowed: true;
9
+ } | {
10
+ allowed: false;
11
+ retryAfterSeconds: number;
12
+ };
13
+ export interface RateLimiter {
14
+ /** Resolves the budget decision; rejects missing, non-string or empty keys with TypeError. */
15
+ check(required: {
16
+ key: string;
17
+ }): Promise<RateLimitResult>;
18
+ size(required: Record<string, never>): Promise<number>;
19
+ }
20
+ //# sourceMappingURL=rate-limit.d.ts.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @file The request rate-limiting port a route consumer calls. The fixed-window implementation
3
+ * (clock, counter store, eviction) stays in `@jini-ai/http-kit/rate-limit`; only the interface a
4
+ * caller depends on lives here, so packages that merely *check* a budget (comments, forms) need no
5
+ * dependency on the HTTP toolkit.
6
+ */
7
+ export {};
8
+ //# sourceMappingURL=rate-limit.js.map
@@ -0,0 +1,26 @@
1
+ import { type Result } from './result.js';
2
+ /** Express's `express.json()` default ceiling, kept so moving a route off Express changes no limit. */
3
+ export declare const DEFAULT_JSON_BODY_MAX_BYTES: number;
4
+ /**
5
+ * Reads the whole body as bytes, refusing (413, `PAYLOAD_TOO_LARGE`) as soon as it passes
6
+ * `maxBytes` — a declared `content-length` above the limit is refused before reading anything.
7
+ * A request with no body gives zero bytes.
8
+ */
9
+ export declare function readBodyBytes({ request }: {
10
+ readonly request: Request;
11
+ }, { maxBytes }?: {
12
+ readonly maxBytes?: number;
13
+ }): Promise<Result<Uint8Array>>;
14
+ /**
15
+ * Reads a JSON body the way the Express 4 host's `express.json()` did, so a converted route sees
16
+ * the same value: no body, an empty body or a non-JSON content type give `{}`; only an object or
17
+ * array is accepted (body-parser's strict mode); invalid JSON is a 400 `BAD_REQUEST`. Unlike
18
+ * `express.json()`, the encoding refusal (415) and the `maxBytes` ceiling (413 `PAYLOAD_TOO_LARGE`)
19
+ * apply to every content type, so a mislabelled body cannot slip past either check.
20
+ */
21
+ export declare function readJsonBody({ request }: {
22
+ readonly request: Request;
23
+ }, { maxBytes }?: {
24
+ readonly maxBytes?: number;
25
+ }): Promise<Result<unknown>>;
26
+ //# sourceMappingURL=request-body.d.ts.map
@@ -0,0 +1,82 @@
1
+ import { err, ok } from './result.js';
2
+ /** Express's `express.json()` default ceiling, kept so moving a route off Express changes no limit. */
3
+ export const DEFAULT_JSON_BODY_MAX_BYTES = 100 * 1024;
4
+ function tooLarge(maxBytes) {
5
+ return ({ code: 'PAYLOAD_TOO_LARGE', message: `The request body is larger than the ${maxBytes} bytes this address accepts. Send less data.` });
6
+ }
7
+ /**
8
+ * Reads the whole body as bytes, refusing (413, `PAYLOAD_TOO_LARGE`) as soon as it passes
9
+ * `maxBytes` — a declared `content-length` above the limit is refused before reading anything.
10
+ * A request with no body gives zero bytes.
11
+ */
12
+ export async function readBodyBytes({ request }, { maxBytes = DEFAULT_JSON_BODY_MAX_BYTES } = {}) {
13
+ const encoding = (request.headers.get('content-encoding') ?? 'identity').trim().toLowerCase();
14
+ // Owner decision 2026-11-14: refuse compressed bodies, never unzip. (1) Zip bombs: a small compressed
15
+ // body can inflate to gigabytes and freeze or crash the server before any size limit sees it.
16
+ // (2) Decompression code is a known attack surface; not running it removes that risk. (3) A compressed
17
+ // body hides its real content and size from our checks and logs, which helps smuggle oversized or
18
+ // malicious input, including text aimed at hijacking the AI. No known client sends compressed bodies.
19
+ if (encoding !== 'identity')
20
+ return err({ error: { code: 'UNSUPPORTED_MEDIA_TYPE', message: 'This address does not accept compressed request bodies. Send the body uncompressed (no Content-Encoding).' } });
21
+ const declared = Number(request.headers.get('content-length') ?? '0');
22
+ if (declared > maxBytes)
23
+ return err({ error: tooLarge(maxBytes) });
24
+ if (!request.body)
25
+ return ok({ value: new Uint8Array(0) });
26
+ return collectBody({ body: request.body, maxBytes });
27
+ }
28
+ async function collectBody({ body, maxBytes }) {
29
+ const reader = body.getReader();
30
+ const chunks = [];
31
+ let total = 0;
32
+ for (;;) {
33
+ const { done, value } = await reader.read();
34
+ if (done)
35
+ break;
36
+ total += value.byteLength;
37
+ if (total > maxBytes) {
38
+ // Stop pulling from the socket at once: an oversized upload must not be buffered to the end.
39
+ await reader.cancel();
40
+ return err({ error: tooLarge(maxBytes) });
41
+ }
42
+ chunks.push(value);
43
+ }
44
+ const bytes = new Uint8Array(total);
45
+ let offset = 0;
46
+ for (const chunk of chunks) {
47
+ bytes.set(chunk, offset);
48
+ offset += chunk.byteLength;
49
+ }
50
+ return ok({ value: bytes });
51
+ }
52
+ function isJsonContentType(contentType) {
53
+ const mediaType = (contentType ?? '').split(';')[0]?.trim().toLowerCase() ?? '';
54
+ return mediaType === 'application/json' || mediaType.endsWith('+json');
55
+ }
56
+ /**
57
+ * Reads a JSON body the way the Express 4 host's `express.json()` did, so a converted route sees
58
+ * the same value: no body, an empty body or a non-JSON content type give `{}`; only an object or
59
+ * array is accepted (body-parser's strict mode); invalid JSON is a 400 `BAD_REQUEST`. Unlike
60
+ * `express.json()`, the encoding refusal (415) and the `maxBytes` ceiling (413 `PAYLOAD_TOO_LARGE`)
61
+ * apply to every content type, so a mislabelled body cannot slip past either check.
62
+ */
63
+ export async function readJsonBody({ request }, { maxBytes = DEFAULT_JSON_BODY_MAX_BYTES } = {}) {
64
+ const bytes = await readBodyBytes({ request }, { maxBytes });
65
+ if (!bytes.ok)
66
+ return bytes;
67
+ if (!isJsonContentType(request.headers.get('content-type')))
68
+ return ok({ value: {} });
69
+ const text = new TextDecoder().decode(bytes.value).trim();
70
+ if (text === '')
71
+ return ok({ value: {} });
72
+ const invalid = { code: 'BAD_REQUEST', message: 'The request body is not valid JSON. Send a JSON object or array.' };
73
+ if (!text.startsWith('{') && !text.startsWith('['))
74
+ return err({ error: invalid });
75
+ try {
76
+ return ok({ value: JSON.parse(text) });
77
+ }
78
+ catch {
79
+ return err({ error: invalid });
80
+ }
81
+ }
82
+ //# sourceMappingURL=request-body.js.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @file The success/failure envelope route parsing, handling and origin checks resolve to instead
3
+ * of throwing, so a route host can fold every failure mode into one error pipeline.
4
+ */
5
+ import type { Result as CoreResult } from '../../primitives/result.js';
6
+ import type { ServerApiError } from './api-error.js';
7
+ /** A discriminated success/failure envelope; the error defaults to the wire error shape. */
8
+ export type Result<T, E = ServerApiError> = CoreResult<T, E>;
9
+ /** Builds a successful `Result` carrying `value`. */
10
+ export declare const ok: <T, E = ServerApiError>({ value }: {
11
+ readonly value: T;
12
+ }, _optional?: Record<string, never>) => Result<T, E>;
13
+ /** Builds a failed `Result` carrying `error`. */
14
+ export declare const err: <T = never, E = ServerApiError>({ error }: {
15
+ readonly error: E;
16
+ }, _optional?: Record<string, never>) => Result<T, E>;
17
+ //# sourceMappingURL=result.d.ts.map
@@ -0,0 +1,5 @@
1
+ /** Builds a successful `Result` carrying `value`. */
2
+ export const ok = ({ value }, _optional = {}) => ({ ok: true, value });
3
+ /** Builds a failed `Result` carrying `error`. */
4
+ export const err = ({ error }, _optional = {}) => ({ ok: false, error });
5
+ //# sourceMappingURL=result.js.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * @file Route table for the `Server` contract: path matching and the contract's precedence rule,
3
+ * shared by every host adapter so none re-implements them. Web-standard only.
4
+ */
5
+ import type { Server, ServerMethod, ServerRoute } from '../server.js';
6
+ /** The outcome of matching one request against a route table. */
7
+ export type RouteMatch = {
8
+ readonly kind: 'route';
9
+ readonly route: ServerRoute;
10
+ readonly params: Readonly<Record<string, string>>;
11
+ } | {
12
+ readonly kind: 'method-not-allowed';
13
+ readonly allow: readonly ServerMethod[];
14
+ }
15
+ /** Only from a table made with `lenientPaths`: a route's shape fits but one `:name` segment is not valid percent-encoding. */
16
+ | {
17
+ readonly kind: 'malformed-path';
18
+ } | {
19
+ readonly kind: 'not-found';
20
+ };
21
+ /** A `Server` that also answers which registered route a request reaches. */
22
+ export interface RouteTable extends Server {
23
+ match(requiredArgs: {
24
+ readonly method: string;
25
+ readonly pathname: string;
26
+ }, optionalArgs?: Record<string, never>): RouteMatch;
27
+ }
28
+ /**
29
+ * Matches a registered `pattern` (e.g. `/notes/:id`) against a URL `pathname` with the contract's
30
+ * path syntax. Returns the decoded `:name` params, or `null`. One matcher, so every adapter agrees.
31
+ */
32
+ export declare function matchServerPath({ pattern, pathname }: {
33
+ readonly pattern: string;
34
+ readonly pathname: string;
35
+ }, _optional?: Record<string, never>): Record<string, string> | null;
36
+ /** Optional settings for {@link createRouteTable}. */
37
+ export interface RouteTableOptions {
38
+ /**
39
+ * Match the way Express 4 does by default, for a host that replaces Express routes with this
40
+ * table and must keep answering the spellings its callers already send: fixed segments ignore
41
+ * letter case, one trailing slash is accepted, and a `:name` segment that is not valid
42
+ * percent-encoding is reported as `malformed-path` (Express answers 400) instead of "no match".
43
+ * Default `false`: the contract's exact matching.
44
+ */
45
+ readonly lenientPaths?: boolean;
46
+ }
47
+ /**
48
+ * Creates an empty route table. `route()` refuses a second registration of the same method + path
49
+ * shape; `match()` applies the contract's precedence (literal beats `:param`, registration order
50
+ * never decides) and answers a HEAD from the GET route when no HEAD route exists.
51
+ * @complexity `match` is O(routes × segments); fine for the few hundred routes a host mounts.
52
+ */
53
+ export declare function createRouteTable(_required?: {}, { lenientPaths }?: RouteTableOptions): RouteTable;
54
+ //# sourceMappingURL=route-table.d.ts.map