sdkloom 0.0.0-stage → 0.1.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 (383) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +239 -2
  3. package/kits/allowed-sources.json +24 -0
  4. package/kits/csharp/kit.json +6 -0
  5. package/kits/csharp/src/Runtime/Client.cs +295 -0
  6. package/kits/csharp/src/Runtime/Context.cs +216 -0
  7. package/kits/csharp/src/Runtime/Errors.cs +121 -0
  8. package/kits/csharp/src/Runtime/Http.cs +218 -0
  9. package/kits/csharp/src/Runtime/Json.cs +650 -0
  10. package/kits/csharp/src/Runtime/Lang.cs +212 -0
  11. package/kits/csharp/src/Runtime/Models.cs +206 -0
  12. package/kits/csharp/src/Runtime/Multipart.cs +108 -0
  13. package/kits/csharp/src/Runtime/Pagination.cs +122 -0
  14. package/kits/csharp/src/Runtime/Sse.cs +197 -0
  15. package/kits/csharp/src/Runtime/Testing.cs +375 -0
  16. package/kits/csharp/src/Runtime/Transport.cs +212 -0
  17. package/kits/csharp/src/Runtime/Wait.cs +57 -0
  18. package/kits/csharp/src/Runtime/Webhooks.cs +148 -0
  19. package/kits/csharp/tests/ClientTests.cs +128 -0
  20. package/kits/csharp/tests/HttpTests.cs +44 -0
  21. package/kits/csharp/tests/JsonTests.cs +132 -0
  22. package/kits/csharp/tests/LangTests.cs +57 -0
  23. package/kits/csharp/tests/MultipartTests.cs +31 -0
  24. package/kits/csharp/tests/PaginationTests.cs +93 -0
  25. package/kits/csharp/tests/SseTests.cs +122 -0
  26. package/kits/csharp/tests/TestRunner.cs +93 -0
  27. package/kits/csharp/tests/TestingTests.cs +80 -0
  28. package/kits/csharp/tests/TransportTests.cs +145 -0
  29. package/kits/csharp/tests/WaitTests.cs +39 -0
  30. package/kits/csharp/tests/WebhooksTests.cs +46 -0
  31. package/kits/csharp/versions.json +12 -0
  32. package/kits/go/kit.json +6 -0
  33. package/kits/go/src/sdkruntime/client.go +322 -0
  34. package/kits/go/src/sdkruntime/context.go +207 -0
  35. package/kits/go/src/sdkruntime/errors.go +74 -0
  36. package/kits/go/src/sdkruntime/http.go +261 -0
  37. package/kits/go/src/sdkruntime/json.go +527 -0
  38. package/kits/go/src/sdkruntime/lang.go +462 -0
  39. package/kits/go/src/sdkruntime/multipart.go +75 -0
  40. package/kits/go/src/sdkruntime/pagination.go +150 -0
  41. package/kits/go/src/sdkruntime/sse.go +267 -0
  42. package/kits/go/src/sdkruntime/testing.go +343 -0
  43. package/kits/go/src/sdkruntime/transport.go +168 -0
  44. package/kits/go/src/sdkruntime/wait.go +49 -0
  45. package/kits/go/src/sdkruntime/webhooks.go +129 -0
  46. package/kits/go/tests/client_test.go +185 -0
  47. package/kits/go/tests/http_test.go +78 -0
  48. package/kits/go/tests/json_test.go +127 -0
  49. package/kits/go/tests/lang_test.go +98 -0
  50. package/kits/go/tests/multipart_test.go +29 -0
  51. package/kits/go/tests/pagination_test.go +69 -0
  52. package/kits/go/tests/sse_test.go +129 -0
  53. package/kits/go/tests/testing_test.go +121 -0
  54. package/kits/go/tests/transport_test.go +133 -0
  55. package/kits/go/tests/wait_test.go +46 -0
  56. package/kits/go/tests/webhooks_test.go +62 -0
  57. package/kits/go/versions.json +12 -0
  58. package/kits/java/kit.json +6 -0
  59. package/kits/java/src/dev/sdkloom/runtime/ApiException.java +63 -0
  60. package/kits/java/src/dev/sdkloom/runtime/ArgumentException.java +24 -0
  61. package/kits/java/src/dev/sdkloom/runtime/Assert.java +72 -0
  62. package/kits/java/src/dev/sdkloom/runtime/ClientRuntime.java +220 -0
  63. package/kits/java/src/dev/sdkloom/runtime/Clock.java +39 -0
  64. package/kits/java/src/dev/sdkloom/runtime/Context.java +79 -0
  65. package/kits/java/src/dev/sdkloom/runtime/Decode.java +200 -0
  66. package/kits/java/src/dev/sdkloom/runtime/DecodeException.java +26 -0
  67. package/kits/java/src/dev/sdkloom/runtime/Decoder.java +16 -0
  68. package/kits/java/src/dev/sdkloom/runtime/Emitter.java +56 -0
  69. package/kits/java/src/dev/sdkloom/runtime/ErrorFactory.java +18 -0
  70. package/kits/java/src/dev/sdkloom/runtime/EventListener.java +20 -0
  71. package/kits/java/src/dev/sdkloom/runtime/EventStream.java +232 -0
  72. package/kits/java/src/dev/sdkloom/runtime/FakeClock.java +37 -0
  73. package/kits/java/src/dev/sdkloom/runtime/Headers.java +42 -0
  74. package/kits/java/src/dev/sdkloom/runtime/HttpRequest.java +88 -0
  75. package/kits/java/src/dev/sdkloom/runtime/HttpResponse.java +69 -0
  76. package/kits/java/src/dev/sdkloom/runtime/JdkTransport.java +97 -0
  77. package/kits/java/src/dev/sdkloom/runtime/Js.java +230 -0
  78. package/kits/java/src/dev/sdkloom/runtime/Json.java +281 -0
  79. package/kits/java/src/dev/sdkloom/runtime/JsonValue.java +15 -0
  80. package/kits/java/src/dev/sdkloom/runtime/Links.java +62 -0
  81. package/kits/java/src/dev/sdkloom/runtime/Middleware.java +16 -0
  82. package/kits/java/src/dev/sdkloom/runtime/MiddlewareEntry.java +43 -0
  83. package/kits/java/src/dev/sdkloom/runtime/MockRoute.java +111 -0
  84. package/kits/java/src/dev/sdkloom/runtime/MockTransport.java +62 -0
  85. package/kits/java/src/dev/sdkloom/runtime/MultipartForm.java +111 -0
  86. package/kits/java/src/dev/sdkloom/runtime/Next.java +16 -0
  87. package/kits/java/src/dev/sdkloom/runtime/OperationInfo.java +35 -0
  88. package/kits/java/src/dev/sdkloom/runtime/OperationMock.java +105 -0
  89. package/kits/java/src/dev/sdkloom/runtime/OperationSpec.java +125 -0
  90. package/kits/java/src/dev/sdkloom/runtime/Pages.java +55 -0
  91. package/kits/java/src/dev/sdkloom/runtime/Pipeline.java +29 -0
  92. package/kits/java/src/dev/sdkloom/runtime/RawResult.java +31 -0
  93. package/kits/java/src/dev/sdkloom/runtime/RecordedEvent.java +36 -0
  94. package/kits/java/src/dev/sdkloom/runtime/SdkInfo.java +38 -0
  95. package/kits/java/src/dev/sdkloom/runtime/SendOptions.java +34 -0
  96. package/kits/java/src/dev/sdkloom/runtime/ServerSentEvent.java +58 -0
  97. package/kits/java/src/dev/sdkloom/runtime/State.java +58 -0
  98. package/kits/java/src/dev/sdkloom/runtime/Test.java +21 -0
  99. package/kits/java/src/dev/sdkloom/runtime/TestRunner.java +63 -0
  100. package/kits/java/src/dev/sdkloom/runtime/Transport.java +16 -0
  101. package/kits/java/src/dev/sdkloom/runtime/TransportException.java +30 -0
  102. package/kits/java/src/dev/sdkloom/runtime/UrlConnectionTransport.java +195 -0
  103. package/kits/java/src/dev/sdkloom/runtime/Urls.java +116 -0
  104. package/kits/java/src/dev/sdkloom/runtime/Waits.java +53 -0
  105. package/kits/java/src/dev/sdkloom/runtime/WebhookSignatureException.java +24 -0
  106. package/kits/java/src/dev/sdkloom/runtime/Webhooks.java +146 -0
  107. package/kits/java/tests/dev/sdkloom/runtime/ClientTest.java +266 -0
  108. package/kits/java/tests/dev/sdkloom/runtime/EventStreamTest.java +131 -0
  109. package/kits/java/tests/dev/sdkloom/runtime/HttpTest.java +95 -0
  110. package/kits/java/tests/dev/sdkloom/runtime/JdkTransportTest.java +12 -0
  111. package/kits/java/tests/dev/sdkloom/runtime/JsTest.java +102 -0
  112. package/kits/java/tests/dev/sdkloom/runtime/JsonTest.java +87 -0
  113. package/kits/java/tests/dev/sdkloom/runtime/LinksTest.java +22 -0
  114. package/kits/java/tests/dev/sdkloom/runtime/MultipartFormTest.java +30 -0
  115. package/kits/java/tests/dev/sdkloom/runtime/PagesTest.java +75 -0
  116. package/kits/java/tests/dev/sdkloom/runtime/TestData.java +53 -0
  117. package/kits/java/tests/dev/sdkloom/runtime/TestingTest.java +156 -0
  118. package/kits/java/tests/dev/sdkloom/runtime/TransportContract.java +201 -0
  119. package/kits/java/tests/dev/sdkloom/runtime/UrlConnectionTransportTest.java +49 -0
  120. package/kits/java/tests/dev/sdkloom/runtime/WaitsTest.java +43 -0
  121. package/kits/java/tests/dev/sdkloom/runtime/WebhooksTest.java +45 -0
  122. package/kits/java/versions.json +41 -0
  123. package/kits/python/kit.json +6 -0
  124. package/kits/python/src/sdkloom_runtime/__init__.py +1 -0
  125. package/kits/python/src/sdkloom_runtime/client.py +232 -0
  126. package/kits/python/src/sdkloom_runtime/compat.py +195 -0
  127. package/kits/python/src/sdkloom_runtime/context.py +134 -0
  128. package/kits/python/src/sdkloom_runtime/errors.py +65 -0
  129. package/kits/python/src/sdkloom_runtime/http.py +192 -0
  130. package/kits/python/src/sdkloom_runtime/lang.py +207 -0
  131. package/kits/python/src/sdkloom_runtime/models.py +221 -0
  132. package/kits/python/src/sdkloom_runtime/multipart.py +69 -0
  133. package/kits/python/src/sdkloom_runtime/pagination.py +61 -0
  134. package/kits/python/src/sdkloom_runtime/pipeline.py +39 -0
  135. package/kits/python/src/sdkloom_runtime/sse.py +121 -0
  136. package/kits/python/src/sdkloom_runtime/testing.py +224 -0
  137. package/kits/python/src/sdkloom_runtime/transport.py +120 -0
  138. package/kits/python/src/sdkloom_runtime/wait.py +44 -0
  139. package/kits/python/src/sdkloom_runtime/webhooks.py +84 -0
  140. package/kits/python/tests/support.py +28 -0
  141. package/kits/python/tests/test_client.py +275 -0
  142. package/kits/python/tests/test_compat.py +87 -0
  143. package/kits/python/tests/test_http.py +94 -0
  144. package/kits/python/tests/test_lang.py +104 -0
  145. package/kits/python/tests/test_models.py +110 -0
  146. package/kits/python/tests/test_multipart.py +37 -0
  147. package/kits/python/tests/test_pagination.py +70 -0
  148. package/kits/python/tests/test_sse.py +61 -0
  149. package/kits/python/tests/test_testing.py +130 -0
  150. package/kits/python/tests/test_transport.py +124 -0
  151. package/kits/python/tests/test_wait.py +46 -0
  152. package/kits/python/tests/test_webhooks.py +57 -0
  153. package/kits/python/versions.json +33 -0
  154. package/kits/rust/kit.json +6 -0
  155. package/kits/rust/src/runtime/client.rs +212 -0
  156. package/kits/rust/src/runtime/context.rs +182 -0
  157. package/kits/rust/src/runtime/crypto.rs +84 -0
  158. package/kits/rust/src/runtime/errors.rs +147 -0
  159. package/kits/rust/src/runtime/http.rs +248 -0
  160. package/kits/rust/src/runtime/json.rs +424 -0
  161. package/kits/rust/src/runtime/lang.rs +296 -0
  162. package/kits/rust/src/runtime/mod.rs +30 -0
  163. package/kits/rust/src/runtime/models.rs +266 -0
  164. package/kits/rust/src/runtime/multipart.rs +81 -0
  165. package/kits/rust/src/runtime/pagination.rs +117 -0
  166. package/kits/rust/src/runtime/sse.rs +195 -0
  167. package/kits/rust/src/runtime/testing.rs +308 -0
  168. package/kits/rust/src/runtime/transport.rs +324 -0
  169. package/kits/rust/src/runtime/wait.rs +29 -0
  170. package/kits/rust/src/runtime/webhooks.rs +142 -0
  171. package/kits/rust/tests/client.rs +152 -0
  172. package/kits/rust/tests/http.rs +44 -0
  173. package/kits/rust/tests/json.rs +82 -0
  174. package/kits/rust/tests/lang.rs +74 -0
  175. package/kits/rust/tests/multipart.rs +21 -0
  176. package/kits/rust/tests/pagination.rs +61 -0
  177. package/kits/rust/tests/sse.rs +77 -0
  178. package/kits/rust/tests/testing.rs +90 -0
  179. package/kits/rust/tests/transport.rs +218 -0
  180. package/kits/rust/tests/wait.rs +32 -0
  181. package/kits/rust/tests/webhooks.rs +73 -0
  182. package/kits/rust/versions.json +6 -0
  183. package/kits/typescript/kit.json +6 -0
  184. package/kits/typescript/src/client.ts +223 -0
  185. package/kits/typescript/src/context.ts +108 -0
  186. package/kits/typescript/src/errors.ts +63 -0
  187. package/kits/typescript/src/helpers.ts +49 -0
  188. package/kits/typescript/src/http.ts +192 -0
  189. package/kits/typescript/src/models.ts +139 -0
  190. package/kits/typescript/src/multipart.ts +66 -0
  191. package/kits/typescript/src/pagination.ts +54 -0
  192. package/kits/typescript/src/pipeline.ts +25 -0
  193. package/kits/typescript/src/sse.ts +102 -0
  194. package/kits/typescript/src/testing.ts +217 -0
  195. package/kits/typescript/src/transport.ts +101 -0
  196. package/kits/typescript/src/wait.ts +36 -0
  197. package/kits/typescript/src/webhooks.ts +168 -0
  198. package/kits/typescript/tests/client.test.ts +269 -0
  199. package/kits/typescript/tests/helpers.test.ts +27 -0
  200. package/kits/typescript/tests/http.test.ts +80 -0
  201. package/kits/typescript/tests/models.test.ts +71 -0
  202. package/kits/typescript/tests/multipart.test.ts +28 -0
  203. package/kits/typescript/tests/pagination.test.ts +76 -0
  204. package/kits/typescript/tests/sse.test.ts +82 -0
  205. package/kits/typescript/tests/testing.test.ts +103 -0
  206. package/kits/typescript/tests/transport.test.ts +127 -0
  207. package/kits/typescript/tests/wait.test.ts +31 -0
  208. package/kits/typescript/tests/webhooks.test.ts +53 -0
  209. package/kits/typescript/versions.json +15 -0
  210. package/package.json +37 -4
  211. package/packages/cli/recipes/apiKeyHeader.ts +16 -0
  212. package/packages/cli/recipes/apiVersionHeader.ts +16 -0
  213. package/packages/cli/recipes/basic.ts +13 -0
  214. package/packages/cli/recipes/bearer.ts +10 -0
  215. package/packages/cli/recipes/hmacSign.ts +23 -0
  216. package/packages/cli/recipes/idempotencyKey.ts +19 -0
  217. package/packages/cli/recipes/oauthClientCredentials.ts +50 -0
  218. package/packages/cli/recipes/retry.ts +42 -0
  219. package/packages/cli/recipes/timing.ts +12 -0
  220. package/packages/cli/recipes/userAgent.ts +8 -0
  221. package/packages/cli/src/build.js +93 -0
  222. package/packages/cli/src/commands/build.js +31 -0
  223. package/packages/cli/src/commands/conformance-check.js +50 -0
  224. package/packages/cli/src/commands/contract.js +181 -0
  225. package/packages/cli/src/commands/diff.js +113 -0
  226. package/packages/cli/src/commands/doctor.js +43 -0
  227. package/packages/cli/src/commands/import-openapi.js +42 -0
  228. package/packages/cli/src/commands/init.js +27 -0
  229. package/packages/cli/src/commands/kit-check.js +145 -0
  230. package/packages/cli/src/commands/publish.js +81 -0
  231. package/packages/cli/src/commands/recipe.js +49 -0
  232. package/packages/cli/src/commands/record.js +181 -0
  233. package/packages/cli/src/commands/serve.js +156 -0
  234. package/packages/cli/src/commands/spec-check.js +57 -0
  235. package/packages/cli/src/commands/test.js +177 -0
  236. package/packages/cli/src/commands/variants.js +32 -0
  237. package/packages/cli/src/commands/verify.js +57 -0
  238. package/packages/cli/src/commands/version.js +63 -0
  239. package/packages/cli/src/containers.js +82 -0
  240. package/packages/cli/src/coverage.js +72 -0
  241. package/packages/cli/src/git.js +25 -0
  242. package/packages/cli/src/io.js +50 -0
  243. package/packages/cli/src/java/ScenarioHarness.java +297 -0
  244. package/packages/cli/src/java/SchemaRoundTrip.java +63 -0
  245. package/packages/cli/src/java.js +70 -0
  246. package/packages/cli/src/js/harness.mjs +120 -0
  247. package/packages/cli/src/kits.js +103 -0
  248. package/packages/cli/src/languages/csharp.js +274 -0
  249. package/packages/cli/src/languages/go.js +185 -0
  250. package/packages/cli/src/languages/index.js +18 -0
  251. package/packages/cli/src/languages/java.js +187 -0
  252. package/packages/cli/src/languages/python.js +120 -0
  253. package/packages/cli/src/languages/rust.js +189 -0
  254. package/packages/cli/src/languages/types.js +93 -0
  255. package/packages/cli/src/languages/typescript.js +112 -0
  256. package/packages/cli/src/main.js +13 -0
  257. package/packages/cli/src/packaging.js +39 -0
  258. package/packages/cli/src/portability.js +45 -0
  259. package/packages/cli/src/profiles.js +55 -0
  260. package/packages/cli/src/project.js +56 -0
  261. package/packages/cli/src/python/scenario_harness.py +162 -0
  262. package/packages/cli/src/python/schema_roundtrip.py +42 -0
  263. package/packages/cli/src/registries.js +214 -0
  264. package/packages/cli/src/resolve-core.js +39 -0
  265. package/packages/cli/src/run.js +133 -0
  266. package/packages/cli/src/runtimes.js +61 -0
  267. package/packages/cli/src/scenarios-java.js +82 -0
  268. package/packages/cli/src/scenarios-javascript.js +54 -0
  269. package/packages/cli/src/scenarios-python.js +90 -0
  270. package/packages/cli/src/scenarios.js +183 -0
  271. package/packages/cli/src/schema.js +84 -0
  272. package/packages/cli/src/templates.js +85 -0
  273. package/packages/cli/src/toolchains.js +68 -0
  274. package/packages/cli/src/transpiled-tests.js +92 -0
  275. package/packages/codegen/src/canonical-json.js +31 -0
  276. package/packages/codegen/src/capabilities.js +50 -0
  277. package/packages/codegen/src/code-writer.js +54 -0
  278. package/packages/codegen/src/file-tree.js +25 -0
  279. package/packages/codegen/src/hash.js +6 -0
  280. package/packages/codegen/src/index.js +16 -0
  281. package/packages/codegen/src/lock.js +106 -0
  282. package/packages/conformance/src/case.js +143 -0
  283. package/packages/conformance/src/checks.js +40 -0
  284. package/packages/conformance/src/index.js +3 -0
  285. package/packages/conformance/src/matrix.js +48 -0
  286. package/packages/conformance/src/suite.js +48 -0
  287. package/packages/differ/src/diff.js +500 -0
  288. package/packages/differ/src/index.js +3 -0
  289. package/packages/differ/src/notes.js +112 -0
  290. package/packages/differ/src/support.js +34 -0
  291. package/packages/gen-csharp/src/emit-client.js +397 -0
  292. package/packages/gen-csharp/src/emit-harness.js +333 -0
  293. package/packages/gen-csharp/src/emit-mock.js +111 -0
  294. package/packages/gen-csharp/src/emit-models.js +119 -0
  295. package/packages/gen-csharp/src/emit-webhooks.js +57 -0
  296. package/packages/gen-csharp/src/generate.js +245 -0
  297. package/packages/gen-csharp/src/index.js +5 -0
  298. package/packages/gen-csharp/src/names.js +284 -0
  299. package/packages/gen-go/src/emit-client.js +405 -0
  300. package/packages/gen-go/src/emit-harness.js +294 -0
  301. package/packages/gen-go/src/emit-mock.js +112 -0
  302. package/packages/gen-go/src/emit-models.js +146 -0
  303. package/packages/gen-go/src/emit-webhooks.js +58 -0
  304. package/packages/gen-go/src/generate.js +205 -0
  305. package/packages/gen-go/src/index.js +5 -0
  306. package/packages/gen-go/src/names.js +197 -0
  307. package/packages/gen-java/src/emit-client.js +441 -0
  308. package/packages/gen-java/src/emit-models.js +342 -0
  309. package/packages/gen-java/src/emit-testing.js +123 -0
  310. package/packages/gen-java/src/emit-webhooks.js +70 -0
  311. package/packages/gen-java/src/generate.js +244 -0
  312. package/packages/gen-java/src/index.js +4 -0
  313. package/packages/gen-java/src/names.js +197 -0
  314. package/packages/gen-python/src/emit-client.js +272 -0
  315. package/packages/gen-python/src/emit-models.js +139 -0
  316. package/packages/gen-python/src/emit-testing.js +93 -0
  317. package/packages/gen-python/src/emit-webhooks.js +48 -0
  318. package/packages/gen-python/src/generate.js +237 -0
  319. package/packages/gen-python/src/index.js +2 -0
  320. package/packages/gen-python/src/names.js +161 -0
  321. package/packages/gen-python/src/style.js +67 -0
  322. package/packages/gen-rust/src/emit-client.js +379 -0
  323. package/packages/gen-rust/src/emit-harness.js +278 -0
  324. package/packages/gen-rust/src/emit-mock.js +121 -0
  325. package/packages/gen-rust/src/emit-models.js +117 -0
  326. package/packages/gen-rust/src/emit-webhooks.js +58 -0
  327. package/packages/gen-rust/src/generate.js +243 -0
  328. package/packages/gen-rust/src/index.js +5 -0
  329. package/packages/gen-rust/src/names.js +223 -0
  330. package/packages/gen-typescript/src/emit-client.js +434 -0
  331. package/packages/gen-typescript/src/emit-models.js +93 -0
  332. package/packages/gen-typescript/src/emit-package.js +90 -0
  333. package/packages/gen-typescript/src/emit-testing.js +138 -0
  334. package/packages/gen-typescript/src/emit-webhooks.js +52 -0
  335. package/packages/gen-typescript/src/generate.js +70 -0
  336. package/packages/gen-typescript/src/index.js +3 -0
  337. package/packages/gen-typescript/src/naming.js +64 -0
  338. package/packages/gen-typescript/src/runtime.js +81 -0
  339. package/packages/gen-typescript/src/types.js +136 -0
  340. package/packages/ir/src/api-surface.js +22 -0
  341. package/packages/ir/src/checks.js +52 -0
  342. package/packages/ir/src/index.js +32 -0
  343. package/packages/ir/src/ir.js +214 -0
  344. package/packages/ir/src/pages.js +18 -0
  345. package/packages/ir/src/validate-ir.js +462 -0
  346. package/packages/ir/src/validate-types.js +140 -0
  347. package/packages/kit/src/block-parser.js +196 -0
  348. package/packages/kit/src/index.js +15 -0
  349. package/packages/kit/src/kit-check.js +203 -0
  350. package/packages/kit/src/sources.js +53 -0
  351. package/packages/kit/src/version-policy.js +133 -0
  352. package/packages/kit/src/version-range.js +132 -0
  353. package/packages/openapi/src/import.js +292 -0
  354. package/packages/openapi/src/index.js +1 -0
  355. package/packages/openapi/src/names.js +50 -0
  356. package/packages/openapi/src/schemas.js +264 -0
  357. package/packages/packager/src/archive.js +106 -0
  358. package/packages/packager/src/crate.js +39 -0
  359. package/packages/packager/src/gomodule.js +11 -0
  360. package/packages/packager/src/index.js +9 -0
  361. package/packages/packager/src/maven.js +85 -0
  362. package/packages/packager/src/metadata.js +34 -0
  363. package/packages/packager/src/npm.js +71 -0
  364. package/packages/packager/src/nuget.js +78 -0
  365. package/packages/packager/src/sbom.js +56 -0
  366. package/packages/packager/src/wheel.js +62 -0
  367. package/packages/spec/src/index.js +11 -0
  368. package/packages/spec/src/requirements.js +139 -0
  369. package/packages/transpile/src/ast.js +51 -0
  370. package/packages/transpile/src/check.js +669 -0
  371. package/packages/transpile/src/emit-csharp.js +469 -0
  372. package/packages/transpile/src/emit-go.js +529 -0
  373. package/packages/transpile/src/emit-java.js +360 -0
  374. package/packages/transpile/src/emit-python.js +320 -0
  375. package/packages/transpile/src/emit-rust.js +499 -0
  376. package/packages/transpile/src/errors.js +15 -0
  377. package/packages/transpile/src/index.js +13 -0
  378. package/packages/transpile/src/lexer.js +161 -0
  379. package/packages/transpile/src/parser.js +543 -0
  380. package/packages/transpile/src/tests/ast.js +46 -0
  381. package/packages/transpile/src/tests/parse.js +376 -0
  382. package/packages/transpile/src/tests/translate.js +849 -0
  383. package/packages/transpile/src/transpile.js +57 -0
@@ -0,0 +1,333 @@
1
+ // The program `sdkloom test` runs against a generated C# SDK: it reads a plan on stdin and prints observations.
2
+ // Scenarios: a local TcpListener server answers as the scenario says and the program calls the operation with the
3
+ // scenario's arguments. Round-trips: every schema sample is decoded and encoded again.
4
+
5
+
6
+ import { pagedItems, } from "@sdkloom/ir";
7
+ import { configFields, kindOf, methodName, paramsType } from "./emit-client.ts";
8
+ import { webhookMethod, webhooksClass } from "./emit-webhooks.ts";
9
+ import { logicClass } from "./generate.ts";
10
+ import { csharp, decoder, encoder, pascal, pathParamName, str, typeName } from "./names.ts";
11
+
12
+ /** The item type of a paginated operation, or undefined. */
13
+ function itemsType(ir , operation ) {
14
+ return operation.paginate === undefined ? undefined : pagedItems(ir, operation).item;
15
+ }
16
+
17
+ function emitCall(writer , ir , operation ) {
18
+ writer.line(`case ${str(operation.name)}:`).line("{").indent((body) => {
19
+ const call = [];
20
+ operation.params
21
+ .filter((param) => param.in === "path")
22
+ .forEach((param) => {
23
+ body.line(`var ${pathParamName(param.name)} = Arg(args, ${str(param.name)}, ${decoder(ir, param.type, "args")});`);
24
+ call.push(pathParamName(param.name));
25
+ });
26
+ const kind = kindOf(operation.body);
27
+ if (kind === "json") {
28
+ body.line(`var body = Arg(args, "body", ${decoder(ir, operation.body , "args")});`);
29
+ call.push("body");
30
+ } else if (kind === "multipart") {
31
+ // A multipart body is described as parts; files are sent as UTF-8 bytes.
32
+ body.line("var body = new MultipartForm();");
33
+ body.line('foreach (var part in (args.Get("body")?.Get("parts") ?? Json.Array()).Items)').line("{").indent((loop) => {
34
+ loop.line('var name = part.Get("name")?.AsString() ?? "";');
35
+ loop.line('var value = part.Get("value")?.AsString() ?? "";');
36
+ loop.line('var filename = part.Get("filename")?.AsString();');
37
+ loop.line('body = filename == null ? body.Field(name, value) : body.File(name, filename, part.Get("contentType")?.AsString() ?? "application/octet-stream", System.Text.Encoding.UTF8.GetBytes(value));');
38
+ });
39
+ body.line("}");
40
+ call.push("body");
41
+ } else if (kind !== undefined) {
42
+ body.line('var body = Js.Utf8(Arg(args, "body", Decode.String));');
43
+ call.push("body");
44
+ }
45
+ const named = operation.params.filter((param) => param.in !== "path");
46
+ if (named.length > 0) {
47
+ body.line(`var parameters = new ${paramsType(operation)}();`);
48
+ named.forEach((param) => {
49
+ body.line(`if (args.Get(${str(param.name)}) != null)`).line("{").indent((branch) => branch.line(`parameters.${pascal(param.name)} = Arg(args, ${str(param.name)}, ${decoder(ir, param.type, "args")});`)).line("}");
50
+ });
51
+ call.push("parameters");
52
+ }
53
+ const items = itemsType(ir, operation);
54
+ if (items !== undefined) {
55
+ // all: the operation's iterator over every page.
56
+ body.line("if (all)").line("{").indent((branch) => {
57
+ branch.line("var items = new List<Json>();");
58
+ branch.line(`await foreach (var item in client.${pascal(operation.name)}AllAsync(${call.join(", ")}))`).line("{").indent((loop) => loop.line(`items.Add(${encoder(ir, items, "item")});`)).line("}");
59
+ branch.line("return Json.Array(items);");
60
+ });
61
+ body.line("}");
62
+ }
63
+ const invoke = `await client.${methodName(operation)}(${call.join(", ")})`;
64
+ if (operation.wait !== undefined) {
65
+ // wait: <Name>AndWaitAsync polls until the work is done.
66
+ body.line("if (wait)").line("{").indent((branch) => {
67
+ branch.line(`var finished = await client.${pascal(operation.name)}AndWaitAsync(${call.join(", ")});`);
68
+ branch.line(`return ${encoder(ir, operation.returns , "finished")};`);
69
+ });
70
+ body.line("}");
71
+ }
72
+ const result = kindOf(operation.returns);
73
+ if (operation.events !== undefined) {
74
+ // Server-sent events: every event the stream delivers, with its data as JSON.
75
+ body.line("var events = new List<Json>();");
76
+ body.line(`await foreach (var item in client.${methodName(operation)}(${call.join(", ")}))`).line("{").indent((loop) =>
77
+ loop.line(`events.Add(Json.Object(("event", Json.Str(item.Event)), ("id", Json.Str(item.Id)), ("data", ${encoder(ir, operation.events , "item.Data")})));`),
78
+ );
79
+ body.line("}");
80
+ body.line("return Json.Array(events);");
81
+ } else if (result === undefined) body.line(`${invoke};`).line("return Json.Null;");
82
+ else if (result !== "json") body.line(`return Json.Str(System.Text.Encoding.UTF8.GetString(${invoke}));`);
83
+ else body.line(`var result = ${invoke};`).line(`return ${encoder(ir, operation.returns , "result")};`);
84
+ });
85
+ writer.line("}");
86
+ }
87
+
88
+ const SERVER = `
89
+ /// <summary>Answers requests in order (the last answer repeats) and records every request.</summary>
90
+ private static (string Url, Func<IReadOnlyList<Json>> Received, Action Stop) Serve(Json answers)
91
+ {
92
+ var listener = new TcpListener(IPAddress.Loopback, 0);
93
+ listener.Start();
94
+ var url = "http://127.0.0.1:" + ((IPEndPoint)listener.LocalEndpoint).Port;
95
+ var gate = new object();
96
+ var received = new List<Json>();
97
+ var stop = new CancellationTokenSource();
98
+ _ = Task.Run(async () =>
99
+ {
100
+ while (!stop.IsCancellationRequested)
101
+ {
102
+ TcpClient client;
103
+ try
104
+ {
105
+ client = await listener.AcceptTcpClientAsync(stop.Token);
106
+ }
107
+ catch (Exception)
108
+ {
109
+ return;
110
+ }
111
+
112
+ using (client)
113
+ {
114
+ var stream = client.GetStream();
115
+ var head = new List<byte>();
116
+ while (head.Count < 4 || head[head.Count - 4] != 13 || head[head.Count - 3] != 10 || head[head.Count - 2] != 13 || head[head.Count - 1] != 10)
117
+ {
118
+ var next = stream.ReadByte();
119
+ if (next < 0)
120
+ {
121
+ break;
122
+ }
123
+
124
+ head.Add((byte)next);
125
+ }
126
+
127
+ var lines = Encoding.ASCII.GetString(head.ToArray()).Split("\\r\\n");
128
+ var start = lines[0].Split(' ');
129
+ var headers = new List<KeyValuePair<string, Json>>();
130
+ var length = 0;
131
+ foreach (var line in lines.Skip(1).Where(line => line.Length > 0))
132
+ {
133
+ var colon = line.IndexOf(':');
134
+ var name = line.Substring(0, colon).Trim().ToLowerInvariant();
135
+ var value = line.Substring(colon + 1).Trim();
136
+ if (name == "content-length")
137
+ {
138
+ length = int.Parse(value);
139
+ }
140
+
141
+ headers.Add(new KeyValuePair<string, Json>(name, value));
142
+ }
143
+
144
+ var body = new byte[length];
145
+ var read = 0;
146
+ while (read < length)
147
+ {
148
+ read += await stream.ReadAsync(body, read, length - read);
149
+ }
150
+
151
+ lock (gate)
152
+ {
153
+ received.Add(Json.Object(("method", start[0]), ("url", start.Length > 1 ? start[1] : ""), ("headers", Json.Object(headers)), ("body", Encoding.UTF8.GetString(body))));
154
+ }
155
+
156
+ Json respond;
157
+ lock (gate)
158
+ {
159
+ respond = answers.Items[Math.Min(received.Count - 1, answers.Items.Count - 1)];
160
+ }
161
+
162
+ var status = respond.Get("status")?.AsLong() ?? 200;
163
+ var payload = respond.Get("text")?.AsString() ?? respond.Get("json")?.ToJsonString() ?? "";
164
+ var bytes = Encoding.UTF8.GetBytes(payload);
165
+ var text = new StringBuilder("HTTP/1.1 " + status + " X\\r\\ncontent-length: " + bytes.Length + "\\r\\nconnection: close\\r\\n");
166
+ if (respond.Get("json") != null)
167
+ {
168
+ text.Append("content-type: application/json\\r\\n");
169
+ }
170
+
171
+ foreach (var extra in (respond.Get("headers") ?? Json.Object()).Fields)
172
+ {
173
+ text.Append(extra.Key + ": " + extra.Value.AsString() + "\\r\\n");
174
+ }
175
+
176
+ text.Append("\\r\\n");
177
+ var answer = Encoding.ASCII.GetBytes(text.ToString()).Concat(bytes).ToArray();
178
+ await stream.WriteAsync(answer, 0, answer.Length);
179
+ }
180
+ }
181
+ });
182
+ return (url, () => { lock (gate) { return received.ToArray(); } }, () => { stop.Cancel(); listener.Stop(); });
183
+ }
184
+ `;
185
+
186
+ export function emitHarness(ir , namespace ) {
187
+ const writer = csharp().line("// Generated by sdkloom for `sdkloom test`; not part of the SDK.").line("#pragma warning disable CS0618").line();
188
+ ["System", "System.Collections.Generic", "System.Linq", "System.Net", "System.Net.Sockets", "System.Text", "System.Threading", "System.Threading.Tasks", namespace, `${namespace}.Runtime`].forEach((name) =>
189
+ writer.line(`using ${name};`),
190
+ );
191
+ writer.line().line("namespace SdkloomHarness").line("{").indent((ns) => {
192
+ ns.line("public static class Program").line("{").indent((body) => {
193
+ SERVER.trim()
194
+ .split("\n")
195
+ .forEach((line) => body.line(line));
196
+ body.line();
197
+ body.line("private static T Arg<T>(Json args, string name, Func<Json, string, T> decode)").line("{").indent((fn) => {
198
+ fn.line("try").line("{").indent((inner) => inner.line('return decode(args.Get(name) ?? Json.Null, "$.args." + name);')).line("}");
199
+ fn.line("catch (DecodeException error)").line("{").indent((inner) => inner.line('throw new SdkException("HarnessError: " + error.Message);')).line("}");
200
+ });
201
+ body.line("}").line();
202
+
203
+ body.line("private static Options Configure(Json config)").line("{").indent((fn) => {
204
+ fn.line("var options = new Options();");
205
+ configFields(ir).forEach((item) => {
206
+ fn.line(`if (config.Get(${str(item.name)}) != null)`).line("{").indent((branch) => branch.line(`options.${pascal(item.name)} = Arg(config, ${str(item.name)}, ${decoder(ir, item.type, "config")});`)).line("}");
207
+ });
208
+ if (ir.apiVersions !== undefined) fn.line('options.ApiVersion = config.Get("apiVersion")?.AsString() ?? options.ApiVersion;');
209
+ fn.line("return options;");
210
+ });
211
+ body.line("}").line();
212
+
213
+ body.line("private static async Task<Json> Invoke(Client client, string op, Json args, bool all, bool wait)").line("{").indent((fn) => {
214
+ fn.line("switch (op)").line("{").indent((arms) => {
215
+ ir.operations.forEach((operation) => emitCall(arms, ir, operation));
216
+ arms.line("default:").indent((arm) => arm.line('throw new SdkException("UnknownOperation: " + op);'));
217
+ });
218
+ fn.line("}");
219
+ });
220
+ body.line("}").line();
221
+
222
+ body.line("private static Json RoundTrip(string name, Json value)").line("{").indent((fn) => {
223
+ fn.line("switch (name)").line("{").indent((arms) => {
224
+ ir.types.forEach((named) => {
225
+ if (named.type.kind === "object") arms.line(`case ${str(named.name)}:`).indent((arm) => arm.line(`return ${typeName(named.name)}.FromJson(value, "$").ToJson();`));
226
+ if (named.type.kind === "union") arms.line(`case ${str(named.name)}:`).indent((arm) => arm.line(`return ${typeName(named.name)}.ToJson(${typeName(named.name)}.FromJson(value, "$"));`));
227
+ });
228
+ arms.line("default:").indent((arm) => arm.line('throw new SdkException("MissingDecoder: " + name);'));
229
+ });
230
+ fn.line("}");
231
+ });
232
+ body.line("}").line();
233
+
234
+ // A webhook case: verify and read the body with the SDK's <Name>Webhooks.Verify<Hook>.
235
+ body.line("private static Json Webhook(Json hook)").line("{").indent((fn) => {
236
+ fn.line("var headers = new List<KeyValuePair<string, string>>();");
237
+ fn.line('foreach (var entry in (hook.Get("headers") ?? Json.Object()).Fields)').line("{").indent((loop) => loop.line('headers.Add(new KeyValuePair<string, string>(entry.Key, entry.Value.AsString() ?? ""));')).line("}");
238
+ fn.line('var body = System.Text.Encoding.UTF8.GetBytes(hook.Get("body")?.AsString() ?? "");');
239
+ fn.line('var secret = hook.Get("secret")?.AsString() ?? "";');
240
+ fn.line('var now = hook.Get("now")?.AsLong() ?? 0;');
241
+ fn.line('switch (hook.Get("name")?.AsString())').line("{").indent((arms) => {
242
+ (ir.webhooks ?? []).forEach((hook) => arms.line(`case ${str(hook.name)}:`).indent((arm) => arm.line(`return ${encoder(ir, hook.payload, `${webhooksClass(ir)}.${webhookMethod(hook.name)}(body, headers, secret, now)`)};`)));
243
+ arms.line("default:").indent((arm) => arm.line('throw new SdkException("UnknownWebhook: " + hook.Get("name")?.AsString());'));
244
+ });
245
+ fn.line("}");
246
+ });
247
+ body.line("}").line();
248
+
249
+ // A logic case: call <Name>Logic.<Name> with its inputs, read from JSON.
250
+ body.line("private static Json Logic(Json call)").line("{").indent((fn) => {
251
+ fn.line('var args = call.Get("args") ?? Json.Object();');
252
+ const read = {
253
+ int: (name) => `args.Get(${str(name)})?.AsLong() ?? 0`,
254
+ number: (name) => `args.Get(${str(name)})?.AsDouble() ?? 0`,
255
+ bool: (name) => `args.Get(${str(name)})?.AsBool() ?? false`,
256
+ string: (name) => `args.Get(${str(name)})?.AsString() ?? ""`,
257
+ };
258
+ const wrap = { int: "Json.Int", number: "Json.Float", bool: "Json.Bool", string: "Json.Str" };
259
+ fn.line('switch (call.Get("name")?.AsString())').line("{").indent((arms) => {
260
+ (ir.logic ?? []).forEach((logic) => {
261
+ const args = logic.input.map((field) => (read[field.type.kind === "primitive" ? field.type.name : "string"] ?? read["string"] ?? String)(field.name));
262
+ const result = logic.returns.kind === "primitive" ? logic.returns.name : "string";
263
+ arms.line(`case ${str(logic.name)}:`).indent((arm) => arm.line(`return ${wrap[result] ?? "Json.Str"}(${logicClass(ir)}.${pascal(logic.name)}(${args.join(", ")}));`));
264
+ });
265
+ arms.line("default:").indent((arm) => arm.line('throw new SdkException("UnknownLogic: " + call.Get("name")?.AsString());'));
266
+ });
267
+ fn.line("}");
268
+ });
269
+ body.line("}").line();
270
+
271
+ body.line("private static Json Failure(Exception error)").line("{").indent((fn) => {
272
+ fn.line('var name = error.Message.StartsWith("HarnessError", StringComparison.Ordinal) ? "HarnessError" : error is SdkException known ? known.Name : error.GetType().Name;');
273
+ fn.line('return Json.Object(("ok", false), ("error", name), ("message", error.Message));');
274
+ });
275
+ body.line("}").line();
276
+
277
+ body.line("private static async Task<Json> Scenario(Json plan)").line("{").indent((fn) => {
278
+ fn.line('var hook = plan.Get("webhook");');
279
+ fn.line("if (hook != null)").line("{").indent((branch) => {
280
+ branch.line("Json result;");
281
+ branch.line("try").line("{").indent((inner) => inner.line('result = Json.Object(("ok", true), ("value", Webhook(hook)));')).line("}");
282
+ branch.line("catch (Exception error)").line("{").indent((inner) => inner.line("result = Failure(error);")).line("}");
283
+ branch.line('return Json.Object(("id", plan.Get("id") ?? Json.Null), ("outcome", result));');
284
+ });
285
+ fn.line("}");
286
+ // A logic function fails only by throwing: reported as Error, as in every language.
287
+ fn.line('var logic = plan.Get("logic");');
288
+ fn.line("if (logic != null)").line("{").indent((branch) => {
289
+ branch.line("Json result;");
290
+ branch.line("try").line("{").indent((inner) => inner.line('result = Json.Object(("ok", true), ("value", Logic(logic)));')).line("}");
291
+ branch.line("catch (Exception error)").line("{").indent((inner) => inner.line('result = Json.Object(("ok", false), ("error", Json.Str("Error")), ("message", Json.Str(error.Message)));')).line("}");
292
+ branch.line('return Json.Object(("id", plan.Get("id") ?? Json.Null), ("outcome", result));');
293
+ });
294
+ fn.line("}");
295
+ fn.line('var (url, received, stop) = Serve(plan.Get("answers") ?? Json.Array(Json.Object()));');
296
+ fn.line("Json outcome;");
297
+ fn.line("try").line("{").indent((inner) => {
298
+ inner.line('var options = Configure(plan.Get("config") ?? Json.Object());');
299
+ inner.line("options.BaseUrl = url;").line("options.TimeoutMs = 5000;");
300
+ inner.line('var value = await Invoke(new Client(options), plan.Get("op")?.AsString() ?? "", plan.Get("args") ?? Json.Object(), plan.Get("all")?.AsBool() == true, plan.Get("wait")?.AsBool() == true);');
301
+ inner.line('outcome = Json.Object(("ok", true), ("value", value));');
302
+ });
303
+ fn.line("}").line("catch (Exception error)").line("{").indent((inner) => inner.line("outcome = Failure(error);")).line("}");
304
+ fn.line("stop();");
305
+ fn.line('var observation = Json.Object(("id", plan.Get("id") ?? Json.Null), ("outcome", outcome));');
306
+ fn.line("var seen = received();");
307
+ fn.line('return seen.Count == 0 ? observation : observation.With("received", seen[0]).With("requests", Json.Array(seen));');
308
+ });
309
+ body.line("}").line();
310
+
311
+ body.line("public static async Task Main()").line("{").indent((fn) => {
312
+ fn.line("var plan = Json.Parse(Console.In.ReadToEnd());");
313
+ fn.line('var roundtrip = plan.Get("mode")?.AsString() == "roundtrip";');
314
+ fn.line("var results = new List<Json>();");
315
+ fn.line('foreach (var item in (plan.Get("cases") ?? Json.Array()).Items)').line("{").indent((loop) => {
316
+ loop.line("if (roundtrip)").line("{").indent((branch) => {
317
+ branch.line("Json outcome;");
318
+ branch.line("try").line("{").indent((inner) => inner.line('outcome = Json.Object(("ok", true), ("value", RoundTrip(item.Get("type")?.AsString() ?? "", item.Get("value") ?? Json.Null)));')).line("}");
319
+ branch.line("catch (Exception error)").line("{").indent((inner) => inner.line("outcome = Failure(error);")).line("}");
320
+ branch.line('results.Add(Json.Object(("id", item.Get("id") ?? Json.Null), ("outcome", outcome)));');
321
+ });
322
+ loop.line("}").line("else").line("{").indent((branch) => branch.line("results.Add(await Scenario(item));")).line("}");
323
+ });
324
+ fn.line("}");
325
+ fn.line("Console.Out.Write(Json.Array(results).ToJsonString());");
326
+ });
327
+ body.line("}");
328
+ });
329
+ ns.line("}");
330
+ });
331
+ writer.line("}");
332
+ return writer.toString();
333
+ }
@@ -0,0 +1,111 @@
1
+ // Testing.cs (namespace <Ns>.Testing): MockClient.Create() gives a client answered by typed mocks, a fake clock and
2
+ // recorded events; Examples gives small valid values. Generated types are named with global:: so a mock or an example
3
+ // named like a model never hides it.
4
+
5
+
6
+ import { configFields, kindOf, resultType, textEvents } from "./emit-client.ts";
7
+ import { propertyName } from "./emit-models.ts";
8
+ import { csharp, csType, decoder, doc, encoder, example, pascal, qualifier, str, typeName, unionInterface } from "./names.ts";
9
+
10
+ const MOCK_BASE_URL = "http://mock.sdkloom.invalid";
11
+ const OPTION_NAMES = ["Server", "BaseUrl", "Transport", "TimeoutMs", "Middleware", "OnEvent", "Clock"];
12
+
13
+ function placeholder(type ) {
14
+ if (type.kind === "enum") return str(type.values[0] ?? "");
15
+ if (type.kind === "primitive" && ["string", "secret", "datetime"].includes(type.name)) return '"test"';
16
+ return undefined;
17
+ }
18
+
19
+ /** Members of Mock besides the operation mocks. */
20
+ const MOCK_MEMBERS = ["Transport", "Clock", "Events", "Record"];
21
+
22
+ export function emitMock(ir , header , namespace ) {
23
+ ir.operations.forEach((operation) => {
24
+ if (MOCK_MEMBERS.includes(pascal(operation.name))) throw new Error(`operation ${operation.name} would clash with Mock.${pascal(operation.name)} in the C# test helpers; rename the operation`);
25
+ });
26
+ const q = qualifier(ir, namespace);
27
+ const writer = csharp().line(header).line("#pragma warning disable CS0618 // mocks cover deprecated operations too").line();
28
+ ["System", "System.Collections.Generic", `${namespace}.Runtime`].forEach((name) => writer.line(`using ${name};`));
29
+ writer.line().line(`namespace ${namespace}.Testing`).line("{").indent((ns) => {
30
+ doc(ns, ["One typed mock per operation, plus the transport, the fake clock and the events middleware emitted."]);
31
+ ns.line("public sealed class Mock").line("{").indent((body) => {
32
+ body.line("private readonly object _gate = new object();").line("private readonly List<RecordedEvent> _events = new List<RecordedEvent>();").line();
33
+ body.line("internal Mock(MockTransport transport, FakeClock clock)").line("{").indent((fn) => {
34
+ fn.line("Transport = transport;").line("Clock = clock;");
35
+ ir.operations.forEach((operation) => {
36
+ if (operation.events !== undefined) {
37
+ // Emits() takes the events; their data is checked and written as JSON, or as text for a string stream.
38
+ const data = q(csType(ir, operation.events));
39
+ const text = textEvents(operation.events);
40
+ const decode = text ? "null" : q(decoder(ir, operation.events, `operations.${operation.name}.events`));
41
+ const encode = text ? "value => Json.Str(value)" : `value => ${q(encoder(ir, operation.events, "value"))}`;
42
+ fn.line(`${pascal(operation.name)} = new OperationMock<${data}>(${str(operation.name)}, transport.Route(${str(operation.method)}, ${str(operation.path)}), ${decode}, ${encode});`);
43
+ return;
44
+ }
45
+ const type = q(resultType(ir, operation) ?? "object?");
46
+ const json = kindOf(operation.returns) === "json";
47
+ const decode = json ? q(decoder(ir, operation.returns , `operations.${operation.name}.returns`)) : "null";
48
+ const encode = json ? `value => ${q(encoder(ir, operation.returns , "value"))}` : "null";
49
+ fn.line(`${pascal(operation.name)} = new OperationMock<${type}>(${str(operation.name)}, transport.Route(${str(operation.method)}, ${str(operation.path)}), ${decode}, ${encode});`);
50
+ });
51
+ });
52
+ body.line("}").line();
53
+ body.line("public MockTransport Transport { get; }").line().line("public FakeClock Clock { get; }").line();
54
+ ir.operations.forEach((operation) => {
55
+ const type = operation.events === undefined ? resultType(ir, operation) ?? "object?" : csType(ir, operation.events);
56
+ body.line(`public OperationMock<${q(type)}> ${pascal(operation.name)} { get; }`).line();
57
+ });
58
+ doc(body, ["The events middleware emitted, in order."]);
59
+ body.line("public IReadOnlyList<RecordedEvent> Events()").line("{").indent((fn) => fn.line("lock (_gate)").line("{").indent((inner) => inner.line("return _events.ToArray();")).line("}")).line("}").line();
60
+ body.line("internal void Record(string name, Json fields)").line("{").indent((fn) => fn.line("lock (_gate)").line("{").indent((inner) => inner.line("_events.Add(new RecordedEvent(name, fields));")).line("}")).line("}");
61
+ });
62
+ ns.line("}").line();
63
+
64
+ doc(ns, ["Builds clients for tests."]);
65
+ ns.line("public static class MockClient").line("{").indent((body) => {
66
+ doc(body, ["A Client whose calls the returned Mock answers; middleware still runs. Required options left empty get placeholders; the given options are not changed."]);
67
+ body.line(`public static (${q("Client")} Client, Mock Mock) Create(${q("Options")}? options = null)`).line("{").indent((fn) => {
68
+ fn.line(`var settings = options ?? new ${q("Options")}();`);
69
+ fn.line("var transport = new MockTransport();").line("var clock = new FakeClock();").line("var mock = new Mock(transport, clock);");
70
+ fn.line("var user = settings.OnEvent;");
71
+ fn.line(`var copy = new ${q("Options")}`).line("{").indent((fields) => {
72
+ configFields(ir).forEach((item) => {
73
+ const name = pascal(item.name);
74
+ const value = placeholder(item.type);
75
+ fields.line(`${name} = ${!item.optional && value !== undefined ? `settings.${name}.Length == 0 ? ${value} : settings.${name}` : `settings.${name}`},`);
76
+ });
77
+ OPTION_NAMES.filter((name) => !["BaseUrl", "Transport", "Clock", "OnEvent"].includes(name)).forEach((name) => fields.line(`${name} = settings.${name},`));
78
+ fields.line(`BaseUrl = ${str(MOCK_BASE_URL)},`).line("Transport = transport,").line("Clock = clock,");
79
+ fields.line("OnEvent = (name, fields) =>").line("{").indent((fn2) => fn2.line("mock.Record(name, fields);").line("user?.Invoke(name, fields);")).line("},");
80
+ });
81
+ fn.line("};");
82
+ fn.line(`return (new ${q("Client")}(copy), mock);`);
83
+ });
84
+ body.line("}");
85
+ });
86
+ ns.line("}").line();
87
+
88
+ doc(ns, ["Small, valid example values; change the fields a test cares about."]);
89
+ ns.line("public static class Examples").line("{").indent((body) => {
90
+ [...ir.types].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)).forEach((named, index) => {
91
+ if (index > 0) body.line();
92
+ if (named.type.kind === "object") {
93
+ const node = named.type;
94
+ const required = node.fields.filter((item) => !item.optional && !item.nullable);
95
+ body.line(`public static ${q(typeName(named.name))} ${typeName(named.name)}() => new ${q(typeName(named.name))}`).line("{").indent((fields) => {
96
+ required.forEach((item) => fields.line(`${propertyName(named.name, item.name)} = ${example(ir, item.type, `types.${named.name}.${item.name}`, q)},`));
97
+ });
98
+ body.line("};");
99
+ } else if (named.type.kind === "union") {
100
+ const first = named.type.variants[0];
101
+ if (first === undefined) throw new Error(`types.${named.name}: a union needs a variant`);
102
+ doc(body, [`The first variant, a ${typeName(first.type)}.`]);
103
+ body.line(`public static ${q(unionInterface(named.name))} ${typeName(named.name)}() => ${typeName(first.type)}();`);
104
+ }
105
+ });
106
+ });
107
+ ns.line("}");
108
+ });
109
+ writer.line("}");
110
+ return writer.toString().replace(/\n\n(\s*)}\n/g, "\n$1}\n");
111
+ }
@@ -0,0 +1,119 @@
1
+ // Models.cs: a class per model with extra fields, FromJson and ToJson; per union an interface its variants implement, an
2
+ // Unknown class and a static class that reads and writes it by its tag.
3
+
4
+
5
+
6
+ import { csharp, doc, fieldDecoder, fieldEncoder, fieldType, initializer, pascal, qualifier, str, typeName, unionInterface } from "./names.ts";
7
+
8
+ /** Members every model has; a field with one of these names would clash. */
9
+ const RESERVED = new Set(["ExtraFields", "FromJson", "ToJson", "GetType", "GetHashCode", "Equals", "ToString", "MemberwiseClone"]);
10
+
11
+ function deprecation(item ) {
12
+ return item.deprecated === undefined ? [] : [`[Obsolete(${str(item.deprecated)})]`];
13
+ }
14
+
15
+ /** Types the model's own code names in expressions; a property with one of these names would hide it. */
16
+ const EXPRESSION_TYPES = new Set(["Json", "Decode", "Encode", "Array", "Dictionary", "Js", "Math"]);
17
+
18
+ /**
19
+ * A property name: PascalCase; one equal to its class's name (C# forbids that) or to a type the class's code uses gets
20
+ * "Value", e.g. a field "json" becomes JsonValue.
21
+ */
22
+ export function propertyName(model , field ) {
23
+ const name = pascal(field);
24
+ return name === typeName(model) || EXPRESSION_TYPES.has(name) ? `${name}Value` : name;
25
+ }
26
+
27
+ /** The unions a model is a variant of. */
28
+ function unionsOf(ir , model ) {
29
+ return ir.types.filter((named) => named.type.kind === "union" && named.type.variants.some((variant) => variant.type === model)).map((named) => named.name);
30
+ }
31
+
32
+ function emitObject(writer , ir , named , node , q ) {
33
+ const name = typeName(named.name);
34
+ node.fields.forEach((item) => {
35
+ if (RESERVED.has(propertyName(named.name, item.name))) throw new Error(`types.${named.name}.${item.name}: the C# name ${pascal(item.name)} is reserved; rename the field`);
36
+ });
37
+ doc(writer, [named.doc ?? name, "", "Fields the server adds later are kept in ExtraFields and sent back unchanged."]);
38
+ deprecation(named).forEach((line) => writer.line(line));
39
+ const implemented = ["IToJson", ...unionsOf(ir, named.name).map(unionInterface)];
40
+ writer.line(`public sealed class ${name} : ${implemented.join(", ")}`).line("{").indent((body) => {
41
+ node.fields.forEach((item) => {
42
+ doc(body, item.doc === undefined ? [] : [item.doc]);
43
+ deprecation(item).forEach((line) => body.line(line));
44
+ body.line(`public ${fieldType(ir, item)} ${propertyName(named.name, item.name)} { get; set; }${initializer(ir, item)}`).line();
45
+ });
46
+ doc(body, ["Fields this SDK version does not know."]);
47
+ body.line("public IReadOnlyList<KeyValuePair<string, Json>> ExtraFields { get; set; } = Array.Empty<KeyValuePair<string, Json>>();").line();
48
+ doc(body, [`Reads a ${name} from JSON; path names it in errors, e.g. "$".`]);
49
+ body.line(`public static ${name} FromJson(Json json, string path)`).line("{").indent((fn) => {
50
+ fn.line("Decode.Object(json, path);");
51
+ fn.line(`return new ${name}`).line("{").indent((fields) => {
52
+ node.fields.forEach((item) => fields.line(`${propertyName(named.name, item.name)} = ${q(fieldDecoder(ir, item, `${named.name}.${item.name}`))},`));
53
+ fields.line(`ExtraFields = Decode.Extra(json${node.fields.map((item) => `, ${str(item.name)}`).join("")}),`);
54
+ });
55
+ fn.line("};");
56
+ });
57
+ body.line("}").line();
58
+ doc(body, ["The JSON form; absent optional fields are left out."]);
59
+ // Properties may be named like a model or union, so generated types are named with global:: in expressions.
60
+ const fields = node.fields.map((item) => `(${str(item.name)}, ${q(fieldEncoder(ir, item, "\u0000")).replaceAll("\u0000", propertyName(named.name, item.name))})`);
61
+ body.line(`public Json ToJson() => Encode.Object(ExtraFields${fields.map((field) => `, ${field}`).join("")});`);
62
+ });
63
+ writer.line("}").line();
64
+ }
65
+
66
+ function emitUnion(writer , named , node ) {
67
+ const name = typeName(named.name);
68
+ const marker = unionInterface(named.name);
69
+ const unknown = `Unknown${name}`;
70
+ doc(writer, [named.doc ?? name, "", `One of: ${node.variants.map((variant) => typeName(variant.type)).join(", ")}, or ${unknown} for a variant this SDK version does not know. Match with a switch that has a default case: later versions may add variants.`]);
71
+ deprecation(named).forEach((line) => writer.line(line));
72
+ writer.line(`public interface ${marker}`).line("{").line("}").line();
73
+
74
+ doc(writer, [`A ${name} variant this SDK version does not know, kept as it came.`]);
75
+ writer.line(`public sealed class ${unknown} : ${marker}`).line("{").indent((body) => {
76
+ body.line(`public ${unknown}(string tag, Json raw)`).line("{").indent((fn) => fn.line("Tag = tag;").line("Raw = raw;")).line("}").line();
77
+ doc(body, [`The ${str(node.discriminator)} value.`]);
78
+ body.line("public string Tag { get; }").line();
79
+ body.line("public Json Raw { get; }");
80
+ });
81
+ writer.line("}").line();
82
+
83
+ doc(writer, [`Reads and writes ${marker} values by their ${str(node.discriminator)} tag.`]);
84
+ writer.line(`public static class ${name}`).line("{").indent((body) => {
85
+ body.line(`public static ${marker} FromJson(Json json, string path)`).line("{").indent((fn) => {
86
+ fn.line("Decode.Object(json, path);");
87
+ fn.line(`var tag = Decode.String(json.Get(${str(node.discriminator)}) ?? Json.Null, path + ${str(`.${node.discriminator}`)});`);
88
+ fn.line("switch (tag)").line("{").indent((arms) => {
89
+ node.variants.forEach((variant) => arms.line(`case ${str(variant.tag)}:`).indent((arm) => arm.line(`return ${typeName(variant.type)}.FromJson(json, path);`)));
90
+ arms.line("default:").indent((arm) => arm.line(`return new ${unknown}(tag, json);`));
91
+ });
92
+ fn.line("}");
93
+ });
94
+ body.line("}").line();
95
+ doc(body, [`The JSON form, with the ${str(node.discriminator)} tag.`]);
96
+ body.line(`public static Json ToJson(${marker} value)`).line("{").indent((fn) => {
97
+ fn.line("switch (value)").line("{").indent((arms) => {
98
+ node.variants.forEach((variant) => arms.line(`case ${typeName(variant.type)} variant:`).indent((arm) => arm.line(`return variant.ToJson().With(${str(node.discriminator)}, ${str(variant.tag)});`)));
99
+ arms.line(`case ${unknown} other:`).indent((arm) => arm.line("return other.Raw;"));
100
+ arms.line("default:").indent((arm) => arm.line(`throw new ArgumentException("not a ${name} variant: " + value, nameof(value));`));
101
+ });
102
+ fn.line("}");
103
+ });
104
+ body.line("}");
105
+ });
106
+ writer.line("}").line();
107
+ }
108
+
109
+ export function emitModels(ir , header , namespace ) {
110
+ const writer = csharp().line(header).line("#pragma warning disable CS0618 // models refer to their own deprecated members").line();
111
+ writer.line("using System;").line("using System.Collections.Generic;").line(`using ${namespace}.Runtime;`).line();
112
+ writer.line(`namespace ${namespace}`).line("{").indent((body) => {
113
+ const q = qualifier(ir, namespace);
114
+ ir.types.filter((named) => named.type.kind === "object").forEach((named) => emitObject(body, ir, named, named.type , q));
115
+ ir.types.filter((named) => named.type.kind === "union").forEach((named) => emitUnion(body, named, named.type ));
116
+ });
117
+ writer.line("}");
118
+ return writer.toString().replace(/\n\n(\s*)}\n/g, "\n$1}\n");
119
+ }
@@ -0,0 +1,57 @@
1
+ // <Name>Webhooks.cs: Verify<Name> per webhook, which checks the signature (kit block webhooks.verify) and decodes the
2
+ // body into the payload type.
3
+
4
+
5
+ import { csharp, csType, decode, doc, pascal, qualifier, str, typeName } from "./names.ts";
6
+
7
+ export function webhooksClass(ir ) {
8
+ return `${typeName(ir.name)}Webhooks`;
9
+ }
10
+
11
+ export function webhookMethod(name ) {
12
+ return `Verify${pascal(name)}`;
13
+ }
14
+
15
+ function signature(hook ) {
16
+ const spec = hook.signature;
17
+ const text = (value ) => (value === undefined ? "null" : str(value));
18
+ return `new WebhookSignature(${[
19
+ str(spec.header), str(spec.encoding), text(spec.prefix), text(spec.separator), str(spec.signed),
20
+ text(spec.timestamp?.header), `${String(spec.timestamp?.toleranceSeconds ?? 0)}L`, str(spec.secret), text(spec.secretPrefix),
21
+ ].join(", ")})`;
22
+ }
23
+
24
+ export function emitWebhooks(ir , header , namespace ) {
25
+ const name = webhooksClass(ir);
26
+ if (ir.types.some((named) => typeName(named.name) === name)) throw new Error(`type ${name} collides with the generated webhooks class; rename the model`);
27
+ const q = qualifier(ir, namespace);
28
+ const writer = csharp().line(header).line();
29
+ writer.line("using System;").line("using System.Collections.Generic;").line("using System.Text;").line(`using ${namespace}.Runtime;`).line();
30
+ writer.line(`namespace ${namespace}`).line("{").indent((body) => {
31
+ doc(body, [`Verifies the webhooks ${ir.name} sends and reads their bodies.`]);
32
+ body.line(`public static class ${name}`).line("{").indent((members) => {
33
+ for (const hook of ir.webhooks ?? []) members.line(`private static readonly WebhookSignature ${pascal(hook.name)}Signature = ${signature(hook)};`).line();
34
+ for (const hook of ir.webhooks ?? []) {
35
+ const type = q(csType(ir, hook.payload));
36
+ doc(members, [
37
+ ...(hook.doc === undefined ? [] : [hook.doc, ""]),
38
+ `Verifies a ${hook.name} webhook and reads its body. Pass the raw body, exactly as received, and the request headers`,
39
+ "(names in any case); nowSeconds defaults to the current Unix time.",
40
+ "Throws WebhookSignatureException when the signature does not match the secret or the webhook is too old or too new,",
41
+ "and DecodeException when the body does not match the payload type.",
42
+ ]);
43
+ members.line(`public static ${type} ${webhookMethod(hook.name)}(byte[] body, IEnumerable<KeyValuePair<string, string>> headers, string secret, long? nowSeconds = null)`).line("{").indent((fn) => {
44
+ fn.line(`Webhooks.Verify(${pascal(hook.name)}Signature, body, headers, secret, nowSeconds ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds());`);
45
+ fn.line("Json value;");
46
+ fn.line("try").line("{").indent((block) => block.line("value = Json.Parse(new UTF8Encoding(false, true).GetString(body));")).line("}");
47
+ fn.line("catch (Exception error) when (error is SdkException || error is ArgumentException)").line("{").indent((block) => block.line('throw new DecodeException("$", error.Message);')).line("}");
48
+ fn.line(`return ${q(decode(ir, hook.payload, `webhooks.${hook.name}.payload`, "value", '"$"'))};`);
49
+ });
50
+ members.line("}").line();
51
+ }
52
+ });
53
+ body.line("}");
54
+ });
55
+ writer.line("}");
56
+ return writer.toString().replace(/\n\n(\s*)}\n/g, "\n$1}\n");
57
+ }