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,272 @@
1
+ // <module>/client.py: the client class, its raw variant and one OperationSpec per operation.
2
+
3
+
4
+ import { pagedItems, } from "@sdkloom/ir";
5
+ import { errorClass, python } from "./emit-models.ts";
6
+ import { pythonName } from "@sdkloom/transpile";
7
+ import { decoder, docstring, encoder, pyType, snake, str } from "./names.ts";
8
+ import { classLine, def, PY3, preamble, typingImport, } from "./style.ts";
9
+
10
+ export function clientName(ir ) {
11
+ return `${ir.name}Client`;
12
+ }
13
+
14
+ const CLIENT_OPTIONS = ["server", "base_url", "transport", "timeout_ms", "middleware", "on_event", "clock", "proxy", "ssl_context"];
15
+
16
+ export function configFields(ir ) {
17
+ const fields = new Map ();
18
+ for (const middleware of ir.middlewares) {
19
+ for (const item of middleware.config) {
20
+ if (CLIENT_OPTIONS.includes(snake(item.name))) throw new Error(`config field ${item.name} of middleware ${middleware.name} collides with a client option`);
21
+ if (!fields.has(item.name)) fields.set(item.name, item);
22
+ }
23
+ }
24
+ return [...fields.values()];
25
+ }
26
+
27
+ function kind(node ) {
28
+ if (node === undefined) return undefined;
29
+ return node.kind === "primitive" && (node.name === "bytes" || node.name === "stream" || node.name === "multipart") ? node.name : "json";
30
+ }
31
+
32
+ export function resultType(node ) {
33
+ const k = kind(node);
34
+ if (k === undefined) return "None";
35
+ if (k === "bytes") return "bytes";
36
+ if (k === "stream") return "Iterator[bytes]";
37
+ return pyType(node );
38
+ }
39
+
40
+ function bodyType(node ) {
41
+ return kind(node) === "stream" ? "Union[bytes, Iterable[bytes]]" : pyType(node);
42
+ }
43
+
44
+ /** The body as the runtime sends it: unions get their tag, bytes and streams pass through. */
45
+ function bodyValue(ir , operation ) {
46
+ if (operation.body === undefined || kind(operation.body) !== "json") return "body";
47
+ const encoded = encoder(ir, operation.body, "body");
48
+ return encoded === "body" ? "body" : `None if body is None else ${encoded}`;
49
+ }
50
+
51
+ /** Path parameters and the body are positional; everything else is keyword-only (by convention on Python 2.7). */
52
+ function parameters(ir , operation ) {
53
+ const path = operation.params.filter((param) => param.in === "path");
54
+ const named = operation.params.filter((param) => param.in !== "path");
55
+ const positional = [...path.map((param) => [snake(param.name), pyType(param.type)]), ...(operation.body === undefined ? [] : [["body", bodyType(operation.body)] ])];
56
+ const keywords = [
57
+ ...named.map((param) => (param.optional ? [snake(param.name), pyType(param.type), "UNSET"] : [snake(param.name), pyType(param.type)])),
58
+ ["options", "Optional[CallOptions]", "None"],
59
+ ];
60
+ const all = [...operation.params.map((param) => `${str(param.name)}: ${snake(param.name)}`), ...(operation.body === undefined ? [] : [`"body": ${bodyValue(ir, operation)}`])];
61
+ const call = [...path.map((param) => snake(param.name)), ...(operation.body === undefined ? [] : ["body"]), ...named.map((param) => `${snake(param.name)}=${snake(param.name)}`), "options=options"];
62
+ return { params: [["self"], ...positional, "*", ...keywords], args: `{${all.join(", ")}}`, call: call.join(", ") };
63
+ }
64
+
65
+ function specName(operation ) {
66
+ return `_${snake(operation.name).toUpperCase()}`;
67
+ }
68
+
69
+ /** An event stream whose data stays text: no decoder, the data is a str. */
70
+ export function textEvents(node ) {
71
+ return node.kind === "primitive" && node.name === "string";
72
+ }
73
+
74
+ function emitSpec(writer , ir , operation ) {
75
+ const result = operation.events === undefined ? kind(operation.returns) : "events";
76
+ writer.line(`${specName(operation)} = OperationSpec(`).indent((body) => {
77
+ body.line(`name=${str(operation.name)},`);
78
+ body.line(`method=${str(operation.method)},`);
79
+ body.line(`path=${str(operation.path)},`);
80
+ body.line(`params=(${operation.params.map((param) => `ParamSpec(${str(param.name)}, ${str(param.in)}), `).join("")}),`);
81
+ if (operation.body !== undefined) body.line(`body=${str(kind(operation.body) ?? "json")},`);
82
+ if (result !== undefined) body.line(`result=${str(result)},`);
83
+ if (result === "json" && operation.returns !== undefined) body.line(`decode=${decoder(ir, operation.returns, `operations.${operation.name}.returns`)},`);
84
+ if (operation.events !== undefined && !textEvents(operation.events)) body.line(`decode_event=${decoder(ir, operation.events, `operations.${operation.name}.events`)},`);
85
+ body.line("errors={").indent((errors) =>
86
+ operation.errors.forEach((error) => errors.line(`${error.status}: lambda status, body, response: ${errorClass(error.name)}(status, body, response, ${str(error.name)}),`)),
87
+ );
88
+ body.line("},");
89
+ body.line(`use=(${operation.use.map((name) => `${str(name)}, `).join("")}),`);
90
+ if (operation.since !== undefined) body.line(`since=${str(operation.since)},`);
91
+ });
92
+ writer.line(")").line();
93
+ }
94
+
95
+ function operationDoc(operation ) {
96
+ return [
97
+ operation.doc ?? operation.name,
98
+ "",
99
+ `HTTP: ${operation.method} ${operation.path}`,
100
+ ...(operation.events === undefined ? [] : [`Server-sent events, read as they arrive; each data is ${pyType(operation.events)}. The request is sent when iteration starts.`]),
101
+ ...(operation.since === undefined ? [] : [`Since API version ${operation.since}.`]),
102
+ ...(operation.stability === "stable" ? [] : [`Stability: ${operation.stability}`]),
103
+ ...operation.errors.map((error) => `Raises ${errorClass(error.name)} for HTTP ${error.status}.`),
104
+ "Raises ApiError for any other non-2xx response.",
105
+ ...(operation.deprecated === undefined ? [] : [`Deprecated: ${operation.deprecated}`]),
106
+ ];
107
+ }
108
+
109
+ function configValue(ir , name ) {
110
+ const middleware = ir.middlewares.find((candidate) => candidate.name === name);
111
+ if (middleware === undefined) throw new Error(`unknown middleware ${name}`);
112
+ return `entry(${str(name)}, _middleware.${pythonName(name)}, {${middleware.config.map((item) => `${str(snake(item.name))}: ${snake(item.name)}`).join(", ")}})`;
113
+ }
114
+
115
+ function emitClass(writer , ir , sdk , style ) {
116
+ const opLevel = [...new Set(ir.operations.flatMap((operation) => operation.use))].sort();
117
+ writer.line(classLine(style, "_Raw")).indent((body) => {
118
+ docstring(body, ["The same operations, returning RawResult(data, response) so the HTTP status and headers are available."]);
119
+ body.line(def(style, "__init__", [["self"], ["runtime", "ClientRuntime"]], "None")).indent((fn) => fn.line("self._runtime = runtime"));
120
+ ir.operations.forEach((operation) => {
121
+ const { params, args } = parameters(ir, operation);
122
+ body.line().line(def(style, snake(operation.name), params, "RawResult")).indent((fn) => fn.line(`return call_operation(self._runtime, ${specName(operation)}, ${args}, options)`));
123
+ });
124
+ });
125
+ writer.line().line();
126
+
127
+ const config = configFields(ir);
128
+ const settings = [
129
+ ["self"],
130
+ "*",
131
+ ...config.map((item) => (item.optional ? [snake(item.name), pyType(item.type), "None"] : [snake(item.name), pyType(item.type)])),
132
+ ["server", "str", "DEFAULT_SERVER"],
133
+ ["base_url", "Optional[str]", "None"],
134
+ ["transport", "Optional[Transport]", "None"],
135
+ ["timeout_ms", "int", "DEFAULT_TIMEOUT_MS"],
136
+ ["middleware", "Sequence[MiddlewareEntry]", "()"],
137
+ ["on_event", "Optional[EventListener]", "None"],
138
+ ["clock", "Any", "None"],
139
+ ["proxy", "Optional[str]", "None"],
140
+ ["ssl_context", "Optional[_ssl.SSLContext]", "None"],
141
+ ...(ir.apiVersions === undefined ? [] : [["api_version", "Optional[str]", "None"] ]),
142
+ ];
143
+ writer.line(classLine(style, clientName(ir))).indent((body) => {
144
+ docstring(body, [ir.doc ?? ir.name, "", "Thread-safe: one client can be shared between threads."]);
145
+ body.line(def(style, "__init__", settings, "None")).indent((fn) => {
146
+ fn.line("clock = clock or SystemClock()");
147
+ fn.line("runtime = ClientRuntime(").indent((args) => {
148
+ args.line("base_url=base_url or SERVERS[server],");
149
+ args.line("transport=transport or UrllibTransport(proxy=proxy, ssl_context=ssl_context),");
150
+ args.line("clock=clock,");
151
+ args.line("state=State(clock),");
152
+ args.line(`middleware=(${ir.use.map((name) => `${configValue(ir, name)}, `).join("")}),`);
153
+ args.line(`registry={${opLevel.map((name) => `${str(name)}: ${configValue(ir, name)}`).join(", ")}},`);
154
+ args.line("user_middleware=tuple(middleware),");
155
+ args.line("listeners=(on_event,) if on_event else (),");
156
+ args.line("timeout_ms=timeout_ms,");
157
+ args.line(`sdk=SdkInfo(${str(sdk.name)}, ${str(sdk.version)}, "python"),`);
158
+ const versions = ir.apiVersions;
159
+ if (versions !== undefined) args.line(`api_version=ApiVersion(${str(versions.header)}, api_version or ${str(versions.values.at(-1) ?? "")}, (${versions.values.map((value) => `${str(value)}, `).join("")})),`);
160
+ });
161
+ fn.line(")");
162
+ fn.line("self.raw = _Raw(runtime)");
163
+ fn.line("self._clock = clock");
164
+ });
165
+ ir.operations.forEach((operation) => {
166
+ const { params, call } = parameters(ir, operation);
167
+ const returns = operation.events === undefined ? resultType(operation.returns) : "Iterator[ServerSentEvent]";
168
+ body.line().line(def(style, snake(operation.name), params, returns)).indent((fn) => {
169
+ docstring(fn, operationDoc(operation));
170
+ if (operation.deprecated !== undefined) fn.line(`warnings.warn(${str(`${snake(operation.name)} is deprecated: ${operation.deprecated}`)}, DeprecationWarning, stacklevel=2)`);
171
+ if (operation.events === undefined) fn.line(`return self.raw.${snake(operation.name)}(${call}).data`);
172
+ else fn.line(`for event in self.raw.${snake(operation.name)}(${call}).data:`).indent((loop) => loop.line("yield event"));
173
+ });
174
+ if (operation.paginate !== undefined) emitIterator(body, ir, operation, operation.paginate, style);
175
+ if (operation.wait !== undefined) emitWait(body, ir, operation, operation.wait, style);
176
+ });
177
+ });
178
+ }
179
+
180
+ /** <name>_all: every item of every page, fetched as the caller iterates (kit block pagination.iterate). */
181
+ /** <name>_and_wait: starts the work, then polls until it is done (kit block lro.wait). */
182
+ function emitWait(writer , ir , operation , wait , style ) {
183
+ const { params, call } = parameters(ir, operation);
184
+ const name = snake(operation.name);
185
+ writer.line().line(def(style, `${name}_and_wait`, params, resultType(operation.returns))).indent((fn) => {
186
+ docstring(fn, [
187
+ `${name}, then ${snake(wait.poll)} every ${wait.intervalMs} ms until ${snake(wait.field)} is ${wait.done.join(" or ")}; the finished result.`,
188
+ "",
189
+ `Raises WaitTimeoutError when the work is not done within ${wait.timeoutMs} ms.`,
190
+ ]);
191
+ fn.line(`first = self.${name}(${call})`);
192
+ fn.line(`done = (${wait.done.map((value) => `${str(value)}, `).join("")})`);
193
+ fn.line(`return wait_until(first, lambda current: self.${snake(wait.poll)}(current.${snake(wait.from)}, options=options), lambda current: current.${snake(wait.field)} in done, self._clock, ${wait.intervalMs}, ${wait.timeoutMs})`);
194
+ });
195
+ }
196
+
197
+ function emitIterator(writer , ir , operation , paginate , style ) {
198
+ const { item, field } = pagedItems(ir, operation);
199
+ const { params } = parameters(ir, operation);
200
+ const names = [...operation.params.map((param) => snake(param.name)), ...(operation.body === undefined ? [] : ["body"]), "options"];
201
+ const name = snake(operation.name);
202
+ const absent = (value ) => `${value} is UNSET or ${value} is None`;
203
+ writer.line().line(def(style, `${name}_all`, params, `Iterator[${pyType(item)}]`)).indent((fn) => {
204
+ docstring(fn, [`Every item of every ${name} page, fetched as you iterate: \`for item in client.${name}_all(...)\`.`]);
205
+ fn.line(`first = {${names.map((entry) => `${str(entry)}: ${entry}`).join(", ")}}`);
206
+ if (paginate.kind === "link") {
207
+ // The Link header names the next page: the same operation is called with that URL.
208
+ fn.line().line("def fetch(state):").indent((inner) => {
209
+ inner.line('settings = first["options"] or CallOptions()');
210
+ inner.line(`return self.raw.${name}(**dict(first, options=settings if state.get("url") is None else replace(settings, url=state["url"])))`);
211
+ });
212
+ fn.line().line("def next_params(state, page, items):").indent((inner) => {
213
+ inner.line('url = next_link(page.response.header("link"))');
214
+ inner.line('return None if url is None else {"url": url}');
215
+ });
216
+ fn.line().line(`return paginate({}, fetch, lambda page: ${field === undefined ? "page.data" : `page.data.${snake(field)}`}, next_params)`);
217
+ return;
218
+ }
219
+ fn.line().line("def next_params(params, page, items):").indent((inner) => {
220
+ const param = str(snake(paginate.param));
221
+ if (paginate.kind === "cursor") {
222
+ inner.line(`cursor = page.${snake(paginate.next)}`);
223
+ inner.line(`if ${absent("cursor")} or cursor == "":`).indent((branch) => branch.line("return None"));
224
+ inner.line(`return dict(params, **{${param}: cursor})`);
225
+ } else {
226
+ const limit = paginate.limit === undefined ? undefined : `params[${str(snake(paginate.limit))}]`;
227
+ const short = limit === undefined ? "" : ` or (not (${absent(limit)}) and len(items) < ${limit})`;
228
+ inner.line(`if not items${short}:`).indent((branch) => branch.line("return None"));
229
+ inner.line(`offset = 0 if ${absent(`params[${param}]`)} else params[${param}]`);
230
+ inner.line(`return dict(params, **{${param}: offset + len(items)})`);
231
+ }
232
+ });
233
+ fn.line();
234
+ fn.line(`return paginate(first, lambda params: self.${name}(**params), lambda page: page.${snake(field ?? "")}, next_params)`);
235
+ });
236
+ }
237
+
238
+ /** Client and mock attributes besides the operations; an operation with one of these names would shadow them. */
239
+ const TAKEN = ["raw", "transport", "clock", "events"];
240
+
241
+ export function emitClient(ir , header , sdk , style = PY3) {
242
+ ir.operations.forEach((operation) => {
243
+ if (TAKEN.includes(snake(operation.name))) throw new Error(`operation ${operation.name} would shadow the ${snake(operation.name)} attribute of the client or its mock; rename the operation`);
244
+ });
245
+ const body = python();
246
+ body.line("SERVERS = {").indent((servers) => ir.servers.forEach((server) => servers.line(`${str(server.name)}: ${str(server.url)},`)));
247
+ body.line("}").line(`DEFAULT_SERVER = ${str(ir.defaultServer)}`).line("DEFAULT_TIMEOUT_MS = 60000").line();
248
+ ir.operations.forEach((operation) => emitSpec(body, ir, operation));
249
+ body.line();
250
+ emitClass(body, ir, sdk, style);
251
+ const text = body.toString();
252
+
253
+ const errors = [...new Set(ir.operations.flatMap((operation) => operation.errors.map((error) => errorClass(error.name))))].sort();
254
+ const writer = preamble(python().line(header), style);
255
+ writer.line("import ssl as _ssl").line("import warnings # noqa: F401");
256
+ writer.line("from decimal import Decimal # noqa: F401");
257
+ typingImport(writer, style, "Any, Dict, Iterable, Iterator, List, Optional, Sequence, Union").line();
258
+ writer.line("from . import middleware as _middleware # noqa: F401");
259
+ writer.line("from ._runtime.client import ApiVersion, CallOptions, ClientRuntime, MiddlewareEntry, OperationSpec, ParamSpec, RawResult, call_operation, entry # noqa: F401");
260
+ writer.line("from ._runtime.context import EventListener, SdkInfo, State, SystemClock");
261
+ writer.line("from ._runtime.models import UNSET, as_boolean, as_decimal, as_enum, as_integer, as_list, as_map, as_number, as_string # noqa: F401");
262
+ writer.line("from ._runtime.compat import replace # noqa: F401");
263
+ writer.line("from ._runtime.pagination import next_link, paginate # noqa: F401");
264
+ writer.line("from ._runtime.sse import ServerSentEvent # noqa: F401");
265
+ writer.line("from ._runtime.wait import WaitTimeoutError, wait_until # noqa: F401");
266
+ writer.line("from ._runtime.multipart import MultipartForm # noqa: F401");
267
+ writer.line("from ._runtime.transport import Transport, UrllibTransport");
268
+ if (errors.length > 0) writer.line(`from .errors import ${errors.join(", ")}`);
269
+ writer.line("from .models import * # noqa: F401,F403").line().line();
270
+ text.split("\n").forEach((line) => writer.line(line));
271
+ return writer.toString();
272
+ }
@@ -0,0 +1,139 @@
1
+ // <module>/models.py and <module>/errors.py.
2
+
3
+ import { createCodeWriter, } from "@sdkloom/codegen";
4
+
5
+ import { decoder, docstring, encoder, pyType, snake, str } from "./names.ts";
6
+ import { assign, classLine, def, PY3, preamble, typingImport, } from "./style.ts";
7
+
8
+ const HELPERS = ["UNSET", "as_boolean", "as_decimal", "as_enum", "as_integer", "as_list", "as_map", "as_number", "as_object", "as_string", "field", "ordered_dict", "with_tag"];
9
+
10
+ export const python = () => createCodeWriter({ indent: " " });
11
+
12
+ const RESERVED = new Set(["extra_fields", "to_json", "from_json"]);
13
+
14
+ /** The class line and fields: a frozen dataclass on Python 3, a Record (the kit's dataclass stand-in) on 2.7. */
15
+ function emitFields(body , style , ordered ) {
16
+ if (style.py27) {
17
+ body.line(`_fields = (${[...ordered.map((item) => str(snake(item.name))), str("extra_fields")].join(", ")},)`);
18
+ body.line(`_defaults = {${[...ordered.filter((item) => item.optional).map((item) => `${str(snake(item.name))}: UNSET`), `${str("extra_fields")}: factory(dict)`].join(", ")}}`);
19
+ body.line(`_hidden = (${str("extra_fields")},)`).line();
20
+ return;
21
+ }
22
+ ordered.forEach((item) => {
23
+ const type = `${pyType(item.type)}${item.nullable ? " | None" : ""}`;
24
+ body.line(`${snake(item.name)}: "${type}"${item.optional ? " = UNSET" : ""}`);
25
+ });
26
+ body.line("extra_fields: Dict[str, Any] = _field(default_factory=dict, repr=False, compare=False)").line();
27
+ }
28
+
29
+ function emitObject(writer , ir , named , node , style ) {
30
+ node.fields.forEach((item) => {
31
+ if (RESERVED.has(snake(item.name))) throw new Error(`types.${named.name}.${item.name}: the Python name ${snake(item.name)} is reserved for model methods; rename the field`);
32
+ });
33
+ const ordered = [...node.fields.filter((item) => !item.optional), ...node.fields.filter((item) => item.optional)];
34
+ const keys = `_${snake(named.name).toUpperCase()}_KEYS`;
35
+ if (!style.py27) writer.line("@dataclass(frozen=True)");
36
+ writer.line(classLine(style, named.name, style.py27 ? "Record" : undefined)).indent((body) => {
37
+ docstring(body, [named.doc ?? named.name, ...(named.deprecated === undefined ? [] : ["", `Deprecated: ${named.deprecated}`])]);
38
+ emitFields(body, style, ordered);
39
+
40
+ body.line("@classmethod").line(def(style, "from_json", [["cls"], ["value", "Any"], ["path", "str", '"$"']], `"${named.name}"`)).indent((fn) => {
41
+ fn.line("obj = as_object(value, path)");
42
+ fn.line("return cls(").indent((args) => {
43
+ node.fields.forEach((item) =>
44
+ args.line(`${snake(item.name)}=field(obj, ${str(item.name)}, path, ${decoder(ir, item.type, `types.${named.name}.${item.name}`)}, optional=${item.optional ? "True" : "False"}, nullable=${item.nullable ? "True" : "False"}),`),
45
+ );
46
+ args.line(
47
+ style.py27
48
+ ? `extra_fields=ordered_dict((key, item) for key, item in obj.items() if key not in ${keys}),`
49
+ : `extra_fields={key: item for key, item in obj.items() if key not in ${keys}},`,
50
+ );
51
+ });
52
+ fn.line(")");
53
+ });
54
+ body.line();
55
+ body.line(def(style, "to_json", [["self"]], "Dict[str, Any]")).indent((fn) => {
56
+ fn.line(assign(style, "data", "Dict[str, Any]", style.py27 ? "ordered_dict(self.extra_fields)" : "dict(self.extra_fields)"));
57
+ node.fields.forEach((item) => {
58
+ const field = `self.${snake(item.name)}`;
59
+ const encoded = encoder(ir, item.type, field);
60
+ const value = encoded === field ? field : `None if ${field} is None else ${encoded}`;
61
+ if (item.optional) fn.line(`if self.${snake(item.name)} is not UNSET:`).indent((branch) => branch.line(`data[${str(item.name)}] = ${value}`));
62
+ else fn.line(`data[${str(item.name)}] = ${value}`);
63
+ });
64
+ fn.line("return data");
65
+ });
66
+ });
67
+ writer.line().line().line(`${keys} = frozenset([${node.fields.map((item) => str(item.name)).join(", ")}])`).line().line();
68
+ }
69
+
70
+ function emitUnion(writer , named , node , style ) {
71
+ const unknown = `Unknown${named.name}`;
72
+ const fn = snake(named.name);
73
+ if (!style.py27) writer.line("@dataclass(frozen=True)");
74
+ writer.line(classLine(style, unknown, style.py27 ? "Record" : undefined)).indent((body) => {
75
+ docstring(body, [`A ${named.name} variant this SDK version does not know yet; raw keeps the data.`]);
76
+ if (style.py27) body.line(`_fields = (${str("tag")}, ${str("raw")})`).line();
77
+ else body.line("tag: str").line("raw: Dict[str, Any]").line();
78
+ body.line(def(style, "to_json", [["self"]], "Dict[str, Any]")).indent((method) => method.line(style.py27 ? "return ordered_dict(self.raw)" : "return dict(self.raw)"));
79
+ });
80
+ writer.line().line();
81
+ // Python 2.7 has no typing.Union; the tuple of classes still works with isinstance().
82
+ writer.line(
83
+ style.py27
84
+ ? `${named.name} = (${[...node.variants.map((variant) => variant.type), unknown].join(", ")})`
85
+ : `${named.name} = Union[${[...node.variants.map((variant) => str(variant.type)), unknown].join(", ")}]`,
86
+ );
87
+ if (named.doc !== undefined) writer.line(`"""${named.doc}"""`);
88
+ writer.line().line();
89
+ writer.line(def(style, `decode_${fn}`, [["value", "Any"], ["path", "str", '"$"']], "Any")).indent((body) => {
90
+ body.line("obj = as_object(value, path)");
91
+ body.line(`tag = as_string(obj.get(${str(node.discriminator)}), path + ${str(`.${node.discriminator}`)})`);
92
+ node.variants.forEach((variant) => body.line(`if tag == ${str(variant.tag)}:`).indent((branch) => branch.line(`return ${variant.type}.from_json(obj, path)`)));
93
+ body.line(`return ${unknown}(tag, obj)`);
94
+ });
95
+ writer.line().line();
96
+ writer.line(def(style, `encode_${fn}`, [["value", "Any"]], "Dict[str, Any]")).indent((body) => {
97
+ docstring(body, [`The JSON form of a ${named.name}, including its "${node.discriminator}" tag; raw JSON passes through.`]);
98
+ body.line("if isinstance(value, dict):").indent((branch) => branch.line("return value"));
99
+ node.variants.forEach((variant) =>
100
+ body.line(`if isinstance(value, ${variant.type}):`).indent((branch) => branch.line(`return with_tag(value.to_json(), ${str(node.discriminator)}, ${str(variant.tag)})`)),
101
+ );
102
+ body.line("return value.to_json()");
103
+ });
104
+ writer.line().line();
105
+ }
106
+
107
+ export function emitModels(ir , header , style = PY3) {
108
+ const body = python();
109
+ ir.types.filter((named) => named.type.kind === "object").forEach((named) => emitObject(body, ir, named, named.type , style));
110
+ ir.types.filter((named) => named.type.kind === "union").forEach((named) => emitUnion(body, named, named.type , style));
111
+ const text = body.toString();
112
+ const used = HELPERS.filter((name) => new RegExp(`\\b${name}\\b`).test(text));
113
+ const writer = preamble(python().line(header), style);
114
+ if (!style.py27) writer.line("from dataclasses import dataclass, field as _field");
115
+ writer.line("from decimal import Decimal # noqa: F401");
116
+ typingImport(writer, style, "Any, Dict, Iterable, List, Union").line();
117
+ if (style.py27) writer.line("from ._runtime.compat import Record, factory");
118
+ if (used.length > 0) writer.line(`from ._runtime.models import ${used.join(", ")}`);
119
+ writer.line().line();
120
+ text.split("\n").forEach((line) => writer.line(line));
121
+ return writer.toString();
122
+ }
123
+
124
+ export function errorClass(name ) {
125
+ return name.endsWith("Error") ? name : `${name}Error`;
126
+ }
127
+
128
+ export function emitErrors(ir , header , style = PY3) {
129
+ const statuses = new Map ();
130
+ ir.operations.forEach((operation) => operation.errors.forEach((error) => statuses.set(error.name, [...(statuses.get(error.name) ?? []), error.status])));
131
+ const writer = preamble(python().line(header), style, false).line("from ._runtime.errors import ApiError # noqa: F401").line().line();
132
+ [...statuses.entries()]
133
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
134
+ .forEach(([name, codes]) => {
135
+ writer.line(`class ${errorClass(name)}(ApiError):`).indent((body) => docstring(body, [`Raised for HTTP ${[...new Set(codes)].sort().join(", ")} (${name}).`]));
136
+ writer.line().line();
137
+ });
138
+ return writer.toString();
139
+ }
@@ -0,0 +1,93 @@
1
+ // <module>/testing.py: mock_client() and deterministic examples.
2
+
3
+
4
+ import { clientName, configFields, textEvents } from "./emit-client.ts";
5
+ import { python } from "./emit-models.ts";
6
+ import { decoder, docstring, encoder, example, snake, str } from "./names.ts";
7
+ import { assign, classLine, def, PY3, preamble, typingImport, } from "./style.ts";
8
+
9
+ const MOCK_BASE_URL = "http://mock.sdkloom.invalid";
10
+
11
+ function placeholder(item ) {
12
+ const type = item.type;
13
+ if (type.kind === "enum") return str(type.values[0] ?? "");
14
+ if (type.kind === "primitive" && (type.name === "int" || type.name === "number")) return "0";
15
+ if (type.kind === "primitive" && type.name === "bool") return "False";
16
+ if (type.kind === "primitive" && ["string", "secret", "decimal", "datetime"].includes(type.name)) return str("test");
17
+ throw new Error(`config field ${item.name}: mock_client() cannot invent a value`);
18
+ }
19
+
20
+ export function emitTesting(ir , header , style = PY3) {
21
+ const client = clientName(ir);
22
+ const writer = preamble(python().line(header), style);
23
+ if (!style.py27) writer.line("from dataclasses import replace");
24
+ writer.line("from decimal import Decimal # noqa: F401");
25
+ typingImport(writer, style, "Any, List, Tuple").line();
26
+ if (style.py27) writer.line("from ._runtime.compat import replace");
27
+ writer.line("from ._runtime.models import as_boolean, as_decimal, as_enum, as_integer, as_list, as_map, as_number, as_string # noqa: F401");
28
+ writer.line("from ._runtime.testing import FakeClock, MockTransport, OperationMock");
29
+ writer.line(`from .client import ${client}`);
30
+ writer.line("from .models import * # noqa: F401,F403").line().line();
31
+ writer.line(`_MOCK_BASE_URL = ${str(MOCK_BASE_URL)}`).line().line();
32
+
33
+ writer.line(classLine(style, `${ir.name}Mock`)).indent((body) => {
34
+ docstring(body, ["One OperationMock per operation, plus the transport, the fake clock and recorded events."]);
35
+ body.line(def(style, "__init__", [["self"], ["transport", "MockTransport"], ["clock", "FakeClock"], ["events", "List[Tuple[str, Any]]"]], "None")).indent((fn) => {
36
+ fn.line("self.transport = transport").line("self.clock = clock").line("self.events = events");
37
+ ir.operations.forEach((operation) => {
38
+ if (operation.events !== undefined) {
39
+ const typed = !textEvents(operation.events);
40
+ const check = typed ? decoder(ir, operation.events, `operations.${operation.name}.events`) : "None";
41
+ const encoded = typed ? encoder(ir, operation.events, "value") : "value";
42
+ const encodeEvent = encoded === "value" ? "None" : `lambda value: ${encoded}`;
43
+ fn.line(`self.${snake(operation.name)} = OperationMock(${str(operation.name)}, transport.route(${str(operation.method)}, ${str(operation.path)}), ${check}, ${encodeEvent}, events=True)`);
44
+ return;
45
+ }
46
+ const decode = operation.returns !== undefined && !(operation.returns.kind === "primitive" && ["bytes", "stream"].includes(operation.returns.name))
47
+ ? `, ${decoder(ir, operation.returns, `operations.${operation.name}.returns`)}`
48
+ : "";
49
+ const encoded = operation.returns === undefined || decode === "" ? "value" : encoder(ir, operation.returns, "value");
50
+ const encode = encoded === "value" ? "" : `, lambda value: ${encoded}`;
51
+ fn.line(`self.${snake(operation.name)} = OperationMock(${str(operation.name)}, transport.route(${str(operation.method)}, ${str(operation.path)})${decode}${encode})`);
52
+ });
53
+ });
54
+ });
55
+ writer.line().line();
56
+
57
+ writer.line(def(style, "mock_client", [["**options", "Any"]], `Tuple[${client}, ${ir.name}Mock]`)).indent((fn) => {
58
+ docstring(fn, [`A ${client} answered by typed mocks: middleware still runs, the clock is fake and events are recorded.`]);
59
+ fn.line("transport = MockTransport()").line("clock = FakeClock()").line(assign(style, "events", "List[Tuple[str, Any]]", "[]"));
60
+ fn.line('user_listener = options.pop("on_event", None)').line();
61
+ fn.line(def(style, "listener", [["name", "str"], ["fields", "Any"]], "None")).indent((inner) => {
62
+ inner.line("events.append((name, fields))");
63
+ inner.line("if user_listener is not None:").indent((branch) => branch.line("user_listener(name, fields)"));
64
+ });
65
+ fn.line();
66
+ fn.line(assign(style, "settings", "Any", `{${configFields(ir).filter((item) => !item.optional).map((item) => `${str(snake(item.name))}: ${placeholder(item)}`).join(", ")}}`));
67
+ fn.line("settings.update(options)");
68
+ // Named arguments before **settings: Python 2.7 allows nothing after **.
69
+ fn.line(`client = ${client}(base_url=_MOCK_BASE_URL, transport=transport.send, clock=clock, on_event=listener, **settings)`);
70
+ fn.line(`return client, ${ir.name}Mock(transport, clock, events)`);
71
+ });
72
+ writer.line().line();
73
+
74
+ writer.line(classLine(style, "_Examples")).indent((body) => {
75
+ docstring(body, ["Small, valid example values; pass overrides for the fields a test cares about."]);
76
+ ir.types.forEach((named) => {
77
+ const type = named.type;
78
+ body.line();
79
+ if (type.kind === "object") {
80
+ const required = type.fields
81
+ .filter((item) => !item.optional)
82
+ .map((item) => `${snake(item.name)}=${item.nullable ? "None" : example(item.type, `types.${named.name}.${item.name}`)}`);
83
+ body.line(def(style, named.name, [["self"], ["**overrides", "Any"]], "Any")).indent((fn) => fn.line(`return replace(${named.name}(${required.join(", ")}), **overrides)`));
84
+ } else if (type.kind === "union") {
85
+ const first = type.variants[0];
86
+ if (first === undefined) throw new Error(`types.${named.name}: a union needs a variant`);
87
+ body.line(def(style, named.name, [["self"]], "Any")).indent((fn) => fn.line(`return self.${first.type}()`));
88
+ }
89
+ });
90
+ });
91
+ writer.line().line().line("examples = _Examples()");
92
+ return writer.toString();
93
+ }
@@ -0,0 +1,48 @@
1
+ // <module>/webhooks.py: verify_<name>_webhook per webhook, which checks the signature (kit block webhooks.verify) and
2
+ // decodes the body into the payload type.
3
+
4
+
5
+ import { python } from "./emit-models.ts";
6
+ import { decoder, docstring, pyType, snake, str } from "./names.ts";
7
+ import { def, preamble, typingImport, } from "./style.ts";
8
+
9
+ export function webhookFunction(hook ) {
10
+ return `verify_${snake(hook.name)}_webhook`;
11
+ }
12
+
13
+ /** The signature as a Python dict literal (only strings, integers and nested dicts). */
14
+ function literal(value ) {
15
+ if (typeof value === "string") return str(value);
16
+ if (typeof value === "number") return String(value);
17
+ const entries = Object.entries(value ).map(([key, item]) => `${str(key)}: ${literal(item)}`);
18
+ return `{${entries.join(", ")}}`;
19
+ }
20
+
21
+ export function emitWebhooks(ir , header , style ) {
22
+ const writer = preamble(python().line(header), style);
23
+ writer.line("import time");
24
+ typingImport(writer, style, "Any, Optional, Union").line();
25
+ writer.line("from ._runtime.compat import json_loads");
26
+ writer.line("from ._runtime.models import as_boolean, as_decimal, as_enum, as_integer, as_list, as_map, as_number, as_string # noqa: F401");
27
+ writer.line("from ._runtime.webhooks import WebhookSignatureError, verify_webhook # noqa: F401");
28
+ writer.line("from .models import * # noqa: F401,F403").line();
29
+ for (const hook of ir.webhooks ?? []) {
30
+ const { kind: _kind, algorithm: _algorithm, ...signature } = hook.signature;
31
+ const constant = `_${snake(hook.name).toUpperCase()}_SIGNATURE`;
32
+ writer.line().line(`${constant} = ${literal(signature)}`).line();
33
+ const params = [["body", "Union[bytes, str]"], ["headers", "Any"], ["secret", "str"], ["now", "Optional[int]", "None"]] ;
34
+ writer.line().line(def(style, webhookFunction(hook), params, pyType(hook.payload))).indent((fn) => {
35
+ docstring(fn, [
36
+ ...(hook.doc === undefined ? [] : [hook.doc, ""]),
37
+ `Verifies a ${hook.name} webhook and reads its body. Pass the raw body, exactly as received, and the request headers.`,
38
+ "",
39
+ "Raises WebhookSignatureError when the signature does not match the secret or the webhook is too old,",
40
+ "and DecodeError when the body does not match the payload type.",
41
+ ]);
42
+ fn.line(`verify_webhook(${constant}, body, headers, secret, int(time.time()) if now is None else now)`);
43
+ fn.line('text = body.decode("utf-8") if isinstance(body, bytes) else body');
44
+ fn.line(`return (${decoder(ir, hook.payload, `webhooks.${hook.name}.payload`)})(json_loads(text), "$")`);
45
+ });
46
+ }
47
+ return writer.toString();
48
+ }