@yolk-sdk/emulators 0.1.0-canary.100

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 (338) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2165 -0
  3. package/dist/anthropic.d.mts +269 -0
  4. package/dist/anthropic.d.mts.map +1 -0
  5. package/dist/anthropic.mjs +177 -0
  6. package/dist/anthropic.mjs.map +1 -0
  7. package/dist/chat-completions.d.mts +288 -0
  8. package/dist/chat-completions.d.mts.map +1 -0
  9. package/dist/chat-completions.mjs +451 -0
  10. package/dist/chat-completions.mjs.map +1 -0
  11. package/dist/codex.d.mts +265 -0
  12. package/dist/codex.d.mts.map +1 -0
  13. package/dist/codex.mjs +199 -0
  14. package/dist/codex.mjs.map +1 -0
  15. package/dist/dropbox/api.d.mts +63 -0
  16. package/dist/dropbox/api.d.mts.map +1 -0
  17. package/dist/dropbox/api.mjs +565 -0
  18. package/dist/dropbox/api.mjs.map +1 -0
  19. package/dist/dropbox/state.d.mts +136 -0
  20. package/dist/dropbox/state.d.mts.map +1 -0
  21. package/dist/dropbox/state.mjs +209 -0
  22. package/dist/dropbox/state.mjs.map +1 -0
  23. package/dist/dropbox.d.mts +79 -0
  24. package/dist/dropbox.d.mts.map +1 -0
  25. package/dist/dropbox.mjs +124 -0
  26. package/dist/dropbox.mjs.map +1 -0
  27. package/dist/email-fixtures.d.mts +36 -0
  28. package/dist/email-fixtures.d.mts.map +1 -0
  29. package/dist/email-fixtures.mjs +1080 -0
  30. package/dist/email-fixtures.mjs.map +1 -0
  31. package/dist/email.d.mts +160 -0
  32. package/dist/email.d.mts.map +1 -0
  33. package/dist/email.mjs +608 -0
  34. package/dist/email.mjs.map +1 -0
  35. package/dist/emulator-compose.d.mts +40 -0
  36. package/dist/emulator-compose.d.mts.map +1 -0
  37. package/dist/emulator-compose.mjs +91 -0
  38. package/dist/emulator-compose.mjs.map +1 -0
  39. package/dist/emulator-http.d.mts +53 -0
  40. package/dist/emulator-http.d.mts.map +1 -0
  41. package/dist/emulator-http.mjs +117 -0
  42. package/dist/emulator-http.mjs.map +1 -0
  43. package/dist/emulator-kernel.d.mts +176 -0
  44. package/dist/emulator-kernel.d.mts.map +1 -0
  45. package/dist/emulator-kernel.mjs +413 -0
  46. package/dist/emulator-kernel.mjs.map +1 -0
  47. package/dist/fixture-route.d.mts +129 -0
  48. package/dist/fixture-route.d.mts.map +1 -0
  49. package/dist/fixture-route.mjs +257 -0
  50. package/dist/fixture-route.mjs.map +1 -0
  51. package/dist/fortnox/api.d.mts +92 -0
  52. package/dist/fortnox/api.d.mts.map +1 -0
  53. package/dist/fortnox/api.mjs +750 -0
  54. package/dist/fortnox/api.mjs.map +1 -0
  55. package/dist/fortnox/state.d.mts +533 -0
  56. package/dist/fortnox/state.d.mts.map +1 -0
  57. package/dist/fortnox/state.mjs +612 -0
  58. package/dist/fortnox/state.mjs.map +1 -0
  59. package/dist/fortnox.d.mts +128 -0
  60. package/dist/fortnox.d.mts.map +1 -0
  61. package/dist/fortnox.mjs +403 -0
  62. package/dist/fortnox.mjs.map +1 -0
  63. package/dist/gateway-evaluate-recordings.d.mts +12 -0
  64. package/dist/gateway-evaluate-recordings.d.mts.map +1 -0
  65. package/dist/gateway-evaluate-recordings.mjs +128 -0
  66. package/dist/gateway-evaluate-recordings.mjs.map +1 -0
  67. package/dist/gateway.d.mts +272 -0
  68. package/dist/gateway.d.mts.map +1 -0
  69. package/dist/gateway.mjs +400 -0
  70. package/dist/gateway.mjs.map +1 -0
  71. package/dist/github/api.d.mts +63 -0
  72. package/dist/github/api.d.mts.map +1 -0
  73. package/dist/github/api.mjs +527 -0
  74. package/dist/github/api.mjs.map +1 -0
  75. package/dist/github/state.d.mts +272 -0
  76. package/dist/github/state.d.mts.map +1 -0
  77. package/dist/github/state.mjs +303 -0
  78. package/dist/github/state.mjs.map +1 -0
  79. package/dist/github.d.mts +77 -0
  80. package/dist/github.d.mts.map +1 -0
  81. package/dist/github.mjs +180 -0
  82. package/dist/github.mjs.map +1 -0
  83. package/dist/google/calendar.d.mts +10 -0
  84. package/dist/google/calendar.d.mts.map +1 -0
  85. package/dist/google/calendar.mjs +252 -0
  86. package/dist/google/calendar.mjs.map +1 -0
  87. package/dist/google/drive.d.mts +8 -0
  88. package/dist/google/drive.d.mts.map +1 -0
  89. package/dist/google/drive.mjs +252 -0
  90. package/dist/google/drive.mjs.map +1 -0
  91. package/dist/google/gmail.d.mts +10 -0
  92. package/dist/google/gmail.d.mts.map +1 -0
  93. package/dist/google/gmail.mjs +591 -0
  94. package/dist/google/gmail.mjs.map +1 -0
  95. package/dist/google/shared.d.mts +107 -0
  96. package/dist/google/shared.d.mts.map +1 -0
  97. package/dist/google/shared.mjs +146 -0
  98. package/dist/google/shared.mjs.map +1 -0
  99. package/dist/google/state.d.mts +385 -0
  100. package/dist/google/state.d.mts.map +1 -0
  101. package/dist/google/state.mjs +496 -0
  102. package/dist/google/state.mjs.map +1 -0
  103. package/dist/google.d.mts +75 -0
  104. package/dist/google.d.mts.map +1 -0
  105. package/dist/google.mjs +210 -0
  106. package/dist/google.mjs.map +1 -0
  107. package/dist/linkedin-search/api.d.mts +45 -0
  108. package/dist/linkedin-search/api.d.mts.map +1 -0
  109. package/dist/linkedin-search/api.mjs +181 -0
  110. package/dist/linkedin-search/api.mjs.map +1 -0
  111. package/dist/linkedin-search/state.d.mts +123 -0
  112. package/dist/linkedin-search/state.d.mts.map +1 -0
  113. package/dist/linkedin-search/state.mjs +261 -0
  114. package/dist/linkedin-search/state.mjs.map +1 -0
  115. package/dist/linkedin-search.d.mts +69 -0
  116. package/dist/linkedin-search.d.mts.map +1 -0
  117. package/dist/linkedin-search.mjs +158 -0
  118. package/dist/linkedin-search.mjs.map +1 -0
  119. package/dist/mcp/afloat-recordings.d.mts +8 -0
  120. package/dist/mcp/afloat-recordings.d.mts.map +1 -0
  121. package/dist/mcp/afloat-recordings.mjs +918 -0
  122. package/dist/mcp/afloat-recordings.mjs.map +1 -0
  123. package/dist/mcp/api.d.mts +45 -0
  124. package/dist/mcp/api.d.mts.map +1 -0
  125. package/dist/mcp/api.mjs +609 -0
  126. package/dist/mcp/api.mjs.map +1 -0
  127. package/dist/mcp/recordings.d.mts +40 -0
  128. package/dist/mcp/recordings.d.mts.map +1 -0
  129. package/dist/mcp/recordings.mjs +2390 -0
  130. package/dist/mcp/recordings.mjs.map +1 -0
  131. package/dist/mcp/state.d.mts +86 -0
  132. package/dist/mcp/state.d.mts.map +1 -0
  133. package/dist/mcp/state.mjs +98 -0
  134. package/dist/mcp/state.mjs.map +1 -0
  135. package/dist/mcp.d.mts +85 -0
  136. package/dist/mcp.d.mts.map +1 -0
  137. package/dist/mcp.mjs +264 -0
  138. package/dist/mcp.mjs.map +1 -0
  139. package/dist/messages.d.mts +183 -0
  140. package/dist/messages.d.mts.map +1 -0
  141. package/dist/messages.mjs +532 -0
  142. package/dist/messages.mjs.map +1 -0
  143. package/dist/microsoft/api.d.mts +47 -0
  144. package/dist/microsoft/api.d.mts.map +1 -0
  145. package/dist/microsoft/api.mjs +178 -0
  146. package/dist/microsoft/api.mjs.map +1 -0
  147. package/dist/microsoft/calendar.d.mts +30 -0
  148. package/dist/microsoft/calendar.d.mts.map +1 -0
  149. package/dist/microsoft/calendar.mjs +271 -0
  150. package/dist/microsoft/calendar.mjs.map +1 -0
  151. package/dist/microsoft/drive.d.mts +36 -0
  152. package/dist/microsoft/drive.d.mts.map +1 -0
  153. package/dist/microsoft/drive.mjs +298 -0
  154. package/dist/microsoft/drive.mjs.map +1 -0
  155. package/dist/microsoft/graph.d.mts +198 -0
  156. package/dist/microsoft/graph.d.mts.map +1 -0
  157. package/dist/microsoft/graph.mjs +264 -0
  158. package/dist/microsoft/graph.mjs.map +1 -0
  159. package/dist/microsoft/mail.d.mts +48 -0
  160. package/dist/microsoft/mail.d.mts.map +1 -0
  161. package/dist/microsoft/mail.mjs +488 -0
  162. package/dist/microsoft/mail.mjs.map +1 -0
  163. package/dist/microsoft/state.d.mts +480 -0
  164. package/dist/microsoft/state.d.mts.map +1 -0
  165. package/dist/microsoft/state.mjs +625 -0
  166. package/dist/microsoft/state.mjs.map +1 -0
  167. package/dist/microsoft.d.mts +168 -0
  168. package/dist/microsoft.d.mts.map +1 -0
  169. package/dist/microsoft.mjs +483 -0
  170. package/dist/microsoft.mjs.map +1 -0
  171. package/dist/node.d.mts +47 -0
  172. package/dist/node.d.mts.map +1 -0
  173. package/dist/node.mjs +178 -0
  174. package/dist/node.mjs.map +1 -0
  175. package/dist/notion/api.d.mts +51 -0
  176. package/dist/notion/api.d.mts.map +1 -0
  177. package/dist/notion/api.mjs +507 -0
  178. package/dist/notion/api.mjs.map +1 -0
  179. package/dist/notion/state.d.mts +329 -0
  180. package/dist/notion/state.d.mts.map +1 -0
  181. package/dist/notion/state.mjs +432 -0
  182. package/dist/notion/state.mjs.map +1 -0
  183. package/dist/notion.d.mts +72 -0
  184. package/dist/notion.d.mts.map +1 -0
  185. package/dist/notion.mjs +127 -0
  186. package/dist/notion.mjs.map +1 -0
  187. package/dist/openai.d.mts +165 -0
  188. package/dist/openai.d.mts.map +1 -0
  189. package/dist/openai.mjs +141 -0
  190. package/dist/openai.mjs.map +1 -0
  191. package/dist/opencode-recordings.d.mts +7 -0
  192. package/dist/opencode-recordings.d.mts.map +1 -0
  193. package/dist/opencode-recordings.mjs +222 -0
  194. package/dist/opencode-recordings.mjs.map +1 -0
  195. package/dist/opencode.d.mts +70 -0
  196. package/dist/opencode.d.mts.map +1 -0
  197. package/dist/opencode.mjs +217 -0
  198. package/dist/opencode.mjs.map +1 -0
  199. package/dist/r2-fixtures.d.mts +36 -0
  200. package/dist/r2-fixtures.d.mts.map +1 -0
  201. package/dist/r2-fixtures.mjs +245 -0
  202. package/dist/r2-fixtures.mjs.map +1 -0
  203. package/dist/r2-guard.d.mts +43 -0
  204. package/dist/r2-guard.d.mts.map +1 -0
  205. package/dist/r2-guard.mjs +216 -0
  206. package/dist/r2-guard.mjs.map +1 -0
  207. package/dist/r2.d.mts +166 -0
  208. package/dist/r2.d.mts.map +1 -0
  209. package/dist/r2.mjs +517 -0
  210. package/dist/r2.mjs.map +1 -0
  211. package/dist/responses.d.mts +231 -0
  212. package/dist/responses.d.mts.map +1 -0
  213. package/dist/responses.mjs +556 -0
  214. package/dist/responses.mjs.map +1 -0
  215. package/dist/route-evidence.d.mts +45 -0
  216. package/dist/route-evidence.d.mts.map +1 -0
  217. package/dist/route-evidence.mjs +56 -0
  218. package/dist/route-evidence.mjs.map +1 -0
  219. package/dist/router.d.mts +93 -0
  220. package/dist/router.d.mts.map +1 -0
  221. package/dist/router.mjs +259 -0
  222. package/dist/router.mjs.map +1 -0
  223. package/dist/stateful-core.d.mts +17 -0
  224. package/dist/stateful-core.d.mts.map +1 -0
  225. package/dist/stateful-core.mjs +41 -0
  226. package/dist/stateful-core.mjs.map +1 -0
  227. package/dist/stateful-emulator.d.mts +578 -0
  228. package/dist/stateful-emulator.d.mts.map +1 -0
  229. package/dist/stateful-emulator.mjs +1248 -0
  230. package/dist/stateful-emulator.mjs.map +1 -0
  231. package/dist/stateful-secrets.d.mts +84 -0
  232. package/dist/stateful-secrets.d.mts.map +1 -0
  233. package/dist/stateful-secrets.mjs +216 -0
  234. package/dist/stateful-secrets.mjs.map +1 -0
  235. package/dist/subscription-usage-recordings.d.mts +9 -0
  236. package/dist/subscription-usage-recordings.d.mts.map +1 -0
  237. package/dist/subscription-usage-recordings.mjs +53 -0
  238. package/dist/subscription-usage-recordings.mjs.map +1 -0
  239. package/dist/subscription-usage.d.mts +53 -0
  240. package/dist/subscription-usage.d.mts.map +1 -0
  241. package/dist/subscription-usage.mjs +21 -0
  242. package/dist/subscription-usage.mjs.map +1 -0
  243. package/dist/telegram/api.d.mts +34 -0
  244. package/dist/telegram/api.d.mts.map +1 -0
  245. package/dist/telegram/api.mjs +257 -0
  246. package/dist/telegram/api.mjs.map +1 -0
  247. package/dist/telegram/state.d.mts +128 -0
  248. package/dist/telegram/state.d.mts.map +1 -0
  249. package/dist/telegram/state.mjs +154 -0
  250. package/dist/telegram/state.mjs.map +1 -0
  251. package/dist/telegram.d.mts +62 -0
  252. package/dist/telegram.d.mts.map +1 -0
  253. package/dist/telegram.mjs +127 -0
  254. package/dist/telegram.mjs.map +1 -0
  255. package/dist/todoist/api.d.mts +55 -0
  256. package/dist/todoist/api.d.mts.map +1 -0
  257. package/dist/todoist/api.mjs +415 -0
  258. package/dist/todoist/api.mjs.map +1 -0
  259. package/dist/todoist/state.d.mts +275 -0
  260. package/dist/todoist/state.d.mts.map +1 -0
  261. package/dist/todoist/state.mjs +345 -0
  262. package/dist/todoist/state.mjs.map +1 -0
  263. package/dist/todoist.d.mts +68 -0
  264. package/dist/todoist.d.mts.map +1 -0
  265. package/dist/todoist.mjs +181 -0
  266. package/dist/todoist.mjs.map +1 -0
  267. package/dist/xai.d.mts +267 -0
  268. package/dist/xai.d.mts.map +1 -0
  269. package/dist/xai.mjs +252 -0
  270. package/dist/xai.mjs.map +1 -0
  271. package/package.json +157 -0
  272. package/src/anthropic.ts +289 -0
  273. package/src/chat-completions.ts +924 -0
  274. package/src/codex.ts +296 -0
  275. package/src/dropbox/api.ts +1084 -0
  276. package/src/dropbox/state.ts +364 -0
  277. package/src/dropbox.ts +203 -0
  278. package/src/email-fixtures.ts +1297 -0
  279. package/src/email.ts +1108 -0
  280. package/src/emulator-compose.ts +147 -0
  281. package/src/emulator-http.ts +184 -0
  282. package/src/emulator-kernel.ts +844 -0
  283. package/src/fixture-route.ts +561 -0
  284. package/src/fortnox/api.ts +1352 -0
  285. package/src/fortnox/state.ts +798 -0
  286. package/src/fortnox.ts +801 -0
  287. package/src/gateway-evaluate-recordings.ts +153 -0
  288. package/src/gateway.ts +530 -0
  289. package/src/github/api.ts +986 -0
  290. package/src/github/state.ts +439 -0
  291. package/src/github.ts +271 -0
  292. package/src/google/calendar.ts +486 -0
  293. package/src/google/drive.ts +471 -0
  294. package/src/google/gmail.ts +1011 -0
  295. package/src/google/shared.ts +321 -0
  296. package/src/google/state.ts +686 -0
  297. package/src/google.ts +298 -0
  298. package/src/linkedin-search/api.ts +363 -0
  299. package/src/linkedin-search/state.ts +373 -0
  300. package/src/linkedin-search.ts +241 -0
  301. package/src/mcp/afloat-recordings.ts +1040 -0
  302. package/src/mcp/api.ts +1105 -0
  303. package/src/mcp/recordings.ts +2665 -0
  304. package/src/mcp/state.ts +144 -0
  305. package/src/mcp.ts +364 -0
  306. package/src/messages.ts +844 -0
  307. package/src/microsoft/api.ts +426 -0
  308. package/src/microsoft/calendar.ts +491 -0
  309. package/src/microsoft/drive.ts +541 -0
  310. package/src/microsoft/graph.ts +550 -0
  311. package/src/microsoft/mail.ts +833 -0
  312. package/src/microsoft/state.ts +822 -0
  313. package/src/microsoft.ts +982 -0
  314. package/src/node.ts +293 -0
  315. package/src/notion/api.ts +976 -0
  316. package/src/notion/state.ts +512 -0
  317. package/src/notion.ts +210 -0
  318. package/src/openai.ts +198 -0
  319. package/src/opencode-recordings.ts +257 -0
  320. package/src/opencode.ts +271 -0
  321. package/src/r2-fixtures.ts +295 -0
  322. package/src/r2-guard.ts +324 -0
  323. package/src/r2.ts +890 -0
  324. package/src/responses.ts +901 -0
  325. package/src/route-evidence.ts +90 -0
  326. package/src/router.ts +490 -0
  327. package/src/stateful-core.ts +70 -0
  328. package/src/stateful-emulator.ts +2620 -0
  329. package/src/stateful-secrets.ts +299 -0
  330. package/src/subscription-usage-recordings.ts +77 -0
  331. package/src/subscription-usage.ts +68 -0
  332. package/src/telegram/api.ts +437 -0
  333. package/src/telegram/state.ts +229 -0
  334. package/src/telegram.ts +227 -0
  335. package/src/todoist/api.ts +736 -0
  336. package/src/todoist/state.ts +456 -0
  337. package/src/todoist.ts +316 -0
  338. package/src/xai.ts +341 -0
@@ -0,0 +1,2620 @@
1
+ /**
2
+ * Shared wrapper of the fixture-only stateful connector emulators (internal; used by `/dropbox`,
3
+ * `/notion`, `/todoist`, `/telegram`, `/github`, `/google`, `/linkedin-search`, and `/mcp`, not by
4
+ * the earlier `/fortnox` and `/microsoft` emulators, which keep their own).
5
+ *
6
+ * The emulator state lives in an `@emulators/core` custom runtime that the Node-only subpath
7
+ * creates and hands in (`src/stateful-core.ts`; this module imports no Node builtin and never
8
+ * imports the core); the request ledger, status faults, credential handling, and the
9
+ * `/_emulate/*` control plane live here, because the core reserves `/_emulate`.
10
+ *
11
+ * The owner rule: response behaviour comes only from the committed conformance fixtures. Every
12
+ * request is answered by its route or with one ledgered 400 not-emulated
13
+ * (`{ error: { type: 'not_emulated', message } }`, `notEmulated` in the ledger). Precedence per
14
+ * request:
15
+ *
16
+ * 1. route match on the raw path (path parameters decoded once; unknown routes and methods, and
17
+ * invalid percent-encoding, are not emulated), and the origin the route is recorded on;
18
+ * 2. a non-empty `Authorization: Bearer` credential (never compared against anything, stored,
19
+ * forwarded, or ledgered) and the emulator's header rules;
20
+ * 3. the body the route takes (none, JSON with an `application/json` media type, or raw bytes);
21
+ * 4. the route's request-shape check, which reads no state;
22
+ * 5. in the core runtime, the route's plan: a pure, state-reading eligibility check that refuses
23
+ * what the state cannot answer the way a fixture does, and otherwise returns a commit;
24
+ * 6. the first matching status fault, decided only for an eligible request (nothing is written);
25
+ * 7. the commit, the only step that writes.
26
+ *
27
+ * A request that is not emulated (steps 1 to 5) never uses up a fault. The plan, the fault
28
+ * decision, and the commit run synchronously together, so no other request interleaves. A route
29
+ * that throws answers an evidence-tagged 500 emulator error
30
+ * (`responseError` in the ledger); a closed emulator answers 503. No recovery answer reads the
31
+ * injectable clock, so a failing clock cannot change it. Every response of a matched route
32
+ * carries `x-emulator-evidence: unverified` when the route is unverified. Ledgered bodies and
33
+ * query parameters have credential-named keys redacted.
34
+ *
35
+ * Fail-closed mode (opt-in, `failClosed`; used by `/github`, `/google`, and `/linkedin-search`):
36
+ * every route parameter has a raw pattern (matched in full), and a request is recognised only when
37
+ * its raw path is exactly an emulated route shape under that route's method and any `Authorization`
38
+ * header is exactly `Bearer <at least 8 non-space characters>` (a recognisable bearer, below).
39
+ * Every other request is ledgered and answered with constant text only (`/<unrecognised>`, a
40
+ * standard method or `<other>`, an empty query, no body, a constant reason). A recognised bearer
41
+ * must match the RFC 6750 `b64token` syntax exactly (`^[A-Za-z0-9\-._~+/]+=*$`, at least 8
42
+ * characters), start with a character in `[G-Zg-z\-._~+/]` other than `n`, `r`, `t`, `u`, and hold
43
+ * at least one character outside the JSON-number alphabet `[0-9.eE+-]` (every GitHub and Google
44
+ * token form does: `ghp_…`, `github_pat_…`, `gho_…`, `ya29.…`). So no number's text can contain it;
45
+ * it holds no escape introducer (`%`, `\`, `"`), so no escape starts inside it; and its first
46
+ * character is no hex digit and no JSON escape letter, so no stray `%`, `\`, or partial escape to
47
+ * its left can complete with it, and its characters always decode in place. An `Authorization`
48
+ * header with any other value is unrecognisable. A recognised request that repeats the bearer value
49
+ * in its raw path, any path segment, the raw query or any query key or value, any recorded header,
50
+ * or its body is refused and ledgered with constant text only: a standard method, the path
51
+ * `/<unrecognised>`, its route template, an empty query, no headers or body, and a constant reason
52
+ * (`the query repeats the credential`, for example). Each part is checked through the closure of
53
+ * two total, lexical transforms that cannot fail: a tolerant percent-decode (every `%XX` below
54
+ * `%80` becomes its ASCII character; any other `%` sequence is left as it is) and a tolerant
55
+ * JSON-unescape (in any text, whether or not it parses as JSON, `\uXXXX` below `\u0080` and `\"`,
56
+ * `\\`, `\/`, `\b`, `\f`, `\n`, `\r`, `\t` become their characters). Starting from each part's raw
57
+ * text, either transform is applied to every text of the previous step, deduplicated, until no new
58
+ * text appears (a fixpoint), and every text is checked for the bearer as a substring; both
59
+ * transforms never lengthen a text and shorten it whenever they change it. So any depth of
60
+ * percent-encoding or JSON escaping, in any order, is seen through in every part: the raw path and
61
+ * each raw path segment, the raw query and each query key and value (already decoded once by
62
+ * `URLSearchParams`), each recorded header, and the raw body. The work is capped at 64 rounds, 1024
63
+ * distinct texts, or 8 Mi characters read by the transforms, whichever comes first; a part whose
64
+ * closure hits a cap before its fixpoint counts as repeating the credential and is refused with the
65
+ * same constant entry (uncertainty refuses, it never admits; so any part over 4 Mi characters is
66
+ * always refused). Any other recognised request has the bearer value scrubbed from its ledgered
67
+ * fields and every not-emulated reason (plan-time reasons included); its recorded query is keyed by
68
+ * recorded key; a key recorded more than once lists its values in order (as a JSON array); and
69
+ * recorded headers and query keys and values that start like JSON (`{`, `[`, `"`) are recorded
70
+ * parsed with credential-named keys redacted at any depth, or as `<redacted>` when they do not
71
+ * parse, whatever the header's declared format. Empty query components (a bare `?`, a stray `&`)
72
+ * are refused. Routes check their own query and body keys with `exactQuery` and `exactBodyKeys`,
73
+ * whose reasons never echo a request's own key (`exactQuery`'s opt-in `rawNames`, used by
74
+ * `/linkedin-search`, also refuses a parameter name in any but its plain form, comparing the raw
75
+ * names the wrapper hands routes as `rawQuery`). A template parameter written `{name+}` spans one
76
+ * or more path segments (each decoded once, none may decode to a `/`). The credential helpers live
77
+ * in `src/stateful-secrets.ts`. A route may also name decoded views of its raw body
78
+ * (`decodedViews`, opt-in; `/google` gives the base64url-decoded MIME of a Gmail draft's
79
+ * `message.raw`, which the provider's own wire format wraps): in fail-closed mode each view goes
80
+ * through the same fixpoint check as the raw body, before anything is recorded, a fault is decided,
81
+ * or anything is committed, and a hit is the same constant credential-repeat entry. A view may
82
+ * throw to refuse a body it cannot check completely: that request is ledgered as the same constant
83
+ * entry, as a repeat when the `DecodedViewRefusal` it threw carries cleanly decoded text holding
84
+ * the bearer, else with the refusal's reason when the route declares it in `viewRefusalReasons` (a
85
+ * constant the route owns, scrubbed defensively), else with
86
+ * `the request body cannot be checked for the credential`. A route without `decodedViews` is
87
+ * checked exactly as before. An emulator may also opt in to a per-origin bearer digest
88
+ * (`bearerDigest`, fail-closed mode only; `/linkedin-search` uses it): routes then see a one-way
89
+ * digest of the bearer for the origin the request arrived on (`EmulatedRequest.bearerDigest`),
90
+ * never the bearer, so a seed can mark a key as rejected on one origin by its digest, and the
91
+ * bearer still never reaches the state, the ledger, or `/_emulate/*`. A digest that throws or
92
+ * repeats the bearer answers the 500 emulator error (`responseError`). Without it, routes see no
93
+ * digest, as before.
94
+ *
95
+ * More opt-ins serve `/mcp`, whose JSON-RPC methods share one HTTP endpoint; a route or emulator
96
+ * that does not take them behaves exactly as before. A route may answer several manifest rows
97
+ * (`variants`, for example `RPC <origin><path>#<method>`): its admission names the row, which
98
+ * becomes the request's ledger route, its coverage row, and what a fault's `match.route` compares
99
+ * (a request refused before admission keeps the route template). A fault's `match.route` must name
100
+ * a manifest row (a variant, or the template of a route without variants); any other value is
101
+ * rejected when the fault is added, and `match.method` is always the HTTP method. A plan may return
102
+ * a `StreamedCommit`: the answer it prepares, and the `commit` that writes. Faults are decided
103
+ * against the prepared answer, and a faulted request never runs `commit`; an emulator built with
104
+ * `makeChunkedStatefulEmulator` also takes `truncate-after-chunks` faults, which send the prepared
105
+ * answer cut short and write nothing (one that cannot take effect answers 500 and is not used up).
106
+ * In fail-closed mode: `constantRefusals` ledgers every refusal with constant text only
107
+ * (`/<unrecognised>`, no query, headers, or body), so request text reaches the ledger only once a
108
+ * route admitted the request; `guardAllHeaders` checks every request header name and value but
109
+ * `Authorization` for a credential repeat, not only the recorded ones; and `guardOutput` checks a
110
+ * streamed commit's prepared answer (every header and chunk) and its `persisted` texts (minted ids,
111
+ * for example) for the bearer before any fault is decided or anything is committed, refusing a hit
112
+ * with the constant credential-repeat entry, so no answer or stored value repeats the bearer, while
113
+ * routes still see only its digest. `uniqueJsonKeys` refuses a JSON body in which an object repeats
114
+ * a key (after unescaping). Routes also see every request header name
115
+ * (`EmulatedRequest.headerNames`), never a credential value. `bearerPrefixes` (fail-closed mode
116
+ * only) gives an origin a fixed bearer prefix (`/mcp` gives `https://useafloat.com` the Afloat key
117
+ * prefix `afloat_`): there a bearer is recognised only as `<prefix><remainder>`, and the remainder,
118
+ * which must itself be a recognisable bearer, is the guarded secret and the digest input.
119
+ *
120
+ * Resolved mode (opt-in, `resolveRequest`; not with `failClosed`; used by `/todoist` and
121
+ * `/telegram`) serves an emulator whose credential the wrapper cannot find by itself (a Telegram
122
+ * bot token in a path segment) or that has its own credential rules (a Todoist bearer of any 8
123
+ * non-space characters): the emulator resolves every request itself, failing closed
124
+ * (`StatefulResolution`): an unrecognised request is ledgered with constant text only (the method
125
+ * as sent when standard, else `<other>`), a request it refuses before its body is read keeps its
126
+ * scrubbed fields, and a recognised one names its route, credential-free parameters, ledger path,
127
+ * guarded path, and the credential values to guard. Those values are scrubbed from everything the
128
+ * ledger keeps or a refusal answers (plan-time reasons included), and a query, guarded path, or
129
+ * body that repeats one (raw or percent-decoded once, and in any parsed JSON key, string, or
130
+ * number) is refused with a constant reason before anything else is checked. The ledger records
131
+ * the resolution's path and the query as sent (credential-named keys redacted), faults'
132
+ * `match.path` compares that path, and routes and the core see it too (routes see no header
133
+ * names and read no header but `content-type`), so the credential never reaches a route or the
134
+ * core. The request body is read once, after the query and path checks (so a query or path refusal
135
+ * leaves it unread, and any later refusal finds it read); a body that is already consumed or
136
+ * locked is refused as unreadable; a refusal reason that cannot be percent-encoded (an unpaired
137
+ * surrogate) is a handler failure (500). Fault answers and refusals are decided in the core with
138
+ * the commit, but returned by the wrapper itself, so a reset or a close before they are read never
139
+ * cancels them (only a commit's answer is the core's own); a core that answers without running
140
+ * the dispatch (closed meanwhile) gives the 500 handler failure (`responseError`
141
+ * `the route handler answered no eligibility verdict`). Resolved mode records no request
142
+ * header (`recordHeaders` must be empty). More opt-ins, off by default: a `json-or-empty` route
143
+ * body (JSON of any media type, or none), `makeHeaderlessStatefulEmulator` (ledger entries without
144
+ * a `headers` field), and `errorTexts` (the texts of the recovery answers).
145
+ *
146
+ * @experimental
147
+ */
148
+ import { Data, Predicate, Result } from 'effect'
149
+ import * as Schema from 'effect/Schema'
150
+ import {
151
+ EmulatorHeaderRecord,
152
+ answeredOutsideCore,
153
+ emulatorJobHeader,
154
+ handlerFailedHeader,
155
+ handlerFailedResponse,
156
+ isCredentialHeaderName,
157
+ isCredentialQueryKey,
158
+ redactCredentialFields,
159
+ redactCredentialQuery,
160
+ redactedCredentialValue
161
+ } from './emulator-http.ts'
162
+ import {
163
+ emulatorEvidenceHeader,
164
+ emulatorRouteKey,
165
+ type EmulatorEvidence,
166
+ type EmulatorRouteEvidence
167
+ } from './route-evidence.ts'
168
+ import {
169
+ isRecognisableBearerValue,
170
+ jsonRepeatsSecret,
171
+ repeatsSecret,
172
+ scrubSecrets,
173
+ textRepeatsSecret,
174
+ unrecognisedLedgerPath,
175
+ unrecognisedMethod
176
+ } from './stateful-secrets.ts'
177
+
178
+ /** A request the emulator does not emulate, with the reason (answered 400 not-emulated). */
179
+ export class NotEmulated extends Data.TaggedClass('NotEmulated')<{ readonly reason: string }> {}
180
+
181
+ /**
182
+ * What a route's decoded view throws to refuse a body with a reason of its own (fail-closed mode;
183
+ * see `StatefulRouteBinding.decodedViews`). `reason` must be one of the route's declared
184
+ * `viewRefusalReasons` (a constant the route owns, never derived from the request); `decoded` holds
185
+ * any text the view did decode cleanly, which is still checked for the bearer first.
186
+ */
187
+ export class DecodedViewRefusal extends Data.TaggedError('DecodedViewRefusal')<{
188
+ readonly reason: string
189
+ readonly decoded: ReadonlyArray<string>
190
+ }> {}
191
+
192
+ export const notEmulated = (reason: string): NotEmulated => new NotEmulated({ reason })
193
+
194
+ export const isNotEmulated = (value: unknown): value is NotEmulated => value instanceof NotEmulated
195
+
196
+ export const jsonResponse = (
197
+ status: number,
198
+ body: unknown,
199
+ headers: HeadersInit = {}
200
+ ): Response => {
201
+ const responseHeaders = new Headers(headers)
202
+
203
+ if (!responseHeaders.has('content-type')) {
204
+ responseHeaders.set('content-type', 'application/json')
205
+ }
206
+
207
+ return new Response(JSON.stringify(body), { status, headers: responseHeaders })
208
+ }
209
+
210
+ /** The one answer for everything no fixture records. */
211
+ export const notEmulatedResponse = (reason: string): Response =>
212
+ jsonResponse(400, { error: { type: 'not_emulated', message: `Not emulated: ${reason}` } })
213
+
214
+ const emulatorError = (status: number, message: string, headers: HeadersInit = {}): Response =>
215
+ jsonResponse(status, { error: { message, type: 'emulator_error' } }, headers)
216
+
217
+ // Fault statuses are errors only (400-599), so no control answers a success no fixture records.
218
+ // One range check, so a rejection names the range actually accepted (400-599 holds no 204, 205,
219
+ // or 3xx, which the shared response-status schema otherwise excludes).
220
+ const FaultStatus = Schema.Int.check(Schema.isBetween({ minimum: 400, maximum: 599 }))
221
+
222
+ const FaultCount = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))
223
+
224
+ const ChunkCount = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
225
+
226
+ /**
227
+ * Optional fault filter; an omitted field matches every request. `method` is the HTTP method
228
+ * (never a manifest row's `RPC`). `path` is the raw request path (in resolved mode, the
229
+ * resolution's ledger path); ending in `*`, a prefix. `route` is a manifest row path, compared
230
+ * with the request's ledger route: the template of its matched route, or the manifest variant its
231
+ * route admitted it as (see `StatefulRouteBinding.variants`).
232
+ * A `route` that names no manifest row of the emulator could never match, so adding the fault
233
+ * rejects it (a route with variants is matched by its variant rows, never its template).
234
+ */
235
+ export const StatefulFaultMatch = Schema.Struct({
236
+ method: Schema.optionalKey(Schema.String),
237
+ path: Schema.optionalKey(Schema.String),
238
+ route: Schema.optionalKey(Schema.String)
239
+ })
240
+
241
+ export type StatefulFaultMatch = typeof StatefulFaultMatch.Type
242
+
243
+ /**
244
+ * A status fault: answer matching requests with this status (400-599), headers, and body before
245
+ * the route runs, so nothing is written. The body defaults to an emulator-fault body
246
+ * (`{ error: { type: 'emulator_fault', message } }`), never a guessed provider envelope. `count`
247
+ * limits how many requests it answers (omitted: all). `match.path` is the raw request path.
248
+ * Invalid header names or values, `location`, and framing headers are rejected.
249
+ */
250
+ export const StatefulFault = Schema.Struct({
251
+ kind: Schema.Literal('status'),
252
+ status: FaultStatus,
253
+ headers: Schema.optionalKey(EmulatorHeaderRecord),
254
+ body: Schema.optionalKey(Schema.Json),
255
+ match: Schema.optionalKey(StatefulFaultMatch),
256
+ count: Schema.optionalKey(FaultCount)
257
+ })
258
+
259
+ export type StatefulFault = typeof StatefulFault.Type
260
+
261
+ /**
262
+ * Opt-in (`makeChunkedStatefulEmulator`): send the first `chunks` body chunks of the answer a
263
+ * streamed commit prepared (`StreamedCommit`), then close the body cleanly (a truncated answer).
264
+ * It is decided where a status fault is, after the plan, and a truncated request writes nothing:
265
+ * its `commit` never runs (no state, counter, or runtime change). One that cannot take effect (the
266
+ * answer is not streamed, or has no more than `chunks` chunks) answers the 500 emulator error and
267
+ * is not used up, never a silent no-op.
268
+ */
269
+ export const StatefulTruncateFault = Schema.Struct({
270
+ kind: Schema.Literal('truncate-after-chunks'),
271
+ chunks: ChunkCount,
272
+ match: Schema.optionalKey(StatefulFaultMatch),
273
+ count: Schema.optionalKey(FaultCount)
274
+ })
275
+
276
+ export type StatefulTruncateFault = typeof StatefulTruncateFault.Type
277
+
278
+ /** A status fault, or (`makeChunkedStatefulEmulator`) a truncation fault. */
279
+ export const StatefulStreamFault = Schema.Union([StatefulFault, StatefulTruncateFault])
280
+
281
+ export type StatefulStreamFault = typeof StatefulStreamFault.Type
282
+
283
+ export type StatefulFaultState<Fault = StatefulFault> = {
284
+ readonly id: number
285
+ readonly fault: Fault
286
+ /** Remaining matching requests; `undefined` for an unlimited fault. */
287
+ readonly remaining: number | undefined
288
+ readonly applied: number
289
+ }
290
+
291
+ export type StatefulLedgerEntry = {
292
+ /** 1-based arrival order since the last ledger clear or reset. */
293
+ readonly seq: number
294
+ readonly method: string
295
+ /**
296
+ * Raw request path; in fail-closed mode with guarded secrets scrubbed, in resolved mode the
297
+ * resolution's ledger path (scrubbed), and `/<unrecognised>` for an unrecognised request.
298
+ */
299
+ readonly path: string
300
+ /** Path template of the matched route. */
301
+ readonly route?: string
302
+ /** Query parameters; the values of credential-named keys are `<redacted>`. */
303
+ readonly query: Readonly<Record<string, string>>
304
+ /** Parsed JSON request body, with credential-named keys redacted at any depth. */
305
+ readonly body?: Schema.Json
306
+ /** Length of a raw (non-JSON) request body. */
307
+ readonly bodyBytes?: number
308
+ /**
309
+ * The non-credential request headers the emulator records (lower-case names); a JSON header is
310
+ * recorded with credential-named keys redacted at any depth, or as `<redacted>` when unparseable.
311
+ */
312
+ readonly headers: Readonly<Record<string, string>>
313
+ readonly status: number
314
+ /** Evidence of the matched route; `unknown-route` for requests on no route. */
315
+ readonly evidence: EmulatorEvidence | 'unknown-route'
316
+ /** Why the request was answered 400 not-emulated. */
317
+ readonly notEmulated?: string
318
+ /** Set when a fault answered the request (`truncate-after-chunks` cut its streamed body). */
319
+ readonly fault?: 'status' | 'truncate-after-chunks'
320
+ /** Set when the emulator could not build the response, or a route threw (answered 500). */
321
+ readonly responseError?: string
322
+ }
323
+
324
+ export type StatefulRouteCoverage = EmulatorRouteEvidence & {
325
+ /** Ledger requests on this route since the last ledger clear or reset. */
326
+ readonly requests: number
327
+ }
328
+
329
+ export type StatefulCoverage = {
330
+ readonly routes: ReadonlyArray<StatefulRouteCoverage>
331
+ /** Ledger requests on no route. */
332
+ readonly unknownRouteRequests: number
333
+ /** Ledger requests answered 400 not-emulated (on a route or not). */
334
+ readonly notEmulatedRequests: number
335
+ }
336
+
337
+ /**
338
+ * A ledger entry of an emulator built with `makeHeaderlessStatefulEmulator`, which records no
339
+ * request header and takes status faults only: the entry carries no `headers` field, no
340
+ * `bodyBytes` (it has no `bytes` routes), and only a `status` fault.
341
+ */
342
+ export type StatefulHeaderlessLedgerEntry = Omit<
343
+ StatefulLedgerEntry,
344
+ 'headers' | 'bodyBytes' | 'fault'
345
+ > & {
346
+ /** Set when a fault answered the request. */
347
+ readonly fault?: 'status'
348
+ }
349
+
350
+ /** One routed API request, as a route sees it. */
351
+ export type EmulatedRequest = {
352
+ readonly method: string
353
+ /** Raw (still percent-encoded) path; in resolved mode, the resolution's ledger path. */
354
+ readonly path: string
355
+ /**
356
+ * Path parameters, percent-decoded once; in resolved mode (`resolveRequest`), the parameters the
357
+ * resolution supplies (never a credential).
358
+ */
359
+ readonly params: Readonly<Record<string, string>>
360
+ readonly query: URLSearchParams
361
+ /**
362
+ * The raw query (after `?`, before `#`, never decoded; `''` without one), as the wrapper saw it.
363
+ * Absent on a request built elsewhere (then `exactQuery`'s `rawNames` refuses any parameter).
364
+ */
365
+ readonly rawQuery?: string | undefined
366
+ /**
367
+ * A non-credential request header (credential headers always read as `undefined`; in resolved
368
+ * mode, every header but `content-type` does).
369
+ */
370
+ readonly header: (name: string) => string | undefined
371
+ /**
372
+ * The lower-case names of every request header, credential headers included (names only, never
373
+ * a credential value); none in resolved mode. Absent on a request built elsewhere.
374
+ */
375
+ readonly headerNames?: ReadonlyArray<string> | undefined
376
+ /** Parsed JSON body (`json` routes, and `json-or-empty` routes with a body). */
377
+ readonly json: Schema.Json | undefined
378
+ /** Raw body (`bytes` routes). */
379
+ readonly bytes: Uint8Array | undefined
380
+ /**
381
+ * Fail-closed mode with `bearerDigest` only: the digest of the recognised bearer for the origin
382
+ * the request arrived on (never the bearer itself); `undefined` otherwise.
383
+ */
384
+ readonly bearerDigest?: string | undefined
385
+ }
386
+
387
+ export type RunContext<Env> = {
388
+ readonly env: Env
389
+ /** Ledger sequence number of the request (for synthetic request ids). */
390
+ readonly seq: number
391
+ }
392
+
393
+ /** The writing part of an eligible request: applies its change and answers. */
394
+ export type Commit = () => Response
395
+
396
+ /** A streamed answer: its status, headers, and body chunks (sent one per pull). */
397
+ export type StreamedAnswer = {
398
+ readonly status: number
399
+ readonly headers: Readonly<Record<string, string>>
400
+ /** The body chunks; none answers no body at all. */
401
+ readonly chunks: ReadonlyArray<string>
402
+ }
403
+
404
+ /**
405
+ * A commit whose answer the plan prepares: `answer` is sent (one chunk per pull) only after
406
+ * `commit` has written the request's change. Because the answer exists before anything is
407
+ * written, the wrapper decides faults against it: a status fault or a `truncate-after-chunks`
408
+ * fault (`makeChunkedStatefulEmulator`) answers without running `commit`, so a faulted request
409
+ * writes nothing. `persisted` lists the texts `commit` will store (minted ids, for example), which
410
+ * the opt-in output guard (`guardOutput`) checks together with the answer.
411
+ */
412
+ export type StreamedCommit = {
413
+ readonly answer: StreamedAnswer
414
+ readonly commit: () => void
415
+ readonly persisted: ReadonlyArray<string>
416
+ }
417
+
418
+ /** A streamed commit: the prepared `answer`, and the write (none by default) it commits. */
419
+ export const streamedCommit = (
420
+ answer: StreamedAnswer,
421
+ commit: () => void = () => undefined,
422
+ persisted: ReadonlyArray<string> = []
423
+ ): StreamedCommit => ({ answer, commit, persisted })
424
+
425
+ /** What a plan returns: a commit, a streamed commit, or not emulated. */
426
+ export type Planned = Commit | StreamedCommit | NotEmulated
427
+
428
+ /** An admitted request: its pure, state-reading eligibility check, returning the commit. */
429
+ export type Admission<State, Env> = {
430
+ readonly plan: (state: State, context: RunContext<Env>) => Planned
431
+ /**
432
+ * The path of the manifest variant the request was admitted as (`StatefulRouteBinding.variants`):
433
+ * required when the route has variants, absent otherwise.
434
+ */
435
+ readonly variant?: string
436
+ }
437
+
438
+ /**
439
+ * The body a route takes: none; JSON with an `application/json` media type; JSON of any media type
440
+ * or none (`json-or-empty`: an empty body is no body, any other must be valid JSON, and the route
441
+ * checks the media type itself); or raw bytes.
442
+ */
443
+ export type RouteBody = 'none' | 'json' | 'json-or-empty' | 'bytes'
444
+
445
+ /** Route parts that are not evidence: the recorded origin and the raw parameter patterns. */
446
+ export type StatefulRouteBinding = {
447
+ /** The origin a fixture records the route on; another origin is not emulated. Omitted: any. */
448
+ readonly origin?: string
449
+ /**
450
+ * Raw (still percent-encoded) patterns of the path parameters; a parameter that does not match
451
+ * its pattern makes the path match no route. Fail-closed emulators give every parameter one.
452
+ */
453
+ readonly params?: Readonly<Record<string, RegExp>>
454
+ /**
455
+ * Fail-closed mode only: texts the route derives from its raw body that the provider's wire
456
+ * format encodes in a way the percent and JSON closure cannot see through (for example base64url
457
+ * content). Each view is checked for the bearer like the raw body. A body that holds no such
458
+ * content yields no view. A view may throw to refuse a body whose encoded content it cannot
459
+ * check completely (for example content the route would refuse anyway); the request is then
460
+ * ledgered as the constant credential-repeat entry shape, before anything is recorded, a fault is
461
+ * decided, or anything is committed, with this reason:
462
+ *
463
+ * - `the request body repeats the credential` when the throw is a `DecodedViewRefusal` whose
464
+ * cleanly `decoded` texts hold the bearer (a repeat, not a refusal);
465
+ * - otherwise its `reason` when that is one of `viewRefusalReasons` (scrubbed of the bearer,
466
+ * defensively);
467
+ * - otherwise (an undeclared reason, or any other throw)
468
+ * `the request body cannot be checked for the credential`.
469
+ *
470
+ * Omitted: none.
471
+ */
472
+ readonly decodedViews?: (body: string) => ReadonlyArray<string>
473
+ /**
474
+ * The constant reasons a decoded view may refuse a body with (`DecodedViewRefusal`); any other
475
+ * reason is replaced by the uncheckable reason. Owned by the route, never derived from a request.
476
+ */
477
+ readonly viewRefusalReasons?: ReadonlyArray<string>
478
+ /**
479
+ * Opt-in: the manifest rows this route answers INSTEAD of its own (for example one row per
480
+ * JSON-RPC method on one HTTP endpoint, `{ method: 'RPC', path: '<origin><path>#<method>' }`).
481
+ * Each admission names its row (`Admission.variant`), which becomes the request's ledger route,
482
+ * its coverage row, and what a fault's `match.route` compares; a request refused before it is
483
+ * admitted keeps the route's own template. Every variant carries the route's evidence, and no
484
+ * variant path repeats another manifest row or a route template (checked at build). Omitted:
485
+ * the route is its own manifest row, as before.
486
+ */
487
+ readonly variants?: ReadonlyArray<EmulatorRouteEvidence>
488
+ }
489
+
490
+ export type StatefulRoute<State, Env> = EmulatorRouteEvidence &
491
+ StatefulRouteBinding & {
492
+ readonly body: RouteBody
493
+ /** The request-shape check (reads no state): an admission, or not emulated. */
494
+ readonly admit: (request: EmulatedRequest, env: Env) => Admission<State, Env> | NotEmulated
495
+ }
496
+
497
+ /**
498
+ * A route of the table: its evidence (and recorded origin), the body it takes, its request-shape
499
+ * check `admit` (no state), and `plan`, which only ever sees an admitted input: it reads the state
500
+ * without writing and answers not emulated or the commit that writes.
501
+ */
502
+ export const statefulRoute = <State, Env, Input>(
503
+ evidence: EmulatorRouteEvidence & StatefulRouteBinding,
504
+ body: RouteBody,
505
+ admit: (request: EmulatedRequest, env: Env) => Input | NotEmulated,
506
+ plan: (state: State, input: Input, context: RunContext<Env>) => Planned
507
+ ): StatefulRoute<State, Env> => ({
508
+ ...evidence,
509
+ body,
510
+ admit: (request, env) => {
511
+ const input = admit(request, env)
512
+
513
+ return isNotEmulated(input) ? input : { plan: (state, context) => plan(state, input, context) }
514
+ }
515
+ })
516
+
517
+ /** Route evidence without the handler parts. */
518
+ export const routeEvidence = <State, Env>({
519
+ body: _body,
520
+ admit: _admit,
521
+ origin: _origin,
522
+ params: _params,
523
+ decodedViews: _decodedViews,
524
+ viewRefusalReasons: _viewRefusalReasons,
525
+ variants: _variants,
526
+ ...evidence
527
+ }: StatefulRoute<State, Env>): EmulatorRouteEvidence => evidence
528
+
529
+ /** The manifest rows of a route: its variants, or the route itself (`routeEvidence`). */
530
+ export const routeManifest = <State, Env>(
531
+ route: StatefulRoute<State, Env>
532
+ ): ReadonlyArray<EmulatorRouteEvidence> => route.variants ?? [routeEvidence(route)]
533
+
534
+ /** A percent-decoded path segment, or `undefined` for invalid percent-encoding. */
535
+ export const decodeSegment = (segment: string): string | undefined => {
536
+ try {
537
+ return decodeURIComponent(segment)
538
+ } catch {
539
+ return undefined
540
+ }
541
+ }
542
+
543
+ // `{name}` is one path segment; `{name+}` is one or more segments.
544
+ const templatePattern = (template: string): RegExp =>
545
+ new RegExp(
546
+ `^${template
547
+ .split(/(\{[A-Za-z]+\+?\})/)
548
+ .map(part =>
549
+ /^\{[A-Za-z]+\}$/.test(part)
550
+ ? '([^/]+)'
551
+ : /^\{[A-Za-z]+\+\}$/.test(part)
552
+ ? '(.+)'
553
+ : part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
554
+ )
555
+ .join('')}$`
556
+ )
557
+
558
+ const templateNames = (template: string): ReadonlyArray<string> =>
559
+ [...template.matchAll(/\{([A-Za-z]+)\+?\}/g)].map(match => match[1] ?? '')
560
+
561
+ /**
562
+ * A multi-segment parameter decoded segment by segment (each once), or `undefined` for an empty
563
+ * segment, invalid percent-encoding, or a segment that decodes to a `/`.
564
+ */
565
+ const decodeSegments = (raw: string): string | undefined => {
566
+ const segments = raw.split('/').map(segment => {
567
+ const decoded = segment === '' ? undefined : decodeSegment(segment)
568
+
569
+ return decoded === undefined || decoded.includes('/') ? undefined : decoded
570
+ })
571
+
572
+ return segments.some(segment => segment === undefined) ? undefined : segments.join('/')
573
+ }
574
+
575
+ export type MatchedRoute<State, Env> = {
576
+ readonly route: StatefulRoute<State, Env>
577
+ readonly params: Readonly<Record<string, string>>
578
+ }
579
+
580
+ /**
581
+ * `pattern` required to match a whole raw parameter: `^(?:source)$` with its flags, so alternation
582
+ * and lazy quantifiers are tried against the whole value, never against a prefix of it.
583
+ */
584
+ const wholePattern = (pattern: RegExp): RegExp =>
585
+ new RegExp(`^(?:${pattern.source})$`, pattern.flags)
586
+
587
+ /**
588
+ * A matcher over a route table: the route answering `method` + raw `path`, with its parameters
589
+ * decoded once, or `undefined` (also for a parameter that is not valid percent-encoding). A raw
590
+ * parameter pattern must match the whole raw parameter; a pattern with the `g` or `y` flag (whose
591
+ * matches depend on earlier ones) is refused when the matcher is built.
592
+ */
593
+ export const routeMatcher = <State, Env>(routes: ReadonlyArray<StatefulRoute<State, Env>>) => {
594
+ const keys = routes.map(route => emulatorRouteKey(route.method, route.path))
595
+ const duplicate = keys.find((key, index) => keys.indexOf(key) !== index)
596
+
597
+ if (duplicate !== undefined) {
598
+ throw new Error(`duplicate emulator route ${duplicate}`)
599
+ }
600
+
601
+ for (const route of routes) {
602
+ for (const [name, pattern] of Object.entries(route.params ?? {})) {
603
+ if (pattern.global || pattern.sticky) {
604
+ const where = `${route.method} ${route.path} parameter ${name}`
605
+
606
+ throw new Error(`raw patterns take no g or y flag (${where})`)
607
+ }
608
+ }
609
+ }
610
+
611
+ const compiled = routes.map(route => ({
612
+ route,
613
+ pattern: templatePattern(route.path),
614
+ names: templateNames(route.path),
615
+ // Compiled when the matcher is built, so no request compiles a RegExp.
616
+ whole: new Map(
617
+ Object.entries(route.params ?? {}).map(([name, raw]) => [name, wholePattern(raw)] as const)
618
+ ),
619
+ multi: new Set([...route.path.matchAll(/\{([A-Za-z]+)\+\}/g)].map(match => match[1] ?? ''))
620
+ }))
621
+
622
+ return (method: string, path: string): MatchedRoute<State, Env> | undefined => {
623
+ for (const candidate of compiled) {
624
+ if (candidate.route.method !== method.toUpperCase()) continue
625
+
626
+ const match = candidate.pattern.exec(path)
627
+
628
+ if (match === null) continue
629
+
630
+ const raws = candidate.names.map((name, index) => [name, match[index + 1] ?? ''] as const)
631
+
632
+ // A raw parameter outside its pattern (matched in full) is no shape of this route.
633
+ if (
634
+ raws.some(([name, raw]) => {
635
+ const pattern = candidate.whole.get(name)
636
+
637
+ return pattern !== undefined && !pattern.test(raw)
638
+ })
639
+ ) {
640
+ continue
641
+ }
642
+
643
+ const params: Record<string, string> = {}
644
+
645
+ for (const [name, raw] of raws) {
646
+ const value = candidate.multi.has(name) ? decodeSegments(raw) : decodeSegment(raw)
647
+
648
+ if (value === undefined) return undefined
649
+
650
+ params[name] = value
651
+ }
652
+
653
+ return { route: candidate.route, params }
654
+ }
655
+
656
+ return undefined
657
+ }
658
+ }
659
+
660
+ /** The template parameters of a route that have no raw pattern (fail-closed emulators need one). */
661
+ export const unpatternedParams = <State, Env>(
662
+ route: StatefulRoute<State, Env>
663
+ ): ReadonlyArray<string> => templateNames(route.path).filter(name => !route.params?.[name])
664
+
665
+ const decodeJsonText = Schema.decodeUnknownResult(Schema.fromJsonString(Schema.Json))
666
+
667
+ /** Parsed JSON, or `undefined` for invalid JSON. */
668
+ export const parseJsonText = (text: string): Schema.Json | undefined => {
669
+ const result = decodeJsonText(text)
670
+
671
+ return Result.isSuccess(result) ? result.success : undefined
672
+ }
673
+
674
+ export const isJsonObject = (value: Schema.Json | undefined): value is Schema.JsonObject =>
675
+ value !== undefined && value !== null && Predicate.isObject(value) && !Array.isArray(value)
676
+
677
+ /**
678
+ * True when any object of a valid JSON text repeats a key, compared after JSON unescaping (so
679
+ * `"id"` and `"\u0069d"` are one key). `JSON.parse` would keep the last value silently.
680
+ */
681
+ export const repeatsJsonKey = (text: string): boolean => {
682
+ // One entry per open object or array: an object's keys so far, and whether a key comes next.
683
+ const open: Array<{ readonly keys: Set<string> | undefined; expectKey: boolean }> = []
684
+ let index = 0
685
+
686
+ while (index < text.length) {
687
+ const character = text[index]
688
+
689
+ if (character === '"') {
690
+ let end = index + 1
691
+
692
+ while (end < text.length && text[end] !== '"') end += text[end] === '\\' ? 2 : 1
693
+
694
+ const top = open.at(-1)
695
+
696
+ if (top?.keys !== undefined && top.expectKey) {
697
+ const key = parseJsonText(text.slice(index, end + 1))
698
+
699
+ if (!Predicate.isString(key) || top.keys.has(key)) return true
700
+
701
+ top.keys.add(key)
702
+ top.expectKey = false
703
+ }
704
+
705
+ index = end + 1
706
+ continue
707
+ }
708
+
709
+ if (character === '{') open.push({ keys: new Set(), expectKey: true })
710
+ else if (character === '[') open.push({ keys: undefined, expectKey: false })
711
+ else if (character === '}' || character === ']') open.pop()
712
+ else if (character === ',') {
713
+ const top = open.at(-1)
714
+
715
+ if (top?.keys !== undefined) top.expectKey = true
716
+ }
717
+
718
+ index += 1
719
+ }
720
+
721
+ return false
722
+ }
723
+
724
+ /** The media type of a `content-type` value (lower-case, without parameters). */
725
+ export const mediaType = (value: string | undefined): string =>
726
+ (value ?? '').split(';')[0]?.trim().toLowerCase() ?? ''
727
+
728
+ /**
729
+ * A JSON object with exactly the `required` keys plus any of the `optional` ones, or not
730
+ * emulated (naming the first missing or unknown key).
731
+ */
732
+ export const exactObject = (
733
+ value: Schema.Json | undefined,
734
+ label: string,
735
+ required: ReadonlyArray<string>,
736
+ optional: ReadonlyArray<string> = []
737
+ ): Schema.JsonObject | NotEmulated => {
738
+ if (!isJsonObject(value)) return notEmulated(`${label} must be a JSON object`)
739
+
740
+ const unknown = Object.keys(value).find(key => !required.includes(key) && !optional.includes(key))
741
+
742
+ if (unknown !== undefined) return notEmulated(`${label} key '${unknown}' is not emulated`)
743
+
744
+ const missing = required.find(key => !(key in value))
745
+
746
+ return missing === undefined
747
+ ? value
748
+ : notEmulated(`${label} without '${missing}' is not emulated`)
749
+ }
750
+
751
+ /**
752
+ * Constant-text shape check (for fail-closed emulators): a JSON object with exactly the `required`
753
+ * keys plus any of the `optional` ones, or not emulated. Unlike `exactObject`, a reason never
754
+ * echoes a request's own key; it names only `label` and a missing key from the route's own list.
755
+ */
756
+ export const exactBodyKeys = (
757
+ value: Schema.Json | undefined,
758
+ label: string,
759
+ required: ReadonlyArray<string>,
760
+ optional: ReadonlyArray<string> = []
761
+ ): Schema.JsonObject | NotEmulated => {
762
+ if (!isJsonObject(value)) return notEmulated(`${label} must be a JSON object`)
763
+
764
+ const keys = Object.keys(value)
765
+
766
+ if (keys.some(key => !required.includes(key) && !optional.includes(key))) {
767
+ return notEmulated(`${label} has a key this route does not take`)
768
+ }
769
+
770
+ const missing = required.find(key => !keys.includes(key))
771
+
772
+ return missing === undefined
773
+ ? value
774
+ : notEmulated(`${label} without '${missing}' is not emulated`)
775
+ }
776
+
777
+ /** Options of `exactQuery`. */
778
+ export type ExactQueryOptions = {
779
+ /**
780
+ * Opt-in: every raw parameter name (before `URLSearchParams` decodes it) must be written exactly
781
+ * as the route names it, so a percent-encoded or `+`-spaced spelling of an accepted name is not
782
+ * emulated. Omitted: names are compared decoded, as before.
783
+ */
784
+ readonly rawNames?: boolean
785
+ }
786
+
787
+ /** The raw parameter names of a raw query, in order (`[]` for an empty query). */
788
+ const rawQueryNames = (raw: string): ReadonlyArray<string> =>
789
+ raw === '' ? [] : raw.split('&').map(component => component.split('=', 1)[0] ?? '')
790
+
791
+ /**
792
+ * Constant-text query check (for fail-closed emulators): exactly the `required` query keys plus
793
+ * any of the `optional` ones, each once, as a record of their values; or not emulated. A reason
794
+ * never echoes a request's own key; it names only a missing key from the route's own list. With
795
+ * `rawNames`, every raw parameter name must also be the plain name it decodes to.
796
+ */
797
+ export const exactQuery = (
798
+ request: EmulatedRequest,
799
+ required: ReadonlyArray<string>,
800
+ optional: ReadonlyArray<string> = [],
801
+ options: ExactQueryOptions = {}
802
+ ): Readonly<Record<string, string>> | NotEmulated => {
803
+ const keys = [...request.query.keys()]
804
+
805
+ if (keys.length !== new Set(keys).size) {
806
+ return notEmulated('repeated query parameters are not emulated')
807
+ }
808
+
809
+ if (keys.some(key => !required.includes(key) && !optional.includes(key))) {
810
+ return notEmulated('a query parameter this route does not take is not emulated')
811
+ }
812
+
813
+ if (options.rawNames === true) {
814
+ const raw = rawQueryNames(request.rawQuery ?? '')
815
+
816
+ if (raw.length !== keys.length || raw.some((name, index) => name !== keys[index])) {
817
+ return notEmulated('a query parameter name in any but its plain form is not emulated')
818
+ }
819
+ }
820
+
821
+ const missing = required.find(key => !keys.includes(key))
822
+
823
+ return missing === undefined
824
+ ? Object.fromEntries(request.query)
825
+ : notEmulated(`requests without query parameter ${missing} are not emulated on this route`)
826
+ }
827
+
828
+ /** An integer in `[minimum, maximum]`, or not emulated. */
829
+ export const integerIn = (
830
+ value: Schema.Json | undefined,
831
+ label: string,
832
+ minimum: number,
833
+ maximum: number
834
+ ): number | NotEmulated =>
835
+ Predicate.isNumber(value) && Number.isSafeInteger(value) && value >= minimum && value <= maximum
836
+ ? value
837
+ : notEmulated(`${label} must be an integer from ${minimum} to ${maximum}`)
838
+
839
+ /** Error-input kinds of the JS API. */
840
+ export type StatefulInputKind = 'seed' | 'fault' | 'option'
841
+
842
+ /** The core runtime the Node subpath creates (state, snapshot, restore), as the wrapper uses it. */
843
+ export type StatefulCore<State> = {
844
+ readonly fetch: (request: Request) => Promise<Response>
845
+ readonly baseUrl: string
846
+ readonly snapshot: () => State
847
+ readonly restore: (state: State) => Promise<void>
848
+ readonly close: () => Promise<void>
849
+ }
850
+
851
+ /**
852
+ * What the core runs for a request the wrapper forwarded: `(state, request)` to a response. The
853
+ * Node subpath registers it as the core app's only route.
854
+ */
855
+ export type CoreDispatch<State> = (state: State, request: Request) => Response
856
+
857
+ /** A request header the ledger records. */
858
+ export type RecordedHeader = { readonly name: string; readonly json: boolean }
859
+
860
+ /**
861
+ * Fail-closed mode: the constant reasons ledgered and answered for an unrecognised request (no
862
+ * emulated route shape) and for an unrecognisable `Authorization` header. Nothing the request
863
+ * carries is ledgered or answered for either.
864
+ */
865
+ export type StatefulFailClosed = {
866
+ readonly unrecognised: string
867
+ readonly unrecognisedAuthorization: string
868
+ }
869
+
870
+ /**
871
+ * Resolved mode: what the emulator's `resolveRequest` decides for one API request, failing closed.
872
+ *
873
+ * - `unrecognised`: the raw request matches no emulated route shape exactly (or its credential
874
+ * cannot be extracted). It is ledgered and answered with constant text only
875
+ * (`/<unrecognised>`, the method as sent when it is a standard one, else `<other>`, an empty
876
+ * query, no headers or body, the constant `reason`).
877
+ * - `refused`: a recognised route refuses the request before its body is read (a missing
878
+ * credential, a query key it does not take); the entry keeps the request's scrubbed fields.
879
+ * - `route`: a recognised request, handed to `route` with the credential-free `params`.
880
+ *
881
+ * For `refused` and `route`, `ledgerPath` is the path the ledger records (and a fault's
882
+ * `match.path` compares), with the credential already replaced by the emulator if the path carries
883
+ * it; `secrets` are the credential values the emulator took from the recognised shape (a path
884
+ * segment, a header), which the wrapper scrubs from everything it ledgers or answers and refuses
885
+ * to see repeated. `guardedPath` is the request text besides the query that must not repeat a
886
+ * secret (the path without the segment that carries the credential, for example).
887
+ */
888
+ export type StatefulResolution<State, Env> =
889
+ | { readonly kind: 'unrecognised'; readonly reason: string }
890
+ | {
891
+ readonly kind: 'refused'
892
+ readonly route: StatefulRoute<State, Env>
893
+ readonly ledgerPath: string
894
+ readonly reason: string
895
+ readonly secrets: ReadonlyArray<string>
896
+ }
897
+ | {
898
+ readonly kind: 'route'
899
+ readonly route: StatefulRoute<State, Env>
900
+ readonly params: Readonly<Record<string, string>>
901
+ readonly ledgerPath: string
902
+ readonly guardedPath: string
903
+ readonly secrets: ReadonlyArray<string>
904
+ }
905
+
906
+ /**
907
+ * The emulator-owned texts of its recovery answers
908
+ * (`{ error: { type: 'emulator_error', message } }`): `failed` when a response cannot be built or a
909
+ * route throws (500), `closed` after `close` (503), and `unhandled` when handling the request
910
+ * itself fails (500).
911
+ */
912
+ export type StatefulErrorTexts = {
913
+ readonly failed: string
914
+ readonly closed: string
915
+ readonly unhandled: string
916
+ }
917
+
918
+ const defaultErrorTexts: StatefulErrorTexts = {
919
+ failed: 'the emulator could not build the response',
920
+ closed: 'the emulator is closed',
921
+ unhandled: 'the emulator failed to handle the request'
922
+ }
923
+
924
+ export type StatefulEmulatorConfig<State, Env> = {
925
+ readonly routes: ReadonlyArray<StatefulRoute<State, Env>>
926
+ readonly env: Env
927
+ readonly initial: State
928
+ /** Decode and build a seed; a string is why it is invalid. */
929
+ readonly buildSeed: (input: unknown) => State | string
930
+ /** Header rules every request must meet (after the credential); a string is not emulated. */
931
+ readonly requestProblem?: (header: (name: string) => string | undefined) => string | undefined
932
+ /**
933
+ * Non-credential request headers the ledger records (lower-case names). A `json` header is
934
+ * parsed and its credential-named keys redacted at any depth; an unparseable value is recorded
935
+ * as `<redacted>`. A credential header name is refused when the emulator is built.
936
+ */
937
+ readonly recordHeaders: ReadonlyArray<RecordedHeader>
938
+ /**
939
+ * Opt-in fail-closed mode (see the module header): constant-text ledger entries for unrecognised
940
+ * requests and Authorization headers, and the bearer value guarded as a secret. Every route
941
+ * parameter must have a raw pattern (checked when the emulator is built).
942
+ */
943
+ readonly failClosed?: StatefulFailClosed
944
+ /**
945
+ * Opt-in resolved mode (not with `failClosed`; checked when the emulator is built), for an
946
+ * emulator whose credential the wrapper cannot find by itself (a token in a path segment) or
947
+ * that has its own credential rules: the emulator resolves every API request itself
948
+ * (`StatefulResolution`) instead of the wrapper's route match and `Authorization` handling, and
949
+ * names the credential values to guard. The wrapper then records the resolution's ledger path
950
+ * and the query as sent (credential-named keys redacted), both scrubbed of the secrets, matches a
951
+ * fault's `match.path` against that ledger path, and refuses, before the request headers are
952
+ * checked or the body is parsed, a recognised request that repeats a secret: the raw query, the
953
+ * `guardedPath`, or the body, each raw or percent-decoded once (`repeatsSecret`), and a JSON body
954
+ * also in any key, string, or number once parsed and as it would be recorded
955
+ * (`jsonRepeatsSecret`). Those refusals keep the request's scrubbed fields and never record the
956
+ * body. Routes see the ledger path and no header names; fault answers and refusals are returned
957
+ * outside the core; `recordHeaders` must be empty (checked at build). See the module header.
958
+ * Omitted: the wrapper matches routes itself, as before.
959
+ */
960
+ readonly resolveRequest?: (request: Request, url: URL) => StatefulResolution<State, Env>
961
+ /**
962
+ * Opt-in: the texts of the emulator's recovery answers (`StatefulErrorTexts`). Omitted: the
963
+ * default texts, as before.
964
+ */
965
+ readonly errorTexts?: StatefulErrorTexts
966
+ /**
967
+ * Opt-in, fail-closed mode only (checked when the emulator is built): a one-way digest of a
968
+ * recognised bearer for the origin the request arrived on, handed to routes as
969
+ * `EmulatedRequest.bearerDigest`, never the bearer itself. A route compares it with digests its
970
+ * state holds (for example of the keys a seed marks as rejected on one origin), so a credential
971
+ * can change an answer without the bearer reaching the state, the ledger, or `/_emulate/*`.
972
+ * Taking the origin makes the digest per origin: one key gives different digests on two origins.
973
+ * A digest that throws or repeats the bearer (through the closure) answers the 500 emulator
974
+ * error before the route's shape check (no fault used, nothing written). Omitted: routes see no
975
+ * digest, as before.
976
+ */
977
+ readonly bearerDigest?: (bearer: string, origin: string) => string
978
+ /**
979
+ * Opt-in, fail-closed mode only (checked at build): per arrival origin, a fixed literal prefix
980
+ * (1 to 32 `b64token` characters) every bearer on that origin must start with. On such an origin
981
+ * an `Authorization` header is recognised only as `Bearer <prefix><remainder>`, and the
982
+ * REMAINDER, not the whole bearer, must be a recognisable bearer (`isRecognisableBearerValue`):
983
+ * it is the guarded secret (checked for repeats, scrubbed, never stored) and what `bearerDigest`
984
+ * receives. A bearer without the prefix is an unrecognisable `Authorization` header there. This
985
+ * serves keys whose fixed public prefix starts with a hex digit or an escape letter (an Afloat
986
+ * `afloat_` key), whose secret part is guarded instead, as resolved mode guards a Telegram bot
987
+ * token's secret part. Other origins keep the plain rule. Omitted: the plain rule everywhere, as
988
+ * before.
989
+ */
990
+ readonly bearerPrefixes?: Readonly<Record<string, string>>
991
+ /**
992
+ * Opt-in, fail-closed mode only (checked at build): every refusal is ledgered with constant text
993
+ * only, like an unrecognised request (`/<unrecognised>`, a standard method or `<other>`, an
994
+ * empty query, no headers or body), keeping only its constant route (template or variant) and
995
+ * reason, so a ledger entry holds request text only once the route admitted the request. Route
996
+ * reasons must then be constants. Omitted: refusals keep the request's recorded fields, as
997
+ * before.
998
+ */
999
+ readonly constantRefusals?: boolean
1000
+ /**
1001
+ * Opt-in, fail-closed mode only (checked at build): every request header other than
1002
+ * `Authorization`, its name and its value, is checked for a credential repeat through the
1003
+ * closure (not only the recorded headers), independently of what the ledger records; a repeat is
1004
+ * refused with the constant credential-repeat entry (`a request header repeats the credential`).
1005
+ * Omitted: only the recorded headers are checked, as before.
1006
+ */
1007
+ readonly guardAllHeaders?: boolean
1008
+ /**
1009
+ * Opt-in, fail-closed mode only (checked at build): a recognised request's prepared output must
1010
+ * not repeat its bearer. Every plan answers a `StreamedCommit` (a plain `Commit` answers the 500
1011
+ * emulator error), and before any fault is decided or anything is committed, every answer header
1012
+ * name and value, every answer chunk, and every `persisted` text are checked for the bearer
1013
+ * through the closure; a hit is refused with the constant credential-repeat entry
1014
+ * (`the answer would repeat the credential`), no fault used and nothing written. Routes still see
1015
+ * only the bearer's digest. Omitted: answers are not checked, as before.
1016
+ */
1017
+ readonly guardOutput?: boolean
1018
+ /**
1019
+ * Opt-in: a JSON body in which any object repeats a key (after JSON unescaping, so `"id"` and
1020
+ * `"\u0069d"` are one key) is not emulated (`a JSON body with a repeated key is not emulated`),
1021
+ * instead of `JSON.parse` keeping the last value. Omitted: the last value wins, as before.
1022
+ */
1023
+ readonly uniqueJsonKeys?: boolean
1024
+ /** Clear runtime data (cursors) on reset and seed. */
1025
+ readonly clearRuntime: () => void
1026
+ /** Extra `/_emulate/state` fields (runtime data). */
1027
+ readonly runtimeState: () => Schema.JsonObject
1028
+ /** The `/_emulate/seed` answer for a new state. */
1029
+ readonly seedSummary: (state: State) => Schema.JsonObject
1030
+ readonly inputInvalid: (input: StatefulInputKind, reason: string) => Error
1031
+ }
1032
+
1033
+ export type StatefulEmulatorApi<State, Seed, Fault = StatefulFault, Entry = StatefulLedgerEntry> = {
1034
+ /**
1035
+ * The fetch handler (API routes and `/_emulate/*`); a request arrives on the origin of its URL.
1036
+ * Never rejects.
1037
+ */
1038
+ readonly fetch: (request: Request) => Promise<Response>
1039
+ /**
1040
+ * The fetch handler for requests that arrive on `origin` whatever their URL says (serve it on
1041
+ * a loopback server behind `EmulatedHttpClient`, which rewrites the origin). Never rejects.
1042
+ */
1043
+ readonly fetchOn: (origin: string) => (request: Request) => Promise<Response>
1044
+ readonly ledger: {
1045
+ readonly entries: () => ReadonlyArray<Entry>
1046
+ readonly clear: () => void
1047
+ }
1048
+ readonly faults: {
1049
+ /** Add a fault; throws the emulator's input-invalid error for an invalid fault. */
1050
+ readonly add: (fault: Fault) => StatefulFaultState<Fault>
1051
+ readonly list: () => ReadonlyArray<StatefulFaultState<Fault>>
1052
+ readonly clear: () => void
1053
+ }
1054
+ /** Restore the current seed and clear the ledger, faults, and runtime data (cursors). */
1055
+ readonly reset: () => Promise<void>
1056
+ /**
1057
+ * Replace the state with a new seed, which becomes what `reset` restores (runtime data is
1058
+ * cleared). Rejects with the emulator's input-invalid error for an invalid seed.
1059
+ */
1060
+ readonly seed: (seed: Seed) => Promise<void>
1061
+ /** A deep copy of the current state. */
1062
+ readonly snapshot: () => State
1063
+ readonly coverage: () => StatefulCoverage
1064
+ /** Close the core runtime. Later requests answer 503. Idempotent. */
1065
+ readonly close: () => Promise<void>
1066
+ }
1067
+
1068
+ const strict = { onExcessProperty: 'error' } as const
1069
+
1070
+ const decodeFault = Schema.decodeUnknownResult(StatefulFault, strict)
1071
+
1072
+ const decodeFaultList = Schema.decodeUnknownResult(
1073
+ Schema.Union([StatefulFault, Schema.Struct({ faults: Schema.Array(StatefulFault) })]),
1074
+ strict
1075
+ )
1076
+
1077
+ const decodeStreamFault = Schema.decodeUnknownResult(StatefulStreamFault, strict)
1078
+
1079
+ const decodeStreamFaultList = Schema.decodeUnknownResult(
1080
+ Schema.Union([StatefulStreamFault, Schema.Struct({ faults: Schema.Array(StatefulStreamFault) })]),
1081
+ strict
1082
+ )
1083
+
1084
+ const issueMessage = (issue: Schema.SchemaError['issue']): string =>
1085
+ new Schema.SchemaError(issue).message
1086
+
1087
+ // A non-empty bearer credential. The value is never checked, stored, forwarded, or ledgered.
1088
+ const bearerPattern = /^bearer\s+\S+/i
1089
+
1090
+ /**
1091
+ * Fail-closed mode: exactly `Bearer `, one space, and one token of at least 8 non-space characters
1092
+ * (no other scheme spelling, no extra words, so combined duplicate headers never match). The token
1093
+ * must also match the RFC 6750 `b64token` syntax, start with a character that completes no escape
1094
+ * (not a hex digit, not `n`, `r`, `t`, `u`), and hold a character outside the JSON-number alphabet
1095
+ * (`isRecognisableBearerValue`, which says why). The value is guarded, never compared against
1096
+ * anything, stored, or ledgered.
1097
+ */
1098
+ const recognisableBearerPattern = /^Bearer ([^\s]{8,})$/
1099
+
1100
+ /**
1101
+ * The fail-closed secret of an `Authorization` header, or `undefined` when unrecognisable. Without
1102
+ * a `prefix` it is the whole bearer. With one (`bearerPrefixes`, for the origin the request arrived
1103
+ * on) the bearer must be `<prefix><remainder>`, and the secret is the remainder: it, not the
1104
+ * bearer, must be recognisable (a key whose fixed prefix starts with a hex digit or an escape
1105
+ * letter guards its secret part, the Telegram precedent).
1106
+ */
1107
+ const recognisableBearer = (
1108
+ authorization: string | null,
1109
+ prefix: string | undefined
1110
+ ): string | undefined => {
1111
+ const bearer = recognisableBearerPattern.exec(authorization ?? '')?.[1]
1112
+
1113
+ if (bearer === undefined) return undefined
1114
+
1115
+ const secret =
1116
+ prefix === undefined ? bearer : bearer.startsWith(prefix) ? bearer.slice(prefix.length) : ''
1117
+
1118
+ return isRecognisableBearerValue(secret) ? secret : undefined
1119
+ }
1120
+
1121
+ /** A `bearerPrefixes` prefix: 1 to 32 `b64token` characters (no `=`). */
1122
+ const bearerPrefixPattern = /^[A-Za-z0-9\-._~+/]{1,32}$/
1123
+
1124
+ /** The raw query of a request URL (after `?`, before `#`), or `undefined` when it has none. */
1125
+ const rawQuery = (requestUrl: string): string | undefined => {
1126
+ const withoutFragment = requestUrl.split('#', 1)[0] ?? ''
1127
+ const start = withoutFragment.indexOf('?')
1128
+
1129
+ return start === -1 ? undefined : withoutFragment.slice(start + 1)
1130
+ }
1131
+
1132
+ /** True for a bare `?` or an empty `&`-separated component (`URLSearchParams` drops both). */
1133
+ const hasEmptyQueryComponent = (requestUrl: string): boolean => {
1134
+ const query = rawQuery(requestUrl)
1135
+
1136
+ return query !== undefined && query.split('&').some(component => component === '')
1137
+ }
1138
+
1139
+ /**
1140
+ * Fail-closed mode: a query key or value or a header value that starts like a JSON object, array,
1141
+ * or string (`{`, `[`, `"`) is recorded parsed with credential-named keys redacted at any depth, or
1142
+ * whole as `<redacted>` when it does not parse; any other text (numbers included) is recorded
1143
+ * unchanged. A request whose text repeats a guarded secret never gets here: it is ledgered with
1144
+ * constant text only.
1145
+ */
1146
+ const recordedJsonLooking = (text: string): string => {
1147
+ const trimmed = text.trimStart()
1148
+
1149
+ if (!trimmed.startsWith('{') && !trimmed.startsWith('[') && !trimmed.startsWith('"')) {
1150
+ return text
1151
+ }
1152
+
1153
+ const parsed = parseJsonText(text)
1154
+
1155
+ return parsed === undefined
1156
+ ? redactedCredentialValue
1157
+ : JSON.stringify(redactCredentialFields(parsed))
1158
+ }
1159
+
1160
+ /**
1161
+ * Fail-closed mode: the recorded query, built from every original pair (never one value per key)
1162
+ * and keyed by recorded key: credential-named keys have their values redacted, keys and values are
1163
+ * recorded as `recordedJsonLooking` does, and a key recorded more than once (two original keys may
1164
+ * record alike, for example two unparseable JSON-looking keys as `<redacted>`) lists its values in
1165
+ * order, as a JSON array.
1166
+ */
1167
+ const recordedQueryPairs = (
1168
+ query: URLSearchParams,
1169
+ scrub: (text: string) => string
1170
+ ): Readonly<Record<string, string>> => {
1171
+ const values = new Map<string, Array<string>>()
1172
+
1173
+ for (const [key, value] of query) {
1174
+ const recordedKey = scrub(recordedJsonLooking(key))
1175
+
1176
+ const recordedValue = scrub(
1177
+ isCredentialQueryKey(key) ? redactedCredentialValue : recordedJsonLooking(value)
1178
+ )
1179
+
1180
+ values.set(recordedKey, [...(values.get(recordedKey) ?? []), recordedValue])
1181
+ }
1182
+
1183
+ return Object.fromEntries(
1184
+ [...values].map(([key, list]) => [
1185
+ key,
1186
+ list.length === 1 ? (list[0] ?? '') : JSON.stringify(list)
1187
+ ])
1188
+ )
1189
+ }
1190
+
1191
+ /** The constant reason of a body a route's decoded view refuses to check (the view threw). */
1192
+ const uncheckableBodyReason = 'the request body cannot be checked for the credential'
1193
+
1194
+ const missingBearerReason =
1195
+ 'requests without Authorization: Bearer <token of at least 8 characters> are not emulated'
1196
+
1197
+ const pathMatches = (pattern: string, path: string): boolean =>
1198
+ pattern.endsWith('*') ? path.startsWith(pattern.slice(0, -1)) : pattern === path
1199
+
1200
+ const faultMatches = (
1201
+ fault: StatefulStreamFault,
1202
+ method: string,
1203
+ path: string,
1204
+ route: string | undefined
1205
+ ): boolean =>
1206
+ (fault.match?.method === undefined || fault.match.method.toUpperCase() === method) &&
1207
+ (fault.match?.path === undefined || pathMatches(fault.match.path, path)) &&
1208
+ (fault.match?.route === undefined || fault.match.route === route)
1209
+
1210
+ const faultBody = (status: number): Schema.Json => ({
1211
+ error: { type: 'emulator_fault', message: `Emulator fault: status ${status}.` }
1212
+ })
1213
+
1214
+ const readText = (request: Request): Promise<string | undefined> =>
1215
+ request.text().then(
1216
+ text => text,
1217
+ () => undefined
1218
+ )
1219
+
1220
+ const readBytes = (request: Request): Promise<Uint8Array | undefined> =>
1221
+ request.arrayBuffer().then(
1222
+ buffer => new Uint8Array(buffer),
1223
+ () => undefined
1224
+ )
1225
+
1226
+ const isControlPath = (path: string): boolean =>
1227
+ path === '/_emulate' || path.startsWith('/_emulate/')
1228
+
1229
+ type MutableLedgerEntry = {
1230
+ seq: number
1231
+ method: string
1232
+ path: string
1233
+ route?: string
1234
+ query: Readonly<Record<string, string>>
1235
+ body?: Schema.Json
1236
+ bodyBytes?: number
1237
+ headers: Record<string, string>
1238
+ status: number
1239
+ evidence: EmulatorEvidence | 'unknown-route'
1240
+ notEmulated?: string
1241
+ fault?: 'status' | 'truncate-after-chunks'
1242
+ responseError?: string
1243
+ }
1244
+
1245
+ type MutableFaultState = {
1246
+ readonly id: number
1247
+ readonly fault: StatefulStreamFault
1248
+ remaining: number | undefined
1249
+ applied: number
1250
+ }
1251
+
1252
+ /** How the first matching fault shapes an eligible request's answer. */
1253
+ type FaultDecision =
1254
+ | { readonly kind: 'none' }
1255
+ | { readonly kind: 'answer'; readonly response: Response }
1256
+ | { readonly kind: 'truncate'; readonly after: number }
1257
+
1258
+ type Job<State, Env> = {
1259
+ readonly admission: Admission<State, Env>
1260
+ /** Ledger sequence number of the request (for synthetic request ids). */
1261
+ readonly seq: number
1262
+ /**
1263
+ * Decides the first matching fault for an answer of `chunks` streamed chunks (`undefined` for an
1264
+ * answer that is not streamed), using it up when it applies.
1265
+ */
1266
+ readonly decideFault: (chunks: number | undefined) => FaultDecision
1267
+ /** Guarded credential values, scrubbed from a plan's not-emulated reason. */
1268
+ readonly secrets: ReadonlyArray<string>
1269
+ notEmulated?: string
1270
+ /** Set when `guardOutput` refused the prepared output (a constant credential-repeat entry). */
1271
+ credentialRepeat?: boolean
1272
+ /** Resolved mode: the fault's answer, decided in the core but returned outside it. */
1273
+ faultAnswer?: Response
1274
+ /** Set when the core ran the dispatch for this job (it may answer without it, when closed). */
1275
+ dispatched?: boolean
1276
+ }
1277
+
1278
+ const withEvidence = (response: Response, evidence: EmulatorEvidence): Response => {
1279
+ const headers = new Headers(response.headers)
1280
+
1281
+ if (evidence === 'unverified') {
1282
+ headers.set(emulatorEvidenceHeader, 'unverified')
1283
+ }
1284
+
1285
+ return new Response(response.body, {
1286
+ status: response.status,
1287
+ statusText: response.statusText,
1288
+ headers
1289
+ })
1290
+ }
1291
+
1292
+ /**
1293
+ * The recorded query: credential-named keys redacted, and any value that parses as a JSON object or
1294
+ * array (Dropbox's browser-style `arg` parameter, for example) recorded with its credential-named
1295
+ * keys redacted at any depth, and a JSON-looking value that does not parse recorded as `<redacted>`,
1296
+ * as a recorded JSON header is.
1297
+ */
1298
+ const recordedQuery = (query: URLSearchParams): Readonly<Record<string, string>> =>
1299
+ Object.fromEntries(
1300
+ Object.entries(redactCredentialQuery(query)).map(([key, value]) => {
1301
+ if (!value.trimStart().startsWith('{') && !value.trimStart().startsWith('[')) {
1302
+ return [key, value]
1303
+ }
1304
+
1305
+ // A JSON-looking value that does not parse cannot be redacted field by field: record it
1306
+ // whole as redacted, as a recorded JSON header is.
1307
+ const parsed = parseJsonText(value)
1308
+
1309
+ return [
1310
+ key,
1311
+ parsed === undefined
1312
+ ? redactedCredentialValue
1313
+ : JSON.stringify(redactCredentialFields(parsed))
1314
+ ]
1315
+ })
1316
+ )
1317
+
1318
+ /** A recorded header value: JSON with credential-named keys redacted, or the plain value. */
1319
+ const recordedHeaderValue = (header: RecordedHeader, value: string): string => {
1320
+ if (!header.json) return value
1321
+
1322
+ const parsed = parseJsonText(value)
1323
+
1324
+ return parsed === undefined
1325
+ ? redactedCredentialValue
1326
+ : JSON.stringify(redactCredentialFields(parsed))
1327
+ }
1328
+
1329
+ /** The request text a ledger entry records (constant in a `constantRefusals` refusal). */
1330
+ type RecordedFields = Pick<MutableLedgerEntry, 'method' | 'path' | 'query' | 'headers'> & {
1331
+ body?: Schema.Json
1332
+ bodyBytes?: number
1333
+ }
1334
+
1335
+ /** `constantRefusals`: a refused request's entry keeps only constant text. */
1336
+ const blankEntry = (entry: MutableLedgerEntry) => {
1337
+ entry.method = unrecognisedMethod(entry.method.toUpperCase())
1338
+ entry.path = unrecognisedLedgerPath
1339
+ entry.query = {}
1340
+ entry.headers = {}
1341
+ delete entry.body
1342
+ delete entry.bodyBytes
1343
+ }
1344
+
1345
+ const snapshotEntry = (entry: MutableLedgerEntry): StatefulLedgerEntry => ({
1346
+ ...entry,
1347
+ query: { ...entry.query },
1348
+ headers: { ...entry.headers }
1349
+ })
1350
+
1351
+ /** Whether an entry records no truncation fault (only a status fault, if any). */
1352
+ const hasStatusFaultOnly = <Entry extends { readonly fault?: MutableLedgerEntry['fault'] }>(
1353
+ entry: Entry
1354
+ ): entry is Entry & { readonly fault?: 'status' } => entry.fault !== 'truncate-after-chunks'
1355
+
1356
+ /** `makeHeaderlessStatefulEmulator`: the entry without its (always empty) `headers` field. */
1357
+ const snapshotHeaderlessEntry = ({
1358
+ headers: _headers,
1359
+ bodyBytes: _bodyBytes,
1360
+ ...entry
1361
+ }: MutableLedgerEntry): StatefulHeaderlessLedgerEntry => {
1362
+ const copy = { ...entry, query: { ...entry.query } }
1363
+
1364
+ if (hasStatusFaultOnly(copy)) return copy
1365
+
1366
+ // Unreachable: a headerless emulator decodes status faults only.
1367
+ throw new Error('a headerless stateful emulator records status faults only')
1368
+ }
1369
+
1370
+ /**
1371
+ * Resolved mode: the constant reason when the raw query or the resolution's `guardedPath` repeats a
1372
+ * guarded secret (`repeatsSecret`: raw, and percent-decoded once), or `undefined`. Checked before
1373
+ * the body is read, so such a refusal leaves the request body unread.
1374
+ */
1375
+ const partsCredentialRepeat = (
1376
+ url: URL,
1377
+ guardedPath: string,
1378
+ secrets: ReadonlyArray<string>
1379
+ ): string | undefined => {
1380
+ if (repeatsSecret(url.search, secrets)) return 'the query repeats the credential'
1381
+
1382
+ return repeatsSecret(guardedPath, secrets) ? 'the request path repeats the credential' : undefined
1383
+ }
1384
+
1385
+ /**
1386
+ * Resolved mode: the constant reason when the body text repeats a guarded secret, or `undefined`:
1387
+ * `repeatsSecret` on the raw text, and for a body that parses as JSON also `jsonRepeatsSecret`
1388
+ * (every key, string, and number) and as it would be recorded. A body that cannot be read or parsed
1389
+ * is left to the route's body check.
1390
+ */
1391
+ const bodyCredentialRepeat = (
1392
+ text: string | undefined,
1393
+ secrets: ReadonlyArray<string>
1394
+ ): string | undefined => {
1395
+ if (text === undefined || text === '') return undefined
1396
+
1397
+ const repeat = 'the request body repeats the credential'
1398
+
1399
+ if (repeatsSecret(text, secrets)) return repeat
1400
+
1401
+ const json = parseJsonText(text)
1402
+
1403
+ // Normalised forms (`\u0051` escapes, `1.2345678e7` numbers) only show once parsed.
1404
+ return json !== undefined &&
1405
+ (jsonRepeatsSecret(json, secrets) || repeatsSecret(JSON.stringify(json), secrets))
1406
+ ? repeat
1407
+ : undefined
1408
+ }
1409
+
1410
+ /** The body as `Request.text()` reads it: UTF-8, a leading byte order mark dropped. */
1411
+ const bodyText = (bytes: Uint8Array): string => new TextDecoder().decode(bytes)
1412
+
1413
+ const snapshotFault = (state: MutableFaultState): StatefulFaultState<StatefulStreamFault> => ({
1414
+ ...state
1415
+ })
1416
+
1417
+ const isStreamedCommit = (planned: Commit | StreamedCommit): planned is StreamedCommit =>
1418
+ !Predicate.isFunction(planned)
1419
+
1420
+ /** The constant reason of a prepared output that would repeat the bearer (`guardOutput`). */
1421
+ const outputRepeatReason = 'the answer would repeat the credential'
1422
+
1423
+ /**
1424
+ * `guardOutput`: whether a streamed commit's answer (every header name and value, every chunk, and
1425
+ * the whole body) or any text it would persist repeats a guarded secret, through the closure.
1426
+ */
1427
+ const outputRepeatsSecret = (planned: StreamedCommit, secrets: ReadonlyArray<string>): boolean => {
1428
+ const { answer } = planned
1429
+
1430
+ return [
1431
+ ...Object.entries(answer.headers).flat(),
1432
+ ...answer.chunks,
1433
+ answer.chunks.join(''),
1434
+ ...planned.persisted
1435
+ ].some(text => textRepeatsSecret(text, secrets))
1436
+ }
1437
+
1438
+ /**
1439
+ * A streamed answer's body, strictly pull-driven (one chunk per pull), closed cleanly after
1440
+ * `after` chunks when a truncation fault applies; no body at all for an answer without chunks.
1441
+ */
1442
+ const streamedResponse = (answer: StreamedAnswer, after: number | undefined): Response => {
1443
+ if (answer.chunks.length === 0) {
1444
+ return new Response(null, { status: answer.status, headers: answer.headers })
1445
+ }
1446
+
1447
+ const encoder = new TextEncoder()
1448
+ const sent = after === undefined ? answer.chunks : answer.chunks.slice(0, after)
1449
+ let next = 0
1450
+
1451
+ const body = new ReadableStream<Uint8Array>(
1452
+ {
1453
+ pull: controller => {
1454
+ const chunk = sent[next]
1455
+
1456
+ if (chunk === undefined) {
1457
+ controller.close()
1458
+
1459
+ return
1460
+ }
1461
+
1462
+ next += 1
1463
+ controller.enqueue(encoder.encode(chunk))
1464
+ }
1465
+ },
1466
+ { highWaterMark: 0 }
1467
+ )
1468
+
1469
+ return new Response(body, { status: answer.status, headers: answer.headers })
1470
+ }
1471
+
1472
+ /**
1473
+ * Build the wrapper over a core runtime (`makeStatefulEmulator`, with truncation faults
1474
+ * `makeChunkedStatefulEmulator`, or without ledgered headers `makeHeaderlessStatefulEmulator`).
1475
+ * `createCore` receives the dispatch the core must run for every request (its only route) and
1476
+ * returns the runtime adapter; `snapshotLedgerEntry` copies a ledger entry for readers.
1477
+ */
1478
+ const buildStatefulEmulator = async <State, Env, Seed, Entry>(
1479
+ config: StatefulEmulatorConfig<State, Env>,
1480
+ createCore: (dispatch: CoreDispatch<State>) => Promise<StatefulCore<State>>,
1481
+ chunkFaults: boolean,
1482
+ snapshotLedgerEntry: (entry: MutableLedgerEntry) => Entry
1483
+ ): Promise<StatefulEmulatorApi<State, Seed, StatefulStreamFault, Entry>> => {
1484
+ const credentialHeader = config.recordHeaders.find(header => isCredentialHeaderName(header.name))
1485
+
1486
+ if (credentialHeader !== undefined) {
1487
+ throw new Error(`the ledger never records the credential header ${credentialHeader.name}`)
1488
+ }
1489
+
1490
+ if (config.resolveRequest !== undefined && config.failClosed !== undefined) {
1491
+ throw new Error('resolveRequest (resolved mode) and failClosed exclude each other')
1492
+ }
1493
+
1494
+ // Resolved mode checks no request header for a credential repeat, so it records none.
1495
+ if (config.resolveRequest !== undefined && config.recordHeaders.length > 0) {
1496
+ throw new Error('resolveRequest (resolved mode) records no request header (recordHeaders)')
1497
+ }
1498
+
1499
+ const resolveRequest = config.resolveRequest
1500
+ const errorTexts = config.errorTexts ?? defaultErrorTexts
1501
+
1502
+ if (config.bearerDigest !== undefined && config.failClosed === undefined) {
1503
+ throw new Error('bearerDigest needs fail-closed mode (failClosed)')
1504
+ }
1505
+
1506
+ if (config.bearerPrefixes !== undefined) {
1507
+ if (config.failClosed === undefined) {
1508
+ throw new Error('bearerPrefixes needs fail-closed mode (failClosed)')
1509
+ }
1510
+
1511
+ for (const [origin, prefix] of Object.entries(config.bearerPrefixes)) {
1512
+ if (!URL.canParse(origin) || new URL(origin).origin !== origin) {
1513
+ throw new Error(`bearerPrefixes takes origins only (${origin})`)
1514
+ }
1515
+
1516
+ if (!bearerPrefixPattern.test(prefix)) {
1517
+ throw new Error(`bearerPrefixes takes 1 to 32 b64token characters (${origin})`)
1518
+ }
1519
+ }
1520
+ }
1521
+
1522
+ for (const option of ['constantRefusals', 'guardAllHeaders', 'guardOutput'] as const) {
1523
+ if (config[option] === true && config.failClosed === undefined) {
1524
+ throw new Error(`${option} needs fail-closed mode (failClosed)`)
1525
+ }
1526
+ }
1527
+
1528
+ const constantRefusals = config.constantRefusals === true
1529
+ const templates = new Set(config.routes.map(route => route.path))
1530
+ const variantRows = new Set<string>()
1531
+
1532
+ for (const route of config.routes) {
1533
+ if (route.variants === undefined) continue
1534
+
1535
+ if (route.variants.length === 0) {
1536
+ throw new Error(`route ${route.method} ${route.path} has an empty variants list`)
1537
+ }
1538
+
1539
+ for (const variant of route.variants) {
1540
+ const where = `variant ${variant.method} ${variant.path} of ${route.method} ${route.path}`
1541
+
1542
+ if (variant.evidence !== route.evidence) {
1543
+ throw new Error(`${where} must carry its route's evidence`)
1544
+ }
1545
+
1546
+ if (templates.has(variant.path) || variantRows.has(variant.path)) {
1547
+ throw new Error(`${where} repeats a route template or another variant path`)
1548
+ }
1549
+
1550
+ variantRows.add(variant.path)
1551
+ }
1552
+ }
1553
+
1554
+ if (config.failClosed !== undefined) {
1555
+ for (const route of config.routes) {
1556
+ const missing = unpatternedParams(route)
1557
+
1558
+ if (missing.length > 0) {
1559
+ const where = `fail-closed route ${route.method} ${route.path}`
1560
+
1561
+ throw new Error(`${where} needs raw patterns for ${missing.join(', ')}`)
1562
+ }
1563
+ }
1564
+ }
1565
+
1566
+ const match = routeMatcher(config.routes)
1567
+ const manifest = config.routes.flatMap(routeManifest)
1568
+ const manifestPaths = new Set(manifest.map(row => row.path))
1569
+ const jobs = new Map<number, Job<State, Env>>()
1570
+ let nextJobId = 1
1571
+
1572
+ // Plan, fault decision, and commit run synchronously together: no request interleaves.
1573
+ const dispatch: CoreDispatch<State> = (state, request) => {
1574
+ const job = jobs.get(Number(request.headers.get(emulatorJobHeader) ?? 'NaN'))
1575
+
1576
+ if (job === undefined) return handlerFailedResponse()
1577
+
1578
+ job.dispatched = true
1579
+
1580
+ try {
1581
+ const planned = job.admission.plan(state, { env: config.env, seq: job.seq })
1582
+
1583
+ if (isNotEmulated(planned)) {
1584
+ // Resolved mode keeps every refusal reason percent-encodable: one that is not (an unpaired
1585
+ // surrogate) is a handler failure.
1586
+ if (
1587
+ resolveRequest !== undefined &&
1588
+ Result.isFailure(Result.try(() => encodeURIComponent(planned.reason)))
1589
+ ) {
1590
+ return handlerFailedResponse()
1591
+ }
1592
+
1593
+ const reason = scrubSecrets(planned.reason, job.secrets)
1594
+
1595
+ job.notEmulated = reason
1596
+
1597
+ // Resolved mode: the wrapper answers the refusal itself, outside the core.
1598
+ return resolveRequest === undefined ? notEmulatedResponse(reason) : answeredOutsideCore()
1599
+ }
1600
+
1601
+ const streamed = isStreamedCommit(planned)
1602
+
1603
+ // `guardOutput`: the prepared answer and the texts the commit would store must not repeat
1604
+ // the bearer; checked before any fault is decided or anything is written.
1605
+ if (config.guardOutput === true) {
1606
+ if (!streamed) return handlerFailedResponse()
1607
+
1608
+ if (outputRepeatsSecret(planned, job.secrets)) {
1609
+ job.notEmulated = outputRepeatReason
1610
+ job.credentialRepeat = true
1611
+
1612
+ return notEmulatedResponse(outputRepeatReason)
1613
+ }
1614
+ }
1615
+
1616
+ const decision = job.decideFault(streamed ? planned.answer.chunks.length : undefined)
1617
+
1618
+ if (decision.kind === 'answer') {
1619
+ if (resolveRequest === undefined) return decision.response
1620
+
1621
+ // Resolved mode: the fault's answer is returned outside the core, so a reset or a close
1622
+ // before it is read never cancels it.
1623
+ job.faultAnswer = decision.response
1624
+
1625
+ return answeredOutsideCore()
1626
+ }
1627
+
1628
+ if (!streamed) return planned()
1629
+
1630
+ // A truncated answer is the prepared one cut short; its commit never runs.
1631
+ if (decision.kind === 'truncate') return streamedResponse(planned.answer, decision.after)
1632
+
1633
+ planned.commit()
1634
+
1635
+ return streamedResponse(planned.answer, undefined)
1636
+ } catch {
1637
+ return handlerFailedResponse()
1638
+ }
1639
+ }
1640
+
1641
+ const core = await createCore(dispatch)
1642
+
1643
+ let baseline: State = config.initial
1644
+ let entries: Array<MutableLedgerEntry> = []
1645
+ let faultStates: Array<MutableFaultState> = []
1646
+ let nextSeq = 1
1647
+ let nextFaultId = 1
1648
+ let closed = false
1649
+
1650
+ const clearLedger = () => {
1651
+ entries = []
1652
+ nextSeq = 1
1653
+ }
1654
+
1655
+ /** Why a fault's `match.route` could never match (it names no manifest row), or `undefined`. */
1656
+ const matchRouteProblem = (fault: StatefulStreamFault): string | undefined => {
1657
+ const route = fault.match?.route
1658
+
1659
+ return route === undefined || manifestPaths.has(route)
1660
+ ? undefined
1661
+ : 'match.route must name a manifest row of this emulator'
1662
+ }
1663
+
1664
+ const addFault = (input: unknown): StatefulFaultState<StatefulStreamFault> | string => {
1665
+ const decoded = chunkFaults ? decodeStreamFault(input) : decodeFault(input)
1666
+
1667
+ if (Result.isFailure(decoded)) {
1668
+ return issueMessage(decoded.failure.issue)
1669
+ }
1670
+
1671
+ const problem = matchRouteProblem(decoded.success)
1672
+
1673
+ if (problem !== undefined) return problem
1674
+
1675
+ const state: MutableFaultState = {
1676
+ id: nextFaultId++,
1677
+ fault: decoded.success,
1678
+ remaining: decoded.success.count,
1679
+ applied: 0
1680
+ }
1681
+
1682
+ faultStates.push(state)
1683
+
1684
+ return snapshotFault(state)
1685
+ }
1686
+
1687
+ const takeFault = (
1688
+ method: string,
1689
+ path: string,
1690
+ route: string | undefined
1691
+ ): MutableFaultState | undefined =>
1692
+ faultStates.find(
1693
+ state =>
1694
+ (state.remaining === undefined || state.remaining > 0) &&
1695
+ faultMatches(state.fault, method, path, route)
1696
+ )
1697
+
1698
+ const spend = (state: MutableFaultState) => {
1699
+ state.applied += 1
1700
+
1701
+ if (state.remaining !== undefined) {
1702
+ state.remaining -= 1
1703
+ }
1704
+ }
1705
+
1706
+ /** Build the fault's response first: a response that cannot be built must not consume it. */
1707
+ const applyFault = (state: MutableFaultState, fault: StatefulFault): Response => {
1708
+ const headers = new Headers(fault.headers ?? {})
1709
+ const body = fault.body ?? faultBody(fault.status)
1710
+
1711
+ if (!headers.has('content-type')) {
1712
+ headers.set('content-type', Predicate.isString(body) ? 'text/plain' : 'application/json')
1713
+ }
1714
+
1715
+ const response = new Response(Predicate.isString(body) ? body : JSON.stringify(body), {
1716
+ status: fault.status,
1717
+ headers
1718
+ })
1719
+
1720
+ spend(state)
1721
+
1722
+ return response
1723
+ }
1724
+
1725
+ const reset = async () => {
1726
+ clearLedger()
1727
+ faultStates = []
1728
+ config.clearRuntime()
1729
+ await core.restore(baseline)
1730
+ }
1731
+
1732
+ const reseed = async (input: unknown): Promise<State | string> => {
1733
+ const next = config.buildSeed(input)
1734
+
1735
+ if (Predicate.isString(next)) {
1736
+ return next
1737
+ }
1738
+
1739
+ await core.restore(next)
1740
+ config.clearRuntime()
1741
+ baseline = next
1742
+
1743
+ return next
1744
+ }
1745
+
1746
+ const coverage = (): StatefulCoverage => ({
1747
+ routes: manifest.map(route => ({
1748
+ ...route,
1749
+ requests: entries.filter(
1750
+ entry =>
1751
+ entry.route === route.path &&
1752
+ (variantRows.has(route.path) || entry.method.toUpperCase() === route.method)
1753
+ ).length
1754
+ })),
1755
+ unknownRouteRequests: entries.filter(entry => entry.evidence === 'unknown-route').length,
1756
+ notEmulatedRequests: entries.filter(entry => entry.notEmulated !== undefined).length
1757
+ })
1758
+
1759
+ /** The ledgered 400; the reason is scrubbed of the request's guarded secrets first. */
1760
+ const refuse = (
1761
+ entry: MutableLedgerEntry,
1762
+ reason: string,
1763
+ secrets: ReadonlyArray<string> = []
1764
+ ): Response => {
1765
+ const safe = scrubSecrets(reason, secrets)
1766
+
1767
+ entry.notEmulated = safe
1768
+
1769
+ return notEmulatedResponse(safe)
1770
+ }
1771
+
1772
+ /**
1773
+ * Fail-closed mode: the constant reason when any part of a recognised request repeats a guarded
1774
+ * secret, or `undefined`. Checked, each through the fixpoint closure of `textRepeatsSecret` (a
1775
+ * capped closure counts as a repeat): the raw path and every path segment, the raw query and
1776
+ * every decoded query key and value, every recorded header, and the body.
1777
+ */
1778
+ const credentialRepeat = (
1779
+ request: Request,
1780
+ url: URL,
1781
+ body: string | undefined,
1782
+ secrets: ReadonlyArray<string>,
1783
+ binding: StatefulRouteBinding
1784
+ ): string | undefined => {
1785
+ if (
1786
+ textRepeatsSecret(url.pathname, secrets) ||
1787
+ url.pathname.split('/').some(segment => textRepeatsSecret(segment, secrets))
1788
+ ) {
1789
+ return 'the request path repeats the credential'
1790
+ }
1791
+
1792
+ if (
1793
+ textRepeatsSecret(url.search, secrets) ||
1794
+ [...url.searchParams].some(
1795
+ ([key, value]) => textRepeatsSecret(key, secrets) || textRepeatsSecret(value, secrets)
1796
+ )
1797
+ ) {
1798
+ return 'the query repeats the credential'
1799
+ }
1800
+
1801
+ if (
1802
+ config.recordHeaders.some(recorded =>
1803
+ textRepeatsSecret(request.headers.get(recorded.name) ?? '', secrets)
1804
+ )
1805
+ ) {
1806
+ return 'a recorded request header repeats the credential'
1807
+ }
1808
+
1809
+ if (config.guardAllHeaders === true) {
1810
+ const headers: Array<string> = []
1811
+
1812
+ request.headers.forEach((value, name) => {
1813
+ if (name !== 'authorization') headers.push(name, value)
1814
+ })
1815
+
1816
+ if (headers.some(text => textRepeatsSecret(text, secrets))) {
1817
+ return 'a request header repeats the credential'
1818
+ }
1819
+ }
1820
+
1821
+ if (body === undefined) return undefined
1822
+
1823
+ const repeat = 'the request body repeats the credential'
1824
+
1825
+ if (textRepeatsSecret(body, secrets)) return repeat
1826
+
1827
+ // The route's decoded views of its body (base64url content, for example) are checked too. A
1828
+ // view that throws refuses the body (uncertainty refuses, it never admits): a repeat when what
1829
+ // it decoded cleanly holds the bearer, else its declared constant reason, else the uncheckable
1830
+ // reason, so a request without the bearer is never told it repeats it.
1831
+ const { decodedViews, viewRefusalReasons = [] } = binding
1832
+ const views = Result.try(() => (decodedViews === undefined ? [] : decodedViews(body)))
1833
+
1834
+ if (Result.isFailure(views)) {
1835
+ const refusal = views.failure
1836
+
1837
+ if (!(refusal instanceof DecodedViewRefusal)) return uncheckableBodyReason
1838
+
1839
+ if (refusal.decoded.some(view => textRepeatsSecret(view, secrets))) return repeat
1840
+
1841
+ return viewRefusalReasons.includes(refusal.reason)
1842
+ ? scrubSecrets(refusal.reason, secrets)
1843
+ : uncheckableBodyReason
1844
+ }
1845
+
1846
+ return views.success.some(view => textRepeatsSecret(view, secrets)) ? repeat : undefined
1847
+ }
1848
+
1849
+ /** Everything after the route match: credential, headers, body, shape, then the core. */
1850
+ const routed = async (
1851
+ request: Request,
1852
+ url: URL,
1853
+ entry: MutableLedgerEntry,
1854
+ matched: MatchedRoute<State, Env>,
1855
+ secrets: ReadonlyArray<string>,
1856
+ arrivedOn: string,
1857
+ recorded: RecordedFields,
1858
+ /** Resolved mode: the request text besides the query that must not repeat a secret. */
1859
+ guardedPath: string | undefined
1860
+ ): Promise<Response> => {
1861
+ // Resolved mode: routes read the content type only, never a header that may carry a secret.
1862
+ const header = (name: string): string | undefined =>
1863
+ isCredentialHeaderName(name) ||
1864
+ (guardedPath !== undefined && name.toLowerCase() !== 'content-type')
1865
+ ? undefined
1866
+ : (request.headers.get(name) ?? undefined)
1867
+
1868
+ const refused = (reason: string) => refuse(entry, reason, secrets)
1869
+
1870
+ // Resolved mode reads the request body once, after the query and path checks, and every later
1871
+ // step reuses that read (`undefined`: the body is unreadable, consumed or locked included).
1872
+ let resolvedBody: { readonly bytes: Uint8Array | undefined } | undefined
1873
+
1874
+ if (guardedPath !== undefined) {
1875
+ // Resolved mode: the emulator resolved the credential; nothing may repeat it.
1876
+ const partsRepeat = partsCredentialRepeat(url, guardedPath, secrets)
1877
+
1878
+ if (partsRepeat !== undefined) return refused(partsRepeat)
1879
+
1880
+ resolvedBody = { bytes: await readBytes(request) }
1881
+
1882
+ const bodyRepeat = bodyCredentialRepeat(
1883
+ resolvedBody.bytes === undefined ? undefined : bodyText(resolvedBody.bytes),
1884
+ secrets
1885
+ )
1886
+
1887
+ if (bodyRepeat !== undefined) return refused(bodyRepeat)
1888
+ } else if (config.failClosed === undefined) {
1889
+ if (!bearerPattern.test(request.headers.get('authorization') ?? '')) {
1890
+ return refused('a non-empty Authorization: Bearer credential is required')
1891
+ }
1892
+ } else {
1893
+ // The header is absent here (an unrecognisable one never reaches a route).
1894
+ if (secrets.length === 0) return refused(missingBearerReason)
1895
+
1896
+ // A request repeating the credential never gets here (see `credentialRepeat`).
1897
+ if (hasEmptyQueryComponent(request.url)) {
1898
+ return refused('empty query components (a bare ? or a stray &) are not emulated')
1899
+ }
1900
+ }
1901
+
1902
+ const problem = config.requestProblem?.(header)
1903
+
1904
+ if (problem !== undefined) return refused(problem)
1905
+
1906
+ // Resolved mode reuses the one body read it already made. Every other emulator awaits
1907
+ // `readText(request)` directly, so its request scheduling is exactly what it was.
1908
+ const resolvedText = (): string | undefined =>
1909
+ resolvedBody?.bytes === undefined ? undefined : bodyText(resolvedBody.bytes)
1910
+
1911
+ let json: Schema.Json | undefined
1912
+ let bytes: Uint8Array | undefined
1913
+
1914
+ switch (matched.route.body) {
1915
+ case 'none': {
1916
+ const text = resolvedBody === undefined ? await readText(request) : resolvedText()
1917
+
1918
+ if (text === undefined || text !== '') {
1919
+ return refused('this route takes no request body')
1920
+ }
1921
+
1922
+ break
1923
+ }
1924
+
1925
+ case 'json': {
1926
+ const text = resolvedBody === undefined ? await readText(request) : resolvedText()
1927
+
1928
+ if (mediaType(header('content-type')) !== 'application/json') {
1929
+ return refused('this route takes a content-type: application/json body')
1930
+ }
1931
+
1932
+ const parsed = text === undefined ? undefined : parseJsonText(text)
1933
+
1934
+ if (parsed === undefined) return refused('the request body is not valid JSON')
1935
+
1936
+ if (config.uniqueJsonKeys === true && text !== undefined && repeatsJsonKey(text)) {
1937
+ return refused('a JSON body with a repeated key is not emulated')
1938
+ }
1939
+
1940
+ // Redacted before it is stored: a refused request's body stays in the ledger too (with
1941
+ // `constantRefusals`, only once the route admits the request).
1942
+ recorded.body = redactCredentialFields(parsed)
1943
+
1944
+ if (!constantRefusals) entry.body = recorded.body
1945
+
1946
+ json = parsed
1947
+
1948
+ break
1949
+ }
1950
+
1951
+ case 'json-or-empty': {
1952
+ const text = resolvedBody === undefined ? await readText(request) : resolvedText()
1953
+
1954
+ if (text === undefined) return refused('the request body is unreadable')
1955
+
1956
+ if (text === '') break
1957
+
1958
+ const parsed = parseJsonText(text)
1959
+
1960
+ if (parsed === undefined) return refused('the request body is not JSON')
1961
+
1962
+ if (config.uniqueJsonKeys === true && repeatsJsonKey(text)) {
1963
+ return refused('a JSON body with a repeated key is not emulated')
1964
+ }
1965
+
1966
+ recorded.body = redactCredentialFields(parsed)
1967
+
1968
+ if (!constantRefusals) entry.body = recorded.body
1969
+
1970
+ json = parsed
1971
+
1972
+ break
1973
+ }
1974
+
1975
+ case 'bytes': {
1976
+ bytes = resolvedBody === undefined ? await readBytes(request) : resolvedBody.bytes
1977
+
1978
+ if (bytes === undefined) return refused('the request body is unreadable')
1979
+
1980
+ recorded.bodyBytes = bytes.byteLength
1981
+
1982
+ if (!constantRefusals) entry.bodyBytes = recorded.bodyBytes
1983
+
1984
+ break
1985
+ }
1986
+ }
1987
+
1988
+ // Fail-closed mode only (checked at build): the per-origin digest of the bearer, never the
1989
+ // bearer. A digest that cannot be made, or that repeats the bearer, is a handler failure.
1990
+ let bearerDigest: string | undefined
1991
+ const [bearer] = secrets
1992
+
1993
+ if (config.bearerDigest !== undefined && bearer !== undefined) {
1994
+ const digest = Result.try(() => config.bearerDigest?.(bearer, arrivedOn))
1995
+
1996
+ if (
1997
+ Result.isFailure(digest) ||
1998
+ !Predicate.isString(digest.success) ||
1999
+ textRepeatsSecret(digest.success, secrets)
2000
+ ) {
2001
+ entry.responseError = 'the bearer digest failed'
2002
+
2003
+ return emulatorError(500, errorTexts.failed)
2004
+ }
2005
+
2006
+ bearerDigest = digest.success
2007
+ }
2008
+
2009
+ // Resolved mode: routes see the ledgered path and no header names, never the credential a
2010
+ // path segment or a header name may carry.
2011
+ const admitted = matched.route.admit(
2012
+ {
2013
+ method: request.method.toUpperCase(),
2014
+ path: guardedPath === undefined ? url.pathname : entry.path,
2015
+ params: matched.params,
2016
+ query: url.searchParams,
2017
+ rawQuery: rawQuery(request.url) ?? '',
2018
+ header,
2019
+ headerNames: guardedPath === undefined ? [...request.headers.keys()] : [],
2020
+ json,
2021
+ bytes,
2022
+ bearerDigest
2023
+ },
2024
+ config.env
2025
+ )
2026
+
2027
+ if (isNotEmulated(admitted)) return refused(admitted.reason)
2028
+
2029
+ // A route with variants admits a request as exactly one of them; a route without variants
2030
+ // admits it as none of them.
2031
+ const variants = matched.route.variants
2032
+ const variant = admitted.variant
2033
+
2034
+ if (
2035
+ variants === undefined ? variant !== undefined : !variants.some(row => row.path === variant)
2036
+ ) {
2037
+ entry.responseError = 'the route admitted the request as no row of its manifest'
2038
+
2039
+ return emulatorError(500, errorTexts.failed)
2040
+ }
2041
+
2042
+ if (variant !== undefined) entry.route = variant
2043
+
2044
+ // `constantRefusals`: the request text is recorded only now that the route admitted it.
2045
+ if (constantRefusals) {
2046
+ entry.method = recorded.method
2047
+ entry.path = recorded.path
2048
+ entry.query = recorded.query
2049
+ entry.headers = recorded.headers
2050
+
2051
+ if (recorded.body !== undefined) entry.body = recorded.body
2052
+
2053
+ if (recorded.bodyBytes !== undefined) entry.bodyBytes = recorded.bodyBytes
2054
+ }
2055
+
2056
+ const method = request.method.toUpperCase()
2057
+ const jobId = nextJobId++
2058
+ // Resolved mode: faults match, and the core sees, the ledgered path (never the credential).
2059
+ const requestPath = guardedPath === undefined ? url.pathname : entry.path
2060
+
2061
+ const job: Job<State, Env> = {
2062
+ admission: admitted,
2063
+ seq: entry.seq,
2064
+ secrets,
2065
+ decideFault: chunks => {
2066
+ const state = takeFault(method, requestPath, entry.route)
2067
+
2068
+ if (state === undefined) return { kind: 'none' }
2069
+
2070
+ const fault = state.fault
2071
+
2072
+ if (fault.kind === 'status') {
2073
+ const response = applyFault(state, fault)
2074
+
2075
+ entry.fault = 'status'
2076
+
2077
+ return { kind: 'answer', response }
2078
+ }
2079
+
2080
+ // A truncation that cannot take effect answers 500 and is not used up (never a no-op).
2081
+ if (chunks === undefined || fault.chunks >= chunks) {
2082
+ entry.responseError =
2083
+ `emulator fault cannot apply: truncate-after-chunks after ${fault.chunks} chunk(s) ` +
2084
+ 'needs a streamed answer of more chunks'
2085
+
2086
+ return { kind: 'answer', response: emulatorError(500, 'emulator fault cannot apply') }
2087
+ }
2088
+
2089
+ spend(state)
2090
+ entry.fault = 'truncate-after-chunks'
2091
+
2092
+ return { kind: 'truncate', after: fault.chunks }
2093
+ }
2094
+ }
2095
+
2096
+ jobs.set(jobId, job)
2097
+
2098
+ try {
2099
+ const response = await core.fetch(
2100
+ new Request(new URL(requestPath, core.baseUrl), {
2101
+ method: 'POST',
2102
+ headers: { [emulatorJobHeader]: String(jobId) }
2103
+ })
2104
+ )
2105
+
2106
+ if (response.headers.has(handlerFailedHeader)) {
2107
+ entry.responseError = 'the route handler failed'
2108
+
2109
+ return emulatorError(500, errorTexts.failed)
2110
+ }
2111
+
2112
+ // Resolved mode: a core that answered without running the dispatch (closed meanwhile)
2113
+ // decided nothing about the request.
2114
+ if (guardedPath !== undefined && job.dispatched !== true) {
2115
+ entry.responseError = 'the route handler answered no eligibility verdict'
2116
+
2117
+ return emulatorError(500, errorTexts.failed)
2118
+ }
2119
+
2120
+ if (job.notEmulated !== undefined) {
2121
+ entry.notEmulated = job.notEmulated
2122
+
2123
+ if (constantRefusals || job.credentialRepeat === true) blankEntry(entry)
2124
+
2125
+ // The constant credential-repeat entry keeps the route template, as a request repeat does.
2126
+ if (job.credentialRepeat === true) entry.route = matched.route.path
2127
+
2128
+ // Resolved mode: the wrapper answers the refusal itself, outside the core.
2129
+ if (guardedPath !== undefined) return notEmulatedResponse(job.notEmulated)
2130
+ }
2131
+
2132
+ return job.faultAnswer ?? response
2133
+ } finally {
2134
+ jobs.delete(jobId)
2135
+ }
2136
+ }
2137
+
2138
+ /**
2139
+ * Fail closed: an unrecognised request is ledgered and answered with constant text only. `method`
2140
+ * is the request method upper-cased (fail-closed mode) or as sent (resolved mode).
2141
+ */
2142
+ const unrecognised = (method: string, reason: string): Response => {
2143
+ entries.push({
2144
+ seq: nextSeq++,
2145
+ method: unrecognisedMethod(method),
2146
+ path: unrecognisedLedgerPath,
2147
+ query: {},
2148
+ headers: {},
2149
+ status: 400,
2150
+ evidence: 'unknown-route',
2151
+ notEmulated: reason
2152
+ })
2153
+
2154
+ return notEmulatedResponse(reason)
2155
+ }
2156
+
2157
+ const emulatedApi = async (request: Request, url: URL, arrivedOn: string): Promise<Response> => {
2158
+ const resolution = resolveRequest?.(request, url)
2159
+
2160
+ // Resolved mode: the emulator's own resolution fails closed with constant text only.
2161
+ if (resolution?.kind === 'unrecognised') return unrecognised(request.method, resolution.reason)
2162
+
2163
+ const matched: MatchedRoute<State, Env> | undefined =
2164
+ resolution === undefined
2165
+ ? match(request.method, url.pathname)
2166
+ : {
2167
+ route: resolution.route,
2168
+ params: resolution.kind === 'route' ? resolution.params : {}
2169
+ }
2170
+
2171
+ const failClosed = config.failClosed
2172
+ let secrets: ReadonlyArray<string> = resolution?.secrets ?? []
2173
+
2174
+ if (failClosed !== undefined) {
2175
+ const authorization = request.headers.get('authorization')
2176
+ const bearer = recognisableBearer(authorization, config.bearerPrefixes?.[arrivedOn])
2177
+
2178
+ // Its credential cannot be extracted and scrubbed: nothing of the request is kept.
2179
+ if (authorization !== null && bearer === undefined) {
2180
+ return unrecognised(request.method.toUpperCase(), failClosed.unrecognisedAuthorization)
2181
+ }
2182
+
2183
+ if (matched === undefined) {
2184
+ return unrecognised(request.method.toUpperCase(), failClosed.unrecognised)
2185
+ }
2186
+
2187
+ secrets = bearer === undefined ? [] : [bearer]
2188
+
2189
+ if (secrets.length > 0) {
2190
+ // Read from a copy: the route reads the body again.
2191
+ const body = request.body === null ? undefined : await readText(request.clone())
2192
+ const reason = credentialRepeat(request, url, body, secrets, matched.route)
2193
+
2194
+ // Nothing of a request that repeats the credential is kept, in any part: it is ledgered
2195
+ // and answered with constant text only (its route template is constant too).
2196
+ if (reason !== undefined) {
2197
+ entries.push({
2198
+ seq: nextSeq++,
2199
+ method: unrecognisedMethod(request.method.toUpperCase()),
2200
+ path: unrecognisedLedgerPath,
2201
+ route: matched.route.path,
2202
+ query: {},
2203
+ headers: {},
2204
+ status: 400,
2205
+ evidence: matched.route.evidence,
2206
+ notEmulated: reason
2207
+ })
2208
+
2209
+ return withEvidence(notEmulatedResponse(reason), matched.route.evidence)
2210
+ }
2211
+ }
2212
+ }
2213
+
2214
+ const scrub = (text: string): string => scrubSecrets(text, secrets)
2215
+
2216
+ // Query keys and values are scrubbed of the request's secrets before they are recorded. In
2217
+ // fail-closed mode every original pair is recorded (no pair repeats a secret by now): a key
2218
+ // that occurs more than once is recorded as a JSON array of its values, in order. Resolved
2219
+ // mode records the values as sent (credential-named keys redacted).
2220
+ const query =
2221
+ failClosed === undefined
2222
+ ? Object.fromEntries(
2223
+ Object.entries(
2224
+ resolution === undefined
2225
+ ? recordedQuery(url.searchParams)
2226
+ : redactCredentialQuery(url.searchParams)
2227
+ ).map(([key, value]) => [scrub(key), scrub(value)])
2228
+ )
2229
+ : recordedQueryPairs(url.searchParams, scrub)
2230
+
2231
+ const recorded: RecordedFields = {
2232
+ method: scrub(request.method),
2233
+ path: scrub(resolution?.ledgerPath ?? url.pathname),
2234
+ query,
2235
+ headers: {}
2236
+ }
2237
+
2238
+ for (const header of config.recordHeaders) {
2239
+ const value = request.headers.get(header.name)
2240
+
2241
+ if (value === null) continue
2242
+
2243
+ const text = recordedHeaderValue(header, value)
2244
+
2245
+ // Fail-closed mode recognises a JSON-looking value whatever the header's declared format.
2246
+ recorded.headers[header.name] = scrub(
2247
+ failClosed === undefined ? text : recordedJsonLooking(text)
2248
+ )
2249
+ }
2250
+
2251
+ const evidence = matched?.route.evidence ?? 'unknown-route'
2252
+
2253
+ // `constantRefusals`: constant text until the route admits the request.
2254
+ const entry: MutableLedgerEntry = constantRefusals
2255
+ ? {
2256
+ seq: nextSeq++,
2257
+ method: unrecognisedMethod(request.method.toUpperCase()),
2258
+ path: unrecognisedLedgerPath,
2259
+ query: {},
2260
+ headers: {},
2261
+ status: 0,
2262
+ evidence
2263
+ }
2264
+ : resolution === undefined
2265
+ ? {
2266
+ seq: nextSeq++,
2267
+ method: recorded.method,
2268
+ path: recorded.path,
2269
+ query: recorded.query,
2270
+ headers: { ...recorded.headers },
2271
+ status: 0,
2272
+ evidence
2273
+ }
2274
+ : // Resolved mode: the route is known from the start (it keeps this position).
2275
+ {
2276
+ seq: nextSeq++,
2277
+ method: recorded.method,
2278
+ path: recorded.path,
2279
+ route: resolution.route.path,
2280
+ query: recorded.query,
2281
+ headers: { ...recorded.headers },
2282
+ status: 0,
2283
+ evidence
2284
+ }
2285
+
2286
+ entries.push(entry)
2287
+
2288
+ if (matched === undefined) {
2289
+ entry.status = 400
2290
+
2291
+ return refuse(entry, 'no emulated route for this method and path')
2292
+ }
2293
+
2294
+ entry.route = matched.route.path
2295
+
2296
+ if (matched.route.origin !== undefined && matched.route.origin !== arrivedOn) {
2297
+ entry.status = 400
2298
+
2299
+ return withEvidence(
2300
+ refuse(entry, `this route is recorded on ${matched.route.origin} only`, secrets),
2301
+ matched.route.evidence
2302
+ )
2303
+ }
2304
+
2305
+ // Resolved mode: the emulator refused the request before its body is read.
2306
+ if (resolution?.kind === 'refused') {
2307
+ const tagged = withEvidence(
2308
+ refuse(entry, resolution.reason, secrets),
2309
+ resolution.route.evidence
2310
+ )
2311
+
2312
+ entry.status = tagged.status
2313
+
2314
+ return tagged
2315
+ }
2316
+
2317
+ const guardedPath = resolution?.guardedPath
2318
+
2319
+ // Error recovery still answers through the route: the fallback 500 is evidence-tagged and
2320
+ // the ledger records the status actually sent.
2321
+ const response = await routed(
2322
+ request,
2323
+ url,
2324
+ entry,
2325
+ matched,
2326
+ secrets,
2327
+ arrivedOn,
2328
+ recorded,
2329
+ guardedPath
2330
+ ).catch(() => {
2331
+ entry.responseError = 'the emulator could not build or produce the response'
2332
+
2333
+ return emulatorError(500, errorTexts.failed)
2334
+ })
2335
+
2336
+ const tagged = withEvidence(response, matched.route.evidence)
2337
+
2338
+ entry.status = tagged.status
2339
+
2340
+ return tagged
2341
+ }
2342
+
2343
+ const controlPlane = async (request: Request, path: string): Promise<Response> => {
2344
+ const method = request.method
2345
+ const allow = (methods: string) => emulatorError(405, 'method not allowed', { allow: methods })
2346
+
2347
+ const jsonBody = async (): Promise<Schema.Json | undefined> => {
2348
+ const text = await readText(request)
2349
+
2350
+ return text === undefined ? undefined : parseJsonText(text)
2351
+ }
2352
+
2353
+ switch (path) {
2354
+ case '/_emulate/ledger':
2355
+ if (method === 'GET') {
2356
+ return jsonResponse(200, { entries: entries.map(snapshotLedgerEntry) })
2357
+ }
2358
+
2359
+ if (method === 'DELETE') {
2360
+ const cleared = entries.length
2361
+
2362
+ clearLedger()
2363
+
2364
+ return jsonResponse(200, { cleared })
2365
+ }
2366
+
2367
+ return allow('GET, DELETE')
2368
+
2369
+ case '/_emulate/faults': {
2370
+ if (method === 'GET') {
2371
+ return jsonResponse(200, { faults: faultStates.map(snapshotFault) })
2372
+ }
2373
+
2374
+ if (method === 'DELETE') {
2375
+ const cleared = faultStates.length
2376
+
2377
+ faultStates = []
2378
+
2379
+ return jsonResponse(200, { cleared })
2380
+ }
2381
+
2382
+ if (method !== 'POST') {
2383
+ return allow('GET, POST, DELETE')
2384
+ }
2385
+
2386
+ const input = await jsonBody()
2387
+
2388
+ const decoded = chunkFaults ? decodeStreamFaultList(input) : decodeFaultList(input)
2389
+
2390
+ if (Result.isFailure(decoded)) {
2391
+ return emulatorError(400, `invalid fault: ${issueMessage(decoded.failure.issue)}`)
2392
+ }
2393
+
2394
+ const faults = 'faults' in decoded.success ? decoded.success.faults : [decoded.success]
2395
+ const problem = faults.map(matchRouteProblem).find(Predicate.isString)
2396
+
2397
+ // Checked before any fault is added: a list is added whole or not at all.
2398
+ if (problem !== undefined) return emulatorError(400, `invalid fault: ${problem}`)
2399
+
2400
+ return jsonResponse(201, { faults: faults.map(fault => addFault(fault)) })
2401
+ }
2402
+
2403
+ case '/_emulate/reset':
2404
+ if (method !== 'POST') {
2405
+ return allow('POST')
2406
+ }
2407
+
2408
+ await reset()
2409
+
2410
+ return jsonResponse(200, { reset: true })
2411
+
2412
+ case '/_emulate/state':
2413
+ if (method !== 'GET') {
2414
+ return allow('GET')
2415
+ }
2416
+
2417
+ return jsonResponse(200, {
2418
+ state: core.snapshot(),
2419
+ ...config.runtimeState(),
2420
+ faults: faultStates.map(snapshotFault),
2421
+ ledgerEntries: entries.length
2422
+ })
2423
+
2424
+ case '/_emulate/seed': {
2425
+ if (method !== 'POST') {
2426
+ return allow('POST')
2427
+ }
2428
+
2429
+ const next = await reseed((await jsonBody()) ?? null)
2430
+
2431
+ if (Predicate.isString(next)) {
2432
+ return emulatorError(400, `invalid seed: ${next}`)
2433
+ }
2434
+
2435
+ return jsonResponse(200, { seeded: true, ...config.seedSummary(next) })
2436
+ }
2437
+
2438
+ case '/_emulate/coverage':
2439
+ if (method !== 'GET') {
2440
+ return allow('GET')
2441
+ }
2442
+
2443
+ return jsonResponse(200, coverage())
2444
+
2445
+ default:
2446
+ return emulatorError(404, 'unknown control-plane route')
2447
+ }
2448
+ }
2449
+
2450
+ /**
2451
+ * Last resort when handling itself fails (for example an unparseable request URL): a 500
2452
+ * emulator error, tagged with the matched route's evidence when there is one (in resolved mode,
2453
+ * whose own resolution may be what failed, never).
2454
+ */
2455
+ const lastResort = (request: Request): Response => {
2456
+ const path = URL.canParse(request.url) ? new URL(request.url).pathname : undefined
2457
+ const failed = emulatorError(500, errorTexts.unhandled)
2458
+
2459
+ if (path === undefined || isControlPath(path) || resolveRequest !== undefined) return failed
2460
+
2461
+ const matched = match(request.method, path)
2462
+
2463
+ return matched === undefined ? failed : withEvidence(failed, matched.route.evidence)
2464
+ }
2465
+
2466
+ const handle = async (request: Request, origin: string | undefined): Promise<Response> => {
2467
+ if (closed) {
2468
+ return emulatorError(503, errorTexts.closed)
2469
+ }
2470
+
2471
+ const url = new URL(request.url)
2472
+
2473
+ return isControlPath(url.pathname)
2474
+ ? controlPlane(request, url.pathname)
2475
+ : emulatedApi(request, url, origin ?? url.origin)
2476
+ }
2477
+
2478
+ const fetchOn =
2479
+ (origin: string | undefined) =>
2480
+ (request: Request): Promise<Response> =>
2481
+ handle(request, origin).catch(() => lastResort(request))
2482
+
2483
+ return {
2484
+ fetch: fetchOn(undefined),
2485
+ fetchOn: origin => fetchOn(origin),
2486
+ ledger: {
2487
+ entries: () => entries.map(snapshotLedgerEntry),
2488
+ clear: clearLedger
2489
+ },
2490
+ faults: {
2491
+ add: fault => {
2492
+ const added = addFault(fault)
2493
+
2494
+ if (Predicate.isString(added)) {
2495
+ throw config.inputInvalid('fault', added)
2496
+ }
2497
+
2498
+ return added
2499
+ },
2500
+ list: () => faultStates.map(snapshotFault),
2501
+ clear: () => {
2502
+ faultStates = []
2503
+ }
2504
+ },
2505
+ reset,
2506
+ seed: async input => {
2507
+ const next = await reseed(input)
2508
+
2509
+ if (Predicate.isString(next)) {
2510
+ throw config.inputInvalid('seed', next)
2511
+ }
2512
+ },
2513
+ snapshot: () => core.snapshot(),
2514
+ coverage,
2515
+ close: () => {
2516
+ closed = true
2517
+
2518
+ return core.close()
2519
+ }
2520
+ }
2521
+ }
2522
+
2523
+ /** The fault states of an emulator without truncation faults (its decoder takes status faults). */
2524
+ const statusFaultStates = (
2525
+ states: ReadonlyArray<StatefulFaultState<StatefulStreamFault>>
2526
+ ): ReadonlyArray<StatefulFaultState> =>
2527
+ states.flatMap(state => {
2528
+ const fault = state.fault
2529
+
2530
+ return fault.kind === 'status' ? [{ ...state, fault }] : []
2531
+ })
2532
+
2533
+ /** The API of an emulator without truncation faults: its fault methods take status faults only. */
2534
+ const withStatusFaults = <State, Seed, Entry>(
2535
+ api: StatefulEmulatorApi<State, Seed, StatefulStreamFault, Entry>,
2536
+ inputInvalid: (input: StatefulInputKind, reason: string) => Error
2537
+ ): StatefulEmulatorApi<State, Seed, StatefulFault, Entry> => ({
2538
+ ...api,
2539
+ faults: {
2540
+ add: fault => {
2541
+ const [added] = statusFaultStates([api.faults.add(fault)])
2542
+
2543
+ if (added === undefined) throw inputInvalid('fault', 'a status fault is required')
2544
+
2545
+ return added
2546
+ },
2547
+ list: () => statusFaultStates(api.faults.list()),
2548
+ clear: api.faults.clear
2549
+ }
2550
+ })
2551
+
2552
+ /**
2553
+ * Build the wrapper over a core runtime. `createCore` receives the dispatch the core must run for
2554
+ * every request (its only route) and returns the runtime adapter. Faults are status faults only.
2555
+ */
2556
+ export const makeStatefulEmulator = async <State, Env, Seed>(
2557
+ config: StatefulEmulatorConfig<State, Env>,
2558
+ createCore: (dispatch: CoreDispatch<State>) => Promise<StatefulCore<State>>
2559
+ ): Promise<StatefulEmulatorApi<State, Seed>> =>
2560
+ withStatusFaults(
2561
+ await buildStatefulEmulator<State, Env, Seed, StatefulLedgerEntry>(
2562
+ config,
2563
+ createCore,
2564
+ false,
2565
+ snapshotEntry
2566
+ ),
2567
+ config.inputInvalid
2568
+ )
2569
+
2570
+ /**
2571
+ * `makeStatefulEmulator` for an emulator that records no request header (opt-in): it takes no
2572
+ * `recordHeaders`, and its ledger entries carry no `headers` field
2573
+ * (`StatefulHeaderlessLedgerEntry`). Faults are status faults only.
2574
+ */
2575
+ export const makeHeaderlessStatefulEmulator = async <State, Env, Seed>(
2576
+ config: Omit<StatefulEmulatorConfig<State, Env>, 'recordHeaders'>,
2577
+ createCore: (dispatch: CoreDispatch<State>) => Promise<StatefulCore<State>>
2578
+ ): Promise<StatefulEmulatorApi<State, Seed, StatefulFault, StatefulHeaderlessLedgerEntry>> =>
2579
+ withStatusFaults(
2580
+ await buildStatefulEmulator<State, Env, Seed, StatefulHeaderlessLedgerEntry>(
2581
+ { ...config, recordHeaders: [] },
2582
+ createCore,
2583
+ false,
2584
+ snapshotHeaderlessEntry
2585
+ ),
2586
+ config.inputInvalid
2587
+ )
2588
+
2589
+ /**
2590
+ * `makeStatefulEmulator` that also takes `truncate-after-chunks` faults
2591
+ * (`StatefulTruncateFault`), which cut a streamed answer (`StreamedCommit`). Opt-in: the other
2592
+ * emulators keep status faults only.
2593
+ */
2594
+ export const makeChunkedStatefulEmulator = <State, Env, Seed>(
2595
+ config: StatefulEmulatorConfig<State, Env>,
2596
+ createCore: (dispatch: CoreDispatch<State>) => Promise<StatefulCore<State>>
2597
+ ): Promise<StatefulEmulatorApi<State, Seed, StatefulStreamFault>> =>
2598
+ buildStatefulEmulator<State, Env, Seed, StatefulLedgerEntry>(
2599
+ config,
2600
+ createCore,
2601
+ true,
2602
+ snapshotEntry
2603
+ )
2604
+
2605
+ /** Throws `inputInvalid('option', ...)` unless every drill knob is a known boolean (or absent). */
2606
+ export const checkBooleanDrills = (
2607
+ drills: object | undefined,
2608
+ knobs: ReadonlyArray<string>,
2609
+ inputInvalid: (input: StatefulInputKind, reason: string) => Error
2610
+ ): void => {
2611
+ for (const [key, value] of Object.entries(drills ?? {})) {
2612
+ if (!knobs.includes(key)) {
2613
+ throw inputInvalid('option', `unknown drill knob ${key}`)
2614
+ }
2615
+
2616
+ if (value !== undefined && !Predicate.isBoolean(value)) {
2617
+ throw inputInvalid('option', `drills.${key} must be a boolean`)
2618
+ }
2619
+ }
2620
+ }