@plune-ai/cairn 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (337) hide show
  1. package/README.md +84 -8
  2. package/dist/agent/check-docs.d.ts +25 -0
  3. package/dist/agent/check-docs.d.ts.map +1 -0
  4. package/dist/agent/check-docs.js +57 -0
  5. package/dist/agent/check-docs.js.map +1 -0
  6. package/dist/agent/collect-docs.d.ts +94 -0
  7. package/dist/agent/collect-docs.d.ts.map +1 -0
  8. package/dist/agent/collect-docs.js +326 -0
  9. package/dist/agent/collect-docs.js.map +1 -0
  10. package/dist/agent/graph.d.ts +39 -2
  11. package/dist/agent/graph.d.ts.map +1 -1
  12. package/dist/agent/graph.js +113 -4
  13. package/dist/agent/graph.js.map +1 -1
  14. package/dist/agent/index.d.ts +14 -0
  15. package/dist/agent/index.d.ts.map +1 -1
  16. package/dist/agent/index.js +114 -10
  17. package/dist/agent/index.js.map +1 -1
  18. package/dist/agent/overlays.d.ts +88 -0
  19. package/dist/agent/overlays.d.ts.map +1 -0
  20. package/dist/agent/overlays.js +447 -0
  21. package/dist/agent/overlays.js.map +1 -0
  22. package/dist/agent/repair-loop.d.ts +8 -1
  23. package/dist/agent/repair-loop.d.ts.map +1 -1
  24. package/dist/agent/repair-loop.js +18 -3
  25. package/dist/agent/repair-loop.js.map +1 -1
  26. package/dist/analyze/index.d.ts +1 -1
  27. package/dist/analyze/index.d.ts.map +1 -1
  28. package/dist/analyze/index.js +3 -2
  29. package/dist/analyze/index.js.map +1 -1
  30. package/dist/api/adversarial.d.ts +1 -1
  31. package/dist/api/adversarial.js +1 -1
  32. package/dist/api/collection.d.ts +20 -0
  33. package/dist/api/collection.d.ts.map +1 -0
  34. package/dist/api/collection.js +357 -0
  35. package/dist/api/collection.js.map +1 -0
  36. package/dist/api/derived.d.ts +179 -0
  37. package/dist/api/derived.d.ts.map +1 -0
  38. package/dist/api/derived.js +852 -0
  39. package/dist/api/derived.js.map +1 -0
  40. package/dist/api/discover.d.ts +66 -0
  41. package/dist/api/discover.d.ts.map +1 -0
  42. package/dist/api/discover.js +125 -0
  43. package/dist/api/discover.js.map +1 -0
  44. package/dist/api/flows.d.ts +194 -0
  45. package/dist/api/flows.d.ts.map +1 -0
  46. package/dist/api/flows.js +663 -0
  47. package/dist/api/flows.js.map +1 -0
  48. package/dist/api/guard.d.ts +19 -0
  49. package/dist/api/guard.d.ts.map +1 -1
  50. package/dist/api/guard.js +18 -4
  51. package/dist/api/guard.js.map +1 -1
  52. package/dist/api/openapi.d.ts +17 -1
  53. package/dist/api/openapi.d.ts.map +1 -1
  54. package/dist/api/openapi.js +64 -3
  55. package/dist/api/openapi.js.map +1 -1
  56. package/dist/api/runner.d.ts.map +1 -1
  57. package/dist/api/runner.js +18 -14
  58. package/dist/api/runner.js.map +1 -1
  59. package/dist/api/two-actor.d.ts +165 -0
  60. package/dist/api/two-actor.d.ts.map +1 -0
  61. package/dist/api/two-actor.js +627 -0
  62. package/dist/api/two-actor.js.map +1 -0
  63. package/dist/artifacts/contract.d.ts +1 -1
  64. package/dist/artifacts/contract.d.ts.map +1 -1
  65. package/dist/artifacts/index.d.ts +5 -0
  66. package/dist/artifacts/index.d.ts.map +1 -1
  67. package/dist/artifacts/index.js +14 -10
  68. package/dist/artifacts/index.js.map +1 -1
  69. package/dist/artifacts/report.d.ts +29 -2
  70. package/dist/artifacts/report.d.ts.map +1 -1
  71. package/dist/artifacts/report.js +65 -1
  72. package/dist/artifacts/report.js.map +1 -1
  73. package/dist/artifacts/testcase-md.d.ts +18 -0
  74. package/dist/artifacts/testcase-md.d.ts.map +1 -1
  75. package/dist/artifacts/testcase-md.js +15 -1
  76. package/dist/artifacts/testcase-md.js.map +1 -1
  77. package/dist/browser/api-traffic.d.ts +85 -0
  78. package/dist/browser/api-traffic.d.ts.map +1 -0
  79. package/dist/browser/api-traffic.js +283 -0
  80. package/dist/browser/api-traffic.js.map +1 -0
  81. package/dist/browser/backends/playwright-cli.d.ts.map +1 -1
  82. package/dist/browser/backends/playwright-cli.js +3 -0
  83. package/dist/browser/backends/playwright-cli.js.map +1 -1
  84. package/dist/browser/backends/playwright-lib.d.ts +84 -1
  85. package/dist/browser/backends/playwright-lib.d.ts.map +1 -1
  86. package/dist/browser/backends/playwright-lib.js +677 -32
  87. package/dist/browser/backends/playwright-lib.js.map +1 -1
  88. package/dist/browser/click-effect.d.ts +84 -0
  89. package/dist/browser/click-effect.d.ts.map +1 -0
  90. package/dist/browser/click-effect.js +235 -0
  91. package/dist/browser/click-effect.js.map +1 -0
  92. package/dist/browser/gateway.d.ts +9 -1
  93. package/dist/browser/gateway.d.ts.map +1 -1
  94. package/dist/browser/index.d.ts +3 -0
  95. package/dist/browser/index.d.ts.map +1 -1
  96. package/dist/browser/index.js +5 -0
  97. package/dist/browser/index.js.map +1 -1
  98. package/dist/browser/types.d.ts +196 -1
  99. package/dist/browser/types.d.ts.map +1 -1
  100. package/dist/cli/index.d.ts +1 -1
  101. package/dist/cli/index.d.ts.map +1 -1
  102. package/dist/cli/index.js +123 -5
  103. package/dist/cli/index.js.map +1 -1
  104. package/dist/codegen/index.d.ts +10 -1
  105. package/dist/codegen/index.d.ts.map +1 -1
  106. package/dist/codegen/index.js +28 -7
  107. package/dist/codegen/index.js.map +1 -1
  108. package/dist/codegen/lint.d.ts +32 -1
  109. package/dist/codegen/lint.d.ts.map +1 -1
  110. package/dist/codegen/lint.js +286 -1
  111. package/dist/codegen/lint.js.map +1 -1
  112. package/dist/codegen/mailbox.d.ts +19 -0
  113. package/dist/codegen/mailbox.d.ts.map +1 -0
  114. package/dist/codegen/mailbox.js +78 -0
  115. package/dist/codegen/mailbox.js.map +1 -0
  116. package/dist/codegen/schema.d.ts.map +1 -1
  117. package/dist/codegen/schema.js +3 -2
  118. package/dist/codegen/schema.js.map +1 -1
  119. package/dist/config/profiles.d.ts +2 -0
  120. package/dist/config/profiles.d.ts.map +1 -1
  121. package/dist/config/profiles.js +2 -0
  122. package/dist/config/profiles.js.map +1 -1
  123. package/dist/core/modalities/api.d.ts.map +1 -1
  124. package/dist/core/modalities/api.js +265 -29
  125. package/dist/core/modalities/api.js.map +1 -1
  126. package/dist/core/modalities/check-docs.d.ts +3 -0
  127. package/dist/core/modalities/check-docs.d.ts.map +1 -0
  128. package/dist/core/modalities/check-docs.js +64 -0
  129. package/dist/core/modalities/check-docs.js.map +1 -0
  130. package/dist/core/modalities/collect-docs.d.ts +3 -0
  131. package/dist/core/modalities/collect-docs.d.ts.map +1 -0
  132. package/dist/core/modalities/collect-docs.js +48 -0
  133. package/dist/core/modalities/collect-docs.js.map +1 -0
  134. package/dist/core/modalities/explore.d.ts.map +1 -1
  135. package/dist/core/modalities/explore.js +2 -0
  136. package/dist/core/modalities/explore.js.map +1 -1
  137. package/dist/core/modalities/mcp-test.d.ts +3 -0
  138. package/dist/core/modalities/mcp-test.d.ts.map +1 -0
  139. package/dist/core/modalities/mcp-test.js +26 -0
  140. package/dist/core/modalities/mcp-test.js.map +1 -0
  141. package/dist/core/registry.d.ts.map +1 -1
  142. package/dist/core/registry.js +11 -3
  143. package/dist/core/registry.js.map +1 -1
  144. package/dist/decider/uses/repair-triage.d.ts +9 -0
  145. package/dist/decider/uses/repair-triage.d.ts.map +1 -1
  146. package/dist/decider/uses/repair-triage.js +20 -3
  147. package/dist/decider/uses/repair-triage.js.map +1 -1
  148. package/dist/design/critique.d.ts +1 -1
  149. package/dist/design/index.d.ts +7 -1
  150. package/dist/design/index.d.ts.map +1 -1
  151. package/dist/design/index.js +20 -2
  152. package/dist/design/index.js.map +1 -1
  153. package/dist/design/schema.d.ts +9 -3
  154. package/dist/design/schema.d.ts.map +1 -1
  155. package/dist/design/schema.js +4 -1
  156. package/dist/design/schema.js.map +1 -1
  157. package/dist/documentarian/check.d.ts +91 -0
  158. package/dist/documentarian/check.d.ts.map +1 -0
  159. package/dist/documentarian/check.js +230 -0
  160. package/dist/documentarian/check.js.map +1 -0
  161. package/dist/documentarian/docs.d.ts +103 -0
  162. package/dist/documentarian/docs.d.ts.map +1 -0
  163. package/dist/documentarian/docs.js +243 -0
  164. package/dist/documentarian/docs.js.map +1 -0
  165. package/dist/documentarian/index.d.ts +2 -0
  166. package/dist/documentarian/index.d.ts.map +1 -1
  167. package/dist/documentarian/index.js +5 -4
  168. package/dist/documentarian/index.js.map +1 -1
  169. package/dist/environment/apply.js +1 -1
  170. package/dist/environment/apply.js.map +1 -1
  171. package/dist/flow/crawl.d.ts +4 -0
  172. package/dist/flow/crawl.d.ts.map +1 -1
  173. package/dist/flow/crawl.js +9 -2
  174. package/dist/flow/crawl.js.map +1 -1
  175. package/dist/fs/inside-dir.d.ts +8 -0
  176. package/dist/fs/inside-dir.d.ts.map +1 -0
  177. package/dist/fs/inside-dir.js +15 -0
  178. package/dist/fs/inside-dir.js.map +1 -0
  179. package/dist/index.d.ts +6 -2
  180. package/dist/index.d.ts.map +1 -1
  181. package/dist/index.js +3 -0
  182. package/dist/index.js.map +1 -1
  183. package/dist/llm/index.d.ts +1 -1
  184. package/dist/llm/index.d.ts.map +1 -1
  185. package/dist/llm/index.js +1 -1
  186. package/dist/llm/index.js.map +1 -1
  187. package/dist/llm/structured.d.ts +19 -0
  188. package/dist/llm/structured.d.ts.map +1 -1
  189. package/dist/llm/structured.js +61 -0
  190. package/dist/llm/structured.js.map +1 -1
  191. package/dist/mailbox/doctor.d.ts +10 -0
  192. package/dist/mailbox/doctor.d.ts.map +1 -0
  193. package/dist/mailbox/doctor.js +33 -0
  194. package/dist/mailbox/doctor.js.map +1 -0
  195. package/dist/mailbox/rule.d.ts +34 -0
  196. package/dist/mailbox/rule.d.ts.map +1 -0
  197. package/dist/mailbox/rule.js +47 -0
  198. package/dist/mailbox/rule.js.map +1 -0
  199. package/dist/mailbox/session.d.ts +5 -0
  200. package/dist/mailbox/session.d.ts.map +1 -1
  201. package/dist/mailbox/session.js +8 -0
  202. package/dist/mailbox/session.js.map +1 -1
  203. package/dist/mcp/server.d.ts +15 -5
  204. package/dist/mcp/server.d.ts.map +1 -1
  205. package/dist/mcp/server.js +75 -27
  206. package/dist/mcp/server.js.map +1 -1
  207. package/dist/mcp/tools.d.ts +194 -82
  208. package/dist/mcp/tools.d.ts.map +1 -1
  209. package/dist/mcp/tools.js +82 -8
  210. package/dist/mcp/tools.js.map +1 -1
  211. package/dist/mcp-test/adversarial.d.ts +80 -0
  212. package/dist/mcp-test/adversarial.d.ts.map +1 -0
  213. package/dist/mcp-test/adversarial.js +99 -0
  214. package/dist/mcp-test/adversarial.js.map +1 -0
  215. package/dist/mcp-test/advice.d.ts +20 -0
  216. package/dist/mcp-test/advice.d.ts.map +1 -0
  217. package/dist/mcp-test/advice.js +22 -0
  218. package/dist/mcp-test/advice.js.map +1 -0
  219. package/dist/mcp-test/call.d.ts +76 -0
  220. package/dist/mcp-test/call.d.ts.map +1 -0
  221. package/dist/mcp-test/call.js +105 -0
  222. package/dist/mcp-test/call.js.map +1 -0
  223. package/dist/mcp-test/cases.d.ts +154 -0
  224. package/dist/mcp-test/cases.d.ts.map +1 -0
  225. package/dist/mcp-test/cases.js +643 -0
  226. package/dist/mcp-test/cases.js.map +1 -0
  227. package/dist/mcp-test/connect.d.ts +70 -0
  228. package/dist/mcp-test/connect.d.ts.map +1 -0
  229. package/dist/mcp-test/connect.js +426 -0
  230. package/dist/mcp-test/connect.js.map +1 -0
  231. package/dist/mcp-test/coverage.d.ts +61 -0
  232. package/dist/mcp-test/coverage.d.ts.map +1 -0
  233. package/dist/mcp-test/coverage.js +76 -0
  234. package/dist/mcp-test/coverage.js.map +1 -0
  235. package/dist/mcp-test/discover.d.ts +40 -0
  236. package/dist/mcp-test/discover.d.ts.map +1 -0
  237. package/dist/mcp-test/discover.js +149 -0
  238. package/dist/mcp-test/discover.js.map +1 -0
  239. package/dist/mcp-test/guard.d.ts +161 -0
  240. package/dist/mcp-test/guard.d.ts.map +1 -0
  241. package/dist/mcp-test/guard.js +363 -0
  242. package/dist/mcp-test/guard.js.map +1 -0
  243. package/dist/mcp-test/model.d.ts +89 -0
  244. package/dist/mcp-test/model.d.ts.map +1 -0
  245. package/dist/mcp-test/model.js +88 -0
  246. package/dist/mcp-test/model.js.map +1 -0
  247. package/dist/mcp-test/payloads.d.ts +20 -0
  248. package/dist/mcp-test/payloads.d.ts.map +1 -0
  249. package/dist/mcp-test/payloads.js +20 -0
  250. package/dist/mcp-test/payloads.js.map +1 -0
  251. package/dist/mcp-test/report.d.ts +55 -0
  252. package/dist/mcp-test/report.d.ts.map +1 -0
  253. package/dist/mcp-test/report.js +157 -0
  254. package/dist/mcp-test/report.js.map +1 -0
  255. package/dist/mcp-test/run.d.ts +68 -0
  256. package/dist/mcp-test/run.d.ts.map +1 -0
  257. package/dist/mcp-test/run.js +467 -0
  258. package/dist/mcp-test/run.js.map +1 -0
  259. package/dist/mcp-test/runner.d.ts +133 -0
  260. package/dist/mcp-test/runner.d.ts.map +1 -0
  261. package/dist/mcp-test/runner.js +412 -0
  262. package/dist/mcp-test/runner.js.map +1 -0
  263. package/dist/mcp-test/schema.d.ts +103 -0
  264. package/dist/mcp-test/schema.d.ts.map +1 -0
  265. package/dist/mcp-test/schema.js +513 -0
  266. package/dist/mcp-test/schema.js.map +1 -0
  267. package/dist/mcp-test/secrets.d.ts +25 -0
  268. package/dist/mcp-test/secrets.d.ts.map +1 -0
  269. package/dist/mcp-test/secrets.js +67 -0
  270. package/dist/mcp-test/secrets.js.map +1 -0
  271. package/dist/observe/index.d.ts +3 -1
  272. package/dist/observe/index.d.ts.map +1 -1
  273. package/dist/observe/index.js +1 -0
  274. package/dist/observe/index.js.map +1 -1
  275. package/dist/observe/locator-hints.d.ts +18 -0
  276. package/dist/observe/locator-hints.d.ts.map +1 -0
  277. package/dist/observe/locator-hints.js +36 -0
  278. package/dist/observe/locator-hints.js.map +1 -0
  279. package/dist/observe/overlays.d.ts +135 -0
  280. package/dist/observe/overlays.d.ts.map +1 -0
  281. package/dist/observe/overlays.js +242 -0
  282. package/dist/observe/overlays.js.map +1 -0
  283. package/dist/observe/parse-aria.d.ts +7 -1
  284. package/dist/observe/parse-aria.d.ts.map +1 -1
  285. package/dist/observe/parse-aria.js +79 -4
  286. package/dist/observe/parse-aria.js.map +1 -1
  287. package/dist/probe/index.d.ts +3 -1
  288. package/dist/probe/index.d.ts.map +1 -1
  289. package/dist/probe/index.js +3 -2
  290. package/dist/probe/index.js.map +1 -1
  291. package/dist/project/index.d.ts +2 -0
  292. package/dist/project/index.d.ts.map +1 -1
  293. package/dist/project/index.js +10 -2
  294. package/dist/project/index.js.map +1 -1
  295. package/dist/prompts/local/describe-screen.d.ts +7 -0
  296. package/dist/prompts/local/describe-screen.d.ts.map +1 -0
  297. package/dist/prompts/local/describe-screen.js +29 -0
  298. package/dist/prompts/local/describe-screen.js.map +1 -0
  299. package/dist/prompts/local/index.d.ts.map +1 -1
  300. package/dist/prompts/local/index.js +7 -0
  301. package/dist/prompts/local/index.js.map +1 -1
  302. package/dist/prompts/local/name-overlays.d.ts +6 -0
  303. package/dist/prompts/local/name-overlays.d.ts.map +1 -0
  304. package/dist/prompts/local/name-overlays.js +16 -0
  305. package/dist/prompts/local/name-overlays.js.map +1 -0
  306. package/dist/prompts/local/qa-api-flows.d.ts +8 -0
  307. package/dist/prompts/local/qa-api-flows.d.ts.map +1 -0
  308. package/dist/prompts/local/qa-api-flows.js +19 -0
  309. package/dist/prompts/local/qa-api-flows.js.map +1 -0
  310. package/dist/prompts/local/qa-playwright-ts-writer.d.ts +1 -1
  311. package/dist/prompts/local/qa-playwright-ts-writer.d.ts.map +1 -1
  312. package/dist/prompts/local/qa-playwright-ts-writer.js +5 -1
  313. package/dist/prompts/local/qa-playwright-ts-writer.js.map +1 -1
  314. package/dist/prompts/local/qa-testcase-from-ui.d.ts +1 -1
  315. package/dist/prompts/local/qa-testcase-from-ui.d.ts.map +1 -1
  316. package/dist/prompts/local/qa-testcase-from-ui.js +2 -0
  317. package/dist/prompts/local/qa-testcase-from-ui.js.map +1 -1
  318. package/dist/session/index.d.ts.map +1 -1
  319. package/dist/session/index.js +24 -2
  320. package/dist/session/index.js.map +1 -1
  321. package/dist/validate/index.d.ts +11 -0
  322. package/dist/validate/index.d.ts.map +1 -1
  323. package/dist/validate/index.js +21 -0
  324. package/dist/validate/index.js.map +1 -1
  325. package/dist/validate/runner.d.ts +15 -1
  326. package/dist/validate/runner.d.ts.map +1 -1
  327. package/dist/validate/runner.js +158 -25
  328. package/dist/validate/runner.js.map +1 -1
  329. package/dist/validate/write-guard.d.ts +24 -0
  330. package/dist/validate/write-guard.d.ts.map +1 -0
  331. package/dist/validate/write-guard.js +210 -0
  332. package/dist/validate/write-guard.js.map +1 -0
  333. package/dist/view/index.d.ts +9 -0
  334. package/dist/view/index.d.ts.map +1 -0
  335. package/dist/view/index.js +126 -0
  336. package/dist/view/index.js.map +1 -0
  337. package/package.json +3 -2
@@ -0,0 +1,852 @@
1
+ /**
2
+ * #228 / #229 — an OpenAPI 3.x document built from examples instead of a written spec.
3
+ *
4
+ * A Postman collection, a HAR file (#228) and the traffic recorded while exploring the UI (#229) all end here: each
5
+ * request seen is an {@link Exchange}, the {@link DerivedSpecBuilder} folds them into operations (ids in the path
6
+ * become parameters, body schemas are inferred from the examples), and {@link writeDerivedSpec} saves the result as
7
+ * `openapi.derived.json`, which `ingestOpenApi` reads like any other spec. No format of our own: what cannot be
8
+ * written as OpenAPI is not kept.
9
+ *
10
+ * What was inferred rather than described carries `x-cairn-derived: true` (the document, each operation, each body
11
+ * schema), so whoever reads the spec knows to trust it less.
12
+ *
13
+ * Whatever the traffic says, the file holds a string that came from it only when that string has passed a fixed form:
14
+ * a name ({@link isName}), a word of a path ({@link isPathWord}) or a media type ({@link writtenMedia}). The form leaves
15
+ * out most free text, not all of it. Anything else is dropped or becomes a parameter. A wrong fold costs one route in a
16
+ * draft, a wrong keep costs someone's data, so when unsure it folds.
17
+ *
18
+ * Secrets are held hard: a credential, a cookie, a value under a sensitive name or a secret of the run reaches the file
19
+ * neither whole, nor as a part of a word, nor as a name ({@link KnownValues.isSecret}). Personal data in a path goes as far
20
+ * as a form can see: a word of several parts equal to a value, or one of three words in a place before a literal word, is a
21
+ * parameter; a word of one part no form tells from a word of the API, it stays, and the docs say so. What a person wrote in
22
+ * a collection stays as written, but for what holds a secret. Bodies, headers, cookies and query values are read for
23
+ * their shape and their values, and not kept.
24
+ */
25
+ import { createHash } from "node:crypto";
26
+ import { mkdir, writeFile } from "node:fs/promises";
27
+ import { join } from "node:path";
28
+ import { secretValues } from "../decider/redact.js";
29
+ import { caseFlips, secretShaped } from "../browser/click-effect.js";
30
+ import { collectSecrets, SENSITIVE } from "./guard.js";
31
+ /** The extension that marks what was inferred from examples. */
32
+ export const DERIVED_KEY = "x-cairn-derived";
33
+ /** The file name a derived spec is saved under in the run's directory. */
34
+ export const DERIVED_SPEC_FILE = "openapi.derived.json";
35
+ const NAMED = [/^\{\{\s*([\w.-]+)\s*\}\}$/, /^:([A-Za-z_][\w-]*)$/, /^\{([A-Za-z_][\w.-]*)\}$/];
36
+ const decoded = (s) => {
37
+ try {
38
+ return decodeURIComponent(s);
39
+ }
40
+ catch {
41
+ return s;
42
+ }
43
+ };
44
+ /** The form of a name: a JSON key, a form field, a query name. No dot: a dotted name reads like a domain. */
45
+ const NAME_FORM = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
46
+ /** Long random text in a name: long hex, letters that flip case like random text, no vowel, digits all through it. */
47
+ function randomName(s) {
48
+ const run = s.replace(/[-_]/g, "");
49
+ if (run.length >= 16 && (/^[0-9a-f]+$/i.test(run) || caseFlips(run) >= run.length / 3))
50
+ return true;
51
+ if (run.length >= 8 && !/[aeiouy]/i.test(run))
52
+ return true;
53
+ return (run.match(/\d+/g)?.length ?? 0) >= 3;
54
+ }
55
+ /** The most `-`/`_` separated parts of a word: more reads as a sentence. Four can still be one: the docs say so. */
56
+ const MAX_PARTS = 4;
57
+ /**
58
+ * What a name and a word of a path share, and most free text and random text have not: up to {@link MAX_PARTS} parts, up
59
+ * to 3 digits at the end of a part, at most one part of 4 or more characters that are all hex, and in a word of 8 letters
60
+ * or more a fifth of them vowels (`y` is one) and at most 3 turns from lower to upper case.
61
+ */
62
+ function wordLike(s) {
63
+ const parts = s.split(/[-_]/).filter(Boolean);
64
+ if (parts.length > MAX_PARTS || parts.some((p) => /\d{4,}$/.test(p)))
65
+ return false;
66
+ if (parts.filter((p) => p.length >= 4 && /^[0-9a-f]+$/i.test(p)).length >= 2)
67
+ return false;
68
+ const letters = s.replace(/[^A-Za-z]/g, "");
69
+ if (letters.length < 8)
70
+ return true;
71
+ return (letters.match(/[aeiouy]/gi)?.length ?? 0) * 5 >= letters.length && (s.match(/[a-z](?=[A-Z])/g)?.length ?? 0) <= 3;
72
+ }
73
+ /** A string that may be written as a name. `address1`, `base64data`, `sha256sum` are; `user.name` and `Alice Smith` are not. */
74
+ export const isName = (s) => s.length <= 64 && NAME_FORM.test(s) && wordLike(s) && !randomName(s);
75
+ const WORD_FORM = /^[A-Za-z]+\d*(?:[-_][A-Za-z]+\d*)*$/;
76
+ /**
77
+ * A word that may stay in a path: per `-`/`_` separated part ASCII letters, with digits only at the end (`v1`, `oauth2`,
78
+ * `s3`; not `a1b2c3d`). Not hex-only of 6 or more (`deadbeef`), no part of 5 or more letters without a vowel, not longer
79
+ * than 32, not credential-shaped ({@link secretShaped}), and {@link wordLike}. The length comes first: no regex sees a long value.
80
+ */
81
+ export function isPathWord(s) {
82
+ if (s.length > 32 || !WORD_FORM.test(s) || /^[0-9a-f]{6,}$/i.test(s) || secretShaped(s) || !wordLike(s))
83
+ return false;
84
+ return s.split(/[-_]/).every((part) => {
85
+ const letters = part.replace(/\d+$/, "");
86
+ return letters.length < 5 || /[aeiouy]/i.test(letters);
87
+ });
88
+ }
89
+ /**
90
+ * The `name=value` parts of a query or a form body, decoded. A part with no `=` has no name at all: `?bare`, a text body
91
+ * or a JSON body sent as a form. It comes back in `bare`, as a value.
92
+ */
93
+ export function formParts(text) {
94
+ const dec = (s) => decoded(s.replace(/\+/g, " "));
95
+ const fields = [];
96
+ const bare = [];
97
+ for (const part of text.split("&")) {
98
+ const eq = part.indexOf("=");
99
+ if (eq >= 0)
100
+ fields.push([dec(part.slice(0, eq)), dec(part.slice(eq + 1))]);
101
+ else if (part)
102
+ bare.push(dec(part));
103
+ }
104
+ return { fields, bare };
105
+ }
106
+ /** `projects` → `projectId`, `categories` → `categoryId`, `v2` (or nothing) → `id`. */
107
+ function nameFor(previous) {
108
+ if (!previous || !/^[A-Za-z][A-Za-z_-]*$/.test(previous))
109
+ return "id";
110
+ const word = previous.replace(/[-_]+(\w)/g, (_, c) => c.toUpperCase());
111
+ const one = /ies$/.test(word) ? `${word.slice(0, -3)}y` : /(?:ss|us)$/.test(word) ? word : word.replace(/s$/, "");
112
+ return `${one.charAt(0).toLowerCase()}${one.slice(1)}Id`;
113
+ }
114
+ const isLiteral = (s) => "literal" in s;
115
+ const shapeOf = (segs) => segs.map((s) => (isLiteral(s) ? s.literal : "{}")).join("/");
116
+ function segmentsOf(path, authored) {
117
+ return path
118
+ .split("/")
119
+ .filter((s, i) => s !== "" || i === 0)
120
+ .map((raw, i) => {
121
+ if (i === 0 && raw === "")
122
+ return { literal: "" }; // what makes the leading `/`
123
+ const s = decoded(raw.split(";")[0] ?? "");
124
+ if (authored) {
125
+ for (const re of NAMED) {
126
+ const m = re.exec(s);
127
+ if (m?.[1])
128
+ return { name: m[1].replace(/[^\w-]/g, "_"), integer: false };
129
+ }
130
+ }
131
+ if (/^\d+$/.test(s))
132
+ return { integer: true };
133
+ // A person wrote it: it stays, but for an id or an address that came with an example, and has no form to pass.
134
+ if (authored)
135
+ return s.includes("@") || s === "‹v›" || s === "{}" || secretShaped(s) ? { integer: false } : { literal: s };
136
+ return isPathWord(s) ? { literal: s } : { integer: false };
137
+ });
138
+ }
139
+ /**
140
+ * The written form of a path. A parameter a person named keeps its name. Any other takes its name only from the word
141
+ * before it, when that word stayed in the path (`/projects/123/tasks/9` → `/projects/{projectId}/tasks/{taskId}`), and
142
+ * is `{id}` otherwise or when it is the only one; numbered when repeated.
143
+ */
144
+ function written(segs) {
145
+ const count = segs.filter((s) => !isLiteral(s)).length;
146
+ const used = new Set();
147
+ const params = [];
148
+ const out = segs.map((p, i) => {
149
+ if (isLiteral(p))
150
+ return p.literal;
151
+ const prev = segs[i - 1];
152
+ let name = p.name ?? (count === 1 ? "id" : nameFor(prev && isLiteral(prev) ? prev.literal : undefined));
153
+ for (let n = 2; used.has(name); n++)
154
+ name = `${p.name ?? "id"}${n}`;
155
+ used.add(name);
156
+ params.push(p.integer ? { name, integer: true } : { name });
157
+ return `{${name}}`;
158
+ });
159
+ const joined = out.join("/");
160
+ return { path: joined.startsWith("/") ? joined : `/${joined}`, params };
161
+ }
162
+ /**
163
+ * The templated form of one path, seen alone. `authored`: a segment named as a parameter (`:id`, `{{id}}`, `{id}`) keeps
164
+ * its name and a word needs no form; in recorded traffic such a segment is a value like any other.
165
+ */
166
+ export function templatePath(path, authored = true) {
167
+ return written(segmentsOf(path, authored));
168
+ }
169
+ // ---------------------------------------------------------------------------------------------------------------
170
+ // Schemas
171
+ const MAX_DEPTH = 8;
172
+ const MAX_ITEMS = 50;
173
+ /** The most keys an object keeps, in one example and over the whole run; then it is a map. */
174
+ const MAX_KEYS = 200;
175
+ /** This many keys of one shape (`user_1`, `user_2`) make an object a map whatever their number. */
176
+ const MANY_OF_ONE_SHAPE = 20;
177
+ /** From this many keys, values all of one shape that is no scalar make an object a map. */
178
+ const ONE_SHAPE_AT = 8;
179
+ /** A schema without its scalars: `{ role: "a", team: null }` and `{ role: "b", team: "c" }` are one shape. */
180
+ function skeleton(s) {
181
+ if (s.type === "array")
182
+ return `[${s.items ? skeleton(s.items) : ""}]`;
183
+ if (s.type !== "object")
184
+ return "";
185
+ const fields = Object.entries((s.properties ?? {})).map(([k, v]) => `${k}:${skeleton(v)}`);
186
+ return `{${fields.sort().join()}${s.additionalProperties ? `*${skeleton(s.additionalProperties)}` : ""}}`;
187
+ }
188
+ function oneShape(values) {
189
+ if (values.length < ONE_SHAPE_AT)
190
+ return false;
191
+ const shapes = new Set(values.filter((v) => v.type !== undefined).map(skeleton));
192
+ return shapes.size === 1 && !shapes.has("");
193
+ }
194
+ function manyOfOneShape(keys) {
195
+ const seen = new Map();
196
+ for (const k of keys) {
197
+ const shape = k.replace(/\d+/g, "0");
198
+ const n = (seen.get(shape) ?? 0) + 1;
199
+ if (n >= MANY_OF_ONE_SHAPE)
200
+ return true;
201
+ seen.set(shape, n);
202
+ }
203
+ return false;
204
+ }
205
+ /**
206
+ * The JSON schema of one example value: types, object keys (all `required`) and array items — never the value. A
207
+ * `null` gives `{ nullable: true }` with no type, so a later example can say what the type is. An empty array has no
208
+ * `items` yet for the same reason. A key that is no {@link isName} is dropped alone. An object most of whose keys are
209
+ * dropped, with many keys of one shape, with many values of one shape or with too many keys, is a map keyed by people or
210
+ * ids: its schema is `additionalProperties` with the values' merged schema, and no key is kept.
211
+ */
212
+ export function schemaOf(v, depth = 0) {
213
+ if (v === null)
214
+ return { nullable: true };
215
+ if (depth > MAX_DEPTH)
216
+ return {};
217
+ if (Array.isArray(v)) {
218
+ let items;
219
+ for (const x of v.slice(0, MAX_ITEMS)) {
220
+ const s = schemaOf(x, depth + 1);
221
+ items = items ? mergeSchema(items, s) : s;
222
+ }
223
+ return items ? { type: "array", items } : { type: "array" };
224
+ }
225
+ switch (typeof v) {
226
+ case "boolean":
227
+ return { type: "boolean" };
228
+ case "number":
229
+ return { type: Number.isInteger(v) ? "integer" : "number" };
230
+ case "string":
231
+ return { type: "string" };
232
+ case "object": {
233
+ const all = Object.keys(v);
234
+ const keys = all.filter(isName);
235
+ const schemas = new Map(all.slice(0, MAX_KEYS).map((k) => [k, schemaOf(v[k], depth + 1)]));
236
+ if (keys.length * 2 < all.length || all.length > MAX_KEYS || manyOfOneShape(keys) || oneShape([...schemas.values()])) {
237
+ return { type: "object", additionalProperties: [...schemas.values()].reduce((m, x) => mergeSchema(m, x)) };
238
+ }
239
+ const properties = {};
240
+ for (const k of keys)
241
+ properties[k] = schemas.get(k);
242
+ return keys.length ? { type: "object", properties, required: keys } : { type: "object" };
243
+ }
244
+ default:
245
+ return {};
246
+ }
247
+ }
248
+ /** Two examples' schemas as one: keys of either, `required` only when in both, `integer` + `number` is `number`, a
249
+ * `null` makes it `nullable`, and two types that do not agree make it anything (`{}`). A map merged with an object is
250
+ * a map whose values take every value seen. */
251
+ export function mergeSchema(a, b) {
252
+ if (Object.keys(a).length === 0 || Object.keys(b).length === 0)
253
+ return {};
254
+ if (a.type === undefined)
255
+ return b.type === undefined ? { nullable: true } : { ...b, nullable: true };
256
+ if (b.type === undefined)
257
+ return { ...a, nullable: true };
258
+ const nullable = a.nullable === true || b.nullable === true;
259
+ let out;
260
+ if (a.type === b.type && a.type === "object" && (a.additionalProperties !== undefined || b.additionalProperties !== undefined)) {
261
+ const values = [a, b].flatMap((x) => [
262
+ ...(x.additionalProperties !== undefined ? [x.additionalProperties] : []),
263
+ ...Object.values((x.properties ?? {})),
264
+ ]);
265
+ out = { type: "object", additionalProperties: values.reduce((m, x) => mergeSchema(m, x)) };
266
+ }
267
+ else if (a.type === b.type && a.type === "object") {
268
+ const pa = (a.properties ?? {});
269
+ const pb = (b.properties ?? {});
270
+ const properties = { ...pa };
271
+ for (const [k, s] of Object.entries(pb))
272
+ properties[k] = pa[k] ? mergeSchema(pa[k], s) : s;
273
+ const names = Object.keys(properties);
274
+ if (names.length > MAX_KEYS || manyOfOneShape(names) || oneShape(Object.values(properties))) {
275
+ const map = { type: "object", additionalProperties: Object.values(properties).reduce((m, x) => mergeSchema(m, x)) };
276
+ return nullable ? { ...map, nullable: true } : map;
277
+ }
278
+ const rb = new Set((b.required ?? []));
279
+ const required = (a.required ?? []).filter((k) => rb.has(k));
280
+ out = { type: "object", ...(Object.keys(properties).length ? { properties } : {}), ...(required.length ? { required } : {}) };
281
+ }
282
+ else if (a.type === b.type && a.type === "array") {
283
+ const ia = a.items;
284
+ const ib = b.items;
285
+ const items = ia && ib ? mergeSchema(ia, ib) : (ia ?? ib);
286
+ out = items ? { type: "array", items } : { type: "array" };
287
+ }
288
+ else if (a.type === b.type) {
289
+ out = { type: a.type };
290
+ }
291
+ else if ((a.type === "integer" || a.type === "number") && (b.type === "integer" || b.type === "number")) {
292
+ out = { type: "number" };
293
+ }
294
+ else {
295
+ return {};
296
+ }
297
+ return nullable ? { ...out, nullable: true } : out;
298
+ }
299
+ /** Ready for the document: an array with no item seen takes any items, a value only ever `null` is left open (not
300
+ * pinned to `null`), a name that is or holds a secret is dropped, and the top is marked derived. */
301
+ function finalSchema(s, known, top = true) {
302
+ let out = { ...s };
303
+ if (out.type === undefined)
304
+ out = {};
305
+ if (out.type === "array")
306
+ out.items = out.items ? finalSchema(out.items, known, false) : {};
307
+ if (out.additionalProperties && typeof out.additionalProperties === "object") {
308
+ out.additionalProperties = finalSchema(out.additionalProperties, known, false);
309
+ }
310
+ if (out.properties) {
311
+ const entries = Object.entries(out.properties);
312
+ const kept = entries.filter(([k]) => !known.isSecret(k));
313
+ if (kept.length * 2 < entries.length) {
314
+ delete out.properties;
315
+ delete out.required;
316
+ out.additionalProperties = finalSchema(entries.map(([, v]) => v).reduce((m, x) => mergeSchema(m, x)), known, false);
317
+ }
318
+ else {
319
+ out.properties = Object.fromEntries(kept.map(([k, v]) => [k, finalSchema(v, known, false)]));
320
+ const required = (out.required ?? []).filter((k) => !known.isSecret(k));
321
+ if (required.length)
322
+ out.required = required;
323
+ else
324
+ delete out.required;
325
+ }
326
+ }
327
+ return top ? { ...out, [DERIVED_KEY]: true } : out;
328
+ }
329
+ // ---------------------------------------------------------------------------------------------------------------
330
+ // Traffic
331
+ const STATIC_TYPES = new Set(["document", "stylesheet", "script", "image", "font", "media", "manifest", "texttrack", "imageset"]);
332
+ const STATIC_MIME = /^(?:text\/(?:html|css|javascript|vtt)|(?:application|text)\/(?:x-)?(?:java|ecma)script|image\/|font\/|audio\/|video\/|application\/(?:font|x-font|wasm|manifest\+json|vnd\.ms-fontobject))/i;
333
+ const STATIC_EXT = /\.(?:m?js|css|map|png|jpe?g|gif|svg|ico|webp|avif|bmp|woff2?|ttf|otf|eot|mp4|webm|mp3|ogg|wav|html?|wasm)$/i;
334
+ /**
335
+ * Path prefixes the hosting layer serves on the app's own origin: not the application's API (#278). Add a family here
336
+ * when a platform's beacon or challenge endpoint shows up in a draft.
337
+ */
338
+ export const INFRASTRUCTURE_PATH_PREFIXES = [
339
+ "/cdn-cgi/", // Cloudflare: rum beacon, trace, challenge
340
+ ];
341
+ /** A request the application's API answers — not an infrastructure endpoint, a page, a script, a style, an image, a font or a media file. */
342
+ export function isApiTraffic(r) {
343
+ if (r.resourceType && STATIC_TYPES.has(r.resourceType.toLowerCase()))
344
+ return false;
345
+ if (r.mimeType && STATIC_MIME.test(r.mimeType.trim()))
346
+ return false;
347
+ let path;
348
+ try {
349
+ path = new URL(r.url).pathname;
350
+ }
351
+ catch {
352
+ path = r.url.split(/[?#]/)[0] ?? "";
353
+ }
354
+ if (INFRASTRUCTURE_PATH_PREFIXES.some((p) => path.startsWith(p)))
355
+ return false;
356
+ return !STATIC_EXT.test(path);
357
+ }
358
+ /** `application/json; charset=utf-8` → `application/json`. */
359
+ export function mediaType(contentType) {
360
+ const t = contentType?.split(";")[0]?.trim().toLowerCase();
361
+ return t ? t : undefined;
362
+ }
363
+ /** A media type whose body is read as JSON (`application/json`, `application/problem+json`, `…+json`). */
364
+ export const isJsonMedia = (t) => t !== undefined && /[/+]json$/.test(t);
365
+ const WRITTEN_MEDIA = new Set([
366
+ "application/x-www-form-urlencoded",
367
+ "multipart/form-data",
368
+ "text/plain",
369
+ "text/csv",
370
+ "text/xml",
371
+ "application/xml",
372
+ "application/octet-stream",
373
+ "application/graphql",
374
+ ]);
375
+ /** The media type to write for one that was seen: from a fixed set, `…+json` is `application/json`, anything else none. */
376
+ export function writtenMedia(contentType) {
377
+ const t = mediaType(contentType);
378
+ if (isJsonMedia(t))
379
+ return "application/json";
380
+ return t !== undefined && WRITTEN_MEDIA.has(t) ? t : undefined;
381
+ }
382
+ // ---------------------------------------------------------------------------------------------------------------
383
+ // Known values
384
+ /** The longest value kept: a longer one cannot be a word of a path or a name. */
385
+ const MAX_KNOWN_LENGTH = 256;
386
+ /** The most values kept: about 120 MB of digests. Past it nothing can be checked, so no file is written. */
387
+ export const MAX_KNOWN_VALUES = 1_000_000;
388
+ export class TooManyValues extends Error {
389
+ constructor(limit) {
390
+ super(`too many distinct values to check the file against (more than ${limit})`);
391
+ }
392
+ }
393
+ const digest = (value) => createHash("sha256").update(value).digest("base64url").slice(0, 16);
394
+ /**
395
+ * How values and words are compared: no case and no width of the letters, and nothing that only spells a word apart (a
396
+ * space, `-`, `_`, `+`, a zero-width character, a soft or non-breaking hyphen, which NFKC makes U+2010).
397
+ */
398
+ const canon = (s) => s.normalize("NFKC").toLowerCase().replace(/[\s\-_+\u00ad\u200b-\u200d\u2010\u2011\u2060]/g, "");
399
+ /** Where a text falls apart: at each character that is no letter or digit (kept as a piece), and where camelCase turns. */
400
+ const PART_EDGE = /([^\p{L}\p{N}])|(?<=[\p{Ll}\p{N}])(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}\p{Ll})/u;
401
+ /**
402
+ * Whether a run of whole parts of a text, in canon form, passes `is`: `resetOpenSesame` holds `open-sesame` and `sesame`.
403
+ * Never a piece of a part: `admin` is not in `administrators`. A run is not grown past `longest`, so a long text costs little.
404
+ */
405
+ function someRun(text, is, longest = MAX_KNOWN_LENGTH) {
406
+ const parts = text.normalize("NFKC").split(PART_EDGE).filter(Boolean).map(canon).filter(Boolean);
407
+ for (let from = 0; from < parts.length; from++) {
408
+ let run = "";
409
+ for (let to = from; to < parts.length && run.length + parts[to].length <= longest; to++) {
410
+ run += parts[to];
411
+ if (is(run))
412
+ return true;
413
+ }
414
+ }
415
+ return false;
416
+ }
417
+ /**
418
+ * Every value the traffic showed, each as a fixed-size digest, so the memory goes with their number and not their size.
419
+ * Filled during the run and read when the document is built, because a value can be seen after its path. A word of several
420
+ * parts equal to any of them is a value ({@link isValue}); of one part no value tells it from a route, so `{"type":"projects"}`
421
+ * leaves `/projects` alone. A word and a name are checked against the secrets ({@link isSecret}), also by their parts:
422
+ * `?sort=name` must not take `name` out of every schema. A name that is a value anywhere else stays; the docs say so.
423
+ */
424
+ export class KnownValues {
425
+ limit;
426
+ values = new Set();
427
+ secrets = new Set();
428
+ /** The limit was hit: some value is not here, so nothing can be checked against this. */
429
+ full = false;
430
+ constructor(limit = MAX_KNOWN_VALUES) {
431
+ this.limit = limit;
432
+ }
433
+ get size() {
434
+ return this.values.size;
435
+ }
436
+ put(raw, secret) {
437
+ if (raw.length > MAX_KNOWN_LENGTH)
438
+ return;
439
+ if (raw.includes("%") && decoded(raw) !== raw)
440
+ this.put(decoded(raw), secret);
441
+ const at = raw.lastIndexOf("@"); // an address: its local part goes alone in a path
442
+ if (at > 0)
443
+ this.put(raw.slice(0, at), secret && worthScrubbing(raw.slice(0, at)));
444
+ const v = canon(raw);
445
+ if (!v)
446
+ return;
447
+ const d = digest(v);
448
+ if (this.values.has(d)) {
449
+ if (secret)
450
+ this.secrets.add(d);
451
+ return;
452
+ }
453
+ if (this.values.size >= this.limit) {
454
+ this.full = true;
455
+ return;
456
+ }
457
+ this.values.add(d);
458
+ if (secret)
459
+ this.secrets.add(d);
460
+ }
461
+ add(value) {
462
+ this.put(value, false);
463
+ }
464
+ /** A value with its name (a query or form field, a key of a body, a variable): under a sensitive name it is a secret. */
465
+ field(name, value) {
466
+ if (SENSITIVE.test(name) && worthScrubbing(value, name))
467
+ this.secret(value);
468
+ else
469
+ this.add(value);
470
+ }
471
+ /**
472
+ * A credential or a secret of the run, also as a cookie holds it: in quotes, or signed (`s:value.signature`). One that is a
473
+ * word of the document's vocabulary is only a value.
474
+ */
475
+ secret(value) {
476
+ const plain = decoded(value).trim().replace(/^"(.*)"$/, "$1");
477
+ for (const v of [value, plain, /^s:(.+)\.[^.]+$/.exec(plain)?.[1] ?? plain])
478
+ this.put(v, worthScrubbing(v));
479
+ }
480
+ /** One header's value, whole; with a credential header's parts (after `Bearer `, each cookie) as secrets. */
481
+ header(name, value) {
482
+ for (const line of value.split("\n")) {
483
+ this.add(line);
484
+ // Of a Set-Cookie only the cookie: `Path=/` and `SameSite=Strict` are not its values.
485
+ const v = /^set-cookie/i.test(name) ? (line.split(";")[0] ?? "") : line;
486
+ if (DROPPED_HEADERS.test(name) || SENSITIVE.test(name))
487
+ for (const s of collectSecrets({ [name]: v }))
488
+ this.secret(s);
489
+ }
490
+ }
491
+ /** Every string in a parsed body with the name it sits under, at any depth and past any item limit: a loop, so a deep body cannot overflow. */
492
+ json(v) {
493
+ const stack = [["", v]];
494
+ while (stack.length > 0) {
495
+ const [name, x] = stack.pop();
496
+ if (typeof x === "string")
497
+ this.field(name, x);
498
+ else if (Array.isArray(x))
499
+ for (const y of x)
500
+ stack.push([name, y]);
501
+ else if (x && typeof x === "object")
502
+ for (const [k, y] of Object.entries(x))
503
+ stack.push([k, y]);
504
+ }
505
+ }
506
+ /** A word of several parts that is a value as a whole: `jane-roe`, also as `jane_roe` and `janeRoe`. */
507
+ isValue(word) {
508
+ return PART_EDGE.test(word) && this.values.has(digest(canon(word)));
509
+ }
510
+ /** The word or name is a secret, or holds one as a run of whole parts ({@link someRun}). */
511
+ isSecret(word) {
512
+ return someRun(word, (run) => this.secrets.has(digest(run)));
513
+ }
514
+ }
515
+ const METHODS = new Set(["get", "put", "post", "delete", "options", "head", "patch", "trace"]);
516
+ /** A longer path is no API's: it is dropped, so the folding below stays cheap whatever a page asks for. */
517
+ const MAX_SEGMENTS = 32;
518
+ /** This many distinct words in one place of a path, between the same words and before a literal word, are values. */
519
+ const FOLD_AT = 3;
520
+ const merged = (prev, next, had) => !had ? next : prev && next ? mergeSchema(prev, next) : (prev ?? next);
521
+ /**
522
+ * Folds {@link Exchange}s into OpenAPI operations one at a time, so nothing but the merged shapes, the words that passed
523
+ * their form and the digests of {@link known} is held. What depends on all the traffic is decided when the document is
524
+ * built, because a value can be seen after its path.
525
+ */
526
+ export class DerivedSpecBuilder {
527
+ ops = new Map();
528
+ known;
529
+ constructor(opts = {}) {
530
+ this.known = new KnownValues(opts.maxKnownValues);
531
+ }
532
+ /** How many operations the requests added so far make. */
533
+ get size() {
534
+ return this.resolved().length;
535
+ }
536
+ add(x) {
537
+ this.known.json(x.request?.body);
538
+ this.known.json(x.response?.body);
539
+ const method = x.method.toLowerCase();
540
+ if (!METHODS.has(method))
541
+ return;
542
+ const segs = segmentsOf(x.path, x.authored === true);
543
+ if (segs.length > MAX_SEGMENTS)
544
+ return;
545
+ const key = `${method} ${shapeOf(segs)}`;
546
+ let op = this.ops.get(key);
547
+ if (!op) {
548
+ op = { method, segs, authored: x.authored === true, query: new Set(), tags: new Set(), seen: 0, withBody: 0, requestBodies: new Map(), responses: new Map() };
549
+ this.ops.set(key, op);
550
+ }
551
+ else {
552
+ // A path parameter is an integer only while every value seen was one.
553
+ for (const [i, s] of segs.entries()) {
554
+ const at = op.segs[i];
555
+ if (at && !isLiteral(at) && !isLiteral(s) && !s.integer)
556
+ at.integer = false;
557
+ }
558
+ }
559
+ op.seen += 1;
560
+ for (const q of x.queryKeys ?? [])
561
+ if (op.authored || isName(q))
562
+ op.query.add(q);
563
+ if (op.summary === undefined && x.summary)
564
+ op.summary = x.summary;
565
+ for (const tag of x.tags ?? [])
566
+ op.tags.add(tag);
567
+ const declared = mediaType(x.request?.contentType);
568
+ const reqType = writtenMedia(declared);
569
+ if (x.request && (declared ? reqType : x.request.body !== undefined)) {
570
+ op.withBody += 1;
571
+ const mt = reqType ?? "application/json";
572
+ const s = x.request.body !== undefined ? schemaOf(x.request.body) : undefined;
573
+ op.requestBodies.set(mt, merged(op.requestBodies.get(mt), s, op.requestBodies.has(mt)));
574
+ }
575
+ if (x.status !== undefined && x.status >= 100 && x.status <= 599) {
576
+ const status = String(x.status);
577
+ const media = op.responses.get(status) ?? new Map();
578
+ op.responses.set(status, media);
579
+ const resType = writtenMedia(x.response?.contentType);
580
+ const body = x.response?.body;
581
+ if (resType && body !== undefined)
582
+ media.set(resType, merged(media.get(resType), schemaOf(body), media.has(resType)));
583
+ }
584
+ }
585
+ /**
586
+ * The operations as the document has them. A word or a name a person gave that holds a secret is a parameter with no
587
+ * name, and so is a recorded word of several parts equal to a known value. Three or more distinct recorded words in one
588
+ * place of a path, with the same places before them and the same ending that holds a literal word, are parameters too: no
589
+ * form tells `alice` from `settings`, their number does. With no word after them they stay: `/api/users` and `/api/users/{id}`.
590
+ * What a person wrote is not folded by a value or by its position.
591
+ */
592
+ resolved() {
593
+ const all = [...this.ops.values()].map((op) => ({
594
+ op,
595
+ segs: op.segs.map((s) => {
596
+ const word = isLiteral(s) ? s.literal : s.name;
597
+ return word && (this.known.isSecret(word) || (!op.authored && this.known.isValue(word))) ? { integer: false } : s;
598
+ }),
599
+ }));
600
+ const recorded = all.filter(({ op }) => !op.authored);
601
+ for (;;) {
602
+ const places = new Map();
603
+ const placeOf = (segs, i) => `${i} ${shapeOf(segs.slice(0, i))} ${shapeOf(segs.slice(i + 1))}`;
604
+ const each = (visit) => {
605
+ for (const { segs } of recorded) {
606
+ for (let i = 0; i < segs.length - 1; i++) {
607
+ const s = segs[i];
608
+ if (isLiteral(s) && s.literal !== "" && segs.slice(i + 1).some(isLiteral))
609
+ visit(segs, i, s.literal);
610
+ }
611
+ }
612
+ };
613
+ each((segs, i, word) => {
614
+ const place = placeOf(segs, i);
615
+ const words = places.get(place) ?? new Set();
616
+ words.add(word);
617
+ places.set(place, words);
618
+ });
619
+ const folds = [];
620
+ each((segs, i) => {
621
+ if (places.get(placeOf(segs, i)).size >= FOLD_AT)
622
+ folds.push([segs, i]);
623
+ });
624
+ if (folds.length === 0)
625
+ break;
626
+ for (const [segs, i] of folds)
627
+ segs[i] = { integer: false };
628
+ }
629
+ const out = new Map();
630
+ for (const { op, segs } of all) {
631
+ const key = `${op.method} ${shapeOf(segs)}`;
632
+ const had = out.get(key);
633
+ if (!had) {
634
+ out.set(key, {
635
+ ...op,
636
+ segs,
637
+ query: new Set(op.query),
638
+ tags: new Set(op.tags),
639
+ requestBodies: new Map(op.requestBodies),
640
+ responses: new Map([...op.responses].map(([status, media]) => [status, new Map(media)])),
641
+ });
642
+ continue;
643
+ }
644
+ had.segs = had.segs.map((s, i) => {
645
+ const other = segs[i];
646
+ return isLiteral(s) || isLiteral(other) ? s : { ...s, integer: s.integer && other.integer };
647
+ });
648
+ for (const q of op.query)
649
+ had.query.add(q);
650
+ for (const t of op.tags)
651
+ had.tags.add(t);
652
+ had.summary ??= op.summary;
653
+ had.seen += op.seen;
654
+ had.withBody += op.withBody;
655
+ for (const [mt, s] of op.requestBodies)
656
+ had.requestBodies.set(mt, merged(had.requestBodies.get(mt), s, had.requestBodies.has(mt)));
657
+ for (const [status, media] of op.responses) {
658
+ const into = had.responses.get(status) ?? new Map();
659
+ had.responses.set(status, into);
660
+ for (const [mt, s] of media)
661
+ into.set(mt, merged(into.get(mt), s, into.has(mt)));
662
+ }
663
+ }
664
+ return [...out.values()];
665
+ }
666
+ /** The OpenAPI 3.0.3 document, paths and methods in a stable order. Throws {@link TooManyValues} past the limit: no document rather than an unchecked one. */
667
+ toOpenApi(info, servers = []) {
668
+ if (this.known.full)
669
+ throw new TooManyValues(this.known.limit);
670
+ const paths = {};
671
+ const ops = this.resolved()
672
+ .map((op) => ({ op, ...written(op.segs) }))
673
+ .sort((a, b) => a.path.localeCompare(b.path) || a.op.method.localeCompare(b.op.method));
674
+ for (const { op, path, params } of ops) {
675
+ const item = (paths[path] ??= {});
676
+ const parameters = [
677
+ ...params.map((p) => ({ name: p.name, in: "path", required: true, schema: { type: p.integer ? "integer" : "string" } })),
678
+ ...[...op.query]
679
+ .filter((name) => !this.known.isSecret(name))
680
+ .sort()
681
+ .map((name) => ({ name, in: "query", required: false, schema: { type: "string" } })),
682
+ ];
683
+ const responses = {};
684
+ for (const [status, media] of [...op.responses].sort(([a], [b]) => a.localeCompare(b))) {
685
+ const content = Object.fromEntries([...media].map(([mt, s]) => [mt, s ? { schema: finalSchema(s, this.known) } : {}]));
686
+ responses[status] = { description: `Status ${status}, as recorded`, ...(media.size ? { content } : {}) };
687
+ }
688
+ if (Object.keys(responses).length === 0)
689
+ responses.default = { description: "No response was recorded" };
690
+ item[op.method] = {
691
+ ...(op.summary ? { summary: op.summary } : {}),
692
+ ...(op.tags.size ? { tags: [...op.tags] } : {}),
693
+ ...(parameters.length ? { parameters } : {}),
694
+ ...(op.requestBodies.size
695
+ ? {
696
+ requestBody: {
697
+ required: op.withBody === op.seen,
698
+ content: Object.fromEntries([...op.requestBodies].map(([mt, s]) => [mt, s ? { schema: finalSchema(s, this.known) } : {}])),
699
+ },
700
+ }
701
+ : {}),
702
+ responses,
703
+ [DERIVED_KEY]: true,
704
+ };
705
+ }
706
+ return {
707
+ openapi: "3.0.3",
708
+ info: { title: info.title, version: info.version ?? "0.0.0", ...(info.description ? { description: info.description } : {}) },
709
+ ...(servers.length ? { servers: servers.map((url) => ({ url })) } : {}),
710
+ paths,
711
+ [DERIVED_KEY]: true,
712
+ };
713
+ }
714
+ }
715
+ // ---------------------------------------------------------------------------------------------------------------
716
+ // Secrets and the file
717
+ /** Headers that are never written, whatever their value: the request's credentials and the cookies set back. */
718
+ export const DROPPED_HEADERS = /^(?:authorization|proxy-authorization|cookie|set-cookie|set-cookie2)$/i;
719
+ /**
720
+ * Words a derived document is made of — JSON and OpenAPI vocabulary, flags, placeholders. A field whose value is one
721
+ * of these (Swagger UI's `"password": "string"`, a cookie `csrftoken=true`) carries no secret.
722
+ */
723
+ const VOCABULARY = new Set([
724
+ "true", "false", "null", "none", "undefined", "nil", "yes", "no", "on", "off",
725
+ "string", "number", "integer", "boolean", "object", "array", "int", "float", "double", "date", "date-time",
726
+ "text", "value", "example", "default", "empty", "secret", "token", "password", "bearer", "basic",
727
+ "openapi", "info", "title", "version", "description", "servers", "server", "url", "paths", "path", "query",
728
+ "header", "cookie", "parameters", "name", "in", "required", "schema", "schemas", "type", "properties", "items",
729
+ "nullable", "content", "responses", "requestbody", "summary", "tags", "status", "recorded", "derived",
730
+ "get", "put", "post", "delete", "options", "head", "patch", "trace",
731
+ "application/json", "text/plain", DERIVED_KEY,
732
+ ].map(canon));
733
+ const MIN_SECRET = 4;
734
+ /** A value that counts as a secret: long enough, not a word the document is made of, not just the field's own name. */
735
+ function worthScrubbing(value, name) {
736
+ const v = value.trim();
737
+ if (v.length < MIN_SECRET)
738
+ return false;
739
+ if (VOCABULARY.has(canon(v)))
740
+ return false;
741
+ if (name !== undefined && name.trim().split(/\s+/).map(canon).includes(canon(v)))
742
+ return false;
743
+ return true;
744
+ }
745
+ /**
746
+ * The values a source carried that must not reach the file: every value of `Authorization`, `Cookie` and
747
+ * `Set-Cookie` and of other sensitive headers (the credential after `Bearer `, each cookie value — the api guard's
748
+ * {@link collectSecrets}), the values `decider/redact.ts` reads as secrets from `name: value` pairs (query, form and
749
+ * body fields, variables: `password: …`, `api_key: …`), the user and password of a URL (`values`), and any value
750
+ * shaped like a credential (a JWT, long hex). Placeholders and vocabulary (`"string"`, `true`, a value equal to its
751
+ * field's name) are not secrets and are left out.
752
+ */
753
+ export function exchangeSecrets(input) {
754
+ const out = new Set();
755
+ const lines = [];
756
+ const add = (v, name) => {
757
+ if (worthScrubbing(v, name))
758
+ out.add(v.trim());
759
+ };
760
+ const shaped = (v) => {
761
+ for (const t of v.split(/[\s,;&=]+/))
762
+ if (t.length >= 8 && secretShaped(t))
763
+ add(t);
764
+ };
765
+ for (const [name, value] of input.headers ?? []) {
766
+ if (DROPPED_HEADERS.test(name) || SENSITIVE.test(name))
767
+ for (const s of collectSecrets({ [name]: value }))
768
+ add(s);
769
+ else
770
+ lines.push(`${name}: ${value}`);
771
+ shaped(value);
772
+ }
773
+ for (const [name, value] of input.fields ?? []) {
774
+ if (SENSITIVE.test(name))
775
+ add(value, name);
776
+ lines.push(`${name}: ${value}`);
777
+ shaped(value);
778
+ }
779
+ for (const v of input.values ?? [])
780
+ add(v);
781
+ for (const s of secretValues(lines.join("\n"), {}))
782
+ add(s);
783
+ return [...out].sort((a, b) => b.length - a.length);
784
+ }
785
+ /** String leaves of a parsed body with their keys — `{ user: { password: "x" } }` → `[["password", "x"]]`. */
786
+ export function bodyFields(v, key = "body", out = [], depth = 0) {
787
+ if (depth > MAX_DEPTH || out.length > 500)
788
+ return out;
789
+ if (typeof v === "string")
790
+ out.push([key, v]);
791
+ else if (typeof v === "number" || typeof v === "boolean")
792
+ out.push([key, String(v)]);
793
+ else if (Array.isArray(v))
794
+ for (const x of v.slice(0, MAX_ITEMS))
795
+ bodyFields(x, key, out, depth + 1);
796
+ else if (v && typeof v === "object")
797
+ for (const [k, x] of Object.entries(v))
798
+ bodyFields(x, k, out, depth + 1);
799
+ return out;
800
+ }
801
+ /**
802
+ * The one check left at the end, for free text a person wrote in a collection (its name, a request's name, a folder) and
803
+ * a server's address: an element that holds a secret as a run of whole parts ({@link someRun}) is dropped or, the title
804
+ * being required, replaced: a secret `test` leaves `Latest projects` alone. The words and names of the document were checked
805
+ * when it was built; no string in it is edited, so its structure stays as it is.
806
+ */
807
+ function withoutSecretText(doc, secrets) {
808
+ const canons = new Set(secrets.map(canon));
809
+ const list = [...canons];
810
+ const longest = list.reduce((m, s) => Math.max(m, s.length), 0);
811
+ const holds = (t) => {
812
+ if (typeof t !== "string")
813
+ return false;
814
+ const whole = canon(t);
815
+ return list.some((s) => whole.includes(s)) && someRun(t, (run) => canons.has(run), longest);
816
+ };
817
+ const out = { ...doc };
818
+ const info = doc.info;
819
+ if (info && holds(info.title))
820
+ out.info = { ...info, title: "API draft" };
821
+ if (Array.isArray(doc.servers)) {
822
+ const servers = doc.servers.filter((s) => !holds(s.url));
823
+ if (servers.length)
824
+ out.servers = servers;
825
+ else
826
+ delete out.servers;
827
+ }
828
+ if (doc.paths && typeof doc.paths === "object") {
829
+ out.paths = Object.fromEntries(Object.entries(doc.paths).map(([path, item]) => [
830
+ path,
831
+ Object.fromEntries(Object.entries(item).map(([method, op]) => {
832
+ const { summary, tags, ...rest } = op;
833
+ const kept = Array.isArray(tags) ? tags.filter((t) => !holds(t)) : [];
834
+ return [method, { ...(summary !== undefined && !holds(summary) ? { summary } : {}), ...(kept.length ? { tags: kept } : {}), ...rest }];
835
+ })),
836
+ ]));
837
+ }
838
+ return out;
839
+ }
840
+ /**
841
+ * Save a derived spec as `openapi.derived.json` in `dir` and return its path. `secrets`: the ones that may be in a
842
+ * collection's free text ({@link withoutSecretText}); give them to the document's {@link KnownValues} too, before it is built.
843
+ */
844
+ export async function writeDerivedSpec(dir, doc, secrets = []) {
845
+ const all = [...new Set(secrets.map((s) => s.trim()))].filter((s) => worthScrubbing(s));
846
+ const text = JSON.stringify(withoutSecretText(doc, all), null, 2);
847
+ await mkdir(dir, { recursive: true });
848
+ const file = join(dir, DERIVED_SPEC_FILE);
849
+ await writeFile(file, `${text}\n`, "utf8");
850
+ return file;
851
+ }
852
+ //# sourceMappingURL=derived.js.map