@lovrozagar/honey 0.6.8 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (674) hide show
  1. package/README.md +514 -192
  2. package/bin/honey.js +25 -0
  3. package/dist/accepts.d.ts +7 -1
  4. package/dist/accepts.d.ts.map +1 -1
  5. package/dist/accepts.js +126 -0
  6. package/dist/accepts.js.map +1 -0
  7. package/dist/body-kind.d.ts +26 -0
  8. package/dist/body-kind.d.ts.map +1 -0
  9. package/dist/body-kind.js +70 -0
  10. package/dist/body-kind.js.map +1 -0
  11. package/dist/body-limit.d.ts +5 -1
  12. package/dist/body-limit.d.ts.map +1 -1
  13. package/dist/body-limit.js +126 -0
  14. package/dist/body-limit.js.map +1 -0
  15. package/dist/build/index.d.ts +19 -3
  16. package/dist/build/index.d.ts.map +1 -1
  17. package/dist/build/index.js +173 -0
  18. package/dist/build/index.js.map +1 -0
  19. package/dist/cli-args.d.ts +33 -0
  20. package/dist/cli-args.d.ts.map +1 -0
  21. package/dist/cli-args.js +102 -0
  22. package/dist/cli-args.js.map +1 -0
  23. package/dist/cli-go/auth.go +26 -0
  24. package/dist/cli-go/config.go +192 -0
  25. package/dist/cli-go/errors.go +75 -0
  26. package/dist/cli-go/multipart.go +79 -0
  27. package/dist/cli-go/output.go +163 -0
  28. package/dist/cli-go/root.go +30 -0
  29. package/dist/cli-go/stream.go +88 -0
  30. package/dist/cli-go/version.go +5 -0
  31. package/dist/cli.d.ts +1 -1
  32. package/dist/cli.js +209 -0
  33. package/dist/cli.js.map +1 -0
  34. package/dist/client/defaults.js +48 -0
  35. package/dist/client/defaults.js.map +1 -0
  36. package/dist/client/error.d.ts +35 -0
  37. package/dist/client/error.d.ts.map +1 -1
  38. package/dist/client/error.js +71 -0
  39. package/dist/client/error.js.map +1 -0
  40. package/dist/client/http.d.ts +67 -8
  41. package/dist/client/http.d.ts.map +1 -1
  42. package/dist/client/http.js +571 -0
  43. package/dist/client/http.js.map +1 -0
  44. package/dist/client/index.d.ts +3 -2
  45. package/dist/client/index.d.ts.map +1 -1
  46. package/dist/client/index.js +95 -0
  47. package/dist/client/index.js.map +1 -0
  48. package/dist/client/path.d.ts +26 -0
  49. package/dist/client/path.d.ts.map +1 -0
  50. package/dist/client/path.js +163 -0
  51. package/dist/client/path.js.map +1 -0
  52. package/dist/client/redirect-policy.d.ts +12 -0
  53. package/dist/client/redirect-policy.d.ts.map +1 -0
  54. package/dist/client/redirect-policy.js +20 -0
  55. package/dist/client/redirect-policy.js.map +1 -0
  56. package/dist/client/sdk.d.ts +36 -0
  57. package/dist/client/sdk.d.ts.map +1 -1
  58. package/dist/client/sdk.js +292 -0
  59. package/dist/client/sdk.js.map +1 -0
  60. package/dist/client/sse.d.ts +13 -0
  61. package/dist/client/sse.d.ts.map +1 -1
  62. package/dist/client/sse.js +129 -0
  63. package/dist/client/sse.js.map +1 -0
  64. package/dist/client/types.js +2 -0
  65. package/dist/client/types.js.map +1 -0
  66. package/dist/client/ws.d.ts +9 -2
  67. package/dist/client/ws.d.ts.map +1 -1
  68. package/dist/client/ws.js +112 -0
  69. package/dist/client/ws.js.map +1 -0
  70. package/dist/client-go/errors.go +236 -0
  71. package/dist/client-go/export.go +44 -0
  72. package/dist/client-go/invalidation.go +371 -0
  73. package/dist/client-go/nullable.go +62 -0
  74. package/dist/client-go/realtime.go +354 -0
  75. package/dist/client-go/result.go +20 -0
  76. package/dist/client-go/runtime.go +975 -0
  77. package/dist/client-go/sse.go +159 -0
  78. package/dist/client-go/transport.go +495 -0
  79. package/dist/client-go/ws.go +128 -0
  80. package/dist/client-info.d.ts +36 -0
  81. package/dist/client-info.d.ts.map +1 -0
  82. package/dist/client-info.js +53 -0
  83. package/dist/client-info.js.map +1 -0
  84. package/dist/client-mcp/README.md +10 -0
  85. package/dist/client-mcp/server.ts +221 -0
  86. package/dist/client-mcp/types.ts +19 -0
  87. package/dist/client-python/_errors.py +115 -0
  88. package/dist/client-python/_invalidation.py +494 -0
  89. package/dist/client-python/_realtime.py +179 -0
  90. package/dist/client-python/_runtime.py +860 -0
  91. package/dist/client-python/_sse.py +155 -0
  92. package/dist/client-python/_transport.py +366 -0
  93. package/dist/client-python/_ws.py +159 -0
  94. package/dist/client-python/py.typed +0 -0
  95. package/dist/client-rust/errors.rs +220 -0
  96. package/dist/client-rust/invalidation.rs +412 -0
  97. package/dist/client-rust/invalidation_sync.rs +93 -0
  98. package/dist/client-rust/nullable.rs +17 -0
  99. package/dist/client-rust/realtime.rs +702 -0
  100. package/dist/client-rust/result.rs +22 -0
  101. package/dist/client-rust/runtime.rs +980 -0
  102. package/dist/client-rust/runtime_sync.rs +484 -0
  103. package/dist/client-rust/sse.rs +188 -0
  104. package/dist/client-rust/ws.rs +167 -0
  105. package/dist/codegen-go-cli.d.ts.map +1 -1
  106. package/dist/codegen-go-cli.js +964 -0
  107. package/dist/codegen-go-cli.js.map +1 -0
  108. package/dist/codegen-go.d.ts +15 -3
  109. package/dist/codegen-go.d.ts.map +1 -1
  110. package/dist/codegen-go.js +872 -0
  111. package/dist/codegen-go.js.map +1 -0
  112. package/dist/codegen-hash.js +9 -0
  113. package/dist/codegen-hash.js.map +1 -0
  114. package/dist/codegen-ir.d.ts +69 -2
  115. package/dist/codegen-ir.d.ts.map +1 -1
  116. package/dist/codegen-ir.js +661 -0
  117. package/dist/codegen-ir.js.map +1 -0
  118. package/dist/codegen-lang.d.ts +65 -0
  119. package/dist/codegen-lang.d.ts.map +1 -0
  120. package/dist/codegen-lang.js +526 -0
  121. package/dist/codegen-lang.js.map +1 -0
  122. package/dist/codegen-load.d.ts +31 -0
  123. package/dist/codegen-load.d.ts.map +1 -0
  124. package/dist/codegen-load.js +138 -0
  125. package/dist/codegen-load.js.map +1 -0
  126. package/dist/codegen-loaders.js +55 -0
  127. package/dist/codegen-loaders.js.map +1 -0
  128. package/dist/codegen-mcp.d.ts.map +1 -1
  129. package/dist/codegen-mcp.js +368 -0
  130. package/dist/codegen-mcp.js.map +1 -0
  131. package/dist/codegen-python.d.ts +13 -1
  132. package/dist/codegen-python.d.ts.map +1 -1
  133. package/dist/codegen-python.js +828 -0
  134. package/dist/codegen-python.js.map +1 -0
  135. package/dist/codegen-route-tree-intern.d.ts +15 -5
  136. package/dist/codegen-route-tree-intern.d.ts.map +1 -1
  137. package/dist/codegen-route-tree-intern.js +221 -0
  138. package/dist/codegen-route-tree-intern.js.map +1 -0
  139. package/dist/codegen-rust.d.ts.map +1 -1
  140. package/dist/codegen-rust.js +1293 -0
  141. package/dist/codegen-rust.js.map +1 -0
  142. package/dist/codegen-sanitize.d.ts.map +1 -1
  143. package/dist/codegen-sanitize.js +56 -0
  144. package/dist/codegen-sanitize.js.map +1 -0
  145. package/dist/codegen-schema-naming.d.ts +5 -0
  146. package/dist/codegen-schema-naming.d.ts.map +1 -1
  147. package/dist/codegen-schema-naming.js +150 -0
  148. package/dist/codegen-schema-naming.js.map +1 -0
  149. package/dist/codegen-sdk-model.d.ts +71 -0
  150. package/dist/codegen-sdk-model.d.ts.map +1 -0
  151. package/dist/codegen-sdk-model.js +179 -0
  152. package/dist/codegen-sdk-model.js.map +1 -0
  153. package/dist/codegen.d.ts +41 -23
  154. package/dist/codegen.d.ts.map +1 -1
  155. package/dist/codegen.js +4610 -0
  156. package/dist/codegen.js.map +1 -0
  157. package/dist/context.d.ts +36 -6
  158. package/dist/context.d.ts.map +1 -1
  159. package/dist/context.js +242 -0
  160. package/dist/context.js.map +1 -0
  161. package/dist/cookie-sign.d.ts +16 -2
  162. package/dist/cookie-sign.d.ts.map +1 -1
  163. package/dist/cookie-sign.js +104 -0
  164. package/dist/cookie-sign.js.map +1 -0
  165. package/dist/cookie.d.ts +12 -0
  166. package/dist/cookie.d.ts.map +1 -1
  167. package/dist/cookie.js +138 -0
  168. package/dist/cookie.js.map +1 -0
  169. package/dist/cors.d.ts +1 -0
  170. package/dist/cors.d.ts.map +1 -1
  171. package/dist/cors.js +87 -0
  172. package/dist/cors.js.map +1 -0
  173. package/dist/crypto.d.ts +6 -1
  174. package/dist/crypto.d.ts.map +1 -1
  175. package/dist/crypto.js +38 -0
  176. package/dist/crypto.js.map +1 -0
  177. package/dist/csrf.d.ts +19 -0
  178. package/dist/csrf.d.ts.map +1 -1
  179. package/dist/csrf.js +79 -0
  180. package/dist/csrf.js.map +1 -0
  181. package/dist/curl-logger.d.ts +14 -3
  182. package/dist/curl-logger.d.ts.map +1 -1
  183. package/dist/curl-logger.js +199 -0
  184. package/dist/curl-logger.js.map +1 -0
  185. package/dist/detect-runtime.js +13 -0
  186. package/dist/detect-runtime.js.map +1 -0
  187. package/dist/dict.d.ts +11 -0
  188. package/dist/dict.d.ts.map +1 -0
  189. package/dist/dict.js +13 -0
  190. package/dist/dict.js.map +1 -0
  191. package/dist/error.d.ts.map +1 -1
  192. package/dist/error.js +44 -0
  193. package/dist/error.js.map +1 -0
  194. package/dist/errors.js +39 -0
  195. package/dist/errors.js.map +1 -0
  196. package/dist/etag.d.ts +2 -0
  197. package/dist/etag.d.ts.map +1 -1
  198. package/dist/etag.js +82 -0
  199. package/dist/etag.js.map +1 -0
  200. package/dist/feature-detect.d.ts +25 -0
  201. package/dist/feature-detect.d.ts.map +1 -0
  202. package/dist/feature-detect.js +144 -0
  203. package/dist/feature-detect.js.map +1 -0
  204. package/dist/feature-load.js +36 -0
  205. package/dist/feature-load.js.map +1 -0
  206. package/dist/feature-slots.d.ts +44 -0
  207. package/dist/feature-slots.d.ts.map +1 -0
  208. package/dist/feature-slots.js +48 -0
  209. package/dist/feature-slots.js.map +1 -0
  210. package/dist/fetch-request.d.ts +10 -0
  211. package/dist/fetch-request.d.ts.map +1 -0
  212. package/dist/fetch-request.js +13 -0
  213. package/dist/fetch-request.js.map +1 -0
  214. package/dist/gen-process.d.ts +15 -0
  215. package/dist/gen-process.d.ts.map +1 -0
  216. package/dist/gen-process.js +43 -0
  217. package/dist/gen-process.js.map +1 -0
  218. package/dist/gen-write.d.ts +19 -0
  219. package/dist/gen-write.d.ts.map +1 -0
  220. package/dist/gen-write.js +120 -0
  221. package/dist/gen-write.js.map +1 -0
  222. package/dist/glob.d.ts +21 -0
  223. package/dist/glob.d.ts.map +1 -0
  224. package/dist/glob.js +115 -0
  225. package/dist/glob.js.map +1 -0
  226. package/dist/go-type-emitter.d.ts +18 -4
  227. package/dist/go-type-emitter.d.ts.map +1 -1
  228. package/dist/go-type-emitter.js +594 -0
  229. package/dist/go-type-emitter.js.map +1 -0
  230. package/dist/honey-response.d.ts.map +1 -1
  231. package/dist/honey-response.js +338 -0
  232. package/dist/honey-response.js.map +1 -0
  233. package/dist/i18n-slot.d.ts +8 -0
  234. package/dist/i18n-slot.d.ts.map +1 -1
  235. package/dist/i18n-slot.js +14 -0
  236. package/dist/i18n-slot.js.map +1 -0
  237. package/dist/i18n.d.ts +3 -0
  238. package/dist/i18n.d.ts.map +1 -1
  239. package/dist/i18n.js +250 -0
  240. package/dist/i18n.js.map +1 -0
  241. package/dist/index.d.ts +408 -148
  242. package/dist/index.d.ts.map +1 -1
  243. package/dist/index.js +2324 -0
  244. package/dist/index.js.map +1 -0
  245. package/dist/init.d.ts +3 -5
  246. package/dist/init.d.ts.map +1 -1
  247. package/dist/init.js +140 -0
  248. package/dist/init.js.map +1 -0
  249. package/dist/input.js +4 -0
  250. package/dist/input.js.map +1 -0
  251. package/dist/invalidate-check.d.ts +11 -0
  252. package/dist/invalidate-check.d.ts.map +1 -1
  253. package/dist/invalidate-check.js +163 -0
  254. package/dist/invalidate-check.js.map +1 -0
  255. package/dist/invoke-user.d.ts +35 -0
  256. package/dist/invoke-user.d.ts.map +1 -0
  257. package/dist/invoke-user.js +73 -0
  258. package/dist/invoke-user.js.map +1 -0
  259. package/dist/ip-restrict.d.ts +13 -1
  260. package/dist/ip-restrict.d.ts.map +1 -1
  261. package/dist/ip-restrict.js +60 -0
  262. package/dist/ip-restrict.js.map +1 -0
  263. package/dist/ip.d.ts +39 -0
  264. package/dist/ip.d.ts.map +1 -0
  265. package/dist/ip.js +209 -0
  266. package/dist/ip.js.map +1 -0
  267. package/dist/logger.d.ts.map +1 -1
  268. package/dist/logger.js +113 -0
  269. package/dist/logger.js.map +1 -0
  270. package/dist/media-type.d.ts +30 -0
  271. package/dist/media-type.d.ts.map +1 -0
  272. package/dist/media-type.js +97 -0
  273. package/dist/media-type.js.map +1 -0
  274. package/dist/meta-spec-merge.d.ts +32 -0
  275. package/dist/meta-spec-merge.d.ts.map +1 -0
  276. package/dist/meta-spec-merge.js +68 -0
  277. package/dist/meta-spec-merge.js.map +1 -0
  278. package/dist/meta-spec.d.ts +16 -3
  279. package/dist/meta-spec.d.ts.map +1 -1
  280. package/dist/meta-spec.js +535 -0
  281. package/dist/meta-spec.js.map +1 -0
  282. package/dist/middleware.d.ts +23 -6
  283. package/dist/middleware.d.ts.map +1 -1
  284. package/dist/middleware.js +253 -0
  285. package/dist/middleware.js.map +1 -0
  286. package/dist/node-request.d.ts +57 -12
  287. package/dist/node-request.d.ts.map +1 -1
  288. package/dist/node-request.js +407 -0
  289. package/dist/node-request.js.map +1 -0
  290. package/dist/node.d.ts +20 -3
  291. package/dist/node.d.ts.map +1 -1
  292. package/dist/node.js +396 -0
  293. package/dist/node.js.map +1 -0
  294. package/dist/openapi/collect.d.ts +6 -3
  295. package/dist/openapi/collect.d.ts.map +1 -1
  296. package/dist/openapi/collect.js +30 -0
  297. package/dist/openapi/collect.js.map +1 -0
  298. package/dist/openapi/docs-page.d.ts +42 -0
  299. package/dist/openapi/docs-page.d.ts.map +1 -0
  300. package/dist/openapi/docs-page.js +80 -0
  301. package/dist/openapi/docs-page.js.map +1 -0
  302. package/dist/openapi/document.d.ts +4 -0
  303. package/dist/openapi/document.d.ts.map +1 -1
  304. package/dist/openapi/document.js +785 -0
  305. package/dist/openapi/document.js.map +1 -0
  306. package/dist/openapi/json-schema-slot.d.ts +7 -0
  307. package/dist/openapi/json-schema-slot.d.ts.map +1 -1
  308. package/dist/openapi/json-schema-slot.js +38 -0
  309. package/dist/openapi/json-schema-slot.js.map +1 -0
  310. package/dist/openapi/register.d.ts.map +1 -1
  311. package/dist/openapi/register.js +20 -0
  312. package/dist/openapi/register.js.map +1 -0
  313. package/dist/openapi/scalar.d.ts +3 -1
  314. package/dist/openapi/scalar.d.ts.map +1 -1
  315. package/dist/openapi/scalar.js +21 -0
  316. package/dist/openapi/scalar.js.map +1 -0
  317. package/dist/openapi/serve.d.ts +9 -0
  318. package/dist/openapi/serve.d.ts.map +1 -0
  319. package/dist/openapi/serve.js +36 -0
  320. package/dist/openapi/serve.js.map +1 -0
  321. package/dist/openapi/spec-factory.d.ts +30 -1
  322. package/dist/openapi/spec-factory.d.ts.map +1 -1
  323. package/dist/openapi/spec-factory.js +52 -0
  324. package/dist/openapi/spec-factory.js.map +1 -0
  325. package/dist/openapi/spec.d.ts +14 -5
  326. package/dist/openapi/spec.d.ts.map +1 -1
  327. package/dist/openapi/spec.js +50 -0
  328. package/dist/openapi/spec.js.map +1 -0
  329. package/dist/openapi/swagger.d.ts +3 -1
  330. package/dist/openapi/swagger.d.ts.map +1 -1
  331. package/dist/openapi/swagger.js +22 -0
  332. package/dist/openapi/swagger.js.map +1 -0
  333. package/dist/pattern.d.ts +71 -0
  334. package/dist/pattern.d.ts.map +1 -0
  335. package/dist/pattern.js +239 -0
  336. package/dist/pattern.js.map +1 -0
  337. package/dist/peer.d.ts +17 -0
  338. package/dist/peer.d.ts.map +1 -0
  339. package/dist/peer.js +50 -0
  340. package/dist/peer.js.map +1 -0
  341. package/dist/plugin.d.ts +67 -16
  342. package/dist/plugin.d.ts.map +1 -1
  343. package/dist/plugin.js +649 -0
  344. package/dist/plugin.js.map +1 -0
  345. package/dist/powered-by.d.ts.map +1 -1
  346. package/dist/powered-by.js +11 -0
  347. package/dist/powered-by.js.map +1 -0
  348. package/dist/pretty-json.d.ts.map +1 -1
  349. package/dist/pretty-json.js +47 -0
  350. package/dist/pretty-json.js.map +1 -0
  351. package/dist/producer-stream.d.ts +47 -0
  352. package/dist/producer-stream.d.ts.map +1 -0
  353. package/dist/producer-stream.js +267 -0
  354. package/dist/producer-stream.js.map +1 -0
  355. package/dist/proxy.d.ts +47 -8
  356. package/dist/proxy.d.ts.map +1 -1
  357. package/dist/proxy.js +274 -0
  358. package/dist/proxy.js.map +1 -0
  359. package/dist/python-type-emitter.d.ts +14 -1
  360. package/dist/python-type-emitter.d.ts.map +1 -1
  361. package/dist/python-type-emitter.js +157 -0
  362. package/dist/python-type-emitter.js.map +1 -0
  363. package/dist/realtime/bus.d.ts +17 -1
  364. package/dist/realtime/bus.d.ts.map +1 -1
  365. package/dist/realtime/bus.js +112 -0
  366. package/dist/realtime/bus.js.map +1 -0
  367. package/dist/realtime/register.d.ts +3 -0
  368. package/dist/realtime/register.d.ts.map +1 -0
  369. package/dist/realtime/register.js +10 -0
  370. package/dist/realtime/register.js.map +1 -0
  371. package/dist/realtime/route.d.ts +65 -26
  372. package/dist/realtime/route.d.ts.map +1 -1
  373. package/dist/realtime/route.js +72 -0
  374. package/dist/realtime/route.js.map +1 -0
  375. package/dist/realtime/server.d.ts +43 -0
  376. package/dist/realtime/server.d.ts.map +1 -0
  377. package/dist/realtime/server.js +255 -0
  378. package/dist/realtime/server.js.map +1 -0
  379. package/dist/request-id.d.ts +7 -0
  380. package/dist/request-id.d.ts.map +1 -1
  381. package/dist/request-id.js +16 -0
  382. package/dist/request-id.js.map +1 -0
  383. package/dist/request-limits.d.ts +3 -0
  384. package/dist/request-limits.d.ts.map +1 -0
  385. package/dist/request-limits.js +3 -0
  386. package/dist/request-limits.js.map +1 -0
  387. package/dist/request-path.d.ts +33 -0
  388. package/dist/request-path.d.ts.map +1 -0
  389. package/dist/request-path.js +178 -0
  390. package/dist/request-path.js.map +1 -0
  391. package/dist/request-to-curl.d.ts +7 -1
  392. package/dist/request-to-curl.d.ts.map +1 -1
  393. package/dist/request-to-curl.js +48 -0
  394. package/dist/request-to-curl.js.map +1 -0
  395. package/dist/response.d.ts +25 -2
  396. package/dist/response.d.ts.map +1 -1
  397. package/dist/response.js +313 -0
  398. package/dist/response.js.map +1 -0
  399. package/dist/rust-type-emitter.d.ts +14 -2
  400. package/dist/rust-type-emitter.d.ts.map +1 -1
  401. package/dist/rust-type-emitter.js +463 -0
  402. package/dist/rust-type-emitter.js.map +1 -0
  403. package/dist/secure-headers.d.ts.map +1 -1
  404. package/dist/secure-headers.js +53 -0
  405. package/dist/secure-headers.js.map +1 -0
  406. package/dist/serve-register.d.ts +4 -0
  407. package/dist/serve-register.d.ts.map +1 -1
  408. package/dist/serve-register.js +9 -0
  409. package/dist/serve-register.js.map +1 -0
  410. package/dist/serve-slot.d.ts +3 -0
  411. package/dist/serve-slot.d.ts.map +1 -1
  412. package/dist/serve-slot.js +52 -0
  413. package/dist/serve-slot.js.map +1 -0
  414. package/dist/serve.d.ts +18 -1
  415. package/dist/serve.d.ts.map +1 -1
  416. package/dist/serve.js +157 -0
  417. package/dist/serve.js.map +1 -0
  418. package/dist/server-timing.d.ts.map +1 -1
  419. package/dist/server-timing.js +51 -0
  420. package/dist/server-timing.js.map +1 -0
  421. package/dist/static.d.ts +9 -0
  422. package/dist/static.d.ts.map +1 -1
  423. package/dist/static.js +102 -0
  424. package/dist/static.js.map +1 -0
  425. package/dist/telemetry/otel.d.ts +2 -0
  426. package/dist/telemetry/otel.d.ts.map +1 -1
  427. package/dist/telemetry/otel.js +135 -0
  428. package/dist/telemetry/otel.js.map +1 -0
  429. package/dist/testing.d.ts +12 -0
  430. package/dist/testing.d.ts.map +1 -1
  431. package/dist/testing.js +124 -0
  432. package/dist/testing.js.map +1 -0
  433. package/dist/timeout.d.ts +6 -0
  434. package/dist/timeout.d.ts.map +1 -1
  435. package/dist/timeout.js +36 -0
  436. package/dist/timeout.js.map +1 -0
  437. package/dist/tree.d.ts +133 -36
  438. package/dist/tree.d.ts.map +1 -1
  439. package/dist/tree.js +437 -0
  440. package/dist/tree.js.map +1 -0
  441. package/dist/trust.d.ts +21 -0
  442. package/dist/trust.d.ts.map +1 -0
  443. package/dist/trust.js +100 -0
  444. package/dist/trust.js.map +1 -0
  445. package/dist/ts-type-emitter.d.ts.map +1 -1
  446. package/dist/ts-type-emitter.js +150 -0
  447. package/dist/ts-type-emitter.js.map +1 -0
  448. package/dist/type-emitter.d.ts +16 -2
  449. package/dist/type-emitter.d.ts.map +1 -1
  450. package/dist/type-emitter.js +729 -0
  451. package/dist/type-emitter.js.map +1 -0
  452. package/dist/type-extractor.d.ts +8 -4
  453. package/dist/type-extractor.d.ts.map +1 -1
  454. package/dist/type-extractor.js +819 -0
  455. package/dist/type-extractor.js.map +1 -0
  456. package/dist/types.d.ts +7 -0
  457. package/dist/types.d.ts.map +1 -1
  458. package/dist/types.js +96 -0
  459. package/dist/types.js.map +1 -0
  460. package/dist/validation.d.ts +14 -2
  461. package/dist/validation.d.ts.map +1 -1
  462. package/dist/validation.js +335 -0
  463. package/dist/validation.js.map +1 -0
  464. package/dist/with-headers.d.ts +15 -0
  465. package/dist/with-headers.d.ts.map +1 -0
  466. package/dist/with-headers.js +45 -0
  467. package/dist/with-headers.js.map +1 -0
  468. package/dist/ws/bun.d.ts +11 -5
  469. package/dist/ws/bun.d.ts.map +1 -1
  470. package/dist/ws/bun.js +82 -0
  471. package/dist/ws/bun.js.map +1 -0
  472. package/dist/ws/cloudflare.d.ts +25 -3
  473. package/dist/ws/cloudflare.d.ts.map +1 -1
  474. package/dist/ws/cloudflare.js +117 -0
  475. package/dist/ws/cloudflare.js.map +1 -0
  476. package/dist/ws/deno.d.ts +4 -4
  477. package/dist/ws/deno.d.ts.map +1 -1
  478. package/dist/ws/deno.js +133 -0
  479. package/dist/ws/deno.js.map +1 -0
  480. package/dist/ws/node.d.ts +20 -3
  481. package/dist/ws/node.d.ts.map +1 -1
  482. package/dist/ws/node.js +173 -0
  483. package/dist/ws/node.js.map +1 -0
  484. package/dist/ws/session.d.ts +11 -0
  485. package/dist/ws/session.d.ts.map +1 -0
  486. package/dist/ws/session.js +60 -0
  487. package/dist/ws/session.js.map +1 -0
  488. package/dist/ws/shared.d.ts +65 -0
  489. package/dist/ws/shared.d.ts.map +1 -0
  490. package/dist/ws/shared.js +103 -0
  491. package/dist/ws/shared.js.map +1 -0
  492. package/dist/ws-origin.d.ts +20 -0
  493. package/dist/ws-origin.d.ts.map +1 -0
  494. package/dist/ws-origin.js +41 -0
  495. package/dist/ws-origin.js.map +1 -0
  496. package/dist/yaml.d.ts +15 -1
  497. package/dist/yaml.d.ts.map +1 -1
  498. package/dist/yaml.js +101 -0
  499. package/dist/yaml.js.map +1 -0
  500. package/docs/invalidate-spec.md +13 -1
  501. package/docs/meta-spec.md +36 -12
  502. package/docs/packaging.md +43 -24
  503. package/docs/regression-matrix/README.md +32 -0
  504. package/docs/regression-matrix/review.md +44 -0
  505. package/docs/regression-matrix/ws1-3.md +97 -0
  506. package/docs/regression-matrix/ws4-8.md +107 -0
  507. package/docs/regression-matrix/ws9-12.md +266 -0
  508. package/docs/sdk.md +102 -52
  509. package/package.json +183 -52
  510. package/src/accepts.ts +91 -33
  511. package/src/body-kind.ts +67 -0
  512. package/src/body-limit.ts +102 -87
  513. package/src/build/index.ts +104 -54
  514. package/src/cli-args.ts +123 -0
  515. package/src/cli-go/auth.go +12 -1
  516. package/src/cli-go/config.go +29 -2
  517. package/src/cli-go/errors.go +28 -10
  518. package/src/cli-go/multipart.go +51 -27
  519. package/src/cli-go/output.go +58 -4
  520. package/src/cli-go/root.go +1 -1
  521. package/src/cli-go/version.go +2 -2
  522. package/src/cli.ts +154 -148
  523. package/src/client/error.ts +56 -1
  524. package/src/client/http.ts +479 -256
  525. package/src/client/index.ts +55 -17
  526. package/src/client/path.ts +169 -0
  527. package/src/client/redirect-policy.ts +19 -0
  528. package/src/client/sdk.ts +180 -101
  529. package/src/client/sse.ts +92 -66
  530. package/src/client/ws.ts +67 -31
  531. package/src/client-go/errors.go +41 -12
  532. package/src/client-go/export.go +44 -0
  533. package/src/client-go/invalidation.go +52 -54
  534. package/src/client-go/nullable.go +62 -0
  535. package/src/client-go/realtime.go +147 -110
  536. package/src/client-go/runtime.go +646 -88
  537. package/src/client-go/sse.go +104 -94
  538. package/src/client-go/transport.go +67 -27
  539. package/src/client-go/ws.go +49 -25
  540. package/src/client-info.ts +79 -0
  541. package/src/client-mcp/server.ts +133 -3
  542. package/src/client-python/_invalidation.py +207 -291
  543. package/src/client-python/_realtime.py +63 -40
  544. package/src/client-python/_runtime.py +501 -119
  545. package/src/client-python/_sse.py +130 -74
  546. package/src/client-python/_transport.py +37 -9
  547. package/src/client-python/_ws.py +50 -22
  548. package/src/client-rust/errors.rs +21 -1
  549. package/src/client-rust/invalidation.rs +202 -231
  550. package/src/client-rust/invalidation_sync.rs +16 -229
  551. package/src/client-rust/nullable.rs +17 -0
  552. package/src/client-rust/realtime.rs +217 -217
  553. package/src/client-rust/runtime.rs +602 -177
  554. package/src/client-rust/runtime_sync.rs +169 -145
  555. package/src/client-rust/sse.rs +142 -121
  556. package/src/client-rust/ws.rs +61 -37
  557. package/src/codegen-go-cli.ts +607 -728
  558. package/src/codegen-go.ts +710 -770
  559. package/src/codegen-ir.ts +381 -75
  560. package/src/codegen-lang.ts +517 -0
  561. package/src/codegen-load.ts +150 -0
  562. package/src/codegen-mcp.ts +207 -108
  563. package/src/codegen-python.ts +684 -816
  564. package/src/codegen-route-tree-intern.ts +51 -25
  565. package/src/codegen-rust.ts +946 -1240
  566. package/src/codegen-sanitize.ts +0 -4
  567. package/src/codegen-schema-naming.ts +19 -6
  568. package/src/codegen-sdk-model.ts +228 -0
  569. package/src/codegen.ts +1488 -1140
  570. package/src/context.ts +130 -11
  571. package/src/cookie-sign.ts +85 -16
  572. package/src/cookie.ts +66 -11
  573. package/src/cors.ts +55 -54
  574. package/src/crypto.ts +27 -5
  575. package/src/csrf.ts +57 -25
  576. package/src/curl-logger.ts +155 -114
  577. package/src/dict.ts +12 -0
  578. package/src/error.ts +4 -2
  579. package/src/etag.ts +58 -34
  580. package/src/feature-detect.ts +147 -0
  581. package/src/feature-slots.ts +70 -0
  582. package/src/fetch-request.ts +13 -0
  583. package/src/gen-process.ts +42 -0
  584. package/src/gen-write.ts +127 -0
  585. package/src/glob.ts +109 -0
  586. package/src/go-type-emitter.ts +406 -155
  587. package/src/honey-response.ts +36 -9
  588. package/src/i18n-slot.ts +10 -0
  589. package/src/i18n.ts +98 -23
  590. package/src/index.ts +1887 -1756
  591. package/src/init.ts +40 -28
  592. package/src/invalidate-check.ts +42 -4
  593. package/src/invoke-user.ts +95 -0
  594. package/src/ip-restrict.ts +47 -161
  595. package/src/ip.ts +194 -0
  596. package/src/logger.ts +65 -36
  597. package/src/media-type.ts +104 -0
  598. package/src/meta-spec-merge.ts +80 -0
  599. package/src/meta-spec.ts +0 -0
  600. package/src/middleware.ts +112 -12
  601. package/src/node-request.ts +242 -52
  602. package/src/node.ts +318 -75
  603. package/src/openapi/collect.ts +19 -44
  604. package/src/openapi/docs-page.ts +89 -0
  605. package/src/openapi/document.ts +503 -224
  606. package/src/openapi/json-schema-slot.ts +40 -0
  607. package/src/openapi/register.ts +7 -2
  608. package/src/openapi/scalar.ts +11 -10
  609. package/src/openapi/serve.ts +39 -0
  610. package/src/openapi/spec-factory.ts +50 -1
  611. package/src/openapi/spec.ts +53 -30
  612. package/src/openapi/swagger.ts +12 -11
  613. package/src/pattern.ts +245 -0
  614. package/src/peer.ts +53 -0
  615. package/src/plugin.ts +270 -185
  616. package/src/powered-by.ts +2 -2
  617. package/src/pretty-json.ts +25 -9
  618. package/src/producer-stream.ts +296 -0
  619. package/src/proxy.ts +253 -55
  620. package/src/python-type-emitter.ts +68 -56
  621. package/src/realtime/bus.ts +56 -9
  622. package/src/realtime/register.ts +13 -0
  623. package/src/realtime/route.ts +129 -80
  624. package/src/realtime/server.ts +298 -0
  625. package/src/request-id.ts +13 -3
  626. package/src/request-limits.ts +2 -0
  627. package/src/request-path.ts +165 -0
  628. package/src/request-to-curl.ts +28 -7
  629. package/src/response.ts +143 -103
  630. package/src/rust-type-emitter.ts +265 -170
  631. package/src/secure-headers.ts +8 -4
  632. package/src/serve-register.ts +4 -0
  633. package/src/serve-slot.ts +38 -0
  634. package/src/serve.ts +113 -25
  635. package/src/server-timing.ts +11 -7
  636. package/src/static.ts +85 -32
  637. package/src/telemetry/otel.ts +29 -7
  638. package/src/testing.ts +76 -14
  639. package/src/timeout.ts +15 -7
  640. package/src/tree.ts +405 -333
  641. package/src/trust.ts +117 -0
  642. package/src/ts-type-emitter.ts +18 -12
  643. package/src/type-emitter.ts +227 -89
  644. package/src/type-extractor.ts +603 -423
  645. package/src/types.ts +8 -0
  646. package/src/validation.ts +221 -96
  647. package/src/with-headers.ts +45 -0
  648. package/src/ws/bun.ts +53 -15
  649. package/src/ws/cloudflare.ts +81 -19
  650. package/src/ws/deno.ts +124 -36
  651. package/src/ws/node.ts +173 -79
  652. package/src/ws/session.ts +73 -0
  653. package/src/ws/shared.ts +140 -0
  654. package/src/ws-origin.ts +53 -0
  655. package/src/yaml.ts +45 -22
  656. package/dist/client-mcp/server.d.ts +0 -10
  657. package/dist/client-mcp/server.d.ts.map +0 -1
  658. package/dist/client-mcp/types.d.ts +0 -16
  659. package/dist/client-mcp/types.d.ts.map +0 -1
  660. package/dist/cloudflare/realtime.d.ts +0 -30
  661. package/dist/cloudflare/realtime.d.ts.map +0 -1
  662. package/dist/realtime/buffer.d.ts +0 -18
  663. package/dist/realtime/buffer.d.ts.map +0 -1
  664. package/dist/realtime/longpoll.d.ts +0 -23
  665. package/dist/realtime/longpoll.d.ts.map +0 -1
  666. package/dist/realtime/protocol.d.ts +0 -50
  667. package/dist/realtime/protocol.d.ts.map +0 -1
  668. package/dist/realtime/runtime.d.ts +0 -74
  669. package/dist/realtime/runtime.d.ts.map +0 -1
  670. package/src/cloudflare/realtime.ts +0 -234
  671. package/src/realtime/buffer.ts +0 -101
  672. package/src/realtime/longpoll.ts +0 -148
  673. package/src/realtime/protocol.ts +0 -128
  674. package/src/realtime/runtime.ts +0 -427
@@ -0,0 +1,1293 @@
1
+ /* Rust SDK emitter — generates a complete Rust crate from an OpenAPI 3.1 spec.
2
+ *
3
+ * Input is the SDK request model (codegen-sdk-model.ts). Every crate-level type name comes from one
4
+ * NameScope seeded with the prelude and the runtime's own types; fields, params and methods are
5
+ * claimed per scope; spec strings reach source only through rustString / rustDoc.
6
+ */
7
+ import { readFileSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
9
+ import { serviceMapOf } from "./codegen.js";
10
+ import { irErrorEnvelope, methodsOf, namespacesOf } from "./codegen-ir.js";
11
+ import { NameScope, RUST_PRELUDE_TYPES, cmpCodeUnit, rustDoc, rustPlainSnake, rustString, rustTypeIdent, rustValueIdent, } from "./codegen-lang.js";
12
+ import { buildSdkModel, isJsonMedia, valueCycleSchemas } from "./codegen-sdk-model.js";
13
+ import { irRenderTopLevelRust, irRenderUseRust } from "./rust-type-emitter.js";
14
+ let runtimeCache = null;
15
+ export function loadRustRuntimeTemplates() {
16
+ if (runtimeCache)
17
+ return runtimeCache;
18
+ const names = [
19
+ "errors.rs",
20
+ "result.rs",
21
+ "runtime.rs",
22
+ "invalidation.rs",
23
+ "invalidation_sync.rs",
24
+ "sse.rs",
25
+ "ws.rs",
26
+ "realtime.rs",
27
+ "runtime_sync.rs",
28
+ "nullable.rs",
29
+ ];
30
+ const cache = new Map();
31
+ for (const name of names) {
32
+ const filePath = fileURLToPath(new URL(`./client-rust/${name}`, import.meta.url));
33
+ let content;
34
+ try {
35
+ content = readFileSync(filePath, "utf8");
36
+ }
37
+ catch {
38
+ throw new Error(`loadRustRuntimeTemplates: missing file ${filePath}`);
39
+ }
40
+ cache.set(name, content);
41
+ }
42
+ runtimeCache = cache;
43
+ return cache;
44
+ }
45
+ /** Validates and normalises a crate name. Throws if invalid per cargo rules. */
46
+ export function validateCrateName(name) {
47
+ if (!/^[a-z][a-z0-9_-]*$/.test(name)) {
48
+ throw new Error(`Invalid crate name: ${JSON.stringify(name)}. Must match ^[a-z][a-z0-9_-]*$`);
49
+ }
50
+ return name;
51
+ }
52
+ /* Names the runtime modules and generated client declare or glob-import. */
53
+ const RUST_RUNTIME_TYPES = [
54
+ "ApiError",
55
+ "AuthState",
56
+ "BadGatewayError",
57
+ "BadRequestError",
58
+ "Client",
59
+ "ClientConfig",
60
+ "ClientInner",
61
+ "ConflictError",
62
+ "ConnectionState",
63
+ "ErrField",
64
+ "Error",
65
+ "ForbiddenError",
66
+ "GatewayTimeoutError",
67
+ "InternalServerError",
68
+ "InvalidationConfig",
69
+ "LogEntry",
70
+ "LongpollConn",
71
+ "LongpollState",
72
+ "LongpollTransport",
73
+ "NotFoundError",
74
+ "OnAuthExpiredHook",
75
+ "OnLogHook",
76
+ "OnRequestHook",
77
+ "OnResponseHook",
78
+ "QueryValue",
79
+ "RateLimitError",
80
+ "RealtimeError",
81
+ "RequestBody",
82
+ "RequestContext",
83
+ "RequestMeta",
84
+ "RequestResult",
85
+ "ResponseContext",
86
+ "ResponseMeta",
87
+ "ResumableConnection",
88
+ "ResumableConnectionOpts",
89
+ "SdkResult",
90
+ "ServiceEntry",
91
+ "ServiceUnavailableError",
92
+ "SseConn",
93
+ "SseEvent",
94
+ "SseParser",
95
+ "SseState",
96
+ "SseTransport",
97
+ "StaleEntry",
98
+ "StaleTracker",
99
+ "StaleTrackerSync",
100
+ "StatusError",
101
+ "SyncAuthState",
102
+ "SyncClient",
103
+ "SyncClientConfig",
104
+ "SyncClientInner",
105
+ "SyncOnRequestHook",
106
+ "SyncOnResponseHook",
107
+ "SyncRequestBody",
108
+ "SyncRequestContext",
109
+ "SyncRequestResult",
110
+ "SyncResponseContext",
111
+ "Transport",
112
+ "TransportConn",
113
+ "TransportKind",
114
+ "TransportOpts",
115
+ "TypedWebSocket",
116
+ "UnauthorizedError",
117
+ "UnprocessableEntityError",
118
+ "WsConn",
119
+ "WsTransport",
120
+ ];
121
+ function buildRustNames(model) {
122
+ const scope = new NameScope([...RUST_PRELUDE_TYPES, ...RUST_RUNTIME_TYPES]);
123
+ const schemaNames = new Map();
124
+ for (const name of model.schemaNames) {
125
+ const base = rustTypeIdent(name);
126
+ schemaNames.set(name, scope.has(base) ? scope.claim(`${base}Model`) : scope.claim(base));
127
+ }
128
+ const hoistKeys = new Map();
129
+ return {
130
+ decls: new Map(),
131
+ scope,
132
+ types: {
133
+ cyclic: valueCycleSchemas(model.ir.schemas),
134
+ hoist: (key, base) => {
135
+ const hit = hoistKeys.get(key);
136
+ if (hit)
137
+ return hit;
138
+ const name = scope.claim(rustTypeIdent(base));
139
+ hoistKeys.set(key, name);
140
+ return name;
141
+ },
142
+ ref: (name) => schemaNames.get(name) ?? rustTypeIdent(name),
143
+ resolve: model.resolve,
144
+ },
145
+ };
146
+ }
147
+ const OPTS_RESERVED = [
148
+ "last_event_id",
149
+ "reconnect_token",
150
+ "protocols",
151
+ "idempotency_key",
152
+ "headers",
153
+ "timeout",
154
+ "cancel_token",
155
+ "sync_cancel_token",
156
+ "max_reconnect_attempts",
157
+ "reconnect_delay_ms",
158
+ ];
159
+ /** Locals every emitted method body uses. */
160
+ const METHOD_LOCALS = [
161
+ "self",
162
+ "opts",
163
+ "query",
164
+ "url_path",
165
+ "result",
166
+ "out",
167
+ "req",
168
+ "resp",
169
+ "stream",
170
+ "cfg",
171
+ "client",
172
+ "auth",
173
+ "body_value",
174
+ "call_headers",
175
+ "path_params",
176
+ "concrete_path",
177
+ "selector",
178
+ "request_meta",
179
+ "stale",
180
+ "targets",
181
+ "headers",
182
+ ];
183
+ /** Per-status error envelopes (standard shapes only), read from the IR with refs resolved. */
184
+ function errorEnvelopes(op, opPascal, model, names) {
185
+ const out = [];
186
+ for (const [status, response] of Object.entries(op.ir.responses).sort(([a], [b]) => cmpCodeUnit(a, b))) {
187
+ const code = Number.parseInt(status, 10);
188
+ if (!/^[0-9]{3}$/.test(status) || code < 400)
189
+ continue;
190
+ if (!response.schema || !response.contentType || !isJsonMedia(response.contentType))
191
+ continue;
192
+ const envelope = irErrorEnvelope(response.schema, model.resolve);
193
+ if (!envelope)
194
+ continue;
195
+ out.push({
196
+ keyEnumName: names.scope.claim(`${opPascal}Err${code}Key`),
197
+ keys: envelope.keys,
198
+ status: code,
199
+ structName: names.scope.claim(`${opPascal}Err${code}`),
200
+ variantName: `Status${code}`,
201
+ });
202
+ }
203
+ return out;
204
+ }
205
+ function emitErrorTypes(plan) {
206
+ if (plan.envelopes.length === 0 || !plan.errorEnum)
207
+ return [];
208
+ const l = [];
209
+ for (const env of plan.envelopes) {
210
+ const variants = new NameScope();
211
+ l.push(`#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]`);
212
+ l.push(`pub enum ${env.keyEnumName} {`);
213
+ for (const k of env.keys) {
214
+ const v = variants.claim(k === "" ? "Empty" : rustTypeIdent(k));
215
+ l.push(`\t#[serde(rename = ${rustString(k)})]`);
216
+ l.push(`\t${v},`);
217
+ }
218
+ l.push(`}`);
219
+ l.push(``);
220
+ l.push(`#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]`);
221
+ l.push(`pub struct ${env.structName} {`);
222
+ l.push(`\tpub error_key: ${env.keyEnumName},`);
223
+ l.push(`\tpub message: String,`);
224
+ l.push(`\tpub fields: std::collections::HashMap<String, Vec<crate::types::ErrField>>,`);
225
+ l.push(`}`);
226
+ l.push(``);
227
+ }
228
+ l.push(`#[derive(Debug)]`);
229
+ l.push(`pub enum ${plan.errorEnum} {`);
230
+ for (const env of plan.envelopes)
231
+ l.push(`\t${env.variantName}(${env.structName}),`);
232
+ l.push(`\tOther(Error),`);
233
+ l.push(`}`);
234
+ l.push(``);
235
+ return l;
236
+ }
237
+ function planOp(op, fnName, pathSegs, names, throwOnError, model) {
238
+ const opPascal = pathSegs.map(rustTypeIdent).join("");
239
+ const optsName = names.scope.claim(`${opPascal}Opts`);
240
+ const locals = new NameScope(METHOD_LOCALS);
241
+ const plan = {
242
+ action: op.segments.length === 1 ? "_call" : op.segments.slice(1).join("."),
243
+ envelopes: [],
244
+ fnName,
245
+ op,
246
+ optFields: [],
247
+ optsName,
248
+ pathParams: [],
249
+ resource: op.segments[0] ?? op.id,
250
+ resultType: "",
251
+ };
252
+ const hasBody = op.body !== undefined && op.stream !== "ws" && op.stream !== "realtime";
253
+ const bodyLocal = hasBody ? locals.claim("body") : "";
254
+ for (const p of op.pathParams)
255
+ plan.pathParams.push({ local: locals.claim(rustPlainSnake(p.name)), wire: p.name });
256
+ if (op.stream !== "realtime") {
257
+ const fieldScope = new NameScope(OPTS_RESERVED);
258
+ const params = [
259
+ ...op.query.map((p) => [p, "query"]),
260
+ ...op.headers.map((p) => [p, "header"]),
261
+ ];
262
+ for (const [p, where] of params) {
263
+ if (op.stream === "sse" && where === "query" && /^last[-_]?event[-_]?id$/i.test(p.name))
264
+ continue;
265
+ const ident = fieldScope.claim(rustPlainSnake(p.name));
266
+ const t = irRenderUseRust(p.schema, {
267
+ decls: names.decls,
268
+ fieldName: p.name,
269
+ names: names.types,
270
+ parentName: optsName,
271
+ });
272
+ plan.optFields.push({
273
+ ident,
274
+ required: p.required === true,
275
+ type: p.required === true || t.startsWith("Option<") ? t : `Option<${t}>`,
276
+ where,
277
+ wire: p.name,
278
+ });
279
+ }
280
+ }
281
+ if (hasBody && op.body) {
282
+ const b = op.body;
283
+ switch (b.kind) {
284
+ case "json": {
285
+ let t;
286
+ if (b.schema.kind === "ref")
287
+ t = names.types.ref(b.schema.name);
288
+ else
289
+ t = irRenderUseRust(b.schema, {
290
+ decls: names.decls,
291
+ fieldName: "Body",
292
+ names: names.types,
293
+ parentName: opPascal,
294
+ });
295
+ plan.bodyParam = { asyncType: `&${t}`, local: bodyLocal, syncType: `&${t}` };
296
+ break;
297
+ }
298
+ case "form":
299
+ plan.bodyParam = {
300
+ asyncType: "&std::collections::HashMap<String, String>",
301
+ local: bodyLocal,
302
+ syncType: "&std::collections::HashMap<String, String>",
303
+ };
304
+ break;
305
+ case "multipart":
306
+ /* multipart Form is consumed (not Clone), passed by value */
307
+ plan.bodyParam = {
308
+ asyncType: "reqwest::multipart::Form",
309
+ local: bodyLocal,
310
+ syncType: "reqwest::blocking::multipart::Form",
311
+ };
312
+ break;
313
+ case "binary":
314
+ /* octet-stream body: generic over any byte stream / reader; single-shot, not retried on 401 */
315
+ plan.bodyParam = {
316
+ asyncType: "S",
317
+ generic: {
318
+ async: `S`,
319
+ asyncWhere: ` where S: futures::TryStream + Send + 'static, S::Error: Into<Box<dyn std::error::Error + Send + Sync>>, bytes::Bytes: From<S::Ok>`,
320
+ sync: `R: std::io::Read + Send + 'static`,
321
+ },
322
+ local: bodyLocal,
323
+ syncType: "R",
324
+ };
325
+ break;
326
+ case "text":
327
+ plan.bodyParam = { asyncType: "&str", local: bodyLocal, syncType: "&str" };
328
+ break;
329
+ }
330
+ }
331
+ if (op.stream === null) {
332
+ const s = op.success;
333
+ if (s.kind === "json") {
334
+ if (!s.schema)
335
+ plan.resultType = "serde_json::Value";
336
+ else if (s.schema.kind === "ref")
337
+ plan.resultType = names.types.ref(s.schema.name);
338
+ else {
339
+ const t = irRenderUseRust(s.schema, {
340
+ decls: names.decls,
341
+ fieldName: "Response",
342
+ names: names.types,
343
+ parentName: opPascal,
344
+ });
345
+ plan.resultType = t.startsWith("Box<") ? t.slice(4, -1) : t;
346
+ }
347
+ }
348
+ else if (s.kind === "text")
349
+ plan.resultType = "String";
350
+ else if (s.kind === "binary")
351
+ plan.resultType = "Vec<u8>";
352
+ /* the typed error enums exist in both modes; only safe-mode methods return them */
353
+ plan.envelopes = errorEnvelopes(op, opPascal, model, names);
354
+ if (plan.envelopes.length > 0)
355
+ plan.errorEnum = names.scope.claim(`${opPascal}Error`);
356
+ }
357
+ void model;
358
+ return plan;
359
+ }
360
+ function emitOptsStruct(plan) {
361
+ const l = [];
362
+ const { op, optsName } = plan;
363
+ const fields = [];
364
+ if (op.stream === "realtime") {
365
+ fields.push(`\tpub reconnect_token: Option<String>,`);
366
+ fields.push(`\tpub last_event_id: Option<String>,`);
367
+ fields.push(`\tpub protocols: Option<Vec<String>>,`);
368
+ fields.push(`\tpub max_reconnect_attempts: Option<u32>,`);
369
+ fields.push(`\tpub reconnect_delay_ms: Option<u64>,`);
370
+ fields.push(`\t#[serde(skip)]`);
371
+ fields.push(`\tpub headers: Option<std::collections::HashMap<String, String>>,`);
372
+ }
373
+ else {
374
+ for (const f of plan.optFields) {
375
+ const bare = f.ident.startsWith("r#") ? f.ident.slice(2) : f.ident;
376
+ const attrs = [];
377
+ if (bare !== f.wire)
378
+ attrs.push(`rename = ${rustString(f.wire)}`);
379
+ if (!f.required)
380
+ attrs.push(`skip_serializing_if = "Option::is_none"`);
381
+ if (attrs.length > 0)
382
+ fields.push(`\t#[serde(${attrs.join(", ")})]`);
383
+ fields.push(`\tpub ${f.ident}: ${f.type},`);
384
+ }
385
+ if (op.stream === "sse")
386
+ fields.push(`\tpub last_event_id: Option<String>,`);
387
+ if (op.stream === "ws") {
388
+ fields.push(`\tpub reconnect_token: Option<String>,`);
389
+ fields.push(`\tpub protocols: Option<Vec<String>>,`);
390
+ }
391
+ if (op.idempotent && op.stream === null) {
392
+ fields.push(`\t#[serde(skip_serializing_if = "Option::is_none")]`);
393
+ fields.push(`\tpub idempotency_key: Option<String>,`);
394
+ }
395
+ /* per-call headers for all non-WS methods (SSE included) */
396
+ if (op.stream !== "ws") {
397
+ fields.push(`\t#[serde(skip)]`);
398
+ fields.push(`\tpub headers: Option<std::collections::HashMap<String, String>>,`);
399
+ }
400
+ if (op.stream === null) {
401
+ fields.push(`\t#[serde(skip)]`);
402
+ fields.push(`\tpub timeout: Option<std::time::Duration>,`);
403
+ /* async consumes `cancel_token`, sync consumes `sync_cancel_token`; both runtime-only */
404
+ fields.push(`\t#[serde(skip)]`);
405
+ fields.push(`\tpub cancel_token: Option<tokio_util::sync::CancellationToken>,`);
406
+ fields.push(`\t#[serde(skip)]`);
407
+ fields.push(`\tpub sync_cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,`);
408
+ }
409
+ }
410
+ l.push(`#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]`);
411
+ l.push(`pub struct ${optsName} {`);
412
+ l.push(...fields);
413
+ l.push(`}`);
414
+ l.push(``);
415
+ return l;
416
+ }
417
+ function docLines(op) {
418
+ const l = [];
419
+ if (op.summary)
420
+ l.push(...rustDoc(op.summary));
421
+ if (op.description) {
422
+ if (op.summary)
423
+ l.push(`///`);
424
+ l.push(...rustDoc(op.description));
425
+ }
426
+ if (op.deprecated)
427
+ l.push(`#[deprecated(note = "the API marks this operation deprecated")]`);
428
+ return l;
429
+ }
430
+ function pathLines(plan) {
431
+ if (plan.pathParams.length === 0)
432
+ return [`\tlet url_path = ${rustString(plan.op.path)}.to_string();`];
433
+ const params = plan.pathParams.map((p) => `(${rustString(p.wire)}, ${p.local})`).join(", ");
434
+ return [`\tlet url_path = crate::runtime::expand_path(${rustString(plan.op.path)}, &[${params}])?;`];
435
+ }
436
+ function queryLines(plan, opts = "opts") {
437
+ const q = plan.optFields.filter((f) => f.where === "query");
438
+ const l = [`\tlet ${q.length > 0 ? "mut " : ""}query: Vec<(String, String)> = Vec::new();`];
439
+ for (const f of q)
440
+ l.push(`\tcrate::runtime::push_serialized(${rustString(f.wire)}, &${opts}.${f.ident}, &mut query);`);
441
+ return l;
442
+ }
443
+ /** Lines that build `call_headers` from opts.headers, header params, then `extra` entries. */
444
+ function headerLines(plan, extra = []) {
445
+ const l = [
446
+ `\tlet mut call_headers: std::collections::HashMap<String, String> = opts.headers.clone().unwrap_or_default();`,
447
+ ];
448
+ for (const f of plan.optFields.filter((x) => x.where === "header")) {
449
+ l.push(`\t{`);
450
+ l.push(`\t\tlet mut values: Vec<(String, String)> = Vec::new();`);
451
+ l.push(`\t\tcrate::runtime::push_serialized(${rustString(f.wire)}, &opts.${f.ident}, &mut values);`);
452
+ l.push(`\t\tif !values.is_empty() {`);
453
+ l.push(`\t\t\tcrate::runtime::set_header(&mut call_headers, ${rustString(f.wire)}, values.into_iter().map(|(_, v)| v).collect::<Vec<_>>().join(","));`);
454
+ l.push(`\t\t}`);
455
+ l.push(`\t}`);
456
+ }
457
+ l.push(...extra);
458
+ return l;
459
+ }
460
+ function bodyExpr(plan, sync) {
461
+ const prefix = sync ? "crate::runtime_sync::SyncRequestBody" : "crate::runtime::RequestBody";
462
+ const b = plan.op.body;
463
+ const local = plan.bodyParam?.local;
464
+ if (!b || !local)
465
+ return { expr: `${prefix}::None`, lines: [] };
466
+ switch (b.kind) {
467
+ case "json":
468
+ return { expr: `${prefix}::Json(&body_value)`, lines: [`\tlet body_value = serde_json::to_value(${local})?;`] };
469
+ case "form":
470
+ return { expr: `${prefix}::FormUrl(crate::runtime::form_pairs(${local}))`, lines: [] };
471
+ case "multipart":
472
+ return { expr: `${prefix}::Multipart(${local})`, lines: [] };
473
+ case "binary":
474
+ return {
475
+ expr: sync
476
+ ? `${prefix}::Stream(reqwest::blocking::Body::new(${local}))`
477
+ : `${prefix}::Stream(reqwest::Body::wrap_stream(${local}))`,
478
+ lines: [],
479
+ };
480
+ case "text":
481
+ return {
482
+ expr: `${prefix}::Raw(${rustString(b.contentType)}, bytes::Bytes::from(${local}.to_string()))`,
483
+ lines: [],
484
+ };
485
+ }
486
+ }
487
+ function decodeLines(plan, throwOnError) {
488
+ switch (plan.op.success.kind) {
489
+ case "text":
490
+ return [`\tlet out: String = String::from_utf8_lossy(&result.body).into_owned();`];
491
+ case "binary":
492
+ /* the bytes move into the result; only a safe-mode call keeps a second copy in `response` */
493
+ return [`\tlet out: Vec<u8> = ${throwOnError ? "result.body" : "result.body.clone()"};`];
494
+ default:
495
+ /* an empty JSON body decodes as `null` (Option / Value types accept it) */
496
+ return [
497
+ `\tlet out: ${plan.resultType} = serde_json::from_slice(if result.body.is_empty() { b"null" } else { &result.body })?;`,
498
+ ];
499
+ }
500
+ }
501
+ function access(selfAccess) {
502
+ return selfAccess === "self"
503
+ ? { auth: "self.inner.auth", cfg: "self.inner.cfg", http: "self.inner.http_client", stale: "self.inner.stale" }
504
+ : { auth: "self.client.auth", cfg: "self.client.cfg", http: "self.client.http_client", stale: "self.client.stale" };
505
+ }
506
+ function returnType(plan, throwOnError) {
507
+ if (plan.resultType === "")
508
+ return "Result<(), Error>";
509
+ if (throwOnError)
510
+ return `Result<${plan.resultType}, Error>`;
511
+ if (plan.errorEnum)
512
+ return `Result<SdkResult<${plan.resultType}, ${plan.errorEnum}>, Error>`;
513
+ return `Result<SdkResult<${plan.resultType}>, Error>`;
514
+ }
515
+ /** Shared tail: run the request (already bound to `result`), invalidate, decode. */
516
+ function resultLines(plan, throwOnError, sync, a, call) {
517
+ const l = [];
518
+ const aw = sync ? "" : ".await";
519
+ const method = plan.op.method;
520
+ /* invalidation pre-flight for every call: reads see and clear staleness too */
521
+ const pp = plan.pathParams.map((p) => `(${rustString(p.wire)}.to_string(), ${p.local}.to_string())`).join(", ");
522
+ l.push(`\tlet path_params: std::collections::HashMap<String, String> = ${plan.pathParams.length > 0 ? `std::collections::HashMap::from([${pp}])` : "std::collections::HashMap::new()"};`);
523
+ l.push(`\tlet selector = format!("{} {}", ${rustString(method)}, url_path);`);
524
+ l.push(`\tlet request_meta: Option<crate::invalidation::RequestMeta> = match ${a.stale} {`);
525
+ l.push(`\t\tSome(ref s) => s.build_request_meta(&selector, &url_path, ${rustString(method)})${aw},`);
526
+ l.push(`\t\tNone => None,`);
527
+ l.push(`\t};`);
528
+ const safe = !throwOnError && plan.resultType !== "";
529
+ if (safe) {
530
+ l.push(`\tlet result = match ${call.join("\n\t\t")} {`);
531
+ l.push(`\t\tOk(r) => r,`);
532
+ l.push(`\t\tErr(Error::Api(api)) => {`);
533
+ l.push(`\t\t\tlet status = api.status();`);
534
+ if (plan.errorEnum) {
535
+ l.push(`\t\t\tlet body = api.body().to_vec();`);
536
+ l.push(`\t\t\tlet error = match status {`);
537
+ for (const env of plan.envelopes) {
538
+ l.push(`\t\t\t\t${env.status} => match serde_json::from_slice::<${env.structName}>(&body) {`);
539
+ l.push(`\t\t\t\t\tOk(v) => ${plan.errorEnum}::${env.variantName}(v),`);
540
+ l.push(`\t\t\t\t\tErr(_) => ${plan.errorEnum}::Other(Error::Api(api)),`);
541
+ l.push(`\t\t\t\t},`);
542
+ }
543
+ l.push(`\t\t\t\t_ => ${plan.errorEnum}::Other(Error::Api(api)),`);
544
+ l.push(`\t\t\t};`);
545
+ l.push(`\t\t\tlet mut response = crate::runtime::ResponseMeta::empty(status);`);
546
+ l.push(`\t\t\tresponse.body = body;`);
547
+ l.push(`\t\t\treturn Ok(SdkResult { data: None, error: Some(error), status, response });`);
548
+ }
549
+ else {
550
+ l.push(`\t\t\tlet mut response = crate::runtime::ResponseMeta::empty(status);`);
551
+ l.push(`\t\t\tresponse.body = api.body().to_vec();`);
552
+ l.push(`\t\t\treturn Ok(SdkResult { data: None, error: Some(Error::Api(api)), status, response });`);
553
+ }
554
+ l.push(`\t\t}`);
555
+ l.push(`\t\tErr(e) => return Err(e),`);
556
+ l.push(`\t};`);
557
+ }
558
+ else {
559
+ l.push(`\tlet result = ${call.join("\n\t\t")}?;`);
560
+ }
561
+ /* invalidation post-flight: mark declared targets stale (templated ones expanded with this
562
+ * call's params), then clear this key if the call read through a stale window */
563
+ l.push(`\tif let Some(ref stale) = ${a.stale} {`);
564
+ if (plan.op.invalidates.length > 0) {
565
+ l.push(`\t\tlet targets: Vec<String> = vec![${plan.op.invalidates.map((t) => `${rustString(t)}.to_string()`).join(", ")}];`);
566
+ l.push(`\t\tstale.mark_stale(&targets, &path_params, &selector)${aw};`);
567
+ }
568
+ l.push(`\t\tif let Some(ref meta) = request_meta {`);
569
+ l.push(`\t\t\tif meta.is_stale {`);
570
+ l.push(`\t\t\t\tstale.clear_stale(&selector, &url_path, ${rustString(method)}, meta.seq_snapshot)${aw};`);
571
+ l.push(`\t\t\t}`);
572
+ l.push(`\t\t}`);
573
+ l.push(`\t}`);
574
+ if (plan.resultType === "") {
575
+ l.push(`\tlet _ = result;`);
576
+ l.push(`\tOk(())`);
577
+ return l;
578
+ }
579
+ l.push(...decodeLines(plan, throwOnError));
580
+ if (throwOnError) {
581
+ l.push(`\tOk(out)`);
582
+ }
583
+ else {
584
+ /* the response snapshot takes the body, headers and URL by move */
585
+ l.push(`\tOk(SdkResult { data: Some(out), error: None, status: result.status, response: crate::runtime::ResponseMeta { status: result.status, headers: result.headers, url: result.url, body: result.body } })`);
586
+ }
587
+ return l;
588
+ }
589
+ function signature(plan, sync) {
590
+ const params = [`&self`];
591
+ for (const p of plan.pathParams)
592
+ params.push(`${p.local}: &str`);
593
+ let generics = "";
594
+ let where = "";
595
+ if (plan.bodyParam) {
596
+ params.push(`${plan.bodyParam.local}: ${sync ? plan.bodyParam.syncType : plan.bodyParam.asyncType}`);
597
+ if (plan.bodyParam.generic) {
598
+ generics = `<${sync ? plan.bodyParam.generic.sync : plan.bodyParam.generic.async}>`;
599
+ if (!sync)
600
+ where = plan.bodyParam.generic.asyncWhere ?? "";
601
+ }
602
+ }
603
+ params.push(`opts: &${plan.optsName}`);
604
+ return { generics, params: params.join(", "), where };
605
+ }
606
+ function emitMethod(plan, selfAccess, throwOnError) {
607
+ const l = [];
608
+ const { op } = plan;
609
+ const a = access(selfAccess);
610
+ l.push(...docLines(op));
611
+ const sig = signature(plan, false);
612
+ if (op.stream === "realtime") {
613
+ l.push(`pub async fn ${plan.fnName}(${sig.params}) -> Result<crate::realtime::ResumableConnection<serde_json::Value, serde_json::Value>, crate::realtime::RealtimeError> {`);
614
+ l.push(`\tlet connect_err = |e: Error| crate::realtime::RealtimeError::Connect(e);`);
615
+ l.push(...pathLines(plan).map((x) => x.replace(/\?;$/, ".map_err(connect_err)?;")));
616
+ l.push(`\tlet url = crate::runtime::build_url(&${a.cfg}.base_url, &url_path, &[]).map_err(connect_err)?;`);
617
+ l.push(`\tlet headers = crate::runtime::auth_headers(&${a.cfg}, &${a.auth}, opts.headers.as_ref()).await;`);
618
+ l.push(`\tlet rt_opts = crate::realtime::ResumableConnectionOpts {`);
619
+ l.push(`\t\treconnect_token: opts.reconnect_token.clone(),`);
620
+ l.push(`\t\tprotocols: opts.protocols.clone(),`);
621
+ l.push(`\t\tmax_reconnect_attempts: opts.max_reconnect_attempts,`);
622
+ l.push(`\t\treconnect_delay_ms: opts.reconnect_delay_ms,`);
623
+ l.push(`\t\tlast_event_id: opts.last_event_id.clone(),`);
624
+ l.push(`\t\theaders,`);
625
+ l.push(`\t\thttp_client: Some(${a.http}.clone()),`);
626
+ l.push(`\t};`);
627
+ l.push(`\tcrate::realtime::ResumableConnection::<serde_json::Value, serde_json::Value>::connect_with_defaults(url.to_string(), rt_opts).await`);
628
+ l.push(`}`);
629
+ l.push(``);
630
+ return l;
631
+ }
632
+ if (op.stream === "sse") {
633
+ l.push(`pub fn ${plan.fnName}${sig.generics}(${sig.params}) -> impl Stream<Item = Result<SseEvent, Error>>${sig.where} {`);
634
+ /* clone everything the stream needs into owned locals: the stream outlives &self/&opts */
635
+ if (plan.pathParams.length === 0) {
636
+ l.push(`\tlet url_path: Result<String, Error> = Ok(${rustString(op.path)}.to_string());`);
637
+ }
638
+ else {
639
+ const params = plan.pathParams.map((p) => `(${rustString(p.wire)}, ${p.local})`).join(", ");
640
+ l.push(`\tlet url_path = crate::runtime::expand_path(${rustString(op.path)}, &[${params}]);`);
641
+ }
642
+ l.push(...queryLines(plan));
643
+ l.push(...headerLines(plan, [
644
+ `\tcrate::runtime::set_header(&mut call_headers, "Accept", "text/event-stream".to_string());`,
645
+ `\tif let Some(ref lei) = opts.last_event_id {`,
646
+ `\t\tcrate::runtime::set_header(&mut call_headers, "Last-Event-ID", lei.clone());`,
647
+ `\t}`,
648
+ ]));
649
+ const body = op.body && plan.bodyParam?.local ? op.body : undefined;
650
+ if (body?.kind === "json")
651
+ l.push(`\tlet body_value = serde_json::to_value(${plan.bodyParam?.local});`);
652
+ l.push(`\tlet cfg = ${a.cfg}.clone();`);
653
+ l.push(`\tlet client = ${a.http}.clone();`);
654
+ l.push(`\tlet auth = std::sync::Arc::clone(&${a.auth});`);
655
+ if (body?.kind === "form")
656
+ l.push(`\tlet form = crate::runtime::form_pairs(${plan.bodyParam?.local});`);
657
+ if (body?.kind === "text")
658
+ l.push(`\tlet text = bytes::Bytes::from(${plan.bodyParam?.local}.to_string());`);
659
+ if (body?.kind === "multipart" || body?.kind === "binary")
660
+ l.push(`\tlet raw_body = ${plan.bodyParam?.local};`);
661
+ l.push(`\tasync_stream::stream! {`);
662
+ l.push(`\t\tuse futures_util::StreamExt;`);
663
+ l.push(`\t\tlet url_path = match url_path {`);
664
+ l.push(`\t\t\tOk(p) => p,`);
665
+ l.push(`\t\t\tErr(e) => { yield Err(e); return; }`);
666
+ l.push(`\t\t};`);
667
+ let expr = "crate::runtime::RequestBody::None";
668
+ if (body?.kind === "json") {
669
+ l.push(`\t\tlet body_value = match body_value {`);
670
+ l.push(`\t\t\tOk(v) => v,`);
671
+ l.push(`\t\t\tErr(e) => { yield Err(Error::Json(e)); return; }`);
672
+ l.push(`\t\t};`);
673
+ expr = "crate::runtime::RequestBody::Json(&body_value)";
674
+ }
675
+ else if (body?.kind === "form")
676
+ expr = "crate::runtime::RequestBody::FormUrl(form)";
677
+ else if (body?.kind === "text")
678
+ expr = `crate::runtime::RequestBody::Raw(${rustString(body.contentType)}, text)`;
679
+ else if (body?.kind === "multipart")
680
+ expr = "crate::runtime::RequestBody::Multipart(raw_body)";
681
+ else if (body?.kind === "binary")
682
+ expr = "crate::runtime::RequestBody::Stream(reqwest::Body::wrap_stream(raw_body))";
683
+ l.push(`\t\tlet opened = crate::runtime::open_stream(&client, &cfg, &auth, reqwest::Method::${op.method}, &url_path, &query, ${expr}, Some(&call_headers)).await;`);
684
+ l.push(`\t\tmatch opened {`);
685
+ l.push(`\t\t\tErr(e) => { yield Err(e); }`);
686
+ l.push(`\t\t\tOk(r) => {`);
687
+ l.push(`\t\t\t\tlet mut s = std::pin::pin!(crate::sse::parse_sse_stream(r));`);
688
+ l.push(`\t\t\t\twhile let Some(item) = s.next().await { yield item; }`);
689
+ l.push(`\t\t\t}`);
690
+ l.push(`\t\t}`);
691
+ l.push(`\t}`);
692
+ l.push(`}`);
693
+ l.push(``);
694
+ return l;
695
+ }
696
+ if (op.stream === "ws") {
697
+ l.push(`pub async fn ${plan.fnName}(${sig.params}) -> Result<TypedWebSocket, Error> {`);
698
+ l.push(...pathLines(plan));
699
+ l.push(...queryLines(plan));
700
+ l.push(`\tif let Some(ref rt) = opts.reconnect_token {`);
701
+ l.push(`\t\tquery.push(("reconnect_token".to_string(), rt.clone()));`);
702
+ l.push(`\t}`);
703
+ l.push(`\tlet url = crate::runtime::build_url(&${a.cfg}.base_url, &url_path, &query)?;`);
704
+ l.push(`\tlet ws_url = crate::runtime::to_ws_url(url.as_str());`);
705
+ l.push(`\tuse tokio_tungstenite::tungstenite::client::IntoClientRequest;`);
706
+ l.push(`\tlet mut req = ws_url.as_str().into_client_request().map_err(|e| Error::Other(e.to_string()))?;`);
707
+ l.push(`\tfor (k, v) in crate::runtime::auth_headers(&${a.cfg}, &${a.auth}, None).await {`);
708
+ l.push(`\t\tif let (Ok(name), Ok(val)) = (`);
709
+ l.push(`\t\t\ttokio_tungstenite::tungstenite::http::HeaderName::from_bytes(k.as_bytes()),`);
710
+ l.push(`\t\t\tv.parse::<tokio_tungstenite::tungstenite::http::HeaderValue>(),`);
711
+ l.push(`\t\t) {`);
712
+ l.push(`\t\t\treq.headers_mut().insert(name, val);`);
713
+ l.push(`\t\t}`);
714
+ l.push(`\t}`);
715
+ l.push(`\tif let Some(ref protos) = opts.protocols {`);
716
+ l.push(`\t\tif !protos.is_empty() {`);
717
+ l.push(`\t\t\treq.headers_mut().insert(`);
718
+ l.push(`\t\t\t\t"Sec-WebSocket-Protocol",`);
719
+ l.push(`\t\t\t\tprotos.join(", ").parse().map_err(|e: tokio_tungstenite::tungstenite::http::header::InvalidHeaderValue| Error::Other(e.to_string()))?,`);
720
+ l.push(`\t\t\t);`);
721
+ l.push(`\t\t}`);
722
+ l.push(`\t}`);
723
+ l.push(`\tlet (stream, _) = tokio_tungstenite::connect_async(req).await.map_err(|e| Error::Other(e.to_string()))?;`);
724
+ l.push(`\tOk(TypedWebSocket::new(stream))`);
725
+ l.push(`}`);
726
+ l.push(``);
727
+ return l;
728
+ }
729
+ l.push(`pub async fn ${plan.fnName}${sig.generics}(${sig.params}) -> ${returnType(plan, throwOnError)}${sig.where} {`);
730
+ l.push(...pathLines(plan));
731
+ l.push(...queryLines(plan));
732
+ l.push(...headerLines(plan, idempotencyLines(plan)));
733
+ const body = bodyExpr(plan, false);
734
+ l.push(...body.lines);
735
+ const call = [
736
+ `crate::runtime::do_request(`,
737
+ `\t&${a.http},`,
738
+ `\t&${a.cfg},`,
739
+ `\t&${a.auth},`,
740
+ `\treqwest::Method::${op.method},`,
741
+ `\t&url_path,`,
742
+ `\t&query,`,
743
+ `\t${body.expr},`,
744
+ `\tSome(&call_headers),`,
745
+ `\topts.timeout,`,
746
+ `\topts.cancel_token.clone(),`,
747
+ `\t${rustString(`${op.method} ${op.path}`)},`,
748
+ `\trequest_meta.as_ref(),`,
749
+ `).await`,
750
+ ];
751
+ l.push(...resultLines(plan, throwOnError, false, a, call));
752
+ l.push(`}`);
753
+ l.push(``);
754
+ return l;
755
+ }
756
+ function idempotencyLines(plan) {
757
+ if (!plan.op.idempotent || plan.op.stream !== null)
758
+ return [];
759
+ /* explicit header (any casing) > opts.idempotency_key > fresh UUID */
760
+ return [
761
+ `\tif !call_headers.keys().any(|k| k.eq_ignore_ascii_case("Idempotency-Key")) {`,
762
+ `\t\tlet key = opts.idempotency_key.clone().unwrap_or_else(|| uuid::Uuid::new_v4().to_string());`,
763
+ `\t\tcall_headers.insert("Idempotency-Key".to_string(), key);`,
764
+ `\t}`,
765
+ ];
766
+ }
767
+ /** emitSyncMethod is the blocking twin of emitMethod — no async, calls do_request_blocking. */
768
+ function emitSyncMethod(plan, selfAccess, throwOnError) {
769
+ if (!isSyncCapable(plan.op))
770
+ return [];
771
+ const l = [];
772
+ const { op } = plan;
773
+ const a = access(selfAccess);
774
+ l.push(...docLines(op));
775
+ const sig = signature(plan, true);
776
+ l.push(`pub fn ${plan.fnName}${sig.generics}(${sig.params}) -> ${returnType(plan, throwOnError)} {`);
777
+ l.push(...pathLines(plan));
778
+ l.push(...queryLines(plan));
779
+ l.push(...headerLines(plan, idempotencyLines(plan)));
780
+ const body = bodyExpr(plan, true);
781
+ l.push(...body.lines);
782
+ const call = [
783
+ `crate::runtime_sync::do_request_blocking(`,
784
+ `\t&${a.http},`,
785
+ `\t&${a.cfg},`,
786
+ `\t&${a.auth},`,
787
+ `\treqwest::Method::${op.method},`,
788
+ `\t&url_path,`,
789
+ `\t&query,`,
790
+ `\t${body.expr},`,
791
+ `\tSome(&call_headers),`,
792
+ `\topts.timeout,`,
793
+ `\topts.sync_cancel_token.clone(),`,
794
+ `\t${rustString(`${op.method} ${op.path}`)},`,
795
+ `\trequest_meta.as_ref(),`,
796
+ `)`,
797
+ ];
798
+ l.push(...resultLines(plan, throwOnError, true, a, call));
799
+ l.push(`}`);
800
+ l.push(``);
801
+ return l;
802
+ }
803
+ function isSyncCapable(op) {
804
+ return op.stream === null;
805
+ }
806
+ function hasSync(node) {
807
+ return node.plans.some((p) => isSyncCapable(p.op)) || node.children.some((c) => hasSync(c.node));
808
+ }
809
+ function buildTree(model, names, throwOnError) {
810
+ const plans = [];
811
+ function visit(ns, path, modName, reserved) {
812
+ const isRoot = path.length === 0;
813
+ const pascal = path.map(rustTypeIdent).join("");
814
+ const node = {
815
+ children: [],
816
+ modName,
817
+ ns,
818
+ path,
819
+ plans: [],
820
+ structName: isRoot ? "Client" : names.scope.claim(`${pascal}Resource`),
821
+ syncStructName: isRoot ? "SyncClient" : names.scope.claim(`${pascal}ResourceSync`),
822
+ };
823
+ const members = new NameScope(reserved);
824
+ const modules = new NameScope();
825
+ const childInfo = [];
826
+ for (const [seg, childNs] of namespacesOf(ns)) {
827
+ childInfo.push({
828
+ accessor: members.claim(rustPlainSnake(seg)),
829
+ mod: modules.claim(rustPlainSnake(seg)),
830
+ ns: childNs,
831
+ seg,
832
+ });
833
+ }
834
+ for (const [seg, irOp] of methodsOf(ns)) {
835
+ const op = model.opsById.get(irOp.id);
836
+ if (!op)
837
+ continue;
838
+ const ident = rustValueIdent(seg);
839
+ const plain = ident.startsWith("r#") ? ident.slice(2) : ident;
840
+ const claimed = members.claim(plain);
841
+ const plan = planOp(op, claimed === plain ? ident : claimed, [...path, seg], names, throwOnError, model);
842
+ node.plans.push(plan);
843
+ plans.push(plan);
844
+ }
845
+ for (const c of childInfo) {
846
+ node.children.push({ accessor: c.accessor, node: visit(c.ns, [...path, c.seg], c.mod, ["client", "new"]) });
847
+ }
848
+ return node;
849
+ }
850
+ const root = visit(model.ir.tree, [], "", ["inner", "new", "is_stale"]);
851
+ return { plans, root };
852
+ }
853
+ /* ── files ── */
854
+ function buildRustTypes(model, names) {
855
+ const body = [];
856
+ /* always emit shared error-envelope field type used by per-op error structs */
857
+ body.push(`#[derive(Debug, Clone, Serialize, Deserialize)]`);
858
+ body.push(`pub struct ErrField {`);
859
+ body.push(`\tpub error_key: String,`);
860
+ body.push(`\tpub message: String,`);
861
+ body.push(`\tpub path: String,`);
862
+ body.push(`}`);
863
+ body.push(``);
864
+ for (const name of model.schemaNames) {
865
+ if (Object.hasOwn(model.ir.schemaDescriptions, name))
866
+ body.push(...rustDoc(model.ir.schemaDescriptions[name]));
867
+ body.push(irRenderTopLevelRust(names.types.ref(name), model.ir.schemas[name], names.decls, undefined, names.types));
868
+ body.push(``);
869
+ }
870
+ return body.join("\n");
871
+ }
872
+ function typesFile(schemaSource, names) {
873
+ const l = [];
874
+ l.push(`/* Code generated by honey. DO NOT EDIT. */`);
875
+ l.push(``);
876
+ l.push(`#![allow(unused_imports, clippy::large_enum_variant)]`);
877
+ l.push(`use serde::{Serialize, Deserialize};`);
878
+ l.push(`use serde_repr::{Serialize_repr, Deserialize_repr};`);
879
+ l.push(`use std::collections::HashMap;`);
880
+ l.push(``);
881
+ l.push(schemaSource);
882
+ for (const name of [...names.decls.keys()].sort(cmpCodeUnit)) {
883
+ const decl = names.decls.get(name);
884
+ if (!decl)
885
+ continue;
886
+ l.push(decl);
887
+ l.push(``);
888
+ }
889
+ return l.join("\n");
890
+ }
891
+ function buildCargoToml(crateName, meta) {
892
+ /* TOML basic strings share JSON's escapes */
893
+ const pkgLines = [
894
+ `[package]`,
895
+ `name = "${crateName}"`,
896
+ `version = ${JSON.stringify(meta.version)}`,
897
+ `edition = "2021"`,
898
+ `rust-version = "1.75"`,
899
+ ];
900
+ if (meta.description)
901
+ pkgLines.push(`description = ${JSON.stringify(meta.description)}`);
902
+ if (meta.homepage)
903
+ pkgLines.push(`homepage = ${JSON.stringify(meta.homepage)}`);
904
+ if (meta.repository)
905
+ pkgLines.push(`repository = ${JSON.stringify(meta.repository)}`);
906
+ if (meta.license)
907
+ pkgLines.push(`license = ${JSON.stringify(meta.license)}`);
908
+ return [
909
+ ...pkgLines,
910
+ ``,
911
+ `[dependencies]`,
912
+ `tokio = { version = "^1.40", features = ["rt-multi-thread", "macros", "sync", "time"] }`,
913
+ `tokio-util = { version = "^0.7", features = ["rt"] }`,
914
+ `reqwest = { version = "^0.12", default-features = false, features = ["json", "stream", "rustls-tls", "multipart", "blocking"] }`,
915
+ `tokio-tungstenite = { version = "^0.24", features = ["rustls-tls-webpki-roots"] }`,
916
+ `futures = "^0.3"`,
917
+ `futures-util = "^0.3"`,
918
+ `serde = { version = "^1.0", features = ["derive"] }`,
919
+ `serde_json = "^1.0"`,
920
+ `serde_repr = "^0.1"`,
921
+ `url = "^2.5"`,
922
+ `urlencoding = "^2.1"`,
923
+ `regex = "^1.10"`,
924
+ `once_cell = "^1.20"`,
925
+ `bytes = "^1.7"`,
926
+ `uuid = { version = "^1", features = ["v4"] }`,
927
+ `async-trait = "^0.1"`,
928
+ `async-stream = "^0.3"`,
929
+ ``,
930
+ ].join("\n");
931
+ }
932
+ function buildLibRs(hasRealtime) {
933
+ const lines = [
934
+ `/* Code generated by honey. DO NOT EDIT. */`,
935
+ ``,
936
+ `pub mod client;`,
937
+ `pub mod errors;`,
938
+ `pub mod invalidation;`,
939
+ `pub mod invalidation_sync;`,
940
+ `pub mod nullable;`,
941
+ `pub mod resources;`,
942
+ `pub mod result;`,
943
+ `pub mod runtime;`,
944
+ `pub mod runtime_sync;`,
945
+ `pub mod sse;`,
946
+ `pub mod types;`,
947
+ `pub mod ws;`,
948
+ ];
949
+ if (hasRealtime)
950
+ lines.push(`pub mod realtime;`);
951
+ lines.push(``);
952
+ lines.push(`pub use client::Client;`);
953
+ lines.push(`pub use client::SyncClient;`);
954
+ lines.push(`pub use errors::Error;`);
955
+ lines.push(`pub use runtime::ClientConfig;`);
956
+ lines.push(`pub use runtime_sync::SyncClientConfig;`);
957
+ lines.push(`pub use result::SdkResult;`);
958
+ lines.push(``);
959
+ return lines.join("\n");
960
+ }
961
+ function fileHeader(sync) {
962
+ const lines = [];
963
+ lines.push(`/* Code generated by honey. DO NOT EDIT. */`);
964
+ lines.push(``);
965
+ lines.push(`#![allow(unused_imports, unused_variables, unused_mut, dead_code, deprecated)]`);
966
+ lines.push(`use std::sync::Arc;`);
967
+ lines.push(`use futures_util::{self, Stream};`);
968
+ lines.push(`use reqwest;`);
969
+ lines.push(`use serde::{Serialize, Deserialize};`);
970
+ lines.push(`use tokio_tungstenite;`);
971
+ lines.push(`use crate::client::ClientInner;`);
972
+ if (sync)
973
+ lines.push(`use crate::client::SyncClientInner;`);
974
+ lines.push(`use crate::errors::Error;`);
975
+ lines.push(`use crate::result::SdkResult;`);
976
+ lines.push(`use crate::types::*;`);
977
+ lines.push(`use crate::sse::SseEvent;`);
978
+ lines.push(`use crate::ws::TypedWebSocket;`);
979
+ lines.push(``);
980
+ return lines;
981
+ }
982
+ function staleInit(tracker) {
983
+ return [
984
+ `\t\tlet stale = match cfg.invalidation.clone() {`,
985
+ `\t\t\tSome(mut inv) if inv.stale_time > 0 => {`,
986
+ `\t\t\t\tif inv.stale_max_entries == 0 {`,
987
+ `\t\t\t\t\tinv.stale_max_entries = cfg.stale_max_entries;`,
988
+ `\t\t\t\t}`,
989
+ `\t\t\t\tSome(${tracker}::new(Some(&inv)))`,
990
+ `\t\t\t}`,
991
+ `\t\t\t_ => None,`,
992
+ `\t\t};`,
993
+ ];
994
+ }
995
+ function buildRustClient(root, plans, throwOnError, auth, serviceMap, realtimeIds) {
996
+ const body = [];
997
+ body.push(`pub(crate) struct ServiceEntry {`);
998
+ body.push(`\tpub method: &'static str,`);
999
+ body.push(`\tpub path: &'static str,`);
1000
+ body.push(`\tpub params: &'static [&'static str],`);
1001
+ body.push(`\tpub sse: bool,`);
1002
+ body.push(`\tpub ws: bool,`);
1003
+ body.push(`\tpub realtime: bool,`);
1004
+ body.push(`\tpub invalidate: &'static [&'static str],`);
1005
+ body.push(`}`);
1006
+ body.push(``);
1007
+ body.push(`pub(crate) static INVALIDATION_MAP: once_cell::sync::Lazy<std::collections::HashMap<&'static str, std::collections::HashMap<&'static str, ServiceEntry>>> =`);
1008
+ body.push(`\tonce_cell::sync::Lazy::new(|| {`);
1009
+ body.push(`\t\tlet mut map = std::collections::HashMap::new();`);
1010
+ for (const [resource, actions] of Object.entries(serviceMap).sort(([a], [b]) => cmpCodeUnit(a, b))) {
1011
+ body.push(`\t\t{`);
1012
+ body.push(`\t\t\tlet mut resource_map = std::collections::HashMap::new();`);
1013
+ for (const [action, entry] of Object.entries(actions).sort(([a], [b]) => cmpCodeUnit(a, b))) {
1014
+ const inv = entry.invalidate ?? [];
1015
+ const params = entry.params ?? [];
1016
+ const opId = action === "_call" ? resource : `${resource}.${action}`;
1017
+ body.push(`\t\t\tresource_map.insert(${rustString(action)}, ServiceEntry { method: ${rustString(String(entry.method))}, path: ${rustString(String(entry.path))}, params: &[${params.map(rustString).join(", ")}], sse: ${entry.sse === true}, ws: ${entry.ws === true}, realtime: ${realtimeIds.has(opId)}, invalidate: &[${inv.map(rustString).join(", ")}] });`);
1018
+ }
1019
+ body.push(`\t\t\tmap.insert(${rustString(resource)}, resource_map);`);
1020
+ body.push(`\t\t}`);
1021
+ }
1022
+ body.push(`\t\tmap`);
1023
+ body.push(`\t});`);
1024
+ body.push(``);
1025
+ body.push(`pub(crate) struct ClientInner {`);
1026
+ body.push(`\tpub(crate) cfg: crate::runtime::ClientConfig,`);
1027
+ body.push(`\tpub(crate) stale: Option<crate::invalidation::StaleTracker>,`);
1028
+ body.push(`\tpub(crate) http_client: reqwest::Client,`);
1029
+ body.push(`\tpub(crate) auth: std::sync::Arc<crate::runtime::AuthState>,`);
1030
+ body.push(`}`);
1031
+ body.push(``);
1032
+ body.push(`/// Client is the generated SDK client.`);
1033
+ body.push(`pub struct Client {`);
1034
+ body.push(`\tpub(crate) inner: std::sync::Arc<ClientInner>,`);
1035
+ for (const c of root.children)
1036
+ body.push(`\t${c.accessor}: ${c.node.structName},`);
1037
+ body.push(`}`);
1038
+ body.push(``);
1039
+ body.push(`impl Client {`);
1040
+ body.push(`\t/// new creates a new SDK client. base_url must be non-empty.`);
1041
+ body.push(`\tpub fn new(mut cfg: crate::runtime::ClientConfig) -> Self {`);
1042
+ body.push(`\t\tif cfg.base_url.is_empty() {`);
1043
+ body.push(`\t\t\tpanic!("honey sdk: ClientConfig.base_url must not be empty");`);
1044
+ body.push(`\t\t}`);
1045
+ body.push(`\t\t/* http_client: None → a default client that never redirects to another origin */`);
1046
+ body.push(`\t\tlet http_client = match cfg.http_client.take() {`);
1047
+ body.push(`\t\t\tSome(c) => c,`);
1048
+ body.push(`\t\t\tNone => crate::runtime::default_http_client(),`);
1049
+ body.push(`\t\t};`);
1050
+ body.push(`\t\tif cfg.auth_header_name.is_none() {`);
1051
+ body.push(`\t\t\tcfg.auth_header_name = Some(${rustString(auth.headerName)}.to_string());`);
1052
+ body.push(`\t\t}`);
1053
+ body.push(`\t\tif cfg.auth_header_prefix.is_none() {`);
1054
+ body.push(`\t\t\tcfg.auth_header_prefix = Some(${rustString(auth.prefix)}.to_string());`);
1055
+ body.push(`\t\t}`);
1056
+ body.push(...staleInit("crate::invalidation::StaleTracker"));
1057
+ body.push(`\t\tlet auth = std::sync::Arc::new(crate::runtime::AuthState::new(cfg.bearer_token.clone()));`);
1058
+ body.push(`\t\tlet inner = std::sync::Arc::new(ClientInner { cfg, stale, http_client, auth });`);
1059
+ body.push(`\t\tClient {`);
1060
+ for (const c of root.children) {
1061
+ body.push(`\t\t\t${c.accessor}: crate::resources::${c.node.modName}::new_resource(&inner),`);
1062
+ }
1063
+ body.push(`\t\t\tinner,`);
1064
+ body.push(`\t\t}`);
1065
+ body.push(`\t}`);
1066
+ body.push(``);
1067
+ for (const c of root.children) {
1068
+ body.push(`\t/// ${c.accessor} returns a reference to the ${c.node.structName}.`);
1069
+ body.push(`\tpub fn ${c.accessor}(&self) -> &${c.node.structName} {`);
1070
+ body.push(`\t\t&self.${c.accessor}`);
1071
+ body.push(`\t}`);
1072
+ body.push(``);
1073
+ }
1074
+ for (const plan of root.plans)
1075
+ body.push(...emitMethod(plan, "self", throwOnError).map((x) => `\t${x}`));
1076
+ body.push(`\t/// is_stale reports whether (method, path) is currently within an active stale window.`);
1077
+ body.push(`\tpub async fn is_stale(&self, method: &str, path: &str) -> bool {`);
1078
+ body.push(`\t\tmatch self.inner.stale {`);
1079
+ body.push(`\t\t\tSome(ref s) => s.is_stale(method, path).await,`);
1080
+ body.push(`\t\t\tNone => false,`);
1081
+ body.push(`\t\t}`);
1082
+ body.push(`\t}`);
1083
+ body.push(`}`);
1084
+ body.push(``);
1085
+ for (const plan of root.plans)
1086
+ body.push(...emitOptsStruct(plan), ...emitErrorTypes(plan));
1087
+ /* ── SyncClient ── */
1088
+ const syncChildren = root.children.filter((c) => hasSync(c.node));
1089
+ body.push(`pub(crate) struct SyncClientInner {`);
1090
+ body.push(`\tpub(crate) cfg: crate::runtime_sync::SyncClientConfig,`);
1091
+ body.push(`\tpub(crate) stale: Option<crate::invalidation_sync::StaleTrackerSync>,`);
1092
+ body.push(`\tpub(crate) http_client: reqwest::blocking::Client,`);
1093
+ body.push(`\tpub(crate) auth: std::sync::Arc<crate::runtime_sync::SyncAuthState>,`);
1094
+ body.push(`}`);
1095
+ body.push(``);
1096
+ body.push(`/// SyncClient is the generated blocking SDK client.`);
1097
+ body.push(`/// WARNING: Do not use from inside a tokio async task — reqwest blocking will deadlock.`);
1098
+ body.push(`pub struct SyncClient {`);
1099
+ body.push(`\tpub(crate) inner: std::sync::Arc<SyncClientInner>,`);
1100
+ for (const c of syncChildren)
1101
+ body.push(`\t${c.accessor}: ${c.node.syncStructName},`);
1102
+ body.push(`}`);
1103
+ body.push(``);
1104
+ body.push(`impl SyncClient {`);
1105
+ body.push(`\t/// new creates a new blocking SDK client. base_url must be non-empty.`);
1106
+ body.push(`\tpub fn new(mut cfg: crate::runtime_sync::SyncClientConfig) -> Self {`);
1107
+ body.push(`\t\tif cfg.base_url.is_empty() {`);
1108
+ body.push(`\t\t\tpanic!("honey sdk: SyncClientConfig.base_url must not be empty");`);
1109
+ body.push(`\t\t}`);
1110
+ body.push(`\t\tlet http_client = match cfg.http_client.take() {`);
1111
+ body.push(`\t\t\tSome(c) => c,`);
1112
+ body.push(`\t\t\tNone => crate::runtime_sync::default_http_client_blocking(),`);
1113
+ body.push(`\t\t};`);
1114
+ body.push(`\t\tif cfg.auth_header_name.is_none() {`);
1115
+ body.push(`\t\t\tcfg.auth_header_name = Some(${rustString(auth.headerName)}.to_string());`);
1116
+ body.push(`\t\t}`);
1117
+ body.push(`\t\tif cfg.auth_header_prefix.is_none() {`);
1118
+ body.push(`\t\t\tcfg.auth_header_prefix = Some(${rustString(auth.prefix)}.to_string());`);
1119
+ body.push(`\t\t}`);
1120
+ body.push(...staleInit("crate::invalidation_sync::StaleTrackerSync"));
1121
+ body.push(`\t\tlet auth = std::sync::Arc::new(crate::runtime_sync::SyncAuthState::new(cfg.bearer_token.clone()));`);
1122
+ body.push(`\t\tlet inner = std::sync::Arc::new(SyncClientInner { cfg, stale, http_client, auth });`);
1123
+ body.push(`\t\tSyncClient {`);
1124
+ for (const c of syncChildren) {
1125
+ body.push(`\t\t\t${c.accessor}: crate::resources::${c.node.modName}::new_resource_sync(&inner),`);
1126
+ }
1127
+ body.push(`\t\t\tinner,`);
1128
+ body.push(`\t\t}`);
1129
+ body.push(`\t}`);
1130
+ body.push(``);
1131
+ for (const c of syncChildren) {
1132
+ body.push(`\t/// ${c.accessor} returns a reference to the ${c.node.syncStructName}.`);
1133
+ body.push(`\tpub fn ${c.accessor}(&self) -> &${c.node.syncStructName} {`);
1134
+ body.push(`\t\t&self.${c.accessor}`);
1135
+ body.push(`\t}`);
1136
+ body.push(``);
1137
+ }
1138
+ for (const plan of root.plans)
1139
+ body.push(...emitSyncMethod(plan, "self", throwOnError).map((x) => `\t${x}`));
1140
+ body.push(`\t/// is_stale reports whether (method, path) is currently within an active stale window.`);
1141
+ body.push(`\tpub fn is_stale(&self, method: &str, path: &str) -> bool {`);
1142
+ body.push(`\t\tmatch self.inner.stale {`);
1143
+ body.push(`\t\t\tSome(ref s) => s.is_stale(method, path),`);
1144
+ body.push(`\t\t\tNone => false,`);
1145
+ body.push(`\t\t}`);
1146
+ body.push(`\t}`);
1147
+ body.push(`}`);
1148
+ body.push(``);
1149
+ void plans;
1150
+ const out = [];
1151
+ out.push(`/* Code generated by honey. DO NOT EDIT. */`);
1152
+ out.push(``);
1153
+ out.push(`#![allow(unused_imports, unused_variables, unused_mut, dead_code, deprecated)]`);
1154
+ out.push(`use std::sync::Arc;`);
1155
+ out.push(`use once_cell;`);
1156
+ out.push(`use reqwest;`);
1157
+ out.push(`use tokio_tungstenite;`);
1158
+ out.push(`use futures_util::{self, Stream};`);
1159
+ out.push(`use crate::errors::Error;`);
1160
+ out.push(`use crate::resources::*;`);
1161
+ out.push(`use crate::result::SdkResult;`);
1162
+ out.push(`use crate::runtime::ClientConfig;`);
1163
+ out.push(`use crate::sse::SseEvent;`);
1164
+ out.push(`use crate::types::*;`);
1165
+ out.push(`use crate::ws::TypedWebSocket;`);
1166
+ out.push(``);
1167
+ out.push(body.join("\n"));
1168
+ return out.join("\n");
1169
+ }
1170
+ function buildRustResources(root, throwOnError) {
1171
+ const files = new Map();
1172
+ const modLines = [`/* Code generated by honey. DO NOT EDIT. */`, ``];
1173
+ for (const c of root.children)
1174
+ modLines.push(`pub mod ${c.node.modName};`);
1175
+ for (const c of root.children) {
1176
+ modLines.push(`pub use ${c.node.modName}::${c.node.structName};`);
1177
+ if (hasSync(c.node))
1178
+ modLines.push(`pub use ${c.node.modName}::${c.node.syncStructName};`);
1179
+ }
1180
+ modLines.push(``);
1181
+ files.set("src/resources/mod.rs", modLines.join("\n"));
1182
+ function emitNode(node, dir) {
1183
+ const sync = hasSync(node);
1184
+ const l = [...fileHeader(sync)];
1185
+ for (const c of node.children)
1186
+ l.push(`pub mod ${c.node.modName};`);
1187
+ for (const c of node.children) {
1188
+ l.push(`pub use ${c.node.modName}::${c.node.structName};`);
1189
+ if (hasSync(c.node))
1190
+ l.push(`pub use ${c.node.modName}::${c.node.syncStructName};`);
1191
+ }
1192
+ if (node.children.length > 0)
1193
+ l.push(``);
1194
+ l.push(`pub struct ${node.structName} {`);
1195
+ l.push(`\tpub(crate) client: std::sync::Arc<crate::client::ClientInner>,`);
1196
+ for (const c of node.children)
1197
+ l.push(`\tpub ${c.accessor}: ${c.node.structName},`);
1198
+ l.push(`}`);
1199
+ l.push(``);
1200
+ l.push(`impl ${node.structName} {`);
1201
+ for (const c of node.children) {
1202
+ l.push(`\tpub fn ${c.accessor}(&self) -> &${c.node.structName} {`);
1203
+ l.push(`\t\t&self.${c.accessor}`);
1204
+ l.push(`\t}`);
1205
+ l.push(``);
1206
+ }
1207
+ for (const plan of node.plans)
1208
+ l.push(...emitMethod(plan, "self.client", throwOnError).map((x) => `\t${x}`));
1209
+ l.push(`}`);
1210
+ l.push(``);
1211
+ l.push(`pub(crate) fn new_resource(client: &std::sync::Arc<crate::client::ClientInner>) -> ${node.structName} {`);
1212
+ l.push(`\t${node.structName} {`);
1213
+ l.push(`\t\tclient: std::sync::Arc::clone(client),`);
1214
+ for (const c of node.children)
1215
+ l.push(`\t\t${c.accessor}: ${c.node.modName}::new_resource(client),`);
1216
+ l.push(`\t}`);
1217
+ l.push(`}`);
1218
+ l.push(``);
1219
+ if (sync) {
1220
+ const syncKids = node.children.filter((c) => hasSync(c.node));
1221
+ l.push(`pub struct ${node.syncStructName} {`);
1222
+ l.push(`\tpub(crate) client: std::sync::Arc<crate::client::SyncClientInner>,`);
1223
+ for (const c of syncKids)
1224
+ l.push(`\tpub ${c.accessor}: ${c.node.syncStructName},`);
1225
+ l.push(`}`);
1226
+ l.push(``);
1227
+ l.push(`impl ${node.syncStructName} {`);
1228
+ for (const c of syncKids) {
1229
+ l.push(`\tpub fn ${c.accessor}(&self) -> &${c.node.syncStructName} {`);
1230
+ l.push(`\t\t&self.${c.accessor}`);
1231
+ l.push(`\t}`);
1232
+ l.push(``);
1233
+ }
1234
+ for (const plan of node.plans)
1235
+ l.push(...emitSyncMethod(plan, "self.client", throwOnError).map((x) => `\t${x}`));
1236
+ l.push(`}`);
1237
+ l.push(``);
1238
+ l.push(`pub(crate) fn new_resource_sync(client: &std::sync::Arc<crate::client::SyncClientInner>) -> ${node.syncStructName} {`);
1239
+ l.push(`\t${node.syncStructName} {`);
1240
+ l.push(`\t\tclient: std::sync::Arc::clone(client),`);
1241
+ for (const c of syncKids)
1242
+ l.push(`\t\t${c.accessor}: ${c.node.modName}::new_resource_sync(client),`);
1243
+ l.push(`\t}`);
1244
+ l.push(`}`);
1245
+ l.push(``);
1246
+ }
1247
+ for (const plan of node.plans)
1248
+ l.push(...emitOptsStruct(plan), ...emitErrorTypes(plan));
1249
+ const here = [...dir, node.modName];
1250
+ const filePath = node.children.length > 0 ? `src/resources/${here.join("/")}/mod.rs` : `src/resources/${here.join("/")}.rs`;
1251
+ files.set(filePath, l.join("\n"));
1252
+ for (const c of node.children)
1253
+ emitNode(c.node, here);
1254
+ }
1255
+ for (const c of root.children)
1256
+ emitNode(c.node, []);
1257
+ return files;
1258
+ }
1259
+ export function generateRustSDK(spec, options = {}) {
1260
+ const crateName = validateCrateName(options.crateName ?? "honey-sdk");
1261
+ const throwOnError = options.throwOnError ?? true;
1262
+ const input = spec;
1263
+ const model = buildSdkModel(input);
1264
+ const serviceMap = serviceMapOf(model.ir);
1265
+ const names = buildRustNames(model);
1266
+ const hasRealtime = model.ops.some((op) => op.stream === "realtime");
1267
+ const realtimeIds = new Set(model.ops.filter((op) => op.stream === "realtime").map((op) => op.id));
1268
+ const files = {};
1269
+ for (const [name, content] of loadRustRuntimeTemplates()) {
1270
+ if (name === "realtime.rs" && !hasRealtime)
1271
+ continue;
1272
+ files[`src/${name}`] = content;
1273
+ }
1274
+ /* schema types claim their names first; operations then hoist into the same table */
1275
+ const schemaSource = buildRustTypes(model, names);
1276
+ const { plans, root } = buildTree(model, names, throwOnError);
1277
+ files["src/client.rs"] = buildRustClient(root, plans, throwOnError, model.ir.auth, serviceMap, realtimeIds);
1278
+ for (const [relPath, content] of buildRustResources(root, throwOnError))
1279
+ files[relPath] = content;
1280
+ files["src/types.rs"] = typesFile(schemaSource, names);
1281
+ files["src/lib.rs"] = buildLibRs(hasRealtime);
1282
+ files["Cargo.toml"] = buildCargoToml(crateName, {
1283
+ description: options.description,
1284
+ homepage: options.homepage,
1285
+ license: options.license,
1286
+ repository: options.repository,
1287
+ version: options.version ?? "0.1.0",
1288
+ });
1289
+ if (!files["src/resources/mod.rs"])
1290
+ files["src/resources/mod.rs"] = `/* Code generated by honey. DO NOT EDIT. */\n`;
1291
+ return { files, serviceMap };
1292
+ }
1293
+ //# sourceMappingURL=codegen-rust.js.map